lguest.c 57 KB

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