xref: /kvmtool/builtin-run.c (revision 5613ae26b9989dec93869090b426c99913ea9ab4)
1 #include "kvm/builtin-run.h"
2 
3 #include "kvm/builtin-setup.h"
4 #include "kvm/virtio-balloon.h"
5 #include "kvm/virtio-console.h"
6 #include "kvm/parse-options.h"
7 #include "kvm/8250-serial.h"
8 #include "kvm/framebuffer.h"
9 #include "kvm/disk-image.h"
10 #include "kvm/threadpool.h"
11 #include "kvm/virtio-scsi.h"
12 #include "kvm/virtio-blk.h"
13 #include "kvm/virtio-net.h"
14 #include "kvm/virtio-rng.h"
15 #include "kvm/ioeventfd.h"
16 #include "kvm/virtio-9p.h"
17 #include "kvm/barrier.h"
18 #include "kvm/kvm-cpu.h"
19 #include "kvm/ioport.h"
20 #include "kvm/symbol.h"
21 #include "kvm/i8042.h"
22 #include "kvm/mutex.h"
23 #include "kvm/term.h"
24 #include "kvm/util.h"
25 #include "kvm/strbuf.h"
26 #include "kvm/vesa.h"
27 #include "kvm/irq.h"
28 #include "kvm/kvm.h"
29 #include "kvm/pci.h"
30 #include "kvm/rtc.h"
31 #include "kvm/sdl.h"
32 #include "kvm/vnc.h"
33 #include "kvm/guest_compat.h"
34 #include "kvm/kvm-ipc.h"
35 #include "kvm/builtin-debug.h"
36 
37 #include <linux/types.h>
38 #include <linux/err.h>
39 
40 #include <sys/utsname.h>
41 #include <sys/types.h>
42 #include <sys/stat.h>
43 #include <termios.h>
44 #include <signal.h>
45 #include <stdlib.h>
46 #include <string.h>
47 #include <unistd.h>
48 #include <ctype.h>
49 #include <stdio.h>
50 
51 #define MB_SHIFT		(20)
52 #define KB_SHIFT		(10)
53 #define GB_SHIFT		(30)
54 
55 __thread struct kvm_cpu *current_kvm_cpu;
56 
57 static int  kvm_run_wrapper;
58 
59 bool do_debug_print = false;
60 
61 static const char * const run_usage[] = {
62 	"lkvm run [<options>] [<kernel image>]",
63 	NULL
64 };
65 
66 enum {
67 	KVM_RUN_DEFAULT,
68 	KVM_RUN_SANDBOX,
69 };
70 
71 static int img_name_parser(const struct option *opt, const char *arg, int unset)
72 {
73 	char path[PATH_MAX];
74 	struct stat st;
75 
76 	snprintf(path, PATH_MAX, "%s%s", kvm__get_dir(), arg);
77 
78 	if ((stat(arg, &st) == 0 && S_ISDIR(st.st_mode)) ||
79 	   (stat(path, &st) == 0 && S_ISDIR(st.st_mode)))
80 		return virtio_9p_img_name_parser(opt, arg, unset);
81 	return disk_img_name_parser(opt, arg, unset);
82 }
83 
84 void kvm_run_set_wrapper_sandbox(void)
85 {
86 	kvm_run_wrapper = KVM_RUN_SANDBOX;
87 }
88 
89 #ifndef OPT_ARCH_RUN
90 #define OPT_ARCH_RUN(...)
91 #endif
92 
93 #define BUILD_OPTIONS(name, cfg, kvm)					\
94 	struct option name[] = {					\
95 	OPT_GROUP("Basic options:"),					\
96 	OPT_STRING('\0', "name", &(cfg)->guest_name, "guest name",	\
97 			"A name for the guest"),			\
98 	OPT_INTEGER('c', "cpus", &(cfg)->nrcpus, "Number of CPUs"),	\
99 	OPT_U64('m', "mem", &(cfg)->ram_size, "Virtual machine memory"	\
100 		" size in MiB."),					\
101 	OPT_CALLBACK('d', "disk", kvm, "image or rootfs_dir", "Disk "	\
102 			" image or rootfs directory", img_name_parser,	\
103 			kvm),						\
104 	OPT_BOOLEAN('\0', "balloon", &(cfg)->balloon, "Enable virtio"	\
105 			" balloon"),					\
106 	OPT_BOOLEAN('\0', "vnc", &(cfg)->vnc, "Enable VNC framebuffer"),\
107 	OPT_BOOLEAN('\0', "gtk", &(cfg)->gtk, "Enable GTK framebuffer"),\
108 	OPT_BOOLEAN('\0', "sdl", &(cfg)->sdl, "Enable SDL framebuffer"),\
109 	OPT_BOOLEAN('\0', "rng", &(cfg)->virtio_rng, "Enable virtio"	\
110 			" Random Number Generator"),			\
111 	OPT_BOOLEAN('\0', "nodefaults", &(cfg)->nodefaults, "Disable"   \
112 			" implicit configuration that cannot be"	\
113 			" disabled otherwise"),				\
114 	OPT_CALLBACK('\0', "9p", NULL, "dir_to_share,tag_name",		\
115 		     "Enable virtio 9p to share files between host and"	\
116 		     " guest", virtio_9p_rootdir_parser, kvm),		\
117 	OPT_STRING('\0', "console", &(cfg)->console, "serial, virtio or"\
118 			" hv", "Console to use"),			\
119 	OPT_U64('\0', "vsock", &(cfg)->vsock_cid,			\
120 			"Guest virtio socket CID"),			\
121 	OPT_STRING('\0', "dev", &(cfg)->dev, "device_file",		\
122 			"KVM device file"),				\
123 	OPT_CALLBACK('\0', "tty", NULL, "tty id",			\
124 		     "Remap guest TTY into a pty on the host",		\
125 		     tty_parser, NULL),					\
126 	OPT_STRING('\0', "sandbox", &(cfg)->sandbox, "script",		\
127 			"Run this script when booting into custom"	\
128 			" rootfs"),					\
129 	OPT_STRING('\0', "hugetlbfs", &(cfg)->hugetlbfs_path, "path",	\
130 			"Hugetlbfs path"),				\
131 									\
132 	OPT_GROUP("Kernel options:"),					\
133 	OPT_STRING('k', "kernel", &(cfg)->kernel_filename, "kernel",	\
134 			"Kernel to boot in virtual machine"),		\
135 	OPT_STRING('i', "initrd", &(cfg)->initrd_filename, "initrd",	\
136 			"Initial RAM disk image"),			\
137 	OPT_STRING('p', "params", &(cfg)->kernel_cmdline, "params",	\
138 			"Kernel command line arguments"),		\
139 	OPT_STRING('f', "firmware", &(cfg)->firmware_filename, "firmware",\
140 			"Firmware image to boot in virtual machine"),	\
141 	OPT_STRING('F', "flash", &(cfg)->flash_filename, "flash",\
142 			"Flash image to present to virtual machine"),	\
143 									\
144 	OPT_GROUP("Networking options:"),				\
145 	OPT_CALLBACK_DEFAULT('n', "network", NULL, "network params",	\
146 		     "Create a new guest NIC",				\
147 		     netdev_parser, NULL, kvm),				\
148 	OPT_BOOLEAN('\0', "no-dhcp", &(cfg)->no_dhcp, "Disable kernel"	\
149 			" DHCP in rootfs mode"),			\
150 									\
151 	OPT_GROUP("VFIO options:"),					\
152 	OPT_CALLBACK('\0', "vfio-pci", NULL, "[domain:]bus:dev.fn",	\
153 		     "Assign a PCI device to the virtual machine",	\
154 		     vfio_device_parser, kvm),				\
155 									\
156 	OPT_GROUP("Debug options:"),					\
157 	OPT_BOOLEAN('\0', "debug", &do_debug_print,			\
158 			"Enable debug messages"),			\
159 	OPT_BOOLEAN('\0', "debug-single-step", &(cfg)->single_step,	\
160 			"Enable single stepping"),			\
161 	OPT_BOOLEAN('\0', "debug-ioport", &(cfg)->ioport_debug,		\
162 			"Enable ioport debugging"),			\
163 	OPT_BOOLEAN('\0', "debug-mmio", &(cfg)->mmio_debug,		\
164 			"Enable MMIO debugging"),			\
165 	OPT_INTEGER('\0', "debug-iodelay", &(cfg)->debug_iodelay,	\
166 			"Delay IO by millisecond"),			\
167 									\
168 	OPT_ARCH(RUN, cfg)						\
169 	OPT_END()							\
170 	};
171 
172 static void *kvm_cpu_thread(void *arg)
173 {
174 	char name[16];
175 
176 	current_kvm_cpu = arg;
177 
178 	sprintf(name, "kvm-vcpu-%lu", current_kvm_cpu->cpu_id);
179 	kvm__set_thread_name(name);
180 
181 	if (kvm_cpu__start(current_kvm_cpu))
182 		goto panic_kvm;
183 
184 	return (void *) (intptr_t) 0;
185 
186 panic_kvm:
187 	fprintf(stderr, "KVM exit reason: %u (\"%s\")\n",
188 		current_kvm_cpu->kvm_run->exit_reason,
189 		kvm_exit_reasons[current_kvm_cpu->kvm_run->exit_reason]);
190 	if (current_kvm_cpu->kvm_run->exit_reason == KVM_EXIT_UNKNOWN)
191 		fprintf(stderr, "KVM exit code: 0x%llu\n",
192 			(unsigned long long)current_kvm_cpu->kvm_run->hw.hardware_exit_reason);
193 
194 	kvm_cpu__set_debug_fd(STDOUT_FILENO);
195 	kvm_cpu__show_registers(current_kvm_cpu);
196 	kvm_cpu__show_code(current_kvm_cpu);
197 	kvm_cpu__show_page_tables(current_kvm_cpu);
198 
199 	return (void *) (intptr_t) 1;
200 }
201 
202 static char kernel[PATH_MAX];
203 
204 static const char *host_kernels[] = {
205 	"/boot/vmlinuz",
206 	"/boot/bzImage",
207 	NULL
208 };
209 
210 static const char *default_kernels[] = {
211 	"./bzImage",
212 	"arch/" BUILD_ARCH "/boot/bzImage",
213 	"../../arch/" BUILD_ARCH "/boot/bzImage",
214 	NULL
215 };
216 
217 static const char *default_vmlinux[] = {
218 	"vmlinux",
219 	"../../../vmlinux",
220 	"../../vmlinux",
221 	NULL
222 };
223 
224 static void kernel_usage_with_options(void)
225 {
226 	const char **k;
227 	struct utsname uts;
228 
229 	fprintf(stderr, "Fatal: could not find default kernel image in:\n");
230 	k = &default_kernels[0];
231 	while (*k) {
232 		fprintf(stderr, "\t%s\n", *k);
233 		k++;
234 	}
235 
236 	if (uname(&uts) < 0)
237 		return;
238 
239 	k = &host_kernels[0];
240 	while (*k) {
241 		if (snprintf(kernel, PATH_MAX, "%s-%s", *k, uts.release) < 0)
242 			return;
243 		fprintf(stderr, "\t%s\n", kernel);
244 		k++;
245 	}
246 	fprintf(stderr, "\nPlease see '%s run --help' for more options.\n\n",
247 		KVM_BINARY_NAME);
248 }
249 
250 static u64 host_ram_size(void)
251 {
252 	long page_size;
253 	long nr_pages;
254 
255 	nr_pages	= sysconf(_SC_PHYS_PAGES);
256 	if (nr_pages < 0) {
257 		pr_warning("sysconf(_SC_PHYS_PAGES) failed");
258 		return 0;
259 	}
260 
261 	page_size	= sysconf(_SC_PAGE_SIZE);
262 	if (page_size < 0) {
263 		pr_warning("sysconf(_SC_PAGE_SIZE) failed");
264 		return 0;
265 	}
266 
267 	return (nr_pages * page_size) >> MB_SHIFT;
268 }
269 
270 /*
271  * If user didn't specify how much memory it wants to allocate for the guest,
272  * avoid filling the whole host RAM.
273  */
274 #define RAM_SIZE_RATIO		0.8
275 
276 static u64 get_ram_size(int nr_cpus)
277 {
278 	u64 available;
279 	u64 ram_size;
280 
281 	ram_size	= 64 * (nr_cpus + 3);
282 
283 	available	= host_ram_size() * RAM_SIZE_RATIO;
284 	if (!available)
285 		available = MIN_RAM_SIZE_MB;
286 
287 	if (ram_size > available)
288 		ram_size	= available;
289 
290 	return ram_size;
291 }
292 
293 static const char *find_kernel(void)
294 {
295 	const char **k;
296 	struct stat st;
297 	struct utsname uts;
298 
299 	k = &default_kernels[0];
300 	while (*k) {
301 		if (stat(*k, &st) < 0 || !S_ISREG(st.st_mode)) {
302 			k++;
303 			continue;
304 		}
305 		strlcpy(kernel, *k, PATH_MAX);
306 		return kernel;
307 	}
308 
309 	if (uname(&uts) < 0)
310 		return NULL;
311 
312 	k = &host_kernels[0];
313 	while (*k) {
314 		if (snprintf(kernel, PATH_MAX, "%s-%s", *k, uts.release) < 0)
315 			return NULL;
316 
317 		if (stat(kernel, &st) < 0 || !S_ISREG(st.st_mode)) {
318 			k++;
319 			continue;
320 		}
321 		return kernel;
322 
323 	}
324 	return NULL;
325 }
326 
327 static const char *find_vmlinux(void)
328 {
329 	const char **vmlinux;
330 
331 	vmlinux = &default_vmlinux[0];
332 	while (*vmlinux) {
333 		struct stat st;
334 
335 		if (stat(*vmlinux, &st) < 0 || !S_ISREG(st.st_mode)) {
336 			vmlinux++;
337 			continue;
338 		}
339 		return *vmlinux;
340 	}
341 	return NULL;
342 }
343 
344 void kvm_run_help(void)
345 {
346 	struct kvm *kvm = NULL;
347 
348 	BUILD_OPTIONS(options, &kvm->cfg, kvm);
349 	usage_with_options(run_usage, options);
350 }
351 
352 static int kvm_run_set_sandbox(struct kvm *kvm)
353 {
354 	const char *guestfs_name = kvm->cfg.custom_rootfs_name;
355 	char path[PATH_MAX], script[PATH_MAX], *tmp;
356 
357 	snprintf(path, PATH_MAX, "%s%s/virt/sandbox.sh", kvm__get_dir(), guestfs_name);
358 
359 	remove(path);
360 
361 	if (kvm->cfg.sandbox == NULL)
362 		return 0;
363 
364 	tmp = realpath(kvm->cfg.sandbox, NULL);
365 	if (tmp == NULL)
366 		return -ENOMEM;
367 
368 	snprintf(script, PATH_MAX, "/host/%s", tmp);
369 	free(tmp);
370 
371 	return symlink(script, path);
372 }
373 
374 static void kvm_write_sandbox_cmd_exactly(int fd, const char *arg)
375 {
376 	const char *single_quote;
377 
378 	if (!*arg) { /* zero length string */
379 		if (write(fd, "''", 2) <= 0)
380 			die("Failed writing sandbox script");
381 		return;
382 	}
383 
384 	while (*arg) {
385 		single_quote = strchrnul(arg, '\'');
386 
387 		/* write non-single-quote string as #('string') */
388 		if (arg != single_quote) {
389 			if (write(fd, "'", 1) <= 0 ||
390 			    write(fd, arg, single_quote - arg) <= 0 ||
391 			    write(fd, "'", 1) <= 0)
392 				die("Failed writing sandbox script");
393 		}
394 
395 		/* write single quote as #("'") */
396 		if (*single_quote) {
397 			if (write(fd, "\"'\"", 3) <= 0)
398 				die("Failed writing sandbox script");
399 		} else
400 			break;
401 
402 		arg = single_quote + 1;
403 	}
404 }
405 
406 static void resolve_program(const char *src, char *dst, size_t len)
407 {
408 	struct stat st;
409 	int err;
410 
411 	err = stat(src, &st);
412 
413 	if (!err && S_ISREG(st.st_mode)) {
414 		char resolved_path[PATH_MAX];
415 
416 		if (!realpath(src, resolved_path))
417 			die("Unable to resolve program %s: %s\n", src, strerror(errno));
418 
419 		if (snprintf(dst, len, "/host%s", resolved_path) >= (int)len)
420 			die("Pathname too long: %s -> %s\n", src, resolved_path);
421 
422 	} else
423 		strlcpy(dst, src, len);
424 }
425 
426 static void kvm_run_write_sandbox_cmd(struct kvm *kvm, const char **argv, int argc)
427 {
428 	const char script_hdr[] = "#! /bin/bash\n\n";
429 	char program[PATH_MAX];
430 	int fd;
431 
432 	remove(kvm->cfg.sandbox);
433 
434 	fd = open(kvm->cfg.sandbox, O_RDWR | O_CREAT, 0777);
435 	if (fd < 0)
436 		die("Failed creating sandbox script");
437 
438 	if (write(fd, script_hdr, sizeof(script_hdr) - 1) <= 0)
439 		die("Failed writing sandbox script");
440 
441 	resolve_program(argv[0], program, PATH_MAX);
442 	kvm_write_sandbox_cmd_exactly(fd, program);
443 
444 	argv++;
445 	argc--;
446 
447 	while (argc) {
448 		if (write(fd, " ", 1) <= 0)
449 			die("Failed writing sandbox script");
450 
451 		kvm_write_sandbox_cmd_exactly(fd, argv[0]);
452 		argv++;
453 		argc--;
454 	}
455 	if (write(fd, "\n", 1) <= 0)
456 		die("Failed writing sandbox script");
457 
458 	close(fd);
459 }
460 
461 static void kvm_run_set_real_cmdline(struct kvm *kvm)
462 {
463 	static char real_cmdline[2048];
464 	bool video;
465 
466 	video = kvm->cfg.vnc || kvm->cfg.sdl || kvm->cfg.gtk;
467 
468 	memset(real_cmdline, 0, sizeof(real_cmdline));
469 	kvm__arch_set_cmdline(real_cmdline, video);
470 
471 	if (video) {
472 		strcat(real_cmdline, " console=tty0");
473 	} else {
474 		switch (kvm->cfg.active_console) {
475 		case CONSOLE_HV:
476 			/* Fallthrough */
477 		case CONSOLE_VIRTIO:
478 			strcat(real_cmdline, " console=hvc0");
479 			break;
480 		case CONSOLE_8250:
481 			strcat(real_cmdline, " console=ttyS0");
482 			break;
483 		}
484 	}
485 
486 	if (kvm->cfg.using_rootfs) {
487 		strcat(real_cmdline, " rw rootflags=trans=virtio,version=9p2000.L,cache=loose rootfstype=9p");
488 		if (kvm->cfg.custom_rootfs) {
489 #ifdef CONFIG_GUEST_PRE_INIT
490 			strcat(real_cmdline, " init=/virt/pre_init");
491 #else
492 			strcat(real_cmdline, " init=/virt/init");
493 #endif
494 			if (!kvm->cfg.no_dhcp)
495 				strcat(real_cmdline, "  ip=dhcp");
496 		}
497 	} else if (!kvm->cfg.kernel_cmdline || !strstr(kvm->cfg.kernel_cmdline, "root=")) {
498 		strlcat(real_cmdline, " root=/dev/vda rw ", sizeof(real_cmdline));
499 	}
500 
501 	if (kvm->cfg.kernel_cmdline) {
502 		strcat(real_cmdline, " ");
503 		strlcat(real_cmdline, kvm->cfg.kernel_cmdline, sizeof(real_cmdline));
504 	}
505 
506 	kvm->cfg.real_cmdline = real_cmdline;
507 }
508 
509 static void kvm_run_validate_cfg(struct kvm *kvm)
510 {
511 	if (kvm->cfg.kernel_filename && kvm->cfg.firmware_filename)
512 		die("Only one of --kernel or --firmware can be specified");
513 
514 	if ((kvm->cfg.vnc && (kvm->cfg.sdl || kvm->cfg.gtk)) ||
515 	    (kvm->cfg.sdl && kvm->cfg.gtk))
516 		die("Only one of --vnc, --sdl or --gtk can be specified");
517 
518 	if (kvm->cfg.firmware_filename && kvm->cfg.initrd_filename)
519 		pr_warning("Ignoring initrd file when loading a firmware image");
520 }
521 
522 static struct kvm *kvm_cmd_run_init(int argc, const char **argv)
523 {
524 	static char default_name[20];
525 	unsigned int nr_online_cpus;
526 	struct kvm *kvm = kvm__new();
527 
528 	if (IS_ERR(kvm))
529 		return kvm;
530 
531 	nr_online_cpus = sysconf(_SC_NPROCESSORS_ONLN);
532 	kvm->cfg.custom_rootfs_name = "default";
533 
534 	while (argc != 0) {
535 		BUILD_OPTIONS(options, &kvm->cfg, kvm);
536 		argc = parse_options(argc, argv, options, run_usage,
537 				PARSE_OPT_STOP_AT_NON_OPTION |
538 				PARSE_OPT_KEEP_DASHDASH);
539 		if (argc != 0) {
540 			/* Cusrom options, should have been handled elsewhere */
541 			if (strcmp(argv[0], "--") == 0) {
542 				if (kvm_run_wrapper == KVM_RUN_SANDBOX) {
543 					kvm->cfg.sandbox = DEFAULT_SANDBOX_FILENAME;
544 					kvm_run_write_sandbox_cmd(kvm, argv+1, argc-1);
545 					break;
546 				}
547 			}
548 
549 			if ((kvm_run_wrapper == KVM_RUN_DEFAULT && kvm->cfg.kernel_filename) ||
550 				(kvm_run_wrapper == KVM_RUN_SANDBOX && kvm->cfg.sandbox)) {
551 				fprintf(stderr, "Cannot handle parameter: "
552 						"%s\n", argv[0]);
553 				usage_with_options(run_usage, options);
554 				free(kvm);
555 				return ERR_PTR(-EINVAL);
556 			}
557 			if (kvm_run_wrapper == KVM_RUN_SANDBOX) {
558 				/*
559 				 * first unhandled parameter is treated as
560 				 * sandbox command
561 				 */
562 				kvm->cfg.sandbox = DEFAULT_SANDBOX_FILENAME;
563 				kvm_run_write_sandbox_cmd(kvm, argv, argc);
564 			} else {
565 				/*
566 				 * first unhandled parameter is treated as a kernel
567 				 * image
568 				 */
569 				kvm->cfg.kernel_filename = argv[0];
570 			}
571 			argv++;
572 			argc--;
573 		}
574 
575 	}
576 
577 	kvm_run_validate_cfg(kvm);
578 
579 	if (!kvm->cfg.kernel_filename && !kvm->cfg.firmware_filename) {
580 		kvm->cfg.kernel_filename = find_kernel();
581 
582 		if (!kvm->cfg.kernel_filename) {
583 			kernel_usage_with_options();
584 			return ERR_PTR(-EINVAL);
585 		}
586 	}
587 
588 	if (kvm->cfg.kernel_filename) {
589 		kvm->cfg.vmlinux_filename = find_vmlinux();
590 		kvm->vmlinux = kvm->cfg.vmlinux_filename;
591 	}
592 
593 	if (kvm->cfg.nrcpus == 0)
594 		kvm->cfg.nrcpus = nr_online_cpus;
595 
596 	if (!kvm->cfg.ram_size)
597 		kvm->cfg.ram_size = get_ram_size(kvm->cfg.nrcpus);
598 
599 	if (kvm->cfg.ram_size > host_ram_size())
600 		pr_warning("Guest memory size %lluMB exceeds host physical RAM size %lluMB",
601 			(unsigned long long)kvm->cfg.ram_size,
602 			(unsigned long long)host_ram_size());
603 
604 	kvm->cfg.ram_size <<= MB_SHIFT;
605 
606 	if (!kvm->cfg.dev)
607 		kvm->cfg.dev = DEFAULT_KVM_DEV;
608 
609 	if (!kvm->cfg.console)
610 		kvm->cfg.console = DEFAULT_CONSOLE;
611 
612 	if (!strncmp(kvm->cfg.console, "virtio", 6))
613 		kvm->cfg.active_console  = CONSOLE_VIRTIO;
614 	else if (!strncmp(kvm->cfg.console, "serial", 6))
615 		kvm->cfg.active_console  = CONSOLE_8250;
616 	else if (!strncmp(kvm->cfg.console, "hv", 2))
617 		kvm->cfg.active_console = CONSOLE_HV;
618 	else
619 		pr_warning("No console!");
620 
621 	if (!kvm->cfg.host_ip)
622 		kvm->cfg.host_ip = DEFAULT_HOST_ADDR;
623 
624 	if (!kvm->cfg.guest_ip)
625 		kvm->cfg.guest_ip = DEFAULT_GUEST_ADDR;
626 
627 	if (!kvm->cfg.guest_mac)
628 		kvm->cfg.guest_mac = DEFAULT_GUEST_MAC;
629 
630 	if (!kvm->cfg.host_mac)
631 		kvm->cfg.host_mac = DEFAULT_HOST_MAC;
632 
633 	if (!kvm->cfg.script)
634 		kvm->cfg.script = DEFAULT_SCRIPT;
635 
636 	if (!kvm->cfg.network)
637                 kvm->cfg.network = DEFAULT_NETWORK;
638 
639 	if (!kvm->cfg.guest_name) {
640 		if (kvm->cfg.custom_rootfs) {
641 			kvm->cfg.guest_name = kvm->cfg.custom_rootfs_name;
642 		} else {
643 			sprintf(default_name, "guest-%u", getpid());
644 			kvm->cfg.guest_name = default_name;
645 		}
646 	}
647 
648 	if (!kvm->cfg.nodefaults &&
649 	    !kvm->cfg.using_rootfs &&
650 	    !kvm->cfg.disk_image[0].filename &&
651 	    !kvm->cfg.initrd_filename) {
652 		char tmp[PATH_MAX];
653 
654 		kvm_setup_create_new(kvm->cfg.custom_rootfs_name);
655 		kvm_setup_resolv(kvm->cfg.custom_rootfs_name);
656 
657 		snprintf(tmp, PATH_MAX, "%s%s", kvm__get_dir(), "default");
658 		if (virtio_9p__register(kvm, tmp, "/dev/root") < 0)
659 			die("Unable to initialize virtio 9p");
660 		if (virtio_9p__register(kvm, "/", "hostfs") < 0)
661 			die("Unable to initialize virtio 9p");
662 		kvm->cfg.using_rootfs = kvm->cfg.custom_rootfs = 1;
663 	}
664 
665 	if (kvm->cfg.custom_rootfs) {
666 		kvm_run_set_sandbox(kvm);
667 		if (kvm_setup_guest_init(kvm->cfg.custom_rootfs_name))
668 			die("Failed to setup init for guest.");
669 	}
670 
671 	if (kvm->cfg.nodefaults)
672 		kvm->cfg.real_cmdline = kvm->cfg.kernel_cmdline;
673 	else
674 		kvm_run_set_real_cmdline(kvm);
675 
676 	if (kvm->cfg.kernel_filename) {
677 		printf("  # %s run -k %s -m %Lu -c %d --name %s\n", KVM_BINARY_NAME,
678 		       kvm->cfg.kernel_filename,
679 		       (unsigned long long)kvm->cfg.ram_size / 1024 / 1024,
680 		       kvm->cfg.nrcpus, kvm->cfg.guest_name);
681 	} else if (kvm->cfg.firmware_filename) {
682 		printf("  # %s run --firmware %s -m %Lu -c %d --name %s\n", KVM_BINARY_NAME,
683 		       kvm->cfg.firmware_filename,
684 		       (unsigned long long)kvm->cfg.ram_size / 1024 / 1024,
685 		       kvm->cfg.nrcpus, kvm->cfg.guest_name);
686 	}
687 
688 	if (init_list__init(kvm) < 0)
689 		die ("Initialisation failed");
690 
691 	return kvm;
692 }
693 
694 static int kvm_cmd_run_work(struct kvm *kvm)
695 {
696 	int i;
697 
698 	for (i = 0; i < kvm->nrcpus; i++) {
699 		if (pthread_create(&kvm->cpus[i]->thread, NULL, kvm_cpu_thread, kvm->cpus[i]) != 0)
700 			die("unable to create KVM VCPU thread");
701 	}
702 
703 	/* Only VCPU #0 is going to exit by itself when shutting down */
704 	if (pthread_join(kvm->cpus[0]->thread, NULL) != 0)
705 		die("unable to join with vcpu 0");
706 
707 	return kvm_cpu__exit(kvm);
708 }
709 
710 static void kvm_cmd_run_exit(struct kvm *kvm, int guest_ret)
711 {
712 	compat__print_all_messages();
713 
714 	init_list__exit(kvm);
715 
716 	if (guest_ret == 0)
717 		printf("\n  # KVM session ended normally.\n");
718 }
719 
720 int kvm_cmd_run(int argc, const char **argv, const char *prefix)
721 {
722 	int ret = -EFAULT;
723 	struct kvm *kvm;
724 
725 	kvm = kvm_cmd_run_init(argc, argv);
726 	if (IS_ERR(kvm))
727 		return PTR_ERR(kvm);
728 
729 	ret = kvm_cmd_run_work(kvm);
730 	kvm_cmd_run_exit(kvm, ret);
731 
732 	return ret;
733 }
734