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 */ 43 44 #include <sys/cdefs.h> 45 __FBSDID("$FreeBSD$"); 46 47 #include <sys/types.h> 48 #ifndef WITHOUT_CAPSICUM 49 #include <sys/capsicum.h> 50 #endif 51 #include <sys/mman.h> 52 #include <sys/time.h> 53 #include <sys/cpuset.h> 54 55 #ifdef __FreeBSD__ 56 #include <amd64/vmm/intel/vmcs.h> 57 #else 58 #include <intel/vmcs.h> 59 #endif 60 61 #include <machine/atomic.h> 62 #include <machine/segments.h> 63 64 #ifndef WITHOUT_CAPSICUM 65 #include <capsicum_helpers.h> 66 #endif 67 #include <stdio.h> 68 #include <stdlib.h> 69 #include <string.h> 70 #include <err.h> 71 #include <errno.h> 72 #include <libgen.h> 73 #include <unistd.h> 74 #include <assert.h> 75 #include <pthread.h> 76 #include <pthread_np.h> 77 #include <sysexits.h> 78 #include <stdbool.h> 79 #include <stdint.h> 80 81 #include <machine/vmm.h> 82 #ifndef WITHOUT_CAPSICUM 83 #include <machine/vmm_dev.h> 84 #endif 85 #include <vmmapi.h> 86 87 #include "bhyverun.h" 88 #include "acpi.h" 89 #include "atkbdc.h" 90 #include "console.h" 91 #include "inout.h" 92 #include "dbgport.h" 93 #include "fwctl.h" 94 #include "gdb.h" 95 #include "ioapic.h" 96 #include "mem.h" 97 #include "mevent.h" 98 #include "mptbl.h" 99 #include "pci_emul.h" 100 #include "pci_irq.h" 101 #include "pci_lpc.h" 102 #include "smbiostbl.h" 103 #include "xmsr.h" 104 #include "spinup_ap.h" 105 #include "rfb.h" 106 #include "rtc.h" 107 #include "vga.h" 108 109 #define GUEST_NIO_PORT 0x488 /* guest upcalls via i/o port */ 110 111 #define MB (1024UL * 1024) 112 #define GB (1024UL * MB) 113 114 static const char * const vmx_exit_reason_desc[] = { 115 [EXIT_REASON_EXCEPTION] = "Exception or non-maskable interrupt (NMI)", 116 [EXIT_REASON_EXT_INTR] = "External interrupt", 117 [EXIT_REASON_TRIPLE_FAULT] = "Triple fault", 118 [EXIT_REASON_INIT] = "INIT signal", 119 [EXIT_REASON_SIPI] = "Start-up IPI (SIPI)", 120 [EXIT_REASON_IO_SMI] = "I/O system-management interrupt (SMI)", 121 [EXIT_REASON_SMI] = "Other SMI", 122 [EXIT_REASON_INTR_WINDOW] = "Interrupt window", 123 [EXIT_REASON_NMI_WINDOW] = "NMI window", 124 [EXIT_REASON_TASK_SWITCH] = "Task switch", 125 [EXIT_REASON_CPUID] = "CPUID", 126 [EXIT_REASON_GETSEC] = "GETSEC", 127 [EXIT_REASON_HLT] = "HLT", 128 [EXIT_REASON_INVD] = "INVD", 129 [EXIT_REASON_INVLPG] = "INVLPG", 130 [EXIT_REASON_RDPMC] = "RDPMC", 131 [EXIT_REASON_RDTSC] = "RDTSC", 132 [EXIT_REASON_RSM] = "RSM", 133 [EXIT_REASON_VMCALL] = "VMCALL", 134 [EXIT_REASON_VMCLEAR] = "VMCLEAR", 135 [EXIT_REASON_VMLAUNCH] = "VMLAUNCH", 136 [EXIT_REASON_VMPTRLD] = "VMPTRLD", 137 [EXIT_REASON_VMPTRST] = "VMPTRST", 138 [EXIT_REASON_VMREAD] = "VMREAD", 139 [EXIT_REASON_VMRESUME] = "VMRESUME", 140 [EXIT_REASON_VMWRITE] = "VMWRITE", 141 [EXIT_REASON_VMXOFF] = "VMXOFF", 142 [EXIT_REASON_VMXON] = "VMXON", 143 [EXIT_REASON_CR_ACCESS] = "Control-register accesses", 144 [EXIT_REASON_DR_ACCESS] = "MOV DR", 145 [EXIT_REASON_INOUT] = "I/O instruction", 146 [EXIT_REASON_RDMSR] = "RDMSR", 147 [EXIT_REASON_WRMSR] = "WRMSR", 148 [EXIT_REASON_INVAL_VMCS] = 149 "VM-entry failure due to invalid guest state", 150 [EXIT_REASON_INVAL_MSR] = "VM-entry failure due to MSR loading", 151 [EXIT_REASON_MWAIT] = "MWAIT", 152 [EXIT_REASON_MTF] = "Monitor trap flag", 153 [EXIT_REASON_MONITOR] = "MONITOR", 154 [EXIT_REASON_PAUSE] = "PAUSE", 155 [EXIT_REASON_MCE_DURING_ENTRY] = 156 "VM-entry failure due to machine-check event", 157 [EXIT_REASON_TPR] = "TPR below threshold", 158 [EXIT_REASON_APIC_ACCESS] = "APIC access", 159 [EXIT_REASON_VIRTUALIZED_EOI] = "Virtualized EOI", 160 [EXIT_REASON_GDTR_IDTR] = "Access to GDTR or IDTR", 161 [EXIT_REASON_LDTR_TR] = "Access to LDTR or TR", 162 [EXIT_REASON_EPT_FAULT] = "EPT violation", 163 [EXIT_REASON_EPT_MISCONFIG] = "EPT misconfiguration", 164 [EXIT_REASON_INVEPT] = "INVEPT", 165 [EXIT_REASON_RDTSCP] = "RDTSCP", 166 [EXIT_REASON_VMX_PREEMPT] = "VMX-preemption timer expired", 167 [EXIT_REASON_INVVPID] = "INVVPID", 168 [EXIT_REASON_WBINVD] = "WBINVD", 169 [EXIT_REASON_XSETBV] = "XSETBV", 170 [EXIT_REASON_APIC_WRITE] = "APIC write", 171 [EXIT_REASON_RDRAND] = "RDRAND", 172 [EXIT_REASON_INVPCID] = "INVPCID", 173 [EXIT_REASON_VMFUNC] = "VMFUNC", 174 [EXIT_REASON_ENCLS] = "ENCLS", 175 [EXIT_REASON_RDSEED] = "RDSEED", 176 [EXIT_REASON_PM_LOG_FULL] = "Page-modification log full", 177 [EXIT_REASON_XSAVES] = "XSAVES", 178 [EXIT_REASON_XRSTORS] = "XRSTORS" 179 }; 180 181 typedef int (*vmexit_handler_t)(struct vmctx *, struct vm_exit *, int *vcpu); 182 extern int vmexit_task_switch(struct vmctx *, struct vm_exit *, int *vcpu); 183 184 char *vmname; 185 186 int guest_ncpus; 187 uint16_t cores, maxcpus, sockets, threads; 188 189 char *guest_uuid_str; 190 191 static int guest_vmexit_on_hlt, guest_vmexit_on_pause; 192 static int virtio_msix = 1; 193 static int x2apic_mode = 0; /* default is xAPIC */ 194 195 static int strictio; 196 static int strictmsr = 1; 197 198 static int acpi; 199 200 static char *progname; 201 static const int BSP = 0; 202 203 #ifndef __FreeBSD__ 204 int bcons_wait = 0; 205 int bcons_connected = 0; 206 pthread_mutex_t bcons_wait_lock = PTHREAD_MUTEX_INITIALIZER; 207 pthread_cond_t bcons_wait_done = PTHREAD_COND_INITIALIZER; 208 #endif 209 210 static cpuset_t cpumask; 211 212 static void vm_loop(struct vmctx *ctx, int vcpu, uint64_t rip); 213 214 static struct vm_exit vmexit[VM_MAXCPU]; 215 216 struct bhyvestats { 217 uint64_t vmexit_bogus; 218 uint64_t vmexit_reqidle; 219 uint64_t vmexit_hlt; 220 uint64_t vmexit_pause; 221 uint64_t vmexit_mtrap; 222 uint64_t vmexit_inst_emul; 223 uint64_t cpu_switch_rotate; 224 uint64_t cpu_switch_direct; 225 } stats; 226 227 struct mt_vmm_info { 228 pthread_t mt_thr; 229 struct vmctx *mt_ctx; 230 int mt_vcpu; 231 } mt_vmm_info[VM_MAXCPU]; 232 233 #ifdef __FreeBSD__ 234 static cpuset_t *vcpumap[VM_MAXCPU] = { NULL }; 235 #endif 236 237 static void 238 usage(int code) 239 { 240 241 fprintf(stderr, 242 "Usage: %s [-abehuwxACHPSWY]\n" 243 " %*s [-c [[cpus=]numcpus][,sockets=n][,cores=n][,threads=n]]\n" 244 " %*s [-g <gdb port>] [-l <lpc>]\n" 245 #ifdef __FreeBSD__ 246 " %*s [-m mem] [-p vcpu:hostcpu] [-s <pci>] [-U uuid] <vm>\n" 247 #else 248 " %*s [-m mem] [-s <pci>] [-U uuid] <vm>\n" 249 #endif 250 " -a: local apic is in xAPIC mode (deprecated)\n" 251 " -A: create ACPI tables\n" 252 " -c: number of cpus and/or topology specification\n" 253 " -C: include guest memory in core file\n" 254 " -e: exit on unhandled I/O access\n" 255 " -g: gdb port\n" 256 " -h: help\n" 257 " -H: vmexit from the guest on hlt\n" 258 " -l: LPC device configuration\n" 259 " -m: memory size\n" 260 #ifdef __FreeBSD__ 261 " -p: pin 'vcpu' to 'hostcpu'\n" 262 #endif 263 " -P: vmexit from the guest on pause\n" 264 " -s: <slot,driver,configinfo> PCI slot config\n" 265 " -S: guest memory cannot be swapped\n" 266 " -u: RTC keeps UTC time\n" 267 " -U: uuid\n" 268 " -w: ignore unimplemented MSRs\n" 269 " -W: force virtio to use single-vector MSI\n" 270 " -x: local apic is in x2APIC mode\n" 271 " -Y: disable MPtable generation\n", 272 progname, (int)strlen(progname), "", (int)strlen(progname), "", 273 (int)strlen(progname), ""); 274 275 exit(code); 276 } 277 278 /* 279 * XXX This parser is known to have the following issues: 280 * 1. It accepts null key=value tokens ",,". 281 * 2. It accepts whitespace after = and before value. 282 * 3. Values out of range of INT are silently wrapped. 283 * 4. It doesn't check non-final values. 284 * 5. The apparently bogus limits of UINT16_MAX are for future expansion. 285 * 286 * The acceptance of a null specification ('-c ""') is by design to match the 287 * manual page syntax specification, this results in a topology of 1 vCPU. 288 */ 289 static int 290 topology_parse(const char *opt) 291 { 292 uint64_t ncpus; 293 int c, chk, n, s, t, tmp; 294 char *cp, *str; 295 bool ns, scts; 296 297 c = 1, n = 1, s = 1, t = 1; 298 ns = false, scts = false; 299 str = strdup(opt); 300 if (str == NULL) 301 goto out; 302 303 while ((cp = strsep(&str, ",")) != NULL) { 304 if (sscanf(cp, "%i%n", &tmp, &chk) == 1) { 305 n = tmp; 306 ns = true; 307 } else if (sscanf(cp, "cpus=%i%n", &tmp, &chk) == 1) { 308 n = tmp; 309 ns = true; 310 } else if (sscanf(cp, "sockets=%i%n", &tmp, &chk) == 1) { 311 s = tmp; 312 scts = true; 313 } else if (sscanf(cp, "cores=%i%n", &tmp, &chk) == 1) { 314 c = tmp; 315 scts = true; 316 } else if (sscanf(cp, "threads=%i%n", &tmp, &chk) == 1) { 317 t = tmp; 318 scts = true; 319 #ifdef notyet /* Do not expose this until vmm.ko implements it */ 320 } else if (sscanf(cp, "maxcpus=%i%n", &tmp, &chk) == 1) { 321 m = tmp; 322 #endif 323 /* Skip the empty argument case from -c "" */ 324 } else if (cp[0] == '\0') 325 continue; 326 else 327 goto out; 328 /* Any trailing garbage causes an error */ 329 if (cp[chk] != '\0') 330 goto out; 331 } 332 free(str); 333 str = NULL; 334 335 /* 336 * Range check 1 <= n <= UINT16_MAX all values 337 */ 338 if (n < 1 || s < 1 || c < 1 || t < 1 || 339 n > UINT16_MAX || s > UINT16_MAX || c > UINT16_MAX || 340 t > UINT16_MAX) 341 return (-1); 342 343 /* If only the cpus was specified, use that as sockets */ 344 if (!scts) 345 s = n; 346 /* 347 * Compute sockets * cores * threads avoiding overflow 348 * The range check above insures these are 16 bit values 349 * If n was specified check it against computed ncpus 350 */ 351 ncpus = (uint64_t)s * c * t; 352 if (ncpus > UINT16_MAX || (ns && n != ncpus)) 353 return (-1); 354 355 guest_ncpus = ncpus; 356 sockets = s; 357 cores = c; 358 threads = t; 359 return(0); 360 361 out: 362 free(str); 363 return (-1); 364 } 365 366 #ifndef WITHOUT_CAPSICUM 367 /* 368 * 11-stable capsicum helpers 369 */ 370 static void 371 bhyve_caph_cache_catpages(void) 372 { 373 374 (void)catopen("libc", NL_CAT_LOCALE); 375 } 376 377 static int 378 bhyve_caph_limit_stdoe(void) 379 { 380 cap_rights_t rights; 381 unsigned long cmds[] = { TIOCGETA, TIOCGWINSZ }; 382 int i, fds[] = { STDOUT_FILENO, STDERR_FILENO }; 383 384 cap_rights_init(&rights, CAP_FCNTL, CAP_FSTAT, CAP_IOCTL); 385 cap_rights_set(&rights, CAP_WRITE); 386 387 for (i = 0; i < nitems(fds); i++) { 388 if (cap_rights_limit(fds[i], &rights) < 0 && errno != ENOSYS) 389 return (-1); 390 391 if (cap_ioctls_limit(fds[i], cmds, nitems(cmds)) < 0 && errno != ENOSYS) 392 return (-1); 393 394 if (cap_fcntls_limit(fds[i], CAP_FCNTL_GETFL) < 0 && errno != ENOSYS) 395 return (-1); 396 } 397 398 return (0); 399 } 400 401 #endif 402 403 #ifdef __FreeBSD__ 404 static int 405 pincpu_parse(const char *opt) 406 { 407 int vcpu, pcpu; 408 409 if (sscanf(opt, "%d:%d", &vcpu, &pcpu) != 2) { 410 fprintf(stderr, "invalid format: %s\n", opt); 411 return (-1); 412 } 413 414 if (vcpu < 0 || vcpu >= VM_MAXCPU) { 415 fprintf(stderr, "vcpu '%d' outside valid range from 0 to %d\n", 416 vcpu, VM_MAXCPU - 1); 417 return (-1); 418 } 419 420 if (pcpu < 0 || pcpu >= CPU_SETSIZE) { 421 fprintf(stderr, "hostcpu '%d' outside valid range from " 422 "0 to %d\n", pcpu, CPU_SETSIZE - 1); 423 return (-1); 424 } 425 426 if (vcpumap[vcpu] == NULL) { 427 if ((vcpumap[vcpu] = malloc(sizeof(cpuset_t))) == NULL) { 428 perror("malloc"); 429 return (-1); 430 } 431 CPU_ZERO(vcpumap[vcpu]); 432 } 433 CPU_SET(pcpu, vcpumap[vcpu]); 434 return (0); 435 } 436 #endif 437 438 void 439 vm_inject_fault(void *arg, int vcpu, int vector, int errcode_valid, 440 int errcode) 441 { 442 struct vmctx *ctx; 443 int error, restart_instruction; 444 445 ctx = arg; 446 restart_instruction = 1; 447 448 error = vm_inject_exception(ctx, vcpu, vector, errcode_valid, errcode, 449 restart_instruction); 450 assert(error == 0); 451 } 452 453 void * 454 paddr_guest2host(struct vmctx *ctx, uintptr_t gaddr, size_t len) 455 { 456 457 return (vm_map_gpa(ctx, gaddr, len)); 458 } 459 460 int 461 fbsdrun_vmexit_on_pause(void) 462 { 463 464 return (guest_vmexit_on_pause); 465 } 466 467 int 468 fbsdrun_vmexit_on_hlt(void) 469 { 470 471 return (guest_vmexit_on_hlt); 472 } 473 474 int 475 fbsdrun_virtio_msix(void) 476 { 477 478 return (virtio_msix); 479 } 480 481 static void * 482 fbsdrun_start_thread(void *param) 483 { 484 char tname[MAXCOMLEN + 1]; 485 struct mt_vmm_info *mtp; 486 int vcpu; 487 488 mtp = param; 489 vcpu = mtp->mt_vcpu; 490 491 snprintf(tname, sizeof(tname), "vcpu %d", vcpu); 492 pthread_set_name_np(mtp->mt_thr, tname); 493 494 gdb_cpu_add(vcpu); 495 496 vm_loop(mtp->mt_ctx, vcpu, vmexit[vcpu].rip); 497 498 /* not reached */ 499 exit(1); 500 return (NULL); 501 } 502 503 void 504 fbsdrun_addcpu(struct vmctx *ctx, int fromcpu, int newcpu, uint64_t rip) 505 { 506 int error; 507 508 assert(fromcpu == BSP); 509 510 /* 511 * The 'newcpu' must be activated in the context of 'fromcpu'. If 512 * vm_activate_cpu() is delayed until newcpu's pthread starts running 513 * then vmm.ko is out-of-sync with bhyve and this can create a race 514 * with vm_suspend(). 515 */ 516 error = vm_activate_cpu(ctx, newcpu); 517 if (error != 0) 518 err(EX_OSERR, "could not activate CPU %d", newcpu); 519 520 CPU_SET_ATOMIC(newcpu, &cpumask); 521 522 /* 523 * Set up the vmexit struct to allow execution to start 524 * at the given RIP 525 */ 526 vmexit[newcpu].rip = rip; 527 vmexit[newcpu].inst_length = 0; 528 529 mt_vmm_info[newcpu].mt_ctx = ctx; 530 mt_vmm_info[newcpu].mt_vcpu = newcpu; 531 532 error = pthread_create(&mt_vmm_info[newcpu].mt_thr, NULL, 533 fbsdrun_start_thread, &mt_vmm_info[newcpu]); 534 assert(error == 0); 535 } 536 537 static int 538 fbsdrun_deletecpu(struct vmctx *ctx, int vcpu) 539 { 540 541 if (!CPU_ISSET(vcpu, &cpumask)) { 542 fprintf(stderr, "Attempting to delete unknown cpu %d\n", vcpu); 543 exit(4); 544 } 545 546 CPU_CLR_ATOMIC(vcpu, &cpumask); 547 return (CPU_EMPTY(&cpumask)); 548 } 549 550 static int 551 vmexit_handle_notify(struct vmctx *ctx, struct vm_exit *vme, int *pvcpu, 552 uint32_t eax) 553 { 554 #if BHYVE_DEBUG 555 /* 556 * put guest-driven debug here 557 */ 558 #endif 559 return (VMEXIT_CONTINUE); 560 } 561 562 static int 563 vmexit_inout(struct vmctx *ctx, struct vm_exit *vme, int *pvcpu) 564 { 565 int error; 566 int bytes, port, in, out; 567 int vcpu; 568 569 vcpu = *pvcpu; 570 571 port = vme->u.inout.port; 572 bytes = vme->u.inout.bytes; 573 in = vme->u.inout.in; 574 out = !in; 575 576 /* Extra-special case of host notifications */ 577 if (out && port == GUEST_NIO_PORT) { 578 error = vmexit_handle_notify(ctx, vme, pvcpu, vme->u.inout.eax); 579 return (error); 580 } 581 582 error = emulate_inout(ctx, vcpu, vme, strictio); 583 if (error) { 584 fprintf(stderr, "Unhandled %s%c 0x%04x at 0x%lx\n", 585 in ? "in" : "out", 586 bytes == 1 ? 'b' : (bytes == 2 ? 'w' : 'l'), 587 port, vmexit->rip); 588 return (VMEXIT_ABORT); 589 } else { 590 return (VMEXIT_CONTINUE); 591 } 592 } 593 594 static int 595 vmexit_rdmsr(struct vmctx *ctx, struct vm_exit *vme, int *pvcpu) 596 { 597 uint64_t val; 598 uint32_t eax, edx; 599 int error; 600 601 val = 0; 602 error = emulate_rdmsr(ctx, *pvcpu, vme->u.msr.code, &val); 603 if (error != 0) { 604 fprintf(stderr, "rdmsr to register %#x on vcpu %d\n", 605 vme->u.msr.code, *pvcpu); 606 if (strictmsr) { 607 vm_inject_gp(ctx, *pvcpu); 608 return (VMEXIT_CONTINUE); 609 } 610 } 611 612 eax = val; 613 error = vm_set_register(ctx, *pvcpu, VM_REG_GUEST_RAX, eax); 614 assert(error == 0); 615 616 edx = val >> 32; 617 error = vm_set_register(ctx, *pvcpu, VM_REG_GUEST_RDX, edx); 618 assert(error == 0); 619 620 return (VMEXIT_CONTINUE); 621 } 622 623 static int 624 vmexit_wrmsr(struct vmctx *ctx, struct vm_exit *vme, int *pvcpu) 625 { 626 int error; 627 628 error = emulate_wrmsr(ctx, *pvcpu, vme->u.msr.code, vme->u.msr.wval); 629 if (error != 0) { 630 fprintf(stderr, "wrmsr to register %#x(%#lx) on vcpu %d\n", 631 vme->u.msr.code, vme->u.msr.wval, *pvcpu); 632 if (strictmsr) { 633 vm_inject_gp(ctx, *pvcpu); 634 return (VMEXIT_CONTINUE); 635 } 636 } 637 return (VMEXIT_CONTINUE); 638 } 639 640 static int 641 vmexit_spinup_ap(struct vmctx *ctx, struct vm_exit *vme, int *pvcpu) 642 { 643 644 (void)spinup_ap(ctx, *pvcpu, 645 vme->u.spinup_ap.vcpu, vme->u.spinup_ap.rip); 646 647 return (VMEXIT_CONTINUE); 648 } 649 650 #define DEBUG_EPT_MISCONFIG 651 #ifdef DEBUG_EPT_MISCONFIG 652 #define VMCS_GUEST_PHYSICAL_ADDRESS 0x00002400 653 654 static uint64_t ept_misconfig_gpa, ept_misconfig_pte[4]; 655 static int ept_misconfig_ptenum; 656 #endif 657 658 static const char * 659 vmexit_vmx_desc(uint32_t exit_reason) 660 { 661 662 if (exit_reason >= nitems(vmx_exit_reason_desc) || 663 vmx_exit_reason_desc[exit_reason] == NULL) 664 return ("Unknown"); 665 return (vmx_exit_reason_desc[exit_reason]); 666 } 667 668 static int 669 vmexit_vmx(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu) 670 { 671 672 fprintf(stderr, "vm exit[%d]\n", *pvcpu); 673 fprintf(stderr, "\treason\t\tVMX\n"); 674 fprintf(stderr, "\trip\t\t0x%016lx\n", vmexit->rip); 675 fprintf(stderr, "\tinst_length\t%d\n", vmexit->inst_length); 676 fprintf(stderr, "\tstatus\t\t%d\n", vmexit->u.vmx.status); 677 fprintf(stderr, "\texit_reason\t%u (%s)\n", vmexit->u.vmx.exit_reason, 678 vmexit_vmx_desc(vmexit->u.vmx.exit_reason)); 679 fprintf(stderr, "\tqualification\t0x%016lx\n", 680 vmexit->u.vmx.exit_qualification); 681 fprintf(stderr, "\tinst_type\t\t%d\n", vmexit->u.vmx.inst_type); 682 fprintf(stderr, "\tinst_error\t\t%d\n", vmexit->u.vmx.inst_error); 683 #ifdef DEBUG_EPT_MISCONFIG 684 if (vmexit->u.vmx.exit_reason == EXIT_REASON_EPT_MISCONFIG) { 685 vm_get_register(ctx, *pvcpu, 686 VMCS_IDENT(VMCS_GUEST_PHYSICAL_ADDRESS), 687 &ept_misconfig_gpa); 688 vm_get_gpa_pmap(ctx, ept_misconfig_gpa, ept_misconfig_pte, 689 &ept_misconfig_ptenum); 690 fprintf(stderr, "\tEPT misconfiguration:\n"); 691 fprintf(stderr, "\t\tGPA: %#lx\n", ept_misconfig_gpa); 692 fprintf(stderr, "\t\tPTE(%d): %#lx %#lx %#lx %#lx\n", 693 ept_misconfig_ptenum, ept_misconfig_pte[0], 694 ept_misconfig_pte[1], ept_misconfig_pte[2], 695 ept_misconfig_pte[3]); 696 } 697 #endif /* DEBUG_EPT_MISCONFIG */ 698 return (VMEXIT_ABORT); 699 } 700 701 static int 702 vmexit_svm(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu) 703 { 704 705 fprintf(stderr, "vm exit[%d]\n", *pvcpu); 706 fprintf(stderr, "\treason\t\tSVM\n"); 707 fprintf(stderr, "\trip\t\t0x%016lx\n", vmexit->rip); 708 fprintf(stderr, "\tinst_length\t%d\n", vmexit->inst_length); 709 fprintf(stderr, "\texitcode\t%#lx\n", vmexit->u.svm.exitcode); 710 fprintf(stderr, "\texitinfo1\t%#lx\n", vmexit->u.svm.exitinfo1); 711 fprintf(stderr, "\texitinfo2\t%#lx\n", vmexit->u.svm.exitinfo2); 712 return (VMEXIT_ABORT); 713 } 714 715 static int 716 vmexit_bogus(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu) 717 { 718 719 assert(vmexit->inst_length == 0); 720 721 stats.vmexit_bogus++; 722 723 return (VMEXIT_CONTINUE); 724 } 725 726 static int 727 vmexit_reqidle(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu) 728 { 729 730 assert(vmexit->inst_length == 0); 731 732 stats.vmexit_reqidle++; 733 734 return (VMEXIT_CONTINUE); 735 } 736 737 static int 738 vmexit_hlt(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu) 739 { 740 741 stats.vmexit_hlt++; 742 743 /* 744 * Just continue execution with the next instruction. We use 745 * the HLT VM exit as a way to be friendly with the host 746 * scheduler. 747 */ 748 return (VMEXIT_CONTINUE); 749 } 750 751 static int 752 vmexit_pause(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu) 753 { 754 755 stats.vmexit_pause++; 756 757 return (VMEXIT_CONTINUE); 758 } 759 760 static int 761 vmexit_mtrap(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu) 762 { 763 764 assert(vmexit->inst_length == 0); 765 766 stats.vmexit_mtrap++; 767 768 gdb_cpu_mtrap(*pvcpu); 769 770 return (VMEXIT_CONTINUE); 771 } 772 773 static int 774 vmexit_inst_emul(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu) 775 { 776 int err, i; 777 struct vie *vie; 778 779 stats.vmexit_inst_emul++; 780 781 vie = &vmexit->u.inst_emul.vie; 782 err = emulate_mem(ctx, *pvcpu, vmexit->u.inst_emul.gpa, 783 vie, &vmexit->u.inst_emul.paging); 784 785 if (err) { 786 if (err == ESRCH) { 787 fprintf(stderr, "Unhandled memory access to 0x%lx\n", 788 vmexit->u.inst_emul.gpa); 789 } 790 791 fprintf(stderr, "Failed to emulate instruction ["); 792 for (i = 0; i < vie->num_valid; i++) { 793 fprintf(stderr, "0x%02x%s", vie->inst[i], 794 i != (vie->num_valid - 1) ? " " : ""); 795 } 796 fprintf(stderr, "] at 0x%lx\n", vmexit->rip); 797 return (VMEXIT_ABORT); 798 } 799 800 return (VMEXIT_CONTINUE); 801 } 802 803 static pthread_mutex_t resetcpu_mtx = PTHREAD_MUTEX_INITIALIZER; 804 static pthread_cond_t resetcpu_cond = PTHREAD_COND_INITIALIZER; 805 806 static int 807 vmexit_suspend(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu) 808 { 809 enum vm_suspend_how how; 810 811 how = vmexit->u.suspended.how; 812 813 fbsdrun_deletecpu(ctx, *pvcpu); 814 815 if (*pvcpu != BSP) { 816 pthread_mutex_lock(&resetcpu_mtx); 817 pthread_cond_signal(&resetcpu_cond); 818 pthread_mutex_unlock(&resetcpu_mtx); 819 pthread_exit(NULL); 820 } 821 822 pthread_mutex_lock(&resetcpu_mtx); 823 while (!CPU_EMPTY(&cpumask)) { 824 pthread_cond_wait(&resetcpu_cond, &resetcpu_mtx); 825 } 826 pthread_mutex_unlock(&resetcpu_mtx); 827 828 switch (how) { 829 case VM_SUSPEND_RESET: 830 exit(0); 831 case VM_SUSPEND_POWEROFF: 832 exit(1); 833 case VM_SUSPEND_HALT: 834 exit(2); 835 case VM_SUSPEND_TRIPLEFAULT: 836 exit(3); 837 default: 838 fprintf(stderr, "vmexit_suspend: invalid reason %d\n", how); 839 exit(100); 840 } 841 return (0); /* NOTREACHED */ 842 } 843 844 static int 845 vmexit_debug(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu) 846 { 847 848 gdb_cpu_suspend(*pvcpu); 849 return (VMEXIT_CONTINUE); 850 } 851 852 static vmexit_handler_t handler[VM_EXITCODE_MAX] = { 853 [VM_EXITCODE_INOUT] = vmexit_inout, 854 [VM_EXITCODE_INOUT_STR] = vmexit_inout, 855 [VM_EXITCODE_VMX] = vmexit_vmx, 856 [VM_EXITCODE_SVM] = vmexit_svm, 857 [VM_EXITCODE_BOGUS] = vmexit_bogus, 858 [VM_EXITCODE_REQIDLE] = vmexit_reqidle, 859 [VM_EXITCODE_RDMSR] = vmexit_rdmsr, 860 [VM_EXITCODE_WRMSR] = vmexit_wrmsr, 861 [VM_EXITCODE_MTRAP] = vmexit_mtrap, 862 [VM_EXITCODE_INST_EMUL] = vmexit_inst_emul, 863 [VM_EXITCODE_SPINUP_AP] = vmexit_spinup_ap, 864 [VM_EXITCODE_SUSPENDED] = vmexit_suspend, 865 [VM_EXITCODE_TASK_SWITCH] = vmexit_task_switch, 866 [VM_EXITCODE_DEBUG] = vmexit_debug, 867 }; 868 869 static void 870 vm_loop(struct vmctx *ctx, int vcpu, uint64_t startrip) 871 { 872 int error, rc; 873 enum vm_exitcode exitcode; 874 cpuset_t active_cpus; 875 876 #ifdef __FreeBSD__ 877 if (vcpumap[vcpu] != NULL) { 878 error = pthread_setaffinity_np(pthread_self(), 879 sizeof(cpuset_t), vcpumap[vcpu]); 880 assert(error == 0); 881 } 882 #endif 883 error = vm_active_cpus(ctx, &active_cpus); 884 assert(CPU_ISSET(vcpu, &active_cpus)); 885 886 error = vm_set_register(ctx, vcpu, VM_REG_GUEST_RIP, startrip); 887 assert(error == 0); 888 889 while (1) { 890 error = vm_run(ctx, vcpu, &vmexit[vcpu]); 891 if (error != 0) 892 break; 893 894 exitcode = vmexit[vcpu].exitcode; 895 if (exitcode >= VM_EXITCODE_MAX || handler[exitcode] == NULL) { 896 fprintf(stderr, "vm_loop: unexpected exitcode 0x%x\n", 897 exitcode); 898 exit(4); 899 } 900 901 rc = (*handler[exitcode])(ctx, &vmexit[vcpu], &vcpu); 902 903 switch (rc) { 904 case VMEXIT_CONTINUE: 905 break; 906 case VMEXIT_ABORT: 907 abort(); 908 default: 909 exit(4); 910 } 911 } 912 fprintf(stderr, "vm_run error %d, errno %d\n", error, errno); 913 } 914 915 static int 916 num_vcpus_allowed(struct vmctx *ctx) 917 { 918 int tmp, error; 919 920 error = vm_get_capability(ctx, BSP, VM_CAP_UNRESTRICTED_GUEST, &tmp); 921 922 /* 923 * The guest is allowed to spinup more than one processor only if the 924 * UNRESTRICTED_GUEST capability is available. 925 */ 926 if (error == 0) 927 return (VM_MAXCPU); 928 else 929 return (1); 930 } 931 932 void 933 fbsdrun_set_capabilities(struct vmctx *ctx, int cpu) 934 { 935 int err, tmp; 936 937 if (fbsdrun_vmexit_on_hlt()) { 938 err = vm_get_capability(ctx, cpu, VM_CAP_HALT_EXIT, &tmp); 939 if (err < 0) { 940 fprintf(stderr, "VM exit on HLT not supported\n"); 941 exit(4); 942 } 943 vm_set_capability(ctx, cpu, VM_CAP_HALT_EXIT, 1); 944 if (cpu == BSP) 945 handler[VM_EXITCODE_HLT] = vmexit_hlt; 946 } 947 948 if (fbsdrun_vmexit_on_pause()) { 949 /* 950 * pause exit support required for this mode 951 */ 952 err = vm_get_capability(ctx, cpu, VM_CAP_PAUSE_EXIT, &tmp); 953 if (err < 0) { 954 fprintf(stderr, 955 "SMP mux requested, no pause support\n"); 956 exit(4); 957 } 958 vm_set_capability(ctx, cpu, VM_CAP_PAUSE_EXIT, 1); 959 if (cpu == BSP) 960 handler[VM_EXITCODE_PAUSE] = vmexit_pause; 961 } 962 963 if (x2apic_mode) 964 err = vm_set_x2apic_state(ctx, cpu, X2APIC_ENABLED); 965 else 966 err = vm_set_x2apic_state(ctx, cpu, X2APIC_DISABLED); 967 968 if (err) { 969 fprintf(stderr, "Unable to set x2apic state (%d)\n", err); 970 exit(4); 971 } 972 973 #ifdef __FreeBSD__ 974 vm_set_capability(ctx, cpu, VM_CAP_ENABLE_INVPCID, 1); 975 #endif 976 } 977 978 static struct vmctx * 979 do_open(const char *vmname) 980 { 981 struct vmctx *ctx; 982 int error; 983 bool reinit, romboot; 984 #ifndef WITHOUT_CAPSICUM 985 cap_rights_t rights; 986 const cap_ioctl_t *cmds; 987 size_t ncmds; 988 #endif 989 990 reinit = romboot = false; 991 992 if (lpc_bootrom()) 993 romboot = true; 994 995 error = vm_create(vmname); 996 if (error) { 997 if (errno == EEXIST) { 998 if (romboot) { 999 reinit = true; 1000 } else { 1001 /* 1002 * The virtual machine has been setup by the 1003 * userspace bootloader. 1004 */ 1005 } 1006 } else { 1007 perror("vm_create"); 1008 exit(4); 1009 } 1010 } else { 1011 if (!romboot) { 1012 /* 1013 * If the virtual machine was just created then a 1014 * bootrom must be configured to boot it. 1015 */ 1016 fprintf(stderr, "virtual machine cannot be booted\n"); 1017 exit(4); 1018 } 1019 } 1020 1021 ctx = vm_open(vmname); 1022 if (ctx == NULL) { 1023 perror("vm_open"); 1024 exit(4); 1025 } 1026 1027 #ifndef WITHOUT_CAPSICUM 1028 cap_rights_init(&rights, CAP_IOCTL, CAP_MMAP_RW); 1029 if (caph_rights_limit(vm_get_device_fd(ctx), &rights) == -1) 1030 errx(EX_OSERR, "Unable to apply rights for sandbox"); 1031 vm_get_ioctls(&ncmds); 1032 cmds = vm_get_ioctls(NULL); 1033 if (cmds == NULL) 1034 errx(EX_OSERR, "out of memory"); 1035 if (caph_ioctls_limit(vm_get_device_fd(ctx), cmds, ncmds) == -1) 1036 errx(EX_OSERR, "Unable to apply rights for sandbox"); 1037 free((cap_ioctl_t *)cmds); 1038 #endif 1039 1040 if (reinit) { 1041 error = vm_reinit(ctx); 1042 if (error) { 1043 perror("vm_reinit"); 1044 exit(4); 1045 } 1046 } 1047 error = vm_set_topology(ctx, sockets, cores, threads, maxcpus); 1048 if (error) 1049 errx(EX_OSERR, "vm_set_topology"); 1050 return (ctx); 1051 } 1052 1053 int 1054 main(int argc, char *argv[]) 1055 { 1056 int c, error, dbg_port, gdb_port, err, bvmcons; 1057 int max_vcpus, mptgen, memflags; 1058 int rtc_localtime; 1059 bool gdb_stop; 1060 struct vmctx *ctx; 1061 uint64_t rip; 1062 size_t memsize; 1063 char *optstr; 1064 1065 bvmcons = 0; 1066 progname = basename(argv[0]); 1067 dbg_port = 0; 1068 gdb_port = 0; 1069 gdb_stop = false; 1070 guest_ncpus = 1; 1071 sockets = cores = threads = 1; 1072 maxcpus = 0; 1073 memsize = 256 * MB; 1074 mptgen = 1; 1075 rtc_localtime = 1; 1076 memflags = 0; 1077 1078 #ifdef __FreeBSD__ 1079 optstr = "abehuwxACHIPSWYp:g:G:c:s:m:l:B:U:"; 1080 #else 1081 optstr = "abehuwxACHIPSWYg:G:c:s:m:l:B:U:"; 1082 #endif 1083 while ((c = getopt(argc, argv, optstr)) != -1) { 1084 switch (c) { 1085 case 'a': 1086 x2apic_mode = 0; 1087 break; 1088 case 'A': 1089 acpi = 1; 1090 break; 1091 case 'b': 1092 bvmcons = 1; 1093 break; 1094 case 'B': 1095 if (smbios_parse(optarg) != 0) { 1096 errx(EX_USAGE, "invalid SMBIOS " 1097 "configuration '%s'", optarg); 1098 } 1099 break; 1100 #ifdef __FreeBSD__ 1101 case 'p': 1102 if (pincpu_parse(optarg) != 0) { 1103 errx(EX_USAGE, "invalid vcpu pinning " 1104 "configuration '%s'", optarg); 1105 } 1106 break; 1107 #endif 1108 case 'c': 1109 if (topology_parse(optarg) != 0) { 1110 errx(EX_USAGE, "invalid cpu topology " 1111 "'%s'", optarg); 1112 } 1113 break; 1114 case 'C': 1115 memflags |= VM_MEM_F_INCORE; 1116 break; 1117 case 'g': 1118 dbg_port = atoi(optarg); 1119 break; 1120 case 'G': 1121 if (optarg[0] == 'w') { 1122 gdb_stop = true; 1123 optarg++; 1124 } 1125 gdb_port = atoi(optarg); 1126 break; 1127 case 'l': 1128 if (strncmp(optarg, "help", strlen(optarg)) == 0) { 1129 lpc_print_supported_devices(); 1130 exit(0); 1131 } else if (lpc_device_parse(optarg) != 0) { 1132 errx(EX_USAGE, "invalid lpc device " 1133 "configuration '%s'", optarg); 1134 } 1135 break; 1136 case 's': 1137 if (strncmp(optarg, "help", strlen(optarg)) == 0) { 1138 pci_print_supported_devices(); 1139 exit(0); 1140 } else if (pci_parse_slot(optarg) != 0) 1141 exit(4); 1142 else 1143 break; 1144 case 'S': 1145 memflags |= VM_MEM_F_WIRED; 1146 break; 1147 case 'm': 1148 error = vm_parse_memsize(optarg, &memsize); 1149 if (error) 1150 errx(EX_USAGE, "invalid memsize '%s'", optarg); 1151 break; 1152 case 'H': 1153 guest_vmexit_on_hlt = 1; 1154 break; 1155 case 'I': 1156 /* 1157 * The "-I" option was used to add an ioapic to the 1158 * virtual machine. 1159 * 1160 * An ioapic is now provided unconditionally for each 1161 * virtual machine and this option is now deprecated. 1162 */ 1163 break; 1164 case 'P': 1165 guest_vmexit_on_pause = 1; 1166 break; 1167 case 'e': 1168 strictio = 1; 1169 break; 1170 case 'u': 1171 rtc_localtime = 0; 1172 break; 1173 case 'U': 1174 guest_uuid_str = optarg; 1175 break; 1176 case 'w': 1177 strictmsr = 0; 1178 break; 1179 case 'W': 1180 virtio_msix = 0; 1181 break; 1182 case 'x': 1183 x2apic_mode = 1; 1184 break; 1185 case 'Y': 1186 mptgen = 0; 1187 break; 1188 case 'h': 1189 usage(0); 1190 default: 1191 usage(1); 1192 } 1193 } 1194 argc -= optind; 1195 argv += optind; 1196 1197 if (argc != 1) 1198 usage(1); 1199 1200 vmname = argv[0]; 1201 ctx = do_open(vmname); 1202 1203 max_vcpus = num_vcpus_allowed(ctx); 1204 if (guest_ncpus > max_vcpus) { 1205 fprintf(stderr, "%d vCPUs requested but only %d available\n", 1206 guest_ncpus, max_vcpus); 1207 exit(4); 1208 } 1209 1210 fbsdrun_set_capabilities(ctx, BSP); 1211 1212 vm_set_memflags(ctx, memflags); 1213 #ifdef __FreeBSD__ 1214 err = vm_setup_memory(ctx, memsize, VM_MMAP_ALL); 1215 #else 1216 do { 1217 errno = 0; 1218 err = vm_setup_memory(ctx, memsize, VM_MMAP_ALL); 1219 error = errno; 1220 if (err != 0 && error == ENOMEM) { 1221 (void) fprintf(stderr, "Unable to allocate memory " 1222 "(%llu), retrying in 1 second\n", memsize); 1223 sleep(1); 1224 } 1225 } while (error == ENOMEM); 1226 #endif 1227 if (err) { 1228 fprintf(stderr, "Unable to setup memory (%d)\n", errno); 1229 exit(4); 1230 } 1231 1232 error = init_msr(); 1233 if (error) { 1234 fprintf(stderr, "init_msr error %d", error); 1235 exit(4); 1236 } 1237 1238 init_mem(); 1239 init_inout(); 1240 atkbdc_init(ctx); 1241 pci_irq_init(ctx); 1242 ioapic_init(ctx); 1243 1244 rtc_init(ctx, rtc_localtime); 1245 sci_init(ctx); 1246 1247 /* 1248 * Exit if a device emulation finds an error in its initilization 1249 */ 1250 if (init_pci(ctx) != 0) { 1251 perror("device emulation initialization error"); 1252 exit(4); 1253 } 1254 1255 if (dbg_port != 0) 1256 init_dbgport(dbg_port); 1257 1258 if (gdb_port != 0) 1259 init_gdb(ctx, gdb_port, gdb_stop); 1260 1261 if (bvmcons) 1262 init_bvmcons(); 1263 1264 vga_init(1); 1265 1266 if (lpc_bootrom()) { 1267 if (vm_set_capability(ctx, BSP, VM_CAP_UNRESTRICTED_GUEST, 1)) { 1268 fprintf(stderr, "ROM boot failed: unrestricted guest " 1269 "capability not available\n"); 1270 exit(4); 1271 } 1272 error = vcpu_reset(ctx, BSP); 1273 assert(error == 0); 1274 } 1275 1276 error = vm_get_register(ctx, BSP, VM_REG_GUEST_RIP, &rip); 1277 assert(error == 0); 1278 1279 /* 1280 * build the guest tables, MP etc. 1281 */ 1282 if (mptgen) { 1283 error = mptable_build(ctx, guest_ncpus); 1284 if (error) { 1285 perror("error to build the guest tables"); 1286 exit(4); 1287 } 1288 } 1289 1290 error = smbios_build(ctx); 1291 assert(error == 0); 1292 1293 if (acpi) { 1294 error = acpi_build(ctx, guest_ncpus); 1295 assert(error == 0); 1296 } 1297 1298 if (lpc_bootrom()) 1299 fwctl_init(); 1300 1301 /* 1302 * Change the proc title to include the VM name. 1303 */ 1304 setproctitle("%s", vmname); 1305 1306 #ifndef WITHOUT_CAPSICUM 1307 caph_cache_catpages(); 1308 1309 if (caph_limit_stdout() == -1 || caph_limit_stderr() == -1) 1310 errx(EX_OSERR, "Unable to apply rights for sandbox"); 1311 1312 if (caph_enter() == -1) 1313 errx(EX_OSERR, "cap_enter() failed"); 1314 #endif 1315 1316 #ifndef __FreeBSD__ 1317 /* 1318 * If applicable, wait for bhyveconsole 1319 */ 1320 if (bcons_wait) { 1321 printf("Waiting for bhyveconsole connection...\n"); 1322 (void) pthread_mutex_lock(&bcons_wait_lock); 1323 while (!bcons_connected) { 1324 (void) pthread_cond_wait(&bcons_wait_done, 1325 &bcons_wait_lock); 1326 } 1327 (void) pthread_mutex_unlock(&bcons_wait_lock); 1328 } 1329 #endif 1330 1331 /* 1332 * Add CPU 0 1333 */ 1334 fbsdrun_addcpu(ctx, BSP, BSP, rip); 1335 1336 /* 1337 * Head off to the main event dispatch loop 1338 */ 1339 mevent_dispatch(); 1340 1341 exit(4); 1342 } 1343