xref: /kvmtool/builtin-run.c (revision a33979d8e21fbd1cd920b16f5fc15ba377416881)
1 #include <stdio.h>
2 #include <string.h>
3 #include <signal.h>
4 #include <stdint.h>
5 #include <unistd.h>
6 #include <inttypes.h>
7 #include <stdlib.h>
8 #include <termios.h>
9 #include <sys/utsname.h>
10 #include <sys/types.h>
11 #include <sys/stat.h>
12 #include <ctype.h>
13 
14 /* user defined header files */
15 #include <linux/types.h>
16 #include <kvm/kvm.h>
17 #include <kvm/kvm-cpu.h>
18 #include <kvm/8250-serial.h>
19 #include <kvm/virtio-blk.h>
20 #include <kvm/virtio-net.h>
21 #include <kvm/virtio-console.h>
22 #include <kvm/virtio-rng.h>
23 #include <kvm/disk-image.h>
24 #include <kvm/util.h>
25 #include <kvm/pci.h>
26 #include <kvm/rtc.h>
27 #include <kvm/term.h>
28 #include <kvm/ioport.h>
29 #include <kvm/threadpool.h>
30 
31 /* header files for gitish interface  */
32 #include <kvm/kvm-run.h>
33 #include <kvm/parse-options.h>
34 
35 #define DEFAULT_KVM_DEV		"/dev/kvm"
36 #define DEFAULT_CONSOLE		"serial"
37 #define DEFAULT_NETWORK		"virtio"
38 #define DEFAULT_HOST_ADDR	"192.168.33.2"
39 #define DEFAULT_GUEST_MAC	"00:11:22:33:44:55"
40 #define DEFAULT_SCRIPT		"none"
41 
42 #define MB_SHIFT		(20)
43 #define MIN_RAM_SIZE_MB		(64ULL)
44 #define MIN_RAM_SIZE_BYTE	(MIN_RAM_SIZE_MB << MB_SHIFT)
45 #define MAX_DISK_IMAGES		4
46 
47 static struct kvm *kvm;
48 static struct kvm_cpu *kvm_cpus[KVM_NR_CPUS];
49 static __thread struct kvm_cpu *current_kvm_cpu;
50 
51 static u64 ram_size = MIN_RAM_SIZE_MB;
52 static u8  image_count;
53 static const char *kernel_cmdline;
54 static const char *kernel_filename;
55 static const char *initrd_filename;
56 static const char *image_filename[MAX_DISK_IMAGES];
57 static const char *console;
58 static const char *kvm_dev;
59 static const char *network;
60 static const char *host_ip_addr;
61 static const char *guest_mac;
62 static const char *script;
63 static bool single_step;
64 static bool readonly_image[MAX_DISK_IMAGES];
65 static bool virtio_rng;
66 extern bool ioport_debug;
67 extern int  active_console;
68 
69 static int nrcpus = 1;
70 
71 static const char * const run_usage[] = {
72 	"kvm run [<options>] [<kernel image>]",
73 	NULL
74 };
75 
76 static int img_name_parser(const struct option *opt, const char *arg, int unset)
77 {
78 	char *sep;
79 
80 	if (image_count >= MAX_DISK_IMAGES)
81 		die("Currently only 4 images are supported");
82 
83 	image_filename[image_count] = arg;
84 	sep = strstr(arg, ",");
85 	if (sep) {
86 		if (strcmp(sep + 1, "ro") == 0)
87 			readonly_image[image_count] = 1;
88 		*sep = 0;
89 	}
90 
91 	image_count++;
92 
93 	return 0;
94 }
95 
96 static const struct option options[] = {
97 	OPT_GROUP("Basic options:"),
98 	OPT_INTEGER('\0', "cpus", &nrcpus, "Number of CPUs"),
99 	OPT_U64('m', "mem", &ram_size, "Virtual machine memory size in MiB."),
100 	OPT_CALLBACK('i', "image", NULL, "image", "Disk image", img_name_parser),
101 	OPT_STRING('c', "console", &console, "serial or virtio",
102 			"Console to use"),
103 	OPT_BOOLEAN('\0', "virtio-rng", &virtio_rng,
104 			"Enable virtio Random Number Generator"),
105 
106 	OPT_GROUP("Kernel options:"),
107 	OPT_STRING('k', "kernel", &kernel_filename, "kernel",
108 			"Kernel to boot in virtual machine"),
109 	OPT_STRING('r', "initrd", &initrd_filename, "initrd",
110 			"Initial RAM disk image"),
111 	OPT_STRING('p', "params", &kernel_cmdline, "params",
112 			"Kernel command line arguments"),
113 
114 	OPT_GROUP("Networking options:"),
115 	OPT_STRING('n', "network", &network, "virtio",
116 			"Network to use"),
117 	OPT_STRING('\0', "host-ip-addr", &host_ip_addr, "a.b.c.d",
118 			"Assign this address to the host side networking"),
119 	OPT_STRING('\0', "guest-mac", &guest_mac, "aa:bb:cc:dd:ee:ff",
120 			"Assign this address to the guest side NIC"),
121 	OPT_STRING('\0', "tapscript", &script, "Script path",
122 			 "Assign a script to process created tap device"),
123 	OPT_GROUP("Debug options:"),
124 	OPT_STRING('d', "kvm-dev", &kvm_dev, "kvm-dev", "KVM device file"),
125 	OPT_BOOLEAN('s', "single-step", &single_step,
126 			"Enable single stepping"),
127 	OPT_BOOLEAN('g', "ioport-debug", &ioport_debug,
128 			"Enable ioport debugging"),
129 	OPT_END()
130 };
131 
132 static void handle_sigquit(int sig)
133 {
134 	int i;
135 
136 	for (i = 0; i < nrcpus; i++) {
137 		struct kvm_cpu *cpu = kvm_cpus[i];
138 
139 		kvm_cpu__show_registers(cpu);
140 		kvm_cpu__show_code(cpu);
141 		kvm_cpu__show_page_tables(cpu);
142 	}
143 
144 	serial8250__inject_sysrq(kvm);
145 }
146 
147 static void handle_sigalrm(int sig)
148 {
149 	serial8250__inject_interrupt(kvm);
150 	virtio_console__inject_interrupt(kvm);
151 }
152 
153 static void *kvm_cpu_thread(void *arg)
154 {
155 	current_kvm_cpu		= arg;
156 
157 	if (kvm_cpu__start(current_kvm_cpu))
158 		goto panic_kvm;
159 
160 	kvm_cpu__delete(current_kvm_cpu);
161 
162 	return (void *) (intptr_t) 0;
163 
164 panic_kvm:
165 	fprintf(stderr, "KVM exit reason: %" PRIu32 " (\"%s\")\n",
166 		current_kvm_cpu->kvm_run->exit_reason,
167 		kvm_exit_reasons[current_kvm_cpu->kvm_run->exit_reason]);
168 	if (current_kvm_cpu->kvm_run->exit_reason == KVM_EXIT_UNKNOWN)
169 		fprintf(stderr, "KVM exit code: 0x%Lu\n",
170 			current_kvm_cpu->kvm_run->hw.hardware_exit_reason);
171 
172 	kvm_cpu__show_registers(current_kvm_cpu);
173 	kvm_cpu__show_code(current_kvm_cpu);
174 	kvm_cpu__show_page_tables(current_kvm_cpu);
175 
176 	kvm_cpu__delete(current_kvm_cpu);
177 
178 	return (void *) (intptr_t) 1;
179 }
180 
181 static char kernel[PATH_MAX];
182 const char *host_kernels[] = {
183 	"/boot/vmlinuz",
184 	"/boot/bzImage",
185 	NULL
186 };
187 const char *default_kernels[] = {
188 	"./bzImage",
189 	"../../arch/x86/boot/bzImage",
190 	NULL
191 };
192 
193 static void kernel_usage_with_options(void)
194 {
195 	const char **k;
196 	struct utsname uts;
197 
198 	fprintf(stderr, "Fatal: could not find default kernel image in:\n");
199 	k = &default_kernels[0];
200 	while (*k) {
201 		fprintf(stderr, "\t%s\n", *k);
202 		k++;
203 	}
204 
205 	if (uname(&uts) < 0)
206 		return;
207 
208 	k = &host_kernels[0];
209 	while (*k) {
210 		if (snprintf(kernel, PATH_MAX, "%s-%s", *k, uts.release) < 0)
211 			return;
212 		fprintf(stderr, "\t%s\n", kernel);
213 		k++;
214 	}
215 	fprintf(stderr, "\nPlease see 'kvm run --help' for more options.\n\n");
216 }
217 
218 static const char *find_kernel(void)
219 {
220 	const char **k;
221 	struct stat st;
222 	struct utsname uts;
223 
224 	k = &default_kernels[0];
225 	while (*k) {
226 		if (stat(*k, &st) < 0 || !S_ISREG(st.st_mode)) {
227 			k++;
228 			continue;
229 		}
230 		strncpy(kernel, *k, PATH_MAX);
231 		return kernel;
232 	}
233 
234 	if (uname(&uts) < 0)
235 		return NULL;
236 
237 	k = &host_kernels[0];
238 	while (*k) {
239 		if (snprintf(kernel, PATH_MAX, "%s-%s", *k, uts.release) < 0)
240 			return NULL;
241 
242 		if (stat(kernel, &st) < 0 || !S_ISREG(st.st_mode)) {
243 			k++;
244 			continue;
245 		}
246 		return kernel;
247 
248 	}
249 	return NULL;
250 }
251 
252 static int root_device(char *dev, long *part)
253 {
254 	FILE   *fp;
255 	char   *line;
256 	int    tmp;
257 	size_t nr_read;
258 	char   device[PATH_MAX];
259 	char   mnt_pt[PATH_MAX];
260 	char   resolved_path[PATH_MAX];
261 	char   *p;
262 	struct stat st;
263 
264 	fp = fopen("/proc/mounts", "r");
265 	if (!fp)
266 		return -1;
267 
268 	line = NULL;
269 	tmp  = 0;
270 	while (!feof(fp)) {
271 		if (getline(&line, &nr_read, fp) < 0)
272 			break;
273 		sscanf(line, "%s %s", device, mnt_pt);
274 		if (!strncmp(device, "/dev", 4) && !strcmp(mnt_pt, "/")) {
275 			tmp = 1;
276 			break;
277 		}
278 	}
279 	fclose(fp);
280 	free(line);
281 
282 	if (!tmp)
283 		return -1;
284 
285 	/* get the absolute path */
286 	if (!realpath(device, resolved_path))
287 		return -1;
288 
289 	/* find the partition number */
290 	p = resolved_path;
291 	while (*p) {
292 		if (isdigit(*p)) {
293 			strncpy(dev, resolved_path, p - resolved_path);
294 			*part = atol(p);
295 			break;
296 		}
297 		p++;
298 	}
299 
300 	/* verify the device path */
301 	if (stat(dev, &st) < 0)
302 		return -1;
303 
304 	if (access(dev, R_OK) < 0)
305 		return -1;
306 
307 	return 0;
308 }
309 
310 static char *host_image(char *cmd_line, size_t size)
311 {
312 	char *t;
313 	char device[PATH_MAX];
314 	long part = 0;
315 
316 	t = malloc(PATH_MAX);
317 	if (!t)
318 		return NULL;
319 
320 	/* check for the root file system */
321 	if (root_device(device, &part) < 0) {
322 		free(t);
323 		return NULL;
324 	}
325 	strncpy(t, device, PATH_MAX);
326 	if (!strstr(cmd_line, "root=")) {
327 		char tmp[PATH_MAX];
328 		snprintf(tmp, sizeof(tmp), "root=/dev/vda%ld rw ", part);
329 		strlcat(cmd_line, tmp, size);
330 	}
331 	return t;
332 }
333 
334 int kvm_cmd_run(int argc, const char **argv, const char *prefix)
335 {
336 	static char real_cmdline[2048];
337 	int exit_code = 0;
338 	int i;
339 	struct virtio_net_parameters net_params;
340 	char *hi;
341 	unsigned int nr_online_cpus;
342 
343 	signal(SIGALRM, handle_sigalrm);
344 	signal(SIGQUIT, handle_sigquit);
345 
346 	while (argc != 0) {
347 		argc = parse_options(argc, argv, options, run_usage,
348 				PARSE_OPT_STOP_AT_NON_OPTION);
349 		if (argc != 0) {
350 			if (kernel_filename) {
351 				fprintf(stderr, "Cannot handle parameter: "
352 						"%s\n", argv[0]);
353 				usage_with_options(run_usage, options);
354 				return EINVAL;
355 			}
356 			/* first unhandled parameter is treated as a kernel
357 			   image
358 			 */
359 			kernel_filename = argv[0];
360 			argv++;
361 			argc--;
362 		}
363 
364 	}
365 
366 	if (!kernel_filename)
367 		kernel_filename = find_kernel();
368 
369 	if (!kernel_filename) {
370 		kernel_usage_with_options();
371 		return EINVAL;
372 	}
373 
374 	if (nrcpus < 1 || nrcpus > KVM_NR_CPUS)
375 		die("Number of CPUs %d is out of [1;%d] range", nrcpus, KVM_NR_CPUS);
376 
377 	/* FIXME: Remove as only SMP gets fully supported */
378 	if (nrcpus > 1) {
379 		warning("Limiting CPUs to 1, true SMP is not yet implemented");
380 		nrcpus = 1;
381 	}
382 
383 	if (ram_size < MIN_RAM_SIZE_MB)
384 		die("Not enough memory specified: %lluMB (min %lluMB)", ram_size, MIN_RAM_SIZE_MB);
385 
386 	ram_size <<= MB_SHIFT;
387 
388 	if (!kvm_dev)
389 		kvm_dev = DEFAULT_KVM_DEV;
390 
391 	if (!console)
392 		console = DEFAULT_CONSOLE;
393 
394 	if (!strncmp(console, "virtio", 6))
395 		active_console  = CONSOLE_VIRTIO;
396 	else
397 		active_console  = CONSOLE_8250;
398 
399 	if (!host_ip_addr)
400 		host_ip_addr = DEFAULT_HOST_ADDR;
401 
402 	if (!guest_mac)
403 		guest_mac = DEFAULT_GUEST_MAC;
404 
405 	if (!script)
406 		script = DEFAULT_SCRIPT;
407 
408 	term_init();
409 
410 	kvm = kvm__init(kvm_dev, ram_size);
411 
412 	kvm->nrcpus = nrcpus;
413 
414 	memset(real_cmdline, 0, sizeof(real_cmdline));
415 	strcpy(real_cmdline, "notsc nolapic noacpi pci=conf1 console=ttyS0 ");
416 	if (kernel_cmdline)
417 		strlcat(real_cmdline, kernel_cmdline, sizeof(real_cmdline));
418 
419 	hi = NULL;
420 	if (!image_filename[0]) {
421 		hi = host_image(real_cmdline, sizeof(real_cmdline));
422 		if (hi) {
423 			image_filename[0] = hi;
424 			readonly_image[0] = true;
425 		}
426 	}
427 
428 	if (!strstr(real_cmdline, "root="))
429 		strlcat(real_cmdline, " root=/dev/vda rw ", sizeof(real_cmdline));
430 
431 	for (i = 0; i < image_count; i++) {
432 		if (image_filename[i]) {
433 			struct disk_image *disk = disk_image__open(image_filename[i], readonly_image[i]);
434 			if (!disk)
435 				die("unable to load disk image %s", image_filename[i]);
436 
437 			virtio_blk__init(kvm, disk);
438 		}
439 	}
440 	free(hi);
441 
442 	if (!kvm__load_kernel(kvm, kernel_filename, initrd_filename,
443 				real_cmdline))
444 		die("unable to load kernel %s", kernel_filename);
445 
446 	ioport__setup_legacy();
447 
448 	rtc__init();
449 
450 	kvm__setup_bios(kvm);
451 
452 	serial8250__init(kvm);
453 
454 	pci__init();
455 
456 	virtio_console__init(kvm);
457 
458 	if (virtio_rng)
459 		virtio_rng__init(kvm);
460 
461 	if (!network)
462 		network = DEFAULT_NETWORK;
463 
464 	if (!strncmp(network, "virtio", 6)) {
465 		net_params = (struct virtio_net_parameters) {
466 			.host_ip = host_ip_addr,
467 			.self = kvm,
468 			.script = script
469 		};
470 		sscanf(guest_mac,	"%hhx:%hhx:%hhx:%hhx:%hhx:%hhx",
471 							net_params.guest_mac,
472 							net_params.guest_mac+1,
473 							net_params.guest_mac+2,
474 							net_params.guest_mac+3,
475 							net_params.guest_mac+4,
476 							net_params.guest_mac+5);
477 
478 		virtio_net__init(&net_params);
479 	}
480 
481 	kvm__start_timer(kvm);
482 
483 	for (i = 0; i < nrcpus; i++) {
484 		kvm_cpus[i] = kvm_cpu__init(kvm, i);
485 		if (!kvm_cpus[i])
486 			die("unable to initialize KVM VCPU");
487 
488 		if (single_step)
489 			kvm_cpu__enable_singlestep(kvm_cpus[i]);
490 	}
491 
492 	kvm__init_ram(kvm);
493 
494 	nr_online_cpus = sysconf(_SC_NPROCESSORS_ONLN);
495 	thread_pool__init(nr_online_cpus);
496 
497 	for (i = 0; i < nrcpus; i++) {
498 		if (pthread_create(&kvm_cpus[i]->thread, NULL, kvm_cpu_thread, kvm_cpus[i]) != 0)
499 			die("unable to create KVM VCPU thread");
500 	}
501 
502 	for (i = 0; i < nrcpus; i++) {
503 		void *ret;
504 
505 		if (pthread_join(kvm_cpus[i]->thread, &ret) != 0)
506 			die("pthread_join");
507 
508 		if (ret != NULL)
509 			exit_code	= 1;
510 	}
511 
512 	kvm__delete(kvm);
513 
514 	if (!exit_code)
515 		printf("\n  # KVM session ended normally.\n");
516 
517 	return exit_code;
518 }
519