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