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