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