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