lguest.c 54 KB

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