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