blob: 401d26b464fffbbf74ec69d3b7ca1d3b098a608e [file] [log] [blame]
Rusty Russellf938d2c2007-07-26 10:41:02 -07001/*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. :*/
Rusty Russell8ca47e02007-07-19 01:49:29 -07008#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>
Ronald G. Minnich6649bb72007-08-28 14:35:59 -070018#include <sys/param.h>
Rusty Russell8ca47e02007-07-19 01:49:29 -070019#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>
Rusty Russelldde79782007-07-26 10:41:03 -070038/*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 */
Rusty Russell8ca47e02007-07-19 01:49:29 -070045typedef unsigned long long u64;
46typedef uint32_t u32;
47typedef uint16_t u16;
48typedef uint8_t u8;
Rusty Russellb45d8cb2007-10-22 10:56:24 +100049#include "linux/lguest_launcher.h"
50#include "asm-x86/e820.h"
Rusty Russelldde79782007-07-26 10:41:03 -070051/*:*/
Rusty Russell8ca47e02007-07-19 01:49:29 -070052
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
Rusty Russelldde79782007-07-26 10:41:03 -070060/*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. */
Rusty Russell8ca47e02007-07-19 01:49:29 -070062static bool verbose;
63#define verbose(args...) \
64 do { if (verbose) printf(args); } while(0)
Rusty Russelldde79782007-07-26 10:41:03 -070065/*:*/
66
67/* The pipe to send commands to the waker process */
Rusty Russell8ca47e02007-07-19 01:49:29 -070068static int waker_fd;
Rusty Russelldde79782007-07-26 10:41:03 -070069/* The top of guest physical memory. */
Rusty Russell6570c45992007-07-23 18:43:56 -070070static u32 top;
Rusty Russell8ca47e02007-07-19 01:49:29 -070071
Rusty Russelldde79782007-07-26 10:41:03 -070072/* This is our list of devices. */
Rusty Russell8ca47e02007-07-19 01:49:29 -070073struct device_list
74{
Rusty Russelldde79782007-07-26 10:41:03 -070075 /* Summary information about the devices in our list: ready to pass to
76 * select() to ask which need servicing.*/
Rusty Russell8ca47e02007-07-19 01:49:29 -070077 fd_set infds;
78 int max_infd;
79
Rusty Russelldde79782007-07-26 10:41:03 -070080 /* The descriptor page for the devices. */
Rusty Russell6570c45992007-07-23 18:43:56 -070081 struct lguest_device_desc *descs;
Rusty Russelldde79782007-07-26 10:41:03 -070082
83 /* A single linked list of devices. */
Rusty Russell8ca47e02007-07-19 01:49:29 -070084 struct device *dev;
Rusty Russelldde79782007-07-26 10:41:03 -070085 /* ... And an end pointer so we can easily append new devices */
Rusty Russell8ca47e02007-07-19 01:49:29 -070086 struct device **lastdev;
87};
88
Rusty Russelldde79782007-07-26 10:41:03 -070089/* The device structure describes a single device. */
Rusty Russell8ca47e02007-07-19 01:49:29 -070090struct device
91{
Rusty Russelldde79782007-07-26 10:41:03 -070092 /* The linked-list pointer. */
Rusty Russell8ca47e02007-07-19 01:49:29 -070093 struct device *next;
Rusty Russelldde79782007-07-26 10:41:03 -070094 /* The descriptor for this device, as mapped into the Guest. */
Rusty Russell8ca47e02007-07-19 01:49:29 -070095 struct lguest_device_desc *desc;
Rusty Russelldde79782007-07-26 10:41:03 -070096 /* The memory page(s) of this device, if any. Also mapped in Guest. */
Rusty Russell8ca47e02007-07-19 01:49:29 -070097 void *mem;
98
Rusty Russelldde79782007-07-26 10:41:03 -070099 /* If handle_input is set, it wants to be called when this file
100 * descriptor is ready. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700101 int fd;
102 bool (*handle_input)(int fd, struct device *me);
103
Rusty Russelldde79782007-07-26 10:41:03 -0700104 /* If handle_output is set, it wants to be called when the Guest sends
105 * DMA to this key. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700106 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
Rusty Russelldde79782007-07-26 10:41:03 -0700114/*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: */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700119static 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
Rusty Russelldde79782007-07-26 10:41:03 -0700127/* map_zeroed_pages() takes a (page-aligned) address and a number of pages. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700128static void *map_zeroed_pages(unsigned long addr, unsigned int num)
129{
Rusty Russelldde79782007-07-26 10:41:03 -0700130 /* We cache the /dev/zero file-descriptor so we only open it once. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700131 static int fd = -1;
132
133 if (fd == -1)
134 fd = open_or_die("/dev/zero", O_RDONLY);
135
Rusty Russelldde79782007-07-26 10:41:03 -0700136 /* 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. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700138 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);
Rusty Russelldde79782007-07-26 10:41:03 -0700142
143 /* Returning the address is just a courtesy: can simplify callers. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700144 return (void *)addr;
145}
146
Rusty Russelldde79782007-07-26 10:41:03 -0700147/* 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. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700150static unsigned long entry_point(void *start, void *end,
151 unsigned long page_offset)
152{
153 void *p;
154
Rusty Russelldde79782007-07-26 10:41:03 -0700155 /* 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". */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700159 for (p = start; p < end; p++)
160 if (memcmp(p, "GenuineLguest", strlen("GenuineLguest")) == 0)
161 return (long)p + strlen("GenuineLguest") + page_offset;
162
Glauber de Oliveira Costababed5c2007-10-22 10:56:21 +1000163 errx(1, "Is this image a genuine lguest?");
Rusty Russell8ca47e02007-07-19 01:49:29 -0700164}
165
Ronald G. Minnich6649bb72007-08-28 14:35:59 -0700166/* 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. */
169static 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
Rusty Russelldde79782007-07-26 10:41:03 -0700190/* 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. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700201static unsigned long map_elf(int elf_fd, const Elf32_Ehdr *ehdr,
202 unsigned long *page_offset)
203{
Rusty Russell8ca47e02007-07-19 01:49:29 -0700204 Elf32_Phdr phdr[ehdr->e_phnum];
205 unsigned int i;
206 unsigned long start = -1UL, end = 0;
207
Rusty Russelldde79782007-07-26 10:41:03 -0700208 /* Sanity checks on the main ELF header: an x86 executable with a
209 * reasonable number of correctly-sized program headers. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700210 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
Rusty Russelldde79782007-07-26 10:41:03 -0700216 /* 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: */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700221 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
Rusty Russelldde79782007-07-26 10:41:03 -0700226 /* We don't know page_offset yet. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700227 *page_offset = 0;
Rusty Russelldde79782007-07-26 10:41:03 -0700228
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. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700231 for (i = 0; i < ehdr->e_phnum; i++) {
Rusty Russelldde79782007-07-26 10:41:03 -0700232 /* If this isn't a loadable segment, we ignore it */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700233 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
Rusty Russelldde79782007-07-26 10:41:03 -0700239 /* 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. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700242 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
Rusty Russelldde79782007-07-26 10:41:03 -0700247 /* We track the first and last address we mapped, so we can
248 * tell entry_point() where to scan. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700249 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
Ronald G. Minnich6649bb72007-08-28 14:35:59 -0700254 /* 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);
Rusty Russell8ca47e02007-07-19 01:49:29 -0700257 }
258
259 return entry_point((void *)start, (void *)end, *page_offset);
260}
261
Rusty Russelldde79782007-07-26 10:41:03 -0700262/*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. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700287static 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
Rusty Russelldde79782007-07-26 10:41:03 -0700299/*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. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700302static unsigned long unpack_bzimage(int fd, unsigned long *page_offset)
303{
304 gzFile f;
305 int ret, len = 0;
Rusty Russelldde79782007-07-26 10:41:03 -0700306 /* 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. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700310 void *img = (void *)0x100000;
311
Rusty Russelldde79782007-07-26 10:41:03 -0700312 /* gzdopen takes our file descriptor (carefully placed at the start of
313 * the GZIP header we found) and returns a gzFile. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700314 f = gzdopen(fd, "rb");
Rusty Russelldde79782007-07-26 10:41:03 -0700315 /* We read it into memory in 64k chunks until we hit the end. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700316 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);
Rusty Russelldde79782007-07-26 10:41:03 -0700322
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. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700326 *page_offset = intuit_page_offset(img, len);
327
328 return entry_point(img, img + len, *page_offset);
329}
330
Rusty Russelldde79782007-07-26 10:41:03 -0700331/*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. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700339static unsigned long load_bzimage(int fd, unsigned long *page_offset)
340{
341 unsigned char c;
342 int state = 0;
343
Rusty Russelldde79782007-07-26 10:41:03 -0700344 /* GZIP header is 0x1F 0x8B <method> <flags>... <compressed-by>. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700345 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:
Rusty Russelldde79782007-07-26 10:41:03 -0700361 /* Seek back to the start of the gzip header. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700362 lseek(fd, -10, SEEK_CUR);
Rusty Russelldde79782007-07-26 10:41:03 -0700363 /* One final check: "compressed under UNIX". */
364 if (c != 0x03)
Rusty Russell8ca47e02007-07-19 01:49:29 -0700365 state = -1;
366 else
367 return unpack_bzimage(fd, page_offset);
368 }
369 }
370 errx(1, "Could not find kernel in bzImage");
371}
372
Rusty Russelldde79782007-07-26 10:41:03 -0700373/*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. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700376static unsigned long load_kernel(int fd, unsigned long *page_offset)
377{
378 Elf32_Ehdr hdr;
379
Rusty Russelldde79782007-07-26 10:41:03 -0700380 /* Read in the first few bytes. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700381 if (read(fd, &hdr, sizeof(hdr)) != sizeof(hdr))
382 err(1, "Reading kernel");
383
Rusty Russelldde79782007-07-26 10:41:03 -0700384 /* If it's an ELF file, it starts with "\177ELF" */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700385 if (memcmp(hdr.e_ident, ELFMAG, SELFMAG) == 0)
386 return map_elf(fd, &hdr, page_offset);
387
Rusty Russelldde79782007-07-26 10:41:03 -0700388 /* Otherwise we assume it's a bzImage, and try to unpack it */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700389 return load_bzimage(fd, page_offset);
390}
391
Rusty Russelldde79782007-07-26 10:41:03 -0700392/* 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. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700397static inline unsigned long page_align(unsigned long addr)
398{
Rusty Russelldde79782007-07-26 10:41:03 -0700399 /* Add upwards and truncate downwards. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700400 return ((addr + getpagesize()-1) & ~(getpagesize()-1));
401}
402
Rusty Russelldde79782007-07-26 10:41:03 -0700403/*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). */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700410static unsigned long load_initrd(const char *name, unsigned long mem)
411{
412 int ifd;
413 struct stat st;
414 unsigned long len;
Rusty Russell8ca47e02007-07-19 01:49:29 -0700415
416 ifd = open_or_die(name, O_RDONLY);
Rusty Russelldde79782007-07-26 10:41:03 -0700417 /* fstat() is needed to get the file size. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700418 if (fstat(ifd, &st) < 0)
419 err(1, "fstat() on initrd '%s'", name);
420
Ronald G. Minnich6649bb72007-08-28 14:35:59 -0700421 /* 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. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700423 len = page_align(st.st_size);
Ronald G. Minnich6649bb72007-08-28 14:35:59 -0700424 map_at(ifd, (void *)mem - len, 0, st.st_size);
Rusty Russelldde79782007-07-26 10:41:03 -0700425 /* Once a file is mapped, you can close the file descriptor. It's a
426 * little odd, but quite useful. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700427 close(ifd);
Ronald G. Minnich6649bb72007-08-28 14:35:59 -0700428 verbose("mapped initrd %s size=%lu @ %p\n", name, len, (void*)mem-len);
Rusty Russelldde79782007-07-26 10:41:03 -0700429
430 /* We return the initrd size. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700431 return len;
432}
433
Rusty Russelldde79782007-07-26 10:41:03 -0700434/* 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). */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700440static 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
Rusty Russelldde79782007-07-26 10:41:03 -0700448 /* 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). */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700451 if (mem <= -page_offset)
452 mapped_pages = mem/getpagesize();
453 else
454 mapped_pages = -page_offset/getpagesize();
455
Rusty Russelldde79782007-07-26 10:41:03 -0700456 /* Each PTE page can map ptes_per_page pages: how many do we need? */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700457 linear_pages = (mapped_pages + ptes_per_page-1)/ptes_per_page;
458
Rusty Russelldde79782007-07-26 10:41:03 -0700459 /* We put the toplevel page directory page at the top of memory. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700460 pgdir = (void *)mem - initrd_size - getpagesize();
Rusty Russelldde79782007-07-26 10:41:03 -0700461
462 /* Now we use the next linear_pages pages as pte pages */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700463 linear = (void *)pgdir - linear_pages*getpagesize();
464
Rusty Russelldde79782007-07-26 10:41:03 -0700465 /* 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. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700468 for (i = 0; i < mapped_pages; i++)
469 linear[i] = ((i * getpagesize()) | PAGE_PRESENT);
470
Rusty Russelldde79782007-07-26 10:41:03 -0700471 /* 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. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700474 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
Rusty Russelldde79782007-07-26 10:41:03 -0700482 /* We return the top level (guest-physical) address: the kernel needs
483 * to know where it is. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700484 return (unsigned long)pgdir;
485}
486
Rusty Russelldde79782007-07-26 10:41:03 -0700487/* Simple routine to roll all the commandline arguments together with spaces
488 * between them. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700489static 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
Rusty Russelldde79782007-07-26 10:41:03 -0700502/* 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. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700506static int tell_kernel(u32 pgdir, u32 start, u32 page_offset)
507{
508 u32 args[] = { LHREQ_INITIALIZE,
Rusty Russell6570c45992007-07-23 18:43:56 -0700509 top/getpagesize(), pgdir, start, page_offset };
Rusty Russell8ca47e02007-07-19 01:49:29 -0700510 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");
Rusty Russelldde79782007-07-26 10:41:03 -0700515
516 /* We return the /dev/lguest file descriptor to control this Guest */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700517 return fd;
518}
Rusty Russelldde79782007-07-26 10:41:03 -0700519/*:*/
Rusty Russell8ca47e02007-07-19 01:49:29 -0700520
521static 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
Rusty Russelldde79782007-07-26 10:41:03 -0700528/*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 */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700543static void wake_parent(int pipefd, int lguest_fd, struct device_list *devices)
544{
Rusty Russelldde79782007-07-26 10:41:03 -0700545 /* Add the pipe from the Launcher to the fdset in the device_list, so
546 * we watch it, too. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700547 set_fd(pipefd, devices);
548
549 for (;;) {
550 fd_set rfds = devices->infds;
551 u32 args[] = { LHREQ_BREAK, 1 };
552
Rusty Russelldde79782007-07-26 10:41:03 -0700553 /* Wait until input is ready from one of the devices. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700554 select(devices->max_infd+1, &rfds, NULL, NULL, NULL);
Rusty Russelldde79782007-07-26 10:41:03 -0700555 /* Is it a message from the Launcher? */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700556 if (FD_ISSET(pipefd, &rfds)) {
557 int ignorefd;
Rusty Russelldde79782007-07-26 10:41:03 -0700558 /* If read() returns 0, it means the Launcher has
559 * exited. We silently follow. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700560 if (read(pipefd, &ignorefd, sizeof(ignorefd)) == 0)
561 exit(0);
Rusty Russelldde79782007-07-26 10:41:03 -0700562 /* 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. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700565 FD_CLR(ignorefd, &devices->infds);
Rusty Russelldde79782007-07-26 10:41:03 -0700566 } else /* Send LHREQ_BREAK command. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700567 write(lguest_fd, args, sizeof(args));
568 }
569}
570
Rusty Russelldde79782007-07-26 10:41:03 -0700571/* This routine just sets up a pipe to the Waker process. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700572static int setup_waker(int lguest_fd, struct device_list *device_list)
573{
574 int pipefd[2], child;
575
Rusty Russelldde79782007-07-26 10:41:03 -0700576 /* We create a pipe to talk to the waker, and also so it knows when the
577 * Launcher dies (and closes pipe). */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700578 pipe(pipefd);
579 child = fork();
580 if (child == -1)
581 err(1, "forking");
582
583 if (child == 0) {
Rusty Russelldde79782007-07-26 10:41:03 -0700584 /* Close the "writing" end of our copy of the pipe */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700585 close(pipefd[1]);
586 wake_parent(pipefd[0], lguest_fd, device_list);
587 }
Rusty Russelldde79782007-07-26 10:41:03 -0700588 /* Close the reading end of our copy of the pipe. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700589 close(pipefd[0]);
590
Rusty Russelldde79782007-07-26 10:41:03 -0700591 /* Here is the fd used to talk to the waker. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700592 return pipefd[1];
593}
594
Rusty Russelldde79782007-07-26 10:41:03 -0700595/*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 */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700603static void *_check_pointer(unsigned long addr, unsigned int size,
604 unsigned int line)
605{
Rusty Russelldde79782007-07-26 10:41:03 -0700606 /* We have to separately check addr and addr+size, because size could
607 * be huge and addr + size might wrap around. */
Rusty Russell6570c45992007-07-23 18:43:56 -0700608 if (addr >= top || addr + size >= top)
Rusty Russell8ca47e02007-07-19 01:49:29 -0700609 errx(1, "%s:%i: Invalid address %li", __FILE__, line, addr);
Rusty Russelldde79782007-07-26 10:41:03 -0700610 /* We return a pointer for the caller's convenience, now we know it's
611 * safe to use. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700612 return (void *)addr;
613}
Rusty Russelldde79782007-07-26 10:41:03 -0700614/* A macro which transparently hands the line number to the real function. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700615#define check_pointer(addr,size) _check_pointer(addr, size, __LINE__)
616
Rusty Russelldde79782007-07-26 10:41:03 -0700617/* 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). */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700620static u32 *dma2iov(unsigned long dma, struct iovec iov[], unsigned *num)
621{
622 unsigned int i;
623 struct lguest_dma *udma;
624
Rusty Russelldde79782007-07-26 10:41:03 -0700625 /* First we make sure that the array memory itself is valid. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700626 udma = check_pointer(dma, sizeof(*udma));
Rusty Russelldde79782007-07-26 10:41:03 -0700627 /* Now we check each element */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700628 for (i = 0; i < LGUEST_MAX_DMA_SECTIONS; i++) {
Rusty Russelldde79782007-07-26 10:41:03 -0700629 /* A zero length ends the array. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700630 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;
Rusty Russelldde79782007-07-26 10:41:03 -0700637
638 /* We return the pointer to where the caller should write the amount of
639 * the buffer used. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700640 return &udma->used_len;
641}
642
Rusty Russelldde79782007-07-26 10:41:03 -0700643/* 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. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700646static 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
Rusty Russelldde79782007-07-26 10:41:03 -0700653 /* Ask the kernel for a DMA buffer corresponding to this key. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700654 udma = write(fd, buf, sizeof(buf));
Rusty Russelldde79782007-07-26 10:41:03 -0700655 /* They haven't registered any, or they're all used? */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700656 if (udma == (unsigned long)-1)
657 return NULL;
658
Rusty Russelldde79782007-07-26 10:41:03 -0700659 /* Convert it into our iovec array */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700660 res = dma2iov(udma, iov, num);
Rusty Russelldde79782007-07-26 10:41:03 -0700661 /* The kernel stashes irq in ->used_len to get it out to us. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700662 *irq = *res;
Rusty Russelldde79782007-07-26 10:41:03 -0700663 /* Return a pointer to ((struct lguest_dma *)udma)->used_len. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700664 return res;
665}
666
Rusty Russelldde79782007-07-26 10:41:03 -0700667/* This is a convenient routine to send the Guest an interrupt. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700668static 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
Rusty Russelldde79782007-07-26 10:41:03 -0700675/* 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. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700679static 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
Rusty Russelldde79782007-07-26 10:41:03 -0700687/* 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. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700689static struct termios orig_term;
690static void restore_term(void)
691{
692 tcsetattr(STDIN_FILENO, TCSANOW, &orig_term);
693}
694
Rusty Russelldde79782007-07-26 10:41:03 -0700695/* We associate some data with the console for our exit hack. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700696struct console_abort
697{
Rusty Russelldde79782007-07-26 10:41:03 -0700698 /* How many times have they hit ^C? */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700699 int count;
Rusty Russelldde79782007-07-26 10:41:03 -0700700 /* When did they start? */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700701 struct timeval start;
702};
703
Rusty Russelldde79782007-07-26 10:41:03 -0700704/* This is the routine which handles console input (ie. stdin). */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700705static 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
Rusty Russelldde79782007-07-26 10:41:03 -0700713 /* First we get the console buffer from the Guest. The key is dev->mem
714 * which was set to 0 in setup_console(). */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700715 lenp = get_dma_buffer(fd, dev->mem, iov, &num, &irq);
716 if (!lenp) {
Rusty Russelldde79782007-07-26 10:41:03 -0700717 /* If it's not ready for input, warn and set up to discard. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700718 warn("console: no dma buffer!");
719 discard_iovec(iov, &num);
720 }
721
Rusty Russelldde79782007-07-26 10:41:03 -0700722 /* This is why we convert to iovecs: the readv() call uses them, and so
723 * it reads straight into the Guest's buffer. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700724 len = readv(dev->fd, iov, num);
725 if (len <= 0) {
Rusty Russelldde79782007-07-26 10:41:03 -0700726 /* 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. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700729 warnx("Failed to get console input, ignoring console.");
730 len = 0;
731 }
732
Rusty Russelldde79782007-07-26 10:41:03 -0700733 /* If we read the data into the Guest, fill in the length and send the
734 * interrupt. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700735 if (lenp) {
736 *lenp = len;
737 trigger_irq(fd, irq);
738 }
739
Rusty Russelldde79782007-07-26 10:41:03 -0700740 /* 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. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700745 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) {
Rusty Russell8ca47e02007-07-19 01:49:29 -0700752 u32 args[] = { LHREQ_BREAK, 0 };
Rusty Russelldde79782007-07-26 10:41:03 -0700753 /* Close the fd so Waker will know it has to
754 * exit. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700755 close(waker_fd);
Rusty Russelldde79782007-07-26 10:41:03 -0700756 /* Just in case waker is blocked in BREAK, send
757 * unbreak now. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700758 write(fd, args, sizeof(args));
759 exit(2);
760 }
761 abort->count = 0;
762 }
763 } else
Rusty Russelldde79782007-07-26 10:41:03 -0700764 /* Any other key resets the abort counter. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700765 abort->count = 0;
766
Rusty Russelldde79782007-07-26 10:41:03 -0700767 /* Now, if we didn't read anything, put the input terminal back and
768 * return failure (meaning, don't call us again). */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700769 if (!len) {
770 restore_term();
771 return false;
772 }
Rusty Russelldde79782007-07-26 10:41:03 -0700773 /* Everything went OK! */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700774 return true;
775}
776
Rusty Russelldde79782007-07-26 10:41:03 -0700777/* Handling console output is much simpler than input. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700778static u32 handle_console_output(int fd, const struct iovec *iov,
779 unsigned num, struct device*dev)
780{
Rusty Russelldde79782007-07-26 10:41:03 -0700781 /* Whatever the Guest sends, write it to standard output. Return the
782 * number of bytes written. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700783 return writev(STDOUT_FILENO, iov, num);
784}
785
Rusty Russelldde79782007-07-26 10:41:03 -0700786/* Guest->Host network output is also pretty easy. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700787static u32 handle_tun_output(int fd, const struct iovec *iov,
788 unsigned num, struct device *dev)
789{
Rusty Russelldde79782007-07-26 10:41:03 -0700790 /* 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() */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700792 *(bool *)dev->priv = true;
Rusty Russelldde79782007-07-26 10:41:03 -0700793 /* Whatever packet the Guest sent us, write it out to the tun
794 * device. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700795 return writev(dev->fd, iov, num);
796}
797
Rusty Russelldde79782007-07-26 10:41:03 -0700798/* 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. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700800static unsigned long peer_offset(unsigned int peernum)
801{
802 return 4 * peernum;
803}
804
Rusty Russelldde79782007-07-26 10:41:03 -0700805/* This is where we handle a packet coming in from the tun device */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700806static 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
Rusty Russelldde79782007-07-26 10:41:03 -0700813 /* First we get a buffer the Guest has bound to its key. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700814 lenp = get_dma_buffer(fd, dev->mem+peer_offset(NET_PEERNUM), iov, &num,
815 &irq);
816 if (!lenp) {
Rusty Russelldde79782007-07-26 10:41:03 -0700817 /* 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! */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700824 if (*(bool *)dev->priv)
825 warn("network: no dma buffer!");
826 discard_iovec(iov, &num);
827 }
828
Rusty Russelldde79782007-07-26 10:41:03 -0700829 /* Read the packet from the device directly into the Guest's buffer. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700830 len = readv(dev->fd, iov, num);
831 if (len <= 0)
832 err(1, "reading network");
Rusty Russelldde79782007-07-26 10:41:03 -0700833
834 /* Write the used_len, and trigger the interrupt for the Guest */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700835 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");
Rusty Russelldde79782007-07-26 10:41:03 -0700842 /* All good. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700843 return true;
844}
845
Rusty Russelldde79782007-07-26 10:41:03 -0700846/* 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". */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700849static 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
Rusty Russelldde79782007-07-26 10:41:03 -0700858 /* First we extract the device length from the dev->priv pointer. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700859 device_len = *(off64_t *)dev->priv;
860
Rusty Russelldde79782007-07-26 10:41:03 -0700861 /* We first check that the read or write is within the length of the
862 * block file. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700863 if (off >= device_len)
Glauber de Oliveira Costababed5c2007-10-22 10:56:21 +1000864 errx(1, "Bad offset %llu vs %llu", off, device_len);
Rusty Russelldde79782007-07-26 10:41:03 -0700865 /* Move to the right location in the block file. This shouldn't fail,
866 * but best to check. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700867 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
Rusty Russelldde79782007-07-26 10:41:03 -0700872 /* 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. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700875 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) {
Rusty Russelldde79782007-07-26 10:41:03 -0700880 /* A write request. The DMA they sent contained the data, so
881 * write it out. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700882 len = writev(dev->fd, iov, num);
Rusty Russelldde79782007-07-26 10:41:03 -0700883 /* 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). */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700886 if (off + len > device_len) {
Rusty Russelldde79782007-07-26 10:41:03 -0700887 /* Trim it back to the correct length */
Chris Malleyf6a592e2007-09-26 14:19:18 +1000888 ftruncate64(dev->fd, device_len);
Rusty Russelldde79782007-07-26 10:41:03 -0700889 /* Die, bad Guest, die. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700890 errx(1, "Write past end %llu+%u", off, len);
891 }
Rusty Russelldde79782007-07-26 10:41:03 -0700892 /* The reply length is 0: we just send back an empty DMA to
893 * interrupt them and tell them the write is finished. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700894 *lenp = 0;
895 } else {
Rusty Russelldde79782007-07-26 10:41:03 -0700896 /* A read request. They sent an empty DMA to start the
897 * request, and we put the read contents into the reply
898 * buffer. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700899 len = readv(dev->fd, reply, reply_num);
900 *lenp = len;
901 }
902
Rusty Russelldde79782007-07-26 10:41:03 -0700903 /* The result is 1 (done), 2 if there was an error (short read or
904 * write). */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700905 p->result = 1 + (p->bytes != len);
Rusty Russelldde79782007-07-26 10:41:03 -0700906 /* Now tell them we've used their reply buffer. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700907 trigger_irq(fd, irq);
Rusty Russelldde79782007-07-26 10:41:03 -0700908
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. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700912 return 0;
913}
914
Rusty Russelldde79782007-07-26 10:41:03 -0700915/* This is the generic routine we call when the Guest sends some DMA out. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700916static 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
Rusty Russelldde79782007-07-26 10:41:03 -0700924 /* Convert the "struct lguest_dma" they're sending to a "struct
925 * iovec". */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700926 lenp = dma2iov(dma, iov, &num);
Rusty Russelldde79782007-07-26 10:41:03 -0700927
928 /* Check each device: if they expect output to this key, tell them to
929 * handle it. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700930 for (i = devices->dev; i; i = i->next) {
931 if (i->handle_output && key == i->watch_key) {
Rusty Russelldde79782007-07-26 10:41:03 -0700932 /* We write the result straight into the used_len field
933 * for them. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700934 *lenp = i->handle_output(fd, iov, num, i);
935 return;
936 }
937 }
Rusty Russelldde79782007-07-26 10:41:03 -0700938
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. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700942 warnx("Pending dma %p, key %p", (void *)dma, (void *)key);
943}
944
Rusty Russelldde79782007-07-26 10:41:03 -0700945/* This is called when the waker wakes us up: check for incoming file
946 * descriptors. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700947static void handle_input(int fd, struct device_list *devices)
948{
Rusty Russelldde79782007-07-26 10:41:03 -0700949 /* select() wants a zeroed timeval to mean "don't wait". */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700950 struct timeval poll = { .tv_sec = 0, .tv_usec = 0 };
951
952 for (;;) {
953 struct device *i;
954 fd_set fds = devices->infds;
955
Rusty Russelldde79782007-07-26 10:41:03 -0700956 /* If nothing is ready, we're done. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700957 if (select(devices->max_infd+1, &fds, NULL, NULL, &poll) == 0)
958 break;
959
Rusty Russelldde79782007-07-26 10:41:03 -0700960 /* Otherwise, call the device(s) which have readable
961 * file descriptors and a method of handling them. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700962 for (i = devices->dev; i; i = i->next) {
963 if (i->handle_input && FD_ISSET(i->fd, &fds)) {
Rusty Russelldde79782007-07-26 10:41:03 -0700964 /* If handle_input() returns false, it means we
965 * should no longer service it.
966 * handle_console_input() does this. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700967 if (!i->handle_input(fd, i)) {
Rusty Russelldde79782007-07-26 10:41:03 -0700968 /* Clear it from the set of input file
969 * descriptors kept at the head of the
970 * device list. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700971 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
Rusty Russelldde79782007-07-26 10:41:03 -0700980/*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. */
Rusty Russell6570c45992007-07-23 18:43:56 -0700989static struct lguest_device_desc *
990new_dev_desc(struct lguest_device_desc *descs,
991 u16 type, u16 features, u16 num_pages)
Rusty Russell8ca47e02007-07-19 01:49:29 -0700992{
Rusty Russell6570c45992007-07-23 18:43:56 -0700993 unsigned int i;
Rusty Russell8ca47e02007-07-19 01:49:29 -0700994
Rusty Russell6570c45992007-07-23 18:43:56 -0700995 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;
Rusty Russelldde79782007-07-26 10:41:03 -07001000 /* If they said the device needs memory, we allocate
1001 * that now, bumping up the top of Guest memory. */
Rusty Russell6570c45992007-07-23 18:43:56 -07001002 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");
Rusty Russell8ca47e02007-07-19 01:49:29 -07001011}
1012
Rusty Russelldde79782007-07-26 10:41:03 -07001013/* 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. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001016static 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
Rusty Russelldde79782007-07-26 10:41:03 -07001028 /* 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. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001032 *devices->lastdev = dev;
1033 dev->next = NULL;
1034 devices->lastdev = &dev->next;
1035
Rusty Russelldde79782007-07-26 10:41:03 -07001036 /* Now we populate the fields one at a time. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001037 dev->fd = fd;
Rusty Russelldde79782007-07-26 10:41:03 -07001038 /* If we have an input handler for this file descriptor, then we add it
1039 * to the device_list's fdset and maxfd. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001040 if (handle_input)
1041 set_fd(dev->fd, devices);
Rusty Russell6570c45992007-07-23 18:43:56 -07001042 dev->desc = new_dev_desc(devices->descs, type, features, num_pages);
Rusty Russell8ca47e02007-07-19 01:49:29 -07001043 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
Rusty Russelldde79782007-07-26 10:41:03 -07001050/* 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. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001052static void setup_console(struct device_list *devices)
1053{
1054 struct device *dev;
1055
Rusty Russelldde79782007-07-26 10:41:03 -07001056 /* If we can save the initial standard input settings... */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001057 if (tcgetattr(STDIN_FILENO, &orig_term) == 0) {
1058 struct termios term = orig_term;
Rusty Russelldde79782007-07-26 10:41:03 -07001059 /* Then we turn off echo, line buffering and ^C etc. We want a
1060 * raw input stream to the Guest. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001061 term.c_lflag &= ~(ISIG|ICANON|ECHO);
1062 tcsetattr(STDIN_FILENO, TCSANOW, &term);
Rusty Russelldde79782007-07-26 10:41:03 -07001063 /* If we exit gracefully, the original settings will be
1064 * restored so the user can see what they're typing. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001065 atexit(restore_term);
1066 }
1067
Rusty Russelldde79782007-07-26 10:41:03 -07001068 /* We don't currently require any memory for the console, so we ask for
1069 * 0 pages. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001070 dev = new_device(devices, LGUEST_DEVICE_T_CONSOLE, 0, 0,
1071 STDIN_FILENO, handle_console_input,
1072 LGUEST_CONSOLE_DMA_KEY, handle_console_output);
Rusty Russelldde79782007-07-26 10:41:03 -07001073 /* We store the console state in dev->priv, and initialize it. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001074 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
Rusty Russelldde79782007-07-26 10:41:03 -07001080/* Setting up a block file is also fairly straightforward. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001081static 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
Rusty Russelldde79782007-07-26 10:41:03 -07001088 /* 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. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001091 fd = open_or_die(filename, O_RDWR|O_LARGEFILE|O_DIRECT);
Rusty Russelldde79782007-07-26 10:41:03 -07001092
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. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001096 dev = new_device(devices, LGUEST_DEVICE_T_BLOCK, 1,
1097 LGUEST_DEVICE_F_RANDOMNESS,
1098 fd, NULL, 0, handle_block_output);
Rusty Russell8ca47e02007-07-19 01:49:29 -07001099
Rusty Russelldde79782007-07-26 10:41:03 -07001100 /* 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;
Rusty Russell8ca47e02007-07-19 01:49:29 -07001110 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
Rusty Russelldde79782007-07-26 10:41:03 -07001115/*
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. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001129static 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;
Rusty Russelldde79782007-07-26 10:41:03 -07001136 /* Try a 1 byte lock in each possible position number */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001137 for (fl.l_start = 0;
1138 fl.l_start < getpagesize()/sizeof(struct lguest_net);
1139 fl.l_start++) {
Rusty Russelldde79782007-07-26 10:41:03 -07001140 /* If we succeed, return the slot number. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001141 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
Rusty Russelldde79782007-07-26 10:41:03 -07001147/* This function sets up the network file */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001148static void setup_net_file(const char *filename,
1149 struct device_list *devices)
1150{
1151 int netfd;
1152 struct device *dev;
1153
Rusty Russelldde79782007-07-26 10:41:03 -07001154 /* We don't use open_or_die() here: for friendliness we create the file
1155 * if it doesn't already exist. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001156 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) {
Rusty Russelldde79782007-07-26 10:41:03 -07001161 /* If we succeeded, initialize the file with a
1162 * blank page. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001163 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
Rusty Russelldde79782007-07-26 10:41:03 -07001172 /* 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. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001176 dev = new_device(devices, LGUEST_DEVICE_T_NET, 1,
1177 find_slot(netfd, filename)|LGUEST_NET_F_NOCSUM,
1178 -1, NULL, 0, NULL);
1179
Rusty Russelldde79782007-07-26 10:41:03 -07001180 /* Map the shared file. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001181 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}
Rusty Russelldde79782007-07-26 10:41:03 -07001188/*:*/
Rusty Russell8ca47e02007-07-19 01:49:29 -07001189
1190static 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
Rusty Russelldde79782007-07-26 10:41:03 -07001198/* 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. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001203static 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
Rusty Russelldde79782007-07-26 10:41:03 -07001221/* 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). */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001224static 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
Rusty Russelldde79782007-07-26 10:41:03 -07001230 /* Don't read these incantations. Just cut & paste them like I did! */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001231 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
Rusty Russelldde79782007-07-26 10:41:03 -07001241 /* 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! */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001244 if (ioctl(fd, SIOCGIFHWADDR, &ifr) != 0)
1245 err(1, "getting hw address for %s", devname);
Rusty Russell8ca47e02007-07-19 01:49:29 -07001246 memcpy(hwaddr, ifr.ifr_hwaddr.sa_data, 6);
1247}
1248
Rusty Russelldde79782007-07-26 10:41:03 -07001249/*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. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001254static 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
Rusty Russelldde79782007-07-26 10:41:03 -07001262 /* 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! */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001266 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");
Rusty Russelldde79782007-07-26 10:41:03 -07001272 /* We don't need checksums calculated for packets coming in this
1273 * device: trust us! */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001274 ioctl(netfd, TUNSETNOCSUM, 1);
1275
Rusty Russelldde79782007-07-26 10:41:03 -07001276 /* 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)": */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001283 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);
Rusty Russelldde79782007-07-26 10:41:03 -07001286
1287 /* We keep a flag which says whether we've seen packets come out from
1288 * this network device. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001289 dev->priv = malloc(sizeof(bool));
1290 *(bool *)dev->priv = false;
1291
Rusty Russelldde79782007-07-26 10:41:03 -07001292 /* 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! */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001294 ipfd = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP);
1295 if (ipfd < 0)
1296 err(1, "opening IP socket");
1297
Rusty Russelldde79782007-07-26 10:41:03 -07001298 /* If the command line was --tunnet=bridge:<name> do bridging. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001299 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);
Rusty Russelldde79782007-07-26 10:41:03 -07001303 } else /* It is an IP address to set up the device with */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001304 ip = str2ip(arg);
1305
Rusty Russelldde79782007-07-26 10:41:03 -07001306 /* 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. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001308 configure_device(ipfd, ifr.ifr_name, ip, dev->mem);
1309
Rusty Russelldde79782007-07-26 10:41:03 -07001310 /* Set "promisc" bit: we want every single packet if we're going to
1311 * bridge to other machines (and otherwise it doesn't matter). */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001312 *((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}
Rusty Russelldde79782007-07-26 10:41:03 -07001322/* That's the end of device setup. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001323
Rusty Russelldde79782007-07-26 10:41:03 -07001324/*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. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001326static void __attribute__((noreturn))
1327run_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
Rusty Russelldde79782007-07-26 10:41:03 -07001337 /* 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. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001342 if (readval == sizeof(arr)) {
1343 handle_output(lguest_fd, arr[0], arr[1], device_list);
1344 continue;
Rusty Russelldde79782007-07-26 10:41:03 -07001345 /* ENOENT means the Guest died. Reading tells us why. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001346 } else if (errno == ENOENT) {
1347 char reason[1024] = { 0 };
1348 read(lguest_fd, reason, sizeof(reason)-1);
1349 errx(1, "%s", reason);
Rusty Russelldde79782007-07-26 10:41:03 -07001350 /* EAGAIN means the waker wanted us to look at some input.
1351 * Anything else means a bug or incompatible change. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001352 } else if (errno != EAGAIN)
1353 err(1, "Running guest failed");
Rusty Russelldde79782007-07-26 10:41:03 -07001354
1355 /* Service input, then unset the BREAK which releases
1356 * the Waker. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001357 handle_input(lguest_fd, device_list);
1358 if (write(lguest_fd, args, sizeof(args)) < 0)
1359 err(1, "Resetting break");
1360 }
1361}
Rusty Russelldde79782007-07-26 10:41:03 -07001362/*
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... :*/
Rusty Russell8ca47e02007-07-19 01:49:29 -07001368
1369static 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};
1377static 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
Rusty Russelldde79782007-07-26 10:41:03 -07001385/*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 */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001400int main(int argc, char *argv[])
1401{
Rusty Russelldde79782007-07-26 10:41:03 -07001402 /* Memory, top-level pagetable, code startpoint, PAGE_OFFSET and size
1403 * of the (optional) initrd. */
Rusty Russell6570c45992007-07-23 18:43:56 -07001404 unsigned long mem = 0, pgdir, start, page_offset, initrd_size = 0;
Rusty Russelldde79782007-07-26 10:41:03 -07001405 /* A temporary and the /dev/lguest file descriptor. */
Rusty Russell6570c45992007-07-23 18:43:56 -07001406 int i, c, lguest_fd;
Rusty Russelldde79782007-07-26 10:41:03 -07001407 /* The list of Guest devices, based on command line arguments. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001408 struct device_list device_list;
Rusty Russelldde79782007-07-26 10:41:03 -07001409 /* The boot information for the Guest: at guest-physical address 0. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001410 void *boot = (void *)0;
Rusty Russelldde79782007-07-26 10:41:03 -07001411 /* If they specify an initrd file to load. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001412 const char *initrd_name = NULL;
1413
Rusty Russelldde79782007-07-26 10:41:03 -07001414 /* 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. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001419 device_list.max_infd = -1;
1420 device_list.dev = NULL;
1421 device_list.lastdev = &device_list.dev;
1422 FD_ZERO(&device_list.infds);
1423
Rusty Russelldde79782007-07-26 10:41:03 -07001424 /* 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. */
Rusty Russell6570c45992007-07-23 18:43:56 -07001428 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 }
Rusty Russelldde79782007-07-26 10:41:03 -07001436
1437 /* The options are fairly straight-forward */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001438 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 }
Rusty Russelldde79782007-07-26 10:41:03 -07001460 /* After the other arguments we expect memory and kernel image name,
1461 * followed by command line arguments for the kernel. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001462 if (optind + 2 > argc)
1463 usage();
1464
Rusty Russelldde79782007-07-26 10:41:03 -07001465 /* We always have a console device */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001466 setup_console(&device_list);
1467
Rusty Russelldde79782007-07-26 10:41:03 -07001468 /* 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. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001471 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
Rusty Russelldde79782007-07-26 10:41:03 -07001477 /* Map the initrd image if requested (at top of physical memory) */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001478 if (initrd_name) {
1479 initrd_size = load_initrd(initrd_name, mem);
Rusty Russelldde79782007-07-26 10:41:03 -07001480 /* These are the location in the Linux boot header where the
1481 * start and size of the initrd are expected to be found. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001482 *(unsigned long *)(boot+0x218) = mem - initrd_size;
1483 *(unsigned long *)(boot+0x21c) = initrd_size;
Rusty Russelldde79782007-07-26 10:41:03 -07001484 /* The bootloader type 0xFF means "unknown"; that's OK. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001485 *(unsigned char *)(boot+0x210) = 0xFF;
1486 }
1487
Rusty Russelldde79782007-07-26 10:41:03 -07001488 /* Set up the initial linear pagetables, starting below the initrd. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001489 pgdir = setup_pagetables(mem, initrd_size, page_offset);
1490
Rusty Russelldde79782007-07-26 10:41:03 -07001491 /* The Linux boot header contains an "E820" memory map: ours is a
1492 * simple, single region. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001493 *(char*)(boot+E820NR) = 1;
1494 *((struct e820entry *)(boot+E820MAP))
1495 = ((struct e820entry) { 0, mem, E820_RAM });
Rusty Russelldde79782007-07-26 10:41:03 -07001496 /* The boot header contains a command line pointer: we put the command
1497 * line after the boot header (at address 4096) */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001498 *(void **)(boot + 0x228) = boot + 4096;
1499 concat(boot + 4096, argv+optind+2);
Rusty Russelldde79782007-07-26 10:41:03 -07001500
1501 /* The guest type value of "1" tells the Guest it's under lguest. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001502 *(int *)(boot + 0x23c) = 1;
1503
Rusty Russelldde79782007-07-26 10:41:03 -07001504 /* We tell the kernel to initialize the Guest: this returns the open
1505 * /dev/lguest file descriptor. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001506 lguest_fd = tell_kernel(pgdir, start, page_offset);
Rusty Russelldde79782007-07-26 10:41:03 -07001507
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. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001511 waker_fd = setup_waker(lguest_fd, &device_list);
1512
Rusty Russelldde79782007-07-26 10:41:03 -07001513 /* Finally, run the Guest. This doesn't return. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001514 run_guest(lguest_fd, &device_list);
1515}
Rusty Russellf56a3842007-07-26 10:41:05 -07001516/*:*/
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 */