1 /*- 2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD 3 * 4 * Copyright (c) 2011 NetApp, Inc. 5 * All rights reserved. 6 * 7 * Redistribution and use in source and binary forms, with or without 8 * modification, are permitted provided that the following conditions 9 * are met: 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. 15 * 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 26 * SUCH DAMAGE. 27 * 28 * $FreeBSD$ 29 */ 30 31 #include <sys/cdefs.h> 32 __FBSDID("$FreeBSD$"); 33 34 #include <sys/types.h> 35 #ifndef WITHOUT_CAPSICUM 36 #include <sys/capsicum.h> 37 #endif 38 #include <sys/mman.h> 39 #ifdef BHYVE_SNAPSHOT 40 #include <sys/socket.h> 41 #include <sys/stat.h> 42 #endif 43 #include <sys/time.h> 44 #ifdef BHYVE_SNAPSHOT 45 #include <sys/un.h> 46 #endif 47 48 #include <amd64/vmm/intel/vmcs.h> 49 #include <x86/apicreg.h> 50 51 #include <machine/atomic.h> 52 #include <machine/segments.h> 53 54 #ifndef WITHOUT_CAPSICUM 55 #include <capsicum_helpers.h> 56 #endif 57 #include <stdio.h> 58 #include <stdlib.h> 59 #include <string.h> 60 #include <err.h> 61 #include <errno.h> 62 #ifdef BHYVE_SNAPSHOT 63 #include <fcntl.h> 64 #endif 65 #include <libgen.h> 66 #include <unistd.h> 67 #include <assert.h> 68 #include <pthread.h> 69 #include <pthread_np.h> 70 #include <sysexits.h> 71 #include <stdbool.h> 72 #include <stdint.h> 73 #ifdef BHYVE_SNAPSHOT 74 #include <ucl.h> 75 #include <unistd.h> 76 77 #include <libxo/xo.h> 78 #endif 79 80 #include <machine/vmm.h> 81 #ifndef WITHOUT_CAPSICUM 82 #include <machine/vmm_dev.h> 83 #endif 84 #include <machine/vmm_instruction_emul.h> 85 #include <vmmapi.h> 86 87 #include "bhyverun.h" 88 #include "acpi.h" 89 #include "atkbdc.h" 90 #include "bootrom.h" 91 #include "config.h" 92 #include "inout.h" 93 #include "debug.h" 94 #include "fwctl.h" 95 #include "gdb.h" 96 #include "ioapic.h" 97 #include "kernemu_dev.h" 98 #include "mem.h" 99 #include "mevent.h" 100 #include "mptbl.h" 101 #include "pci_emul.h" 102 #include "pci_irq.h" 103 #include "pci_lpc.h" 104 #include "smbiostbl.h" 105 #ifdef BHYVE_SNAPSHOT 106 #include "snapshot.h" 107 #endif 108 #include "xmsr.h" 109 #include "spinup_ap.h" 110 #include "rtc.h" 111 #include "vmgenc.h" 112 113 #define GUEST_NIO_PORT 0x488 /* guest upcalls via i/o port */ 114 115 #define MB (1024UL * 1024) 116 #define GB (1024UL * MB) 117 118 static const char * const vmx_exit_reason_desc[] = { 119 [EXIT_REASON_EXCEPTION] = "Exception or non-maskable interrupt (NMI)", 120 [EXIT_REASON_EXT_INTR] = "External interrupt", 121 [EXIT_REASON_TRIPLE_FAULT] = "Triple fault", 122 [EXIT_REASON_INIT] = "INIT signal", 123 [EXIT_REASON_SIPI] = "Start-up IPI (SIPI)", 124 [EXIT_REASON_IO_SMI] = "I/O system-management interrupt (SMI)", 125 [EXIT_REASON_SMI] = "Other SMI", 126 [EXIT_REASON_INTR_WINDOW] = "Interrupt window", 127 [EXIT_REASON_NMI_WINDOW] = "NMI window", 128 [EXIT_REASON_TASK_SWITCH] = "Task switch", 129 [EXIT_REASON_CPUID] = "CPUID", 130 [EXIT_REASON_GETSEC] = "GETSEC", 131 [EXIT_REASON_HLT] = "HLT", 132 [EXIT_REASON_INVD] = "INVD", 133 [EXIT_REASON_INVLPG] = "INVLPG", 134 [EXIT_REASON_RDPMC] = "RDPMC", 135 [EXIT_REASON_RDTSC] = "RDTSC", 136 [EXIT_REASON_RSM] = "RSM", 137 [EXIT_REASON_VMCALL] = "VMCALL", 138 [EXIT_REASON_VMCLEAR] = "VMCLEAR", 139 [EXIT_REASON_VMLAUNCH] = "VMLAUNCH", 140 [EXIT_REASON_VMPTRLD] = "VMPTRLD", 141 [EXIT_REASON_VMPTRST] = "VMPTRST", 142 [EXIT_REASON_VMREAD] = "VMREAD", 143 [EXIT_REASON_VMRESUME] = "VMRESUME", 144 [EXIT_REASON_VMWRITE] = "VMWRITE", 145 [EXIT_REASON_VMXOFF] = "VMXOFF", 146 [EXIT_REASON_VMXON] = "VMXON", 147 [EXIT_REASON_CR_ACCESS] = "Control-register accesses", 148 [EXIT_REASON_DR_ACCESS] = "MOV DR", 149 [EXIT_REASON_INOUT] = "I/O instruction", 150 [EXIT_REASON_RDMSR] = "RDMSR", 151 [EXIT_REASON_WRMSR] = "WRMSR", 152 [EXIT_REASON_INVAL_VMCS] = 153 "VM-entry failure due to invalid guest state", 154 [EXIT_REASON_INVAL_MSR] = "VM-entry failure due to MSR loading", 155 [EXIT_REASON_MWAIT] = "MWAIT", 156 [EXIT_REASON_MTF] = "Monitor trap flag", 157 [EXIT_REASON_MONITOR] = "MONITOR", 158 [EXIT_REASON_PAUSE] = "PAUSE", 159 [EXIT_REASON_MCE_DURING_ENTRY] = 160 "VM-entry failure due to machine-check event", 161 [EXIT_REASON_TPR] = "TPR below threshold", 162 [EXIT_REASON_APIC_ACCESS] = "APIC access", 163 [EXIT_REASON_VIRTUALIZED_EOI] = "Virtualized EOI", 164 [EXIT_REASON_GDTR_IDTR] = "Access to GDTR or IDTR", 165 [EXIT_REASON_LDTR_TR] = "Access to LDTR or TR", 166 [EXIT_REASON_EPT_FAULT] = "EPT violation", 167 [EXIT_REASON_EPT_MISCONFIG] = "EPT misconfiguration", 168 [EXIT_REASON_INVEPT] = "INVEPT", 169 [EXIT_REASON_RDTSCP] = "RDTSCP", 170 [EXIT_REASON_VMX_PREEMPT] = "VMX-preemption timer expired", 171 [EXIT_REASON_INVVPID] = "INVVPID", 172 [EXIT_REASON_WBINVD] = "WBINVD", 173 [EXIT_REASON_XSETBV] = "XSETBV", 174 [EXIT_REASON_APIC_WRITE] = "APIC write", 175 [EXIT_REASON_RDRAND] = "RDRAND", 176 [EXIT_REASON_INVPCID] = "INVPCID", 177 [EXIT_REASON_VMFUNC] = "VMFUNC", 178 [EXIT_REASON_ENCLS] = "ENCLS", 179 [EXIT_REASON_RDSEED] = "RDSEED", 180 [EXIT_REASON_PM_LOG_FULL] = "Page-modification log full", 181 [EXIT_REASON_XSAVES] = "XSAVES", 182 [EXIT_REASON_XRSTORS] = "XRSTORS" 183 }; 184 185 typedef int (*vmexit_handler_t)(struct vmctx *, struct vm_exit *, int *vcpu); 186 187 int guest_ncpus; 188 uint16_t cpu_cores, cpu_sockets, cpu_threads; 189 190 int raw_stdio = 0; 191 192 static char *progname; 193 static const int BSP = 0; 194 195 static cpuset_t cpumask; 196 197 static void vm_loop(struct vmctx *ctx, int vcpu); 198 199 static struct bhyvestats { 200 uint64_t vmexit_bogus; 201 uint64_t vmexit_reqidle; 202 uint64_t vmexit_hlt; 203 uint64_t vmexit_pause; 204 uint64_t vmexit_mtrap; 205 uint64_t vmexit_inst_emul; 206 uint64_t cpu_switch_rotate; 207 uint64_t cpu_switch_direct; 208 } stats; 209 210 static struct mt_vmm_info { 211 pthread_t mt_thr; 212 struct vmctx *mt_ctx; 213 int mt_vcpu; 214 } *mt_vmm_info; 215 216 static cpuset_t **vcpumap; 217 218 static void 219 usage(int code) 220 { 221 222 fprintf(stderr, 223 "Usage: %s [-AaCDeHhPSuWwxY]\n" 224 " %*s [-c [[cpus=]numcpus][,sockets=n][,cores=n][,threads=n]]\n" 225 " %*s [-G port] [-k config_file] [-l lpc] [-m mem] [-o var=value]\n" 226 " %*s [-p vcpu:hostcpu] [-r file] [-s pci] [-U uuid] vmname\n" 227 " -A: create ACPI tables\n" 228 " -a: local apic is in xAPIC mode (deprecated)\n" 229 " -C: include guest memory in core file\n" 230 " -c: number of CPUs and/or topology specification\n" 231 " -D: destroy on power-off\n" 232 " -e: exit on unhandled I/O access\n" 233 " -G: start a debug server\n" 234 " -H: vmexit from the guest on HLT\n" 235 " -h: help\n" 236 " -k: key=value flat config file\n" 237 " -K: PS2 keyboard layout\n" 238 " -l: LPC device configuration\n" 239 " -m: memory size\n" 240 " -o: set config 'var' to 'value'\n" 241 " -P: vmexit from the guest on pause\n" 242 " -p: pin 'vcpu' to 'hostcpu'\n" 243 #ifdef BHYVE_SNAPSHOT 244 " -r: path to checkpoint file\n" 245 #endif 246 " -S: guest memory cannot be swapped\n" 247 " -s: <slot,driver,configinfo> PCI slot config\n" 248 " -U: UUID\n" 249 " -u: RTC keeps UTC time\n" 250 " -W: force virtio to use single-vector MSI\n" 251 " -w: ignore unimplemented MSRs\n" 252 " -x: local APIC is in x2APIC mode\n" 253 " -Y: disable MPtable generation\n", 254 progname, (int)strlen(progname), "", (int)strlen(progname), "", 255 (int)strlen(progname), ""); 256 257 exit(code); 258 } 259 260 /* 261 * XXX This parser is known to have the following issues: 262 * 1. It accepts null key=value tokens ",," as setting "cpus" to an 263 * empty string. 264 * 265 * The acceptance of a null specification ('-c ""') is by design to match the 266 * manual page syntax specification, this results in a topology of 1 vCPU. 267 */ 268 static int 269 topology_parse(const char *opt) 270 { 271 char *cp, *str, *tofree; 272 273 if (*opt == '\0') { 274 set_config_value("sockets", "1"); 275 set_config_value("cores", "1"); 276 set_config_value("threads", "1"); 277 set_config_value("cpus", "1"); 278 return (0); 279 } 280 281 tofree = str = strdup(opt); 282 if (str == NULL) 283 errx(4, "Failed to allocate memory"); 284 285 while ((cp = strsep(&str, ",")) != NULL) { 286 if (strncmp(cp, "cpus=", strlen("cpus=")) == 0) 287 set_config_value("cpus", cp + strlen("cpus=")); 288 else if (strncmp(cp, "sockets=", strlen("sockets=")) == 0) 289 set_config_value("sockets", cp + strlen("sockets=")); 290 else if (strncmp(cp, "cores=", strlen("cores=")) == 0) 291 set_config_value("cores", cp + strlen("cores=")); 292 else if (strncmp(cp, "threads=", strlen("threads=")) == 0) 293 set_config_value("threads", cp + strlen("threads=")); 294 #ifdef notyet /* Do not expose this until vmm.ko implements it */ 295 else if (strncmp(cp, "maxcpus=", strlen("maxcpus=")) == 0) 296 set_config_value("maxcpus", cp + strlen("maxcpus=")); 297 #endif 298 else if (strchr(cp, '=') != NULL) 299 goto out; 300 else 301 set_config_value("cpus", cp); 302 } 303 free(tofree); 304 return (0); 305 306 out: 307 free(tofree); 308 return (-1); 309 } 310 311 static int 312 parse_int_value(const char *key, const char *value, int minval, int maxval) 313 { 314 char *cp; 315 long lval; 316 317 errno = 0; 318 lval = strtol(value, &cp, 0); 319 if (errno != 0 || *cp != '\0' || cp == value || lval < minval || 320 lval > maxval) 321 errx(4, "Invalid value for %s: '%s'", key, value); 322 return (lval); 323 } 324 325 /* 326 * Set the sockets, cores, threads, and guest_cpus variables based on 327 * the configured topology. 328 * 329 * The limits of UINT16_MAX are due to the types passed to 330 * vm_set_topology(). vmm.ko may enforce tighter limits. 331 */ 332 static void 333 calc_topology(void) 334 { 335 const char *value; 336 bool explicit_cpus; 337 uint64_t ncpus; 338 339 value = get_config_value("cpus"); 340 if (value != NULL) { 341 guest_ncpus = parse_int_value("cpus", value, 1, UINT16_MAX); 342 explicit_cpus = true; 343 } else { 344 guest_ncpus = 1; 345 explicit_cpus = false; 346 } 347 value = get_config_value("cores"); 348 if (value != NULL) 349 cpu_cores = parse_int_value("cores", value, 1, UINT16_MAX); 350 else 351 cpu_cores = 1; 352 value = get_config_value("threads"); 353 if (value != NULL) 354 cpu_threads = parse_int_value("threads", value, 1, UINT16_MAX); 355 else 356 cpu_threads = 1; 357 value = get_config_value("sockets"); 358 if (value != NULL) 359 cpu_sockets = parse_int_value("sockets", value, 1, UINT16_MAX); 360 else 361 cpu_sockets = guest_ncpus; 362 363 /* 364 * Compute sockets * cores * threads avoiding overflow. The 365 * range check above insures these are 16 bit values. 366 */ 367 ncpus = (uint64_t)cpu_sockets * cpu_cores * cpu_threads; 368 if (ncpus > UINT16_MAX) 369 errx(4, "Computed number of vCPUs too high: %ju", 370 (uintmax_t)ncpus); 371 372 if (explicit_cpus) { 373 if (guest_ncpus != (int)ncpus) 374 errx(4, "Topology (%d sockets, %d cores, %d threads) " 375 "does not match %d vCPUs", 376 cpu_sockets, cpu_cores, cpu_threads, 377 guest_ncpus); 378 } else 379 guest_ncpus = ncpus; 380 } 381 382 static int 383 pincpu_parse(const char *opt) 384 { 385 const char *value; 386 char *newval; 387 char key[16]; 388 int vcpu, pcpu; 389 390 if (sscanf(opt, "%d:%d", &vcpu, &pcpu) != 2) { 391 fprintf(stderr, "invalid format: %s\n", opt); 392 return (-1); 393 } 394 395 if (vcpu < 0) { 396 fprintf(stderr, "invalid vcpu '%d'\n", vcpu); 397 return (-1); 398 } 399 400 if (pcpu < 0 || pcpu >= CPU_SETSIZE) { 401 fprintf(stderr, "hostcpu '%d' outside valid range from " 402 "0 to %d\n", pcpu, CPU_SETSIZE - 1); 403 return (-1); 404 } 405 406 snprintf(key, sizeof(key), "vcpu.%d.cpuset", vcpu); 407 value = get_config_value(key); 408 409 if (asprintf(&newval, "%s%s%d", value != NULL ? value : "", 410 value != NULL ? "," : "", pcpu) == -1) { 411 perror("failed to build new cpuset string"); 412 return (-1); 413 } 414 415 set_config_value(key, newval); 416 free(newval); 417 return (0); 418 } 419 420 static void 421 parse_cpuset(int vcpu, const char *list, cpuset_t *set) 422 { 423 char *cp, *token; 424 int pcpu, start; 425 426 CPU_ZERO(set); 427 start = -1; 428 token = __DECONST(char *, list); 429 for (;;) { 430 pcpu = strtoul(token, &cp, 0); 431 if (cp == token) 432 errx(4, "invalid cpuset for vcpu %d: '%s'", vcpu, list); 433 if (pcpu < 0 || pcpu >= CPU_SETSIZE) 434 errx(4, "hostcpu '%d' outside valid range from 0 to %d", 435 pcpu, CPU_SETSIZE - 1); 436 switch (*cp) { 437 case ',': 438 case '\0': 439 if (start >= 0) { 440 if (start > pcpu) 441 errx(4, "Invalid hostcpu range %d-%d", 442 start, pcpu); 443 while (start < pcpu) { 444 CPU_SET(start, set); 445 start++; 446 } 447 start = -1; 448 } 449 CPU_SET(pcpu, set); 450 break; 451 case '-': 452 if (start >= 0) 453 errx(4, "invalid cpuset for vcpu %d: '%s'", 454 vcpu, list); 455 start = pcpu; 456 break; 457 default: 458 errx(4, "invalid cpuset for vcpu %d: '%s'", vcpu, list); 459 } 460 if (*cp == '\0') 461 break; 462 token = cp + 1; 463 } 464 } 465 466 static void 467 build_vcpumaps(void) 468 { 469 char key[16]; 470 const char *value; 471 int vcpu; 472 473 vcpumap = calloc(guest_ncpus, sizeof(*vcpumap)); 474 for (vcpu = 0; vcpu < guest_ncpus; vcpu++) { 475 snprintf(key, sizeof(key), "vcpu.%d.cpuset", vcpu); 476 value = get_config_value(key); 477 if (value == NULL) 478 continue; 479 vcpumap[vcpu] = malloc(sizeof(cpuset_t)); 480 if (vcpumap[vcpu] == NULL) 481 err(4, "Failed to allocate cpuset for vcpu %d", vcpu); 482 parse_cpuset(vcpu, value, vcpumap[vcpu]); 483 } 484 } 485 486 void 487 vm_inject_fault(void *arg, int vcpu, int vector, int errcode_valid, 488 int errcode) 489 { 490 struct vmctx *ctx; 491 int error, restart_instruction; 492 493 ctx = arg; 494 restart_instruction = 1; 495 496 error = vm_inject_exception(ctx, vcpu, vector, errcode_valid, errcode, 497 restart_instruction); 498 assert(error == 0); 499 } 500 501 void * 502 paddr_guest2host(struct vmctx *ctx, uintptr_t gaddr, size_t len) 503 { 504 505 return (vm_map_gpa(ctx, gaddr, len)); 506 } 507 508 #ifdef BHYVE_SNAPSHOT 509 uintptr_t 510 paddr_host2guest(struct vmctx *ctx, void *addr) 511 { 512 return (vm_rev_map_gpa(ctx, addr)); 513 } 514 #endif 515 516 int 517 fbsdrun_virtio_msix(void) 518 { 519 520 return (get_config_bool_default("virtio_msix", true)); 521 } 522 523 static void * 524 fbsdrun_start_thread(void *param) 525 { 526 char tname[MAXCOMLEN + 1]; 527 struct mt_vmm_info *mtp; 528 int error, vcpu; 529 530 mtp = param; 531 vcpu = mtp->mt_vcpu; 532 533 snprintf(tname, sizeof(tname), "vcpu %d", vcpu); 534 pthread_set_name_np(mtp->mt_thr, tname); 535 536 if (vcpumap[vcpu] != NULL) { 537 error = pthread_setaffinity_np(mtp->mt_thr, sizeof(cpuset_t), 538 vcpumap[vcpu]); 539 assert(error == 0); 540 } 541 542 #ifdef BHYVE_SNAPSHOT 543 checkpoint_cpu_add(vcpu); 544 #endif 545 gdb_cpu_add(vcpu); 546 547 vm_loop(mtp->mt_ctx, vcpu); 548 549 /* not reached */ 550 exit(1); 551 return (NULL); 552 } 553 554 static void 555 fbsdrun_addcpu(struct vmctx *ctx, int newcpu, bool suspend) 556 { 557 int error; 558 559 error = vm_activate_cpu(ctx, newcpu); 560 if (error != 0) 561 err(EX_OSERR, "could not activate CPU %d", newcpu); 562 563 CPU_SET_ATOMIC(newcpu, &cpumask); 564 565 if (suspend) 566 vm_suspend_cpu(ctx, newcpu); 567 568 mt_vmm_info[newcpu].mt_ctx = ctx; 569 mt_vmm_info[newcpu].mt_vcpu = newcpu; 570 571 error = pthread_create(&mt_vmm_info[newcpu].mt_thr, NULL, 572 fbsdrun_start_thread, &mt_vmm_info[newcpu]); 573 assert(error == 0); 574 } 575 576 static int 577 fbsdrun_deletecpu(int vcpu) 578 { 579 580 if (!CPU_ISSET(vcpu, &cpumask)) { 581 fprintf(stderr, "Attempting to delete unknown cpu %d\n", vcpu); 582 exit(4); 583 } 584 585 CPU_CLR_ATOMIC(vcpu, &cpumask); 586 return (CPU_EMPTY(&cpumask)); 587 } 588 589 static int 590 vmexit_handle_notify(struct vmctx *ctx __unused, struct vm_exit *vme __unused, 591 int *pvcpu __unused, uint32_t eax __unused) 592 { 593 #if BHYVE_DEBUG 594 /* 595 * put guest-driven debug here 596 */ 597 #endif 598 return (VMEXIT_CONTINUE); 599 } 600 601 static int 602 vmexit_inout(struct vmctx *ctx, struct vm_exit *vme, int *pvcpu) 603 { 604 int error; 605 int bytes, port, in, out; 606 int vcpu; 607 608 vcpu = *pvcpu; 609 610 port = vme->u.inout.port; 611 bytes = vme->u.inout.bytes; 612 in = vme->u.inout.in; 613 out = !in; 614 615 /* Extra-special case of host notifications */ 616 if (out && port == GUEST_NIO_PORT) { 617 error = vmexit_handle_notify(ctx, vme, pvcpu, vme->u.inout.eax); 618 return (error); 619 } 620 621 error = emulate_inout(ctx, vcpu, vme); 622 if (error) { 623 fprintf(stderr, "Unhandled %s%c 0x%04x at 0x%lx\n", 624 in ? "in" : "out", 625 bytes == 1 ? 'b' : (bytes == 2 ? 'w' : 'l'), 626 port, vme->rip); 627 return (VMEXIT_ABORT); 628 } else { 629 return (VMEXIT_CONTINUE); 630 } 631 } 632 633 static int 634 vmexit_rdmsr(struct vmctx *ctx, struct vm_exit *vme, int *pvcpu) 635 { 636 uint64_t val; 637 uint32_t eax, edx; 638 int error; 639 640 val = 0; 641 error = emulate_rdmsr(ctx, *pvcpu, vme->u.msr.code, &val); 642 if (error != 0) { 643 fprintf(stderr, "rdmsr to register %#x on vcpu %d\n", 644 vme->u.msr.code, *pvcpu); 645 if (get_config_bool("x86.strictmsr")) { 646 vm_inject_gp(ctx, *pvcpu); 647 return (VMEXIT_CONTINUE); 648 } 649 } 650 651 eax = val; 652 error = vm_set_register(ctx, *pvcpu, VM_REG_GUEST_RAX, eax); 653 assert(error == 0); 654 655 edx = val >> 32; 656 error = vm_set_register(ctx, *pvcpu, VM_REG_GUEST_RDX, edx); 657 assert(error == 0); 658 659 return (VMEXIT_CONTINUE); 660 } 661 662 static int 663 vmexit_wrmsr(struct vmctx *ctx, struct vm_exit *vme, int *pvcpu) 664 { 665 int error; 666 667 error = emulate_wrmsr(ctx, *pvcpu, vme->u.msr.code, vme->u.msr.wval); 668 if (error != 0) { 669 fprintf(stderr, "wrmsr to register %#x(%#lx) on vcpu %d\n", 670 vme->u.msr.code, vme->u.msr.wval, *pvcpu); 671 if (get_config_bool("x86.strictmsr")) { 672 vm_inject_gp(ctx, *pvcpu); 673 return (VMEXIT_CONTINUE); 674 } 675 } 676 return (VMEXIT_CONTINUE); 677 } 678 679 #define DEBUG_EPT_MISCONFIG 680 #ifdef DEBUG_EPT_MISCONFIG 681 #define VMCS_GUEST_PHYSICAL_ADDRESS 0x00002400 682 683 static uint64_t ept_misconfig_gpa, ept_misconfig_pte[4]; 684 static int ept_misconfig_ptenum; 685 #endif 686 687 static const char * 688 vmexit_vmx_desc(uint32_t exit_reason) 689 { 690 691 if (exit_reason >= nitems(vmx_exit_reason_desc) || 692 vmx_exit_reason_desc[exit_reason] == NULL) 693 return ("Unknown"); 694 return (vmx_exit_reason_desc[exit_reason]); 695 } 696 697 static int 698 vmexit_vmx(struct vmctx *ctx, struct vm_exit *vme, int *pvcpu) 699 { 700 701 fprintf(stderr, "vm exit[%d]\n", *pvcpu); 702 fprintf(stderr, "\treason\t\tVMX\n"); 703 fprintf(stderr, "\trip\t\t0x%016lx\n", vme->rip); 704 fprintf(stderr, "\tinst_length\t%d\n", vme->inst_length); 705 fprintf(stderr, "\tstatus\t\t%d\n", vme->u.vmx.status); 706 fprintf(stderr, "\texit_reason\t%u (%s)\n", vme->u.vmx.exit_reason, 707 vmexit_vmx_desc(vme->u.vmx.exit_reason)); 708 fprintf(stderr, "\tqualification\t0x%016lx\n", 709 vme->u.vmx.exit_qualification); 710 fprintf(stderr, "\tinst_type\t\t%d\n", vme->u.vmx.inst_type); 711 fprintf(stderr, "\tinst_error\t\t%d\n", vme->u.vmx.inst_error); 712 #ifdef DEBUG_EPT_MISCONFIG 713 if (vme->u.vmx.exit_reason == EXIT_REASON_EPT_MISCONFIG) { 714 vm_get_register(ctx, *pvcpu, 715 VMCS_IDENT(VMCS_GUEST_PHYSICAL_ADDRESS), 716 &ept_misconfig_gpa); 717 vm_get_gpa_pmap(ctx, ept_misconfig_gpa, ept_misconfig_pte, 718 &ept_misconfig_ptenum); 719 fprintf(stderr, "\tEPT misconfiguration:\n"); 720 fprintf(stderr, "\t\tGPA: %#lx\n", ept_misconfig_gpa); 721 fprintf(stderr, "\t\tPTE(%d): %#lx %#lx %#lx %#lx\n", 722 ept_misconfig_ptenum, ept_misconfig_pte[0], 723 ept_misconfig_pte[1], ept_misconfig_pte[2], 724 ept_misconfig_pte[3]); 725 } 726 #endif /* DEBUG_EPT_MISCONFIG */ 727 return (VMEXIT_ABORT); 728 } 729 730 static int 731 vmexit_svm(struct vmctx *ctx __unused, struct vm_exit *vme, int *pvcpu) 732 { 733 734 fprintf(stderr, "vm exit[%d]\n", *pvcpu); 735 fprintf(stderr, "\treason\t\tSVM\n"); 736 fprintf(stderr, "\trip\t\t0x%016lx\n", vme->rip); 737 fprintf(stderr, "\tinst_length\t%d\n", vme->inst_length); 738 fprintf(stderr, "\texitcode\t%#lx\n", vme->u.svm.exitcode); 739 fprintf(stderr, "\texitinfo1\t%#lx\n", vme->u.svm.exitinfo1); 740 fprintf(stderr, "\texitinfo2\t%#lx\n", vme->u.svm.exitinfo2); 741 return (VMEXIT_ABORT); 742 } 743 744 static int 745 vmexit_bogus(struct vmctx *ctx __unused, struct vm_exit *vme, 746 int *pvcpu __unused) 747 { 748 749 assert(vme->inst_length == 0); 750 751 stats.vmexit_bogus++; 752 753 return (VMEXIT_CONTINUE); 754 } 755 756 static int 757 vmexit_reqidle(struct vmctx *ctx __unused, struct vm_exit *vme, 758 int *pvcpu __unused) 759 { 760 761 assert(vme->inst_length == 0); 762 763 stats.vmexit_reqidle++; 764 765 return (VMEXIT_CONTINUE); 766 } 767 768 static int 769 vmexit_hlt(struct vmctx *ctx __unused, struct vm_exit *vme __unused, 770 int *pvcpu __unused) 771 { 772 773 stats.vmexit_hlt++; 774 775 /* 776 * Just continue execution with the next instruction. We use 777 * the HLT VM exit as a way to be friendly with the host 778 * scheduler. 779 */ 780 return (VMEXIT_CONTINUE); 781 } 782 783 static int 784 vmexit_pause(struct vmctx *ctx __unused, struct vm_exit *vme __unused, 785 int *pvcpu __unused) 786 { 787 788 stats.vmexit_pause++; 789 790 return (VMEXIT_CONTINUE); 791 } 792 793 static int 794 vmexit_mtrap(struct vmctx *ctx __unused, struct vm_exit *vme, int *pvcpu) 795 { 796 797 assert(vme->inst_length == 0); 798 799 stats.vmexit_mtrap++; 800 801 #ifdef BHYVE_SNAPSHOT 802 checkpoint_cpu_suspend(*pvcpu); 803 #endif 804 gdb_cpu_mtrap(*pvcpu); 805 #ifdef BHYVE_SNAPSHOT 806 checkpoint_cpu_resume(*pvcpu); 807 #endif 808 809 return (VMEXIT_CONTINUE); 810 } 811 812 static int 813 vmexit_inst_emul(struct vmctx *ctx, struct vm_exit *vme, int *pvcpu) 814 { 815 int err, i, cs_d; 816 struct vie *vie; 817 enum vm_cpu_mode mode; 818 819 stats.vmexit_inst_emul++; 820 821 vie = &vme->u.inst_emul.vie; 822 if (!vie->decoded) { 823 /* 824 * Attempt to decode in userspace as a fallback. This allows 825 * updating instruction decode in bhyve without rebooting the 826 * kernel (rapid prototyping), albeit with much slower 827 * emulation. 828 */ 829 vie_restart(vie); 830 mode = vme->u.inst_emul.paging.cpu_mode; 831 cs_d = vme->u.inst_emul.cs_d; 832 if (vmm_decode_instruction(mode, cs_d, vie) != 0) 833 goto fail; 834 if (vm_set_register(ctx, *pvcpu, VM_REG_GUEST_RIP, 835 vme->rip + vie->num_processed) != 0) 836 goto fail; 837 } 838 839 err = emulate_mem(ctx, *pvcpu, vme->u.inst_emul.gpa, 840 vie, &vme->u.inst_emul.paging); 841 if (err) { 842 if (err == ESRCH) { 843 EPRINTLN("Unhandled memory access to 0x%lx\n", 844 vme->u.inst_emul.gpa); 845 } 846 goto fail; 847 } 848 849 return (VMEXIT_CONTINUE); 850 851 fail: 852 fprintf(stderr, "Failed to emulate instruction sequence [ "); 853 for (i = 0; i < vie->num_valid; i++) 854 fprintf(stderr, "%02x", vie->inst[i]); 855 FPRINTLN(stderr, " ] at 0x%lx", vme->rip); 856 return (VMEXIT_ABORT); 857 } 858 859 static pthread_mutex_t resetcpu_mtx = PTHREAD_MUTEX_INITIALIZER; 860 static pthread_cond_t resetcpu_cond = PTHREAD_COND_INITIALIZER; 861 862 static int 863 vmexit_suspend(struct vmctx *ctx, struct vm_exit *vme, int *pvcpu) 864 { 865 enum vm_suspend_how how; 866 867 how = vme->u.suspended.how; 868 869 fbsdrun_deletecpu(*pvcpu); 870 871 if (*pvcpu != BSP) { 872 pthread_mutex_lock(&resetcpu_mtx); 873 pthread_cond_signal(&resetcpu_cond); 874 pthread_mutex_unlock(&resetcpu_mtx); 875 pthread_exit(NULL); 876 } 877 878 pthread_mutex_lock(&resetcpu_mtx); 879 while (!CPU_EMPTY(&cpumask)) { 880 pthread_cond_wait(&resetcpu_cond, &resetcpu_mtx); 881 } 882 pthread_mutex_unlock(&resetcpu_mtx); 883 884 switch (how) { 885 case VM_SUSPEND_RESET: 886 exit(0); 887 case VM_SUSPEND_POWEROFF: 888 if (get_config_bool_default("destroy_on_poweroff", false)) 889 vm_destroy(ctx); 890 exit(1); 891 case VM_SUSPEND_HALT: 892 exit(2); 893 case VM_SUSPEND_TRIPLEFAULT: 894 exit(3); 895 default: 896 fprintf(stderr, "vmexit_suspend: invalid reason %d\n", how); 897 exit(100); 898 } 899 return (0); /* NOTREACHED */ 900 } 901 902 static int 903 vmexit_debug(struct vmctx *ctx __unused, struct vm_exit *vme __unused, 904 int *pvcpu) 905 { 906 907 #ifdef BHYVE_SNAPSHOT 908 checkpoint_cpu_suspend(*pvcpu); 909 #endif 910 gdb_cpu_suspend(*pvcpu); 911 #ifdef BHYVE_SNAPSHOT 912 checkpoint_cpu_resume(*pvcpu); 913 #endif 914 return (VMEXIT_CONTINUE); 915 } 916 917 static int 918 vmexit_breakpoint(struct vmctx *ctx __unused, struct vm_exit *vme, int *pvcpu) 919 { 920 921 gdb_cpu_breakpoint(*pvcpu, vme); 922 return (VMEXIT_CONTINUE); 923 } 924 925 static int 926 vmexit_ipi(struct vmctx *ctx, struct vm_exit *vme, int *pvcpu __unused) 927 { 928 int error = -1; 929 int i; 930 switch (vme->u.ipi.mode) { 931 case APIC_DELMODE_INIT: 932 CPU_FOREACH_ISSET(i, &vme->u.ipi.dmask) { 933 error = vm_suspend_cpu(ctx, i); 934 if (error) { 935 warnx("%s: failed to suspend cpu %d\n", 936 __func__, i); 937 break; 938 } 939 } 940 break; 941 case APIC_DELMODE_STARTUP: 942 CPU_FOREACH_ISSET(i, &vme->u.ipi.dmask) { 943 spinup_ap(ctx, i, vme->u.ipi.vector << PAGE_SHIFT); 944 } 945 error = 0; 946 break; 947 default: 948 break; 949 } 950 951 return (error); 952 } 953 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, 970 }; 971 972 static void 973 vm_loop(struct vmctx *ctx, int vcpu) 974 { 975 struct vm_exit vme; 976 int error, rc; 977 enum vm_exitcode exitcode; 978 cpuset_t active_cpus; 979 980 error = vm_active_cpus(ctx, &active_cpus); 981 assert(CPU_ISSET(vcpu, &active_cpus)); 982 983 while (1) { 984 error = vm_run(ctx, vcpu, &vme); 985 if (error != 0) 986 break; 987 988 exitcode = vme.exitcode; 989 if (exitcode >= VM_EXITCODE_MAX || handler[exitcode] == NULL) { 990 fprintf(stderr, "vm_loop: unexpected exitcode 0x%x\n", 991 exitcode); 992 exit(4); 993 } 994 995 rc = (*handler[exitcode])(ctx, &vme, &vcpu); 996 997 switch (rc) { 998 case VMEXIT_CONTINUE: 999 break; 1000 case VMEXIT_ABORT: 1001 abort(); 1002 default: 1003 exit(4); 1004 } 1005 } 1006 fprintf(stderr, "vm_run error %d, errno %d\n", error, errno); 1007 } 1008 1009 static int 1010 num_vcpus_allowed(struct vmctx *ctx) 1011 { 1012 uint16_t sockets, cores, threads, maxcpus; 1013 int tmp, error; 1014 1015 /* 1016 * The guest is allowed to spinup more than one processor only if the 1017 * UNRESTRICTED_GUEST capability is available. 1018 */ 1019 error = vm_get_capability(ctx, BSP, VM_CAP_UNRESTRICTED_GUEST, &tmp); 1020 if (error != 0) 1021 return (1); 1022 1023 error = vm_get_topology(ctx, &sockets, &cores, &threads, &maxcpus); 1024 if (error == 0) 1025 return (maxcpus); 1026 else 1027 return (1); 1028 } 1029 1030 static void 1031 fbsdrun_set_capabilities(struct vmctx *ctx, int cpu) 1032 { 1033 int err, tmp; 1034 1035 if (get_config_bool_default("x86.vmexit_on_hlt", false)) { 1036 err = vm_get_capability(ctx, cpu, VM_CAP_HALT_EXIT, &tmp); 1037 if (err < 0) { 1038 fprintf(stderr, "VM exit on HLT not supported\n"); 1039 exit(4); 1040 } 1041 vm_set_capability(ctx, cpu, VM_CAP_HALT_EXIT, 1); 1042 if (cpu == BSP) 1043 handler[VM_EXITCODE_HLT] = vmexit_hlt; 1044 } 1045 1046 if (get_config_bool_default("x86.vmexit_on_pause", false)) { 1047 /* 1048 * pause exit support required for this mode 1049 */ 1050 err = vm_get_capability(ctx, cpu, VM_CAP_PAUSE_EXIT, &tmp); 1051 if (err < 0) { 1052 fprintf(stderr, 1053 "SMP mux requested, no pause support\n"); 1054 exit(4); 1055 } 1056 vm_set_capability(ctx, cpu, VM_CAP_PAUSE_EXIT, 1); 1057 if (cpu == BSP) 1058 handler[VM_EXITCODE_PAUSE] = vmexit_pause; 1059 } 1060 1061 if (get_config_bool_default("x86.x2apic", false)) 1062 err = vm_set_x2apic_state(ctx, cpu, X2APIC_ENABLED); 1063 else 1064 err = vm_set_x2apic_state(ctx, cpu, X2APIC_DISABLED); 1065 1066 if (err) { 1067 fprintf(stderr, "Unable to set x2apic state (%d)\n", err); 1068 exit(4); 1069 } 1070 1071 vm_set_capability(ctx, cpu, VM_CAP_ENABLE_INVPCID, 1); 1072 1073 err = vm_set_capability(ctx, cpu, VM_CAP_IPI_EXIT, 1); 1074 assert(err == 0); 1075 } 1076 1077 static struct vmctx * 1078 do_open(const char *vmname) 1079 { 1080 struct vmctx *ctx; 1081 int error; 1082 bool reinit, romboot; 1083 1084 reinit = romboot = false; 1085 1086 if (lpc_bootrom()) 1087 romboot = true; 1088 1089 error = vm_create(vmname); 1090 if (error) { 1091 if (errno == EEXIST) { 1092 if (romboot) { 1093 reinit = true; 1094 } else { 1095 /* 1096 * The virtual machine has been setup by the 1097 * userspace bootloader. 1098 */ 1099 } 1100 } else { 1101 perror("vm_create"); 1102 exit(4); 1103 } 1104 } else { 1105 if (!romboot) { 1106 /* 1107 * If the virtual machine was just created then a 1108 * bootrom must be configured to boot it. 1109 */ 1110 fprintf(stderr, "virtual machine cannot be booted\n"); 1111 exit(4); 1112 } 1113 } 1114 1115 ctx = vm_open(vmname); 1116 if (ctx == NULL) { 1117 perror("vm_open"); 1118 exit(4); 1119 } 1120 1121 #ifndef WITHOUT_CAPSICUM 1122 if (vm_limit_rights(ctx) != 0) 1123 err(EX_OSERR, "vm_limit_rights"); 1124 #endif 1125 1126 if (reinit) { 1127 error = vm_reinit(ctx); 1128 if (error) { 1129 perror("vm_reinit"); 1130 exit(4); 1131 } 1132 } 1133 error = vm_set_topology(ctx, cpu_sockets, cpu_cores, cpu_threads, 1134 0 /* maxcpus, unimplemented */); 1135 if (error) 1136 errx(EX_OSERR, "vm_set_topology"); 1137 return (ctx); 1138 } 1139 1140 static void 1141 spinup_vcpu(struct vmctx *ctx, int vcpu, bool suspend) 1142 { 1143 int error; 1144 1145 if (vcpu != BSP) { 1146 fbsdrun_set_capabilities(ctx, vcpu); 1147 1148 /* 1149 * Enable the 'unrestricted guest' mode for APs. 1150 * 1151 * APs startup in power-on 16-bit mode. 1152 */ 1153 error = vm_set_capability(ctx, vcpu, VM_CAP_UNRESTRICTED_GUEST, 1); 1154 assert(error == 0); 1155 } 1156 1157 fbsdrun_addcpu(ctx, vcpu, suspend); 1158 } 1159 1160 static bool 1161 parse_config_option(const char *option) 1162 { 1163 const char *value; 1164 char *path; 1165 1166 value = strchr(option, '='); 1167 if (value == NULL || value[1] == '\0') 1168 return (false); 1169 path = strndup(option, value - option); 1170 if (path == NULL) 1171 err(4, "Failed to allocate memory"); 1172 set_config_value(path, value + 1); 1173 return (true); 1174 } 1175 1176 static void 1177 parse_simple_config_file(const char *path) 1178 { 1179 FILE *fp; 1180 char *line, *cp; 1181 size_t linecap; 1182 unsigned int lineno; 1183 1184 fp = fopen(path, "r"); 1185 if (fp == NULL) 1186 err(4, "Failed to open configuration file %s", path); 1187 line = NULL; 1188 linecap = 0; 1189 lineno = 1; 1190 for (lineno = 1; getline(&line, &linecap, fp) > 0; lineno++) { 1191 if (*line == '#' || *line == '\n') 1192 continue; 1193 cp = strchr(line, '\n'); 1194 if (cp != NULL) 1195 *cp = '\0'; 1196 if (!parse_config_option(line)) 1197 errx(4, "%s line %u: invalid config option '%s'", path, 1198 lineno, line); 1199 } 1200 free(line); 1201 fclose(fp); 1202 } 1203 1204 static void 1205 parse_gdb_options(const char *opt) 1206 { 1207 const char *sport; 1208 char *colon; 1209 1210 if (opt[0] == 'w') { 1211 set_config_bool("gdb.wait", true); 1212 opt++; 1213 } 1214 1215 colon = strrchr(opt, ':'); 1216 if (colon == NULL) { 1217 sport = opt; 1218 } else { 1219 *colon = '\0'; 1220 colon++; 1221 sport = colon; 1222 set_config_value("gdb.address", opt); 1223 } 1224 1225 set_config_value("gdb.port", sport); 1226 } 1227 1228 static void 1229 set_defaults(void) 1230 { 1231 1232 set_config_bool("acpi_tables", false); 1233 set_config_value("memory.size", "256M"); 1234 set_config_bool("x86.strictmsr", true); 1235 } 1236 1237 int 1238 main(int argc, char *argv[]) 1239 { 1240 int c, error, err; 1241 int max_vcpus, memflags; 1242 struct vmctx *ctx; 1243 uint64_t rip; 1244 size_t memsize; 1245 const char *optstr, *value, *vmname; 1246 #ifdef BHYVE_SNAPSHOT 1247 char *restore_file; 1248 struct restore_state rstate; 1249 1250 restore_file = NULL; 1251 #endif 1252 1253 init_config(); 1254 set_defaults(); 1255 progname = basename(argv[0]); 1256 1257 #ifdef BHYVE_SNAPSHOT 1258 optstr = "aehuwxACDHIPSWYk:o:p:G:c:s:m:l:K:U:r:"; 1259 #else 1260 optstr = "aehuwxACDHIPSWYk:o:p:G:c:s:m:l:K:U:"; 1261 #endif 1262 while ((c = getopt(argc, argv, optstr)) != -1) { 1263 switch (c) { 1264 case 'a': 1265 set_config_bool("x86.x2apic", false); 1266 break; 1267 case 'A': 1268 set_config_bool("acpi_tables", true); 1269 break; 1270 case 'D': 1271 set_config_bool("destroy_on_poweroff", true); 1272 break; 1273 case 'p': 1274 if (pincpu_parse(optarg) != 0) { 1275 errx(EX_USAGE, "invalid vcpu pinning " 1276 "configuration '%s'", optarg); 1277 } 1278 break; 1279 case 'c': 1280 if (topology_parse(optarg) != 0) { 1281 errx(EX_USAGE, "invalid cpu topology " 1282 "'%s'", optarg); 1283 } 1284 break; 1285 case 'C': 1286 set_config_bool("memory.guest_in_core", true); 1287 break; 1288 case 'G': 1289 parse_gdb_options(optarg); 1290 break; 1291 case 'k': 1292 parse_simple_config_file(optarg); 1293 break; 1294 case 'K': 1295 set_config_value("keyboard.layout", optarg); 1296 break; 1297 case 'l': 1298 if (strncmp(optarg, "help", strlen(optarg)) == 0) { 1299 lpc_print_supported_devices(); 1300 exit(0); 1301 } else if (lpc_device_parse(optarg) != 0) { 1302 errx(EX_USAGE, "invalid lpc device " 1303 "configuration '%s'", optarg); 1304 } 1305 break; 1306 #ifdef BHYVE_SNAPSHOT 1307 case 'r': 1308 restore_file = optarg; 1309 break; 1310 #endif 1311 case 's': 1312 if (strncmp(optarg, "help", strlen(optarg)) == 0) { 1313 pci_print_supported_devices(); 1314 exit(0); 1315 } else if (pci_parse_slot(optarg) != 0) 1316 exit(4); 1317 else 1318 break; 1319 case 'S': 1320 set_config_bool("memory.wired", true); 1321 break; 1322 case 'm': 1323 set_config_value("memory.size", optarg); 1324 break; 1325 case 'o': 1326 if (!parse_config_option(optarg)) 1327 errx(EX_USAGE, "invalid configuration option '%s'", optarg); 1328 break; 1329 case 'H': 1330 set_config_bool("x86.vmexit_on_hlt", true); 1331 break; 1332 case 'I': 1333 /* 1334 * The "-I" option was used to add an ioapic to the 1335 * virtual machine. 1336 * 1337 * An ioapic is now provided unconditionally for each 1338 * virtual machine and this option is now deprecated. 1339 */ 1340 break; 1341 case 'P': 1342 set_config_bool("x86.vmexit_on_pause", true); 1343 break; 1344 case 'e': 1345 set_config_bool("x86.strictio", true); 1346 break; 1347 case 'u': 1348 set_config_bool("rtc.use_localtime", false); 1349 break; 1350 case 'U': 1351 set_config_value("uuid", optarg); 1352 break; 1353 case 'w': 1354 set_config_bool("x86.strictmsr", false); 1355 break; 1356 case 'W': 1357 set_config_bool("virtio_msix", false); 1358 break; 1359 case 'x': 1360 set_config_bool("x86.x2apic", true); 1361 break; 1362 case 'Y': 1363 set_config_bool("x86.mptable", false); 1364 break; 1365 case 'h': 1366 usage(0); 1367 default: 1368 usage(1); 1369 } 1370 } 1371 argc -= optind; 1372 argv += optind; 1373 1374 if (argc > 1) 1375 usage(1); 1376 1377 #ifdef BHYVE_SNAPSHOT 1378 if (restore_file != NULL) { 1379 error = load_restore_file(restore_file, &rstate); 1380 if (error) { 1381 fprintf(stderr, "Failed to read checkpoint info from " 1382 "file: '%s'.\n", restore_file); 1383 exit(1); 1384 } 1385 vmname = lookup_vmname(&rstate); 1386 if (vmname != NULL) 1387 set_config_value("name", vmname); 1388 } 1389 #endif 1390 1391 if (argc == 1) 1392 set_config_value("name", argv[0]); 1393 1394 vmname = get_config_value("name"); 1395 if (vmname == NULL) 1396 usage(1); 1397 1398 if (get_config_bool_default("config.dump", false)) { 1399 dump_config(); 1400 exit(1); 1401 } 1402 1403 calc_topology(); 1404 build_vcpumaps(); 1405 1406 value = get_config_value("memory.size"); 1407 error = vm_parse_memsize(value, &memsize); 1408 if (error) 1409 errx(EX_USAGE, "invalid memsize '%s'", value); 1410 1411 ctx = do_open(vmname); 1412 1413 #ifdef BHYVE_SNAPSHOT 1414 if (restore_file != NULL) { 1415 guest_ncpus = lookup_guest_ncpus(&rstate); 1416 memflags = lookup_memflags(&rstate); 1417 memsize = lookup_memsize(&rstate); 1418 } 1419 1420 if (guest_ncpus < 1) { 1421 fprintf(stderr, "Invalid guest vCPUs (%d)\n", guest_ncpus); 1422 exit(1); 1423 } 1424 #endif 1425 1426 max_vcpus = num_vcpus_allowed(ctx); 1427 if (guest_ncpus > max_vcpus) { 1428 fprintf(stderr, "%d vCPUs requested but only %d available\n", 1429 guest_ncpus, max_vcpus); 1430 exit(4); 1431 } 1432 1433 fbsdrun_set_capabilities(ctx, BSP); 1434 1435 memflags = 0; 1436 if (get_config_bool_default("memory.wired", false)) 1437 memflags |= VM_MEM_F_WIRED; 1438 if (get_config_bool_default("memory.guest_in_core", false)) 1439 memflags |= VM_MEM_F_INCORE; 1440 vm_set_memflags(ctx, memflags); 1441 err = vm_setup_memory(ctx, memsize, VM_MMAP_ALL); 1442 if (err) { 1443 fprintf(stderr, "Unable to setup memory (%d)\n", errno); 1444 exit(4); 1445 } 1446 1447 error = init_msr(); 1448 if (error) { 1449 fprintf(stderr, "init_msr error %d", error); 1450 exit(4); 1451 } 1452 1453 init_mem(guest_ncpus); 1454 init_inout(); 1455 kernemu_dev_init(); 1456 init_bootrom(ctx); 1457 atkbdc_init(ctx); 1458 pci_irq_init(ctx); 1459 ioapic_init(ctx); 1460 1461 rtc_init(ctx); 1462 sci_init(ctx); 1463 1464 /* 1465 * Exit if a device emulation finds an error in its initilization 1466 */ 1467 if (init_pci(ctx) != 0) { 1468 perror("device emulation initialization error"); 1469 exit(4); 1470 } 1471 1472 /* 1473 * Initialize after PCI, to allow a bootrom file to reserve the high 1474 * region. 1475 */ 1476 if (get_config_bool("acpi_tables")) 1477 vmgenc_init(ctx); 1478 1479 init_gdb(ctx); 1480 1481 if (lpc_bootrom()) { 1482 if (vm_set_capability(ctx, BSP, VM_CAP_UNRESTRICTED_GUEST, 1)) { 1483 fprintf(stderr, "ROM boot failed: unrestricted guest " 1484 "capability not available\n"); 1485 exit(4); 1486 } 1487 error = vcpu_reset(ctx, BSP); 1488 assert(error == 0); 1489 } 1490 1491 #ifdef BHYVE_SNAPSHOT 1492 if (restore_file != NULL) { 1493 fprintf(stdout, "Pausing pci devs...\r\n"); 1494 if (vm_pause_user_devs(ctx) != 0) { 1495 fprintf(stderr, "Failed to pause PCI device state.\n"); 1496 exit(1); 1497 } 1498 1499 fprintf(stdout, "Restoring vm mem...\r\n"); 1500 if (restore_vm_mem(ctx, &rstate) != 0) { 1501 fprintf(stderr, "Failed to restore VM memory.\n"); 1502 exit(1); 1503 } 1504 1505 fprintf(stdout, "Restoring pci devs...\r\n"); 1506 if (vm_restore_user_devs(ctx, &rstate) != 0) { 1507 fprintf(stderr, "Failed to restore PCI device state.\n"); 1508 exit(1); 1509 } 1510 1511 fprintf(stdout, "Restoring kernel structs...\r\n"); 1512 if (vm_restore_kern_structs(ctx, &rstate) != 0) { 1513 fprintf(stderr, "Failed to restore kernel structs.\n"); 1514 exit(1); 1515 } 1516 1517 fprintf(stdout, "Resuming pci devs...\r\n"); 1518 if (vm_resume_user_devs(ctx) != 0) { 1519 fprintf(stderr, "Failed to resume PCI device state.\n"); 1520 exit(1); 1521 } 1522 } 1523 #endif 1524 1525 error = vm_get_register(ctx, BSP, VM_REG_GUEST_RIP, &rip); 1526 assert(error == 0); 1527 1528 /* 1529 * build the guest tables, MP etc. 1530 */ 1531 if (get_config_bool_default("x86.mptable", true)) { 1532 error = mptable_build(ctx, guest_ncpus); 1533 if (error) { 1534 perror("error to build the guest tables"); 1535 exit(4); 1536 } 1537 } 1538 1539 error = smbios_build(ctx); 1540 if (error != 0) 1541 exit(4); 1542 1543 if (get_config_bool("acpi_tables")) { 1544 error = acpi_build(ctx, guest_ncpus); 1545 assert(error == 0); 1546 } 1547 1548 if (lpc_bootrom()) 1549 fwctl_init(); 1550 1551 /* 1552 * Change the proc title to include the VM name. 1553 */ 1554 setproctitle("%s", vmname); 1555 1556 #ifndef WITHOUT_CAPSICUM 1557 caph_cache_catpages(); 1558 1559 if (caph_limit_stdout() == -1 || caph_limit_stderr() == -1) 1560 errx(EX_OSERR, "Unable to apply rights for sandbox"); 1561 1562 if (caph_enter() == -1) 1563 errx(EX_OSERR, "cap_enter() failed"); 1564 #endif 1565 1566 #ifdef BHYVE_SNAPSHOT 1567 if (restore_file != NULL) 1568 destroy_restore_state(&rstate); 1569 1570 /* initialize mutex/cond variables */ 1571 init_snapshot(); 1572 1573 /* 1574 * checkpointing thread for communication with bhyvectl 1575 */ 1576 if (init_checkpoint_thread(ctx) < 0) 1577 printf("Failed to start checkpoint thread!\r\n"); 1578 1579 if (restore_file != NULL) 1580 vm_restore_time(ctx); 1581 #endif 1582 1583 /* Allocate per-VCPU resources. */ 1584 mt_vmm_info = calloc(guest_ncpus, sizeof(*mt_vmm_info)); 1585 1586 /* 1587 * Add all vCPUs. 1588 */ 1589 for (int vcpu = 0; vcpu < guest_ncpus; vcpu++) { 1590 bool suspend = (vcpu != BSP); 1591 #ifdef BHYVE_SNAPSHOT 1592 if (restore_file != NULL) 1593 suspend = false; 1594 #endif 1595 spinup_vcpu(ctx, vcpu, suspend); 1596 } 1597 1598 /* 1599 * Head off to the main event dispatch loop 1600 */ 1601 mevent_dispatch(); 1602 1603 exit(4); 1604 } 1605