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