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