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