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