xref: /freebsd/sys/amd64/vmm/vmm.c (revision 6ef6ba9950260f42b47499d17874d00ca9290955)
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/vm.h>
56 #include <machine/pcb.h>
57 #include <machine/smp.h>
58 #include <x86/apicreg.h>
59 #include <machine/vmparam.h>
60 
61 #include <machine/vmm.h>
62 #include <machine/vmm_dev.h>
63 
64 #include "vmm_ktr.h"
65 #include "vmm_host.h"
66 #include "vmm_mem.h"
67 #include "vmm_util.h"
68 #include "vioapic.h"
69 #include "vlapic.h"
70 #include "vmm_msr.h"
71 #include "vmm_ipi.h"
72 #include "vmm_stat.h"
73 #include "vmm_lapic.h"
74 
75 #include "io/ppt.h"
76 #include "io/iommu.h"
77 
78 struct vlapic;
79 
80 struct vcpu {
81 	int		flags;
82 	enum vcpu_state	state;
83 	struct mtx	mtx;
84 	int		hostcpu;	/* host cpuid this vcpu last ran on */
85 	uint64_t	guest_msrs[VMM_MSR_NUM];
86 	struct vlapic	*vlapic;
87 	int		 vcpuid;
88 	struct savefpu	*guestfpu;	/* guest fpu state */
89 	void		*stats;
90 	struct vm_exit	exitinfo;
91 	enum x2apic_state x2apic_state;
92 	int		nmi_pending;
93 };
94 
95 #define	vcpu_lock_init(v)	mtx_init(&((v)->mtx), "vcpu lock", 0, MTX_SPIN)
96 #define	vcpu_lock(v)		mtx_lock_spin(&((v)->mtx))
97 #define	vcpu_unlock(v)		mtx_unlock_spin(&((v)->mtx))
98 #define	vcpu_assert_locked(v)	mtx_assert(&((v)->mtx), MA_OWNED)
99 
100 struct mem_seg {
101 	vm_paddr_t	gpa;
102 	size_t		len;
103 	boolean_t	wired;
104 	vm_object_t	object;
105 };
106 #define	VM_MAX_MEMORY_SEGMENTS	2
107 
108 struct vm {
109 	void		*cookie;	/* processor-specific data */
110 	void		*iommu;		/* iommu-specific data */
111 	struct vioapic	*vioapic;	/* virtual ioapic */
112 	struct vmspace	*vmspace;	/* guest's address space */
113 	struct vcpu	vcpu[VM_MAXCPU];
114 	int		num_mem_segs;
115 	struct mem_seg	mem_segs[VM_MAX_MEMORY_SEGMENTS];
116 	char		name[VM_MAX_NAMELEN];
117 
118 	/*
119 	 * Set of active vcpus.
120 	 * An active vcpu is one that has been started implicitly (BSP) or
121 	 * explicitly (AP) by sending it a startup ipi.
122 	 */
123 	cpuset_t	active_cpus;
124 };
125 
126 static int vmm_initialized;
127 
128 static struct vmm_ops *ops;
129 #define	VMM_INIT()	(ops != NULL ? (*ops->init)() : 0)
130 #define	VMM_CLEANUP()	(ops != NULL ? (*ops->cleanup)() : 0)
131 
132 #define	VMINIT(vm, pmap) (ops != NULL ? (*ops->vminit)(vm, pmap): NULL)
133 #define	VMRUN(vmi, vcpu, rip, pmap) \
134 	(ops != NULL ? (*ops->vmrun)(vmi, vcpu, rip, pmap) : ENXIO)
135 #define	VMCLEANUP(vmi)	(ops != NULL ? (*ops->vmcleanup)(vmi) : NULL)
136 #define	VMSPACE_ALLOC(min, max) \
137 	(ops != NULL ? (*ops->vmspace_alloc)(min, max) : NULL)
138 #define	VMSPACE_FREE(vmspace) \
139 	(ops != NULL ? (*ops->vmspace_free)(vmspace) : ENXIO)
140 #define	VMGETREG(vmi, vcpu, num, retval)		\
141 	(ops != NULL ? (*ops->vmgetreg)(vmi, vcpu, num, retval) : ENXIO)
142 #define	VMSETREG(vmi, vcpu, num, val)		\
143 	(ops != NULL ? (*ops->vmsetreg)(vmi, vcpu, num, val) : ENXIO)
144 #define	VMGETDESC(vmi, vcpu, num, desc)		\
145 	(ops != NULL ? (*ops->vmgetdesc)(vmi, vcpu, num, desc) : ENXIO)
146 #define	VMSETDESC(vmi, vcpu, num, desc)		\
147 	(ops != NULL ? (*ops->vmsetdesc)(vmi, vcpu, num, desc) : ENXIO)
148 #define	VMINJECT(vmi, vcpu, type, vec, ec, ecv)	\
149 	(ops != NULL ? (*ops->vminject)(vmi, vcpu, type, vec, ec, ecv) : ENXIO)
150 #define	VMGETCAP(vmi, vcpu, num, retval)	\
151 	(ops != NULL ? (*ops->vmgetcap)(vmi, vcpu, num, retval) : ENXIO)
152 #define	VMSETCAP(vmi, vcpu, num, val)		\
153 	(ops != NULL ? (*ops->vmsetcap)(vmi, vcpu, num, val) : ENXIO)
154 
155 #define	fpu_start_emulating()	load_cr0(rcr0() | CR0_TS)
156 #define	fpu_stop_emulating()	clts()
157 
158 static MALLOC_DEFINE(M_VM, "vm", "vm");
159 CTASSERT(VMM_MSR_NUM <= 64);	/* msr_mask can keep track of up to 64 msrs */
160 
161 /* statistics */
162 static VMM_STAT(VCPU_TOTAL_RUNTIME, "vcpu total runtime");
163 
164 static void
165 vcpu_cleanup(struct vcpu *vcpu)
166 {
167 	vlapic_cleanup(vcpu->vlapic);
168 	vmm_stat_free(vcpu->stats);
169 	fpu_save_area_free(vcpu->guestfpu);
170 }
171 
172 static void
173 vcpu_init(struct vm *vm, uint32_t vcpu_id)
174 {
175 	struct vcpu *vcpu;
176 
177 	vcpu = &vm->vcpu[vcpu_id];
178 
179 	vcpu_lock_init(vcpu);
180 	vcpu->hostcpu = NOCPU;
181 	vcpu->vcpuid = vcpu_id;
182 	vcpu->vlapic = vlapic_init(vm, vcpu_id);
183 	vm_set_x2apic_state(vm, vcpu_id, X2APIC_ENABLED);
184 	vcpu->guestfpu = fpu_save_area_alloc();
185 	fpu_save_area_reset(vcpu->guestfpu);
186 	vcpu->stats = vmm_stat_alloc();
187 }
188 
189 struct vm_exit *
190 vm_exitinfo(struct vm *vm, int cpuid)
191 {
192 	struct vcpu *vcpu;
193 
194 	if (cpuid < 0 || cpuid >= VM_MAXCPU)
195 		panic("vm_exitinfo: invalid cpuid %d", cpuid);
196 
197 	vcpu = &vm->vcpu[cpuid];
198 
199 	return (&vcpu->exitinfo);
200 }
201 
202 static int
203 vmm_init(void)
204 {
205 	int error;
206 
207 	vmm_host_state_init();
208 	vmm_ipi_init();
209 
210 	error = vmm_mem_init();
211 	if (error)
212 		return (error);
213 
214 	if (vmm_is_intel())
215 		ops = &vmm_ops_intel;
216 	else if (vmm_is_amd())
217 		ops = &vmm_ops_amd;
218 	else
219 		return (ENXIO);
220 
221 	vmm_msr_init();
222 
223 	return (VMM_INIT());
224 }
225 
226 static int
227 vmm_handler(module_t mod, int what, void *arg)
228 {
229 	int error;
230 
231 	switch (what) {
232 	case MOD_LOAD:
233 		vmmdev_init();
234 		iommu_init();
235 		error = vmm_init();
236 		if (error == 0)
237 			vmm_initialized = 1;
238 		break;
239 	case MOD_UNLOAD:
240 		error = vmmdev_cleanup();
241 		if (error == 0) {
242 			iommu_cleanup();
243 			vmm_ipi_cleanup();
244 			error = VMM_CLEANUP();
245 			/*
246 			 * Something bad happened - prevent new
247 			 * VMs from being created
248 			 */
249 			if (error)
250 				vmm_initialized = 0;
251 		}
252 		break;
253 	default:
254 		error = 0;
255 		break;
256 	}
257 	return (error);
258 }
259 
260 static moduledata_t vmm_kmod = {
261 	"vmm",
262 	vmm_handler,
263 	NULL
264 };
265 
266 /*
267  * vmm initialization has the following dependencies:
268  *
269  * - iommu initialization must happen after the pci passthru driver has had
270  *   a chance to attach to any passthru devices (after SI_SUB_CONFIGURE).
271  *
272  * - VT-x initialization requires smp_rendezvous() and therefore must happen
273  *   after SMP is fully functional (after SI_SUB_SMP).
274  */
275 DECLARE_MODULE(vmm, vmm_kmod, SI_SUB_SMP + 1, SI_ORDER_ANY);
276 MODULE_VERSION(vmm, 1);
277 
278 SYSCTL_NODE(_hw, OID_AUTO, vmm, CTLFLAG_RW, NULL, NULL);
279 
280 int
281 vm_create(const char *name, struct vm **retvm)
282 {
283 	int i;
284 	struct vm *vm;
285 	struct vmspace *vmspace;
286 
287 	const int BSP = 0;
288 
289 	/*
290 	 * If vmm.ko could not be successfully initialized then don't attempt
291 	 * to create the virtual machine.
292 	 */
293 	if (!vmm_initialized)
294 		return (ENXIO);
295 
296 	if (name == NULL || strlen(name) >= VM_MAX_NAMELEN)
297 		return (EINVAL);
298 
299 	vmspace = VMSPACE_ALLOC(VM_MIN_ADDRESS, VM_MAXUSER_ADDRESS);
300 	if (vmspace == NULL)
301 		return (ENOMEM);
302 
303 	vm = malloc(sizeof(struct vm), M_VM, M_WAITOK | M_ZERO);
304 	strcpy(vm->name, name);
305 	vm->cookie = VMINIT(vm, vmspace_pmap(vmspace));
306 	vm->vioapic = vioapic_init(vm);
307 
308 	for (i = 0; i < VM_MAXCPU; i++) {
309 		vcpu_init(vm, i);
310 		guest_msrs_init(vm, i);
311 	}
312 
313 	vm_activate_cpu(vm, BSP);
314 	vm->vmspace = vmspace;
315 
316 	*retvm = vm;
317 	return (0);
318 }
319 
320 static void
321 vm_free_mem_seg(struct vm *vm, struct mem_seg *seg)
322 {
323 
324 	if (seg->object != NULL)
325 		vmm_mem_free(vm->vmspace, seg->gpa, seg->len);
326 
327 	bzero(seg, sizeof(*seg));
328 }
329 
330 void
331 vm_destroy(struct vm *vm)
332 {
333 	int i;
334 
335 	ppt_unassign_all(vm);
336 
337 	if (vm->iommu != NULL)
338 		iommu_destroy_domain(vm->iommu);
339 
340 	for (i = 0; i < vm->num_mem_segs; i++)
341 		vm_free_mem_seg(vm, &vm->mem_segs[i]);
342 
343 	vm->num_mem_segs = 0;
344 
345 	for (i = 0; i < VM_MAXCPU; i++)
346 		vcpu_cleanup(&vm->vcpu[i]);
347 
348 	vioapic_cleanup(vm->vioapic);
349 
350 	VMSPACE_FREE(vm->vmspace);
351 
352 	VMCLEANUP(vm->cookie);
353 
354 	free(vm, M_VM);
355 }
356 
357 const char *
358 vm_name(struct vm *vm)
359 {
360 	return (vm->name);
361 }
362 
363 int
364 vm_map_mmio(struct vm *vm, vm_paddr_t gpa, size_t len, vm_paddr_t hpa)
365 {
366 	vm_object_t obj;
367 
368 	if ((obj = vmm_mmio_alloc(vm->vmspace, gpa, len, hpa)) == NULL)
369 		return (ENOMEM);
370 	else
371 		return (0);
372 }
373 
374 int
375 vm_unmap_mmio(struct vm *vm, vm_paddr_t gpa, size_t len)
376 {
377 
378 	vmm_mmio_free(vm->vmspace, gpa, len);
379 	return (0);
380 }
381 
382 boolean_t
383 vm_mem_allocated(struct vm *vm, vm_paddr_t gpa)
384 {
385 	int i;
386 	vm_paddr_t gpabase, gpalimit;
387 
388 	for (i = 0; i < vm->num_mem_segs; i++) {
389 		gpabase = vm->mem_segs[i].gpa;
390 		gpalimit = gpabase + vm->mem_segs[i].len;
391 		if (gpa >= gpabase && gpa < gpalimit)
392 			return (TRUE);		/* 'gpa' is regular memory */
393 	}
394 
395 	if (ppt_is_mmio(vm, gpa))
396 		return (TRUE);			/* 'gpa' is pci passthru mmio */
397 
398 	return (FALSE);
399 }
400 
401 int
402 vm_malloc(struct vm *vm, vm_paddr_t gpa, size_t len)
403 {
404 	int available, allocated;
405 	struct mem_seg *seg;
406 	vm_object_t object;
407 	vm_paddr_t g;
408 
409 	if ((gpa & PAGE_MASK) || (len & PAGE_MASK) || len == 0)
410 		return (EINVAL);
411 
412 	available = allocated = 0;
413 	g = gpa;
414 	while (g < gpa + len) {
415 		if (vm_mem_allocated(vm, g))
416 			allocated++;
417 		else
418 			available++;
419 
420 		g += PAGE_SIZE;
421 	}
422 
423 	/*
424 	 * If there are some allocated and some available pages in the address
425 	 * range then it is an error.
426 	 */
427 	if (allocated && available)
428 		return (EINVAL);
429 
430 	/*
431 	 * If the entire address range being requested has already been
432 	 * allocated then there isn't anything more to do.
433 	 */
434 	if (allocated && available == 0)
435 		return (0);
436 
437 	if (vm->num_mem_segs >= VM_MAX_MEMORY_SEGMENTS)
438 		return (E2BIG);
439 
440 	seg = &vm->mem_segs[vm->num_mem_segs];
441 
442 	if ((object = vmm_mem_alloc(vm->vmspace, gpa, len)) == NULL)
443 		return (ENOMEM);
444 
445 	seg->gpa = gpa;
446 	seg->len = len;
447 	seg->object = object;
448 	seg->wired = FALSE;
449 
450 	vm->num_mem_segs++;
451 
452 	return (0);
453 }
454 
455 static void
456 vm_gpa_unwire(struct vm *vm)
457 {
458 	int i, rv;
459 	struct mem_seg *seg;
460 
461 	for (i = 0; i < vm->num_mem_segs; i++) {
462 		seg = &vm->mem_segs[i];
463 		if (!seg->wired)
464 			continue;
465 
466 		rv = vm_map_unwire(&vm->vmspace->vm_map,
467 				   seg->gpa, seg->gpa + seg->len,
468 				   VM_MAP_WIRE_USER | VM_MAP_WIRE_NOHOLES);
469 		KASSERT(rv == KERN_SUCCESS, ("vm(%s) memory segment "
470 		    "%#lx/%ld could not be unwired: %d",
471 		    vm_name(vm), seg->gpa, seg->len, rv));
472 
473 		seg->wired = FALSE;
474 	}
475 }
476 
477 static int
478 vm_gpa_wire(struct vm *vm)
479 {
480 	int i, rv;
481 	struct mem_seg *seg;
482 
483 	for (i = 0; i < vm->num_mem_segs; i++) {
484 		seg = &vm->mem_segs[i];
485 		if (seg->wired)
486 			continue;
487 
488 		/* XXX rlimits? */
489 		rv = vm_map_wire(&vm->vmspace->vm_map,
490 				 seg->gpa, seg->gpa + seg->len,
491 				 VM_MAP_WIRE_USER | VM_MAP_WIRE_NOHOLES);
492 		if (rv != KERN_SUCCESS)
493 			break;
494 
495 		seg->wired = TRUE;
496 	}
497 
498 	if (i < vm->num_mem_segs) {
499 		/*
500 		 * Undo the wiring before returning an error.
501 		 */
502 		vm_gpa_unwire(vm);
503 		return (EAGAIN);
504 	}
505 
506 	return (0);
507 }
508 
509 static void
510 vm_iommu_modify(struct vm *vm, boolean_t map)
511 {
512 	int i, sz;
513 	vm_paddr_t gpa, hpa;
514 	struct mem_seg *seg;
515 	void *vp, *cookie, *host_domain;
516 
517 	sz = PAGE_SIZE;
518 	host_domain = iommu_host_domain();
519 
520 	for (i = 0; i < vm->num_mem_segs; i++) {
521 		seg = &vm->mem_segs[i];
522 		KASSERT(seg->wired, ("vm(%s) memory segment %#lx/%ld not wired",
523 		    vm_name(vm), seg->gpa, seg->len));
524 
525 		gpa = seg->gpa;
526 		while (gpa < seg->gpa + seg->len) {
527 			vp = vm_gpa_hold(vm, gpa, PAGE_SIZE, VM_PROT_WRITE,
528 					 &cookie);
529 			KASSERT(vp != NULL, ("vm(%s) could not map gpa %#lx",
530 			    vm_name(vm), gpa));
531 
532 			vm_gpa_release(cookie);
533 
534 			hpa = DMAP_TO_PHYS((uintptr_t)vp);
535 			if (map) {
536 				iommu_create_mapping(vm->iommu, gpa, hpa, sz);
537 				iommu_remove_mapping(host_domain, hpa, sz);
538 			} else {
539 				iommu_remove_mapping(vm->iommu, gpa, sz);
540 				iommu_create_mapping(host_domain, hpa, hpa, sz);
541 			}
542 
543 			gpa += PAGE_SIZE;
544 		}
545 	}
546 
547 	/*
548 	 * Invalidate the cached translations associated with the domain
549 	 * from which pages were removed.
550 	 */
551 	if (map)
552 		iommu_invalidate_tlb(host_domain);
553 	else
554 		iommu_invalidate_tlb(vm->iommu);
555 }
556 
557 #define	vm_iommu_unmap(vm)	vm_iommu_modify((vm), FALSE)
558 #define	vm_iommu_map(vm)	vm_iommu_modify((vm), TRUE)
559 
560 int
561 vm_unassign_pptdev(struct vm *vm, int bus, int slot, int func)
562 {
563 	int error;
564 
565 	error = ppt_unassign_device(vm, bus, slot, func);
566 	if (error)
567 		return (error);
568 
569 	if (ppt_num_devices(vm) == 0) {
570 		vm_iommu_unmap(vm);
571 		vm_gpa_unwire(vm);
572 	}
573 	return (0);
574 }
575 
576 int
577 vm_assign_pptdev(struct vm *vm, int bus, int slot, int func)
578 {
579 	int error;
580 	vm_paddr_t maxaddr;
581 
582 	/*
583 	 * Virtual machines with pci passthru devices get special treatment:
584 	 * - the guest physical memory is wired
585 	 * - the iommu is programmed to do the 'gpa' to 'hpa' translation
586 	 *
587 	 * We need to do this before the first pci passthru device is attached.
588 	 */
589 	if (ppt_num_devices(vm) == 0) {
590 		KASSERT(vm->iommu == NULL,
591 		    ("vm_assign_pptdev: iommu must be NULL"));
592 		maxaddr = vmm_mem_maxaddr();
593 		vm->iommu = iommu_create_domain(maxaddr);
594 
595 		error = vm_gpa_wire(vm);
596 		if (error)
597 			return (error);
598 
599 		vm_iommu_map(vm);
600 	}
601 
602 	error = ppt_assign_device(vm, bus, slot, func);
603 	return (error);
604 }
605 
606 void *
607 vm_gpa_hold(struct vm *vm, vm_paddr_t gpa, size_t len, int reqprot,
608 	    void **cookie)
609 {
610 	int count, pageoff;
611 	vm_page_t m;
612 
613 	pageoff = gpa & PAGE_MASK;
614 	if (len > PAGE_SIZE - pageoff)
615 		panic("vm_gpa_hold: invalid gpa/len: 0x%016lx/%lu", gpa, len);
616 
617 	count = vm_fault_quick_hold_pages(&vm->vmspace->vm_map,
618 	    trunc_page(gpa), PAGE_SIZE, reqprot, &m, 1);
619 
620 	if (count == 1) {
621 		*cookie = m;
622 		return ((void *)(PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m)) + pageoff));
623 	} else {
624 		*cookie = NULL;
625 		return (NULL);
626 	}
627 }
628 
629 void
630 vm_gpa_release(void *cookie)
631 {
632 	vm_page_t m = cookie;
633 
634 	vm_page_lock(m);
635 	vm_page_unhold(m);
636 	vm_page_unlock(m);
637 }
638 
639 int
640 vm_gpabase2memseg(struct vm *vm, vm_paddr_t gpabase,
641 		  struct vm_memory_segment *seg)
642 {
643 	int i;
644 
645 	for (i = 0; i < vm->num_mem_segs; i++) {
646 		if (gpabase == vm->mem_segs[i].gpa) {
647 			seg->gpa = vm->mem_segs[i].gpa;
648 			seg->len = vm->mem_segs[i].len;
649 			seg->wired = vm->mem_segs[i].wired;
650 			return (0);
651 		}
652 	}
653 	return (-1);
654 }
655 
656 int
657 vm_get_memobj(struct vm *vm, vm_paddr_t gpa, size_t len,
658 	      vm_offset_t *offset, struct vm_object **object)
659 {
660 	int i;
661 	size_t seg_len;
662 	vm_paddr_t seg_gpa;
663 	vm_object_t seg_obj;
664 
665 	for (i = 0; i < vm->num_mem_segs; i++) {
666 		if ((seg_obj = vm->mem_segs[i].object) == NULL)
667 			continue;
668 
669 		seg_gpa = vm->mem_segs[i].gpa;
670 		seg_len = vm->mem_segs[i].len;
671 
672 		if (gpa >= seg_gpa && gpa < seg_gpa + seg_len) {
673 			*offset = gpa - seg_gpa;
674 			*object = seg_obj;
675 			vm_object_reference(seg_obj);
676 			return (0);
677 		}
678 	}
679 
680 	return (EINVAL);
681 }
682 
683 int
684 vm_get_register(struct vm *vm, int vcpu, int reg, uint64_t *retval)
685 {
686 
687 	if (vcpu < 0 || vcpu >= VM_MAXCPU)
688 		return (EINVAL);
689 
690 	if (reg >= VM_REG_LAST)
691 		return (EINVAL);
692 
693 	return (VMGETREG(vm->cookie, vcpu, reg, retval));
694 }
695 
696 int
697 vm_set_register(struct vm *vm, int vcpu, int reg, uint64_t val)
698 {
699 
700 	if (vcpu < 0 || vcpu >= VM_MAXCPU)
701 		return (EINVAL);
702 
703 	if (reg >= VM_REG_LAST)
704 		return (EINVAL);
705 
706 	return (VMSETREG(vm->cookie, vcpu, reg, val));
707 }
708 
709 static boolean_t
710 is_descriptor_table(int reg)
711 {
712 
713 	switch (reg) {
714 	case VM_REG_GUEST_IDTR:
715 	case VM_REG_GUEST_GDTR:
716 		return (TRUE);
717 	default:
718 		return (FALSE);
719 	}
720 }
721 
722 static boolean_t
723 is_segment_register(int reg)
724 {
725 
726 	switch (reg) {
727 	case VM_REG_GUEST_ES:
728 	case VM_REG_GUEST_CS:
729 	case VM_REG_GUEST_SS:
730 	case VM_REG_GUEST_DS:
731 	case VM_REG_GUEST_FS:
732 	case VM_REG_GUEST_GS:
733 	case VM_REG_GUEST_TR:
734 	case VM_REG_GUEST_LDTR:
735 		return (TRUE);
736 	default:
737 		return (FALSE);
738 	}
739 }
740 
741 int
742 vm_get_seg_desc(struct vm *vm, int vcpu, int reg,
743 		struct seg_desc *desc)
744 {
745 
746 	if (vcpu < 0 || vcpu >= VM_MAXCPU)
747 		return (EINVAL);
748 
749 	if (!is_segment_register(reg) && !is_descriptor_table(reg))
750 		return (EINVAL);
751 
752 	return (VMGETDESC(vm->cookie, vcpu, reg, desc));
753 }
754 
755 int
756 vm_set_seg_desc(struct vm *vm, int vcpu, int reg,
757 		struct seg_desc *desc)
758 {
759 	if (vcpu < 0 || vcpu >= VM_MAXCPU)
760 		return (EINVAL);
761 
762 	if (!is_segment_register(reg) && !is_descriptor_table(reg))
763 		return (EINVAL);
764 
765 	return (VMSETDESC(vm->cookie, vcpu, reg, desc));
766 }
767 
768 static void
769 restore_guest_fpustate(struct vcpu *vcpu)
770 {
771 
772 	/* flush host state to the pcb */
773 	fpuexit(curthread);
774 
775 	/* restore guest FPU state */
776 	fpu_stop_emulating();
777 	fpurestore(vcpu->guestfpu);
778 
779 	/*
780 	 * The FPU is now "dirty" with the guest's state so turn on emulation
781 	 * to trap any access to the FPU by the host.
782 	 */
783 	fpu_start_emulating();
784 }
785 
786 static void
787 save_guest_fpustate(struct vcpu *vcpu)
788 {
789 
790 	if ((rcr0() & CR0_TS) == 0)
791 		panic("fpu emulation not enabled in host!");
792 
793 	/* save guest FPU state */
794 	fpu_stop_emulating();
795 	fpusave(vcpu->guestfpu);
796 	fpu_start_emulating();
797 }
798 
799 static VMM_STAT(VCPU_IDLE_TICKS, "number of ticks vcpu was idle");
800 
801 static int
802 vcpu_set_state_locked(struct vcpu *vcpu, enum vcpu_state newstate)
803 {
804 	int error;
805 
806 	vcpu_assert_locked(vcpu);
807 
808 	/*
809 	 * The following state transitions are allowed:
810 	 * IDLE -> FROZEN -> IDLE
811 	 * FROZEN -> RUNNING -> FROZEN
812 	 * FROZEN -> SLEEPING -> FROZEN
813 	 */
814 	switch (vcpu->state) {
815 	case VCPU_IDLE:
816 	case VCPU_RUNNING:
817 	case VCPU_SLEEPING:
818 		error = (newstate != VCPU_FROZEN);
819 		break;
820 	case VCPU_FROZEN:
821 		error = (newstate == VCPU_FROZEN);
822 		break;
823 	default:
824 		error = 1;
825 		break;
826 	}
827 
828 	if (error == 0)
829 		vcpu->state = newstate;
830 	else
831 		error = EBUSY;
832 
833 	return (error);
834 }
835 
836 static void
837 vcpu_require_state(struct vm *vm, int vcpuid, enum vcpu_state newstate)
838 {
839 	int error;
840 
841 	if ((error = vcpu_set_state(vm, vcpuid, newstate)) != 0)
842 		panic("Error %d setting state to %d\n", error, newstate);
843 }
844 
845 static void
846 vcpu_require_state_locked(struct vcpu *vcpu, enum vcpu_state newstate)
847 {
848 	int error;
849 
850 	if ((error = vcpu_set_state_locked(vcpu, newstate)) != 0)
851 		panic("Error %d setting state to %d", error, newstate);
852 }
853 
854 /*
855  * Emulate a guest 'hlt' by sleeping until the vcpu is ready to run.
856  */
857 static int
858 vm_handle_hlt(struct vm *vm, int vcpuid, boolean_t *retu)
859 {
860 	struct vcpu *vcpu;
861 	int sleepticks, t;
862 
863 	vcpu = &vm->vcpu[vcpuid];
864 
865 	vcpu_lock(vcpu);
866 
867 	/*
868 	 * Figure out the number of host ticks until the next apic
869 	 * timer interrupt in the guest.
870 	 */
871 	sleepticks = lapic_timer_tick(vm, vcpuid);
872 
873 	/*
874 	 * If the guest local apic timer is disabled then sleep for
875 	 * a long time but not forever.
876 	 */
877 	if (sleepticks < 0)
878 		sleepticks = hz;
879 
880 	/*
881 	 * Do a final check for pending NMI or interrupts before
882 	 * really putting this thread to sleep.
883 	 *
884 	 * These interrupts could have happened any time after we
885 	 * returned from VMRUN() and before we grabbed the vcpu lock.
886 	 */
887 	if (!vm_nmi_pending(vm, vcpuid) && lapic_pending_intr(vm, vcpuid) < 0) {
888 		if (sleepticks <= 0)
889 			panic("invalid sleepticks %d", sleepticks);
890 		t = ticks;
891 		vcpu_require_state_locked(vcpu, VCPU_SLEEPING);
892 		msleep_spin(vcpu, &vcpu->mtx, "vmidle", sleepticks);
893 		vcpu_require_state_locked(vcpu, VCPU_FROZEN);
894 		vmm_stat_incr(vm, vcpuid, VCPU_IDLE_TICKS, ticks - t);
895 	}
896 	vcpu_unlock(vcpu);
897 
898 	return (0);
899 }
900 
901 static int
902 vm_handle_paging(struct vm *vm, int vcpuid, boolean_t *retu)
903 {
904 	int rv, ftype;
905 	struct vm_map *map;
906 	struct vcpu *vcpu;
907 	struct vm_exit *vme;
908 
909 	vcpu = &vm->vcpu[vcpuid];
910 	vme = &vcpu->exitinfo;
911 
912 	ftype = vme->u.paging.fault_type;
913 	KASSERT(ftype == VM_PROT_READ ||
914 	    ftype == VM_PROT_WRITE || ftype == VM_PROT_EXECUTE,
915 	    ("vm_handle_paging: invalid fault_type %d", ftype));
916 
917 	if (ftype == VM_PROT_READ || ftype == VM_PROT_WRITE) {
918 		rv = pmap_emulate_accessed_dirty(vmspace_pmap(vm->vmspace),
919 		    vme->u.paging.gpa, ftype);
920 		if (rv == 0)
921 			goto done;
922 	}
923 
924 	map = &vm->vmspace->vm_map;
925 	rv = vm_fault(map, vme->u.paging.gpa, ftype, VM_FAULT_NORMAL);
926 
927 	VCPU_CTR3(vm, vcpuid, "vm_handle_paging rv = %d, gpa = %#lx, "
928 	    "ftype = %d", rv, vme->u.paging.gpa, ftype);
929 
930 	if (rv != KERN_SUCCESS)
931 		return (EFAULT);
932 done:
933 	/* restart execution at the faulting instruction */
934 	vme->inst_length = 0;
935 
936 	return (0);
937 }
938 
939 static int
940 vm_handle_inst_emul(struct vm *vm, int vcpuid, boolean_t *retu)
941 {
942 	struct vie *vie;
943 	struct vcpu *vcpu;
944 	struct vm_exit *vme;
945 	int error, inst_length;
946 	uint64_t rip, gla, gpa, cr3;
947 	mem_region_read_t mread;
948 	mem_region_write_t mwrite;
949 
950 	vcpu = &vm->vcpu[vcpuid];
951 	vme = &vcpu->exitinfo;
952 
953 	rip = vme->rip;
954 	inst_length = vme->inst_length;
955 
956 	gla = vme->u.inst_emul.gla;
957 	gpa = vme->u.inst_emul.gpa;
958 	cr3 = vme->u.inst_emul.cr3;
959 	vie = &vme->u.inst_emul.vie;
960 
961 	vie_init(vie);
962 
963 	/* Fetch, decode and emulate the faulting instruction */
964 	if (vmm_fetch_instruction(vm, vcpuid, rip, inst_length, cr3, vie) != 0)
965 		return (EFAULT);
966 
967 	if (vmm_decode_instruction(vm, vcpuid, gla, vie) != 0)
968 		return (EFAULT);
969 
970 	/* return to userland unless this is a local apic access */
971 	if (gpa >= DEFAULT_APIC_BASE && gpa < DEFAULT_APIC_BASE + PAGE_SIZE) {
972 		mread = lapic_mmio_read;
973 		mwrite = lapic_mmio_write;
974 	} else if (gpa >= VIOAPIC_BASE && gpa < VIOAPIC_BASE + VIOAPIC_SIZE) {
975 		mread = vioapic_mmio_read;
976 		mwrite = vioapic_mmio_write;
977 	} else {
978 		*retu = TRUE;
979 		return (0);
980 	}
981 
982 	error = vmm_emulate_instruction(vm, vcpuid, gpa, vie, mread, mwrite, 0);
983 
984 	/* return to userland to spin up the AP */
985 	if (error == 0 && vme->exitcode == VM_EXITCODE_SPINUP_AP)
986 		*retu = TRUE;
987 
988 	return (error);
989 }
990 
991 int
992 vm_run(struct vm *vm, struct vm_run *vmrun)
993 {
994 	int error, vcpuid;
995 	struct vcpu *vcpu;
996 	struct pcb *pcb;
997 	uint64_t tscval, rip;
998 	struct vm_exit *vme;
999 	boolean_t retu;
1000 	pmap_t pmap;
1001 
1002 	vcpuid = vmrun->cpuid;
1003 
1004 	if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1005 		return (EINVAL);
1006 
1007 	pmap = vmspace_pmap(vm->vmspace);
1008 	vcpu = &vm->vcpu[vcpuid];
1009 	vme = &vcpu->exitinfo;
1010 	rip = vmrun->rip;
1011 restart:
1012 	critical_enter();
1013 
1014 	KASSERT(!CPU_ISSET(curcpu, &pmap->pm_active),
1015 	    ("vm_run: absurd pm_active"));
1016 
1017 	tscval = rdtsc();
1018 
1019 	pcb = PCPU_GET(curpcb);
1020 	set_pcb_flags(pcb, PCB_FULL_IRET);
1021 
1022 	restore_guest_msrs(vm, vcpuid);
1023 	restore_guest_fpustate(vcpu);
1024 
1025 	vcpu_require_state(vm, vcpuid, VCPU_RUNNING);
1026 	vcpu->hostcpu = curcpu;
1027 	error = VMRUN(vm->cookie, vcpuid, rip, pmap);
1028 	vcpu->hostcpu = NOCPU;
1029 	vcpu_require_state(vm, vcpuid, VCPU_FROZEN);
1030 
1031 	save_guest_fpustate(vcpu);
1032 	restore_host_msrs(vm, vcpuid);
1033 
1034 	vmm_stat_incr(vm, vcpuid, VCPU_TOTAL_RUNTIME, rdtsc() - tscval);
1035 
1036 	critical_exit();
1037 
1038 	if (error == 0) {
1039 		retu = FALSE;
1040 		switch (vme->exitcode) {
1041 		case VM_EXITCODE_HLT:
1042 			error = vm_handle_hlt(vm, vcpuid, &retu);
1043 			break;
1044 		case VM_EXITCODE_PAGING:
1045 			error = vm_handle_paging(vm, vcpuid, &retu);
1046 			break;
1047 		case VM_EXITCODE_INST_EMUL:
1048 			error = vm_handle_inst_emul(vm, vcpuid, &retu);
1049 			break;
1050 		default:
1051 			retu = TRUE;	/* handled in userland */
1052 			break;
1053 		}
1054 	}
1055 
1056 	if (error == 0 && retu == FALSE) {
1057 		rip = vme->rip + vme->inst_length;
1058 		goto restart;
1059 	}
1060 
1061 	/* copy the exit information */
1062 	bcopy(vme, &vmrun->vm_exit, sizeof(struct vm_exit));
1063 	return (error);
1064 }
1065 
1066 int
1067 vm_inject_event(struct vm *vm, int vcpuid, int type,
1068 		int vector, uint32_t code, int code_valid)
1069 {
1070 	if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1071 		return (EINVAL);
1072 
1073 	if ((type > VM_EVENT_NONE && type < VM_EVENT_MAX) == 0)
1074 		return (EINVAL);
1075 
1076 	if (vector < 0 || vector > 255)
1077 		return (EINVAL);
1078 
1079 	return (VMINJECT(vm->cookie, vcpuid, type, vector, code, code_valid));
1080 }
1081 
1082 static VMM_STAT(VCPU_NMI_COUNT, "number of NMIs delivered to vcpu");
1083 
1084 int
1085 vm_inject_nmi(struct vm *vm, int vcpuid)
1086 {
1087 	struct vcpu *vcpu;
1088 
1089 	if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1090 		return (EINVAL);
1091 
1092 	vcpu = &vm->vcpu[vcpuid];
1093 
1094 	vcpu->nmi_pending = 1;
1095 	vm_interrupt_hostcpu(vm, vcpuid);
1096 	return (0);
1097 }
1098 
1099 int
1100 vm_nmi_pending(struct vm *vm, int vcpuid)
1101 {
1102 	struct vcpu *vcpu;
1103 
1104 	if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1105 		panic("vm_nmi_pending: invalid vcpuid %d", vcpuid);
1106 
1107 	vcpu = &vm->vcpu[vcpuid];
1108 
1109 	return (vcpu->nmi_pending);
1110 }
1111 
1112 void
1113 vm_nmi_clear(struct vm *vm, int vcpuid)
1114 {
1115 	struct vcpu *vcpu;
1116 
1117 	if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1118 		panic("vm_nmi_pending: invalid vcpuid %d", vcpuid);
1119 
1120 	vcpu = &vm->vcpu[vcpuid];
1121 
1122 	if (vcpu->nmi_pending == 0)
1123 		panic("vm_nmi_clear: inconsistent nmi_pending state");
1124 
1125 	vcpu->nmi_pending = 0;
1126 	vmm_stat_incr(vm, vcpuid, VCPU_NMI_COUNT, 1);
1127 }
1128 
1129 int
1130 vm_get_capability(struct vm *vm, int vcpu, int type, int *retval)
1131 {
1132 	if (vcpu < 0 || vcpu >= VM_MAXCPU)
1133 		return (EINVAL);
1134 
1135 	if (type < 0 || type >= VM_CAP_MAX)
1136 		return (EINVAL);
1137 
1138 	return (VMGETCAP(vm->cookie, vcpu, type, retval));
1139 }
1140 
1141 int
1142 vm_set_capability(struct vm *vm, int vcpu, int type, int val)
1143 {
1144 	if (vcpu < 0 || vcpu >= VM_MAXCPU)
1145 		return (EINVAL);
1146 
1147 	if (type < 0 || type >= VM_CAP_MAX)
1148 		return (EINVAL);
1149 
1150 	return (VMSETCAP(vm->cookie, vcpu, type, val));
1151 }
1152 
1153 uint64_t *
1154 vm_guest_msrs(struct vm *vm, int cpu)
1155 {
1156 	return (vm->vcpu[cpu].guest_msrs);
1157 }
1158 
1159 struct vlapic *
1160 vm_lapic(struct vm *vm, int cpu)
1161 {
1162 	return (vm->vcpu[cpu].vlapic);
1163 }
1164 
1165 struct vioapic *
1166 vm_ioapic(struct vm *vm)
1167 {
1168 
1169 	return (vm->vioapic);
1170 }
1171 
1172 boolean_t
1173 vmm_is_pptdev(int bus, int slot, int func)
1174 {
1175 	int found, i, n;
1176 	int b, s, f;
1177 	char *val, *cp, *cp2;
1178 
1179 	/*
1180 	 * XXX
1181 	 * The length of an environment variable is limited to 128 bytes which
1182 	 * puts an upper limit on the number of passthru devices that may be
1183 	 * specified using a single environment variable.
1184 	 *
1185 	 * Work around this by scanning multiple environment variable
1186 	 * names instead of a single one - yuck!
1187 	 */
1188 	const char *names[] = { "pptdevs", "pptdevs2", "pptdevs3", NULL };
1189 
1190 	/* set pptdevs="1/2/3 4/5/6 7/8/9 10/11/12" */
1191 	found = 0;
1192 	for (i = 0; names[i] != NULL && !found; i++) {
1193 		cp = val = getenv(names[i]);
1194 		while (cp != NULL && *cp != '\0') {
1195 			if ((cp2 = strchr(cp, ' ')) != NULL)
1196 				*cp2 = '\0';
1197 
1198 			n = sscanf(cp, "%d/%d/%d", &b, &s, &f);
1199 			if (n == 3 && bus == b && slot == s && func == f) {
1200 				found = 1;
1201 				break;
1202 			}
1203 
1204 			if (cp2 != NULL)
1205 				*cp2++ = ' ';
1206 
1207 			cp = cp2;
1208 		}
1209 		freeenv(val);
1210 	}
1211 	return (found);
1212 }
1213 
1214 void *
1215 vm_iommu_domain(struct vm *vm)
1216 {
1217 
1218 	return (vm->iommu);
1219 }
1220 
1221 int
1222 vcpu_set_state(struct vm *vm, int vcpuid, enum vcpu_state newstate)
1223 {
1224 	int error;
1225 	struct vcpu *vcpu;
1226 
1227 	if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1228 		panic("vm_set_run_state: invalid vcpuid %d", vcpuid);
1229 
1230 	vcpu = &vm->vcpu[vcpuid];
1231 
1232 	vcpu_lock(vcpu);
1233 	error = vcpu_set_state_locked(vcpu, newstate);
1234 	vcpu_unlock(vcpu);
1235 
1236 	return (error);
1237 }
1238 
1239 enum vcpu_state
1240 vcpu_get_state(struct vm *vm, int vcpuid, int *hostcpu)
1241 {
1242 	struct vcpu *vcpu;
1243 	enum vcpu_state state;
1244 
1245 	if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1246 		panic("vm_get_run_state: invalid vcpuid %d", vcpuid);
1247 
1248 	vcpu = &vm->vcpu[vcpuid];
1249 
1250 	vcpu_lock(vcpu);
1251 	state = vcpu->state;
1252 	if (hostcpu != NULL)
1253 		*hostcpu = vcpu->hostcpu;
1254 	vcpu_unlock(vcpu);
1255 
1256 	return (state);
1257 }
1258 
1259 void
1260 vm_activate_cpu(struct vm *vm, int vcpuid)
1261 {
1262 
1263 	if (vcpuid >= 0 && vcpuid < VM_MAXCPU)
1264 		CPU_SET(vcpuid, &vm->active_cpus);
1265 }
1266 
1267 cpuset_t
1268 vm_active_cpus(struct vm *vm)
1269 {
1270 
1271 	return (vm->active_cpus);
1272 }
1273 
1274 void *
1275 vcpu_stats(struct vm *vm, int vcpuid)
1276 {
1277 
1278 	return (vm->vcpu[vcpuid].stats);
1279 }
1280 
1281 int
1282 vm_get_x2apic_state(struct vm *vm, int vcpuid, enum x2apic_state *state)
1283 {
1284 	if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1285 		return (EINVAL);
1286 
1287 	*state = vm->vcpu[vcpuid].x2apic_state;
1288 
1289 	return (0);
1290 }
1291 
1292 int
1293 vm_set_x2apic_state(struct vm *vm, int vcpuid, enum x2apic_state state)
1294 {
1295 	if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1296 		return (EINVAL);
1297 
1298 	if (state >= X2APIC_STATE_LAST)
1299 		return (EINVAL);
1300 
1301 	vm->vcpu[vcpuid].x2apic_state = state;
1302 
1303 	vlapic_set_x2apic_state(vm, vcpuid, state);
1304 
1305 	return (0);
1306 }
1307 
1308 void
1309 vm_interrupt_hostcpu(struct vm *vm, int vcpuid)
1310 {
1311 	int hostcpu;
1312 	struct vcpu *vcpu;
1313 
1314 	vcpu = &vm->vcpu[vcpuid];
1315 
1316 	vcpu_lock(vcpu);
1317 	hostcpu = vcpu->hostcpu;
1318 	if (hostcpu == NOCPU) {
1319 		if (vcpu->state == VCPU_SLEEPING)
1320 			wakeup_one(vcpu);
1321 	} else {
1322 		if (vcpu->state != VCPU_RUNNING)
1323 			panic("invalid vcpu state %d", vcpu->state);
1324 		if (hostcpu != curcpu)
1325 			ipi_cpu(hostcpu, vmm_ipinum);
1326 	}
1327 	vcpu_unlock(vcpu);
1328 }
1329 
1330 struct vmspace *
1331 vm_get_vmspace(struct vm *vm)
1332 {
1333 
1334 	return (vm->vmspace);
1335 }
1336 
1337 int
1338 vm_apicid2vcpuid(struct vm *vm, int apicid)
1339 {
1340 	/*
1341 	 * XXX apic id is assumed to be numerically identical to vcpu id
1342 	 */
1343 	return (apicid);
1344 }
1345