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