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