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