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