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