lguest.c 55 KB

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