xref: /freebsd/usr.sbin/bhyve/bhyverun.c (revision 427db2c45eb3a6e362e0ce2804dd9abd2e6909a4)
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 	vm_suspend_cpu(vi->vcpu);
417 
418 	error = pthread_create(&thr, NULL, fbsdrun_start_thread, vi);
419 	assert(error == 0);
420 }
421 
422 void
423 fbsdrun_deletecpu(int vcpu)
424 {
425 	static pthread_mutex_t resetcpu_mtx = PTHREAD_MUTEX_INITIALIZER;
426 	static pthread_cond_t resetcpu_cond = PTHREAD_COND_INITIALIZER;
427 
428 	pthread_mutex_lock(&resetcpu_mtx);
429 	if (!CPU_ISSET(vcpu, &cpumask)) {
430 		EPRINTLN("Attempting to delete unknown cpu %d", vcpu);
431 		exit(4);
432 	}
433 
434 	CPU_CLR(vcpu, &cpumask);
435 
436 	if (vcpu != BSP) {
437 		pthread_cond_signal(&resetcpu_cond);
438 		pthread_mutex_unlock(&resetcpu_mtx);
439 		pthread_exit(NULL);
440 		/* NOTREACHED */
441 	}
442 
443 	while (!CPU_EMPTY(&cpumask)) {
444 		pthread_cond_wait(&resetcpu_cond, &resetcpu_mtx);
445 	}
446 	pthread_mutex_unlock(&resetcpu_mtx);
447 }
448 
449 int
450 fbsdrun_suspendcpu(int vcpuid)
451 {
452 	return (vm_suspend_cpu(vcpu_info[vcpuid].vcpu));
453 }
454 
455 static void
456 vm_loop(struct vmctx *ctx, struct vcpu *vcpu)
457 {
458 	struct vm_exit vme;
459 	struct vm_run vmrun;
460 	int error, rc;
461 	enum vm_exitcode exitcode;
462 	cpuset_t active_cpus, dmask;
463 
464 	error = vm_active_cpus(ctx, &active_cpus);
465 	assert(CPU_ISSET(vcpu_id(vcpu), &active_cpus));
466 
467 	vmrun.vm_exit = &vme;
468 	vmrun.cpuset = &dmask;
469 	vmrun.cpusetsize = sizeof(dmask);
470 
471 	while (1) {
472 		error = vm_run(vcpu, &vmrun);
473 		if (error != 0)
474 			break;
475 
476 		exitcode = vme.exitcode;
477 		if (exitcode >= VM_EXITCODE_MAX ||
478 		    vmexit_handlers[exitcode] == NULL) {
479 			warnx("vm_loop: unexpected exitcode 0x%x", exitcode);
480 			exit(4);
481 		}
482 
483 		rc = (*vmexit_handlers[exitcode])(ctx, vcpu, &vmrun);
484 
485 		switch (rc) {
486 		case VMEXIT_CONTINUE:
487 			break;
488 		case VMEXIT_ABORT:
489 			abort();
490 		default:
491 			exit(4);
492 		}
493 	}
494 	EPRINTLN("vm_run error %d, errno %d", error, errno);
495 }
496 
497 static int
498 num_vcpus_allowed(struct vmctx *ctx, struct vcpu *vcpu)
499 {
500 	uint16_t sockets, cores, threads, maxcpus;
501 	int tmp, error;
502 
503 	/*
504 	 * The guest is allowed to spinup more than one processor only if the
505 	 * UNRESTRICTED_GUEST capability is available.
506 	 */
507 	error = vm_get_capability(vcpu, VM_CAP_UNRESTRICTED_GUEST, &tmp);
508 	if (error != 0)
509 		return (1);
510 
511 	error = vm_get_topology(ctx, &sockets, &cores, &threads, &maxcpus);
512 	if (error == 0)
513 		return (maxcpus);
514 	else
515 		return (1);
516 }
517 
518 static struct vmctx *
519 do_open(const char *vmname)
520 {
521 	struct vmctx *ctx;
522 	int error;
523 	bool reinit, romboot;
524 
525 	reinit = false;
526 
527 #ifdef __amd64__
528 	romboot = lpc_bootrom() != NULL;
529 #else
530 	romboot = true;
531 #endif
532 
533 	error = vm_create(vmname);
534 	if (error) {
535 		if (errno == EEXIST) {
536 			if (romboot) {
537 				reinit = true;
538 			} else {
539 				/*
540 				 * The virtual machine has been setup by the
541 				 * userspace bootloader.
542 				 */
543 			}
544 		} else {
545 			perror("vm_create");
546 			exit(4);
547 		}
548 	} else {
549 		if (!romboot) {
550 			/*
551 			 * If the virtual machine was just created then a
552 			 * bootrom must be configured to boot it.
553 			 */
554 			fprintf(stderr, "virtual machine cannot be booted\n");
555 			exit(4);
556 		}
557 	}
558 
559 	ctx = vm_open(vmname);
560 	if (ctx == NULL) {
561 		perror("vm_open");
562 		exit(4);
563 	}
564 
565 #ifndef WITHOUT_CAPSICUM
566 	if (vm_limit_rights(ctx) != 0)
567 		err(EX_OSERR, "vm_limit_rights");
568 #endif
569 
570 	if (reinit) {
571 		error = vm_reinit(ctx);
572 		if (error) {
573 			perror("vm_reinit");
574 			exit(4);
575 		}
576 	}
577 	error = vm_set_topology(ctx, cpu_sockets, cpu_cores, cpu_threads, 0);
578 	if (error)
579 		errx(EX_OSERR, "vm_set_topology");
580 	return (ctx);
581 }
582 
583 bool
584 bhyve_parse_config_option(const char *option)
585 {
586 	const char *value;
587 	char *path;
588 
589 	value = strchr(option, '=');
590 	if (value == NULL || value[1] == '\0')
591 		return (false);
592 	path = strndup(option, value - option);
593 	if (path == NULL)
594 		err(4, "Failed to allocate memory");
595 	set_config_value(path, value + 1);
596 	free(path);
597 	return (true);
598 }
599 
600 void
601 bhyve_parse_simple_config_file(const char *path)
602 {
603 	FILE *fp;
604 	char *line, *cp;
605 	size_t linecap;
606 	unsigned int lineno;
607 
608 	fp = fopen(path, "r");
609 	if (fp == NULL)
610 		err(4, "Failed to open configuration file %s", path);
611 	line = NULL;
612 	linecap = 0;
613 	lineno = 1;
614 	for (lineno = 1; getline(&line, &linecap, fp) > 0; lineno++) {
615 		if (*line == '#' || *line == '\n')
616 			continue;
617 		cp = strchr(line, '\n');
618 		if (cp != NULL)
619 			*cp = '\0';
620 		if (!bhyve_parse_config_option(line))
621 			errx(4, "%s line %u: invalid config option '%s'", path,
622 			    lineno, line);
623 	}
624 	free(line);
625 	fclose(fp);
626 }
627 
628 #ifdef BHYVE_GDB
629 void
630 bhyve_parse_gdb_options(const char *opt)
631 {
632 	const char *sport;
633 	char *colon;
634 
635 	if (opt[0] == 'w') {
636 		set_config_bool("gdb.wait", true);
637 		opt++;
638 	}
639 
640 	colon = strrchr(opt, ':');
641 	if (colon == NULL) {
642 		sport = opt;
643 	} else {
644 		*colon = '\0';
645 		colon++;
646 		sport = colon;
647 		set_config_value("gdb.address", opt);
648 	}
649 
650 	set_config_value("gdb.port", sport);
651 }
652 #endif
653 
654 int
655 main(int argc, char *argv[])
656 {
657 	int error;
658 	int max_vcpus, memflags;
659 	struct vcpu *bsp;
660 	struct vmctx *ctx;
661 	size_t memsize;
662 	const char *value, *vmname;
663 #ifdef BHYVE_SNAPSHOT
664 	struct restore_state rstate;
665 #endif
666 
667 	bhyve_init_config();
668 	bhyve_optparse(argc, argv);
669 	argc -= optind;
670 	argv += optind;
671 
672 	if (argc > 1)
673 		bhyve_usage(1);
674 
675 #ifdef BHYVE_SNAPSHOT
676 	if (restore_file != NULL) {
677 		error = load_restore_file(restore_file, &rstate);
678 		if (error) {
679 			fprintf(stderr, "Failed to read checkpoint info from "
680 					"file: '%s'.\n", restore_file);
681 			exit(1);
682 		}
683 		vmname = lookup_vmname(&rstate);
684 		if (vmname != NULL)
685 			set_config_value("name", vmname);
686 	}
687 #endif
688 
689 	if (argc == 1)
690 		set_config_value("name", argv[0]);
691 
692 	vmname = get_config_value("name");
693 	if (vmname == NULL)
694 		bhyve_usage(1);
695 
696 	if (get_config_bool_default("config.dump", false)) {
697 		dump_config();
698 		exit(1);
699 	}
700 
701 	calc_topology();
702 	build_vcpumaps();
703 
704 	value = get_config_value("memory.size");
705 	error = vm_parse_memsize(value, &memsize);
706 	if (error)
707 		errx(EX_USAGE, "invalid memsize '%s'", value);
708 
709 	ctx = do_open(vmname);
710 
711 #ifdef BHYVE_SNAPSHOT
712 	if (restore_file != NULL) {
713 		guest_ncpus = lookup_guest_ncpus(&rstate);
714 		memflags = lookup_memflags(&rstate);
715 		memsize = lookup_memsize(&rstate);
716 	}
717 
718 	if (guest_ncpus < 1) {
719 		fprintf(stderr, "Invalid guest vCPUs (%d)\n", guest_ncpus);
720 		exit(1);
721 	}
722 #endif
723 
724 	bsp = vm_vcpu_open(ctx, BSP);
725 	max_vcpus = num_vcpus_allowed(ctx, bsp);
726 	if (guest_ncpus > max_vcpus) {
727 		fprintf(stderr, "%d vCPUs requested but only %d available\n",
728 			guest_ncpus, max_vcpus);
729 		exit(4);
730 	}
731 
732 	bhyve_init_vcpu(bsp);
733 
734 	/* Allocate per-VCPU resources. */
735 	vcpu_info = calloc(guest_ncpus, sizeof(*vcpu_info));
736 	for (int vcpuid = 0; vcpuid < guest_ncpus; vcpuid++) {
737 		vcpu_info[vcpuid].ctx = ctx;
738 		vcpu_info[vcpuid].vcpuid = vcpuid;
739 		if (vcpuid == BSP)
740 			vcpu_info[vcpuid].vcpu = bsp;
741 		else
742 			vcpu_info[vcpuid].vcpu = vm_vcpu_open(ctx, vcpuid);
743 	}
744 
745 	memflags = 0;
746 	if (get_config_bool_default("memory.wired", false))
747 		memflags |= VM_MEM_F_WIRED;
748 	if (get_config_bool_default("memory.guest_in_core", false))
749 		memflags |= VM_MEM_F_INCORE;
750 	vm_set_memflags(ctx, memflags);
751 	error = vm_setup_memory(ctx, memsize, VM_MMAP_ALL);
752 	if (error) {
753 		fprintf(stderr, "Unable to setup memory (%d)\n", errno);
754 		exit(4);
755 	}
756 
757 	init_mem(guest_ncpus);
758 	init_bootrom(ctx);
759 	if (bhyve_init_platform(ctx, bsp) != 0)
760 		exit(4);
761 
762 	if (qemu_fwcfg_init(ctx) != 0) {
763 		fprintf(stderr, "qemu fwcfg initialization error\n");
764 		exit(4);
765 	}
766 
767 	if (qemu_fwcfg_add_file("opt/bhyve/hw.ncpu", sizeof(guest_ncpus),
768 	    &guest_ncpus) != 0) {
769 		fprintf(stderr, "Could not add qemu fwcfg opt/bhyve/hw.ncpu\n");
770 		exit(4);
771 	}
772 
773 	/*
774 	 * Exit if a device emulation finds an error in its initialization
775 	 */
776 	if (init_pci(ctx) != 0) {
777 		EPRINTLN("Device emulation initialization error: %s",
778 		    strerror(errno));
779 		exit(4);
780 	}
781 	if (init_tpm(ctx) != 0) {
782 		EPRINTLN("Failed to init TPM device");
783 		exit(4);
784 	}
785 
786 	/*
787 	 * Initialize after PCI, to allow a bootrom file to reserve the high
788 	 * region.
789 	 */
790 	if (get_config_bool("acpi_tables"))
791 		vmgenc_init(ctx);
792 
793 #ifdef BHYVE_GDB
794 	init_gdb(ctx);
795 #endif
796 
797 	/*
798 	 * Add all vCPUs.
799 	 */
800 	for (int vcpuid = 0; vcpuid < guest_ncpus; vcpuid++)
801 		bhyve_start_vcpu(vcpu_info[vcpuid].vcpu, vcpuid == BSP);
802 
803 #ifdef BHYVE_SNAPSHOT
804 	if (restore_file != NULL) {
805 		FPRINTLN(stdout, "Pausing pci devs...");
806 		if (vm_pause_devices() != 0) {
807 			EPRINTLN("Failed to pause PCI device state.");
808 			exit(1);
809 		}
810 
811 		FPRINTLN(stdout, "Restoring vm mem...");
812 		if (restore_vm_mem(ctx, &rstate) != 0) {
813 			EPRINTLN("Failed to restore VM memory.");
814 			exit(1);
815 		}
816 
817 		FPRINTLN(stdout, "Restoring pci devs...");
818 		if (vm_restore_devices(&rstate) != 0) {
819 			EPRINTLN("Failed to restore PCI device state.");
820 			exit(1);
821 		}
822 
823 		FPRINTLN(stdout, "Restoring kernel structs...");
824 		if (vm_restore_kern_structs(ctx, &rstate) != 0) {
825 			EPRINTLN("Failed to restore kernel structs.");
826 			exit(1);
827 		}
828 
829 		FPRINTLN(stdout, "Resuming pci devs...");
830 		if (vm_resume_devices() != 0) {
831 			EPRINTLN("Failed to resume PCI device state.");
832 			exit(1);
833 		}
834 	}
835 #endif
836 
837 	if (bhyve_init_platform_late(ctx, bsp) != 0)
838 		exit(4);
839 
840 	/*
841 	 * Change the proc title to include the VM name.
842 	 */
843 	setproctitle("%s", vmname);
844 
845 #ifdef BHYVE_SNAPSHOT
846 	/*
847 	 * checkpointing thread for communication with bhyvectl
848 	 */
849 	if (init_checkpoint_thread(ctx) != 0)
850 		errx(EX_OSERR, "Failed to start checkpoint thread");
851 #endif
852 
853 #ifndef WITHOUT_CAPSICUM
854 	caph_cache_catpages();
855 
856 	if (caph_limit_stdout() == -1 || caph_limit_stderr() == -1)
857 		errx(EX_OSERR, "Unable to apply rights for sandbox");
858 
859 	if (caph_enter() == -1)
860 		errx(EX_OSERR, "cap_enter() failed");
861 #endif
862 
863 #ifdef BHYVE_SNAPSHOT
864 	if (restore_file != NULL) {
865 		destroy_restore_state(&rstate);
866 		if (vm_restore_time(ctx) < 0)
867 			err(EX_OSERR, "Unable to restore time");
868 
869 		for (int vcpuid = 0; vcpuid < guest_ncpus; vcpuid++)
870 			vm_resume_cpu(vcpu_info[vcpuid].vcpu);
871 	} else
872 #endif
873 		vm_resume_cpu(bsp);
874 
875 	/*
876 	 * Head off to the main event dispatch loop
877 	 */
878 	mevent_dispatch();
879 
880 	exit(4);
881 }
882