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