lguest.c 57 KB

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