lguest.c 59 KB

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