Accept elf files that are valid but have sections that can not be mmap'ed for some...
[deliverable/linux.git] / Documentation / lguest / lguest.c
1 /*P:100 This is the Launcher code, a simple program which lays out the
2 * "physical" memory for the new Guest by mapping the kernel image and the
3 * virtual devices, then reads repeatedly from /dev/lguest to run the Guest.
4 *
5 * The only trick: the Makefile links it at a high address so it will be clear
6 * of the guest memory region. It means that each Guest cannot have more than
7 * about 2.5G of memory on a normally configured Host. :*/
8 #define _LARGEFILE64_SOURCE
9 #define _GNU_SOURCE
10 #include <stdio.h>
11 #include <string.h>
12 #include <unistd.h>
13 #include <err.h>
14 #include <stdint.h>
15 #include <stdlib.h>
16 #include <elf.h>
17 #include <sys/mman.h>
18 #include <sys/param.h>
19 #include <sys/types.h>
20 #include <sys/stat.h>
21 #include <sys/wait.h>
22 #include <fcntl.h>
23 #include <stdbool.h>
24 #include <errno.h>
25 #include <ctype.h>
26 #include <sys/socket.h>
27 #include <sys/ioctl.h>
28 #include <sys/time.h>
29 #include <time.h>
30 #include <netinet/in.h>
31 #include <net/if.h>
32 #include <linux/sockios.h>
33 #include <linux/if_tun.h>
34 #include <sys/uio.h>
35 #include <termios.h>
36 #include <getopt.h>
37 #include <zlib.h>
38 /*L:110 We can ignore the 28 include files we need for this program, but I do
39 * want to draw attention to the use of kernel-style types.
40 *
41 * As Linus said, "C is a Spartan language, and so should your naming be." I
42 * like these abbreviations and the header we need uses them, so we define them
43 * here.
44 */
45 typedef unsigned long long u64;
46 typedef uint32_t u32;
47 typedef uint16_t u16;
48 typedef uint8_t u8;
49 #include "linux/lguest_launcher.h"
50 #include "asm-x86/e820.h"
51 /*:*/
52
53 #define PAGE_PRESENT 0x7 /* Present, RW, Execute */
54 #define NET_PEERNUM 1
55 #define BRIDGE_PFX "bridge:"
56 #ifndef SIOCBRADDIF
57 #define SIOCBRADDIF 0x89a2 /* add interface to bridge */
58 #endif
59
60 /*L:120 verbose is both a global flag and a macro. The C preprocessor allows
61 * this, and although I wouldn't recommend it, it works quite nicely here. */
62 static bool verbose;
63 #define verbose(args...) \
64 do { if (verbose) printf(args); } while(0)
65 /*:*/
66
67 /* The pipe to send commands to the waker process */
68 static int waker_fd;
69 /* The top of guest physical memory. */
70 static u32 top;
71
72 /* This is our list of devices. */
73 struct device_list
74 {
75 /* Summary information about the devices in our list: ready to pass to
76 * select() to ask which need servicing.*/
77 fd_set infds;
78 int max_infd;
79
80 /* The descriptor page for the devices. */
81 struct lguest_device_desc *descs;
82
83 /* A single linked list of devices. */
84 struct device *dev;
85 /* ... And an end pointer so we can easily append new devices */
86 struct device **lastdev;
87 };
88
89 /* The device structure describes a single device. */
90 struct device
91 {
92 /* The linked-list pointer. */
93 struct device *next;
94 /* The descriptor for this device, as mapped into the Guest. */
95 struct lguest_device_desc *desc;
96 /* The memory page(s) of this device, if any. Also mapped in Guest. */
97 void *mem;
98
99 /* If handle_input is set, it wants to be called when this file
100 * descriptor is ready. */
101 int fd;
102 bool (*handle_input)(int fd, struct device *me);
103
104 /* If handle_output is set, it wants to be called when the Guest sends
105 * DMA to this key. */
106 unsigned long watch_key;
107 u32 (*handle_output)(int fd, const struct iovec *iov,
108 unsigned int num, struct device *me);
109
110 /* Device-specific data. */
111 void *priv;
112 };
113
114 /*L:130
115 * Loading the Kernel.
116 *
117 * We start with couple of simple helper routines. open_or_die() avoids
118 * error-checking code cluttering the callers: */
119 static int open_or_die(const char *name, int flags)
120 {
121 int fd = open(name, flags);
122 if (fd < 0)
123 err(1, "Failed to open %s", name);
124 return fd;
125 }
126
127 /* map_zeroed_pages() takes a (page-aligned) address and a number of pages. */
128 static void *map_zeroed_pages(unsigned long addr, unsigned int num)
129 {
130 /* We cache the /dev/zero file-descriptor so we only open it once. */
131 static int fd = -1;
132
133 if (fd == -1)
134 fd = open_or_die("/dev/zero", O_RDONLY);
135
136 /* We use a private mapping (ie. if we write to the page, it will be
137 * copied), and obviously we insist that it be mapped where we ask. */
138 if (mmap((void *)addr, getpagesize() * num,
139 PROT_READ|PROT_WRITE|PROT_EXEC, MAP_FIXED|MAP_PRIVATE, fd, 0)
140 != (void *)addr)
141 err(1, "Mmaping %u pages of /dev/zero @%p", num, (void *)addr);
142
143 /* Returning the address is just a courtesy: can simplify callers. */
144 return (void *)addr;
145 }
146
147 /* To find out where to start we look for the magic Guest string, which marks
148 * the code we see in lguest_asm.S. This is a hack which we are currently
149 * plotting to replace with the normal Linux entry point. */
150 static unsigned long entry_point(void *start, void *end,
151 unsigned long page_offset)
152 {
153 void *p;
154
155 /* The scan gives us the physical starting address. We want the
156 * virtual address in this case, and fortunately, we already figured
157 * out the physical-virtual difference and passed it here in
158 * "page_offset". */
159 for (p = start; p < end; p++)
160 if (memcmp(p, "GenuineLguest", strlen("GenuineLguest")) == 0)
161 return (long)p + strlen("GenuineLguest") + page_offset;
162
163 errx(1, "Is this image a genuine lguest?");
164 }
165
166 /* This routine is used to load the kernel or initrd. It tries mmap, but if
167 * that fails (Plan 9's kernel file isn't nicely aligned on page boundaries),
168 * it falls back to reading the memory in. */
169 static void map_at(int fd, void *addr, unsigned long offset, unsigned long len)
170 {
171 ssize_t r;
172
173 /* We map writable even though for some segments are marked read-only.
174 * The kernel really wants to be writable: it patches its own
175 * instructions.
176 *
177 * MAP_PRIVATE means that the page won't be copied until a write is
178 * done to it. This allows us to share untouched memory between
179 * Guests. */
180 if (mmap(addr, len, PROT_READ|PROT_WRITE|PROT_EXEC,
181 MAP_FIXED|MAP_PRIVATE, fd, offset) != MAP_FAILED)
182 return;
183
184 /* pread does a seek and a read in one shot: saves a few lines. */
185 r = pread(fd, addr, len, offset);
186 if (r != len)
187 err(1, "Reading offset %lu len %lu gave %zi", offset, len, r);
188 }
189
190 /* This routine takes an open vmlinux image, which is in ELF, and maps it into
191 * the Guest memory. ELF = Embedded Linking Format, which is the format used
192 * by all modern binaries on Linux including the kernel.
193 *
194 * The ELF headers give *two* addresses: a physical address, and a virtual
195 * address. The Guest kernel expects to be placed in memory at the physical
196 * address, and the page tables set up so it will correspond to that virtual
197 * address. We return the difference between the virtual and physical
198 * addresses in the "page_offset" pointer.
199 *
200 * We return the starting address. */
201 static unsigned long map_elf(int elf_fd, const Elf32_Ehdr *ehdr,
202 unsigned long *page_offset)
203 {
204 Elf32_Phdr phdr[ehdr->e_phnum];
205 unsigned int i;
206 unsigned long start = -1UL, end = 0;
207
208 /* Sanity checks on the main ELF header: an x86 executable with a
209 * reasonable number of correctly-sized program headers. */
210 if (ehdr->e_type != ET_EXEC
211 || ehdr->e_machine != EM_386
212 || ehdr->e_phentsize != sizeof(Elf32_Phdr)
213 || ehdr->e_phnum < 1 || ehdr->e_phnum > 65536U/sizeof(Elf32_Phdr))
214 errx(1, "Malformed elf header");
215
216 /* An ELF executable contains an ELF header and a number of "program"
217 * headers which indicate which parts ("segments") of the program to
218 * load where. */
219
220 /* We read in all the program headers at once: */
221 if (lseek(elf_fd, ehdr->e_phoff, SEEK_SET) < 0)
222 err(1, "Seeking to program headers");
223 if (read(elf_fd, phdr, sizeof(phdr)) != sizeof(phdr))
224 err(1, "Reading program headers");
225
226 /* We don't know page_offset yet. */
227 *page_offset = 0;
228
229 /* Try all the headers: there are usually only three. A read-only one,
230 * a read-write one, and a "note" section which isn't loadable. */
231 for (i = 0; i < ehdr->e_phnum; i++) {
232 /* If this isn't a loadable segment, we ignore it */
233 if (phdr[i].p_type != PT_LOAD)
234 continue;
235
236 verbose("Section %i: size %i addr %p\n",
237 i, phdr[i].p_memsz, (void *)phdr[i].p_paddr);
238
239 /* We expect a simple linear address space: every segment must
240 * have the same difference between virtual (p_vaddr) and
241 * physical (p_paddr) address. */
242 if (!*page_offset)
243 *page_offset = phdr[i].p_vaddr - phdr[i].p_paddr;
244 else if (*page_offset != phdr[i].p_vaddr - phdr[i].p_paddr)
245 errx(1, "Page offset of section %i different", i);
246
247 /* We track the first and last address we mapped, so we can
248 * tell entry_point() where to scan. */
249 if (phdr[i].p_paddr < start)
250 start = phdr[i].p_paddr;
251 if (phdr[i].p_paddr + phdr[i].p_filesz > end)
252 end = phdr[i].p_paddr + phdr[i].p_filesz;
253
254 /* We map this section of the file at its physical address. */
255 map_at(elf_fd, (void *)phdr[i].p_paddr,
256 phdr[i].p_offset, phdr[i].p_filesz);
257 }
258
259 return entry_point((void *)start, (void *)end, *page_offset);
260 }
261
262 /*L:170 Prepare to be SHOCKED and AMAZED. And possibly a trifle nauseated.
263 *
264 * We know that CONFIG_PAGE_OFFSET sets what virtual address the kernel expects
265 * to be. We don't know what that option was, but we can figure it out
266 * approximately by looking at the addresses in the code. I chose the common
267 * case of reading a memory location into the %eax register:
268 *
269 * movl <some-address>, %eax
270 *
271 * This gets encoded as five bytes: "0xA1 <4-byte-address>". For example,
272 * "0xA1 0x18 0x60 0x47 0xC0" reads the address 0xC0476018 into %eax.
273 *
274 * In this example can guess that the kernel was compiled with
275 * CONFIG_PAGE_OFFSET set to 0xC0000000 (it's always a round number). If the
276 * kernel were larger than 16MB, we might see 0xC1 addresses show up, but our
277 * kernel isn't that bloated yet.
278 *
279 * Unfortunately, x86 has variable-length instructions, so finding this
280 * particular instruction properly involves writing a disassembler. Instead,
281 * we rely on statistics. We look for "0xA1" and tally the different bytes
282 * which occur 4 bytes later (the "0xC0" in our example above). When one of
283 * those bytes appears three times, we can be reasonably confident that it
284 * forms the start of CONFIG_PAGE_OFFSET.
285 *
286 * This is amazingly reliable. */
287 static unsigned long intuit_page_offset(unsigned char *img, unsigned long len)
288 {
289 unsigned int i, possibilities[256] = { 0 };
290
291 for (i = 0; i + 4 < len; i++) {
292 /* mov 0xXXXXXXXX,%eax */
293 if (img[i] == 0xA1 && ++possibilities[img[i+4]] > 3)
294 return (unsigned long)img[i+4] << 24;
295 }
296 errx(1, "could not determine page offset");
297 }
298
299 /*L:160 Unfortunately the entire ELF image isn't compressed: the segments
300 * which need loading are extracted and compressed raw. This denies us the
301 * information we need to make a fully-general loader. */
302 static unsigned long unpack_bzimage(int fd, unsigned long *page_offset)
303 {
304 gzFile f;
305 int ret, len = 0;
306 /* A bzImage always gets loaded at physical address 1M. This is
307 * actually configurable as CONFIG_PHYSICAL_START, but as the comment
308 * there says, "Don't change this unless you know what you are doing".
309 * Indeed. */
310 void *img = (void *)0x100000;
311
312 /* gzdopen takes our file descriptor (carefully placed at the start of
313 * the GZIP header we found) and returns a gzFile. */
314 f = gzdopen(fd, "rb");
315 /* We read it into memory in 64k chunks until we hit the end. */
316 while ((ret = gzread(f, img + len, 65536)) > 0)
317 len += ret;
318 if (ret < 0)
319 err(1, "reading image from bzImage");
320
321 verbose("Unpacked size %i addr %p\n", len, img);
322
323 /* Without the ELF header, we can't tell virtual-physical gap. This is
324 * CONFIG_PAGE_OFFSET, and people do actually change it. Fortunately,
325 * I have a clever way of figuring it out from the code itself. */
326 *page_offset = intuit_page_offset(img, len);
327
328 return entry_point(img, img + len, *page_offset);
329 }
330
331 /*L:150 A bzImage, unlike an ELF file, is not meant to be loaded. You're
332 * supposed to jump into it and it will unpack itself. We can't do that
333 * because the Guest can't run the unpacking code, and adding features to
334 * lguest kills puppies, so we don't want to.
335 *
336 * The bzImage is formed by putting the decompressing code in front of the
337 * compressed kernel code. So we can simple scan through it looking for the
338 * first "gzip" header, and start decompressing from there. */
339 static unsigned long load_bzimage(int fd, unsigned long *page_offset)
340 {
341 unsigned char c;
342 int state = 0;
343
344 /* GZIP header is 0x1F 0x8B <method> <flags>... <compressed-by>. */
345 while (read(fd, &c, 1) == 1) {
346 switch (state) {
347 case 0:
348 if (c == 0x1F)
349 state++;
350 break;
351 case 1:
352 if (c == 0x8B)
353 state++;
354 else
355 state = 0;
356 break;
357 case 2 ... 8:
358 state++;
359 break;
360 case 9:
361 /* Seek back to the start of the gzip header. */
362 lseek(fd, -10, SEEK_CUR);
363 /* One final check: "compressed under UNIX". */
364 if (c != 0x03)
365 state = -1;
366 else
367 return unpack_bzimage(fd, page_offset);
368 }
369 }
370 errx(1, "Could not find kernel in bzImage");
371 }
372
373 /*L:140 Loading the kernel is easy when it's a "vmlinux", but most kernels
374 * come wrapped up in the self-decompressing "bzImage" format. With some funky
375 * coding, we can load those, too. */
376 static unsigned long load_kernel(int fd, unsigned long *page_offset)
377 {
378 Elf32_Ehdr hdr;
379
380 /* Read in the first few bytes. */
381 if (read(fd, &hdr, sizeof(hdr)) != sizeof(hdr))
382 err(1, "Reading kernel");
383
384 /* If it's an ELF file, it starts with "\177ELF" */
385 if (memcmp(hdr.e_ident, ELFMAG, SELFMAG) == 0)
386 return map_elf(fd, &hdr, page_offset);
387
388 /* Otherwise we assume it's a bzImage, and try to unpack it */
389 return load_bzimage(fd, page_offset);
390 }
391
392 /* This is a trivial little helper to align pages. Andi Kleen hated it because
393 * it calls getpagesize() twice: "it's dumb code."
394 *
395 * Kernel guys get really het up about optimization, even when it's not
396 * necessary. I leave this code as a reaction against that. */
397 static inline unsigned long page_align(unsigned long addr)
398 {
399 /* Add upwards and truncate downwards. */
400 return ((addr + getpagesize()-1) & ~(getpagesize()-1));
401 }
402
403 /*L:180 An "initial ram disk" is a disk image loaded into memory along with
404 * the kernel which the kernel can use to boot from without needing any
405 * drivers. Most distributions now use this as standard: the initrd contains
406 * the code to load the appropriate driver modules for the current machine.
407 *
408 * Importantly, James Morris works for RedHat, and Fedora uses initrds for its
409 * kernels. He sent me this (and tells me when I break it). */
410 static unsigned long load_initrd(const char *name, unsigned long mem)
411 {
412 int ifd;
413 struct stat st;
414 unsigned long len;
415
416 ifd = open_or_die(name, O_RDONLY);
417 /* fstat() is needed to get the file size. */
418 if (fstat(ifd, &st) < 0)
419 err(1, "fstat() on initrd '%s'", name);
420
421 /* We map the initrd at the top of memory, but mmap wants it to be
422 * page-aligned, so we round the size up for that. */
423 len = page_align(st.st_size);
424 map_at(ifd, (void *)mem - len, 0, st.st_size);
425 /* Once a file is mapped, you can close the file descriptor. It's a
426 * little odd, but quite useful. */
427 close(ifd);
428 verbose("mapped initrd %s size=%lu @ %p\n", name, len, (void*)mem-len);
429
430 /* We return the initrd size. */
431 return len;
432 }
433
434 /* Once we know how much memory we have, and the address the Guest kernel
435 * expects, we can construct simple linear page tables which will get the Guest
436 * far enough into the boot to create its own.
437 *
438 * We lay them out of the way, just below the initrd (which is why we need to
439 * know its size). */
440 static unsigned long setup_pagetables(unsigned long mem,
441 unsigned long initrd_size,
442 unsigned long page_offset)
443 {
444 u32 *pgdir, *linear;
445 unsigned int mapped_pages, i, linear_pages;
446 unsigned int ptes_per_page = getpagesize()/sizeof(u32);
447
448 /* Ideally we map all physical memory starting at page_offset.
449 * However, if page_offset is 0xC0000000 we can only map 1G of physical
450 * (0xC0000000 + 1G overflows). */
451 if (mem <= -page_offset)
452 mapped_pages = mem/getpagesize();
453 else
454 mapped_pages = -page_offset/getpagesize();
455
456 /* Each PTE page can map ptes_per_page pages: how many do we need? */
457 linear_pages = (mapped_pages + ptes_per_page-1)/ptes_per_page;
458
459 /* We put the toplevel page directory page at the top of memory. */
460 pgdir = (void *)mem - initrd_size - getpagesize();
461
462 /* Now we use the next linear_pages pages as pte pages */
463 linear = (void *)pgdir - linear_pages*getpagesize();
464
465 /* Linear mapping is easy: put every page's address into the mapping in
466 * order. PAGE_PRESENT contains the flags Present, Writable and
467 * Executable. */
468 for (i = 0; i < mapped_pages; i++)
469 linear[i] = ((i * getpagesize()) | PAGE_PRESENT);
470
471 /* The top level points to the linear page table pages above. The
472 * entry representing page_offset points to the first one, and they
473 * continue from there. */
474 for (i = 0; i < mapped_pages; i += ptes_per_page) {
475 pgdir[(i + page_offset/getpagesize())/ptes_per_page]
476 = (((u32)linear + i*sizeof(u32)) | PAGE_PRESENT);
477 }
478
479 verbose("Linear mapping of %u pages in %u pte pages at %p\n",
480 mapped_pages, linear_pages, linear);
481
482 /* We return the top level (guest-physical) address: the kernel needs
483 * to know where it is. */
484 return (unsigned long)pgdir;
485 }
486
487 /* Simple routine to roll all the commandline arguments together with spaces
488 * between them. */
489 static void concat(char *dst, char *args[])
490 {
491 unsigned int i, len = 0;
492
493 for (i = 0; args[i]; i++) {
494 strcpy(dst+len, args[i]);
495 strcat(dst+len, " ");
496 len += strlen(args[i]) + 1;
497 }
498 /* In case it's empty. */
499 dst[len] = '\0';
500 }
501
502 /* This is where we actually tell the kernel to initialize the Guest. We saw
503 * the arguments it expects when we looked at initialize() in lguest_user.c:
504 * the top physical page to allow, the top level pagetable, the entry point and
505 * the page_offset constant for the Guest. */
506 static int tell_kernel(u32 pgdir, u32 start, u32 page_offset)
507 {
508 u32 args[] = { LHREQ_INITIALIZE,
509 top/getpagesize(), pgdir, start, page_offset };
510 int fd;
511
512 fd = open_or_die("/dev/lguest", O_RDWR);
513 if (write(fd, args, sizeof(args)) < 0)
514 err(1, "Writing to /dev/lguest");
515
516 /* We return the /dev/lguest file descriptor to control this Guest */
517 return fd;
518 }
519 /*:*/
520
521 static void set_fd(int fd, struct device_list *devices)
522 {
523 FD_SET(fd, &devices->infds);
524 if (fd > devices->max_infd)
525 devices->max_infd = fd;
526 }
527
528 /*L:200
529 * The Waker.
530 *
531 * With a console and network devices, we can have lots of input which we need
532 * to process. We could try to tell the kernel what file descriptors to watch,
533 * but handing a file descriptor mask through to the kernel is fairly icky.
534 *
535 * Instead, we fork off a process which watches the file descriptors and writes
536 * the LHREQ_BREAK command to the /dev/lguest filedescriptor to tell the Host
537 * loop to stop running the Guest. This causes it to return from the
538 * /dev/lguest read with -EAGAIN, where it will write to /dev/lguest to reset
539 * the LHREQ_BREAK and wake us up again.
540 *
541 * This, of course, is merely a different *kind* of icky.
542 */
543 static void wake_parent(int pipefd, int lguest_fd, struct device_list *devices)
544 {
545 /* Add the pipe from the Launcher to the fdset in the device_list, so
546 * we watch it, too. */
547 set_fd(pipefd, devices);
548
549 for (;;) {
550 fd_set rfds = devices->infds;
551 u32 args[] = { LHREQ_BREAK, 1 };
552
553 /* Wait until input is ready from one of the devices. */
554 select(devices->max_infd+1, &rfds, NULL, NULL, NULL);
555 /* Is it a message from the Launcher? */
556 if (FD_ISSET(pipefd, &rfds)) {
557 int ignorefd;
558 /* If read() returns 0, it means the Launcher has
559 * exited. We silently follow. */
560 if (read(pipefd, &ignorefd, sizeof(ignorefd)) == 0)
561 exit(0);
562 /* Otherwise it's telling us there's a problem with one
563 * of the devices, and we should ignore that file
564 * descriptor from now on. */
565 FD_CLR(ignorefd, &devices->infds);
566 } else /* Send LHREQ_BREAK command. */
567 write(lguest_fd, args, sizeof(args));
568 }
569 }
570
571 /* This routine just sets up a pipe to the Waker process. */
572 static int setup_waker(int lguest_fd, struct device_list *device_list)
573 {
574 int pipefd[2], child;
575
576 /* We create a pipe to talk to the waker, and also so it knows when the
577 * Launcher dies (and closes pipe). */
578 pipe(pipefd);
579 child = fork();
580 if (child == -1)
581 err(1, "forking");
582
583 if (child == 0) {
584 /* Close the "writing" end of our copy of the pipe */
585 close(pipefd[1]);
586 wake_parent(pipefd[0], lguest_fd, device_list);
587 }
588 /* Close the reading end of our copy of the pipe. */
589 close(pipefd[0]);
590
591 /* Here is the fd used to talk to the waker. */
592 return pipefd[1];
593 }
594
595 /*L:210
596 * Device Handling.
597 *
598 * When the Guest sends DMA to us, it sends us an array of addresses and sizes.
599 * We need to make sure it's not trying to reach into the Launcher itself, so
600 * we have a convenient routine which check it and exits with an error message
601 * if something funny is going on:
602 */
603 static void *_check_pointer(unsigned long addr, unsigned int size,
604 unsigned int line)
605 {
606 /* We have to separately check addr and addr+size, because size could
607 * be huge and addr + size might wrap around. */
608 if (addr >= top || addr + size >= top)
609 errx(1, "%s:%i: Invalid address %li", __FILE__, line, addr);
610 /* We return a pointer for the caller's convenience, now we know it's
611 * safe to use. */
612 return (void *)addr;
613 }
614 /* A macro which transparently hands the line number to the real function. */
615 #define check_pointer(addr,size) _check_pointer(addr, size, __LINE__)
616
617 /* The Guest has given us the address of a "struct lguest_dma". We check it's
618 * OK and convert it to an iovec (which is a simple array of ptr/size
619 * pairs). */
620 static u32 *dma2iov(unsigned long dma, struct iovec iov[], unsigned *num)
621 {
622 unsigned int i;
623 struct lguest_dma *udma;
624
625 /* First we make sure that the array memory itself is valid. */
626 udma = check_pointer(dma, sizeof(*udma));
627 /* Now we check each element */
628 for (i = 0; i < LGUEST_MAX_DMA_SECTIONS; i++) {
629 /* A zero length ends the array. */
630 if (!udma->len[i])
631 break;
632
633 iov[i].iov_base = check_pointer(udma->addr[i], udma->len[i]);
634 iov[i].iov_len = udma->len[i];
635 }
636 *num = i;
637
638 /* We return the pointer to where the caller should write the amount of
639 * the buffer used. */
640 return &udma->used_len;
641 }
642
643 /* This routine gets a DMA buffer from the Guest for a given key, and converts
644 * it to an iovec array. It returns the interrupt the Guest wants when we're
645 * finished, and a pointer to the "used_len" field to fill in. */
646 static u32 *get_dma_buffer(int fd, void *key,
647 struct iovec iov[], unsigned int *num, u32 *irq)
648 {
649 u32 buf[] = { LHREQ_GETDMA, (u32)key };
650 unsigned long udma;
651 u32 *res;
652
653 /* Ask the kernel for a DMA buffer corresponding to this key. */
654 udma = write(fd, buf, sizeof(buf));
655 /* They haven't registered any, or they're all used? */
656 if (udma == (unsigned long)-1)
657 return NULL;
658
659 /* Convert it into our iovec array */
660 res = dma2iov(udma, iov, num);
661 /* The kernel stashes irq in ->used_len to get it out to us. */
662 *irq = *res;
663 /* Return a pointer to ((struct lguest_dma *)udma)->used_len. */
664 return res;
665 }
666
667 /* This is a convenient routine to send the Guest an interrupt. */
668 static void trigger_irq(int fd, u32 irq)
669 {
670 u32 buf[] = { LHREQ_IRQ, irq };
671 if (write(fd, buf, sizeof(buf)) != 0)
672 err(1, "Triggering irq %i", irq);
673 }
674
675 /* This simply sets up an iovec array where we can put data to be discarded.
676 * This happens when the Guest doesn't want or can't handle the input: we have
677 * to get rid of it somewhere, and if we bury it in the ceiling space it will
678 * start to smell after a week. */
679 static void discard_iovec(struct iovec *iov, unsigned int *num)
680 {
681 static char discard_buf[1024];
682 *num = 1;
683 iov->iov_base = discard_buf;
684 iov->iov_len = sizeof(discard_buf);
685 }
686
687 /* Here is the input terminal setting we save, and the routine to restore them
688 * on exit so the user can see what they type next. */
689 static struct termios orig_term;
690 static void restore_term(void)
691 {
692 tcsetattr(STDIN_FILENO, TCSANOW, &orig_term);
693 }
694
695 /* We associate some data with the console for our exit hack. */
696 struct console_abort
697 {
698 /* How many times have they hit ^C? */
699 int count;
700 /* When did they start? */
701 struct timeval start;
702 };
703
704 /* This is the routine which handles console input (ie. stdin). */
705 static bool handle_console_input(int fd, struct device *dev)
706 {
707 u32 irq = 0, *lenp;
708 int len;
709 unsigned int num;
710 struct iovec iov[LGUEST_MAX_DMA_SECTIONS];
711 struct console_abort *abort = dev->priv;
712
713 /* First we get the console buffer from the Guest. The key is dev->mem
714 * which was set to 0 in setup_console(). */
715 lenp = get_dma_buffer(fd, dev->mem, iov, &num, &irq);
716 if (!lenp) {
717 /* If it's not ready for input, warn and set up to discard. */
718 warn("console: no dma buffer!");
719 discard_iovec(iov, &num);
720 }
721
722 /* This is why we convert to iovecs: the readv() call uses them, and so
723 * it reads straight into the Guest's buffer. */
724 len = readv(dev->fd, iov, num);
725 if (len <= 0) {
726 /* This implies that the console is closed, is /dev/null, or
727 * something went terribly wrong. We still go through the rest
728 * of the logic, though, especially the exit handling below. */
729 warnx("Failed to get console input, ignoring console.");
730 len = 0;
731 }
732
733 /* If we read the data into the Guest, fill in the length and send the
734 * interrupt. */
735 if (lenp) {
736 *lenp = len;
737 trigger_irq(fd, irq);
738 }
739
740 /* Three ^C within one second? Exit.
741 *
742 * This is such a hack, but works surprisingly well. Each ^C has to be
743 * in a buffer by itself, so they can't be too fast. But we check that
744 * we get three within about a second, so they can't be too slow. */
745 if (len == 1 && ((char *)iov[0].iov_base)[0] == 3) {
746 if (!abort->count++)
747 gettimeofday(&abort->start, NULL);
748 else if (abort->count == 3) {
749 struct timeval now;
750 gettimeofday(&now, NULL);
751 if (now.tv_sec <= abort->start.tv_sec+1) {
752 u32 args[] = { LHREQ_BREAK, 0 };
753 /* Close the fd so Waker will know it has to
754 * exit. */
755 close(waker_fd);
756 /* Just in case waker is blocked in BREAK, send
757 * unbreak now. */
758 write(fd, args, sizeof(args));
759 exit(2);
760 }
761 abort->count = 0;
762 }
763 } else
764 /* Any other key resets the abort counter. */
765 abort->count = 0;
766
767 /* Now, if we didn't read anything, put the input terminal back and
768 * return failure (meaning, don't call us again). */
769 if (!len) {
770 restore_term();
771 return false;
772 }
773 /* Everything went OK! */
774 return true;
775 }
776
777 /* Handling console output is much simpler than input. */
778 static u32 handle_console_output(int fd, const struct iovec *iov,
779 unsigned num, struct device*dev)
780 {
781 /* Whatever the Guest sends, write it to standard output. Return the
782 * number of bytes written. */
783 return writev(STDOUT_FILENO, iov, num);
784 }
785
786 /* Guest->Host network output is also pretty easy. */
787 static u32 handle_tun_output(int fd, const struct iovec *iov,
788 unsigned num, struct device *dev)
789 {
790 /* We put a flag in the "priv" pointer of the network device, and set
791 * it as soon as we see output. We'll see why in handle_tun_input() */
792 *(bool *)dev->priv = true;
793 /* Whatever packet the Guest sent us, write it out to the tun
794 * device. */
795 return writev(dev->fd, iov, num);
796 }
797
798 /* This matches the peer_key() in lguest_net.c. The key for any given slot
799 * is the address of the network device's page plus 4 * the slot number. */
800 static unsigned long peer_offset(unsigned int peernum)
801 {
802 return 4 * peernum;
803 }
804
805 /* This is where we handle a packet coming in from the tun device */
806 static bool handle_tun_input(int fd, struct device *dev)
807 {
808 u32 irq = 0, *lenp;
809 int len;
810 unsigned num;
811 struct iovec iov[LGUEST_MAX_DMA_SECTIONS];
812
813 /* First we get a buffer the Guest has bound to its key. */
814 lenp = get_dma_buffer(fd, dev->mem+peer_offset(NET_PEERNUM), iov, &num,
815 &irq);
816 if (!lenp) {
817 /* Now, it's expected that if we try to send a packet too
818 * early, the Guest won't be ready yet. This is why we set a
819 * flag when the Guest sends its first packet. If it's sent a
820 * packet we assume it should be ready to receive them.
821 *
822 * Actually, this is what the status bits in the descriptor are
823 * for: we should *use* them. FIXME! */
824 if (*(bool *)dev->priv)
825 warn("network: no dma buffer!");
826 discard_iovec(iov, &num);
827 }
828
829 /* Read the packet from the device directly into the Guest's buffer. */
830 len = readv(dev->fd, iov, num);
831 if (len <= 0)
832 err(1, "reading network");
833
834 /* Write the used_len, and trigger the interrupt for the Guest */
835 if (lenp) {
836 *lenp = len;
837 trigger_irq(fd, irq);
838 }
839 verbose("tun input packet len %i [%02x %02x] (%s)\n", len,
840 ((u8 *)iov[0].iov_base)[0], ((u8 *)iov[0].iov_base)[1],
841 lenp ? "sent" : "discarded");
842 /* All good. */
843 return true;
844 }
845
846 /* The last device handling routine is block output: the Guest has sent a DMA
847 * to the block device. It will have placed the command it wants in the
848 * "struct lguest_block_page". */
849 static u32 handle_block_output(int fd, const struct iovec *iov,
850 unsigned num, struct device *dev)
851 {
852 struct lguest_block_page *p = dev->mem;
853 u32 irq, *lenp;
854 unsigned int len, reply_num;
855 struct iovec reply[LGUEST_MAX_DMA_SECTIONS];
856 off64_t device_len, off = (off64_t)p->sector * 512;
857
858 /* First we extract the device length from the dev->priv pointer. */
859 device_len = *(off64_t *)dev->priv;
860
861 /* We first check that the read or write is within the length of the
862 * block file. */
863 if (off >= device_len)
864 errx(1, "Bad offset %llu vs %llu", off, device_len);
865 /* Move to the right location in the block file. This shouldn't fail,
866 * but best to check. */
867 if (lseek64(dev->fd, off, SEEK_SET) != off)
868 err(1, "Bad seek to sector %i", p->sector);
869
870 verbose("Block: %s at offset %llu\n", p->type ? "WRITE" : "READ", off);
871
872 /* They were supposed to bind a reply buffer at key equal to the start
873 * of the block device memory. We need this to tell them when the
874 * request is finished. */
875 lenp = get_dma_buffer(fd, dev->mem, reply, &reply_num, &irq);
876 if (!lenp)
877 err(1, "Block request didn't give us a dma buffer");
878
879 if (p->type) {
880 /* A write request. The DMA they sent contained the data, so
881 * write it out. */
882 len = writev(dev->fd, iov, num);
883 /* Grr... Now we know how long the "struct lguest_dma" they
884 * sent was, we make sure they didn't try to write over the end
885 * of the block file (possibly extending it). */
886 if (off + len > device_len) {
887 /* Trim it back to the correct length */
888 ftruncate64(dev->fd, device_len);
889 /* Die, bad Guest, die. */
890 errx(1, "Write past end %llu+%u", off, len);
891 }
892 /* The reply length is 0: we just send back an empty DMA to
893 * interrupt them and tell them the write is finished. */
894 *lenp = 0;
895 } else {
896 /* A read request. They sent an empty DMA to start the
897 * request, and we put the read contents into the reply
898 * buffer. */
899 len = readv(dev->fd, reply, reply_num);
900 *lenp = len;
901 }
902
903 /* The result is 1 (done), 2 if there was an error (short read or
904 * write). */
905 p->result = 1 + (p->bytes != len);
906 /* Now tell them we've used their reply buffer. */
907 trigger_irq(fd, irq);
908
909 /* We're supposed to return the number of bytes of the output buffer we
910 * used. But the block device uses the "result" field instead, so we
911 * don't bother. */
912 return 0;
913 }
914
915 /* This is the generic routine we call when the Guest sends some DMA out. */
916 static void handle_output(int fd, unsigned long dma, unsigned long key,
917 struct device_list *devices)
918 {
919 struct device *i;
920 u32 *lenp;
921 struct iovec iov[LGUEST_MAX_DMA_SECTIONS];
922 unsigned num = 0;
923
924 /* Convert the "struct lguest_dma" they're sending to a "struct
925 * iovec". */
926 lenp = dma2iov(dma, iov, &num);
927
928 /* Check each device: if they expect output to this key, tell them to
929 * handle it. */
930 for (i = devices->dev; i; i = i->next) {
931 if (i->handle_output && key == i->watch_key) {
932 /* We write the result straight into the used_len field
933 * for them. */
934 *lenp = i->handle_output(fd, iov, num, i);
935 return;
936 }
937 }
938
939 /* This can happen: the kernel sends any SEND_DMA which doesn't match
940 * another Guest to us. It could be that another Guest just left a
941 * network, for example. But it's unusual. */
942 warnx("Pending dma %p, key %p", (void *)dma, (void *)key);
943 }
944
945 /* This is called when the waker wakes us up: check for incoming file
946 * descriptors. */
947 static void handle_input(int fd, struct device_list *devices)
948 {
949 /* select() wants a zeroed timeval to mean "don't wait". */
950 struct timeval poll = { .tv_sec = 0, .tv_usec = 0 };
951
952 for (;;) {
953 struct device *i;
954 fd_set fds = devices->infds;
955
956 /* If nothing is ready, we're done. */
957 if (select(devices->max_infd+1, &fds, NULL, NULL, &poll) == 0)
958 break;
959
960 /* Otherwise, call the device(s) which have readable
961 * file descriptors and a method of handling them. */
962 for (i = devices->dev; i; i = i->next) {
963 if (i->handle_input && FD_ISSET(i->fd, &fds)) {
964 /* If handle_input() returns false, it means we
965 * should no longer service it.
966 * handle_console_input() does this. */
967 if (!i->handle_input(fd, i)) {
968 /* Clear it from the set of input file
969 * descriptors kept at the head of the
970 * device list. */
971 FD_CLR(i->fd, &devices->infds);
972 /* Tell waker to ignore it too... */
973 write(waker_fd, &i->fd, sizeof(i->fd));
974 }
975 }
976 }
977 }
978 }
979
980 /*L:190
981 * Device Setup
982 *
983 * All devices need a descriptor so the Guest knows it exists, and a "struct
984 * device" so the Launcher can keep track of it. We have common helper
985 * routines to allocate them.
986 *
987 * This routine allocates a new "struct lguest_device_desc" from descriptor
988 * table in the devices array just above the Guest's normal memory. */
989 static struct lguest_device_desc *
990 new_dev_desc(struct lguest_device_desc *descs,
991 u16 type, u16 features, u16 num_pages)
992 {
993 unsigned int i;
994
995 for (i = 0; i < LGUEST_MAX_DEVICES; i++) {
996 if (!descs[i].type) {
997 descs[i].type = type;
998 descs[i].features = features;
999 descs[i].num_pages = num_pages;
1000 /* If they said the device needs memory, we allocate
1001 * that now, bumping up the top of Guest memory. */
1002 if (num_pages) {
1003 map_zeroed_pages(top, num_pages);
1004 descs[i].pfn = top/getpagesize();
1005 top += num_pages*getpagesize();
1006 }
1007 return &descs[i];
1008 }
1009 }
1010 errx(1, "too many devices");
1011 }
1012
1013 /* This monster routine does all the creation and setup of a new device,
1014 * including caling new_dev_desc() to allocate the descriptor and device
1015 * memory. */
1016 static struct device *new_device(struct device_list *devices,
1017 u16 type, u16 num_pages, u16 features,
1018 int fd,
1019 bool (*handle_input)(int, struct device *),
1020 unsigned long watch_off,
1021 u32 (*handle_output)(int,
1022 const struct iovec *,
1023 unsigned,
1024 struct device *))
1025 {
1026 struct device *dev = malloc(sizeof(*dev));
1027
1028 /* Append to device list. Prepending to a single-linked list is
1029 * easier, but the user expects the devices to be arranged on the bus
1030 * in command-line order. The first network device on the command line
1031 * is eth0, the first block device /dev/lgba, etc. */
1032 *devices->lastdev = dev;
1033 dev->next = NULL;
1034 devices->lastdev = &dev->next;
1035
1036 /* Now we populate the fields one at a time. */
1037 dev->fd = fd;
1038 /* If we have an input handler for this file descriptor, then we add it
1039 * to the device_list's fdset and maxfd. */
1040 if (handle_input)
1041 set_fd(dev->fd, devices);
1042 dev->desc = new_dev_desc(devices->descs, type, features, num_pages);
1043 dev->mem = (void *)(dev->desc->pfn * getpagesize());
1044 dev->handle_input = handle_input;
1045 dev->watch_key = (unsigned long)dev->mem + watch_off;
1046 dev->handle_output = handle_output;
1047 return dev;
1048 }
1049
1050 /* Our first setup routine is the console. It's a fairly simple device, but
1051 * UNIX tty handling makes it uglier than it could be. */
1052 static void setup_console(struct device_list *devices)
1053 {
1054 struct device *dev;
1055
1056 /* If we can save the initial standard input settings... */
1057 if (tcgetattr(STDIN_FILENO, &orig_term) == 0) {
1058 struct termios term = orig_term;
1059 /* Then we turn off echo, line buffering and ^C etc. We want a
1060 * raw input stream to the Guest. */
1061 term.c_lflag &= ~(ISIG|ICANON|ECHO);
1062 tcsetattr(STDIN_FILENO, TCSANOW, &term);
1063 /* If we exit gracefully, the original settings will be
1064 * restored so the user can see what they're typing. */
1065 atexit(restore_term);
1066 }
1067
1068 /* We don't currently require any memory for the console, so we ask for
1069 * 0 pages. */
1070 dev = new_device(devices, LGUEST_DEVICE_T_CONSOLE, 0, 0,
1071 STDIN_FILENO, handle_console_input,
1072 LGUEST_CONSOLE_DMA_KEY, handle_console_output);
1073 /* We store the console state in dev->priv, and initialize it. */
1074 dev->priv = malloc(sizeof(struct console_abort));
1075 ((struct console_abort *)dev->priv)->count = 0;
1076 verbose("device %p: console\n",
1077 (void *)(dev->desc->pfn * getpagesize()));
1078 }
1079
1080 /* Setting up a block file is also fairly straightforward. */
1081 static void setup_block_file(const char *filename, struct device_list *devices)
1082 {
1083 int fd;
1084 struct device *dev;
1085 off64_t *device_len;
1086 struct lguest_block_page *p;
1087
1088 /* We open with O_LARGEFILE because otherwise we get stuck at 2G. We
1089 * open with O_DIRECT because otherwise our benchmarks go much too
1090 * fast. */
1091 fd = open_or_die(filename, O_RDWR|O_LARGEFILE|O_DIRECT);
1092
1093 /* We want one page, and have no input handler (the block file never
1094 * has anything interesting to say to us). Our timing will be quite
1095 * random, so it should be a reasonable randomness source. */
1096 dev = new_device(devices, LGUEST_DEVICE_T_BLOCK, 1,
1097 LGUEST_DEVICE_F_RANDOMNESS,
1098 fd, NULL, 0, handle_block_output);
1099
1100 /* We store the device size in the private area */
1101 device_len = dev->priv = malloc(sizeof(*device_len));
1102 /* This is the safe way of establishing the size of our device: it
1103 * might be a normal file or an actual block device like /dev/hdb. */
1104 *device_len = lseek64(fd, 0, SEEK_END);
1105
1106 /* The device memory is a "struct lguest_block_page". It's zeroed
1107 * already, we just need to put in the device size. Block devices
1108 * think in sectors (ie. 512 byte chunks), so we translate here. */
1109 p = dev->mem;
1110 p->num_sectors = *device_len/512;
1111 verbose("device %p: block %i sectors\n",
1112 (void *)(dev->desc->pfn * getpagesize()), p->num_sectors);
1113 }
1114
1115 /*
1116 * Network Devices.
1117 *
1118 * Setting up network devices is quite a pain, because we have three types.
1119 * First, we have the inter-Guest network. This is a file which is mapped into
1120 * the address space of the Guests who are on the network. Because it is a
1121 * shared mapping, the same page underlies all the devices, and they can send
1122 * DMA to each other.
1123 *
1124 * Remember from our network driver, the Guest is told what slot in the page it
1125 * is to use. We use exclusive fnctl locks to reserve a slot. If another
1126 * Guest is using a slot, the lock will fail and we try another. Because fnctl
1127 * locks are cleaned up automatically when we die, this cleverly means that our
1128 * reservation on the slot will vanish if we crash. */
1129 static unsigned int find_slot(int netfd, const char *filename)
1130 {
1131 struct flock fl;
1132
1133 fl.l_type = F_WRLCK;
1134 fl.l_whence = SEEK_SET;
1135 fl.l_len = 1;
1136 /* Try a 1 byte lock in each possible position number */
1137 for (fl.l_start = 0;
1138 fl.l_start < getpagesize()/sizeof(struct lguest_net);
1139 fl.l_start++) {
1140 /* If we succeed, return the slot number. */
1141 if (fcntl(netfd, F_SETLK, &fl) == 0)
1142 return fl.l_start;
1143 }
1144 errx(1, "No free slots in network file %s", filename);
1145 }
1146
1147 /* This function sets up the network file */
1148 static void setup_net_file(const char *filename,
1149 struct device_list *devices)
1150 {
1151 int netfd;
1152 struct device *dev;
1153
1154 /* We don't use open_or_die() here: for friendliness we create the file
1155 * if it doesn't already exist. */
1156 netfd = open(filename, O_RDWR, 0);
1157 if (netfd < 0) {
1158 if (errno == ENOENT) {
1159 netfd = open(filename, O_RDWR|O_CREAT, 0600);
1160 if (netfd >= 0) {
1161 /* If we succeeded, initialize the file with a
1162 * blank page. */
1163 char page[getpagesize()];
1164 memset(page, 0, sizeof(page));
1165 write(netfd, page, sizeof(page));
1166 }
1167 }
1168 if (netfd < 0)
1169 err(1, "cannot open net file '%s'", filename);
1170 }
1171
1172 /* We need 1 page, and the features indicate the slot to use and that
1173 * no checksum is needed. We never touch this device again; it's
1174 * between the Guests on the network, so we don't register input or
1175 * output handlers. */
1176 dev = new_device(devices, LGUEST_DEVICE_T_NET, 1,
1177 find_slot(netfd, filename)|LGUEST_NET_F_NOCSUM,
1178 -1, NULL, 0, NULL);
1179
1180 /* Map the shared file. */
1181 if (mmap(dev->mem, getpagesize(), PROT_READ|PROT_WRITE,
1182 MAP_FIXED|MAP_SHARED, netfd, 0) != dev->mem)
1183 err(1, "could not mmap '%s'", filename);
1184 verbose("device %p: shared net %s, peer %i\n",
1185 (void *)(dev->desc->pfn * getpagesize()), filename,
1186 dev->desc->features & ~LGUEST_NET_F_NOCSUM);
1187 }
1188 /*:*/
1189
1190 static u32 str2ip(const char *ipaddr)
1191 {
1192 unsigned int byte[4];
1193
1194 sscanf(ipaddr, "%u.%u.%u.%u", &byte[0], &byte[1], &byte[2], &byte[3]);
1195 return (byte[0] << 24) | (byte[1] << 16) | (byte[2] << 8) | byte[3];
1196 }
1197
1198 /* This code is "adapted" from libbridge: it attaches the Host end of the
1199 * network device to the bridge device specified by the command line.
1200 *
1201 * This is yet another James Morris contribution (I'm an IP-level guy, so I
1202 * dislike bridging), and I just try not to break it. */
1203 static void add_to_bridge(int fd, const char *if_name, const char *br_name)
1204 {
1205 int ifidx;
1206 struct ifreq ifr;
1207
1208 if (!*br_name)
1209 errx(1, "must specify bridge name");
1210
1211 ifidx = if_nametoindex(if_name);
1212 if (!ifidx)
1213 errx(1, "interface %s does not exist!", if_name);
1214
1215 strncpy(ifr.ifr_name, br_name, IFNAMSIZ);
1216 ifr.ifr_ifindex = ifidx;
1217 if (ioctl(fd, SIOCBRADDIF, &ifr) < 0)
1218 err(1, "can't add %s to bridge %s", if_name, br_name);
1219 }
1220
1221 /* This sets up the Host end of the network device with an IP address, brings
1222 * it up so packets will flow, the copies the MAC address into the hwaddr
1223 * pointer (in practice, the Host's slot in the network device's memory). */
1224 static void configure_device(int fd, const char *devname, u32 ipaddr,
1225 unsigned char hwaddr[6])
1226 {
1227 struct ifreq ifr;
1228 struct sockaddr_in *sin = (struct sockaddr_in *)&ifr.ifr_addr;
1229
1230 /* Don't read these incantations. Just cut & paste them like I did! */
1231 memset(&ifr, 0, sizeof(ifr));
1232 strcpy(ifr.ifr_name, devname);
1233 sin->sin_family = AF_INET;
1234 sin->sin_addr.s_addr = htonl(ipaddr);
1235 if (ioctl(fd, SIOCSIFADDR, &ifr) != 0)
1236 err(1, "Setting %s interface address", devname);
1237 ifr.ifr_flags = IFF_UP;
1238 if (ioctl(fd, SIOCSIFFLAGS, &ifr) != 0)
1239 err(1, "Bringing interface %s up", devname);
1240
1241 /* SIOC stands for Socket I/O Control. G means Get (vs S for Set
1242 * above). IF means Interface, and HWADDR is hardware address.
1243 * Simple! */
1244 if (ioctl(fd, SIOCGIFHWADDR, &ifr) != 0)
1245 err(1, "getting hw address for %s", devname);
1246 memcpy(hwaddr, ifr.ifr_hwaddr.sa_data, 6);
1247 }
1248
1249 /*L:195 The other kind of network is a Host<->Guest network. This can either
1250 * use briding or routing, but the principle is the same: it uses the "tun"
1251 * device to inject packets into the Host as if they came in from a normal
1252 * network card. We just shunt packets between the Guest and the tun
1253 * device. */
1254 static void setup_tun_net(const char *arg, struct device_list *devices)
1255 {
1256 struct device *dev;
1257 struct ifreq ifr;
1258 int netfd, ipfd;
1259 u32 ip;
1260 const char *br_name = NULL;
1261
1262 /* We open the /dev/net/tun device and tell it we want a tap device. A
1263 * tap device is like a tun device, only somehow different. To tell
1264 * the truth, I completely blundered my way through this code, but it
1265 * works now! */
1266 netfd = open_or_die("/dev/net/tun", O_RDWR);
1267 memset(&ifr, 0, sizeof(ifr));
1268 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
1269 strcpy(ifr.ifr_name, "tap%d");
1270 if (ioctl(netfd, TUNSETIFF, &ifr) != 0)
1271 err(1, "configuring /dev/net/tun");
1272 /* We don't need checksums calculated for packets coming in this
1273 * device: trust us! */
1274 ioctl(netfd, TUNSETNOCSUM, 1);
1275
1276 /* We create the net device with 1 page, using the features field of
1277 * the descriptor to tell the Guest it is in slot 1 (NET_PEERNUM), and
1278 * that the device has fairly random timing. We do *not* specify
1279 * LGUEST_NET_F_NOCSUM: these packets can reach the real world.
1280 *
1281 * We will put our MAC address is slot 0 for the Guest to see, so
1282 * it will send packets to us using the key "peer_offset(0)": */
1283 dev = new_device(devices, LGUEST_DEVICE_T_NET, 1,
1284 NET_PEERNUM|LGUEST_DEVICE_F_RANDOMNESS, netfd,
1285 handle_tun_input, peer_offset(0), handle_tun_output);
1286
1287 /* We keep a flag which says whether we've seen packets come out from
1288 * this network device. */
1289 dev->priv = malloc(sizeof(bool));
1290 *(bool *)dev->priv = false;
1291
1292 /* We need a socket to perform the magic network ioctls to bring up the
1293 * tap interface, connect to the bridge etc. Any socket will do! */
1294 ipfd = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP);
1295 if (ipfd < 0)
1296 err(1, "opening IP socket");
1297
1298 /* If the command line was --tunnet=bridge:<name> do bridging. */
1299 if (!strncmp(BRIDGE_PFX, arg, strlen(BRIDGE_PFX))) {
1300 ip = INADDR_ANY;
1301 br_name = arg + strlen(BRIDGE_PFX);
1302 add_to_bridge(ipfd, ifr.ifr_name, br_name);
1303 } else /* It is an IP address to set up the device with */
1304 ip = str2ip(arg);
1305
1306 /* We are peer 0, ie. first slot, so we hand dev->mem to this routine
1307 * to write the MAC address at the start of the device memory. */
1308 configure_device(ipfd, ifr.ifr_name, ip, dev->mem);
1309
1310 /* Set "promisc" bit: we want every single packet if we're going to
1311 * bridge to other machines (and otherwise it doesn't matter). */
1312 *((u8 *)dev->mem) |= 0x1;
1313
1314 close(ipfd);
1315
1316 verbose("device %p: tun net %u.%u.%u.%u\n",
1317 (void *)(dev->desc->pfn * getpagesize()),
1318 (u8)(ip>>24), (u8)(ip>>16), (u8)(ip>>8), (u8)ip);
1319 if (br_name)
1320 verbose("attached to bridge: %s\n", br_name);
1321 }
1322 /* That's the end of device setup. */
1323
1324 /*L:220 Finally we reach the core of the Launcher, which runs the Guest, serves
1325 * its input and output, and finally, lays it to rest. */
1326 static void __attribute__((noreturn))
1327 run_guest(int lguest_fd, struct device_list *device_list)
1328 {
1329 for (;;) {
1330 u32 args[] = { LHREQ_BREAK, 0 };
1331 unsigned long arr[2];
1332 int readval;
1333
1334 /* We read from the /dev/lguest device to run the Guest. */
1335 readval = read(lguest_fd, arr, sizeof(arr));
1336
1337 /* The read can only really return sizeof(arr) (the Guest did a
1338 * SEND_DMA to us), or an error. */
1339
1340 /* For a successful read, arr[0] is the address of the "struct
1341 * lguest_dma", and arr[1] is the key the Guest sent to. */
1342 if (readval == sizeof(arr)) {
1343 handle_output(lguest_fd, arr[0], arr[1], device_list);
1344 continue;
1345 /* ENOENT means the Guest died. Reading tells us why. */
1346 } else if (errno == ENOENT) {
1347 char reason[1024] = { 0 };
1348 read(lguest_fd, reason, sizeof(reason)-1);
1349 errx(1, "%s", reason);
1350 /* EAGAIN means the waker wanted us to look at some input.
1351 * Anything else means a bug or incompatible change. */
1352 } else if (errno != EAGAIN)
1353 err(1, "Running guest failed");
1354
1355 /* Service input, then unset the BREAK which releases
1356 * the Waker. */
1357 handle_input(lguest_fd, device_list);
1358 if (write(lguest_fd, args, sizeof(args)) < 0)
1359 err(1, "Resetting break");
1360 }
1361 }
1362 /*
1363 * This is the end of the Launcher.
1364 *
1365 * But wait! We've seen I/O from the Launcher, and we've seen I/O from the
1366 * Drivers. If we were to see the Host kernel I/O code, our understanding
1367 * would be complete... :*/
1368
1369 static struct option opts[] = {
1370 { "verbose", 0, NULL, 'v' },
1371 { "sharenet", 1, NULL, 's' },
1372 { "tunnet", 1, NULL, 't' },
1373 { "block", 1, NULL, 'b' },
1374 { "initrd", 1, NULL, 'i' },
1375 { NULL },
1376 };
1377 static void usage(void)
1378 {
1379 errx(1, "Usage: lguest [--verbose] "
1380 "[--sharenet=<filename>|--tunnet=(<ipaddr>|bridge:<bridgename>)\n"
1381 "|--block=<filename>|--initrd=<filename>]...\n"
1382 "<mem-in-mb> vmlinux [args...]");
1383 }
1384
1385 /*L:100 The Launcher code itself takes us out into userspace, that scary place
1386 * where pointers run wild and free! Unfortunately, like most userspace
1387 * programs, it's quite boring (which is why everyone like to hack on the
1388 * kernel!). Perhaps if you make up an Lguest Drinking Game at this point, it
1389 * will get you through this section. Or, maybe not.
1390 *
1391 * The Launcher binary sits up high, usually starting at address 0xB8000000.
1392 * Everything below this is the "physical" memory for the Guest. For example,
1393 * if the Guest were to write a "1" at physical address 0, we would see a "1"
1394 * in the Launcher at "(int *)0". Guest physical == Launcher virtual.
1395 *
1396 * This can be tough to get your head around, but usually it just means that we
1397 * don't need to do any conversion when the Guest gives us it's "physical"
1398 * addresses.
1399 */
1400 int main(int argc, char *argv[])
1401 {
1402 /* Memory, top-level pagetable, code startpoint, PAGE_OFFSET and size
1403 * of the (optional) initrd. */
1404 unsigned long mem = 0, pgdir, start, page_offset, initrd_size = 0;
1405 /* A temporary and the /dev/lguest file descriptor. */
1406 int i, c, lguest_fd;
1407 /* The list of Guest devices, based on command line arguments. */
1408 struct device_list device_list;
1409 /* The boot information for the Guest: at guest-physical address 0. */
1410 void *boot = (void *)0;
1411 /* If they specify an initrd file to load. */
1412 const char *initrd_name = NULL;
1413
1414 /* First we initialize the device list. Since console and network
1415 * device receive input from a file descriptor, we keep an fdset
1416 * (infds) and the maximum fd number (max_infd) with the head of the
1417 * list. We also keep a pointer to the last device, for easy appending
1418 * to the list. */
1419 device_list.max_infd = -1;
1420 device_list.dev = NULL;
1421 device_list.lastdev = &device_list.dev;
1422 FD_ZERO(&device_list.infds);
1423
1424 /* We need to know how much memory so we can set up the device
1425 * descriptor and memory pages for the devices as we parse the command
1426 * line. So we quickly look through the arguments to find the amount
1427 * of memory now. */
1428 for (i = 1; i < argc; i++) {
1429 if (argv[i][0] != '-') {
1430 mem = top = atoi(argv[i]) * 1024 * 1024;
1431 device_list.descs = map_zeroed_pages(top, 1);
1432 top += getpagesize();
1433 break;
1434 }
1435 }
1436
1437 /* The options are fairly straight-forward */
1438 while ((c = getopt_long(argc, argv, "v", opts, NULL)) != EOF) {
1439 switch (c) {
1440 case 'v':
1441 verbose = true;
1442 break;
1443 case 's':
1444 setup_net_file(optarg, &device_list);
1445 break;
1446 case 't':
1447 setup_tun_net(optarg, &device_list);
1448 break;
1449 case 'b':
1450 setup_block_file(optarg, &device_list);
1451 break;
1452 case 'i':
1453 initrd_name = optarg;
1454 break;
1455 default:
1456 warnx("Unknown argument %s", argv[optind]);
1457 usage();
1458 }
1459 }
1460 /* After the other arguments we expect memory and kernel image name,
1461 * followed by command line arguments for the kernel. */
1462 if (optind + 2 > argc)
1463 usage();
1464
1465 /* We always have a console device */
1466 setup_console(&device_list);
1467
1468 /* We start by mapping anonymous pages over all of guest-physical
1469 * memory range. This fills it with 0, and ensures that the Guest
1470 * won't be killed when it tries to access it. */
1471 map_zeroed_pages(0, mem / getpagesize());
1472
1473 /* Now we load the kernel */
1474 start = load_kernel(open_or_die(argv[optind+1], O_RDONLY),
1475 &page_offset);
1476
1477 /* Map the initrd image if requested (at top of physical memory) */
1478 if (initrd_name) {
1479 initrd_size = load_initrd(initrd_name, mem);
1480 /* These are the location in the Linux boot header where the
1481 * start and size of the initrd are expected to be found. */
1482 *(unsigned long *)(boot+0x218) = mem - initrd_size;
1483 *(unsigned long *)(boot+0x21c) = initrd_size;
1484 /* The bootloader type 0xFF means "unknown"; that's OK. */
1485 *(unsigned char *)(boot+0x210) = 0xFF;
1486 }
1487
1488 /* Set up the initial linear pagetables, starting below the initrd. */
1489 pgdir = setup_pagetables(mem, initrd_size, page_offset);
1490
1491 /* The Linux boot header contains an "E820" memory map: ours is a
1492 * simple, single region. */
1493 *(char*)(boot+E820NR) = 1;
1494 *((struct e820entry *)(boot+E820MAP))
1495 = ((struct e820entry) { 0, mem, E820_RAM });
1496 /* The boot header contains a command line pointer: we put the command
1497 * line after the boot header (at address 4096) */
1498 *(void **)(boot + 0x228) = boot + 4096;
1499 concat(boot + 4096, argv+optind+2);
1500
1501 /* The guest type value of "1" tells the Guest it's under lguest. */
1502 *(int *)(boot + 0x23c) = 1;
1503
1504 /* We tell the kernel to initialize the Guest: this returns the open
1505 * /dev/lguest file descriptor. */
1506 lguest_fd = tell_kernel(pgdir, start, page_offset);
1507
1508 /* We fork off a child process, which wakes the Launcher whenever one
1509 * of the input file descriptors needs attention. Otherwise we would
1510 * run the Guest until it tries to output something. */
1511 waker_fd = setup_waker(lguest_fd, &device_list);
1512
1513 /* Finally, run the Guest. This doesn't return. */
1514 run_guest(lguest_fd, &device_list);
1515 }
1516 /*:*/
1517
1518 /*M:999
1519 * Mastery is done: you now know everything I do.
1520 *
1521 * But surely you have seen code, features and bugs in your wanderings which
1522 * you now yearn to attack? That is the real game, and I look forward to you
1523 * patching and forking lguest into the Your-Name-Here-visor.
1524 *
1525 * Farewell, and good coding!
1526 * Rusty Russell.
1527 */
This page took 0.066154 seconds and 6 git commands to generate.