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