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
29 #include <sys/cdefs.h>
30 #include <sys/types.h>
31 #ifndef WITHOUT_CAPSICUM
32 #include <sys/capsicum.h>
36 #include <sys/socket.h>
44 #include <amd64/vmm/intel/vmcs.h>
45 #include <x86/apicreg.h>
47 #include <machine/atomic.h>
48 #include <machine/segments.h>
50 #ifndef WITHOUT_CAPSICUM
51 #include <capsicum_helpers.h>
65 #include <pthread_np.h>
76 #include <machine/vmm.h>
77 #ifndef WITHOUT_CAPSICUM
78 #include <machine/vmm_dev.h>
80 #include <machine/vmm_instruction_emul.h>
94 #include "kernemu_dev.h"
101 #include "qemu_fwcfg.h"
102 #include "smbiostbl.h"
103 #ifdef BHYVE_SNAPSHOT
104 #include "snapshot.h"
106 #include "tpm_device.h"
108 #include "spinup_ap.h"
112 #define MB (1024UL * 1024)
113 #define GB (1024UL * MB)
115 static const char * const vmx_exit_reason_desc[] = {
116 [EXIT_REASON_EXCEPTION] = "Exception or non-maskable interrupt (NMI)",
117 [EXIT_REASON_EXT_INTR] = "External interrupt",
118 [EXIT_REASON_TRIPLE_FAULT] = "Triple fault",
119 [EXIT_REASON_INIT] = "INIT signal",
120 [EXIT_REASON_SIPI] = "Start-up IPI (SIPI)",
121 [EXIT_REASON_IO_SMI] = "I/O system-management interrupt (SMI)",
122 [EXIT_REASON_SMI] = "Other SMI",
123 [EXIT_REASON_INTR_WINDOW] = "Interrupt window",
124 [EXIT_REASON_NMI_WINDOW] = "NMI window",
125 [EXIT_REASON_TASK_SWITCH] = "Task switch",
126 [EXIT_REASON_CPUID] = "CPUID",
127 [EXIT_REASON_GETSEC] = "GETSEC",
128 [EXIT_REASON_HLT] = "HLT",
129 [EXIT_REASON_INVD] = "INVD",
130 [EXIT_REASON_INVLPG] = "INVLPG",
131 [EXIT_REASON_RDPMC] = "RDPMC",
132 [EXIT_REASON_RDTSC] = "RDTSC",
133 [EXIT_REASON_RSM] = "RSM",
134 [EXIT_REASON_VMCALL] = "VMCALL",
135 [EXIT_REASON_VMCLEAR] = "VMCLEAR",
136 [EXIT_REASON_VMLAUNCH] = "VMLAUNCH",
137 [EXIT_REASON_VMPTRLD] = "VMPTRLD",
138 [EXIT_REASON_VMPTRST] = "VMPTRST",
139 [EXIT_REASON_VMREAD] = "VMREAD",
140 [EXIT_REASON_VMRESUME] = "VMRESUME",
141 [EXIT_REASON_VMWRITE] = "VMWRITE",
142 [EXIT_REASON_VMXOFF] = "VMXOFF",
143 [EXIT_REASON_VMXON] = "VMXON",
144 [EXIT_REASON_CR_ACCESS] = "Control-register accesses",
145 [EXIT_REASON_DR_ACCESS] = "MOV DR",
146 [EXIT_REASON_INOUT] = "I/O instruction",
147 [EXIT_REASON_RDMSR] = "RDMSR",
148 [EXIT_REASON_WRMSR] = "WRMSR",
149 [EXIT_REASON_INVAL_VMCS] =
150 "VM-entry failure due to invalid guest state",
151 [EXIT_REASON_INVAL_MSR] = "VM-entry failure due to MSR loading",
152 [EXIT_REASON_MWAIT] = "MWAIT",
153 [EXIT_REASON_MTF] = "Monitor trap flag",
154 [EXIT_REASON_MONITOR] = "MONITOR",
155 [EXIT_REASON_PAUSE] = "PAUSE",
156 [EXIT_REASON_MCE_DURING_ENTRY] =
157 "VM-entry failure due to machine-check event",
158 [EXIT_REASON_TPR] = "TPR below threshold",
159 [EXIT_REASON_APIC_ACCESS] = "APIC access",
160 [EXIT_REASON_VIRTUALIZED_EOI] = "Virtualized EOI",
161 [EXIT_REASON_GDTR_IDTR] = "Access to GDTR or IDTR",
162 [EXIT_REASON_LDTR_TR] = "Access to LDTR or TR",
163 [EXIT_REASON_EPT_FAULT] = "EPT violation",
164 [EXIT_REASON_EPT_MISCONFIG] = "EPT misconfiguration",
165 [EXIT_REASON_INVEPT] = "INVEPT",
166 [EXIT_REASON_RDTSCP] = "RDTSCP",
167 [EXIT_REASON_VMX_PREEMPT] = "VMX-preemption timer expired",
168 [EXIT_REASON_INVVPID] = "INVVPID",
169 [EXIT_REASON_WBINVD] = "WBINVD",
170 [EXIT_REASON_XSETBV] = "XSETBV",
171 [EXIT_REASON_APIC_WRITE] = "APIC write",
172 [EXIT_REASON_RDRAND] = "RDRAND",
173 [EXIT_REASON_INVPCID] = "INVPCID",
174 [EXIT_REASON_VMFUNC] = "VMFUNC",
175 [EXIT_REASON_ENCLS] = "ENCLS",
176 [EXIT_REASON_RDSEED] = "RDSEED",
177 [EXIT_REASON_PM_LOG_FULL] = "Page-modification log full",
178 [EXIT_REASON_XSAVES] = "XSAVES",
179 [EXIT_REASON_XRSTORS] = "XRSTORS"
182 typedef int (*vmexit_handler_t)(struct vmctx *, struct vcpu *, struct vm_run *);
185 uint16_t cpu_cores, cpu_sockets, cpu_threads;
189 static char *progname;
190 static const int BSP = 0;
192 static cpuset_t cpumask;
194 static void vm_loop(struct vmctx *ctx, struct vcpu *vcpu);
196 static struct vcpu_info {
202 static cpuset_t **vcpumap;
209 "Usage: %s [-AaCDeHhPSuWwxY]\n"
210 " %*s [-c [[cpus=]numcpus][,sockets=n][,cores=n][,threads=n]]\n"
211 " %*s [-G port] [-k config_file] [-l lpc] [-m mem] [-o var=value]\n"
212 " %*s [-p vcpu:hostcpu] [-r file] [-s pci] [-U uuid] vmname\n"
213 " -A: create ACPI tables\n"
214 " -a: local apic is in xAPIC mode (deprecated)\n"
215 " -C: include guest memory in core file\n"
216 " -c: number of CPUs and/or topology specification\n"
217 " -D: destroy on power-off\n"
218 " -e: exit on unhandled I/O access\n"
219 " -G: start a debug server\n"
220 " -H: vmexit from the guest on HLT\n"
222 " -k: key=value flat config file\n"
223 " -K: PS2 keyboard layout\n"
224 " -l: LPC device configuration\n"
226 " -o: set config 'var' to 'value'\n"
227 " -P: vmexit from the guest on pause\n"
228 " -p: pin 'vcpu' to 'hostcpu'\n"
229 #ifdef BHYVE_SNAPSHOT
230 " -r: path to checkpoint file\n"
232 " -S: guest memory cannot be swapped\n"
233 " -s: <slot,driver,configinfo> PCI slot config\n"
235 " -u: RTC keeps UTC time\n"
236 " -W: force virtio to use single-vector MSI\n"
237 " -w: ignore unimplemented MSRs\n"
238 " -x: local APIC is in x2APIC mode\n"
239 " -Y: disable MPtable generation\n",
240 progname, (int)strlen(progname), "", (int)strlen(progname), "",
241 (int)strlen(progname), "");
247 * XXX This parser is known to have the following issues:
248 * 1. It accepts null key=value tokens ",," as setting "cpus" to an
251 * The acceptance of a null specification ('-c ""') is by design to match the
252 * manual page syntax specification, this results in a topology of 1 vCPU.
255 topology_parse(const char *opt)
257 char *cp, *str, *tofree;
260 set_config_value("sockets", "1");
261 set_config_value("cores", "1");
262 set_config_value("threads", "1");
263 set_config_value("cpus", "1");
267 tofree = str = strdup(opt);
269 errx(4, "Failed to allocate memory");
271 while ((cp = strsep(&str, ",")) != NULL) {
272 if (strncmp(cp, "cpus=", strlen("cpus=")) == 0)
273 set_config_value("cpus", cp + strlen("cpus="));
274 else if (strncmp(cp, "sockets=", strlen("sockets=")) == 0)
275 set_config_value("sockets", cp + strlen("sockets="));
276 else if (strncmp(cp, "cores=", strlen("cores=")) == 0)
277 set_config_value("cores", cp + strlen("cores="));
278 else if (strncmp(cp, "threads=", strlen("threads=")) == 0)
279 set_config_value("threads", cp + strlen("threads="));
280 else if (strchr(cp, '=') != NULL)
283 set_config_value("cpus", cp);
294 parse_int_value(const char *key, const char *value, int minval, int maxval)
300 lval = strtol(value, &cp, 0);
301 if (errno != 0 || *cp != '\0' || cp == value || lval < minval ||
303 errx(4, "Invalid value for %s: '%s'", key, value);
308 * Set the sockets, cores, threads, and guest_cpus variables based on
309 * the configured topology.
311 * The limits of UINT16_MAX are due to the types passed to
312 * vm_set_topology(). vmm.ko may enforce tighter limits.
321 value = get_config_value("cpus");
323 guest_ncpus = parse_int_value("cpus", value, 1, UINT16_MAX);
324 explicit_cpus = true;
327 explicit_cpus = false;
329 value = get_config_value("cores");
331 cpu_cores = parse_int_value("cores", value, 1, UINT16_MAX);
334 value = get_config_value("threads");
336 cpu_threads = parse_int_value("threads", value, 1, UINT16_MAX);
339 value = get_config_value("sockets");
341 cpu_sockets = parse_int_value("sockets", value, 1, UINT16_MAX);
343 cpu_sockets = guest_ncpus;
346 * Compute sockets * cores * threads avoiding overflow. The
347 * range check above insures these are 16 bit values.
349 ncpus = (uint64_t)cpu_sockets * cpu_cores * cpu_threads;
350 if (ncpus > UINT16_MAX)
351 errx(4, "Computed number of vCPUs too high: %ju",
355 if (guest_ncpus != (int)ncpus)
356 errx(4, "Topology (%d sockets, %d cores, %d threads) "
357 "does not match %d vCPUs",
358 cpu_sockets, cpu_cores, cpu_threads,
365 pincpu_parse(const char *opt)
372 if (sscanf(opt, "%d:%d", &vcpu, &pcpu) != 2) {
373 fprintf(stderr, "invalid format: %s\n", opt);
378 fprintf(stderr, "invalid vcpu '%d'\n", vcpu);
382 if (pcpu < 0 || pcpu >= CPU_SETSIZE) {
383 fprintf(stderr, "hostcpu '%d' outside valid range from "
384 "0 to %d\n", pcpu, CPU_SETSIZE - 1);
388 snprintf(key, sizeof(key), "vcpu.%d.cpuset", vcpu);
389 value = get_config_value(key);
391 if (asprintf(&newval, "%s%s%d", value != NULL ? value : "",
392 value != NULL ? "," : "", pcpu) == -1) {
393 perror("failed to build new cpuset string");
397 set_config_value(key, newval);
403 parse_cpuset(int vcpu, const char *list, cpuset_t *set)
410 token = __DECONST(char *, list);
412 pcpu = strtoul(token, &cp, 0);
414 errx(4, "invalid cpuset for vcpu %d: '%s'", vcpu, list);
415 if (pcpu < 0 || pcpu >= CPU_SETSIZE)
416 errx(4, "hostcpu '%d' outside valid range from 0 to %d",
417 pcpu, CPU_SETSIZE - 1);
423 errx(4, "Invalid hostcpu range %d-%d",
425 while (start < pcpu) {
435 errx(4, "invalid cpuset for vcpu %d: '%s'",
440 errx(4, "invalid cpuset for vcpu %d: '%s'", vcpu, list);
455 vcpumap = calloc(guest_ncpus, sizeof(*vcpumap));
456 for (vcpu = 0; vcpu < guest_ncpus; vcpu++) {
457 snprintf(key, sizeof(key), "vcpu.%d.cpuset", vcpu);
458 value = get_config_value(key);
461 vcpumap[vcpu] = malloc(sizeof(cpuset_t));
462 if (vcpumap[vcpu] == NULL)
463 err(4, "Failed to allocate cpuset for vcpu %d", vcpu);
464 parse_cpuset(vcpu, value, vcpumap[vcpu]);
469 vm_inject_fault(struct vcpu *vcpu, int vector, int errcode_valid,
472 int error, restart_instruction;
474 restart_instruction = 1;
476 error = vm_inject_exception(vcpu, vector, errcode_valid, errcode,
477 restart_instruction);
482 paddr_guest2host(struct vmctx *ctx, uintptr_t gaddr, size_t len)
485 return (vm_map_gpa(ctx, gaddr, len));
488 #ifdef BHYVE_SNAPSHOT
490 paddr_host2guest(struct vmctx *ctx, void *addr)
492 return (vm_rev_map_gpa(ctx, addr));
497 fbsdrun_virtio_msix(void)
500 return (get_config_bool_default("virtio_msix", true));
504 fbsdrun_start_thread(void *param)
506 char tname[MAXCOMLEN + 1];
507 struct vcpu_info *vi = param;
510 snprintf(tname, sizeof(tname), "vcpu %d", vi->vcpuid);
511 pthread_set_name_np(pthread_self(), tname);
513 if (vcpumap[vi->vcpuid] != NULL) {
514 error = pthread_setaffinity_np(pthread_self(),
515 sizeof(cpuset_t), vcpumap[vi->vcpuid]);
519 #ifdef BHYVE_SNAPSHOT
520 checkpoint_cpu_add(vi->vcpuid);
522 gdb_cpu_add(vi->vcpu);
524 vm_loop(vi->ctx, vi->vcpu);
532 fbsdrun_addcpu(struct vcpu_info *vi)
537 error = vm_activate_cpu(vi->vcpu);
539 err(EX_OSERR, "could not activate CPU %d", vi->vcpuid);
541 CPU_SET_ATOMIC(vi->vcpuid, &cpumask);
543 vm_suspend_cpu(vi->vcpu);
545 error = pthread_create(&thr, NULL, fbsdrun_start_thread, vi);
550 fbsdrun_deletecpu(int vcpu)
552 static pthread_mutex_t resetcpu_mtx = PTHREAD_MUTEX_INITIALIZER;
553 static pthread_cond_t resetcpu_cond = PTHREAD_COND_INITIALIZER;
555 pthread_mutex_lock(&resetcpu_mtx);
556 if (!CPU_ISSET(vcpu, &cpumask)) {
557 fprintf(stderr, "Attempting to delete unknown cpu %d\n", vcpu);
561 CPU_CLR(vcpu, &cpumask);
564 pthread_cond_signal(&resetcpu_cond);
565 pthread_mutex_unlock(&resetcpu_mtx);
570 while (!CPU_EMPTY(&cpumask)) {
571 pthread_cond_wait(&resetcpu_cond, &resetcpu_mtx);
573 pthread_mutex_unlock(&resetcpu_mtx);
577 vmexit_inout(struct vmctx *ctx, struct vcpu *vcpu, struct vm_run *vmrun)
583 vme = vmrun->vm_exit;
584 port = vme->u.inout.port;
585 bytes = vme->u.inout.bytes;
586 in = vme->u.inout.in;
588 error = emulate_inout(ctx, vcpu, vme);
590 fprintf(stderr, "Unhandled %s%c 0x%04x at 0x%lx\n",
592 bytes == 1 ? 'b' : (bytes == 2 ? 'w' : 'l'),
594 return (VMEXIT_ABORT);
596 return (VMEXIT_CONTINUE);
601 vmexit_rdmsr(struct vmctx *ctx __unused, struct vcpu *vcpu,
602 struct vm_run *vmrun)
609 vme = vmrun->vm_exit;
612 error = emulate_rdmsr(vcpu, vme->u.msr.code, &val);
614 fprintf(stderr, "rdmsr to register %#x on vcpu %d\n",
615 vme->u.msr.code, vcpu_id(vcpu));
616 if (get_config_bool("x86.strictmsr")) {
618 return (VMEXIT_CONTINUE);
623 error = vm_set_register(vcpu, VM_REG_GUEST_RAX, eax);
627 error = vm_set_register(vcpu, VM_REG_GUEST_RDX, edx);
630 return (VMEXIT_CONTINUE);
634 vmexit_wrmsr(struct vmctx *ctx __unused, struct vcpu *vcpu,
635 struct vm_run *vmrun)
640 vme = vmrun->vm_exit;
642 error = emulate_wrmsr(vcpu, vme->u.msr.code, vme->u.msr.wval);
644 fprintf(stderr, "wrmsr to register %#x(%#lx) on vcpu %d\n",
645 vme->u.msr.code, vme->u.msr.wval, vcpu_id(vcpu));
646 if (get_config_bool("x86.strictmsr")) {
648 return (VMEXIT_CONTINUE);
651 return (VMEXIT_CONTINUE);
654 #define DEBUG_EPT_MISCONFIG
655 #ifdef DEBUG_EPT_MISCONFIG
656 #define VMCS_GUEST_PHYSICAL_ADDRESS 0x00002400
658 static uint64_t ept_misconfig_gpa, ept_misconfig_pte[4];
659 static int ept_misconfig_ptenum;
663 vmexit_vmx_desc(uint32_t exit_reason)
666 if (exit_reason >= nitems(vmx_exit_reason_desc) ||
667 vmx_exit_reason_desc[exit_reason] == NULL)
669 return (vmx_exit_reason_desc[exit_reason]);
673 vmexit_vmx(struct vmctx *ctx, struct vcpu *vcpu, struct vm_run *vmrun)
677 vme = vmrun->vm_exit;
679 fprintf(stderr, "vm exit[%d]\n", vcpu_id(vcpu));
680 fprintf(stderr, "\treason\t\tVMX\n");
681 fprintf(stderr, "\trip\t\t0x%016lx\n", vme->rip);
682 fprintf(stderr, "\tinst_length\t%d\n", vme->inst_length);
683 fprintf(stderr, "\tstatus\t\t%d\n", vme->u.vmx.status);
684 fprintf(stderr, "\texit_reason\t%u (%s)\n", vme->u.vmx.exit_reason,
685 vmexit_vmx_desc(vme->u.vmx.exit_reason));
686 fprintf(stderr, "\tqualification\t0x%016lx\n",
687 vme->u.vmx.exit_qualification);
688 fprintf(stderr, "\tinst_type\t\t%d\n", vme->u.vmx.inst_type);
689 fprintf(stderr, "\tinst_error\t\t%d\n", vme->u.vmx.inst_error);
690 #ifdef DEBUG_EPT_MISCONFIG
691 if (vme->u.vmx.exit_reason == EXIT_REASON_EPT_MISCONFIG) {
692 vm_get_register(vcpu,
693 VMCS_IDENT(VMCS_GUEST_PHYSICAL_ADDRESS),
695 vm_get_gpa_pmap(ctx, ept_misconfig_gpa, ept_misconfig_pte,
696 &ept_misconfig_ptenum);
697 fprintf(stderr, "\tEPT misconfiguration:\n");
698 fprintf(stderr, "\t\tGPA: %#lx\n", ept_misconfig_gpa);
699 fprintf(stderr, "\t\tPTE(%d): %#lx %#lx %#lx %#lx\n",
700 ept_misconfig_ptenum, ept_misconfig_pte[0],
701 ept_misconfig_pte[1], ept_misconfig_pte[2],
702 ept_misconfig_pte[3]);
704 #endif /* DEBUG_EPT_MISCONFIG */
705 return (VMEXIT_ABORT);
709 vmexit_svm(struct vmctx *ctx __unused, struct vcpu *vcpu, struct vm_run *vmrun)
713 vme = vmrun->vm_exit;
715 fprintf(stderr, "vm exit[%d]\n", vcpu_id(vcpu));
716 fprintf(stderr, "\treason\t\tSVM\n");
717 fprintf(stderr, "\trip\t\t0x%016lx\n", vme->rip);
718 fprintf(stderr, "\tinst_length\t%d\n", vme->inst_length);
719 fprintf(stderr, "\texitcode\t%#lx\n", vme->u.svm.exitcode);
720 fprintf(stderr, "\texitinfo1\t%#lx\n", vme->u.svm.exitinfo1);
721 fprintf(stderr, "\texitinfo2\t%#lx\n", vme->u.svm.exitinfo2);
722 return (VMEXIT_ABORT);
726 vmexit_bogus(struct vmctx *ctx __unused, struct vcpu *vcpu __unused,
727 struct vm_run *vmrun)
729 assert(vmrun->vm_exit->inst_length == 0);
731 return (VMEXIT_CONTINUE);
735 vmexit_reqidle(struct vmctx *ctx __unused, struct vcpu *vcpu __unused,
736 struct vm_run *vmrun)
738 assert(vmrun->vm_exit->inst_length == 0);
740 return (VMEXIT_CONTINUE);
744 vmexit_hlt(struct vmctx *ctx __unused, struct vcpu *vcpu __unused,
745 struct vm_run *vmrun __unused)
748 * Just continue execution with the next instruction. We use
749 * the HLT VM exit as a way to be friendly with the host
752 return (VMEXIT_CONTINUE);
756 vmexit_pause(struct vmctx *ctx __unused, struct vcpu *vcpu __unused,
757 struct vm_run *vmrun __unused)
759 return (VMEXIT_CONTINUE);
763 vmexit_mtrap(struct vmctx *ctx __unused, struct vcpu *vcpu,
764 struct vm_run *vmrun)
766 assert(vmrun->vm_exit->inst_length == 0);
768 #ifdef BHYVE_SNAPSHOT
769 checkpoint_cpu_suspend(vcpu_id(vcpu));
772 #ifdef BHYVE_SNAPSHOT
773 checkpoint_cpu_resume(vcpu_id(vcpu));
776 return (VMEXIT_CONTINUE);
780 vmexit_inst_emul(struct vmctx *ctx __unused, struct vcpu *vcpu,
781 struct vm_run *vmrun)
786 enum vm_cpu_mode mode;
788 vme = vmrun->vm_exit;
790 vie = &vme->u.inst_emul.vie;
793 * Attempt to decode in userspace as a fallback. This allows
794 * updating instruction decode in bhyve without rebooting the
795 * kernel (rapid prototyping), albeit with much slower
799 mode = vme->u.inst_emul.paging.cpu_mode;
800 cs_d = vme->u.inst_emul.cs_d;
801 if (vmm_decode_instruction(mode, cs_d, vie) != 0)
803 if (vm_set_register(vcpu, VM_REG_GUEST_RIP,
804 vme->rip + vie->num_processed) != 0)
808 err = emulate_mem(vcpu, vme->u.inst_emul.gpa, vie,
809 &vme->u.inst_emul.paging);
812 EPRINTLN("Unhandled memory access to 0x%lx\n",
813 vme->u.inst_emul.gpa);
818 return (VMEXIT_CONTINUE);
821 fprintf(stderr, "Failed to emulate instruction sequence [ ");
822 for (i = 0; i < vie->num_valid; i++)
823 fprintf(stderr, "%02x", vie->inst[i]);
824 FPRINTLN(stderr, " ] at 0x%lx", vme->rip);
825 return (VMEXIT_ABORT);
829 vmexit_suspend(struct vmctx *ctx, struct vcpu *vcpu, struct vm_run *vmrun)
832 enum vm_suspend_how how;
833 int vcpuid = vcpu_id(vcpu);
835 vme = vmrun->vm_exit;
837 how = vme->u.suspended.how;
839 fbsdrun_deletecpu(vcpuid);
842 case VM_SUSPEND_RESET:
844 case VM_SUSPEND_POWEROFF:
845 if (get_config_bool_default("destroy_on_poweroff", false))
848 case VM_SUSPEND_HALT:
850 case VM_SUSPEND_TRIPLEFAULT:
853 fprintf(stderr, "vmexit_suspend: invalid reason %d\n", how);
856 return (0); /* NOTREACHED */
860 vmexit_debug(struct vmctx *ctx __unused, struct vcpu *vcpu,
861 struct vm_run *vmrun __unused)
864 #ifdef BHYVE_SNAPSHOT
865 checkpoint_cpu_suspend(vcpu_id(vcpu));
867 gdb_cpu_suspend(vcpu);
868 #ifdef BHYVE_SNAPSHOT
869 checkpoint_cpu_resume(vcpu_id(vcpu));
872 * XXX-MJ sleep for a short period to avoid chewing up the CPU in the
873 * window between activation of the vCPU thread and the STARTUP IPI.
876 return (VMEXIT_CONTINUE);
880 vmexit_breakpoint(struct vmctx *ctx __unused, struct vcpu *vcpu,
881 struct vm_run *vmrun)
883 gdb_cpu_breakpoint(vcpu, vmrun->vm_exit);
884 return (VMEXIT_CONTINUE);
888 vmexit_ipi(struct vmctx *ctx __unused, struct vcpu *vcpu __unused,
889 struct vm_run *vmrun)
896 dmask = vmrun->cpuset;
897 vme = vmrun->vm_exit;
899 switch (vme->u.ipi.mode) {
900 case APIC_DELMODE_INIT:
901 CPU_FOREACH_ISSET(i, dmask) {
902 error = vm_suspend_cpu(vcpu_info[i].vcpu);
904 warnx("%s: failed to suspend cpu %d\n",
910 case APIC_DELMODE_STARTUP:
911 CPU_FOREACH_ISSET(i, dmask) {
912 spinup_ap(vcpu_info[i].vcpu,
913 vme->u.ipi.vector << PAGE_SHIFT);
924 static const vmexit_handler_t handler[VM_EXITCODE_MAX] = {
925 [VM_EXITCODE_INOUT] = vmexit_inout,
926 [VM_EXITCODE_INOUT_STR] = vmexit_inout,
927 [VM_EXITCODE_VMX] = vmexit_vmx,
928 [VM_EXITCODE_SVM] = vmexit_svm,
929 [VM_EXITCODE_BOGUS] = vmexit_bogus,
930 [VM_EXITCODE_REQIDLE] = vmexit_reqidle,
931 [VM_EXITCODE_RDMSR] = vmexit_rdmsr,
932 [VM_EXITCODE_WRMSR] = vmexit_wrmsr,
933 [VM_EXITCODE_MTRAP] = vmexit_mtrap,
934 [VM_EXITCODE_INST_EMUL] = vmexit_inst_emul,
935 [VM_EXITCODE_SUSPENDED] = vmexit_suspend,
936 [VM_EXITCODE_TASK_SWITCH] = vmexit_task_switch,
937 [VM_EXITCODE_DEBUG] = vmexit_debug,
938 [VM_EXITCODE_BPT] = vmexit_breakpoint,
939 [VM_EXITCODE_IPI] = vmexit_ipi,
940 [VM_EXITCODE_HLT] = vmexit_hlt,
941 [VM_EXITCODE_PAUSE] = vmexit_pause,
945 vm_loop(struct vmctx *ctx, struct vcpu *vcpu)
950 enum vm_exitcode exitcode;
951 cpuset_t active_cpus, dmask;
953 error = vm_active_cpus(ctx, &active_cpus);
954 assert(CPU_ISSET(vcpu_id(vcpu), &active_cpus));
956 vmrun.vm_exit = &vme;
957 vmrun.cpuset = &dmask;
958 vmrun.cpusetsize = sizeof(dmask);
961 error = vm_run(vcpu, &vmrun);
965 exitcode = vme.exitcode;
966 if (exitcode >= VM_EXITCODE_MAX || handler[exitcode] == NULL) {
967 fprintf(stderr, "vm_loop: unexpected exitcode 0x%x\n",
972 rc = (*handler[exitcode])(ctx, vcpu, &vmrun);
975 case VMEXIT_CONTINUE:
983 fprintf(stderr, "vm_run error %d, errno %d\n", error, errno);
987 num_vcpus_allowed(struct vmctx *ctx, struct vcpu *vcpu)
989 uint16_t sockets, cores, threads, maxcpus;
993 * The guest is allowed to spinup more than one processor only if the
994 * UNRESTRICTED_GUEST capability is available.
996 error = vm_get_capability(vcpu, VM_CAP_UNRESTRICTED_GUEST, &tmp);
1000 error = vm_get_topology(ctx, &sockets, &cores, &threads, &maxcpus);
1008 fbsdrun_set_capabilities(struct vcpu *vcpu)
1012 if (get_config_bool_default("x86.vmexit_on_hlt", false)) {
1013 err = vm_get_capability(vcpu, VM_CAP_HALT_EXIT, &tmp);
1015 fprintf(stderr, "VM exit on HLT not supported\n");
1018 vm_set_capability(vcpu, VM_CAP_HALT_EXIT, 1);
1021 if (get_config_bool_default("x86.vmexit_on_pause", false)) {
1023 * pause exit support required for this mode
1025 err = vm_get_capability(vcpu, VM_CAP_PAUSE_EXIT, &tmp);
1028 "SMP mux requested, no pause support\n");
1031 vm_set_capability(vcpu, VM_CAP_PAUSE_EXIT, 1);
1034 if (get_config_bool_default("x86.x2apic", false))
1035 err = vm_set_x2apic_state(vcpu, X2APIC_ENABLED);
1037 err = vm_set_x2apic_state(vcpu, X2APIC_DISABLED);
1040 fprintf(stderr, "Unable to set x2apic state (%d)\n", err);
1044 vm_set_capability(vcpu, VM_CAP_ENABLE_INVPCID, 1);
1046 err = vm_set_capability(vcpu, VM_CAP_IPI_EXIT, 1);
1050 static struct vmctx *
1051 do_open(const char *vmname)
1055 bool reinit, romboot;
1057 reinit = romboot = false;
1062 error = vm_create(vmname);
1064 if (errno == EEXIST) {
1069 * The virtual machine has been setup by the
1070 * userspace bootloader.
1074 perror("vm_create");
1080 * If the virtual machine was just created then a
1081 * bootrom must be configured to boot it.
1083 fprintf(stderr, "virtual machine cannot be booted\n");
1088 ctx = vm_open(vmname);
1094 #ifndef WITHOUT_CAPSICUM
1095 if (vm_limit_rights(ctx) != 0)
1096 err(EX_OSERR, "vm_limit_rights");
1100 error = vm_reinit(ctx);
1102 perror("vm_reinit");
1106 error = vm_set_topology(ctx, cpu_sockets, cpu_cores, cpu_threads, 0);
1108 errx(EX_OSERR, "vm_set_topology");
1113 spinup_vcpu(struct vcpu_info *vi, bool bsp)
1118 fbsdrun_set_capabilities(vi->vcpu);
1121 * Enable the 'unrestricted guest' mode for APs.
1123 * APs startup in power-on 16-bit mode.
1125 error = vm_set_capability(vi->vcpu, VM_CAP_UNRESTRICTED_GUEST, 1);
1133 parse_config_option(const char *option)
1138 value = strchr(option, '=');
1139 if (value == NULL || value[1] == '\0')
1141 path = strndup(option, value - option);
1143 err(4, "Failed to allocate memory");
1144 set_config_value(path, value + 1);
1149 parse_simple_config_file(const char *path)
1154 unsigned int lineno;
1156 fp = fopen(path, "r");
1158 err(4, "Failed to open configuration file %s", path);
1162 for (lineno = 1; getline(&line, &linecap, fp) > 0; lineno++) {
1163 if (*line == '#' || *line == '\n')
1165 cp = strchr(line, '\n');
1168 if (!parse_config_option(line))
1169 errx(4, "%s line %u: invalid config option '%s'", path,
1177 parse_gdb_options(const char *opt)
1182 if (opt[0] == 'w') {
1183 set_config_bool("gdb.wait", true);
1187 colon = strrchr(opt, ':');
1188 if (colon == NULL) {
1194 set_config_value("gdb.address", opt);
1197 set_config_value("gdb.port", sport);
1204 set_config_bool("acpi_tables", false);
1205 set_config_bool("acpi_tables_in_memory", true);
1206 set_config_value("memory.size", "256M");
1207 set_config_bool("x86.strictmsr", true);
1208 set_config_value("lpc.fwcfg", "bhyve");
1212 main(int argc, char *argv[])
1215 int max_vcpus, memflags;
1218 struct qemu_fwcfg_item *e820_fwcfg_item;
1220 const char *optstr, *value, *vmname;
1221 #ifdef BHYVE_SNAPSHOT
1223 struct restore_state rstate;
1225 restore_file = NULL;
1230 progname = basename(argv[0]);
1232 #ifdef BHYVE_SNAPSHOT
1233 optstr = "aehuwxACDHIPSWYk:f:o:p:G:c:s:m:l:K:U:r:";
1235 optstr = "aehuwxACDHIPSWYk:f:o:p:G:c:s:m:l:K:U:";
1237 while ((c = getopt(argc, argv, optstr)) != -1) {
1240 set_config_bool("x86.x2apic", false);
1243 set_config_bool("acpi_tables", true);
1246 set_config_bool("destroy_on_poweroff", true);
1249 if (pincpu_parse(optarg) != 0) {
1250 errx(EX_USAGE, "invalid vcpu pinning "
1251 "configuration '%s'", optarg);
1255 if (topology_parse(optarg) != 0) {
1256 errx(EX_USAGE, "invalid cpu topology "
1261 set_config_bool("memory.guest_in_core", true);
1264 if (qemu_fwcfg_parse_cmdline_arg(optarg) != 0) {
1265 errx(EX_USAGE, "invalid fwcfg item '%s'", optarg);
1269 parse_gdb_options(optarg);
1272 parse_simple_config_file(optarg);
1275 set_config_value("keyboard.layout", optarg);
1278 if (strncmp(optarg, "help", strlen(optarg)) == 0) {
1279 lpc_print_supported_devices();
1281 } else if (lpc_device_parse(optarg) != 0) {
1282 errx(EX_USAGE, "invalid lpc device "
1283 "configuration '%s'", optarg);
1286 #ifdef BHYVE_SNAPSHOT
1288 restore_file = optarg;
1292 if (strncmp(optarg, "help", strlen(optarg)) == 0) {
1293 pci_print_supported_devices();
1295 } else if (pci_parse_slot(optarg) != 0)
1300 set_config_bool("memory.wired", true);
1303 set_config_value("memory.size", optarg);
1306 if (!parse_config_option(optarg))
1307 errx(EX_USAGE, "invalid configuration option '%s'", optarg);
1310 set_config_bool("x86.vmexit_on_hlt", true);
1314 * The "-I" option was used to add an ioapic to the
1317 * An ioapic is now provided unconditionally for each
1318 * virtual machine and this option is now deprecated.
1322 set_config_bool("x86.vmexit_on_pause", true);
1325 set_config_bool("x86.strictio", true);
1328 set_config_bool("rtc.use_localtime", false);
1331 set_config_value("uuid", optarg);
1334 set_config_bool("x86.strictmsr", false);
1337 set_config_bool("virtio_msix", false);
1340 set_config_bool("x86.x2apic", true);
1343 set_config_bool("x86.mptable", false);
1357 #ifdef BHYVE_SNAPSHOT
1358 if (restore_file != NULL) {
1359 error = load_restore_file(restore_file, &rstate);
1361 fprintf(stderr, "Failed to read checkpoint info from "
1362 "file: '%s'.\n", restore_file);
1365 vmname = lookup_vmname(&rstate);
1367 set_config_value("name", vmname);
1372 set_config_value("name", argv[0]);
1374 vmname = get_config_value("name");
1378 if (get_config_bool_default("config.dump", false)) {
1386 value = get_config_value("memory.size");
1387 error = vm_parse_memsize(value, &memsize);
1389 errx(EX_USAGE, "invalid memsize '%s'", value);
1391 ctx = do_open(vmname);
1393 #ifdef BHYVE_SNAPSHOT
1394 if (restore_file != NULL) {
1395 guest_ncpus = lookup_guest_ncpus(&rstate);
1396 memflags = lookup_memflags(&rstate);
1397 memsize = lookup_memsize(&rstate);
1400 if (guest_ncpus < 1) {
1401 fprintf(stderr, "Invalid guest vCPUs (%d)\n", guest_ncpus);
1406 bsp = vm_vcpu_open(ctx, BSP);
1407 max_vcpus = num_vcpus_allowed(ctx, bsp);
1408 if (guest_ncpus > max_vcpus) {
1409 fprintf(stderr, "%d vCPUs requested but only %d available\n",
1410 guest_ncpus, max_vcpus);
1414 fbsdrun_set_capabilities(bsp);
1416 /* Allocate per-VCPU resources. */
1417 vcpu_info = calloc(guest_ncpus, sizeof(*vcpu_info));
1418 for (int vcpuid = 0; vcpuid < guest_ncpus; vcpuid++) {
1419 vcpu_info[vcpuid].ctx = ctx;
1420 vcpu_info[vcpuid].vcpuid = vcpuid;
1422 vcpu_info[vcpuid].vcpu = bsp;
1424 vcpu_info[vcpuid].vcpu = vm_vcpu_open(ctx, vcpuid);
1428 if (get_config_bool_default("memory.wired", false))
1429 memflags |= VM_MEM_F_WIRED;
1430 if (get_config_bool_default("memory.guest_in_core", false))
1431 memflags |= VM_MEM_F_INCORE;
1432 vm_set_memflags(ctx, memflags);
1433 error = vm_setup_memory(ctx, memsize, VM_MMAP_ALL);
1435 fprintf(stderr, "Unable to setup memory (%d)\n", errno);
1441 fprintf(stderr, "init_msr error %d", error);
1445 init_mem(guest_ncpus);
1456 if (qemu_fwcfg_init(ctx) != 0) {
1457 fprintf(stderr, "qemu fwcfg initialization error");
1461 if (qemu_fwcfg_add_file("opt/bhyve/hw.ncpu", sizeof(guest_ncpus),
1462 &guest_ncpus) != 0) {
1463 fprintf(stderr, "Could not add qemu fwcfg opt/bhyve/hw.ncpu");
1467 if (e820_init(ctx) != 0) {
1468 fprintf(stderr, "Unable to setup E820");
1473 * Exit if a device emulation finds an error in its initialization
1475 if (init_pci(ctx) != 0) {
1476 perror("device emulation initialization error");
1479 if (init_tpm(ctx) != 0) {
1480 fprintf(stderr, "Failed to init TPM device");
1485 * Initialize after PCI, to allow a bootrom file to reserve the high
1488 if (get_config_bool("acpi_tables"))
1493 if (lpc_bootrom()) {
1494 if (vm_set_capability(bsp, VM_CAP_UNRESTRICTED_GUEST, 1)) {
1495 fprintf(stderr, "ROM boot failed: unrestricted guest "
1496 "capability not available\n");
1499 error = vcpu_reset(bsp);
1506 for (int vcpuid = 0; vcpuid < guest_ncpus; vcpuid++)
1507 spinup_vcpu(&vcpu_info[vcpuid], vcpuid == BSP);
1509 #ifdef BHYVE_SNAPSHOT
1510 if (restore_file != NULL) {
1511 fprintf(stdout, "Pausing pci devs...\r\n");
1512 if (vm_pause_devices() != 0) {
1513 fprintf(stderr, "Failed to pause PCI device state.\n");
1517 fprintf(stdout, "Restoring vm mem...\r\n");
1518 if (restore_vm_mem(ctx, &rstate) != 0) {
1519 fprintf(stderr, "Failed to restore VM memory.\n");
1523 fprintf(stdout, "Restoring pci devs...\r\n");
1524 if (vm_restore_devices(&rstate) != 0) {
1525 fprintf(stderr, "Failed to restore PCI device state.\n");
1529 fprintf(stdout, "Restoring kernel structs...\r\n");
1530 if (vm_restore_kern_structs(ctx, &rstate) != 0) {
1531 fprintf(stderr, "Failed to restore kernel structs.\n");
1535 fprintf(stdout, "Resuming pci devs...\r\n");
1536 if (vm_resume_devices() != 0) {
1537 fprintf(stderr, "Failed to resume PCI device state.\n");
1544 * build the guest tables, MP etc.
1546 if (get_config_bool_default("x86.mptable", true)) {
1547 error = mptable_build(ctx, guest_ncpus);
1549 perror("error to build the guest tables");
1554 error = smbios_build(ctx);
1558 if (get_config_bool("acpi_tables")) {
1559 error = acpi_build(ctx, guest_ncpus);
1563 e820_fwcfg_item = e820_get_fwcfg_item();
1564 if (e820_fwcfg_item == NULL) {
1565 fprintf(stderr, "invalid e820 table");
1568 if (qemu_fwcfg_add_file("etc/e820", e820_fwcfg_item->size,
1569 e820_fwcfg_item->data) != 0) {
1570 fprintf(stderr, "could not add qemu fwcfg etc/e820");
1573 free(e820_fwcfg_item);
1575 if (lpc_bootrom() && strcmp(lpc_fwcfg(), "bhyve") == 0) {
1580 * Change the proc title to include the VM name.
1582 setproctitle("%s", vmname);
1584 #ifdef BHYVE_SNAPSHOT
1585 /* initialize mutex/cond variables */
1589 * checkpointing thread for communication with bhyvectl
1591 if (init_checkpoint_thread(ctx) != 0)
1592 errx(EX_OSERR, "Failed to start checkpoint thread");
1595 #ifndef WITHOUT_CAPSICUM
1596 caph_cache_catpages();
1598 if (caph_limit_stdout() == -1 || caph_limit_stderr() == -1)
1599 errx(EX_OSERR, "Unable to apply rights for sandbox");
1601 if (caph_enter() == -1)
1602 errx(EX_OSERR, "cap_enter() failed");
1605 #ifdef BHYVE_SNAPSHOT
1606 if (restore_file != NULL) {
1607 destroy_restore_state(&rstate);
1608 if (vm_restore_time(ctx) < 0)
1609 err(EX_OSERR, "Unable to restore time");
1611 for (int vcpuid = 0; vcpuid < guest_ncpus; vcpuid++)
1612 vm_resume_cpu(vcpu_info[vcpuid].vcpu);
1618 * Head off to the main event dispatch loop