xref: /illumos-gate/usr/src/cmd/bhyve/bhyverun.c (revision 7d10cd4d)
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;
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 #endif /* __FreeBSD__ */
840 
841 #ifdef __FreeBSD__
842 #define	DEBUG_EPT_MISCONFIG
843 #else
844 /* EPT misconfig debugging not possible now that raw VMCS access is gone */
845 #endif
846 
847 #ifdef DEBUG_EPT_MISCONFIG
848 #define	VMCS_GUEST_PHYSICAL_ADDRESS	0x00002400
849 
850 static uint64_t ept_misconfig_gpa, ept_misconfig_pte[4];
851 static int ept_misconfig_ptenum;
852 #endif
853 
854 static const char *
855 vmexit_vmx_desc(uint32_t exit_reason)
856 {
857 
858 	if (exit_reason >= nitems(vmx_exit_reason_desc) ||
859 	    vmx_exit_reason_desc[exit_reason] == NULL)
860 		return ("Unknown");
861 	return (vmx_exit_reason_desc[exit_reason]);
862 }
863 
864 static int
865 vmexit_vmx(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
866 {
867 
868 	fprintf(stderr, "vm exit[%d]\n", *pvcpu);
869 	fprintf(stderr, "\treason\t\tVMX\n");
870 	fprintf(stderr, "\trip\t\t0x%016lx\n", vmexit->rip);
871 	fprintf(stderr, "\tinst_length\t%d\n", vmexit->inst_length);
872 	fprintf(stderr, "\tstatus\t\t%d\n", vmexit->u.vmx.status);
873 	fprintf(stderr, "\texit_reason\t%u (%s)\n", vmexit->u.vmx.exit_reason,
874 	    vmexit_vmx_desc(vmexit->u.vmx.exit_reason));
875 	fprintf(stderr, "\tqualification\t0x%016lx\n",
876 	    vmexit->u.vmx.exit_qualification);
877 	fprintf(stderr, "\tinst_type\t\t%d\n", vmexit->u.vmx.inst_type);
878 	fprintf(stderr, "\tinst_error\t\t%d\n", vmexit->u.vmx.inst_error);
879 #ifdef DEBUG_EPT_MISCONFIG
880 	if (vmexit->u.vmx.exit_reason == EXIT_REASON_EPT_MISCONFIG) {
881 		vm_get_register(ctx, *pvcpu,
882 		    VMCS_IDENT(VMCS_GUEST_PHYSICAL_ADDRESS),
883 		    &ept_misconfig_gpa);
884 		vm_get_gpa_pmap(ctx, ept_misconfig_gpa, ept_misconfig_pte,
885 		    &ept_misconfig_ptenum);
886 		fprintf(stderr, "\tEPT misconfiguration:\n");
887 		fprintf(stderr, "\t\tGPA: %#lx\n", ept_misconfig_gpa);
888 		fprintf(stderr, "\t\tPTE(%d): %#lx %#lx %#lx %#lx\n",
889 		    ept_misconfig_ptenum, ept_misconfig_pte[0],
890 		    ept_misconfig_pte[1], ept_misconfig_pte[2],
891 		    ept_misconfig_pte[3]);
892 	}
893 #endif	/* DEBUG_EPT_MISCONFIG */
894 	return (VMEXIT_ABORT);
895 }
896 
897 static int
898 vmexit_svm(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
899 {
900 
901 	fprintf(stderr, "vm exit[%d]\n", *pvcpu);
902 	fprintf(stderr, "\treason\t\tSVM\n");
903 	fprintf(stderr, "\trip\t\t0x%016lx\n", vmexit->rip);
904 	fprintf(stderr, "\tinst_length\t%d\n", vmexit->inst_length);
905 	fprintf(stderr, "\texitcode\t%#lx\n", vmexit->u.svm.exitcode);
906 	fprintf(stderr, "\texitinfo1\t%#lx\n", vmexit->u.svm.exitinfo1);
907 	fprintf(stderr, "\texitinfo2\t%#lx\n", vmexit->u.svm.exitinfo2);
908 	return (VMEXIT_ABORT);
909 }
910 
911 static int
912 vmexit_bogus(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
913 {
914 
915 	assert(vmexit->inst_length == 0);
916 
917 	stats.vmexit_bogus++;
918 
919 	return (VMEXIT_CONTINUE);
920 }
921 
922 static int
923 vmexit_reqidle(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
924 {
925 
926 	assert(vmexit->inst_length == 0);
927 
928 	stats.vmexit_reqidle++;
929 
930 	return (VMEXIT_CONTINUE);
931 }
932 
933 static int
934 vmexit_hlt(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
935 {
936 
937 	stats.vmexit_hlt++;
938 
939 	/*
940 	 * Just continue execution with the next instruction. We use
941 	 * the HLT VM exit as a way to be friendly with the host
942 	 * scheduler.
943 	 */
944 	return (VMEXIT_CONTINUE);
945 }
946 
947 static int
948 vmexit_pause(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
949 {
950 
951 	stats.vmexit_pause++;
952 
953 	return (VMEXIT_CONTINUE);
954 }
955 
956 static int
957 vmexit_mtrap(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
958 {
959 
960 	assert(vmexit->inst_length == 0);
961 
962 	stats.vmexit_mtrap++;
963 
964 	gdb_cpu_mtrap(*pvcpu);
965 
966 	return (VMEXIT_CONTINUE);
967 }
968 
969 static int
970 vmexit_inst_emul(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
971 {
972 	uint8_t i, valid;
973 
974 	fprintf(stderr, "Failed to emulate instruction sequence ");
975 
976 	valid = vmexit->u.inst_emul.num_valid;
977 	if (valid != 0) {
978 		assert(valid <= sizeof (vmexit->u.inst_emul.inst));
979 		fprintf(stderr, "[");
980 		for (i = 0; i < valid; i++) {
981 			if (i == 0) {
982 				fprintf(stderr, "%02x",
983 				    vmexit->u.inst_emul.inst[i]);
984 			} else {
985 				fprintf(stderr, ", %02x",
986 				    vmexit->u.inst_emul.inst[i]);
987 			}
988 		}
989 		fprintf(stderr, "] ");
990 	}
991 	fprintf(stderr, "@ %rip = %x\n", vmexit->rip);
992 
993 	return (VMEXIT_ABORT);
994 }
995 
996 static int
997 vmexit_mmio(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
998 {
999 	int vcpu, err;
1000 	struct vm_mmio mmio;
1001 	bool is_read;
1002 
1003 	stats.vmexit_mmio++;
1004 
1005 	vcpu = *pvcpu;
1006 	mmio = vmexit->u.mmio;
1007 	is_read = (mmio.read != 0);
1008 
1009 	err = emulate_mem(ctx, vcpu, &mmio);
1010 
1011 	if (err == ESRCH) {
1012 		fprintf(stderr, "Unhandled memory access to 0x%lx\n", mmio.gpa);
1013 		stats.mmio_unhandled++;
1014 
1015 		/*
1016 		 * Access to non-existent physical addresses is not likely to
1017 		 * result in fatal errors on hardware machines, but rather reads
1018 		 * of all-ones or discarded-but-acknowledged writes.
1019 		 */
1020 		mmio.data = ~0UL;
1021 		err = 0;
1022 	}
1023 
1024 	if (err == 0) {
1025 		if (is_read) {
1026 			vmentry_mmio_read(vcpu, mmio.gpa, mmio.bytes,
1027 			    mmio.data);
1028 		} else {
1029 			vmentry_mmio_write(vcpu, mmio.gpa, mmio.bytes);
1030 		}
1031 		return (VMEXIT_CONTINUE);
1032 	}
1033 
1034 	fprintf(stderr, "Unhandled mmio error to 0x%lx: %d\n", mmio.gpa, err);
1035 	return (VMEXIT_ABORT);
1036 }
1037 
1038 static pthread_mutex_t resetcpu_mtx = PTHREAD_MUTEX_INITIALIZER;
1039 static pthread_cond_t resetcpu_cond = PTHREAD_COND_INITIALIZER;
1040 
1041 static int
1042 vmexit_suspend(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
1043 {
1044 	enum vm_suspend_how how;
1045 
1046 	how = vmexit->u.suspended.how;
1047 
1048 	fbsdrun_deletecpu(ctx, *pvcpu);
1049 
1050 	if (*pvcpu != BSP) {
1051 		pthread_mutex_lock(&resetcpu_mtx);
1052 		pthread_cond_signal(&resetcpu_cond);
1053 		pthread_mutex_unlock(&resetcpu_mtx);
1054 		pthread_exit(NULL);
1055 	}
1056 
1057 	pthread_mutex_lock(&resetcpu_mtx);
1058 	while (!CPU_EMPTY(&cpumask)) {
1059 		pthread_cond_wait(&resetcpu_cond, &resetcpu_mtx);
1060 	}
1061 	pthread_mutex_unlock(&resetcpu_mtx);
1062 
1063 	switch (how) {
1064 	case VM_SUSPEND_RESET:
1065 		exit(0);
1066 	case VM_SUSPEND_POWEROFF:
1067 		if (get_config_bool_default("destroy_on_poweroff", false))
1068 			vm_destroy(ctx);
1069 		exit(1);
1070 	case VM_SUSPEND_HALT:
1071 		exit(2);
1072 	case VM_SUSPEND_TRIPLEFAULT:
1073 		exit(3);
1074 	default:
1075 		fprintf(stderr, "vmexit_suspend: invalid reason %d\n", how);
1076 		exit(100);
1077 	}
1078 	return (0);	/* NOTREACHED */
1079 }
1080 
1081 static int
1082 vmexit_debug(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
1083 {
1084 
1085 	gdb_cpu_suspend(*pvcpu);
1086 	return (VMEXIT_CONTINUE);
1087 }
1088 
1089 static int
1090 vmexit_breakpoint(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
1091 {
1092 
1093 	gdb_cpu_breakpoint(*pvcpu, vmexit);
1094 	return (VMEXIT_CONTINUE);
1095 }
1096 
1097 static vmexit_handler_t handler[VM_EXITCODE_MAX] = {
1098 	[VM_EXITCODE_INOUT]  = vmexit_inout,
1099 	[VM_EXITCODE_MMIO]  = vmexit_mmio,
1100 	[VM_EXITCODE_VMX]    = vmexit_vmx,
1101 	[VM_EXITCODE_SVM]    = vmexit_svm,
1102 	[VM_EXITCODE_BOGUS]  = vmexit_bogus,
1103 	[VM_EXITCODE_REQIDLE] = vmexit_reqidle,
1104 	[VM_EXITCODE_RDMSR]  = vmexit_rdmsr,
1105 	[VM_EXITCODE_WRMSR]  = vmexit_wrmsr,
1106 	[VM_EXITCODE_MTRAP]  = vmexit_mtrap,
1107 	[VM_EXITCODE_INST_EMUL] = vmexit_inst_emul,
1108 #ifdef __FreeBSD__
1109 	[VM_EXITCODE_SPINUP_AP] = vmexit_spinup_ap,
1110 #else
1111 	[VM_EXITCODE_RUN_STATE] = vmexit_run_state,
1112 #endif
1113 	[VM_EXITCODE_SUSPENDED] = vmexit_suspend,
1114 	[VM_EXITCODE_TASK_SWITCH] = vmexit_task_switch,
1115 	[VM_EXITCODE_DEBUG] = vmexit_debug,
1116 	[VM_EXITCODE_BPT] = vmexit_breakpoint,
1117 };
1118 
1119 static void
1120 vm_loop(struct vmctx *ctx, int vcpu, uint64_t startrip)
1121 {
1122 	int error, rc;
1123 	enum vm_exitcode exitcode;
1124 	cpuset_t active_cpus;
1125 	struct vm_exit *vexit;
1126 	struct vm_entry *ventry;
1127 
1128 #ifdef	__FreeBSD__
1129 	if (vcpumap[vcpu] != NULL) {
1130 		error = pthread_setaffinity_np(pthread_self(),
1131 		    sizeof(cpuset_t), vcpumap[vcpu]);
1132 		assert(error == 0);
1133 	}
1134 #endif
1135 	error = vm_active_cpus(ctx, &active_cpus);
1136 	assert(CPU_ISSET(vcpu, &active_cpus));
1137 
1138 	error = vm_set_register(ctx, vcpu, VM_REG_GUEST_RIP, startrip);
1139 	assert(error == 0);
1140 
1141 	ventry = &vmentry[vcpu];
1142 	vexit = &vmexit[vcpu];
1143 
1144 	while (1) {
1145 		error = vm_run(ctx, vcpu, ventry, vexit);
1146 		if (error != 0)
1147 			break;
1148 
1149 		if (ventry->cmd != VEC_DEFAULT) {
1150 			/*
1151 			 * Discard any lingering entry state after it has been
1152 			 * submitted via vm_run().
1153 			 */
1154 			bzero(ventry, sizeof (*ventry));
1155 		}
1156 
1157 		exitcode = vexit->exitcode;
1158 		if (exitcode >= VM_EXITCODE_MAX || handler[exitcode] == NULL) {
1159 			fprintf(stderr, "vm_loop: unexpected exitcode 0x%x\n",
1160 			    exitcode);
1161 			exit(4);
1162 		}
1163 
1164 		rc = (*handler[exitcode])(ctx, vexit, &vcpu);
1165 
1166 		switch (rc) {
1167 		case VMEXIT_CONTINUE:
1168 			break;
1169 		case VMEXIT_ABORT:
1170 			abort();
1171 		default:
1172 			exit(4);
1173 		}
1174 	}
1175 	fprintf(stderr, "vm_run error %d, errno %d\n", error, errno);
1176 }
1177 
1178 static int
1179 num_vcpus_allowed(struct vmctx *ctx)
1180 {
1181 	uint16_t sockets, cores, threads, maxcpus;
1182 #ifdef __FreeBSD__
1183 	int tmp, error;
1184 
1185 	/*
1186 	 * The guest is allowed to spinup more than one processor only if the
1187 	 * UNRESTRICTED_GUEST capability is available.
1188 	 */
1189 	error = vm_get_capability(ctx, BSP, VM_CAP_UNRESTRICTED_GUEST, &tmp);
1190 	if (error != 0)
1191 		return (1);
1192 #else
1193 	int error;
1194 	/* Unrestricted Guest is always enabled on illumos */
1195 
1196 #endif /* __FreeBSD__ */
1197 
1198 	error = vm_get_topology(ctx, &sockets, &cores, &threads, &maxcpus);
1199 	if (error == 0)
1200 		return (maxcpus);
1201 	else
1202 		return (1);
1203 }
1204 
1205 void
1206 fbsdrun_set_capabilities(struct vmctx *ctx, int cpu)
1207 {
1208 	int err, tmp;
1209 
1210 	if (get_config_bool_default("x86.vmexit_on_hlt", false)) {
1211 		err = vm_get_capability(ctx, cpu, VM_CAP_HALT_EXIT, &tmp);
1212 		if (err < 0) {
1213 			fprintf(stderr, "VM exit on HLT not supported\n");
1214 			exit(4);
1215 		}
1216 		vm_set_capability(ctx, cpu, VM_CAP_HALT_EXIT, 1);
1217 		if (cpu == BSP)
1218 			handler[VM_EXITCODE_HLT] = vmexit_hlt;
1219 	}
1220 
1221 	if (get_config_bool_default("x86.vmexit_on_pause", false)) {
1222 		/*
1223 		 * pause exit support required for this mode
1224 		 */
1225 		err = vm_get_capability(ctx, cpu, VM_CAP_PAUSE_EXIT, &tmp);
1226 		if (err < 0) {
1227 			fprintf(stderr,
1228 			    "SMP mux requested, no pause support\n");
1229 			exit(4);
1230 		}
1231 		vm_set_capability(ctx, cpu, VM_CAP_PAUSE_EXIT, 1);
1232 		if (cpu == BSP)
1233 			handler[VM_EXITCODE_PAUSE] = vmexit_pause;
1234         }
1235 
1236 	if (get_config_bool_default("x86.x2apic", false))
1237 		err = vm_set_x2apic_state(ctx, cpu, X2APIC_ENABLED);
1238 	else
1239 		err = vm_set_x2apic_state(ctx, cpu, X2APIC_DISABLED);
1240 
1241 	if (err) {
1242 		fprintf(stderr, "Unable to set x2apic state (%d)\n", err);
1243 		exit(4);
1244 	}
1245 
1246 #ifdef	__FreeBSD__
1247 	vm_set_capability(ctx, cpu, VM_CAP_ENABLE_INVPCID, 1);
1248 #endif
1249 }
1250 
1251 static struct vmctx *
1252 do_open(const char *vmname)
1253 {
1254 	struct vmctx *ctx;
1255 	int error;
1256 	bool reinit, romboot;
1257 #ifndef WITHOUT_CAPSICUM
1258 	cap_rights_t rights;
1259 	const cap_ioctl_t *cmds;
1260 	size_t ncmds;
1261 #endif
1262 
1263 	reinit = romboot = false;
1264 
1265 	if (lpc_bootrom())
1266 		romboot = true;
1267 #ifndef __FreeBSD__
1268 	uint64_t create_flags = 0;
1269 	if (get_config_bool_default("memory.use_reservoir", false)) {
1270 		create_flags |= VCF_RESERVOIR_MEM;
1271 	}
1272 	error = vm_create(vmname, create_flags);
1273 #else
1274 	error = vm_create(vmname);
1275 #endif /* __FreeBSD__ */
1276 	if (error) {
1277 		if (errno == EEXIST) {
1278 			if (romboot) {
1279 				reinit = true;
1280 			} else {
1281 				/*
1282 				 * The virtual machine has been setup by the
1283 				 * userspace bootloader.
1284 				 */
1285 			}
1286 		} else {
1287 			perror("vm_create");
1288 			exit(4);
1289 		}
1290 	} else {
1291 		if (!romboot) {
1292 			/*
1293 			 * If the virtual machine was just created then a
1294 			 * bootrom must be configured to boot it.
1295 			 */
1296 			fprintf(stderr, "virtual machine cannot be booted\n");
1297 			exit(4);
1298 		}
1299 	}
1300 
1301 	ctx = vm_open(vmname);
1302 	if (ctx == NULL) {
1303 		perror("vm_open");
1304 		exit(4);
1305 	}
1306 
1307 #ifndef WITHOUT_CAPSICUM
1308 	cap_rights_init(&rights, CAP_IOCTL, CAP_MMAP_RW);
1309 	if (caph_rights_limit(vm_get_device_fd(ctx), &rights) == -1)
1310 		errx(EX_OSERR, "Unable to apply rights for sandbox");
1311 	vm_get_ioctls(&ncmds);
1312 	cmds = vm_get_ioctls(NULL);
1313 	if (cmds == NULL)
1314 		errx(EX_OSERR, "out of memory");
1315 	if (caph_ioctls_limit(vm_get_device_fd(ctx), cmds, ncmds) == -1)
1316 		errx(EX_OSERR, "Unable to apply rights for sandbox");
1317 	free((cap_ioctl_t *)cmds);
1318 #endif
1319 
1320 	if (reinit) {
1321 #ifndef __FreeBSD__
1322 		error = vm_reinit(ctx, 0);
1323 #else
1324 		error = vm_reinit(ctx);
1325 #endif
1326 		if (error) {
1327 			perror("vm_reinit");
1328 			exit(4);
1329 		}
1330 	}
1331 	error = vm_set_topology(ctx, sockets, cores, threads, maxcpus);
1332 	if (error)
1333 		errx(EX_OSERR, "vm_set_topology");
1334 	return (ctx);
1335 }
1336 
1337 static bool
1338 parse_config_option(const char *option)
1339 {
1340 	const char *value;
1341 	char *path;
1342 
1343 	value = strchr(option, '=');
1344 	if (value == NULL || value[1] == '\0')
1345 		return (false);
1346 	path = strndup(option, value - option);
1347 	if (path == NULL)
1348 		err(4, "Failed to allocate memory");
1349 	set_config_value(path, value + 1);
1350 	return (true);
1351 }
1352 
1353 static void
1354 parse_simple_config_file(const char *path)
1355 {
1356 	FILE *fp;
1357 	char *line, *cp;
1358 	size_t linecap;
1359 	unsigned int lineno;
1360 
1361 	fp = fopen(path, "r");
1362 	if (fp == NULL)
1363 		err(4, "Failed to open configuration file %s", path);
1364 	line = NULL;
1365 	linecap = 0;
1366 	lineno = 1;
1367 	for (lineno = 1; getline(&line, &linecap, fp) > 0; lineno++) {
1368 		if (*line == '#' || *line == '\n')
1369 			continue;
1370 		cp = strchr(line, '\n');
1371 		if (cp != NULL)
1372 			*cp = '\0';
1373 		if (!parse_config_option(line))
1374 			errx(4, "%s line %u: invalid config option '%s'", path,
1375 			    lineno, line);
1376 	}
1377 	free(line);
1378 	fclose(fp);
1379 }
1380 
1381 static void
1382 parse_gdb_options(char *optarg)
1383 {
1384 	const char *sport;
1385 	char *colon;
1386 
1387 	if (optarg[0] == 'w') {
1388 		set_config_bool("gdb.wait", true);
1389 		optarg++;
1390 	}
1391 
1392 	colon = strrchr(optarg, ':');
1393 	if (colon == NULL) {
1394 		sport = optarg;
1395 	} else {
1396 		*colon = '\0';
1397 		colon++;
1398 		sport = colon;
1399 		set_config_value("gdb.address", optarg);
1400 	}
1401 
1402 	set_config_value("gdb.port", sport);
1403 }
1404 
1405 static void
1406 set_defaults(void)
1407 {
1408 
1409 	set_config_bool("acpi_tables", false);
1410 	set_config_value("memory.size", "256M");
1411 	set_config_bool("x86.strictmsr", true);
1412 }
1413 
1414 int
1415 main(int argc, char *argv[])
1416 {
1417 	int c, error, err;
1418 	int max_vcpus, memflags;
1419 	struct vmctx *ctx;
1420 	uint64_t rip;
1421 	size_t memsize;
1422 	const char *value, *vmname;
1423 	char *optstr;
1424 
1425 	init_config();
1426 	set_defaults();
1427 	progname = basename(argv[0]);
1428 
1429 #ifdef	__FreeBSD__
1430 	optstr = "aehuwxACDHIPSWYk:o:p:G:c:s:m:l:K:U:";
1431 #else
1432 	/* +d, +B, -p */
1433 	optstr = "adehuwxACDHIPSWYk:o:G:c:s:m:l:B:K:U:";
1434 #endif
1435 	while ((c = getopt(argc, argv, optstr)) != -1) {
1436 		switch (c) {
1437 		case 'a':
1438 			set_config_bool("x86.x2apic", false);
1439 			break;
1440 		case 'A':
1441 #ifdef __FreeBSD__
1442 			/*
1443 			 * This option is ignored on illumos since the
1444 			 * generated ACPI tables are not used; the bootroms
1445 			 * have their own. The option is retained for backwards
1446 			 * compatibility but does nothing. Note that the
1447 			 * acpi_tables configuration is still accepted via
1448 			 * -o if somebody really wants to generate these tables.
1449 			 */
1450 			set_config_bool("acpi_tables", true);
1451 #endif
1452 			break;
1453 		case 'D':
1454 			set_config_bool("destroy_on_poweroff", true);
1455 			break;
1456 #ifndef	__FreeBSD__
1457 		case 'B':
1458 			if (smbios_parse(optarg) != 0) {
1459 				errx(EX_USAGE, "invalid SMBIOS "
1460 				    "configuration '%s'", optarg);
1461 			}
1462 			break;
1463 		case 'd':
1464 			set_config_bool("suspend_at_boot", true);
1465 			break;
1466 #endif
1467 #ifdef	__FreeBSD__
1468 		case 'p':
1469 			if (pincpu_parse(optarg) != 0) {
1470 				errx(EX_USAGE, "invalid vcpu pinning "
1471 				    "configuration '%s'", optarg);
1472 			}
1473 			break;
1474 #endif
1475                 case 'c':
1476 			if (topology_parse(optarg) != 0) {
1477 			    errx(EX_USAGE, "invalid cpu topology "
1478 				"'%s'", optarg);
1479 			}
1480 			break;
1481 		case 'C':
1482 			set_config_bool("memory.guest_in_core", true);
1483 			break;
1484 		case 'G':
1485 			parse_gdb_options(optarg);
1486 			break;
1487 		case 'k':
1488 			parse_simple_config_file(optarg);
1489 			break;
1490 		case 'K':
1491 			set_config_value("keyboard.layout", optarg);
1492 			break;
1493 		case 'l':
1494 			if (strncmp(optarg, "help", strlen(optarg)) == 0) {
1495 				lpc_print_supported_devices();
1496 				exit(0);
1497 			} else if (lpc_device_parse(optarg) != 0) {
1498 				errx(EX_USAGE, "invalid lpc device "
1499 				    "configuration '%s'", optarg);
1500 			}
1501 			break;
1502 		case 's':
1503 			if (strncmp(optarg, "help", strlen(optarg)) == 0) {
1504 				pci_print_supported_devices();
1505 				exit(0);
1506 			} else if (pci_parse_slot(optarg) != 0)
1507 				exit(4);
1508 			else
1509 				break;
1510 		case 'S':
1511 			set_config_bool("memory.wired", true);
1512 			break;
1513                 case 'm':
1514 			set_config_value("memory.size", optarg);
1515 			break;
1516 		case 'o':
1517 			if (!parse_config_option(optarg))
1518 				errx(EX_USAGE, "invalid configuration option '%s'", optarg);
1519 			break;
1520 		case 'H':
1521 			set_config_bool("x86.vmexit_on_hlt", true);
1522 			break;
1523 		case 'I':
1524 			/*
1525 			 * The "-I" option was used to add an ioapic to the
1526 			 * virtual machine.
1527 			 *
1528 			 * An ioapic is now provided unconditionally for each
1529 			 * virtual machine and this option is now deprecated.
1530 			 */
1531 			break;
1532 		case 'P':
1533 			set_config_bool("x86.vmexit_on_pause", true);
1534 			break;
1535 		case 'e':
1536 			set_config_bool("x86.strictio", true);
1537 			break;
1538 		case 'u':
1539 			set_config_bool("rtc.use_localtime", false);
1540 			break;
1541 		case 'U':
1542 			set_config_value("uuid", optarg);
1543 			break;
1544 		case 'w':
1545 			set_config_bool("x86.strictmsr", false);
1546 			break;
1547 		case 'W':
1548 			set_config_bool("virtio_msix", false);
1549 			break;
1550 		case 'x':
1551 			set_config_bool("x86.x2apic", true);
1552 			break;
1553 		case 'Y':
1554 			set_config_bool("x86.mptable", false);
1555 			break;
1556 		case 'h':
1557 			usage(0);
1558 		default:
1559 			usage(1);
1560 		}
1561 	}
1562 	argc -= optind;
1563 	argv += optind;
1564 
1565 	if (argc > 1)
1566 		usage(1);
1567 
1568 	if (argc == 1)
1569 		set_config_value("name", argv[0]);
1570 
1571 	vmname = get_config_value("name");
1572 	if (vmname == NULL)
1573 		usage(1);
1574 
1575 	if (get_config_bool_default("config.dump", false)) {
1576 		dump_config();
1577 		exit(1);
1578 	}
1579 
1580 #ifndef __FreeBSD__
1581 	illumos_priv_init();
1582 #endif
1583 
1584 	calc_topolopgy();
1585 #ifdef __FreeBSD__
1586 	build_vcpumaps();
1587 #endif
1588 
1589 	value = get_config_value("memory.size");
1590 	error = vm_parse_memsize(value, &memsize);
1591 	if (error)
1592 		errx(EX_USAGE, "invalid memsize '%s'", value);
1593 
1594 	ctx = do_open(vmname);
1595 
1596         max_vcpus = num_vcpus_allowed(ctx);
1597         if (guest_ncpus > max_vcpus) {
1598 		fprintf(stderr, "%d vCPUs requested but only %d available\n",
1599 			guest_ncpus, max_vcpus);
1600 		exit(4);
1601 	}
1602 
1603 	fbsdrun_set_capabilities(ctx, BSP);
1604 
1605 	memflags = 0;
1606 	if (get_config_bool_default("memory.wired", false))
1607 		memflags |= VM_MEM_F_WIRED;
1608 	if (get_config_bool_default("memory.guest_in_core", false))
1609 		memflags |= VM_MEM_F_INCORE;
1610 	vm_set_memflags(ctx, memflags);
1611 #ifdef	__FreeBSD__
1612 	err = vm_setup_memory(ctx, memsize, VM_MMAP_ALL);
1613 #else
1614 	do {
1615 		errno = 0;
1616 		err = vm_setup_memory(ctx, memsize, VM_MMAP_ALL);
1617 		error = errno;
1618 		if (err != 0 && error == ENOMEM) {
1619 			(void) fprintf(stderr, "Unable to allocate memory "
1620 			    "(%llu), retrying in 1 second\n", memsize);
1621 			sleep(1);
1622 		}
1623 	} while (error == ENOMEM);
1624 #endif
1625 	if (err) {
1626 		fprintf(stderr, "Unable to set up memory (%d)\n", errno);
1627 		exit(4);
1628 	}
1629 
1630 	error = init_msr();
1631 	if (error) {
1632 		fprintf(stderr, "init_msr error %d", error);
1633 		exit(4);
1634 	}
1635 
1636 	init_mem(guest_ncpus);
1637 	init_inout();
1638 #ifdef	__FreeBSD__
1639 	kernemu_dev_init();
1640 #endif
1641 	init_bootrom(ctx);
1642 	atkbdc_init(ctx);
1643 	pci_irq_init(ctx);
1644 	ioapic_init(ctx);
1645 
1646 	rtc_init(ctx);
1647 	sci_init(ctx);
1648 #ifndef	__FreeBSD__
1649 	pmtmr_init(ctx);
1650 #endif
1651 
1652 	/* Allocate per-VCPU resources. */
1653 	vmexit = calloc(guest_ncpus, sizeof(*vmexit));
1654 	mt_vmm_info = calloc(guest_ncpus, sizeof(*mt_vmm_info));
1655 #ifndef	__FreeBSD__
1656 	vmentry = calloc(guest_ncpus, sizeof(*vmentry));
1657 #endif
1658 
1659 	/*
1660 	 * Exit if a device emulation finds an error in its initilization
1661 	 */
1662 	if (init_pci(ctx) != 0) {
1663 		perror("device emulation initialization error");
1664 		exit(4);
1665 	}
1666 
1667 	/*
1668 	 * Initialize after PCI, to allow a bootrom file to reserve the high
1669 	 * region.
1670 	 */
1671 	if (get_config_bool("acpi_tables"))
1672 		vmgenc_init(ctx);
1673 
1674 #ifdef __FreeBSD__
1675 	init_gdb(ctx);
1676 #else
1677 	if (value != NULL) {
1678 		int port = atoi(value);
1679 
1680 		if (port < 0)
1681 			init_mdb(ctx);
1682 		else
1683 			init_gdb(ctx);
1684 	}
1685 #endif
1686 
1687 	if (lpc_bootrom()) {
1688 #ifdef __FreeBSD__
1689 		if (vm_set_capability(ctx, BSP, VM_CAP_UNRESTRICTED_GUEST, 1)) {
1690 			fprintf(stderr, "ROM boot failed: unrestricted guest "
1691 			    "capability not available\n");
1692 			exit(4);
1693 		}
1694 #else
1695 		/* Unrestricted Guest is always enabled on illumos */
1696 #endif
1697 		error = vcpu_reset(ctx, BSP);
1698 		assert(error == 0);
1699 	}
1700 
1701 	error = vm_get_register(ctx, BSP, VM_REG_GUEST_RIP, &rip);
1702 	assert(error == 0);
1703 
1704 	/*
1705  	 * build the guest tables, MP etc.
1706 	 */
1707 	if (get_config_bool_default("x86.mptable", true)) {
1708 		error = mptable_build(ctx, guest_ncpus);
1709 		if (error) {
1710 			perror("error to build the guest tables");
1711 			exit(4);
1712 		}
1713 	}
1714 
1715 #ifndef __FreeBSD__
1716 	smbios_apply();
1717 #endif
1718 	error = smbios_build(ctx);
1719 	assert(error == 0);
1720 
1721 	if (get_config_bool("acpi_tables")) {
1722 		error = acpi_build(ctx, guest_ncpus);
1723 		assert(error == 0);
1724 	}
1725 
1726 	if (lpc_bootrom())
1727 		fwctl_init();
1728 
1729 	/*
1730 	 * Change the proc title to include the VM name.
1731 	 */
1732 	setproctitle("%s", vmname);
1733 
1734 #ifndef WITHOUT_CAPSICUM
1735 	caph_cache_catpages();
1736 
1737 	if (caph_limit_stdout() == -1 || caph_limit_stderr() == -1)
1738 		errx(EX_OSERR, "Unable to apply rights for sandbox");
1739 
1740 	if (caph_enter() == -1)
1741 		errx(EX_OSERR, "cap_enter() failed");
1742 #endif
1743 
1744 #ifndef __FreeBSD__
1745 	illumos_priv_lock();
1746 #endif
1747 
1748 #ifdef __FreeBSD__
1749 	/*
1750 	 * Add CPU 0
1751 	 */
1752 	fbsdrun_addcpu(ctx, BSP, BSP, rip);
1753 #else
1754 	/* Set BSP to run (unlike the APs which wait for INIT) */
1755 	error = vm_set_run_state(ctx, BSP, VRS_RUN, 0);
1756 	assert(error == 0);
1757 	fbsdrun_addcpu(ctx, BSP, rip,
1758 	    get_config_bool_default("suspend_at_boot", false));
1759 
1760 	/* Add subsequent CPUs, which will wait until INIT/SIPI-ed */
1761 	for (uint_t i = 1; i < guest_ncpus; i++) {
1762 		spinup_halted_ap(ctx, i);
1763 	}
1764 #endif
1765 	/*
1766 	 * Head off to the main event dispatch loop
1767 	 */
1768 	mevent_dispatch();
1769 
1770 	exit(4);
1771 }
1772