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