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