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