2 * Copyright (c) 2011 NetApp, Inc.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
14 * THIS SOFTWARE IS PROVIDED BY NETAPP, INC ``AS IS'' AND
15 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17 * ARE DISCLAIMED. IN NO EVENT SHALL NETAPP, INC OR CONTRIBUTORS BE LIABLE
18 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
32 #include <sys/types.h>
36 #include <machine/atomic.h>
37 #include <machine/segments.h>
48 #include <pthread_np.h>
52 #include <machine/vmm.h>
67 #include "smbiostbl.h"
69 #include "spinup_ap.h"
72 #define GUEST_NIO_PORT 0x488 /* guest upcalls via i/o port */
74 #define MB (1024UL * 1024)
75 #define GB (1024UL * MB)
77 typedef int (*vmexit_handler_t)(struct vmctx *, struct vm_exit *, int *vcpu);
78 extern int vmexit_task_switch(struct vmctx *, struct vm_exit *, int *vcpu);
85 static int guest_vmexit_on_hlt, guest_vmexit_on_pause;
86 static int virtio_msix = 1;
87 static int x2apic_mode = 0; /* default is xAPIC */
90 static int strictmsr = 1;
94 static char *progname;
95 static const int BSP = 0;
97 static cpuset_t cpumask;
99 static void vm_loop(struct vmctx *ctx, int vcpu, uint64_t rip);
101 static struct vm_exit vmexit[VM_MAXCPU];
104 uint64_t vmexit_bogus;
105 uint64_t vmexit_reqidle;
107 uint64_t vmexit_pause;
108 uint64_t vmexit_mtrap;
109 uint64_t vmexit_inst_emul;
110 uint64_t cpu_switch_rotate;
111 uint64_t cpu_switch_direct;
116 struct vmctx *mt_ctx;
118 } mt_vmm_info[VM_MAXCPU];
120 static cpuset_t *vcpumap[VM_MAXCPU] = { NULL };
127 "Usage: %s [-abehuwxACHPSWY] [-c vcpus] [-g <gdb port>] [-l <lpc>]\n"
128 " %*s [-m mem] [-p vcpu:hostcpu] [-s <pci>] [-U uuid] <vm>\n"
129 " -a: local apic is in xAPIC mode (deprecated)\n"
130 " -A: create ACPI tables\n"
131 " -c: # cpus (default 1)\n"
132 " -C: include guest memory in core file\n"
133 " -e: exit on unhandled I/O access\n"
136 " -H: vmexit from the guest on hlt\n"
137 " -l: LPC device configuration\n"
138 " -m: memory size in MB\n"
139 " -p: pin 'vcpu' to 'hostcpu'\n"
140 " -P: vmexit from the guest on pause\n"
141 " -s: <slot,driver,configinfo> PCI slot config\n"
142 " -S: guest memory cannot be swapped\n"
143 " -u: RTC keeps UTC time\n"
145 " -w: ignore unimplemented MSRs\n"
146 " -W: force virtio to use single-vector MSI\n"
147 " -x: local apic is in x2APIC mode\n"
148 " -Y: disable MPtable generation\n",
149 progname, (int)strlen(progname), "");
155 pincpu_parse(const char *opt)
159 if (sscanf(opt, "%d:%d", &vcpu, &pcpu) != 2) {
160 fprintf(stderr, "invalid format: %s\n", opt);
164 if (vcpu < 0 || vcpu >= VM_MAXCPU) {
165 fprintf(stderr, "vcpu '%d' outside valid range from 0 to %d\n",
166 vcpu, VM_MAXCPU - 1);
170 if (pcpu < 0 || pcpu >= CPU_SETSIZE) {
171 fprintf(stderr, "hostcpu '%d' outside valid range from "
172 "0 to %d\n", pcpu, CPU_SETSIZE - 1);
176 if (vcpumap[vcpu] == NULL) {
177 if ((vcpumap[vcpu] = malloc(sizeof(cpuset_t))) == NULL) {
181 CPU_ZERO(vcpumap[vcpu]);
183 CPU_SET(pcpu, vcpumap[vcpu]);
188 vm_inject_fault(void *arg, int vcpu, int vector, int errcode_valid,
192 int error, restart_instruction;
195 restart_instruction = 1;
197 error = vm_inject_exception(ctx, vcpu, vector, errcode_valid, errcode,
198 restart_instruction);
203 paddr_guest2host(struct vmctx *ctx, uintptr_t gaddr, size_t len)
206 return (vm_map_gpa(ctx, gaddr, len));
210 fbsdrun_vmexit_on_pause(void)
213 return (guest_vmexit_on_pause);
217 fbsdrun_vmexit_on_hlt(void)
220 return (guest_vmexit_on_hlt);
224 fbsdrun_virtio_msix(void)
227 return (virtio_msix);
231 fbsdrun_start_thread(void *param)
233 char tname[MAXCOMLEN + 1];
234 struct mt_vmm_info *mtp;
240 snprintf(tname, sizeof(tname), "vcpu %d", vcpu);
241 pthread_set_name_np(mtp->mt_thr, tname);
243 vm_loop(mtp->mt_ctx, vcpu, vmexit[vcpu].rip);
251 fbsdrun_addcpu(struct vmctx *ctx, int fromcpu, int newcpu, uint64_t rip)
255 assert(fromcpu == BSP);
258 * The 'newcpu' must be activated in the context of 'fromcpu'. If
259 * vm_activate_cpu() is delayed until newcpu's pthread starts running
260 * then vmm.ko is out-of-sync with bhyve and this can create a race
263 error = vm_activate_cpu(ctx, newcpu);
265 err(EX_OSERR, "could not activate CPU %d", newcpu);
267 CPU_SET_ATOMIC(newcpu, &cpumask);
270 * Set up the vmexit struct to allow execution to start
273 vmexit[newcpu].rip = rip;
274 vmexit[newcpu].inst_length = 0;
276 mt_vmm_info[newcpu].mt_ctx = ctx;
277 mt_vmm_info[newcpu].mt_vcpu = newcpu;
279 error = pthread_create(&mt_vmm_info[newcpu].mt_thr, NULL,
280 fbsdrun_start_thread, &mt_vmm_info[newcpu]);
285 fbsdrun_deletecpu(struct vmctx *ctx, int vcpu)
288 if (!CPU_ISSET(vcpu, &cpumask)) {
289 fprintf(stderr, "Attempting to delete unknown cpu %d\n", vcpu);
293 CPU_CLR_ATOMIC(vcpu, &cpumask);
294 return (CPU_EMPTY(&cpumask));
298 vmexit_handle_notify(struct vmctx *ctx, struct vm_exit *vme, int *pvcpu,
303 * put guest-driven debug here
306 return (VMEXIT_CONTINUE);
310 vmexit_inout(struct vmctx *ctx, struct vm_exit *vme, int *pvcpu)
313 int bytes, port, in, out;
318 port = vme->u.inout.port;
319 bytes = vme->u.inout.bytes;
320 in = vme->u.inout.in;
323 /* Extra-special case of host notifications */
324 if (out && port == GUEST_NIO_PORT) {
325 error = vmexit_handle_notify(ctx, vme, pvcpu, vme->u.inout.eax);
329 error = emulate_inout(ctx, vcpu, vme, strictio);
331 fprintf(stderr, "Unhandled %s%c 0x%04x at 0x%lx\n",
333 bytes == 1 ? 'b' : (bytes == 2 ? 'w' : 'l'),
335 return (VMEXIT_ABORT);
337 return (VMEXIT_CONTINUE);
342 vmexit_rdmsr(struct vmctx *ctx, struct vm_exit *vme, int *pvcpu)
349 error = emulate_rdmsr(ctx, *pvcpu, vme->u.msr.code, &val);
351 fprintf(stderr, "rdmsr to register %#x on vcpu %d\n",
352 vme->u.msr.code, *pvcpu);
354 vm_inject_gp(ctx, *pvcpu);
355 return (VMEXIT_CONTINUE);
360 error = vm_set_register(ctx, *pvcpu, VM_REG_GUEST_RAX, eax);
364 error = vm_set_register(ctx, *pvcpu, VM_REG_GUEST_RDX, edx);
367 return (VMEXIT_CONTINUE);
371 vmexit_wrmsr(struct vmctx *ctx, struct vm_exit *vme, int *pvcpu)
375 error = emulate_wrmsr(ctx, *pvcpu, vme->u.msr.code, vme->u.msr.wval);
377 fprintf(stderr, "wrmsr to register %#x(%#lx) on vcpu %d\n",
378 vme->u.msr.code, vme->u.msr.wval, *pvcpu);
380 vm_inject_gp(ctx, *pvcpu);
381 return (VMEXIT_CONTINUE);
384 return (VMEXIT_CONTINUE);
388 vmexit_spinup_ap(struct vmctx *ctx, struct vm_exit *vme, int *pvcpu)
391 int retval = VMEXIT_CONTINUE;
393 newcpu = spinup_ap(ctx, *pvcpu,
394 vme->u.spinup_ap.vcpu, vme->u.spinup_ap.rip);
399 #define DEBUG_EPT_MISCONFIG
400 #ifdef DEBUG_EPT_MISCONFIG
401 #define EXIT_REASON_EPT_MISCONFIG 49
402 #define VMCS_GUEST_PHYSICAL_ADDRESS 0x00002400
403 #define VMCS_IDENT(x) ((x) | 0x80000000)
405 static uint64_t ept_misconfig_gpa, ept_misconfig_pte[4];
406 static int ept_misconfig_ptenum;
410 vmexit_vmx(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
413 fprintf(stderr, "vm exit[%d]\n", *pvcpu);
414 fprintf(stderr, "\treason\t\tVMX\n");
415 fprintf(stderr, "\trip\t\t0x%016lx\n", vmexit->rip);
416 fprintf(stderr, "\tinst_length\t%d\n", vmexit->inst_length);
417 fprintf(stderr, "\tstatus\t\t%d\n", vmexit->u.vmx.status);
418 fprintf(stderr, "\texit_reason\t%u\n", vmexit->u.vmx.exit_reason);
419 fprintf(stderr, "\tqualification\t0x%016lx\n",
420 vmexit->u.vmx.exit_qualification);
421 fprintf(stderr, "\tinst_type\t\t%d\n", vmexit->u.vmx.inst_type);
422 fprintf(stderr, "\tinst_error\t\t%d\n", vmexit->u.vmx.inst_error);
423 #ifdef DEBUG_EPT_MISCONFIG
424 if (vmexit->u.vmx.exit_reason == EXIT_REASON_EPT_MISCONFIG) {
425 vm_get_register(ctx, *pvcpu,
426 VMCS_IDENT(VMCS_GUEST_PHYSICAL_ADDRESS),
428 vm_get_gpa_pmap(ctx, ept_misconfig_gpa, ept_misconfig_pte,
429 &ept_misconfig_ptenum);
430 fprintf(stderr, "\tEPT misconfiguration:\n");
431 fprintf(stderr, "\t\tGPA: %#lx\n", ept_misconfig_gpa);
432 fprintf(stderr, "\t\tPTE(%d): %#lx %#lx %#lx %#lx\n",
433 ept_misconfig_ptenum, ept_misconfig_pte[0],
434 ept_misconfig_pte[1], ept_misconfig_pte[2],
435 ept_misconfig_pte[3]);
437 #endif /* DEBUG_EPT_MISCONFIG */
438 return (VMEXIT_ABORT);
442 vmexit_svm(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
445 fprintf(stderr, "vm exit[%d]\n", *pvcpu);
446 fprintf(stderr, "\treason\t\tSVM\n");
447 fprintf(stderr, "\trip\t\t0x%016lx\n", vmexit->rip);
448 fprintf(stderr, "\tinst_length\t%d\n", vmexit->inst_length);
449 fprintf(stderr, "\texitcode\t%#lx\n", vmexit->u.svm.exitcode);
450 fprintf(stderr, "\texitinfo1\t%#lx\n", vmexit->u.svm.exitinfo1);
451 fprintf(stderr, "\texitinfo2\t%#lx\n", vmexit->u.svm.exitinfo2);
452 return (VMEXIT_ABORT);
456 vmexit_bogus(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
459 assert(vmexit->inst_length == 0);
461 stats.vmexit_bogus++;
463 return (VMEXIT_CONTINUE);
467 vmexit_reqidle(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
470 assert(vmexit->inst_length == 0);
472 stats.vmexit_reqidle++;
474 return (VMEXIT_CONTINUE);
478 vmexit_hlt(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
484 * Just continue execution with the next instruction. We use
485 * the HLT VM exit as a way to be friendly with the host
488 return (VMEXIT_CONTINUE);
492 vmexit_pause(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
495 stats.vmexit_pause++;
497 return (VMEXIT_CONTINUE);
501 vmexit_mtrap(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
504 assert(vmexit->inst_length == 0);
506 stats.vmexit_mtrap++;
508 return (VMEXIT_CONTINUE);
512 vmexit_inst_emul(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
517 stats.vmexit_inst_emul++;
519 vie = &vmexit->u.inst_emul.vie;
520 err = emulate_mem(ctx, *pvcpu, vmexit->u.inst_emul.gpa,
521 vie, &vmexit->u.inst_emul.paging);
525 fprintf(stderr, "Unhandled memory access to 0x%lx\n",
526 vmexit->u.inst_emul.gpa);
529 fprintf(stderr, "Failed to emulate instruction [");
530 for (i = 0; i < vie->num_valid; i++) {
531 fprintf(stderr, "0x%02x%s", vie->inst[i],
532 i != (vie->num_valid - 1) ? " " : "");
534 fprintf(stderr, "] at 0x%lx\n", vmexit->rip);
535 return (VMEXIT_ABORT);
538 return (VMEXIT_CONTINUE);
541 static pthread_mutex_t resetcpu_mtx = PTHREAD_MUTEX_INITIALIZER;
542 static pthread_cond_t resetcpu_cond = PTHREAD_COND_INITIALIZER;
545 vmexit_suspend(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
547 enum vm_suspend_how how;
549 how = vmexit->u.suspended.how;
551 fbsdrun_deletecpu(ctx, *pvcpu);
554 pthread_mutex_lock(&resetcpu_mtx);
555 pthread_cond_signal(&resetcpu_cond);
556 pthread_mutex_unlock(&resetcpu_mtx);
560 pthread_mutex_lock(&resetcpu_mtx);
561 while (!CPU_EMPTY(&cpumask)) {
562 pthread_cond_wait(&resetcpu_cond, &resetcpu_mtx);
564 pthread_mutex_unlock(&resetcpu_mtx);
567 case VM_SUSPEND_RESET:
569 case VM_SUSPEND_POWEROFF:
571 case VM_SUSPEND_HALT:
573 case VM_SUSPEND_TRIPLEFAULT:
576 fprintf(stderr, "vmexit_suspend: invalid reason %d\n", how);
579 return (0); /* NOTREACHED */
582 static vmexit_handler_t handler[VM_EXITCODE_MAX] = {
583 [VM_EXITCODE_INOUT] = vmexit_inout,
584 [VM_EXITCODE_INOUT_STR] = vmexit_inout,
585 [VM_EXITCODE_VMX] = vmexit_vmx,
586 [VM_EXITCODE_SVM] = vmexit_svm,
587 [VM_EXITCODE_BOGUS] = vmexit_bogus,
588 [VM_EXITCODE_REQIDLE] = vmexit_reqidle,
589 [VM_EXITCODE_RDMSR] = vmexit_rdmsr,
590 [VM_EXITCODE_WRMSR] = vmexit_wrmsr,
591 [VM_EXITCODE_MTRAP] = vmexit_mtrap,
592 [VM_EXITCODE_INST_EMUL] = vmexit_inst_emul,
593 [VM_EXITCODE_SPINUP_AP] = vmexit_spinup_ap,
594 [VM_EXITCODE_SUSPENDED] = vmexit_suspend,
595 [VM_EXITCODE_TASK_SWITCH] = vmexit_task_switch,
599 vm_loop(struct vmctx *ctx, int vcpu, uint64_t startrip)
602 enum vm_exitcode exitcode;
603 cpuset_t active_cpus;
605 if (vcpumap[vcpu] != NULL) {
606 error = pthread_setaffinity_np(pthread_self(),
607 sizeof(cpuset_t), vcpumap[vcpu]);
611 error = vm_active_cpus(ctx, &active_cpus);
612 assert(CPU_ISSET(vcpu, &active_cpus));
614 error = vm_set_register(ctx, vcpu, VM_REG_GUEST_RIP, startrip);
618 error = vm_run(ctx, vcpu, &vmexit[vcpu]);
622 exitcode = vmexit[vcpu].exitcode;
623 if (exitcode >= VM_EXITCODE_MAX || handler[exitcode] == NULL) {
624 fprintf(stderr, "vm_loop: unexpected exitcode 0x%x\n",
629 rc = (*handler[exitcode])(ctx, &vmexit[vcpu], &vcpu);
632 case VMEXIT_CONTINUE:
640 fprintf(stderr, "vm_run error %d, errno %d\n", error, errno);
644 num_vcpus_allowed(struct vmctx *ctx)
648 error = vm_get_capability(ctx, BSP, VM_CAP_UNRESTRICTED_GUEST, &tmp);
651 * The guest is allowed to spinup more than one processor only if the
652 * UNRESTRICTED_GUEST capability is available.
661 fbsdrun_set_capabilities(struct vmctx *ctx, int cpu)
665 if (fbsdrun_vmexit_on_hlt()) {
666 err = vm_get_capability(ctx, cpu, VM_CAP_HALT_EXIT, &tmp);
668 fprintf(stderr, "VM exit on HLT not supported\n");
671 vm_set_capability(ctx, cpu, VM_CAP_HALT_EXIT, 1);
673 handler[VM_EXITCODE_HLT] = vmexit_hlt;
676 if (fbsdrun_vmexit_on_pause()) {
678 * pause exit support required for this mode
680 err = vm_get_capability(ctx, cpu, VM_CAP_PAUSE_EXIT, &tmp);
683 "SMP mux requested, no pause support\n");
686 vm_set_capability(ctx, cpu, VM_CAP_PAUSE_EXIT, 1);
688 handler[VM_EXITCODE_PAUSE] = vmexit_pause;
692 err = vm_set_x2apic_state(ctx, cpu, X2APIC_ENABLED);
694 err = vm_set_x2apic_state(ctx, cpu, X2APIC_DISABLED);
697 fprintf(stderr, "Unable to set x2apic state (%d)\n", err);
701 vm_set_capability(ctx, cpu, VM_CAP_ENABLE_INVPCID, 1);
704 static struct vmctx *
705 do_open(const char *vmname)
709 bool reinit, romboot;
711 reinit = romboot = false;
716 error = vm_create(vmname);
718 if (errno == EEXIST) {
723 * The virtual machine has been setup by the
724 * userspace bootloader.
734 * If the virtual machine was just created then a
735 * bootrom must be configured to boot it.
737 fprintf(stderr, "virtual machine cannot be booted\n");
742 ctx = vm_open(vmname);
749 error = vm_reinit(ctx);
759 main(int argc, char *argv[])
761 int c, error, gdb_port, err, bvmcons;
762 int max_vcpus, mptgen, memflags;
770 progname = basename(argv[0]);
778 optstr = "abehuwxACHIPSWYp:g:c:s:m:l:U:";
779 while ((c = getopt(argc, argv, optstr)) != -1) {
791 if (pincpu_parse(optarg) != 0) {
792 errx(EX_USAGE, "invalid vcpu pinning "
793 "configuration '%s'", optarg);
797 guest_ncpus = atoi(optarg);
800 memflags |= VM_MEM_F_INCORE;
803 gdb_port = atoi(optarg);
806 if (lpc_device_parse(optarg) != 0) {
807 errx(EX_USAGE, "invalid lpc device "
808 "configuration '%s'", optarg);
812 if (pci_parse_slot(optarg) != 0)
817 memflags |= VM_MEM_F_WIRED;
820 error = vm_parse_memsize(optarg, &memsize);
822 errx(EX_USAGE, "invalid memsize '%s'", optarg);
825 guest_vmexit_on_hlt = 1;
829 * The "-I" option was used to add an ioapic to the
832 * An ioapic is now provided unconditionally for each
833 * virtual machine and this option is now deprecated.
837 guest_vmexit_on_pause = 1;
846 guest_uuid_str = optarg;
873 ctx = do_open(vmname);
875 if (guest_ncpus < 1) {
876 fprintf(stderr, "Invalid guest vCPUs (%d)\n", guest_ncpus);
880 max_vcpus = num_vcpus_allowed(ctx);
881 if (guest_ncpus > max_vcpus) {
882 fprintf(stderr, "%d vCPUs requested but only %d available\n",
883 guest_ncpus, max_vcpus);
887 fbsdrun_set_capabilities(ctx, BSP);
889 vm_set_memflags(ctx, memflags);
890 err = vm_setup_memory(ctx, memsize, VM_MMAP_ALL);
892 fprintf(stderr, "Unable to setup memory (%d)\n", errno);
898 fprintf(stderr, "init_msr error %d", error);
907 rtc_init(ctx, rtc_localtime);
911 * Exit if a device emulation finds an error in it's initilization
913 if (init_pci(ctx) != 0)
917 init_dbgport(gdb_port);
923 if (vm_set_capability(ctx, BSP, VM_CAP_UNRESTRICTED_GUEST, 1)) {
924 fprintf(stderr, "ROM boot failed: unrestricted guest "
925 "capability not available\n");
928 error = vcpu_reset(ctx, BSP);
932 error = vm_get_register(ctx, BSP, VM_REG_GUEST_RIP, &rip);
936 * build the guest tables, MP etc.
939 error = mptable_build(ctx, guest_ncpus);
944 error = smbios_build(ctx);
948 error = acpi_build(ctx, guest_ncpus);
956 * Change the proc title to include the VM name.
958 setproctitle("%s", vmname);
963 fbsdrun_addcpu(ctx, BSP, BSP, rip);
966 * Head off to the main event dispatch loop