lguest.c 52 KB

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