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