xref: /freebsd/sys/amd64/vmm/vmm.c (revision 892feec2)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2011 NetApp, Inc.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY NETAPP, INC ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL NETAPP, INC OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  *
28  * $FreeBSD$
29  */
30 
31 #include <sys/cdefs.h>
32 __FBSDID("$FreeBSD$");
33 
34 #include "opt_bhyve_snapshot.h"
35 
36 #include <sys/param.h>
37 #include <sys/systm.h>
38 #include <sys/kernel.h>
39 #include <sys/module.h>
40 #include <sys/sysctl.h>
41 #include <sys/malloc.h>
42 #include <sys/pcpu.h>
43 #include <sys/lock.h>
44 #include <sys/mutex.h>
45 #include <sys/proc.h>
46 #include <sys/rwlock.h>
47 #include <sys/sched.h>
48 #include <sys/smp.h>
49 #include <sys/sx.h>
50 #include <sys/vnode.h>
51 
52 #include <vm/vm.h>
53 #include <vm/vm_param.h>
54 #include <vm/vm_extern.h>
55 #include <vm/vm_object.h>
56 #include <vm/vm_page.h>
57 #include <vm/pmap.h>
58 #include <vm/vm_map.h>
59 #include <vm/vm_pager.h>
60 #include <vm/vm_kern.h>
61 #include <vm/vnode_pager.h>
62 #include <vm/swap_pager.h>
63 #include <vm/uma.h>
64 
65 #include <machine/cpu.h>
66 #include <machine/pcb.h>
67 #include <machine/smp.h>
68 #include <machine/md_var.h>
69 #include <x86/psl.h>
70 #include <x86/apicreg.h>
71 #include <x86/ifunc.h>
72 
73 #include <machine/vmm.h>
74 #include <machine/vmm_dev.h>
75 #include <machine/vmm_instruction_emul.h>
76 #include <machine/vmm_snapshot.h>
77 
78 #include "vmm_ioport.h"
79 #include "vmm_ktr.h"
80 #include "vmm_host.h"
81 #include "vmm_mem.h"
82 #include "vmm_util.h"
83 #include "vatpic.h"
84 #include "vatpit.h"
85 #include "vhpet.h"
86 #include "vioapic.h"
87 #include "vlapic.h"
88 #include "vpmtmr.h"
89 #include "vrtc.h"
90 #include "vmm_stat.h"
91 #include "vmm_lapic.h"
92 
93 #include "io/ppt.h"
94 #include "io/iommu.h"
95 
96 struct vlapic;
97 
98 /*
99  * Initialization:
100  * (a) allocated when vcpu is created
101  * (i) initialized when vcpu is created and when it is reinitialized
102  * (o) initialized the first time the vcpu is created
103  * (x) initialized before use
104  */
105 struct vcpu {
106 	struct mtx 	mtx;		/* (o) protects 'state' and 'hostcpu' */
107 	enum vcpu_state	state;		/* (o) vcpu state */
108 	int		vcpuid;		/* (o) */
109 	int		hostcpu;	/* (o) vcpu's host cpu */
110 	int		reqidle;	/* (i) request vcpu to idle */
111 	struct vm	*vm;		/* (o) */
112 	void		*cookie;	/* (i) cpu-specific data */
113 	struct vlapic	*vlapic;	/* (i) APIC device model */
114 	enum x2apic_state x2apic_state;	/* (i) APIC mode */
115 	uint64_t	exitintinfo;	/* (i) events pending at VM exit */
116 	int		nmi_pending;	/* (i) NMI pending */
117 	int		extint_pending;	/* (i) INTR pending */
118 	int	exception_pending;	/* (i) exception pending */
119 	int	exc_vector;		/* (x) exception collateral */
120 	int	exc_errcode_valid;
121 	uint32_t exc_errcode;
122 	struct savefpu	*guestfpu;	/* (a,i) guest fpu state */
123 	uint64_t	guest_xcr0;	/* (i) guest %xcr0 register */
124 	void		*stats;		/* (a,i) statistics */
125 	struct vm_exit	exitinfo;	/* (x) exit reason and collateral */
126 	uint64_t	nextrip;	/* (x) next instruction to execute */
127 	uint64_t	tsc_offset;	/* (o) TSC offsetting */
128 };
129 
130 #define	vcpu_lock_init(v)	mtx_init(&((v)->mtx), "vcpu lock", 0, MTX_SPIN)
131 #define	vcpu_lock_destroy(v)	mtx_destroy(&((v)->mtx))
132 #define	vcpu_lock(v)		mtx_lock_spin(&((v)->mtx))
133 #define	vcpu_unlock(v)		mtx_unlock_spin(&((v)->mtx))
134 #define	vcpu_assert_locked(v)	mtx_assert(&((v)->mtx), MA_OWNED)
135 
136 struct mem_seg {
137 	size_t	len;
138 	bool	sysmem;
139 	struct vm_object *object;
140 };
141 #define	VM_MAX_MEMSEGS	4
142 
143 struct mem_map {
144 	vm_paddr_t	gpa;
145 	size_t		len;
146 	vm_ooffset_t	segoff;
147 	int		segid;
148 	int		prot;
149 	int		flags;
150 };
151 #define	VM_MAX_MEMMAPS	8
152 
153 /*
154  * Initialization:
155  * (o) initialized the first time the VM is created
156  * (i) initialized when VM is created and when it is reinitialized
157  * (x) initialized before use
158  *
159  * Locking:
160  * [m] mem_segs_lock
161  * [r] rendezvous_mtx
162  * [v] reads require one frozen vcpu, writes require freezing all vcpus
163  */
164 struct vm {
165 	void		*cookie;		/* (i) cpu-specific data */
166 	void		*iommu;			/* (x) iommu-specific data */
167 	struct vhpet	*vhpet;			/* (i) virtual HPET */
168 	struct vioapic	*vioapic;		/* (i) virtual ioapic */
169 	struct vatpic	*vatpic;		/* (i) virtual atpic */
170 	struct vatpit	*vatpit;		/* (i) virtual atpit */
171 	struct vpmtmr	*vpmtmr;		/* (i) virtual ACPI PM timer */
172 	struct vrtc	*vrtc;			/* (o) virtual RTC */
173 	volatile cpuset_t active_cpus;		/* (i) active vcpus */
174 	volatile cpuset_t debug_cpus;		/* (i) vcpus stopped for debug */
175 	cpuset_t	startup_cpus;		/* (i) [r] waiting for startup */
176 	int		suspend;		/* (i) stop VM execution */
177 	bool		dying;			/* (o) is dying */
178 	volatile cpuset_t suspended_cpus; 	/* (i) suspended vcpus */
179 	volatile cpuset_t halted_cpus;		/* (x) cpus in a hard halt */
180 	cpuset_t	rendezvous_req_cpus;	/* (x) [r] rendezvous requested */
181 	cpuset_t	rendezvous_done_cpus;	/* (x) [r] rendezvous finished */
182 	void		*rendezvous_arg;	/* (x) [r] rendezvous func/arg */
183 	vm_rendezvous_func_t rendezvous_func;
184 	struct mtx	rendezvous_mtx;		/* (o) rendezvous lock */
185 	struct mem_map	mem_maps[VM_MAX_MEMMAPS]; /* (i) [m+v] guest address space */
186 	struct mem_seg	mem_segs[VM_MAX_MEMSEGS]; /* (o) [m+v] guest memory regions */
187 	struct vmspace	*vmspace;		/* (o) guest's address space */
188 	char		name[VM_MAX_NAMELEN+1];	/* (o) virtual machine name */
189 	struct vcpu	**vcpu;			/* (o) guest vcpus */
190 	/* The following describe the vm cpu topology */
191 	uint16_t	sockets;		/* (o) num of sockets */
192 	uint16_t	cores;			/* (o) num of cores/socket */
193 	uint16_t	threads;		/* (o) num of threads/core */
194 	uint16_t	maxcpus;		/* (o) max pluggable cpus */
195 	struct sx	mem_segs_lock;		/* (o) */
196 	struct sx	vcpus_init_lock;	/* (o) */
197 };
198 
199 #define	VMM_CTR0(vcpu, format)						\
200 	VCPU_CTR0((vcpu)->vm, (vcpu)->vcpuid, format)
201 
202 #define	VMM_CTR1(vcpu, format, p1)					\
203 	VCPU_CTR1((vcpu)->vm, (vcpu)->vcpuid, format, p1)
204 
205 #define	VMM_CTR2(vcpu, format, p1, p2)					\
206 	VCPU_CTR2((vcpu)->vm, (vcpu)->vcpuid, format, p1, p2)
207 
208 #define	VMM_CTR3(vcpu, format, p1, p2, p3)				\
209 	VCPU_CTR3((vcpu)->vm, (vcpu)->vcpuid, format, p1, p2, p3)
210 
211 #define	VMM_CTR4(vcpu, format, p1, p2, p3, p4)				\
212 	VCPU_CTR4((vcpu)->vm, (vcpu)->vcpuid, format, p1, p2, p3, p4)
213 
214 static int vmm_initialized;
215 
216 static void	vmmops_panic(void);
217 
218 static void
219 vmmops_panic(void)
220 {
221 	panic("vmm_ops func called when !vmm_is_intel() && !vmm_is_svm()");
222 }
223 
224 #define	DEFINE_VMMOPS_IFUNC(ret_type, opname, args)			\
225     DEFINE_IFUNC(static, ret_type, vmmops_##opname, args)		\
226     {									\
227     	if (vmm_is_intel())						\
228     		return (vmm_ops_intel.opname);				\
229     	else if (vmm_is_svm())						\
230     		return (vmm_ops_amd.opname);				\
231     	else								\
232     		return ((ret_type (*)args)vmmops_panic);		\
233     }
234 
235 DEFINE_VMMOPS_IFUNC(int, modinit, (int ipinum))
236 DEFINE_VMMOPS_IFUNC(int, modcleanup, (void))
237 DEFINE_VMMOPS_IFUNC(void, modresume, (void))
238 DEFINE_VMMOPS_IFUNC(void *, init, (struct vm *vm, struct pmap *pmap))
239 DEFINE_VMMOPS_IFUNC(int, run, (void *vcpui, register_t rip, struct pmap *pmap,
240     struct vm_eventinfo *info))
241 DEFINE_VMMOPS_IFUNC(void, cleanup, (void *vmi))
242 DEFINE_VMMOPS_IFUNC(void *, vcpu_init, (void *vmi, struct vcpu *vcpu,
243     int vcpu_id))
244 DEFINE_VMMOPS_IFUNC(void, vcpu_cleanup, (void *vcpui))
245 DEFINE_VMMOPS_IFUNC(int, getreg, (void *vcpui, int num, uint64_t *retval))
246 DEFINE_VMMOPS_IFUNC(int, setreg, (void *vcpui, int num, uint64_t val))
247 DEFINE_VMMOPS_IFUNC(int, getdesc, (void *vcpui, int num, struct seg_desc *desc))
248 DEFINE_VMMOPS_IFUNC(int, setdesc, (void *vcpui, int num, struct seg_desc *desc))
249 DEFINE_VMMOPS_IFUNC(int, getcap, (void *vcpui, int num, int *retval))
250 DEFINE_VMMOPS_IFUNC(int, setcap, (void *vcpui, int num, int val))
251 DEFINE_VMMOPS_IFUNC(struct vmspace *, vmspace_alloc, (vm_offset_t min,
252     vm_offset_t max))
253 DEFINE_VMMOPS_IFUNC(void, vmspace_free, (struct vmspace *vmspace))
254 DEFINE_VMMOPS_IFUNC(struct vlapic *, vlapic_init, (void *vcpui))
255 DEFINE_VMMOPS_IFUNC(void, vlapic_cleanup, (struct vlapic *vlapic))
256 #ifdef BHYVE_SNAPSHOT
257 DEFINE_VMMOPS_IFUNC(int, snapshot, (void *vmi, struct vm_snapshot_meta *meta))
258 DEFINE_VMMOPS_IFUNC(int, vcpu_snapshot, (void *vcpui,
259     struct vm_snapshot_meta *meta))
260 DEFINE_VMMOPS_IFUNC(int, restore_tsc, (void *vcpui, uint64_t now))
261 #endif
262 
263 #define	fpu_start_emulating()	load_cr0(rcr0() | CR0_TS)
264 #define	fpu_stop_emulating()	clts()
265 
266 SDT_PROVIDER_DEFINE(vmm);
267 
268 static MALLOC_DEFINE(M_VM, "vm", "vm");
269 
270 /* statistics */
271 static VMM_STAT(VCPU_TOTAL_RUNTIME, "vcpu total runtime");
272 
273 SYSCTL_NODE(_hw, OID_AUTO, vmm, CTLFLAG_RW | CTLFLAG_MPSAFE, NULL,
274     NULL);
275 
276 /*
277  * Halt the guest if all vcpus are executing a HLT instruction with
278  * interrupts disabled.
279  */
280 static int halt_detection_enabled = 1;
281 SYSCTL_INT(_hw_vmm, OID_AUTO, halt_detection, CTLFLAG_RDTUN,
282     &halt_detection_enabled, 0,
283     "Halt VM if all vcpus execute HLT with interrupts disabled");
284 
285 static int vmm_ipinum;
286 SYSCTL_INT(_hw_vmm, OID_AUTO, ipinum, CTLFLAG_RD, &vmm_ipinum, 0,
287     "IPI vector used for vcpu notifications");
288 
289 static int trace_guest_exceptions;
290 SYSCTL_INT(_hw_vmm, OID_AUTO, trace_guest_exceptions, CTLFLAG_RDTUN,
291     &trace_guest_exceptions, 0,
292     "Trap into hypervisor on all guest exceptions and reflect them back");
293 
294 static int trap_wbinvd;
295 SYSCTL_INT(_hw_vmm, OID_AUTO, trap_wbinvd, CTLFLAG_RDTUN, &trap_wbinvd, 0,
296     "WBINVD triggers a VM-exit");
297 
298 u_int vm_maxcpu;
299 SYSCTL_UINT(_hw_vmm, OID_AUTO, maxcpu, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
300     &vm_maxcpu, 0, "Maximum number of vCPUs");
301 
302 static void vm_free_memmap(struct vm *vm, int ident);
303 static bool sysmem_mapping(struct vm *vm, struct mem_map *mm);
304 static void vcpu_notify_event_locked(struct vcpu *vcpu, bool lapic_intr);
305 
306 /*
307  * Upper limit on vm_maxcpu.  Limited by use of uint16_t types for CPU
308  * counts as well as range of vpid values for VT-x and by the capacity
309  * of cpuset_t masks.  The call to new_unrhdr() in vpid_init() in
310  * vmx.c requires 'vm_maxcpu + 1 <= 0xffff', hence the '- 1' below.
311  */
312 #define	VM_MAXCPU	MIN(0xffff - 1, CPU_SETSIZE)
313 
314 #ifdef KTR
315 static const char *
316 vcpu_state2str(enum vcpu_state state)
317 {
318 
319 	switch (state) {
320 	case VCPU_IDLE:
321 		return ("idle");
322 	case VCPU_FROZEN:
323 		return ("frozen");
324 	case VCPU_RUNNING:
325 		return ("running");
326 	case VCPU_SLEEPING:
327 		return ("sleeping");
328 	default:
329 		return ("unknown");
330 	}
331 }
332 #endif
333 
334 static void
335 vcpu_cleanup(struct vcpu *vcpu, bool destroy)
336 {
337 	vmmops_vlapic_cleanup(vcpu->vlapic);
338 	vmmops_vcpu_cleanup(vcpu->cookie);
339 	vcpu->cookie = NULL;
340 	if (destroy) {
341 		vmm_stat_free(vcpu->stats);
342 		fpu_save_area_free(vcpu->guestfpu);
343 		vcpu_lock_destroy(vcpu);
344 		free(vcpu, M_VM);
345 	}
346 }
347 
348 static struct vcpu *
349 vcpu_alloc(struct vm *vm, int vcpu_id)
350 {
351 	struct vcpu *vcpu;
352 
353 	KASSERT(vcpu_id >= 0 && vcpu_id < vm->maxcpus,
354 	    ("vcpu_init: invalid vcpu %d", vcpu_id));
355 
356 	vcpu = malloc(sizeof(*vcpu), M_VM, M_WAITOK | M_ZERO);
357 	vcpu_lock_init(vcpu);
358 	vcpu->state = VCPU_IDLE;
359 	vcpu->hostcpu = NOCPU;
360 	vcpu->vcpuid = vcpu_id;
361 	vcpu->vm = vm;
362 	vcpu->guestfpu = fpu_save_area_alloc();
363 	vcpu->stats = vmm_stat_alloc();
364 	vcpu->tsc_offset = 0;
365 	return (vcpu);
366 }
367 
368 static void
369 vcpu_init(struct vcpu *vcpu)
370 {
371 	vcpu->cookie = vmmops_vcpu_init(vcpu->vm->cookie, vcpu, vcpu->vcpuid);
372 	vcpu->vlapic = vmmops_vlapic_init(vcpu->cookie);
373 	vm_set_x2apic_state(vcpu, X2APIC_DISABLED);
374 	vcpu->reqidle = 0;
375 	vcpu->exitintinfo = 0;
376 	vcpu->nmi_pending = 0;
377 	vcpu->extint_pending = 0;
378 	vcpu->exception_pending = 0;
379 	vcpu->guest_xcr0 = XFEATURE_ENABLED_X87;
380 	fpu_save_area_reset(vcpu->guestfpu);
381 	vmm_stat_init(vcpu->stats);
382 }
383 
384 int
385 vcpu_trace_exceptions(struct vcpu *vcpu)
386 {
387 
388 	return (trace_guest_exceptions);
389 }
390 
391 int
392 vcpu_trap_wbinvd(struct vcpu *vcpu)
393 {
394 	return (trap_wbinvd);
395 }
396 
397 struct vm_exit *
398 vm_exitinfo(struct vcpu *vcpu)
399 {
400 	return (&vcpu->exitinfo);
401 }
402 
403 static int
404 vmm_init(void)
405 {
406 	int error;
407 
408 	if (!vmm_is_hw_supported())
409 		return (ENXIO);
410 
411 	vm_maxcpu = mp_ncpus;
412 	TUNABLE_INT_FETCH("hw.vmm.maxcpu", &vm_maxcpu);
413 
414 	if (vm_maxcpu > VM_MAXCPU) {
415 		printf("vmm: vm_maxcpu clamped to %u\n", VM_MAXCPU);
416 		vm_maxcpu = VM_MAXCPU;
417 	}
418 	if (vm_maxcpu == 0)
419 		vm_maxcpu = 1;
420 
421 	vmm_host_state_init();
422 
423 	vmm_ipinum = lapic_ipi_alloc(pti ? &IDTVEC(justreturn1_pti) :
424 	    &IDTVEC(justreturn));
425 	if (vmm_ipinum < 0)
426 		vmm_ipinum = IPI_AST;
427 
428 	error = vmm_mem_init();
429 	if (error)
430 		return (error);
431 
432 	vmm_resume_p = vmmops_modresume;
433 
434 	return (vmmops_modinit(vmm_ipinum));
435 }
436 
437 static int
438 vmm_handler(module_t mod, int what, void *arg)
439 {
440 	int error;
441 
442 	switch (what) {
443 	case MOD_LOAD:
444 		if (vmm_is_hw_supported()) {
445 			vmmdev_init();
446 			error = vmm_init();
447 			if (error == 0)
448 				vmm_initialized = 1;
449 		} else {
450 			error = ENXIO;
451 		}
452 		break;
453 	case MOD_UNLOAD:
454 		if (vmm_is_hw_supported()) {
455 			error = vmmdev_cleanup();
456 			if (error == 0) {
457 				vmm_resume_p = NULL;
458 				iommu_cleanup();
459 				if (vmm_ipinum != IPI_AST)
460 					lapic_ipi_free(vmm_ipinum);
461 				error = vmmops_modcleanup();
462 				/*
463 				 * Something bad happened - prevent new
464 				 * VMs from being created
465 				 */
466 				if (error)
467 					vmm_initialized = 0;
468 			}
469 		} else {
470 			error = 0;
471 		}
472 		break;
473 	default:
474 		error = 0;
475 		break;
476 	}
477 	return (error);
478 }
479 
480 static moduledata_t vmm_kmod = {
481 	"vmm",
482 	vmm_handler,
483 	NULL
484 };
485 
486 /*
487  * vmm initialization has the following dependencies:
488  *
489  * - VT-x initialization requires smp_rendezvous() and therefore must happen
490  *   after SMP is fully functional (after SI_SUB_SMP).
491  */
492 DECLARE_MODULE(vmm, vmm_kmod, SI_SUB_SMP + 1, SI_ORDER_ANY);
493 MODULE_VERSION(vmm, 1);
494 
495 static void
496 vm_init(struct vm *vm, bool create)
497 {
498 	vm->cookie = vmmops_init(vm, vmspace_pmap(vm->vmspace));
499 	vm->iommu = NULL;
500 	vm->vioapic = vioapic_init(vm);
501 	vm->vhpet = vhpet_init(vm);
502 	vm->vatpic = vatpic_init(vm);
503 	vm->vatpit = vatpit_init(vm);
504 	vm->vpmtmr = vpmtmr_init(vm);
505 	if (create)
506 		vm->vrtc = vrtc_init(vm);
507 
508 	CPU_ZERO(&vm->active_cpus);
509 	CPU_ZERO(&vm->debug_cpus);
510 	CPU_ZERO(&vm->startup_cpus);
511 
512 	vm->suspend = 0;
513 	CPU_ZERO(&vm->suspended_cpus);
514 
515 	if (!create) {
516 		for (int i = 0; i < vm->maxcpus; i++) {
517 			if (vm->vcpu[i] != NULL)
518 				vcpu_init(vm->vcpu[i]);
519 		}
520 	}
521 }
522 
523 void
524 vm_disable_vcpu_creation(struct vm *vm)
525 {
526 	sx_xlock(&vm->vcpus_init_lock);
527 	vm->dying = true;
528 	sx_xunlock(&vm->vcpus_init_lock);
529 }
530 
531 struct vcpu *
532 vm_alloc_vcpu(struct vm *vm, int vcpuid)
533 {
534 	struct vcpu *vcpu;
535 
536 	if (vcpuid < 0 || vcpuid >= vm_get_maxcpus(vm))
537 		return (NULL);
538 
539 	vcpu = atomic_load_ptr(&vm->vcpu[vcpuid]);
540 	if (__predict_true(vcpu != NULL))
541 		return (vcpu);
542 
543 	sx_xlock(&vm->vcpus_init_lock);
544 	vcpu = vm->vcpu[vcpuid];
545 	if (vcpu == NULL && !vm->dying) {
546 		vcpu = vcpu_alloc(vm, vcpuid);
547 		vcpu_init(vcpu);
548 
549 		/*
550 		 * Ensure vCPU is fully created before updating pointer
551 		 * to permit unlocked reads above.
552 		 */
553 		atomic_store_rel_ptr((uintptr_t *)&vm->vcpu[vcpuid],
554 		    (uintptr_t)vcpu);
555 	}
556 	sx_xunlock(&vm->vcpus_init_lock);
557 	return (vcpu);
558 }
559 
560 void
561 vm_slock_vcpus(struct vm *vm)
562 {
563 	sx_slock(&vm->vcpus_init_lock);
564 }
565 
566 void
567 vm_unlock_vcpus(struct vm *vm)
568 {
569 	sx_unlock(&vm->vcpus_init_lock);
570 }
571 
572 /*
573  * The default CPU topology is a single thread per package.
574  */
575 u_int cores_per_package = 1;
576 u_int threads_per_core = 1;
577 
578 int
579 vm_create(const char *name, struct vm **retvm)
580 {
581 	struct vm *vm;
582 	struct vmspace *vmspace;
583 
584 	/*
585 	 * If vmm.ko could not be successfully initialized then don't attempt
586 	 * to create the virtual machine.
587 	 */
588 	if (!vmm_initialized)
589 		return (ENXIO);
590 
591 	if (name == NULL || strnlen(name, VM_MAX_NAMELEN + 1) ==
592 	    VM_MAX_NAMELEN + 1)
593 		return (EINVAL);
594 
595 	vmspace = vmmops_vmspace_alloc(0, VM_MAXUSER_ADDRESS_LA48);
596 	if (vmspace == NULL)
597 		return (ENOMEM);
598 
599 	vm = malloc(sizeof(struct vm), M_VM, M_WAITOK | M_ZERO);
600 	strcpy(vm->name, name);
601 	vm->vmspace = vmspace;
602 	mtx_init(&vm->rendezvous_mtx, "vm rendezvous lock", 0, MTX_DEF);
603 	sx_init(&vm->mem_segs_lock, "vm mem_segs");
604 	sx_init(&vm->vcpus_init_lock, "vm vcpus");
605 	vm->vcpu = malloc(sizeof(*vm->vcpu) * vm_maxcpu, M_VM, M_WAITOK |
606 	    M_ZERO);
607 
608 	vm->sockets = 1;
609 	vm->cores = cores_per_package;	/* XXX backwards compatibility */
610 	vm->threads = threads_per_core;	/* XXX backwards compatibility */
611 	vm->maxcpus = vm_maxcpu;
612 
613 	vm_init(vm, true);
614 
615 	*retvm = vm;
616 	return (0);
617 }
618 
619 void
620 vm_get_topology(struct vm *vm, uint16_t *sockets, uint16_t *cores,
621     uint16_t *threads, uint16_t *maxcpus)
622 {
623 	*sockets = vm->sockets;
624 	*cores = vm->cores;
625 	*threads = vm->threads;
626 	*maxcpus = vm->maxcpus;
627 }
628 
629 uint16_t
630 vm_get_maxcpus(struct vm *vm)
631 {
632 	return (vm->maxcpus);
633 }
634 
635 int
636 vm_set_topology(struct vm *vm, uint16_t sockets, uint16_t cores,
637     uint16_t threads, uint16_t maxcpus __unused)
638 {
639 	/* Ignore maxcpus. */
640 	if ((sockets * cores * threads) > vm->maxcpus)
641 		return (EINVAL);
642 	vm->sockets = sockets;
643 	vm->cores = cores;
644 	vm->threads = threads;
645 	return(0);
646 }
647 
648 static void
649 vm_cleanup(struct vm *vm, bool destroy)
650 {
651 	struct mem_map *mm;
652 	int i;
653 
654 	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_modify(struct vm *vm, bool map)
1042 {
1043 	int i, sz;
1044 	vm_paddr_t gpa, hpa;
1045 	struct mem_map *mm;
1046 	void *vp, *cookie, *host_domain;
1047 
1048 	sz = PAGE_SIZE;
1049 	host_domain = iommu_host_domain();
1050 
1051 	for (i = 0; i < VM_MAX_MEMMAPS; i++) {
1052 		mm = &vm->mem_maps[i];
1053 		if (!sysmem_mapping(vm, mm))
1054 			continue;
1055 
1056 		if (map) {
1057 			KASSERT((mm->flags & VM_MEMMAP_F_IOMMU) == 0,
1058 			    ("iommu map found invalid memmap %#lx/%#lx/%#x",
1059 			    mm->gpa, mm->len, mm->flags));
1060 			if ((mm->flags & VM_MEMMAP_F_WIRED) == 0)
1061 				continue;
1062 			mm->flags |= VM_MEMMAP_F_IOMMU;
1063 		} else {
1064 			if ((mm->flags & VM_MEMMAP_F_IOMMU) == 0)
1065 				continue;
1066 			mm->flags &= ~VM_MEMMAP_F_IOMMU;
1067 			KASSERT((mm->flags & VM_MEMMAP_F_WIRED) != 0,
1068 			    ("iommu unmap found invalid memmap %#lx/%#lx/%#x",
1069 			    mm->gpa, mm->len, mm->flags));
1070 		}
1071 
1072 		gpa = mm->gpa;
1073 		while (gpa < mm->gpa + mm->len) {
1074 			vp = vm_gpa_hold_global(vm, gpa, PAGE_SIZE,
1075 			    VM_PROT_WRITE, &cookie);
1076 			KASSERT(vp != NULL, ("vm(%s) could not map gpa %#lx",
1077 			    vm_name(vm), gpa));
1078 
1079 			vm_gpa_release(cookie);
1080 
1081 			hpa = DMAP_TO_PHYS((uintptr_t)vp);
1082 			if (map) {
1083 				iommu_create_mapping(vm->iommu, gpa, hpa, sz);
1084 			} else {
1085 				iommu_remove_mapping(vm->iommu, gpa, sz);
1086 			}
1087 
1088 			gpa += PAGE_SIZE;
1089 		}
1090 	}
1091 
1092 	/*
1093 	 * Invalidate the cached translations associated with the domain
1094 	 * from which pages were removed.
1095 	 */
1096 	if (map)
1097 		iommu_invalidate_tlb(host_domain);
1098 	else
1099 		iommu_invalidate_tlb(vm->iommu);
1100 }
1101 
1102 #define	vm_iommu_unmap(vm)	vm_iommu_modify((vm), false)
1103 #define	vm_iommu_map(vm)	vm_iommu_modify((vm), true)
1104 
1105 int
1106 vm_unassign_pptdev(struct vm *vm, int bus, int slot, int func)
1107 {
1108 	int error;
1109 
1110 	error = ppt_unassign_device(vm, bus, slot, func);
1111 	if (error)
1112 		return (error);
1113 
1114 	if (ppt_assigned_devices(vm) == 0)
1115 		vm_iommu_unmap(vm);
1116 
1117 	return (0);
1118 }
1119 
1120 int
1121 vm_assign_pptdev(struct vm *vm, int bus, int slot, int func)
1122 {
1123 	int error;
1124 	vm_paddr_t maxaddr;
1125 
1126 	/* Set up the IOMMU to do the 'gpa' to 'hpa' translation */
1127 	if (ppt_assigned_devices(vm) == 0) {
1128 		KASSERT(vm->iommu == NULL,
1129 		    ("vm_assign_pptdev: iommu must be NULL"));
1130 		maxaddr = vmm_sysmem_maxaddr(vm);
1131 		vm->iommu = iommu_create_domain(maxaddr);
1132 		if (vm->iommu == NULL)
1133 			return (ENXIO);
1134 		vm_iommu_map(vm);
1135 	}
1136 
1137 	error = ppt_assign_device(vm, bus, slot, func);
1138 	return (error);
1139 }
1140 
1141 static void *
1142 _vm_gpa_hold(struct vm *vm, vm_paddr_t gpa, size_t len, int reqprot,
1143     void **cookie)
1144 {
1145 	int i, count, pageoff;
1146 	struct mem_map *mm;
1147 	vm_page_t m;
1148 
1149 	pageoff = gpa & PAGE_MASK;
1150 	if (len > PAGE_SIZE - pageoff)
1151 		panic("vm_gpa_hold: invalid gpa/len: 0x%016lx/%lu", gpa, len);
1152 
1153 	count = 0;
1154 	for (i = 0; i < VM_MAX_MEMMAPS; i++) {
1155 		mm = &vm->mem_maps[i];
1156 		if (gpa >= mm->gpa && gpa < mm->gpa + mm->len) {
1157 			count = vm_fault_quick_hold_pages(&vm->vmspace->vm_map,
1158 			    trunc_page(gpa), PAGE_SIZE, reqprot, &m, 1);
1159 			break;
1160 		}
1161 	}
1162 
1163 	if (count == 1) {
1164 		*cookie = m;
1165 		return ((void *)(PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m)) + pageoff));
1166 	} else {
1167 		*cookie = NULL;
1168 		return (NULL);
1169 	}
1170 }
1171 
1172 void *
1173 vm_gpa_hold(struct vcpu *vcpu, vm_paddr_t gpa, size_t len, int reqprot,
1174     void **cookie)
1175 {
1176 #ifdef INVARIANTS
1177 	/*
1178 	 * The current vcpu should be frozen to ensure 'vm_memmap[]'
1179 	 * stability.
1180 	 */
1181 	int state = vcpu_get_state(vcpu, NULL);
1182 	KASSERT(state == VCPU_FROZEN, ("%s: invalid vcpu state %d",
1183 	    __func__, state));
1184 #endif
1185 	return (_vm_gpa_hold(vcpu->vm, gpa, len, reqprot, cookie));
1186 }
1187 
1188 void *
1189 vm_gpa_hold_global(struct vm *vm, vm_paddr_t gpa, size_t len, int reqprot,
1190     void **cookie)
1191 {
1192 	sx_assert(&vm->mem_segs_lock, SX_LOCKED);
1193 	return (_vm_gpa_hold(vm, gpa, len, reqprot, cookie));
1194 }
1195 
1196 void
1197 vm_gpa_release(void *cookie)
1198 {
1199 	vm_page_t m = cookie;
1200 
1201 	vm_page_unwire(m, PQ_ACTIVE);
1202 }
1203 
1204 int
1205 vm_get_register(struct vcpu *vcpu, int reg, uint64_t *retval)
1206 {
1207 
1208 	if (reg >= VM_REG_LAST)
1209 		return (EINVAL);
1210 
1211 	return (vmmops_getreg(vcpu->cookie, reg, retval));
1212 }
1213 
1214 int
1215 vm_set_register(struct vcpu *vcpu, int reg, uint64_t val)
1216 {
1217 	int error;
1218 
1219 	if (reg >= VM_REG_LAST)
1220 		return (EINVAL);
1221 
1222 	error = vmmops_setreg(vcpu->cookie, reg, val);
1223 	if (error || reg != VM_REG_GUEST_RIP)
1224 		return (error);
1225 
1226 	/* Set 'nextrip' to match the value of %rip */
1227 	VMM_CTR1(vcpu, "Setting nextrip to %#lx", val);
1228 	vcpu->nextrip = val;
1229 	return (0);
1230 }
1231 
1232 static bool
1233 is_descriptor_table(int reg)
1234 {
1235 
1236 	switch (reg) {
1237 	case VM_REG_GUEST_IDTR:
1238 	case VM_REG_GUEST_GDTR:
1239 		return (true);
1240 	default:
1241 		return (false);
1242 	}
1243 }
1244 
1245 static bool
1246 is_segment_register(int reg)
1247 {
1248 
1249 	switch (reg) {
1250 	case VM_REG_GUEST_ES:
1251 	case VM_REG_GUEST_CS:
1252 	case VM_REG_GUEST_SS:
1253 	case VM_REG_GUEST_DS:
1254 	case VM_REG_GUEST_FS:
1255 	case VM_REG_GUEST_GS:
1256 	case VM_REG_GUEST_TR:
1257 	case VM_REG_GUEST_LDTR:
1258 		return (true);
1259 	default:
1260 		return (false);
1261 	}
1262 }
1263 
1264 int
1265 vm_get_seg_desc(struct vcpu *vcpu, int reg, struct seg_desc *desc)
1266 {
1267 
1268 	if (!is_segment_register(reg) && !is_descriptor_table(reg))
1269 		return (EINVAL);
1270 
1271 	return (vmmops_getdesc(vcpu->cookie, reg, desc));
1272 }
1273 
1274 int
1275 vm_set_seg_desc(struct vcpu *vcpu, int reg, struct seg_desc *desc)
1276 {
1277 
1278 	if (!is_segment_register(reg) && !is_descriptor_table(reg))
1279 		return (EINVAL);
1280 
1281 	return (vmmops_setdesc(vcpu->cookie, reg, desc));
1282 }
1283 
1284 static void
1285 restore_guest_fpustate(struct vcpu *vcpu)
1286 {
1287 
1288 	/* flush host state to the pcb */
1289 	fpuexit(curthread);
1290 
1291 	/* restore guest FPU state */
1292 	fpu_stop_emulating();
1293 	fpurestore(vcpu->guestfpu);
1294 
1295 	/* restore guest XCR0 if XSAVE is enabled in the host */
1296 	if (rcr4() & CR4_XSAVE)
1297 		load_xcr(0, vcpu->guest_xcr0);
1298 
1299 	/*
1300 	 * The FPU is now "dirty" with the guest's state so turn on emulation
1301 	 * to trap any access to the FPU by the host.
1302 	 */
1303 	fpu_start_emulating();
1304 }
1305 
1306 static void
1307 save_guest_fpustate(struct vcpu *vcpu)
1308 {
1309 
1310 	if ((rcr0() & CR0_TS) == 0)
1311 		panic("fpu emulation not enabled in host!");
1312 
1313 	/* save guest XCR0 and restore host XCR0 */
1314 	if (rcr4() & CR4_XSAVE) {
1315 		vcpu->guest_xcr0 = rxcr(0);
1316 		load_xcr(0, vmm_get_host_xcr0());
1317 	}
1318 
1319 	/* save guest FPU state */
1320 	fpu_stop_emulating();
1321 	fpusave(vcpu->guestfpu);
1322 	fpu_start_emulating();
1323 }
1324 
1325 static VMM_STAT(VCPU_IDLE_TICKS, "number of ticks vcpu was idle");
1326 
1327 static int
1328 vcpu_set_state_locked(struct vcpu *vcpu, enum vcpu_state newstate,
1329     bool from_idle)
1330 {
1331 	int error;
1332 
1333 	vcpu_assert_locked(vcpu);
1334 
1335 	/*
1336 	 * State transitions from the vmmdev_ioctl() must always begin from
1337 	 * the VCPU_IDLE state. This guarantees that there is only a single
1338 	 * ioctl() operating on a vcpu at any point.
1339 	 */
1340 	if (from_idle) {
1341 		while (vcpu->state != VCPU_IDLE) {
1342 			vcpu->reqidle = 1;
1343 			vcpu_notify_event_locked(vcpu, false);
1344 			VMM_CTR1(vcpu, "vcpu state change from %s to "
1345 			    "idle requested", vcpu_state2str(vcpu->state));
1346 			msleep_spin(&vcpu->state, &vcpu->mtx, "vmstat", hz);
1347 		}
1348 	} else {
1349 		KASSERT(vcpu->state != VCPU_IDLE, ("invalid transition from "
1350 		    "vcpu idle state"));
1351 	}
1352 
1353 	if (vcpu->state == VCPU_RUNNING) {
1354 		KASSERT(vcpu->hostcpu == curcpu, ("curcpu %d and hostcpu %d "
1355 		    "mismatch for running vcpu", curcpu, vcpu->hostcpu));
1356 	} else {
1357 		KASSERT(vcpu->hostcpu == NOCPU, ("Invalid hostcpu %d for a "
1358 		    "vcpu that is not running", vcpu->hostcpu));
1359 	}
1360 
1361 	/*
1362 	 * The following state transitions are allowed:
1363 	 * IDLE -> FROZEN -> IDLE
1364 	 * FROZEN -> RUNNING -> FROZEN
1365 	 * FROZEN -> SLEEPING -> FROZEN
1366 	 */
1367 	switch (vcpu->state) {
1368 	case VCPU_IDLE:
1369 	case VCPU_RUNNING:
1370 	case VCPU_SLEEPING:
1371 		error = (newstate != VCPU_FROZEN);
1372 		break;
1373 	case VCPU_FROZEN:
1374 		error = (newstate == VCPU_FROZEN);
1375 		break;
1376 	default:
1377 		error = 1;
1378 		break;
1379 	}
1380 
1381 	if (error)
1382 		return (EBUSY);
1383 
1384 	VMM_CTR2(vcpu, "vcpu state changed from %s to %s",
1385 	    vcpu_state2str(vcpu->state), vcpu_state2str(newstate));
1386 
1387 	vcpu->state = newstate;
1388 	if (newstate == VCPU_RUNNING)
1389 		vcpu->hostcpu = curcpu;
1390 	else
1391 		vcpu->hostcpu = NOCPU;
1392 
1393 	if (newstate == VCPU_IDLE)
1394 		wakeup(&vcpu->state);
1395 
1396 	return (0);
1397 }
1398 
1399 static void
1400 vcpu_require_state(struct vcpu *vcpu, enum vcpu_state newstate)
1401 {
1402 	int error;
1403 
1404 	if ((error = vcpu_set_state(vcpu, newstate, false)) != 0)
1405 		panic("Error %d setting state to %d\n", error, newstate);
1406 }
1407 
1408 static void
1409 vcpu_require_state_locked(struct vcpu *vcpu, enum vcpu_state newstate)
1410 {
1411 	int error;
1412 
1413 	if ((error = vcpu_set_state_locked(vcpu, newstate, false)) != 0)
1414 		panic("Error %d setting state to %d", error, newstate);
1415 }
1416 
1417 static int
1418 vm_handle_rendezvous(struct vcpu *vcpu)
1419 {
1420 	struct vm *vm = vcpu->vm;
1421 	struct thread *td;
1422 	int error, vcpuid;
1423 
1424 	error = 0;
1425 	vcpuid = vcpu->vcpuid;
1426 	td = curthread;
1427 	mtx_lock(&vm->rendezvous_mtx);
1428 	while (vm->rendezvous_func != NULL) {
1429 		/* 'rendezvous_req_cpus' must be a subset of 'active_cpus' */
1430 		CPU_AND(&vm->rendezvous_req_cpus, &vm->rendezvous_req_cpus, &vm->active_cpus);
1431 
1432 		if (CPU_ISSET(vcpuid, &vm->rendezvous_req_cpus) &&
1433 		    !CPU_ISSET(vcpuid, &vm->rendezvous_done_cpus)) {
1434 			VMM_CTR0(vcpu, "Calling rendezvous func");
1435 			(*vm->rendezvous_func)(vcpu, vm->rendezvous_arg);
1436 			CPU_SET(vcpuid, &vm->rendezvous_done_cpus);
1437 		}
1438 		if (CPU_CMP(&vm->rendezvous_req_cpus,
1439 		    &vm->rendezvous_done_cpus) == 0) {
1440 			VMM_CTR0(vcpu, "Rendezvous completed");
1441 			CPU_ZERO(&vm->rendezvous_req_cpus);
1442 			vm->rendezvous_func = NULL;
1443 			wakeup(&vm->rendezvous_func);
1444 			break;
1445 		}
1446 		VMM_CTR0(vcpu, "Wait for rendezvous completion");
1447 		mtx_sleep(&vm->rendezvous_func, &vm->rendezvous_mtx, 0,
1448 		    "vmrndv", hz);
1449 		if (td_ast_pending(td, TDA_SUSPEND)) {
1450 			mtx_unlock(&vm->rendezvous_mtx);
1451 			error = thread_check_susp(td, true);
1452 			if (error != 0)
1453 				return (error);
1454 			mtx_lock(&vm->rendezvous_mtx);
1455 		}
1456 	}
1457 	mtx_unlock(&vm->rendezvous_mtx);
1458 	return (0);
1459 }
1460 
1461 /*
1462  * Emulate a guest 'hlt' by sleeping until the vcpu is ready to run.
1463  */
1464 static int
1465 vm_handle_hlt(struct vcpu *vcpu, bool intr_disabled, bool *retu)
1466 {
1467 	struct vm *vm = vcpu->vm;
1468 	const char *wmesg;
1469 	struct thread *td;
1470 	int error, t, vcpuid, vcpu_halted, vm_halted;
1471 
1472 	vcpuid = vcpu->vcpuid;
1473 	vcpu_halted = 0;
1474 	vm_halted = 0;
1475 	error = 0;
1476 	td = curthread;
1477 
1478 	KASSERT(!CPU_ISSET(vcpuid, &vm->halted_cpus), ("vcpu already halted"));
1479 
1480 	vcpu_lock(vcpu);
1481 	while (1) {
1482 		/*
1483 		 * Do a final check for pending NMI or interrupts before
1484 		 * really putting this thread to sleep. Also check for
1485 		 * software events that would cause this vcpu to wakeup.
1486 		 *
1487 		 * These interrupts/events could have happened after the
1488 		 * vcpu returned from vmmops_run() and before it acquired the
1489 		 * vcpu lock above.
1490 		 */
1491 		if (vm->rendezvous_func != NULL || vm->suspend || vcpu->reqidle)
1492 			break;
1493 		if (vm_nmi_pending(vcpu))
1494 			break;
1495 		if (!intr_disabled) {
1496 			if (vm_extint_pending(vcpu) ||
1497 			    vlapic_pending_intr(vcpu->vlapic, NULL)) {
1498 				break;
1499 			}
1500 		}
1501 
1502 		/* Don't go to sleep if the vcpu thread needs to yield */
1503 		if (vcpu_should_yield(vcpu))
1504 			break;
1505 
1506 		if (vcpu_debugged(vcpu))
1507 			break;
1508 
1509 		/*
1510 		 * Some Linux guests implement "halt" by having all vcpus
1511 		 * execute HLT with interrupts disabled. 'halted_cpus' keeps
1512 		 * track of the vcpus that have entered this state. When all
1513 		 * vcpus enter the halted state the virtual machine is halted.
1514 		 */
1515 		if (intr_disabled) {
1516 			wmesg = "vmhalt";
1517 			VMM_CTR0(vcpu, "Halted");
1518 			if (!vcpu_halted && halt_detection_enabled) {
1519 				vcpu_halted = 1;
1520 				CPU_SET_ATOMIC(vcpuid, &vm->halted_cpus);
1521 			}
1522 			if (CPU_CMP(&vm->halted_cpus, &vm->active_cpus) == 0) {
1523 				vm_halted = 1;
1524 				break;
1525 			}
1526 		} else {
1527 			wmesg = "vmidle";
1528 		}
1529 
1530 		t = ticks;
1531 		vcpu_require_state_locked(vcpu, VCPU_SLEEPING);
1532 		/*
1533 		 * XXX msleep_spin() cannot be interrupted by signals so
1534 		 * wake up periodically to check pending signals.
1535 		 */
1536 		msleep_spin(vcpu, &vcpu->mtx, wmesg, hz);
1537 		vcpu_require_state_locked(vcpu, VCPU_FROZEN);
1538 		vmm_stat_incr(vcpu, VCPU_IDLE_TICKS, ticks - t);
1539 		if (td_ast_pending(td, TDA_SUSPEND)) {
1540 			vcpu_unlock(vcpu);
1541 			error = thread_check_susp(td, false);
1542 			if (error != 0) {
1543 				if (vcpu_halted) {
1544 					CPU_CLR_ATOMIC(vcpuid,
1545 					    &vm->halted_cpus);
1546 				}
1547 				return (error);
1548 			}
1549 			vcpu_lock(vcpu);
1550 		}
1551 	}
1552 
1553 	if (vcpu_halted)
1554 		CPU_CLR_ATOMIC(vcpuid, &vm->halted_cpus);
1555 
1556 	vcpu_unlock(vcpu);
1557 
1558 	if (vm_halted)
1559 		vm_suspend(vm, VM_SUSPEND_HALT);
1560 
1561 	return (0);
1562 }
1563 
1564 static int
1565 vm_handle_paging(struct vcpu *vcpu, bool *retu)
1566 {
1567 	struct vm *vm = vcpu->vm;
1568 	int rv, ftype;
1569 	struct vm_map *map;
1570 	struct vm_exit *vme;
1571 
1572 	vme = &vcpu->exitinfo;
1573 
1574 	KASSERT(vme->inst_length == 0, ("%s: invalid inst_length %d",
1575 	    __func__, vme->inst_length));
1576 
1577 	ftype = vme->u.paging.fault_type;
1578 	KASSERT(ftype == VM_PROT_READ ||
1579 	    ftype == VM_PROT_WRITE || ftype == VM_PROT_EXECUTE,
1580 	    ("vm_handle_paging: invalid fault_type %d", ftype));
1581 
1582 	if (ftype == VM_PROT_READ || ftype == VM_PROT_WRITE) {
1583 		rv = pmap_emulate_accessed_dirty(vmspace_pmap(vm->vmspace),
1584 		    vme->u.paging.gpa, ftype);
1585 		if (rv == 0) {
1586 			VMM_CTR2(vcpu, "%s bit emulation for gpa %#lx",
1587 			    ftype == VM_PROT_READ ? "accessed" : "dirty",
1588 			    vme->u.paging.gpa);
1589 			goto done;
1590 		}
1591 	}
1592 
1593 	map = &vm->vmspace->vm_map;
1594 	rv = vm_fault(map, vme->u.paging.gpa, ftype, VM_FAULT_NORMAL, NULL);
1595 
1596 	VMM_CTR3(vcpu, "vm_handle_paging rv = %d, gpa = %#lx, "
1597 	    "ftype = %d", rv, vme->u.paging.gpa, ftype);
1598 
1599 	if (rv != KERN_SUCCESS)
1600 		return (EFAULT);
1601 done:
1602 	return (0);
1603 }
1604 
1605 static int
1606 vm_handle_inst_emul(struct vcpu *vcpu, bool *retu)
1607 {
1608 	struct vie *vie;
1609 	struct vm_exit *vme;
1610 	uint64_t gla, gpa, cs_base;
1611 	struct vm_guest_paging *paging;
1612 	mem_region_read_t mread;
1613 	mem_region_write_t mwrite;
1614 	enum vm_cpu_mode cpu_mode;
1615 	int cs_d, error, fault;
1616 
1617 	vme = &vcpu->exitinfo;
1618 
1619 	KASSERT(vme->inst_length == 0, ("%s: invalid inst_length %d",
1620 	    __func__, vme->inst_length));
1621 
1622 	gla = vme->u.inst_emul.gla;
1623 	gpa = vme->u.inst_emul.gpa;
1624 	cs_base = vme->u.inst_emul.cs_base;
1625 	cs_d = vme->u.inst_emul.cs_d;
1626 	vie = &vme->u.inst_emul.vie;
1627 	paging = &vme->u.inst_emul.paging;
1628 	cpu_mode = paging->cpu_mode;
1629 
1630 	VMM_CTR1(vcpu, "inst_emul fault accessing gpa %#lx", gpa);
1631 
1632 	/* Fetch, decode and emulate the faulting instruction */
1633 	if (vie->num_valid == 0) {
1634 		error = vmm_fetch_instruction(vcpu, paging, vme->rip + cs_base,
1635 		    VIE_INST_SIZE, vie, &fault);
1636 	} else {
1637 		/*
1638 		 * The instruction bytes have already been copied into 'vie'
1639 		 */
1640 		error = fault = 0;
1641 	}
1642 	if (error || fault)
1643 		return (error);
1644 
1645 	if (vmm_decode_instruction(vcpu, gla, cpu_mode, cs_d, vie) != 0) {
1646 		VMM_CTR1(vcpu, "Error decoding instruction at %#lx",
1647 		    vme->rip + cs_base);
1648 		*retu = true;	    /* dump instruction bytes in userspace */
1649 		return (0);
1650 	}
1651 
1652 	/*
1653 	 * Update 'nextrip' based on the length of the emulated instruction.
1654 	 */
1655 	vme->inst_length = vie->num_processed;
1656 	vcpu->nextrip += vie->num_processed;
1657 	VMM_CTR1(vcpu, "nextrip updated to %#lx after instruction decoding",
1658 	    vcpu->nextrip);
1659 
1660 	/* return to userland unless this is an in-kernel emulated device */
1661 	if (gpa >= DEFAULT_APIC_BASE && gpa < DEFAULT_APIC_BASE + PAGE_SIZE) {
1662 		mread = lapic_mmio_read;
1663 		mwrite = lapic_mmio_write;
1664 	} else if (gpa >= VIOAPIC_BASE && gpa < VIOAPIC_BASE + VIOAPIC_SIZE) {
1665 		mread = vioapic_mmio_read;
1666 		mwrite = vioapic_mmio_write;
1667 	} else if (gpa >= VHPET_BASE && gpa < VHPET_BASE + VHPET_SIZE) {
1668 		mread = vhpet_mmio_read;
1669 		mwrite = vhpet_mmio_write;
1670 	} else {
1671 		*retu = true;
1672 		return (0);
1673 	}
1674 
1675 	error = vmm_emulate_instruction(vcpu, gpa, vie, paging, mread, mwrite,
1676 	    retu);
1677 
1678 	return (error);
1679 }
1680 
1681 static int
1682 vm_handle_suspend(struct vcpu *vcpu, bool *retu)
1683 {
1684 	struct vm *vm = vcpu->vm;
1685 	int error, i;
1686 	struct thread *td;
1687 
1688 	error = 0;
1689 	td = curthread;
1690 
1691 	CPU_SET_ATOMIC(vcpu->vcpuid, &vm->suspended_cpus);
1692 
1693 	/*
1694 	 * Wait until all 'active_cpus' have suspended themselves.
1695 	 *
1696 	 * Since a VM may be suspended at any time including when one or
1697 	 * more vcpus are doing a rendezvous we need to call the rendezvous
1698 	 * handler while we are waiting to prevent a deadlock.
1699 	 */
1700 	vcpu_lock(vcpu);
1701 	while (error == 0) {
1702 		if (CPU_CMP(&vm->suspended_cpus, &vm->active_cpus) == 0) {
1703 			VMM_CTR0(vcpu, "All vcpus suspended");
1704 			break;
1705 		}
1706 
1707 		if (vm->rendezvous_func == NULL) {
1708 			VMM_CTR0(vcpu, "Sleeping during suspend");
1709 			vcpu_require_state_locked(vcpu, VCPU_SLEEPING);
1710 			msleep_spin(vcpu, &vcpu->mtx, "vmsusp", hz);
1711 			vcpu_require_state_locked(vcpu, VCPU_FROZEN);
1712 			if (td_ast_pending(td, TDA_SUSPEND)) {
1713 				vcpu_unlock(vcpu);
1714 				error = thread_check_susp(td, false);
1715 				vcpu_lock(vcpu);
1716 			}
1717 		} else {
1718 			VMM_CTR0(vcpu, "Rendezvous during suspend");
1719 			vcpu_unlock(vcpu);
1720 			error = vm_handle_rendezvous(vcpu);
1721 			vcpu_lock(vcpu);
1722 		}
1723 	}
1724 	vcpu_unlock(vcpu);
1725 
1726 	/*
1727 	 * Wakeup the other sleeping vcpus and return to userspace.
1728 	 */
1729 	for (i = 0; i < vm->maxcpus; i++) {
1730 		if (CPU_ISSET(i, &vm->suspended_cpus)) {
1731 			vcpu_notify_event(vm_vcpu(vm, i), false);
1732 		}
1733 	}
1734 
1735 	*retu = true;
1736 	return (error);
1737 }
1738 
1739 static int
1740 vm_handle_reqidle(struct vcpu *vcpu, bool *retu)
1741 {
1742 	vcpu_lock(vcpu);
1743 	KASSERT(vcpu->reqidle, ("invalid vcpu reqidle %d", vcpu->reqidle));
1744 	vcpu->reqidle = 0;
1745 	vcpu_unlock(vcpu);
1746 	*retu = true;
1747 	return (0);
1748 }
1749 
1750 int
1751 vm_suspend(struct vm *vm, enum vm_suspend_how how)
1752 {
1753 	int i;
1754 
1755 	if (how <= VM_SUSPEND_NONE || how >= VM_SUSPEND_LAST)
1756 		return (EINVAL);
1757 
1758 	if (atomic_cmpset_int(&vm->suspend, 0, how) == 0) {
1759 		VM_CTR2(vm, "virtual machine already suspended %d/%d",
1760 		    vm->suspend, how);
1761 		return (EALREADY);
1762 	}
1763 
1764 	VM_CTR1(vm, "virtual machine successfully suspended %d", how);
1765 
1766 	/*
1767 	 * Notify all active vcpus that they are now suspended.
1768 	 */
1769 	for (i = 0; i < vm->maxcpus; i++) {
1770 		if (CPU_ISSET(i, &vm->active_cpus))
1771 			vcpu_notify_event(vm_vcpu(vm, i), false);
1772 	}
1773 
1774 	return (0);
1775 }
1776 
1777 void
1778 vm_exit_suspended(struct vcpu *vcpu, uint64_t rip)
1779 {
1780 	struct vm *vm = vcpu->vm;
1781 	struct vm_exit *vmexit;
1782 
1783 	KASSERT(vm->suspend > VM_SUSPEND_NONE && vm->suspend < VM_SUSPEND_LAST,
1784 	    ("vm_exit_suspended: invalid suspend type %d", vm->suspend));
1785 
1786 	vmexit = vm_exitinfo(vcpu);
1787 	vmexit->rip = rip;
1788 	vmexit->inst_length = 0;
1789 	vmexit->exitcode = VM_EXITCODE_SUSPENDED;
1790 	vmexit->u.suspended.how = vm->suspend;
1791 }
1792 
1793 void
1794 vm_exit_debug(struct vcpu *vcpu, uint64_t rip)
1795 {
1796 	struct vm_exit *vmexit;
1797 
1798 	vmexit = vm_exitinfo(vcpu);
1799 	vmexit->rip = rip;
1800 	vmexit->inst_length = 0;
1801 	vmexit->exitcode = VM_EXITCODE_DEBUG;
1802 }
1803 
1804 void
1805 vm_exit_rendezvous(struct vcpu *vcpu, uint64_t rip)
1806 {
1807 	struct vm_exit *vmexit;
1808 
1809 	vmexit = vm_exitinfo(vcpu);
1810 	vmexit->rip = rip;
1811 	vmexit->inst_length = 0;
1812 	vmexit->exitcode = VM_EXITCODE_RENDEZVOUS;
1813 	vmm_stat_incr(vcpu, VMEXIT_RENDEZVOUS, 1);
1814 }
1815 
1816 void
1817 vm_exit_reqidle(struct vcpu *vcpu, uint64_t rip)
1818 {
1819 	struct vm_exit *vmexit;
1820 
1821 	vmexit = vm_exitinfo(vcpu);
1822 	vmexit->rip = rip;
1823 	vmexit->inst_length = 0;
1824 	vmexit->exitcode = VM_EXITCODE_REQIDLE;
1825 	vmm_stat_incr(vcpu, VMEXIT_REQIDLE, 1);
1826 }
1827 
1828 void
1829 vm_exit_astpending(struct vcpu *vcpu, uint64_t rip)
1830 {
1831 	struct vm_exit *vmexit;
1832 
1833 	vmexit = vm_exitinfo(vcpu);
1834 	vmexit->rip = rip;
1835 	vmexit->inst_length = 0;
1836 	vmexit->exitcode = VM_EXITCODE_BOGUS;
1837 	vmm_stat_incr(vcpu, VMEXIT_ASTPENDING, 1);
1838 }
1839 
1840 int
1841 vm_run(struct vcpu *vcpu, struct vm_exit *vme_user)
1842 {
1843 	struct vm *vm = vcpu->vm;
1844 	struct vm_eventinfo evinfo;
1845 	int error, vcpuid;
1846 	struct pcb *pcb;
1847 	uint64_t tscval;
1848 	struct vm_exit *vme;
1849 	bool retu, intr_disabled;
1850 	pmap_t pmap;
1851 
1852 	vcpuid = vcpu->vcpuid;
1853 
1854 	if (!CPU_ISSET(vcpuid, &vm->active_cpus))
1855 		return (EINVAL);
1856 
1857 	if (CPU_ISSET(vcpuid, &vm->suspended_cpus))
1858 		return (EINVAL);
1859 
1860 	pmap = vmspace_pmap(vm->vmspace);
1861 	vme = &vcpu->exitinfo;
1862 	evinfo.rptr = &vm->rendezvous_req_cpus;
1863 	evinfo.sptr = &vm->suspend;
1864 	evinfo.iptr = &vcpu->reqidle;
1865 restart:
1866 	critical_enter();
1867 
1868 	KASSERT(!CPU_ISSET(curcpu, &pmap->pm_active),
1869 	    ("vm_run: absurd pm_active"));
1870 
1871 	tscval = rdtsc();
1872 
1873 	pcb = PCPU_GET(curpcb);
1874 	set_pcb_flags(pcb, PCB_FULL_IRET);
1875 
1876 	restore_guest_fpustate(vcpu);
1877 
1878 	vcpu_require_state(vcpu, VCPU_RUNNING);
1879 	error = vmmops_run(vcpu->cookie, vcpu->nextrip, pmap, &evinfo);
1880 	vcpu_require_state(vcpu, VCPU_FROZEN);
1881 
1882 	save_guest_fpustate(vcpu);
1883 
1884 	vmm_stat_incr(vcpu, VCPU_TOTAL_RUNTIME, rdtsc() - tscval);
1885 
1886 	critical_exit();
1887 
1888 	if (error == 0) {
1889 		retu = false;
1890 		vcpu->nextrip = vme->rip + vme->inst_length;
1891 		switch (vme->exitcode) {
1892 		case VM_EXITCODE_REQIDLE:
1893 			error = vm_handle_reqidle(vcpu, &retu);
1894 			break;
1895 		case VM_EXITCODE_SUSPENDED:
1896 			error = vm_handle_suspend(vcpu, &retu);
1897 			break;
1898 		case VM_EXITCODE_IOAPIC_EOI:
1899 			vioapic_process_eoi(vm, vme->u.ioapic_eoi.vector);
1900 			break;
1901 		case VM_EXITCODE_RENDEZVOUS:
1902 			error = vm_handle_rendezvous(vcpu);
1903 			break;
1904 		case VM_EXITCODE_HLT:
1905 			intr_disabled = ((vme->u.hlt.rflags & PSL_I) == 0);
1906 			error = vm_handle_hlt(vcpu, intr_disabled, &retu);
1907 			break;
1908 		case VM_EXITCODE_PAGING:
1909 			error = vm_handle_paging(vcpu, &retu);
1910 			break;
1911 		case VM_EXITCODE_INST_EMUL:
1912 			error = vm_handle_inst_emul(vcpu, &retu);
1913 			break;
1914 		case VM_EXITCODE_INOUT:
1915 		case VM_EXITCODE_INOUT_STR:
1916 			error = vm_handle_inout(vcpu, vme, &retu);
1917 			break;
1918 		case VM_EXITCODE_MONITOR:
1919 		case VM_EXITCODE_MWAIT:
1920 		case VM_EXITCODE_VMINSN:
1921 			vm_inject_ud(vcpu);
1922 			break;
1923 		default:
1924 			retu = true;	/* handled in userland */
1925 			break;
1926 		}
1927 	}
1928 
1929 	/*
1930 	 * VM_EXITCODE_INST_EMUL could access the apic which could transform the
1931 	 * exit code into VM_EXITCODE_IPI.
1932 	 */
1933 	if (error == 0 && vme->exitcode == VM_EXITCODE_IPI) {
1934 		retu = false;
1935 		error = vm_handle_ipi(vcpu, vme, &retu);
1936 	}
1937 
1938 	if (error == 0 && retu == false)
1939 		goto restart;
1940 
1941 	vmm_stat_incr(vcpu, VMEXIT_USERSPACE, 1);
1942 	VMM_CTR2(vcpu, "retu %d/%d", error, vme->exitcode);
1943 
1944 	/* copy the exit information */
1945 	*vme_user = *vme;
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 	}
2865 
2866 done:
2867 	return (ret);
2868 }
2869 
2870 static int
2871 vm_snapshot_vm(struct vm *vm, struct vm_snapshot_meta *meta)
2872 {
2873 	int ret;
2874 
2875 	ret = vm_snapshot_vcpus(vm, meta);
2876 	if (ret != 0)
2877 		goto done;
2878 
2879 	SNAPSHOT_VAR_OR_LEAVE(vm->startup_cpus, meta, ret, done);
2880 done:
2881 	return (ret);
2882 }
2883 
2884 static int
2885 vm_snapshot_vcpu(struct vm *vm, struct vm_snapshot_meta *meta)
2886 {
2887 	int error;
2888 	struct vcpu *vcpu;
2889 	uint16_t i, maxcpus;
2890 
2891 	error = 0;
2892 
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 		error = vmmops_vcpu_snapshot(vcpu->cookie, meta);
2900 		if (error != 0) {
2901 			printf("%s: failed to snapshot vmcs/vmcb data for "
2902 			       "vCPU: %d; error: %d\n", __func__, i, error);
2903 			goto done;
2904 		}
2905 	}
2906 
2907 done:
2908 	return (error);
2909 }
2910 
2911 /*
2912  * Save kernel-side structures to user-space for snapshotting.
2913  */
2914 int
2915 vm_snapshot_req(struct vm *vm, struct vm_snapshot_meta *meta)
2916 {
2917 	int ret = 0;
2918 
2919 	switch (meta->dev_req) {
2920 	case STRUCT_VMX:
2921 		ret = vmmops_snapshot(vm->cookie, meta);
2922 		break;
2923 	case STRUCT_VMCX:
2924 		ret = vm_snapshot_vcpu(vm, meta);
2925 		break;
2926 	case STRUCT_VM:
2927 		ret = vm_snapshot_vm(vm, meta);
2928 		break;
2929 	case STRUCT_VIOAPIC:
2930 		ret = vioapic_snapshot(vm_ioapic(vm), meta);
2931 		break;
2932 	case STRUCT_VLAPIC:
2933 		ret = vlapic_snapshot(vm, meta);
2934 		break;
2935 	case STRUCT_VHPET:
2936 		ret = vhpet_snapshot(vm_hpet(vm), meta);
2937 		break;
2938 	case STRUCT_VATPIC:
2939 		ret = vatpic_snapshot(vm_atpic(vm), meta);
2940 		break;
2941 	case STRUCT_VATPIT:
2942 		ret = vatpit_snapshot(vm_atpit(vm), meta);
2943 		break;
2944 	case STRUCT_VPMTMR:
2945 		ret = vpmtmr_snapshot(vm_pmtmr(vm), meta);
2946 		break;
2947 	case STRUCT_VRTC:
2948 		ret = vrtc_snapshot(vm_rtc(vm), meta);
2949 		break;
2950 	default:
2951 		printf("%s: failed to find the requested type %#x\n",
2952 		       __func__, meta->dev_req);
2953 		ret = (EINVAL);
2954 	}
2955 	return (ret);
2956 }
2957 
2958 void
2959 vm_set_tsc_offset(struct vcpu *vcpu, uint64_t offset)
2960 {
2961 	vcpu->tsc_offset = offset;
2962 }
2963 
2964 int
2965 vm_restore_time(struct vm *vm)
2966 {
2967 	int error;
2968 	uint64_t now;
2969 	struct vcpu *vcpu;
2970 	uint16_t i, maxcpus;
2971 
2972 	now = rdtsc();
2973 
2974 	error = vhpet_restore_time(vm_hpet(vm));
2975 	if (error)
2976 		return (error);
2977 
2978 	maxcpus = vm_get_maxcpus(vm);
2979 	for (i = 0; i < maxcpus; i++) {
2980 		vcpu = vm->vcpu[i];
2981 		if (vcpu == NULL)
2982 			continue;
2983 
2984 		error = vmmops_restore_tsc(vcpu->cookie,
2985 		    vcpu->tsc_offset - now);
2986 		if (error)
2987 			return (error);
2988 	}
2989 
2990 	return (0);
2991 }
2992 #endif
2993