xref: /illumos-gate/usr/src/cmd/bhyve/bhyverun.c (revision 2606939d)
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 newcpu, uint64_t rip, bool suspend)
518 #endif
519 {
520 	int error;
521 
522 #ifdef __FreeBSD__
523 	assert(fromcpu == BSP);
524 #endif
525 
526 	/*
527 	 * The 'newcpu' must be activated in the context of 'fromcpu'. If
528 	 * vm_activate_cpu() is delayed until newcpu's pthread starts running
529 	 * then vmm.ko is out-of-sync with bhyve and this can create a race
530 	 * with vm_suspend().
531 	 */
532 	error = vm_activate_cpu(ctx, newcpu);
533 	if (error != 0)
534 		err(EX_OSERR, "could not activate CPU %d", newcpu);
535 
536 	CPU_SET_ATOMIC(newcpu, &cpumask);
537 
538 #ifndef __FreeBSD__
539 	if (suspend)
540 		(void) vm_suspend_cpu(ctx, newcpu);
541 #endif
542 
543 	/*
544 	 * Set up the vmexit struct to allow execution to start
545 	 * at the given RIP
546 	 */
547 	mt_vmm_info[newcpu].mt_ctx = ctx;
548 	mt_vmm_info[newcpu].mt_vcpu = newcpu;
549 	mt_vmm_info[newcpu].mt_startrip = rip;
550 
551 	error = pthread_create(&mt_vmm_info[newcpu].mt_thr, NULL,
552 	    fbsdrun_start_thread, &mt_vmm_info[newcpu]);
553 	assert(error == 0);
554 }
555 
556 static int
557 fbsdrun_deletecpu(struct vmctx *ctx, int vcpu)
558 {
559 
560 	if (!CPU_ISSET(vcpu, &cpumask)) {
561 		fprintf(stderr, "Attempting to delete unknown cpu %d\n", vcpu);
562 		exit(4);
563 	}
564 
565 	CPU_CLR_ATOMIC(vcpu, &cpumask);
566 	return (CPU_EMPTY(&cpumask));
567 }
568 
569 static void
570 vmentry_mmio_read(int vcpu, uint64_t gpa, uint8_t bytes, uint64_t data)
571 {
572 	struct vm_entry *entry = &vmentry[vcpu];
573 	struct vm_mmio *mmio = &entry->u.mmio;
574 
575 	assert(entry->cmd == VEC_DEFAULT);
576 
577 	entry->cmd = VEC_FULFILL_MMIO;
578 	mmio->bytes = bytes;
579 	mmio->read = 1;
580 	mmio->gpa = gpa;
581 	mmio->data = data;
582 }
583 
584 static void
585 vmentry_mmio_write(int vcpu, uint64_t gpa, uint8_t bytes)
586 {
587 	struct vm_entry *entry = &vmentry[vcpu];
588 	struct vm_mmio *mmio = &entry->u.mmio;
589 
590 	assert(entry->cmd == VEC_DEFAULT);
591 
592 	entry->cmd = VEC_FULFILL_MMIO;
593 	mmio->bytes = bytes;
594 	mmio->read = 0;
595 	mmio->gpa = gpa;
596 	mmio->data = 0;
597 }
598 
599 static void
600 vmentry_inout_read(int vcpu, uint16_t port, uint8_t bytes, uint32_t data)
601 {
602 	struct vm_entry *entry = &vmentry[vcpu];
603 	struct vm_inout *inout = &entry->u.inout;
604 
605 	assert(entry->cmd == VEC_DEFAULT);
606 
607 	entry->cmd = VEC_FULFILL_INOUT;
608 	inout->bytes = bytes;
609 	inout->flags = INOUT_IN;
610 	inout->port = port;
611 	inout->eax = data;
612 }
613 
614 static void
615 vmentry_inout_write(int vcpu, uint16_t port, uint8_t bytes)
616 {
617 	struct vm_entry *entry = &vmentry[vcpu];
618 	struct vm_inout *inout = &entry->u.inout;
619 
620 	assert(entry->cmd == VEC_DEFAULT);
621 
622 	entry->cmd = VEC_FULFILL_INOUT;
623 	inout->bytes = bytes;
624 	inout->flags = 0;
625 	inout->port = port;
626 	inout->eax = 0;
627 }
628 
629 static int
630 vmexit_handle_notify(struct vmctx *ctx, struct vm_exit *vme, int *pvcpu,
631 		     uint32_t eax)
632 {
633 #if BHYVE_DEBUG
634 	/*
635 	 * put guest-driven debug here
636 	 */
637 #endif
638 	return (VMEXIT_CONTINUE);
639 }
640 
641 static int
642 vmexit_inout(struct vmctx *ctx, struct vm_exit *vme, int *pvcpu)
643 {
644 	int error;
645 	int vcpu;
646 	struct vm_inout inout;
647 	bool in;
648 	uint8_t bytes;
649 
650 	stats.vmexit_inout++;
651 
652 	vcpu = *pvcpu;
653 	inout = vme->u.inout;
654 	in = (inout.flags & INOUT_IN) != 0;
655 	bytes = inout.bytes;
656 
657         /* Extra-special case of host notifications */
658         if (!in && inout.port == GUEST_NIO_PORT) {
659                 error = vmexit_handle_notify(ctx, vme, pvcpu, inout.eax);
660 		vmentry_inout_write(vcpu, inout.port, bytes);
661 		return (error);
662 	}
663 
664 	error = emulate_inout(ctx, vcpu, &inout, strictio != 0);
665 	if (error) {
666 		fprintf(stderr, "Unhandled %s%c 0x%04x at 0x%lx\n",
667 		    in ? "in" : "out",
668 		    bytes == 1 ? 'b' : (bytes == 2 ? 'w' : 'l'),
669 		    inout.port, vmexit->rip);
670 		return (VMEXIT_ABORT);
671 	} else {
672 		/*
673 		 * Communicate the status of the inout operation back to the
674 		 * in-kernel instruction emulation.
675 		 */
676 		if (in) {
677 			vmentry_inout_read(vcpu, inout.port, bytes, inout.eax);
678 		} else {
679 			vmentry_inout_write(vcpu, inout.port, bytes);
680 		}
681 		return (VMEXIT_CONTINUE);
682 	}
683 }
684 
685 static int
686 vmexit_rdmsr(struct vmctx *ctx, struct vm_exit *vme, int *pvcpu)
687 {
688 	uint64_t val;
689 	uint32_t eax, edx;
690 	int error;
691 
692 	val = 0;
693 	error = emulate_rdmsr(ctx, *pvcpu, vme->u.msr.code, &val);
694 	if (error != 0) {
695 		fprintf(stderr, "rdmsr to register %#x on vcpu %d\n",
696 		    vme->u.msr.code, *pvcpu);
697 		if (strictmsr) {
698 			vm_inject_gp(ctx, *pvcpu);
699 			return (VMEXIT_CONTINUE);
700 		}
701 	}
702 
703 	eax = val;
704 	error = vm_set_register(ctx, *pvcpu, VM_REG_GUEST_RAX, eax);
705 	assert(error == 0);
706 
707 	edx = val >> 32;
708 	error = vm_set_register(ctx, *pvcpu, VM_REG_GUEST_RDX, edx);
709 	assert(error == 0);
710 
711 	return (VMEXIT_CONTINUE);
712 }
713 
714 static int
715 vmexit_wrmsr(struct vmctx *ctx, struct vm_exit *vme, int *pvcpu)
716 {
717 	int error;
718 
719 	error = emulate_wrmsr(ctx, *pvcpu, vme->u.msr.code, vme->u.msr.wval);
720 	if (error != 0) {
721 		fprintf(stderr, "wrmsr to register %#x(%#lx) on vcpu %d\n",
722 		    vme->u.msr.code, vme->u.msr.wval, *pvcpu);
723 		if (strictmsr) {
724 			vm_inject_gp(ctx, *pvcpu);
725 			return (VMEXIT_CONTINUE);
726 		}
727 	}
728 	return (VMEXIT_CONTINUE);
729 }
730 
731 #ifdef __FreeBSD__
732 static int
733 vmexit_spinup_ap(struct vmctx *ctx, struct vm_exit *vme, int *pvcpu)
734 {
735 
736 	(void)spinup_ap(ctx, *pvcpu,
737 		    vme->u.spinup_ap.vcpu, vme->u.spinup_ap.rip);
738 
739 	return (VMEXIT_CONTINUE);
740 }
741 #else
742 static int
743 vmexit_run_state(struct vmctx *ctx, struct vm_exit *vme, int *pvcpu)
744 {
745 	/*
746 	 * Run-state transitions (INIT, SIPI, etc) are handled in-kernel, so an
747 	 * exit to userspace with that code is not expected.
748 	 */
749 	fprintf(stderr, "unexpected run-state VM exit");
750 	return (VMEXIT_ABORT);
751 }
752 #endif /* __FreeBSD__ */
753 
754 #ifdef __FreeBSD__
755 #define	DEBUG_EPT_MISCONFIG
756 #else
757 /* EPT misconfig debugging not possible now that raw VMCS access is gone */
758 #endif
759 
760 #ifdef DEBUG_EPT_MISCONFIG
761 #define	VMCS_GUEST_PHYSICAL_ADDRESS	0x00002400
762 
763 static uint64_t ept_misconfig_gpa, ept_misconfig_pte[4];
764 static int ept_misconfig_ptenum;
765 #endif
766 
767 static const char *
768 vmexit_vmx_desc(uint32_t exit_reason)
769 {
770 
771 	if (exit_reason >= nitems(vmx_exit_reason_desc) ||
772 	    vmx_exit_reason_desc[exit_reason] == NULL)
773 		return ("Unknown");
774 	return (vmx_exit_reason_desc[exit_reason]);
775 }
776 
777 static int
778 vmexit_vmx(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
779 {
780 
781 	fprintf(stderr, "vm exit[%d]\n", *pvcpu);
782 	fprintf(stderr, "\treason\t\tVMX\n");
783 	fprintf(stderr, "\trip\t\t0x%016lx\n", vmexit->rip);
784 	fprintf(stderr, "\tinst_length\t%d\n", vmexit->inst_length);
785 	fprintf(stderr, "\tstatus\t\t%d\n", vmexit->u.vmx.status);
786 	fprintf(stderr, "\texit_reason\t%u (%s)\n", vmexit->u.vmx.exit_reason,
787 	    vmexit_vmx_desc(vmexit->u.vmx.exit_reason));
788 	fprintf(stderr, "\tqualification\t0x%016lx\n",
789 	    vmexit->u.vmx.exit_qualification);
790 	fprintf(stderr, "\tinst_type\t\t%d\n", vmexit->u.vmx.inst_type);
791 	fprintf(stderr, "\tinst_error\t\t%d\n", vmexit->u.vmx.inst_error);
792 #ifdef DEBUG_EPT_MISCONFIG
793 	if (vmexit->u.vmx.exit_reason == EXIT_REASON_EPT_MISCONFIG) {
794 		vm_get_register(ctx, *pvcpu,
795 		    VMCS_IDENT(VMCS_GUEST_PHYSICAL_ADDRESS),
796 		    &ept_misconfig_gpa);
797 		vm_get_gpa_pmap(ctx, ept_misconfig_gpa, ept_misconfig_pte,
798 		    &ept_misconfig_ptenum);
799 		fprintf(stderr, "\tEPT misconfiguration:\n");
800 		fprintf(stderr, "\t\tGPA: %#lx\n", ept_misconfig_gpa);
801 		fprintf(stderr, "\t\tPTE(%d): %#lx %#lx %#lx %#lx\n",
802 		    ept_misconfig_ptenum, ept_misconfig_pte[0],
803 		    ept_misconfig_pte[1], ept_misconfig_pte[2],
804 		    ept_misconfig_pte[3]);
805 	}
806 #endif	/* DEBUG_EPT_MISCONFIG */
807 	return (VMEXIT_ABORT);
808 }
809 
810 static int
811 vmexit_svm(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
812 {
813 
814 	fprintf(stderr, "vm exit[%d]\n", *pvcpu);
815 	fprintf(stderr, "\treason\t\tSVM\n");
816 	fprintf(stderr, "\trip\t\t0x%016lx\n", vmexit->rip);
817 	fprintf(stderr, "\tinst_length\t%d\n", vmexit->inst_length);
818 	fprintf(stderr, "\texitcode\t%#lx\n", vmexit->u.svm.exitcode);
819 	fprintf(stderr, "\texitinfo1\t%#lx\n", vmexit->u.svm.exitinfo1);
820 	fprintf(stderr, "\texitinfo2\t%#lx\n", vmexit->u.svm.exitinfo2);
821 	return (VMEXIT_ABORT);
822 }
823 
824 static int
825 vmexit_bogus(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
826 {
827 
828 	assert(vmexit->inst_length == 0);
829 
830 	stats.vmexit_bogus++;
831 
832 	return (VMEXIT_CONTINUE);
833 }
834 
835 static int
836 vmexit_reqidle(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
837 {
838 
839 	assert(vmexit->inst_length == 0);
840 
841 	stats.vmexit_reqidle++;
842 
843 	return (VMEXIT_CONTINUE);
844 }
845 
846 static int
847 vmexit_hlt(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
848 {
849 
850 	stats.vmexit_hlt++;
851 
852 	/*
853 	 * Just continue execution with the next instruction. We use
854 	 * the HLT VM exit as a way to be friendly with the host
855 	 * scheduler.
856 	 */
857 	return (VMEXIT_CONTINUE);
858 }
859 
860 static int
861 vmexit_pause(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
862 {
863 
864 	stats.vmexit_pause++;
865 
866 	return (VMEXIT_CONTINUE);
867 }
868 
869 static int
870 vmexit_mtrap(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
871 {
872 
873 	assert(vmexit->inst_length == 0);
874 
875 	stats.vmexit_mtrap++;
876 
877 	if (gdb_port == 0) {
878 		fprintf(stderr, "vm_loop: unexpected VMEXIT_MTRAP\n");
879 		exit(4);
880 	}
881 	gdb_cpu_mtrap(*pvcpu);
882 	return (VMEXIT_CONTINUE);
883 }
884 
885 static int
886 vmexit_inst_emul(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
887 {
888 	uint8_t i, valid;
889 
890 	fprintf(stderr, "Failed to emulate instruction sequence ");
891 
892 	valid = vmexit->u.inst_emul.num_valid;
893 	if (valid != 0) {
894 		assert(valid <= sizeof (vmexit->u.inst_emul.inst));
895 		fprintf(stderr, "[");
896 		for (i = 0; i < valid; i++) {
897 			if (i == 0) {
898 				fprintf(stderr, "%02x",
899 				    vmexit->u.inst_emul.inst[i]);
900 			} else {
901 				fprintf(stderr, ", %02x",
902 				    vmexit->u.inst_emul.inst[i]);
903 			}
904 		}
905 		fprintf(stderr, "] ");
906 	}
907 	fprintf(stderr, "@ %rip = %x\n", vmexit->rip);
908 
909 	return (VMEXIT_ABORT);
910 }
911 
912 static int
913 vmexit_mmio(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
914 {
915 	int vcpu, err;
916 	struct vm_mmio mmio;
917 	bool is_read;
918 
919 	stats.vmexit_mmio++;
920 
921 	vcpu = *pvcpu;
922 	mmio = vmexit->u.mmio;
923 	is_read = (mmio.read != 0);
924 
925 	err = emulate_mem(ctx, vcpu, &mmio);
926 
927 	if (err == ESRCH) {
928 		fprintf(stderr, "Unhandled memory access to 0x%lx\n", mmio.gpa);
929 		stats.mmio_unhandled++;
930 
931 		/*
932 		 * Access to non-existent physical addresses is not likely to
933 		 * result in fatal errors on hardware machines, but rather reads
934 		 * of all-ones or discarded-but-acknowledged writes.
935 		 */
936 		mmio.data = ~0UL;
937 		err = 0;
938 	}
939 
940 	if (err == 0) {
941 		if (is_read) {
942 			vmentry_mmio_read(vcpu, mmio.gpa, mmio.bytes,
943 			    mmio.data);
944 		} else {
945 			vmentry_mmio_write(vcpu, mmio.gpa, mmio.bytes);
946 		}
947 		return (VMEXIT_CONTINUE);
948 	}
949 
950 	fprintf(stderr, "Unhandled mmio error to 0x%lx: %d\n", mmio.gpa, err);
951 	return (VMEXIT_ABORT);
952 }
953 
954 static pthread_mutex_t resetcpu_mtx = PTHREAD_MUTEX_INITIALIZER;
955 static pthread_cond_t resetcpu_cond = PTHREAD_COND_INITIALIZER;
956 
957 static int
958 vmexit_suspend(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
959 {
960 	enum vm_suspend_how how;
961 
962 	how = vmexit->u.suspended.how;
963 
964 	fbsdrun_deletecpu(ctx, *pvcpu);
965 
966 	if (*pvcpu != BSP) {
967 		pthread_mutex_lock(&resetcpu_mtx);
968 		pthread_cond_signal(&resetcpu_cond);
969 		pthread_mutex_unlock(&resetcpu_mtx);
970 		pthread_exit(NULL);
971 	}
972 
973 	pthread_mutex_lock(&resetcpu_mtx);
974 	while (!CPU_EMPTY(&cpumask)) {
975 		pthread_cond_wait(&resetcpu_cond, &resetcpu_mtx);
976 	}
977 	pthread_mutex_unlock(&resetcpu_mtx);
978 
979 	switch (how) {
980 	case VM_SUSPEND_RESET:
981 		exit(0);
982 	case VM_SUSPEND_POWEROFF:
983 		exit(1);
984 	case VM_SUSPEND_HALT:
985 		exit(2);
986 	case VM_SUSPEND_TRIPLEFAULT:
987 		exit(3);
988 	default:
989 		fprintf(stderr, "vmexit_suspend: invalid reason %d\n", how);
990 		exit(100);
991 	}
992 	return (0);	/* NOTREACHED */
993 }
994 
995 static int
996 vmexit_debug(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
997 {
998 
999 	if (gdb_port == 0) {
1000 		fprintf(stderr, "vm_loop: unexpected VMEXIT_DEBUG\n");
1001 		exit(4);
1002 	}
1003 	gdb_cpu_suspend(*pvcpu);
1004 	return (VMEXIT_CONTINUE);
1005 }
1006 
1007 static int
1008 vmexit_breakpoint(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
1009 {
1010 
1011 	if (gdb_port == 0) {
1012 		fprintf(stderr, "vm_loop: unexpected VMEXIT_DEBUG\n");
1013 		exit(4);
1014 	}
1015 	gdb_cpu_breakpoint(*pvcpu, vmexit);
1016 	return (VMEXIT_CONTINUE);
1017 }
1018 
1019 static vmexit_handler_t handler[VM_EXITCODE_MAX] = {
1020 	[VM_EXITCODE_INOUT]  = vmexit_inout,
1021 	[VM_EXITCODE_MMIO]  = vmexit_mmio,
1022 	[VM_EXITCODE_VMX]    = vmexit_vmx,
1023 	[VM_EXITCODE_SVM]    = vmexit_svm,
1024 	[VM_EXITCODE_BOGUS]  = vmexit_bogus,
1025 	[VM_EXITCODE_REQIDLE] = vmexit_reqidle,
1026 	[VM_EXITCODE_RDMSR]  = vmexit_rdmsr,
1027 	[VM_EXITCODE_WRMSR]  = vmexit_wrmsr,
1028 	[VM_EXITCODE_MTRAP]  = vmexit_mtrap,
1029 	[VM_EXITCODE_INST_EMUL] = vmexit_inst_emul,
1030 #ifdef __FreeBSD__
1031 	[VM_EXITCODE_SPINUP_AP] = vmexit_spinup_ap,
1032 #else
1033 	[VM_EXITCODE_RUN_STATE] = vmexit_run_state,
1034 #endif
1035 	[VM_EXITCODE_SUSPENDED] = vmexit_suspend,
1036 	[VM_EXITCODE_TASK_SWITCH] = vmexit_task_switch,
1037 	[VM_EXITCODE_DEBUG] = vmexit_debug,
1038 	[VM_EXITCODE_BPT] = vmexit_breakpoint,
1039 };
1040 
1041 static void
1042 vm_loop(struct vmctx *ctx, int vcpu, uint64_t startrip)
1043 {
1044 	int error, rc;
1045 	enum vm_exitcode exitcode;
1046 	cpuset_t active_cpus;
1047 	struct vm_exit *vexit;
1048 	struct vm_entry *ventry;
1049 
1050 #ifdef	__FreeBSD__
1051 	if (vcpumap[vcpu] != NULL) {
1052 		error = pthread_setaffinity_np(pthread_self(),
1053 		    sizeof(cpuset_t), vcpumap[vcpu]);
1054 		assert(error == 0);
1055 	}
1056 #endif
1057 	error = vm_active_cpus(ctx, &active_cpus);
1058 	assert(CPU_ISSET(vcpu, &active_cpus));
1059 
1060 	error = vm_set_register(ctx, vcpu, VM_REG_GUEST_RIP, startrip);
1061 	assert(error == 0);
1062 
1063 	ventry = &vmentry[vcpu];
1064 	vexit = &vmexit[vcpu];
1065 
1066 	while (1) {
1067 		error = vm_run(ctx, vcpu, ventry, vexit);
1068 		if (error != 0)
1069 			break;
1070 
1071 		if (ventry->cmd != VEC_DEFAULT) {
1072 			/*
1073 			 * Discard any lingering entry state after it has been
1074 			 * submitted via vm_run().
1075 			 */
1076 			bzero(ventry, sizeof (*ventry));
1077 		}
1078 
1079 		exitcode = vexit->exitcode;
1080 		if (exitcode >= VM_EXITCODE_MAX || handler[exitcode] == NULL) {
1081 			fprintf(stderr, "vm_loop: unexpected exitcode 0x%x\n",
1082 			    exitcode);
1083 			exit(4);
1084 		}
1085 
1086 		rc = (*handler[exitcode])(ctx, vexit, &vcpu);
1087 
1088 		switch (rc) {
1089 		case VMEXIT_CONTINUE:
1090 			break;
1091 		case VMEXIT_ABORT:
1092 			abort();
1093 		default:
1094 			exit(4);
1095 		}
1096 	}
1097 	fprintf(stderr, "vm_run error %d, errno %d\n", error, errno);
1098 }
1099 
1100 static int
1101 num_vcpus_allowed(struct vmctx *ctx)
1102 {
1103 #ifdef __FreeBSD__
1104 	int tmp, error;
1105 
1106 	error = vm_get_capability(ctx, BSP, VM_CAP_UNRESTRICTED_GUEST, &tmp);
1107 
1108 	/*
1109 	 * The guest is allowed to spinup more than one processor only if the
1110 	 * UNRESTRICTED_GUEST capability is available.
1111 	 */
1112 	if (error == 0)
1113 		return (VM_MAXCPU);
1114 	else
1115 		return (1);
1116 #else
1117 	/* Unrestricted Guest is always enabled on illumos */
1118 	return (VM_MAXCPU);
1119 #endif /* __FreeBSD__ */
1120 }
1121 
1122 void
1123 fbsdrun_set_capabilities(struct vmctx *ctx, int cpu)
1124 {
1125 	int err, tmp;
1126 
1127 	if (fbsdrun_vmexit_on_hlt()) {
1128 		err = vm_get_capability(ctx, cpu, VM_CAP_HALT_EXIT, &tmp);
1129 		if (err < 0) {
1130 			fprintf(stderr, "VM exit on HLT not supported\n");
1131 			exit(4);
1132 		}
1133 		vm_set_capability(ctx, cpu, VM_CAP_HALT_EXIT, 1);
1134 		if (cpu == BSP)
1135 			handler[VM_EXITCODE_HLT] = vmexit_hlt;
1136 	}
1137 
1138         if (fbsdrun_vmexit_on_pause()) {
1139 		/*
1140 		 * pause exit support required for this mode
1141 		 */
1142 		err = vm_get_capability(ctx, cpu, VM_CAP_PAUSE_EXIT, &tmp);
1143 		if (err < 0) {
1144 			fprintf(stderr,
1145 			    "SMP mux requested, no pause support\n");
1146 			exit(4);
1147 		}
1148 		vm_set_capability(ctx, cpu, VM_CAP_PAUSE_EXIT, 1);
1149 		if (cpu == BSP)
1150 			handler[VM_EXITCODE_PAUSE] = vmexit_pause;
1151         }
1152 
1153 	if (x2apic_mode)
1154 		err = vm_set_x2apic_state(ctx, cpu, X2APIC_ENABLED);
1155 	else
1156 		err = vm_set_x2apic_state(ctx, cpu, X2APIC_DISABLED);
1157 
1158 	if (err) {
1159 		fprintf(stderr, "Unable to set x2apic state (%d)\n", err);
1160 		exit(4);
1161 	}
1162 
1163 #ifdef	__FreeBSD__
1164 	vm_set_capability(ctx, cpu, VM_CAP_ENABLE_INVPCID, 1);
1165 #endif
1166 }
1167 
1168 static struct vmctx *
1169 do_open(const char *vmname)
1170 {
1171 	struct vmctx *ctx;
1172 	int error;
1173 	bool reinit, romboot;
1174 #ifndef WITHOUT_CAPSICUM
1175 	cap_rights_t rights;
1176 	const cap_ioctl_t *cmds;
1177 	size_t ncmds;
1178 #endif
1179 
1180 	reinit = romboot = false;
1181 
1182 	if (lpc_bootrom())
1183 		romboot = true;
1184 
1185 	error = vm_create(vmname);
1186 	if (error) {
1187 		if (errno == EEXIST) {
1188 			if (romboot) {
1189 				reinit = true;
1190 			} else {
1191 				/*
1192 				 * The virtual machine has been setup by the
1193 				 * userspace bootloader.
1194 				 */
1195 			}
1196 		} else {
1197 			perror("vm_create");
1198 			exit(4);
1199 		}
1200 	} else {
1201 		if (!romboot) {
1202 			/*
1203 			 * If the virtual machine was just created then a
1204 			 * bootrom must be configured to boot it.
1205 			 */
1206 			fprintf(stderr, "virtual machine cannot be booted\n");
1207 			exit(4);
1208 		}
1209 	}
1210 
1211 	ctx = vm_open(vmname);
1212 	if (ctx == NULL) {
1213 		perror("vm_open");
1214 		exit(4);
1215 	}
1216 
1217 #ifndef WITHOUT_CAPSICUM
1218 	cap_rights_init(&rights, CAP_IOCTL, CAP_MMAP_RW);
1219 	if (caph_rights_limit(vm_get_device_fd(ctx), &rights) == -1)
1220 		errx(EX_OSERR, "Unable to apply rights for sandbox");
1221 	vm_get_ioctls(&ncmds);
1222 	cmds = vm_get_ioctls(NULL);
1223 	if (cmds == NULL)
1224 		errx(EX_OSERR, "out of memory");
1225 	if (caph_ioctls_limit(vm_get_device_fd(ctx), cmds, ncmds) == -1)
1226 		errx(EX_OSERR, "Unable to apply rights for sandbox");
1227 	free((cap_ioctl_t *)cmds);
1228 #endif
1229 
1230 	if (reinit) {
1231 		error = vm_reinit(ctx);
1232 		if (error) {
1233 			perror("vm_reinit");
1234 			exit(4);
1235 		}
1236 	}
1237 	error = vm_set_topology(ctx, sockets, cores, threads, maxcpus);
1238 	if (error)
1239 		errx(EX_OSERR, "vm_set_topology");
1240 	return (ctx);
1241 }
1242 
1243 int
1244 main(int argc, char *argv[])
1245 {
1246 	int c, error, dbg_port, err, bvmcons;
1247 	int max_vcpus, mptgen, memflags;
1248 	int rtc_localtime;
1249 	bool gdb_stop;
1250 #ifndef __FreeBSD__
1251 	bool suspend = false;
1252 #endif
1253 	struct vmctx *ctx;
1254 	uint64_t rip;
1255 	size_t memsize;
1256 	char *optstr;
1257 
1258 	bvmcons = 0;
1259 	progname = basename(argv[0]);
1260 	dbg_port = 0;
1261 	gdb_stop = false;
1262 	guest_ncpus = 1;
1263 	sockets = cores = threads = 1;
1264 	maxcpus = 0;
1265 	memsize = 256 * MB;
1266 	mptgen = 1;
1267 	rtc_localtime = 1;
1268 	memflags = 0;
1269 
1270 #ifdef	__FreeBSD__
1271 	optstr = "abehuwxACHIPSWYp:g:G:c:s:m:l:B:U:";
1272 #else
1273 	optstr = "abdehuwxACHIPSWYg:G:c:s:m:l:B:U:";
1274 #endif
1275 	while ((c = getopt(argc, argv, optstr)) != -1) {
1276 		switch (c) {
1277 		case 'a':
1278 			x2apic_mode = 0;
1279 			break;
1280 		case 'A':
1281 			acpi = 1;
1282 			break;
1283 		case 'b':
1284 			bvmcons = 1;
1285 			break;
1286 		case 'B':
1287 			if (smbios_parse(optarg) != 0) {
1288 				errx(EX_USAGE, "invalid SMBIOS "
1289 				    "configuration '%s'", optarg);
1290 			}
1291 			break;
1292 #ifndef	__FreeBSD__
1293 		case 'd':
1294 			suspend = true;
1295 			break;
1296 #else
1297 		case 'p':
1298 			if (pincpu_parse(optarg) != 0) {
1299 				errx(EX_USAGE, "invalid vcpu pinning "
1300 				    "configuration '%s'", optarg);
1301 			}
1302 			break;
1303 #endif
1304                 case 'c':
1305 			if (topology_parse(optarg) != 0) {
1306 			    errx(EX_USAGE, "invalid cpu topology "
1307 				"'%s'", optarg);
1308 			}
1309 			break;
1310 		case 'C':
1311 			memflags |= VM_MEM_F_INCORE;
1312 			break;
1313 		case 'g':
1314 			dbg_port = atoi(optarg);
1315 			break;
1316 		case 'G':
1317 			if (optarg[0] == 'w') {
1318 				gdb_stop = true;
1319 				optarg++;
1320 			}
1321 			gdb_port = atoi(optarg);
1322 			break;
1323 		case 'l':
1324 			if (strncmp(optarg, "help", strlen(optarg)) == 0) {
1325 				lpc_print_supported_devices();
1326 				exit(0);
1327 			} else if (lpc_device_parse(optarg) != 0) {
1328 				errx(EX_USAGE, "invalid lpc device "
1329 				    "configuration '%s'", optarg);
1330 			}
1331 			break;
1332 		case 's':
1333 			if (strncmp(optarg, "help", strlen(optarg)) == 0) {
1334 				pci_print_supported_devices();
1335 				exit(0);
1336 			} else if (pci_parse_slot(optarg) != 0)
1337 				exit(4);
1338 			else
1339 				break;
1340 		case 'S':
1341 			memflags |= VM_MEM_F_WIRED;
1342 			break;
1343                 case 'm':
1344 			error = vm_parse_memsize(optarg, &memsize);
1345 			if (error)
1346 				errx(EX_USAGE, "invalid memsize '%s'", optarg);
1347 			break;
1348 		case 'H':
1349 			guest_vmexit_on_hlt = 1;
1350 			break;
1351 		case 'I':
1352 			/*
1353 			 * The "-I" option was used to add an ioapic to the
1354 			 * virtual machine.
1355 			 *
1356 			 * An ioapic is now provided unconditionally for each
1357 			 * virtual machine and this option is now deprecated.
1358 			 */
1359 			break;
1360 		case 'P':
1361 			guest_vmexit_on_pause = 1;
1362 			break;
1363 		case 'e':
1364 			strictio = 1;
1365 			break;
1366 		case 'u':
1367 			rtc_localtime = 0;
1368 			break;
1369 		case 'U':
1370 			guest_uuid_str = optarg;
1371 			break;
1372 		case 'w':
1373 			strictmsr = 0;
1374 			break;
1375 		case 'W':
1376 			virtio_msix = 0;
1377 			break;
1378 		case 'x':
1379 			x2apic_mode = 1;
1380 			break;
1381 		case 'Y':
1382 			mptgen = 0;
1383 			break;
1384 		case 'h':
1385 			usage(0);
1386 		default:
1387 			usage(1);
1388 		}
1389 	}
1390 	argc -= optind;
1391 	argv += optind;
1392 
1393 	if (argc != 1)
1394 		usage(1);
1395 
1396 	vmname = argv[0];
1397 	ctx = do_open(vmname);
1398 
1399 	max_vcpus = num_vcpus_allowed(ctx);
1400 	if (guest_ncpus > max_vcpus) {
1401 		fprintf(stderr, "%d vCPUs requested but only %d available\n",
1402 			guest_ncpus, max_vcpus);
1403 		exit(4);
1404 	}
1405 
1406 	fbsdrun_set_capabilities(ctx, BSP);
1407 
1408 	vm_set_memflags(ctx, memflags);
1409 #ifdef	__FreeBSD__
1410 	err = vm_setup_memory(ctx, memsize, VM_MMAP_ALL);
1411 #else
1412 	do {
1413 		errno = 0;
1414 		err = vm_setup_memory(ctx, memsize, VM_MMAP_ALL);
1415 		error = errno;
1416 		if (err != 0 && error == ENOMEM) {
1417 			(void) fprintf(stderr, "Unable to allocate memory "
1418 			    "(%llu), retrying in 1 second\n", memsize);
1419 			sleep(1);
1420 		}
1421 	} while (error == ENOMEM);
1422 #endif
1423 	if (err) {
1424 		fprintf(stderr, "Unable to setup memory (%d)\n", errno);
1425 		exit(4);
1426 	}
1427 
1428 	error = init_msr();
1429 	if (error) {
1430 		fprintf(stderr, "init_msr error %d", error);
1431 		exit(4);
1432 	}
1433 
1434 	init_mem();
1435 	init_inout();
1436 #ifdef	__FreeBSD__
1437 	kernemu_dev_init();
1438 #endif
1439 	init_bootrom(ctx);
1440 	atkbdc_init(ctx);
1441 	pci_irq_init(ctx);
1442 	ioapic_init(ctx);
1443 
1444 	rtc_init(ctx, rtc_localtime);
1445 	sci_init(ctx);
1446 #ifndef	__FreeBSD__
1447 	pmtmr_init(ctx);
1448 #endif
1449 
1450 	/*
1451 	 * Exit if a device emulation finds an error in its initilization
1452 	 */
1453 	if (init_pci(ctx) != 0) {
1454 		perror("device emulation initialization error");
1455 		exit(4);
1456 	}
1457 
1458 	/*
1459 	 * Initialize after PCI, to allow a bootrom file to reserve the high
1460 	 * region.
1461 	 */
1462 	if (acpi)
1463 		vmgenc_init(ctx);
1464 
1465 	if (dbg_port != 0)
1466 		init_dbgport(dbg_port);
1467 
1468 #ifdef __FreeBSD__
1469 	if (gdb_port != 0)
1470 		init_gdb(ctx, gdb_port, gdb_stop);
1471 #else
1472 	if (gdb_port < 0) {
1473 		/*
1474 		 * Set up the internal gdb state needed for basic debugging, but
1475 		 * skip the step of listening on a port for the GDB server.
1476 		 */
1477 		init_mdb(ctx, gdb_stop);
1478 	} else if (gdb_port != 0) {
1479 		init_gdb(ctx, gdb_port, gdb_stop);
1480 	}
1481 #endif
1482 
1483 	if (bvmcons)
1484 		init_bvmcons();
1485 
1486 	vga_init(1);
1487 
1488 	if (lpc_bootrom()) {
1489 #ifdef __FreeBSD__
1490 		if (vm_set_capability(ctx, BSP, VM_CAP_UNRESTRICTED_GUEST, 1)) {
1491 			fprintf(stderr, "ROM boot failed: unrestricted guest "
1492 			    "capability not available\n");
1493 			exit(4);
1494 		}
1495 #else
1496 		/* Unrestricted Guest is always enabled on illumos */
1497 #endif
1498 		error = vcpu_reset(ctx, BSP);
1499 		assert(error == 0);
1500 	}
1501 
1502 	error = vm_get_register(ctx, BSP, VM_REG_GUEST_RIP, &rip);
1503 	assert(error == 0);
1504 
1505 	/*
1506  	 * build the guest tables, MP etc.
1507 	 */
1508 	if (mptgen) {
1509 		error = mptable_build(ctx, guest_ncpus);
1510 		if (error) {
1511 			perror("error to build the guest tables");
1512 			exit(4);
1513 		}
1514 	}
1515 
1516 	error = smbios_build(ctx);
1517 	assert(error == 0);
1518 
1519 	if (acpi) {
1520 		error = acpi_build(ctx, guest_ncpus);
1521 		assert(error == 0);
1522 	}
1523 
1524 	if (lpc_bootrom())
1525 		fwctl_init();
1526 
1527 	/*
1528 	 * Change the proc title to include the VM name.
1529 	 */
1530 	setproctitle("%s", vmname);
1531 
1532 #ifndef WITHOUT_CAPSICUM
1533 	caph_cache_catpages();
1534 
1535 	if (caph_limit_stdout() == -1 || caph_limit_stderr() == -1)
1536 		errx(EX_OSERR, "Unable to apply rights for sandbox");
1537 
1538 	if (caph_enter() == -1)
1539 		errx(EX_OSERR, "cap_enter() failed");
1540 #endif
1541 
1542 #ifdef __FreeBSD__
1543 	/*
1544 	 * Add CPU 0
1545 	 */
1546 	fbsdrun_addcpu(ctx, BSP, BSP, rip);
1547 #else
1548 	/* Set BSP to run (unlike the APs which wait for INIT) */
1549 	error = vm_set_run_state(ctx, BSP, VRS_RUN, 0);
1550 	assert(error == 0);
1551 	fbsdrun_addcpu(ctx, BSP, rip, suspend);
1552 
1553 	/* Add subsequent CPUs, which will wait until INIT/SIPI-ed */
1554 	for (uint_t i = 1; i < guest_ncpus; i++) {
1555 		spinup_halted_ap(ctx, i);
1556 	}
1557 #endif
1558 	/*
1559 	 * Head off to the main event dispatch loop
1560 	 */
1561 	mevent_dispatch();
1562 
1563 	exit(4);
1564 }
1565