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