xref: /freebsd/usr.sbin/bhyve/bhyverun.c (revision 96190b4fef3b4a0cc3ca0606b0c4e3e69a5e6717)
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/types.h>
30 #ifndef WITHOUT_CAPSICUM
31 #include <sys/capsicum.h>
32 #endif
33 #include <sys/mman.h>
34 #ifdef BHYVE_SNAPSHOT
35 #include <sys/socket.h>
36 #include <sys/stat.h>
37 #endif
38 #include <sys/time.h>
39 #ifdef BHYVE_SNAPSHOT
40 #include <sys/un.h>
41 #endif
42 
43 #include <machine/atomic.h>
44 
45 #ifndef WITHOUT_CAPSICUM
46 #include <capsicum_helpers.h>
47 #endif
48 #include <stdio.h>
49 #include <stdlib.h>
50 #include <string.h>
51 #include <err.h>
52 #include <errno.h>
53 #ifdef BHYVE_SNAPSHOT
54 #include <fcntl.h>
55 #endif
56 #include <libgen.h>
57 #include <unistd.h>
58 #include <assert.h>
59 #include <pthread.h>
60 #include <pthread_np.h>
61 #include <sysexits.h>
62 #include <stdbool.h>
63 #include <stdint.h>
64 #ifdef BHYVE_SNAPSHOT
65 #include <ucl.h>
66 #include <unistd.h>
67 
68 #include <libxo/xo.h>
69 #endif
70 
71 #include <vmmapi.h>
72 
73 #include "acpi.h"
74 #include "bhyverun.h"
75 #include "bootrom.h"
76 #include "config.h"
77 #include "debug.h"
78 #ifdef BHYVE_GDB
79 #include "gdb.h"
80 #endif
81 #include "mem.h"
82 #include "mevent.h"
83 #include "pci_emul.h"
84 #ifdef __amd64__
85 #include "amd64/pci_lpc.h"
86 #endif
87 #include "qemu_fwcfg.h"
88 #ifdef BHYVE_SNAPSHOT
89 #include "snapshot.h"
90 #endif
91 #include "tpm_device.h"
92 #include "vmgenc.h"
93 #include "vmexit.h"
94 
95 #define MB		(1024UL * 1024)
96 #define GB		(1024UL * MB)
97 
98 int guest_ncpus;
99 uint16_t cpu_cores, cpu_sockets, cpu_threads;
100 
101 int raw_stdio = 0;
102 
103 #ifdef BHYVE_SNAPSHOT
104 char *restore_file;
105 #endif
106 
107 static const int BSP = 0;
108 
109 static cpuset_t cpumask;
110 
111 static void vm_loop(struct vmctx *ctx, struct vcpu *vcpu);
112 
113 static struct vcpu_info {
114 	struct vmctx	*ctx;
115 	struct vcpu	*vcpu;
116 	int		vcpuid;
117 } *vcpu_info;
118 
119 static cpuset_t **vcpumap;
120 
121 /*
122  * XXX This parser is known to have the following issues:
123  * 1.  It accepts null key=value tokens ",," as setting "cpus" to an
124  *     empty string.
125  *
126  * The acceptance of a null specification ('-c ""') is by design to match the
127  * manual page syntax specification, this results in a topology of 1 vCPU.
128  */
129 int
130 bhyve_topology_parse(const char *opt)
131 {
132 	char *cp, *str, *tofree;
133 
134 	if (*opt == '\0') {
135 		set_config_value("sockets", "1");
136 		set_config_value("cores", "1");
137 		set_config_value("threads", "1");
138 		set_config_value("cpus", "1");
139 		return (0);
140 	}
141 
142 	tofree = str = strdup(opt);
143 	if (str == NULL)
144 		errx(4, "Failed to allocate memory");
145 
146 	while ((cp = strsep(&str, ",")) != NULL) {
147 		if (strncmp(cp, "cpus=", strlen("cpus=")) == 0)
148 			set_config_value("cpus", cp + strlen("cpus="));
149 		else if (strncmp(cp, "sockets=", strlen("sockets=")) == 0)
150 			set_config_value("sockets", cp + strlen("sockets="));
151 		else if (strncmp(cp, "cores=", strlen("cores=")) == 0)
152 			set_config_value("cores", cp + strlen("cores="));
153 		else if (strncmp(cp, "threads=", strlen("threads=")) == 0)
154 			set_config_value("threads", cp + strlen("threads="));
155 		else if (strchr(cp, '=') != NULL)
156 			goto out;
157 		else
158 			set_config_value("cpus", cp);
159 	}
160 	free(tofree);
161 	return (0);
162 
163 out:
164 	free(tofree);
165 	return (-1);
166 }
167 
168 static int
169 parse_int_value(const char *key, const char *value, int minval, int maxval)
170 {
171 	char *cp;
172 	long lval;
173 
174 	errno = 0;
175 	lval = strtol(value, &cp, 0);
176 	if (errno != 0 || *cp != '\0' || cp == value || lval < minval ||
177 	    lval > maxval)
178 		errx(4, "Invalid value for %s: '%s'", key, value);
179 	return (lval);
180 }
181 
182 /*
183  * Set the sockets, cores, threads, and guest_cpus variables based on
184  * the configured topology.
185  *
186  * The limits of UINT16_MAX are due to the types passed to
187  * vm_set_topology().  vmm.ko may enforce tighter limits.
188  */
189 static void
190 calc_topology(void)
191 {
192 	const char *value;
193 	bool explicit_cpus;
194 	uint64_t ncpus;
195 
196 	value = get_config_value("cpus");
197 	if (value != NULL) {
198 		guest_ncpus = parse_int_value("cpus", value, 1, UINT16_MAX);
199 		explicit_cpus = true;
200 	} else {
201 		guest_ncpus = 1;
202 		explicit_cpus = false;
203 	}
204 	value = get_config_value("cores");
205 	if (value != NULL)
206 		cpu_cores = parse_int_value("cores", value, 1, UINT16_MAX);
207 	else
208 		cpu_cores = 1;
209 	value = get_config_value("threads");
210 	if (value != NULL)
211 		cpu_threads = parse_int_value("threads", value, 1, UINT16_MAX);
212 	else
213 		cpu_threads = 1;
214 	value = get_config_value("sockets");
215 	if (value != NULL)
216 		cpu_sockets = parse_int_value("sockets", value, 1, UINT16_MAX);
217 	else
218 		cpu_sockets = guest_ncpus;
219 
220 	/*
221 	 * Compute sockets * cores * threads avoiding overflow.  The
222 	 * range check above insures these are 16 bit values.
223 	 */
224 	ncpus = (uint64_t)cpu_sockets * cpu_cores * cpu_threads;
225 	if (ncpus > UINT16_MAX)
226 		errx(4, "Computed number of vCPUs too high: %ju",
227 		    (uintmax_t)ncpus);
228 
229 	if (explicit_cpus) {
230 		if (guest_ncpus != (int)ncpus)
231 			errx(4, "Topology (%d sockets, %d cores, %d threads) "
232 			    "does not match %d vCPUs",
233 			    cpu_sockets, cpu_cores, cpu_threads,
234 			    guest_ncpus);
235 	} else
236 		guest_ncpus = ncpus;
237 }
238 
239 int
240 bhyve_pincpu_parse(const char *opt)
241 {
242 	const char *value;
243 	char *newval;
244 	char key[16];
245 	int vcpu, pcpu;
246 
247 	if (sscanf(opt, "%d:%d", &vcpu, &pcpu) != 2) {
248 		fprintf(stderr, "invalid format: %s\n", opt);
249 		return (-1);
250 	}
251 
252 	if (vcpu < 0) {
253 		fprintf(stderr, "invalid vcpu '%d'\n", vcpu);
254 		return (-1);
255 	}
256 
257 	if (pcpu < 0 || pcpu >= CPU_SETSIZE) {
258 		fprintf(stderr, "hostcpu '%d' outside valid range from "
259 		    "0 to %d\n", pcpu, CPU_SETSIZE - 1);
260 		return (-1);
261 	}
262 
263 	snprintf(key, sizeof(key), "vcpu.%d.cpuset", vcpu);
264 	value = get_config_value(key);
265 
266 	if (asprintf(&newval, "%s%s%d", value != NULL ? value : "",
267 	    value != NULL ? "," : "", pcpu) == -1) {
268 		perror("failed to build new cpuset string");
269 		return (-1);
270 	}
271 
272 	set_config_value(key, newval);
273 	free(newval);
274 	return (0);
275 }
276 
277 static void
278 parse_cpuset(int vcpu, const char *list, cpuset_t *set)
279 {
280 	char *cp, *token;
281 	int pcpu, start;
282 
283 	CPU_ZERO(set);
284 	start = -1;
285 	token = __DECONST(char *, list);
286 	for (;;) {
287 		pcpu = strtoul(token, &cp, 0);
288 		if (cp == token)
289 			errx(4, "invalid cpuset for vcpu %d: '%s'", vcpu, list);
290 		if (pcpu < 0 || pcpu >= CPU_SETSIZE)
291 			errx(4, "hostcpu '%d' outside valid range from 0 to %d",
292 			    pcpu, CPU_SETSIZE - 1);
293 		switch (*cp) {
294 		case ',':
295 		case '\0':
296 			if (start >= 0) {
297 				if (start > pcpu)
298 					errx(4, "Invalid hostcpu range %d-%d",
299 					    start, pcpu);
300 				while (start < pcpu) {
301 					CPU_SET(start, set);
302 					start++;
303 				}
304 				start = -1;
305 			}
306 			CPU_SET(pcpu, set);
307 			break;
308 		case '-':
309 			if (start >= 0)
310 				errx(4, "invalid cpuset for vcpu %d: '%s'",
311 				    vcpu, list);
312 			start = pcpu;
313 			break;
314 		default:
315 			errx(4, "invalid cpuset for vcpu %d: '%s'", vcpu, list);
316 		}
317 		if (*cp == '\0')
318 			break;
319 		token = cp + 1;
320 	}
321 }
322 
323 static void
324 build_vcpumaps(void)
325 {
326 	char key[16];
327 	const char *value;
328 	int vcpu;
329 
330 	vcpumap = calloc(guest_ncpus, sizeof(*vcpumap));
331 	for (vcpu = 0; vcpu < guest_ncpus; vcpu++) {
332 		snprintf(key, sizeof(key), "vcpu.%d.cpuset", vcpu);
333 		value = get_config_value(key);
334 		if (value == NULL)
335 			continue;
336 		vcpumap[vcpu] = malloc(sizeof(cpuset_t));
337 		if (vcpumap[vcpu] == NULL)
338 			err(4, "Failed to allocate cpuset for vcpu %d", vcpu);
339 		parse_cpuset(vcpu, value, vcpumap[vcpu]);
340 	}
341 }
342 
343 void *
344 paddr_guest2host(struct vmctx *ctx, uintptr_t gaddr, size_t len)
345 {
346 
347 	return (vm_map_gpa(ctx, gaddr, len));
348 }
349 
350 #ifdef BHYVE_SNAPSHOT
351 uintptr_t
352 paddr_host2guest(struct vmctx *ctx, void *addr)
353 {
354 	return (vm_rev_map_gpa(ctx, addr));
355 }
356 #endif
357 
358 int
359 fbsdrun_virtio_msix(void)
360 {
361 
362 	return (get_config_bool_default("virtio_msix", true));
363 }
364 
365 struct vcpu *
366 fbsdrun_vcpu(int vcpuid)
367 {
368 	return (vcpu_info[vcpuid].vcpu);
369 }
370 
371 static void *
372 fbsdrun_start_thread(void *param)
373 {
374 	char tname[MAXCOMLEN + 1];
375 	struct vcpu_info *vi = param;
376 	int error;
377 
378 	snprintf(tname, sizeof(tname), "vcpu %d", vi->vcpuid);
379 	pthread_set_name_np(pthread_self(), tname);
380 
381 	if (vcpumap[vi->vcpuid] != NULL) {
382 		error = pthread_setaffinity_np(pthread_self(),
383 		    sizeof(cpuset_t), vcpumap[vi->vcpuid]);
384 		assert(error == 0);
385 	}
386 
387 #ifdef BHYVE_SNAPSHOT
388 	checkpoint_cpu_add(vi->vcpuid);
389 #endif
390 #ifdef BHYVE_GDB
391 	gdb_cpu_add(vi->vcpu);
392 #endif
393 
394 	vm_loop(vi->ctx, vi->vcpu);
395 
396 	/* not reached */
397 	exit(1);
398 	return (NULL);
399 }
400 
401 void
402 fbsdrun_addcpu(int vcpuid)
403 {
404 	struct vcpu_info *vi;
405 	pthread_t thr;
406 	int error;
407 
408 	vi = &vcpu_info[vcpuid];
409 
410 	error = vm_activate_cpu(vi->vcpu);
411 	if (error != 0)
412 		err(EX_OSERR, "could not activate CPU %d", vi->vcpuid);
413 
414 	CPU_SET_ATOMIC(vcpuid, &cpumask);
415 
416 	error = vm_suspend_cpu(vi->vcpu);
417 	assert(error == 0);
418 
419 	error = pthread_create(&thr, NULL, fbsdrun_start_thread, vi);
420 	assert(error == 0);
421 }
422 
423 void
424 fbsdrun_deletecpu(int vcpu)
425 {
426 	static pthread_mutex_t resetcpu_mtx = PTHREAD_MUTEX_INITIALIZER;
427 	static pthread_cond_t resetcpu_cond = PTHREAD_COND_INITIALIZER;
428 
429 	pthread_mutex_lock(&resetcpu_mtx);
430 	if (!CPU_ISSET(vcpu, &cpumask)) {
431 		EPRINTLN("Attempting to delete unknown cpu %d", vcpu);
432 		exit(4);
433 	}
434 
435 	CPU_CLR(vcpu, &cpumask);
436 
437 	if (vcpu != BSP) {
438 		pthread_cond_signal(&resetcpu_cond);
439 		pthread_mutex_unlock(&resetcpu_mtx);
440 		pthread_exit(NULL);
441 		/* NOTREACHED */
442 	}
443 
444 	while (!CPU_EMPTY(&cpumask)) {
445 		pthread_cond_wait(&resetcpu_cond, &resetcpu_mtx);
446 	}
447 	pthread_mutex_unlock(&resetcpu_mtx);
448 }
449 
450 int
451 fbsdrun_suspendcpu(int vcpuid)
452 {
453 	return (vm_suspend_cpu(vcpu_info[vcpuid].vcpu));
454 }
455 
456 static void
457 vm_loop(struct vmctx *ctx, struct vcpu *vcpu)
458 {
459 	struct vm_exit vme;
460 	struct vm_run vmrun;
461 	int error, rc;
462 	enum vm_exitcode exitcode;
463 	cpuset_t active_cpus, dmask;
464 
465 	error = vm_active_cpus(ctx, &active_cpus);
466 	assert(CPU_ISSET(vcpu_id(vcpu), &active_cpus));
467 
468 	vmrun.vm_exit = &vme;
469 	vmrun.cpuset = &dmask;
470 	vmrun.cpusetsize = sizeof(dmask);
471 
472 	while (1) {
473 		error = vm_run(vcpu, &vmrun);
474 		if (error != 0)
475 			break;
476 
477 		exitcode = vme.exitcode;
478 		if (exitcode >= VM_EXITCODE_MAX ||
479 		    vmexit_handlers[exitcode] == NULL) {
480 			warnx("vm_loop: unexpected exitcode 0x%x", exitcode);
481 			exit(4);
482 		}
483 
484 		rc = (*vmexit_handlers[exitcode])(ctx, vcpu, &vmrun);
485 
486 		switch (rc) {
487 		case VMEXIT_CONTINUE:
488 			break;
489 		case VMEXIT_ABORT:
490 			abort();
491 		default:
492 			exit(4);
493 		}
494 	}
495 	EPRINTLN("vm_run error %d, errno %d", error, errno);
496 }
497 
498 static int
499 num_vcpus_allowed(struct vmctx *ctx, struct vcpu *vcpu)
500 {
501 	uint16_t sockets, cores, threads, maxcpus;
502 	int tmp, error;
503 
504 	/*
505 	 * The guest is allowed to spinup more than one processor only if the
506 	 * UNRESTRICTED_GUEST capability is available.
507 	 */
508 	error = vm_get_capability(vcpu, VM_CAP_UNRESTRICTED_GUEST, &tmp);
509 	if (error != 0)
510 		return (1);
511 
512 	error = vm_get_topology(ctx, &sockets, &cores, &threads, &maxcpus);
513 	if (error == 0)
514 		return (maxcpus);
515 	else
516 		return (1);
517 }
518 
519 static struct vmctx *
520 do_open(const char *vmname)
521 {
522 	struct vmctx *ctx;
523 	int error;
524 	bool reinit, romboot;
525 
526 	reinit = false;
527 
528 	romboot = bootrom_boot();
529 	error = vm_create(vmname);
530 	if (error) {
531 		if (errno == EEXIST) {
532 			if (romboot) {
533 				reinit = true;
534 			} else {
535 				/*
536 				 * The virtual machine has been setup by the
537 				 * userspace bootloader.
538 				 */
539 			}
540 		} else {
541 			perror("vm_create");
542 			exit(4);
543 		}
544 	} else {
545 		if (!romboot) {
546 			/*
547 			 * If the virtual machine was just created then a
548 			 * bootrom must be configured to boot it.
549 			 */
550 			fprintf(stderr, "virtual machine cannot be booted\n");
551 			exit(4);
552 		}
553 	}
554 
555 	ctx = vm_open(vmname);
556 	if (ctx == NULL) {
557 		perror("vm_open");
558 		exit(4);
559 	}
560 
561 #ifndef WITHOUT_CAPSICUM
562 	if (vm_limit_rights(ctx) != 0)
563 		err(EX_OSERR, "vm_limit_rights");
564 #endif
565 
566 	if (reinit) {
567 		error = vm_reinit(ctx);
568 		if (error) {
569 			perror("vm_reinit");
570 			exit(4);
571 		}
572 	}
573 	error = vm_set_topology(ctx, cpu_sockets, cpu_cores, cpu_threads, 0);
574 	if (error)
575 		errx(EX_OSERR, "vm_set_topology");
576 	return (ctx);
577 }
578 
579 bool
580 bhyve_parse_config_option(const char *option)
581 {
582 	const char *value;
583 	char *path;
584 
585 	value = strchr(option, '=');
586 	if (value == NULL || value[1] == '\0')
587 		return (false);
588 	path = strndup(option, value - option);
589 	if (path == NULL)
590 		err(4, "Failed to allocate memory");
591 	set_config_value(path, value + 1);
592 	free(path);
593 	return (true);
594 }
595 
596 void
597 bhyve_parse_simple_config_file(const char *path)
598 {
599 	FILE *fp;
600 	char *line, *cp;
601 	size_t linecap;
602 	unsigned int lineno;
603 
604 	fp = fopen(path, "r");
605 	if (fp == NULL)
606 		err(4, "Failed to open configuration file %s", path);
607 	line = NULL;
608 	linecap = 0;
609 	lineno = 1;
610 	for (lineno = 1; getline(&line, &linecap, fp) > 0; lineno++) {
611 		if (*line == '#' || *line == '\n')
612 			continue;
613 		cp = strchr(line, '\n');
614 		if (cp != NULL)
615 			*cp = '\0';
616 		if (!bhyve_parse_config_option(line))
617 			errx(4, "%s line %u: invalid config option '%s'", path,
618 			    lineno, line);
619 	}
620 	free(line);
621 	fclose(fp);
622 }
623 
624 #ifdef BHYVE_GDB
625 void
626 bhyve_parse_gdb_options(const char *opt)
627 {
628 	const char *sport;
629 	char *colon;
630 
631 	if (opt[0] == 'w') {
632 		set_config_bool("gdb.wait", true);
633 		opt++;
634 	}
635 
636 	colon = strrchr(opt, ':');
637 	if (colon == NULL) {
638 		sport = opt;
639 	} else {
640 		*colon = '\0';
641 		colon++;
642 		sport = colon;
643 		set_config_value("gdb.address", opt);
644 	}
645 
646 	set_config_value("gdb.port", sport);
647 }
648 #endif
649 
650 int
651 main(int argc, char *argv[])
652 {
653 	int error;
654 	int max_vcpus, memflags;
655 	struct vcpu *bsp;
656 	struct vmctx *ctx;
657 	size_t memsize;
658 	const char *value, *vmname;
659 #ifdef BHYVE_SNAPSHOT
660 	struct restore_state rstate;
661 #endif
662 
663 	bhyve_init_config();
664 	bhyve_optparse(argc, argv);
665 	argc -= optind;
666 	argv += optind;
667 
668 	if (argc > 1)
669 		bhyve_usage(1);
670 
671 #ifdef BHYVE_SNAPSHOT
672 	if (restore_file != NULL) {
673 		error = load_restore_file(restore_file, &rstate);
674 		if (error) {
675 			fprintf(stderr, "Failed to read checkpoint info from "
676 					"file: '%s'.\n", restore_file);
677 			exit(1);
678 		}
679 		vmname = lookup_vmname(&rstate);
680 		if (vmname != NULL)
681 			set_config_value("name", vmname);
682 	}
683 #endif
684 
685 	if (argc == 1)
686 		set_config_value("name", argv[0]);
687 
688 	vmname = get_config_value("name");
689 	if (vmname == NULL)
690 		bhyve_usage(1);
691 
692 	if (get_config_bool_default("config.dump", false)) {
693 		dump_config();
694 		exit(1);
695 	}
696 
697 	calc_topology();
698 	build_vcpumaps();
699 
700 	value = get_config_value("memory.size");
701 	error = vm_parse_memsize(value, &memsize);
702 	if (error)
703 		errx(EX_USAGE, "invalid memsize '%s'", value);
704 
705 	ctx = do_open(vmname);
706 
707 #ifdef BHYVE_SNAPSHOT
708 	if (restore_file != NULL) {
709 		guest_ncpus = lookup_guest_ncpus(&rstate);
710 		memflags = lookup_memflags(&rstate);
711 		memsize = lookup_memsize(&rstate);
712 	}
713 
714 	if (guest_ncpus < 1) {
715 		fprintf(stderr, "Invalid guest vCPUs (%d)\n", guest_ncpus);
716 		exit(1);
717 	}
718 #endif
719 
720 	bsp = vm_vcpu_open(ctx, BSP);
721 	max_vcpus = num_vcpus_allowed(ctx, bsp);
722 	if (guest_ncpus > max_vcpus) {
723 		fprintf(stderr, "%d vCPUs requested but only %d available\n",
724 			guest_ncpus, max_vcpus);
725 		exit(4);
726 	}
727 
728 	bhyve_init_vcpu(bsp);
729 
730 	/* Allocate per-VCPU resources. */
731 	vcpu_info = calloc(guest_ncpus, sizeof(*vcpu_info));
732 	for (int vcpuid = 0; vcpuid < guest_ncpus; vcpuid++) {
733 		vcpu_info[vcpuid].ctx = ctx;
734 		vcpu_info[vcpuid].vcpuid = vcpuid;
735 		if (vcpuid == BSP)
736 			vcpu_info[vcpuid].vcpu = bsp;
737 		else
738 			vcpu_info[vcpuid].vcpu = vm_vcpu_open(ctx, vcpuid);
739 	}
740 
741 	memflags = 0;
742 	if (get_config_bool_default("memory.wired", false))
743 		memflags |= VM_MEM_F_WIRED;
744 	if (get_config_bool_default("memory.guest_in_core", false))
745 		memflags |= VM_MEM_F_INCORE;
746 	vm_set_memflags(ctx, memflags);
747 	error = vm_setup_memory(ctx, memsize, VM_MMAP_ALL);
748 	if (error) {
749 		fprintf(stderr, "Unable to setup memory (%d)\n", errno);
750 		exit(4);
751 	}
752 
753 	init_mem(guest_ncpus);
754 	init_bootrom(ctx);
755 	if (bhyve_init_platform(ctx, bsp) != 0)
756 		exit(4);
757 
758 	if (qemu_fwcfg_init(ctx) != 0) {
759 		fprintf(stderr, "qemu fwcfg initialization error\n");
760 		exit(4);
761 	}
762 
763 	if (qemu_fwcfg_add_file("opt/bhyve/hw.ncpu", sizeof(guest_ncpus),
764 	    &guest_ncpus) != 0) {
765 		fprintf(stderr, "Could not add qemu fwcfg opt/bhyve/hw.ncpu\n");
766 		exit(4);
767 	}
768 
769 	/*
770 	 * Exit if a device emulation finds an error in its initialization
771 	 */
772 	if (init_pci(ctx) != 0) {
773 		EPRINTLN("Device emulation initialization error: %s",
774 		    strerror(errno));
775 		exit(4);
776 	}
777 	if (init_tpm(ctx) != 0) {
778 		EPRINTLN("Failed to init TPM device");
779 		exit(4);
780 	}
781 
782 	/*
783 	 * Initialize after PCI, to allow a bootrom file to reserve the high
784 	 * region.
785 	 */
786 	if (get_config_bool("acpi_tables"))
787 		vmgenc_init(ctx);
788 
789 #ifdef BHYVE_GDB
790 	init_gdb(ctx);
791 #endif
792 
793 	/*
794 	 * Add all vCPUs.
795 	 */
796 	for (int vcpuid = 0; vcpuid < guest_ncpus; vcpuid++)
797 		bhyve_start_vcpu(vcpu_info[vcpuid].vcpu, vcpuid == BSP);
798 
799 #ifdef BHYVE_SNAPSHOT
800 	if (restore_file != NULL) {
801 		FPRINTLN(stdout, "Pausing pci devs...");
802 		if (vm_pause_devices() != 0) {
803 			EPRINTLN("Failed to pause PCI device state.");
804 			exit(1);
805 		}
806 
807 		FPRINTLN(stdout, "Restoring vm mem...");
808 		if (restore_vm_mem(ctx, &rstate) != 0) {
809 			EPRINTLN("Failed to restore VM memory.");
810 			exit(1);
811 		}
812 
813 		FPRINTLN(stdout, "Restoring pci devs...");
814 		if (vm_restore_devices(&rstate) != 0) {
815 			EPRINTLN("Failed to restore PCI device state.");
816 			exit(1);
817 		}
818 
819 		FPRINTLN(stdout, "Restoring kernel structs...");
820 		if (vm_restore_kern_structs(ctx, &rstate) != 0) {
821 			EPRINTLN("Failed to restore kernel structs.");
822 			exit(1);
823 		}
824 
825 		FPRINTLN(stdout, "Resuming pci devs...");
826 		if (vm_resume_devices() != 0) {
827 			EPRINTLN("Failed to resume PCI device state.");
828 			exit(1);
829 		}
830 	}
831 #endif
832 
833 	if (bhyve_init_platform_late(ctx, bsp) != 0)
834 		exit(4);
835 
836 	/*
837 	 * Change the proc title to include the VM name.
838 	 */
839 	setproctitle("%s", vmname);
840 
841 #ifdef BHYVE_SNAPSHOT
842 	/*
843 	 * checkpointing thread for communication with bhyvectl
844 	 */
845 	if (init_checkpoint_thread(ctx) != 0)
846 		errx(EX_OSERR, "Failed to start checkpoint thread");
847 #endif
848 
849 #ifndef WITHOUT_CAPSICUM
850 	caph_cache_catpages();
851 
852 	if (caph_limit_stdout() == -1 || caph_limit_stderr() == -1)
853 		errx(EX_OSERR, "Unable to apply rights for sandbox");
854 
855 	if (caph_enter() == -1)
856 		errx(EX_OSERR, "cap_enter() failed");
857 #endif
858 
859 #ifdef BHYVE_SNAPSHOT
860 	if (restore_file != NULL) {
861 		destroy_restore_state(&rstate);
862 		if (vm_restore_time(ctx) < 0)
863 			err(EX_OSERR, "Unable to restore time");
864 
865 		for (int vcpuid = 0; vcpuid < guest_ncpus; vcpuid++)
866 			vm_resume_cpu(vcpu_info[vcpuid].vcpu);
867 	} else
868 #endif
869 		vm_resume_cpu(bsp);
870 
871 	/*
872 	 * Head off to the main event dispatch loop
873 	 */
874 	mevent_dispatch();
875 
876 	exit(4);
877 }
878