lguest.c 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769
  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. #include <assert.h>
  36. #include <sched.h>
  37. #include <limits.h>
  38. #include <stddef.h>
  39. #include "linux/lguest_launcher.h"
  40. #include "linux/virtio_config.h"
  41. #include "linux/virtio_net.h"
  42. #include "linux/virtio_blk.h"
  43. #include "linux/virtio_console.h"
  44. #include "linux/virtio_ring.h"
  45. #include "asm-x86/bootparam.h"
  46. /*L:110 We can ignore the 38 include files we need for this program, but I do
  47. * want to draw attention to the use of kernel-style types.
  48. *
  49. * As Linus said, "C is a Spartan language, and so should your naming be." I
  50. * like these abbreviations, so we define them here. Note that u64 is always
  51. * unsigned long long, which works on all Linux systems: this means that we can
  52. * use %llu in printf for any u64. */
  53. typedef unsigned long long u64;
  54. typedef uint32_t u32;
  55. typedef uint16_t u16;
  56. typedef uint8_t u8;
  57. /*:*/
  58. #define PAGE_PRESENT 0x7 /* Present, RW, Execute */
  59. #define NET_PEERNUM 1
  60. #define BRIDGE_PFX "bridge:"
  61. #ifndef SIOCBRADDIF
  62. #define SIOCBRADDIF 0x89a2 /* add interface to bridge */
  63. #endif
  64. /* We can have up to 256 pages for devices. */
  65. #define DEVICE_PAGES 256
  66. /* This will occupy 2 pages: it must be a power of 2. */
  67. #define VIRTQUEUE_NUM 128
  68. /*L:120 verbose is both a global flag and a macro. The C preprocessor allows
  69. * this, and although I wouldn't recommend it, it works quite nicely here. */
  70. static bool verbose;
  71. #define verbose(args...) \
  72. do { if (verbose) printf(args); } while(0)
  73. /*:*/
  74. /* The pipe to send commands to the waker process */
  75. static int waker_fd;
  76. /* The pointer to the start of guest memory. */
  77. static void *guest_base;
  78. /* The maximum guest physical address allowed, and maximum possible. */
  79. static unsigned long guest_limit, guest_max;
  80. /* a per-cpu variable indicating whose vcpu is currently running */
  81. static unsigned int __thread cpu_id;
  82. /* This is our list of devices. */
  83. struct device_list
  84. {
  85. /* Summary information about the devices in our list: ready to pass to
  86. * select() to ask which need servicing.*/
  87. fd_set infds;
  88. int max_infd;
  89. /* Counter to assign interrupt numbers. */
  90. unsigned int next_irq;
  91. /* Counter to print out convenient device numbers. */
  92. unsigned int device_num;
  93. /* The descriptor page for the devices. */
  94. u8 *descpage;
  95. /* A single linked list of devices. */
  96. struct device *dev;
  97. /* And a pointer to the last device for easy append and also for
  98. * configuration appending. */
  99. struct device *lastdev;
  100. };
  101. /* The list of Guest devices, based on command line arguments. */
  102. static struct device_list devices;
  103. /* The device structure describes a single device. */
  104. struct device
  105. {
  106. /* The linked-list pointer. */
  107. struct device *next;
  108. /* The this device's descriptor, as mapped into the Guest. */
  109. struct lguest_device_desc *desc;
  110. /* The name of this device, for --verbose. */
  111. const char *name;
  112. /* If handle_input is set, it wants to be called when this file
  113. * descriptor is ready. */
  114. int fd;
  115. bool (*handle_input)(int fd, struct device *me);
  116. /* Any queues attached to this device */
  117. struct virtqueue *vq;
  118. /* Device-specific data. */
  119. void *priv;
  120. };
  121. /* The virtqueue structure describes a queue attached to a device. */
  122. struct virtqueue
  123. {
  124. struct virtqueue *next;
  125. /* Which device owns me. */
  126. struct device *dev;
  127. /* The configuration for this queue. */
  128. struct lguest_vqconfig config;
  129. /* The actual ring of buffers. */
  130. struct vring vring;
  131. /* Last available index we saw. */
  132. u16 last_avail_idx;
  133. /* The routine to call when the Guest pings us. */
  134. void (*handle_output)(int fd, struct virtqueue *me);
  135. };
  136. /* Remember the arguments to the program so we can "reboot" */
  137. static char **main_args;
  138. /* Since guest is UP and we don't run at the same time, we don't need barriers.
  139. * But I include them in the code in case others copy it. */
  140. #define wmb()
  141. /* Convert an iovec element to the given type.
  142. *
  143. * This is a fairly ugly trick: we need to know the size of the type and
  144. * alignment requirement to check the pointer is kosher. It's also nice to
  145. * have the name of the type in case we report failure.
  146. *
  147. * Typing those three things all the time is cumbersome and error prone, so we
  148. * have a macro which sets them all up and passes to the real function. */
  149. #define convert(iov, type) \
  150. ((type *)_convert((iov), sizeof(type), __alignof__(type), #type))
  151. static void *_convert(struct iovec *iov, size_t size, size_t align,
  152. const char *name)
  153. {
  154. if (iov->iov_len != size)
  155. errx(1, "Bad iovec size %zu for %s", iov->iov_len, name);
  156. if ((unsigned long)iov->iov_base % align != 0)
  157. errx(1, "Bad alignment %p for %s", iov->iov_base, name);
  158. return iov->iov_base;
  159. }
  160. /* The virtio configuration space is defined to be little-endian. x86 is
  161. * little-endian too, but it's nice to be explicit so we have these helpers. */
  162. #define cpu_to_le16(v16) (v16)
  163. #define cpu_to_le32(v32) (v32)
  164. #define cpu_to_le64(v64) (v64)
  165. #define le16_to_cpu(v16) (v16)
  166. #define le32_to_cpu(v32) (v32)
  167. #define le64_to_cpu(v64) (v64)
  168. /*L:100 The Launcher code itself takes us out into userspace, that scary place
  169. * where pointers run wild and free! Unfortunately, like most userspace
  170. * programs, it's quite boring (which is why everyone likes to hack on the
  171. * kernel!). Perhaps if you make up an Lguest Drinking Game at this point, it
  172. * will get you through this section. Or, maybe not.
  173. *
  174. * The Launcher sets up a big chunk of memory to be the Guest's "physical"
  175. * memory and stores it in "guest_base". In other words, Guest physical ==
  176. * Launcher virtual with an offset.
  177. *
  178. * This can be tough to get your head around, but usually it just means that we
  179. * use these trivial conversion functions when the Guest gives us it's
  180. * "physical" addresses: */
  181. static void *from_guest_phys(unsigned long addr)
  182. {
  183. return guest_base + addr;
  184. }
  185. static unsigned long to_guest_phys(const void *addr)
  186. {
  187. return (addr - guest_base);
  188. }
  189. /*L:130
  190. * Loading the Kernel.
  191. *
  192. * We start with couple of simple helper routines. open_or_die() avoids
  193. * error-checking code cluttering the callers: */
  194. static int open_or_die(const char *name, int flags)
  195. {
  196. int fd = open(name, flags);
  197. if (fd < 0)
  198. err(1, "Failed to open %s", name);
  199. return fd;
  200. }
  201. /* map_zeroed_pages() takes a number of pages. */
  202. static void *map_zeroed_pages(unsigned int num)
  203. {
  204. int fd = open_or_die("/dev/zero", O_RDONLY);
  205. void *addr;
  206. /* We use a private mapping (ie. if we write to the page, it will be
  207. * copied). */
  208. addr = mmap(NULL, getpagesize() * num,
  209. PROT_READ|PROT_WRITE|PROT_EXEC, MAP_PRIVATE, fd, 0);
  210. if (addr == MAP_FAILED)
  211. err(1, "Mmaping %u pages of /dev/zero", num);
  212. return addr;
  213. }
  214. /* Get some more pages for a device. */
  215. static void *get_pages(unsigned int num)
  216. {
  217. void *addr = from_guest_phys(guest_limit);
  218. guest_limit += num * getpagesize();
  219. if (guest_limit > guest_max)
  220. errx(1, "Not enough memory for devices");
  221. return addr;
  222. }
  223. /* This routine is used to load the kernel or initrd. It tries mmap, but if
  224. * that fails (Plan 9's kernel file isn't nicely aligned on page boundaries),
  225. * it falls back to reading the memory in. */
  226. static void map_at(int fd, void *addr, unsigned long offset, unsigned long len)
  227. {
  228. ssize_t r;
  229. /* We map writable even though for some segments are marked read-only.
  230. * The kernel really wants to be writable: it patches its own
  231. * instructions.
  232. *
  233. * MAP_PRIVATE means that the page won't be copied until a write is
  234. * done to it. This allows us to share untouched memory between
  235. * Guests. */
  236. if (mmap(addr, len, PROT_READ|PROT_WRITE|PROT_EXEC,
  237. MAP_FIXED|MAP_PRIVATE, fd, offset) != MAP_FAILED)
  238. return;
  239. /* pread does a seek and a read in one shot: saves a few lines. */
  240. r = pread(fd, addr, len, offset);
  241. if (r != len)
  242. err(1, "Reading offset %lu len %lu gave %zi", offset, len, r);
  243. }
  244. /* This routine takes an open vmlinux image, which is in ELF, and maps it into
  245. * the Guest memory. ELF = Embedded Linking Format, which is the format used
  246. * by all modern binaries on Linux including the kernel.
  247. *
  248. * The ELF headers give *two* addresses: a physical address, and a virtual
  249. * address. We use the physical address; the Guest will map itself to the
  250. * virtual address.
  251. *
  252. * We return the starting address. */
  253. static unsigned long map_elf(int elf_fd, const Elf32_Ehdr *ehdr)
  254. {
  255. Elf32_Phdr phdr[ehdr->e_phnum];
  256. unsigned int i;
  257. /* Sanity checks on the main ELF header: an x86 executable with a
  258. * reasonable number of correctly-sized program headers. */
  259. if (ehdr->e_type != ET_EXEC
  260. || ehdr->e_machine != EM_386
  261. || ehdr->e_phentsize != sizeof(Elf32_Phdr)
  262. || ehdr->e_phnum < 1 || ehdr->e_phnum > 65536U/sizeof(Elf32_Phdr))
  263. errx(1, "Malformed elf header");
  264. /* An ELF executable contains an ELF header and a number of "program"
  265. * headers which indicate which parts ("segments") of the program to
  266. * load where. */
  267. /* We read in all the program headers at once: */
  268. if (lseek(elf_fd, ehdr->e_phoff, SEEK_SET) < 0)
  269. err(1, "Seeking to program headers");
  270. if (read(elf_fd, phdr, sizeof(phdr)) != sizeof(phdr))
  271. err(1, "Reading program headers");
  272. /* Try all the headers: there are usually only three. A read-only one,
  273. * a read-write one, and a "note" section which isn't loadable. */
  274. for (i = 0; i < ehdr->e_phnum; i++) {
  275. /* If this isn't a loadable segment, we ignore it */
  276. if (phdr[i].p_type != PT_LOAD)
  277. continue;
  278. verbose("Section %i: size %i addr %p\n",
  279. i, phdr[i].p_memsz, (void *)phdr[i].p_paddr);
  280. /* We map this section of the file at its physical address. */
  281. map_at(elf_fd, from_guest_phys(phdr[i].p_paddr),
  282. phdr[i].p_offset, phdr[i].p_filesz);
  283. }
  284. /* The entry point is given in the ELF header. */
  285. return ehdr->e_entry;
  286. }
  287. /*L:150 A bzImage, unlike an ELF file, is not meant to be loaded. You're
  288. * supposed to jump into it and it will unpack itself. We used to have to
  289. * perform some hairy magic because the unpacking code scared me.
  290. *
  291. * Fortunately, Jeremy Fitzhardinge convinced me it wasn't that hard and wrote
  292. * a small patch to jump over the tricky bits in the Guest, so now we just read
  293. * the funky header so we know where in the file to load, and away we go! */
  294. static unsigned long load_bzimage(int fd)
  295. {
  296. struct boot_params boot;
  297. int r;
  298. /* Modern bzImages get loaded at 1M. */
  299. void *p = from_guest_phys(0x100000);
  300. /* Go back to the start of the file and read the header. It should be
  301. * a Linux boot header (see Documentation/i386/boot.txt) */
  302. lseek(fd, 0, SEEK_SET);
  303. read(fd, &boot, sizeof(boot));
  304. /* Inside the setup_hdr, we expect the magic "HdrS" */
  305. if (memcmp(&boot.hdr.header, "HdrS", 4) != 0)
  306. errx(1, "This doesn't look like a bzImage to me");
  307. /* Skip over the extra sectors of the header. */
  308. lseek(fd, (boot.hdr.setup_sects+1) * 512, SEEK_SET);
  309. /* Now read everything into memory. in nice big chunks. */
  310. while ((r = read(fd, p, 65536)) > 0)
  311. p += r;
  312. /* Finally, code32_start tells us where to enter the kernel. */
  313. return boot.hdr.code32_start;
  314. }
  315. /*L:140 Loading the kernel is easy when it's a "vmlinux", but most kernels
  316. * come wrapped up in the self-decompressing "bzImage" format. With a little
  317. * work, we can load those, too. */
  318. static unsigned long load_kernel(int fd)
  319. {
  320. Elf32_Ehdr hdr;
  321. /* Read in the first few bytes. */
  322. if (read(fd, &hdr, sizeof(hdr)) != sizeof(hdr))
  323. err(1, "Reading kernel");
  324. /* If it's an ELF file, it starts with "\177ELF" */
  325. if (memcmp(hdr.e_ident, ELFMAG, SELFMAG) == 0)
  326. return map_elf(fd, &hdr);
  327. /* Otherwise we assume it's a bzImage, and try to unpack it */
  328. return load_bzimage(fd);
  329. }
  330. /* This is a trivial little helper to align pages. Andi Kleen hated it because
  331. * it calls getpagesize() twice: "it's dumb code."
  332. *
  333. * Kernel guys get really het up about optimization, even when it's not
  334. * necessary. I leave this code as a reaction against that. */
  335. static inline unsigned long page_align(unsigned long addr)
  336. {
  337. /* Add upwards and truncate downwards. */
  338. return ((addr + getpagesize()-1) & ~(getpagesize()-1));
  339. }
  340. /*L:180 An "initial ram disk" is a disk image loaded into memory along with
  341. * the kernel which the kernel can use to boot from without needing any
  342. * drivers. Most distributions now use this as standard: the initrd contains
  343. * the code to load the appropriate driver modules for the current machine.
  344. *
  345. * Importantly, James Morris works for RedHat, and Fedora uses initrds for its
  346. * kernels. He sent me this (and tells me when I break it). */
  347. static unsigned long load_initrd(const char *name, unsigned long mem)
  348. {
  349. int ifd;
  350. struct stat st;
  351. unsigned long len;
  352. ifd = open_or_die(name, O_RDONLY);
  353. /* fstat() is needed to get the file size. */
  354. if (fstat(ifd, &st) < 0)
  355. err(1, "fstat() on initrd '%s'", name);
  356. /* We map the initrd at the top of memory, but mmap wants it to be
  357. * page-aligned, so we round the size up for that. */
  358. len = page_align(st.st_size);
  359. map_at(ifd, from_guest_phys(mem - len), 0, st.st_size);
  360. /* Once a file is mapped, you can close the file descriptor. It's a
  361. * little odd, but quite useful. */
  362. close(ifd);
  363. verbose("mapped initrd %s size=%lu @ %p\n", name, len, (void*)mem-len);
  364. /* We return the initrd size. */
  365. return len;
  366. }
  367. /* Once we know how much memory we have, we can construct simple linear page
  368. * tables which set virtual == physical which will get the Guest far enough
  369. * into the boot to create its own.
  370. *
  371. * We lay them out of the way, just below the initrd (which is why we need to
  372. * know its size). */
  373. static unsigned long setup_pagetables(unsigned long mem,
  374. unsigned long initrd_size)
  375. {
  376. unsigned long *pgdir, *linear;
  377. unsigned int mapped_pages, i, linear_pages;
  378. unsigned int ptes_per_page = getpagesize()/sizeof(void *);
  379. mapped_pages = mem/getpagesize();
  380. /* Each PTE page can map ptes_per_page pages: how many do we need? */
  381. linear_pages = (mapped_pages + ptes_per_page-1)/ptes_per_page;
  382. /* We put the toplevel page directory page at the top of memory. */
  383. pgdir = from_guest_phys(mem) - initrd_size - getpagesize();
  384. /* Now we use the next linear_pages pages as pte pages */
  385. linear = (void *)pgdir - linear_pages*getpagesize();
  386. /* Linear mapping is easy: put every page's address into the mapping in
  387. * order. PAGE_PRESENT contains the flags Present, Writable and
  388. * Executable. */
  389. for (i = 0; i < mapped_pages; i++)
  390. linear[i] = ((i * getpagesize()) | PAGE_PRESENT);
  391. /* The top level points to the linear page table pages above. */
  392. for (i = 0; i < mapped_pages; i += ptes_per_page) {
  393. pgdir[i/ptes_per_page]
  394. = ((to_guest_phys(linear) + i*sizeof(void *))
  395. | PAGE_PRESENT);
  396. }
  397. verbose("Linear mapping of %u pages in %u pte pages at %#lx\n",
  398. mapped_pages, linear_pages, to_guest_phys(linear));
  399. /* We return the top level (guest-physical) address: the kernel needs
  400. * to know where it is. */
  401. return to_guest_phys(pgdir);
  402. }
  403. /*:*/
  404. /* Simple routine to roll all the commandline arguments together with spaces
  405. * between them. */
  406. static void concat(char *dst, char *args[])
  407. {
  408. unsigned int i, len = 0;
  409. for (i = 0; args[i]; i++) {
  410. strcpy(dst+len, args[i]);
  411. strcat(dst+len, " ");
  412. len += strlen(args[i]) + 1;
  413. }
  414. /* In case it's empty. */
  415. dst[len] = '\0';
  416. }
  417. /*L:185 This is where we actually tell the kernel to initialize the Guest. We
  418. * saw the arguments it expects when we looked at initialize() in lguest_user.c:
  419. * the base of Guest "physical" memory, the top physical page to allow, the
  420. * top level pagetable and the entry point for the Guest. */
  421. static int tell_kernel(unsigned long pgdir, unsigned long start)
  422. {
  423. unsigned long args[] = { LHREQ_INITIALIZE,
  424. (unsigned long)guest_base,
  425. guest_limit / getpagesize(), pgdir, start };
  426. int fd;
  427. verbose("Guest: %p - %p (%#lx)\n",
  428. guest_base, guest_base + guest_limit, guest_limit);
  429. fd = open_or_die("/dev/lguest", O_RDWR);
  430. if (write(fd, args, sizeof(args)) < 0)
  431. err(1, "Writing to /dev/lguest");
  432. /* We return the /dev/lguest file descriptor to control this Guest */
  433. return fd;
  434. }
  435. /*:*/
  436. static void add_device_fd(int fd)
  437. {
  438. FD_SET(fd, &devices.infds);
  439. if (fd > devices.max_infd)
  440. devices.max_infd = fd;
  441. }
  442. /*L:200
  443. * The Waker.
  444. *
  445. * With console, block and network devices, we can have lots of input which we
  446. * need to process. We could try to tell the kernel what file descriptors to
  447. * watch, but handing a file descriptor mask through to the kernel is fairly
  448. * icky.
  449. *
  450. * Instead, we fork off a process which watches the file descriptors and writes
  451. * the LHREQ_BREAK command to the /dev/lguest file descriptor to tell the Host
  452. * stop running the Guest. This causes the Launcher to return from the
  453. * /dev/lguest read with -EAGAIN, where it will write to /dev/lguest to reset
  454. * the LHREQ_BREAK and wake us up again.
  455. *
  456. * This, of course, is merely a different *kind* of icky.
  457. */
  458. static void wake_parent(int pipefd, int lguest_fd)
  459. {
  460. /* Add the pipe from the Launcher to the fdset in the device_list, so
  461. * we watch it, too. */
  462. add_device_fd(pipefd);
  463. for (;;) {
  464. fd_set rfds = devices.infds;
  465. unsigned long args[] = { LHREQ_BREAK, 1 };
  466. /* Wait until input is ready from one of the devices. */
  467. select(devices.max_infd+1, &rfds, NULL, NULL, NULL);
  468. /* Is it a message from the Launcher? */
  469. if (FD_ISSET(pipefd, &rfds)) {
  470. int fd;
  471. /* If read() returns 0, it means the Launcher has
  472. * exited. We silently follow. */
  473. if (read(pipefd, &fd, sizeof(fd)) == 0)
  474. exit(0);
  475. /* Otherwise it's telling us to change what file
  476. * descriptors we're to listen to. Positive means
  477. * listen to a new one, negative means stop
  478. * listening. */
  479. if (fd >= 0)
  480. FD_SET(fd, &devices.infds);
  481. else
  482. FD_CLR(-fd - 1, &devices.infds);
  483. } else /* Send LHREQ_BREAK command. */
  484. pwrite(lguest_fd, args, sizeof(args), cpu_id);
  485. }
  486. }
  487. /* This routine just sets up a pipe to the Waker process. */
  488. static int setup_waker(int lguest_fd)
  489. {
  490. int pipefd[2], child;
  491. /* We create a pipe to talk to the Waker, and also so it knows when the
  492. * Launcher dies (and closes pipe). */
  493. pipe(pipefd);
  494. child = fork();
  495. if (child == -1)
  496. err(1, "forking");
  497. if (child == 0) {
  498. /* We are the Waker: close the "writing" end of our copy of the
  499. * pipe and start waiting for input. */
  500. close(pipefd[1]);
  501. wake_parent(pipefd[0], lguest_fd);
  502. }
  503. /* Close the reading end of our copy of the pipe. */
  504. close(pipefd[0]);
  505. /* Here is the fd used to talk to the waker. */
  506. return pipefd[1];
  507. }
  508. /*
  509. * Device Handling.
  510. *
  511. * When the Guest gives us a buffer, it sends an array of addresses and sizes.
  512. * We need to make sure it's not trying to reach into the Launcher itself, so
  513. * we have a convenient routine which checks it and exits with an error message
  514. * if something funny is going on:
  515. */
  516. static void *_check_pointer(unsigned long addr, unsigned int size,
  517. unsigned int line)
  518. {
  519. /* We have to separately check addr and addr+size, because size could
  520. * be huge and addr + size might wrap around. */
  521. if (addr >= guest_limit || addr + size >= guest_limit)
  522. errx(1, "%s:%i: Invalid address %#lx", __FILE__, line, addr);
  523. /* We return a pointer for the caller's convenience, now we know it's
  524. * safe to use. */
  525. return from_guest_phys(addr);
  526. }
  527. /* A macro which transparently hands the line number to the real function. */
  528. #define check_pointer(addr,size) _check_pointer(addr, size, __LINE__)
  529. /* Each buffer in the virtqueues is actually a chain of descriptors. This
  530. * function returns the next descriptor in the chain, or vq->vring.num if we're
  531. * at the end. */
  532. static unsigned next_desc(struct virtqueue *vq, unsigned int i)
  533. {
  534. unsigned int next;
  535. /* If this descriptor says it doesn't chain, we're done. */
  536. if (!(vq->vring.desc[i].flags & VRING_DESC_F_NEXT))
  537. return vq->vring.num;
  538. /* Check they're not leading us off end of descriptors. */
  539. next = vq->vring.desc[i].next;
  540. /* Make sure compiler knows to grab that: we don't want it changing! */
  541. wmb();
  542. if (next >= vq->vring.num)
  543. errx(1, "Desc next is %u", next);
  544. return next;
  545. }
  546. /* This looks in the virtqueue and for the first available buffer, and converts
  547. * it to an iovec for convenient access. Since descriptors consist of some
  548. * number of output then some number of input descriptors, it's actually two
  549. * iovecs, but we pack them into one and note how many of each there were.
  550. *
  551. * This function returns the descriptor number found, or vq->vring.num (which
  552. * is never a valid descriptor number) if none was found. */
  553. static unsigned get_vq_desc(struct virtqueue *vq,
  554. struct iovec iov[],
  555. unsigned int *out_num, unsigned int *in_num)
  556. {
  557. unsigned int i, head;
  558. /* Check it isn't doing very strange things with descriptor numbers. */
  559. if ((u16)(vq->vring.avail->idx - vq->last_avail_idx) > vq->vring.num)
  560. errx(1, "Guest moved used index from %u to %u",
  561. vq->last_avail_idx, vq->vring.avail->idx);
  562. /* If there's nothing new since last we looked, return invalid. */
  563. if (vq->vring.avail->idx == vq->last_avail_idx)
  564. return vq->vring.num;
  565. /* Grab the next descriptor number they're advertising, and increment
  566. * the index we've seen. */
  567. head = vq->vring.avail->ring[vq->last_avail_idx++ % vq->vring.num];
  568. /* If their number is silly, that's a fatal mistake. */
  569. if (head >= vq->vring.num)
  570. errx(1, "Guest says index %u is available", head);
  571. /* When we start there are none of either input nor output. */
  572. *out_num = *in_num = 0;
  573. i = head;
  574. do {
  575. /* Grab the first descriptor, and check it's OK. */
  576. iov[*out_num + *in_num].iov_len = vq->vring.desc[i].len;
  577. iov[*out_num + *in_num].iov_base
  578. = check_pointer(vq->vring.desc[i].addr,
  579. vq->vring.desc[i].len);
  580. /* If this is an input descriptor, increment that count. */
  581. if (vq->vring.desc[i].flags & VRING_DESC_F_WRITE)
  582. (*in_num)++;
  583. else {
  584. /* If it's an output descriptor, they're all supposed
  585. * to come before any input descriptors. */
  586. if (*in_num)
  587. errx(1, "Descriptor has out after in");
  588. (*out_num)++;
  589. }
  590. /* If we've got too many, that implies a descriptor loop. */
  591. if (*out_num + *in_num > vq->vring.num)
  592. errx(1, "Looped descriptor");
  593. } while ((i = next_desc(vq, i)) != vq->vring.num);
  594. return head;
  595. }
  596. /* After we've used one of their buffers, we tell them about it. We'll then
  597. * want to send them an interrupt, using trigger_irq(). */
  598. static void add_used(struct virtqueue *vq, unsigned int head, int len)
  599. {
  600. struct vring_used_elem *used;
  601. /* The virtqueue contains a ring of used buffers. Get a pointer to the
  602. * next entry in that used ring. */
  603. used = &vq->vring.used->ring[vq->vring.used->idx % vq->vring.num];
  604. used->id = head;
  605. used->len = len;
  606. /* Make sure buffer is written before we update index. */
  607. wmb();
  608. vq->vring.used->idx++;
  609. }
  610. /* This actually sends the interrupt for this virtqueue */
  611. static void trigger_irq(int fd, struct virtqueue *vq)
  612. {
  613. unsigned long buf[] = { LHREQ_IRQ, vq->config.irq };
  614. /* If they don't want an interrupt, don't send one. */
  615. if (vq->vring.avail->flags & VRING_AVAIL_F_NO_INTERRUPT)
  616. return;
  617. /* Send the Guest an interrupt tell them we used something up. */
  618. if (write(fd, buf, sizeof(buf)) != 0)
  619. err(1, "Triggering irq %i", vq->config.irq);
  620. }
  621. /* And here's the combo meal deal. Supersize me! */
  622. static void add_used_and_trigger(int fd, struct virtqueue *vq,
  623. unsigned int head, int len)
  624. {
  625. add_used(vq, head, len);
  626. trigger_irq(fd, vq);
  627. }
  628. /*
  629. * The Console
  630. *
  631. * Here is the input terminal setting we save, and the routine to restore them
  632. * on exit so the user gets their terminal back. */
  633. static struct termios orig_term;
  634. static void restore_term(void)
  635. {
  636. tcsetattr(STDIN_FILENO, TCSANOW, &orig_term);
  637. }
  638. /* We associate some data with the console for our exit hack. */
  639. struct console_abort
  640. {
  641. /* How many times have they hit ^C? */
  642. int count;
  643. /* When did they start? */
  644. struct timeval start;
  645. };
  646. /* This is the routine which handles console input (ie. stdin). */
  647. static bool handle_console_input(int fd, struct device *dev)
  648. {
  649. int len;
  650. unsigned int head, in_num, out_num;
  651. struct iovec iov[dev->vq->vring.num];
  652. struct console_abort *abort = dev->priv;
  653. /* First we need a console buffer from the Guests's input virtqueue. */
  654. head = get_vq_desc(dev->vq, iov, &out_num, &in_num);
  655. /* If they're not ready for input, stop listening to this file
  656. * descriptor. We'll start again once they add an input buffer. */
  657. if (head == dev->vq->vring.num)
  658. return false;
  659. if (out_num)
  660. errx(1, "Output buffers in console in queue?");
  661. /* This is why we convert to iovecs: the readv() call uses them, and so
  662. * it reads straight into the Guest's buffer. */
  663. len = readv(dev->fd, iov, in_num);
  664. if (len <= 0) {
  665. /* This implies that the console is closed, is /dev/null, or
  666. * something went terribly wrong. */
  667. warnx("Failed to get console input, ignoring console.");
  668. /* Put the input terminal back. */
  669. restore_term();
  670. /* Remove callback from input vq, so it doesn't restart us. */
  671. dev->vq->handle_output = NULL;
  672. /* Stop listening to this fd: don't call us again. */
  673. return false;
  674. }
  675. /* Tell the Guest about the new input. */
  676. add_used_and_trigger(fd, dev->vq, head, len);
  677. /* Three ^C within one second? Exit.
  678. *
  679. * This is such a hack, but works surprisingly well. Each ^C has to be
  680. * in a buffer by itself, so they can't be too fast. But we check that
  681. * we get three within about a second, so they can't be too slow. */
  682. if (len == 1 && ((char *)iov[0].iov_base)[0] == 3) {
  683. if (!abort->count++)
  684. gettimeofday(&abort->start, NULL);
  685. else if (abort->count == 3) {
  686. struct timeval now;
  687. gettimeofday(&now, NULL);
  688. if (now.tv_sec <= abort->start.tv_sec+1) {
  689. unsigned long args[] = { LHREQ_BREAK, 0 };
  690. /* Close the fd so Waker will know it has to
  691. * exit. */
  692. close(waker_fd);
  693. /* Just in case waker is blocked in BREAK, send
  694. * unbreak now. */
  695. write(fd, args, sizeof(args));
  696. exit(2);
  697. }
  698. abort->count = 0;
  699. }
  700. } else
  701. /* Any other key resets the abort counter. */
  702. abort->count = 0;
  703. /* Everything went OK! */
  704. return true;
  705. }
  706. /* Handling output for console is simple: we just get all the output buffers
  707. * and write them to stdout. */
  708. static void handle_console_output(int fd, struct virtqueue *vq)
  709. {
  710. unsigned int head, out, in;
  711. int len;
  712. struct iovec iov[vq->vring.num];
  713. /* Keep getting output buffers from the Guest until we run out. */
  714. while ((head = get_vq_desc(vq, iov, &out, &in)) != vq->vring.num) {
  715. if (in)
  716. errx(1, "Input buffers in output queue?");
  717. len = writev(STDOUT_FILENO, iov, out);
  718. add_used_and_trigger(fd, vq, head, len);
  719. }
  720. }
  721. /*
  722. * The Network
  723. *
  724. * Handling output for network is also simple: we get all the output buffers
  725. * and write them (ignoring the first element) to this device's file descriptor
  726. * (stdout). */
  727. static void handle_net_output(int fd, struct virtqueue *vq)
  728. {
  729. unsigned int head, out, in;
  730. int len;
  731. struct iovec iov[vq->vring.num];
  732. /* Keep getting output buffers from the Guest until we run out. */
  733. while ((head = get_vq_desc(vq, iov, &out, &in)) != vq->vring.num) {
  734. if (in)
  735. errx(1, "Input buffers in output queue?");
  736. /* Check header, but otherwise ignore it (we told the Guest we
  737. * supported no features, so it shouldn't have anything
  738. * interesting). */
  739. (void)convert(&iov[0], struct virtio_net_hdr);
  740. len = writev(vq->dev->fd, iov+1, out-1);
  741. add_used_and_trigger(fd, vq, head, len);
  742. }
  743. }
  744. /* This is where we handle a packet coming in from the tun device to our
  745. * Guest. */
  746. static bool handle_tun_input(int fd, struct device *dev)
  747. {
  748. unsigned int head, in_num, out_num;
  749. int len;
  750. struct iovec iov[dev->vq->vring.num];
  751. struct virtio_net_hdr *hdr;
  752. /* First we need a network buffer from the Guests's recv virtqueue. */
  753. head = get_vq_desc(dev->vq, iov, &out_num, &in_num);
  754. if (head == dev->vq->vring.num) {
  755. /* Now, it's expected that if we try to send a packet too
  756. * early, the Guest won't be ready yet. Wait until the device
  757. * status says it's ready. */
  758. /* FIXME: Actually want DRIVER_ACTIVE here. */
  759. if (dev->desc->status & VIRTIO_CONFIG_S_DRIVER_OK)
  760. warn("network: no dma buffer!");
  761. /* We'll turn this back on if input buffers are registered. */
  762. return false;
  763. } else if (out_num)
  764. errx(1, "Output buffers in network recv queue?");
  765. /* First element is the header: we set it to 0 (no features). */
  766. hdr = convert(&iov[0], struct virtio_net_hdr);
  767. hdr->flags = 0;
  768. hdr->gso_type = VIRTIO_NET_HDR_GSO_NONE;
  769. /* Read the packet from the device directly into the Guest's buffer. */
  770. len = readv(dev->fd, iov+1, in_num-1);
  771. if (len <= 0)
  772. err(1, "reading network");
  773. /* Tell the Guest about the new packet. */
  774. add_used_and_trigger(fd, dev->vq, head, sizeof(*hdr) + len);
  775. verbose("tun input packet len %i [%02x %02x] (%s)\n", len,
  776. ((u8 *)iov[1].iov_base)[0], ((u8 *)iov[1].iov_base)[1],
  777. head != dev->vq->vring.num ? "sent" : "discarded");
  778. /* All good. */
  779. return true;
  780. }
  781. /*L:215 This is the callback attached to the network and console input
  782. * virtqueues: it ensures we try again, in case we stopped console or net
  783. * delivery because Guest didn't have any buffers. */
  784. static void enable_fd(int fd, struct virtqueue *vq)
  785. {
  786. add_device_fd(vq->dev->fd);
  787. /* Tell waker to listen to it again */
  788. write(waker_fd, &vq->dev->fd, sizeof(vq->dev->fd));
  789. }
  790. /* This is the generic routine we call when the Guest uses LHCALL_NOTIFY. */
  791. static void handle_output(int fd, unsigned long addr)
  792. {
  793. struct device *i;
  794. struct virtqueue *vq;
  795. /* Check each virtqueue. */
  796. for (i = devices.dev; i; i = i->next) {
  797. for (vq = i->vq; vq; vq = vq->next) {
  798. if (vq->config.pfn == addr/getpagesize()) {
  799. verbose("Output to %s\n", vq->dev->name);
  800. if (vq->handle_output)
  801. vq->handle_output(fd, vq);
  802. return;
  803. }
  804. }
  805. }
  806. /* Early console write is done using notify on a nul-terminated string
  807. * in Guest memory. */
  808. if (addr >= guest_limit)
  809. errx(1, "Bad NOTIFY %#lx", addr);
  810. write(STDOUT_FILENO, from_guest_phys(addr),
  811. strnlen(from_guest_phys(addr), guest_limit - addr));
  812. }
  813. /* This is called when the Waker wakes us up: check for incoming file
  814. * descriptors. */
  815. static void handle_input(int fd)
  816. {
  817. /* select() wants a zeroed timeval to mean "don't wait". */
  818. struct timeval poll = { .tv_sec = 0, .tv_usec = 0 };
  819. for (;;) {
  820. struct device *i;
  821. fd_set fds = devices.infds;
  822. /* If nothing is ready, we're done. */
  823. if (select(devices.max_infd+1, &fds, NULL, NULL, &poll) == 0)
  824. break;
  825. /* Otherwise, call the device(s) which have readable
  826. * file descriptors and a method of handling them. */
  827. for (i = devices.dev; i; i = i->next) {
  828. if (i->handle_input && FD_ISSET(i->fd, &fds)) {
  829. int dev_fd;
  830. if (i->handle_input(fd, i))
  831. continue;
  832. /* If handle_input() returns false, it means we
  833. * should no longer service it. Networking and
  834. * console do this when there's no input
  835. * buffers to deliver into. Console also uses
  836. * it when it discovers that stdin is
  837. * closed. */
  838. FD_CLR(i->fd, &devices.infds);
  839. /* Tell waker to ignore it too, by sending a
  840. * negative fd number (-1, since 0 is a valid
  841. * FD number). */
  842. dev_fd = -i->fd - 1;
  843. write(waker_fd, &dev_fd, sizeof(dev_fd));
  844. }
  845. }
  846. }
  847. }
  848. /*L:190
  849. * Device Setup
  850. *
  851. * All devices need a descriptor so the Guest knows it exists, and a "struct
  852. * device" so the Launcher can keep track of it. We have common helper
  853. * routines to allocate and manage them. */
  854. /* The layout of the device page is a "struct lguest_device_desc" followed by a
  855. * number of virtqueue descriptors, then two sets of feature bits, then an
  856. * array of configuration bytes. This routine returns the configuration
  857. * pointer. */
  858. static u8 *device_config(const struct device *dev)
  859. {
  860. return (void *)(dev->desc + 1)
  861. + dev->desc->num_vq * sizeof(struct lguest_vqconfig)
  862. + dev->desc->feature_len * 2;
  863. }
  864. /* This routine allocates a new "struct lguest_device_desc" from descriptor
  865. * table page just above the Guest's normal memory. It returns a pointer to
  866. * that descriptor. */
  867. static struct lguest_device_desc *new_dev_desc(u16 type)
  868. {
  869. struct lguest_device_desc d = { .type = type };
  870. void *p;
  871. /* Figure out where the next device config is, based on the last one. */
  872. if (devices.lastdev)
  873. p = device_config(devices.lastdev)
  874. + devices.lastdev->desc->config_len;
  875. else
  876. p = devices.descpage;
  877. /* We only have one page for all the descriptors. */
  878. if (p + sizeof(d) > (void *)devices.descpage + getpagesize())
  879. errx(1, "Too many devices");
  880. /* p might not be aligned, so we memcpy in. */
  881. return memcpy(p, &d, sizeof(d));
  882. }
  883. /* Each device descriptor is followed by the description of its virtqueues. We
  884. * specify how many descriptors the virtqueue is to have. */
  885. static void add_virtqueue(struct device *dev, unsigned int num_descs,
  886. void (*handle_output)(int fd, struct virtqueue *me))
  887. {
  888. unsigned int pages;
  889. struct virtqueue **i, *vq = malloc(sizeof(*vq));
  890. void *p;
  891. /* First we need some pages for this virtqueue. */
  892. pages = (vring_size(num_descs, getpagesize()) + getpagesize() - 1)
  893. / getpagesize();
  894. p = get_pages(pages);
  895. /* Initialize the virtqueue */
  896. vq->next = NULL;
  897. vq->last_avail_idx = 0;
  898. vq->dev = dev;
  899. /* Initialize the configuration. */
  900. vq->config.num = num_descs;
  901. vq->config.irq = devices.next_irq++;
  902. vq->config.pfn = to_guest_phys(p) / getpagesize();
  903. /* Initialize the vring. */
  904. vring_init(&vq->vring, num_descs, p, getpagesize());
  905. /* Append virtqueue to this device's descriptor. We use
  906. * device_config() to get the end of the device's current virtqueues;
  907. * we check that we haven't added any config or feature information
  908. * yet, otherwise we'd be overwriting them. */
  909. assert(dev->desc->config_len == 0 && dev->desc->feature_len == 0);
  910. memcpy(device_config(dev), &vq->config, sizeof(vq->config));
  911. dev->desc->num_vq++;
  912. verbose("Virtqueue page %#lx\n", to_guest_phys(p));
  913. /* Add to tail of list, so dev->vq is first vq, dev->vq->next is
  914. * second. */
  915. for (i = &dev->vq; *i; i = &(*i)->next);
  916. *i = vq;
  917. /* Set the routine to call when the Guest does something to this
  918. * virtqueue. */
  919. vq->handle_output = handle_output;
  920. /* As an optimization, set the advisory "Don't Notify Me" flag if we
  921. * don't have a handler */
  922. if (!handle_output)
  923. vq->vring.used->flags = VRING_USED_F_NO_NOTIFY;
  924. }
  925. /* The virtqueue descriptors are followed by feature bytes. */
  926. static void add_feature(struct device *dev, unsigned bit)
  927. {
  928. u8 *features;
  929. /* We can't extend the feature bits once we've added config bytes */
  930. if (dev->desc->feature_len <= bit / CHAR_BIT) {
  931. assert(dev->desc->config_len == 0);
  932. dev->desc->feature_len = (bit / CHAR_BIT) + 1;
  933. }
  934. features = (u8 *)(dev->desc + 1)
  935. + dev->desc->num_vq * sizeof(struct lguest_vqconfig);
  936. features[bit / CHAR_BIT] |= (1 << (bit % CHAR_BIT));
  937. }
  938. /* This routine sets the configuration fields for an existing device's
  939. * descriptor. It only works for the last device, but that's OK because that's
  940. * how we use it. */
  941. static void set_config(struct device *dev, unsigned len, const void *conf)
  942. {
  943. /* Check we haven't overflowed our single page. */
  944. if (device_config(dev) + len > devices.descpage + getpagesize())
  945. errx(1, "Too many devices");
  946. /* Copy in the config information, and store the length. */
  947. memcpy(device_config(dev), conf, len);
  948. dev->desc->config_len = len;
  949. }
  950. /* This routine does all the creation and setup of a new device, including
  951. * calling new_dev_desc() to allocate the descriptor and device memory. */
  952. static struct device *new_device(const char *name, u16 type, int fd,
  953. bool (*handle_input)(int, struct device *))
  954. {
  955. struct device *dev = malloc(sizeof(*dev));
  956. /* Now we populate the fields one at a time. */
  957. dev->fd = fd;
  958. /* If we have an input handler for this file descriptor, then we add it
  959. * to the device_list's fdset and maxfd. */
  960. if (handle_input)
  961. add_device_fd(dev->fd);
  962. dev->desc = new_dev_desc(type);
  963. dev->handle_input = handle_input;
  964. dev->name = name;
  965. dev->vq = NULL;
  966. /* Append to device list. Prepending to a single-linked list is
  967. * easier, but the user expects the devices to be arranged on the bus
  968. * in command-line order. The first network device on the command line
  969. * is eth0, the first block device /dev/vda, etc. */
  970. if (devices.lastdev)
  971. devices.lastdev->next = dev;
  972. else
  973. devices.dev = dev;
  974. devices.lastdev = dev;
  975. return dev;
  976. }
  977. /* Our first setup routine is the console. It's a fairly simple device, but
  978. * UNIX tty handling makes it uglier than it could be. */
  979. static void setup_console(void)
  980. {
  981. struct device *dev;
  982. /* If we can save the initial standard input settings... */
  983. if (tcgetattr(STDIN_FILENO, &orig_term) == 0) {
  984. struct termios term = orig_term;
  985. /* Then we turn off echo, line buffering and ^C etc. We want a
  986. * raw input stream to the Guest. */
  987. term.c_lflag &= ~(ISIG|ICANON|ECHO);
  988. tcsetattr(STDIN_FILENO, TCSANOW, &term);
  989. /* If we exit gracefully, the original settings will be
  990. * restored so the user can see what they're typing. */
  991. atexit(restore_term);
  992. }
  993. dev = new_device("console", VIRTIO_ID_CONSOLE,
  994. STDIN_FILENO, handle_console_input);
  995. /* We store the console state in dev->priv, and initialize it. */
  996. dev->priv = malloc(sizeof(struct console_abort));
  997. ((struct console_abort *)dev->priv)->count = 0;
  998. /* The console needs two virtqueues: the input then the output. When
  999. * they put something the input queue, we make sure we're listening to
  1000. * stdin. When they put something in the output queue, we write it to
  1001. * stdout. */
  1002. add_virtqueue(dev, VIRTQUEUE_NUM, enable_fd);
  1003. add_virtqueue(dev, VIRTQUEUE_NUM, handle_console_output);
  1004. verbose("device %u: console\n", devices.device_num++);
  1005. }
  1006. /*:*/
  1007. /*M:010 Inter-guest networking is an interesting area. Simplest is to have a
  1008. * --sharenet=<name> option which opens or creates a named pipe. This can be
  1009. * used to send packets to another guest in a 1:1 manner.
  1010. *
  1011. * More sopisticated is to use one of the tools developed for project like UML
  1012. * to do networking.
  1013. *
  1014. * Faster is to do virtio bonding in kernel. Doing this 1:1 would be
  1015. * completely generic ("here's my vring, attach to your vring") and would work
  1016. * for any traffic. Of course, namespace and permissions issues need to be
  1017. * dealt with. A more sophisticated "multi-channel" virtio_net.c could hide
  1018. * multiple inter-guest channels behind one interface, although it would
  1019. * require some manner of hotplugging new virtio channels.
  1020. *
  1021. * Finally, we could implement a virtio network switch in the kernel. :*/
  1022. static u32 str2ip(const char *ipaddr)
  1023. {
  1024. unsigned int byte[4];
  1025. sscanf(ipaddr, "%u.%u.%u.%u", &byte[0], &byte[1], &byte[2], &byte[3]);
  1026. return (byte[0] << 24) | (byte[1] << 16) | (byte[2] << 8) | byte[3];
  1027. }
  1028. /* This code is "adapted" from libbridge: it attaches the Host end of the
  1029. * network device to the bridge device specified by the command line.
  1030. *
  1031. * This is yet another James Morris contribution (I'm an IP-level guy, so I
  1032. * dislike bridging), and I just try not to break it. */
  1033. static void add_to_bridge(int fd, const char *if_name, const char *br_name)
  1034. {
  1035. int ifidx;
  1036. struct ifreq ifr;
  1037. if (!*br_name)
  1038. errx(1, "must specify bridge name");
  1039. ifidx = if_nametoindex(if_name);
  1040. if (!ifidx)
  1041. errx(1, "interface %s does not exist!", if_name);
  1042. strncpy(ifr.ifr_name, br_name, IFNAMSIZ);
  1043. ifr.ifr_ifindex = ifidx;
  1044. if (ioctl(fd, SIOCBRADDIF, &ifr) < 0)
  1045. err(1, "can't add %s to bridge %s", if_name, br_name);
  1046. }
  1047. /* This sets up the Host end of the network device with an IP address, brings
  1048. * it up so packets will flow, the copies the MAC address into the hwaddr
  1049. * pointer. */
  1050. static void configure_device(int fd, const char *devname, u32 ipaddr,
  1051. unsigned char hwaddr[6])
  1052. {
  1053. struct ifreq ifr;
  1054. struct sockaddr_in *sin = (struct sockaddr_in *)&ifr.ifr_addr;
  1055. /* Don't read these incantations. Just cut & paste them like I did! */
  1056. memset(&ifr, 0, sizeof(ifr));
  1057. strcpy(ifr.ifr_name, devname);
  1058. sin->sin_family = AF_INET;
  1059. sin->sin_addr.s_addr = htonl(ipaddr);
  1060. if (ioctl(fd, SIOCSIFADDR, &ifr) != 0)
  1061. err(1, "Setting %s interface address", devname);
  1062. ifr.ifr_flags = IFF_UP;
  1063. if (ioctl(fd, SIOCSIFFLAGS, &ifr) != 0)
  1064. err(1, "Bringing interface %s up", devname);
  1065. /* SIOC stands for Socket I/O Control. G means Get (vs S for Set
  1066. * above). IF means Interface, and HWADDR is hardware address.
  1067. * Simple! */
  1068. if (ioctl(fd, SIOCGIFHWADDR, &ifr) != 0)
  1069. err(1, "getting hw address for %s", devname);
  1070. memcpy(hwaddr, ifr.ifr_hwaddr.sa_data, 6);
  1071. }
  1072. /*L:195 Our network is a Host<->Guest network. This can either use bridging or
  1073. * routing, but the principle is the same: it uses the "tun" device to inject
  1074. * packets into the Host as if they came in from a normal network card. We
  1075. * just shunt packets between the Guest and the tun device. */
  1076. static void setup_tun_net(const char *arg)
  1077. {
  1078. struct device *dev;
  1079. struct ifreq ifr;
  1080. int netfd, ipfd;
  1081. u32 ip;
  1082. const char *br_name = NULL;
  1083. struct virtio_net_config conf;
  1084. /* We open the /dev/net/tun device and tell it we want a tap device. A
  1085. * tap device is like a tun device, only somehow different. To tell
  1086. * the truth, I completely blundered my way through this code, but it
  1087. * works now! */
  1088. netfd = open_or_die("/dev/net/tun", O_RDWR);
  1089. memset(&ifr, 0, sizeof(ifr));
  1090. ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
  1091. strcpy(ifr.ifr_name, "tap%d");
  1092. if (ioctl(netfd, TUNSETIFF, &ifr) != 0)
  1093. err(1, "configuring /dev/net/tun");
  1094. /* We don't need checksums calculated for packets coming in this
  1095. * device: trust us! */
  1096. ioctl(netfd, TUNSETNOCSUM, 1);
  1097. /* First we create a new network device. */
  1098. dev = new_device("net", VIRTIO_ID_NET, netfd, handle_tun_input);
  1099. /* Network devices need a receive and a send queue, just like
  1100. * console. */
  1101. add_virtqueue(dev, VIRTQUEUE_NUM, enable_fd);
  1102. add_virtqueue(dev, VIRTQUEUE_NUM, handle_net_output);
  1103. /* We need a socket to perform the magic network ioctls to bring up the
  1104. * tap interface, connect to the bridge etc. Any socket will do! */
  1105. ipfd = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP);
  1106. if (ipfd < 0)
  1107. err(1, "opening IP socket");
  1108. /* If the command line was --tunnet=bridge:<name> do bridging. */
  1109. if (!strncmp(BRIDGE_PFX, arg, strlen(BRIDGE_PFX))) {
  1110. ip = INADDR_ANY;
  1111. br_name = arg + strlen(BRIDGE_PFX);
  1112. add_to_bridge(ipfd, ifr.ifr_name, br_name);
  1113. } else /* It is an IP address to set up the device with */
  1114. ip = str2ip(arg);
  1115. /* Set up the tun device, and get the mac address for the interface. */
  1116. configure_device(ipfd, ifr.ifr_name, ip, conf.mac);
  1117. /* Tell Guest what MAC address to use. */
  1118. add_feature(dev, VIRTIO_NET_F_MAC);
  1119. set_config(dev, sizeof(conf), &conf);
  1120. /* We don't need the socket any more; setup is done. */
  1121. close(ipfd);
  1122. verbose("device %u: tun net %u.%u.%u.%u\n",
  1123. devices.device_num++,
  1124. (u8)(ip>>24),(u8)(ip>>16),(u8)(ip>>8),(u8)ip);
  1125. if (br_name)
  1126. verbose("attached to bridge: %s\n", br_name);
  1127. }
  1128. /* Our block (disk) device should be really simple: the Guest asks for a block
  1129. * number and we read or write that position in the file. Unfortunately, that
  1130. * was amazingly slow: the Guest waits until the read is finished before
  1131. * running anything else, even if it could have been doing useful work.
  1132. *
  1133. * We could use async I/O, except it's reputed to suck so hard that characters
  1134. * actually go missing from your code when you try to use it.
  1135. *
  1136. * So we farm the I/O out to thread, and communicate with it via a pipe. */
  1137. /* This hangs off device->priv. */
  1138. struct vblk_info
  1139. {
  1140. /* The size of the file. */
  1141. off64_t len;
  1142. /* The file descriptor for the file. */
  1143. int fd;
  1144. /* IO thread listens on this file descriptor [0]. */
  1145. int workpipe[2];
  1146. /* IO thread writes to this file descriptor to mark it done, then
  1147. * Launcher triggers interrupt to Guest. */
  1148. int done_fd;
  1149. };
  1150. /*:*/
  1151. /*L:210
  1152. * The Disk
  1153. *
  1154. * Remember that the block device is handled by a separate I/O thread. We head
  1155. * straight into the core of that thread here:
  1156. */
  1157. static bool service_io(struct device *dev)
  1158. {
  1159. struct vblk_info *vblk = dev->priv;
  1160. unsigned int head, out_num, in_num, wlen;
  1161. int ret;
  1162. struct virtio_blk_inhdr *in;
  1163. struct virtio_blk_outhdr *out;
  1164. struct iovec iov[dev->vq->vring.num];
  1165. off64_t off;
  1166. /* See if there's a request waiting. If not, nothing to do. */
  1167. head = get_vq_desc(dev->vq, iov, &out_num, &in_num);
  1168. if (head == dev->vq->vring.num)
  1169. return false;
  1170. /* Every block request should contain at least one output buffer
  1171. * (detailing the location on disk and the type of request) and one
  1172. * input buffer (to hold the result). */
  1173. if (out_num == 0 || in_num == 0)
  1174. errx(1, "Bad virtblk cmd %u out=%u in=%u",
  1175. head, out_num, in_num);
  1176. out = convert(&iov[0], struct virtio_blk_outhdr);
  1177. in = convert(&iov[out_num+in_num-1], struct virtio_blk_inhdr);
  1178. off = out->sector * 512;
  1179. /* The block device implements "barriers", where the Guest indicates
  1180. * that it wants all previous writes to occur before this write. We
  1181. * don't have a way of asking our kernel to do a barrier, so we just
  1182. * synchronize all the data in the file. Pretty poor, no? */
  1183. if (out->type & VIRTIO_BLK_T_BARRIER)
  1184. fdatasync(vblk->fd);
  1185. /* In general the virtio block driver is allowed to try SCSI commands.
  1186. * It'd be nice if we supported eject, for example, but we don't. */
  1187. if (out->type & VIRTIO_BLK_T_SCSI_CMD) {
  1188. fprintf(stderr, "Scsi commands unsupported\n");
  1189. in->status = VIRTIO_BLK_S_UNSUPP;
  1190. wlen = sizeof(*in);
  1191. } else if (out->type & VIRTIO_BLK_T_OUT) {
  1192. /* Write */
  1193. /* Move to the right location in the block file. This can fail
  1194. * if they try to write past end. */
  1195. if (lseek64(vblk->fd, off, SEEK_SET) != off)
  1196. err(1, "Bad seek to sector %llu", out->sector);
  1197. ret = writev(vblk->fd, iov+1, out_num-1);
  1198. verbose("WRITE to sector %llu: %i\n", out->sector, ret);
  1199. /* Grr... Now we know how long the descriptor they sent was, we
  1200. * make sure they didn't try to write over the end of the block
  1201. * file (possibly extending it). */
  1202. if (ret > 0 && off + ret > vblk->len) {
  1203. /* Trim it back to the correct length */
  1204. ftruncate64(vblk->fd, vblk->len);
  1205. /* Die, bad Guest, die. */
  1206. errx(1, "Write past end %llu+%u", off, ret);
  1207. }
  1208. wlen = sizeof(*in);
  1209. in->status = (ret >= 0 ? VIRTIO_BLK_S_OK : VIRTIO_BLK_S_IOERR);
  1210. } else {
  1211. /* Read */
  1212. /* Move to the right location in the block file. This can fail
  1213. * if they try to read past end. */
  1214. if (lseek64(vblk->fd, off, SEEK_SET) != off)
  1215. err(1, "Bad seek to sector %llu", out->sector);
  1216. ret = readv(vblk->fd, iov+1, in_num-1);
  1217. verbose("READ from sector %llu: %i\n", out->sector, ret);
  1218. if (ret >= 0) {
  1219. wlen = sizeof(*in) + ret;
  1220. in->status = VIRTIO_BLK_S_OK;
  1221. } else {
  1222. wlen = sizeof(*in);
  1223. in->status = VIRTIO_BLK_S_IOERR;
  1224. }
  1225. }
  1226. /* We can't trigger an IRQ, because we're not the Launcher. It does
  1227. * that when we tell it we're done. */
  1228. add_used(dev->vq, head, wlen);
  1229. return true;
  1230. }
  1231. /* This is the thread which actually services the I/O. */
  1232. static int io_thread(void *_dev)
  1233. {
  1234. struct device *dev = _dev;
  1235. struct vblk_info *vblk = dev->priv;
  1236. char c;
  1237. /* Close other side of workpipe so we get 0 read when main dies. */
  1238. close(vblk->workpipe[1]);
  1239. /* Close the other side of the done_fd pipe. */
  1240. close(dev->fd);
  1241. /* When this read fails, it means Launcher died, so we follow. */
  1242. while (read(vblk->workpipe[0], &c, 1) == 1) {
  1243. /* We acknowledge each request immediately to reduce latency,
  1244. * rather than waiting until we've done them all. I haven't
  1245. * measured to see if it makes any difference. */
  1246. while (service_io(dev))
  1247. write(vblk->done_fd, &c, 1);
  1248. }
  1249. return 0;
  1250. }
  1251. /* Now we've seen the I/O thread, we return to the Launcher to see what happens
  1252. * when the thread tells us it's completed some I/O. */
  1253. static bool handle_io_finish(int fd, struct device *dev)
  1254. {
  1255. char c;
  1256. /* If the I/O thread died, presumably it printed the error, so we
  1257. * simply exit. */
  1258. if (read(dev->fd, &c, 1) != 1)
  1259. exit(1);
  1260. /* It did some work, so trigger the irq. */
  1261. trigger_irq(fd, dev->vq);
  1262. return true;
  1263. }
  1264. /* When the Guest submits some I/O, we just need to wake the I/O thread. */
  1265. static void handle_virtblk_output(int fd, struct virtqueue *vq)
  1266. {
  1267. struct vblk_info *vblk = vq->dev->priv;
  1268. char c = 0;
  1269. /* Wake up I/O thread and tell it to go to work! */
  1270. if (write(vblk->workpipe[1], &c, 1) != 1)
  1271. /* Presumably it indicated why it died. */
  1272. exit(1);
  1273. }
  1274. /*L:198 This actually sets up a virtual block device. */
  1275. static void setup_block_file(const char *filename)
  1276. {
  1277. int p[2];
  1278. struct device *dev;
  1279. struct vblk_info *vblk;
  1280. void *stack;
  1281. struct virtio_blk_config conf;
  1282. /* This is the pipe the I/O thread will use to tell us I/O is done. */
  1283. pipe(p);
  1284. /* The device responds to return from I/O thread. */
  1285. dev = new_device("block", VIRTIO_ID_BLOCK, p[0], handle_io_finish);
  1286. /* The device has one virtqueue, where the Guest places requests. */
  1287. add_virtqueue(dev, VIRTQUEUE_NUM, handle_virtblk_output);
  1288. /* Allocate the room for our own bookkeeping */
  1289. vblk = dev->priv = malloc(sizeof(*vblk));
  1290. /* First we open the file and store the length. */
  1291. vblk->fd = open_or_die(filename, O_RDWR|O_LARGEFILE);
  1292. vblk->len = lseek64(vblk->fd, 0, SEEK_END);
  1293. /* We support barriers. */
  1294. add_feature(dev, VIRTIO_BLK_F_BARRIER);
  1295. /* Tell Guest how many sectors this device has. */
  1296. conf.capacity = cpu_to_le64(vblk->len / 512);
  1297. /* Tell Guest not to put in too many descriptors at once: two are used
  1298. * for the in and out elements. */
  1299. add_feature(dev, VIRTIO_BLK_F_SEG_MAX);
  1300. conf.seg_max = cpu_to_le32(VIRTQUEUE_NUM - 2);
  1301. set_config(dev, sizeof(conf), &conf);
  1302. /* The I/O thread writes to this end of the pipe when done. */
  1303. vblk->done_fd = p[1];
  1304. /* This is the second pipe, which is how we tell the I/O thread about
  1305. * more work. */
  1306. pipe(vblk->workpipe);
  1307. /* Create stack for thread and run it */
  1308. stack = malloc(32768);
  1309. /* SIGCHLD - We dont "wait" for our cloned thread, so prevent it from
  1310. * becoming a zombie. */
  1311. if (clone(io_thread, stack + 32768, CLONE_VM | SIGCHLD, dev) == -1)
  1312. err(1, "Creating clone");
  1313. /* We don't need to keep the I/O thread's end of the pipes open. */
  1314. close(vblk->done_fd);
  1315. close(vblk->workpipe[0]);
  1316. verbose("device %u: virtblock %llu sectors\n",
  1317. devices.device_num, le64_to_cpu(conf.capacity));
  1318. }
  1319. /* That's the end of device setup. :*/
  1320. /* Reboot */
  1321. static void __attribute__((noreturn)) restart_guest(void)
  1322. {
  1323. unsigned int i;
  1324. /* Closing pipes causes the waker thread and io_threads to die, and
  1325. * closing /dev/lguest cleans up the Guest. Since we don't track all
  1326. * open fds, we simply close everything beyond stderr. */
  1327. for (i = 3; i < FD_SETSIZE; i++)
  1328. close(i);
  1329. execv(main_args[0], main_args);
  1330. err(1, "Could not exec %s", main_args[0]);
  1331. }
  1332. /*L:220 Finally we reach the core of the Launcher, which runs the Guest, serves
  1333. * its input and output, and finally, lays it to rest. */
  1334. static void __attribute__((noreturn)) run_guest(int lguest_fd)
  1335. {
  1336. for (;;) {
  1337. unsigned long args[] = { LHREQ_BREAK, 0 };
  1338. unsigned long notify_addr;
  1339. int readval;
  1340. /* We read from the /dev/lguest device to run the Guest. */
  1341. readval = pread(lguest_fd, &notify_addr,
  1342. sizeof(notify_addr), cpu_id);
  1343. /* One unsigned long means the Guest did HCALL_NOTIFY */
  1344. if (readval == sizeof(notify_addr)) {
  1345. verbose("Notify on address %#lx\n", notify_addr);
  1346. handle_output(lguest_fd, notify_addr);
  1347. continue;
  1348. /* ENOENT means the Guest died. Reading tells us why. */
  1349. } else if (errno == ENOENT) {
  1350. char reason[1024] = { 0 };
  1351. pread(lguest_fd, reason, sizeof(reason)-1, cpu_id);
  1352. errx(1, "%s", reason);
  1353. /* ERESTART means that we need to reboot the guest */
  1354. } else if (errno == ERESTART) {
  1355. restart_guest();
  1356. /* EAGAIN means the Waker wanted us to look at some input.
  1357. * Anything else means a bug or incompatible change. */
  1358. } else if (errno != EAGAIN)
  1359. err(1, "Running guest failed");
  1360. /* Only service input on thread for CPU 0. */
  1361. if (cpu_id != 0)
  1362. continue;
  1363. /* Service input, then unset the BREAK to release the Waker. */
  1364. handle_input(lguest_fd);
  1365. if (pwrite(lguest_fd, args, sizeof(args), cpu_id) < 0)
  1366. err(1, "Resetting break");
  1367. }
  1368. }
  1369. /*
  1370. * This is the end of the Launcher. The good news: we are over halfway
  1371. * through! The bad news: the most fiendish part of the code still lies ahead
  1372. * of us.
  1373. *
  1374. * Are you ready? Take a deep breath and join me in the core of the Host, in
  1375. * "make Host".
  1376. :*/
  1377. static struct option opts[] = {
  1378. { "verbose", 0, NULL, 'v' },
  1379. { "tunnet", 1, NULL, 't' },
  1380. { "block", 1, NULL, 'b' },
  1381. { "initrd", 1, NULL, 'i' },
  1382. { NULL },
  1383. };
  1384. static void usage(void)
  1385. {
  1386. errx(1, "Usage: lguest [--verbose] "
  1387. "[--tunnet=(<ipaddr>|bridge:<bridgename>)\n"
  1388. "|--block=<filename>|--initrd=<filename>]...\n"
  1389. "<mem-in-mb> vmlinux [args...]");
  1390. }
  1391. /*L:105 The main routine is where the real work begins: */
  1392. int main(int argc, char *argv[])
  1393. {
  1394. /* Memory, top-level pagetable, code startpoint and size of the
  1395. * (optional) initrd. */
  1396. unsigned long mem = 0, pgdir, start, initrd_size = 0;
  1397. /* Two temporaries and the /dev/lguest file descriptor. */
  1398. int i, c, lguest_fd;
  1399. /* The boot information for the Guest. */
  1400. struct boot_params *boot;
  1401. /* If they specify an initrd file to load. */
  1402. const char *initrd_name = NULL;
  1403. /* Save the args: we "reboot" by execing ourselves again. */
  1404. main_args = argv;
  1405. /* We don't "wait" for the children, so prevent them from becoming
  1406. * zombies. */
  1407. signal(SIGCHLD, SIG_IGN);
  1408. /* First we initialize the device list. Since console and network
  1409. * device receive input from a file descriptor, we keep an fdset
  1410. * (infds) and the maximum fd number (max_infd) with the head of the
  1411. * list. We also keep a pointer to the last device. Finally, we keep
  1412. * the next interrupt number to hand out (1: remember that 0 is used by
  1413. * the timer). */
  1414. FD_ZERO(&devices.infds);
  1415. devices.max_infd = -1;
  1416. devices.lastdev = NULL;
  1417. devices.next_irq = 1;
  1418. cpu_id = 0;
  1419. /* We need to know how much memory so we can set up the device
  1420. * descriptor and memory pages for the devices as we parse the command
  1421. * line. So we quickly look through the arguments to find the amount
  1422. * of memory now. */
  1423. for (i = 1; i < argc; i++) {
  1424. if (argv[i][0] != '-') {
  1425. mem = atoi(argv[i]) * 1024 * 1024;
  1426. /* We start by mapping anonymous pages over all of
  1427. * guest-physical memory range. This fills it with 0,
  1428. * and ensures that the Guest won't be killed when it
  1429. * tries to access it. */
  1430. guest_base = map_zeroed_pages(mem / getpagesize()
  1431. + DEVICE_PAGES);
  1432. guest_limit = mem;
  1433. guest_max = mem + DEVICE_PAGES*getpagesize();
  1434. devices.descpage = get_pages(1);
  1435. break;
  1436. }
  1437. }
  1438. /* The options are fairly straight-forward */
  1439. while ((c = getopt_long(argc, argv, "v", opts, NULL)) != EOF) {
  1440. switch (c) {
  1441. case 'v':
  1442. verbose = true;
  1443. break;
  1444. case 't':
  1445. setup_tun_net(optarg);
  1446. break;
  1447. case 'b':
  1448. setup_block_file(optarg);
  1449. break;
  1450. case 'i':
  1451. initrd_name = optarg;
  1452. break;
  1453. default:
  1454. warnx("Unknown argument %s", argv[optind]);
  1455. usage();
  1456. }
  1457. }
  1458. /* After the other arguments we expect memory and kernel image name,
  1459. * followed by command line arguments for the kernel. */
  1460. if (optind + 2 > argc)
  1461. usage();
  1462. verbose("Guest base is at %p\n", guest_base);
  1463. /* We always have a console device */
  1464. setup_console();
  1465. /* Now we load the kernel */
  1466. start = load_kernel(open_or_die(argv[optind+1], O_RDONLY));
  1467. /* Boot information is stashed at physical address 0 */
  1468. boot = from_guest_phys(0);
  1469. /* Map the initrd image if requested (at top of physical memory) */
  1470. if (initrd_name) {
  1471. initrd_size = load_initrd(initrd_name, mem);
  1472. /* These are the location in the Linux boot header where the
  1473. * start and size of the initrd are expected to be found. */
  1474. boot->hdr.ramdisk_image = mem - initrd_size;
  1475. boot->hdr.ramdisk_size = initrd_size;
  1476. /* The bootloader type 0xFF means "unknown"; that's OK. */
  1477. boot->hdr.type_of_loader = 0xFF;
  1478. }
  1479. /* Set up the initial linear pagetables, starting below the initrd. */
  1480. pgdir = setup_pagetables(mem, initrd_size);
  1481. /* The Linux boot header contains an "E820" memory map: ours is a
  1482. * simple, single region. */
  1483. boot->e820_entries = 1;
  1484. boot->e820_map[0] = ((struct e820entry) { 0, mem, E820_RAM });
  1485. /* The boot header contains a command line pointer: we put the command
  1486. * line after the boot header. */
  1487. boot->hdr.cmd_line_ptr = to_guest_phys(boot + 1);
  1488. /* We use a simple helper to copy the arguments separated by spaces. */
  1489. concat((char *)(boot + 1), argv+optind+2);
  1490. /* Boot protocol version: 2.07 supports the fields for lguest. */
  1491. boot->hdr.version = 0x207;
  1492. /* The hardware_subarch value of "1" tells the Guest it's an lguest. */
  1493. boot->hdr.hardware_subarch = 1;
  1494. /* Tell the entry path not to try to reload segment registers. */
  1495. boot->hdr.loadflags |= KEEP_SEGMENTS;
  1496. /* We tell the kernel to initialize the Guest: this returns the open
  1497. * /dev/lguest file descriptor. */
  1498. lguest_fd = tell_kernel(pgdir, start);
  1499. /* We fork off a child process, which wakes the Launcher whenever one
  1500. * of the input file descriptors needs attention. Otherwise we would
  1501. * run the Guest until it tries to output something. */
  1502. waker_fd = setup_waker(lguest_fd);
  1503. /* Finally, run the Guest. This doesn't return. */
  1504. run_guest(lguest_fd);
  1505. }
  1506. /*:*/
  1507. /*M:999
  1508. * Mastery is done: you now know everything I do.
  1509. *
  1510. * But surely you have seen code, features and bugs in your wanderings which
  1511. * you now yearn to attack? That is the real game, and I look forward to you
  1512. * patching and forking lguest into the Your-Name-Here-visor.
  1513. *
  1514. * Farewell, and good coding!
  1515. * Rusty Russell.
  1516. */