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 <machine/atomic.h>
46 #ifndef WITHOUT_CAPSICUM
47 #include <capsicum_helpers.h>
61 #include <pthread_np.h>
86 #include "amd64/pci_lpc.h"
88 #include "qemu_fwcfg.h"
92 #include "tpm_device.h"
96 #define MB (1024UL * 1024)
97 #define GB (1024UL * MB)
100 uint16_t cpu_cores, cpu_sockets, cpu_threads;
104 static char *progname;
105 static const int BSP = 0;
107 static cpuset_t cpumask;
109 static void vm_loop(struct vmctx *ctx, struct vcpu *vcpu);
111 static struct vcpu_info {
117 static cpuset_t **vcpumap;
124 "Usage: %s [-AaCDeHhPSuWwxY]\n"
125 " %*s [-c [[cpus=]numcpus][,sockets=n][,cores=n][,threads=n]]\n"
126 " %*s [-G port] [-k config_file] [-l lpc] [-m mem] [-o var=value]\n"
127 " %*s [-p vcpu:hostcpu] [-r file] [-s pci] [-U uuid] vmname\n"
128 " -A: create ACPI tables\n"
129 " -a: local apic is in xAPIC mode (deprecated)\n"
130 " -C: include guest memory in core file\n"
131 " -c: number of CPUs and/or topology specification\n"
132 " -D: destroy on power-off\n"
133 " -e: exit on unhandled I/O access\n"
134 " -G: start a debug server\n"
135 " -H: vmexit from the guest on HLT\n"
137 " -k: key=value flat config file\n"
138 " -K: PS2 keyboard layout\n"
139 " -l: LPC device configuration\n"
141 " -o: set config 'var' to 'value'\n"
142 " -P: vmexit from the guest on pause\n"
143 " -p: pin 'vcpu' to 'hostcpu'\n"
144 #ifdef BHYVE_SNAPSHOT
145 " -r: path to checkpoint file\n"
147 " -S: guest memory cannot be swapped\n"
148 " -s: <slot,driver,configinfo> PCI slot config\n"
150 " -u: RTC keeps UTC time\n"
151 " -W: force virtio to use single-vector MSI\n"
152 " -w: ignore unimplemented MSRs\n"
153 " -x: local APIC is in x2APIC mode\n"
154 " -Y: disable MPtable generation\n",
155 progname, (int)strlen(progname), "", (int)strlen(progname), "",
156 (int)strlen(progname), "");
162 * XXX This parser is known to have the following issues:
163 * 1. It accepts null key=value tokens ",," as setting "cpus" to an
166 * The acceptance of a null specification ('-c ""') is by design to match the
167 * manual page syntax specification, this results in a topology of 1 vCPU.
170 topology_parse(const char *opt)
172 char *cp, *str, *tofree;
175 set_config_value("sockets", "1");
176 set_config_value("cores", "1");
177 set_config_value("threads", "1");
178 set_config_value("cpus", "1");
182 tofree = str = strdup(opt);
184 errx(4, "Failed to allocate memory");
186 while ((cp = strsep(&str, ",")) != NULL) {
187 if (strncmp(cp, "cpus=", strlen("cpus=")) == 0)
188 set_config_value("cpus", cp + strlen("cpus="));
189 else if (strncmp(cp, "sockets=", strlen("sockets=")) == 0)
190 set_config_value("sockets", cp + strlen("sockets="));
191 else if (strncmp(cp, "cores=", strlen("cores=")) == 0)
192 set_config_value("cores", cp + strlen("cores="));
193 else if (strncmp(cp, "threads=", strlen("threads=")) == 0)
194 set_config_value("threads", cp + strlen("threads="));
195 else if (strchr(cp, '=') != NULL)
198 set_config_value("cpus", cp);
209 parse_int_value(const char *key, const char *value, int minval, int maxval)
215 lval = strtol(value, &cp, 0);
216 if (errno != 0 || *cp != '\0' || cp == value || lval < minval ||
218 errx(4, "Invalid value for %s: '%s'", key, value);
223 * Set the sockets, cores, threads, and guest_cpus variables based on
224 * the configured topology.
226 * The limits of UINT16_MAX are due to the types passed to
227 * vm_set_topology(). vmm.ko may enforce tighter limits.
236 value = get_config_value("cpus");
238 guest_ncpus = parse_int_value("cpus", value, 1, UINT16_MAX);
239 explicit_cpus = true;
242 explicit_cpus = false;
244 value = get_config_value("cores");
246 cpu_cores = parse_int_value("cores", value, 1, UINT16_MAX);
249 value = get_config_value("threads");
251 cpu_threads = parse_int_value("threads", value, 1, UINT16_MAX);
254 value = get_config_value("sockets");
256 cpu_sockets = parse_int_value("sockets", value, 1, UINT16_MAX);
258 cpu_sockets = guest_ncpus;
261 * Compute sockets * cores * threads avoiding overflow. The
262 * range check above insures these are 16 bit values.
264 ncpus = (uint64_t)cpu_sockets * cpu_cores * cpu_threads;
265 if (ncpus > UINT16_MAX)
266 errx(4, "Computed number of vCPUs too high: %ju",
270 if (guest_ncpus != (int)ncpus)
271 errx(4, "Topology (%d sockets, %d cores, %d threads) "
272 "does not match %d vCPUs",
273 cpu_sockets, cpu_cores, cpu_threads,
280 pincpu_parse(const char *opt)
287 if (sscanf(opt, "%d:%d", &vcpu, &pcpu) != 2) {
288 fprintf(stderr, "invalid format: %s\n", opt);
293 fprintf(stderr, "invalid vcpu '%d'\n", vcpu);
297 if (pcpu < 0 || pcpu >= CPU_SETSIZE) {
298 fprintf(stderr, "hostcpu '%d' outside valid range from "
299 "0 to %d\n", pcpu, CPU_SETSIZE - 1);
303 snprintf(key, sizeof(key), "vcpu.%d.cpuset", vcpu);
304 value = get_config_value(key);
306 if (asprintf(&newval, "%s%s%d", value != NULL ? value : "",
307 value != NULL ? "," : "", pcpu) == -1) {
308 perror("failed to build new cpuset string");
312 set_config_value(key, newval);
318 parse_cpuset(int vcpu, const char *list, cpuset_t *set)
325 token = __DECONST(char *, list);
327 pcpu = strtoul(token, &cp, 0);
329 errx(4, "invalid cpuset for vcpu %d: '%s'", vcpu, list);
330 if (pcpu < 0 || pcpu >= CPU_SETSIZE)
331 errx(4, "hostcpu '%d' outside valid range from 0 to %d",
332 pcpu, CPU_SETSIZE - 1);
338 errx(4, "Invalid hostcpu range %d-%d",
340 while (start < pcpu) {
350 errx(4, "invalid cpuset for vcpu %d: '%s'",
355 errx(4, "invalid cpuset for vcpu %d: '%s'", vcpu, list);
370 vcpumap = calloc(guest_ncpus, sizeof(*vcpumap));
371 for (vcpu = 0; vcpu < guest_ncpus; vcpu++) {
372 snprintf(key, sizeof(key), "vcpu.%d.cpuset", vcpu);
373 value = get_config_value(key);
376 vcpumap[vcpu] = malloc(sizeof(cpuset_t));
377 if (vcpumap[vcpu] == NULL)
378 err(4, "Failed to allocate cpuset for vcpu %d", vcpu);
379 parse_cpuset(vcpu, value, vcpumap[vcpu]);
384 paddr_guest2host(struct vmctx *ctx, uintptr_t gaddr, size_t len)
387 return (vm_map_gpa(ctx, gaddr, len));
390 #ifdef BHYVE_SNAPSHOT
392 paddr_host2guest(struct vmctx *ctx, void *addr)
394 return (vm_rev_map_gpa(ctx, addr));
399 fbsdrun_virtio_msix(void)
402 return (get_config_bool_default("virtio_msix", true));
406 fbsdrun_vcpu(int vcpuid)
408 return (vcpu_info[vcpuid].vcpu);
412 fbsdrun_start_thread(void *param)
414 char tname[MAXCOMLEN + 1];
415 struct vcpu_info *vi = param;
418 snprintf(tname, sizeof(tname), "vcpu %d", vi->vcpuid);
419 pthread_set_name_np(pthread_self(), tname);
421 if (vcpumap[vi->vcpuid] != NULL) {
422 error = pthread_setaffinity_np(pthread_self(),
423 sizeof(cpuset_t), vcpumap[vi->vcpuid]);
427 #ifdef BHYVE_SNAPSHOT
428 checkpoint_cpu_add(vi->vcpuid);
431 gdb_cpu_add(vi->vcpu);
434 vm_loop(vi->ctx, vi->vcpu);
442 fbsdrun_addcpu(int vcpuid)
444 struct vcpu_info *vi;
448 vi = &vcpu_info[vcpuid];
450 error = vm_activate_cpu(vi->vcpu);
452 err(EX_OSERR, "could not activate CPU %d", vi->vcpuid);
454 CPU_SET_ATOMIC(vcpuid, &cpumask);
456 vm_suspend_cpu(vi->vcpu);
458 error = pthread_create(&thr, NULL, fbsdrun_start_thread, vi);
463 fbsdrun_deletecpu(int vcpu)
465 static pthread_mutex_t resetcpu_mtx = PTHREAD_MUTEX_INITIALIZER;
466 static pthread_cond_t resetcpu_cond = PTHREAD_COND_INITIALIZER;
468 pthread_mutex_lock(&resetcpu_mtx);
469 if (!CPU_ISSET(vcpu, &cpumask)) {
470 EPRINTLN("Attempting to delete unknown cpu %d", vcpu);
474 CPU_CLR(vcpu, &cpumask);
477 pthread_cond_signal(&resetcpu_cond);
478 pthread_mutex_unlock(&resetcpu_mtx);
483 while (!CPU_EMPTY(&cpumask)) {
484 pthread_cond_wait(&resetcpu_cond, &resetcpu_mtx);
486 pthread_mutex_unlock(&resetcpu_mtx);
490 fbsdrun_suspendcpu(int vcpuid)
492 return (vm_suspend_cpu(vcpu_info[vcpuid].vcpu));
496 vm_loop(struct vmctx *ctx, struct vcpu *vcpu)
501 enum vm_exitcode exitcode;
502 cpuset_t active_cpus, dmask;
504 error = vm_active_cpus(ctx, &active_cpus);
505 assert(CPU_ISSET(vcpu_id(vcpu), &active_cpus));
507 vmrun.vm_exit = &vme;
508 vmrun.cpuset = &dmask;
509 vmrun.cpusetsize = sizeof(dmask);
512 error = vm_run(vcpu, &vmrun);
516 exitcode = vme.exitcode;
517 if (exitcode >= VM_EXITCODE_MAX ||
518 vmexit_handlers[exitcode] == NULL) {
519 warnx("vm_loop: unexpected exitcode 0x%x", exitcode);
523 rc = (*vmexit_handlers[exitcode])(ctx, vcpu, &vmrun);
526 case VMEXIT_CONTINUE:
534 EPRINTLN("vm_run error %d, errno %d", error, errno);
538 num_vcpus_allowed(struct vmctx *ctx, struct vcpu *vcpu)
540 uint16_t sockets, cores, threads, maxcpus;
544 * The guest is allowed to spinup more than one processor only if the
545 * UNRESTRICTED_GUEST capability is available.
547 error = vm_get_capability(vcpu, VM_CAP_UNRESTRICTED_GUEST, &tmp);
551 error = vm_get_topology(ctx, &sockets, &cores, &threads, &maxcpus);
558 static struct vmctx *
559 do_open(const char *vmname)
563 bool reinit, romboot;
565 reinit = romboot = false;
572 error = vm_create(vmname);
574 if (errno == EEXIST) {
579 * The virtual machine has been setup by the
580 * userspace bootloader.
590 * If the virtual machine was just created then a
591 * bootrom must be configured to boot it.
593 fprintf(stderr, "virtual machine cannot be booted\n");
598 ctx = vm_open(vmname);
604 #ifndef WITHOUT_CAPSICUM
605 if (vm_limit_rights(ctx) != 0)
606 err(EX_OSERR, "vm_limit_rights");
610 error = vm_reinit(ctx);
616 error = vm_set_topology(ctx, cpu_sockets, cpu_cores, cpu_threads, 0);
618 errx(EX_OSERR, "vm_set_topology");
623 parse_config_option(const char *option)
628 value = strchr(option, '=');
629 if (value == NULL || value[1] == '\0')
631 path = strndup(option, value - option);
633 err(4, "Failed to allocate memory");
634 set_config_value(path, value + 1);
639 parse_simple_config_file(const char *path)
646 fp = fopen(path, "r");
648 err(4, "Failed to open configuration file %s", path);
652 for (lineno = 1; getline(&line, &linecap, fp) > 0; lineno++) {
653 if (*line == '#' || *line == '\n')
655 cp = strchr(line, '\n');
658 if (!parse_config_option(line))
659 errx(4, "%s line %u: invalid config option '%s'", path,
668 parse_gdb_options(const char *opt)
674 set_config_bool("gdb.wait", true);
678 colon = strrchr(opt, ':');
685 set_config_value("gdb.address", opt);
688 set_config_value("gdb.port", sport);
693 main(int argc, char *argv[])
696 int max_vcpus, memflags;
700 const char *optstr, *value, *vmname;
701 #ifdef BHYVE_SNAPSHOT
703 struct restore_state rstate;
710 progname = basename(argv[0]);
712 #ifdef BHYVE_SNAPSHOT
713 optstr = "aehuwxACDHIPSWYk:f:o:p:G:c:s:m:l:K:U:r:";
715 optstr = "aehuwxACDHIPSWYk:f:o:p:G:c:s:m:l:K:U:";
717 while ((c = getopt(argc, argv, optstr)) != -1) {
721 set_config_bool("x86.x2apic", false);
726 * NOP. For backward compatibility. Most systems don't
727 * work properly without sane ACPI tables. Therefore,
728 * we're always generating them.
732 set_config_bool("destroy_on_poweroff", true);
735 if (pincpu_parse(optarg) != 0) {
736 errx(EX_USAGE, "invalid vcpu pinning "
737 "configuration '%s'", optarg);
741 if (topology_parse(optarg) != 0) {
742 errx(EX_USAGE, "invalid cpu topology "
747 set_config_bool("memory.guest_in_core", true);
750 if (qemu_fwcfg_parse_cmdline_arg(optarg) != 0) {
751 errx(EX_USAGE, "invalid fwcfg item '%s'", optarg);
756 parse_gdb_options(optarg);
760 parse_simple_config_file(optarg);
763 set_config_value("keyboard.layout", optarg);
767 if (strncmp(optarg, "help", strlen(optarg)) == 0) {
768 lpc_print_supported_devices();
770 } else if (lpc_device_parse(optarg) != 0) {
771 errx(EX_USAGE, "invalid lpc device "
772 "configuration '%s'", optarg);
776 #ifdef BHYVE_SNAPSHOT
778 restore_file = optarg;
782 if (strncmp(optarg, "help", strlen(optarg)) == 0) {
783 pci_print_supported_devices();
785 } else if (pci_parse_slot(optarg) != 0)
790 set_config_bool("memory.wired", true);
793 set_config_value("memory.size", optarg);
796 if (!parse_config_option(optarg))
797 errx(EX_USAGE, "invalid configuration option '%s'", optarg);
801 set_config_bool("x86.vmexit_on_hlt", true);
805 * The "-I" option was used to add an ioapic to the
808 * An ioapic is now provided unconditionally for each
809 * virtual machine and this option is now deprecated.
813 set_config_bool("x86.vmexit_on_pause", true);
816 set_config_bool("x86.strictio", true);
819 set_config_bool("rtc.use_localtime", false);
823 set_config_value("uuid", optarg);
827 set_config_bool("x86.strictmsr", false);
831 set_config_bool("virtio_msix", false);
835 set_config_bool("x86.x2apic", true);
838 set_config_bool("x86.mptable", false);
853 #ifdef BHYVE_SNAPSHOT
854 if (restore_file != NULL) {
855 error = load_restore_file(restore_file, &rstate);
857 fprintf(stderr, "Failed to read checkpoint info from "
858 "file: '%s'.\n", restore_file);
861 vmname = lookup_vmname(&rstate);
863 set_config_value("name", vmname);
868 set_config_value("name", argv[0]);
870 vmname = get_config_value("name");
874 if (get_config_bool_default("config.dump", false)) {
882 value = get_config_value("memory.size");
883 error = vm_parse_memsize(value, &memsize);
885 errx(EX_USAGE, "invalid memsize '%s'", value);
887 ctx = do_open(vmname);
889 #ifdef BHYVE_SNAPSHOT
890 if (restore_file != NULL) {
891 guest_ncpus = lookup_guest_ncpus(&rstate);
892 memflags = lookup_memflags(&rstate);
893 memsize = lookup_memsize(&rstate);
896 if (guest_ncpus < 1) {
897 fprintf(stderr, "Invalid guest vCPUs (%d)\n", guest_ncpus);
902 bsp = vm_vcpu_open(ctx, BSP);
903 max_vcpus = num_vcpus_allowed(ctx, bsp);
904 if (guest_ncpus > max_vcpus) {
905 fprintf(stderr, "%d vCPUs requested but only %d available\n",
906 guest_ncpus, max_vcpus);
910 bhyve_init_vcpu(bsp);
912 /* Allocate per-VCPU resources. */
913 vcpu_info = calloc(guest_ncpus, sizeof(*vcpu_info));
914 for (int vcpuid = 0; vcpuid < guest_ncpus; vcpuid++) {
915 vcpu_info[vcpuid].ctx = ctx;
916 vcpu_info[vcpuid].vcpuid = vcpuid;
918 vcpu_info[vcpuid].vcpu = bsp;
920 vcpu_info[vcpuid].vcpu = vm_vcpu_open(ctx, vcpuid);
924 if (get_config_bool_default("memory.wired", false))
925 memflags |= VM_MEM_F_WIRED;
926 if (get_config_bool_default("memory.guest_in_core", false))
927 memflags |= VM_MEM_F_INCORE;
928 vm_set_memflags(ctx, memflags);
929 error = vm_setup_memory(ctx, memsize, VM_MMAP_ALL);
931 fprintf(stderr, "Unable to setup memory (%d)\n", errno);
935 init_mem(guest_ncpus);
937 if (bhyve_init_platform(ctx, bsp) != 0)
940 if (qemu_fwcfg_init(ctx) != 0) {
941 fprintf(stderr, "qemu fwcfg initialization error\n");
945 if (qemu_fwcfg_add_file("opt/bhyve/hw.ncpu", sizeof(guest_ncpus),
946 &guest_ncpus) != 0) {
947 fprintf(stderr, "Could not add qemu fwcfg opt/bhyve/hw.ncpu\n");
952 * Exit if a device emulation finds an error in its initialization
954 if (init_pci(ctx) != 0) {
955 EPRINTLN("Device emulation initialization error: %s",
959 if (init_tpm(ctx) != 0) {
960 EPRINTLN("Failed to init TPM device");
965 * Initialize after PCI, to allow a bootrom file to reserve the high
968 if (get_config_bool("acpi_tables"))
978 for (int vcpuid = 0; vcpuid < guest_ncpus; vcpuid++)
979 bhyve_start_vcpu(vcpu_info[vcpuid].vcpu, vcpuid == BSP);
981 #ifdef BHYVE_SNAPSHOT
982 if (restore_file != NULL) {
983 FPRINTLN(stdout, "Pausing pci devs...");
984 if (vm_pause_devices() != 0) {
985 EPRINTLN("Failed to pause PCI device state.");
989 FPRINTLN(stdout, "Restoring vm mem...");
990 if (restore_vm_mem(ctx, &rstate) != 0) {
991 EPRINTLN("Failed to restore VM memory.");
995 FPRINTLN(stdout, "Restoring pci devs...");
996 if (vm_restore_devices(&rstate) != 0) {
997 EPRINTLN("Failed to restore PCI device state.");
1001 FPRINTLN(stdout, "Restoring kernel structs...");
1002 if (vm_restore_kern_structs(ctx, &rstate) != 0) {
1003 EPRINTLN("Failed to restore kernel structs.");
1007 FPRINTLN(stdout, "Resuming pci devs...");
1008 if (vm_resume_devices() != 0) {
1009 EPRINTLN("Failed to resume PCI device state.");
1015 if (bhyve_init_platform_late(ctx, bsp) != 0)
1019 * Change the proc title to include the VM name.
1021 setproctitle("%s", vmname);
1023 #ifdef BHYVE_SNAPSHOT
1025 * checkpointing thread for communication with bhyvectl
1027 if (init_checkpoint_thread(ctx) != 0)
1028 errx(EX_OSERR, "Failed to start checkpoint thread");
1031 #ifndef WITHOUT_CAPSICUM
1032 caph_cache_catpages();
1034 if (caph_limit_stdout() == -1 || caph_limit_stderr() == -1)
1035 errx(EX_OSERR, "Unable to apply rights for sandbox");
1037 if (caph_enter() == -1)
1038 errx(EX_OSERR, "cap_enter() failed");
1041 #ifdef BHYVE_SNAPSHOT
1042 if (restore_file != NULL) {
1043 destroy_restore_state(&rstate);
1044 if (vm_restore_time(ctx) < 0)
1045 err(EX_OSERR, "Unable to restore time");
1047 for (int vcpuid = 0; vcpuid < guest_ncpus; vcpuid++)
1048 vm_resume_cpu(vcpu_info[vcpuid].vcpu);
1054 * Head off to the main event dispatch loop