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