2 * SPDX-License-Identifier: BSD-2-Clause
4 * Copyright (c) 2011 NetApp, Inc.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
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.
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
31 #include <sys/cdefs.h>
32 __FBSDID("$FreeBSD$");
34 #include <sys/types.h>
35 #ifndef WITHOUT_CAPSICUM
36 #include <sys/capsicum.h>
40 #include <sys/socket.h>
48 #include <amd64/vmm/intel/vmcs.h>
49 #include <x86/apicreg.h>
51 #include <machine/atomic.h>
52 #include <machine/segments.h>
54 #ifndef WITHOUT_CAPSICUM
55 #include <capsicum_helpers.h>
69 #include <pthread_np.h>
80 #include <machine/vmm.h>
81 #ifndef WITHOUT_CAPSICUM
82 #include <machine/vmm_dev.h>
84 #include <machine/vmm_instruction_emul.h>
98 #include "kernemu_dev.h"
101 #ifdef BHYVE_SNAPSHOT
102 #include "migration.h"
105 #include "pci_emul.h"
108 #include "qemu_fwcfg.h"
109 #include "smbiostbl.h"
110 #ifdef BHYVE_SNAPSHOT
111 #include "snapshot.h"
114 #include "spinup_ap.h"
118 #define MB (1024UL * 1024)
119 #define GB (1024UL * MB)
121 static const char * const vmx_exit_reason_desc[] = {
122 [EXIT_REASON_EXCEPTION] = "Exception or non-maskable interrupt (NMI)",
123 [EXIT_REASON_EXT_INTR] = "External interrupt",
124 [EXIT_REASON_TRIPLE_FAULT] = "Triple fault",
125 [EXIT_REASON_INIT] = "INIT signal",
126 [EXIT_REASON_SIPI] = "Start-up IPI (SIPI)",
127 [EXIT_REASON_IO_SMI] = "I/O system-management interrupt (SMI)",
128 [EXIT_REASON_SMI] = "Other SMI",
129 [EXIT_REASON_INTR_WINDOW] = "Interrupt window",
130 [EXIT_REASON_NMI_WINDOW] = "NMI window",
131 [EXIT_REASON_TASK_SWITCH] = "Task switch",
132 [EXIT_REASON_CPUID] = "CPUID",
133 [EXIT_REASON_GETSEC] = "GETSEC",
134 [EXIT_REASON_HLT] = "HLT",
135 [EXIT_REASON_INVD] = "INVD",
136 [EXIT_REASON_INVLPG] = "INVLPG",
137 [EXIT_REASON_RDPMC] = "RDPMC",
138 [EXIT_REASON_RDTSC] = "RDTSC",
139 [EXIT_REASON_RSM] = "RSM",
140 [EXIT_REASON_VMCALL] = "VMCALL",
141 [EXIT_REASON_VMCLEAR] = "VMCLEAR",
142 [EXIT_REASON_VMLAUNCH] = "VMLAUNCH",
143 [EXIT_REASON_VMPTRLD] = "VMPTRLD",
144 [EXIT_REASON_VMPTRST] = "VMPTRST",
145 [EXIT_REASON_VMREAD] = "VMREAD",
146 [EXIT_REASON_VMRESUME] = "VMRESUME",
147 [EXIT_REASON_VMWRITE] = "VMWRITE",
148 [EXIT_REASON_VMXOFF] = "VMXOFF",
149 [EXIT_REASON_VMXON] = "VMXON",
150 [EXIT_REASON_CR_ACCESS] = "Control-register accesses",
151 [EXIT_REASON_DR_ACCESS] = "MOV DR",
152 [EXIT_REASON_INOUT] = "I/O instruction",
153 [EXIT_REASON_RDMSR] = "RDMSR",
154 [EXIT_REASON_WRMSR] = "WRMSR",
155 [EXIT_REASON_INVAL_VMCS] =
156 "VM-entry failure due to invalid guest state",
157 [EXIT_REASON_INVAL_MSR] = "VM-entry failure due to MSR loading",
158 [EXIT_REASON_MWAIT] = "MWAIT",
159 [EXIT_REASON_MTF] = "Monitor trap flag",
160 [EXIT_REASON_MONITOR] = "MONITOR",
161 [EXIT_REASON_PAUSE] = "PAUSE",
162 [EXIT_REASON_MCE_DURING_ENTRY] =
163 "VM-entry failure due to machine-check event",
164 [EXIT_REASON_TPR] = "TPR below threshold",
165 [EXIT_REASON_APIC_ACCESS] = "APIC access",
166 [EXIT_REASON_VIRTUALIZED_EOI] = "Virtualized EOI",
167 [EXIT_REASON_GDTR_IDTR] = "Access to GDTR or IDTR",
168 [EXIT_REASON_LDTR_TR] = "Access to LDTR or TR",
169 [EXIT_REASON_EPT_FAULT] = "EPT violation",
170 [EXIT_REASON_EPT_MISCONFIG] = "EPT misconfiguration",
171 [EXIT_REASON_INVEPT] = "INVEPT",
172 [EXIT_REASON_RDTSCP] = "RDTSCP",
173 [EXIT_REASON_VMX_PREEMPT] = "VMX-preemption timer expired",
174 [EXIT_REASON_INVVPID] = "INVVPID",
175 [EXIT_REASON_WBINVD] = "WBINVD",
176 [EXIT_REASON_XSETBV] = "XSETBV",
177 [EXIT_REASON_APIC_WRITE] = "APIC write",
178 [EXIT_REASON_RDRAND] = "RDRAND",
179 [EXIT_REASON_INVPCID] = "INVPCID",
180 [EXIT_REASON_VMFUNC] = "VMFUNC",
181 [EXIT_REASON_ENCLS] = "ENCLS",
182 [EXIT_REASON_RDSEED] = "RDSEED",
183 [EXIT_REASON_PM_LOG_FULL] = "Page-modification log full",
184 [EXIT_REASON_XSAVES] = "XSAVES",
185 [EXIT_REASON_XRSTORS] = "XRSTORS"
188 typedef int (*vmexit_handler_t)(struct vmctx *, struct vcpu *, struct vm_run *);
191 uint16_t cpu_cores, cpu_sockets, cpu_threads;
195 static char *progname;
196 static const int BSP = 0;
198 static cpuset_t cpumask;
200 static void vm_loop(struct vmctx *ctx, struct vcpu *vcpu);
202 static struct vcpu_info {
208 static cpuset_t **vcpumap;
215 "Usage: %s [-AaCDeHhPSuWwxY]\n"
216 " %*s [-c [[cpus=]numcpus][,sockets=n][,cores=n][,threads=n]]\n"
217 " %*s [-G port] [-k config_file] [-l lpc] [-m mem] [-o var=value]\n"
218 " %*s [-p vcpu:hostcpu] [-r file] [-s pci] [-U uuid] vmname\n"
219 " -A: create ACPI tables\n"
220 " -a: local apic is in xAPIC mode (deprecated)\n"
221 " -C: include guest memory in core file\n"
222 " -c: number of CPUs and/or topology specification\n"
223 " -D: destroy on power-off\n"
224 " -e: exit on unhandled I/O access\n"
225 " -G: start a debug server\n"
226 " -H: vmexit from the guest on HLT\n"
228 " -k: key=value flat config file\n"
229 " -K: PS2 keyboard layout\n"
230 " -l: LPC device configuration\n"
232 " -o: set config 'var' to 'value'\n"
233 " -P: vmexit from the guest on pause\n"
234 " -p: pin 'vcpu' to 'hostcpu'\n"
235 #ifdef BHYVE_SNAPSHOT
236 " -r: path to checkpoint file\n"
237 " -R: <host[:port]> the source vm host and port for migration\n"
239 " -S: guest memory cannot be swapped\n"
240 " -s: <slot,driver,configinfo> PCI slot config\n"
242 " -u: RTC keeps UTC time\n"
243 " -W: force virtio to use single-vector MSI\n"
244 " -w: ignore unimplemented MSRs\n"
245 " -x: local APIC is in x2APIC mode\n"
246 " -Y: disable MPtable generation\n",
247 progname, (int)strlen(progname), "", (int)strlen(progname), "",
248 (int)strlen(progname), "");
254 * XXX This parser is known to have the following issues:
255 * 1. It accepts null key=value tokens ",," as setting "cpus" to an
258 * The acceptance of a null specification ('-c ""') is by design to match the
259 * manual page syntax specification, this results in a topology of 1 vCPU.
262 topology_parse(const char *opt)
264 char *cp, *str, *tofree;
267 set_config_value("sockets", "1");
268 set_config_value("cores", "1");
269 set_config_value("threads", "1");
270 set_config_value("cpus", "1");
274 tofree = str = strdup(opt);
276 errx(4, "Failed to allocate memory");
278 while ((cp = strsep(&str, ",")) != NULL) {
279 if (strncmp(cp, "cpus=", strlen("cpus=")) == 0)
280 set_config_value("cpus", cp + strlen("cpus="));
281 else if (strncmp(cp, "sockets=", strlen("sockets=")) == 0)
282 set_config_value("sockets", cp + strlen("sockets="));
283 else if (strncmp(cp, "cores=", strlen("cores=")) == 0)
284 set_config_value("cores", cp + strlen("cores="));
285 else if (strncmp(cp, "threads=", strlen("threads=")) == 0)
286 set_config_value("threads", cp + strlen("threads="));
287 else if (strchr(cp, '=') != NULL)
290 set_config_value("cpus", cp);
301 parse_int_value(const char *key, const char *value, int minval, int maxval)
307 lval = strtol(value, &cp, 0);
308 if (errno != 0 || *cp != '\0' || cp == value || lval < minval ||
310 errx(4, "Invalid value for %s: '%s'", key, value);
315 * Set the sockets, cores, threads, and guest_cpus variables based on
316 * the configured topology.
318 * The limits of UINT16_MAX are due to the types passed to
319 * vm_set_topology(). vmm.ko may enforce tighter limits.
328 value = get_config_value("cpus");
330 guest_ncpus = parse_int_value("cpus", value, 1, UINT16_MAX);
331 explicit_cpus = true;
334 explicit_cpus = false;
336 value = get_config_value("cores");
338 cpu_cores = parse_int_value("cores", value, 1, UINT16_MAX);
341 value = get_config_value("threads");
343 cpu_threads = parse_int_value("threads", value, 1, UINT16_MAX);
346 value = get_config_value("sockets");
348 cpu_sockets = parse_int_value("sockets", value, 1, UINT16_MAX);
350 cpu_sockets = guest_ncpus;
353 * Compute sockets * cores * threads avoiding overflow. The
354 * range check above insures these are 16 bit values.
356 ncpus = (uint64_t)cpu_sockets * cpu_cores * cpu_threads;
357 if (ncpus > UINT16_MAX)
358 errx(4, "Computed number of vCPUs too high: %ju",
362 if (guest_ncpus != (int)ncpus)
363 errx(4, "Topology (%d sockets, %d cores, %d threads) "
364 "does not match %d vCPUs",
365 cpu_sockets, cpu_cores, cpu_threads,
372 pincpu_parse(const char *opt)
379 if (sscanf(opt, "%d:%d", &vcpu, &pcpu) != 2) {
380 fprintf(stderr, "invalid format: %s\n", opt);
385 fprintf(stderr, "invalid vcpu '%d'\n", vcpu);
389 if (pcpu < 0 || pcpu >= CPU_SETSIZE) {
390 fprintf(stderr, "hostcpu '%d' outside valid range from "
391 "0 to %d\n", pcpu, CPU_SETSIZE - 1);
395 snprintf(key, sizeof(key), "vcpu.%d.cpuset", vcpu);
396 value = get_config_value(key);
398 if (asprintf(&newval, "%s%s%d", value != NULL ? value : "",
399 value != NULL ? "," : "", pcpu) == -1) {
400 perror("failed to build new cpuset string");
404 set_config_value(key, newval);
410 parse_cpuset(int vcpu, const char *list, cpuset_t *set)
417 token = __DECONST(char *, list);
419 pcpu = strtoul(token, &cp, 0);
421 errx(4, "invalid cpuset for vcpu %d: '%s'", vcpu, list);
422 if (pcpu < 0 || pcpu >= CPU_SETSIZE)
423 errx(4, "hostcpu '%d' outside valid range from 0 to %d",
424 pcpu, CPU_SETSIZE - 1);
430 errx(4, "Invalid hostcpu range %d-%d",
432 while (start < pcpu) {
442 errx(4, "invalid cpuset for vcpu %d: '%s'",
447 errx(4, "invalid cpuset for vcpu %d: '%s'", vcpu, list);
462 vcpumap = calloc(guest_ncpus, sizeof(*vcpumap));
463 for (vcpu = 0; vcpu < guest_ncpus; vcpu++) {
464 snprintf(key, sizeof(key), "vcpu.%d.cpuset", vcpu);
465 value = get_config_value(key);
468 vcpumap[vcpu] = malloc(sizeof(cpuset_t));
469 if (vcpumap[vcpu] == NULL)
470 err(4, "Failed to allocate cpuset for vcpu %d", vcpu);
471 parse_cpuset(vcpu, value, vcpumap[vcpu]);
476 vm_inject_fault(struct vcpu *vcpu, int vector, int errcode_valid,
479 int error, restart_instruction;
481 restart_instruction = 1;
483 error = vm_inject_exception(vcpu, vector, errcode_valid, errcode,
484 restart_instruction);
489 paddr_guest2host(struct vmctx *ctx, uintptr_t gaddr, size_t len)
492 return (vm_map_gpa(ctx, gaddr, len));
495 #ifdef BHYVE_SNAPSHOT
497 paddr_host2guest(struct vmctx *ctx, void *addr)
499 return (vm_rev_map_gpa(ctx, addr));
504 fbsdrun_virtio_msix(void)
507 return (get_config_bool_default("virtio_msix", true));
511 fbsdrun_start_thread(void *param)
513 char tname[MAXCOMLEN + 1];
514 struct vcpu_info *vi = param;
517 snprintf(tname, sizeof(tname), "vcpu %d", vi->vcpuid);
518 pthread_set_name_np(pthread_self(), tname);
520 if (vcpumap[vi->vcpuid] != NULL) {
521 error = pthread_setaffinity_np(pthread_self(),
522 sizeof(cpuset_t), vcpumap[vi->vcpuid]);
526 #ifdef BHYVE_SNAPSHOT
527 checkpoint_cpu_add(vi->vcpuid);
529 gdb_cpu_add(vi->vcpu);
531 vm_loop(vi->ctx, vi->vcpu);
539 fbsdrun_addcpu(struct vcpu_info *vi)
544 error = vm_activate_cpu(vi->vcpu);
546 err(EX_OSERR, "could not activate CPU %d", vi->vcpuid);
548 CPU_SET_ATOMIC(vi->vcpuid, &cpumask);
550 vm_suspend_cpu(vi->vcpu);
552 error = pthread_create(&thr, NULL, fbsdrun_start_thread, vi);
557 fbsdrun_deletecpu(int vcpu)
560 if (!CPU_ISSET(vcpu, &cpumask)) {
561 fprintf(stderr, "Attempting to delete unknown cpu %d\n", vcpu);
565 CPU_CLR_ATOMIC(vcpu, &cpumask);
566 return (CPU_EMPTY(&cpumask));
570 vmexit_inout(struct vmctx *ctx, struct vcpu *vcpu, struct vm_run *vmrun)
576 vme = vmrun->vm_exit;
577 port = vme->u.inout.port;
578 bytes = vme->u.inout.bytes;
579 in = vme->u.inout.in;
581 error = emulate_inout(ctx, vcpu, vme);
583 fprintf(stderr, "Unhandled %s%c 0x%04x at 0x%lx\n",
585 bytes == 1 ? 'b' : (bytes == 2 ? 'w' : 'l'),
587 return (VMEXIT_ABORT);
589 return (VMEXIT_CONTINUE);
594 vmexit_rdmsr(struct vmctx *ctx __unused, struct vcpu *vcpu,
595 struct vm_run *vmrun)
602 vme = vmrun->vm_exit;
605 error = emulate_rdmsr(vcpu, vme->u.msr.code, &val);
607 fprintf(stderr, "rdmsr to register %#x on vcpu %d\n",
608 vme->u.msr.code, vcpu_id(vcpu));
609 if (get_config_bool("x86.strictmsr")) {
611 return (VMEXIT_CONTINUE);
616 error = vm_set_register(vcpu, VM_REG_GUEST_RAX, eax);
620 error = vm_set_register(vcpu, VM_REG_GUEST_RDX, edx);
623 return (VMEXIT_CONTINUE);
627 vmexit_wrmsr(struct vmctx *ctx __unused, struct vcpu *vcpu,
628 struct vm_run *vmrun)
633 vme = vmrun->vm_exit;
635 error = emulate_wrmsr(vcpu, vme->u.msr.code, vme->u.msr.wval);
637 fprintf(stderr, "wrmsr to register %#x(%#lx) on vcpu %d\n",
638 vme->u.msr.code, vme->u.msr.wval, vcpu_id(vcpu));
639 if (get_config_bool("x86.strictmsr")) {
641 return (VMEXIT_CONTINUE);
644 return (VMEXIT_CONTINUE);
647 #define DEBUG_EPT_MISCONFIG
648 #ifdef DEBUG_EPT_MISCONFIG
649 #define VMCS_GUEST_PHYSICAL_ADDRESS 0x00002400
651 static uint64_t ept_misconfig_gpa, ept_misconfig_pte[4];
652 static int ept_misconfig_ptenum;
656 vmexit_vmx_desc(uint32_t exit_reason)
659 if (exit_reason >= nitems(vmx_exit_reason_desc) ||
660 vmx_exit_reason_desc[exit_reason] == NULL)
662 return (vmx_exit_reason_desc[exit_reason]);
666 vmexit_vmx(struct vmctx *ctx, struct vcpu *vcpu, struct vm_run *vmrun)
670 vme = vmrun->vm_exit;
672 fprintf(stderr, "vm exit[%d]\n", vcpu_id(vcpu));
673 fprintf(stderr, "\treason\t\tVMX\n");
674 fprintf(stderr, "\trip\t\t0x%016lx\n", vme->rip);
675 fprintf(stderr, "\tinst_length\t%d\n", vme->inst_length);
676 fprintf(stderr, "\tstatus\t\t%d\n", vme->u.vmx.status);
677 fprintf(stderr, "\texit_reason\t%u (%s)\n", vme->u.vmx.exit_reason,
678 vmexit_vmx_desc(vme->u.vmx.exit_reason));
679 fprintf(stderr, "\tqualification\t0x%016lx\n",
680 vme->u.vmx.exit_qualification);
681 fprintf(stderr, "\tinst_type\t\t%d\n", vme->u.vmx.inst_type);
682 fprintf(stderr, "\tinst_error\t\t%d\n", vme->u.vmx.inst_error);
683 #ifdef DEBUG_EPT_MISCONFIG
684 if (vme->u.vmx.exit_reason == EXIT_REASON_EPT_MISCONFIG) {
685 vm_get_register(vcpu,
686 VMCS_IDENT(VMCS_GUEST_PHYSICAL_ADDRESS),
688 vm_get_gpa_pmap(ctx, ept_misconfig_gpa, ept_misconfig_pte,
689 &ept_misconfig_ptenum);
690 fprintf(stderr, "\tEPT misconfiguration:\n");
691 fprintf(stderr, "\t\tGPA: %#lx\n", ept_misconfig_gpa);
692 fprintf(stderr, "\t\tPTE(%d): %#lx %#lx %#lx %#lx\n",
693 ept_misconfig_ptenum, ept_misconfig_pte[0],
694 ept_misconfig_pte[1], ept_misconfig_pte[2],
695 ept_misconfig_pte[3]);
697 #endif /* DEBUG_EPT_MISCONFIG */
698 return (VMEXIT_ABORT);
702 vmexit_svm(struct vmctx *ctx __unused, struct vcpu *vcpu, struct vm_run *vmrun)
706 vme = vmrun->vm_exit;
708 fprintf(stderr, "vm exit[%d]\n", vcpu_id(vcpu));
709 fprintf(stderr, "\treason\t\tSVM\n");
710 fprintf(stderr, "\trip\t\t0x%016lx\n", vme->rip);
711 fprintf(stderr, "\tinst_length\t%d\n", vme->inst_length);
712 fprintf(stderr, "\texitcode\t%#lx\n", vme->u.svm.exitcode);
713 fprintf(stderr, "\texitinfo1\t%#lx\n", vme->u.svm.exitinfo1);
714 fprintf(stderr, "\texitinfo2\t%#lx\n", vme->u.svm.exitinfo2);
715 return (VMEXIT_ABORT);
719 vmexit_bogus(struct vmctx *ctx __unused, struct vcpu *vcpu __unused,
720 struct vm_run *vmrun)
722 assert(vmrun->vm_exit->inst_length == 0);
724 return (VMEXIT_CONTINUE);
728 vmexit_reqidle(struct vmctx *ctx __unused, struct vcpu *vcpu __unused,
729 struct vm_run *vmrun)
731 assert(vmrun->vm_exit->inst_length == 0);
733 return (VMEXIT_CONTINUE);
737 vmexit_hlt(struct vmctx *ctx __unused, struct vcpu *vcpu __unused,
738 struct vm_run *vmrun __unused)
741 * Just continue execution with the next instruction. We use
742 * the HLT VM exit as a way to be friendly with the host
745 return (VMEXIT_CONTINUE);
749 vmexit_pause(struct vmctx *ctx __unused, struct vcpu *vcpu __unused,
750 struct vm_run *vmrun __unused)
752 return (VMEXIT_CONTINUE);
756 vmexit_mtrap(struct vmctx *ctx __unused, struct vcpu *vcpu,
757 struct vm_run *vmrun)
759 assert(vmrun->vm_exit->inst_length == 0);
761 #ifdef BHYVE_SNAPSHOT
762 checkpoint_cpu_suspend(vcpu_id(vcpu));
765 #ifdef BHYVE_SNAPSHOT
766 checkpoint_cpu_resume(vcpu_id(vcpu));
769 return (VMEXIT_CONTINUE);
773 vmexit_inst_emul(struct vmctx *ctx __unused, struct vcpu *vcpu,
774 struct vm_run *vmrun)
779 enum vm_cpu_mode mode;
781 vme = vmrun->vm_exit;
783 vie = &vme->u.inst_emul.vie;
786 * Attempt to decode in userspace as a fallback. This allows
787 * updating instruction decode in bhyve without rebooting the
788 * kernel (rapid prototyping), albeit with much slower
792 mode = vme->u.inst_emul.paging.cpu_mode;
793 cs_d = vme->u.inst_emul.cs_d;
794 if (vmm_decode_instruction(mode, cs_d, vie) != 0)
796 if (vm_set_register(vcpu, VM_REG_GUEST_RIP,
797 vme->rip + vie->num_processed) != 0)
801 err = emulate_mem(vcpu, vme->u.inst_emul.gpa, vie,
802 &vme->u.inst_emul.paging);
805 EPRINTLN("Unhandled memory access to 0x%lx\n",
806 vme->u.inst_emul.gpa);
811 return (VMEXIT_CONTINUE);
814 fprintf(stderr, "Failed to emulate instruction sequence [ ");
815 for (i = 0; i < vie->num_valid; i++)
816 fprintf(stderr, "%02x", vie->inst[i]);
817 FPRINTLN(stderr, " ] at 0x%lx", vme->rip);
818 return (VMEXIT_ABORT);
821 static pthread_mutex_t resetcpu_mtx = PTHREAD_MUTEX_INITIALIZER;
822 static pthread_cond_t resetcpu_cond = PTHREAD_COND_INITIALIZER;
825 vmexit_suspend(struct vmctx *ctx, struct vcpu *vcpu, struct vm_run *vmrun)
828 enum vm_suspend_how how;
829 int vcpuid = vcpu_id(vcpu);
831 vme = vmrun->vm_exit;
833 how = vme->u.suspended.how;
835 fbsdrun_deletecpu(vcpuid);
838 pthread_mutex_lock(&resetcpu_mtx);
839 pthread_cond_signal(&resetcpu_cond);
840 pthread_mutex_unlock(&resetcpu_mtx);
844 pthread_mutex_lock(&resetcpu_mtx);
845 while (!CPU_EMPTY(&cpumask)) {
846 pthread_cond_wait(&resetcpu_cond, &resetcpu_mtx);
848 pthread_mutex_unlock(&resetcpu_mtx);
851 case VM_SUSPEND_RESET:
853 case VM_SUSPEND_POWEROFF:
854 if (get_config_bool_default("destroy_on_poweroff", false))
857 case VM_SUSPEND_HALT:
859 case VM_SUSPEND_TRIPLEFAULT:
862 fprintf(stderr, "vmexit_suspend: invalid reason %d\n", how);
865 return (0); /* NOTREACHED */
869 vmexit_debug(struct vmctx *ctx __unused, struct vcpu *vcpu,
870 struct vm_run *vmrun __unused)
873 #ifdef BHYVE_SNAPSHOT
874 checkpoint_cpu_suspend(vcpu_id(vcpu));
876 gdb_cpu_suspend(vcpu);
877 #ifdef BHYVE_SNAPSHOT
878 checkpoint_cpu_resume(vcpu_id(vcpu));
881 * XXX-MJ sleep for a short period to avoid chewing up the CPU in the
882 * window between activation of the vCPU thread and the STARTUP IPI.
885 return (VMEXIT_CONTINUE);
889 vmexit_breakpoint(struct vmctx *ctx __unused, struct vcpu *vcpu,
890 struct vm_run *vmrun)
892 gdb_cpu_breakpoint(vcpu, vmrun->vm_exit);
893 return (VMEXIT_CONTINUE);
897 vmexit_ipi(struct vmctx *ctx __unused, struct vcpu *vcpu __unused,
898 struct vm_run *vmrun)
905 dmask = vmrun->cpuset;
906 vme = vmrun->vm_exit;
908 switch (vme->u.ipi.mode) {
909 case APIC_DELMODE_INIT:
910 CPU_FOREACH_ISSET(i, dmask) {
911 error = vm_suspend_cpu(vcpu_info[i].vcpu);
913 warnx("%s: failed to suspend cpu %d\n",
919 case APIC_DELMODE_STARTUP:
920 CPU_FOREACH_ISSET(i, dmask) {
921 spinup_ap(vcpu_info[i].vcpu,
922 vme->u.ipi.vector << PAGE_SHIFT);
933 static vmexit_handler_t handler[VM_EXITCODE_MAX] = {
934 [VM_EXITCODE_INOUT] = vmexit_inout,
935 [VM_EXITCODE_INOUT_STR] = vmexit_inout,
936 [VM_EXITCODE_VMX] = vmexit_vmx,
937 [VM_EXITCODE_SVM] = vmexit_svm,
938 [VM_EXITCODE_BOGUS] = vmexit_bogus,
939 [VM_EXITCODE_REQIDLE] = vmexit_reqidle,
940 [VM_EXITCODE_RDMSR] = vmexit_rdmsr,
941 [VM_EXITCODE_WRMSR] = vmexit_wrmsr,
942 [VM_EXITCODE_MTRAP] = vmexit_mtrap,
943 [VM_EXITCODE_INST_EMUL] = vmexit_inst_emul,
944 [VM_EXITCODE_SUSPENDED] = vmexit_suspend,
945 [VM_EXITCODE_TASK_SWITCH] = vmexit_task_switch,
946 [VM_EXITCODE_DEBUG] = vmexit_debug,
947 [VM_EXITCODE_BPT] = vmexit_breakpoint,
948 [VM_EXITCODE_IPI] = vmexit_ipi,
952 vm_loop(struct vmctx *ctx, struct vcpu *vcpu)
957 enum vm_exitcode exitcode;
958 cpuset_t active_cpus, dmask;
960 error = vm_active_cpus(ctx, &active_cpus);
961 assert(CPU_ISSET(vcpu_id(vcpu), &active_cpus));
963 vmrun.vm_exit = &vme;
964 vmrun.cpuset = &dmask;
965 vmrun.cpusetsize = sizeof(dmask);
968 error = vm_run(vcpu, &vmrun);
972 exitcode = vme.exitcode;
973 if (exitcode >= VM_EXITCODE_MAX || handler[exitcode] == NULL) {
974 fprintf(stderr, "vm_loop: unexpected exitcode 0x%x\n",
979 rc = (*handler[exitcode])(ctx, vcpu, &vmrun);
982 case VMEXIT_CONTINUE:
990 fprintf(stderr, "vm_run error %d, errno %d\n", error, errno);
994 num_vcpus_allowed(struct vmctx *ctx, struct vcpu *vcpu)
996 uint16_t sockets, cores, threads, maxcpus;
1000 * The guest is allowed to spinup more than one processor only if the
1001 * UNRESTRICTED_GUEST capability is available.
1003 error = vm_get_capability(vcpu, VM_CAP_UNRESTRICTED_GUEST, &tmp);
1007 error = vm_get_topology(ctx, &sockets, &cores, &threads, &maxcpus);
1015 fbsdrun_set_capabilities(struct vcpu *vcpu, bool bsp)
1019 if (get_config_bool_default("x86.vmexit_on_hlt", false)) {
1020 err = vm_get_capability(vcpu, VM_CAP_HALT_EXIT, &tmp);
1022 fprintf(stderr, "VM exit on HLT not supported\n");
1025 vm_set_capability(vcpu, VM_CAP_HALT_EXIT, 1);
1027 handler[VM_EXITCODE_HLT] = vmexit_hlt;
1030 if (get_config_bool_default("x86.vmexit_on_pause", false)) {
1032 * pause exit support required for this mode
1034 err = vm_get_capability(vcpu, VM_CAP_PAUSE_EXIT, &tmp);
1037 "SMP mux requested, no pause support\n");
1040 vm_set_capability(vcpu, VM_CAP_PAUSE_EXIT, 1);
1042 handler[VM_EXITCODE_PAUSE] = vmexit_pause;
1045 if (get_config_bool_default("x86.x2apic", false))
1046 err = vm_set_x2apic_state(vcpu, X2APIC_ENABLED);
1048 err = vm_set_x2apic_state(vcpu, X2APIC_DISABLED);
1051 fprintf(stderr, "Unable to set x2apic state (%d)\n", err);
1055 vm_set_capability(vcpu, VM_CAP_ENABLE_INVPCID, 1);
1057 err = vm_set_capability(vcpu, VM_CAP_IPI_EXIT, 1);
1061 static struct vmctx *
1062 do_open(const char *vmname)
1066 bool reinit, romboot;
1068 reinit = romboot = false;
1073 error = vm_create(vmname);
1075 if (errno == EEXIST) {
1080 * The virtual machine has been setup by the
1081 * userspace bootloader.
1085 perror("vm_create");
1089 #ifndef BHYVE_SNAPSHOT
1092 if (!romboot && !get_config_bool_default("is_migrated", false)) {
1095 * If the virtual machine was just created then a
1096 * bootrom must be configured to boot it.
1098 fprintf(stderr, "virtual machine cannot be booted\n");
1103 ctx = vm_open(vmname);
1109 #ifndef WITHOUT_CAPSICUM
1110 if (vm_limit_rights(ctx) != 0)
1111 err(EX_OSERR, "vm_limit_rights");
1115 error = vm_reinit(ctx);
1117 perror("vm_reinit");
1121 error = vm_set_topology(ctx, cpu_sockets, cpu_cores, cpu_threads, 0);
1123 errx(EX_OSERR, "vm_set_topology");
1128 spinup_vcpu(struct vcpu_info *vi, bool bsp)
1133 fbsdrun_set_capabilities(vi->vcpu, false);
1136 * Enable the 'unrestricted guest' mode for APs.
1138 * APs startup in power-on 16-bit mode.
1140 error = vm_set_capability(vi->vcpu, VM_CAP_UNRESTRICTED_GUEST, 1);
1148 parse_config_option(const char *option)
1153 value = strchr(option, '=');
1154 if (value == NULL || value[1] == '\0')
1156 path = strndup(option, value - option);
1158 err(4, "Failed to allocate memory");
1159 set_config_value(path, value + 1);
1164 parse_simple_config_file(const char *path)
1169 unsigned int lineno;
1171 fp = fopen(path, "r");
1173 err(4, "Failed to open configuration file %s", path);
1177 for (lineno = 1; getline(&line, &linecap, fp) > 0; lineno++) {
1178 if (*line == '#' || *line == '\n')
1180 cp = strchr(line, '\n');
1183 if (!parse_config_option(line))
1184 errx(4, "%s line %u: invalid config option '%s'", path,
1192 parse_gdb_options(const char *opt)
1197 if (opt[0] == 'w') {
1198 set_config_bool("gdb.wait", true);
1202 colon = strrchr(opt, ':');
1203 if (colon == NULL) {
1209 set_config_value("gdb.address", opt);
1212 set_config_value("gdb.port", sport);
1219 set_config_bool("acpi_tables", false);
1220 set_config_value("memory.size", "256M");
1221 set_config_bool("x86.strictmsr", true);
1222 set_config_value("lpc.fwcfg", "bhyve");
1226 main(int argc, char *argv[])
1229 int max_vcpus, memflags;
1232 struct qemu_fwcfg_item *e820_fwcfg_item;
1235 const char *optstr, *value, *vmname;
1236 #ifdef BHYVE_SNAPSHOT
1238 char *migration_host;
1239 struct restore_state rstate;
1241 restore_file = NULL;
1242 migration_host = NULL;
1247 progname = basename(argv[0]);
1249 #ifdef BHYVE_SNAPSHOT
1250 optstr = "aehuwxACDHIPSWYk:f:o:p:G:c:s:m:l:K:U:r:R:";
1252 optstr = "aehuwxACDHIPSWYk:f:o:p:G:c:s:m:l:K:U:";
1254 while ((c = getopt(argc, argv, optstr)) != -1) {
1257 set_config_bool("x86.x2apic", false);
1260 set_config_bool("acpi_tables", true);
1263 set_config_bool("destroy_on_poweroff", true);
1266 if (pincpu_parse(optarg) != 0) {
1267 errx(EX_USAGE, "invalid vcpu pinning "
1268 "configuration '%s'", optarg);
1272 if (topology_parse(optarg) != 0) {
1273 errx(EX_USAGE, "invalid cpu topology "
1278 set_config_bool("memory.guest_in_core", true);
1281 if (qemu_fwcfg_parse_cmdline_arg(optarg) != 0) {
1282 errx(EX_USAGE, "invalid fwcfg item '%s'", optarg);
1286 parse_gdb_options(optarg);
1289 parse_simple_config_file(optarg);
1292 set_config_value("keyboard.layout", optarg);
1295 if (strncmp(optarg, "help", strlen(optarg)) == 0) {
1296 lpc_print_supported_devices();
1298 } else if (lpc_device_parse(optarg) != 0) {
1299 errx(EX_USAGE, "invalid lpc device "
1300 "configuration '%s'", optarg);
1303 #ifdef BHYVE_SNAPSHOT
1305 restore_file = optarg;
1308 migration_host = optarg;
1309 set_config_bool("is_migrated", true);
1313 if (strncmp(optarg, "help", strlen(optarg)) == 0) {
1314 pci_print_supported_devices();
1316 } else if (pci_parse_slot(optarg) != 0)
1321 set_config_bool("memory.wired", true);
1324 set_config_value("memory.size", optarg);
1327 if (!parse_config_option(optarg))
1328 errx(EX_USAGE, "invalid configuration option '%s'", optarg);
1331 set_config_bool("x86.vmexit_on_hlt", true);
1335 * The "-I" option was used to add an ioapic to the
1338 * An ioapic is now provided unconditionally for each
1339 * virtual machine and this option is now deprecated.
1343 set_config_bool("x86.vmexit_on_pause", true);
1346 set_config_bool("x86.strictio", true);
1349 set_config_bool("rtc.use_localtime", false);
1352 set_config_value("uuid", optarg);
1355 set_config_bool("x86.strictmsr", false);
1358 set_config_bool("virtio_msix", false);
1361 set_config_bool("x86.x2apic", true);
1364 set_config_bool("x86.mptable", false);
1378 #ifdef BHYVE_SNAPSHOT
1379 if (restore_file != NULL) {
1380 error = load_restore_file(restore_file, &rstate);
1382 fprintf(stderr, "Failed to read checkpoint info from "
1383 "file: '%s'.\n", restore_file);
1386 vmname = lookup_vmname(&rstate);
1388 set_config_value("name", vmname);
1393 set_config_value("name", argv[0]);
1395 vmname = get_config_value("name");
1399 if (get_config_bool_default("config.dump", false)) {
1407 value = get_config_value("memory.size");
1408 error = vm_parse_memsize(value, &memsize);
1410 errx(EX_USAGE, "invalid memsize '%s'", value);
1412 ctx = do_open(vmname);
1414 #ifdef BHYVE_SNAPSHOT
1415 if (restore_file != NULL) {
1416 guest_ncpus = lookup_guest_ncpus(&rstate);
1417 memflags = lookup_memflags(&rstate);
1418 memsize = lookup_memsize(&rstate);
1421 if (guest_ncpus < 1) {
1422 fprintf(stderr, "Invalid guest vCPUs (%d)\n", guest_ncpus);
1427 bsp = vm_vcpu_open(ctx, BSP);
1428 max_vcpus = num_vcpus_allowed(ctx, bsp);
1429 if (guest_ncpus > max_vcpus) {
1430 fprintf(stderr, "%d vCPUs requested but only %d available\n",
1431 guest_ncpus, max_vcpus);
1435 fbsdrun_set_capabilities(bsp, true);
1437 /* Allocate per-VCPU resources. */
1438 vcpu_info = calloc(guest_ncpus, sizeof(*vcpu_info));
1439 for (int vcpuid = 0; vcpuid < guest_ncpus; vcpuid++) {
1440 vcpu_info[vcpuid].ctx = ctx;
1441 vcpu_info[vcpuid].vcpuid = vcpuid;
1443 vcpu_info[vcpuid].vcpu = bsp;
1445 vcpu_info[vcpuid].vcpu = vm_vcpu_open(ctx, vcpuid);
1449 if (get_config_bool_default("memory.wired", false))
1450 memflags |= VM_MEM_F_WIRED;
1451 if (get_config_bool_default("memory.guest_in_core", false))
1452 memflags |= VM_MEM_F_INCORE;
1453 vm_set_memflags(ctx, memflags);
1454 error = vm_setup_memory(ctx, memsize, VM_MMAP_ALL);
1456 fprintf(stderr, "Unable to setup memory (%d)\n", errno);
1462 fprintf(stderr, "init_msr error %d", error);
1466 init_mem(guest_ncpus);
1477 if (qemu_fwcfg_init(ctx) != 0) {
1478 fprintf(stderr, "qemu fwcfg initialization error");
1482 if (qemu_fwcfg_add_file("opt/bhyve/hw.ncpu", sizeof(guest_ncpus),
1483 &guest_ncpus) != 0) {
1484 fprintf(stderr, "Could not add qemu fwcfg opt/bhyve/hw.ncpu");
1488 if (e820_init(ctx) != 0) {
1489 fprintf(stderr, "Unable to setup E820");
1494 * Exit if a device emulation finds an error in its initialization
1496 if (init_pci(ctx) != 0) {
1497 perror("device emulation initialization error");
1502 * Initialize after PCI, to allow a bootrom file to reserve the high
1505 if (get_config_bool("acpi_tables"))
1510 if (lpc_bootrom()) {
1511 if (vm_set_capability(bsp, VM_CAP_UNRESTRICTED_GUEST, 1)) {
1512 fprintf(stderr, "ROM boot failed: unrestricted guest "
1513 "capability not available\n");
1516 error = vcpu_reset(bsp);
1523 for (int vcpuid = 0; vcpuid < guest_ncpus; vcpuid++)
1524 spinup_vcpu(&vcpu_info[vcpuid], vcpuid == BSP);
1526 #ifdef BHYVE_SNAPSHOT
1527 if (restore_file != NULL || migration_host != NULL) {
1528 fprintf(stdout, "Pausing pci devs...\n");
1529 if (vm_pause_devices() != 0) {
1530 fprintf(stderr, "Failed to pause PCI device state.\n");
1534 if (restore_file != NULL) {
1535 fprintf(stdout, "Restoring vm mem...\n");
1536 if (restore_vm_mem(ctx, &rstate) != 0) {
1538 "Failed to restore VM memory.\n");
1542 fprintf(stdout, "Restoring pci devs...\n");
1543 if (vm_restore_devices(&rstate) != 0) {
1545 "Failed to restore PCI device state.\n");
1549 fprintf(stdout, "Restoring kernel structs...\n");
1550 if (vm_restore_kern_structs(ctx, &rstate) != 0) {
1552 "Failed to restore kernel structs.\n");
1557 if (migration_host != NULL) {
1558 fprintf(stdout, "Starting the migration process...\n");
1559 if (receive_vm_migration(ctx, migration_host) != 0) {
1560 fprintf(stderr, "Failed to migrate the vm.\n");
1565 fprintf(stdout, "Resuming pci devs...\n");
1566 if (vm_resume_devices() != 0) {
1567 fprintf(stderr, "Failed to resume PCI device state.\n");
1571 #endif /* BHYVE_SNAPSHOT */
1573 error = vm_get_register(bsp, VM_REG_GUEST_RIP, &rip);
1577 * build the guest tables, MP etc.
1579 if (get_config_bool_default("x86.mptable", true)) {
1580 error = mptable_build(ctx, guest_ncpus);
1582 perror("error to build the guest tables");
1587 error = smbios_build(ctx);
1591 if (get_config_bool("acpi_tables")) {
1592 error = acpi_build(ctx, guest_ncpus);
1596 e820_fwcfg_item = e820_get_fwcfg_item();
1597 if (e820_fwcfg_item == NULL) {
1598 fprintf(stderr, "invalid e820 table");
1601 if (qemu_fwcfg_add_file("etc/e820", e820_fwcfg_item->size,
1602 e820_fwcfg_item->data) != 0) {
1603 fprintf(stderr, "could not add qemu fwcfg etc/e820");
1606 free(e820_fwcfg_item);
1608 if (lpc_bootrom() && strcmp(lpc_fwcfg(), "bhyve") == 0) {
1613 * Change the proc title to include the VM name.
1615 setproctitle("%s", vmname);
1617 #ifdef BHYVE_SNAPSHOT
1618 /* initialize mutex/cond variables */
1622 * checkpointing thread for communication with bhyvectl
1624 if (init_checkpoint_thread(ctx) != 0)
1625 errx(EX_OSERR, "Failed to start checkpoint thread");
1628 #ifndef WITHOUT_CAPSICUM
1629 caph_cache_catpages();
1631 if (caph_limit_stdout() == -1 || caph_limit_stderr() == -1)
1632 errx(EX_OSERR, "Unable to apply rights for sandbox");
1634 if (caph_enter() == -1)
1635 errx(EX_OSERR, "cap_enter() failed");
1638 #ifdef BHYVE_SNAPSHOT
1639 if (restore_file != NULL)
1640 destroy_restore_state(&rstate);
1641 if (restore_file != NULL || migration_host != NULL) {
1642 if (vm_restore_time(ctx) < 0)
1643 err(EX_OSERR, "Unable to restore time");
1645 for (int vcpuid = 0; vcpuid < guest_ncpus; vcpuid++)
1646 vm_resume_cpu(vcpu_info[vcpuid].vcpu);
1652 * Head off to the main event dispatch loop