xref: /freebsd/usr.sbin/bhyve/bhyverun.c (revision b1879975794772ee51f0b4865753364c7d7626c3)
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 romboot;
525 
526 	romboot = bootrom_boot();
527 
528 	/*
529 	 * If we don't have a boot ROM, the guest context must have been
530 	 * initialized by bhyveload(8) or equivalent.
531 	 */
532 	ctx = vm_openf(vmname, romboot ? VMMAPI_OPEN_REINIT : 0);
533 	if (ctx == NULL) {
534 		if (errno != ENOENT)
535 			err(4, "vm_openf");
536 		if (!romboot)
537 			errx(4, "no bootrom was configured");
538 		ctx = vm_openf(vmname, VMMAPI_OPEN_CREATE);
539 		if (ctx == NULL)
540 			err(4, "vm_openf");
541 	}
542 
543 #ifndef WITHOUT_CAPSICUM
544 	if (vm_limit_rights(ctx) != 0)
545 		err(EX_OSERR, "vm_limit_rights");
546 #endif
547 
548 	error = vm_set_topology(ctx, cpu_sockets, cpu_cores, cpu_threads, 0);
549 	if (error)
550 		errx(EX_OSERR, "vm_set_topology");
551 	return (ctx);
552 }
553 
554 bool
555 bhyve_parse_config_option(const char *option)
556 {
557 	const char *value;
558 	char *path;
559 
560 	value = strchr(option, '=');
561 	if (value == NULL || value[1] == '\0')
562 		return (false);
563 	path = strndup(option, value - option);
564 	if (path == NULL)
565 		err(4, "Failed to allocate memory");
566 	set_config_value(path, value + 1);
567 	free(path);
568 	return (true);
569 }
570 
571 void
572 bhyve_parse_simple_config_file(const char *path)
573 {
574 	FILE *fp;
575 	char *line, *cp;
576 	size_t linecap;
577 	unsigned int lineno;
578 
579 	fp = fopen(path, "r");
580 	if (fp == NULL)
581 		err(4, "Failed to open configuration file %s", path);
582 	line = NULL;
583 	linecap = 0;
584 	lineno = 1;
585 	for (lineno = 1; getline(&line, &linecap, fp) > 0; lineno++) {
586 		if (*line == '#' || *line == '\n')
587 			continue;
588 		cp = strchr(line, '\n');
589 		if (cp != NULL)
590 			*cp = '\0';
591 		if (!bhyve_parse_config_option(line))
592 			errx(4, "%s line %u: invalid config option '%s'", path,
593 			    lineno, line);
594 	}
595 	free(line);
596 	fclose(fp);
597 }
598 
599 #ifdef BHYVE_GDB
600 void
601 bhyve_parse_gdb_options(const char *opt)
602 {
603 	const char *sport;
604 	char *colon;
605 
606 	if (opt[0] == 'w') {
607 		set_config_bool("gdb.wait", true);
608 		opt++;
609 	}
610 
611 	colon = strrchr(opt, ':');
612 	if (colon == NULL) {
613 		sport = opt;
614 	} else {
615 		*colon = '\0';
616 		colon++;
617 		sport = colon;
618 		set_config_value("gdb.address", opt);
619 	}
620 
621 	set_config_value("gdb.port", sport);
622 }
623 #endif
624 
625 int
626 main(int argc, char *argv[])
627 {
628 	int error;
629 	int max_vcpus, memflags;
630 	struct vcpu *bsp;
631 	struct vmctx *ctx;
632 	size_t memsize;
633 	const char *value, *vmname;
634 #ifdef BHYVE_SNAPSHOT
635 	struct restore_state rstate;
636 #endif
637 
638 	bhyve_init_config();
639 	bhyve_optparse(argc, argv);
640 	argc -= optind;
641 	argv += optind;
642 
643 	if (argc > 1)
644 		bhyve_usage(1);
645 
646 #ifdef BHYVE_SNAPSHOT
647 	if (restore_file != NULL) {
648 		error = load_restore_file(restore_file, &rstate);
649 		if (error) {
650 			fprintf(stderr, "Failed to read checkpoint info from "
651 					"file: '%s'.\n", restore_file);
652 			exit(1);
653 		}
654 		vmname = lookup_vmname(&rstate);
655 		if (vmname != NULL)
656 			set_config_value("name", vmname);
657 	}
658 #endif
659 
660 	if (argc == 1)
661 		set_config_value("name", argv[0]);
662 
663 	vmname = get_config_value("name");
664 	if (vmname == NULL)
665 		bhyve_usage(1);
666 
667 	if (get_config_bool_default("config.dump", false)) {
668 		dump_config();
669 		exit(1);
670 	}
671 
672 	calc_topology();
673 	build_vcpumaps();
674 
675 	value = get_config_value("memory.size");
676 	error = vm_parse_memsize(value, &memsize);
677 	if (error)
678 		errx(EX_USAGE, "invalid memsize '%s'", value);
679 
680 	ctx = do_open(vmname);
681 
682 #ifdef BHYVE_SNAPSHOT
683 	if (restore_file != NULL) {
684 		guest_ncpus = lookup_guest_ncpus(&rstate);
685 		memflags = lookup_memflags(&rstate);
686 		memsize = lookup_memsize(&rstate);
687 	}
688 
689 	if (guest_ncpus < 1) {
690 		fprintf(stderr, "Invalid guest vCPUs (%d)\n", guest_ncpus);
691 		exit(1);
692 	}
693 #endif
694 
695 	bsp = vm_vcpu_open(ctx, BSP);
696 	max_vcpus = num_vcpus_allowed(ctx, bsp);
697 	if (guest_ncpus > max_vcpus) {
698 		fprintf(stderr, "%d vCPUs requested but only %d available\n",
699 			guest_ncpus, max_vcpus);
700 		exit(4);
701 	}
702 
703 	bhyve_init_vcpu(bsp);
704 
705 	/* Allocate per-VCPU resources. */
706 	vcpu_info = calloc(guest_ncpus, sizeof(*vcpu_info));
707 	for (int vcpuid = 0; vcpuid < guest_ncpus; vcpuid++) {
708 		vcpu_info[vcpuid].ctx = ctx;
709 		vcpu_info[vcpuid].vcpuid = vcpuid;
710 		if (vcpuid == BSP)
711 			vcpu_info[vcpuid].vcpu = bsp;
712 		else
713 			vcpu_info[vcpuid].vcpu = vm_vcpu_open(ctx, vcpuid);
714 	}
715 
716 	memflags = 0;
717 	if (get_config_bool_default("memory.wired", false))
718 		memflags |= VM_MEM_F_WIRED;
719 	if (get_config_bool_default("memory.guest_in_core", false))
720 		memflags |= VM_MEM_F_INCORE;
721 	vm_set_memflags(ctx, memflags);
722 	error = vm_setup_memory(ctx, memsize, VM_MMAP_ALL);
723 	if (error) {
724 		fprintf(stderr, "Unable to setup memory (%d)\n", errno);
725 		exit(4);
726 	}
727 
728 	init_mem(guest_ncpus);
729 	init_bootrom(ctx);
730 	if (bhyve_init_platform(ctx, bsp) != 0)
731 		exit(4);
732 
733 	if (qemu_fwcfg_init(ctx) != 0) {
734 		fprintf(stderr, "qemu fwcfg initialization error\n");
735 		exit(4);
736 	}
737 
738 	if (qemu_fwcfg_add_file("opt/bhyve/hw.ncpu", sizeof(guest_ncpus),
739 	    &guest_ncpus) != 0) {
740 		fprintf(stderr, "Could not add qemu fwcfg opt/bhyve/hw.ncpu\n");
741 		exit(4);
742 	}
743 
744 	/*
745 	 * Exit if a device emulation finds an error in its initialization
746 	 */
747 	if (init_pci(ctx) != 0) {
748 		EPRINTLN("Device emulation initialization error: %s",
749 		    strerror(errno));
750 		exit(4);
751 	}
752 	if (init_tpm(ctx) != 0) {
753 		EPRINTLN("Failed to init TPM device");
754 		exit(4);
755 	}
756 
757 	/*
758 	 * Initialize after PCI, to allow a bootrom file to reserve the high
759 	 * region.
760 	 */
761 	if (get_config_bool("acpi_tables"))
762 		vmgenc_init(ctx);
763 
764 #ifdef BHYVE_GDB
765 	init_gdb(ctx);
766 #endif
767 
768 	/*
769 	 * Add all vCPUs.
770 	 */
771 	for (int vcpuid = 0; vcpuid < guest_ncpus; vcpuid++)
772 		bhyve_start_vcpu(vcpu_info[vcpuid].vcpu, vcpuid == BSP);
773 
774 #ifdef BHYVE_SNAPSHOT
775 	if (restore_file != NULL) {
776 		FPRINTLN(stdout, "Pausing pci devs...");
777 		if (vm_pause_devices() != 0) {
778 			EPRINTLN("Failed to pause PCI device state.");
779 			exit(1);
780 		}
781 
782 		FPRINTLN(stdout, "Restoring vm mem...");
783 		if (restore_vm_mem(ctx, &rstate) != 0) {
784 			EPRINTLN("Failed to restore VM memory.");
785 			exit(1);
786 		}
787 
788 		FPRINTLN(stdout, "Restoring pci devs...");
789 		if (vm_restore_devices(&rstate) != 0) {
790 			EPRINTLN("Failed to restore PCI device state.");
791 			exit(1);
792 		}
793 
794 		FPRINTLN(stdout, "Restoring kernel structs...");
795 		if (vm_restore_kern_structs(ctx, &rstate) != 0) {
796 			EPRINTLN("Failed to restore kernel structs.");
797 			exit(1);
798 		}
799 
800 		FPRINTLN(stdout, "Resuming pci devs...");
801 		if (vm_resume_devices() != 0) {
802 			EPRINTLN("Failed to resume PCI device state.");
803 			exit(1);
804 		}
805 	}
806 #endif
807 
808 	if (bhyve_init_platform_late(ctx, bsp) != 0)
809 		exit(4);
810 
811 	/*
812 	 * Change the proc title to include the VM name.
813 	 */
814 	setproctitle("%s", vmname);
815 
816 #ifdef BHYVE_SNAPSHOT
817 	/*
818 	 * checkpointing thread for communication with bhyvectl
819 	 */
820 	if (init_checkpoint_thread(ctx) != 0)
821 		errx(EX_OSERR, "Failed to start checkpoint thread");
822 #endif
823 
824 #ifndef WITHOUT_CAPSICUM
825 	caph_cache_catpages();
826 
827 	if (caph_limit_stdout() == -1 || caph_limit_stderr() == -1)
828 		errx(EX_OSERR, "Unable to apply rights for sandbox");
829 
830 	if (caph_enter() == -1)
831 		errx(EX_OSERR, "cap_enter() failed");
832 #endif
833 
834 #ifdef BHYVE_SNAPSHOT
835 	if (restore_file != NULL) {
836 		destroy_restore_state(&rstate);
837 		if (vm_restore_time(ctx) < 0)
838 			err(EX_OSERR, "Unable to restore time");
839 
840 		for (int vcpuid = 0; vcpuid < guest_ncpus; vcpuid++)
841 			vm_resume_cpu(vcpu_info[vcpuid].vcpu);
842 	} else
843 #endif
844 		vm_resume_cpu(bsp);
845 
846 	/*
847 	 * Head off to the main event dispatch loop
848 	 */
849 	mevent_dispatch();
850 
851 	exit(4);
852 }
853