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