blob: 140bd98a8417ca7faef8e3ec262e0d714082bab6 [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.
Rusty Russell3c6b5bf2007-10-22 11:03:26 +10004:*/
Rusty Russell8ca47e02007-07-19 01:49:29 -07005#define _LARGEFILE64_SOURCE
6#define _GNU_SOURCE
7#include <stdio.h>
8#include <string.h>
9#include <unistd.h>
10#include <err.h>
11#include <stdint.h>
12#include <stdlib.h>
13#include <elf.h>
14#include <sys/mman.h>
Ronald G. Minnich6649bb72007-08-28 14:35:59 -070015#include <sys/param.h>
Rusty Russell8ca47e02007-07-19 01:49:29 -070016#include <sys/types.h>
17#include <sys/stat.h>
18#include <sys/wait.h>
19#include <fcntl.h>
20#include <stdbool.h>
21#include <errno.h>
22#include <ctype.h>
23#include <sys/socket.h>
24#include <sys/ioctl.h>
25#include <sys/time.h>
26#include <time.h>
27#include <netinet/in.h>
28#include <net/if.h>
29#include <linux/sockios.h>
30#include <linux/if_tun.h>
31#include <sys/uio.h>
32#include <termios.h>
33#include <getopt.h>
34#include <zlib.h>
Rusty Russelldde79782007-07-26 10:41:03 -070035/*L:110 We can ignore the 28 include files we need for this program, but I do
36 * want to draw attention to the use of kernel-style types.
37 *
38 * As Linus said, "C is a Spartan language, and so should your naming be." I
39 * like these abbreviations and the header we need uses them, so we define them
40 * here.
41 */
Rusty Russell8ca47e02007-07-19 01:49:29 -070042typedef unsigned long long u64;
43typedef uint32_t u32;
44typedef uint16_t u16;
45typedef uint8_t u8;
Rusty Russellb45d8cb2007-10-22 10:56:24 +100046#include "linux/lguest_launcher.h"
47#include "asm-x86/e820.h"
Rusty Russelldde79782007-07-26 10:41:03 -070048/*:*/
Rusty Russell8ca47e02007-07-19 01:49:29 -070049
50#define PAGE_PRESENT 0x7 /* Present, RW, Execute */
51#define NET_PEERNUM 1
52#define BRIDGE_PFX "bridge:"
53#ifndef SIOCBRADDIF
54#define SIOCBRADDIF 0x89a2 /* add interface to bridge */
55#endif
Rusty Russell3c6b5bf2007-10-22 11:03:26 +100056/* We can have up to 256 pages for devices. */
57#define DEVICE_PAGES 256
Rusty Russell8ca47e02007-07-19 01:49:29 -070058
Rusty Russelldde79782007-07-26 10:41:03 -070059/*L:120 verbose is both a global flag and a macro. The C preprocessor allows
60 * this, and although I wouldn't recommend it, it works quite nicely here. */
Rusty Russell8ca47e02007-07-19 01:49:29 -070061static bool verbose;
62#define verbose(args...) \
63 do { if (verbose) printf(args); } while(0)
Rusty Russelldde79782007-07-26 10:41:03 -070064/*:*/
65
66/* The pipe to send commands to the waker process */
Rusty Russell8ca47e02007-07-19 01:49:29 -070067static int waker_fd;
Rusty Russell3c6b5bf2007-10-22 11:03:26 +100068/* The pointer to the start of guest memory. */
69static void *guest_base;
70/* The maximum guest physical address allowed, and maximum possible. */
71static unsigned long guest_limit, guest_max;
Rusty Russell8ca47e02007-07-19 01:49:29 -070072
Rusty Russelldde79782007-07-26 10:41:03 -070073/* This is our list of devices. */
Rusty Russell8ca47e02007-07-19 01:49:29 -070074struct device_list
75{
Rusty Russelldde79782007-07-26 10:41:03 -070076 /* Summary information about the devices in our list: ready to pass to
77 * select() to ask which need servicing.*/
Rusty Russell8ca47e02007-07-19 01:49:29 -070078 fd_set infds;
79 int max_infd;
80
Rusty Russelldde79782007-07-26 10:41:03 -070081 /* The descriptor page for the devices. */
Rusty Russell6570c45992007-07-23 18:43:56 -070082 struct lguest_device_desc *descs;
Rusty Russelldde79782007-07-26 10:41:03 -070083
84 /* A single linked list of devices. */
Rusty Russell8ca47e02007-07-19 01:49:29 -070085 struct device *dev;
Rusty Russelldde79782007-07-26 10:41:03 -070086 /* ... And an end pointer so we can easily append new devices */
Rusty Russell8ca47e02007-07-19 01:49:29 -070087 struct device **lastdev;
88};
89
Rusty Russelldde79782007-07-26 10:41:03 -070090/* The device structure describes a single device. */
Rusty Russell8ca47e02007-07-19 01:49:29 -070091struct device
92{
Rusty Russelldde79782007-07-26 10:41:03 -070093 /* The linked-list pointer. */
Rusty Russell8ca47e02007-07-19 01:49:29 -070094 struct device *next;
Rusty Russelldde79782007-07-26 10:41:03 -070095 /* The descriptor for this device, as mapped into the Guest. */
Rusty Russell8ca47e02007-07-19 01:49:29 -070096 struct lguest_device_desc *desc;
Rusty Russelldde79782007-07-26 10:41:03 -070097 /* The memory page(s) of this device, if any. Also mapped in Guest. */
Rusty Russell8ca47e02007-07-19 01:49:29 -070098 void *mem;
99
Rusty Russelldde79782007-07-26 10:41:03 -0700100 /* If handle_input is set, it wants to be called when this file
101 * descriptor is ready. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700102 int fd;
103 bool (*handle_input)(int fd, struct device *me);
104
Rusty Russelldde79782007-07-26 10:41:03 -0700105 /* If handle_output is set, it wants to be called when the Guest sends
106 * DMA to this key. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700107 unsigned long watch_key;
108 u32 (*handle_output)(int fd, const struct iovec *iov,
109 unsigned int num, struct device *me);
110
111 /* Device-specific data. */
112 void *priv;
113};
114
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000115/*L:100 The Launcher code itself takes us out into userspace, that scary place
116 * where pointers run wild and free! Unfortunately, like most userspace
117 * programs, it's quite boring (which is why everyone likes to hack on the
118 * kernel!). Perhaps if you make up an Lguest Drinking Game at this point, it
119 * will get you through this section. Or, maybe not.
120 *
121 * The Launcher sets up a big chunk of memory to be the Guest's "physical"
122 * memory and stores it in "guest_base". In other words, Guest physical ==
123 * Launcher virtual with an offset.
124 *
125 * This can be tough to get your head around, but usually it just means that we
126 * use these trivial conversion functions when the Guest gives us it's
127 * "physical" addresses: */
128static void *from_guest_phys(unsigned long addr)
129{
130 return guest_base + addr;
131}
132
133static unsigned long to_guest_phys(const void *addr)
134{
135 return (addr - guest_base);
136}
137
Rusty Russelldde79782007-07-26 10:41:03 -0700138/*L:130
139 * Loading the Kernel.
140 *
141 * We start with couple of simple helper routines. open_or_die() avoids
142 * error-checking code cluttering the callers: */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700143static int open_or_die(const char *name, int flags)
144{
145 int fd = open(name, flags);
146 if (fd < 0)
147 err(1, "Failed to open %s", name);
148 return fd;
149}
150
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000151/* map_zeroed_pages() takes a number of pages. */
152static void *map_zeroed_pages(unsigned int num)
Rusty Russell8ca47e02007-07-19 01:49:29 -0700153{
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000154 int fd = open_or_die("/dev/zero", O_RDONLY);
155 void *addr;
Rusty Russell8ca47e02007-07-19 01:49:29 -0700156
Rusty Russelldde79782007-07-26 10:41:03 -0700157 /* We use a private mapping (ie. if we write to the page, it will be
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000158 * copied). */
159 addr = mmap(NULL, getpagesize() * num,
160 PROT_READ|PROT_WRITE|PROT_EXEC, MAP_PRIVATE, fd, 0);
161 if (addr == MAP_FAILED)
162 err(1, "Mmaping %u pages of /dev/zero", num);
Rusty Russelldde79782007-07-26 10:41:03 -0700163
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000164 return addr;
165}
166
167/* Get some more pages for a device. */
168static void *get_pages(unsigned int num)
169{
170 void *addr = from_guest_phys(guest_limit);
171
172 guest_limit += num * getpagesize();
173 if (guest_limit > guest_max)
174 errx(1, "Not enough memory for devices");
175 return addr;
Rusty Russell8ca47e02007-07-19 01:49:29 -0700176}
177
Rusty Russelldde79782007-07-26 10:41:03 -0700178/* To find out where to start we look for the magic Guest string, which marks
179 * the code we see in lguest_asm.S. This is a hack which we are currently
180 * plotting to replace with the normal Linux entry point. */
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000181static unsigned long entry_point(const void *start, const void *end,
Rusty Russell8ca47e02007-07-19 01:49:29 -0700182 unsigned long page_offset)
183{
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000184 const void *p;
Rusty Russell8ca47e02007-07-19 01:49:29 -0700185
Rusty Russelldde79782007-07-26 10:41:03 -0700186 /* The scan gives us the physical starting address. We want the
187 * virtual address in this case, and fortunately, we already figured
188 * out the physical-virtual difference and passed it here in
189 * "page_offset". */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700190 for (p = start; p < end; p++)
191 if (memcmp(p, "GenuineLguest", strlen("GenuineLguest")) == 0)
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000192 return to_guest_phys(p + strlen("GenuineLguest"))
193 + page_offset;
Rusty Russell8ca47e02007-07-19 01:49:29 -0700194
Glauber de Oliveira Costababed5c2007-10-22 10:56:21 +1000195 errx(1, "Is this image a genuine lguest?");
Rusty Russell8ca47e02007-07-19 01:49:29 -0700196}
197
Ronald G. Minnich6649bb72007-08-28 14:35:59 -0700198/* This routine is used to load the kernel or initrd. It tries mmap, but if
199 * that fails (Plan 9's kernel file isn't nicely aligned on page boundaries),
200 * it falls back to reading the memory in. */
201static void map_at(int fd, void *addr, unsigned long offset, unsigned long len)
202{
203 ssize_t r;
204
205 /* We map writable even though for some segments are marked read-only.
206 * The kernel really wants to be writable: it patches its own
207 * instructions.
208 *
209 * MAP_PRIVATE means that the page won't be copied until a write is
210 * done to it. This allows us to share untouched memory between
211 * Guests. */
212 if (mmap(addr, len, PROT_READ|PROT_WRITE|PROT_EXEC,
213 MAP_FIXED|MAP_PRIVATE, fd, offset) != MAP_FAILED)
214 return;
215
216 /* pread does a seek and a read in one shot: saves a few lines. */
217 r = pread(fd, addr, len, offset);
218 if (r != len)
219 err(1, "Reading offset %lu len %lu gave %zi", offset, len, r);
220}
221
Rusty Russelldde79782007-07-26 10:41:03 -0700222/* This routine takes an open vmlinux image, which is in ELF, and maps it into
223 * the Guest memory. ELF = Embedded Linking Format, which is the format used
224 * by all modern binaries on Linux including the kernel.
225 *
226 * The ELF headers give *two* addresses: a physical address, and a virtual
227 * address. The Guest kernel expects to be placed in memory at the physical
228 * address, and the page tables set up so it will correspond to that virtual
229 * address. We return the difference between the virtual and physical
230 * addresses in the "page_offset" pointer.
231 *
232 * We return the starting address. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700233static unsigned long map_elf(int elf_fd, const Elf32_Ehdr *ehdr,
234 unsigned long *page_offset)
235{
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000236 void *start = (void *)-1, *end = NULL;
Rusty Russell8ca47e02007-07-19 01:49:29 -0700237 Elf32_Phdr phdr[ehdr->e_phnum];
238 unsigned int i;
Rusty Russell8ca47e02007-07-19 01:49:29 -0700239
Rusty Russelldde79782007-07-26 10:41:03 -0700240 /* Sanity checks on the main ELF header: an x86 executable with a
241 * reasonable number of correctly-sized program headers. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700242 if (ehdr->e_type != ET_EXEC
243 || ehdr->e_machine != EM_386
244 || ehdr->e_phentsize != sizeof(Elf32_Phdr)
245 || ehdr->e_phnum < 1 || ehdr->e_phnum > 65536U/sizeof(Elf32_Phdr))
246 errx(1, "Malformed elf header");
247
Rusty Russelldde79782007-07-26 10:41:03 -0700248 /* An ELF executable contains an ELF header and a number of "program"
249 * headers which indicate which parts ("segments") of the program to
250 * load where. */
251
252 /* We read in all the program headers at once: */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700253 if (lseek(elf_fd, ehdr->e_phoff, SEEK_SET) < 0)
254 err(1, "Seeking to program headers");
255 if (read(elf_fd, phdr, sizeof(phdr)) != sizeof(phdr))
256 err(1, "Reading program headers");
257
Rusty Russelldde79782007-07-26 10:41:03 -0700258 /* We don't know page_offset yet. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700259 *page_offset = 0;
Rusty Russelldde79782007-07-26 10:41:03 -0700260
261 /* Try all the headers: there are usually only three. A read-only one,
262 * a read-write one, and a "note" section which isn't loadable. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700263 for (i = 0; i < ehdr->e_phnum; i++) {
Rusty Russelldde79782007-07-26 10:41:03 -0700264 /* If this isn't a loadable segment, we ignore it */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700265 if (phdr[i].p_type != PT_LOAD)
266 continue;
267
268 verbose("Section %i: size %i addr %p\n",
269 i, phdr[i].p_memsz, (void *)phdr[i].p_paddr);
270
Rusty Russelldde79782007-07-26 10:41:03 -0700271 /* We expect a simple linear address space: every segment must
272 * have the same difference between virtual (p_vaddr) and
273 * physical (p_paddr) address. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700274 if (!*page_offset)
275 *page_offset = phdr[i].p_vaddr - phdr[i].p_paddr;
276 else if (*page_offset != phdr[i].p_vaddr - phdr[i].p_paddr)
277 errx(1, "Page offset of section %i different", i);
278
Rusty Russelldde79782007-07-26 10:41:03 -0700279 /* We track the first and last address we mapped, so we can
280 * tell entry_point() where to scan. */
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000281 if (from_guest_phys(phdr[i].p_paddr) < start)
282 start = from_guest_phys(phdr[i].p_paddr);
283 if (from_guest_phys(phdr[i].p_paddr) + phdr[i].p_filesz > end)
284 end=from_guest_phys(phdr[i].p_paddr)+phdr[i].p_filesz;
Rusty Russell8ca47e02007-07-19 01:49:29 -0700285
Ronald G. Minnich6649bb72007-08-28 14:35:59 -0700286 /* We map this section of the file at its physical address. */
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000287 map_at(elf_fd, from_guest_phys(phdr[i].p_paddr),
Ronald G. Minnich6649bb72007-08-28 14:35:59 -0700288 phdr[i].p_offset, phdr[i].p_filesz);
Rusty Russell8ca47e02007-07-19 01:49:29 -0700289 }
290
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000291 return entry_point(start, end, *page_offset);
Rusty Russell8ca47e02007-07-19 01:49:29 -0700292}
293
Rusty Russelldde79782007-07-26 10:41:03 -0700294/*L:170 Prepare to be SHOCKED and AMAZED. And possibly a trifle nauseated.
295 *
296 * We know that CONFIG_PAGE_OFFSET sets what virtual address the kernel expects
297 * to be. We don't know what that option was, but we can figure it out
298 * approximately by looking at the addresses in the code. I chose the common
299 * case of reading a memory location into the %eax register:
300 *
301 * movl <some-address>, %eax
302 *
303 * This gets encoded as five bytes: "0xA1 <4-byte-address>". For example,
304 * "0xA1 0x18 0x60 0x47 0xC0" reads the address 0xC0476018 into %eax.
305 *
306 * In this example can guess that the kernel was compiled with
307 * CONFIG_PAGE_OFFSET set to 0xC0000000 (it's always a round number). If the
308 * kernel were larger than 16MB, we might see 0xC1 addresses show up, but our
309 * kernel isn't that bloated yet.
310 *
311 * Unfortunately, x86 has variable-length instructions, so finding this
312 * particular instruction properly involves writing a disassembler. Instead,
313 * we rely on statistics. We look for "0xA1" and tally the different bytes
314 * which occur 4 bytes later (the "0xC0" in our example above). When one of
315 * those bytes appears three times, we can be reasonably confident that it
316 * forms the start of CONFIG_PAGE_OFFSET.
317 *
318 * This is amazingly reliable. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700319static unsigned long intuit_page_offset(unsigned char *img, unsigned long len)
320{
321 unsigned int i, possibilities[256] = { 0 };
322
323 for (i = 0; i + 4 < len; i++) {
324 /* mov 0xXXXXXXXX,%eax */
325 if (img[i] == 0xA1 && ++possibilities[img[i+4]] > 3)
326 return (unsigned long)img[i+4] << 24;
327 }
328 errx(1, "could not determine page offset");
329}
330
Rusty Russelldde79782007-07-26 10:41:03 -0700331/*L:160 Unfortunately the entire ELF image isn't compressed: the segments
332 * which need loading are extracted and compressed raw. This denies us the
333 * information we need to make a fully-general loader. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700334static unsigned long unpack_bzimage(int fd, unsigned long *page_offset)
335{
336 gzFile f;
337 int ret, len = 0;
Rusty Russelldde79782007-07-26 10:41:03 -0700338 /* A bzImage always gets loaded at physical address 1M. This is
339 * actually configurable as CONFIG_PHYSICAL_START, but as the comment
340 * there says, "Don't change this unless you know what you are doing".
341 * Indeed. */
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000342 void *img = from_guest_phys(0x100000);
Rusty Russell8ca47e02007-07-19 01:49:29 -0700343
Rusty Russelldde79782007-07-26 10:41:03 -0700344 /* gzdopen takes our file descriptor (carefully placed at the start of
345 * the GZIP header we found) and returns a gzFile. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700346 f = gzdopen(fd, "rb");
Rusty Russelldde79782007-07-26 10:41:03 -0700347 /* We read it into memory in 64k chunks until we hit the end. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700348 while ((ret = gzread(f, img + len, 65536)) > 0)
349 len += ret;
350 if (ret < 0)
351 err(1, "reading image from bzImage");
352
353 verbose("Unpacked size %i addr %p\n", len, img);
Rusty Russelldde79782007-07-26 10:41:03 -0700354
355 /* Without the ELF header, we can't tell virtual-physical gap. This is
356 * CONFIG_PAGE_OFFSET, and people do actually change it. Fortunately,
357 * I have a clever way of figuring it out from the code itself. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700358 *page_offset = intuit_page_offset(img, len);
359
360 return entry_point(img, img + len, *page_offset);
361}
362
Rusty Russelldde79782007-07-26 10:41:03 -0700363/*L:150 A bzImage, unlike an ELF file, is not meant to be loaded. You're
364 * supposed to jump into it and it will unpack itself. We can't do that
365 * because the Guest can't run the unpacking code, and adding features to
366 * lguest kills puppies, so we don't want to.
367 *
368 * The bzImage is formed by putting the decompressing code in front of the
369 * compressed kernel code. So we can simple scan through it looking for the
370 * first "gzip" header, and start decompressing from there. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700371static unsigned long load_bzimage(int fd, unsigned long *page_offset)
372{
373 unsigned char c;
374 int state = 0;
375
Rusty Russelldde79782007-07-26 10:41:03 -0700376 /* GZIP header is 0x1F 0x8B <method> <flags>... <compressed-by>. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700377 while (read(fd, &c, 1) == 1) {
378 switch (state) {
379 case 0:
380 if (c == 0x1F)
381 state++;
382 break;
383 case 1:
384 if (c == 0x8B)
385 state++;
386 else
387 state = 0;
388 break;
389 case 2 ... 8:
390 state++;
391 break;
392 case 9:
Rusty Russelldde79782007-07-26 10:41:03 -0700393 /* Seek back to the start of the gzip header. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700394 lseek(fd, -10, SEEK_CUR);
Rusty Russelldde79782007-07-26 10:41:03 -0700395 /* One final check: "compressed under UNIX". */
396 if (c != 0x03)
Rusty Russell8ca47e02007-07-19 01:49:29 -0700397 state = -1;
398 else
399 return unpack_bzimage(fd, page_offset);
400 }
401 }
402 errx(1, "Could not find kernel in bzImage");
403}
404
Rusty Russelldde79782007-07-26 10:41:03 -0700405/*L:140 Loading the kernel is easy when it's a "vmlinux", but most kernels
406 * come wrapped up in the self-decompressing "bzImage" format. With some funky
407 * coding, we can load those, too. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700408static unsigned long load_kernel(int fd, unsigned long *page_offset)
409{
410 Elf32_Ehdr hdr;
411
Rusty Russelldde79782007-07-26 10:41:03 -0700412 /* Read in the first few bytes. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700413 if (read(fd, &hdr, sizeof(hdr)) != sizeof(hdr))
414 err(1, "Reading kernel");
415
Rusty Russelldde79782007-07-26 10:41:03 -0700416 /* If it's an ELF file, it starts with "\177ELF" */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700417 if (memcmp(hdr.e_ident, ELFMAG, SELFMAG) == 0)
418 return map_elf(fd, &hdr, page_offset);
419
Rusty Russelldde79782007-07-26 10:41:03 -0700420 /* Otherwise we assume it's a bzImage, and try to unpack it */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700421 return load_bzimage(fd, page_offset);
422}
423
Rusty Russelldde79782007-07-26 10:41:03 -0700424/* This is a trivial little helper to align pages. Andi Kleen hated it because
425 * it calls getpagesize() twice: "it's dumb code."
426 *
427 * Kernel guys get really het up about optimization, even when it's not
428 * necessary. I leave this code as a reaction against that. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700429static inline unsigned long page_align(unsigned long addr)
430{
Rusty Russelldde79782007-07-26 10:41:03 -0700431 /* Add upwards and truncate downwards. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700432 return ((addr + getpagesize()-1) & ~(getpagesize()-1));
433}
434
Rusty Russelldde79782007-07-26 10:41:03 -0700435/*L:180 An "initial ram disk" is a disk image loaded into memory along with
436 * the kernel which the kernel can use to boot from without needing any
437 * drivers. Most distributions now use this as standard: the initrd contains
438 * the code to load the appropriate driver modules for the current machine.
439 *
440 * Importantly, James Morris works for RedHat, and Fedora uses initrds for its
441 * kernels. He sent me this (and tells me when I break it). */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700442static unsigned long load_initrd(const char *name, unsigned long mem)
443{
444 int ifd;
445 struct stat st;
446 unsigned long len;
Rusty Russell8ca47e02007-07-19 01:49:29 -0700447
448 ifd = open_or_die(name, O_RDONLY);
Rusty Russelldde79782007-07-26 10:41:03 -0700449 /* fstat() is needed to get the file size. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700450 if (fstat(ifd, &st) < 0)
451 err(1, "fstat() on initrd '%s'", name);
452
Ronald G. Minnich6649bb72007-08-28 14:35:59 -0700453 /* We map the initrd at the top of memory, but mmap wants it to be
454 * page-aligned, so we round the size up for that. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700455 len = page_align(st.st_size);
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000456 map_at(ifd, from_guest_phys(mem - len), 0, st.st_size);
Rusty Russelldde79782007-07-26 10:41:03 -0700457 /* Once a file is mapped, you can close the file descriptor. It's a
458 * little odd, but quite useful. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700459 close(ifd);
Ronald G. Minnich6649bb72007-08-28 14:35:59 -0700460 verbose("mapped initrd %s size=%lu @ %p\n", name, len, (void*)mem-len);
Rusty Russelldde79782007-07-26 10:41:03 -0700461
462 /* We return the initrd size. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700463 return len;
464}
465
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000466/* Once we know the address the Guest kernel expects, we can construct simple
467 * linear page tables for all of memory which will get the Guest far enough
468 * into the boot to create its own.
Rusty Russelldde79782007-07-26 10:41:03 -0700469 *
470 * We lay them out of the way, just below the initrd (which is why we need to
471 * know its size). */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700472static unsigned long setup_pagetables(unsigned long mem,
473 unsigned long initrd_size,
474 unsigned long page_offset)
475{
476 u32 *pgdir, *linear;
477 unsigned int mapped_pages, i, linear_pages;
478 unsigned int ptes_per_page = getpagesize()/sizeof(u32);
479
Rusty Russelldde79782007-07-26 10:41:03 -0700480 /* Ideally we map all physical memory starting at page_offset.
481 * However, if page_offset is 0xC0000000 we can only map 1G of physical
482 * (0xC0000000 + 1G overflows). */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700483 if (mem <= -page_offset)
484 mapped_pages = mem/getpagesize();
485 else
486 mapped_pages = -page_offset/getpagesize();
487
Rusty Russelldde79782007-07-26 10:41:03 -0700488 /* Each PTE page can map ptes_per_page pages: how many do we need? */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700489 linear_pages = (mapped_pages + ptes_per_page-1)/ptes_per_page;
490
Rusty Russelldde79782007-07-26 10:41:03 -0700491 /* We put the toplevel page directory page at the top of memory. */
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000492 pgdir = from_guest_phys(mem) - initrd_size - getpagesize();
Rusty Russelldde79782007-07-26 10:41:03 -0700493
494 /* Now we use the next linear_pages pages as pte pages */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700495 linear = (void *)pgdir - linear_pages*getpagesize();
496
Rusty Russelldde79782007-07-26 10:41:03 -0700497 /* Linear mapping is easy: put every page's address into the mapping in
498 * order. PAGE_PRESENT contains the flags Present, Writable and
499 * Executable. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700500 for (i = 0; i < mapped_pages; i++)
501 linear[i] = ((i * getpagesize()) | PAGE_PRESENT);
502
Rusty Russelldde79782007-07-26 10:41:03 -0700503 /* The top level points to the linear page table pages above. The
504 * entry representing page_offset points to the first one, and they
505 * continue from there. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700506 for (i = 0; i < mapped_pages; i += ptes_per_page) {
507 pgdir[(i + page_offset/getpagesize())/ptes_per_page]
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000508 = ((to_guest_phys(linear) + i*sizeof(u32))
509 | PAGE_PRESENT);
Rusty Russell8ca47e02007-07-19 01:49:29 -0700510 }
511
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000512 verbose("Linear mapping of %u pages in %u pte pages at %#lx\n",
513 mapped_pages, linear_pages, to_guest_phys(linear));
Rusty Russell8ca47e02007-07-19 01:49:29 -0700514
Rusty Russelldde79782007-07-26 10:41:03 -0700515 /* We return the top level (guest-physical) address: the kernel needs
516 * to know where it is. */
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000517 return to_guest_phys(pgdir);
Rusty Russell8ca47e02007-07-19 01:49:29 -0700518}
519
Rusty Russelldde79782007-07-26 10:41:03 -0700520/* Simple routine to roll all the commandline arguments together with spaces
521 * between them. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700522static void concat(char *dst, char *args[])
523{
524 unsigned int i, len = 0;
525
526 for (i = 0; args[i]; i++) {
527 strcpy(dst+len, args[i]);
528 strcat(dst+len, " ");
529 len += strlen(args[i]) + 1;
530 }
531 /* In case it's empty. */
532 dst[len] = '\0';
533}
534
Rusty Russelldde79782007-07-26 10:41:03 -0700535/* This is where we actually tell the kernel to initialize the Guest. We saw
536 * the arguments it expects when we looked at initialize() in lguest_user.c:
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000537 * the base of guest "physical" memory, the top physical page to allow, the
538 * top level pagetable, the entry point and the page_offset constant for the
539 * Guest. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700540static int tell_kernel(u32 pgdir, u32 start, u32 page_offset)
541{
542 u32 args[] = { LHREQ_INITIALIZE,
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000543 (unsigned long)guest_base,
544 guest_limit / getpagesize(),
545 pgdir, start, page_offset };
Rusty Russell8ca47e02007-07-19 01:49:29 -0700546 int fd;
547
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000548 verbose("Guest: %p - %p (%#lx)\n",
549 guest_base, guest_base + guest_limit, guest_limit);
Rusty Russell8ca47e02007-07-19 01:49:29 -0700550 fd = open_or_die("/dev/lguest", O_RDWR);
551 if (write(fd, args, sizeof(args)) < 0)
552 err(1, "Writing to /dev/lguest");
Rusty Russelldde79782007-07-26 10:41:03 -0700553
554 /* We return the /dev/lguest file descriptor to control this Guest */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700555 return fd;
556}
Rusty Russelldde79782007-07-26 10:41:03 -0700557/*:*/
Rusty Russell8ca47e02007-07-19 01:49:29 -0700558
559static void set_fd(int fd, struct device_list *devices)
560{
561 FD_SET(fd, &devices->infds);
562 if (fd > devices->max_infd)
563 devices->max_infd = fd;
564}
565
Rusty Russelldde79782007-07-26 10:41:03 -0700566/*L:200
567 * The Waker.
568 *
569 * With a console and network devices, we can have lots of input which we need
570 * to process. We could try to tell the kernel what file descriptors to watch,
571 * but handing a file descriptor mask through to the kernel is fairly icky.
572 *
573 * Instead, we fork off a process which watches the file descriptors and writes
574 * the LHREQ_BREAK command to the /dev/lguest filedescriptor to tell the Host
575 * loop to stop running the Guest. This causes it to return from the
576 * /dev/lguest read with -EAGAIN, where it will write to /dev/lguest to reset
577 * the LHREQ_BREAK and wake us up again.
578 *
579 * This, of course, is merely a different *kind* of icky.
580 */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700581static void wake_parent(int pipefd, int lguest_fd, struct device_list *devices)
582{
Rusty Russelldde79782007-07-26 10:41:03 -0700583 /* Add the pipe from the Launcher to the fdset in the device_list, so
584 * we watch it, too. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700585 set_fd(pipefd, devices);
586
587 for (;;) {
588 fd_set rfds = devices->infds;
589 u32 args[] = { LHREQ_BREAK, 1 };
590
Rusty Russelldde79782007-07-26 10:41:03 -0700591 /* Wait until input is ready from one of the devices. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700592 select(devices->max_infd+1, &rfds, NULL, NULL, NULL);
Rusty Russelldde79782007-07-26 10:41:03 -0700593 /* Is it a message from the Launcher? */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700594 if (FD_ISSET(pipefd, &rfds)) {
595 int ignorefd;
Rusty Russelldde79782007-07-26 10:41:03 -0700596 /* If read() returns 0, it means the Launcher has
597 * exited. We silently follow. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700598 if (read(pipefd, &ignorefd, sizeof(ignorefd)) == 0)
599 exit(0);
Rusty Russelldde79782007-07-26 10:41:03 -0700600 /* Otherwise it's telling us there's a problem with one
601 * of the devices, and we should ignore that file
602 * descriptor from now on. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700603 FD_CLR(ignorefd, &devices->infds);
Rusty Russelldde79782007-07-26 10:41:03 -0700604 } else /* Send LHREQ_BREAK command. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700605 write(lguest_fd, args, sizeof(args));
606 }
607}
608
Rusty Russelldde79782007-07-26 10:41:03 -0700609/* This routine just sets up a pipe to the Waker process. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700610static int setup_waker(int lguest_fd, struct device_list *device_list)
611{
612 int pipefd[2], child;
613
Rusty Russelldde79782007-07-26 10:41:03 -0700614 /* We create a pipe to talk to the waker, and also so it knows when the
615 * Launcher dies (and closes pipe). */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700616 pipe(pipefd);
617 child = fork();
618 if (child == -1)
619 err(1, "forking");
620
621 if (child == 0) {
Rusty Russelldde79782007-07-26 10:41:03 -0700622 /* Close the "writing" end of our copy of the pipe */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700623 close(pipefd[1]);
624 wake_parent(pipefd[0], lguest_fd, device_list);
625 }
Rusty Russelldde79782007-07-26 10:41:03 -0700626 /* Close the reading end of our copy of the pipe. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700627 close(pipefd[0]);
628
Rusty Russelldde79782007-07-26 10:41:03 -0700629 /* Here is the fd used to talk to the waker. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700630 return pipefd[1];
631}
632
Rusty Russelldde79782007-07-26 10:41:03 -0700633/*L:210
634 * Device Handling.
635 *
636 * When the Guest sends DMA to us, it sends us an array of addresses and sizes.
637 * We need to make sure it's not trying to reach into the Launcher itself, so
638 * we have a convenient routine which check it and exits with an error message
639 * if something funny is going on:
640 */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700641static void *_check_pointer(unsigned long addr, unsigned int size,
642 unsigned int line)
643{
Rusty Russelldde79782007-07-26 10:41:03 -0700644 /* We have to separately check addr and addr+size, because size could
645 * be huge and addr + size might wrap around. */
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000646 if (addr >= guest_limit || addr + size >= guest_limit)
Rusty Russell8ca47e02007-07-19 01:49:29 -0700647 errx(1, "%s:%i: Invalid address %li", __FILE__, line, addr);
Rusty Russelldde79782007-07-26 10:41:03 -0700648 /* We return a pointer for the caller's convenience, now we know it's
649 * safe to use. */
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000650 return from_guest_phys(addr);
Rusty Russell8ca47e02007-07-19 01:49:29 -0700651}
Rusty Russelldde79782007-07-26 10:41:03 -0700652/* A macro which transparently hands the line number to the real function. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700653#define check_pointer(addr,size) _check_pointer(addr, size, __LINE__)
654
Rusty Russelldde79782007-07-26 10:41:03 -0700655/* The Guest has given us the address of a "struct lguest_dma". We check it's
656 * OK and convert it to an iovec (which is a simple array of ptr/size
657 * pairs). */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700658static u32 *dma2iov(unsigned long dma, struct iovec iov[], unsigned *num)
659{
660 unsigned int i;
661 struct lguest_dma *udma;
662
Rusty Russelldde79782007-07-26 10:41:03 -0700663 /* First we make sure that the array memory itself is valid. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700664 udma = check_pointer(dma, sizeof(*udma));
Rusty Russelldde79782007-07-26 10:41:03 -0700665 /* Now we check each element */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700666 for (i = 0; i < LGUEST_MAX_DMA_SECTIONS; i++) {
Rusty Russelldde79782007-07-26 10:41:03 -0700667 /* A zero length ends the array. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700668 if (!udma->len[i])
669 break;
670
671 iov[i].iov_base = check_pointer(udma->addr[i], udma->len[i]);
672 iov[i].iov_len = udma->len[i];
673 }
674 *num = i;
Rusty Russelldde79782007-07-26 10:41:03 -0700675
676 /* We return the pointer to where the caller should write the amount of
677 * the buffer used. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700678 return &udma->used_len;
679}
680
Rusty Russelldde79782007-07-26 10:41:03 -0700681/* This routine gets a DMA buffer from the Guest for a given key, and converts
682 * it to an iovec array. It returns the interrupt the Guest wants when we're
683 * finished, and a pointer to the "used_len" field to fill in. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700684static u32 *get_dma_buffer(int fd, void *key,
685 struct iovec iov[], unsigned int *num, u32 *irq)
686{
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000687 u32 buf[] = { LHREQ_GETDMA, to_guest_phys(key) };
Rusty Russell8ca47e02007-07-19 01:49:29 -0700688 unsigned long udma;
689 u32 *res;
690
Rusty Russelldde79782007-07-26 10:41:03 -0700691 /* Ask the kernel for a DMA buffer corresponding to this key. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700692 udma = write(fd, buf, sizeof(buf));
Rusty Russelldde79782007-07-26 10:41:03 -0700693 /* They haven't registered any, or they're all used? */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700694 if (udma == (unsigned long)-1)
695 return NULL;
696
Rusty Russelldde79782007-07-26 10:41:03 -0700697 /* Convert it into our iovec array */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700698 res = dma2iov(udma, iov, num);
Rusty Russelldde79782007-07-26 10:41:03 -0700699 /* The kernel stashes irq in ->used_len to get it out to us. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700700 *irq = *res;
Rusty Russelldde79782007-07-26 10:41:03 -0700701 /* Return a pointer to ((struct lguest_dma *)udma)->used_len. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700702 return res;
703}
704
Rusty Russelldde79782007-07-26 10:41:03 -0700705/* This is a convenient routine to send the Guest an interrupt. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700706static void trigger_irq(int fd, u32 irq)
707{
708 u32 buf[] = { LHREQ_IRQ, irq };
709 if (write(fd, buf, sizeof(buf)) != 0)
710 err(1, "Triggering irq %i", irq);
711}
712
Rusty Russelldde79782007-07-26 10:41:03 -0700713/* This simply sets up an iovec array where we can put data to be discarded.
714 * This happens when the Guest doesn't want or can't handle the input: we have
715 * to get rid of it somewhere, and if we bury it in the ceiling space it will
716 * start to smell after a week. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700717static void discard_iovec(struct iovec *iov, unsigned int *num)
718{
719 static char discard_buf[1024];
720 *num = 1;
721 iov->iov_base = discard_buf;
722 iov->iov_len = sizeof(discard_buf);
723}
724
Rusty Russelldde79782007-07-26 10:41:03 -0700725/* Here is the input terminal setting we save, and the routine to restore them
726 * on exit so the user can see what they type next. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700727static struct termios orig_term;
728static void restore_term(void)
729{
730 tcsetattr(STDIN_FILENO, TCSANOW, &orig_term);
731}
732
Rusty Russelldde79782007-07-26 10:41:03 -0700733/* We associate some data with the console for our exit hack. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700734struct console_abort
735{
Rusty Russelldde79782007-07-26 10:41:03 -0700736 /* How many times have they hit ^C? */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700737 int count;
Rusty Russelldde79782007-07-26 10:41:03 -0700738 /* When did they start? */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700739 struct timeval start;
740};
741
Rusty Russelldde79782007-07-26 10:41:03 -0700742/* This is the routine which handles console input (ie. stdin). */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700743static bool handle_console_input(int fd, struct device *dev)
744{
745 u32 irq = 0, *lenp;
746 int len;
747 unsigned int num;
748 struct iovec iov[LGUEST_MAX_DMA_SECTIONS];
749 struct console_abort *abort = dev->priv;
750
Rusty Russelldde79782007-07-26 10:41:03 -0700751 /* First we get the console buffer from the Guest. The key is dev->mem
752 * which was set to 0 in setup_console(). */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700753 lenp = get_dma_buffer(fd, dev->mem, iov, &num, &irq);
754 if (!lenp) {
Rusty Russelldde79782007-07-26 10:41:03 -0700755 /* If it's not ready for input, warn and set up to discard. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700756 warn("console: no dma buffer!");
757 discard_iovec(iov, &num);
758 }
759
Rusty Russelldde79782007-07-26 10:41:03 -0700760 /* This is why we convert to iovecs: the readv() call uses them, and so
761 * it reads straight into the Guest's buffer. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700762 len = readv(dev->fd, iov, num);
763 if (len <= 0) {
Rusty Russelldde79782007-07-26 10:41:03 -0700764 /* This implies that the console is closed, is /dev/null, or
765 * something went terribly wrong. We still go through the rest
766 * of the logic, though, especially the exit handling below. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700767 warnx("Failed to get console input, ignoring console.");
768 len = 0;
769 }
770
Rusty Russelldde79782007-07-26 10:41:03 -0700771 /* If we read the data into the Guest, fill in the length and send the
772 * interrupt. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700773 if (lenp) {
774 *lenp = len;
775 trigger_irq(fd, irq);
776 }
777
Rusty Russelldde79782007-07-26 10:41:03 -0700778 /* Three ^C within one second? Exit.
779 *
780 * This is such a hack, but works surprisingly well. Each ^C has to be
781 * in a buffer by itself, so they can't be too fast. But we check that
782 * we get three within about a second, so they can't be too slow. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700783 if (len == 1 && ((char *)iov[0].iov_base)[0] == 3) {
784 if (!abort->count++)
785 gettimeofday(&abort->start, NULL);
786 else if (abort->count == 3) {
787 struct timeval now;
788 gettimeofday(&now, NULL);
789 if (now.tv_sec <= abort->start.tv_sec+1) {
Rusty Russell8ca47e02007-07-19 01:49:29 -0700790 u32 args[] = { LHREQ_BREAK, 0 };
Rusty Russelldde79782007-07-26 10:41:03 -0700791 /* Close the fd so Waker will know it has to
792 * exit. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700793 close(waker_fd);
Rusty Russelldde79782007-07-26 10:41:03 -0700794 /* Just in case waker is blocked in BREAK, send
795 * unbreak now. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700796 write(fd, args, sizeof(args));
797 exit(2);
798 }
799 abort->count = 0;
800 }
801 } else
Rusty Russelldde79782007-07-26 10:41:03 -0700802 /* Any other key resets the abort counter. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700803 abort->count = 0;
804
Rusty Russelldde79782007-07-26 10:41:03 -0700805 /* Now, if we didn't read anything, put the input terminal back and
806 * return failure (meaning, don't call us again). */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700807 if (!len) {
808 restore_term();
809 return false;
810 }
Rusty Russelldde79782007-07-26 10:41:03 -0700811 /* Everything went OK! */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700812 return true;
813}
814
Rusty Russelldde79782007-07-26 10:41:03 -0700815/* Handling console output is much simpler than input. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700816static u32 handle_console_output(int fd, const struct iovec *iov,
817 unsigned num, struct device*dev)
818{
Rusty Russelldde79782007-07-26 10:41:03 -0700819 /* Whatever the Guest sends, write it to standard output. Return the
820 * number of bytes written. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700821 return writev(STDOUT_FILENO, iov, num);
822}
823
Rusty Russelldde79782007-07-26 10:41:03 -0700824/* Guest->Host network output is also pretty easy. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700825static u32 handle_tun_output(int fd, const struct iovec *iov,
826 unsigned num, struct device *dev)
827{
Rusty Russelldde79782007-07-26 10:41:03 -0700828 /* We put a flag in the "priv" pointer of the network device, and set
829 * it as soon as we see output. We'll see why in handle_tun_input() */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700830 *(bool *)dev->priv = true;
Rusty Russelldde79782007-07-26 10:41:03 -0700831 /* Whatever packet the Guest sent us, write it out to the tun
832 * device. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700833 return writev(dev->fd, iov, num);
834}
835
Rusty Russelldde79782007-07-26 10:41:03 -0700836/* This matches the peer_key() in lguest_net.c. The key for any given slot
837 * is the address of the network device's page plus 4 * the slot number. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700838static unsigned long peer_offset(unsigned int peernum)
839{
840 return 4 * peernum;
841}
842
Rusty Russelldde79782007-07-26 10:41:03 -0700843/* This is where we handle a packet coming in from the tun device */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700844static bool handle_tun_input(int fd, struct device *dev)
845{
846 u32 irq = 0, *lenp;
847 int len;
848 unsigned num;
849 struct iovec iov[LGUEST_MAX_DMA_SECTIONS];
850
Rusty Russelldde79782007-07-26 10:41:03 -0700851 /* First we get a buffer the Guest has bound to its key. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700852 lenp = get_dma_buffer(fd, dev->mem+peer_offset(NET_PEERNUM), iov, &num,
853 &irq);
854 if (!lenp) {
Rusty Russelldde79782007-07-26 10:41:03 -0700855 /* Now, it's expected that if we try to send a packet too
856 * early, the Guest won't be ready yet. This is why we set a
857 * flag when the Guest sends its first packet. If it's sent a
858 * packet we assume it should be ready to receive them.
859 *
860 * Actually, this is what the status bits in the descriptor are
861 * for: we should *use* them. FIXME! */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700862 if (*(bool *)dev->priv)
863 warn("network: no dma buffer!");
864 discard_iovec(iov, &num);
865 }
866
Rusty Russelldde79782007-07-26 10:41:03 -0700867 /* Read the packet from the device directly into the Guest's buffer. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700868 len = readv(dev->fd, iov, num);
869 if (len <= 0)
870 err(1, "reading network");
Rusty Russelldde79782007-07-26 10:41:03 -0700871
872 /* Write the used_len, and trigger the interrupt for the Guest */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700873 if (lenp) {
874 *lenp = len;
875 trigger_irq(fd, irq);
876 }
877 verbose("tun input packet len %i [%02x %02x] (%s)\n", len,
878 ((u8 *)iov[0].iov_base)[0], ((u8 *)iov[0].iov_base)[1],
879 lenp ? "sent" : "discarded");
Rusty Russelldde79782007-07-26 10:41:03 -0700880 /* All good. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700881 return true;
882}
883
Rusty Russelldde79782007-07-26 10:41:03 -0700884/* The last device handling routine is block output: the Guest has sent a DMA
885 * to the block device. It will have placed the command it wants in the
886 * "struct lguest_block_page". */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700887static u32 handle_block_output(int fd, const struct iovec *iov,
888 unsigned num, struct device *dev)
889{
890 struct lguest_block_page *p = dev->mem;
891 u32 irq, *lenp;
892 unsigned int len, reply_num;
893 struct iovec reply[LGUEST_MAX_DMA_SECTIONS];
894 off64_t device_len, off = (off64_t)p->sector * 512;
895
Rusty Russelldde79782007-07-26 10:41:03 -0700896 /* First we extract the device length from the dev->priv pointer. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700897 device_len = *(off64_t *)dev->priv;
898
Rusty Russelldde79782007-07-26 10:41:03 -0700899 /* We first check that the read or write is within the length of the
900 * block file. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700901 if (off >= device_len)
Glauber de Oliveira Costababed5c2007-10-22 10:56:21 +1000902 errx(1, "Bad offset %llu vs %llu", off, device_len);
Rusty Russelldde79782007-07-26 10:41:03 -0700903 /* Move to the right location in the block file. This shouldn't fail,
904 * but best to check. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700905 if (lseek64(dev->fd, off, SEEK_SET) != off)
906 err(1, "Bad seek to sector %i", p->sector);
907
908 verbose("Block: %s at offset %llu\n", p->type ? "WRITE" : "READ", off);
909
Rusty Russelldde79782007-07-26 10:41:03 -0700910 /* They were supposed to bind a reply buffer at key equal to the start
911 * of the block device memory. We need this to tell them when the
912 * request is finished. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700913 lenp = get_dma_buffer(fd, dev->mem, reply, &reply_num, &irq);
914 if (!lenp)
915 err(1, "Block request didn't give us a dma buffer");
916
917 if (p->type) {
Rusty Russelldde79782007-07-26 10:41:03 -0700918 /* A write request. The DMA they sent contained the data, so
919 * write it out. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700920 len = writev(dev->fd, iov, num);
Rusty Russelldde79782007-07-26 10:41:03 -0700921 /* Grr... Now we know how long the "struct lguest_dma" they
922 * sent was, we make sure they didn't try to write over the end
923 * of the block file (possibly extending it). */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700924 if (off + len > device_len) {
Rusty Russelldde79782007-07-26 10:41:03 -0700925 /* Trim it back to the correct length */
Chris Malleyf6a592e2007-09-26 14:19:18 +1000926 ftruncate64(dev->fd, device_len);
Rusty Russelldde79782007-07-26 10:41:03 -0700927 /* Die, bad Guest, die. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700928 errx(1, "Write past end %llu+%u", off, len);
929 }
Rusty Russelldde79782007-07-26 10:41:03 -0700930 /* The reply length is 0: we just send back an empty DMA to
931 * interrupt them and tell them the write is finished. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700932 *lenp = 0;
933 } else {
Rusty Russelldde79782007-07-26 10:41:03 -0700934 /* A read request. They sent an empty DMA to start the
935 * request, and we put the read contents into the reply
936 * buffer. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700937 len = readv(dev->fd, reply, reply_num);
938 *lenp = len;
939 }
940
Rusty Russelldde79782007-07-26 10:41:03 -0700941 /* The result is 1 (done), 2 if there was an error (short read or
942 * write). */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700943 p->result = 1 + (p->bytes != len);
Rusty Russelldde79782007-07-26 10:41:03 -0700944 /* Now tell them we've used their reply buffer. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700945 trigger_irq(fd, irq);
Rusty Russelldde79782007-07-26 10:41:03 -0700946
947 /* We're supposed to return the number of bytes of the output buffer we
948 * used. But the block device uses the "result" field instead, so we
949 * don't bother. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700950 return 0;
951}
952
Rusty Russelldde79782007-07-26 10:41:03 -0700953/* This is the generic routine we call when the Guest sends some DMA out. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700954static void handle_output(int fd, unsigned long dma, unsigned long key,
955 struct device_list *devices)
956{
957 struct device *i;
958 u32 *lenp;
959 struct iovec iov[LGUEST_MAX_DMA_SECTIONS];
960 unsigned num = 0;
961
Rusty Russelldde79782007-07-26 10:41:03 -0700962 /* Convert the "struct lguest_dma" they're sending to a "struct
963 * iovec". */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700964 lenp = dma2iov(dma, iov, &num);
Rusty Russelldde79782007-07-26 10:41:03 -0700965
966 /* Check each device: if they expect output to this key, tell them to
967 * handle it. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700968 for (i = devices->dev; i; i = i->next) {
969 if (i->handle_output && key == i->watch_key) {
Rusty Russelldde79782007-07-26 10:41:03 -0700970 /* We write the result straight into the used_len field
971 * for them. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700972 *lenp = i->handle_output(fd, iov, num, i);
973 return;
974 }
975 }
Rusty Russelldde79782007-07-26 10:41:03 -0700976
977 /* This can happen: the kernel sends any SEND_DMA which doesn't match
978 * another Guest to us. It could be that another Guest just left a
979 * network, for example. But it's unusual. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700980 warnx("Pending dma %p, key %p", (void *)dma, (void *)key);
981}
982
Rusty Russelldde79782007-07-26 10:41:03 -0700983/* This is called when the waker wakes us up: check for incoming file
984 * descriptors. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700985static void handle_input(int fd, struct device_list *devices)
986{
Rusty Russelldde79782007-07-26 10:41:03 -0700987 /* select() wants a zeroed timeval to mean "don't wait". */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700988 struct timeval poll = { .tv_sec = 0, .tv_usec = 0 };
989
990 for (;;) {
991 struct device *i;
992 fd_set fds = devices->infds;
993
Rusty Russelldde79782007-07-26 10:41:03 -0700994 /* If nothing is ready, we're done. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700995 if (select(devices->max_infd+1, &fds, NULL, NULL, &poll) == 0)
996 break;
997
Rusty Russelldde79782007-07-26 10:41:03 -0700998 /* Otherwise, call the device(s) which have readable
999 * file descriptors and a method of handling them. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001000 for (i = devices->dev; i; i = i->next) {
1001 if (i->handle_input && FD_ISSET(i->fd, &fds)) {
Rusty Russelldde79782007-07-26 10:41:03 -07001002 /* If handle_input() returns false, it means we
1003 * should no longer service it.
1004 * handle_console_input() does this. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001005 if (!i->handle_input(fd, i)) {
Rusty Russelldde79782007-07-26 10:41:03 -07001006 /* Clear it from the set of input file
1007 * descriptors kept at the head of the
1008 * device list. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001009 FD_CLR(i->fd, &devices->infds);
1010 /* Tell waker to ignore it too... */
1011 write(waker_fd, &i->fd, sizeof(i->fd));
1012 }
1013 }
1014 }
1015 }
1016}
1017
Rusty Russelldde79782007-07-26 10:41:03 -07001018/*L:190
1019 * Device Setup
1020 *
1021 * All devices need a descriptor so the Guest knows it exists, and a "struct
1022 * device" so the Launcher can keep track of it. We have common helper
1023 * routines to allocate them.
1024 *
1025 * This routine allocates a new "struct lguest_device_desc" from descriptor
1026 * table in the devices array just above the Guest's normal memory. */
Rusty Russell6570c45992007-07-23 18:43:56 -07001027static struct lguest_device_desc *
1028new_dev_desc(struct lguest_device_desc *descs,
1029 u16 type, u16 features, u16 num_pages)
Rusty Russell8ca47e02007-07-19 01:49:29 -07001030{
Rusty Russell6570c45992007-07-23 18:43:56 -07001031 unsigned int i;
Rusty Russell8ca47e02007-07-19 01:49:29 -07001032
Rusty Russell6570c45992007-07-23 18:43:56 -07001033 for (i = 0; i < LGUEST_MAX_DEVICES; i++) {
1034 if (!descs[i].type) {
1035 descs[i].type = type;
1036 descs[i].features = features;
1037 descs[i].num_pages = num_pages;
Rusty Russelldde79782007-07-26 10:41:03 -07001038 /* If they said the device needs memory, we allocate
Rusty Russell3c6b5bf2007-10-22 11:03:26 +10001039 * that now. */
Rusty Russell6570c45992007-07-23 18:43:56 -07001040 if (num_pages) {
Rusty Russell3c6b5bf2007-10-22 11:03:26 +10001041 unsigned long pa;
1042 pa = to_guest_phys(get_pages(num_pages));
1043 descs[i].pfn = pa / getpagesize();
Rusty Russell6570c45992007-07-23 18:43:56 -07001044 }
1045 return &descs[i];
1046 }
1047 }
1048 errx(1, "too many devices");
Rusty Russell8ca47e02007-07-19 01:49:29 -07001049}
1050
Rusty Russelldde79782007-07-26 10:41:03 -07001051/* This monster routine does all the creation and setup of a new device,
1052 * including caling new_dev_desc() to allocate the descriptor and device
1053 * memory. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001054static struct device *new_device(struct device_list *devices,
1055 u16 type, u16 num_pages, u16 features,
1056 int fd,
1057 bool (*handle_input)(int, struct device *),
1058 unsigned long watch_off,
1059 u32 (*handle_output)(int,
1060 const struct iovec *,
1061 unsigned,
1062 struct device *))
1063{
1064 struct device *dev = malloc(sizeof(*dev));
1065
Rusty Russelldde79782007-07-26 10:41:03 -07001066 /* Append to device list. Prepending to a single-linked list is
1067 * easier, but the user expects the devices to be arranged on the bus
1068 * in command-line order. The first network device on the command line
1069 * is eth0, the first block device /dev/lgba, etc. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001070 *devices->lastdev = dev;
1071 dev->next = NULL;
1072 devices->lastdev = &dev->next;
1073
Rusty Russelldde79782007-07-26 10:41:03 -07001074 /* Now we populate the fields one at a time. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001075 dev->fd = fd;
Rusty Russelldde79782007-07-26 10:41:03 -07001076 /* If we have an input handler for this file descriptor, then we add it
1077 * to the device_list's fdset and maxfd. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001078 if (handle_input)
1079 set_fd(dev->fd, devices);
Rusty Russell6570c45992007-07-23 18:43:56 -07001080 dev->desc = new_dev_desc(devices->descs, type, features, num_pages);
Rusty Russell3c6b5bf2007-10-22 11:03:26 +10001081 dev->mem = from_guest_phys(dev->desc->pfn * getpagesize());
Rusty Russell8ca47e02007-07-19 01:49:29 -07001082 dev->handle_input = handle_input;
Rusty Russell3c6b5bf2007-10-22 11:03:26 +10001083 dev->watch_key = to_guest_phys(dev->mem) + watch_off;
Rusty Russell8ca47e02007-07-19 01:49:29 -07001084 dev->handle_output = handle_output;
1085 return dev;
1086}
1087
Rusty Russelldde79782007-07-26 10:41:03 -07001088/* Our first setup routine is the console. It's a fairly simple device, but
1089 * UNIX tty handling makes it uglier than it could be. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001090static void setup_console(struct device_list *devices)
1091{
1092 struct device *dev;
1093
Rusty Russelldde79782007-07-26 10:41:03 -07001094 /* If we can save the initial standard input settings... */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001095 if (tcgetattr(STDIN_FILENO, &orig_term) == 0) {
1096 struct termios term = orig_term;
Rusty Russelldde79782007-07-26 10:41:03 -07001097 /* Then we turn off echo, line buffering and ^C etc. We want a
1098 * raw input stream to the Guest. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001099 term.c_lflag &= ~(ISIG|ICANON|ECHO);
1100 tcsetattr(STDIN_FILENO, TCSANOW, &term);
Rusty Russelldde79782007-07-26 10:41:03 -07001101 /* If we exit gracefully, the original settings will be
1102 * restored so the user can see what they're typing. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001103 atexit(restore_term);
1104 }
1105
Rusty Russelldde79782007-07-26 10:41:03 -07001106 /* We don't currently require any memory for the console, so we ask for
1107 * 0 pages. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001108 dev = new_device(devices, LGUEST_DEVICE_T_CONSOLE, 0, 0,
1109 STDIN_FILENO, handle_console_input,
1110 LGUEST_CONSOLE_DMA_KEY, handle_console_output);
Rusty Russelldde79782007-07-26 10:41:03 -07001111 /* We store the console state in dev->priv, and initialize it. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001112 dev->priv = malloc(sizeof(struct console_abort));
1113 ((struct console_abort *)dev->priv)->count = 0;
1114 verbose("device %p: console\n",
1115 (void *)(dev->desc->pfn * getpagesize()));
1116}
1117
Rusty Russelldde79782007-07-26 10:41:03 -07001118/* Setting up a block file is also fairly straightforward. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001119static void setup_block_file(const char *filename, struct device_list *devices)
1120{
1121 int fd;
1122 struct device *dev;
1123 off64_t *device_len;
1124 struct lguest_block_page *p;
1125
Rusty Russelldde79782007-07-26 10:41:03 -07001126 /* We open with O_LARGEFILE because otherwise we get stuck at 2G. We
1127 * open with O_DIRECT because otherwise our benchmarks go much too
1128 * fast. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001129 fd = open_or_die(filename, O_RDWR|O_LARGEFILE|O_DIRECT);
Rusty Russelldde79782007-07-26 10:41:03 -07001130
1131 /* We want one page, and have no input handler (the block file never
1132 * has anything interesting to say to us). Our timing will be quite
1133 * random, so it should be a reasonable randomness source. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001134 dev = new_device(devices, LGUEST_DEVICE_T_BLOCK, 1,
1135 LGUEST_DEVICE_F_RANDOMNESS,
1136 fd, NULL, 0, handle_block_output);
Rusty Russell8ca47e02007-07-19 01:49:29 -07001137
Rusty Russelldde79782007-07-26 10:41:03 -07001138 /* We store the device size in the private area */
1139 device_len = dev->priv = malloc(sizeof(*device_len));
1140 /* This is the safe way of establishing the size of our device: it
1141 * might be a normal file or an actual block device like /dev/hdb. */
1142 *device_len = lseek64(fd, 0, SEEK_END);
1143
1144 /* The device memory is a "struct lguest_block_page". It's zeroed
1145 * already, we just need to put in the device size. Block devices
1146 * think in sectors (ie. 512 byte chunks), so we translate here. */
1147 p = dev->mem;
Rusty Russell8ca47e02007-07-19 01:49:29 -07001148 p->num_sectors = *device_len/512;
1149 verbose("device %p: block %i sectors\n",
1150 (void *)(dev->desc->pfn * getpagesize()), p->num_sectors);
1151}
1152
Rusty Russelldde79782007-07-26 10:41:03 -07001153/*
1154 * Network Devices.
1155 *
1156 * Setting up network devices is quite a pain, because we have three types.
1157 * First, we have the inter-Guest network. This is a file which is mapped into
1158 * the address space of the Guests who are on the network. Because it is a
1159 * shared mapping, the same page underlies all the devices, and they can send
1160 * DMA to each other.
1161 *
1162 * Remember from our network driver, the Guest is told what slot in the page it
1163 * is to use. We use exclusive fnctl locks to reserve a slot. If another
1164 * Guest is using a slot, the lock will fail and we try another. Because fnctl
1165 * locks are cleaned up automatically when we die, this cleverly means that our
1166 * reservation on the slot will vanish if we crash. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001167static unsigned int find_slot(int netfd, const char *filename)
1168{
1169 struct flock fl;
1170
1171 fl.l_type = F_WRLCK;
1172 fl.l_whence = SEEK_SET;
1173 fl.l_len = 1;
Rusty Russelldde79782007-07-26 10:41:03 -07001174 /* Try a 1 byte lock in each possible position number */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001175 for (fl.l_start = 0;
1176 fl.l_start < getpagesize()/sizeof(struct lguest_net);
1177 fl.l_start++) {
Rusty Russelldde79782007-07-26 10:41:03 -07001178 /* If we succeed, return the slot number. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001179 if (fcntl(netfd, F_SETLK, &fl) == 0)
1180 return fl.l_start;
1181 }
1182 errx(1, "No free slots in network file %s", filename);
1183}
1184
Rusty Russelldde79782007-07-26 10:41:03 -07001185/* This function sets up the network file */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001186static void setup_net_file(const char *filename,
1187 struct device_list *devices)
1188{
1189 int netfd;
1190 struct device *dev;
1191
Rusty Russelldde79782007-07-26 10:41:03 -07001192 /* We don't use open_or_die() here: for friendliness we create the file
1193 * if it doesn't already exist. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001194 netfd = open(filename, O_RDWR, 0);
1195 if (netfd < 0) {
1196 if (errno == ENOENT) {
1197 netfd = open(filename, O_RDWR|O_CREAT, 0600);
1198 if (netfd >= 0) {
Rusty Russelldde79782007-07-26 10:41:03 -07001199 /* If we succeeded, initialize the file with a
1200 * blank page. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001201 char page[getpagesize()];
1202 memset(page, 0, sizeof(page));
1203 write(netfd, page, sizeof(page));
1204 }
1205 }
1206 if (netfd < 0)
1207 err(1, "cannot open net file '%s'", filename);
1208 }
1209
Rusty Russelldde79782007-07-26 10:41:03 -07001210 /* We need 1 page, and the features indicate the slot to use and that
1211 * no checksum is needed. We never touch this device again; it's
1212 * between the Guests on the network, so we don't register input or
1213 * output handlers. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001214 dev = new_device(devices, LGUEST_DEVICE_T_NET, 1,
1215 find_slot(netfd, filename)|LGUEST_NET_F_NOCSUM,
1216 -1, NULL, 0, NULL);
1217
Rusty Russelldde79782007-07-26 10:41:03 -07001218 /* Map the shared file. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001219 if (mmap(dev->mem, getpagesize(), PROT_READ|PROT_WRITE,
1220 MAP_FIXED|MAP_SHARED, netfd, 0) != dev->mem)
1221 err(1, "could not mmap '%s'", filename);
1222 verbose("device %p: shared net %s, peer %i\n",
1223 (void *)(dev->desc->pfn * getpagesize()), filename,
1224 dev->desc->features & ~LGUEST_NET_F_NOCSUM);
1225}
Rusty Russelldde79782007-07-26 10:41:03 -07001226/*:*/
Rusty Russell8ca47e02007-07-19 01:49:29 -07001227
1228static u32 str2ip(const char *ipaddr)
1229{
1230 unsigned int byte[4];
1231
1232 sscanf(ipaddr, "%u.%u.%u.%u", &byte[0], &byte[1], &byte[2], &byte[3]);
1233 return (byte[0] << 24) | (byte[1] << 16) | (byte[2] << 8) | byte[3];
1234}
1235
Rusty Russelldde79782007-07-26 10:41:03 -07001236/* This code is "adapted" from libbridge: it attaches the Host end of the
1237 * network device to the bridge device specified by the command line.
1238 *
1239 * This is yet another James Morris contribution (I'm an IP-level guy, so I
1240 * dislike bridging), and I just try not to break it. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001241static void add_to_bridge(int fd, const char *if_name, const char *br_name)
1242{
1243 int ifidx;
1244 struct ifreq ifr;
1245
1246 if (!*br_name)
1247 errx(1, "must specify bridge name");
1248
1249 ifidx = if_nametoindex(if_name);
1250 if (!ifidx)
1251 errx(1, "interface %s does not exist!", if_name);
1252
1253 strncpy(ifr.ifr_name, br_name, IFNAMSIZ);
1254 ifr.ifr_ifindex = ifidx;
1255 if (ioctl(fd, SIOCBRADDIF, &ifr) < 0)
1256 err(1, "can't add %s to bridge %s", if_name, br_name);
1257}
1258
Rusty Russelldde79782007-07-26 10:41:03 -07001259/* This sets up the Host end of the network device with an IP address, brings
1260 * it up so packets will flow, the copies the MAC address into the hwaddr
1261 * pointer (in practice, the Host's slot in the network device's memory). */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001262static void configure_device(int fd, const char *devname, u32 ipaddr,
1263 unsigned char hwaddr[6])
1264{
1265 struct ifreq ifr;
1266 struct sockaddr_in *sin = (struct sockaddr_in *)&ifr.ifr_addr;
1267
Rusty Russelldde79782007-07-26 10:41:03 -07001268 /* Don't read these incantations. Just cut & paste them like I did! */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001269 memset(&ifr, 0, sizeof(ifr));
1270 strcpy(ifr.ifr_name, devname);
1271 sin->sin_family = AF_INET;
1272 sin->sin_addr.s_addr = htonl(ipaddr);
1273 if (ioctl(fd, SIOCSIFADDR, &ifr) != 0)
1274 err(1, "Setting %s interface address", devname);
1275 ifr.ifr_flags = IFF_UP;
1276 if (ioctl(fd, SIOCSIFFLAGS, &ifr) != 0)
1277 err(1, "Bringing interface %s up", devname);
1278
Rusty Russelldde79782007-07-26 10:41:03 -07001279 /* SIOC stands for Socket I/O Control. G means Get (vs S for Set
1280 * above). IF means Interface, and HWADDR is hardware address.
1281 * Simple! */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001282 if (ioctl(fd, SIOCGIFHWADDR, &ifr) != 0)
1283 err(1, "getting hw address for %s", devname);
Rusty Russell8ca47e02007-07-19 01:49:29 -07001284 memcpy(hwaddr, ifr.ifr_hwaddr.sa_data, 6);
1285}
1286
Rusty Russelldde79782007-07-26 10:41:03 -07001287/*L:195 The other kind of network is a Host<->Guest network. This can either
1288 * use briding or routing, but the principle is the same: it uses the "tun"
1289 * device to inject packets into the Host as if they came in from a normal
1290 * network card. We just shunt packets between the Guest and the tun
1291 * device. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001292static void setup_tun_net(const char *arg, struct device_list *devices)
1293{
1294 struct device *dev;
1295 struct ifreq ifr;
1296 int netfd, ipfd;
1297 u32 ip;
1298 const char *br_name = NULL;
1299
Rusty Russelldde79782007-07-26 10:41:03 -07001300 /* We open the /dev/net/tun device and tell it we want a tap device. A
1301 * tap device is like a tun device, only somehow different. To tell
1302 * the truth, I completely blundered my way through this code, but it
1303 * works now! */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001304 netfd = open_or_die("/dev/net/tun", O_RDWR);
1305 memset(&ifr, 0, sizeof(ifr));
1306 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
1307 strcpy(ifr.ifr_name, "tap%d");
1308 if (ioctl(netfd, TUNSETIFF, &ifr) != 0)
1309 err(1, "configuring /dev/net/tun");
Rusty Russelldde79782007-07-26 10:41:03 -07001310 /* We don't need checksums calculated for packets coming in this
1311 * device: trust us! */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001312 ioctl(netfd, TUNSETNOCSUM, 1);
1313
Rusty Russelldde79782007-07-26 10:41:03 -07001314 /* We create the net device with 1 page, using the features field of
1315 * the descriptor to tell the Guest it is in slot 1 (NET_PEERNUM), and
1316 * that the device has fairly random timing. We do *not* specify
1317 * LGUEST_NET_F_NOCSUM: these packets can reach the real world.
1318 *
1319 * We will put our MAC address is slot 0 for the Guest to see, so
1320 * it will send packets to us using the key "peer_offset(0)": */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001321 dev = new_device(devices, LGUEST_DEVICE_T_NET, 1,
1322 NET_PEERNUM|LGUEST_DEVICE_F_RANDOMNESS, netfd,
1323 handle_tun_input, peer_offset(0), handle_tun_output);
Rusty Russelldde79782007-07-26 10:41:03 -07001324
1325 /* We keep a flag which says whether we've seen packets come out from
1326 * this network device. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001327 dev->priv = malloc(sizeof(bool));
1328 *(bool *)dev->priv = false;
1329
Rusty Russelldde79782007-07-26 10:41:03 -07001330 /* We need a socket to perform the magic network ioctls to bring up the
1331 * tap interface, connect to the bridge etc. Any socket will do! */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001332 ipfd = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP);
1333 if (ipfd < 0)
1334 err(1, "opening IP socket");
1335
Rusty Russelldde79782007-07-26 10:41:03 -07001336 /* If the command line was --tunnet=bridge:<name> do bridging. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001337 if (!strncmp(BRIDGE_PFX, arg, strlen(BRIDGE_PFX))) {
1338 ip = INADDR_ANY;
1339 br_name = arg + strlen(BRIDGE_PFX);
1340 add_to_bridge(ipfd, ifr.ifr_name, br_name);
Rusty Russelldde79782007-07-26 10:41:03 -07001341 } else /* It is an IP address to set up the device with */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001342 ip = str2ip(arg);
1343
Rusty Russelldde79782007-07-26 10:41:03 -07001344 /* We are peer 0, ie. first slot, so we hand dev->mem to this routine
1345 * to write the MAC address at the start of the device memory. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001346 configure_device(ipfd, ifr.ifr_name, ip, dev->mem);
1347
Rusty Russelldde79782007-07-26 10:41:03 -07001348 /* Set "promisc" bit: we want every single packet if we're going to
1349 * bridge to other machines (and otherwise it doesn't matter). */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001350 *((u8 *)dev->mem) |= 0x1;
1351
1352 close(ipfd);
1353
1354 verbose("device %p: tun net %u.%u.%u.%u\n",
1355 (void *)(dev->desc->pfn * getpagesize()),
1356 (u8)(ip>>24), (u8)(ip>>16), (u8)(ip>>8), (u8)ip);
1357 if (br_name)
1358 verbose("attached to bridge: %s\n", br_name);
1359}
Rusty Russelldde79782007-07-26 10:41:03 -07001360/* That's the end of device setup. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001361
Rusty Russelldde79782007-07-26 10:41:03 -07001362/*L:220 Finally we reach the core of the Launcher, which runs the Guest, serves
1363 * its input and output, and finally, lays it to rest. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001364static void __attribute__((noreturn))
1365run_guest(int lguest_fd, struct device_list *device_list)
1366{
1367 for (;;) {
1368 u32 args[] = { LHREQ_BREAK, 0 };
1369 unsigned long arr[2];
1370 int readval;
1371
1372 /* We read from the /dev/lguest device to run the Guest. */
1373 readval = read(lguest_fd, arr, sizeof(arr));
1374
Rusty Russelldde79782007-07-26 10:41:03 -07001375 /* The read can only really return sizeof(arr) (the Guest did a
1376 * SEND_DMA to us), or an error. */
1377
1378 /* For a successful read, arr[0] is the address of the "struct
1379 * lguest_dma", and arr[1] is the key the Guest sent to. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001380 if (readval == sizeof(arr)) {
1381 handle_output(lguest_fd, arr[0], arr[1], device_list);
1382 continue;
Rusty Russelldde79782007-07-26 10:41:03 -07001383 /* ENOENT means the Guest died. Reading tells us why. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001384 } else if (errno == ENOENT) {
1385 char reason[1024] = { 0 };
1386 read(lguest_fd, reason, sizeof(reason)-1);
1387 errx(1, "%s", reason);
Rusty Russelldde79782007-07-26 10:41:03 -07001388 /* EAGAIN means the waker wanted us to look at some input.
1389 * Anything else means a bug or incompatible change. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001390 } else if (errno != EAGAIN)
1391 err(1, "Running guest failed");
Rusty Russelldde79782007-07-26 10:41:03 -07001392
1393 /* Service input, then unset the BREAK which releases
1394 * the Waker. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001395 handle_input(lguest_fd, device_list);
1396 if (write(lguest_fd, args, sizeof(args)) < 0)
1397 err(1, "Resetting break");
1398 }
1399}
Rusty Russelldde79782007-07-26 10:41:03 -07001400/*
1401 * This is the end of the Launcher.
1402 *
1403 * But wait! We've seen I/O from the Launcher, and we've seen I/O from the
1404 * Drivers. If we were to see the Host kernel I/O code, our understanding
1405 * would be complete... :*/
Rusty Russell8ca47e02007-07-19 01:49:29 -07001406
1407static struct option opts[] = {
1408 { "verbose", 0, NULL, 'v' },
1409 { "sharenet", 1, NULL, 's' },
1410 { "tunnet", 1, NULL, 't' },
1411 { "block", 1, NULL, 'b' },
1412 { "initrd", 1, NULL, 'i' },
1413 { NULL },
1414};
1415static void usage(void)
1416{
1417 errx(1, "Usage: lguest [--verbose] "
1418 "[--sharenet=<filename>|--tunnet=(<ipaddr>|bridge:<bridgename>)\n"
1419 "|--block=<filename>|--initrd=<filename>]...\n"
1420 "<mem-in-mb> vmlinux [args...]");
1421}
1422
Rusty Russell3c6b5bf2007-10-22 11:03:26 +10001423/*L:105 The main routine is where the real work begins: */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001424int main(int argc, char *argv[])
1425{
Rusty Russelldde79782007-07-26 10:41:03 -07001426 /* Memory, top-level pagetable, code startpoint, PAGE_OFFSET and size
1427 * of the (optional) initrd. */
Rusty Russell6570c45992007-07-23 18:43:56 -07001428 unsigned long mem = 0, pgdir, start, page_offset, initrd_size = 0;
Rusty Russelldde79782007-07-26 10:41:03 -07001429 /* A temporary and the /dev/lguest file descriptor. */
Rusty Russell6570c45992007-07-23 18:43:56 -07001430 int i, c, lguest_fd;
Rusty Russelldde79782007-07-26 10:41:03 -07001431 /* The list of Guest devices, based on command line arguments. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001432 struct device_list device_list;
Rusty Russell3c6b5bf2007-10-22 11:03:26 +10001433 /* The boot information for the Guest. */
1434 void *boot;
Rusty Russelldde79782007-07-26 10:41:03 -07001435 /* If they specify an initrd file to load. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001436 const char *initrd_name = NULL;
1437
Rusty Russelldde79782007-07-26 10:41:03 -07001438 /* First we initialize the device list. Since console and network
1439 * device receive input from a file descriptor, we keep an fdset
1440 * (infds) and the maximum fd number (max_infd) with the head of the
1441 * list. We also keep a pointer to the last device, for easy appending
1442 * to the list. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001443 device_list.max_infd = -1;
1444 device_list.dev = NULL;
1445 device_list.lastdev = &device_list.dev;
1446 FD_ZERO(&device_list.infds);
1447
Rusty Russelldde79782007-07-26 10:41:03 -07001448 /* We need to know how much memory so we can set up the device
1449 * descriptor and memory pages for the devices as we parse the command
1450 * line. So we quickly look through the arguments to find the amount
1451 * of memory now. */
Rusty Russell6570c45992007-07-23 18:43:56 -07001452 for (i = 1; i < argc; i++) {
1453 if (argv[i][0] != '-') {
Rusty Russell3c6b5bf2007-10-22 11:03:26 +10001454 mem = atoi(argv[i]) * 1024 * 1024;
1455 /* We start by mapping anonymous pages over all of
1456 * guest-physical memory range. This fills it with 0,
1457 * and ensures that the Guest won't be killed when it
1458 * tries to access it. */
1459 guest_base = map_zeroed_pages(mem / getpagesize()
1460 + DEVICE_PAGES);
1461 guest_limit = mem;
1462 guest_max = mem + DEVICE_PAGES*getpagesize();
1463 device_list.descs = get_pages(1);
Rusty Russell6570c45992007-07-23 18:43:56 -07001464 break;
1465 }
1466 }
Rusty Russelldde79782007-07-26 10:41:03 -07001467
1468 /* The options are fairly straight-forward */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001469 while ((c = getopt_long(argc, argv, "v", opts, NULL)) != EOF) {
1470 switch (c) {
1471 case 'v':
1472 verbose = true;
1473 break;
1474 case 's':
1475 setup_net_file(optarg, &device_list);
1476 break;
1477 case 't':
1478 setup_tun_net(optarg, &device_list);
1479 break;
1480 case 'b':
1481 setup_block_file(optarg, &device_list);
1482 break;
1483 case 'i':
1484 initrd_name = optarg;
1485 break;
1486 default:
1487 warnx("Unknown argument %s", argv[optind]);
1488 usage();
1489 }
1490 }
Rusty Russelldde79782007-07-26 10:41:03 -07001491 /* After the other arguments we expect memory and kernel image name,
1492 * followed by command line arguments for the kernel. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001493 if (optind + 2 > argc)
1494 usage();
1495
Rusty Russell3c6b5bf2007-10-22 11:03:26 +10001496 verbose("Guest base is at %p\n", guest_base);
1497
Rusty Russelldde79782007-07-26 10:41:03 -07001498 /* We always have a console device */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001499 setup_console(&device_list);
1500
Rusty Russell8ca47e02007-07-19 01:49:29 -07001501 /* Now we load the kernel */
1502 start = load_kernel(open_or_die(argv[optind+1], O_RDONLY),
1503 &page_offset);
1504
Rusty Russell3c6b5bf2007-10-22 11:03:26 +10001505 /* Boot information is stashed at physical address 0 */
1506 boot = from_guest_phys(0);
1507
Rusty Russelldde79782007-07-26 10:41:03 -07001508 /* Map the initrd image if requested (at top of physical memory) */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001509 if (initrd_name) {
1510 initrd_size = load_initrd(initrd_name, mem);
Rusty Russelldde79782007-07-26 10:41:03 -07001511 /* These are the location in the Linux boot header where the
1512 * start and size of the initrd are expected to be found. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001513 *(unsigned long *)(boot+0x218) = mem - initrd_size;
1514 *(unsigned long *)(boot+0x21c) = initrd_size;
Rusty Russelldde79782007-07-26 10:41:03 -07001515 /* The bootloader type 0xFF means "unknown"; that's OK. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001516 *(unsigned char *)(boot+0x210) = 0xFF;
1517 }
1518
Rusty Russelldde79782007-07-26 10:41:03 -07001519 /* Set up the initial linear pagetables, starting below the initrd. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001520 pgdir = setup_pagetables(mem, initrd_size, page_offset);
1521
Rusty Russelldde79782007-07-26 10:41:03 -07001522 /* The Linux boot header contains an "E820" memory map: ours is a
1523 * simple, single region. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001524 *(char*)(boot+E820NR) = 1;
1525 *((struct e820entry *)(boot+E820MAP))
1526 = ((struct e820entry) { 0, mem, E820_RAM });
Rusty Russelldde79782007-07-26 10:41:03 -07001527 /* The boot header contains a command line pointer: we put the command
1528 * line after the boot header (at address 4096) */
Rusty Russell3c6b5bf2007-10-22 11:03:26 +10001529 *(u32 *)(boot + 0x228) = 4096;
Rusty Russell8ca47e02007-07-19 01:49:29 -07001530 concat(boot + 4096, argv+optind+2);
Rusty Russelldde79782007-07-26 10:41:03 -07001531
1532 /* The guest type value of "1" tells the Guest it's under lguest. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001533 *(int *)(boot + 0x23c) = 1;
1534
Rusty Russelldde79782007-07-26 10:41:03 -07001535 /* We tell the kernel to initialize the Guest: this returns the open
1536 * /dev/lguest file descriptor. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001537 lguest_fd = tell_kernel(pgdir, start, page_offset);
Rusty Russelldde79782007-07-26 10:41:03 -07001538
1539 /* We fork off a child process, which wakes the Launcher whenever one
1540 * of the input file descriptors needs attention. Otherwise we would
1541 * run the Guest until it tries to output something. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001542 waker_fd = setup_waker(lguest_fd, &device_list);
1543
Rusty Russelldde79782007-07-26 10:41:03 -07001544 /* Finally, run the Guest. This doesn't return. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001545 run_guest(lguest_fd, &device_list);
1546}
Rusty Russellf56a3842007-07-26 10:41:05 -07001547/*:*/
1548
1549/*M:999
1550 * Mastery is done: you now know everything I do.
1551 *
1552 * But surely you have seen code, features and bugs in your wanderings which
1553 * you now yearn to attack? That is the real game, and I look forward to you
1554 * patching and forking lguest into the Your-Name-Here-visor.
1555 *
1556 * Farewell, and good coding!
1557 * Rusty Russell.
1558 */