lguest.c 49 KB

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