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