xref: /kvmtool/builtin-run.c (revision 4298ddade7b629079b3dfb0457cf4bcff7c47d3e)
1 #include <stdio.h>
2 #include <string.h>
3 #include <signal.h>
4 #include <unistd.h>
5 #include <stdlib.h>
6 #include <termios.h>
7 #include <sys/utsname.h>
8 #include <sys/types.h>
9 #include <sys/stat.h>
10 #include <ctype.h>
11 
12 /* user defined header files */
13 #include <linux/types.h>
14 #include <kvm/kvm.h>
15 #include <kvm/kvm-cpu.h>
16 #include <kvm/8250-serial.h>
17 #include <kvm/virtio-blk.h>
18 #include <kvm/virtio-net.h>
19 #include <kvm/virtio-console.h>
20 #include <kvm/virtio-rng.h>
21 #include <kvm/disk-image.h>
22 #include <kvm/util.h>
23 #include <kvm/pci.h>
24 #include <kvm/rtc.h>
25 #include <kvm/term.h>
26 #include <kvm/ioport.h>
27 #include <kvm/threadpool.h>
28 #include <kvm/barrier.h>
29 #include <kvm/symbol.h>
30 #include <kvm/virtio-9p.h>
31 #include <kvm/vesa.h>
32 #include <kvm/ioeventfd.h>
33 
34 /* header files for gitish interface  */
35 #include <kvm/kvm-run.h>
36 #include <kvm/parse-options.h>
37 #include <kvm/mutex.h>
38 
39 #define DEFAULT_KVM_DEV		"/dev/kvm"
40 #define DEFAULT_CONSOLE		"serial"
41 #define DEFAULT_NETWORK		"virtio"
42 #define DEFAULT_HOST_ADDR	"192.168.33.2"
43 #define DEFAULT_GUEST_MAC	"00:11:22:33:44:55"
44 #define DEFAULT_SCRIPT		"none"
45 
46 #define MB_SHIFT		(20)
47 #define MIN_RAM_SIZE_MB		(64ULL)
48 #define MIN_RAM_SIZE_BYTE	(MIN_RAM_SIZE_MB << MB_SHIFT)
49 
50 struct kvm *kvm;
51 struct kvm_cpu *kvm_cpus[KVM_NR_CPUS];
52 __thread struct kvm_cpu *current_kvm_cpu;
53 
54 static u64 ram_size;
55 static u8  image_count;
56 static int virtio_rng;
57 static const char *kernel_cmdline;
58 static const char *kernel_filename;
59 static const char *vmlinux_filename;
60 static const char *initrd_filename;
61 static const char *image_filename[MAX_DISK_IMAGES];
62 static const char *console;
63 static const char *kvm_dev;
64 static const char *network;
65 static const char *host_ip_addr;
66 static const char *guest_mac;
67 static const char *script;
68 static const char *virtio_9p_dir;
69 static bool single_step;
70 static bool readonly_image[MAX_DISK_IMAGES];
71 static bool vnc;
72 extern bool ioport_debug;
73 extern int  active_console;
74 
75 bool do_debug_print = false;
76 
77 static int nrcpus;
78 
79 static const char * const run_usage[] = {
80 	"kvm run [<options>] [<kernel image>]",
81 	NULL
82 };
83 
84 static int img_name_parser(const struct option *opt, const char *arg, int unset)
85 {
86 	char *sep;
87 
88 	if (image_count >= MAX_DISK_IMAGES)
89 		die("Currently only 4 images are supported");
90 
91 	image_filename[image_count] = arg;
92 	sep = strstr(arg, ",");
93 	if (sep) {
94 		if (strcmp(sep + 1, "ro") == 0)
95 			readonly_image[image_count] = 1;
96 		*sep = 0;
97 	}
98 
99 	image_count++;
100 
101 	return 0;
102 }
103 
104 static const struct option options[] = {
105 	OPT_GROUP("Basic options:"),
106 	OPT_INTEGER('c', "cpus", &nrcpus, "Number of CPUs"),
107 	OPT_U64('m', "mem", &ram_size, "Virtual machine memory size in MiB."),
108 	OPT_CALLBACK('d', "disk", NULL, "image", "Disk image", img_name_parser),
109 	OPT_STRING('\0', "console", &console, "serial or virtio",
110 			"Console to use"),
111 	OPT_INCR('\0', "rng", &virtio_rng,
112 			"Enable virtio Random Number Generator"),
113 	OPT_STRING('\0', "kvm-dev", &kvm_dev, "kvm-dev", "KVM device file"),
114 	OPT_STRING('\0', "virtio-9p", &virtio_9p_dir, "root dir",
115 			"Enable 9p over virtio"),
116 	OPT_BOOLEAN('\0', "vnc", &vnc, "Enable VNC framebuffer"),
117 
118 	OPT_GROUP("Kernel options:"),
119 	OPT_STRING('k', "kernel", &kernel_filename, "kernel",
120 			"Kernel to boot in virtual machine"),
121 	OPT_STRING('i', "initrd", &initrd_filename, "initrd",
122 			"Initial RAM disk image"),
123 	OPT_STRING('p', "params", &kernel_cmdline, "params",
124 			"Kernel command line arguments"),
125 
126 	OPT_GROUP("Networking options:"),
127 	OPT_STRING('n', "network", &network, "virtio",
128 			"Network to use"),
129 	OPT_STRING('\0', "host-ip-addr", &host_ip_addr, "a.b.c.d",
130 			"Assign this address to the host side networking"),
131 	OPT_STRING('\0', "guest-mac", &guest_mac, "aa:bb:cc:dd:ee:ff",
132 			"Assign this address to the guest side NIC"),
133 	OPT_STRING('\0', "tapscript", &script, "Script path",
134 			 "Assign a script to process created tap device"),
135 
136 	OPT_GROUP("Debug options:"),
137 	OPT_BOOLEAN('\0', "debug", &do_debug_print,
138 			"Enable debug messages"),
139 	OPT_BOOLEAN('\0', "debug-single-step", &single_step,
140 			"Enable single stepping"),
141 	OPT_BOOLEAN('\0', "debug-ioport-debug", &ioport_debug,
142 			"Enable ioport debugging"),
143 	OPT_END()
144 };
145 
146 /*
147  * Serialize debug printout so that the output of multiple vcpus does not
148  * get mixed up:
149  */
150 static int printout_done;
151 
152 static void handle_sigusr1(int sig)
153 {
154 	struct kvm_cpu *cpu = current_kvm_cpu;
155 
156 	if (!cpu)
157 		return;
158 
159 	printf("\n #\n # vCPU #%ld's dump:\n #\n", cpu->cpu_id);
160 	kvm_cpu__show_registers(cpu);
161 	kvm_cpu__show_code(cpu);
162 	kvm_cpu__show_page_tables(cpu);
163 	fflush(stdout);
164 	printout_done = 1;
165 	mb();
166 }
167 
168 static void handle_sigquit(int sig)
169 {
170 	int i;
171 
172 	for (i = 0; i < nrcpus; i++) {
173 		struct kvm_cpu *cpu = kvm_cpus[i];
174 
175 		if (!cpu)
176 			continue;
177 
178 		printout_done = 0;
179 		pthread_kill(cpu->thread, SIGUSR1);
180 		/*
181 		 * Wait for the vCPU to dump state before signalling
182 		 * the next thread. Since this is debug code it does
183 		 * not matter that we are burning CPU time a bit:
184 		 */
185 		while (!printout_done)
186 			mb();
187 	}
188 
189 	serial8250__inject_sysrq(kvm);
190 }
191 
192 static void handle_sigalrm(int sig)
193 {
194 	serial8250__inject_interrupt(kvm);
195 	virtio_console__inject_interrupt(kvm);
196 }
197 
198 static void *kvm_cpu_thread(void *arg)
199 {
200 	current_kvm_cpu		= arg;
201 
202 	if (kvm_cpu__start(current_kvm_cpu))
203 		goto panic_kvm;
204 
205 	kvm_cpu__delete(current_kvm_cpu);
206 
207 	return (void *) (intptr_t) 0;
208 
209 panic_kvm:
210 	fprintf(stderr, "KVM exit reason: %u (\"%s\")\n",
211 		current_kvm_cpu->kvm_run->exit_reason,
212 		kvm_exit_reasons[current_kvm_cpu->kvm_run->exit_reason]);
213 	if (current_kvm_cpu->kvm_run->exit_reason == KVM_EXIT_UNKNOWN)
214 		fprintf(stderr, "KVM exit code: 0x%Lu\n",
215 			current_kvm_cpu->kvm_run->hw.hardware_exit_reason);
216 
217 	kvm_cpu__show_registers(current_kvm_cpu);
218 	kvm_cpu__show_code(current_kvm_cpu);
219 	kvm_cpu__show_page_tables(current_kvm_cpu);
220 
221 	kvm_cpu__delete(current_kvm_cpu);
222 
223 	return (void *) (intptr_t) 1;
224 }
225 
226 static char kernel[PATH_MAX];
227 
228 static const char *host_kernels[] = {
229 	"/boot/vmlinuz",
230 	"/boot/bzImage",
231 	NULL
232 };
233 
234 static const char *default_kernels[] = {
235 	"./bzImage",
236 	"../../arch/x86/boot/bzImage",
237 	NULL
238 };
239 
240 static const char *default_vmlinux[] = {
241 	"../../../vmlinux",
242 	"../../vmlinux",
243 	NULL
244 };
245 
246 static void kernel_usage_with_options(void)
247 {
248 	const char **k;
249 	struct utsname uts;
250 
251 	fprintf(stderr, "Fatal: could not find default kernel image in:\n");
252 	k = &default_kernels[0];
253 	while (*k) {
254 		fprintf(stderr, "\t%s\n", *k);
255 		k++;
256 	}
257 
258 	if (uname(&uts) < 0)
259 		return;
260 
261 	k = &host_kernels[0];
262 	while (*k) {
263 		if (snprintf(kernel, PATH_MAX, "%s-%s", *k, uts.release) < 0)
264 			return;
265 		fprintf(stderr, "\t%s\n", kernel);
266 		k++;
267 	}
268 	fprintf(stderr, "\nPlease see 'kvm run --help' for more options.\n\n");
269 }
270 
271 static u64 host_ram_size(void)
272 {
273 	long page_size;
274 	long nr_pages;
275 
276 	nr_pages	= sysconf(_SC_PHYS_PAGES);
277 	if (nr_pages < 0) {
278 		pr_warning("sysconf(_SC_PHYS_PAGES) failed");
279 		return 0;
280 	}
281 
282 	page_size	= sysconf(_SC_PAGE_SIZE);
283 	if (page_size < 0) {
284 		pr_warning("sysconf(_SC_PAGE_SIZE) failed");
285 		return 0;
286 	}
287 
288 	return (nr_pages * page_size) >> MB_SHIFT;
289 }
290 
291 /*
292  * If user didn't specify how much memory it wants to allocate for the guest,
293  * avoid filling the whole host RAM.
294  */
295 #define RAM_SIZE_RATIO		0.8
296 
297 static u64 get_ram_size(int nr_cpus)
298 {
299 	long available;
300 	long ram_size;
301 
302 	ram_size	= 64 * (nr_cpus + 3);
303 
304 	available	= host_ram_size() * RAM_SIZE_RATIO;
305 	if (!available)
306 		available = MIN_RAM_SIZE_MB;
307 
308 	if (ram_size > available)
309 		ram_size	= available;
310 
311 	return ram_size;
312 }
313 
314 static const char *find_kernel(void)
315 {
316 	const char **k;
317 	struct stat st;
318 	struct utsname uts;
319 
320 	k = &default_kernels[0];
321 	while (*k) {
322 		if (stat(*k, &st) < 0 || !S_ISREG(st.st_mode)) {
323 			k++;
324 			continue;
325 		}
326 		strncpy(kernel, *k, PATH_MAX);
327 		return kernel;
328 	}
329 
330 	if (uname(&uts) < 0)
331 		return NULL;
332 
333 	k = &host_kernels[0];
334 	while (*k) {
335 		if (snprintf(kernel, PATH_MAX, "%s-%s", *k, uts.release) < 0)
336 			return NULL;
337 
338 		if (stat(kernel, &st) < 0 || !S_ISREG(st.st_mode)) {
339 			k++;
340 			continue;
341 		}
342 		return kernel;
343 
344 	}
345 	return NULL;
346 }
347 
348 static const char *find_vmlinux(void)
349 {
350 	const char **vmlinux;
351 
352 	vmlinux = &default_vmlinux[0];
353 	while (*vmlinux) {
354 		struct stat st;
355 
356 		if (stat(*vmlinux, &st) < 0 || !S_ISREG(st.st_mode)) {
357 			vmlinux++;
358 			continue;
359 		}
360 		return *vmlinux;
361 	}
362 	return NULL;
363 }
364 
365 static int root_device(char *dev, long *part)
366 {
367 	struct stat st;
368 
369 	if (stat("/", &st) < 0)
370 		return -1;
371 
372 	*part = minor(st.st_dev);
373 
374 	sprintf(dev, "/dev/block/%u:0", major(st.st_dev));
375 	if (access(dev, R_OK) < 0)
376 		return -1;
377 
378 	return 0;
379 }
380 
381 static char *host_image(char *cmd_line, size_t size)
382 {
383 	char *t;
384 	char device[PATH_MAX];
385 	long part = 0;
386 
387 	t = malloc(PATH_MAX);
388 	if (!t)
389 		return NULL;
390 
391 	/* check for the root file system */
392 	if (root_device(device, &part) < 0) {
393 		free(t);
394 		return NULL;
395 	}
396 	strncpy(t, device, PATH_MAX);
397 	if (!strstr(cmd_line, "root=")) {
398 		char tmp[PATH_MAX];
399 		snprintf(tmp, sizeof(tmp), "root=/dev/vda%ld rw ", part);
400 		strlcat(cmd_line, tmp, size);
401 	}
402 	return t;
403 }
404 
405 void kvm_run_help(void)
406 {
407 	usage_with_options(run_usage, options);
408 }
409 
410 int kvm_cmd_run(int argc, const char **argv, const char *prefix)
411 {
412 	struct virtio_net_parameters net_params;
413 	static char real_cmdline[2048];
414 	unsigned int nr_online_cpus;
415 	int exit_code = 0;
416 	int max_cpus;
417 	char *hi;
418 	int i;
419 	void *ret;
420 	u16 vidmode = 0;
421 
422 	signal(SIGALRM, handle_sigalrm);
423 	signal(SIGQUIT, handle_sigquit);
424 	signal(SIGUSR1, handle_sigusr1);
425 
426 	nr_online_cpus = sysconf(_SC_NPROCESSORS_ONLN);
427 
428 	while (argc != 0) {
429 		argc = parse_options(argc, argv, options, run_usage,
430 				PARSE_OPT_STOP_AT_NON_OPTION);
431 		if (argc != 0) {
432 			if (kernel_filename) {
433 				fprintf(stderr, "Cannot handle parameter: "
434 						"%s\n", argv[0]);
435 				usage_with_options(run_usage, options);
436 				return EINVAL;
437 			}
438 			/* first unhandled parameter is treated as a kernel
439 			   image
440 			 */
441 			kernel_filename = argv[0];
442 			argv++;
443 			argc--;
444 		}
445 
446 	}
447 
448 	if (!kernel_filename)
449 		kernel_filename = find_kernel();
450 
451 	if (!kernel_filename) {
452 		kernel_usage_with_options();
453 		return EINVAL;
454 	}
455 
456 	vmlinux_filename = find_vmlinux();
457 
458 	if (nrcpus == 0)
459 		nrcpus = nr_online_cpus;
460 	else if (nrcpus < 1 || nrcpus > KVM_NR_CPUS)
461 		die("Number of CPUs %d is out of [1;%d] range", nrcpus, KVM_NR_CPUS);
462 
463 	if (!ram_size)
464 		ram_size	= get_ram_size(nrcpus);
465 
466 	if (ram_size < MIN_RAM_SIZE_MB)
467 		die("Not enough memory specified: %lluMB (min %lluMB)", ram_size, MIN_RAM_SIZE_MB);
468 
469 	if (ram_size > host_ram_size())
470 		pr_warning("Guest memory size %lluMB exceeds host physical RAM size %lluMB", ram_size, host_ram_size());
471 
472 	ram_size <<= MB_SHIFT;
473 
474 	if (!kvm_dev)
475 		kvm_dev = DEFAULT_KVM_DEV;
476 
477 	if (!console)
478 		console = DEFAULT_CONSOLE;
479 
480 	if (!strncmp(console, "virtio", 6))
481 		active_console  = CONSOLE_VIRTIO;
482 	else
483 		active_console  = CONSOLE_8250;
484 
485 	if (!host_ip_addr)
486 		host_ip_addr = DEFAULT_HOST_ADDR;
487 
488 	if (!guest_mac)
489 		guest_mac = DEFAULT_GUEST_MAC;
490 
491 	if (!script)
492 		script = DEFAULT_SCRIPT;
493 
494 	if (virtio_9p_dir) {
495 		char tmp[PATH_MAX];
496 
497 		if (realpath(virtio_9p_dir, tmp))
498 			virtio_9p__init(kvm, tmp);
499 		else
500 			die("Failed resolving 9p path");
501 	}
502 
503 	symbol__init(vmlinux_filename);
504 
505 	term_init();
506 
507 	kvm = kvm__init(kvm_dev, ram_size);
508 
509 	ioeventfd__init();
510 
511 	max_cpus = kvm__max_cpus(kvm);
512 
513 	if (nrcpus > max_cpus) {
514 		printf("  # Limit the number of CPUs to %d\n", max_cpus);
515 		kvm->nrcpus	= max_cpus;
516 	}
517 
518 	kvm->nrcpus = nrcpus;
519 
520 	memset(real_cmdline, 0, sizeof(real_cmdline));
521 	strcpy(real_cmdline, "notsc noapic noacpi pci=conf1");
522 	if (vnc) {
523 		strcat(real_cmdline, " video=vesafb console=tty0");
524 		vidmode = 0x312;
525 	} else {
526 		strcat(real_cmdline, " console=ttyS0 earlyprintk=serial");
527 	}
528 	strcat(real_cmdline, " ");
529 	if (kernel_cmdline)
530 		strlcat(real_cmdline, kernel_cmdline, sizeof(real_cmdline));
531 
532 	hi = NULL;
533 	if (!image_filename[0]) {
534 		hi = host_image(real_cmdline, sizeof(real_cmdline));
535 		if (hi) {
536 			image_filename[0] = hi;
537 			readonly_image[0] = true;
538 			image_count++;
539 		}
540 	}
541 
542 	if (!strstr(real_cmdline, "root="))
543 		strlcat(real_cmdline, " root=/dev/vda rw ", sizeof(real_cmdline));
544 
545 	if (image_count) {
546 		kvm->nr_disks = image_count;
547 		kvm->disks    = disk_image__open_all(image_filename, readonly_image, image_count);
548 		if (!kvm->disks)
549 			die("Unable to load all disk images.");
550 
551 		virtio_blk__init_all(kvm);
552 	}
553 
554 	free(hi);
555 
556 	printf("  # kvm run -k %s -m %Lu -c %d\n", kernel_filename, ram_size / 1024 / 1024, nrcpus);
557 
558 	if (!kvm__load_kernel(kvm, kernel_filename, initrd_filename,
559 				real_cmdline, vidmode))
560 		die("unable to load kernel %s", kernel_filename);
561 
562 	kvm->vmlinux		= vmlinux_filename;
563 
564 	ioport__setup_legacy();
565 
566 	rtc__init();
567 
568 	serial8250__init(kvm);
569 
570 	pci__init();
571 
572 	if (active_console == CONSOLE_VIRTIO)
573 		virtio_console__init(kvm);
574 
575 	if (virtio_rng)
576 		while (virtio_rng--)
577 			virtio_rng__init(kvm);
578 
579 	if (!network)
580 		network = DEFAULT_NETWORK;
581 
582 	if (!strncmp(network, "virtio", 6)) {
583 		net_params = (struct virtio_net_parameters) {
584 			.host_ip = host_ip_addr,
585 			.kvm = kvm,
586 			.script = script
587 		};
588 		sscanf(guest_mac,	"%hhx:%hhx:%hhx:%hhx:%hhx:%hhx",
589 							net_params.guest_mac,
590 							net_params.guest_mac+1,
591 							net_params.guest_mac+2,
592 							net_params.guest_mac+3,
593 							net_params.guest_mac+4,
594 							net_params.guest_mac+5);
595 
596 		virtio_net__init(&net_params);
597 	}
598 
599 	kvm__start_timer(kvm);
600 
601 	kvm__setup_bios(kvm);
602 
603 	for (i = 0; i < nrcpus; i++) {
604 		kvm_cpus[i] = kvm_cpu__init(kvm, i);
605 		if (!kvm_cpus[i])
606 			die("unable to initialize KVM VCPU");
607 
608 		if (single_step)
609 			kvm_cpu__enable_singlestep(kvm_cpus[i]);
610 	}
611 
612 	kvm__init_ram(kvm);
613 
614 	if (vnc)
615 		vesa__init(kvm);
616 
617 	thread_pool__init(nr_online_cpus);
618 	ioeventfd__start();
619 
620 	for (i = 0; i < nrcpus; i++) {
621 		if (pthread_create(&kvm_cpus[i]->thread, NULL, kvm_cpu_thread, kvm_cpus[i]) != 0)
622 			die("unable to create KVM VCPU thread");
623 	}
624 
625 	/* Only VCPU #0 is going to exit by itself when shutting down */
626 	if (pthread_join(kvm_cpus[0]->thread, &ret) != 0)
627 		exit_code = 1;
628 
629 	for (i = 1; i < nrcpus; i++) {
630 		pthread_kill(kvm_cpus[i]->thread, SIGKVMEXIT);
631 		if (pthread_join(kvm_cpus[i]->thread, &ret) != 0)
632 			die("pthread_join");
633 
634 		if (ret != NULL)
635 			exit_code = 1;
636 	}
637 
638 	virtio_blk__delete_all(kvm);
639 	virtio_rng__delete_all(kvm);
640 
641 	disk_image__close_all(kvm->disks, image_count);
642 	kvm__delete(kvm);
643 
644 	if (!exit_code)
645 		printf("\n  # KVM session ended normally.\n");
646 
647 	return exit_code;
648 }
649