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