2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
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>
97 #include "kernemu_dev.h"
101 #include "pci_emul.h"
104 #include "qemu_fwcfg.h"
105 #include "smbiostbl.h"
106 #ifdef BHYVE_SNAPSHOT
107 #include "snapshot.h"
110 #include "spinup_ap.h"
114 #define GUEST_NIO_PORT 0x488 /* guest upcalls via i/o port */
116 #define MB (1024UL * 1024)
117 #define GB (1024UL * MB)
119 static const char * const vmx_exit_reason_desc[] = {
120 [EXIT_REASON_EXCEPTION] = "Exception or non-maskable interrupt (NMI)",
121 [EXIT_REASON_EXT_INTR] = "External interrupt",
122 [EXIT_REASON_TRIPLE_FAULT] = "Triple fault",
123 [EXIT_REASON_INIT] = "INIT signal",
124 [EXIT_REASON_SIPI] = "Start-up IPI (SIPI)",
125 [EXIT_REASON_IO_SMI] = "I/O system-management interrupt (SMI)",
126 [EXIT_REASON_SMI] = "Other SMI",
127 [EXIT_REASON_INTR_WINDOW] = "Interrupt window",
128 [EXIT_REASON_NMI_WINDOW] = "NMI window",
129 [EXIT_REASON_TASK_SWITCH] = "Task switch",
130 [EXIT_REASON_CPUID] = "CPUID",
131 [EXIT_REASON_GETSEC] = "GETSEC",
132 [EXIT_REASON_HLT] = "HLT",
133 [EXIT_REASON_INVD] = "INVD",
134 [EXIT_REASON_INVLPG] = "INVLPG",
135 [EXIT_REASON_RDPMC] = "RDPMC",
136 [EXIT_REASON_RDTSC] = "RDTSC",
137 [EXIT_REASON_RSM] = "RSM",
138 [EXIT_REASON_VMCALL] = "VMCALL",
139 [EXIT_REASON_VMCLEAR] = "VMCLEAR",
140 [EXIT_REASON_VMLAUNCH] = "VMLAUNCH",
141 [EXIT_REASON_VMPTRLD] = "VMPTRLD",
142 [EXIT_REASON_VMPTRST] = "VMPTRST",
143 [EXIT_REASON_VMREAD] = "VMREAD",
144 [EXIT_REASON_VMRESUME] = "VMRESUME",
145 [EXIT_REASON_VMWRITE] = "VMWRITE",
146 [EXIT_REASON_VMXOFF] = "VMXOFF",
147 [EXIT_REASON_VMXON] = "VMXON",
148 [EXIT_REASON_CR_ACCESS] = "Control-register accesses",
149 [EXIT_REASON_DR_ACCESS] = "MOV DR",
150 [EXIT_REASON_INOUT] = "I/O instruction",
151 [EXIT_REASON_RDMSR] = "RDMSR",
152 [EXIT_REASON_WRMSR] = "WRMSR",
153 [EXIT_REASON_INVAL_VMCS] =
154 "VM-entry failure due to invalid guest state",
155 [EXIT_REASON_INVAL_MSR] = "VM-entry failure due to MSR loading",
156 [EXIT_REASON_MWAIT] = "MWAIT",
157 [EXIT_REASON_MTF] = "Monitor trap flag",
158 [EXIT_REASON_MONITOR] = "MONITOR",
159 [EXIT_REASON_PAUSE] = "PAUSE",
160 [EXIT_REASON_MCE_DURING_ENTRY] =
161 "VM-entry failure due to machine-check event",
162 [EXIT_REASON_TPR] = "TPR below threshold",
163 [EXIT_REASON_APIC_ACCESS] = "APIC access",
164 [EXIT_REASON_VIRTUALIZED_EOI] = "Virtualized EOI",
165 [EXIT_REASON_GDTR_IDTR] = "Access to GDTR or IDTR",
166 [EXIT_REASON_LDTR_TR] = "Access to LDTR or TR",
167 [EXIT_REASON_EPT_FAULT] = "EPT violation",
168 [EXIT_REASON_EPT_MISCONFIG] = "EPT misconfiguration",
169 [EXIT_REASON_INVEPT] = "INVEPT",
170 [EXIT_REASON_RDTSCP] = "RDTSCP",
171 [EXIT_REASON_VMX_PREEMPT] = "VMX-preemption timer expired",
172 [EXIT_REASON_INVVPID] = "INVVPID",
173 [EXIT_REASON_WBINVD] = "WBINVD",
174 [EXIT_REASON_XSETBV] = "XSETBV",
175 [EXIT_REASON_APIC_WRITE] = "APIC write",
176 [EXIT_REASON_RDRAND] = "RDRAND",
177 [EXIT_REASON_INVPCID] = "INVPCID",
178 [EXIT_REASON_VMFUNC] = "VMFUNC",
179 [EXIT_REASON_ENCLS] = "ENCLS",
180 [EXIT_REASON_RDSEED] = "RDSEED",
181 [EXIT_REASON_PM_LOG_FULL] = "Page-modification log full",
182 [EXIT_REASON_XSAVES] = "XSAVES",
183 [EXIT_REASON_XRSTORS] = "XRSTORS"
186 typedef int (*vmexit_handler_t)(struct vmctx *, struct vcpu *, struct vm_exit *);
189 uint16_t cpu_cores, cpu_sockets, cpu_threads;
193 static char *progname;
194 static const int BSP = 0;
196 static cpuset_t cpumask;
198 static void vm_loop(struct vmctx *ctx, struct vcpu *vcpu);
200 static struct bhyvestats {
201 uint64_t vmexit_bogus;
202 uint64_t vmexit_reqidle;
204 uint64_t vmexit_pause;
205 uint64_t vmexit_mtrap;
206 uint64_t vmexit_inst_emul;
207 uint64_t cpu_switch_rotate;
208 uint64_t cpu_switch_direct;
211 static struct vcpu_info {
217 static cpuset_t **vcpumap;
224 "Usage: %s [-AaCDeHhPSuWwxY]\n"
225 " %*s [-c [[cpus=]numcpus][,sockets=n][,cores=n][,threads=n]]\n"
226 " %*s [-G port] [-k config_file] [-l lpc] [-m mem] [-o var=value]\n"
227 " %*s [-p vcpu:hostcpu] [-r file] [-s pci] [-U uuid] vmname\n"
228 " -A: create ACPI tables\n"
229 " -a: local apic is in xAPIC mode (deprecated)\n"
230 " -C: include guest memory in core file\n"
231 " -c: number of CPUs and/or topology specification\n"
232 " -D: destroy on power-off\n"
233 " -e: exit on unhandled I/O access\n"
234 " -G: start a debug server\n"
235 " -H: vmexit from the guest on HLT\n"
237 " -k: key=value flat config file\n"
238 " -K: PS2 keyboard layout\n"
239 " -l: LPC device configuration\n"
241 " -o: set config 'var' to 'value'\n"
242 " -P: vmexit from the guest on pause\n"
243 " -p: pin 'vcpu' to 'hostcpu'\n"
244 #ifdef BHYVE_SNAPSHOT
245 " -r: path to checkpoint file\n"
247 " -S: guest memory cannot be swapped\n"
248 " -s: <slot,driver,configinfo> PCI slot config\n"
250 " -u: RTC keeps UTC time\n"
251 " -W: force virtio to use single-vector MSI\n"
252 " -w: ignore unimplemented MSRs\n"
253 " -x: local APIC is in x2APIC mode\n"
254 " -Y: disable MPtable generation\n",
255 progname, (int)strlen(progname), "", (int)strlen(progname), "",
256 (int)strlen(progname), "");
262 * XXX This parser is known to have the following issues:
263 * 1. It accepts null key=value tokens ",," as setting "cpus" to an
266 * The acceptance of a null specification ('-c ""') is by design to match the
267 * manual page syntax specification, this results in a topology of 1 vCPU.
270 topology_parse(const char *opt)
272 char *cp, *str, *tofree;
275 set_config_value("sockets", "1");
276 set_config_value("cores", "1");
277 set_config_value("threads", "1");
278 set_config_value("cpus", "1");
282 tofree = str = strdup(opt);
284 errx(4, "Failed to allocate memory");
286 while ((cp = strsep(&str, ",")) != NULL) {
287 if (strncmp(cp, "cpus=", strlen("cpus=")) == 0)
288 set_config_value("cpus", cp + strlen("cpus="));
289 else if (strncmp(cp, "sockets=", strlen("sockets=")) == 0)
290 set_config_value("sockets", cp + strlen("sockets="));
291 else if (strncmp(cp, "cores=", strlen("cores=")) == 0)
292 set_config_value("cores", cp + strlen("cores="));
293 else if (strncmp(cp, "threads=", strlen("threads=")) == 0)
294 set_config_value("threads", cp + strlen("threads="));
295 #ifdef notyet /* Do not expose this until vmm.ko implements it */
296 else if (strncmp(cp, "maxcpus=", strlen("maxcpus=")) == 0)
297 set_config_value("maxcpus", cp + strlen("maxcpus="));
299 else if (strchr(cp, '=') != NULL)
302 set_config_value("cpus", cp);
313 parse_int_value(const char *key, const char *value, int minval, int maxval)
319 lval = strtol(value, &cp, 0);
320 if (errno != 0 || *cp != '\0' || cp == value || lval < minval ||
322 errx(4, "Invalid value for %s: '%s'", key, value);
327 * Set the sockets, cores, threads, and guest_cpus variables based on
328 * the configured topology.
330 * The limits of UINT16_MAX are due to the types passed to
331 * vm_set_topology(). vmm.ko may enforce tighter limits.
340 value = get_config_value("cpus");
342 guest_ncpus = parse_int_value("cpus", value, 1, UINT16_MAX);
343 explicit_cpus = true;
346 explicit_cpus = false;
348 value = get_config_value("cores");
350 cpu_cores = parse_int_value("cores", value, 1, UINT16_MAX);
353 value = get_config_value("threads");
355 cpu_threads = parse_int_value("threads", value, 1, UINT16_MAX);
358 value = get_config_value("sockets");
360 cpu_sockets = parse_int_value("sockets", value, 1, UINT16_MAX);
362 cpu_sockets = guest_ncpus;
365 * Compute sockets * cores * threads avoiding overflow. The
366 * range check above insures these are 16 bit values.
368 ncpus = (uint64_t)cpu_sockets * cpu_cores * cpu_threads;
369 if (ncpus > UINT16_MAX)
370 errx(4, "Computed number of vCPUs too high: %ju",
374 if (guest_ncpus != (int)ncpus)
375 errx(4, "Topology (%d sockets, %d cores, %d threads) "
376 "does not match %d vCPUs",
377 cpu_sockets, cpu_cores, cpu_threads,
384 pincpu_parse(const char *opt)
391 if (sscanf(opt, "%d:%d", &vcpu, &pcpu) != 2) {
392 fprintf(stderr, "invalid format: %s\n", opt);
397 fprintf(stderr, "invalid vcpu '%d'\n", vcpu);
401 if (pcpu < 0 || pcpu >= CPU_SETSIZE) {
402 fprintf(stderr, "hostcpu '%d' outside valid range from "
403 "0 to %d\n", pcpu, CPU_SETSIZE - 1);
407 snprintf(key, sizeof(key), "vcpu.%d.cpuset", vcpu);
408 value = get_config_value(key);
410 if (asprintf(&newval, "%s%s%d", value != NULL ? value : "",
411 value != NULL ? "," : "", pcpu) == -1) {
412 perror("failed to build new cpuset string");
416 set_config_value(key, newval);
422 parse_cpuset(int vcpu, const char *list, cpuset_t *set)
429 token = __DECONST(char *, list);
431 pcpu = strtoul(token, &cp, 0);
433 errx(4, "invalid cpuset for vcpu %d: '%s'", vcpu, list);
434 if (pcpu < 0 || pcpu >= CPU_SETSIZE)
435 errx(4, "hostcpu '%d' outside valid range from 0 to %d",
436 pcpu, CPU_SETSIZE - 1);
442 errx(4, "Invalid hostcpu range %d-%d",
444 while (start < pcpu) {
454 errx(4, "invalid cpuset for vcpu %d: '%s'",
459 errx(4, "invalid cpuset for vcpu %d: '%s'", vcpu, list);
474 vcpumap = calloc(guest_ncpus, sizeof(*vcpumap));
475 for (vcpu = 0; vcpu < guest_ncpus; vcpu++) {
476 snprintf(key, sizeof(key), "vcpu.%d.cpuset", vcpu);
477 value = get_config_value(key);
480 vcpumap[vcpu] = malloc(sizeof(cpuset_t));
481 if (vcpumap[vcpu] == NULL)
482 err(4, "Failed to allocate cpuset for vcpu %d", vcpu);
483 parse_cpuset(vcpu, value, vcpumap[vcpu]);
488 vm_inject_fault(struct vcpu *vcpu, int vector, int errcode_valid,
491 int error, restart_instruction;
493 restart_instruction = 1;
495 error = vm_inject_exception(vcpu, vector, errcode_valid, errcode,
496 restart_instruction);
501 paddr_guest2host(struct vmctx *ctx, uintptr_t gaddr, size_t len)
504 return (vm_map_gpa(ctx, gaddr, len));
507 #ifdef BHYVE_SNAPSHOT
509 paddr_host2guest(struct vmctx *ctx, void *addr)
511 return (vm_rev_map_gpa(ctx, addr));
516 fbsdrun_virtio_msix(void)
519 return (get_config_bool_default("virtio_msix", true));
523 fbsdrun_start_thread(void *param)
525 char tname[MAXCOMLEN + 1];
526 struct vcpu_info *vi = param;
529 snprintf(tname, sizeof(tname), "vcpu %d", vi->vcpuid);
530 pthread_set_name_np(pthread_self(), tname);
532 if (vcpumap[vi->vcpuid] != NULL) {
533 error = pthread_setaffinity_np(pthread_self(),
534 sizeof(cpuset_t), vcpumap[vi->vcpuid]);
538 #ifdef BHYVE_SNAPSHOT
539 checkpoint_cpu_add(vi->vcpuid);
541 gdb_cpu_add(vi->vcpu);
543 vm_loop(vi->ctx, vi->vcpu);
551 fbsdrun_addcpu(struct vcpu_info *vi)
556 error = vm_activate_cpu(vi->vcpu);
558 err(EX_OSERR, "could not activate CPU %d", vi->vcpuid);
560 CPU_SET_ATOMIC(vi->vcpuid, &cpumask);
562 vm_suspend_cpu(vi->vcpu);
564 error = pthread_create(&thr, NULL, fbsdrun_start_thread, vi);
569 fbsdrun_deletecpu(int vcpu)
572 if (!CPU_ISSET(vcpu, &cpumask)) {
573 fprintf(stderr, "Attempting to delete unknown cpu %d\n", vcpu);
577 CPU_CLR_ATOMIC(vcpu, &cpumask);
578 return (CPU_EMPTY(&cpumask));
582 vmexit_handle_notify(struct vmctx *ctx __unused, struct vcpu *vcpu __unused,
583 struct vm_exit *vme __unused, uint32_t eax __unused)
587 * put guest-driven debug here
590 return (VMEXIT_CONTINUE);
594 vmexit_inout(struct vmctx *ctx, struct vcpu *vcpu, struct vm_exit *vme)
597 int bytes, port, in, out;
599 port = vme->u.inout.port;
600 bytes = vme->u.inout.bytes;
601 in = vme->u.inout.in;
604 /* Extra-special case of host notifications */
605 if (out && port == GUEST_NIO_PORT) {
606 error = vmexit_handle_notify(ctx, vcpu, vme, vme->u.inout.eax);
610 error = emulate_inout(ctx, vcpu, vme);
612 fprintf(stderr, "Unhandled %s%c 0x%04x at 0x%lx\n",
614 bytes == 1 ? 'b' : (bytes == 2 ? 'w' : 'l'),
616 return (VMEXIT_ABORT);
618 return (VMEXIT_CONTINUE);
623 vmexit_rdmsr(struct vmctx *ctx __unused, struct vcpu *vcpu, struct vm_exit *vme)
630 error = emulate_rdmsr(vcpu, vme->u.msr.code, &val);
632 fprintf(stderr, "rdmsr to register %#x on vcpu %d\n",
633 vme->u.msr.code, vcpu_id(vcpu));
634 if (get_config_bool("x86.strictmsr")) {
636 return (VMEXIT_CONTINUE);
641 error = vm_set_register(vcpu, VM_REG_GUEST_RAX, eax);
645 error = vm_set_register(vcpu, VM_REG_GUEST_RDX, edx);
648 return (VMEXIT_CONTINUE);
652 vmexit_wrmsr(struct vmctx *ctx __unused, struct vcpu *vcpu, struct vm_exit *vme)
656 error = emulate_wrmsr(vcpu, vme->u.msr.code, vme->u.msr.wval);
658 fprintf(stderr, "wrmsr to register %#x(%#lx) on vcpu %d\n",
659 vme->u.msr.code, vme->u.msr.wval, vcpu_id(vcpu));
660 if (get_config_bool("x86.strictmsr")) {
662 return (VMEXIT_CONTINUE);
665 return (VMEXIT_CONTINUE);
668 #define DEBUG_EPT_MISCONFIG
669 #ifdef DEBUG_EPT_MISCONFIG
670 #define VMCS_GUEST_PHYSICAL_ADDRESS 0x00002400
672 static uint64_t ept_misconfig_gpa, ept_misconfig_pte[4];
673 static int ept_misconfig_ptenum;
677 vmexit_vmx_desc(uint32_t exit_reason)
680 if (exit_reason >= nitems(vmx_exit_reason_desc) ||
681 vmx_exit_reason_desc[exit_reason] == NULL)
683 return (vmx_exit_reason_desc[exit_reason]);
687 vmexit_vmx(struct vmctx *ctx, struct vcpu *vcpu, struct vm_exit *vme)
690 fprintf(stderr, "vm exit[%d]\n", vcpu_id(vcpu));
691 fprintf(stderr, "\treason\t\tVMX\n");
692 fprintf(stderr, "\trip\t\t0x%016lx\n", vme->rip);
693 fprintf(stderr, "\tinst_length\t%d\n", vme->inst_length);
694 fprintf(stderr, "\tstatus\t\t%d\n", vme->u.vmx.status);
695 fprintf(stderr, "\texit_reason\t%u (%s)\n", vme->u.vmx.exit_reason,
696 vmexit_vmx_desc(vme->u.vmx.exit_reason));
697 fprintf(stderr, "\tqualification\t0x%016lx\n",
698 vme->u.vmx.exit_qualification);
699 fprintf(stderr, "\tinst_type\t\t%d\n", vme->u.vmx.inst_type);
700 fprintf(stderr, "\tinst_error\t\t%d\n", vme->u.vmx.inst_error);
701 #ifdef DEBUG_EPT_MISCONFIG
702 if (vme->u.vmx.exit_reason == EXIT_REASON_EPT_MISCONFIG) {
703 vm_get_register(vcpu,
704 VMCS_IDENT(VMCS_GUEST_PHYSICAL_ADDRESS),
706 vm_get_gpa_pmap(ctx, ept_misconfig_gpa, ept_misconfig_pte,
707 &ept_misconfig_ptenum);
708 fprintf(stderr, "\tEPT misconfiguration:\n");
709 fprintf(stderr, "\t\tGPA: %#lx\n", ept_misconfig_gpa);
710 fprintf(stderr, "\t\tPTE(%d): %#lx %#lx %#lx %#lx\n",
711 ept_misconfig_ptenum, ept_misconfig_pte[0],
712 ept_misconfig_pte[1], ept_misconfig_pte[2],
713 ept_misconfig_pte[3]);
715 #endif /* DEBUG_EPT_MISCONFIG */
716 return (VMEXIT_ABORT);
720 vmexit_svm(struct vmctx *ctx __unused, struct vcpu *vcpu, struct vm_exit *vme)
723 fprintf(stderr, "vm exit[%d]\n", vcpu_id(vcpu));
724 fprintf(stderr, "\treason\t\tSVM\n");
725 fprintf(stderr, "\trip\t\t0x%016lx\n", vme->rip);
726 fprintf(stderr, "\tinst_length\t%d\n", vme->inst_length);
727 fprintf(stderr, "\texitcode\t%#lx\n", vme->u.svm.exitcode);
728 fprintf(stderr, "\texitinfo1\t%#lx\n", vme->u.svm.exitinfo1);
729 fprintf(stderr, "\texitinfo2\t%#lx\n", vme->u.svm.exitinfo2);
730 return (VMEXIT_ABORT);
734 vmexit_bogus(struct vmctx *ctx __unused, struct vcpu *vcpu __unused,
738 assert(vme->inst_length == 0);
740 stats.vmexit_bogus++;
742 return (VMEXIT_CONTINUE);
746 vmexit_reqidle(struct vmctx *ctx __unused, struct vcpu *vcpu __unused,
750 assert(vme->inst_length == 0);
752 stats.vmexit_reqidle++;
754 return (VMEXIT_CONTINUE);
758 vmexit_hlt(struct vmctx *ctx __unused, struct vcpu *vcpu __unused,
759 struct vm_exit *vme __unused)
765 * Just continue execution with the next instruction. We use
766 * the HLT VM exit as a way to be friendly with the host
769 return (VMEXIT_CONTINUE);
773 vmexit_pause(struct vmctx *ctx __unused, struct vcpu *vcpu __unused,
774 struct vm_exit *vme __unused)
777 stats.vmexit_pause++;
779 return (VMEXIT_CONTINUE);
783 vmexit_mtrap(struct vmctx *ctx __unused, struct vcpu *vcpu,
787 assert(vme->inst_length == 0);
789 stats.vmexit_mtrap++;
791 #ifdef BHYVE_SNAPSHOT
792 checkpoint_cpu_suspend(vcpu_id(vcpu));
795 #ifdef BHYVE_SNAPSHOT
796 checkpoint_cpu_resume(vcpu_id(vcpu));
799 return (VMEXIT_CONTINUE);
803 vmexit_inst_emul(struct vmctx *ctx __unused, struct vcpu *vcpu,
808 enum vm_cpu_mode mode;
810 stats.vmexit_inst_emul++;
812 vie = &vme->u.inst_emul.vie;
815 * Attempt to decode in userspace as a fallback. This allows
816 * updating instruction decode in bhyve without rebooting the
817 * kernel (rapid prototyping), albeit with much slower
821 mode = vme->u.inst_emul.paging.cpu_mode;
822 cs_d = vme->u.inst_emul.cs_d;
823 if (vmm_decode_instruction(mode, cs_d, vie) != 0)
825 if (vm_set_register(vcpu, VM_REG_GUEST_RIP,
826 vme->rip + vie->num_processed) != 0)
830 err = emulate_mem(vcpu, vme->u.inst_emul.gpa, vie,
831 &vme->u.inst_emul.paging);
834 EPRINTLN("Unhandled memory access to 0x%lx\n",
835 vme->u.inst_emul.gpa);
840 return (VMEXIT_CONTINUE);
843 fprintf(stderr, "Failed to emulate instruction sequence [ ");
844 for (i = 0; i < vie->num_valid; i++)
845 fprintf(stderr, "%02x", vie->inst[i]);
846 FPRINTLN(stderr, " ] at 0x%lx", vme->rip);
847 return (VMEXIT_ABORT);
850 static pthread_mutex_t resetcpu_mtx = PTHREAD_MUTEX_INITIALIZER;
851 static pthread_cond_t resetcpu_cond = PTHREAD_COND_INITIALIZER;
854 vmexit_suspend(struct vmctx *ctx, struct vcpu *vcpu, struct vm_exit *vme)
856 enum vm_suspend_how how;
857 int vcpuid = vcpu_id(vcpu);
859 how = vme->u.suspended.how;
861 fbsdrun_deletecpu(vcpuid);
864 pthread_mutex_lock(&resetcpu_mtx);
865 pthread_cond_signal(&resetcpu_cond);
866 pthread_mutex_unlock(&resetcpu_mtx);
870 pthread_mutex_lock(&resetcpu_mtx);
871 while (!CPU_EMPTY(&cpumask)) {
872 pthread_cond_wait(&resetcpu_cond, &resetcpu_mtx);
874 pthread_mutex_unlock(&resetcpu_mtx);
877 case VM_SUSPEND_RESET:
879 case VM_SUSPEND_POWEROFF:
880 if (get_config_bool_default("destroy_on_poweroff", false))
883 case VM_SUSPEND_HALT:
885 case VM_SUSPEND_TRIPLEFAULT:
888 fprintf(stderr, "vmexit_suspend: invalid reason %d\n", how);
891 return (0); /* NOTREACHED */
895 vmexit_debug(struct vmctx *ctx __unused, struct vcpu *vcpu,
896 struct vm_exit *vme __unused)
899 #ifdef BHYVE_SNAPSHOT
900 checkpoint_cpu_suspend(vcpu_id(vcpu));
902 gdb_cpu_suspend(vcpu);
903 #ifdef BHYVE_SNAPSHOT
904 checkpoint_cpu_resume(vcpu_id(vcpu));
907 * XXX-MJ sleep for a short period to avoid chewing up the CPU in the
908 * window between activation of the vCPU thread and the STARTUP IPI.
911 return (VMEXIT_CONTINUE);
915 vmexit_breakpoint(struct vmctx *ctx __unused, struct vcpu *vcpu,
919 gdb_cpu_breakpoint(vcpu, vme);
920 return (VMEXIT_CONTINUE);
924 vmexit_ipi(struct vmctx *ctx __unused, struct vcpu *vcpu __unused,
929 switch (vme->u.ipi.mode) {
930 case APIC_DELMODE_INIT:
931 CPU_FOREACH_ISSET(i, &vme->u.ipi.dmask) {
932 error = vm_suspend_cpu(vcpu_info[i].vcpu);
934 warnx("%s: failed to suspend cpu %d\n",
940 case APIC_DELMODE_STARTUP:
941 CPU_FOREACH_ISSET(i, &vme->u.ipi.dmask) {
942 spinup_ap(vcpu_info[i].vcpu,
943 vme->u.ipi.vector << PAGE_SHIFT);
954 static vmexit_handler_t handler[VM_EXITCODE_MAX] = {
955 [VM_EXITCODE_INOUT] = vmexit_inout,
956 [VM_EXITCODE_INOUT_STR] = vmexit_inout,
957 [VM_EXITCODE_VMX] = vmexit_vmx,
958 [VM_EXITCODE_SVM] = vmexit_svm,
959 [VM_EXITCODE_BOGUS] = vmexit_bogus,
960 [VM_EXITCODE_REQIDLE] = vmexit_reqidle,
961 [VM_EXITCODE_RDMSR] = vmexit_rdmsr,
962 [VM_EXITCODE_WRMSR] = vmexit_wrmsr,
963 [VM_EXITCODE_MTRAP] = vmexit_mtrap,
964 [VM_EXITCODE_INST_EMUL] = vmexit_inst_emul,
965 [VM_EXITCODE_SUSPENDED] = vmexit_suspend,
966 [VM_EXITCODE_TASK_SWITCH] = vmexit_task_switch,
967 [VM_EXITCODE_DEBUG] = vmexit_debug,
968 [VM_EXITCODE_BPT] = vmexit_breakpoint,
969 [VM_EXITCODE_IPI] = vmexit_ipi,
973 vm_loop(struct vmctx *ctx, struct vcpu *vcpu)
977 enum vm_exitcode exitcode;
978 cpuset_t active_cpus;
980 error = vm_active_cpus(ctx, &active_cpus);
981 assert(CPU_ISSET(vcpu_id(vcpu), &active_cpus));
984 error = vm_run(vcpu, &vme);
988 exitcode = vme.exitcode;
989 if (exitcode >= VM_EXITCODE_MAX || handler[exitcode] == NULL) {
990 fprintf(stderr, "vm_loop: unexpected exitcode 0x%x\n",
995 rc = (*handler[exitcode])(ctx, vcpu, &vme);
998 case VMEXIT_CONTINUE:
1006 fprintf(stderr, "vm_run error %d, errno %d\n", error, errno);
1010 num_vcpus_allowed(struct vmctx *ctx, struct vcpu *vcpu)
1012 uint16_t sockets, cores, threads, maxcpus;
1016 * The guest is allowed to spinup more than one processor only if the
1017 * UNRESTRICTED_GUEST capability is available.
1019 error = vm_get_capability(vcpu, VM_CAP_UNRESTRICTED_GUEST, &tmp);
1023 error = vm_get_topology(ctx, &sockets, &cores, &threads, &maxcpus);
1031 fbsdrun_set_capabilities(struct vcpu *vcpu, bool bsp)
1035 if (get_config_bool_default("x86.vmexit_on_hlt", false)) {
1036 err = vm_get_capability(vcpu, VM_CAP_HALT_EXIT, &tmp);
1038 fprintf(stderr, "VM exit on HLT not supported\n");
1041 vm_set_capability(vcpu, VM_CAP_HALT_EXIT, 1);
1043 handler[VM_EXITCODE_HLT] = vmexit_hlt;
1046 if (get_config_bool_default("x86.vmexit_on_pause", false)) {
1048 * pause exit support required for this mode
1050 err = vm_get_capability(vcpu, VM_CAP_PAUSE_EXIT, &tmp);
1053 "SMP mux requested, no pause support\n");
1056 vm_set_capability(vcpu, VM_CAP_PAUSE_EXIT, 1);
1058 handler[VM_EXITCODE_PAUSE] = vmexit_pause;
1061 if (get_config_bool_default("x86.x2apic", false))
1062 err = vm_set_x2apic_state(vcpu, X2APIC_ENABLED);
1064 err = vm_set_x2apic_state(vcpu, X2APIC_DISABLED);
1067 fprintf(stderr, "Unable to set x2apic state (%d)\n", err);
1071 vm_set_capability(vcpu, VM_CAP_ENABLE_INVPCID, 1);
1073 err = vm_set_capability(vcpu, VM_CAP_IPI_EXIT, 1);
1077 static struct vmctx *
1078 do_open(const char *vmname)
1082 bool reinit, romboot;
1084 reinit = romboot = false;
1089 error = vm_create(vmname);
1091 if (errno == EEXIST) {
1096 * The virtual machine has been setup by the
1097 * userspace bootloader.
1101 perror("vm_create");
1107 * If the virtual machine was just created then a
1108 * bootrom must be configured to boot it.
1110 fprintf(stderr, "virtual machine cannot be booted\n");
1115 ctx = vm_open(vmname);
1121 #ifndef WITHOUT_CAPSICUM
1122 if (vm_limit_rights(ctx) != 0)
1123 err(EX_OSERR, "vm_limit_rights");
1127 error = vm_reinit(ctx);
1129 perror("vm_reinit");
1133 error = vm_set_topology(ctx, cpu_sockets, cpu_cores, cpu_threads,
1134 0 /* maxcpus, unimplemented */);
1136 errx(EX_OSERR, "vm_set_topology");
1141 spinup_vcpu(struct vcpu_info *vi, bool bsp)
1146 fbsdrun_set_capabilities(vi->vcpu, false);
1149 * Enable the 'unrestricted guest' mode for APs.
1151 * APs startup in power-on 16-bit mode.
1153 error = vm_set_capability(vi->vcpu, VM_CAP_UNRESTRICTED_GUEST, 1);
1161 parse_config_option(const char *option)
1166 value = strchr(option, '=');
1167 if (value == NULL || value[1] == '\0')
1169 path = strndup(option, value - option);
1171 err(4, "Failed to allocate memory");
1172 set_config_value(path, value + 1);
1177 parse_simple_config_file(const char *path)
1182 unsigned int lineno;
1184 fp = fopen(path, "r");
1186 err(4, "Failed to open configuration file %s", path);
1190 for (lineno = 1; getline(&line, &linecap, fp) > 0; lineno++) {
1191 if (*line == '#' || *line == '\n')
1193 cp = strchr(line, '\n');
1196 if (!parse_config_option(line))
1197 errx(4, "%s line %u: invalid config option '%s'", path,
1205 parse_gdb_options(const char *opt)
1210 if (opt[0] == 'w') {
1211 set_config_bool("gdb.wait", true);
1215 colon = strrchr(opt, ':');
1216 if (colon == NULL) {
1222 set_config_value("gdb.address", opt);
1225 set_config_value("gdb.port", sport);
1232 set_config_bool("acpi_tables", false);
1233 set_config_value("memory.size", "256M");
1234 set_config_bool("x86.strictmsr", true);
1235 set_config_value("lpc.fwcfg", "bhyve");
1239 main(int argc, char *argv[])
1242 int max_vcpus, memflags;
1247 const char *optstr, *value, *vmname;
1248 #ifdef BHYVE_SNAPSHOT
1250 struct restore_state rstate;
1252 restore_file = NULL;
1257 progname = basename(argv[0]);
1259 #ifdef BHYVE_SNAPSHOT
1260 optstr = "aehuwxACDHIPSWYk:o:p:G:c:s:m:l:K:U:r:";
1262 optstr = "aehuwxACDHIPSWYk:o:p:G:c:s:m:l:K:U:";
1264 while ((c = getopt(argc, argv, optstr)) != -1) {
1267 set_config_bool("x86.x2apic", false);
1270 set_config_bool("acpi_tables", true);
1273 set_config_bool("destroy_on_poweroff", true);
1276 if (pincpu_parse(optarg) != 0) {
1277 errx(EX_USAGE, "invalid vcpu pinning "
1278 "configuration '%s'", optarg);
1282 if (topology_parse(optarg) != 0) {
1283 errx(EX_USAGE, "invalid cpu topology "
1288 set_config_bool("memory.guest_in_core", true);
1291 parse_gdb_options(optarg);
1294 parse_simple_config_file(optarg);
1297 set_config_value("keyboard.layout", optarg);
1300 if (strncmp(optarg, "help", strlen(optarg)) == 0) {
1301 lpc_print_supported_devices();
1303 } else if (lpc_device_parse(optarg) != 0) {
1304 errx(EX_USAGE, "invalid lpc device "
1305 "configuration '%s'", optarg);
1308 #ifdef BHYVE_SNAPSHOT
1310 restore_file = optarg;
1314 if (strncmp(optarg, "help", strlen(optarg)) == 0) {
1315 pci_print_supported_devices();
1317 } else if (pci_parse_slot(optarg) != 0)
1322 set_config_bool("memory.wired", true);
1325 set_config_value("memory.size", optarg);
1328 if (!parse_config_option(optarg))
1329 errx(EX_USAGE, "invalid configuration option '%s'", optarg);
1332 set_config_bool("x86.vmexit_on_hlt", true);
1336 * The "-I" option was used to add an ioapic to the
1339 * An ioapic is now provided unconditionally for each
1340 * virtual machine and this option is now deprecated.
1344 set_config_bool("x86.vmexit_on_pause", true);
1347 set_config_bool("x86.strictio", true);
1350 set_config_bool("rtc.use_localtime", false);
1353 set_config_value("uuid", optarg);
1356 set_config_bool("x86.strictmsr", false);
1359 set_config_bool("virtio_msix", false);
1362 set_config_bool("x86.x2apic", true);
1365 set_config_bool("x86.mptable", false);
1379 #ifdef BHYVE_SNAPSHOT
1380 if (restore_file != NULL) {
1381 error = load_restore_file(restore_file, &rstate);
1383 fprintf(stderr, "Failed to read checkpoint info from "
1384 "file: '%s'.\n", restore_file);
1387 vmname = lookup_vmname(&rstate);
1389 set_config_value("name", vmname);
1394 set_config_value("name", argv[0]);
1396 vmname = get_config_value("name");
1400 if (get_config_bool_default("config.dump", false)) {
1408 value = get_config_value("memory.size");
1409 error = vm_parse_memsize(value, &memsize);
1411 errx(EX_USAGE, "invalid memsize '%s'", value);
1413 ctx = do_open(vmname);
1415 #ifdef BHYVE_SNAPSHOT
1416 if (restore_file != NULL) {
1417 guest_ncpus = lookup_guest_ncpus(&rstate);
1418 memflags = lookup_memflags(&rstate);
1419 memsize = lookup_memsize(&rstate);
1422 if (guest_ncpus < 1) {
1423 fprintf(stderr, "Invalid guest vCPUs (%d)\n", guest_ncpus);
1428 bsp = vm_vcpu_open(ctx, BSP);
1429 max_vcpus = num_vcpus_allowed(ctx, bsp);
1430 if (guest_ncpus > max_vcpus) {
1431 fprintf(stderr, "%d vCPUs requested but only %d available\n",
1432 guest_ncpus, max_vcpus);
1436 fbsdrun_set_capabilities(bsp, true);
1438 /* Allocate per-VCPU resources. */
1439 vcpu_info = calloc(guest_ncpus, sizeof(*vcpu_info));
1440 for (int vcpuid = 0; vcpuid < guest_ncpus; vcpuid++) {
1441 vcpu_info[vcpuid].ctx = ctx;
1442 vcpu_info[vcpuid].vcpuid = vcpuid;
1444 vcpu_info[vcpuid].vcpu = bsp;
1446 vcpu_info[vcpuid].vcpu = vm_vcpu_open(ctx, vcpuid);
1450 if (get_config_bool_default("memory.wired", false))
1451 memflags |= VM_MEM_F_WIRED;
1452 if (get_config_bool_default("memory.guest_in_core", false))
1453 memflags |= VM_MEM_F_INCORE;
1454 vm_set_memflags(ctx, memflags);
1455 error = vm_setup_memory(ctx, memsize, VM_MMAP_ALL);
1457 fprintf(stderr, "Unable to setup memory (%d)\n", errno);
1463 fprintf(stderr, "init_msr error %d", error);
1467 init_mem(guest_ncpus);
1478 if (qemu_fwcfg_init(ctx) != 0) {
1479 fprintf(stderr, "qemu fwcfg initialization error");
1483 if (qemu_fwcfg_add_file("opt/bhyve/hw.ncpu", sizeof(guest_ncpus),
1484 &guest_ncpus) != 0) {
1485 fprintf(stderr, "Could not add qemu fwcfg opt/bhyve/hw.ncpu");
1490 * Exit if a device emulation finds an error in its initilization
1492 if (init_pci(ctx) != 0) {
1493 perror("device emulation initialization error");
1498 * Initialize after PCI, to allow a bootrom file to reserve the high
1501 if (get_config_bool("acpi_tables"))
1506 if (lpc_bootrom()) {
1507 if (vm_set_capability(bsp, VM_CAP_UNRESTRICTED_GUEST, 1)) {
1508 fprintf(stderr, "ROM boot failed: unrestricted guest "
1509 "capability not available\n");
1512 error = vcpu_reset(bsp);
1519 for (int vcpuid = 0; vcpuid < guest_ncpus; vcpuid++)
1520 spinup_vcpu(&vcpu_info[vcpuid], vcpuid == BSP);
1522 #ifdef BHYVE_SNAPSHOT
1523 if (restore_file != NULL) {
1524 fprintf(stdout, "Pausing pci devs...\r\n");
1525 if (vm_pause_user_devs() != 0) {
1526 fprintf(stderr, "Failed to pause PCI device state.\n");
1530 fprintf(stdout, "Restoring vm mem...\r\n");
1531 if (restore_vm_mem(ctx, &rstate) != 0) {
1532 fprintf(stderr, "Failed to restore VM memory.\n");
1536 fprintf(stdout, "Restoring pci devs...\r\n");
1537 if (vm_restore_user_devs(&rstate) != 0) {
1538 fprintf(stderr, "Failed to restore PCI device state.\n");
1542 fprintf(stdout, "Restoring kernel structs...\r\n");
1543 if (vm_restore_kern_structs(ctx, &rstate) != 0) {
1544 fprintf(stderr, "Failed to restore kernel structs.\n");
1548 fprintf(stdout, "Resuming pci devs...\r\n");
1549 if (vm_resume_user_devs() != 0) {
1550 fprintf(stderr, "Failed to resume PCI device state.\n");
1556 error = vm_get_register(bsp, VM_REG_GUEST_RIP, &rip);
1560 * build the guest tables, MP etc.
1562 if (get_config_bool_default("x86.mptable", true)) {
1563 error = mptable_build(ctx, guest_ncpus);
1565 perror("error to build the guest tables");
1570 error = smbios_build(ctx);
1574 if (get_config_bool("acpi_tables")) {
1575 error = acpi_build(ctx, guest_ncpus);
1579 if (lpc_bootrom() && strcmp(lpc_fwcfg(), "bhyve") == 0) {
1584 * Change the proc title to include the VM name.
1586 setproctitle("%s", vmname);
1588 #ifdef BHYVE_SNAPSHOT
1589 /* initialize mutex/cond variables */
1593 * checkpointing thread for communication with bhyvectl
1595 if (init_checkpoint_thread(ctx) != 0)
1596 errx(EX_OSERR, "Failed to start checkpoint thread");
1599 #ifndef WITHOUT_CAPSICUM
1600 caph_cache_catpages();
1602 if (caph_limit_stdout() == -1 || caph_limit_stderr() == -1)
1603 errx(EX_OSERR, "Unable to apply rights for sandbox");
1605 if (caph_enter() == -1)
1606 errx(EX_OSERR, "cap_enter() failed");
1609 #ifdef BHYVE_SNAPSHOT
1610 if (restore_file != NULL) {
1611 destroy_restore_state(&rstate);
1612 if (vm_restore_time(ctx) < 0)
1613 err(EX_OSERR, "Unable to restore time");
1615 for (int vcpuid = 0; vcpuid < guest_ncpus; vcpuid++)
1616 vm_resume_cpu(vcpu_info[vcpuid].vcpu);
1622 * Head off to the main event dispatch loop