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