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