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