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