xref: /freebsd/sys/amd64/vmm/vmm.c (revision 7543a9c0280a0f4262489671936a6e03b9b2c563)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2011 NetApp, Inc.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY NETAPP, INC ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL NETAPP, INC OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  *
28  * $FreeBSD$
29  */
30 
31 #include <sys/cdefs.h>
32 __FBSDID("$FreeBSD$");
33 
34 #include "opt_bhyve_snapshot.h"
35 
36 #include <sys/param.h>
37 #include <sys/systm.h>
38 #include <sys/kernel.h>
39 #include <sys/module.h>
40 #include <sys/sysctl.h>
41 #include <sys/malloc.h>
42 #include <sys/pcpu.h>
43 #include <sys/lock.h>
44 #include <sys/mutex.h>
45 #include <sys/proc.h>
46 #include <sys/rwlock.h>
47 #include <sys/sched.h>
48 #include <sys/smp.h>
49 #include <sys/sx.h>
50 #include <sys/vnode.h>
51 
52 #include <vm/vm.h>
53 #include <vm/vm_param.h>
54 #include <vm/vm_extern.h>
55 #include <vm/vm_object.h>
56 #include <vm/vm_page.h>
57 #include <vm/pmap.h>
58 #include <vm/vm_map.h>
59 #include <vm/vm_pager.h>
60 #include <vm/vm_kern.h>
61 #include <vm/vnode_pager.h>
62 #include <vm/swap_pager.h>
63 #include <vm/uma.h>
64 
65 #include <machine/cpu.h>
66 #include <machine/pcb.h>
67 #include <machine/smp.h>
68 #include <machine/md_var.h>
69 #include <x86/psl.h>
70 #include <x86/apicreg.h>
71 #include <x86/ifunc.h>
72 
73 #include <machine/vmm.h>
74 #include <machine/vmm_dev.h>
75 #include <machine/vmm_instruction_emul.h>
76 #include <machine/vmm_snapshot.h>
77 
78 #include "vmm_ioport.h"
79 #include "vmm_ktr.h"
80 #include "vmm_host.h"
81 #include "vmm_mem.h"
82 #include "vmm_util.h"
83 #include "vatpic.h"
84 #include "vatpit.h"
85 #include "vhpet.h"
86 #include "vioapic.h"
87 #include "vlapic.h"
88 #include "vpmtmr.h"
89 #include "vrtc.h"
90 #include "vmm_stat.h"
91 #include "vmm_lapic.h"
92 
93 #include "io/ppt.h"
94 #include "io/iommu.h"
95 
96 struct vlapic;
97 
98 /*
99  * Initialization:
100  * (a) allocated when vcpu is created
101  * (i) initialized when vcpu is created and when it is reinitialized
102  * (o) initialized the first time the vcpu is created
103  * (x) initialized before use
104  */
105 struct vcpu {
106 	struct mtx 	mtx;		/* (o) protects 'state' and 'hostcpu' */
107 	enum vcpu_state	state;		/* (o) vcpu state */
108 	int		vcpuid;		/* (o) */
109 	int		hostcpu;	/* (o) vcpu's host cpu */
110 	int		reqidle;	/* (i) request vcpu to idle */
111 	struct vm	*vm;		/* (o) */
112 	void		*cookie;	/* (i) cpu-specific data */
113 	struct vlapic	*vlapic;	/* (i) APIC device model */
114 	enum x2apic_state x2apic_state;	/* (i) APIC mode */
115 	uint64_t	exitintinfo;	/* (i) events pending at VM exit */
116 	int		nmi_pending;	/* (i) NMI pending */
117 	int		extint_pending;	/* (i) INTR pending */
118 	int	exception_pending;	/* (i) exception pending */
119 	int	exc_vector;		/* (x) exception collateral */
120 	int	exc_errcode_valid;
121 	uint32_t exc_errcode;
122 	struct savefpu	*guestfpu;	/* (a,i) guest fpu state */
123 	uint64_t	guest_xcr0;	/* (i) guest %xcr0 register */
124 	void		*stats;		/* (a,i) statistics */
125 	struct vm_exit	exitinfo;	/* (x) exit reason and collateral */
126 	uint64_t	nextrip;	/* (x) next instruction to execute */
127 	uint64_t	tsc_offset;	/* (o) TSC offsetting */
128 };
129 
130 #define	vcpu_lock_init(v)	mtx_init(&((v)->mtx), "vcpu lock", 0, MTX_SPIN)
131 #define	vcpu_lock_destroy(v)	mtx_destroy(&((v)->mtx))
132 #define	vcpu_lock(v)		mtx_lock_spin(&((v)->mtx))
133 #define	vcpu_unlock(v)		mtx_unlock_spin(&((v)->mtx))
134 #define	vcpu_assert_locked(v)	mtx_assert(&((v)->mtx), MA_OWNED)
135 
136 struct mem_seg {
137 	size_t	len;
138 	bool	sysmem;
139 	struct vm_object *object;
140 };
141 #define	VM_MAX_MEMSEGS	4
142 
143 struct mem_map {
144 	vm_paddr_t	gpa;
145 	size_t		len;
146 	vm_ooffset_t	segoff;
147 	int		segid;
148 	int		prot;
149 	int		flags;
150 };
151 #define	VM_MAX_MEMMAPS	8
152 
153 /*
154  * Initialization:
155  * (o) initialized the first time the VM is created
156  * (i) initialized when VM is created and when it is reinitialized
157  * (x) initialized before use
158  *
159  * Locking:
160  * [m] mem_segs_lock
161  * [r] rendezvous_mtx
162  * [v] reads require one frozen vcpu, writes require freezing all vcpus
163  */
164 struct vm {
165 	void		*cookie;		/* (i) cpu-specific data */
166 	void		*iommu;			/* (x) iommu-specific data */
167 	struct vhpet	*vhpet;			/* (i) virtual HPET */
168 	struct vioapic	*vioapic;		/* (i) virtual ioapic */
169 	struct vatpic	*vatpic;		/* (i) virtual atpic */
170 	struct vatpit	*vatpit;		/* (i) virtual atpit */
171 	struct vpmtmr	*vpmtmr;		/* (i) virtual ACPI PM timer */
172 	struct vrtc	*vrtc;			/* (o) virtual RTC */
173 	volatile cpuset_t active_cpus;		/* (i) active vcpus */
174 	volatile cpuset_t debug_cpus;		/* (i) vcpus stopped for debug */
175 	cpuset_t	startup_cpus;		/* (i) [r] waiting for startup */
176 	int		suspend;		/* (i) stop VM execution */
177 	bool		dying;			/* (o) is dying */
178 	volatile cpuset_t suspended_cpus; 	/* (i) suspended vcpus */
179 	volatile cpuset_t halted_cpus;		/* (x) cpus in a hard halt */
180 	cpuset_t	rendezvous_req_cpus;	/* (x) [r] rendezvous requested */
181 	cpuset_t	rendezvous_done_cpus;	/* (x) [r] rendezvous finished */
182 	void		*rendezvous_arg;	/* (x) [r] rendezvous func/arg */
183 	vm_rendezvous_func_t rendezvous_func;
184 	struct mtx	rendezvous_mtx;		/* (o) rendezvous lock */
185 	struct mem_map	mem_maps[VM_MAX_MEMMAPS]; /* (i) [m+v] guest address space */
186 	struct mem_seg	mem_segs[VM_MAX_MEMSEGS]; /* (o) [m+v] guest memory regions */
187 	struct vmspace	*vmspace;		/* (o) guest's address space */
188 	char		name[VM_MAX_NAMELEN+1];	/* (o) virtual machine name */
189 	struct vcpu	**vcpu;			/* (o) guest vcpus */
190 	/* The following describe the vm cpu topology */
191 	uint16_t	sockets;		/* (o) num of sockets */
192 	uint16_t	cores;			/* (o) num of cores/socket */
193 	uint16_t	threads;		/* (o) num of threads/core */
194 	uint16_t	maxcpus;		/* (o) max pluggable cpus */
195 	struct sx	mem_segs_lock;		/* (o) */
196 	struct sx	vcpus_init_lock;	/* (o) */
197 };
198 
199 #define	VMM_CTR0(vcpu, format)						\
200 	VCPU_CTR0((vcpu)->vm, (vcpu)->vcpuid, format)
201 
202 #define	VMM_CTR1(vcpu, format, p1)					\
203 	VCPU_CTR1((vcpu)->vm, (vcpu)->vcpuid, format, p1)
204 
205 #define	VMM_CTR2(vcpu, format, p1, p2)					\
206 	VCPU_CTR2((vcpu)->vm, (vcpu)->vcpuid, format, p1, p2)
207 
208 #define	VMM_CTR3(vcpu, format, p1, p2, p3)				\
209 	VCPU_CTR3((vcpu)->vm, (vcpu)->vcpuid, format, p1, p2, p3)
210 
211 #define	VMM_CTR4(vcpu, format, p1, p2, p3, p4)				\
212 	VCPU_CTR4((vcpu)->vm, (vcpu)->vcpuid, format, p1, p2, p3, p4)
213 
214 static int vmm_initialized;
215 
216 static void	vmmops_panic(void);
217 
218 static void
219 vmmops_panic(void)
220 {
221 	panic("vmm_ops func called when !vmm_is_intel() && !vmm_is_svm()");
222 }
223 
224 #define	DEFINE_VMMOPS_IFUNC(ret_type, opname, args)			\
225     DEFINE_IFUNC(static, ret_type, vmmops_##opname, args)		\
226     {									\
227     	if (vmm_is_intel())						\
228     		return (vmm_ops_intel.opname);				\
229     	else if (vmm_is_svm())						\
230     		return (vmm_ops_amd.opname);				\
231     	else								\
232     		return ((ret_type (*)args)vmmops_panic);		\
233     }
234 
235 DEFINE_VMMOPS_IFUNC(int, modinit, (int ipinum))
236 DEFINE_VMMOPS_IFUNC(int, modcleanup, (void))
237 DEFINE_VMMOPS_IFUNC(void, modresume, (void))
238 DEFINE_VMMOPS_IFUNC(void *, init, (struct vm *vm, struct pmap *pmap))
239 DEFINE_VMMOPS_IFUNC(int, run, (void *vcpui, register_t rip, struct pmap *pmap,
240     struct vm_eventinfo *info))
241 DEFINE_VMMOPS_IFUNC(void, cleanup, (void *vmi))
242 DEFINE_VMMOPS_IFUNC(void *, vcpu_init, (void *vmi, struct vcpu *vcpu,
243     int vcpu_id))
244 DEFINE_VMMOPS_IFUNC(void, vcpu_cleanup, (void *vcpui))
245 DEFINE_VMMOPS_IFUNC(int, getreg, (void *vcpui, int num, uint64_t *retval))
246 DEFINE_VMMOPS_IFUNC(int, setreg, (void *vcpui, int num, uint64_t val))
247 DEFINE_VMMOPS_IFUNC(int, getdesc, (void *vcpui, int num, struct seg_desc *desc))
248 DEFINE_VMMOPS_IFUNC(int, setdesc, (void *vcpui, int num, struct seg_desc *desc))
249 DEFINE_VMMOPS_IFUNC(int, getcap, (void *vcpui, int num, int *retval))
250 DEFINE_VMMOPS_IFUNC(int, setcap, (void *vcpui, int num, int val))
251 DEFINE_VMMOPS_IFUNC(struct vmspace *, vmspace_alloc, (vm_offset_t min,
252     vm_offset_t max))
253 DEFINE_VMMOPS_IFUNC(void, vmspace_free, (struct vmspace *vmspace))
254 DEFINE_VMMOPS_IFUNC(struct vlapic *, vlapic_init, (void *vcpui))
255 DEFINE_VMMOPS_IFUNC(void, vlapic_cleanup, (struct vlapic *vlapic))
256 #ifdef BHYVE_SNAPSHOT
257 DEFINE_VMMOPS_IFUNC(int, snapshot, (void *vmi, struct vm_snapshot_meta *meta))
258 DEFINE_VMMOPS_IFUNC(int, vcpu_snapshot, (void *vcpui,
259     struct vm_snapshot_meta *meta))
260 DEFINE_VMMOPS_IFUNC(int, restore_tsc, (void *vcpui, uint64_t now))
261 #endif
262 
263 #define	fpu_start_emulating()	load_cr0(rcr0() | CR0_TS)
264 #define	fpu_stop_emulating()	clts()
265 
266 SDT_PROVIDER_DEFINE(vmm);
267 
268 static MALLOC_DEFINE(M_VM, "vm", "vm");
269 
270 /* statistics */
271 static VMM_STAT(VCPU_TOTAL_RUNTIME, "vcpu total runtime");
272 
273 SYSCTL_NODE(_hw, OID_AUTO, vmm, CTLFLAG_RW | CTLFLAG_MPSAFE, NULL,
274     NULL);
275 
276 /*
277  * Halt the guest if all vcpus are executing a HLT instruction with
278  * interrupts disabled.
279  */
280 static int halt_detection_enabled = 1;
281 SYSCTL_INT(_hw_vmm, OID_AUTO, halt_detection, CTLFLAG_RDTUN,
282     &halt_detection_enabled, 0,
283     "Halt VM if all vcpus execute HLT with interrupts disabled");
284 
285 static int vmm_ipinum;
286 SYSCTL_INT(_hw_vmm, OID_AUTO, ipinum, CTLFLAG_RD, &vmm_ipinum, 0,
287     "IPI vector used for vcpu notifications");
288 
289 static int trace_guest_exceptions;
290 SYSCTL_INT(_hw_vmm, OID_AUTO, trace_guest_exceptions, CTLFLAG_RDTUN,
291     &trace_guest_exceptions, 0,
292     "Trap into hypervisor on all guest exceptions and reflect them back");
293 
294 static int trap_wbinvd;
295 SYSCTL_INT(_hw_vmm, OID_AUTO, trap_wbinvd, CTLFLAG_RDTUN, &trap_wbinvd, 0,
296     "WBINVD triggers a VM-exit");
297 
298 u_int vm_maxcpu;
299 SYSCTL_UINT(_hw_vmm, OID_AUTO, maxcpu, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
300     &vm_maxcpu, 0, "Maximum number of vCPUs");
301 
302 static void vm_free_memmap(struct vm *vm, int ident);
303 static bool sysmem_mapping(struct vm *vm, struct mem_map *mm);
304 static void vcpu_notify_event_locked(struct vcpu *vcpu, bool lapic_intr);
305 
306 /*
307  * Upper limit on vm_maxcpu.  Limited by use of uint16_t types for CPU
308  * counts as well as range of vpid values for VT-x and by the capacity
309  * of cpuset_t masks.  The call to new_unrhdr() in vpid_init() in
310  * vmx.c requires 'vm_maxcpu + 1 <= 0xffff', hence the '- 1' below.
311  */
312 #define	VM_MAXCPU	MIN(0xffff - 1, CPU_SETSIZE)
313 
314 #ifdef KTR
315 static const char *
316 vcpu_state2str(enum vcpu_state state)
317 {
318 
319 	switch (state) {
320 	case VCPU_IDLE:
321 		return ("idle");
322 	case VCPU_FROZEN:
323 		return ("frozen");
324 	case VCPU_RUNNING:
325 		return ("running");
326 	case VCPU_SLEEPING:
327 		return ("sleeping");
328 	default:
329 		return ("unknown");
330 	}
331 }
332 #endif
333 
334 static void
335 vcpu_cleanup(struct vcpu *vcpu, bool destroy)
336 {
337 	vmmops_vlapic_cleanup(vcpu->vlapic);
338 	vmmops_vcpu_cleanup(vcpu->cookie);
339 	vcpu->cookie = NULL;
340 	if (destroy) {
341 		vmm_stat_free(vcpu->stats);
342 		fpu_save_area_free(vcpu->guestfpu);
343 		vcpu_lock_destroy(vcpu);
344 	}
345 }
346 
347 static struct vcpu *
348 vcpu_alloc(struct vm *vm, int vcpu_id)
349 {
350 	struct vcpu *vcpu;
351 
352 	KASSERT(vcpu_id >= 0 && vcpu_id < vm->maxcpus,
353 	    ("vcpu_init: invalid vcpu %d", vcpu_id));
354 
355 	vcpu = malloc(sizeof(*vcpu), M_VM, M_WAITOK | M_ZERO);
356 	vcpu_lock_init(vcpu);
357 	vcpu->state = VCPU_IDLE;
358 	vcpu->hostcpu = NOCPU;
359 	vcpu->vcpuid = vcpu_id;
360 	vcpu->vm = vm;
361 	vcpu->guestfpu = fpu_save_area_alloc();
362 	vcpu->stats = vmm_stat_alloc();
363 	vcpu->tsc_offset = 0;
364 	return (vcpu);
365 }
366 
367 static void
368 vcpu_init(struct vcpu *vcpu)
369 {
370 	vcpu->cookie = vmmops_vcpu_init(vcpu->vm->cookie, vcpu, vcpu->vcpuid);
371 	vcpu->vlapic = vmmops_vlapic_init(vcpu->cookie);
372 	vm_set_x2apic_state(vcpu, X2APIC_DISABLED);
373 	vcpu->reqidle = 0;
374 	vcpu->exitintinfo = 0;
375 	vcpu->nmi_pending = 0;
376 	vcpu->extint_pending = 0;
377 	vcpu->exception_pending = 0;
378 	vcpu->guest_xcr0 = XFEATURE_ENABLED_X87;
379 	fpu_save_area_reset(vcpu->guestfpu);
380 	vmm_stat_init(vcpu->stats);
381 }
382 
383 int
384 vcpu_trace_exceptions(struct vcpu *vcpu)
385 {
386 
387 	return (trace_guest_exceptions);
388 }
389 
390 int
391 vcpu_trap_wbinvd(struct vcpu *vcpu)
392 {
393 	return (trap_wbinvd);
394 }
395 
396 struct vm_exit *
397 vm_exitinfo(struct vcpu *vcpu)
398 {
399 	return (&vcpu->exitinfo);
400 }
401 
402 static int
403 vmm_init(void)
404 {
405 	int error;
406 
407 	if (!vmm_is_hw_supported())
408 		return (ENXIO);
409 
410 	vm_maxcpu = mp_ncpus;
411 	TUNABLE_INT_FETCH("hw.vmm.maxcpu", &vm_maxcpu);
412 
413 	if (vm_maxcpu > VM_MAXCPU) {
414 		printf("vmm: vm_maxcpu clamped to %u\n", VM_MAXCPU);
415 		vm_maxcpu = VM_MAXCPU;
416 	}
417 	if (vm_maxcpu == 0)
418 		vm_maxcpu = 1;
419 
420 	vmm_host_state_init();
421 
422 	vmm_ipinum = lapic_ipi_alloc(pti ? &IDTVEC(justreturn1_pti) :
423 	    &IDTVEC(justreturn));
424 	if (vmm_ipinum < 0)
425 		vmm_ipinum = IPI_AST;
426 
427 	error = vmm_mem_init();
428 	if (error)
429 		return (error);
430 
431 	vmm_resume_p = vmmops_modresume;
432 
433 	return (vmmops_modinit(vmm_ipinum));
434 }
435 
436 static int
437 vmm_handler(module_t mod, int what, void *arg)
438 {
439 	int error;
440 
441 	switch (what) {
442 	case MOD_LOAD:
443 		if (vmm_is_hw_supported()) {
444 			vmmdev_init();
445 			error = vmm_init();
446 			if (error == 0)
447 				vmm_initialized = 1;
448 		} else {
449 			error = ENXIO;
450 		}
451 		break;
452 	case MOD_UNLOAD:
453 		if (vmm_is_hw_supported()) {
454 			error = vmmdev_cleanup();
455 			if (error == 0) {
456 				vmm_resume_p = NULL;
457 				iommu_cleanup();
458 				if (vmm_ipinum != IPI_AST)
459 					lapic_ipi_free(vmm_ipinum);
460 				error = vmmops_modcleanup();
461 				/*
462 				 * Something bad happened - prevent new
463 				 * VMs from being created
464 				 */
465 				if (error)
466 					vmm_initialized = 0;
467 			}
468 		} else {
469 			error = 0;
470 		}
471 		break;
472 	default:
473 		error = 0;
474 		break;
475 	}
476 	return (error);
477 }
478 
479 static moduledata_t vmm_kmod = {
480 	"vmm",
481 	vmm_handler,
482 	NULL
483 };
484 
485 /*
486  * vmm initialization has the following dependencies:
487  *
488  * - VT-x initialization requires smp_rendezvous() and therefore must happen
489  *   after SMP is fully functional (after SI_SUB_SMP).
490  */
491 DECLARE_MODULE(vmm, vmm_kmod, SI_SUB_SMP + 1, SI_ORDER_ANY);
492 MODULE_VERSION(vmm, 1);
493 
494 static void
495 vm_init(struct vm *vm, bool create)
496 {
497 	vm->cookie = vmmops_init(vm, vmspace_pmap(vm->vmspace));
498 	vm->iommu = NULL;
499 	vm->vioapic = vioapic_init(vm);
500 	vm->vhpet = vhpet_init(vm);
501 	vm->vatpic = vatpic_init(vm);
502 	vm->vatpit = vatpit_init(vm);
503 	vm->vpmtmr = vpmtmr_init(vm);
504 	if (create)
505 		vm->vrtc = vrtc_init(vm);
506 
507 	CPU_ZERO(&vm->active_cpus);
508 	CPU_ZERO(&vm->debug_cpus);
509 	CPU_ZERO(&vm->startup_cpus);
510 
511 	vm->suspend = 0;
512 	CPU_ZERO(&vm->suspended_cpus);
513 
514 	if (!create) {
515 		for (int i = 0; i < vm->maxcpus; i++) {
516 			if (vm->vcpu[i] != NULL)
517 				vcpu_init(vm->vcpu[i]);
518 		}
519 	}
520 }
521 
522 void
523 vm_disable_vcpu_creation(struct vm *vm)
524 {
525 	sx_xlock(&vm->vcpus_init_lock);
526 	vm->dying = true;
527 	sx_xunlock(&vm->vcpus_init_lock);
528 }
529 
530 struct vcpu *
531 vm_alloc_vcpu(struct vm *vm, int vcpuid)
532 {
533 	struct vcpu *vcpu;
534 
535 	if (vcpuid < 0 || vcpuid >= vm_get_maxcpus(vm))
536 		return (NULL);
537 
538 	vcpu = atomic_load_ptr(&vm->vcpu[vcpuid]);
539 	if (__predict_true(vcpu != NULL))
540 		return (vcpu);
541 
542 	sx_xlock(&vm->vcpus_init_lock);
543 	vcpu = vm->vcpu[vcpuid];
544 	if (vcpu == NULL && !vm->dying) {
545 		vcpu = vcpu_alloc(vm, vcpuid);
546 		vcpu_init(vcpu);
547 
548 		/*
549 		 * Ensure vCPU is fully created before updating pointer
550 		 * to permit unlocked reads above.
551 		 */
552 		atomic_store_rel_ptr((uintptr_t *)&vm->vcpu[vcpuid],
553 		    (uintptr_t)vcpu);
554 	}
555 	sx_xunlock(&vm->vcpus_init_lock);
556 	return (vcpu);
557 }
558 
559 void
560 vm_slock_vcpus(struct vm *vm)
561 {
562 	sx_slock(&vm->vcpus_init_lock);
563 }
564 
565 void
566 vm_unlock_vcpus(struct vm *vm)
567 {
568 	sx_unlock(&vm->vcpus_init_lock);
569 }
570 
571 /*
572  * The default CPU topology is a single thread per package.
573  */
574 u_int cores_per_package = 1;
575 u_int threads_per_core = 1;
576 
577 int
578 vm_create(const char *name, struct vm **retvm)
579 {
580 	struct vm *vm;
581 	struct vmspace *vmspace;
582 
583 	/*
584 	 * If vmm.ko could not be successfully initialized then don't attempt
585 	 * to create the virtual machine.
586 	 */
587 	if (!vmm_initialized)
588 		return (ENXIO);
589 
590 	if (name == NULL || strnlen(name, VM_MAX_NAMELEN + 1) ==
591 	    VM_MAX_NAMELEN + 1)
592 		return (EINVAL);
593 
594 	vmspace = vmmops_vmspace_alloc(0, VM_MAXUSER_ADDRESS_LA48);
595 	if (vmspace == NULL)
596 		return (ENOMEM);
597 
598 	vm = malloc(sizeof(struct vm), M_VM, M_WAITOK | M_ZERO);
599 	strcpy(vm->name, name);
600 	vm->vmspace = vmspace;
601 	mtx_init(&vm->rendezvous_mtx, "vm rendezvous lock", 0, MTX_DEF);
602 	sx_init(&vm->mem_segs_lock, "vm mem_segs");
603 	sx_init(&vm->vcpus_init_lock, "vm vcpus");
604 	vm->vcpu = malloc(sizeof(*vm->vcpu) * vm_maxcpu, M_VM, M_WAITOK |
605 	    M_ZERO);
606 
607 	vm->sockets = 1;
608 	vm->cores = cores_per_package;	/* XXX backwards compatibility */
609 	vm->threads = threads_per_core;	/* XXX backwards compatibility */
610 	vm->maxcpus = vm_maxcpu;
611 
612 	vm_init(vm, true);
613 
614 	*retvm = vm;
615 	return (0);
616 }
617 
618 void
619 vm_get_topology(struct vm *vm, uint16_t *sockets, uint16_t *cores,
620     uint16_t *threads, uint16_t *maxcpus)
621 {
622 	*sockets = vm->sockets;
623 	*cores = vm->cores;
624 	*threads = vm->threads;
625 	*maxcpus = vm->maxcpus;
626 }
627 
628 uint16_t
629 vm_get_maxcpus(struct vm *vm)
630 {
631 	return (vm->maxcpus);
632 }
633 
634 int
635 vm_set_topology(struct vm *vm, uint16_t sockets, uint16_t cores,
636     uint16_t threads, uint16_t maxcpus __unused)
637 {
638 	/* Ignore maxcpus. */
639 	if ((sockets * cores * threads) > vm->maxcpus)
640 		return (EINVAL);
641 	vm->sockets = sockets;
642 	vm->cores = cores;
643 	vm->threads = threads;
644 	return(0);
645 }
646 
647 static void
648 vm_cleanup(struct vm *vm, bool destroy)
649 {
650 	struct mem_map *mm;
651 	int i;
652 
653 	ppt_unassign_all(vm);
654 
655 	if (vm->iommu != NULL)
656 		iommu_destroy_domain(vm->iommu);
657 
658 	if (destroy)
659 		vrtc_cleanup(vm->vrtc);
660 	else
661 		vrtc_reset(vm->vrtc);
662 	vpmtmr_cleanup(vm->vpmtmr);
663 	vatpit_cleanup(vm->vatpit);
664 	vhpet_cleanup(vm->vhpet);
665 	vatpic_cleanup(vm->vatpic);
666 	vioapic_cleanup(vm->vioapic);
667 
668 	for (i = 0; i < vm->maxcpus; i++) {
669 		if (vm->vcpu[i] != NULL)
670 			vcpu_cleanup(vm->vcpu[i], destroy);
671 	}
672 
673 	vmmops_cleanup(vm->cookie);
674 
675 	/*
676 	 * System memory is removed from the guest address space only when
677 	 * the VM is destroyed. This is because the mapping remains the same
678 	 * across VM reset.
679 	 *
680 	 * Device memory can be relocated by the guest (e.g. using PCI BARs)
681 	 * so those mappings are removed on a VM reset.
682 	 */
683 	for (i = 0; i < VM_MAX_MEMMAPS; i++) {
684 		mm = &vm->mem_maps[i];
685 		if (destroy || !sysmem_mapping(vm, mm))
686 			vm_free_memmap(vm, i);
687 	}
688 
689 	if (destroy) {
690 		for (i = 0; i < VM_MAX_MEMSEGS; i++)
691 			vm_free_memseg(vm, i);
692 
693 		vmmops_vmspace_free(vm->vmspace);
694 		vm->vmspace = NULL;
695 
696 		free(vm->vcpu, M_VM);
697 		sx_destroy(&vm->vcpus_init_lock);
698 		sx_destroy(&vm->mem_segs_lock);
699 		mtx_destroy(&vm->rendezvous_mtx);
700 	}
701 }
702 
703 void
704 vm_destroy(struct vm *vm)
705 {
706 	vm_cleanup(vm, true);
707 	free(vm, M_VM);
708 }
709 
710 int
711 vm_reinit(struct vm *vm)
712 {
713 	int error;
714 
715 	/*
716 	 * A virtual machine can be reset only if all vcpus are suspended.
717 	 */
718 	if (CPU_CMP(&vm->suspended_cpus, &vm->active_cpus) == 0) {
719 		vm_cleanup(vm, false);
720 		vm_init(vm, false);
721 		error = 0;
722 	} else {
723 		error = EBUSY;
724 	}
725 
726 	return (error);
727 }
728 
729 const char *
730 vm_name(struct vm *vm)
731 {
732 	return (vm->name);
733 }
734 
735 void
736 vm_slock_memsegs(struct vm *vm)
737 {
738 	sx_slock(&vm->mem_segs_lock);
739 }
740 
741 void
742 vm_xlock_memsegs(struct vm *vm)
743 {
744 	sx_xlock(&vm->mem_segs_lock);
745 }
746 
747 void
748 vm_unlock_memsegs(struct vm *vm)
749 {
750 	sx_unlock(&vm->mem_segs_lock);
751 }
752 
753 int
754 vm_map_mmio(struct vm *vm, vm_paddr_t gpa, size_t len, vm_paddr_t hpa)
755 {
756 	vm_object_t obj;
757 
758 	if ((obj = vmm_mmio_alloc(vm->vmspace, gpa, len, hpa)) == NULL)
759 		return (ENOMEM);
760 	else
761 		return (0);
762 }
763 
764 int
765 vm_unmap_mmio(struct vm *vm, vm_paddr_t gpa, size_t len)
766 {
767 
768 	vmm_mmio_free(vm->vmspace, gpa, len);
769 	return (0);
770 }
771 
772 /*
773  * Return 'true' if 'gpa' is allocated in the guest address space.
774  *
775  * This function is called in the context of a running vcpu which acts as
776  * an implicit lock on 'vm->mem_maps[]'.
777  */
778 bool
779 vm_mem_allocated(struct vcpu *vcpu, vm_paddr_t gpa)
780 {
781 	struct vm *vm = vcpu->vm;
782 	struct mem_map *mm;
783 	int i;
784 
785 #ifdef INVARIANTS
786 	int hostcpu, state;
787 	state = vcpu_get_state(vcpu, &hostcpu);
788 	KASSERT(state == VCPU_RUNNING && hostcpu == curcpu,
789 	    ("%s: invalid vcpu state %d/%d", __func__, state, hostcpu));
790 #endif
791 
792 	for (i = 0; i < VM_MAX_MEMMAPS; i++) {
793 		mm = &vm->mem_maps[i];
794 		if (mm->len != 0 && gpa >= mm->gpa && gpa < mm->gpa + mm->len)
795 			return (true);		/* 'gpa' is sysmem or devmem */
796 	}
797 
798 	if (ppt_is_mmio(vm, gpa))
799 		return (true);			/* 'gpa' is pci passthru mmio */
800 
801 	return (false);
802 }
803 
804 int
805 vm_alloc_memseg(struct vm *vm, int ident, size_t len, bool sysmem)
806 {
807 	struct mem_seg *seg;
808 	vm_object_t obj;
809 
810 	sx_assert(&vm->mem_segs_lock, SX_XLOCKED);
811 
812 	if (ident < 0 || ident >= VM_MAX_MEMSEGS)
813 		return (EINVAL);
814 
815 	if (len == 0 || (len & PAGE_MASK))
816 		return (EINVAL);
817 
818 	seg = &vm->mem_segs[ident];
819 	if (seg->object != NULL) {
820 		if (seg->len == len && seg->sysmem == sysmem)
821 			return (EEXIST);
822 		else
823 			return (EINVAL);
824 	}
825 
826 	obj = vm_object_allocate(OBJT_SWAP, len >> PAGE_SHIFT);
827 	if (obj == NULL)
828 		return (ENOMEM);
829 
830 	seg->len = len;
831 	seg->object = obj;
832 	seg->sysmem = sysmem;
833 	return (0);
834 }
835 
836 int
837 vm_get_memseg(struct vm *vm, int ident, size_t *len, bool *sysmem,
838     vm_object_t *objptr)
839 {
840 	struct mem_seg *seg;
841 
842 	sx_assert(&vm->mem_segs_lock, SX_LOCKED);
843 
844 	if (ident < 0 || ident >= VM_MAX_MEMSEGS)
845 		return (EINVAL);
846 
847 	seg = &vm->mem_segs[ident];
848 	if (len)
849 		*len = seg->len;
850 	if (sysmem)
851 		*sysmem = seg->sysmem;
852 	if (objptr)
853 		*objptr = seg->object;
854 	return (0);
855 }
856 
857 void
858 vm_free_memseg(struct vm *vm, int ident)
859 {
860 	struct mem_seg *seg;
861 
862 	KASSERT(ident >= 0 && ident < VM_MAX_MEMSEGS,
863 	    ("%s: invalid memseg ident %d", __func__, ident));
864 
865 	seg = &vm->mem_segs[ident];
866 	if (seg->object != NULL) {
867 		vm_object_deallocate(seg->object);
868 		bzero(seg, sizeof(struct mem_seg));
869 	}
870 }
871 
872 int
873 vm_mmap_memseg(struct vm *vm, vm_paddr_t gpa, int segid, vm_ooffset_t first,
874     size_t len, int prot, int flags)
875 {
876 	struct mem_seg *seg;
877 	struct mem_map *m, *map;
878 	vm_ooffset_t last;
879 	int i, error;
880 
881 	if (prot == 0 || (prot & ~(VM_PROT_ALL)) != 0)
882 		return (EINVAL);
883 
884 	if (flags & ~VM_MEMMAP_F_WIRED)
885 		return (EINVAL);
886 
887 	if (segid < 0 || segid >= VM_MAX_MEMSEGS)
888 		return (EINVAL);
889 
890 	seg = &vm->mem_segs[segid];
891 	if (seg->object == NULL)
892 		return (EINVAL);
893 
894 	last = first + len;
895 	if (first < 0 || first >= last || last > seg->len)
896 		return (EINVAL);
897 
898 	if ((gpa | first | last) & PAGE_MASK)
899 		return (EINVAL);
900 
901 	map = NULL;
902 	for (i = 0; i < VM_MAX_MEMMAPS; i++) {
903 		m = &vm->mem_maps[i];
904 		if (m->len == 0) {
905 			map = m;
906 			break;
907 		}
908 	}
909 
910 	if (map == NULL)
911 		return (ENOSPC);
912 
913 	error = vm_map_find(&vm->vmspace->vm_map, seg->object, first, &gpa,
914 	    len, 0, VMFS_NO_SPACE, prot, prot, 0);
915 	if (error != KERN_SUCCESS)
916 		return (EFAULT);
917 
918 	vm_object_reference(seg->object);
919 
920 	if (flags & VM_MEMMAP_F_WIRED) {
921 		error = vm_map_wire(&vm->vmspace->vm_map, gpa, gpa + len,
922 		    VM_MAP_WIRE_USER | VM_MAP_WIRE_NOHOLES);
923 		if (error != KERN_SUCCESS) {
924 			vm_map_remove(&vm->vmspace->vm_map, gpa, gpa + len);
925 			return (error == KERN_RESOURCE_SHORTAGE ? ENOMEM :
926 			    EFAULT);
927 		}
928 	}
929 
930 	map->gpa = gpa;
931 	map->len = len;
932 	map->segoff = first;
933 	map->segid = segid;
934 	map->prot = prot;
935 	map->flags = flags;
936 	return (0);
937 }
938 
939 int
940 vm_munmap_memseg(struct vm *vm, vm_paddr_t gpa, size_t len)
941 {
942 	struct mem_map *m;
943 	int i;
944 
945 	for (i = 0; i < VM_MAX_MEMMAPS; i++) {
946 		m = &vm->mem_maps[i];
947 		if (m->gpa == gpa && m->len == len &&
948 		    (m->flags & VM_MEMMAP_F_IOMMU) == 0) {
949 			vm_free_memmap(vm, i);
950 			return (0);
951 		}
952 	}
953 
954 	return (EINVAL);
955 }
956 
957 int
958 vm_mmap_getnext(struct vm *vm, vm_paddr_t *gpa, int *segid,
959     vm_ooffset_t *segoff, size_t *len, int *prot, int *flags)
960 {
961 	struct mem_map *mm, *mmnext;
962 	int i;
963 
964 	mmnext = NULL;
965 	for (i = 0; i < VM_MAX_MEMMAPS; i++) {
966 		mm = &vm->mem_maps[i];
967 		if (mm->len == 0 || mm->gpa < *gpa)
968 			continue;
969 		if (mmnext == NULL || mm->gpa < mmnext->gpa)
970 			mmnext = mm;
971 	}
972 
973 	if (mmnext != NULL) {
974 		*gpa = mmnext->gpa;
975 		if (segid)
976 			*segid = mmnext->segid;
977 		if (segoff)
978 			*segoff = mmnext->segoff;
979 		if (len)
980 			*len = mmnext->len;
981 		if (prot)
982 			*prot = mmnext->prot;
983 		if (flags)
984 			*flags = mmnext->flags;
985 		return (0);
986 	} else {
987 		return (ENOENT);
988 	}
989 }
990 
991 static void
992 vm_free_memmap(struct vm *vm, int ident)
993 {
994 	struct mem_map *mm;
995 	int error __diagused;
996 
997 	mm = &vm->mem_maps[ident];
998 	if (mm->len) {
999 		error = vm_map_remove(&vm->vmspace->vm_map, mm->gpa,
1000 		    mm->gpa + mm->len);
1001 		KASSERT(error == KERN_SUCCESS, ("%s: vm_map_remove error %d",
1002 		    __func__, error));
1003 		bzero(mm, sizeof(struct mem_map));
1004 	}
1005 }
1006 
1007 static __inline bool
1008 sysmem_mapping(struct vm *vm, struct mem_map *mm)
1009 {
1010 
1011 	if (mm->len != 0 && vm->mem_segs[mm->segid].sysmem)
1012 		return (true);
1013 	else
1014 		return (false);
1015 }
1016 
1017 vm_paddr_t
1018 vmm_sysmem_maxaddr(struct vm *vm)
1019 {
1020 	struct mem_map *mm;
1021 	vm_paddr_t maxaddr;
1022 	int i;
1023 
1024 	maxaddr = 0;
1025 	for (i = 0; i < VM_MAX_MEMMAPS; i++) {
1026 		mm = &vm->mem_maps[i];
1027 		if (sysmem_mapping(vm, mm)) {
1028 			if (maxaddr < mm->gpa + mm->len)
1029 				maxaddr = mm->gpa + mm->len;
1030 		}
1031 	}
1032 	return (maxaddr);
1033 }
1034 
1035 static void
1036 vm_iommu_modify(struct vm *vm, bool map)
1037 {
1038 	int i, sz;
1039 	vm_paddr_t gpa, hpa;
1040 	struct mem_map *mm;
1041 	void *vp, *cookie, *host_domain;
1042 
1043 	sz = PAGE_SIZE;
1044 	host_domain = iommu_host_domain();
1045 
1046 	for (i = 0; i < VM_MAX_MEMMAPS; i++) {
1047 		mm = &vm->mem_maps[i];
1048 		if (!sysmem_mapping(vm, mm))
1049 			continue;
1050 
1051 		if (map) {
1052 			KASSERT((mm->flags & VM_MEMMAP_F_IOMMU) == 0,
1053 			    ("iommu map found invalid memmap %#lx/%#lx/%#x",
1054 			    mm->gpa, mm->len, mm->flags));
1055 			if ((mm->flags & VM_MEMMAP_F_WIRED) == 0)
1056 				continue;
1057 			mm->flags |= VM_MEMMAP_F_IOMMU;
1058 		} else {
1059 			if ((mm->flags & VM_MEMMAP_F_IOMMU) == 0)
1060 				continue;
1061 			mm->flags &= ~VM_MEMMAP_F_IOMMU;
1062 			KASSERT((mm->flags & VM_MEMMAP_F_WIRED) != 0,
1063 			    ("iommu unmap found invalid memmap %#lx/%#lx/%#x",
1064 			    mm->gpa, mm->len, mm->flags));
1065 		}
1066 
1067 		gpa = mm->gpa;
1068 		while (gpa < mm->gpa + mm->len) {
1069 			vp = vm_gpa_hold_global(vm, gpa, PAGE_SIZE,
1070 			    VM_PROT_WRITE, &cookie);
1071 			KASSERT(vp != NULL, ("vm(%s) could not map gpa %#lx",
1072 			    vm_name(vm), gpa));
1073 
1074 			vm_gpa_release(cookie);
1075 
1076 			hpa = DMAP_TO_PHYS((uintptr_t)vp);
1077 			if (map) {
1078 				iommu_create_mapping(vm->iommu, gpa, hpa, sz);
1079 			} else {
1080 				iommu_remove_mapping(vm->iommu, gpa, sz);
1081 			}
1082 
1083 			gpa += PAGE_SIZE;
1084 		}
1085 	}
1086 
1087 	/*
1088 	 * Invalidate the cached translations associated with the domain
1089 	 * from which pages were removed.
1090 	 */
1091 	if (map)
1092 		iommu_invalidate_tlb(host_domain);
1093 	else
1094 		iommu_invalidate_tlb(vm->iommu);
1095 }
1096 
1097 #define	vm_iommu_unmap(vm)	vm_iommu_modify((vm), false)
1098 #define	vm_iommu_map(vm)	vm_iommu_modify((vm), true)
1099 
1100 int
1101 vm_unassign_pptdev(struct vm *vm, int bus, int slot, int func)
1102 {
1103 	int error;
1104 
1105 	error = ppt_unassign_device(vm, bus, slot, func);
1106 	if (error)
1107 		return (error);
1108 
1109 	if (ppt_assigned_devices(vm) == 0)
1110 		vm_iommu_unmap(vm);
1111 
1112 	return (0);
1113 }
1114 
1115 int
1116 vm_assign_pptdev(struct vm *vm, int bus, int slot, int func)
1117 {
1118 	int error;
1119 	vm_paddr_t maxaddr;
1120 
1121 	/* Set up the IOMMU to do the 'gpa' to 'hpa' translation */
1122 	if (ppt_assigned_devices(vm) == 0) {
1123 		KASSERT(vm->iommu == NULL,
1124 		    ("vm_assign_pptdev: iommu must be NULL"));
1125 		maxaddr = vmm_sysmem_maxaddr(vm);
1126 		vm->iommu = iommu_create_domain(maxaddr);
1127 		if (vm->iommu == NULL)
1128 			return (ENXIO);
1129 		vm_iommu_map(vm);
1130 	}
1131 
1132 	error = ppt_assign_device(vm, bus, slot, func);
1133 	return (error);
1134 }
1135 
1136 static void *
1137 _vm_gpa_hold(struct vm *vm, vm_paddr_t gpa, size_t len, int reqprot,
1138     void **cookie)
1139 {
1140 	int i, count, pageoff;
1141 	struct mem_map *mm;
1142 	vm_page_t m;
1143 
1144 	pageoff = gpa & PAGE_MASK;
1145 	if (len > PAGE_SIZE - pageoff)
1146 		panic("vm_gpa_hold: invalid gpa/len: 0x%016lx/%lu", gpa, len);
1147 
1148 	count = 0;
1149 	for (i = 0; i < VM_MAX_MEMMAPS; i++) {
1150 		mm = &vm->mem_maps[i];
1151 		if (gpa >= mm->gpa && gpa < mm->gpa + mm->len) {
1152 			count = vm_fault_quick_hold_pages(&vm->vmspace->vm_map,
1153 			    trunc_page(gpa), PAGE_SIZE, reqprot, &m, 1);
1154 			break;
1155 		}
1156 	}
1157 
1158 	if (count == 1) {
1159 		*cookie = m;
1160 		return ((void *)(PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m)) + pageoff));
1161 	} else {
1162 		*cookie = NULL;
1163 		return (NULL);
1164 	}
1165 }
1166 
1167 void *
1168 vm_gpa_hold(struct vcpu *vcpu, vm_paddr_t gpa, size_t len, int reqprot,
1169     void **cookie)
1170 {
1171 #ifdef INVARIANTS
1172 	/*
1173 	 * The current vcpu should be frozen to ensure 'vm_memmap[]'
1174 	 * stability.
1175 	 */
1176 	int state = vcpu_get_state(vcpu, NULL);
1177 	KASSERT(state == VCPU_FROZEN, ("%s: invalid vcpu state %d",
1178 	    __func__, state));
1179 #endif
1180 	return (_vm_gpa_hold(vcpu->vm, gpa, len, reqprot, cookie));
1181 }
1182 
1183 void *
1184 vm_gpa_hold_global(struct vm *vm, vm_paddr_t gpa, size_t len, int reqprot,
1185     void **cookie)
1186 {
1187 	sx_assert(&vm->mem_segs_lock, SX_LOCKED);
1188 	return (_vm_gpa_hold(vm, gpa, len, reqprot, cookie));
1189 }
1190 
1191 void
1192 vm_gpa_release(void *cookie)
1193 {
1194 	vm_page_t m = cookie;
1195 
1196 	vm_page_unwire(m, PQ_ACTIVE);
1197 }
1198 
1199 int
1200 vm_get_register(struct vcpu *vcpu, int reg, uint64_t *retval)
1201 {
1202 
1203 	if (reg >= VM_REG_LAST)
1204 		return (EINVAL);
1205 
1206 	return (vmmops_getreg(vcpu->cookie, reg, retval));
1207 }
1208 
1209 int
1210 vm_set_register(struct vcpu *vcpu, int reg, uint64_t val)
1211 {
1212 	int error;
1213 
1214 	if (reg >= VM_REG_LAST)
1215 		return (EINVAL);
1216 
1217 	error = vmmops_setreg(vcpu->cookie, reg, val);
1218 	if (error || reg != VM_REG_GUEST_RIP)
1219 		return (error);
1220 
1221 	/* Set 'nextrip' to match the value of %rip */
1222 	VMM_CTR1(vcpu, "Setting nextrip to %#lx", val);
1223 	vcpu->nextrip = val;
1224 	return (0);
1225 }
1226 
1227 static bool
1228 is_descriptor_table(int reg)
1229 {
1230 
1231 	switch (reg) {
1232 	case VM_REG_GUEST_IDTR:
1233 	case VM_REG_GUEST_GDTR:
1234 		return (true);
1235 	default:
1236 		return (false);
1237 	}
1238 }
1239 
1240 static bool
1241 is_segment_register(int reg)
1242 {
1243 
1244 	switch (reg) {
1245 	case VM_REG_GUEST_ES:
1246 	case VM_REG_GUEST_CS:
1247 	case VM_REG_GUEST_SS:
1248 	case VM_REG_GUEST_DS:
1249 	case VM_REG_GUEST_FS:
1250 	case VM_REG_GUEST_GS:
1251 	case VM_REG_GUEST_TR:
1252 	case VM_REG_GUEST_LDTR:
1253 		return (true);
1254 	default:
1255 		return (false);
1256 	}
1257 }
1258 
1259 int
1260 vm_get_seg_desc(struct vcpu *vcpu, int reg, struct seg_desc *desc)
1261 {
1262 
1263 	if (!is_segment_register(reg) && !is_descriptor_table(reg))
1264 		return (EINVAL);
1265 
1266 	return (vmmops_getdesc(vcpu->cookie, reg, desc));
1267 }
1268 
1269 int
1270 vm_set_seg_desc(struct vcpu *vcpu, int reg, struct seg_desc *desc)
1271 {
1272 
1273 	if (!is_segment_register(reg) && !is_descriptor_table(reg))
1274 		return (EINVAL);
1275 
1276 	return (vmmops_setdesc(vcpu->cookie, reg, desc));
1277 }
1278 
1279 static void
1280 restore_guest_fpustate(struct vcpu *vcpu)
1281 {
1282 
1283 	/* flush host state to the pcb */
1284 	fpuexit(curthread);
1285 
1286 	/* restore guest FPU state */
1287 	fpu_stop_emulating();
1288 	fpurestore(vcpu->guestfpu);
1289 
1290 	/* restore guest XCR0 if XSAVE is enabled in the host */
1291 	if (rcr4() & CR4_XSAVE)
1292 		load_xcr(0, vcpu->guest_xcr0);
1293 
1294 	/*
1295 	 * The FPU is now "dirty" with the guest's state so turn on emulation
1296 	 * to trap any access to the FPU by the host.
1297 	 */
1298 	fpu_start_emulating();
1299 }
1300 
1301 static void
1302 save_guest_fpustate(struct vcpu *vcpu)
1303 {
1304 
1305 	if ((rcr0() & CR0_TS) == 0)
1306 		panic("fpu emulation not enabled in host!");
1307 
1308 	/* save guest XCR0 and restore host XCR0 */
1309 	if (rcr4() & CR4_XSAVE) {
1310 		vcpu->guest_xcr0 = rxcr(0);
1311 		load_xcr(0, vmm_get_host_xcr0());
1312 	}
1313 
1314 	/* save guest FPU state */
1315 	fpu_stop_emulating();
1316 	fpusave(vcpu->guestfpu);
1317 	fpu_start_emulating();
1318 }
1319 
1320 static VMM_STAT(VCPU_IDLE_TICKS, "number of ticks vcpu was idle");
1321 
1322 static int
1323 vcpu_set_state_locked(struct vcpu *vcpu, enum vcpu_state newstate,
1324     bool from_idle)
1325 {
1326 	int error;
1327 
1328 	vcpu_assert_locked(vcpu);
1329 
1330 	/*
1331 	 * State transitions from the vmmdev_ioctl() must always begin from
1332 	 * the VCPU_IDLE state. This guarantees that there is only a single
1333 	 * ioctl() operating on a vcpu at any point.
1334 	 */
1335 	if (from_idle) {
1336 		while (vcpu->state != VCPU_IDLE) {
1337 			vcpu->reqidle = 1;
1338 			vcpu_notify_event_locked(vcpu, false);
1339 			VMM_CTR1(vcpu, "vcpu state change from %s to "
1340 			    "idle requested", vcpu_state2str(vcpu->state));
1341 			msleep_spin(&vcpu->state, &vcpu->mtx, "vmstat", hz);
1342 		}
1343 	} else {
1344 		KASSERT(vcpu->state != VCPU_IDLE, ("invalid transition from "
1345 		    "vcpu idle state"));
1346 	}
1347 
1348 	if (vcpu->state == VCPU_RUNNING) {
1349 		KASSERT(vcpu->hostcpu == curcpu, ("curcpu %d and hostcpu %d "
1350 		    "mismatch for running vcpu", curcpu, vcpu->hostcpu));
1351 	} else {
1352 		KASSERT(vcpu->hostcpu == NOCPU, ("Invalid hostcpu %d for a "
1353 		    "vcpu that is not running", vcpu->hostcpu));
1354 	}
1355 
1356 	/*
1357 	 * The following state transitions are allowed:
1358 	 * IDLE -> FROZEN -> IDLE
1359 	 * FROZEN -> RUNNING -> FROZEN
1360 	 * FROZEN -> SLEEPING -> FROZEN
1361 	 */
1362 	switch (vcpu->state) {
1363 	case VCPU_IDLE:
1364 	case VCPU_RUNNING:
1365 	case VCPU_SLEEPING:
1366 		error = (newstate != VCPU_FROZEN);
1367 		break;
1368 	case VCPU_FROZEN:
1369 		error = (newstate == VCPU_FROZEN);
1370 		break;
1371 	default:
1372 		error = 1;
1373 		break;
1374 	}
1375 
1376 	if (error)
1377 		return (EBUSY);
1378 
1379 	VMM_CTR2(vcpu, "vcpu state changed from %s to %s",
1380 	    vcpu_state2str(vcpu->state), vcpu_state2str(newstate));
1381 
1382 	vcpu->state = newstate;
1383 	if (newstate == VCPU_RUNNING)
1384 		vcpu->hostcpu = curcpu;
1385 	else
1386 		vcpu->hostcpu = NOCPU;
1387 
1388 	if (newstate == VCPU_IDLE)
1389 		wakeup(&vcpu->state);
1390 
1391 	return (0);
1392 }
1393 
1394 static void
1395 vcpu_require_state(struct vcpu *vcpu, enum vcpu_state newstate)
1396 {
1397 	int error;
1398 
1399 	if ((error = vcpu_set_state(vcpu, newstate, false)) != 0)
1400 		panic("Error %d setting state to %d\n", error, newstate);
1401 }
1402 
1403 static void
1404 vcpu_require_state_locked(struct vcpu *vcpu, enum vcpu_state newstate)
1405 {
1406 	int error;
1407 
1408 	if ((error = vcpu_set_state_locked(vcpu, newstate, false)) != 0)
1409 		panic("Error %d setting state to %d", error, newstate);
1410 }
1411 
1412 static int
1413 vm_handle_rendezvous(struct vcpu *vcpu)
1414 {
1415 	struct vm *vm = vcpu->vm;
1416 	struct thread *td;
1417 	int error, vcpuid;
1418 
1419 	error = 0;
1420 	vcpuid = vcpu->vcpuid;
1421 	td = curthread;
1422 	mtx_lock(&vm->rendezvous_mtx);
1423 	while (vm->rendezvous_func != NULL) {
1424 		/* 'rendezvous_req_cpus' must be a subset of 'active_cpus' */
1425 		CPU_AND(&vm->rendezvous_req_cpus, &vm->rendezvous_req_cpus, &vm->active_cpus);
1426 
1427 		if (CPU_ISSET(vcpuid, &vm->rendezvous_req_cpus) &&
1428 		    !CPU_ISSET(vcpuid, &vm->rendezvous_done_cpus)) {
1429 			VMM_CTR0(vcpu, "Calling rendezvous func");
1430 			(*vm->rendezvous_func)(vcpu, vm->rendezvous_arg);
1431 			CPU_SET(vcpuid, &vm->rendezvous_done_cpus);
1432 		}
1433 		if (CPU_CMP(&vm->rendezvous_req_cpus,
1434 		    &vm->rendezvous_done_cpus) == 0) {
1435 			VMM_CTR0(vcpu, "Rendezvous completed");
1436 			vm->rendezvous_func = NULL;
1437 			wakeup(&vm->rendezvous_func);
1438 			break;
1439 		}
1440 		VMM_CTR0(vcpu, "Wait for rendezvous completion");
1441 		mtx_sleep(&vm->rendezvous_func, &vm->rendezvous_mtx, 0,
1442 		    "vmrndv", hz);
1443 		if (td_ast_pending(td, TDA_SUSPEND)) {
1444 			mtx_unlock(&vm->rendezvous_mtx);
1445 			error = thread_check_susp(td, true);
1446 			if (error != 0)
1447 				return (error);
1448 			mtx_lock(&vm->rendezvous_mtx);
1449 		}
1450 	}
1451 	mtx_unlock(&vm->rendezvous_mtx);
1452 	return (0);
1453 }
1454 
1455 /*
1456  * Emulate a guest 'hlt' by sleeping until the vcpu is ready to run.
1457  */
1458 static int
1459 vm_handle_hlt(struct vcpu *vcpu, bool intr_disabled, bool *retu)
1460 {
1461 	struct vm *vm = vcpu->vm;
1462 	const char *wmesg;
1463 	struct thread *td;
1464 	int error, t, vcpuid, vcpu_halted, vm_halted;
1465 
1466 	vcpuid = vcpu->vcpuid;
1467 	vcpu_halted = 0;
1468 	vm_halted = 0;
1469 	error = 0;
1470 	td = curthread;
1471 
1472 	KASSERT(!CPU_ISSET(vcpuid, &vm->halted_cpus), ("vcpu already halted"));
1473 
1474 	vcpu_lock(vcpu);
1475 	while (1) {
1476 		/*
1477 		 * Do a final check for pending NMI or interrupts before
1478 		 * really putting this thread to sleep. Also check for
1479 		 * software events that would cause this vcpu to wakeup.
1480 		 *
1481 		 * These interrupts/events could have happened after the
1482 		 * vcpu returned from vmmops_run() and before it acquired the
1483 		 * vcpu lock above.
1484 		 */
1485 		if (vm->rendezvous_func != NULL || vm->suspend || vcpu->reqidle)
1486 			break;
1487 		if (vm_nmi_pending(vcpu))
1488 			break;
1489 		if (!intr_disabled) {
1490 			if (vm_extint_pending(vcpu) ||
1491 			    vlapic_pending_intr(vcpu->vlapic, NULL)) {
1492 				break;
1493 			}
1494 		}
1495 
1496 		/* Don't go to sleep if the vcpu thread needs to yield */
1497 		if (vcpu_should_yield(vcpu))
1498 			break;
1499 
1500 		if (vcpu_debugged(vcpu))
1501 			break;
1502 
1503 		/*
1504 		 * Some Linux guests implement "halt" by having all vcpus
1505 		 * execute HLT with interrupts disabled. 'halted_cpus' keeps
1506 		 * track of the vcpus that have entered this state. When all
1507 		 * vcpus enter the halted state the virtual machine is halted.
1508 		 */
1509 		if (intr_disabled) {
1510 			wmesg = "vmhalt";
1511 			VMM_CTR0(vcpu, "Halted");
1512 			if (!vcpu_halted && halt_detection_enabled) {
1513 				vcpu_halted = 1;
1514 				CPU_SET_ATOMIC(vcpuid, &vm->halted_cpus);
1515 			}
1516 			if (CPU_CMP(&vm->halted_cpus, &vm->active_cpus) == 0) {
1517 				vm_halted = 1;
1518 				break;
1519 			}
1520 		} else {
1521 			wmesg = "vmidle";
1522 		}
1523 
1524 		t = ticks;
1525 		vcpu_require_state_locked(vcpu, VCPU_SLEEPING);
1526 		/*
1527 		 * XXX msleep_spin() cannot be interrupted by signals so
1528 		 * wake up periodically to check pending signals.
1529 		 */
1530 		msleep_spin(vcpu, &vcpu->mtx, wmesg, hz);
1531 		vcpu_require_state_locked(vcpu, VCPU_FROZEN);
1532 		vmm_stat_incr(vcpu, VCPU_IDLE_TICKS, ticks - t);
1533 		if (td_ast_pending(td, TDA_SUSPEND)) {
1534 			vcpu_unlock(vcpu);
1535 			error = thread_check_susp(td, false);
1536 			if (error != 0) {
1537 				if (vcpu_halted) {
1538 					CPU_CLR_ATOMIC(vcpuid,
1539 					    &vm->halted_cpus);
1540 				}
1541 				return (error);
1542 			}
1543 			vcpu_lock(vcpu);
1544 		}
1545 	}
1546 
1547 	if (vcpu_halted)
1548 		CPU_CLR_ATOMIC(vcpuid, &vm->halted_cpus);
1549 
1550 	vcpu_unlock(vcpu);
1551 
1552 	if (vm_halted)
1553 		vm_suspend(vm, VM_SUSPEND_HALT);
1554 
1555 	return (0);
1556 }
1557 
1558 static int
1559 vm_handle_paging(struct vcpu *vcpu, bool *retu)
1560 {
1561 	struct vm *vm = vcpu->vm;
1562 	int rv, ftype;
1563 	struct vm_map *map;
1564 	struct vm_exit *vme;
1565 
1566 	vme = &vcpu->exitinfo;
1567 
1568 	KASSERT(vme->inst_length == 0, ("%s: invalid inst_length %d",
1569 	    __func__, vme->inst_length));
1570 
1571 	ftype = vme->u.paging.fault_type;
1572 	KASSERT(ftype == VM_PROT_READ ||
1573 	    ftype == VM_PROT_WRITE || ftype == VM_PROT_EXECUTE,
1574 	    ("vm_handle_paging: invalid fault_type %d", ftype));
1575 
1576 	if (ftype == VM_PROT_READ || ftype == VM_PROT_WRITE) {
1577 		rv = pmap_emulate_accessed_dirty(vmspace_pmap(vm->vmspace),
1578 		    vme->u.paging.gpa, ftype);
1579 		if (rv == 0) {
1580 			VMM_CTR2(vcpu, "%s bit emulation for gpa %#lx",
1581 			    ftype == VM_PROT_READ ? "accessed" : "dirty",
1582 			    vme->u.paging.gpa);
1583 			goto done;
1584 		}
1585 	}
1586 
1587 	map = &vm->vmspace->vm_map;
1588 	rv = vm_fault(map, vme->u.paging.gpa, ftype, VM_FAULT_NORMAL, NULL);
1589 
1590 	VMM_CTR3(vcpu, "vm_handle_paging rv = %d, gpa = %#lx, "
1591 	    "ftype = %d", rv, vme->u.paging.gpa, ftype);
1592 
1593 	if (rv != KERN_SUCCESS)
1594 		return (EFAULT);
1595 done:
1596 	return (0);
1597 }
1598 
1599 static int
1600 vm_handle_inst_emul(struct vcpu *vcpu, bool *retu)
1601 {
1602 	struct vie *vie;
1603 	struct vm_exit *vme;
1604 	uint64_t gla, gpa, cs_base;
1605 	struct vm_guest_paging *paging;
1606 	mem_region_read_t mread;
1607 	mem_region_write_t mwrite;
1608 	enum vm_cpu_mode cpu_mode;
1609 	int cs_d, error, fault;
1610 
1611 	vme = &vcpu->exitinfo;
1612 
1613 	KASSERT(vme->inst_length == 0, ("%s: invalid inst_length %d",
1614 	    __func__, vme->inst_length));
1615 
1616 	gla = vme->u.inst_emul.gla;
1617 	gpa = vme->u.inst_emul.gpa;
1618 	cs_base = vme->u.inst_emul.cs_base;
1619 	cs_d = vme->u.inst_emul.cs_d;
1620 	vie = &vme->u.inst_emul.vie;
1621 	paging = &vme->u.inst_emul.paging;
1622 	cpu_mode = paging->cpu_mode;
1623 
1624 	VMM_CTR1(vcpu, "inst_emul fault accessing gpa %#lx", gpa);
1625 
1626 	/* Fetch, decode and emulate the faulting instruction */
1627 	if (vie->num_valid == 0) {
1628 		error = vmm_fetch_instruction(vcpu, paging, vme->rip + cs_base,
1629 		    VIE_INST_SIZE, vie, &fault);
1630 	} else {
1631 		/*
1632 		 * The instruction bytes have already been copied into 'vie'
1633 		 */
1634 		error = fault = 0;
1635 	}
1636 	if (error || fault)
1637 		return (error);
1638 
1639 	if (vmm_decode_instruction(vcpu, gla, cpu_mode, cs_d, vie) != 0) {
1640 		VMM_CTR1(vcpu, "Error decoding instruction at %#lx",
1641 		    vme->rip + cs_base);
1642 		*retu = true;	    /* dump instruction bytes in userspace */
1643 		return (0);
1644 	}
1645 
1646 	/*
1647 	 * Update 'nextrip' based on the length of the emulated instruction.
1648 	 */
1649 	vme->inst_length = vie->num_processed;
1650 	vcpu->nextrip += vie->num_processed;
1651 	VMM_CTR1(vcpu, "nextrip updated to %#lx after instruction decoding",
1652 	    vcpu->nextrip);
1653 
1654 	/* return to userland unless this is an in-kernel emulated device */
1655 	if (gpa >= DEFAULT_APIC_BASE && gpa < DEFAULT_APIC_BASE + PAGE_SIZE) {
1656 		mread = lapic_mmio_read;
1657 		mwrite = lapic_mmio_write;
1658 	} else if (gpa >= VIOAPIC_BASE && gpa < VIOAPIC_BASE + VIOAPIC_SIZE) {
1659 		mread = vioapic_mmio_read;
1660 		mwrite = vioapic_mmio_write;
1661 	} else if (gpa >= VHPET_BASE && gpa < VHPET_BASE + VHPET_SIZE) {
1662 		mread = vhpet_mmio_read;
1663 		mwrite = vhpet_mmio_write;
1664 	} else {
1665 		*retu = true;
1666 		return (0);
1667 	}
1668 
1669 	error = vmm_emulate_instruction(vcpu, gpa, vie, paging, mread, mwrite,
1670 	    retu);
1671 
1672 	return (error);
1673 }
1674 
1675 static int
1676 vm_handle_suspend(struct vcpu *vcpu, bool *retu)
1677 {
1678 	struct vm *vm = vcpu->vm;
1679 	int error, i;
1680 	struct thread *td;
1681 
1682 	error = 0;
1683 	td = curthread;
1684 
1685 	CPU_SET_ATOMIC(vcpu->vcpuid, &vm->suspended_cpus);
1686 
1687 	/*
1688 	 * Wait until all 'active_cpus' have suspended themselves.
1689 	 *
1690 	 * Since a VM may be suspended at any time including when one or
1691 	 * more vcpus are doing a rendezvous we need to call the rendezvous
1692 	 * handler while we are waiting to prevent a deadlock.
1693 	 */
1694 	vcpu_lock(vcpu);
1695 	while (error == 0) {
1696 		if (CPU_CMP(&vm->suspended_cpus, &vm->active_cpus) == 0) {
1697 			VMM_CTR0(vcpu, "All vcpus suspended");
1698 			break;
1699 		}
1700 
1701 		if (vm->rendezvous_func == NULL) {
1702 			VMM_CTR0(vcpu, "Sleeping during suspend");
1703 			vcpu_require_state_locked(vcpu, VCPU_SLEEPING);
1704 			msleep_spin(vcpu, &vcpu->mtx, "vmsusp", hz);
1705 			vcpu_require_state_locked(vcpu, VCPU_FROZEN);
1706 			if (td_ast_pending(td, TDA_SUSPEND)) {
1707 				vcpu_unlock(vcpu);
1708 				error = thread_check_susp(td, false);
1709 				vcpu_lock(vcpu);
1710 			}
1711 		} else {
1712 			VMM_CTR0(vcpu, "Rendezvous during suspend");
1713 			vcpu_unlock(vcpu);
1714 			error = vm_handle_rendezvous(vcpu);
1715 			vcpu_lock(vcpu);
1716 		}
1717 	}
1718 	vcpu_unlock(vcpu);
1719 
1720 	/*
1721 	 * Wakeup the other sleeping vcpus and return to userspace.
1722 	 */
1723 	for (i = 0; i < vm->maxcpus; i++) {
1724 		if (CPU_ISSET(i, &vm->suspended_cpus)) {
1725 			vcpu_notify_event(vm_vcpu(vm, i), false);
1726 		}
1727 	}
1728 
1729 	*retu = true;
1730 	return (error);
1731 }
1732 
1733 static int
1734 vm_handle_reqidle(struct vcpu *vcpu, bool *retu)
1735 {
1736 	vcpu_lock(vcpu);
1737 	KASSERT(vcpu->reqidle, ("invalid vcpu reqidle %d", vcpu->reqidle));
1738 	vcpu->reqidle = 0;
1739 	vcpu_unlock(vcpu);
1740 	*retu = true;
1741 	return (0);
1742 }
1743 
1744 int
1745 vm_suspend(struct vm *vm, enum vm_suspend_how how)
1746 {
1747 	int i;
1748 
1749 	if (how <= VM_SUSPEND_NONE || how >= VM_SUSPEND_LAST)
1750 		return (EINVAL);
1751 
1752 	if (atomic_cmpset_int(&vm->suspend, 0, how) == 0) {
1753 		VM_CTR2(vm, "virtual machine already suspended %d/%d",
1754 		    vm->suspend, how);
1755 		return (EALREADY);
1756 	}
1757 
1758 	VM_CTR1(vm, "virtual machine successfully suspended %d", how);
1759 
1760 	/*
1761 	 * Notify all active vcpus that they are now suspended.
1762 	 */
1763 	for (i = 0; i < vm->maxcpus; i++) {
1764 		if (CPU_ISSET(i, &vm->active_cpus))
1765 			vcpu_notify_event(vm_vcpu(vm, i), false);
1766 	}
1767 
1768 	return (0);
1769 }
1770 
1771 void
1772 vm_exit_suspended(struct vcpu *vcpu, uint64_t rip)
1773 {
1774 	struct vm *vm = vcpu->vm;
1775 	struct vm_exit *vmexit;
1776 
1777 	KASSERT(vm->suspend > VM_SUSPEND_NONE && vm->suspend < VM_SUSPEND_LAST,
1778 	    ("vm_exit_suspended: invalid suspend type %d", vm->suspend));
1779 
1780 	vmexit = vm_exitinfo(vcpu);
1781 	vmexit->rip = rip;
1782 	vmexit->inst_length = 0;
1783 	vmexit->exitcode = VM_EXITCODE_SUSPENDED;
1784 	vmexit->u.suspended.how = vm->suspend;
1785 }
1786 
1787 void
1788 vm_exit_debug(struct vcpu *vcpu, uint64_t rip)
1789 {
1790 	struct vm_exit *vmexit;
1791 
1792 	vmexit = vm_exitinfo(vcpu);
1793 	vmexit->rip = rip;
1794 	vmexit->inst_length = 0;
1795 	vmexit->exitcode = VM_EXITCODE_DEBUG;
1796 }
1797 
1798 void
1799 vm_exit_rendezvous(struct vcpu *vcpu, uint64_t rip)
1800 {
1801 	struct vm_exit *vmexit;
1802 
1803 	vmexit = vm_exitinfo(vcpu);
1804 	vmexit->rip = rip;
1805 	vmexit->inst_length = 0;
1806 	vmexit->exitcode = VM_EXITCODE_RENDEZVOUS;
1807 	vmm_stat_incr(vcpu, VMEXIT_RENDEZVOUS, 1);
1808 }
1809 
1810 void
1811 vm_exit_reqidle(struct vcpu *vcpu, uint64_t rip)
1812 {
1813 	struct vm_exit *vmexit;
1814 
1815 	vmexit = vm_exitinfo(vcpu);
1816 	vmexit->rip = rip;
1817 	vmexit->inst_length = 0;
1818 	vmexit->exitcode = VM_EXITCODE_REQIDLE;
1819 	vmm_stat_incr(vcpu, VMEXIT_REQIDLE, 1);
1820 }
1821 
1822 void
1823 vm_exit_astpending(struct vcpu *vcpu, uint64_t rip)
1824 {
1825 	struct vm_exit *vmexit;
1826 
1827 	vmexit = vm_exitinfo(vcpu);
1828 	vmexit->rip = rip;
1829 	vmexit->inst_length = 0;
1830 	vmexit->exitcode = VM_EXITCODE_BOGUS;
1831 	vmm_stat_incr(vcpu, VMEXIT_ASTPENDING, 1);
1832 }
1833 
1834 int
1835 vm_run(struct vcpu *vcpu, struct vm_exit *vme_user)
1836 {
1837 	struct vm *vm = vcpu->vm;
1838 	struct vm_eventinfo evinfo;
1839 	int error, vcpuid;
1840 	struct pcb *pcb;
1841 	uint64_t tscval;
1842 	struct vm_exit *vme;
1843 	bool retu, intr_disabled;
1844 	pmap_t pmap;
1845 
1846 	vcpuid = vcpu->vcpuid;
1847 
1848 	if (!CPU_ISSET(vcpuid, &vm->active_cpus))
1849 		return (EINVAL);
1850 
1851 	if (CPU_ISSET(vcpuid, &vm->suspended_cpus))
1852 		return (EINVAL);
1853 
1854 	pmap = vmspace_pmap(vm->vmspace);
1855 	vme = &vcpu->exitinfo;
1856 	evinfo.rptr = &vm->rendezvous_func;
1857 	evinfo.sptr = &vm->suspend;
1858 	evinfo.iptr = &vcpu->reqidle;
1859 restart:
1860 	critical_enter();
1861 
1862 	KASSERT(!CPU_ISSET(curcpu, &pmap->pm_active),
1863 	    ("vm_run: absurd pm_active"));
1864 
1865 	tscval = rdtsc();
1866 
1867 	pcb = PCPU_GET(curpcb);
1868 	set_pcb_flags(pcb, PCB_FULL_IRET);
1869 
1870 	restore_guest_fpustate(vcpu);
1871 
1872 	vcpu_require_state(vcpu, VCPU_RUNNING);
1873 	error = vmmops_run(vcpu->cookie, vcpu->nextrip, pmap, &evinfo);
1874 	vcpu_require_state(vcpu, VCPU_FROZEN);
1875 
1876 	save_guest_fpustate(vcpu);
1877 
1878 	vmm_stat_incr(vcpu, VCPU_TOTAL_RUNTIME, rdtsc() - tscval);
1879 
1880 	critical_exit();
1881 
1882 	if (error == 0) {
1883 		retu = false;
1884 		vcpu->nextrip = vme->rip + vme->inst_length;
1885 		switch (vme->exitcode) {
1886 		case VM_EXITCODE_REQIDLE:
1887 			error = vm_handle_reqidle(vcpu, &retu);
1888 			break;
1889 		case VM_EXITCODE_SUSPENDED:
1890 			error = vm_handle_suspend(vcpu, &retu);
1891 			break;
1892 		case VM_EXITCODE_IOAPIC_EOI:
1893 			vioapic_process_eoi(vm, vme->u.ioapic_eoi.vector);
1894 			break;
1895 		case VM_EXITCODE_RENDEZVOUS:
1896 			error = vm_handle_rendezvous(vcpu);
1897 			break;
1898 		case VM_EXITCODE_HLT:
1899 			intr_disabled = ((vme->u.hlt.rflags & PSL_I) == 0);
1900 			error = vm_handle_hlt(vcpu, intr_disabled, &retu);
1901 			break;
1902 		case VM_EXITCODE_PAGING:
1903 			error = vm_handle_paging(vcpu, &retu);
1904 			break;
1905 		case VM_EXITCODE_INST_EMUL:
1906 			error = vm_handle_inst_emul(vcpu, &retu);
1907 			break;
1908 		case VM_EXITCODE_INOUT:
1909 		case VM_EXITCODE_INOUT_STR:
1910 			error = vm_handle_inout(vcpu, vme, &retu);
1911 			break;
1912 		case VM_EXITCODE_MONITOR:
1913 		case VM_EXITCODE_MWAIT:
1914 		case VM_EXITCODE_VMINSN:
1915 			vm_inject_ud(vcpu);
1916 			break;
1917 		default:
1918 			retu = true;	/* handled in userland */
1919 			break;
1920 		}
1921 	}
1922 
1923 	/*
1924 	 * VM_EXITCODE_INST_EMUL could access the apic which could transform the
1925 	 * exit code into VM_EXITCODE_IPI.
1926 	 */
1927 	if (error == 0 && vme->exitcode == VM_EXITCODE_IPI) {
1928 		retu = false;
1929 		error = vm_handle_ipi(vcpu, vme, &retu);
1930 	}
1931 
1932 	if (error == 0 && retu == false)
1933 		goto restart;
1934 
1935 	vmm_stat_incr(vcpu, VMEXIT_USERSPACE, 1);
1936 	VMM_CTR2(vcpu, "retu %d/%d", error, vme->exitcode);
1937 
1938 	/* copy the exit information */
1939 	*vme_user = *vme;
1940 	return (error);
1941 }
1942 
1943 int
1944 vm_restart_instruction(struct vcpu *vcpu)
1945 {
1946 	enum vcpu_state state;
1947 	uint64_t rip;
1948 	int error __diagused;
1949 
1950 	state = vcpu_get_state(vcpu, NULL);
1951 	if (state == VCPU_RUNNING) {
1952 		/*
1953 		 * When a vcpu is "running" the next instruction is determined
1954 		 * by adding 'rip' and 'inst_length' in the vcpu's 'exitinfo'.
1955 		 * Thus setting 'inst_length' to zero will cause the current
1956 		 * instruction to be restarted.
1957 		 */
1958 		vcpu->exitinfo.inst_length = 0;
1959 		VMM_CTR1(vcpu, "restarting instruction at %#lx by "
1960 		    "setting inst_length to zero", vcpu->exitinfo.rip);
1961 	} else if (state == VCPU_FROZEN) {
1962 		/*
1963 		 * When a vcpu is "frozen" it is outside the critical section
1964 		 * around vmmops_run() and 'nextrip' points to the next
1965 		 * instruction. Thus instruction restart is achieved by setting
1966 		 * 'nextrip' to the vcpu's %rip.
1967 		 */
1968 		error = vm_get_register(vcpu, VM_REG_GUEST_RIP, &rip);
1969 		KASSERT(!error, ("%s: error %d getting rip", __func__, error));
1970 		VMM_CTR2(vcpu, "restarting instruction by updating "
1971 		    "nextrip from %#lx to %#lx", vcpu->nextrip, rip);
1972 		vcpu->nextrip = rip;
1973 	} else {
1974 		panic("%s: invalid state %d", __func__, state);
1975 	}
1976 	return (0);
1977 }
1978 
1979 int
1980 vm_exit_intinfo(struct vcpu *vcpu, uint64_t info)
1981 {
1982 	int type, vector;
1983 
1984 	if (info & VM_INTINFO_VALID) {
1985 		type = info & VM_INTINFO_TYPE;
1986 		vector = info & 0xff;
1987 		if (type == VM_INTINFO_NMI && vector != IDT_NMI)
1988 			return (EINVAL);
1989 		if (type == VM_INTINFO_HWEXCEPTION && vector >= 32)
1990 			return (EINVAL);
1991 		if (info & VM_INTINFO_RSVD)
1992 			return (EINVAL);
1993 	} else {
1994 		info = 0;
1995 	}
1996 	VMM_CTR2(vcpu, "%s: info1(%#lx)", __func__, info);
1997 	vcpu->exitintinfo = info;
1998 	return (0);
1999 }
2000 
2001 enum exc_class {
2002 	EXC_BENIGN,
2003 	EXC_CONTRIBUTORY,
2004 	EXC_PAGEFAULT
2005 };
2006 
2007 #define	IDT_VE	20	/* Virtualization Exception (Intel specific) */
2008 
2009 static enum exc_class
2010 exception_class(uint64_t info)
2011 {
2012 	int type, vector;
2013 
2014 	KASSERT(info & VM_INTINFO_VALID, ("intinfo must be valid: %#lx", info));
2015 	type = info & VM_INTINFO_TYPE;
2016 	vector = info & 0xff;
2017 
2018 	/* Table 6-4, "Interrupt and Exception Classes", Intel SDM, Vol 3 */
2019 	switch (type) {
2020 	case VM_INTINFO_HWINTR:
2021 	case VM_INTINFO_SWINTR:
2022 	case VM_INTINFO_NMI:
2023 		return (EXC_BENIGN);
2024 	default:
2025 		/*
2026 		 * Hardware exception.
2027 		 *
2028 		 * SVM and VT-x use identical type values to represent NMI,
2029 		 * hardware interrupt and software interrupt.
2030 		 *
2031 		 * SVM uses type '3' for all exceptions. VT-x uses type '3'
2032 		 * for exceptions except #BP and #OF. #BP and #OF use a type
2033 		 * value of '5' or '6'. Therefore we don't check for explicit
2034 		 * values of 'type' to classify 'intinfo' into a hardware
2035 		 * exception.
2036 		 */
2037 		break;
2038 	}
2039 
2040 	switch (vector) {
2041 	case IDT_PF:
2042 	case IDT_VE:
2043 		return (EXC_PAGEFAULT);
2044 	case IDT_DE:
2045 	case IDT_TS:
2046 	case IDT_NP:
2047 	case IDT_SS:
2048 	case IDT_GP:
2049 		return (EXC_CONTRIBUTORY);
2050 	default:
2051 		return (EXC_BENIGN);
2052 	}
2053 }
2054 
2055 static int
2056 nested_fault(struct vcpu *vcpu, uint64_t info1, uint64_t info2,
2057     uint64_t *retinfo)
2058 {
2059 	enum exc_class exc1, exc2;
2060 	int type1, vector1;
2061 
2062 	KASSERT(info1 & VM_INTINFO_VALID, ("info1 %#lx is not valid", info1));
2063 	KASSERT(info2 & VM_INTINFO_VALID, ("info2 %#lx is not valid", info2));
2064 
2065 	/*
2066 	 * If an exception occurs while attempting to call the double-fault
2067 	 * handler the processor enters shutdown mode (aka triple fault).
2068 	 */
2069 	type1 = info1 & VM_INTINFO_TYPE;
2070 	vector1 = info1 & 0xff;
2071 	if (type1 == VM_INTINFO_HWEXCEPTION && vector1 == IDT_DF) {
2072 		VMM_CTR2(vcpu, "triple fault: info1(%#lx), info2(%#lx)",
2073 		    info1, info2);
2074 		vm_suspend(vcpu->vm, VM_SUSPEND_TRIPLEFAULT);
2075 		*retinfo = 0;
2076 		return (0);
2077 	}
2078 
2079 	/*
2080 	 * Table 6-5 "Conditions for Generating a Double Fault", Intel SDM, Vol3
2081 	 */
2082 	exc1 = exception_class(info1);
2083 	exc2 = exception_class(info2);
2084 	if ((exc1 == EXC_CONTRIBUTORY && exc2 == EXC_CONTRIBUTORY) ||
2085 	    (exc1 == EXC_PAGEFAULT && exc2 != EXC_BENIGN)) {
2086 		/* Convert nested fault into a double fault. */
2087 		*retinfo = IDT_DF;
2088 		*retinfo |= VM_INTINFO_VALID | VM_INTINFO_HWEXCEPTION;
2089 		*retinfo |= VM_INTINFO_DEL_ERRCODE;
2090 	} else {
2091 		/* Handle exceptions serially */
2092 		*retinfo = info2;
2093 	}
2094 	return (1);
2095 }
2096 
2097 static uint64_t
2098 vcpu_exception_intinfo(struct vcpu *vcpu)
2099 {
2100 	uint64_t info = 0;
2101 
2102 	if (vcpu->exception_pending) {
2103 		info = vcpu->exc_vector & 0xff;
2104 		info |= VM_INTINFO_VALID | VM_INTINFO_HWEXCEPTION;
2105 		if (vcpu->exc_errcode_valid) {
2106 			info |= VM_INTINFO_DEL_ERRCODE;
2107 			info |= (uint64_t)vcpu->exc_errcode << 32;
2108 		}
2109 	}
2110 	return (info);
2111 }
2112 
2113 int
2114 vm_entry_intinfo(struct vcpu *vcpu, uint64_t *retinfo)
2115 {
2116 	uint64_t info1, info2;
2117 	int valid;
2118 
2119 	info1 = vcpu->exitintinfo;
2120 	vcpu->exitintinfo = 0;
2121 
2122 	info2 = 0;
2123 	if (vcpu->exception_pending) {
2124 		info2 = vcpu_exception_intinfo(vcpu);
2125 		vcpu->exception_pending = 0;
2126 		VMM_CTR2(vcpu, "Exception %d delivered: %#lx",
2127 		    vcpu->exc_vector, info2);
2128 	}
2129 
2130 	if ((info1 & VM_INTINFO_VALID) && (info2 & VM_INTINFO_VALID)) {
2131 		valid = nested_fault(vcpu, info1, info2, retinfo);
2132 	} else if (info1 & VM_INTINFO_VALID) {
2133 		*retinfo = info1;
2134 		valid = 1;
2135 	} else if (info2 & VM_INTINFO_VALID) {
2136 		*retinfo = info2;
2137 		valid = 1;
2138 	} else {
2139 		valid = 0;
2140 	}
2141 
2142 	if (valid) {
2143 		VMM_CTR4(vcpu, "%s: info1(%#lx), info2(%#lx), "
2144 		    "retinfo(%#lx)", __func__, info1, info2, *retinfo);
2145 	}
2146 
2147 	return (valid);
2148 }
2149 
2150 int
2151 vm_get_intinfo(struct vcpu *vcpu, uint64_t *info1, uint64_t *info2)
2152 {
2153 	*info1 = vcpu->exitintinfo;
2154 	*info2 = vcpu_exception_intinfo(vcpu);
2155 	return (0);
2156 }
2157 
2158 int
2159 vm_inject_exception(struct vcpu *vcpu, int vector, int errcode_valid,
2160     uint32_t errcode, int restart_instruction)
2161 {
2162 	uint64_t regval;
2163 	int error __diagused;
2164 
2165 	if (vector < 0 || vector >= 32)
2166 		return (EINVAL);
2167 
2168 	/*
2169 	 * A double fault exception should never be injected directly into
2170 	 * the guest. It is a derived exception that results from specific
2171 	 * combinations of nested faults.
2172 	 */
2173 	if (vector == IDT_DF)
2174 		return (EINVAL);
2175 
2176 	if (vcpu->exception_pending) {
2177 		VMM_CTR2(vcpu, "Unable to inject exception %d due to "
2178 		    "pending exception %d", vector, vcpu->exc_vector);
2179 		return (EBUSY);
2180 	}
2181 
2182 	if (errcode_valid) {
2183 		/*
2184 		 * Exceptions don't deliver an error code in real mode.
2185 		 */
2186 		error = vm_get_register(vcpu, VM_REG_GUEST_CR0, &regval);
2187 		KASSERT(!error, ("%s: error %d getting CR0", __func__, error));
2188 		if (!(regval & CR0_PE))
2189 			errcode_valid = 0;
2190 	}
2191 
2192 	/*
2193 	 * From section 26.6.1 "Interruptibility State" in Intel SDM:
2194 	 *
2195 	 * Event blocking by "STI" or "MOV SS" is cleared after guest executes
2196 	 * one instruction or incurs an exception.
2197 	 */
2198 	error = vm_set_register(vcpu, VM_REG_GUEST_INTR_SHADOW, 0);
2199 	KASSERT(error == 0, ("%s: error %d clearing interrupt shadow",
2200 	    __func__, error));
2201 
2202 	if (restart_instruction)
2203 		vm_restart_instruction(vcpu);
2204 
2205 	vcpu->exception_pending = 1;
2206 	vcpu->exc_vector = vector;
2207 	vcpu->exc_errcode = errcode;
2208 	vcpu->exc_errcode_valid = errcode_valid;
2209 	VMM_CTR1(vcpu, "Exception %d pending", vector);
2210 	return (0);
2211 }
2212 
2213 void
2214 vm_inject_fault(struct vcpu *vcpu, int vector, int errcode_valid, int errcode)
2215 {
2216 	int error __diagused, restart_instruction;
2217 
2218 	restart_instruction = 1;
2219 
2220 	error = vm_inject_exception(vcpu, vector, errcode_valid,
2221 	    errcode, restart_instruction);
2222 	KASSERT(error == 0, ("vm_inject_exception error %d", error));
2223 }
2224 
2225 void
2226 vm_inject_pf(struct vcpu *vcpu, int error_code, uint64_t cr2)
2227 {
2228 	int error __diagused;
2229 
2230 	VMM_CTR2(vcpu, "Injecting page fault: error_code %#x, cr2 %#lx",
2231 	    error_code, cr2);
2232 
2233 	error = vm_set_register(vcpu, VM_REG_GUEST_CR2, cr2);
2234 	KASSERT(error == 0, ("vm_set_register(cr2) error %d", error));
2235 
2236 	vm_inject_fault(vcpu, IDT_PF, 1, error_code);
2237 }
2238 
2239 static VMM_STAT(VCPU_NMI_COUNT, "number of NMIs delivered to vcpu");
2240 
2241 int
2242 vm_inject_nmi(struct vcpu *vcpu)
2243 {
2244 
2245 	vcpu->nmi_pending = 1;
2246 	vcpu_notify_event(vcpu, false);
2247 	return (0);
2248 }
2249 
2250 int
2251 vm_nmi_pending(struct vcpu *vcpu)
2252 {
2253 	return (vcpu->nmi_pending);
2254 }
2255 
2256 void
2257 vm_nmi_clear(struct vcpu *vcpu)
2258 {
2259 	if (vcpu->nmi_pending == 0)
2260 		panic("vm_nmi_clear: inconsistent nmi_pending state");
2261 
2262 	vcpu->nmi_pending = 0;
2263 	vmm_stat_incr(vcpu, VCPU_NMI_COUNT, 1);
2264 }
2265 
2266 static VMM_STAT(VCPU_EXTINT_COUNT, "number of ExtINTs delivered to vcpu");
2267 
2268 int
2269 vm_inject_extint(struct vcpu *vcpu)
2270 {
2271 
2272 	vcpu->extint_pending = 1;
2273 	vcpu_notify_event(vcpu, false);
2274 	return (0);
2275 }
2276 
2277 int
2278 vm_extint_pending(struct vcpu *vcpu)
2279 {
2280 	return (vcpu->extint_pending);
2281 }
2282 
2283 void
2284 vm_extint_clear(struct vcpu *vcpu)
2285 {
2286 	if (vcpu->extint_pending == 0)
2287 		panic("vm_extint_clear: inconsistent extint_pending state");
2288 
2289 	vcpu->extint_pending = 0;
2290 	vmm_stat_incr(vcpu, VCPU_EXTINT_COUNT, 1);
2291 }
2292 
2293 int
2294 vm_get_capability(struct vcpu *vcpu, int type, int *retval)
2295 {
2296 	if (type < 0 || type >= VM_CAP_MAX)
2297 		return (EINVAL);
2298 
2299 	return (vmmops_getcap(vcpu->cookie, type, retval));
2300 }
2301 
2302 int
2303 vm_set_capability(struct vcpu *vcpu, int type, int val)
2304 {
2305 	if (type < 0 || type >= VM_CAP_MAX)
2306 		return (EINVAL);
2307 
2308 	return (vmmops_setcap(vcpu->cookie, type, val));
2309 }
2310 
2311 struct vm *
2312 vcpu_vm(struct vcpu *vcpu)
2313 {
2314 	return (vcpu->vm);
2315 }
2316 
2317 int
2318 vcpu_vcpuid(struct vcpu *vcpu)
2319 {
2320 	return (vcpu->vcpuid);
2321 }
2322 
2323 struct vcpu *
2324 vm_vcpu(struct vm *vm, int vcpuid)
2325 {
2326 	return (vm->vcpu[vcpuid]);
2327 }
2328 
2329 struct vlapic *
2330 vm_lapic(struct vcpu *vcpu)
2331 {
2332 	return (vcpu->vlapic);
2333 }
2334 
2335 struct vioapic *
2336 vm_ioapic(struct vm *vm)
2337 {
2338 
2339 	return (vm->vioapic);
2340 }
2341 
2342 struct vhpet *
2343 vm_hpet(struct vm *vm)
2344 {
2345 
2346 	return (vm->vhpet);
2347 }
2348 
2349 bool
2350 vmm_is_pptdev(int bus, int slot, int func)
2351 {
2352 	int b, f, i, n, s;
2353 	char *val, *cp, *cp2;
2354 	bool found;
2355 
2356 	/*
2357 	 * XXX
2358 	 * The length of an environment variable is limited to 128 bytes which
2359 	 * puts an upper limit on the number of passthru devices that may be
2360 	 * specified using a single environment variable.
2361 	 *
2362 	 * Work around this by scanning multiple environment variable
2363 	 * names instead of a single one - yuck!
2364 	 */
2365 	const char *names[] = { "pptdevs", "pptdevs2", "pptdevs3", NULL };
2366 
2367 	/* set pptdevs="1/2/3 4/5/6 7/8/9 10/11/12" */
2368 	found = false;
2369 	for (i = 0; names[i] != NULL && !found; i++) {
2370 		cp = val = kern_getenv(names[i]);
2371 		while (cp != NULL && *cp != '\0') {
2372 			if ((cp2 = strchr(cp, ' ')) != NULL)
2373 				*cp2 = '\0';
2374 
2375 			n = sscanf(cp, "%d/%d/%d", &b, &s, &f);
2376 			if (n == 3 && bus == b && slot == s && func == f) {
2377 				found = true;
2378 				break;
2379 			}
2380 
2381 			if (cp2 != NULL)
2382 				*cp2++ = ' ';
2383 
2384 			cp = cp2;
2385 		}
2386 		freeenv(val);
2387 	}
2388 	return (found);
2389 }
2390 
2391 void *
2392 vm_iommu_domain(struct vm *vm)
2393 {
2394 
2395 	return (vm->iommu);
2396 }
2397 
2398 int
2399 vcpu_set_state(struct vcpu *vcpu, enum vcpu_state newstate, bool from_idle)
2400 {
2401 	int error;
2402 
2403 	vcpu_lock(vcpu);
2404 	error = vcpu_set_state_locked(vcpu, newstate, from_idle);
2405 	vcpu_unlock(vcpu);
2406 
2407 	return (error);
2408 }
2409 
2410 enum vcpu_state
2411 vcpu_get_state(struct vcpu *vcpu, int *hostcpu)
2412 {
2413 	enum vcpu_state state;
2414 
2415 	vcpu_lock(vcpu);
2416 	state = vcpu->state;
2417 	if (hostcpu != NULL)
2418 		*hostcpu = vcpu->hostcpu;
2419 	vcpu_unlock(vcpu);
2420 
2421 	return (state);
2422 }
2423 
2424 int
2425 vm_activate_cpu(struct vcpu *vcpu)
2426 {
2427 	struct vm *vm = vcpu->vm;
2428 
2429 	if (CPU_ISSET(vcpu->vcpuid, &vm->active_cpus))
2430 		return (EBUSY);
2431 
2432 	VMM_CTR0(vcpu, "activated");
2433 	CPU_SET_ATOMIC(vcpu->vcpuid, &vm->active_cpus);
2434 	return (0);
2435 }
2436 
2437 int
2438 vm_suspend_cpu(struct vm *vm, struct vcpu *vcpu)
2439 {
2440 	if (vcpu == NULL) {
2441 		vm->debug_cpus = vm->active_cpus;
2442 		for (int i = 0; i < vm->maxcpus; i++) {
2443 			if (CPU_ISSET(i, &vm->active_cpus))
2444 				vcpu_notify_event(vm_vcpu(vm, i), false);
2445 		}
2446 	} else {
2447 		if (!CPU_ISSET(vcpu->vcpuid, &vm->active_cpus))
2448 			return (EINVAL);
2449 
2450 		CPU_SET_ATOMIC(vcpu->vcpuid, &vm->debug_cpus);
2451 		vcpu_notify_event(vcpu, false);
2452 	}
2453 	return (0);
2454 }
2455 
2456 int
2457 vm_resume_cpu(struct vm *vm, struct vcpu *vcpu)
2458 {
2459 
2460 	if (vcpu == NULL) {
2461 		CPU_ZERO(&vm->debug_cpus);
2462 	} else {
2463 		if (!CPU_ISSET(vcpu->vcpuid, &vm->debug_cpus))
2464 			return (EINVAL);
2465 
2466 		CPU_CLR_ATOMIC(vcpu->vcpuid, &vm->debug_cpus);
2467 	}
2468 	return (0);
2469 }
2470 
2471 int
2472 vcpu_debugged(struct vcpu *vcpu)
2473 {
2474 
2475 	return (CPU_ISSET(vcpu->vcpuid, &vcpu->vm->debug_cpus));
2476 }
2477 
2478 cpuset_t
2479 vm_active_cpus(struct vm *vm)
2480 {
2481 
2482 	return (vm->active_cpus);
2483 }
2484 
2485 cpuset_t
2486 vm_debug_cpus(struct vm *vm)
2487 {
2488 
2489 	return (vm->debug_cpus);
2490 }
2491 
2492 cpuset_t
2493 vm_suspended_cpus(struct vm *vm)
2494 {
2495 
2496 	return (vm->suspended_cpus);
2497 }
2498 
2499 /*
2500  * Returns the subset of vCPUs in tostart that are awaiting startup.
2501  * These vCPUs are also marked as no longer awaiting startup.
2502  */
2503 cpuset_t
2504 vm_start_cpus(struct vm *vm, const cpuset_t *tostart)
2505 {
2506 	cpuset_t set;
2507 
2508 	mtx_lock(&vm->rendezvous_mtx);
2509 	CPU_AND(&set, &vm->startup_cpus, tostart);
2510 	CPU_ANDNOT(&vm->startup_cpus, &vm->startup_cpus, &set);
2511 	mtx_unlock(&vm->rendezvous_mtx);
2512 	return (set);
2513 }
2514 
2515 void
2516 vm_await_start(struct vm *vm, const cpuset_t *waiting)
2517 {
2518 	mtx_lock(&vm->rendezvous_mtx);
2519 	CPU_OR(&vm->startup_cpus, &vm->startup_cpus, waiting);
2520 	mtx_unlock(&vm->rendezvous_mtx);
2521 }
2522 
2523 void *
2524 vcpu_stats(struct vcpu *vcpu)
2525 {
2526 
2527 	return (vcpu->stats);
2528 }
2529 
2530 int
2531 vm_get_x2apic_state(struct vcpu *vcpu, enum x2apic_state *state)
2532 {
2533 	*state = vcpu->x2apic_state;
2534 
2535 	return (0);
2536 }
2537 
2538 int
2539 vm_set_x2apic_state(struct vcpu *vcpu, enum x2apic_state state)
2540 {
2541 	if (state >= X2APIC_STATE_LAST)
2542 		return (EINVAL);
2543 
2544 	vcpu->x2apic_state = state;
2545 
2546 	vlapic_set_x2apic_state(vcpu, state);
2547 
2548 	return (0);
2549 }
2550 
2551 /*
2552  * This function is called to ensure that a vcpu "sees" a pending event
2553  * as soon as possible:
2554  * - If the vcpu thread is sleeping then it is woken up.
2555  * - If the vcpu is running on a different host_cpu then an IPI will be directed
2556  *   to the host_cpu to cause the vcpu to trap into the hypervisor.
2557  */
2558 static void
2559 vcpu_notify_event_locked(struct vcpu *vcpu, bool lapic_intr)
2560 {
2561 	int hostcpu;
2562 
2563 	hostcpu = vcpu->hostcpu;
2564 	if (vcpu->state == VCPU_RUNNING) {
2565 		KASSERT(hostcpu != NOCPU, ("vcpu running on invalid hostcpu"));
2566 		if (hostcpu != curcpu) {
2567 			if (lapic_intr) {
2568 				vlapic_post_intr(vcpu->vlapic, hostcpu,
2569 				    vmm_ipinum);
2570 			} else {
2571 				ipi_cpu(hostcpu, vmm_ipinum);
2572 			}
2573 		} else {
2574 			/*
2575 			 * If the 'vcpu' is running on 'curcpu' then it must
2576 			 * be sending a notification to itself (e.g. SELF_IPI).
2577 			 * The pending event will be picked up when the vcpu
2578 			 * transitions back to guest context.
2579 			 */
2580 		}
2581 	} else {
2582 		KASSERT(hostcpu == NOCPU, ("vcpu state %d not consistent "
2583 		    "with hostcpu %d", vcpu->state, hostcpu));
2584 		if (vcpu->state == VCPU_SLEEPING)
2585 			wakeup_one(vcpu);
2586 	}
2587 }
2588 
2589 void
2590 vcpu_notify_event(struct vcpu *vcpu, bool lapic_intr)
2591 {
2592 	vcpu_lock(vcpu);
2593 	vcpu_notify_event_locked(vcpu, lapic_intr);
2594 	vcpu_unlock(vcpu);
2595 }
2596 
2597 struct vmspace *
2598 vm_get_vmspace(struct vm *vm)
2599 {
2600 
2601 	return (vm->vmspace);
2602 }
2603 
2604 int
2605 vm_apicid2vcpuid(struct vm *vm, int apicid)
2606 {
2607 	/*
2608 	 * XXX apic id is assumed to be numerically identical to vcpu id
2609 	 */
2610 	return (apicid);
2611 }
2612 
2613 int
2614 vm_smp_rendezvous(struct vcpu *vcpu, cpuset_t dest,
2615     vm_rendezvous_func_t func, void *arg)
2616 {
2617 	struct vm *vm = vcpu->vm;
2618 	int error, i;
2619 
2620 	/*
2621 	 * Enforce that this function is called without any locks
2622 	 */
2623 	WITNESS_WARN(WARN_PANIC, NULL, "vm_smp_rendezvous");
2624 
2625 restart:
2626 	mtx_lock(&vm->rendezvous_mtx);
2627 	if (vm->rendezvous_func != NULL) {
2628 		/*
2629 		 * If a rendezvous is already in progress then we need to
2630 		 * call the rendezvous handler in case this 'vcpu' is one
2631 		 * of the targets of the rendezvous.
2632 		 */
2633 		VMM_CTR0(vcpu, "Rendezvous already in progress");
2634 		mtx_unlock(&vm->rendezvous_mtx);
2635 		error = vm_handle_rendezvous(vcpu);
2636 		if (error != 0)
2637 			return (error);
2638 		goto restart;
2639 	}
2640 	KASSERT(vm->rendezvous_func == NULL, ("vm_smp_rendezvous: previous "
2641 	    "rendezvous is still in progress"));
2642 
2643 	VMM_CTR0(vcpu, "Initiating rendezvous");
2644 	vm->rendezvous_req_cpus = dest;
2645 	CPU_ZERO(&vm->rendezvous_done_cpus);
2646 	vm->rendezvous_arg = arg;
2647 	vm->rendezvous_func = func;
2648 	mtx_unlock(&vm->rendezvous_mtx);
2649 
2650 	/*
2651 	 * Wake up any sleeping vcpus and trigger a VM-exit in any running
2652 	 * vcpus so they handle the rendezvous as soon as possible.
2653 	 */
2654 	for (i = 0; i < vm->maxcpus; i++) {
2655 		if (CPU_ISSET(i, &dest))
2656 			vcpu_notify_event(vm_vcpu(vm, i), false);
2657 	}
2658 
2659 	return (vm_handle_rendezvous(vcpu));
2660 }
2661 
2662 struct vatpic *
2663 vm_atpic(struct vm *vm)
2664 {
2665 	return (vm->vatpic);
2666 }
2667 
2668 struct vatpit *
2669 vm_atpit(struct vm *vm)
2670 {
2671 	return (vm->vatpit);
2672 }
2673 
2674 struct vpmtmr *
2675 vm_pmtmr(struct vm *vm)
2676 {
2677 
2678 	return (vm->vpmtmr);
2679 }
2680 
2681 struct vrtc *
2682 vm_rtc(struct vm *vm)
2683 {
2684 
2685 	return (vm->vrtc);
2686 }
2687 
2688 enum vm_reg_name
2689 vm_segment_name(int seg)
2690 {
2691 	static enum vm_reg_name seg_names[] = {
2692 		VM_REG_GUEST_ES,
2693 		VM_REG_GUEST_CS,
2694 		VM_REG_GUEST_SS,
2695 		VM_REG_GUEST_DS,
2696 		VM_REG_GUEST_FS,
2697 		VM_REG_GUEST_GS
2698 	};
2699 
2700 	KASSERT(seg >= 0 && seg < nitems(seg_names),
2701 	    ("%s: invalid segment encoding %d", __func__, seg));
2702 	return (seg_names[seg]);
2703 }
2704 
2705 void
2706 vm_copy_teardown(struct vm_copyinfo *copyinfo, int num_copyinfo)
2707 {
2708 	int idx;
2709 
2710 	for (idx = 0; idx < num_copyinfo; idx++) {
2711 		if (copyinfo[idx].cookie != NULL)
2712 			vm_gpa_release(copyinfo[idx].cookie);
2713 	}
2714 	bzero(copyinfo, num_copyinfo * sizeof(struct vm_copyinfo));
2715 }
2716 
2717 int
2718 vm_copy_setup(struct vcpu *vcpu, struct vm_guest_paging *paging,
2719     uint64_t gla, size_t len, int prot, struct vm_copyinfo *copyinfo,
2720     int num_copyinfo, int *fault)
2721 {
2722 	int error, idx, nused;
2723 	size_t n, off, remaining;
2724 	void *hva, *cookie;
2725 	uint64_t gpa;
2726 
2727 	bzero(copyinfo, sizeof(struct vm_copyinfo) * num_copyinfo);
2728 
2729 	nused = 0;
2730 	remaining = len;
2731 	while (remaining > 0) {
2732 		KASSERT(nused < num_copyinfo, ("insufficient vm_copyinfo"));
2733 		error = vm_gla2gpa(vcpu, paging, gla, prot, &gpa, fault);
2734 		if (error || *fault)
2735 			return (error);
2736 		off = gpa & PAGE_MASK;
2737 		n = min(remaining, PAGE_SIZE - off);
2738 		copyinfo[nused].gpa = gpa;
2739 		copyinfo[nused].len = n;
2740 		remaining -= n;
2741 		gla += n;
2742 		nused++;
2743 	}
2744 
2745 	for (idx = 0; idx < nused; idx++) {
2746 		hva = vm_gpa_hold(vcpu, copyinfo[idx].gpa,
2747 		    copyinfo[idx].len, prot, &cookie);
2748 		if (hva == NULL)
2749 			break;
2750 		copyinfo[idx].hva = hva;
2751 		copyinfo[idx].cookie = cookie;
2752 	}
2753 
2754 	if (idx != nused) {
2755 		vm_copy_teardown(copyinfo, num_copyinfo);
2756 		return (EFAULT);
2757 	} else {
2758 		*fault = 0;
2759 		return (0);
2760 	}
2761 }
2762 
2763 void
2764 vm_copyin(struct vm_copyinfo *copyinfo, void *kaddr, size_t len)
2765 {
2766 	char *dst;
2767 	int idx;
2768 
2769 	dst = kaddr;
2770 	idx = 0;
2771 	while (len > 0) {
2772 		bcopy(copyinfo[idx].hva, dst, copyinfo[idx].len);
2773 		len -= copyinfo[idx].len;
2774 		dst += copyinfo[idx].len;
2775 		idx++;
2776 	}
2777 }
2778 
2779 void
2780 vm_copyout(const void *kaddr, struct vm_copyinfo *copyinfo, size_t len)
2781 {
2782 	const char *src;
2783 	int idx;
2784 
2785 	src = kaddr;
2786 	idx = 0;
2787 	while (len > 0) {
2788 		bcopy(src, copyinfo[idx].hva, copyinfo[idx].len);
2789 		len -= copyinfo[idx].len;
2790 		src += copyinfo[idx].len;
2791 		idx++;
2792 	}
2793 }
2794 
2795 /*
2796  * Return the amount of in-use and wired memory for the VM. Since
2797  * these are global stats, only return the values with for vCPU 0
2798  */
2799 VMM_STAT_DECLARE(VMM_MEM_RESIDENT);
2800 VMM_STAT_DECLARE(VMM_MEM_WIRED);
2801 
2802 static void
2803 vm_get_rescnt(struct vcpu *vcpu, struct vmm_stat_type *stat)
2804 {
2805 
2806 	if (vcpu->vcpuid == 0) {
2807 		vmm_stat_set(vcpu, VMM_MEM_RESIDENT, PAGE_SIZE *
2808 		    vmspace_resident_count(vcpu->vm->vmspace));
2809 	}
2810 }
2811 
2812 static void
2813 vm_get_wiredcnt(struct vcpu *vcpu, struct vmm_stat_type *stat)
2814 {
2815 
2816 	if (vcpu->vcpuid == 0) {
2817 		vmm_stat_set(vcpu, VMM_MEM_WIRED, PAGE_SIZE *
2818 		    pmap_wired_count(vmspace_pmap(vcpu->vm->vmspace)));
2819 	}
2820 }
2821 
2822 VMM_STAT_FUNC(VMM_MEM_RESIDENT, "Resident memory", vm_get_rescnt);
2823 VMM_STAT_FUNC(VMM_MEM_WIRED, "Wired memory", vm_get_wiredcnt);
2824 
2825 #ifdef BHYVE_SNAPSHOT
2826 static int
2827 vm_snapshot_vcpus(struct vm *vm, struct vm_snapshot_meta *meta)
2828 {
2829 	uint64_t tsc, now;
2830 	int ret;
2831 	struct vcpu *vcpu;
2832 	uint16_t i, maxcpus;
2833 
2834 	now = rdtsc();
2835 	maxcpus = vm_get_maxcpus(vm);
2836 	for (i = 0; i < maxcpus; i++) {
2837 		vcpu = vm->vcpu[i];
2838 		if (vcpu == NULL)
2839 			continue;
2840 
2841 		SNAPSHOT_VAR_OR_LEAVE(vcpu->x2apic_state, meta, ret, done);
2842 		SNAPSHOT_VAR_OR_LEAVE(vcpu->exitintinfo, meta, ret, done);
2843 		SNAPSHOT_VAR_OR_LEAVE(vcpu->exc_vector, meta, ret, done);
2844 		SNAPSHOT_VAR_OR_LEAVE(vcpu->exc_errcode_valid, meta, ret, done);
2845 		SNAPSHOT_VAR_OR_LEAVE(vcpu->exc_errcode, meta, ret, done);
2846 		SNAPSHOT_VAR_OR_LEAVE(vcpu->guest_xcr0, meta, ret, done);
2847 		SNAPSHOT_VAR_OR_LEAVE(vcpu->exitinfo, meta, ret, done);
2848 		SNAPSHOT_VAR_OR_LEAVE(vcpu->nextrip, meta, ret, done);
2849 
2850 		/*
2851 		 * Save the absolute TSC value by adding now to tsc_offset.
2852 		 *
2853 		 * It will be turned turned back into an actual offset when the
2854 		 * TSC restore function is called
2855 		 */
2856 		tsc = now + vcpu->tsc_offset;
2857 		SNAPSHOT_VAR_OR_LEAVE(tsc, meta, ret, done);
2858 	}
2859 
2860 done:
2861 	return (ret);
2862 }
2863 
2864 static int
2865 vm_snapshot_vm(struct vm *vm, struct vm_snapshot_meta *meta)
2866 {
2867 	int ret;
2868 
2869 	ret = vm_snapshot_vcpus(vm, meta);
2870 	if (ret != 0)
2871 		goto done;
2872 
2873 	SNAPSHOT_VAR_OR_LEAVE(vm->startup_cpus, meta, ret, done);
2874 done:
2875 	return (ret);
2876 }
2877 
2878 static int
2879 vm_snapshot_vcpu(struct vm *vm, struct vm_snapshot_meta *meta)
2880 {
2881 	int error;
2882 	struct vcpu *vcpu;
2883 	uint16_t i, maxcpus;
2884 
2885 	error = 0;
2886 
2887 	maxcpus = vm_get_maxcpus(vm);
2888 	for (i = 0; i < maxcpus; i++) {
2889 		vcpu = vm->vcpu[i];
2890 		if (vcpu == NULL)
2891 			continue;
2892 
2893 		error = vmmops_vcpu_snapshot(vcpu->cookie, meta);
2894 		if (error != 0) {
2895 			printf("%s: failed to snapshot vmcs/vmcb data for "
2896 			       "vCPU: %d; error: %d\n", __func__, i, error);
2897 			goto done;
2898 		}
2899 	}
2900 
2901 done:
2902 	return (error);
2903 }
2904 
2905 /*
2906  * Save kernel-side structures to user-space for snapshotting.
2907  */
2908 int
2909 vm_snapshot_req(struct vm *vm, struct vm_snapshot_meta *meta)
2910 {
2911 	int ret = 0;
2912 
2913 	switch (meta->dev_req) {
2914 	case STRUCT_VMX:
2915 		ret = vmmops_snapshot(vm->cookie, meta);
2916 		break;
2917 	case STRUCT_VMCX:
2918 		ret = vm_snapshot_vcpu(vm, meta);
2919 		break;
2920 	case STRUCT_VM:
2921 		ret = vm_snapshot_vm(vm, meta);
2922 		break;
2923 	case STRUCT_VIOAPIC:
2924 		ret = vioapic_snapshot(vm_ioapic(vm), meta);
2925 		break;
2926 	case STRUCT_VLAPIC:
2927 		ret = vlapic_snapshot(vm, meta);
2928 		break;
2929 	case STRUCT_VHPET:
2930 		ret = vhpet_snapshot(vm_hpet(vm), meta);
2931 		break;
2932 	case STRUCT_VATPIC:
2933 		ret = vatpic_snapshot(vm_atpic(vm), meta);
2934 		break;
2935 	case STRUCT_VATPIT:
2936 		ret = vatpit_snapshot(vm_atpit(vm), meta);
2937 		break;
2938 	case STRUCT_VPMTMR:
2939 		ret = vpmtmr_snapshot(vm_pmtmr(vm), meta);
2940 		break;
2941 	case STRUCT_VRTC:
2942 		ret = vrtc_snapshot(vm_rtc(vm), meta);
2943 		break;
2944 	default:
2945 		printf("%s: failed to find the requested type %#x\n",
2946 		       __func__, meta->dev_req);
2947 		ret = (EINVAL);
2948 	}
2949 	return (ret);
2950 }
2951 
2952 void
2953 vm_set_tsc_offset(struct vcpu *vcpu, uint64_t offset)
2954 {
2955 	vcpu->tsc_offset = offset;
2956 }
2957 
2958 int
2959 vm_restore_time(struct vm *vm)
2960 {
2961 	int error;
2962 	uint64_t now;
2963 	struct vcpu *vcpu;
2964 	uint16_t i, maxcpus;
2965 
2966 	now = rdtsc();
2967 
2968 	error = vhpet_restore_time(vm_hpet(vm));
2969 	if (error)
2970 		return (error);
2971 
2972 	maxcpus = vm_get_maxcpus(vm);
2973 	for (i = 0; i < maxcpus; i++) {
2974 		vcpu = vm->vcpu[i];
2975 		if (vcpu == NULL)
2976 			continue;
2977 
2978 		error = vmmops_restore_tsc(vcpu->cookie,
2979 		    vcpu->tsc_offset - now);
2980 		if (error)
2981 			return (error);
2982 	}
2983 
2984 	return (0);
2985 }
2986 #endif
2987