lguest.c 53 KB

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