lguest.c 57 KB

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