xref: /kvmtool/builtin-run.c (revision ca99b3d34022301a54d55d8ca4d00d5721832431)
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 	usage_with_options(run_usage, options);
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 	return 0;
268 }
269 
270 static char *host_image(char *cmd_line, size_t size)
271 {
272 	char *t;
273 	char device[PATH_MAX];
274 	long part = 0;
275 
276 	t = malloc(PATH_MAX);
277 	if (!t)
278 		return NULL;
279 
280 	/* check for the root file system */
281 	if (root_device(device, &part) < 0) {
282 		free(t);
283 		return NULL;
284 	}
285 	strncpy(t, device, PATH_MAX);
286 	if (!strstr(cmd_line, "root=")) {
287 		char tmp[PATH_MAX];
288 		snprintf(tmp, sizeof(tmp), "root=/dev/vda%ld rw ", part);
289 		strlcat(cmd_line, tmp, size);
290 	}
291 	return t;
292 }
293 
294 int kvm_cmd_run(int argc, const char **argv, const char *prefix)
295 {
296 	static char real_cmdline[2048];
297 	int exit_code = 0;
298 	int i;
299 	struct virtio_net_parameters net_params;
300 	char *hi;
301 
302 	signal(SIGALRM, handle_sigalrm);
303 	signal(SIGQUIT, handle_sigquit);
304 
305 	while (argc != 0) {
306 		argc = parse_options(argc, argv, options, run_usage,
307 				PARSE_OPT_STOP_AT_NON_OPTION);
308 		if (argc != 0) {
309 			if (kernel_filename) {
310 				fprintf(stderr, "Cannot handle parameter: "
311 						"%s\n", argv[0]);
312 				usage_with_options(run_usage, options);
313 				return EINVAL;
314 			}
315 			/* first unhandled parameter is treated as a kernel
316 			   image
317 			 */
318 			kernel_filename = argv[0];
319 			argv++;
320 			argc--;
321 		}
322 
323 	}
324 
325 	if (!kernel_filename)
326 		kernel_filename = find_kernel();
327 
328 	if (!kernel_filename) {
329 		kernel_usage_with_options();
330 		return EINVAL;
331 	}
332 
333 	if (nrcpus < 1 || nrcpus > KVM_NR_CPUS)
334 		die("Number of CPUs %d is out of [1;%d] range", nrcpus, KVM_NR_CPUS);
335 
336 	/* FIXME: Remove as only SMP gets fully supported */
337 	if (nrcpus > 1) {
338 		warning("Limiting CPUs to 1, true SMP is not yet implemented");
339 		nrcpus = 1;
340 	}
341 
342 	if (ram_size < MIN_RAM_SIZE_MB)
343 		die("Not enough memory specified: %lluMB (min %lluMB)", ram_size, MIN_RAM_SIZE_MB);
344 
345 	ram_size <<= MB_SHIFT;
346 
347 	if (!kvm_dev)
348 		kvm_dev = DEFAULT_KVM_DEV;
349 
350 	if (!console)
351 		console = DEFAULT_CONSOLE;
352 
353 	if (!strncmp(console, "virtio", 6))
354 		active_console  = CONSOLE_VIRTIO;
355 	else
356 		active_console  = CONSOLE_8250;
357 
358 	if (!host_ip_addr)
359 		host_ip_addr = DEFAULT_HOST_ADDR;
360 
361 	if (!guest_mac)
362 		guest_mac = DEFAULT_GUEST_MAC;
363 
364 	if (!script)
365 		script = DEFAULT_SCRIPT;
366 
367 	term_init();
368 
369 	kvm = kvm__init(kvm_dev, ram_size);
370 
371 	kvm->nrcpus = nrcpus;
372 
373 	memset(real_cmdline, 0, sizeof(real_cmdline));
374 	strcpy(real_cmdline, "notsc nolapic noacpi pci=conf1 console=ttyS0 ");
375 	if (kernel_cmdline)
376 		strlcat(real_cmdline, kernel_cmdline, sizeof(real_cmdline));
377 
378 	hi = NULL;
379 	if (!image_filename) {
380 		hi = host_image(real_cmdline, sizeof(real_cmdline));
381 		if (hi) {
382 			image_filename = hi;
383 			readonly_image = true;
384 		}
385 	}
386 
387 	if (!strstr(real_cmdline, "root="))
388 		strlcat(real_cmdline, " root=/dev/vda rw ", sizeof(real_cmdline));
389 
390 	if (image_filename) {
391 		kvm->disk_image	= disk_image__open(image_filename, readonly_image);
392 		if (!kvm->disk_image)
393 			die("unable to load disk image %s", image_filename);
394 	}
395 	free(hi);
396 
397 	if (!kvm__load_kernel(kvm, kernel_filename, initrd_filename,
398 				real_cmdline))
399 		die("unable to load kernel %s", kernel_filename);
400 
401 	ioport__setup_legacy();
402 
403 	kvm__setup_bios(kvm);
404 
405 	serial8250__init(kvm);
406 
407 	pci__init();
408 
409 	virtio_blk__init(kvm);
410 
411 	virtio_console__init(kvm);
412 
413 	if (!network)
414 		network = DEFAULT_NETWORK;
415 
416 	if (!strncmp(network, "virtio", 6)) {
417 		net_params = (struct virtio_net_parameters) {
418 			.host_ip = host_ip_addr,
419 			.self = kvm,
420 			.script = script
421 		};
422 		sscanf(guest_mac,	"%hhx:%hhx:%hhx:%hhx:%hhx:%hhx",
423 							net_params.guest_mac,
424 							net_params.guest_mac+1,
425 							net_params.guest_mac+2,
426 							net_params.guest_mac+3,
427 							net_params.guest_mac+4,
428 							net_params.guest_mac+5);
429 
430 		virtio_net__init(&net_params);
431 	}
432 
433 	kvm__start_timer(kvm);
434 
435 	for (i = 0; i < nrcpus; i++) {
436 		kvm_cpus[i] = kvm_cpu__init(kvm, i);
437 		if (!kvm_cpus[i])
438 			die("unable to initialize KVM VCPU");
439 
440 		if (single_step)
441 			kvm_cpu__enable_singlestep(kvm_cpus[i]);
442 	}
443 
444 	kvm__init_ram(kvm);
445 
446 	for (i = 0; i < nrcpus; i++) {
447 		if (pthread_create(&kvm_cpus[i]->thread, NULL, kvm_cpu_thread, kvm_cpus[i]) != 0)
448 			die("unable to create KVM VCPU thread");
449 	}
450 
451 	for (i = 0; i < nrcpus; i++) {
452 		void *ret;
453 
454 		if (pthread_join(kvm_cpus[i]->thread, &ret) != 0)
455 			die("pthread_join");
456 
457 		if (ret != NULL)
458 			exit_code	= 1;
459 	}
460 
461 	disk_image__close(kvm->disk_image);
462 	kvm__delete(kvm);
463 
464 	if (!exit_code)
465 		printf("\n  # KVM session ended normally.\n");
466 
467 	return exit_code;
468 }
469