xref: /illumos-gate/usr/src/cmd/bhyve/bhyverun.c (revision 85f4cb87104c72587029a6e0f1663332c85ba118)
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 #ifdef __FreeBSD__
741 #define	DEBUG_EPT_MISCONFIG
742 #else
743 /* EPT misconfig debugging not possible now that raw VMCS access is gone */
744 #endif
745 
746 #ifdef DEBUG_EPT_MISCONFIG
747 #define	VMCS_GUEST_PHYSICAL_ADDRESS	0x00002400
748 
749 static uint64_t ept_misconfig_gpa, ept_misconfig_pte[4];
750 static int ept_misconfig_ptenum;
751 #endif
752 
753 static const char *
754 vmexit_vmx_desc(uint32_t exit_reason)
755 {
756 
757 	if (exit_reason >= nitems(vmx_exit_reason_desc) ||
758 	    vmx_exit_reason_desc[exit_reason] == NULL)
759 		return ("Unknown");
760 	return (vmx_exit_reason_desc[exit_reason]);
761 }
762 
763 static int
764 vmexit_vmx(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
765 {
766 
767 	fprintf(stderr, "vm exit[%d]\n", *pvcpu);
768 	fprintf(stderr, "\treason\t\tVMX\n");
769 	fprintf(stderr, "\trip\t\t0x%016lx\n", vmexit->rip);
770 	fprintf(stderr, "\tinst_length\t%d\n", vmexit->inst_length);
771 	fprintf(stderr, "\tstatus\t\t%d\n", vmexit->u.vmx.status);
772 	fprintf(stderr, "\texit_reason\t%u (%s)\n", vmexit->u.vmx.exit_reason,
773 	    vmexit_vmx_desc(vmexit->u.vmx.exit_reason));
774 	fprintf(stderr, "\tqualification\t0x%016lx\n",
775 	    vmexit->u.vmx.exit_qualification);
776 	fprintf(stderr, "\tinst_type\t\t%d\n", vmexit->u.vmx.inst_type);
777 	fprintf(stderr, "\tinst_error\t\t%d\n", vmexit->u.vmx.inst_error);
778 #ifdef DEBUG_EPT_MISCONFIG
779 	if (vmexit->u.vmx.exit_reason == EXIT_REASON_EPT_MISCONFIG) {
780 		vm_get_register(ctx, *pvcpu,
781 		    VMCS_IDENT(VMCS_GUEST_PHYSICAL_ADDRESS),
782 		    &ept_misconfig_gpa);
783 		vm_get_gpa_pmap(ctx, ept_misconfig_gpa, ept_misconfig_pte,
784 		    &ept_misconfig_ptenum);
785 		fprintf(stderr, "\tEPT misconfiguration:\n");
786 		fprintf(stderr, "\t\tGPA: %#lx\n", ept_misconfig_gpa);
787 		fprintf(stderr, "\t\tPTE(%d): %#lx %#lx %#lx %#lx\n",
788 		    ept_misconfig_ptenum, ept_misconfig_pte[0],
789 		    ept_misconfig_pte[1], ept_misconfig_pte[2],
790 		    ept_misconfig_pte[3]);
791 	}
792 #endif	/* DEBUG_EPT_MISCONFIG */
793 	return (VMEXIT_ABORT);
794 }
795 
796 static int
797 vmexit_svm(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
798 {
799 
800 	fprintf(stderr, "vm exit[%d]\n", *pvcpu);
801 	fprintf(stderr, "\treason\t\tSVM\n");
802 	fprintf(stderr, "\trip\t\t0x%016lx\n", vmexit->rip);
803 	fprintf(stderr, "\tinst_length\t%d\n", vmexit->inst_length);
804 	fprintf(stderr, "\texitcode\t%#lx\n", vmexit->u.svm.exitcode);
805 	fprintf(stderr, "\texitinfo1\t%#lx\n", vmexit->u.svm.exitinfo1);
806 	fprintf(stderr, "\texitinfo2\t%#lx\n", vmexit->u.svm.exitinfo2);
807 	return (VMEXIT_ABORT);
808 }
809 
810 static int
811 vmexit_bogus(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
812 {
813 
814 	assert(vmexit->inst_length == 0);
815 
816 	stats.vmexit_bogus++;
817 
818 	return (VMEXIT_CONTINUE);
819 }
820 
821 static int
822 vmexit_reqidle(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
823 {
824 
825 	assert(vmexit->inst_length == 0);
826 
827 	stats.vmexit_reqidle++;
828 
829 	return (VMEXIT_CONTINUE);
830 }
831 
832 static int
833 vmexit_hlt(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
834 {
835 
836 	stats.vmexit_hlt++;
837 
838 	/*
839 	 * Just continue execution with the next instruction. We use
840 	 * the HLT VM exit as a way to be friendly with the host
841 	 * scheduler.
842 	 */
843 	return (VMEXIT_CONTINUE);
844 }
845 
846 static int
847 vmexit_pause(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
848 {
849 
850 	stats.vmexit_pause++;
851 
852 	return (VMEXIT_CONTINUE);
853 }
854 
855 static int
856 vmexit_mtrap(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
857 {
858 
859 	assert(vmexit->inst_length == 0);
860 
861 	stats.vmexit_mtrap++;
862 
863 	if (gdb_port == 0) {
864 		fprintf(stderr, "vm_loop: unexpected VMEXIT_MTRAP\n");
865 		exit(4);
866 	}
867 	gdb_cpu_mtrap(*pvcpu);
868 	return (VMEXIT_CONTINUE);
869 }
870 
871 static int
872 vmexit_inst_emul(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
873 {
874 	uint8_t i, valid;
875 
876 	fprintf(stderr, "Failed to emulate instruction sequence ");
877 
878 	valid = vmexit->u.inst_emul.num_valid;
879 	if (valid != 0) {
880 		assert(valid <= sizeof (vmexit->u.inst_emul.inst));
881 		fprintf(stderr, "[");
882 		for (i = 0; i < valid; i++) {
883 			if (i == 0) {
884 				fprintf(stderr, "%02x",
885 				    vmexit->u.inst_emul.inst[i]);
886 			} else {
887 				fprintf(stderr, ", %02x",
888 				    vmexit->u.inst_emul.inst[i]);
889 			}
890 		}
891 		fprintf(stderr, "] ");
892 	}
893 	fprintf(stderr, "@ %rip = %x\n", vmexit->rip);
894 
895 	return (VMEXIT_ABORT);
896 }
897 
898 static int
899 vmexit_mmio(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
900 {
901 	int vcpu, err;
902 	struct vm_mmio mmio;
903 	bool is_read;
904 
905 	stats.vmexit_mmio++;
906 
907 	vcpu = *pvcpu;
908 	mmio = vmexit->u.mmio;
909 	is_read = (mmio.read != 0);
910 
911 	err = emulate_mem(ctx, vcpu, &mmio);
912 
913 	if (err == ESRCH) {
914 		fprintf(stderr, "Unhandled memory access to 0x%lx\n", mmio.gpa);
915 		stats.mmio_unhandled++;
916 
917 		/*
918 		 * Access to non-existent physical addresses is not likely to
919 		 * result in fatal errors on hardware machines, but rather reads
920 		 * of all-ones or discarded-but-acknowledged writes.
921 		 */
922 		mmio.data = ~0UL;
923 		err = 0;
924 	}
925 
926 	if (err == 0) {
927 		if (is_read) {
928 			vmentry_mmio_read(vcpu, mmio.gpa, mmio.bytes,
929 			    mmio.data);
930 		} else {
931 			vmentry_mmio_write(vcpu, mmio.gpa, mmio.bytes);
932 		}
933 		return (VMEXIT_CONTINUE);
934 	}
935 
936 	fprintf(stderr, "Unhandled mmio error to 0x%lx: %d\n", mmio.gpa, err);
937 	return (VMEXIT_ABORT);
938 }
939 
940 static pthread_mutex_t resetcpu_mtx = PTHREAD_MUTEX_INITIALIZER;
941 static pthread_cond_t resetcpu_cond = PTHREAD_COND_INITIALIZER;
942 
943 static int
944 vmexit_suspend(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
945 {
946 	enum vm_suspend_how how;
947 
948 	how = vmexit->u.suspended.how;
949 
950 	fbsdrun_deletecpu(ctx, *pvcpu);
951 
952 	if (*pvcpu != BSP) {
953 		pthread_mutex_lock(&resetcpu_mtx);
954 		pthread_cond_signal(&resetcpu_cond);
955 		pthread_mutex_unlock(&resetcpu_mtx);
956 		pthread_exit(NULL);
957 	}
958 
959 	pthread_mutex_lock(&resetcpu_mtx);
960 	while (!CPU_EMPTY(&cpumask)) {
961 		pthread_cond_wait(&resetcpu_cond, &resetcpu_mtx);
962 	}
963 	pthread_mutex_unlock(&resetcpu_mtx);
964 
965 	switch (how) {
966 	case VM_SUSPEND_RESET:
967 		exit(0);
968 	case VM_SUSPEND_POWEROFF:
969 		exit(1);
970 	case VM_SUSPEND_HALT:
971 		exit(2);
972 	case VM_SUSPEND_TRIPLEFAULT:
973 		exit(3);
974 	default:
975 		fprintf(stderr, "vmexit_suspend: invalid reason %d\n", how);
976 		exit(100);
977 	}
978 	return (0);	/* NOTREACHED */
979 }
980 
981 static int
982 vmexit_debug(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
983 {
984 
985 	if (gdb_port == 0) {
986 		fprintf(stderr, "vm_loop: unexpected VMEXIT_DEBUG\n");
987 		exit(4);
988 	}
989 	gdb_cpu_suspend(*pvcpu);
990 	return (VMEXIT_CONTINUE);
991 }
992 
993 static int
994 vmexit_breakpoint(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
995 {
996 
997 	if (gdb_port == 0) {
998 		fprintf(stderr, "vm_loop: unexpected VMEXIT_DEBUG\n");
999 		exit(4);
1000 	}
1001 	gdb_cpu_breakpoint(*pvcpu, vmexit);
1002 	return (VMEXIT_CONTINUE);
1003 }
1004 
1005 static vmexit_handler_t handler[VM_EXITCODE_MAX] = {
1006 	[VM_EXITCODE_INOUT]  = vmexit_inout,
1007 	[VM_EXITCODE_MMIO]  = vmexit_mmio,
1008 	[VM_EXITCODE_VMX]    = vmexit_vmx,
1009 	[VM_EXITCODE_SVM]    = vmexit_svm,
1010 	[VM_EXITCODE_BOGUS]  = vmexit_bogus,
1011 	[VM_EXITCODE_REQIDLE] = vmexit_reqidle,
1012 	[VM_EXITCODE_RDMSR]  = vmexit_rdmsr,
1013 	[VM_EXITCODE_WRMSR]  = vmexit_wrmsr,
1014 	[VM_EXITCODE_MTRAP]  = vmexit_mtrap,
1015 	[VM_EXITCODE_INST_EMUL] = vmexit_inst_emul,
1016 	[VM_EXITCODE_SPINUP_AP] = vmexit_spinup_ap,
1017 	[VM_EXITCODE_SUSPENDED] = vmexit_suspend,
1018 	[VM_EXITCODE_TASK_SWITCH] = vmexit_task_switch,
1019 	[VM_EXITCODE_DEBUG] = vmexit_debug,
1020 	[VM_EXITCODE_BPT] = vmexit_breakpoint,
1021 };
1022 
1023 static void
1024 vm_loop(struct vmctx *ctx, int vcpu, uint64_t startrip)
1025 {
1026 	int error, rc;
1027 	enum vm_exitcode exitcode;
1028 	cpuset_t active_cpus;
1029 	struct vm_exit *vexit;
1030 	struct vm_entry *ventry;
1031 
1032 #ifdef	__FreeBSD__
1033 	if (vcpumap[vcpu] != NULL) {
1034 		error = pthread_setaffinity_np(pthread_self(),
1035 		    sizeof(cpuset_t), vcpumap[vcpu]);
1036 		assert(error == 0);
1037 	}
1038 #endif
1039 	error = vm_active_cpus(ctx, &active_cpus);
1040 	assert(CPU_ISSET(vcpu, &active_cpus));
1041 
1042 	error = vm_set_register(ctx, vcpu, VM_REG_GUEST_RIP, startrip);
1043 	assert(error == 0);
1044 
1045 	ventry = &vmentry[vcpu];
1046 	vexit = &vmexit[vcpu];
1047 
1048 	while (1) {
1049 		error = vm_run(ctx, vcpu, ventry, vexit);
1050 		if (error != 0)
1051 			break;
1052 
1053 		if (ventry->cmd != VEC_DEFAULT) {
1054 			/*
1055 			 * Discard any lingering entry state after it has been
1056 			 * submitted via vm_run().
1057 			 */
1058 			bzero(ventry, sizeof (*ventry));
1059 		}
1060 
1061 		exitcode = vexit->exitcode;
1062 		if (exitcode >= VM_EXITCODE_MAX || handler[exitcode] == NULL) {
1063 			fprintf(stderr, "vm_loop: unexpected exitcode 0x%x\n",
1064 			    exitcode);
1065 			exit(4);
1066 		}
1067 
1068 		rc = (*handler[exitcode])(ctx, vexit, &vcpu);
1069 
1070 		switch (rc) {
1071 		case VMEXIT_CONTINUE:
1072 			break;
1073 		case VMEXIT_ABORT:
1074 			abort();
1075 		default:
1076 			exit(4);
1077 		}
1078 	}
1079 	fprintf(stderr, "vm_run error %d, errno %d\n", error, errno);
1080 }
1081 
1082 static int
1083 num_vcpus_allowed(struct vmctx *ctx)
1084 {
1085 #ifdef __FreeBSD__
1086 	int tmp, error;
1087 
1088 	error = vm_get_capability(ctx, BSP, VM_CAP_UNRESTRICTED_GUEST, &tmp);
1089 
1090 	/*
1091 	 * The guest is allowed to spinup more than one processor only if the
1092 	 * UNRESTRICTED_GUEST capability is available.
1093 	 */
1094 	if (error == 0)
1095 		return (VM_MAXCPU);
1096 	else
1097 		return (1);
1098 #else
1099 	/* Unrestricted Guest is always enabled on illumos */
1100 	return (VM_MAXCPU);
1101 #endif /* __FreeBSD__ */
1102 }
1103 
1104 void
1105 fbsdrun_set_capabilities(struct vmctx *ctx, int cpu)
1106 {
1107 	int err, tmp;
1108 
1109 	if (fbsdrun_vmexit_on_hlt()) {
1110 		err = vm_get_capability(ctx, cpu, VM_CAP_HALT_EXIT, &tmp);
1111 		if (err < 0) {
1112 			fprintf(stderr, "VM exit on HLT not supported\n");
1113 			exit(4);
1114 		}
1115 		vm_set_capability(ctx, cpu, VM_CAP_HALT_EXIT, 1);
1116 		if (cpu == BSP)
1117 			handler[VM_EXITCODE_HLT] = vmexit_hlt;
1118 	}
1119 
1120         if (fbsdrun_vmexit_on_pause()) {
1121 		/*
1122 		 * pause exit support required for this mode
1123 		 */
1124 		err = vm_get_capability(ctx, cpu, VM_CAP_PAUSE_EXIT, &tmp);
1125 		if (err < 0) {
1126 			fprintf(stderr,
1127 			    "SMP mux requested, no pause support\n");
1128 			exit(4);
1129 		}
1130 		vm_set_capability(ctx, cpu, VM_CAP_PAUSE_EXIT, 1);
1131 		if (cpu == BSP)
1132 			handler[VM_EXITCODE_PAUSE] = vmexit_pause;
1133         }
1134 
1135 	if (x2apic_mode)
1136 		err = vm_set_x2apic_state(ctx, cpu, X2APIC_ENABLED);
1137 	else
1138 		err = vm_set_x2apic_state(ctx, cpu, X2APIC_DISABLED);
1139 
1140 	if (err) {
1141 		fprintf(stderr, "Unable to set x2apic state (%d)\n", err);
1142 		exit(4);
1143 	}
1144 
1145 #ifdef	__FreeBSD__
1146 	vm_set_capability(ctx, cpu, VM_CAP_ENABLE_INVPCID, 1);
1147 #endif
1148 }
1149 
1150 static struct vmctx *
1151 do_open(const char *vmname)
1152 {
1153 	struct vmctx *ctx;
1154 	int error;
1155 	bool reinit, romboot;
1156 #ifndef WITHOUT_CAPSICUM
1157 	cap_rights_t rights;
1158 	const cap_ioctl_t *cmds;
1159 	size_t ncmds;
1160 #endif
1161 
1162 	reinit = romboot = false;
1163 
1164 	if (lpc_bootrom())
1165 		romboot = true;
1166 
1167 	error = vm_create(vmname);
1168 	if (error) {
1169 		if (errno == EEXIST) {
1170 			if (romboot) {
1171 				reinit = true;
1172 			} else {
1173 				/*
1174 				 * The virtual machine has been setup by the
1175 				 * userspace bootloader.
1176 				 */
1177 			}
1178 		} else {
1179 			perror("vm_create");
1180 			exit(4);
1181 		}
1182 	} else {
1183 		if (!romboot) {
1184 			/*
1185 			 * If the virtual machine was just created then a
1186 			 * bootrom must be configured to boot it.
1187 			 */
1188 			fprintf(stderr, "virtual machine cannot be booted\n");
1189 			exit(4);
1190 		}
1191 	}
1192 
1193 	ctx = vm_open(vmname);
1194 	if (ctx == NULL) {
1195 		perror("vm_open");
1196 		exit(4);
1197 	}
1198 
1199 #ifndef WITHOUT_CAPSICUM
1200 	cap_rights_init(&rights, CAP_IOCTL, CAP_MMAP_RW);
1201 	if (caph_rights_limit(vm_get_device_fd(ctx), &rights) == -1)
1202 		errx(EX_OSERR, "Unable to apply rights for sandbox");
1203 	vm_get_ioctls(&ncmds);
1204 	cmds = vm_get_ioctls(NULL);
1205 	if (cmds == NULL)
1206 		errx(EX_OSERR, "out of memory");
1207 	if (caph_ioctls_limit(vm_get_device_fd(ctx), cmds, ncmds) == -1)
1208 		errx(EX_OSERR, "Unable to apply rights for sandbox");
1209 	free((cap_ioctl_t *)cmds);
1210 #endif
1211 
1212 	if (reinit) {
1213 		error = vm_reinit(ctx);
1214 		if (error) {
1215 			perror("vm_reinit");
1216 			exit(4);
1217 		}
1218 	}
1219 	error = vm_set_topology(ctx, sockets, cores, threads, maxcpus);
1220 	if (error)
1221 		errx(EX_OSERR, "vm_set_topology");
1222 	return (ctx);
1223 }
1224 
1225 int
1226 main(int argc, char *argv[])
1227 {
1228 	int c, error, dbg_port, err, bvmcons;
1229 	int max_vcpus, mptgen, memflags;
1230 	int rtc_localtime;
1231 	bool gdb_stop;
1232 #ifndef __FreeBSD__
1233 	bool suspend = false;
1234 #endif
1235 	struct vmctx *ctx;
1236 	uint64_t rip;
1237 	size_t memsize;
1238 	char *optstr;
1239 
1240 	bvmcons = 0;
1241 	progname = basename(argv[0]);
1242 	dbg_port = 0;
1243 	gdb_stop = false;
1244 	guest_ncpus = 1;
1245 	sockets = cores = threads = 1;
1246 	maxcpus = 0;
1247 	memsize = 256 * MB;
1248 	mptgen = 1;
1249 	rtc_localtime = 1;
1250 	memflags = 0;
1251 
1252 #ifdef	__FreeBSD__
1253 	optstr = "abehuwxACHIPSWYp:g:G:c:s:m:l:B:U:";
1254 #else
1255 	optstr = "abdehuwxACHIPSWYg:G:c:s:m:l:B:U:";
1256 #endif
1257 	while ((c = getopt(argc, argv, optstr)) != -1) {
1258 		switch (c) {
1259 		case 'a':
1260 			x2apic_mode = 0;
1261 			break;
1262 		case 'A':
1263 			acpi = 1;
1264 			break;
1265 		case 'b':
1266 			bvmcons = 1;
1267 			break;
1268 		case 'B':
1269 			if (smbios_parse(optarg) != 0) {
1270 				errx(EX_USAGE, "invalid SMBIOS "
1271 				    "configuration '%s'", optarg);
1272 			}
1273 			break;
1274 #ifndef	__FreeBSD__
1275 		case 'd':
1276 			suspend = true;
1277 			break;
1278 #else
1279 		case 'p':
1280 			if (pincpu_parse(optarg) != 0) {
1281 				errx(EX_USAGE, "invalid vcpu pinning "
1282 				    "configuration '%s'", optarg);
1283 			}
1284 			break;
1285 #endif
1286                 case 'c':
1287 			if (topology_parse(optarg) != 0) {
1288 			    errx(EX_USAGE, "invalid cpu topology "
1289 				"'%s'", optarg);
1290 			}
1291 			break;
1292 		case 'C':
1293 			memflags |= VM_MEM_F_INCORE;
1294 			break;
1295 		case 'g':
1296 			dbg_port = atoi(optarg);
1297 			break;
1298 		case 'G':
1299 			if (optarg[0] == 'w') {
1300 				gdb_stop = true;
1301 				optarg++;
1302 			}
1303 			gdb_port = atoi(optarg);
1304 			break;
1305 		case 'l':
1306 			if (strncmp(optarg, "help", strlen(optarg)) == 0) {
1307 				lpc_print_supported_devices();
1308 				exit(0);
1309 			} else if (lpc_device_parse(optarg) != 0) {
1310 				errx(EX_USAGE, "invalid lpc device "
1311 				    "configuration '%s'", optarg);
1312 			}
1313 			break;
1314 		case 's':
1315 			if (strncmp(optarg, "help", strlen(optarg)) == 0) {
1316 				pci_print_supported_devices();
1317 				exit(0);
1318 			} else if (pci_parse_slot(optarg) != 0)
1319 				exit(4);
1320 			else
1321 				break;
1322 		case 'S':
1323 			memflags |= VM_MEM_F_WIRED;
1324 			break;
1325                 case 'm':
1326 			error = vm_parse_memsize(optarg, &memsize);
1327 			if (error)
1328 				errx(EX_USAGE, "invalid memsize '%s'", optarg);
1329 			break;
1330 		case 'H':
1331 			guest_vmexit_on_hlt = 1;
1332 			break;
1333 		case 'I':
1334 			/*
1335 			 * The "-I" option was used to add an ioapic to the
1336 			 * virtual machine.
1337 			 *
1338 			 * An ioapic is now provided unconditionally for each
1339 			 * virtual machine and this option is now deprecated.
1340 			 */
1341 			break;
1342 		case 'P':
1343 			guest_vmexit_on_pause = 1;
1344 			break;
1345 		case 'e':
1346 			strictio = 1;
1347 			break;
1348 		case 'u':
1349 			rtc_localtime = 0;
1350 			break;
1351 		case 'U':
1352 			guest_uuid_str = optarg;
1353 			break;
1354 		case 'w':
1355 			strictmsr = 0;
1356 			break;
1357 		case 'W':
1358 			virtio_msix = 0;
1359 			break;
1360 		case 'x':
1361 			x2apic_mode = 1;
1362 			break;
1363 		case 'Y':
1364 			mptgen = 0;
1365 			break;
1366 		case 'h':
1367 			usage(0);
1368 		default:
1369 			usage(1);
1370 		}
1371 	}
1372 	argc -= optind;
1373 	argv += optind;
1374 
1375 	if (argc != 1)
1376 		usage(1);
1377 
1378 	vmname = argv[0];
1379 	ctx = do_open(vmname);
1380 
1381 	max_vcpus = num_vcpus_allowed(ctx);
1382 	if (guest_ncpus > max_vcpus) {
1383 		fprintf(stderr, "%d vCPUs requested but only %d available\n",
1384 			guest_ncpus, max_vcpus);
1385 		exit(4);
1386 	}
1387 
1388 	fbsdrun_set_capabilities(ctx, BSP);
1389 
1390 	vm_set_memflags(ctx, memflags);
1391 #ifdef	__FreeBSD__
1392 	err = vm_setup_memory(ctx, memsize, VM_MMAP_ALL);
1393 #else
1394 	do {
1395 		errno = 0;
1396 		err = vm_setup_memory(ctx, memsize, VM_MMAP_ALL);
1397 		error = errno;
1398 		if (err != 0 && error == ENOMEM) {
1399 			(void) fprintf(stderr, "Unable to allocate memory "
1400 			    "(%llu), retrying in 1 second\n", memsize);
1401 			sleep(1);
1402 		}
1403 	} while (error == ENOMEM);
1404 #endif
1405 	if (err) {
1406 		fprintf(stderr, "Unable to setup memory (%d)\n", errno);
1407 		exit(4);
1408 	}
1409 
1410 	error = init_msr();
1411 	if (error) {
1412 		fprintf(stderr, "init_msr error %d", error);
1413 		exit(4);
1414 	}
1415 
1416 	init_mem();
1417 	init_inout();
1418 #ifdef	__FreeBSD__
1419 	kernemu_dev_init();
1420 #endif
1421 	init_bootrom(ctx);
1422 	atkbdc_init(ctx);
1423 	pci_irq_init(ctx);
1424 	ioapic_init(ctx);
1425 
1426 	rtc_init(ctx, rtc_localtime);
1427 	sci_init(ctx);
1428 
1429 	/*
1430 	 * Exit if a device emulation finds an error in its initilization
1431 	 */
1432 	if (init_pci(ctx) != 0) {
1433 		perror("device emulation initialization error");
1434 		exit(4);
1435 	}
1436 
1437 	/*
1438 	 * Initialize after PCI, to allow a bootrom file to reserve the high
1439 	 * region.
1440 	 */
1441 	if (acpi)
1442 		vmgenc_init(ctx);
1443 
1444 	if (dbg_port != 0)
1445 		init_dbgport(dbg_port);
1446 
1447 #ifdef __FreeBSD__
1448 	if (gdb_port != 0)
1449 		init_gdb(ctx, gdb_port, gdb_stop);
1450 #else
1451 	if (gdb_port < 0) {
1452 		/*
1453 		 * Set up the internal gdb state needed for basic debugging, but
1454 		 * skip the step of listening on a port for the GDB server.
1455 		 */
1456 		init_mdb(ctx, gdb_stop);
1457 	} else if (gdb_port != 0) {
1458 		init_gdb(ctx, gdb_port, gdb_stop);
1459 	}
1460 #endif
1461 
1462 	if (bvmcons)
1463 		init_bvmcons();
1464 
1465 	vga_init(1);
1466 
1467 	if (lpc_bootrom()) {
1468 #ifdef __FreeBSD__
1469 		if (vm_set_capability(ctx, BSP, VM_CAP_UNRESTRICTED_GUEST, 1)) {
1470 			fprintf(stderr, "ROM boot failed: unrestricted guest "
1471 			    "capability not available\n");
1472 			exit(4);
1473 		}
1474 #else
1475 		/* Unrestricted Guest is always enabled on illumos */
1476 #endif
1477 		error = vcpu_reset(ctx, BSP);
1478 		assert(error == 0);
1479 	}
1480 
1481 	error = vm_get_register(ctx, BSP, VM_REG_GUEST_RIP, &rip);
1482 	assert(error == 0);
1483 
1484 	/*
1485  	 * build the guest tables, MP etc.
1486 	 */
1487 	if (mptgen) {
1488 		error = mptable_build(ctx, guest_ncpus);
1489 		if (error) {
1490 			perror("error to build the guest tables");
1491 			exit(4);
1492 		}
1493 	}
1494 
1495 	error = smbios_build(ctx);
1496 	assert(error == 0);
1497 
1498 	if (acpi) {
1499 		error = acpi_build(ctx, guest_ncpus);
1500 		assert(error == 0);
1501 	}
1502 
1503 	if (lpc_bootrom())
1504 		fwctl_init();
1505 
1506 	/*
1507 	 * Change the proc title to include the VM name.
1508 	 */
1509 	setproctitle("%s", vmname);
1510 
1511 #ifndef WITHOUT_CAPSICUM
1512 	caph_cache_catpages();
1513 
1514 	if (caph_limit_stdout() == -1 || caph_limit_stderr() == -1)
1515 		errx(EX_OSERR, "Unable to apply rights for sandbox");
1516 
1517 	if (caph_enter() == -1)
1518 		errx(EX_OSERR, "cap_enter() failed");
1519 #endif
1520 
1521 	/*
1522 	 * Add CPU 0
1523 	 */
1524 #ifdef __FreeBSD__
1525 	fbsdrun_addcpu(ctx, BSP, BSP, rip);
1526 #else
1527 	fbsdrun_addcpu(ctx, BSP, BSP, rip, suspend);
1528 #endif
1529 	/*
1530 	 * Head off to the main event dispatch loop
1531 	 */
1532 	mevent_dispatch();
1533 
1534 	exit(4);
1535 }
1536