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