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