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 2020 Oxide Computer Company
  43  */
  44 
  45 #include <sys/cdefs.h>
  46 __FBSDID("$FreeBSD$");
  47 
  48 #include <sys/types.h>
  49 #ifndef WITHOUT_CAPSICUM
  50 #include <sys/capsicum.h>
  51 #endif
  52 #include <sys/mman.h>
  53 #include <sys/time.h>
  54 #include <sys/cpuset.h>
  55 
  56 #ifdef __FreeBSD__
  57 #include <amd64/vmm/intel/vmcs.h>
  58 #else
  59 #include <intel/vmcs.h>
  60 #endif
  61 
  62 #include <machine/atomic.h>
  63 #include <machine/segments.h>
  64 
  65 #ifndef WITHOUT_CAPSICUM
  66 #include <capsicum_helpers.h>
  67 #endif
  68 #include <stdio.h>
  69 #include <stdlib.h>
  70 #include <string.h>
  71 #include <err.h>
  72 #include <errno.h>
  73 #include <libgen.h>
  74 #include <unistd.h>
  75 #include <assert.h>
  76 #include <pthread.h>
  77 #include <pthread_np.h>
  78 #include <sysexits.h>
  79 #include <stdbool.h>
  80 #include <stdint.h>
  81 
  82 #include <machine/vmm.h>
  83 #ifndef WITHOUT_CAPSICUM
  84 #include <machine/vmm_dev.h>
  85 #endif
  86 #include <vmmapi.h>
  87 
  88 #ifndef __FreeBSD__
  89 #include <sys/stat.h>
  90 #endif
  91 
  92 #include "bhyverun.h"
  93 #include "acpi.h"
  94 #include "atkbdc.h"
  95 #include "console.h"
  96 #include "bootrom.h"
  97 #include "inout.h"
  98 #include "dbgport.h"
  99 #include "debug.h"
 100 #include "fwctl.h"
 101 #include "gdb.h"
 102 #include "ioapic.h"
 103 #include "kernemu_dev.h"
 104 #include "mem.h"
 105 #include "mevent.h"
 106 #include "mptbl.h"
 107 #include "pci_emul.h"
 108 #include "pci_irq.h"
 109 #include "pci_lpc.h"
 110 #include "smbiostbl.h"
 111 #include "xmsr.h"
 112 #include "spinup_ap.h"
 113 #include "rfb.h"
 114 #include "rtc.h"
 115 #include "vga.h"
 116 #include "vmgenc.h"
 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 char *vmname;
 194 
 195 int guest_ncpus;
 196 uint16_t cores, maxcpus, sockets, threads;
 197 
 198 char *guest_uuid_str;
 199 
 200 int raw_stdio = 0;
 201 
 202 static int gdb_port = 0;
 203 static int guest_vmexit_on_hlt, guest_vmexit_on_pause;
 204 static int virtio_msix = 1;
 205 static int x2apic_mode = 0;     /* default is xAPIC */
 206 
 207 static int strictio;
 208 static int strictmsr = 1;
 209 
 210 static int acpi;
 211 
 212 static char *progname;
 213 static const int BSP = 0;
 214 
 215 static cpuset_t cpumask;
 216 
 217 static void vm_loop(struct vmctx *ctx, int vcpu, uint64_t rip);
 218 
 219 static struct vm_exit vmexit[VM_MAXCPU];
 220 static struct vm_entry vmentry[VM_MAXCPU];
 221 
 222 struct bhyvestats {
 223         uint64_t        vmexit_bogus;
 224         uint64_t        vmexit_reqidle;
 225         uint64_t        vmexit_hlt;
 226         uint64_t        vmexit_pause;
 227         uint64_t        vmexit_mtrap;
 228         uint64_t        vmexit_mmio;
 229         uint64_t        vmexit_inout;
 230         uint64_t        cpu_switch_rotate;
 231         uint64_t        cpu_switch_direct;
 232         uint64_t        mmio_unhandled;
 233 } stats;
 234 
 235 struct mt_vmm_info {
 236         pthread_t       mt_thr;
 237         struct vmctx    *mt_ctx;
 238         int             mt_vcpu;
 239         uint64_t        mt_startrip;
 240 } mt_vmm_info[VM_MAXCPU];
 241 
 242 #ifdef  __FreeBSD__
 243 static cpuset_t *vcpumap[VM_MAXCPU] = { NULL };
 244 #endif
 245 
 246 static void
 247 usage(int code)
 248 {
 249 
 250         fprintf(stderr,
 251                 "Usage: %s [-abehuwxACHPSWY]\n"
 252                 "       %*s [-c [[cpus=]numcpus][,sockets=n][,cores=n][,threads=n]]\n"
 253                 "       %*s [-g <gdb port>] [-l <lpc>]\n"
 254 #ifdef  __FreeBSD__
 255                 "       %*s [-m mem] [-p vcpu:hostcpu] [-s <pci>] [-U uuid] <vm>\n"
 256 #else
 257                 "       %*s [-m mem] [-s <pci>] [-U uuid] <vm>\n"
 258 #endif
 259                 "       -a: local apic is in xAPIC mode (deprecated)\n"
 260                 "       -A: create ACPI tables\n"
 261                 "       -c: number of cpus and/or topology specification\n"
 262                 "       -C: include guest memory in core file\n"
 263 #ifndef __FreeBSD__
 264                 "       -d: suspend cpu at boot\n"
 265 #endif
 266                 "       -e: exit on unhandled I/O access\n"
 267                 "       -g: gdb port\n"
 268                 "       -h: help\n"
 269                 "       -H: vmexit from the guest on hlt\n"
 270                 "       -l: LPC device configuration\n"
 271                 "       -m: memory size\n"
 272 #ifdef  __FreeBSD__
 273                 "       -p: pin 'vcpu' to 'hostcpu'\n"
 274 #endif
 275                 "       -P: vmexit from the guest on pause\n"
 276                 "       -s: <slot,driver,configinfo> PCI slot config\n"
 277                 "       -S: guest memory cannot be swapped\n"
 278                 "       -u: RTC keeps UTC time\n"
 279                 "       -U: uuid\n"
 280                 "       -w: ignore unimplemented MSRs\n"
 281                 "       -W: force virtio to use single-vector MSI\n"
 282                 "       -x: local apic is in x2APIC mode\n"
 283                 "       -Y: disable MPtable generation\n",
 284                 progname, (int)strlen(progname), "", (int)strlen(progname), "",
 285                 (int)strlen(progname), "");
 286 
 287         exit(code);
 288 }
 289 
 290 /*
 291  * XXX This parser is known to have the following issues:
 292  * 1.  It accepts null key=value tokens ",,".
 293  * 2.  It accepts whitespace after = and before value.
 294  * 3.  Values out of range of INT are silently wrapped.
 295  * 4.  It doesn't check non-final values.
 296  * 5.  The apparently bogus limits of UINT16_MAX are for future expansion.
 297  *
 298  * The acceptance of a null specification ('-c ""') is by design to match the
 299  * manual page syntax specification, this results in a topology of 1 vCPU.
 300  */
 301 static int
 302 topology_parse(const char *opt)
 303 {
 304         uint64_t ncpus;
 305         int c, chk, n, s, t, tmp;
 306         char *cp, *str;
 307         bool ns, scts;
 308 
 309         c = 1, n = 1, s = 1, t = 1;
 310         ns = false, scts = false;
 311         str = strdup(opt);
 312         if (str == NULL)
 313                 goto out;
 314 
 315         while ((cp = strsep(&str, ",")) != NULL) {
 316                 if (sscanf(cp, "%i%n", &tmp, &chk) == 1) {
 317                         n = tmp;
 318                         ns = true;
 319                 } else if (sscanf(cp, "cpus=%i%n", &tmp, &chk) == 1) {
 320                         n = tmp;
 321                         ns = true;
 322                 } else if (sscanf(cp, "sockets=%i%n", &tmp, &chk) == 1) {
 323                         s = tmp;
 324                         scts = true;
 325                 } else if (sscanf(cp, "cores=%i%n", &tmp, &chk) == 1) {
 326                         c = tmp;
 327                         scts = true;
 328                 } else if (sscanf(cp, "threads=%i%n", &tmp, &chk) == 1) {
 329                         t = tmp;
 330                         scts = true;
 331 #ifdef notyet  /* Do not expose this until vmm.ko implements it */
 332                 } else if (sscanf(cp, "maxcpus=%i%n", &tmp, &chk) == 1) {
 333                         m = tmp;
 334 #endif
 335                 /* Skip the empty argument case from -c "" */
 336                 } else if (cp[0] == '\0')
 337                         continue;
 338                 else
 339                         goto out;
 340                 /* Any trailing garbage causes an error */
 341                 if (cp[chk] != '\0')
 342                         goto out;
 343         }
 344         free(str);
 345         str = NULL;
 346 
 347         /*
 348          * Range check 1 <= n <= UINT16_MAX all values
 349          */
 350         if (n < 1 || s < 1 || c < 1 || t < 1 ||
 351             n > UINT16_MAX || s > UINT16_MAX || c > UINT16_MAX  ||
 352             t > UINT16_MAX)
 353                 return (-1);
 354 
 355         /* If only the cpus was specified, use that as sockets */
 356         if (!scts)
 357                 s = n;
 358         /*
 359          * Compute sockets * cores * threads avoiding overflow
 360          * The range check above insures these are 16 bit values
 361          * If n was specified check it against computed ncpus
 362          */
 363         ncpus = (uint64_t)s * c * t;
 364         if (ncpus > UINT16_MAX || (ns && n != ncpus))
 365                 return (-1);
 366 
 367         guest_ncpus = ncpus;
 368         sockets = s;
 369         cores = c;
 370         threads = t;
 371         return(0);
 372 
 373 out:
 374         free(str);
 375         return (-1);
 376 }
 377 
 378 #ifndef WITHOUT_CAPSICUM
 379 /*
 380  * 11-stable capsicum helpers
 381  */
 382 static void
 383 bhyve_caph_cache_catpages(void)
 384 {
 385 
 386         (void)catopen("libc", NL_CAT_LOCALE);
 387 }
 388 
 389 static int
 390 bhyve_caph_limit_stdoe(void)
 391 {
 392         cap_rights_t rights;
 393         unsigned long cmds[] = { TIOCGETA, TIOCGWINSZ };
 394         int i, fds[] = { STDOUT_FILENO, STDERR_FILENO };
 395 
 396         cap_rights_init(&rights, CAP_FCNTL, CAP_FSTAT, CAP_IOCTL);
 397         cap_rights_set(&rights, CAP_WRITE);
 398 
 399         for (i = 0; i < nitems(fds); i++) {
 400                 if (cap_rights_limit(fds[i], &rights) < 0 && errno != ENOSYS)
 401                         return (-1);
 402 
 403                 if (cap_ioctls_limit(fds[i], cmds, nitems(cmds)) < 0 && errno != ENOSYS)
 404                         return (-1);
 405 
 406                 if (cap_fcntls_limit(fds[i], CAP_FCNTL_GETFL) < 0 && errno != ENOSYS)
 407                         return (-1);
 408         }
 409 
 410         return (0);
 411 }
 412 
 413 #endif
 414 
 415 #ifdef  __FreeBSD__
 416 static int
 417 pincpu_parse(const char *opt)
 418 {
 419         int vcpu, pcpu;
 420 
 421         if (sscanf(opt, "%d:%d", &vcpu, &pcpu) != 2) {
 422                 fprintf(stderr, "invalid format: %s\n", opt);
 423                 return (-1);
 424         }
 425 
 426         if (vcpu < 0 || vcpu >= VM_MAXCPU) {
 427                 fprintf(stderr, "vcpu '%d' outside valid range from 0 to %d\n",
 428                     vcpu, VM_MAXCPU - 1);
 429                 return (-1);
 430         }
 431 
 432         if (pcpu < 0 || pcpu >= CPU_SETSIZE) {
 433                 fprintf(stderr, "hostcpu '%d' outside valid range from "
 434                     "0 to %d\n", pcpu, CPU_SETSIZE - 1);
 435                 return (-1);
 436         }
 437 
 438         if (vcpumap[vcpu] == NULL) {
 439                 if ((vcpumap[vcpu] = malloc(sizeof(cpuset_t))) == NULL) {
 440                         perror("malloc");
 441                         return (-1);
 442                 }
 443                 CPU_ZERO(vcpumap[vcpu]);
 444         }
 445         CPU_SET(pcpu, vcpumap[vcpu]);
 446         return (0);
 447 }
 448 
 449 void
 450 vm_inject_fault(void *arg, int vcpu, int vector, int errcode_valid,
 451     int errcode)
 452 {
 453         struct vmctx *ctx;
 454         int error, restart_instruction;
 455 
 456         ctx = arg;
 457         restart_instruction = 1;
 458 
 459         error = vm_inject_exception(ctx, vcpu, vector, errcode_valid, errcode,
 460             restart_instruction);
 461         assert(error == 0);
 462 }
 463 #endif /* __FreeBSD__ */
 464 
 465 void *
 466 paddr_guest2host(struct vmctx *ctx, uintptr_t gaddr, size_t len)
 467 {
 468 
 469         return (vm_map_gpa(ctx, gaddr, len));
 470 }
 471 
 472 int
 473 fbsdrun_vmexit_on_pause(void)
 474 {
 475 
 476         return (guest_vmexit_on_pause);
 477 }
 478 
 479 int
 480 fbsdrun_vmexit_on_hlt(void)
 481 {
 482 
 483         return (guest_vmexit_on_hlt);
 484 }
 485 
 486 int
 487 fbsdrun_virtio_msix(void)
 488 {
 489 
 490         return (virtio_msix);
 491 }
 492 
 493 static void *
 494 fbsdrun_start_thread(void *param)
 495 {
 496         char tname[MAXCOMLEN + 1];
 497         struct mt_vmm_info *mtp;
 498         int vcpu;
 499 
 500         mtp = param;
 501         vcpu = mtp->mt_vcpu;
 502 
 503         snprintf(tname, sizeof(tname), "vcpu %d", vcpu);
 504         pthread_set_name_np(mtp->mt_thr, tname);
 505 
 506         if (gdb_port != 0)
 507                 gdb_cpu_add(vcpu);
 508 
 509         vm_loop(mtp->mt_ctx, vcpu, mtp->mt_startrip);
 510 
 511         /* not reached */
 512         exit(1);
 513         return (NULL);
 514 }
 515 
 516 #ifdef __FreeBSD__
 517 void
 518 fbsdrun_addcpu(struct vmctx *ctx, int fromcpu, int newcpu, uint64_t rip)
 519 #else
 520 void
 521 fbsdrun_addcpu(struct vmctx *ctx, int newcpu, uint64_t rip, bool suspend)
 522 #endif
 523 {
 524         int error;
 525 
 526 #ifdef __FreeBSD__
 527         assert(fromcpu == BSP);
 528 #endif
 529 
 530         /*
 531          * The 'newcpu' must be activated in the context of 'fromcpu'. If
 532          * vm_activate_cpu() is delayed until newcpu's pthread starts running
 533          * then vmm.ko is out-of-sync with bhyve and this can create a race
 534          * with vm_suspend().
 535          */
 536         error = vm_activate_cpu(ctx, newcpu);
 537         if (error != 0)
 538                 err(EX_OSERR, "could not activate CPU %d", newcpu);
 539 
 540         CPU_SET_ATOMIC(newcpu, &cpumask);
 541 
 542 #ifndef __FreeBSD__
 543         if (suspend)
 544                 (void) vm_suspend_cpu(ctx, newcpu);
 545 #endif
 546 
 547         /*
 548          * Set up the vmexit struct to allow execution to start
 549          * at the given RIP
 550          */
 551         mt_vmm_info[newcpu].mt_ctx = ctx;
 552         mt_vmm_info[newcpu].mt_vcpu = newcpu;
 553         mt_vmm_info[newcpu].mt_startrip = rip;
 554 
 555         error = pthread_create(&mt_vmm_info[newcpu].mt_thr, NULL,
 556             fbsdrun_start_thread, &mt_vmm_info[newcpu]);
 557         assert(error == 0);
 558 }
 559 
 560 static int
 561 fbsdrun_deletecpu(struct vmctx *ctx, int vcpu)
 562 {
 563 
 564         if (!CPU_ISSET(vcpu, &cpumask)) {
 565                 fprintf(stderr, "Attempting to delete unknown cpu %d\n", vcpu);
 566                 exit(4);
 567         }
 568 
 569         CPU_CLR_ATOMIC(vcpu, &cpumask);
 570         return (CPU_EMPTY(&cpumask));
 571 }
 572 
 573 static void
 574 vmentry_mmio_read(int vcpu, uint64_t gpa, uint8_t bytes, uint64_t data)
 575 {
 576         struct vm_entry *entry = &vmentry[vcpu];
 577         struct vm_mmio *mmio = &entry->u.mmio;
 578 
 579         assert(entry->cmd == VEC_DEFAULT);
 580 
 581         entry->cmd = VEC_FULFILL_MMIO;
 582         mmio->bytes = bytes;
 583         mmio->read = 1;
 584         mmio->gpa = gpa;
 585         mmio->data = data;
 586 }
 587 
 588 static void
 589 vmentry_mmio_write(int vcpu, uint64_t gpa, uint8_t bytes)
 590 {
 591         struct vm_entry *entry = &vmentry[vcpu];
 592         struct vm_mmio *mmio = &entry->u.mmio;
 593 
 594         assert(entry->cmd == VEC_DEFAULT);
 595 
 596         entry->cmd = VEC_FULFILL_MMIO;
 597         mmio->bytes = bytes;
 598         mmio->read = 0;
 599         mmio->gpa = gpa;
 600         mmio->data = 0;
 601 }
 602 
 603 static void
 604 vmentry_inout_read(int vcpu, uint16_t port, uint8_t bytes, uint32_t data)
 605 {
 606         struct vm_entry *entry = &vmentry[vcpu];
 607         struct vm_inout *inout = &entry->u.inout;
 608 
 609         assert(entry->cmd == VEC_DEFAULT);
 610 
 611         entry->cmd = VEC_FULFILL_INOUT;
 612         inout->bytes = bytes;
 613         inout->flags = INOUT_IN;
 614         inout->port = port;
 615         inout->eax = data;
 616 }
 617 
 618 static void
 619 vmentry_inout_write(int vcpu, uint16_t port, uint8_t bytes)
 620 {
 621         struct vm_entry *entry = &vmentry[vcpu];
 622         struct vm_inout *inout = &entry->u.inout;
 623 
 624         assert(entry->cmd == VEC_DEFAULT);
 625 
 626         entry->cmd = VEC_FULFILL_INOUT;
 627         inout->bytes = bytes;
 628         inout->flags = 0;
 629         inout->port = port;
 630         inout->eax = 0;
 631 }
 632 
 633 static int
 634 vmexit_handle_notify(struct vmctx *ctx, struct vm_exit *vme, int *pvcpu,
 635                      uint32_t eax)
 636 {
 637 #if BHYVE_DEBUG
 638         /*
 639          * put guest-driven debug here
 640          */
 641 #endif
 642         return (VMEXIT_CONTINUE);
 643 }
 644 
 645 static int
 646 vmexit_inout(struct vmctx *ctx, struct vm_exit *vme, int *pvcpu)
 647 {
 648         int error;
 649         int vcpu;
 650         struct vm_inout inout;
 651         bool in;
 652         uint8_t bytes;
 653 
 654         stats.vmexit_inout++;
 655 
 656         vcpu = *pvcpu;
 657         inout = vme->u.inout;
 658         in = (inout.flags & INOUT_IN) != 0;
 659         bytes = inout.bytes;
 660 
 661         /* Extra-special case of host notifications */
 662         if (!in && inout.port == GUEST_NIO_PORT) {
 663                 error = vmexit_handle_notify(ctx, vme, pvcpu, inout.eax);
 664                 vmentry_inout_write(vcpu, inout.port, bytes);
 665                 return (error);
 666         }
 667 
 668         error = emulate_inout(ctx, vcpu, &inout, strictio != 0);
 669         if (error) {
 670                 fprintf(stderr, "Unhandled %s%c 0x%04x at 0x%lx\n",
 671                     in ? "in" : "out",
 672                     bytes == 1 ? 'b' : (bytes == 2 ? 'w' : 'l'),
 673                     inout.port, vmexit->rip);
 674                 return (VMEXIT_ABORT);
 675         } else {
 676                 /*
 677                  * Communicate the status of the inout operation back to the
 678                  * in-kernel instruction emulation.
 679                  */
 680                 if (in) {
 681                         vmentry_inout_read(vcpu, inout.port, bytes, inout.eax);
 682                 } else {
 683                         vmentry_inout_write(vcpu, inout.port, bytes);
 684                 }
 685                 return (VMEXIT_CONTINUE);
 686         }
 687 }
 688 
 689 static int
 690 vmexit_rdmsr(struct vmctx *ctx, struct vm_exit *vme, int *pvcpu)
 691 {
 692         uint64_t val;
 693         uint32_t eax, edx;
 694         int error;
 695 
 696         val = 0;
 697         error = emulate_rdmsr(ctx, *pvcpu, vme->u.msr.code, &val);
 698         if (error != 0) {
 699                 fprintf(stderr, "rdmsr to register %#x on vcpu %d\n",
 700                     vme->u.msr.code, *pvcpu);
 701                 if (strictmsr) {
 702                         vm_inject_gp(ctx, *pvcpu);
 703                         return (VMEXIT_CONTINUE);
 704                 }
 705         }
 706 
 707         eax = val;
 708         error = vm_set_register(ctx, *pvcpu, VM_REG_GUEST_RAX, eax);
 709         assert(error == 0);
 710 
 711         edx = val >> 32;
 712         error = vm_set_register(ctx, *pvcpu, VM_REG_GUEST_RDX, edx);
 713         assert(error == 0);
 714 
 715         return (VMEXIT_CONTINUE);
 716 }
 717 
 718 static int
 719 vmexit_wrmsr(struct vmctx *ctx, struct vm_exit *vme, int *pvcpu)
 720 {
 721         int error;
 722 
 723         error = emulate_wrmsr(ctx, *pvcpu, vme->u.msr.code, vme->u.msr.wval);
 724         if (error != 0) {
 725                 fprintf(stderr, "wrmsr to register %#x(%#lx) on vcpu %d\n",
 726                     vme->u.msr.code, vme->u.msr.wval, *pvcpu);
 727                 if (strictmsr) {
 728                         vm_inject_gp(ctx, *pvcpu);
 729                         return (VMEXIT_CONTINUE);
 730                 }
 731         }
 732         return (VMEXIT_CONTINUE);
 733 }
 734 
 735 #ifdef __FreeBSD__
 736 static int
 737 vmexit_spinup_ap(struct vmctx *ctx, struct vm_exit *vme, int *pvcpu)
 738 {
 739 
 740         (void)spinup_ap(ctx, *pvcpu,
 741                     vme->u.spinup_ap.vcpu, vme->u.spinup_ap.rip);
 742 
 743         return (VMEXIT_CONTINUE);
 744 }
 745 #else
 746 static int
 747 vmexit_run_state(struct vmctx *ctx, struct vm_exit *vme, int *pvcpu)
 748 {
 749         /*
 750          * Run-state transitions (INIT, SIPI, etc) are handled in-kernel, so an
 751          * exit to userspace with that code is not expected.
 752          */
 753         fprintf(stderr, "unexpected run-state VM exit");
 754         return (VMEXIT_ABORT);
 755 }
 756 #endif /* __FreeBSD__ */
 757 
 758 #ifdef __FreeBSD__
 759 #define DEBUG_EPT_MISCONFIG
 760 #else
 761 /* EPT misconfig debugging not possible now that raw VMCS access is gone */
 762 #endif
 763 
 764 #ifdef DEBUG_EPT_MISCONFIG
 765 #define VMCS_GUEST_PHYSICAL_ADDRESS     0x00002400
 766 
 767 static uint64_t ept_misconfig_gpa, ept_misconfig_pte[4];
 768 static int ept_misconfig_ptenum;
 769 #endif
 770 
 771 static const char *
 772 vmexit_vmx_desc(uint32_t exit_reason)
 773 {
 774 
 775         if (exit_reason >= nitems(vmx_exit_reason_desc) ||
 776             vmx_exit_reason_desc[exit_reason] == NULL)
 777                 return ("Unknown");
 778         return (vmx_exit_reason_desc[exit_reason]);
 779 }
 780 
 781 static int
 782 vmexit_vmx(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
 783 {
 784 
 785         fprintf(stderr, "vm exit[%d]\n", *pvcpu);
 786         fprintf(stderr, "\treason\t\tVMX\n");
 787         fprintf(stderr, "\trip\t\t0x%016lx\n", vmexit->rip);
 788         fprintf(stderr, "\tinst_length\t%d\n", vmexit->inst_length);
 789         fprintf(stderr, "\tstatus\t\t%d\n", vmexit->u.vmx.status);
 790         fprintf(stderr, "\texit_reason\t%u (%s)\n", vmexit->u.vmx.exit_reason,
 791             vmexit_vmx_desc(vmexit->u.vmx.exit_reason));
 792         fprintf(stderr, "\tqualification\t0x%016lx\n",
 793             vmexit->u.vmx.exit_qualification);
 794         fprintf(stderr, "\tinst_type\t\t%d\n", vmexit->u.vmx.inst_type);
 795         fprintf(stderr, "\tinst_error\t\t%d\n", vmexit->u.vmx.inst_error);
 796 #ifdef DEBUG_EPT_MISCONFIG
 797         if (vmexit->u.vmx.exit_reason == EXIT_REASON_EPT_MISCONFIG) {
 798                 vm_get_register(ctx, *pvcpu,
 799                     VMCS_IDENT(VMCS_GUEST_PHYSICAL_ADDRESS),
 800                     &ept_misconfig_gpa);
 801                 vm_get_gpa_pmap(ctx, ept_misconfig_gpa, ept_misconfig_pte,
 802                     &ept_misconfig_ptenum);
 803                 fprintf(stderr, "\tEPT misconfiguration:\n");
 804                 fprintf(stderr, "\t\tGPA: %#lx\n", ept_misconfig_gpa);
 805                 fprintf(stderr, "\t\tPTE(%d): %#lx %#lx %#lx %#lx\n",
 806                     ept_misconfig_ptenum, ept_misconfig_pte[0],
 807                     ept_misconfig_pte[1], ept_misconfig_pte[2],
 808                     ept_misconfig_pte[3]);
 809         }
 810 #endif  /* DEBUG_EPT_MISCONFIG */
 811         return (VMEXIT_ABORT);
 812 }
 813 
 814 static int
 815 vmexit_svm(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
 816 {
 817 
 818         fprintf(stderr, "vm exit[%d]\n", *pvcpu);
 819         fprintf(stderr, "\treason\t\tSVM\n");
 820         fprintf(stderr, "\trip\t\t0x%016lx\n", vmexit->rip);
 821         fprintf(stderr, "\tinst_length\t%d\n", vmexit->inst_length);
 822         fprintf(stderr, "\texitcode\t%#lx\n", vmexit->u.svm.exitcode);
 823         fprintf(stderr, "\texitinfo1\t%#lx\n", vmexit->u.svm.exitinfo1);
 824         fprintf(stderr, "\texitinfo2\t%#lx\n", vmexit->u.svm.exitinfo2);
 825         return (VMEXIT_ABORT);
 826 }
 827 
 828 static int
 829 vmexit_bogus(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
 830 {
 831 
 832         assert(vmexit->inst_length == 0);
 833 
 834         stats.vmexit_bogus++;
 835 
 836         return (VMEXIT_CONTINUE);
 837 }
 838 
 839 static int
 840 vmexit_reqidle(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
 841 {
 842 
 843         assert(vmexit->inst_length == 0);
 844 
 845         stats.vmexit_reqidle++;
 846 
 847         return (VMEXIT_CONTINUE);
 848 }
 849 
 850 static int
 851 vmexit_hlt(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
 852 {
 853 
 854         stats.vmexit_hlt++;
 855 
 856         /*
 857          * Just continue execution with the next instruction. We use
 858          * the HLT VM exit as a way to be friendly with the host
 859          * scheduler.
 860          */
 861         return (VMEXIT_CONTINUE);
 862 }
 863 
 864 static int
 865 vmexit_pause(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
 866 {
 867 
 868         stats.vmexit_pause++;
 869 
 870         return (VMEXIT_CONTINUE);
 871 }
 872 
 873 static int
 874 vmexit_mtrap(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
 875 {
 876 
 877         assert(vmexit->inst_length == 0);
 878 
 879         stats.vmexit_mtrap++;
 880 
 881         if (gdb_port == 0) {
 882                 fprintf(stderr, "vm_loop: unexpected VMEXIT_MTRAP\n");
 883                 exit(4);
 884         }
 885         gdb_cpu_mtrap(*pvcpu);
 886         return (VMEXIT_CONTINUE);
 887 }
 888 
 889 static int
 890 vmexit_inst_emul(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
 891 {
 892         uint8_t i, valid;
 893 
 894         fprintf(stderr, "Failed to emulate instruction sequence ");
 895 
 896         valid = vmexit->u.inst_emul.num_valid;
 897         if (valid != 0) {
 898                 assert(valid <= sizeof (vmexit->u.inst_emul.inst));
 899                 fprintf(stderr, "[");
 900                 for (i = 0; i < valid; i++) {
 901                         if (i == 0) {
 902                                 fprintf(stderr, "%02x",
 903                                     vmexit->u.inst_emul.inst[i]);
 904                         } else {
 905                                 fprintf(stderr, ", %02x",
 906                                     vmexit->u.inst_emul.inst[i]);
 907                         }
 908                 }
 909                 fprintf(stderr, "] ");
 910         }
 911         fprintf(stderr, "@ %rip = %x\n", vmexit->rip);
 912 
 913         return (VMEXIT_ABORT);
 914 }
 915 
 916 static int
 917 vmexit_mmio(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
 918 {
 919         int vcpu, err;
 920         struct vm_mmio mmio;
 921         bool is_read;
 922 
 923         stats.vmexit_mmio++;
 924 
 925         vcpu = *pvcpu;
 926         mmio = vmexit->u.mmio;
 927         is_read = (mmio.read != 0);
 928 
 929         err = emulate_mem(ctx, vcpu, &mmio);
 930 
 931         if (err == ESRCH) {
 932                 fprintf(stderr, "Unhandled memory access to 0x%lx\n", mmio.gpa);
 933                 stats.mmio_unhandled++;
 934 
 935                 /*
 936                  * Access to non-existent physical addresses is not likely to
 937                  * result in fatal errors on hardware machines, but rather reads
 938                  * of all-ones or discarded-but-acknowledged writes.
 939                  */
 940                 mmio.data = ~0UL;
 941                 err = 0;
 942         }
 943 
 944         if (err == 0) {
 945                 if (is_read) {
 946                         vmentry_mmio_read(vcpu, mmio.gpa, mmio.bytes,
 947                             mmio.data);
 948                 } else {
 949                         vmentry_mmio_write(vcpu, mmio.gpa, mmio.bytes);
 950                 }
 951                 return (VMEXIT_CONTINUE);
 952         }
 953 
 954         fprintf(stderr, "Unhandled mmio error to 0x%lx: %d\n", mmio.gpa, err);
 955         return (VMEXIT_ABORT);
 956 }
 957 
 958 static pthread_mutex_t resetcpu_mtx = PTHREAD_MUTEX_INITIALIZER;
 959 static pthread_cond_t resetcpu_cond = PTHREAD_COND_INITIALIZER;
 960 
 961 static int
 962 vmexit_suspend(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
 963 {
 964         enum vm_suspend_how how;
 965 
 966         how = vmexit->u.suspended.how;
 967 
 968         fbsdrun_deletecpu(ctx, *pvcpu);
 969 
 970         if (*pvcpu != BSP) {
 971                 pthread_mutex_lock(&resetcpu_mtx);
 972                 pthread_cond_signal(&resetcpu_cond);
 973                 pthread_mutex_unlock(&resetcpu_mtx);
 974                 pthread_exit(NULL);
 975         }
 976 
 977         pthread_mutex_lock(&resetcpu_mtx);
 978         while (!CPU_EMPTY(&cpumask)) {
 979                 pthread_cond_wait(&resetcpu_cond, &resetcpu_mtx);
 980         }
 981         pthread_mutex_unlock(&resetcpu_mtx);
 982 
 983         switch (how) {
 984         case VM_SUSPEND_RESET:
 985                 exit(0);
 986         case VM_SUSPEND_POWEROFF:
 987                 exit(1);
 988         case VM_SUSPEND_HALT:
 989                 exit(2);
 990         case VM_SUSPEND_TRIPLEFAULT:
 991                 exit(3);
 992         default:
 993                 fprintf(stderr, "vmexit_suspend: invalid reason %d\n", how);
 994                 exit(100);
 995         }
 996         return (0);     /* NOTREACHED */
 997 }
 998 
 999 static int
1000 vmexit_debug(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
1001 {
1002 
1003         if (gdb_port == 0) {
1004                 fprintf(stderr, "vm_loop: unexpected VMEXIT_DEBUG\n");
1005                 exit(4);
1006         }
1007         gdb_cpu_suspend(*pvcpu);
1008         return (VMEXIT_CONTINUE);
1009 }
1010 
1011 static int
1012 vmexit_breakpoint(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
1013 {
1014 
1015         if (gdb_port == 0) {
1016                 fprintf(stderr, "vm_loop: unexpected VMEXIT_DEBUG\n");
1017                 exit(4);
1018         }
1019         gdb_cpu_breakpoint(*pvcpu, vmexit);
1020         return (VMEXIT_CONTINUE);
1021 }
1022 
1023 static vmexit_handler_t handler[VM_EXITCODE_MAX] = {
1024         [VM_EXITCODE_INOUT]  = vmexit_inout,
1025         [VM_EXITCODE_MMIO]  = vmexit_mmio,
1026         [VM_EXITCODE_VMX]    = vmexit_vmx,
1027         [VM_EXITCODE_SVM]    = vmexit_svm,
1028         [VM_EXITCODE_BOGUS]  = vmexit_bogus,
1029         [VM_EXITCODE_REQIDLE] = vmexit_reqidle,
1030         [VM_EXITCODE_RDMSR]  = vmexit_rdmsr,
1031         [VM_EXITCODE_WRMSR]  = vmexit_wrmsr,
1032         [VM_EXITCODE_MTRAP]  = vmexit_mtrap,
1033         [VM_EXITCODE_INST_EMUL] = vmexit_inst_emul,
1034 #ifdef __FreeBSD__
1035         [VM_EXITCODE_SPINUP_AP] = vmexit_spinup_ap,
1036 #else
1037         [VM_EXITCODE_RUN_STATE] = vmexit_run_state,
1038 #endif
1039         [VM_EXITCODE_SUSPENDED] = vmexit_suspend,
1040         [VM_EXITCODE_TASK_SWITCH] = vmexit_task_switch,
1041         [VM_EXITCODE_DEBUG] = vmexit_debug,
1042         [VM_EXITCODE_BPT] = vmexit_breakpoint,
1043 };
1044 
1045 static void
1046 vm_loop(struct vmctx *ctx, int vcpu, uint64_t startrip)
1047 {
1048         int error, rc;
1049         enum vm_exitcode exitcode;
1050         cpuset_t active_cpus;
1051         struct vm_exit *vexit;
1052         struct vm_entry *ventry;
1053 
1054 #ifdef  __FreeBSD__
1055         if (vcpumap[vcpu] != NULL) {
1056                 error = pthread_setaffinity_np(pthread_self(),
1057                     sizeof(cpuset_t), vcpumap[vcpu]);
1058                 assert(error == 0);
1059         }
1060 #endif
1061         error = vm_active_cpus(ctx, &active_cpus);
1062         assert(CPU_ISSET(vcpu, &active_cpus));
1063 
1064         error = vm_set_register(ctx, vcpu, VM_REG_GUEST_RIP, startrip);
1065         assert(error == 0);
1066 
1067         ventry = &vmentry[vcpu];
1068         vexit = &vmexit[vcpu];
1069 
1070         while (1) {
1071                 error = vm_run(ctx, vcpu, ventry, vexit);
1072                 if (error != 0)
1073                         break;
1074 
1075                 if (ventry->cmd != VEC_DEFAULT) {
1076                         /*
1077                          * Discard any lingering entry state after it has been
1078                          * submitted via vm_run().
1079                          */
1080                         bzero(ventry, sizeof (*ventry));
1081                 }
1082 
1083                 exitcode = vexit->exitcode;
1084                 if (exitcode >= VM_EXITCODE_MAX || handler[exitcode] == NULL) {
1085                         fprintf(stderr, "vm_loop: unexpected exitcode 0x%x\n",
1086                             exitcode);
1087                         exit(4);
1088                 }
1089 
1090                 rc = (*handler[exitcode])(ctx, vexit, &vcpu);
1091 
1092                 switch (rc) {
1093                 case VMEXIT_CONTINUE:
1094                         break;
1095                 case VMEXIT_ABORT:
1096                         abort();
1097                 default:
1098                         exit(4);
1099                 }
1100         }
1101         fprintf(stderr, "vm_run error %d, errno %d\n", error, errno);
1102 }
1103 
1104 static int
1105 num_vcpus_allowed(struct vmctx *ctx)
1106 {
1107 #ifdef __FreeBSD__
1108         int tmp, error;
1109 
1110         error = vm_get_capability(ctx, BSP, VM_CAP_UNRESTRICTED_GUEST, &tmp);
1111 
1112         /*
1113          * The guest is allowed to spinup more than one processor only if the
1114          * UNRESTRICTED_GUEST capability is available.
1115          */
1116         if (error == 0)
1117                 return (VM_MAXCPU);
1118         else
1119                 return (1);
1120 #else
1121         /* Unrestricted Guest is always enabled on illumos */
1122         return (VM_MAXCPU);
1123 #endif /* __FreeBSD__ */
1124 }
1125 
1126 void
1127 fbsdrun_set_capabilities(struct vmctx *ctx, int cpu)
1128 {
1129         int err, tmp;
1130 
1131         if (fbsdrun_vmexit_on_hlt()) {
1132                 err = vm_get_capability(ctx, cpu, VM_CAP_HALT_EXIT, &tmp);
1133                 if (err < 0) {
1134                         fprintf(stderr, "VM exit on HLT not supported\n");
1135                         exit(4);
1136                 }
1137                 vm_set_capability(ctx, cpu, VM_CAP_HALT_EXIT, 1);
1138                 if (cpu == BSP)
1139                         handler[VM_EXITCODE_HLT] = vmexit_hlt;
1140         }
1141 
1142         if (fbsdrun_vmexit_on_pause()) {
1143                 /*
1144                  * pause exit support required for this mode
1145                  */
1146                 err = vm_get_capability(ctx, cpu, VM_CAP_PAUSE_EXIT, &tmp);
1147                 if (err < 0) {
1148                         fprintf(stderr,
1149                             "SMP mux requested, no pause support\n");
1150                         exit(4);
1151                 }
1152                 vm_set_capability(ctx, cpu, VM_CAP_PAUSE_EXIT, 1);
1153                 if (cpu == BSP)
1154                         handler[VM_EXITCODE_PAUSE] = vmexit_pause;
1155         }
1156 
1157         if (x2apic_mode)
1158                 err = vm_set_x2apic_state(ctx, cpu, X2APIC_ENABLED);
1159         else
1160                 err = vm_set_x2apic_state(ctx, cpu, X2APIC_DISABLED);
1161 
1162         if (err) {
1163                 fprintf(stderr, "Unable to set x2apic state (%d)\n", err);
1164                 exit(4);
1165         }
1166 
1167 #ifdef  __FreeBSD__
1168         vm_set_capability(ctx, cpu, VM_CAP_ENABLE_INVPCID, 1);
1169 #endif
1170 }
1171 
1172 static struct vmctx *
1173 do_open(const char *vmname)
1174 {
1175         struct vmctx *ctx;
1176         int error;
1177         bool reinit, romboot;
1178 #ifndef WITHOUT_CAPSICUM
1179         cap_rights_t rights;
1180         const cap_ioctl_t *cmds;        
1181         size_t ncmds;
1182 #endif
1183 
1184         reinit = romboot = false;
1185 
1186         if (lpc_bootrom())
1187                 romboot = true;
1188 
1189         error = vm_create(vmname);
1190         if (error) {
1191                 if (errno == EEXIST) {
1192                         if (romboot) {
1193                                 reinit = true;
1194                         } else {
1195                                 /*
1196                                  * The virtual machine has been setup by the
1197                                  * userspace bootloader.
1198                                  */
1199                         }
1200                 } else {
1201                         perror("vm_create");
1202                         exit(4);
1203                 }
1204         } else {
1205                 if (!romboot) {
1206                         /*
1207                          * If the virtual machine was just created then a
1208                          * bootrom must be configured to boot it.
1209                          */
1210                         fprintf(stderr, "virtual machine cannot be booted\n");
1211                         exit(4);
1212                 }
1213         }
1214 
1215         ctx = vm_open(vmname);
1216         if (ctx == NULL) {
1217                 perror("vm_open");
1218                 exit(4);
1219         }
1220 
1221 #ifndef WITHOUT_CAPSICUM
1222         cap_rights_init(&rights, CAP_IOCTL, CAP_MMAP_RW);
1223         if (caph_rights_limit(vm_get_device_fd(ctx), &rights) == -1) 
1224                 errx(EX_OSERR, "Unable to apply rights for sandbox");
1225         vm_get_ioctls(&ncmds);
1226         cmds = vm_get_ioctls(NULL);
1227         if (cmds == NULL)
1228                 errx(EX_OSERR, "out of memory");
1229         if (caph_ioctls_limit(vm_get_device_fd(ctx), cmds, ncmds) == -1)
1230                 errx(EX_OSERR, "Unable to apply rights for sandbox");
1231         free((cap_ioctl_t *)cmds);
1232 #endif
1233  
1234         if (reinit) {
1235                 error = vm_reinit(ctx);
1236                 if (error) {
1237                         perror("vm_reinit");
1238                         exit(4);
1239                 }
1240         }
1241         error = vm_set_topology(ctx, sockets, cores, threads, maxcpus);
1242         if (error)
1243                 errx(EX_OSERR, "vm_set_topology");
1244         return (ctx);
1245 }
1246 
1247 #ifndef __FreeBSD__
1248 
1249 #define FILE_PROVISIONING       "/var/svc/provisioning"
1250 #define FILE_PROVISION_SUCCESS  "/var/svc/provision_success"
1251 
1252 static void
1253 mark_provisioned(void)
1254 {
1255         struct stat stbuf;
1256 
1257         if (lstat(FILE_PROVISIONING, &stbuf) != 0)
1258                 return;
1259 
1260         if (rename(FILE_PROVISIONING, FILE_PROVISION_SUCCESS) != 0) {
1261                 (void) fprintf(stderr, "Cannot rename %s to %s: %s\n",
1262                     FILE_PROVISIONING, FILE_PROVISION_SUCCESS,
1263                     strerror(errno));
1264         }
1265 }
1266 
1267 #endif
1268 
1269 int
1270 main(int argc, char *argv[])
1271 {
1272         int c, error, dbg_port, err, bvmcons;
1273         int max_vcpus, mptgen, memflags;
1274         int rtc_localtime;
1275         bool gdb_stop;
1276 #ifndef __FreeBSD__
1277         bool suspend = false;
1278 #endif
1279         struct vmctx *ctx;
1280         uint64_t rip;
1281         size_t memsize;
1282         char *optstr;
1283 
1284         bvmcons = 0;
1285         progname = basename(argv[0]);
1286         dbg_port = 0;
1287         gdb_stop = false;
1288         guest_ncpus = 1;
1289         sockets = cores = threads = 1;
1290         maxcpus = 0;
1291         memsize = 256 * MB;
1292         mptgen = 1;
1293         rtc_localtime = 1;
1294         memflags = 0;
1295 
1296 #ifdef  __FreeBSD__
1297         optstr = "abehuwxACHIPSWYp:g:G:c:s:m:l:B:U:";
1298 #else
1299         optstr = "abdehuwxACHIPSWYg:G:c:s:m:l:B:U:";
1300 #endif
1301         while ((c = getopt(argc, argv, optstr)) != -1) {
1302                 switch (c) {
1303                 case 'a':
1304                         x2apic_mode = 0;
1305                         break;
1306                 case 'A':
1307                         acpi = 1;
1308                         break;
1309                 case 'b':
1310                         bvmcons = 1;
1311                         break;
1312                 case 'B':
1313                         if (smbios_parse(optarg) != 0) {
1314                                 errx(EX_USAGE, "invalid SMBIOS "
1315                                     "configuration '%s'", optarg);
1316                         }
1317                         break;
1318 #ifndef __FreeBSD__
1319                 case 'd':
1320                         suspend = true;
1321                         break;
1322 #else
1323                 case 'p':
1324                         if (pincpu_parse(optarg) != 0) {
1325                                 errx(EX_USAGE, "invalid vcpu pinning "
1326                                     "configuration '%s'", optarg);
1327                         }
1328                         break;
1329 #endif
1330                 case 'c':
1331                         if (topology_parse(optarg) != 0) {
1332                             errx(EX_USAGE, "invalid cpu topology "
1333                                 "'%s'", optarg);
1334                         }
1335                         break;
1336                 case 'C':
1337                         memflags |= VM_MEM_F_INCORE;
1338                         break;
1339                 case 'g':
1340                         dbg_port = atoi(optarg);
1341                         break;
1342                 case 'G':
1343                         if (optarg[0] == 'w') {
1344                                 gdb_stop = true;
1345                                 optarg++;
1346                         }
1347                         gdb_port = atoi(optarg);
1348                         break;
1349                 case 'l':
1350                         if (strncmp(optarg, "help", strlen(optarg)) == 0) {
1351                                 lpc_print_supported_devices();
1352                                 exit(0);
1353                         } else if (lpc_device_parse(optarg) != 0) {
1354                                 errx(EX_USAGE, "invalid lpc device "
1355                                     "configuration '%s'", optarg);
1356                         }
1357                         break;
1358                 case 's':
1359                         if (strncmp(optarg, "help", strlen(optarg)) == 0) {
1360                                 pci_print_supported_devices();
1361                                 exit(0);
1362                         } else if (pci_parse_slot(optarg) != 0)
1363                                 exit(4);
1364                         else
1365                                 break;
1366                 case 'S':
1367                         memflags |= VM_MEM_F_WIRED;
1368                         break;
1369                 case 'm':
1370                         error = vm_parse_memsize(optarg, &memsize);
1371                         if (error)
1372                                 errx(EX_USAGE, "invalid memsize '%s'", optarg);
1373                         break;
1374                 case 'H':
1375                         guest_vmexit_on_hlt = 1;
1376                         break;
1377                 case 'I':
1378                         /*
1379                          * The "-I" option was used to add an ioapic to the
1380                          * virtual machine.
1381                          *
1382                          * An ioapic is now provided unconditionally for each
1383                          * virtual machine and this option is now deprecated.
1384                          */
1385                         break;
1386                 case 'P':
1387                         guest_vmexit_on_pause = 1;
1388                         break;
1389                 case 'e':
1390                         strictio = 1;
1391                         break;
1392                 case 'u':
1393                         rtc_localtime = 0;
1394                         break;
1395                 case 'U':
1396                         guest_uuid_str = optarg;
1397                         break;
1398                 case 'w':
1399                         strictmsr = 0;
1400                         break;
1401                 case 'W':
1402                         virtio_msix = 0;
1403                         break;
1404                 case 'x':
1405                         x2apic_mode = 1;
1406                         break;
1407                 case 'Y':
1408                         mptgen = 0;
1409                         break;
1410                 case 'h':
1411                         usage(0);                       
1412                 default:
1413                         usage(1);
1414                 }
1415         }
1416         argc -= optind;
1417         argv += optind;
1418 
1419         if (argc != 1)
1420                 usage(1);
1421 
1422         vmname = argv[0];
1423         ctx = do_open(vmname);
1424 
1425         max_vcpus = num_vcpus_allowed(ctx);
1426         if (guest_ncpus > max_vcpus) {
1427                 fprintf(stderr, "%d vCPUs requested but only %d available\n",
1428                         guest_ncpus, max_vcpus);
1429                 exit(4);
1430         }
1431 
1432         fbsdrun_set_capabilities(ctx, BSP);
1433 
1434         vm_set_memflags(ctx, memflags);
1435 #ifdef  __FreeBSD__
1436         err = vm_setup_memory(ctx, memsize, VM_MMAP_ALL);
1437 #else
1438         do {
1439                 errno = 0;
1440                 err = vm_setup_memory(ctx, memsize, VM_MMAP_ALL);
1441                 error = errno;
1442                 if (err != 0 && error == ENOMEM) {
1443                         (void) fprintf(stderr, "Unable to allocate memory "
1444                             "(%llu), retrying in 1 second\n", memsize);
1445                         sleep(1);
1446                 }
1447         } while (error == ENOMEM);
1448 #endif
1449         if (err) {
1450                 fprintf(stderr, "Unable to setup memory (%d)\n", errno);
1451                 exit(4);
1452         }
1453 
1454         error = init_msr();
1455         if (error) {
1456                 fprintf(stderr, "init_msr error %d", error);
1457                 exit(4);
1458         }
1459 
1460         init_mem();
1461         init_inout();
1462 #ifdef  __FreeBSD__
1463         kernemu_dev_init();
1464 #endif
1465         init_bootrom(ctx);
1466         atkbdc_init(ctx);
1467         pci_irq_init(ctx);
1468         ioapic_init(ctx);
1469 
1470         rtc_init(ctx, rtc_localtime);
1471         sci_init(ctx);
1472 #ifndef __FreeBSD__
1473         pmtmr_init(ctx);
1474 #endif
1475 
1476         /*
1477          * Exit if a device emulation finds an error in its initilization
1478          */
1479         if (init_pci(ctx) != 0) {
1480                 perror("device emulation initialization error");
1481                 exit(4);
1482         }
1483 
1484         /*
1485          * Initialize after PCI, to allow a bootrom file to reserve the high
1486          * region.
1487          */
1488         if (acpi)
1489                 vmgenc_init(ctx);
1490 
1491         if (dbg_port != 0)
1492                 init_dbgport(dbg_port);
1493 
1494 #ifdef __FreeBSD__
1495         if (gdb_port != 0)
1496                 init_gdb(ctx, gdb_port, gdb_stop);
1497 #else
1498         if (gdb_port < 0) {
1499                 /*
1500                  * Set up the internal gdb state needed for basic debugging, but
1501                  * skip the step of listening on a port for the GDB server.
1502                  */
1503                 init_mdb(ctx, gdb_stop);
1504         } else if (gdb_port != 0) {
1505                 init_gdb(ctx, gdb_port, gdb_stop);
1506         }
1507 #endif
1508 
1509         if (bvmcons)
1510                 init_bvmcons();
1511 
1512         vga_init(1);
1513 
1514         if (lpc_bootrom()) {
1515 #ifdef __FreeBSD__
1516                 if (vm_set_capability(ctx, BSP, VM_CAP_UNRESTRICTED_GUEST, 1)) {
1517                         fprintf(stderr, "ROM boot failed: unrestricted guest "
1518                             "capability not available\n");
1519                         exit(4);
1520                 }
1521 #else
1522                 /* Unrestricted Guest is always enabled on illumos */
1523 #endif
1524                 error = vcpu_reset(ctx, BSP);
1525                 assert(error == 0);
1526         }
1527 
1528         error = vm_get_register(ctx, BSP, VM_REG_GUEST_RIP, &rip);
1529         assert(error == 0);
1530 
1531         /*
1532          * build the guest tables, MP etc.
1533          */
1534         if (mptgen) {
1535                 error = mptable_build(ctx, guest_ncpus);
1536                 if (error) {
1537                         perror("error to build the guest tables");
1538                         exit(4);
1539                 }
1540         }
1541 
1542         error = smbios_build(ctx);
1543         assert(error == 0);
1544 
1545         if (acpi) {
1546                 error = acpi_build(ctx, guest_ncpus);
1547                 assert(error == 0);
1548         }
1549 
1550         if (lpc_bootrom())
1551                 fwctl_init();
1552 
1553         /*
1554          * Change the proc title to include the VM name.
1555          */
1556         setproctitle("%s", vmname);
1557 
1558 #ifndef WITHOUT_CAPSICUM
1559         caph_cache_catpages();
1560 
1561         if (caph_limit_stdout() == -1 || caph_limit_stderr() == -1)
1562                 errx(EX_OSERR, "Unable to apply rights for sandbox");
1563 
1564         if (caph_enter() == -1)
1565                 errx(EX_OSERR, "cap_enter() failed");
1566 #endif
1567 
1568 #ifdef __FreeBSD__
1569         /*
1570          * Add CPU 0
1571          */
1572         fbsdrun_addcpu(ctx, BSP, BSP, rip);
1573 #else
1574         /* Set BSP to run (unlike the APs which wait for INIT) */
1575         error = vm_set_run_state(ctx, BSP, VRS_RUN, 0);
1576         assert(error == 0);
1577         fbsdrun_addcpu(ctx, BSP, rip, suspend);
1578 
1579         /* Add subsequent CPUs, which will wait until INIT/SIPI-ed */
1580         for (uint_t i = 1; i < guest_ncpus; i++) {
1581                 spinup_halted_ap(ctx, i);
1582         }
1583         mark_provisioned();
1584 #endif
1585 
1586         /*
1587          * Head off to the main event dispatch loop
1588          */
1589         mevent_dispatch();
1590 
1591         exit(4);
1592 }