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