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