lguest.c 52 KB

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