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