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