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