xref: /kvmtool/builtin-run.c (revision 82d65b5e8212a018c8d8f3cce5e895846b863f02)
1 #include "kvm/builtin-run.h"
2 
3 #include "kvm/virtio-balloon.h"
4 #include "kvm/virtio-console.h"
5 #include "kvm/parse-options.h"
6 #include "kvm/8250-serial.h"
7 #include "kvm/framebuffer.h"
8 #include "kvm/disk-image.h"
9 #include "kvm/threadpool.h"
10 #include "kvm/virtio-blk.h"
11 #include "kvm/virtio-net.h"
12 #include "kvm/virtio-rng.h"
13 #include "kvm/ioeventfd.h"
14 #include "kvm/virtio-9p.h"
15 #include "kvm/barrier.h"
16 #include "kvm/kvm-cpu.h"
17 #include "kvm/ioport.h"
18 #include "kvm/symbol.h"
19 #include "kvm/i8042.h"
20 #include "kvm/mutex.h"
21 #include "kvm/term.h"
22 #include "kvm/util.h"
23 #include "kvm/vesa.h"
24 #include "kvm/irq.h"
25 #include "kvm/kvm.h"
26 #include "kvm/pci.h"
27 #include "kvm/rtc.h"
28 #include "kvm/sdl.h"
29 #include "kvm/vnc.h"
30 #include "kvm/guest_compat.h"
31 #include "kvm/pci-shmem.h"
32 
33 #include <linux/types.h>
34 
35 #include <sys/utsname.h>
36 #include <sys/types.h>
37 #include <sys/stat.h>
38 #include <termios.h>
39 #include <signal.h>
40 #include <stdlib.h>
41 #include <string.h>
42 #include <unistd.h>
43 #include <ctype.h>
44 #include <stdio.h>
45 
46 #define DEFAULT_KVM_DEV		"/dev/kvm"
47 #define DEFAULT_CONSOLE		"serial"
48 #define DEFAULT_NETWORK		"user"
49 #define DEFAULT_HOST_ADDR	"192.168.33.1"
50 #define DEFAULT_GUEST_ADDR	"192.168.33.15"
51 #define DEFAULT_GUEST_MAC	"02:15:15:15:15:15"
52 #define DEFAULT_HOST_MAC	"02:01:01:01:01:01"
53 #define DEFAULT_SCRIPT		"none"
54 
55 #define MB_SHIFT		(20)
56 #define KB_SHIFT		(10)
57 #define GB_SHIFT		(30)
58 #define MIN_RAM_SIZE_MB		(64ULL)
59 #define MIN_RAM_SIZE_BYTE	(MIN_RAM_SIZE_MB << MB_SHIFT)
60 
61 struct kvm *kvm;
62 struct kvm_cpu *kvm_cpus[KVM_NR_CPUS];
63 __thread struct kvm_cpu *current_kvm_cpu;
64 
65 static u64 ram_size;
66 static u8  image_count;
67 static bool virtio_rng;
68 static const char *kernel_cmdline;
69 static const char *kernel_filename;
70 static const char *vmlinux_filename;
71 static const char *initrd_filename;
72 static const char *image_filename[MAX_DISK_IMAGES];
73 static const char *console;
74 static const char *dev;
75 static const char *network;
76 static const char *host_ip;
77 static const char *guest_ip;
78 static const char *guest_mac;
79 static const char *host_mac;
80 static const char *script;
81 static const char *guest_name;
82 static bool single_step;
83 static bool readonly_image[MAX_DISK_IMAGES];
84 static bool vnc;
85 static bool sdl;
86 static bool balloon;
87 static bool using_rootfs;
88 static bool custom_rootfs;
89 extern bool ioport_debug;
90 extern int  active_console;
91 extern int  debug_iodelay;
92 
93 bool do_debug_print = false;
94 
95 static int nrcpus;
96 static int vidmode = -1;
97 
98 static const char * const run_usage[] = {
99 	"kvm run [<options>] [<kernel image>]",
100 	NULL
101 };
102 
103 static int img_name_parser(const struct option *opt, const char *arg, int unset)
104 {
105 	char *sep;
106 	struct stat st;
107 	char path[PATH_MAX];
108 
109 	if (stat(arg, &st) == 0 &&
110 	    S_ISDIR(st.st_mode)) {
111 		char tmp[PATH_MAX];
112 
113 		if (realpath(arg, tmp) == 0 ||
114 		    virtio_9p__register(kvm, tmp, "/dev/root") < 0)
115 			die("Unable to initialize virtio 9p");
116 		using_rootfs = 1;
117 		return 0;
118 	}
119 
120 	snprintf(path, PATH_MAX, "%s%s%s", HOME_DIR, KVM_PID_FILE_PATH, arg);
121 
122 	if (stat(path, &st) == 0 &&
123 	    S_ISDIR(st.st_mode)) {
124 		char tmp[PATH_MAX];
125 
126 		if (realpath(path, tmp) == 0 ||
127 		    virtio_9p__register(kvm, tmp, "/dev/root") < 0)
128 			die("Unable to initialize virtio 9p");
129 		if (virtio_9p__register(kvm, "/", "hostfs") < 0)
130 			die("Unable to initialize virtio 9p");
131 		using_rootfs = custom_rootfs = 1;
132 		return 0;
133 	}
134 
135 	if (image_count >= MAX_DISK_IMAGES)
136 		die("Currently only 4 images are supported");
137 
138 	image_filename[image_count] = arg;
139 	sep = strstr(arg, ",");
140 	if (sep) {
141 		if (strcmp(sep + 1, "ro") == 0)
142 			readonly_image[image_count] = 1;
143 		*sep = 0;
144 	}
145 
146 	image_count++;
147 
148 	return 0;
149 }
150 
151 static int virtio_9p_rootdir_parser(const struct option *opt, const char *arg, int unset)
152 {
153 	char *tag_name;
154 	char tmp[PATH_MAX];
155 
156 	/*
157 	 * 9p dir can be of the form dirname,tag_name or
158 	 * just dirname. In the later case we use the
159 	 * default tag name
160 	 */
161 	tag_name = strstr(arg, ",");
162 	if (tag_name) {
163 		*tag_name = '\0';
164 		tag_name++;
165 	}
166 	if (realpath(arg, tmp)) {
167 		if (virtio_9p__register(kvm, tmp, tag_name) < 0)
168 			die("Unable to initialize virtio 9p");
169 	} else
170 		die("Failed resolving 9p path");
171 	return 0;
172 }
173 
174 static int shmem_parser(const struct option *opt, const char *arg, int unset)
175 {
176 	const uint64_t default_size = SHMEM_DEFAULT_SIZE;
177 	const uint64_t default_phys_addr = SHMEM_DEFAULT_ADDR;
178 	const char *default_handle = SHMEM_DEFAULT_HANDLE;
179 	struct shmem_info *si = malloc(sizeof(struct shmem_info));
180 	enum { PCI, UNK } addr_type = PCI;
181 	uint64_t phys_addr;
182 	uint64_t size;
183 	char *handle = NULL;
184 	int create = 0;
185 	const char *p = arg;
186 	char *next;
187 	int base = 10;
188 	int verbose = 0;
189 
190 	const int skip_pci = strlen("pci:");
191 	if (verbose)
192 		pr_info("shmem_parser(%p,%s,%d)", opt, arg, unset);
193 	/* parse out optional addr family */
194 	if (strcasestr(p, "pci:")) {
195 		p += skip_pci;
196 		addr_type = PCI;
197 	} else if (strcasestr(p, "mem:")) {
198 		die("I can't add to E820 map yet.\n");
199 	}
200 	/* parse out physical addr */
201 	base = 10;
202 	if (strcasestr(p, "0x"))
203 		base = 16;
204 	phys_addr = strtoll(p, &next, base);
205 	if (next == p && phys_addr == 0) {
206 		pr_info("shmem: no physical addr specified, using default.");
207 		phys_addr = default_phys_addr;
208 	}
209 	if (*next != ':' && *next != '\0')
210 		die("shmem: unexpected chars after phys addr.\n");
211 	if (*next == '\0')
212 		p = next;
213 	else
214 		p = next + 1;
215 	/* parse out size */
216 	base = 10;
217 	if (strcasestr(p, "0x"))
218 		base = 16;
219 	size = strtoll(p, &next, base);
220 	if (next == p && size == 0) {
221 		pr_info("shmem: no size specified, using default.");
222 		size = default_size;
223 	}
224 	/* look for [KMGkmg][Bb]*  uses base 2. */
225 	int skip_B = 0;
226 	if (strspn(next, "KMGkmg")) {	/* might have a prefix */
227 		if (*(next + 1) == 'B' || *(next + 1) == 'b')
228 			skip_B = 1;
229 		switch (*next) {
230 		case 'K':
231 		case 'k':
232 			size = size << KB_SHIFT;
233 			break;
234 		case 'M':
235 		case 'm':
236 			size = size << MB_SHIFT;
237 			break;
238 		case 'G':
239 		case 'g':
240 			size = size << GB_SHIFT;
241 			break;
242 		default:
243 			die("shmem: bug in detecting size prefix.");
244 			break;
245 		}
246 		next += 1 + skip_B;
247 	}
248 	if (*next != ':' && *next != '\0') {
249 		die("shmem: unexpected chars after phys size. <%c><%c>\n",
250 		    *next, *p);
251 	}
252 	if (*next == '\0')
253 		p = next;
254 	else
255 		p = next + 1;
256 	/* parse out optional shmem handle */
257 	const int skip_handle = strlen("handle=");
258 	next = strcasestr(p, "handle=");
259 	if (*p && next) {
260 		if (p != next)
261 			die("unexpected chars before handle\n");
262 		p += skip_handle;
263 		next = strchrnul(p, ':');
264 		if (next - p) {
265 			handle = malloc(next - p + 1);
266 			strncpy(handle, p, next - p);
267 			handle[next - p] = '\0';	/* just in case. */
268 		}
269 		if (*next == '\0')
270 			p = next;
271 		else
272 			p = next + 1;
273 	}
274 	/* parse optional create flag to see if we should create shm seg. */
275 	if (*p && strcasestr(p, "create")) {
276 		create = 1;
277 		p += strlen("create");
278 	}
279 	if (*p != '\0')
280 		die("shmem: unexpected trailing chars\n");
281 	if (handle == NULL) {
282 		handle = malloc(strlen(default_handle) + 1);
283 		strcpy(handle, default_handle);
284 	}
285 	if (verbose) {
286 		pr_info("shmem: phys_addr = %lx", phys_addr);
287 		pr_info("shmem: size      = %lx", size);
288 		pr_info("shmem: handle    = %s", handle);
289 		pr_info("shmem: create    = %d", create);
290 	}
291 
292 	si->phys_addr = phys_addr;
293 	si->size = size;
294 	si->handle = handle;
295 	si->create = create;
296 	pci_shmem__register_mem(si);	/* ownership of si, etc. passed on. */
297 	return 0;
298 }
299 
300 static const struct option options[] = {
301 	OPT_GROUP("Basic options:"),
302 	OPT_STRING('\0', "name", &guest_name, "guest name",
303 			"A name for the guest"),
304 	OPT_INTEGER('c', "cpus", &nrcpus, "Number of CPUs"),
305 	OPT_U64('m', "mem", &ram_size, "Virtual machine memory size in MiB."),
306 	OPT_CALLBACK('\0', "shmem", NULL,
307 		     "[pci:]<addr>:<size>[:handle=<handle>][:create]",
308 		     "Share host shmem with guest via pci device",
309 		     shmem_parser),
310 	OPT_CALLBACK('d', "disk", NULL, "image or rootfs_dir", "Disk image or rootfs directory", img_name_parser),
311 	OPT_BOOLEAN('\0', "balloon", &balloon, "Enable virtio balloon"),
312 	OPT_BOOLEAN('\0', "vnc", &vnc, "Enable VNC framebuffer"),
313 	OPT_BOOLEAN('\0', "sdl", &sdl, "Enable SDL framebuffer"),
314 	OPT_BOOLEAN('\0', "rng", &virtio_rng, "Enable virtio Random Number Generator"),
315 	OPT_CALLBACK('\0', "9p", NULL, "dir_to_share,tag_name",
316 		     "Enable virtio 9p to share files between host and guest", virtio_9p_rootdir_parser),
317 	OPT_STRING('\0', "console", &console, "serial or virtio",
318 			"Console to use"),
319 	OPT_STRING('\0', "dev", &dev, "device_file", "KVM device file"),
320 
321 	OPT_GROUP("Kernel options:"),
322 	OPT_STRING('k', "kernel", &kernel_filename, "kernel",
323 			"Kernel to boot in virtual machine"),
324 	OPT_STRING('i', "initrd", &initrd_filename, "initrd",
325 			"Initial RAM disk image"),
326 	OPT_STRING('p', "params", &kernel_cmdline, "params",
327 			"Kernel command line arguments"),
328 
329 	OPT_GROUP("Networking options:"),
330 	OPT_STRING('n', "network", &network, "user, tap, none",
331 			"Network to use"),
332 	OPT_STRING('\0', "host-ip", &host_ip, "a.b.c.d",
333 			"Assign this address to the host side networking"),
334 	OPT_STRING('\0', "guest-ip", &guest_ip, "a.b.c.d",
335 			"Assign this address to the guest side networking"),
336 	OPT_STRING('\0', "host-mac", &host_mac, "aa:bb:cc:dd:ee:ff",
337 			"Assign this address to the host side NIC"),
338 	OPT_STRING('\0', "guest-mac", &guest_mac, "aa:bb:cc:dd:ee:ff",
339 			"Assign this address to the guest side NIC"),
340 	OPT_STRING('\0', "tapscript", &script, "Script path",
341 			 "Assign a script to process created tap device"),
342 
343 	OPT_GROUP("BIOS options:"),
344 	OPT_INTEGER('\0', "vidmode", &vidmode,
345 		    "Video mode"),
346 
347 	OPT_GROUP("Debug options:"),
348 	OPT_BOOLEAN('\0', "debug", &do_debug_print,
349 			"Enable debug messages"),
350 	OPT_BOOLEAN('\0', "debug-single-step", &single_step,
351 			"Enable single stepping"),
352 	OPT_BOOLEAN('\0', "debug-ioport", &ioport_debug,
353 			"Enable ioport debugging"),
354 	OPT_INTEGER('\0', "debug-iodelay", &debug_iodelay,
355 			"Delay IO by millisecond"),
356 	OPT_END()
357 };
358 
359 /*
360  * Serialize debug printout so that the output of multiple vcpus does not
361  * get mixed up:
362  */
363 static int printout_done;
364 
365 static void handle_sigusr1(int sig)
366 {
367 	struct kvm_cpu *cpu = current_kvm_cpu;
368 
369 	if (!cpu)
370 		return;
371 
372 	printf("\n #\n # vCPU #%ld's dump:\n #\n", cpu->cpu_id);
373 	kvm_cpu__show_registers(cpu);
374 	kvm_cpu__show_code(cpu);
375 	kvm_cpu__show_page_tables(cpu);
376 	fflush(stdout);
377 	printout_done = 1;
378 	mb();
379 }
380 
381 /* Pause/resume the guest using SIGUSR2 */
382 static int is_paused;
383 
384 static void handle_sigusr2(int sig)
385 {
386 	if (sig == SIGKVMRESUME && is_paused)
387 		kvm__continue();
388 	else if (sig == SIGUSR2 && !is_paused)
389 		kvm__pause();
390 	else
391 		return;
392 
393 	is_paused = !is_paused;
394 	pr_info("Guest %s\n", is_paused ? "paused" : "resumed");
395 }
396 
397 static void handle_sigquit(int sig)
398 {
399 	int i;
400 
401 	for (i = 0; i < nrcpus; i++) {
402 		struct kvm_cpu *cpu = kvm_cpus[i];
403 
404 		if (!cpu)
405 			continue;
406 
407 		printout_done = 0;
408 		pthread_kill(cpu->thread, SIGUSR1);
409 		/*
410 		 * Wait for the vCPU to dump state before signalling
411 		 * the next thread. Since this is debug code it does
412 		 * not matter that we are burning CPU time a bit:
413 		 */
414 		while (!printout_done)
415 			mb();
416 	}
417 
418 	serial8250__inject_sysrq(kvm);
419 }
420 
421 static void handle_sigalrm(int sig)
422 {
423 	serial8250__inject_interrupt(kvm);
424 	virtio_console__inject_interrupt(kvm);
425 }
426 
427 static void handle_sigstop(int sig)
428 {
429 	kvm_cpu__reboot();
430 }
431 
432 static void *kvm_cpu_thread(void *arg)
433 {
434 	current_kvm_cpu		= arg;
435 
436 	if (kvm_cpu__start(current_kvm_cpu))
437 		goto panic_kvm;
438 
439 	kvm_cpu__delete(current_kvm_cpu);
440 
441 	return (void *) (intptr_t) 0;
442 
443 panic_kvm:
444 	fprintf(stderr, "KVM exit reason: %u (\"%s\")\n",
445 		current_kvm_cpu->kvm_run->exit_reason,
446 		kvm_exit_reasons[current_kvm_cpu->kvm_run->exit_reason]);
447 	if (current_kvm_cpu->kvm_run->exit_reason == KVM_EXIT_UNKNOWN)
448 		fprintf(stderr, "KVM exit code: 0x%Lu\n",
449 			current_kvm_cpu->kvm_run->hw.hardware_exit_reason);
450 
451 	kvm_cpu__show_registers(current_kvm_cpu);
452 	kvm_cpu__show_code(current_kvm_cpu);
453 	kvm_cpu__show_page_tables(current_kvm_cpu);
454 
455 	kvm_cpu__delete(current_kvm_cpu);
456 
457 	return (void *) (intptr_t) 1;
458 }
459 
460 static char kernel[PATH_MAX];
461 
462 static const char *host_kernels[] = {
463 	"/boot/vmlinuz",
464 	"/boot/bzImage",
465 	NULL
466 };
467 
468 static const char *default_kernels[] = {
469 	"./bzImage",
470 	"../../arch/x86/boot/bzImage",
471 	NULL
472 };
473 
474 static const char *default_vmlinux[] = {
475 	"../../../vmlinux",
476 	"../../vmlinux",
477 	NULL
478 };
479 
480 static void kernel_usage_with_options(void)
481 {
482 	const char **k;
483 	struct utsname uts;
484 
485 	fprintf(stderr, "Fatal: could not find default kernel image in:\n");
486 	k = &default_kernels[0];
487 	while (*k) {
488 		fprintf(stderr, "\t%s\n", *k);
489 		k++;
490 	}
491 
492 	if (uname(&uts) < 0)
493 		return;
494 
495 	k = &host_kernels[0];
496 	while (*k) {
497 		if (snprintf(kernel, PATH_MAX, "%s-%s", *k, uts.release) < 0)
498 			return;
499 		fprintf(stderr, "\t%s\n", kernel);
500 		k++;
501 	}
502 	fprintf(stderr, "\nPlease see 'kvm run --help' for more options.\n\n");
503 }
504 
505 static u64 host_ram_size(void)
506 {
507 	long page_size;
508 	long nr_pages;
509 
510 	nr_pages	= sysconf(_SC_PHYS_PAGES);
511 	if (nr_pages < 0) {
512 		pr_warning("sysconf(_SC_PHYS_PAGES) failed");
513 		return 0;
514 	}
515 
516 	page_size	= sysconf(_SC_PAGE_SIZE);
517 	if (page_size < 0) {
518 		pr_warning("sysconf(_SC_PAGE_SIZE) failed");
519 		return 0;
520 	}
521 
522 	return (nr_pages * page_size) >> MB_SHIFT;
523 }
524 
525 /*
526  * If user didn't specify how much memory it wants to allocate for the guest,
527  * avoid filling the whole host RAM.
528  */
529 #define RAM_SIZE_RATIO		0.8
530 
531 static u64 get_ram_size(int nr_cpus)
532 {
533 	u64 available;
534 	u64 ram_size;
535 
536 	ram_size	= 64 * (nr_cpus + 3);
537 
538 	available	= host_ram_size() * RAM_SIZE_RATIO;
539 	if (!available)
540 		available = MIN_RAM_SIZE_MB;
541 
542 	if (ram_size > available)
543 		ram_size	= available;
544 
545 	return ram_size;
546 }
547 
548 static const char *find_kernel(void)
549 {
550 	const char **k;
551 	struct stat st;
552 	struct utsname uts;
553 
554 	k = &default_kernels[0];
555 	while (*k) {
556 		if (stat(*k, &st) < 0 || !S_ISREG(st.st_mode)) {
557 			k++;
558 			continue;
559 		}
560 		strncpy(kernel, *k, PATH_MAX);
561 		return kernel;
562 	}
563 
564 	if (uname(&uts) < 0)
565 		return NULL;
566 
567 	k = &host_kernels[0];
568 	while (*k) {
569 		if (snprintf(kernel, PATH_MAX, "%s-%s", *k, uts.release) < 0)
570 			return NULL;
571 
572 		if (stat(kernel, &st) < 0 || !S_ISREG(st.st_mode)) {
573 			k++;
574 			continue;
575 		}
576 		return kernel;
577 
578 	}
579 	return NULL;
580 }
581 
582 static const char *find_vmlinux(void)
583 {
584 	const char **vmlinux;
585 
586 	vmlinux = &default_vmlinux[0];
587 	while (*vmlinux) {
588 		struct stat st;
589 
590 		if (stat(*vmlinux, &st) < 0 || !S_ISREG(st.st_mode)) {
591 			vmlinux++;
592 			continue;
593 		}
594 		return *vmlinux;
595 	}
596 	return NULL;
597 }
598 
599 void kvm_run_help(void)
600 {
601 	usage_with_options(run_usage, options);
602 }
603 
604 int kvm_cmd_run(int argc, const char **argv, const char *prefix)
605 {
606 	struct virtio_net_parameters net_params;
607 	static char real_cmdline[2048], default_name[20];
608 	struct framebuffer *fb = NULL;
609 	unsigned int nr_online_cpus;
610 	int exit_code = 0;
611 	int max_cpus, recommended_cpus;
612 	int i;
613 	void *ret;
614 
615 	signal(SIGALRM, handle_sigalrm);
616 	signal(SIGQUIT, handle_sigquit);
617 	signal(SIGUSR1, handle_sigusr1);
618 	signal(SIGUSR2, handle_sigusr2);
619 	signal(SIGKVMSTOP, handle_sigstop);
620 	signal(SIGKVMRESUME, handle_sigusr2);
621 	/* ignore balloon signal by default if not enable balloon optiion */
622 	signal(SIGKVMADDMEM, SIG_IGN);
623 	signal(SIGKVMDELMEM, SIG_IGN);
624 
625 	nr_online_cpus = sysconf(_SC_NPROCESSORS_ONLN);
626 
627 	while (argc != 0) {
628 		argc = parse_options(argc, argv, options, run_usage,
629 				PARSE_OPT_STOP_AT_NON_OPTION);
630 		if (argc != 0) {
631 			if (kernel_filename) {
632 				fprintf(stderr, "Cannot handle parameter: "
633 						"%s\n", argv[0]);
634 				usage_with_options(run_usage, options);
635 				return EINVAL;
636 			}
637 			/* first unhandled parameter is treated as a kernel
638 			   image
639 			 */
640 			kernel_filename = argv[0];
641 			argv++;
642 			argc--;
643 		}
644 
645 	}
646 
647 	if (!kernel_filename)
648 		kernel_filename = find_kernel();
649 
650 	if (!kernel_filename) {
651 		kernel_usage_with_options();
652 		return EINVAL;
653 	}
654 
655 	vmlinux_filename = find_vmlinux();
656 
657 	if (nrcpus == 0)
658 		nrcpus = nr_online_cpus;
659 	else if (nrcpus < 1 || nrcpus > KVM_NR_CPUS)
660 		die("Number of CPUs %d is out of [1;%d] range", nrcpus, KVM_NR_CPUS);
661 
662 	if (!ram_size)
663 		ram_size	= get_ram_size(nrcpus);
664 
665 	if (ram_size < MIN_RAM_SIZE_MB)
666 		die("Not enough memory specified: %lluMB (min %lluMB)", ram_size, MIN_RAM_SIZE_MB);
667 
668 	if (ram_size > host_ram_size())
669 		pr_warning("Guest memory size %lluMB exceeds host physical RAM size %lluMB", ram_size, host_ram_size());
670 
671 	ram_size <<= MB_SHIFT;
672 
673 	if (!dev)
674 		dev = DEFAULT_KVM_DEV;
675 
676 	if (!console)
677 		console = DEFAULT_CONSOLE;
678 
679 	if (!strncmp(console, "virtio", 6))
680 		active_console  = CONSOLE_VIRTIO;
681 	else
682 		active_console  = CONSOLE_8250;
683 
684 	if (!host_ip)
685 		host_ip = DEFAULT_HOST_ADDR;
686 
687 	if (!guest_ip)
688 		guest_ip = DEFAULT_GUEST_ADDR;
689 
690 	if (!guest_mac)
691 		guest_mac = DEFAULT_GUEST_MAC;
692 
693 	if (!host_mac)
694 		host_mac = DEFAULT_HOST_MAC;
695 
696 	if (!script)
697 		script = DEFAULT_SCRIPT;
698 
699 	symbol__init(vmlinux_filename);
700 
701 	term_init();
702 
703 	if (!guest_name) {
704 		sprintf(default_name, "guest-%u", getpid());
705 		guest_name = default_name;
706 	}
707 
708 	kvm = kvm__init(dev, ram_size, guest_name);
709 
710 	irq__init(kvm);
711 
712 	kvm->single_step = single_step;
713 
714 	ioeventfd__init();
715 
716 	max_cpus = kvm__max_cpus(kvm);
717 	recommended_cpus = kvm__recommended_cpus(kvm);
718 
719 	if (nrcpus > max_cpus) {
720 		printf("  # Limit the number of CPUs to %d\n", max_cpus);
721 		kvm->nrcpus	= max_cpus;
722 	} else if (nrcpus > recommended_cpus) {
723 		printf("  # Warning: The maximum recommended amount of VCPUs"
724 			" is %d\n", recommended_cpus);
725 	}
726 
727 	kvm->nrcpus = nrcpus;
728 
729 	/*
730 	 * vidmode should be either specified
731 	 * either set by default
732 	 */
733 	if (vnc || sdl) {
734 		if (vidmode == -1)
735 			vidmode = 0x312;
736 	} else
737 		vidmode = 0;
738 
739 	memset(real_cmdline, 0, sizeof(real_cmdline));
740 	strcpy(real_cmdline, "notsc noapic noacpi pci=conf1 reboot=k panic=1 i8042.direct=1 i8042.dumbkbd=1 i8042.nopnp=1");
741 	if (vnc || sdl) {
742 		strcat(real_cmdline, " video=vesafb console=tty0");
743 	} else
744 		strcat(real_cmdline, " console=ttyS0 earlyprintk=serial");
745 	strcat(real_cmdline, " ");
746 	if (kernel_cmdline)
747 		strlcat(real_cmdline, kernel_cmdline, sizeof(real_cmdline));
748 
749 	if (!using_rootfs && !image_filename[0]) {
750 		if (virtio_9p__register(kvm, "/", "/dev/root") < 0)
751 			die("Unable to initialize virtio 9p");
752 
753 		using_rootfs = 1;
754 
755 		if (!strstr(real_cmdline, "init="))
756 			strlcat(real_cmdline, " init=/bin/sh ", sizeof(real_cmdline));
757 	}
758 
759 	if (using_rootfs) {
760 		strcat(real_cmdline, " root=/dev/root rw rootflags=rw,trans=virtio,version=9p2000.L rootfstype=9p");
761 		if (custom_rootfs)
762 			strcat(real_cmdline, " init=/virt/init");
763 	} else if (!strstr(real_cmdline, "root=")) {
764 		strlcat(real_cmdline, " root=/dev/vda rw ", sizeof(real_cmdline));
765 	}
766 
767 	if (image_count) {
768 		kvm->nr_disks = image_count;
769 		kvm->disks    = disk_image__open_all(image_filename, readonly_image, image_count);
770 		if (!kvm->disks)
771 			die("Unable to load all disk images.");
772 
773 		virtio_blk__init_all(kvm);
774 	}
775 
776 	printf("  # kvm run -k %s -m %Lu -c %d --name %s\n", kernel_filename, ram_size / 1024 / 1024, nrcpus, guest_name);
777 
778 	if (!kvm__load_kernel(kvm, kernel_filename, initrd_filename,
779 				real_cmdline, vidmode))
780 		die("unable to load kernel %s", kernel_filename);
781 
782 	kvm->vmlinux		= vmlinux_filename;
783 
784 	ioport__setup_legacy();
785 
786 	rtc__init();
787 
788 	serial8250__init(kvm);
789 
790 	pci__init();
791 
792 	if (active_console == CONSOLE_VIRTIO)
793 		virtio_console__init(kvm);
794 
795 	if (virtio_rng)
796 		virtio_rng__init(kvm);
797 
798 	if (balloon)
799 		virtio_bln__init(kvm);
800 
801 	if (!network)
802 		network = DEFAULT_NETWORK;
803 
804 	virtio_9p__init(kvm);
805 
806 	if (strncmp(network, "none", 4)) {
807 		net_params.guest_ip = guest_ip;
808 		net_params.host_ip = host_ip;
809 		net_params.kvm = kvm;
810 		net_params.script = script;
811 		sscanf(guest_mac, "%hhx:%hhx:%hhx:%hhx:%hhx:%hhx",
812 			net_params.guest_mac,
813 			net_params.guest_mac+1,
814 			net_params.guest_mac+2,
815 			net_params.guest_mac+3,
816 			net_params.guest_mac+4,
817 			net_params.guest_mac+5);
818 		sscanf(host_mac, "%hhx:%hhx:%hhx:%hhx:%hhx:%hhx",
819 			net_params.host_mac,
820 			net_params.host_mac+1,
821 			net_params.host_mac+2,
822 			net_params.host_mac+3,
823 			net_params.host_mac+4,
824 			net_params.host_mac+5);
825 
826 		if (!strncmp(network, "user", 4))
827 			net_params.mode = NET_MODE_USER;
828 		else if (!strncmp(network, "tap", 3))
829 			net_params.mode = NET_MODE_TAP;
830 		else
831 			die("Unkown network mode %s, please use -network user, tap, none", network);
832 		virtio_net__init(&net_params);
833 	}
834 
835 	kvm__start_timer(kvm);
836 
837 	kvm__setup_bios(kvm);
838 
839 	for (i = 0; i < nrcpus; i++) {
840 		kvm_cpus[i] = kvm_cpu__init(kvm, i);
841 		if (!kvm_cpus[i])
842 			die("unable to initialize KVM VCPU");
843 	}
844 
845 	kvm__init_ram(kvm);
846 
847 	kbd__init(kvm);
848 
849 	pci_shmem__init(kvm);
850 
851 	if (vnc || sdl)
852 		fb = vesa__init(kvm);
853 
854 	if (vnc) {
855 		if (fb)
856 			vnc__init(fb);
857 	}
858 
859 	if (sdl) {
860 		if (fb)
861 			sdl__init(fb);
862 	}
863 
864 	fb__start();
865 
866 	thread_pool__init(nr_online_cpus);
867 	ioeventfd__start();
868 
869 	for (i = 0; i < nrcpus; i++) {
870 		if (pthread_create(&kvm_cpus[i]->thread, NULL, kvm_cpu_thread, kvm_cpus[i]) != 0)
871 			die("unable to create KVM VCPU thread");
872 	}
873 
874 	/* Only VCPU #0 is going to exit by itself when shutting down */
875 	if (pthread_join(kvm_cpus[0]->thread, &ret) != 0)
876 		exit_code = 1;
877 
878 	for (i = 1; i < nrcpus; i++) {
879 		if (kvm_cpus[i]->is_running) {
880 			pthread_kill(kvm_cpus[i]->thread, SIGKVMEXIT);
881 			if (pthread_join(kvm_cpus[i]->thread, &ret) != 0)
882 				die("pthread_join");
883 		}
884 		if (ret != NULL)
885 			exit_code = 1;
886 	}
887 
888 	compat__print_all_messages();
889 
890 	fb__stop();
891 
892 	virtio_blk__delete_all(kvm);
893 	virtio_rng__delete_all(kvm);
894 
895 	disk_image__close_all(kvm->disks, image_count);
896 	kvm__delete(kvm);
897 
898 	if (!exit_code)
899 		printf("\n  # KVM session ended normally.\n");
900 
901 	return exit_code;
902 }
903