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