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>
41 #include <amd64/vmm/intel/vmcs.h>
43 #include <machine/atomic.h>
44 #include <machine/segments.h>
56 #include <pthread_np.h>
60 #ifndef WITHOUT_CAPSICUM
65 #include <machine/vmm.h>
66 #ifndef WITHOUT_CAPSICUM
67 #include <machine/vmm_dev.h>
84 #include "smbiostbl.h"
86 #include "spinup_ap.h"
89 #define GUEST_NIO_PORT 0x488 /* guest upcalls via i/o port */
91 #define MB (1024UL * 1024)
92 #define GB (1024UL * MB)
94 static const char * const vmx_exit_reason_desc[] = {
95 [EXIT_REASON_EXCEPTION] = "Exception or non-maskable interrupt (NMI)",
96 [EXIT_REASON_EXT_INTR] = "External interrupt",
97 [EXIT_REASON_TRIPLE_FAULT] = "Triple fault",
98 [EXIT_REASON_INIT] = "INIT signal",
99 [EXIT_REASON_SIPI] = "Start-up IPI (SIPI)",
100 [EXIT_REASON_IO_SMI] = "I/O system-management interrupt (SMI)",
101 [EXIT_REASON_SMI] = "Other SMI",
102 [EXIT_REASON_INTR_WINDOW] = "Interrupt window",
103 [EXIT_REASON_NMI_WINDOW] = "NMI window",
104 [EXIT_REASON_TASK_SWITCH] = "Task switch",
105 [EXIT_REASON_CPUID] = "CPUID",
106 [EXIT_REASON_GETSEC] = "GETSEC",
107 [EXIT_REASON_HLT] = "HLT",
108 [EXIT_REASON_INVD] = "INVD",
109 [EXIT_REASON_INVLPG] = "INVLPG",
110 [EXIT_REASON_RDPMC] = "RDPMC",
111 [EXIT_REASON_RDTSC] = "RDTSC",
112 [EXIT_REASON_RSM] = "RSM",
113 [EXIT_REASON_VMCALL] = "VMCALL",
114 [EXIT_REASON_VMCLEAR] = "VMCLEAR",
115 [EXIT_REASON_VMLAUNCH] = "VMLAUNCH",
116 [EXIT_REASON_VMPTRLD] = "VMPTRLD",
117 [EXIT_REASON_VMPTRST] = "VMPTRST",
118 [EXIT_REASON_VMREAD] = "VMREAD",
119 [EXIT_REASON_VMRESUME] = "VMRESUME",
120 [EXIT_REASON_VMWRITE] = "VMWRITE",
121 [EXIT_REASON_VMXOFF] = "VMXOFF",
122 [EXIT_REASON_VMXON] = "VMXON",
123 [EXIT_REASON_CR_ACCESS] = "Control-register accesses",
124 [EXIT_REASON_DR_ACCESS] = "MOV DR",
125 [EXIT_REASON_INOUT] = "I/O instruction",
126 [EXIT_REASON_RDMSR] = "RDMSR",
127 [EXIT_REASON_WRMSR] = "WRMSR",
128 [EXIT_REASON_INVAL_VMCS] =
129 "VM-entry failure due to invalid guest state",
130 [EXIT_REASON_INVAL_MSR] = "VM-entry failure due to MSR loading",
131 [EXIT_REASON_MWAIT] = "MWAIT",
132 [EXIT_REASON_MTF] = "Monitor trap flag",
133 [EXIT_REASON_MONITOR] = "MONITOR",
134 [EXIT_REASON_PAUSE] = "PAUSE",
135 [EXIT_REASON_MCE_DURING_ENTRY] =
136 "VM-entry failure due to machine-check event",
137 [EXIT_REASON_TPR] = "TPR below threshold",
138 [EXIT_REASON_APIC_ACCESS] = "APIC access",
139 [EXIT_REASON_VIRTUALIZED_EOI] = "Virtualized EOI",
140 [EXIT_REASON_GDTR_IDTR] = "Access to GDTR or IDTR",
141 [EXIT_REASON_LDTR_TR] = "Access to LDTR or TR",
142 [EXIT_REASON_EPT_FAULT] = "EPT violation",
143 [EXIT_REASON_EPT_MISCONFIG] = "EPT misconfiguration",
144 [EXIT_REASON_INVEPT] = "INVEPT",
145 [EXIT_REASON_RDTSCP] = "RDTSCP",
146 [EXIT_REASON_VMX_PREEMPT] = "VMX-preemption timer expired",
147 [EXIT_REASON_INVVPID] = "INVVPID",
148 [EXIT_REASON_WBINVD] = "WBINVD",
149 [EXIT_REASON_XSETBV] = "XSETBV",
150 [EXIT_REASON_APIC_WRITE] = "APIC write",
151 [EXIT_REASON_RDRAND] = "RDRAND",
152 [EXIT_REASON_INVPCID] = "INVPCID",
153 [EXIT_REASON_VMFUNC] = "VMFUNC",
154 [EXIT_REASON_ENCLS] = "ENCLS",
155 [EXIT_REASON_RDSEED] = "RDSEED",
156 [EXIT_REASON_PM_LOG_FULL] = "Page-modification log full",
157 [EXIT_REASON_XSAVES] = "XSAVES",
158 [EXIT_REASON_XRSTORS] = "XRSTORS"
161 typedef int (*vmexit_handler_t)(struct vmctx *, struct vm_exit *, int *vcpu);
162 extern int vmexit_task_switch(struct vmctx *, struct vm_exit *, int *vcpu);
167 uint16_t cores, maxcpus, sockets, threads;
169 char *guest_uuid_str;
171 static int guest_vmexit_on_hlt, guest_vmexit_on_pause;
172 static int virtio_msix = 1;
173 static int x2apic_mode = 0; /* default is xAPIC */
176 static int strictmsr = 1;
180 static char *progname;
181 static const int BSP = 0;
183 static cpuset_t cpumask;
185 static void vm_loop(struct vmctx *ctx, int vcpu, uint64_t rip);
187 static struct vm_exit vmexit[VM_MAXCPU];
190 uint64_t vmexit_bogus;
191 uint64_t vmexit_reqidle;
193 uint64_t vmexit_pause;
194 uint64_t vmexit_mtrap;
195 uint64_t vmexit_inst_emul;
196 uint64_t cpu_switch_rotate;
197 uint64_t cpu_switch_direct;
202 struct vmctx *mt_ctx;
204 } mt_vmm_info[VM_MAXCPU];
206 static cpuset_t *vcpumap[VM_MAXCPU] = { NULL };
213 "Usage: %s [-abehuwxACHPSWY]\n"
214 " %*s [-c [[cpus=]numcpus][,sockets=n][,cores=n][,threads=n]]\n"
215 " %*s [-g <gdb port>] [-l <lpc>]\n"
216 " %*s [-m mem] [-p vcpu:hostcpu] [-s <pci>] [-U uuid] <vm>\n"
217 " -a: local apic is in xAPIC mode (deprecated)\n"
218 " -A: create ACPI tables\n"
219 " -c: number of cpus and/or topology specification\n"
220 " -C: include guest memory in core file\n"
221 " -e: exit on unhandled I/O access\n"
224 " -H: vmexit from the guest on hlt\n"
225 " -l: LPC device configuration\n"
226 " -m: memory size in MB\n"
227 " -p: pin 'vcpu' to 'hostcpu'\n"
228 " -P: vmexit from the guest on pause\n"
229 " -s: <slot,driver,configinfo> PCI slot config\n"
230 " -S: guest memory cannot be swapped\n"
231 " -u: RTC keeps UTC time\n"
233 " -w: ignore unimplemented MSRs\n"
234 " -W: force virtio to use single-vector MSI\n"
235 " -x: local apic is in x2APIC mode\n"
236 " -Y: disable MPtable generation\n",
237 progname, (int)strlen(progname), "", (int)strlen(progname), "",
238 (int)strlen(progname), "");
243 #ifndef WITHOUT_CAPSICUM
245 * 11-stable capsicum helpers
248 bhyve_caph_cache_catpages(void)
251 (void)catopen("libc", NL_CAT_LOCALE);
255 bhyve_caph_limit_stdoe(void)
258 unsigned long cmds[] = { TIOCGETA, TIOCGWINSZ };
259 int i, fds[] = { STDOUT_FILENO, STDERR_FILENO };
261 cap_rights_init(&rights, CAP_FCNTL, CAP_FSTAT, CAP_IOCTL);
262 cap_rights_set(&rights, CAP_WRITE);
264 for (i = 0; i < nitems(fds); i++) {
265 if (cap_rights_limit(fds[i], &rights) < 0 && errno != ENOSYS)
268 if (cap_ioctls_limit(fds[i], cmds, nitems(cmds)) < 0 && errno != ENOSYS)
271 if (cap_fcntls_limit(fds[i], CAP_FCNTL_GETFL) < 0 && errno != ENOSYS)
281 * XXX This parser is known to have the following issues:
282 * 1. It accepts null key=value tokens ",,".
283 * 2. It accepts whitespace after = and before value.
284 * 3. Values out of range of INT are silently wrapped.
285 * 4. It doesn't check non-final values.
286 * 5. The apparently bogus limits of UINT16_MAX are for future expansion.
288 * The acceptance of a null specification ('-c ""') is by design to match the
289 * manual page syntax specification, this results in a topology of 1 vCPU.
292 topology_parse(const char *opt)
295 int c, chk, n, s, t, tmp;
299 c = 1, n = 1, s = 1, t = 1;
300 ns = false, scts = false;
305 while ((cp = strsep(&str, ",")) != NULL) {
306 if (sscanf(cp, "%i%n", &tmp, &chk) == 1) {
309 } else if (sscanf(cp, "cpus=%i%n", &tmp, &chk) == 1) {
312 } else if (sscanf(cp, "sockets=%i%n", &tmp, &chk) == 1) {
315 } else if (sscanf(cp, "cores=%i%n", &tmp, &chk) == 1) {
318 } else if (sscanf(cp, "threads=%i%n", &tmp, &chk) == 1) {
321 #ifdef notyet /* Do not expose this until vmm.ko implements it */
322 } else if (sscanf(cp, "maxcpus=%i%n", &tmp, &chk) == 1) {
325 /* Skip the empty argument case from -c "" */
326 } else if (cp[0] == '\0')
330 /* Any trailing garbage causes an error */
338 * Range check 1 <= n <= UINT16_MAX all values
340 if (n < 1 || s < 1 || c < 1 || t < 1 ||
341 n > UINT16_MAX || s > UINT16_MAX || c > UINT16_MAX ||
345 /* If only the cpus was specified, use that as sockets */
349 * Compute sockets * cores * threads avoiding overflow
350 * The range check above insures these are 16 bit values
351 * If n was specified check it against computed ncpus
353 ncpus = (uint64_t)s * c * t;
354 if (ncpus > UINT16_MAX || (ns && n != ncpus))
369 pincpu_parse(const char *opt)
373 if (sscanf(opt, "%d:%d", &vcpu, &pcpu) != 2) {
374 fprintf(stderr, "invalid format: %s\n", opt);
378 if (vcpu < 0 || vcpu >= VM_MAXCPU) {
379 fprintf(stderr, "vcpu '%d' outside valid range from 0 to %d\n",
380 vcpu, VM_MAXCPU - 1);
384 if (pcpu < 0 || pcpu >= CPU_SETSIZE) {
385 fprintf(stderr, "hostcpu '%d' outside valid range from "
386 "0 to %d\n", pcpu, CPU_SETSIZE - 1);
390 if (vcpumap[vcpu] == NULL) {
391 if ((vcpumap[vcpu] = malloc(sizeof(cpuset_t))) == NULL) {
395 CPU_ZERO(vcpumap[vcpu]);
397 CPU_SET(pcpu, vcpumap[vcpu]);
402 vm_inject_fault(void *arg, int vcpu, int vector, int errcode_valid,
406 int error, restart_instruction;
409 restart_instruction = 1;
411 error = vm_inject_exception(ctx, vcpu, vector, errcode_valid, errcode,
412 restart_instruction);
417 paddr_guest2host(struct vmctx *ctx, uintptr_t gaddr, size_t len)
420 return (vm_map_gpa(ctx, gaddr, len));
424 fbsdrun_vmexit_on_pause(void)
427 return (guest_vmexit_on_pause);
431 fbsdrun_vmexit_on_hlt(void)
434 return (guest_vmexit_on_hlt);
438 fbsdrun_virtio_msix(void)
441 return (virtio_msix);
445 fbsdrun_start_thread(void *param)
447 char tname[MAXCOMLEN + 1];
448 struct mt_vmm_info *mtp;
454 snprintf(tname, sizeof(tname), "vcpu %d", vcpu);
455 pthread_set_name_np(mtp->mt_thr, tname);
457 vm_loop(mtp->mt_ctx, vcpu, vmexit[vcpu].rip);
465 fbsdrun_addcpu(struct vmctx *ctx, int fromcpu, int newcpu, uint64_t rip)
469 assert(fromcpu == BSP);
472 * The 'newcpu' must be activated in the context of 'fromcpu'. If
473 * vm_activate_cpu() is delayed until newcpu's pthread starts running
474 * then vmm.ko is out-of-sync with bhyve and this can create a race
477 error = vm_activate_cpu(ctx, newcpu);
479 err(EX_OSERR, "could not activate CPU %d", newcpu);
481 CPU_SET_ATOMIC(newcpu, &cpumask);
484 * Set up the vmexit struct to allow execution to start
487 vmexit[newcpu].rip = rip;
488 vmexit[newcpu].inst_length = 0;
490 mt_vmm_info[newcpu].mt_ctx = ctx;
491 mt_vmm_info[newcpu].mt_vcpu = newcpu;
493 error = pthread_create(&mt_vmm_info[newcpu].mt_thr, NULL,
494 fbsdrun_start_thread, &mt_vmm_info[newcpu]);
499 fbsdrun_deletecpu(struct vmctx *ctx, int vcpu)
502 if (!CPU_ISSET(vcpu, &cpumask)) {
503 fprintf(stderr, "Attempting to delete unknown cpu %d\n", vcpu);
507 CPU_CLR_ATOMIC(vcpu, &cpumask);
508 return (CPU_EMPTY(&cpumask));
512 vmexit_handle_notify(struct vmctx *ctx, struct vm_exit *vme, int *pvcpu,
517 * put guest-driven debug here
520 return (VMEXIT_CONTINUE);
524 vmexit_inout(struct vmctx *ctx, struct vm_exit *vme, int *pvcpu)
527 int bytes, port, in, out;
532 port = vme->u.inout.port;
533 bytes = vme->u.inout.bytes;
534 in = vme->u.inout.in;
537 /* Extra-special case of host notifications */
538 if (out && port == GUEST_NIO_PORT) {
539 error = vmexit_handle_notify(ctx, vme, pvcpu, vme->u.inout.eax);
543 error = emulate_inout(ctx, vcpu, vme, strictio);
545 fprintf(stderr, "Unhandled %s%c 0x%04x at 0x%lx\n",
547 bytes == 1 ? 'b' : (bytes == 2 ? 'w' : 'l'),
549 return (VMEXIT_ABORT);
551 return (VMEXIT_CONTINUE);
556 vmexit_rdmsr(struct vmctx *ctx, struct vm_exit *vme, int *pvcpu)
563 error = emulate_rdmsr(ctx, *pvcpu, vme->u.msr.code, &val);
565 fprintf(stderr, "rdmsr to register %#x on vcpu %d\n",
566 vme->u.msr.code, *pvcpu);
568 vm_inject_gp(ctx, *pvcpu);
569 return (VMEXIT_CONTINUE);
574 error = vm_set_register(ctx, *pvcpu, VM_REG_GUEST_RAX, eax);
578 error = vm_set_register(ctx, *pvcpu, VM_REG_GUEST_RDX, edx);
581 return (VMEXIT_CONTINUE);
585 vmexit_wrmsr(struct vmctx *ctx, struct vm_exit *vme, int *pvcpu)
589 error = emulate_wrmsr(ctx, *pvcpu, vme->u.msr.code, vme->u.msr.wval);
591 fprintf(stderr, "wrmsr to register %#x(%#lx) on vcpu %d\n",
592 vme->u.msr.code, vme->u.msr.wval, *pvcpu);
594 vm_inject_gp(ctx, *pvcpu);
595 return (VMEXIT_CONTINUE);
598 return (VMEXIT_CONTINUE);
602 vmexit_spinup_ap(struct vmctx *ctx, struct vm_exit *vme, int *pvcpu)
605 (void)spinup_ap(ctx, *pvcpu,
606 vme->u.spinup_ap.vcpu, vme->u.spinup_ap.rip);
608 return (VMEXIT_CONTINUE);
611 #define DEBUG_EPT_MISCONFIG
612 #ifdef DEBUG_EPT_MISCONFIG
613 #define VMCS_GUEST_PHYSICAL_ADDRESS 0x00002400
615 static uint64_t ept_misconfig_gpa, ept_misconfig_pte[4];
616 static int ept_misconfig_ptenum;
620 vmexit_vmx_desc(uint32_t exit_reason)
623 if (exit_reason >= nitems(vmx_exit_reason_desc) ||
624 vmx_exit_reason_desc[exit_reason] == NULL)
626 return (vmx_exit_reason_desc[exit_reason]);
630 vmexit_vmx(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
633 fprintf(stderr, "vm exit[%d]\n", *pvcpu);
634 fprintf(stderr, "\treason\t\tVMX\n");
635 fprintf(stderr, "\trip\t\t0x%016lx\n", vmexit->rip);
636 fprintf(stderr, "\tinst_length\t%d\n", vmexit->inst_length);
637 fprintf(stderr, "\tstatus\t\t%d\n", vmexit->u.vmx.status);
638 fprintf(stderr, "\texit_reason\t%u (%s)\n", vmexit->u.vmx.exit_reason,
639 vmexit_vmx_desc(vmexit->u.vmx.exit_reason));
640 fprintf(stderr, "\tqualification\t0x%016lx\n",
641 vmexit->u.vmx.exit_qualification);
642 fprintf(stderr, "\tinst_type\t\t%d\n", vmexit->u.vmx.inst_type);
643 fprintf(stderr, "\tinst_error\t\t%d\n", vmexit->u.vmx.inst_error);
644 #ifdef DEBUG_EPT_MISCONFIG
645 if (vmexit->u.vmx.exit_reason == EXIT_REASON_EPT_MISCONFIG) {
646 vm_get_register(ctx, *pvcpu,
647 VMCS_IDENT(VMCS_GUEST_PHYSICAL_ADDRESS),
649 vm_get_gpa_pmap(ctx, ept_misconfig_gpa, ept_misconfig_pte,
650 &ept_misconfig_ptenum);
651 fprintf(stderr, "\tEPT misconfiguration:\n");
652 fprintf(stderr, "\t\tGPA: %#lx\n", ept_misconfig_gpa);
653 fprintf(stderr, "\t\tPTE(%d): %#lx %#lx %#lx %#lx\n",
654 ept_misconfig_ptenum, ept_misconfig_pte[0],
655 ept_misconfig_pte[1], ept_misconfig_pte[2],
656 ept_misconfig_pte[3]);
658 #endif /* DEBUG_EPT_MISCONFIG */
659 return (VMEXIT_ABORT);
663 vmexit_svm(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
666 fprintf(stderr, "vm exit[%d]\n", *pvcpu);
667 fprintf(stderr, "\treason\t\tSVM\n");
668 fprintf(stderr, "\trip\t\t0x%016lx\n", vmexit->rip);
669 fprintf(stderr, "\tinst_length\t%d\n", vmexit->inst_length);
670 fprintf(stderr, "\texitcode\t%#lx\n", vmexit->u.svm.exitcode);
671 fprintf(stderr, "\texitinfo1\t%#lx\n", vmexit->u.svm.exitinfo1);
672 fprintf(stderr, "\texitinfo2\t%#lx\n", vmexit->u.svm.exitinfo2);
673 return (VMEXIT_ABORT);
677 vmexit_bogus(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
680 assert(vmexit->inst_length == 0);
682 stats.vmexit_bogus++;
684 return (VMEXIT_CONTINUE);
688 vmexit_reqidle(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
691 assert(vmexit->inst_length == 0);
693 stats.vmexit_reqidle++;
695 return (VMEXIT_CONTINUE);
699 vmexit_hlt(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
705 * Just continue execution with the next instruction. We use
706 * the HLT VM exit as a way to be friendly with the host
709 return (VMEXIT_CONTINUE);
713 vmexit_pause(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
716 stats.vmexit_pause++;
718 return (VMEXIT_CONTINUE);
722 vmexit_mtrap(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
725 assert(vmexit->inst_length == 0);
727 stats.vmexit_mtrap++;
729 return (VMEXIT_CONTINUE);
733 vmexit_inst_emul(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
738 stats.vmexit_inst_emul++;
740 vie = &vmexit->u.inst_emul.vie;
741 err = emulate_mem(ctx, *pvcpu, vmexit->u.inst_emul.gpa,
742 vie, &vmexit->u.inst_emul.paging);
746 fprintf(stderr, "Unhandled memory access to 0x%lx\n",
747 vmexit->u.inst_emul.gpa);
750 fprintf(stderr, "Failed to emulate instruction [");
751 for (i = 0; i < vie->num_valid; i++) {
752 fprintf(stderr, "0x%02x%s", vie->inst[i],
753 i != (vie->num_valid - 1) ? " " : "");
755 fprintf(stderr, "] at 0x%lx\n", vmexit->rip);
756 return (VMEXIT_ABORT);
759 return (VMEXIT_CONTINUE);
762 static pthread_mutex_t resetcpu_mtx = PTHREAD_MUTEX_INITIALIZER;
763 static pthread_cond_t resetcpu_cond = PTHREAD_COND_INITIALIZER;
766 vmexit_suspend(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
768 enum vm_suspend_how how;
770 how = vmexit->u.suspended.how;
772 fbsdrun_deletecpu(ctx, *pvcpu);
775 pthread_mutex_lock(&resetcpu_mtx);
776 pthread_cond_signal(&resetcpu_cond);
777 pthread_mutex_unlock(&resetcpu_mtx);
781 pthread_mutex_lock(&resetcpu_mtx);
782 while (!CPU_EMPTY(&cpumask)) {
783 pthread_cond_wait(&resetcpu_cond, &resetcpu_mtx);
785 pthread_mutex_unlock(&resetcpu_mtx);
788 case VM_SUSPEND_RESET:
790 case VM_SUSPEND_POWEROFF:
792 case VM_SUSPEND_HALT:
794 case VM_SUSPEND_TRIPLEFAULT:
797 fprintf(stderr, "vmexit_suspend: invalid reason %d\n", how);
800 return (0); /* NOTREACHED */
803 static vmexit_handler_t handler[VM_EXITCODE_MAX] = {
804 [VM_EXITCODE_INOUT] = vmexit_inout,
805 [VM_EXITCODE_INOUT_STR] = vmexit_inout,
806 [VM_EXITCODE_VMX] = vmexit_vmx,
807 [VM_EXITCODE_SVM] = vmexit_svm,
808 [VM_EXITCODE_BOGUS] = vmexit_bogus,
809 [VM_EXITCODE_REQIDLE] = vmexit_reqidle,
810 [VM_EXITCODE_RDMSR] = vmexit_rdmsr,
811 [VM_EXITCODE_WRMSR] = vmexit_wrmsr,
812 [VM_EXITCODE_MTRAP] = vmexit_mtrap,
813 [VM_EXITCODE_INST_EMUL] = vmexit_inst_emul,
814 [VM_EXITCODE_SPINUP_AP] = vmexit_spinup_ap,
815 [VM_EXITCODE_SUSPENDED] = vmexit_suspend,
816 [VM_EXITCODE_TASK_SWITCH] = vmexit_task_switch,
820 vm_loop(struct vmctx *ctx, int vcpu, uint64_t startrip)
823 enum vm_exitcode exitcode;
824 cpuset_t active_cpus;
826 if (vcpumap[vcpu] != NULL) {
827 error = pthread_setaffinity_np(pthread_self(),
828 sizeof(cpuset_t), vcpumap[vcpu]);
832 error = vm_active_cpus(ctx, &active_cpus);
833 assert(CPU_ISSET(vcpu, &active_cpus));
835 error = vm_set_register(ctx, vcpu, VM_REG_GUEST_RIP, startrip);
839 error = vm_run(ctx, vcpu, &vmexit[vcpu]);
843 exitcode = vmexit[vcpu].exitcode;
844 if (exitcode >= VM_EXITCODE_MAX || handler[exitcode] == NULL) {
845 fprintf(stderr, "vm_loop: unexpected exitcode 0x%x\n",
850 rc = (*handler[exitcode])(ctx, &vmexit[vcpu], &vcpu);
853 case VMEXIT_CONTINUE:
861 fprintf(stderr, "vm_run error %d, errno %d\n", error, errno);
865 num_vcpus_allowed(struct vmctx *ctx)
869 error = vm_get_capability(ctx, BSP, VM_CAP_UNRESTRICTED_GUEST, &tmp);
872 * The guest is allowed to spinup more than one processor only if the
873 * UNRESTRICTED_GUEST capability is available.
882 fbsdrun_set_capabilities(struct vmctx *ctx, int cpu)
886 if (fbsdrun_vmexit_on_hlt()) {
887 err = vm_get_capability(ctx, cpu, VM_CAP_HALT_EXIT, &tmp);
889 fprintf(stderr, "VM exit on HLT not supported\n");
892 vm_set_capability(ctx, cpu, VM_CAP_HALT_EXIT, 1);
894 handler[VM_EXITCODE_HLT] = vmexit_hlt;
897 if (fbsdrun_vmexit_on_pause()) {
899 * pause exit support required for this mode
901 err = vm_get_capability(ctx, cpu, VM_CAP_PAUSE_EXIT, &tmp);
904 "SMP mux requested, no pause support\n");
907 vm_set_capability(ctx, cpu, VM_CAP_PAUSE_EXIT, 1);
909 handler[VM_EXITCODE_PAUSE] = vmexit_pause;
913 err = vm_set_x2apic_state(ctx, cpu, X2APIC_ENABLED);
915 err = vm_set_x2apic_state(ctx, cpu, X2APIC_DISABLED);
918 fprintf(stderr, "Unable to set x2apic state (%d)\n", err);
922 vm_set_capability(ctx, cpu, VM_CAP_ENABLE_INVPCID, 1);
925 static struct vmctx *
926 do_open(const char *vmname)
930 bool reinit, romboot;
931 #ifndef WITHOUT_CAPSICUM
933 const cap_ioctl_t *cmds;
937 reinit = romboot = false;
942 error = vm_create(vmname);
944 if (errno == EEXIST) {
949 * The virtual machine has been setup by the
950 * userspace bootloader.
960 * If the virtual machine was just created then a
961 * bootrom must be configured to boot it.
963 fprintf(stderr, "virtual machine cannot be booted\n");
968 ctx = vm_open(vmname);
974 #ifndef WITHOUT_CAPSICUM
975 cap_rights_init(&rights, CAP_IOCTL, CAP_MMAP_RW);
976 if (cap_rights_limit(vm_get_device_fd(ctx), &rights) == -1 &&
978 errx(EX_OSERR, "Unable to apply rights for sandbox");
979 vm_get_ioctls(&ncmds);
980 cmds = vm_get_ioctls(NULL);
982 errx(EX_OSERR, "out of memory");
983 if (cap_ioctls_limit(vm_get_device_fd(ctx), cmds, ncmds) == -1 &&
985 errx(EX_OSERR, "Unable to apply rights for sandbox");
986 free((cap_ioctl_t *)cmds);
990 error = vm_reinit(ctx);
996 error = vm_set_topology(ctx, sockets, cores, threads, maxcpus);
998 errx(EX_OSERR, "vm_set_topology");
1003 main(int argc, char *argv[])
1005 int c, error, gdb_port, err, bvmcons;
1006 int max_vcpus, mptgen, memflags;
1014 progname = basename(argv[0]);
1017 sockets = cores = threads = 1;
1024 optstr = "abehuwxACHIPSWYp:g:c:s:m:l:U:";
1025 while ((c = getopt(argc, argv, optstr)) != -1) {
1037 if (pincpu_parse(optarg) != 0) {
1038 errx(EX_USAGE, "invalid vcpu pinning "
1039 "configuration '%s'", optarg);
1043 if (topology_parse(optarg) != 0) {
1044 errx(EX_USAGE, "invalid cpu topology "
1049 memflags |= VM_MEM_F_INCORE;
1052 gdb_port = atoi(optarg);
1055 if (lpc_device_parse(optarg) != 0) {
1056 errx(EX_USAGE, "invalid lpc device "
1057 "configuration '%s'", optarg);
1061 if (pci_parse_slot(optarg) != 0)
1066 memflags |= VM_MEM_F_WIRED;
1069 error = vm_parse_memsize(optarg, &memsize);
1071 errx(EX_USAGE, "invalid memsize '%s'", optarg);
1074 guest_vmexit_on_hlt = 1;
1078 * The "-I" option was used to add an ioapic to the
1081 * An ioapic is now provided unconditionally for each
1082 * virtual machine and this option is now deprecated.
1086 guest_vmexit_on_pause = 1;
1095 guest_uuid_str = optarg;
1122 ctx = do_open(vmname);
1124 max_vcpus = num_vcpus_allowed(ctx);
1125 if (guest_ncpus > max_vcpus) {
1126 fprintf(stderr, "%d vCPUs requested but only %d available\n",
1127 guest_ncpus, max_vcpus);
1131 fbsdrun_set_capabilities(ctx, BSP);
1133 vm_set_memflags(ctx, memflags);
1134 err = vm_setup_memory(ctx, memsize, VM_MMAP_ALL);
1136 fprintf(stderr, "Unable to setup memory (%d)\n", errno);
1142 fprintf(stderr, "init_msr error %d", error);
1152 rtc_init(ctx, rtc_localtime);
1156 * Exit if a device emulation finds an error in it's initilization
1158 if (init_pci(ctx) != 0) {
1159 perror("device emulation initialization error");
1164 init_dbgport(gdb_port);
1169 if (lpc_bootrom()) {
1170 if (vm_set_capability(ctx, BSP, VM_CAP_UNRESTRICTED_GUEST, 1)) {
1171 fprintf(stderr, "ROM boot failed: unrestricted guest "
1172 "capability not available\n");
1175 error = vcpu_reset(ctx, BSP);
1179 error = vm_get_register(ctx, BSP, VM_REG_GUEST_RIP, &rip);
1183 * build the guest tables, MP etc.
1186 error = mptable_build(ctx, guest_ncpus);
1188 perror("error to build the guest tables");
1193 error = smbios_build(ctx);
1197 error = acpi_build(ctx, guest_ncpus);
1205 * Change the proc title to include the VM name.
1207 setproctitle("%s", vmname);
1209 #ifndef WITHOUT_CAPSICUM
1210 bhyve_caph_cache_catpages();
1212 if (bhyve_caph_limit_stdoe() == -1)
1213 errx(EX_OSERR, "Unable to apply rights for sandbox");
1215 if (cap_enter() == -1 && errno != ENOSYS)
1216 errx(EX_OSERR, "cap_enter() failed");
1222 fbsdrun_addcpu(ctx, BSP, BSP, rip);
1225 * Head off to the main event dispatch loop