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