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