lguest.c 95 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414
  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. #include <sys/user.h>
  45. #include <linux/pci_regs.h>
  46. #ifndef VIRTIO_F_ANY_LAYOUT
  47. #define VIRTIO_F_ANY_LAYOUT 27
  48. #endif
  49. /*L:110
  50. * We can ignore the 43 include files we need for this program, but I do want
  51. * to draw attention to the use of kernel-style types.
  52. *
  53. * As Linus said, "C is a Spartan language, and so should your naming be." I
  54. * like these abbreviations, so we define them here. Note that u64 is always
  55. * unsigned long long, which works on all Linux systems: this means that we can
  56. * use %llu in printf for any u64.
  57. */
  58. typedef unsigned long long u64;
  59. typedef uint32_t u32;
  60. typedef uint16_t u16;
  61. typedef uint8_t u8;
  62. /*:*/
  63. #define VIRTIO_CONFIG_NO_LEGACY
  64. #define VIRTIO_PCI_NO_LEGACY
  65. #define VIRTIO_BLK_NO_LEGACY
  66. #define VIRTIO_NET_NO_LEGACY
  67. /* Use in-kernel ones, which defines VIRTIO_F_VERSION_1 */
  68. #include "../../include/uapi/linux/virtio_config.h"
  69. #include "../../include/uapi/linux/virtio_net.h"
  70. #include "../../include/uapi/linux/virtio_blk.h"
  71. #include "../../include/uapi/linux/virtio_console.h"
  72. #include "../../include/uapi/linux/virtio_rng.h"
  73. #include <linux/virtio_ring.h>
  74. #include "../../include/uapi/linux/virtio_pci.h"
  75. #include <asm/bootparam.h>
  76. #include "../../include/linux/lguest_launcher.h"
  77. #define BRIDGE_PFX "bridge:"
  78. #ifndef SIOCBRADDIF
  79. #define SIOCBRADDIF 0x89a2 /* add interface to bridge */
  80. #endif
  81. /* We can have up to 256 pages for devices. */
  82. #define DEVICE_PAGES 256
  83. /* This will occupy 3 pages: it must be a power of 2. */
  84. #define VIRTQUEUE_NUM 256
  85. /*L:120
  86. * verbose is both a global flag and a macro. The C preprocessor allows
  87. * this, and although I wouldn't recommend it, it works quite nicely here.
  88. */
  89. static bool verbose;
  90. #define verbose(args...) \
  91. do { if (verbose) printf(args); } while(0)
  92. /*:*/
  93. /* The pointer to the start of guest memory. */
  94. static void *guest_base;
  95. /* The maximum guest physical address allowed, and maximum possible. */
  96. static unsigned long guest_limit, guest_max, guest_mmio;
  97. /* The /dev/lguest file descriptor. */
  98. static int lguest_fd;
  99. /* a per-cpu variable indicating whose vcpu is currently running */
  100. static unsigned int __thread cpu_id;
  101. /* 5 bit device number in the PCI_CONFIG_ADDR => 32 only */
  102. #define MAX_PCI_DEVICES 32
  103. /* This is our list of devices. */
  104. struct device_list {
  105. /* Counter to assign interrupt numbers. */
  106. unsigned int next_irq;
  107. /* Counter to print out convenient device numbers. */
  108. unsigned int device_num;
  109. /* PCI devices. */
  110. struct device *pci[MAX_PCI_DEVICES];
  111. };
  112. /* The list of Guest devices, based on command line arguments. */
  113. static struct device_list devices;
  114. /*
  115. * Just like struct virtio_pci_cfg_cap in uapi/linux/virtio_pci.h,
  116. * but uses a u32 explicitly for the data.
  117. */
  118. struct virtio_pci_cfg_cap_u32 {
  119. struct virtio_pci_cap cap;
  120. u32 pci_cfg_data; /* Data for BAR access. */
  121. };
  122. struct virtio_pci_mmio {
  123. struct virtio_pci_common_cfg cfg;
  124. u16 notify;
  125. u8 isr;
  126. u8 padding;
  127. /* Device-specific configuration follows this. */
  128. };
  129. /* This is the layout (little-endian) of the PCI config space. */
  130. struct pci_config {
  131. u16 vendor_id, device_id;
  132. u16 command, status;
  133. u8 revid, prog_if, subclass, class;
  134. u8 cacheline_size, lat_timer, header_type, bist;
  135. u32 bar[6];
  136. u32 cardbus_cis_ptr;
  137. u16 subsystem_vendor_id, subsystem_device_id;
  138. u32 expansion_rom_addr;
  139. u8 capabilities, reserved1[3];
  140. u32 reserved2;
  141. u8 irq_line, irq_pin, min_grant, max_latency;
  142. /* Now, this is the linked capability list. */
  143. struct virtio_pci_cap common;
  144. struct virtio_pci_notify_cap notify;
  145. struct virtio_pci_cap isr;
  146. struct virtio_pci_cap device;
  147. struct virtio_pci_cfg_cap_u32 cfg_access;
  148. };
  149. /* The device structure describes a single device. */
  150. struct device {
  151. /* The name of this device, for --verbose. */
  152. const char *name;
  153. /* Any queues attached to this device */
  154. struct virtqueue *vq;
  155. /* Is it operational */
  156. bool running;
  157. /* Has it written FEATURES_OK but not re-checked it? */
  158. bool wrote_features_ok;
  159. /* PCI configuration */
  160. union {
  161. struct pci_config config;
  162. u32 config_words[sizeof(struct pci_config) / sizeof(u32)];
  163. };
  164. /* Features we offer, and those accepted. */
  165. u64 features, features_accepted;
  166. /* Device-specific config hangs off the end of this. */
  167. struct virtio_pci_mmio *mmio;
  168. /* PCI MMIO resources (all in BAR0) */
  169. size_t mmio_size;
  170. u32 mmio_addr;
  171. /* Device-specific data. */
  172. void *priv;
  173. };
  174. /* The virtqueue structure describes a queue attached to a device. */
  175. struct virtqueue {
  176. struct virtqueue *next;
  177. /* Which device owns me. */
  178. struct device *dev;
  179. /* Name for printing errors. */
  180. const char *name;
  181. /* The actual ring of buffers. */
  182. struct vring vring;
  183. /* The information about this virtqueue (we only use queue_size on) */
  184. struct virtio_pci_common_cfg pci_config;
  185. /* Last available index we saw. */
  186. u16 last_avail_idx;
  187. /* How many are used since we sent last irq? */
  188. unsigned int pending_used;
  189. /* Eventfd where Guest notifications arrive. */
  190. int eventfd;
  191. /* Function for the thread which is servicing this virtqueue. */
  192. void (*service)(struct virtqueue *vq);
  193. pid_t thread;
  194. };
  195. /* Remember the arguments to the program so we can "reboot" */
  196. static char **main_args;
  197. /* The original tty settings to restore on exit. */
  198. static struct termios orig_term;
  199. /*
  200. * We have to be careful with barriers: our devices are all run in separate
  201. * threads and so we need to make sure that changes visible to the Guest happen
  202. * in precise order.
  203. */
  204. #define wmb() __asm__ __volatile__("" : : : "memory")
  205. #define rmb() __asm__ __volatile__("lock; addl $0,0(%%esp)" : : : "memory")
  206. #define mb() __asm__ __volatile__("lock; addl $0,0(%%esp)" : : : "memory")
  207. /* Wrapper for the last available index. Makes it easier to change. */
  208. #define lg_last_avail(vq) ((vq)->last_avail_idx)
  209. /*
  210. * The virtio configuration space is defined to be little-endian. x86 is
  211. * little-endian too, but it's nice to be explicit so we have these helpers.
  212. */
  213. #define cpu_to_le16(v16) (v16)
  214. #define cpu_to_le32(v32) (v32)
  215. #define cpu_to_le64(v64) (v64)
  216. #define le16_to_cpu(v16) (v16)
  217. #define le32_to_cpu(v32) (v32)
  218. #define le64_to_cpu(v64) (v64)
  219. /*
  220. * A real device would ignore weird/non-compliant driver behaviour. We
  221. * stop and flag it, to help debugging Linux problems.
  222. */
  223. #define bad_driver(d, fmt, ...) \
  224. errx(1, "%s: bad driver: " fmt, (d)->name, ## __VA_ARGS__)
  225. #define bad_driver_vq(vq, fmt, ...) \
  226. errx(1, "%s vq %s: bad driver: " fmt, (vq)->dev->name, \
  227. vq->name, ## __VA_ARGS__)
  228. /* Is this iovec empty? */
  229. static bool iov_empty(const struct iovec iov[], unsigned int num_iov)
  230. {
  231. unsigned int i;
  232. for (i = 0; i < num_iov; i++)
  233. if (iov[i].iov_len)
  234. return false;
  235. return true;
  236. }
  237. /* Take len bytes from the front of this iovec. */
  238. static void iov_consume(struct device *d,
  239. struct iovec iov[], unsigned num_iov,
  240. void *dest, unsigned len)
  241. {
  242. unsigned int i;
  243. for (i = 0; i < num_iov; i++) {
  244. unsigned int used;
  245. used = iov[i].iov_len < len ? iov[i].iov_len : len;
  246. if (dest) {
  247. memcpy(dest, iov[i].iov_base, used);
  248. dest += used;
  249. }
  250. iov[i].iov_base += used;
  251. iov[i].iov_len -= used;
  252. len -= used;
  253. }
  254. if (len != 0)
  255. bad_driver(d, "iovec too short!");
  256. }
  257. /*L:100
  258. * The Launcher code itself takes us out into userspace, that scary place where
  259. * pointers run wild and free! Unfortunately, like most userspace programs,
  260. * it's quite boring (which is why everyone likes to hack on the kernel!).
  261. * Perhaps if you make up an Lguest Drinking Game at this point, it will get
  262. * you through this section. Or, maybe not.
  263. *
  264. * The Launcher sets up a big chunk of memory to be the Guest's "physical"
  265. * memory and stores it in "guest_base". In other words, Guest physical ==
  266. * Launcher virtual with an offset.
  267. *
  268. * This can be tough to get your head around, but usually it just means that we
  269. * use these trivial conversion functions when the Guest gives us its
  270. * "physical" addresses:
  271. */
  272. static void *from_guest_phys(unsigned long addr)
  273. {
  274. return guest_base + addr;
  275. }
  276. static unsigned long to_guest_phys(const void *addr)
  277. {
  278. return (addr - guest_base);
  279. }
  280. /*L:130
  281. * Loading the Kernel.
  282. *
  283. * We start with couple of simple helper routines. open_or_die() avoids
  284. * error-checking code cluttering the callers:
  285. */
  286. static int open_or_die(const char *name, int flags)
  287. {
  288. int fd = open(name, flags);
  289. if (fd < 0)
  290. err(1, "Failed to open %s", name);
  291. return fd;
  292. }
  293. /* map_zeroed_pages() takes a number of pages. */
  294. static void *map_zeroed_pages(unsigned int num)
  295. {
  296. int fd = open_or_die("/dev/zero", O_RDONLY);
  297. void *addr;
  298. /*
  299. * We use a private mapping (ie. if we write to the page, it will be
  300. * copied). We allocate an extra two pages PROT_NONE to act as guard
  301. * pages against read/write attempts that exceed allocated space.
  302. */
  303. addr = mmap(NULL, getpagesize() * (num+2),
  304. PROT_NONE, MAP_PRIVATE, fd, 0);
  305. if (addr == MAP_FAILED)
  306. err(1, "Mmapping %u pages of /dev/zero", num);
  307. if (mprotect(addr + getpagesize(), getpagesize() * num,
  308. PROT_READ|PROT_WRITE) == -1)
  309. err(1, "mprotect rw %u pages failed", num);
  310. /*
  311. * One neat mmap feature is that you can close the fd, and it
  312. * stays mapped.
  313. */
  314. close(fd);
  315. /* Return address after PROT_NONE page */
  316. return addr + getpagesize();
  317. }
  318. /* Get some bytes which won't be mapped into the guest. */
  319. static unsigned long get_mmio_region(size_t size)
  320. {
  321. unsigned long addr = guest_mmio;
  322. size_t i;
  323. if (!size)
  324. return addr;
  325. /* Size has to be a power of 2 (and multiple of 16) */
  326. for (i = 1; i < size; i <<= 1);
  327. guest_mmio += i;
  328. return addr;
  329. }
  330. /*
  331. * This routine is used to load the kernel or initrd. It tries mmap, but if
  332. * that fails (Plan 9's kernel file isn't nicely aligned on page boundaries),
  333. * it falls back to reading the memory in.
  334. */
  335. static void map_at(int fd, void *addr, unsigned long offset, unsigned long len)
  336. {
  337. ssize_t r;
  338. /*
  339. * We map writable even though for some segments are marked read-only.
  340. * The kernel really wants to be writable: it patches its own
  341. * instructions.
  342. *
  343. * MAP_PRIVATE means that the page won't be copied until a write is
  344. * done to it. This allows us to share untouched memory between
  345. * Guests.
  346. */
  347. if (mmap(addr, len, PROT_READ|PROT_WRITE,
  348. MAP_FIXED|MAP_PRIVATE, fd, offset) != MAP_FAILED)
  349. return;
  350. /* pread does a seek and a read in one shot: saves a few lines. */
  351. r = pread(fd, addr, len, offset);
  352. if (r != len)
  353. err(1, "Reading offset %lu len %lu gave %zi", offset, len, r);
  354. }
  355. /*
  356. * This routine takes an open vmlinux image, which is in ELF, and maps it into
  357. * the Guest memory. ELF = Embedded Linking Format, which is the format used
  358. * by all modern binaries on Linux including the kernel.
  359. *
  360. * The ELF headers give *two* addresses: a physical address, and a virtual
  361. * address. We use the physical address; the Guest will map itself to the
  362. * virtual address.
  363. *
  364. * We return the starting address.
  365. */
  366. static unsigned long map_elf(int elf_fd, const Elf32_Ehdr *ehdr)
  367. {
  368. Elf32_Phdr phdr[ehdr->e_phnum];
  369. unsigned int i;
  370. /*
  371. * Sanity checks on the main ELF header: an x86 executable with a
  372. * reasonable number of correctly-sized program headers.
  373. */
  374. if (ehdr->e_type != ET_EXEC
  375. || ehdr->e_machine != EM_386
  376. || ehdr->e_phentsize != sizeof(Elf32_Phdr)
  377. || ehdr->e_phnum < 1 || ehdr->e_phnum > 65536U/sizeof(Elf32_Phdr))
  378. errx(1, "Malformed elf header");
  379. /*
  380. * An ELF executable contains an ELF header and a number of "program"
  381. * headers which indicate which parts ("segments") of the program to
  382. * load where.
  383. */
  384. /* We read in all the program headers at once: */
  385. if (lseek(elf_fd, ehdr->e_phoff, SEEK_SET) < 0)
  386. err(1, "Seeking to program headers");
  387. if (read(elf_fd, phdr, sizeof(phdr)) != sizeof(phdr))
  388. err(1, "Reading program headers");
  389. /*
  390. * Try all the headers: there are usually only three. A read-only one,
  391. * a read-write one, and a "note" section which we don't load.
  392. */
  393. for (i = 0; i < ehdr->e_phnum; i++) {
  394. /* If this isn't a loadable segment, we ignore it */
  395. if (phdr[i].p_type != PT_LOAD)
  396. continue;
  397. verbose("Section %i: size %i addr %p\n",
  398. i, phdr[i].p_memsz, (void *)phdr[i].p_paddr);
  399. /* We map this section of the file at its physical address. */
  400. map_at(elf_fd, from_guest_phys(phdr[i].p_paddr),
  401. phdr[i].p_offset, phdr[i].p_filesz);
  402. }
  403. /* The entry point is given in the ELF header. */
  404. return ehdr->e_entry;
  405. }
  406. /*L:150
  407. * A bzImage, unlike an ELF file, is not meant to be loaded. You're supposed
  408. * to jump into it and it will unpack itself. We used to have to perform some
  409. * hairy magic because the unpacking code scared me.
  410. *
  411. * Fortunately, Jeremy Fitzhardinge convinced me it wasn't that hard and wrote
  412. * a small patch to jump over the tricky bits in the Guest, so now we just read
  413. * the funky header so we know where in the file to load, and away we go!
  414. */
  415. static unsigned long load_bzimage(int fd)
  416. {
  417. struct boot_params boot;
  418. int r;
  419. /* Modern bzImages get loaded at 1M. */
  420. void *p = from_guest_phys(0x100000);
  421. /*
  422. * Go back to the start of the file and read the header. It should be
  423. * a Linux boot header (see Documentation/x86/boot.txt)
  424. */
  425. lseek(fd, 0, SEEK_SET);
  426. read(fd, &boot, sizeof(boot));
  427. /* Inside the setup_hdr, we expect the magic "HdrS" */
  428. if (memcmp(&boot.hdr.header, "HdrS", 4) != 0)
  429. errx(1, "This doesn't look like a bzImage to me");
  430. /* Skip over the extra sectors of the header. */
  431. lseek(fd, (boot.hdr.setup_sects+1) * 512, SEEK_SET);
  432. /* Now read everything into memory. in nice big chunks. */
  433. while ((r = read(fd, p, 65536)) > 0)
  434. p += r;
  435. /* Finally, code32_start tells us where to enter the kernel. */
  436. return boot.hdr.code32_start;
  437. }
  438. /*L:140
  439. * Loading the kernel is easy when it's a "vmlinux", but most kernels
  440. * come wrapped up in the self-decompressing "bzImage" format. With a little
  441. * work, we can load those, too.
  442. */
  443. static unsigned long load_kernel(int fd)
  444. {
  445. Elf32_Ehdr hdr;
  446. /* Read in the first few bytes. */
  447. if (read(fd, &hdr, sizeof(hdr)) != sizeof(hdr))
  448. err(1, "Reading kernel");
  449. /* If it's an ELF file, it starts with "\177ELF" */
  450. if (memcmp(hdr.e_ident, ELFMAG, SELFMAG) == 0)
  451. return map_elf(fd, &hdr);
  452. /* Otherwise we assume it's a bzImage, and try to load it. */
  453. return load_bzimage(fd);
  454. }
  455. /*
  456. * This is a trivial little helper to align pages. Andi Kleen hated it because
  457. * it calls getpagesize() twice: "it's dumb code."
  458. *
  459. * Kernel guys get really het up about optimization, even when it's not
  460. * necessary. I leave this code as a reaction against that.
  461. */
  462. static inline unsigned long page_align(unsigned long addr)
  463. {
  464. /* Add upwards and truncate downwards. */
  465. return ((addr + getpagesize()-1) & ~(getpagesize()-1));
  466. }
  467. /*L:180
  468. * An "initial ram disk" is a disk image loaded into memory along with the
  469. * kernel which the kernel can use to boot from without needing any drivers.
  470. * Most distributions now use this as standard: the initrd contains the code to
  471. * load the appropriate driver modules for the current machine.
  472. *
  473. * Importantly, James Morris works for RedHat, and Fedora uses initrds for its
  474. * kernels. He sent me this (and tells me when I break it).
  475. */
  476. static unsigned long load_initrd(const char *name, unsigned long mem)
  477. {
  478. int ifd;
  479. struct stat st;
  480. unsigned long len;
  481. ifd = open_or_die(name, O_RDONLY);
  482. /* fstat() is needed to get the file size. */
  483. if (fstat(ifd, &st) < 0)
  484. err(1, "fstat() on initrd '%s'", name);
  485. /*
  486. * We map the initrd at the top of memory, but mmap wants it to be
  487. * page-aligned, so we round the size up for that.
  488. */
  489. len = page_align(st.st_size);
  490. map_at(ifd, from_guest_phys(mem - len), 0, st.st_size);
  491. /*
  492. * Once a file is mapped, you can close the file descriptor. It's a
  493. * little odd, but quite useful.
  494. */
  495. close(ifd);
  496. verbose("mapped initrd %s size=%lu @ %p\n", name, len, (void*)mem-len);
  497. /* We return the initrd size. */
  498. return len;
  499. }
  500. /*:*/
  501. /*
  502. * Simple routine to roll all the commandline arguments together with spaces
  503. * between them.
  504. */
  505. static void concat(char *dst, char *args[])
  506. {
  507. unsigned int i, len = 0;
  508. for (i = 0; args[i]; i++) {
  509. if (i) {
  510. strcat(dst+len, " ");
  511. len++;
  512. }
  513. strcpy(dst+len, args[i]);
  514. len += strlen(args[i]);
  515. }
  516. /* In case it's empty. */
  517. dst[len] = '\0';
  518. }
  519. /*L:185
  520. * This is where we actually tell the kernel to initialize the Guest. We
  521. * saw the arguments it expects when we looked at initialize() in lguest_user.c:
  522. * the base of Guest "physical" memory, the top physical page to allow and the
  523. * entry point for the Guest.
  524. */
  525. static void tell_kernel(unsigned long start)
  526. {
  527. unsigned long args[] = { LHREQ_INITIALIZE,
  528. (unsigned long)guest_base,
  529. guest_limit / getpagesize(), start,
  530. (guest_mmio+getpagesize()-1) / getpagesize() };
  531. verbose("Guest: %p - %p (%#lx, MMIO %#lx)\n",
  532. guest_base, guest_base + guest_limit,
  533. guest_limit, guest_mmio);
  534. lguest_fd = open_or_die("/dev/lguest", O_RDWR);
  535. if (write(lguest_fd, args, sizeof(args)) < 0)
  536. err(1, "Writing to /dev/lguest");
  537. }
  538. /*:*/
  539. /*L:200
  540. * Device Handling.
  541. *
  542. * When the Guest gives us a buffer, it sends an array of addresses and sizes.
  543. * We need to make sure it's not trying to reach into the Launcher itself, so
  544. * we have a convenient routine which checks it and exits with an error message
  545. * if something funny is going on:
  546. */
  547. static void *_check_pointer(struct device *d,
  548. unsigned long addr, unsigned int size,
  549. unsigned int line)
  550. {
  551. /*
  552. * Check if the requested address and size exceeds the allocated memory,
  553. * or addr + size wraps around.
  554. */
  555. if ((addr + size) > guest_limit || (addr + size) < addr)
  556. bad_driver(d, "%s:%i: Invalid address %#lx",
  557. __FILE__, line, addr);
  558. /*
  559. * We return a pointer for the caller's convenience, now we know it's
  560. * safe to use.
  561. */
  562. return from_guest_phys(addr);
  563. }
  564. /* A macro which transparently hands the line number to the real function. */
  565. #define check_pointer(d,addr,size) _check_pointer(d, addr, size, __LINE__)
  566. /*
  567. * Each buffer in the virtqueues is actually a chain of descriptors. This
  568. * function returns the next descriptor in the chain, or vq->vring.num if we're
  569. * at the end.
  570. */
  571. static unsigned next_desc(struct device *d, struct vring_desc *desc,
  572. unsigned int i, unsigned int max)
  573. {
  574. unsigned int next;
  575. /* If this descriptor says it doesn't chain, we're done. */
  576. if (!(desc[i].flags & VRING_DESC_F_NEXT))
  577. return max;
  578. /* Check they're not leading us off end of descriptors. */
  579. next = desc[i].next;
  580. /* Make sure compiler knows to grab that: we don't want it changing! */
  581. wmb();
  582. if (next >= max)
  583. bad_driver(d, "Desc next is %u", next);
  584. return next;
  585. }
  586. /*
  587. * This actually sends the interrupt for this virtqueue, if we've used a
  588. * buffer.
  589. */
  590. static void trigger_irq(struct virtqueue *vq)
  591. {
  592. unsigned long buf[] = { LHREQ_IRQ, vq->dev->config.irq_line };
  593. /* Don't inform them if nothing used. */
  594. if (!vq->pending_used)
  595. return;
  596. vq->pending_used = 0;
  597. /*
  598. * 2.4.7.1:
  599. *
  600. * If the VIRTIO_F_EVENT_IDX feature bit is not negotiated:
  601. * The driver MUST set flags to 0 or 1.
  602. */
  603. if (vq->vring.avail->flags > 1)
  604. bad_driver_vq(vq, "avail->flags = %u\n", vq->vring.avail->flags);
  605. /*
  606. * 2.4.7.2:
  607. *
  608. * If the VIRTIO_F_EVENT_IDX feature bit is not negotiated:
  609. *
  610. * - The device MUST ignore the used_event value.
  611. * - After the device writes a descriptor index into the used ring:
  612. * - If flags is 1, the device SHOULD NOT send an interrupt.
  613. * - If flags is 0, the device MUST send an interrupt.
  614. */
  615. if (vq->vring.avail->flags & VRING_AVAIL_F_NO_INTERRUPT) {
  616. return;
  617. }
  618. /*
  619. * 4.1.4.5.1:
  620. *
  621. * If MSI-X capability is disabled, the device MUST set the Queue
  622. * Interrupt bit in ISR status before sending a virtqueue notification
  623. * to the driver.
  624. */
  625. vq->dev->mmio->isr = 0x1;
  626. /* Send the Guest an interrupt tell them we used something up. */
  627. if (write(lguest_fd, buf, sizeof(buf)) != 0)
  628. err(1, "Triggering irq %i", vq->dev->config.irq_line);
  629. }
  630. /*
  631. * This looks in the virtqueue for the first available buffer, and converts
  632. * it to an iovec for convenient access. Since descriptors consist of some
  633. * number of output then some number of input descriptors, it's actually two
  634. * iovecs, but we pack them into one and note how many of each there were.
  635. *
  636. * This function waits if necessary, and returns the descriptor number found.
  637. */
  638. static unsigned wait_for_vq_desc(struct virtqueue *vq,
  639. struct iovec iov[],
  640. unsigned int *out_num, unsigned int *in_num)
  641. {
  642. unsigned int i, head, max;
  643. struct vring_desc *desc;
  644. u16 last_avail = lg_last_avail(vq);
  645. /*
  646. * 2.4.7.1:
  647. *
  648. * The driver MUST handle spurious interrupts from the device.
  649. *
  650. * That's why this is a while loop.
  651. */
  652. /* There's nothing available? */
  653. while (last_avail == vq->vring.avail->idx) {
  654. u64 event;
  655. /*
  656. * Since we're about to sleep, now is a good time to tell the
  657. * Guest about what we've used up to now.
  658. */
  659. trigger_irq(vq);
  660. /* OK, now we need to know about added descriptors. */
  661. vq->vring.used->flags &= ~VRING_USED_F_NO_NOTIFY;
  662. /*
  663. * They could have slipped one in as we were doing that: make
  664. * sure it's written, then check again.
  665. */
  666. mb();
  667. if (last_avail != vq->vring.avail->idx) {
  668. vq->vring.used->flags |= VRING_USED_F_NO_NOTIFY;
  669. break;
  670. }
  671. /* Nothing new? Wait for eventfd to tell us they refilled. */
  672. if (read(vq->eventfd, &event, sizeof(event)) != sizeof(event))
  673. errx(1, "Event read failed?");
  674. /* We don't need to be notified again. */
  675. vq->vring.used->flags |= VRING_USED_F_NO_NOTIFY;
  676. }
  677. /* Check it isn't doing very strange things with descriptor numbers. */
  678. if ((u16)(vq->vring.avail->idx - last_avail) > vq->vring.num)
  679. bad_driver_vq(vq, "Guest moved used index from %u to %u",
  680. last_avail, vq->vring.avail->idx);
  681. /*
  682. * Make sure we read the descriptor number *after* we read the ring
  683. * update; don't let the cpu or compiler change the order.
  684. */
  685. rmb();
  686. /*
  687. * Grab the next descriptor number they're advertising, and increment
  688. * the index we've seen.
  689. */
  690. head = vq->vring.avail->ring[last_avail % vq->vring.num];
  691. lg_last_avail(vq)++;
  692. /* If their number is silly, that's a fatal mistake. */
  693. if (head >= vq->vring.num)
  694. bad_driver_vq(vq, "Guest says index %u is available", head);
  695. /* When we start there are none of either input nor output. */
  696. *out_num = *in_num = 0;
  697. max = vq->vring.num;
  698. desc = vq->vring.desc;
  699. i = head;
  700. /*
  701. * We have to read the descriptor after we read the descriptor number,
  702. * but there's a data dependency there so the CPU shouldn't reorder
  703. * that: no rmb() required.
  704. */
  705. do {
  706. /*
  707. * If this is an indirect entry, then this buffer contains a
  708. * descriptor table which we handle as if it's any normal
  709. * descriptor chain.
  710. */
  711. if (desc[i].flags & VRING_DESC_F_INDIRECT) {
  712. /* 2.4.5.3.1:
  713. *
  714. * The driver MUST NOT set the VIRTQ_DESC_F_INDIRECT
  715. * flag unless the VIRTIO_F_INDIRECT_DESC feature was
  716. * negotiated.
  717. */
  718. if (!(vq->dev->features_accepted &
  719. (1<<VIRTIO_RING_F_INDIRECT_DESC)))
  720. bad_driver_vq(vq, "vq indirect not negotiated");
  721. /*
  722. * 2.4.5.3.1:
  723. *
  724. * The driver MUST NOT set the VIRTQ_DESC_F_INDIRECT
  725. * flag within an indirect descriptor (ie. only one
  726. * table per descriptor).
  727. */
  728. if (desc != vq->vring.desc)
  729. bad_driver_vq(vq, "Indirect within indirect");
  730. /*
  731. * Proposed update VIRTIO-134 spells this out:
  732. *
  733. * A driver MUST NOT set both VIRTQ_DESC_F_INDIRECT
  734. * and VIRTQ_DESC_F_NEXT in flags.
  735. */
  736. if (desc[i].flags & VRING_DESC_F_NEXT)
  737. bad_driver_vq(vq, "indirect and next together");
  738. if (desc[i].len % sizeof(struct vring_desc))
  739. bad_driver_vq(vq,
  740. "Invalid size for indirect table");
  741. /*
  742. * 2.4.5.3.2:
  743. *
  744. * The device MUST ignore the write-only flag
  745. * (flags&VIRTQ_DESC_F_WRITE) in the descriptor that
  746. * refers to an indirect table.
  747. *
  748. * We ignore it here: :)
  749. */
  750. max = desc[i].len / sizeof(struct vring_desc);
  751. desc = check_pointer(vq->dev, desc[i].addr, desc[i].len);
  752. i = 0;
  753. /* 2.4.5.3.1:
  754. *
  755. * A driver MUST NOT create a descriptor chain longer
  756. * than the Queue Size of the device.
  757. */
  758. if (max > vq->pci_config.queue_size)
  759. bad_driver_vq(vq,
  760. "indirect has too many entries");
  761. }
  762. /* Grab the first descriptor, and check it's OK. */
  763. iov[*out_num + *in_num].iov_len = desc[i].len;
  764. iov[*out_num + *in_num].iov_base
  765. = check_pointer(vq->dev, desc[i].addr, desc[i].len);
  766. /* If this is an input descriptor, increment that count. */
  767. if (desc[i].flags & VRING_DESC_F_WRITE)
  768. (*in_num)++;
  769. else {
  770. /*
  771. * If it's an output descriptor, they're all supposed
  772. * to come before any input descriptors.
  773. */
  774. if (*in_num)
  775. bad_driver_vq(vq,
  776. "Descriptor has out after in");
  777. (*out_num)++;
  778. }
  779. /* If we've got too many, that implies a descriptor loop. */
  780. if (*out_num + *in_num > max)
  781. bad_driver_vq(vq, "Looped descriptor");
  782. } while ((i = next_desc(vq->dev, desc, i, max)) != max);
  783. return head;
  784. }
  785. /*
  786. * After we've used one of their buffers, we tell the Guest about it. Sometime
  787. * later we'll want to send them an interrupt using trigger_irq(); note that
  788. * wait_for_vq_desc() does that for us if it has to wait.
  789. */
  790. static void add_used(struct virtqueue *vq, unsigned int head, int len)
  791. {
  792. struct vring_used_elem *used;
  793. /*
  794. * The virtqueue contains a ring of used buffers. Get a pointer to the
  795. * next entry in that used ring.
  796. */
  797. used = &vq->vring.used->ring[vq->vring.used->idx % vq->vring.num];
  798. used->id = head;
  799. used->len = len;
  800. /* Make sure buffer is written before we update index. */
  801. wmb();
  802. vq->vring.used->idx++;
  803. vq->pending_used++;
  804. }
  805. /* And here's the combo meal deal. Supersize me! */
  806. static void add_used_and_trigger(struct virtqueue *vq, unsigned head, int len)
  807. {
  808. add_used(vq, head, len);
  809. trigger_irq(vq);
  810. }
  811. /*
  812. * The Console
  813. *
  814. * We associate some data with the console for our exit hack.
  815. */
  816. struct console_abort {
  817. /* How many times have they hit ^C? */
  818. int count;
  819. /* When did they start? */
  820. struct timeval start;
  821. };
  822. /* This is the routine which handles console input (ie. stdin). */
  823. static void console_input(struct virtqueue *vq)
  824. {
  825. int len;
  826. unsigned int head, in_num, out_num;
  827. struct console_abort *abort = vq->dev->priv;
  828. struct iovec iov[vq->vring.num];
  829. /* Make sure there's a descriptor available. */
  830. head = wait_for_vq_desc(vq, iov, &out_num, &in_num);
  831. if (out_num)
  832. bad_driver_vq(vq, "Output buffers in console in queue?");
  833. /* Read into it. This is where we usually wait. */
  834. len = readv(STDIN_FILENO, iov, in_num);
  835. if (len <= 0) {
  836. /* Ran out of input? */
  837. warnx("Failed to get console input, ignoring console.");
  838. /*
  839. * For simplicity, dying threads kill the whole Launcher. So
  840. * just nap here.
  841. */
  842. for (;;)
  843. pause();
  844. }
  845. /* Tell the Guest we used a buffer. */
  846. add_used_and_trigger(vq, head, len);
  847. /*
  848. * Three ^C within one second? Exit.
  849. *
  850. * This is such a hack, but works surprisingly well. Each ^C has to
  851. * be in a buffer by itself, so they can't be too fast. But we check
  852. * that we get three within about a second, so they can't be too
  853. * slow.
  854. */
  855. if (len != 1 || ((char *)iov[0].iov_base)[0] != 3) {
  856. abort->count = 0;
  857. return;
  858. }
  859. abort->count++;
  860. if (abort->count == 1)
  861. gettimeofday(&abort->start, NULL);
  862. else if (abort->count == 3) {
  863. struct timeval now;
  864. gettimeofday(&now, NULL);
  865. /* Kill all Launcher processes with SIGINT, like normal ^C */
  866. if (now.tv_sec <= abort->start.tv_sec+1)
  867. kill(0, SIGINT);
  868. abort->count = 0;
  869. }
  870. }
  871. /* This is the routine which handles console output (ie. stdout). */
  872. static void console_output(struct virtqueue *vq)
  873. {
  874. unsigned int head, out, in;
  875. struct iovec iov[vq->vring.num];
  876. /* We usually wait in here, for the Guest to give us something. */
  877. head = wait_for_vq_desc(vq, iov, &out, &in);
  878. if (in)
  879. bad_driver_vq(vq, "Input buffers in console output queue?");
  880. /* writev can return a partial write, so we loop here. */
  881. while (!iov_empty(iov, out)) {
  882. int len = writev(STDOUT_FILENO, iov, out);
  883. if (len <= 0) {
  884. warn("Write to stdout gave %i (%d)", len, errno);
  885. break;
  886. }
  887. iov_consume(vq->dev, iov, out, NULL, len);
  888. }
  889. /*
  890. * We're finished with that buffer: if we're going to sleep,
  891. * wait_for_vq_desc() will prod the Guest with an interrupt.
  892. */
  893. add_used(vq, head, 0);
  894. }
  895. /*
  896. * The Network
  897. *
  898. * Handling output for network is also simple: we get all the output buffers
  899. * and write them to /dev/net/tun.
  900. */
  901. struct net_info {
  902. int tunfd;
  903. };
  904. static void net_output(struct virtqueue *vq)
  905. {
  906. struct net_info *net_info = vq->dev->priv;
  907. unsigned int head, out, in;
  908. struct iovec iov[vq->vring.num];
  909. /* We usually wait in here for the Guest to give us a packet. */
  910. head = wait_for_vq_desc(vq, iov, &out, &in);
  911. if (in)
  912. bad_driver_vq(vq, "Input buffers in net output queue?");
  913. /*
  914. * Send the whole thing through to /dev/net/tun. It expects the exact
  915. * same format: what a coincidence!
  916. */
  917. if (writev(net_info->tunfd, iov, out) < 0)
  918. warnx("Write to tun failed (%d)?", errno);
  919. /*
  920. * Done with that one; wait_for_vq_desc() will send the interrupt if
  921. * all packets are processed.
  922. */
  923. add_used(vq, head, 0);
  924. }
  925. /*
  926. * Handling network input is a bit trickier, because I've tried to optimize it.
  927. *
  928. * First we have a helper routine which tells is if from this file descriptor
  929. * (ie. the /dev/net/tun device) will block:
  930. */
  931. static bool will_block(int fd)
  932. {
  933. fd_set fdset;
  934. struct timeval zero = { 0, 0 };
  935. FD_ZERO(&fdset);
  936. FD_SET(fd, &fdset);
  937. return select(fd+1, &fdset, NULL, NULL, &zero) != 1;
  938. }
  939. /*
  940. * This handles packets coming in from the tun device to our Guest. Like all
  941. * service routines, it gets called again as soon as it returns, so you don't
  942. * see a while(1) loop here.
  943. */
  944. static void net_input(struct virtqueue *vq)
  945. {
  946. int len;
  947. unsigned int head, out, in;
  948. struct iovec iov[vq->vring.num];
  949. struct net_info *net_info = vq->dev->priv;
  950. /*
  951. * Get a descriptor to write an incoming packet into. This will also
  952. * send an interrupt if they're out of descriptors.
  953. */
  954. head = wait_for_vq_desc(vq, iov, &out, &in);
  955. if (out)
  956. bad_driver_vq(vq, "Output buffers in net input queue?");
  957. /*
  958. * If it looks like we'll block reading from the tun device, send them
  959. * an interrupt.
  960. */
  961. if (vq->pending_used && will_block(net_info->tunfd))
  962. trigger_irq(vq);
  963. /*
  964. * Read in the packet. This is where we normally wait (when there's no
  965. * incoming network traffic).
  966. */
  967. len = readv(net_info->tunfd, iov, in);
  968. if (len <= 0)
  969. warn("Failed to read from tun (%d).", errno);
  970. /*
  971. * Mark that packet buffer as used, but don't interrupt here. We want
  972. * to wait until we've done as much work as we can.
  973. */
  974. add_used(vq, head, len);
  975. }
  976. /*:*/
  977. /* This is the helper to create threads: run the service routine in a loop. */
  978. static int do_thread(void *_vq)
  979. {
  980. struct virtqueue *vq = _vq;
  981. for (;;)
  982. vq->service(vq);
  983. return 0;
  984. }
  985. /*
  986. * When a child dies, we kill our entire process group with SIGTERM. This
  987. * also has the side effect that the shell restores the console for us!
  988. */
  989. static void kill_launcher(int signal)
  990. {
  991. kill(0, SIGTERM);
  992. }
  993. static void reset_vq_pci_config(struct virtqueue *vq)
  994. {
  995. vq->pci_config.queue_size = VIRTQUEUE_NUM;
  996. vq->pci_config.queue_enable = 0;
  997. }
  998. static void reset_device(struct device *dev)
  999. {
  1000. struct virtqueue *vq;
  1001. verbose("Resetting device %s\n", dev->name);
  1002. /* Clear any features they've acked. */
  1003. dev->features_accepted = 0;
  1004. /* We're going to be explicitly killing threads, so ignore them. */
  1005. signal(SIGCHLD, SIG_IGN);
  1006. /*
  1007. * 4.1.4.3.1:
  1008. *
  1009. * The device MUST present a 0 in queue_enable on reset.
  1010. *
  1011. * This means we set it here, and reset the saved ones in every vq.
  1012. */
  1013. dev->mmio->cfg.queue_enable = 0;
  1014. /* Get rid of the virtqueue threads */
  1015. for (vq = dev->vq; vq; vq = vq->next) {
  1016. vq->last_avail_idx = 0;
  1017. reset_vq_pci_config(vq);
  1018. if (vq->thread != (pid_t)-1) {
  1019. kill(vq->thread, SIGTERM);
  1020. waitpid(vq->thread, NULL, 0);
  1021. vq->thread = (pid_t)-1;
  1022. }
  1023. }
  1024. dev->running = false;
  1025. dev->wrote_features_ok = false;
  1026. /* Now we care if threads die. */
  1027. signal(SIGCHLD, (void *)kill_launcher);
  1028. }
  1029. static void cleanup_devices(void)
  1030. {
  1031. unsigned int i;
  1032. for (i = 1; i < MAX_PCI_DEVICES; i++) {
  1033. struct device *d = devices.pci[i];
  1034. if (!d)
  1035. continue;
  1036. reset_device(d);
  1037. }
  1038. /* If we saved off the original terminal settings, restore them now. */
  1039. if (orig_term.c_lflag & (ISIG|ICANON|ECHO))
  1040. tcsetattr(STDIN_FILENO, TCSANOW, &orig_term);
  1041. }
  1042. /*L:217
  1043. * We do PCI. This is mainly done to let us test the kernel virtio PCI
  1044. * code.
  1045. */
  1046. /* Linux expects a PCI host bridge: ours is a dummy, and first on the bus. */
  1047. static struct device pci_host_bridge;
  1048. static void init_pci_host_bridge(void)
  1049. {
  1050. pci_host_bridge.name = "PCI Host Bridge";
  1051. pci_host_bridge.config.class = 0x06; /* bridge */
  1052. pci_host_bridge.config.subclass = 0; /* host bridge */
  1053. devices.pci[0] = &pci_host_bridge;
  1054. }
  1055. /* The IO ports used to read the PCI config space. */
  1056. #define PCI_CONFIG_ADDR 0xCF8
  1057. #define PCI_CONFIG_DATA 0xCFC
  1058. /*
  1059. * Not really portable, but does help readability: this is what the Guest
  1060. * writes to the PCI_CONFIG_ADDR IO port.
  1061. */
  1062. union pci_config_addr {
  1063. struct {
  1064. unsigned mbz: 2;
  1065. unsigned offset: 6;
  1066. unsigned funcnum: 3;
  1067. unsigned devnum: 5;
  1068. unsigned busnum: 8;
  1069. unsigned reserved: 7;
  1070. unsigned enabled : 1;
  1071. } bits;
  1072. u32 val;
  1073. };
  1074. /*
  1075. * We cache what they wrote to the address port, so we know what they're
  1076. * talking about when they access the data port.
  1077. */
  1078. static union pci_config_addr pci_config_addr;
  1079. static struct device *find_pci_device(unsigned int index)
  1080. {
  1081. return devices.pci[index];
  1082. }
  1083. /* PCI can do 1, 2 and 4 byte reads; we handle that here. */
  1084. static void ioread(u16 off, u32 v, u32 mask, u32 *val)
  1085. {
  1086. assert(off < 4);
  1087. assert(mask == 0xFF || mask == 0xFFFF || mask == 0xFFFFFFFF);
  1088. *val = (v >> (off * 8)) & mask;
  1089. }
  1090. /* PCI can do 1, 2 and 4 byte writes; we handle that here. */
  1091. static void iowrite(u16 off, u32 v, u32 mask, u32 *dst)
  1092. {
  1093. assert(off < 4);
  1094. assert(mask == 0xFF || mask == 0xFFFF || mask == 0xFFFFFFFF);
  1095. *dst &= ~(mask << (off * 8));
  1096. *dst |= (v & mask) << (off * 8);
  1097. }
  1098. /*
  1099. * Where PCI_CONFIG_DATA accesses depends on the previous write to
  1100. * PCI_CONFIG_ADDR.
  1101. */
  1102. static struct device *dev_and_reg(u32 *reg)
  1103. {
  1104. if (!pci_config_addr.bits.enabled)
  1105. return NULL;
  1106. if (pci_config_addr.bits.funcnum != 0)
  1107. return NULL;
  1108. if (pci_config_addr.bits.busnum != 0)
  1109. return NULL;
  1110. if (pci_config_addr.bits.offset * 4 >= sizeof(struct pci_config))
  1111. return NULL;
  1112. *reg = pci_config_addr.bits.offset;
  1113. return find_pci_device(pci_config_addr.bits.devnum);
  1114. }
  1115. /*
  1116. * We can get invalid combinations of values while they're writing, so we
  1117. * only fault if they try to write with some invalid bar/offset/length.
  1118. */
  1119. static bool valid_bar_access(struct device *d,
  1120. struct virtio_pci_cfg_cap_u32 *cfg_access)
  1121. {
  1122. /* We only have 1 bar (BAR0) */
  1123. if (cfg_access->cap.bar != 0)
  1124. return false;
  1125. /* Check it's within BAR0. */
  1126. if (cfg_access->cap.offset >= d->mmio_size
  1127. || cfg_access->cap.offset + cfg_access->cap.length > d->mmio_size)
  1128. return false;
  1129. /* Check length is 1, 2 or 4. */
  1130. if (cfg_access->cap.length != 1
  1131. && cfg_access->cap.length != 2
  1132. && cfg_access->cap.length != 4)
  1133. return false;
  1134. /*
  1135. * 4.1.4.7.2:
  1136. *
  1137. * The driver MUST NOT write a cap.offset which is not a multiple of
  1138. * cap.length (ie. all accesses MUST be aligned).
  1139. */
  1140. if (cfg_access->cap.offset % cfg_access->cap.length != 0)
  1141. return false;
  1142. /* Return pointer into word in BAR0. */
  1143. return true;
  1144. }
  1145. /* Is this accessing the PCI config address port?. */
  1146. static bool is_pci_addr_port(u16 port)
  1147. {
  1148. return port >= PCI_CONFIG_ADDR && port < PCI_CONFIG_ADDR + 4;
  1149. }
  1150. static bool pci_addr_iowrite(u16 port, u32 mask, u32 val)
  1151. {
  1152. iowrite(port - PCI_CONFIG_ADDR, val, mask,
  1153. &pci_config_addr.val);
  1154. verbose("PCI%s: %#x/%x: bus %u dev %u func %u reg %u\n",
  1155. pci_config_addr.bits.enabled ? "" : " DISABLED",
  1156. val, mask,
  1157. pci_config_addr.bits.busnum,
  1158. pci_config_addr.bits.devnum,
  1159. pci_config_addr.bits.funcnum,
  1160. pci_config_addr.bits.offset);
  1161. return true;
  1162. }
  1163. static void pci_addr_ioread(u16 port, u32 mask, u32 *val)
  1164. {
  1165. ioread(port - PCI_CONFIG_ADDR, pci_config_addr.val, mask, val);
  1166. }
  1167. /* Is this accessing the PCI config data port?. */
  1168. static bool is_pci_data_port(u16 port)
  1169. {
  1170. return port >= PCI_CONFIG_DATA && port < PCI_CONFIG_DATA + 4;
  1171. }
  1172. static void emulate_mmio_write(struct device *d, u32 off, u32 val, u32 mask);
  1173. static bool pci_data_iowrite(u16 port, u32 mask, u32 val)
  1174. {
  1175. u32 reg, portoff;
  1176. struct device *d = dev_and_reg(&reg);
  1177. /* Complain if they don't belong to a device. */
  1178. if (!d)
  1179. return false;
  1180. /* They can do 1 byte writes, etc. */
  1181. portoff = port - PCI_CONFIG_DATA;
  1182. /*
  1183. * PCI uses a weird way to determine the BAR size: the OS
  1184. * writes all 1's, and sees which ones stick.
  1185. */
  1186. if (&d->config_words[reg] == &d->config.bar[0]) {
  1187. int i;
  1188. iowrite(portoff, val, mask, &d->config.bar[0]);
  1189. for (i = 0; (1 << i) < d->mmio_size; i++)
  1190. d->config.bar[0] &= ~(1 << i);
  1191. return true;
  1192. } else if ((&d->config_words[reg] > &d->config.bar[0]
  1193. && &d->config_words[reg] <= &d->config.bar[6])
  1194. || &d->config_words[reg] == &d->config.expansion_rom_addr) {
  1195. /* Allow writing to any other BAR, or expansion ROM */
  1196. iowrite(portoff, val, mask, &d->config_words[reg]);
  1197. return true;
  1198. /* We let them overide latency timer and cacheline size */
  1199. } else if (&d->config_words[reg] == (void *)&d->config.cacheline_size) {
  1200. /* Only let them change the first two fields. */
  1201. if (mask == 0xFFFFFFFF)
  1202. mask = 0xFFFF;
  1203. iowrite(portoff, val, mask, &d->config_words[reg]);
  1204. return true;
  1205. } else if (&d->config_words[reg] == (void *)&d->config.command
  1206. && mask == 0xFFFF) {
  1207. /* Ignore command writes. */
  1208. return true;
  1209. } else if (&d->config_words[reg]
  1210. == (void *)&d->config.cfg_access.cap.bar
  1211. || &d->config_words[reg]
  1212. == &d->config.cfg_access.cap.length
  1213. || &d->config_words[reg]
  1214. == &d->config.cfg_access.cap.offset) {
  1215. /*
  1216. * The VIRTIO_PCI_CAP_PCI_CFG capability
  1217. * provides a backdoor to access the MMIO
  1218. * regions without mapping them. Weird, but
  1219. * useful.
  1220. */
  1221. iowrite(portoff, val, mask, &d->config_words[reg]);
  1222. return true;
  1223. } else if (&d->config_words[reg] == &d->config.cfg_access.pci_cfg_data) {
  1224. u32 write_mask;
  1225. /*
  1226. * 4.1.4.7.1:
  1227. *
  1228. * Upon detecting driver write access to pci_cfg_data, the
  1229. * device MUST execute a write access at offset cap.offset at
  1230. * BAR selected by cap.bar using the first cap.length bytes
  1231. * from pci_cfg_data.
  1232. */
  1233. /* Must be bar 0 */
  1234. if (!valid_bar_access(d, &d->config.cfg_access))
  1235. return false;
  1236. iowrite(portoff, val, mask, &d->config.cfg_access.pci_cfg_data);
  1237. /*
  1238. * Now emulate a write. The mask we use is set by
  1239. * len, *not* this write!
  1240. */
  1241. write_mask = (1ULL<<(8*d->config.cfg_access.cap.length)) - 1;
  1242. verbose("Window writing %#x/%#x to bar %u, offset %u len %u\n",
  1243. d->config.cfg_access.pci_cfg_data, write_mask,
  1244. d->config.cfg_access.cap.bar,
  1245. d->config.cfg_access.cap.offset,
  1246. d->config.cfg_access.cap.length);
  1247. emulate_mmio_write(d, d->config.cfg_access.cap.offset,
  1248. d->config.cfg_access.pci_cfg_data,
  1249. write_mask);
  1250. return true;
  1251. }
  1252. /*
  1253. * 4.1.4.1:
  1254. *
  1255. * The driver MUST NOT write into any field of the capability
  1256. * structure, with the exception of those with cap_type
  1257. * VIRTIO_PCI_CAP_PCI_CFG...
  1258. */
  1259. return false;
  1260. }
  1261. static u32 emulate_mmio_read(struct device *d, u32 off, u32 mask);
  1262. static void pci_data_ioread(u16 port, u32 mask, u32 *val)
  1263. {
  1264. u32 reg;
  1265. struct device *d = dev_and_reg(&reg);
  1266. if (!d)
  1267. return;
  1268. /* Read through the PCI MMIO access window is special */
  1269. if (&d->config_words[reg] == &d->config.cfg_access.pci_cfg_data) {
  1270. u32 read_mask;
  1271. /*
  1272. * 4.1.4.7.1:
  1273. *
  1274. * Upon detecting driver read access to pci_cfg_data, the
  1275. * device MUST execute a read access of length cap.length at
  1276. * offset cap.offset at BAR selected by cap.bar and store the
  1277. * first cap.length bytes in pci_cfg_data.
  1278. */
  1279. /* Must be bar 0 */
  1280. if (!valid_bar_access(d, &d->config.cfg_access))
  1281. bad_driver(d,
  1282. "Invalid cfg_access to bar%u, offset %u len %u",
  1283. d->config.cfg_access.cap.bar,
  1284. d->config.cfg_access.cap.offset,
  1285. d->config.cfg_access.cap.length);
  1286. /*
  1287. * Read into the window. The mask we use is set by
  1288. * len, *not* this read!
  1289. */
  1290. read_mask = (1ULL<<(8*d->config.cfg_access.cap.length))-1;
  1291. d->config.cfg_access.pci_cfg_data
  1292. = emulate_mmio_read(d,
  1293. d->config.cfg_access.cap.offset,
  1294. read_mask);
  1295. verbose("Window read %#x/%#x from bar %u, offset %u len %u\n",
  1296. d->config.cfg_access.pci_cfg_data, read_mask,
  1297. d->config.cfg_access.cap.bar,
  1298. d->config.cfg_access.cap.offset,
  1299. d->config.cfg_access.cap.length);
  1300. }
  1301. ioread(port - PCI_CONFIG_DATA, d->config_words[reg], mask, val);
  1302. }
  1303. /*L:216
  1304. * This is where we emulate a handful of Guest instructions. It's ugly
  1305. * and we used to do it in the kernel but it grew over time.
  1306. */
  1307. /*
  1308. * We use the ptrace syscall's pt_regs struct to talk about registers
  1309. * to lguest: these macros convert the names to the offsets.
  1310. */
  1311. #define getreg(name) getreg_off(offsetof(struct user_regs_struct, name))
  1312. #define setreg(name, val) \
  1313. setreg_off(offsetof(struct user_regs_struct, name), (val))
  1314. static u32 getreg_off(size_t offset)
  1315. {
  1316. u32 r;
  1317. unsigned long args[] = { LHREQ_GETREG, offset };
  1318. if (pwrite(lguest_fd, args, sizeof(args), cpu_id) < 0)
  1319. err(1, "Getting register %u", offset);
  1320. if (pread(lguest_fd, &r, sizeof(r), cpu_id) != sizeof(r))
  1321. err(1, "Reading register %u", offset);
  1322. return r;
  1323. }
  1324. static void setreg_off(size_t offset, u32 val)
  1325. {
  1326. unsigned long args[] = { LHREQ_SETREG, offset, val };
  1327. if (pwrite(lguest_fd, args, sizeof(args), cpu_id) < 0)
  1328. err(1, "Setting register %u", offset);
  1329. }
  1330. /* Get register by instruction encoding */
  1331. static u32 getreg_num(unsigned regnum, u32 mask)
  1332. {
  1333. /* 8 bit ops use regnums 4-7 for high parts of word */
  1334. if (mask == 0xFF && (regnum & 0x4))
  1335. return getreg_num(regnum & 0x3, 0xFFFF) >> 8;
  1336. switch (regnum) {
  1337. case 0: return getreg(eax) & mask;
  1338. case 1: return getreg(ecx) & mask;
  1339. case 2: return getreg(edx) & mask;
  1340. case 3: return getreg(ebx) & mask;
  1341. case 4: return getreg(esp) & mask;
  1342. case 5: return getreg(ebp) & mask;
  1343. case 6: return getreg(esi) & mask;
  1344. case 7: return getreg(edi) & mask;
  1345. }
  1346. abort();
  1347. }
  1348. /* Set register by instruction encoding */
  1349. static void setreg_num(unsigned regnum, u32 val, u32 mask)
  1350. {
  1351. /* Don't try to set bits out of range */
  1352. assert(~(val & ~mask));
  1353. /* 8 bit ops use regnums 4-7 for high parts of word */
  1354. if (mask == 0xFF && (regnum & 0x4)) {
  1355. /* Construct the 16 bits we want. */
  1356. val = (val << 8) | getreg_num(regnum & 0x3, 0xFF);
  1357. setreg_num(regnum & 0x3, val, 0xFFFF);
  1358. return;
  1359. }
  1360. switch (regnum) {
  1361. case 0: setreg(eax, val | (getreg(eax) & ~mask)); return;
  1362. case 1: setreg(ecx, val | (getreg(ecx) & ~mask)); return;
  1363. case 2: setreg(edx, val | (getreg(edx) & ~mask)); return;
  1364. case 3: setreg(ebx, val | (getreg(ebx) & ~mask)); return;
  1365. case 4: setreg(esp, val | (getreg(esp) & ~mask)); return;
  1366. case 5: setreg(ebp, val | (getreg(ebp) & ~mask)); return;
  1367. case 6: setreg(esi, val | (getreg(esi) & ~mask)); return;
  1368. case 7: setreg(edi, val | (getreg(edi) & ~mask)); return;
  1369. }
  1370. abort();
  1371. }
  1372. /* Get bytes of displacement appended to instruction, from r/m encoding */
  1373. static u32 insn_displacement_len(u8 mod_reg_rm)
  1374. {
  1375. /* Switch on the mod bits */
  1376. switch (mod_reg_rm >> 6) {
  1377. case 0:
  1378. /* If mod == 0, and r/m == 101, 16-bit displacement follows */
  1379. if ((mod_reg_rm & 0x7) == 0x5)
  1380. return 2;
  1381. /* Normally, mod == 0 means no literal displacement */
  1382. return 0;
  1383. case 1:
  1384. /* One byte displacement */
  1385. return 1;
  1386. case 2:
  1387. /* Four byte displacement */
  1388. return 4;
  1389. case 3:
  1390. /* Register mode */
  1391. return 0;
  1392. }
  1393. abort();
  1394. }
  1395. static void emulate_insn(const u8 insn[])
  1396. {
  1397. unsigned long args[] = { LHREQ_TRAP, 13 };
  1398. unsigned int insnlen = 0, in = 0, small_operand = 0, byte_access;
  1399. unsigned int eax, port, mask;
  1400. /*
  1401. * Default is to return all-ones on IO port reads, which traditionally
  1402. * means "there's nothing there".
  1403. */
  1404. u32 val = 0xFFFFFFFF;
  1405. /*
  1406. * This must be the Guest kernel trying to do something, not userspace!
  1407. * The bottom two bits of the CS segment register are the privilege
  1408. * level.
  1409. */
  1410. if ((getreg(xcs) & 3) != 0x1)
  1411. goto no_emulate;
  1412. /* Decoding x86 instructions is icky. */
  1413. /*
  1414. * Around 2.6.33, the kernel started using an emulation for the
  1415. * cmpxchg8b instruction in early boot on many configurations. This
  1416. * code isn't paravirtualized, and it tries to disable interrupts.
  1417. * Ignore it, which will Mostly Work.
  1418. */
  1419. if (insn[insnlen] == 0xfa) {
  1420. /* "cli", or Clear Interrupt Enable instruction. Skip it. */
  1421. insnlen = 1;
  1422. goto skip_insn;
  1423. }
  1424. /*
  1425. * 0x66 is an "operand prefix". It means a 16, not 32 bit in/out.
  1426. */
  1427. if (insn[insnlen] == 0x66) {
  1428. small_operand = 1;
  1429. /* The instruction is 1 byte so far, read the next byte. */
  1430. insnlen = 1;
  1431. }
  1432. /* If the lower bit isn't set, it's a single byte access */
  1433. byte_access = !(insn[insnlen] & 1);
  1434. /*
  1435. * Now we can ignore the lower bit and decode the 4 opcodes
  1436. * we need to emulate.
  1437. */
  1438. switch (insn[insnlen] & 0xFE) {
  1439. case 0xE4: /* in <next byte>,%al */
  1440. port = insn[insnlen+1];
  1441. insnlen += 2;
  1442. in = 1;
  1443. break;
  1444. case 0xEC: /* in (%dx),%al */
  1445. port = getreg(edx) & 0xFFFF;
  1446. insnlen += 1;
  1447. in = 1;
  1448. break;
  1449. case 0xE6: /* out %al,<next byte> */
  1450. port = insn[insnlen+1];
  1451. insnlen += 2;
  1452. break;
  1453. case 0xEE: /* out %al,(%dx) */
  1454. port = getreg(edx) & 0xFFFF;
  1455. insnlen += 1;
  1456. break;
  1457. default:
  1458. /* OK, we don't know what this is, can't emulate. */
  1459. goto no_emulate;
  1460. }
  1461. /* Set a mask of the 1, 2 or 4 bytes, depending on size of IO */
  1462. if (byte_access)
  1463. mask = 0xFF;
  1464. else if (small_operand)
  1465. mask = 0xFFFF;
  1466. else
  1467. mask = 0xFFFFFFFF;
  1468. /*
  1469. * If it was an "IN" instruction, they expect the result to be read
  1470. * into %eax, so we change %eax.
  1471. */
  1472. eax = getreg(eax);
  1473. if (in) {
  1474. /* This is the PS/2 keyboard status; 1 means ready for output */
  1475. if (port == 0x64)
  1476. val = 1;
  1477. else if (is_pci_addr_port(port))
  1478. pci_addr_ioread(port, mask, &val);
  1479. else if (is_pci_data_port(port))
  1480. pci_data_ioread(port, mask, &val);
  1481. /* Clear the bits we're about to read */
  1482. eax &= ~mask;
  1483. /* Copy bits in from val. */
  1484. eax |= val & mask;
  1485. /* Now update the register. */
  1486. setreg(eax, eax);
  1487. } else {
  1488. if (is_pci_addr_port(port)) {
  1489. if (!pci_addr_iowrite(port, mask, eax))
  1490. goto bad_io;
  1491. } else if (is_pci_data_port(port)) {
  1492. if (!pci_data_iowrite(port, mask, eax))
  1493. goto bad_io;
  1494. }
  1495. /* There are many other ports, eg. CMOS clock, serial
  1496. * and parallel ports, so we ignore them all. */
  1497. }
  1498. verbose("IO %s of %x to %u: %#08x\n",
  1499. in ? "IN" : "OUT", mask, port, eax);
  1500. skip_insn:
  1501. /* Finally, we've "done" the instruction, so move past it. */
  1502. setreg(eip, getreg(eip) + insnlen);
  1503. return;
  1504. bad_io:
  1505. warnx("Attempt to %s port %u (%#x mask)",
  1506. in ? "read from" : "write to", port, mask);
  1507. no_emulate:
  1508. /* Inject trap into Guest. */
  1509. if (write(lguest_fd, args, sizeof(args)) < 0)
  1510. err(1, "Reinjecting trap 13 for fault at %#x", getreg(eip));
  1511. }
  1512. static struct device *find_mmio_region(unsigned long paddr, u32 *off)
  1513. {
  1514. unsigned int i;
  1515. for (i = 1; i < MAX_PCI_DEVICES; i++) {
  1516. struct device *d = devices.pci[i];
  1517. if (!d)
  1518. continue;
  1519. if (paddr < d->mmio_addr)
  1520. continue;
  1521. if (paddr >= d->mmio_addr + d->mmio_size)
  1522. continue;
  1523. *off = paddr - d->mmio_addr;
  1524. return d;
  1525. }
  1526. return NULL;
  1527. }
  1528. /* FIXME: Use vq array. */
  1529. static struct virtqueue *vq_by_num(struct device *d, u32 num)
  1530. {
  1531. struct virtqueue *vq = d->vq;
  1532. while (num-- && vq)
  1533. vq = vq->next;
  1534. return vq;
  1535. }
  1536. static void save_vq_config(const struct virtio_pci_common_cfg *cfg,
  1537. struct virtqueue *vq)
  1538. {
  1539. vq->pci_config = *cfg;
  1540. }
  1541. static void restore_vq_config(struct virtio_pci_common_cfg *cfg,
  1542. struct virtqueue *vq)
  1543. {
  1544. /* Only restore the per-vq part */
  1545. size_t off = offsetof(struct virtio_pci_common_cfg, queue_size);
  1546. memcpy((void *)cfg + off, (void *)&vq->pci_config + off,
  1547. sizeof(*cfg) - off);
  1548. }
  1549. /*
  1550. * 4.1.4.3.2:
  1551. *
  1552. * The driver MUST configure the other virtqueue fields before
  1553. * enabling the virtqueue with queue_enable.
  1554. *
  1555. * When they enable the virtqueue, we check that their setup is valid.
  1556. */
  1557. static void check_virtqueue(struct device *d, struct virtqueue *vq)
  1558. {
  1559. /* Because lguest is 32 bit, all the descriptor high bits must be 0 */
  1560. if (vq->pci_config.queue_desc_hi
  1561. || vq->pci_config.queue_avail_hi
  1562. || vq->pci_config.queue_used_hi)
  1563. bad_driver_vq(vq, "invalid 64-bit queue address");
  1564. /*
  1565. * 2.4.1:
  1566. *
  1567. * The driver MUST ensure that the physical address of the first byte
  1568. * of each virtqueue part is a multiple of the specified alignment
  1569. * value in the above table.
  1570. */
  1571. if (vq->pci_config.queue_desc_lo % 16
  1572. || vq->pci_config.queue_avail_lo % 2
  1573. || vq->pci_config.queue_used_lo % 4)
  1574. bad_driver_vq(vq, "invalid alignment in queue addresses");
  1575. /* Initialize the virtqueue and check they're all in range. */
  1576. vq->vring.num = vq->pci_config.queue_size;
  1577. vq->vring.desc = check_pointer(vq->dev,
  1578. vq->pci_config.queue_desc_lo,
  1579. sizeof(*vq->vring.desc) * vq->vring.num);
  1580. vq->vring.avail = check_pointer(vq->dev,
  1581. vq->pci_config.queue_avail_lo,
  1582. sizeof(*vq->vring.avail)
  1583. + (sizeof(vq->vring.avail->ring[0])
  1584. * vq->vring.num));
  1585. vq->vring.used = check_pointer(vq->dev,
  1586. vq->pci_config.queue_used_lo,
  1587. sizeof(*vq->vring.used)
  1588. + (sizeof(vq->vring.used->ring[0])
  1589. * vq->vring.num));
  1590. /*
  1591. * 2.4.9.1:
  1592. *
  1593. * The driver MUST initialize flags in the used ring to 0
  1594. * when allocating the used ring.
  1595. */
  1596. if (vq->vring.used->flags != 0)
  1597. bad_driver_vq(vq, "invalid initial used.flags %#x",
  1598. vq->vring.used->flags);
  1599. }
  1600. static void start_virtqueue(struct virtqueue *vq)
  1601. {
  1602. /*
  1603. * Create stack for thread. Since the stack grows upwards, we point
  1604. * the stack pointer to the end of this region.
  1605. */
  1606. char *stack = malloc(32768);
  1607. /* Create a zero-initialized eventfd. */
  1608. vq->eventfd = eventfd(0, 0);
  1609. if (vq->eventfd < 0)
  1610. err(1, "Creating eventfd");
  1611. /*
  1612. * CLONE_VM: because it has to access the Guest memory, and SIGCHLD so
  1613. * we get a signal if it dies.
  1614. */
  1615. vq->thread = clone(do_thread, stack + 32768, CLONE_VM | SIGCHLD, vq);
  1616. if (vq->thread == (pid_t)-1)
  1617. err(1, "Creating clone");
  1618. }
  1619. static void start_virtqueues(struct device *d)
  1620. {
  1621. struct virtqueue *vq;
  1622. for (vq = d->vq; vq; vq = vq->next) {
  1623. if (vq->pci_config.queue_enable)
  1624. start_virtqueue(vq);
  1625. }
  1626. }
  1627. static void emulate_mmio_write(struct device *d, u32 off, u32 val, u32 mask)
  1628. {
  1629. struct virtqueue *vq;
  1630. switch (off) {
  1631. case offsetof(struct virtio_pci_mmio, cfg.device_feature_select):
  1632. /*
  1633. * 4.1.4.3.1:
  1634. *
  1635. * The device MUST present the feature bits it is offering in
  1636. * device_feature, starting at bit device_feature_select ∗ 32
  1637. * for any device_feature_select written by the driver
  1638. */
  1639. if (val == 0)
  1640. d->mmio->cfg.device_feature = d->features;
  1641. else if (val == 1)
  1642. d->mmio->cfg.device_feature = (d->features >> 32);
  1643. else
  1644. d->mmio->cfg.device_feature = 0;
  1645. goto feature_write_through32;
  1646. case offsetof(struct virtio_pci_mmio, cfg.guest_feature_select):
  1647. if (val > 1)
  1648. bad_driver(d, "Unexpected driver select %u", val);
  1649. goto feature_write_through32;
  1650. case offsetof(struct virtio_pci_mmio, cfg.guest_feature):
  1651. if (d->mmio->cfg.guest_feature_select == 0) {
  1652. d->features_accepted &= ~((u64)0xFFFFFFFF);
  1653. d->features_accepted |= val;
  1654. } else {
  1655. assert(d->mmio->cfg.guest_feature_select == 1);
  1656. d->features_accepted &= 0xFFFFFFFF;
  1657. d->features_accepted |= ((u64)val) << 32;
  1658. }
  1659. /*
  1660. * 2.2.1:
  1661. *
  1662. * The driver MUST NOT accept a feature which the device did
  1663. * not offer
  1664. */
  1665. if (d->features_accepted & ~d->features)
  1666. bad_driver(d, "over-accepted features %#llx of %#llx",
  1667. d->features_accepted, d->features);
  1668. goto feature_write_through32;
  1669. case offsetof(struct virtio_pci_mmio, cfg.device_status): {
  1670. u8 prev;
  1671. verbose("%s: device status -> %#x\n", d->name, val);
  1672. /*
  1673. * 4.1.4.3.1:
  1674. *
  1675. * The device MUST reset when 0 is written to device_status,
  1676. * and present a 0 in device_status once that is done.
  1677. */
  1678. if (val == 0) {
  1679. reset_device(d);
  1680. goto write_through8;
  1681. }
  1682. /* 2.1.1: The driver MUST NOT clear a device status bit. */
  1683. if (d->mmio->cfg.device_status & ~val)
  1684. bad_driver(d, "unset of device status bit %#x -> %#x",
  1685. d->mmio->cfg.device_status, val);
  1686. /*
  1687. * 2.1.2:
  1688. *
  1689. * The device MUST NOT consume buffers or notify the driver
  1690. * before DRIVER_OK.
  1691. */
  1692. if (val & VIRTIO_CONFIG_S_DRIVER_OK
  1693. && !(d->mmio->cfg.device_status & VIRTIO_CONFIG_S_DRIVER_OK))
  1694. start_virtqueues(d);
  1695. /*
  1696. * 3.1.1:
  1697. *
  1698. * The driver MUST follow this sequence to initialize a device:
  1699. * - Reset the device.
  1700. * - Set the ACKNOWLEDGE status bit: the guest OS has
  1701. * notice the device.
  1702. * - Set the DRIVER status bit: the guest OS knows how
  1703. * to drive the device.
  1704. * - Read device feature bits, and write the subset
  1705. * of feature bits understood by the OS and driver
  1706. * to the device. During this step the driver MAY
  1707. * read (but MUST NOT write) the device-specific
  1708. * configuration fields to check that it can
  1709. * support the device before accepting it.
  1710. * - Set the FEATURES_OK status bit. The driver
  1711. * MUST not accept new feature bits after this
  1712. * step.
  1713. * - Re-read device status to ensure the FEATURES_OK
  1714. * bit is still set: otherwise, the device does
  1715. * not support our subset of features and the
  1716. * device is unusable.
  1717. * - Perform device-specific setup, including
  1718. * discovery of virtqueues for the device,
  1719. * optional per-bus setup, reading and possibly
  1720. * writing the device’s virtio configuration
  1721. * space, and population of virtqueues.
  1722. * - Set the DRIVER_OK status bit. At this point the
  1723. * device is “live”.
  1724. */
  1725. prev = 0;
  1726. switch (val & ~d->mmio->cfg.device_status) {
  1727. case VIRTIO_CONFIG_S_DRIVER_OK:
  1728. prev |= VIRTIO_CONFIG_S_FEATURES_OK; /* fall thru */
  1729. case VIRTIO_CONFIG_S_FEATURES_OK:
  1730. prev |= VIRTIO_CONFIG_S_DRIVER; /* fall thru */
  1731. case VIRTIO_CONFIG_S_DRIVER:
  1732. prev |= VIRTIO_CONFIG_S_ACKNOWLEDGE; /* fall thru */
  1733. case VIRTIO_CONFIG_S_ACKNOWLEDGE:
  1734. break;
  1735. default:
  1736. bad_driver(d, "unknown device status bit %#x -> %#x",
  1737. d->mmio->cfg.device_status, val);
  1738. }
  1739. if (d->mmio->cfg.device_status != prev)
  1740. bad_driver(d, "unexpected status transition %#x -> %#x",
  1741. d->mmio->cfg.device_status, val);
  1742. /* If they just wrote FEATURES_OK, we make sure they read */
  1743. switch (val & ~d->mmio->cfg.device_status) {
  1744. case VIRTIO_CONFIG_S_FEATURES_OK:
  1745. d->wrote_features_ok = true;
  1746. break;
  1747. case VIRTIO_CONFIG_S_DRIVER_OK:
  1748. if (d->wrote_features_ok)
  1749. bad_driver(d, "did not re-read FEATURES_OK");
  1750. break;
  1751. }
  1752. goto write_through8;
  1753. }
  1754. case offsetof(struct virtio_pci_mmio, cfg.queue_select):
  1755. vq = vq_by_num(d, val);
  1756. /*
  1757. * 4.1.4.3.1:
  1758. *
  1759. * The device MUST present a 0 in queue_size if the virtqueue
  1760. * corresponding to the current queue_select is unavailable.
  1761. */
  1762. if (!vq) {
  1763. d->mmio->cfg.queue_size = 0;
  1764. goto write_through16;
  1765. }
  1766. /* Save registers for old vq, if it was a valid vq */
  1767. if (d->mmio->cfg.queue_size)
  1768. save_vq_config(&d->mmio->cfg,
  1769. vq_by_num(d, d->mmio->cfg.queue_select));
  1770. /* Restore the registers for the queue they asked for */
  1771. restore_vq_config(&d->mmio->cfg, vq);
  1772. goto write_through16;
  1773. case offsetof(struct virtio_pci_mmio, cfg.queue_size):
  1774. /*
  1775. * 4.1.4.3.2:
  1776. *
  1777. * The driver MUST NOT write a value which is not a power of 2
  1778. * to queue_size.
  1779. */
  1780. if (val & (val-1))
  1781. bad_driver(d, "invalid queue size %u", val);
  1782. if (d->mmio->cfg.queue_enable)
  1783. bad_driver(d, "changing queue size on live device");
  1784. goto write_through16;
  1785. case offsetof(struct virtio_pci_mmio, cfg.queue_msix_vector):
  1786. bad_driver(d, "attempt to set MSIX vector to %u", val);
  1787. case offsetof(struct virtio_pci_mmio, cfg.queue_enable): {
  1788. struct virtqueue *vq = vq_by_num(d, d->mmio->cfg.queue_select);
  1789. /*
  1790. * 4.1.4.3.2:
  1791. *
  1792. * The driver MUST NOT write a 0 to queue_enable.
  1793. */
  1794. if (val != 1)
  1795. bad_driver(d, "setting queue_enable to %u", val);
  1796. /*
  1797. * 3.1.1:
  1798. *
  1799. * 7. Perform device-specific setup, including discovery of
  1800. * virtqueues for the device, optional per-bus setup,
  1801. * reading and possibly writing the device’s virtio
  1802. * configuration space, and population of virtqueues.
  1803. * 8. Set the DRIVER_OK status bit.
  1804. *
  1805. * All our devices require all virtqueues to be enabled, so
  1806. * they should have done that before setting DRIVER_OK.
  1807. */
  1808. if (d->mmio->cfg.device_status & VIRTIO_CONFIG_S_DRIVER_OK)
  1809. bad_driver(d, "enabling vq after DRIVER_OK");
  1810. d->mmio->cfg.queue_enable = val;
  1811. save_vq_config(&d->mmio->cfg, vq);
  1812. check_virtqueue(d, vq);
  1813. goto write_through16;
  1814. }
  1815. case offsetof(struct virtio_pci_mmio, cfg.queue_notify_off):
  1816. bad_driver(d, "attempt to write to queue_notify_off");
  1817. case offsetof(struct virtio_pci_mmio, cfg.queue_desc_lo):
  1818. case offsetof(struct virtio_pci_mmio, cfg.queue_desc_hi):
  1819. case offsetof(struct virtio_pci_mmio, cfg.queue_avail_lo):
  1820. case offsetof(struct virtio_pci_mmio, cfg.queue_avail_hi):
  1821. case offsetof(struct virtio_pci_mmio, cfg.queue_used_lo):
  1822. case offsetof(struct virtio_pci_mmio, cfg.queue_used_hi):
  1823. /*
  1824. * 4.1.4.3.2:
  1825. *
  1826. * The driver MUST configure the other virtqueue fields before
  1827. * enabling the virtqueue with queue_enable.
  1828. */
  1829. if (d->mmio->cfg.queue_enable)
  1830. bad_driver(d, "changing queue on live device");
  1831. /*
  1832. * 3.1.1:
  1833. *
  1834. * The driver MUST follow this sequence to initialize a device:
  1835. *...
  1836. * 5. Set the FEATURES_OK status bit. The driver MUST not
  1837. * accept new feature bits after this step.
  1838. */
  1839. if (!(d->mmio->cfg.device_status & VIRTIO_CONFIG_S_FEATURES_OK))
  1840. bad_driver(d, "setting up vq before FEATURES_OK");
  1841. /*
  1842. * 6. Re-read device status to ensure the FEATURES_OK bit is
  1843. * still set...
  1844. */
  1845. if (d->wrote_features_ok)
  1846. bad_driver(d, "didn't re-read FEATURES_OK before setup");
  1847. goto write_through32;
  1848. case offsetof(struct virtio_pci_mmio, notify):
  1849. vq = vq_by_num(d, val);
  1850. if (!vq)
  1851. bad_driver(d, "Invalid vq notification on %u", val);
  1852. /* Notify the process handling this vq by adding 1 to eventfd */
  1853. write(vq->eventfd, "\1\0\0\0\0\0\0\0", 8);
  1854. goto write_through16;
  1855. case offsetof(struct virtio_pci_mmio, isr):
  1856. bad_driver(d, "Unexpected write to isr");
  1857. /* Weird corner case: write to emerg_wr of console */
  1858. case sizeof(struct virtio_pci_mmio)
  1859. + offsetof(struct virtio_console_config, emerg_wr):
  1860. if (strcmp(d->name, "console") == 0) {
  1861. char c = val;
  1862. write(STDOUT_FILENO, &c, 1);
  1863. goto write_through32;
  1864. }
  1865. /* Fall through... */
  1866. default:
  1867. /*
  1868. * 4.1.4.3.2:
  1869. *
  1870. * The driver MUST NOT write to device_feature, num_queues,
  1871. * config_generation or queue_notify_off.
  1872. */
  1873. bad_driver(d, "Unexpected write to offset %u", off);
  1874. }
  1875. feature_write_through32:
  1876. /*
  1877. * 3.1.1:
  1878. *
  1879. * The driver MUST follow this sequence to initialize a device:
  1880. *...
  1881. * - Set the DRIVER status bit: the guest OS knows how
  1882. * to drive the device.
  1883. * - Read device feature bits, and write the subset
  1884. * of feature bits understood by the OS and driver
  1885. * to the device.
  1886. *...
  1887. * - Set the FEATURES_OK status bit. The driver MUST not
  1888. * accept new feature bits after this step.
  1889. */
  1890. if (!(d->mmio->cfg.device_status & VIRTIO_CONFIG_S_DRIVER))
  1891. bad_driver(d, "feature write before VIRTIO_CONFIG_S_DRIVER");
  1892. if (d->mmio->cfg.device_status & VIRTIO_CONFIG_S_FEATURES_OK)
  1893. bad_driver(d, "feature write after VIRTIO_CONFIG_S_FEATURES_OK");
  1894. /*
  1895. * 4.1.3.1:
  1896. *
  1897. * The driver MUST access each field using the “natural” access
  1898. * method, i.e. 32-bit accesses for 32-bit fields, 16-bit accesses for
  1899. * 16-bit fields and 8-bit accesses for 8-bit fields.
  1900. */
  1901. write_through32:
  1902. if (mask != 0xFFFFFFFF) {
  1903. bad_driver(d, "non-32-bit write to offset %u (%#x)",
  1904. off, getreg(eip));
  1905. return;
  1906. }
  1907. memcpy((char *)d->mmio + off, &val, 4);
  1908. return;
  1909. write_through16:
  1910. if (mask != 0xFFFF)
  1911. bad_driver(d, "non-16-bit write to offset %u (%#x)",
  1912. off, getreg(eip));
  1913. memcpy((char *)d->mmio + off, &val, 2);
  1914. return;
  1915. write_through8:
  1916. if (mask != 0xFF)
  1917. bad_driver(d, "non-8-bit write to offset %u (%#x)",
  1918. off, getreg(eip));
  1919. memcpy((char *)d->mmio + off, &val, 1);
  1920. return;
  1921. }
  1922. static u32 emulate_mmio_read(struct device *d, u32 off, u32 mask)
  1923. {
  1924. u8 isr;
  1925. u32 val = 0;
  1926. switch (off) {
  1927. case offsetof(struct virtio_pci_mmio, cfg.device_feature_select):
  1928. case offsetof(struct virtio_pci_mmio, cfg.device_feature):
  1929. case offsetof(struct virtio_pci_mmio, cfg.guest_feature_select):
  1930. case offsetof(struct virtio_pci_mmio, cfg.guest_feature):
  1931. /*
  1932. * 3.1.1:
  1933. *
  1934. * The driver MUST follow this sequence to initialize a device:
  1935. *...
  1936. * - Set the DRIVER status bit: the guest OS knows how
  1937. * to drive the device.
  1938. * - Read device feature bits, and write the subset
  1939. * of feature bits understood by the OS and driver
  1940. * to the device.
  1941. */
  1942. if (!(d->mmio->cfg.device_status & VIRTIO_CONFIG_S_DRIVER))
  1943. bad_driver(d,
  1944. "feature read before VIRTIO_CONFIG_S_DRIVER");
  1945. goto read_through32;
  1946. case offsetof(struct virtio_pci_mmio, cfg.msix_config):
  1947. bad_driver(d, "read of msix_config");
  1948. case offsetof(struct virtio_pci_mmio, cfg.num_queues):
  1949. goto read_through16;
  1950. case offsetof(struct virtio_pci_mmio, cfg.device_status):
  1951. /* As they did read, any write of FEATURES_OK is now fine. */
  1952. d->wrote_features_ok = false;
  1953. goto read_through8;
  1954. case offsetof(struct virtio_pci_mmio, cfg.config_generation):
  1955. /*
  1956. * 4.1.4.3.1:
  1957. *
  1958. * The device MUST present a changed config_generation after
  1959. * the driver has read a device-specific configuration value
  1960. * which has changed since any part of the device-specific
  1961. * configuration was last read.
  1962. *
  1963. * This is simple: none of our devices change config, so this
  1964. * is always 0.
  1965. */
  1966. goto read_through8;
  1967. case offsetof(struct virtio_pci_mmio, notify):
  1968. /*
  1969. * 3.1.1:
  1970. *
  1971. * The driver MUST NOT notify the device before setting
  1972. * DRIVER_OK.
  1973. */
  1974. if (!(d->mmio->cfg.device_status & VIRTIO_CONFIG_S_DRIVER_OK))
  1975. bad_driver(d, "notify before VIRTIO_CONFIG_S_DRIVER_OK");
  1976. goto read_through16;
  1977. case offsetof(struct virtio_pci_mmio, isr):
  1978. if (mask != 0xFF)
  1979. bad_driver(d, "non-8-bit read from offset %u (%#x)",
  1980. off, getreg(eip));
  1981. isr = d->mmio->isr;
  1982. /*
  1983. * 4.1.4.5.1:
  1984. *
  1985. * The device MUST reset ISR status to 0 on driver read.
  1986. */
  1987. d->mmio->isr = 0;
  1988. return isr;
  1989. case offsetof(struct virtio_pci_mmio, padding):
  1990. bad_driver(d, "read from padding (%#x)", getreg(eip));
  1991. default:
  1992. /* Read from device config space, beware unaligned overflow */
  1993. if (off > d->mmio_size - 4)
  1994. bad_driver(d, "read past end (%#x)", getreg(eip));
  1995. /*
  1996. * 3.1.1:
  1997. * The driver MUST follow this sequence to initialize a device:
  1998. *...
  1999. * 3. Set the DRIVER status bit: the guest OS knows how to
  2000. * drive the device.
  2001. * 4. Read device feature bits, and write the subset of
  2002. * feature bits understood by the OS and driver to the
  2003. * device. During this step the driver MAY read (but MUST NOT
  2004. * write) the device-specific configuration fields to check
  2005. * that it can support the device before accepting it.
  2006. */
  2007. if (!(d->mmio->cfg.device_status & VIRTIO_CONFIG_S_DRIVER))
  2008. bad_driver(d,
  2009. "config read before VIRTIO_CONFIG_S_DRIVER");
  2010. if (mask == 0xFFFFFFFF)
  2011. goto read_through32;
  2012. else if (mask == 0xFFFF)
  2013. goto read_through16;
  2014. else
  2015. goto read_through8;
  2016. }
  2017. /*
  2018. * 4.1.3.1:
  2019. *
  2020. * The driver MUST access each field using the “natural” access
  2021. * method, i.e. 32-bit accesses for 32-bit fields, 16-bit accesses for
  2022. * 16-bit fields and 8-bit accesses for 8-bit fields.
  2023. */
  2024. read_through32:
  2025. if (mask != 0xFFFFFFFF)
  2026. bad_driver(d, "non-32-bit read to offset %u (%#x)",
  2027. off, getreg(eip));
  2028. memcpy(&val, (char *)d->mmio + off, 4);
  2029. return val;
  2030. read_through16:
  2031. if (mask != 0xFFFF)
  2032. bad_driver(d, "non-16-bit read to offset %u (%#x)",
  2033. off, getreg(eip));
  2034. memcpy(&val, (char *)d->mmio + off, 2);
  2035. return val;
  2036. read_through8:
  2037. if (mask != 0xFF)
  2038. bad_driver(d, "non-8-bit read to offset %u (%#x)",
  2039. off, getreg(eip));
  2040. memcpy(&val, (char *)d->mmio + off, 1);
  2041. return val;
  2042. }
  2043. static void emulate_mmio(unsigned long paddr, const u8 *insn)
  2044. {
  2045. u32 val, off, mask = 0xFFFFFFFF, insnlen = 0;
  2046. struct device *d = find_mmio_region(paddr, &off);
  2047. unsigned long args[] = { LHREQ_TRAP, 14 };
  2048. if (!d) {
  2049. warnx("MMIO touching %#08lx (not a device)", paddr);
  2050. goto reinject;
  2051. }
  2052. /* Prefix makes it a 16 bit op */
  2053. if (insn[0] == 0x66) {
  2054. mask = 0xFFFF;
  2055. insnlen++;
  2056. }
  2057. /* iowrite */
  2058. if (insn[insnlen] == 0x89) {
  2059. /* Next byte is r/m byte: bits 3-5 are register. */
  2060. val = getreg_num((insn[insnlen+1] >> 3) & 0x7, mask);
  2061. emulate_mmio_write(d, off, val, mask);
  2062. insnlen += 2 + insn_displacement_len(insn[insnlen+1]);
  2063. } else if (insn[insnlen] == 0x8b) { /* ioread */
  2064. /* Next byte is r/m byte: bits 3-5 are register. */
  2065. val = emulate_mmio_read(d, off, mask);
  2066. setreg_num((insn[insnlen+1] >> 3) & 0x7, val, mask);
  2067. insnlen += 2 + insn_displacement_len(insn[insnlen+1]);
  2068. } else if (insn[0] == 0x88) { /* 8-bit iowrite */
  2069. mask = 0xff;
  2070. /* Next byte is r/m byte: bits 3-5 are register. */
  2071. val = getreg_num((insn[1] >> 3) & 0x7, mask);
  2072. emulate_mmio_write(d, off, val, mask);
  2073. insnlen = 2 + insn_displacement_len(insn[1]);
  2074. } else if (insn[0] == 0x8a) { /* 8-bit ioread */
  2075. mask = 0xff;
  2076. val = emulate_mmio_read(d, off, mask);
  2077. setreg_num((insn[1] >> 3) & 0x7, val, mask);
  2078. insnlen = 2 + insn_displacement_len(insn[1]);
  2079. } else {
  2080. warnx("Unknown MMIO instruction touching %#08lx:"
  2081. " %02x %02x %02x %02x at %u",
  2082. paddr, insn[0], insn[1], insn[2], insn[3], getreg(eip));
  2083. reinject:
  2084. /* Inject trap into Guest. */
  2085. if (write(lguest_fd, args, sizeof(args)) < 0)
  2086. err(1, "Reinjecting trap 14 for fault at %#x",
  2087. getreg(eip));
  2088. return;
  2089. }
  2090. /* Finally, we've "done" the instruction, so move past it. */
  2091. setreg(eip, getreg(eip) + insnlen);
  2092. }
  2093. /*L:190
  2094. * Device Setup
  2095. *
  2096. * All devices need a descriptor so the Guest knows it exists, and a "struct
  2097. * device" so the Launcher can keep track of it. We have common helper
  2098. * routines to allocate and manage them.
  2099. */
  2100. static void add_pci_virtqueue(struct device *dev,
  2101. void (*service)(struct virtqueue *),
  2102. const char *name)
  2103. {
  2104. struct virtqueue **i, *vq = malloc(sizeof(*vq));
  2105. /* Initialize the virtqueue */
  2106. vq->next = NULL;
  2107. vq->last_avail_idx = 0;
  2108. vq->dev = dev;
  2109. vq->name = name;
  2110. /*
  2111. * This is the routine the service thread will run, and its Process ID
  2112. * once it's running.
  2113. */
  2114. vq->service = service;
  2115. vq->thread = (pid_t)-1;
  2116. /* Initialize the configuration. */
  2117. reset_vq_pci_config(vq);
  2118. vq->pci_config.queue_notify_off = 0;
  2119. /* Add one to the number of queues */
  2120. vq->dev->mmio->cfg.num_queues++;
  2121. /*
  2122. * Add to tail of list, so dev->vq is first vq, dev->vq->next is
  2123. * second.
  2124. */
  2125. for (i = &dev->vq; *i; i = &(*i)->next);
  2126. *i = vq;
  2127. }
  2128. /* The Guest accesses the feature bits via the PCI common config MMIO region */
  2129. static void add_pci_feature(struct device *dev, unsigned bit)
  2130. {
  2131. dev->features |= (1ULL << bit);
  2132. }
  2133. /* For devices with no config. */
  2134. static void no_device_config(struct device *dev)
  2135. {
  2136. dev->mmio_addr = get_mmio_region(dev->mmio_size);
  2137. dev->config.bar[0] = dev->mmio_addr;
  2138. /* Bottom 4 bits must be zero */
  2139. assert(~(dev->config.bar[0] & 0xF));
  2140. }
  2141. /* This puts the device config into BAR0 */
  2142. static void set_device_config(struct device *dev, const void *conf, size_t len)
  2143. {
  2144. /* Set up BAR 0 */
  2145. dev->mmio_size += len;
  2146. dev->mmio = realloc(dev->mmio, dev->mmio_size);
  2147. memcpy(dev->mmio + 1, conf, len);
  2148. /*
  2149. * 4.1.4.6:
  2150. *
  2151. * The device MUST present at least one VIRTIO_PCI_CAP_DEVICE_CFG
  2152. * capability for any device type which has a device-specific
  2153. * configuration.
  2154. */
  2155. /* Hook up device cfg */
  2156. dev->config.cfg_access.cap.cap_next
  2157. = offsetof(struct pci_config, device);
  2158. /*
  2159. * 4.1.4.6.1:
  2160. *
  2161. * The offset for the device-specific configuration MUST be 4-byte
  2162. * aligned.
  2163. */
  2164. assert(dev->config.cfg_access.cap.cap_next % 4 == 0);
  2165. /* Fix up device cfg field length. */
  2166. dev->config.device.length = len;
  2167. /* The rest is the same as the no-config case */
  2168. no_device_config(dev);
  2169. }
  2170. static void init_cap(struct virtio_pci_cap *cap, size_t caplen, int type,
  2171. size_t bar_offset, size_t bar_bytes, u8 next)
  2172. {
  2173. cap->cap_vndr = PCI_CAP_ID_VNDR;
  2174. cap->cap_next = next;
  2175. cap->cap_len = caplen;
  2176. cap->cfg_type = type;
  2177. cap->bar = 0;
  2178. memset(cap->padding, 0, sizeof(cap->padding));
  2179. cap->offset = bar_offset;
  2180. cap->length = bar_bytes;
  2181. }
  2182. /*
  2183. * This sets up the pci_config structure, as defined in the virtio 1.0
  2184. * standard (and PCI standard).
  2185. */
  2186. static void init_pci_config(struct pci_config *pci, u16 type,
  2187. u8 class, u8 subclass)
  2188. {
  2189. size_t bar_offset, bar_len;
  2190. /*
  2191. * 4.1.4.4.1:
  2192. *
  2193. * The device MUST either present notify_off_multiplier as an even
  2194. * power of 2, or present notify_off_multiplier as 0.
  2195. *
  2196. * 2.1.2:
  2197. *
  2198. * The device MUST initialize device status to 0 upon reset.
  2199. */
  2200. memset(pci, 0, sizeof(*pci));
  2201. /* 4.1.2.1: Devices MUST have the PCI Vendor ID 0x1AF4 */
  2202. pci->vendor_id = 0x1AF4;
  2203. /* 4.1.2.1: ... PCI Device ID calculated by adding 0x1040 ... */
  2204. pci->device_id = 0x1040 + type;
  2205. /*
  2206. * PCI have specific codes for different types of devices.
  2207. * Linux doesn't care, but it's a good clue for people looking
  2208. * at the device.
  2209. */
  2210. pci->class = class;
  2211. pci->subclass = subclass;
  2212. /*
  2213. * 4.1.2.1:
  2214. *
  2215. * Non-transitional devices SHOULD have a PCI Revision ID of 1 or
  2216. * higher
  2217. */
  2218. pci->revid = 1;
  2219. /*
  2220. * 4.1.2.1:
  2221. *
  2222. * Non-transitional devices SHOULD have a PCI Subsystem Device ID of
  2223. * 0x40 or higher.
  2224. */
  2225. pci->subsystem_device_id = 0x40;
  2226. /* We use our dummy interrupt controller, and irq_line is the irq */
  2227. pci->irq_line = devices.next_irq++;
  2228. pci->irq_pin = 0;
  2229. /* Support for extended capabilities. */
  2230. pci->status = (1 << 4);
  2231. /* Link them in. */
  2232. /*
  2233. * 4.1.4.3.1:
  2234. *
  2235. * The device MUST present at least one common configuration
  2236. * capability.
  2237. */
  2238. pci->capabilities = offsetof(struct pci_config, common);
  2239. /* 4.1.4.3.1 ... offset MUST be 4-byte aligned. */
  2240. assert(pci->capabilities % 4 == 0);
  2241. bar_offset = offsetof(struct virtio_pci_mmio, cfg);
  2242. bar_len = sizeof(((struct virtio_pci_mmio *)0)->cfg);
  2243. init_cap(&pci->common, sizeof(pci->common), VIRTIO_PCI_CAP_COMMON_CFG,
  2244. bar_offset, bar_len,
  2245. offsetof(struct pci_config, notify));
  2246. /*
  2247. * 4.1.4.4.1:
  2248. *
  2249. * The device MUST present at least one notification capability.
  2250. */
  2251. bar_offset += bar_len;
  2252. bar_len = sizeof(((struct virtio_pci_mmio *)0)->notify);
  2253. /*
  2254. * 4.1.4.4.1:
  2255. *
  2256. * The cap.offset MUST be 2-byte aligned.
  2257. */
  2258. assert(pci->common.cap_next % 2 == 0);
  2259. /* FIXME: Use a non-zero notify_off, for per-queue notification? */
  2260. /*
  2261. * 4.1.4.4.1:
  2262. *
  2263. * The value cap.length presented by the device MUST be at least 2 and
  2264. * MUST be large enough to support queue notification offsets for all
  2265. * supported queues in all possible configurations.
  2266. */
  2267. assert(bar_len >= 2);
  2268. init_cap(&pci->notify.cap, sizeof(pci->notify),
  2269. VIRTIO_PCI_CAP_NOTIFY_CFG,
  2270. bar_offset, bar_len,
  2271. offsetof(struct pci_config, isr));
  2272. bar_offset += bar_len;
  2273. bar_len = sizeof(((struct virtio_pci_mmio *)0)->isr);
  2274. /*
  2275. * 4.1.4.5.1:
  2276. *
  2277. * The device MUST present at least one VIRTIO_PCI_CAP_ISR_CFG
  2278. * capability.
  2279. */
  2280. init_cap(&pci->isr, sizeof(pci->isr),
  2281. VIRTIO_PCI_CAP_ISR_CFG,
  2282. bar_offset, bar_len,
  2283. offsetof(struct pci_config, cfg_access));
  2284. /*
  2285. * 4.1.4.7.1:
  2286. *
  2287. * The device MUST present at least one VIRTIO_PCI_CAP_PCI_CFG
  2288. * capability.
  2289. */
  2290. /* This doesn't have any presence in the BAR */
  2291. init_cap(&pci->cfg_access.cap, sizeof(pci->cfg_access),
  2292. VIRTIO_PCI_CAP_PCI_CFG,
  2293. 0, 0, 0);
  2294. bar_offset += bar_len + sizeof(((struct virtio_pci_mmio *)0)->padding);
  2295. assert(bar_offset == sizeof(struct virtio_pci_mmio));
  2296. /*
  2297. * This gets sewn in and length set in set_device_config().
  2298. * Some devices don't have a device configuration interface, so
  2299. * we never expose this if we don't call set_device_config().
  2300. */
  2301. init_cap(&pci->device, sizeof(pci->device), VIRTIO_PCI_CAP_DEVICE_CFG,
  2302. bar_offset, 0, 0);
  2303. }
  2304. /*
  2305. * This routine does all the creation and setup of a new device, but we don't
  2306. * actually place the MMIO region until we know the size (if any) of the
  2307. * device-specific config. And we don't actually start the service threads
  2308. * until later.
  2309. *
  2310. * See what I mean about userspace being boring?
  2311. */
  2312. static struct device *new_pci_device(const char *name, u16 type,
  2313. u8 class, u8 subclass)
  2314. {
  2315. struct device *dev = malloc(sizeof(*dev));
  2316. /* Now we populate the fields one at a time. */
  2317. dev->name = name;
  2318. dev->vq = NULL;
  2319. dev->running = false;
  2320. dev->wrote_features_ok = false;
  2321. dev->mmio_size = sizeof(struct virtio_pci_mmio);
  2322. dev->mmio = calloc(1, dev->mmio_size);
  2323. dev->features = (u64)1 << VIRTIO_F_VERSION_1;
  2324. dev->features_accepted = 0;
  2325. if (devices.device_num + 1 >= MAX_PCI_DEVICES)
  2326. errx(1, "Can only handle 31 PCI devices");
  2327. init_pci_config(&dev->config, type, class, subclass);
  2328. assert(!devices.pci[devices.device_num+1]);
  2329. devices.pci[++devices.device_num] = dev;
  2330. return dev;
  2331. }
  2332. /*
  2333. * Our first setup routine is the console. It's a fairly simple device, but
  2334. * UNIX tty handling makes it uglier than it could be.
  2335. */
  2336. static void setup_console(void)
  2337. {
  2338. struct device *dev;
  2339. struct virtio_console_config conf;
  2340. /* If we can save the initial standard input settings... */
  2341. if (tcgetattr(STDIN_FILENO, &orig_term) == 0) {
  2342. struct termios term = orig_term;
  2343. /*
  2344. * Then we turn off echo, line buffering and ^C etc: We want a
  2345. * raw input stream to the Guest.
  2346. */
  2347. term.c_lflag &= ~(ISIG|ICANON|ECHO);
  2348. tcsetattr(STDIN_FILENO, TCSANOW, &term);
  2349. }
  2350. dev = new_pci_device("console", VIRTIO_ID_CONSOLE, 0x07, 0x00);
  2351. /* We store the console state in dev->priv, and initialize it. */
  2352. dev->priv = malloc(sizeof(struct console_abort));
  2353. ((struct console_abort *)dev->priv)->count = 0;
  2354. /*
  2355. * The console needs two virtqueues: the input then the output. When
  2356. * they put something the input queue, we make sure we're listening to
  2357. * stdin. When they put something in the output queue, we write it to
  2358. * stdout.
  2359. */
  2360. add_pci_virtqueue(dev, console_input, "input");
  2361. add_pci_virtqueue(dev, console_output, "output");
  2362. /* We need a configuration area for the emerg_wr early writes. */
  2363. add_pci_feature(dev, VIRTIO_CONSOLE_F_EMERG_WRITE);
  2364. set_device_config(dev, &conf, sizeof(conf));
  2365. verbose("device %u: console\n", devices.device_num);
  2366. }
  2367. /*:*/
  2368. /*M:010
  2369. * Inter-guest networking is an interesting area. Simplest is to have a
  2370. * --sharenet=<name> option which opens or creates a named pipe. This can be
  2371. * used to send packets to another guest in a 1:1 manner.
  2372. *
  2373. * More sophisticated is to use one of the tools developed for project like UML
  2374. * to do networking.
  2375. *
  2376. * Faster is to do virtio bonding in kernel. Doing this 1:1 would be
  2377. * completely generic ("here's my vring, attach to your vring") and would work
  2378. * for any traffic. Of course, namespace and permissions issues need to be
  2379. * dealt with. A more sophisticated "multi-channel" virtio_net.c could hide
  2380. * multiple inter-guest channels behind one interface, although it would
  2381. * require some manner of hotplugging new virtio channels.
  2382. *
  2383. * Finally, we could use a virtio network switch in the kernel, ie. vhost.
  2384. :*/
  2385. static u32 str2ip(const char *ipaddr)
  2386. {
  2387. unsigned int b[4];
  2388. if (sscanf(ipaddr, "%u.%u.%u.%u", &b[0], &b[1], &b[2], &b[3]) != 4)
  2389. errx(1, "Failed to parse IP address '%s'", ipaddr);
  2390. return (b[0] << 24) | (b[1] << 16) | (b[2] << 8) | b[3];
  2391. }
  2392. static void str2mac(const char *macaddr, unsigned char mac[6])
  2393. {
  2394. unsigned int m[6];
  2395. if (sscanf(macaddr, "%02x:%02x:%02x:%02x:%02x:%02x",
  2396. &m[0], &m[1], &m[2], &m[3], &m[4], &m[5]) != 6)
  2397. errx(1, "Failed to parse mac address '%s'", macaddr);
  2398. mac[0] = m[0];
  2399. mac[1] = m[1];
  2400. mac[2] = m[2];
  2401. mac[3] = m[3];
  2402. mac[4] = m[4];
  2403. mac[5] = m[5];
  2404. }
  2405. /*
  2406. * This code is "adapted" from libbridge: it attaches the Host end of the
  2407. * network device to the bridge device specified by the command line.
  2408. *
  2409. * This is yet another James Morris contribution (I'm an IP-level guy, so I
  2410. * dislike bridging), and I just try not to break it.
  2411. */
  2412. static void add_to_bridge(int fd, const char *if_name, const char *br_name)
  2413. {
  2414. int ifidx;
  2415. struct ifreq ifr;
  2416. if (!*br_name)
  2417. errx(1, "must specify bridge name");
  2418. ifidx = if_nametoindex(if_name);
  2419. if (!ifidx)
  2420. errx(1, "interface %s does not exist!", if_name);
  2421. strncpy(ifr.ifr_name, br_name, IFNAMSIZ);
  2422. ifr.ifr_name[IFNAMSIZ-1] = '\0';
  2423. ifr.ifr_ifindex = ifidx;
  2424. if (ioctl(fd, SIOCBRADDIF, &ifr) < 0)
  2425. err(1, "can't add %s to bridge %s", if_name, br_name);
  2426. }
  2427. /*
  2428. * This sets up the Host end of the network device with an IP address, brings
  2429. * it up so packets will flow, the copies the MAC address into the hwaddr
  2430. * pointer.
  2431. */
  2432. static void configure_device(int fd, const char *tapif, u32 ipaddr)
  2433. {
  2434. struct ifreq ifr;
  2435. struct sockaddr_in sin;
  2436. memset(&ifr, 0, sizeof(ifr));
  2437. strcpy(ifr.ifr_name, tapif);
  2438. /* Don't read these incantations. Just cut & paste them like I did! */
  2439. sin.sin_family = AF_INET;
  2440. sin.sin_addr.s_addr = htonl(ipaddr);
  2441. memcpy(&ifr.ifr_addr, &sin, sizeof(sin));
  2442. if (ioctl(fd, SIOCSIFADDR, &ifr) != 0)
  2443. err(1, "Setting %s interface address", tapif);
  2444. ifr.ifr_flags = IFF_UP;
  2445. if (ioctl(fd, SIOCSIFFLAGS, &ifr) != 0)
  2446. err(1, "Bringing interface %s up", tapif);
  2447. }
  2448. static int get_tun_device(char tapif[IFNAMSIZ])
  2449. {
  2450. struct ifreq ifr;
  2451. int vnet_hdr_sz;
  2452. int netfd;
  2453. /* Start with this zeroed. Messy but sure. */
  2454. memset(&ifr, 0, sizeof(ifr));
  2455. /*
  2456. * We open the /dev/net/tun device and tell it we want a tap device. A
  2457. * tap device is like a tun device, only somehow different. To tell
  2458. * the truth, I completely blundered my way through this code, but it
  2459. * works now!
  2460. */
  2461. netfd = open_or_die("/dev/net/tun", O_RDWR);
  2462. ifr.ifr_flags = IFF_TAP | IFF_NO_PI | IFF_VNET_HDR;
  2463. strcpy(ifr.ifr_name, "tap%d");
  2464. if (ioctl(netfd, TUNSETIFF, &ifr) != 0)
  2465. err(1, "configuring /dev/net/tun");
  2466. if (ioctl(netfd, TUNSETOFFLOAD,
  2467. TUN_F_CSUM|TUN_F_TSO4|TUN_F_TSO6|TUN_F_TSO_ECN) != 0)
  2468. err(1, "Could not set features for tun device");
  2469. /*
  2470. * We don't need checksums calculated for packets coming in this
  2471. * device: trust us!
  2472. */
  2473. ioctl(netfd, TUNSETNOCSUM, 1);
  2474. /*
  2475. * In virtio before 1.0 (aka legacy virtio), we added a 16-bit
  2476. * field at the end of the network header iff
  2477. * VIRTIO_NET_F_MRG_RXBUF was negotiated. For virtio 1.0,
  2478. * that became the norm, but we need to tell the tun device
  2479. * about our expanded header (which is called
  2480. * virtio_net_hdr_mrg_rxbuf in the legacy system).
  2481. */
  2482. vnet_hdr_sz = sizeof(struct virtio_net_hdr_v1);
  2483. if (ioctl(netfd, TUNSETVNETHDRSZ, &vnet_hdr_sz) != 0)
  2484. err(1, "Setting tun header size to %u", vnet_hdr_sz);
  2485. memcpy(tapif, ifr.ifr_name, IFNAMSIZ);
  2486. return netfd;
  2487. }
  2488. /*L:195
  2489. * Our network is a Host<->Guest network. This can either use bridging or
  2490. * routing, but the principle is the same: it uses the "tun" device to inject
  2491. * packets into the Host as if they came in from a normal network card. We
  2492. * just shunt packets between the Guest and the tun device.
  2493. */
  2494. static void setup_tun_net(char *arg)
  2495. {
  2496. struct device *dev;
  2497. struct net_info *net_info = malloc(sizeof(*net_info));
  2498. int ipfd;
  2499. u32 ip = INADDR_ANY;
  2500. bool bridging = false;
  2501. char tapif[IFNAMSIZ], *p;
  2502. struct virtio_net_config conf;
  2503. net_info->tunfd = get_tun_device(tapif);
  2504. /* First we create a new network device. */
  2505. dev = new_pci_device("net", VIRTIO_ID_NET, 0x02, 0x00);
  2506. dev->priv = net_info;
  2507. /* Network devices need a recv and a send queue, just like console. */
  2508. add_pci_virtqueue(dev, net_input, "rx");
  2509. add_pci_virtqueue(dev, net_output, "tx");
  2510. /*
  2511. * We need a socket to perform the magic network ioctls to bring up the
  2512. * tap interface, connect to the bridge etc. Any socket will do!
  2513. */
  2514. ipfd = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP);
  2515. if (ipfd < 0)
  2516. err(1, "opening IP socket");
  2517. /* If the command line was --tunnet=bridge:<name> do bridging. */
  2518. if (!strncmp(BRIDGE_PFX, arg, strlen(BRIDGE_PFX))) {
  2519. arg += strlen(BRIDGE_PFX);
  2520. bridging = true;
  2521. }
  2522. /* A mac address may follow the bridge name or IP address */
  2523. p = strchr(arg, ':');
  2524. if (p) {
  2525. str2mac(p+1, conf.mac);
  2526. add_pci_feature(dev, VIRTIO_NET_F_MAC);
  2527. *p = '\0';
  2528. }
  2529. /* arg is now either an IP address or a bridge name */
  2530. if (bridging)
  2531. add_to_bridge(ipfd, tapif, arg);
  2532. else
  2533. ip = str2ip(arg);
  2534. /* Set up the tun device. */
  2535. configure_device(ipfd, tapif, ip);
  2536. /* Expect Guest to handle everything except UFO */
  2537. add_pci_feature(dev, VIRTIO_NET_F_CSUM);
  2538. add_pci_feature(dev, VIRTIO_NET_F_GUEST_CSUM);
  2539. add_pci_feature(dev, VIRTIO_NET_F_GUEST_TSO4);
  2540. add_pci_feature(dev, VIRTIO_NET_F_GUEST_TSO6);
  2541. add_pci_feature(dev, VIRTIO_NET_F_GUEST_ECN);
  2542. add_pci_feature(dev, VIRTIO_NET_F_HOST_TSO4);
  2543. add_pci_feature(dev, VIRTIO_NET_F_HOST_TSO6);
  2544. add_pci_feature(dev, VIRTIO_NET_F_HOST_ECN);
  2545. /* We handle indirect ring entries */
  2546. add_pci_feature(dev, VIRTIO_RING_F_INDIRECT_DESC);
  2547. set_device_config(dev, &conf, sizeof(conf));
  2548. /* We don't need the socket any more; setup is done. */
  2549. close(ipfd);
  2550. if (bridging)
  2551. verbose("device %u: tun %s attached to bridge: %s\n",
  2552. devices.device_num, tapif, arg);
  2553. else
  2554. verbose("device %u: tun %s: %s\n",
  2555. devices.device_num, tapif, arg);
  2556. }
  2557. /*:*/
  2558. /* This hangs off device->priv. */
  2559. struct vblk_info {
  2560. /* The size of the file. */
  2561. off64_t len;
  2562. /* The file descriptor for the file. */
  2563. int fd;
  2564. };
  2565. /*L:210
  2566. * The Disk
  2567. *
  2568. * The disk only has one virtqueue, so it only has one thread. It is really
  2569. * simple: the Guest asks for a block number and we read or write that position
  2570. * in the file.
  2571. *
  2572. * Before we serviced each virtqueue in a separate thread, that was unacceptably
  2573. * slow: the Guest waits until the read is finished before running anything
  2574. * else, even if it could have been doing useful work.
  2575. *
  2576. * We could have used async I/O, except it's reputed to suck so hard that
  2577. * characters actually go missing from your code when you try to use it.
  2578. */
  2579. static void blk_request(struct virtqueue *vq)
  2580. {
  2581. struct vblk_info *vblk = vq->dev->priv;
  2582. unsigned int head, out_num, in_num, wlen;
  2583. int ret, i;
  2584. u8 *in;
  2585. struct virtio_blk_outhdr out;
  2586. struct iovec iov[vq->vring.num];
  2587. off64_t off;
  2588. /*
  2589. * Get the next request, where we normally wait. It triggers the
  2590. * interrupt to acknowledge previously serviced requests (if any).
  2591. */
  2592. head = wait_for_vq_desc(vq, iov, &out_num, &in_num);
  2593. /* Copy the output header from the front of the iov (adjusts iov) */
  2594. iov_consume(vq->dev, iov, out_num, &out, sizeof(out));
  2595. /* Find and trim end of iov input array, for our status byte. */
  2596. in = NULL;
  2597. for (i = out_num + in_num - 1; i >= out_num; i--) {
  2598. if (iov[i].iov_len > 0) {
  2599. in = iov[i].iov_base + iov[i].iov_len - 1;
  2600. iov[i].iov_len--;
  2601. break;
  2602. }
  2603. }
  2604. if (!in)
  2605. bad_driver_vq(vq, "Bad virtblk cmd with no room for status");
  2606. /*
  2607. * For historical reasons, block operations are expressed in 512 byte
  2608. * "sectors".
  2609. */
  2610. off = out.sector * 512;
  2611. if (out.type & VIRTIO_BLK_T_OUT) {
  2612. /*
  2613. * Write
  2614. *
  2615. * Move to the right location in the block file. This can fail
  2616. * if they try to write past end.
  2617. */
  2618. if (lseek64(vblk->fd, off, SEEK_SET) != off)
  2619. err(1, "Bad seek to sector %llu", out.sector);
  2620. ret = writev(vblk->fd, iov, out_num);
  2621. verbose("WRITE to sector %llu: %i\n", out.sector, ret);
  2622. /*
  2623. * Grr... Now we know how long the descriptor they sent was, we
  2624. * make sure they didn't try to write over the end of the block
  2625. * file (possibly extending it).
  2626. */
  2627. if (ret > 0 && off + ret > vblk->len) {
  2628. /* Trim it back to the correct length */
  2629. ftruncate64(vblk->fd, vblk->len);
  2630. /* Die, bad Guest, die. */
  2631. bad_driver_vq(vq, "Write past end %llu+%u", off, ret);
  2632. }
  2633. wlen = sizeof(*in);
  2634. *in = (ret >= 0 ? VIRTIO_BLK_S_OK : VIRTIO_BLK_S_IOERR);
  2635. } else if (out.type & VIRTIO_BLK_T_FLUSH) {
  2636. /* Flush */
  2637. ret = fdatasync(vblk->fd);
  2638. verbose("FLUSH fdatasync: %i\n", ret);
  2639. wlen = sizeof(*in);
  2640. *in = (ret >= 0 ? VIRTIO_BLK_S_OK : VIRTIO_BLK_S_IOERR);
  2641. } else {
  2642. /*
  2643. * Read
  2644. *
  2645. * Move to the right location in the block file. This can fail
  2646. * if they try to read past end.
  2647. */
  2648. if (lseek64(vblk->fd, off, SEEK_SET) != off)
  2649. err(1, "Bad seek to sector %llu", out.sector);
  2650. ret = readv(vblk->fd, iov + out_num, in_num);
  2651. if (ret >= 0) {
  2652. wlen = sizeof(*in) + ret;
  2653. *in = VIRTIO_BLK_S_OK;
  2654. } else {
  2655. wlen = sizeof(*in);
  2656. *in = VIRTIO_BLK_S_IOERR;
  2657. }
  2658. }
  2659. /* Finished that request. */
  2660. add_used(vq, head, wlen);
  2661. }
  2662. /*L:198 This actually sets up a virtual block device. */
  2663. static void setup_block_file(const char *filename)
  2664. {
  2665. struct device *dev;
  2666. struct vblk_info *vblk;
  2667. struct virtio_blk_config conf;
  2668. /* Create the device. */
  2669. dev = new_pci_device("block", VIRTIO_ID_BLOCK, 0x01, 0x80);
  2670. /* The device has one virtqueue, where the Guest places requests. */
  2671. add_pci_virtqueue(dev, blk_request, "request");
  2672. /* Allocate the room for our own bookkeeping */
  2673. vblk = dev->priv = malloc(sizeof(*vblk));
  2674. /* First we open the file and store the length. */
  2675. vblk->fd = open_or_die(filename, O_RDWR|O_LARGEFILE);
  2676. vblk->len = lseek64(vblk->fd, 0, SEEK_END);
  2677. /* Tell Guest how many sectors this device has. */
  2678. conf.capacity = cpu_to_le64(vblk->len / 512);
  2679. /*
  2680. * Tell Guest not to put in too many descriptors at once: two are used
  2681. * for the in and out elements.
  2682. */
  2683. add_pci_feature(dev, VIRTIO_BLK_F_SEG_MAX);
  2684. conf.seg_max = cpu_to_le32(VIRTQUEUE_NUM - 2);
  2685. set_device_config(dev, &conf, sizeof(struct virtio_blk_config));
  2686. verbose("device %u: virtblock %llu sectors\n",
  2687. devices.device_num, le64_to_cpu(conf.capacity));
  2688. }
  2689. /*L:211
  2690. * Our random number generator device reads from /dev/urandom into the Guest's
  2691. * input buffers. The usual case is that the Guest doesn't want random numbers
  2692. * and so has no buffers although /dev/urandom is still readable, whereas
  2693. * console is the reverse.
  2694. *
  2695. * The same logic applies, however.
  2696. */
  2697. struct rng_info {
  2698. int rfd;
  2699. };
  2700. static void rng_input(struct virtqueue *vq)
  2701. {
  2702. int len;
  2703. unsigned int head, in_num, out_num, totlen = 0;
  2704. struct rng_info *rng_info = vq->dev->priv;
  2705. struct iovec iov[vq->vring.num];
  2706. /* First we need a buffer from the Guests's virtqueue. */
  2707. head = wait_for_vq_desc(vq, iov, &out_num, &in_num);
  2708. if (out_num)
  2709. bad_driver_vq(vq, "Output buffers in rng?");
  2710. /*
  2711. * Just like the console write, we loop to cover the whole iovec.
  2712. * In this case, short reads actually happen quite a bit.
  2713. */
  2714. while (!iov_empty(iov, in_num)) {
  2715. len = readv(rng_info->rfd, iov, in_num);
  2716. if (len <= 0)
  2717. err(1, "Read from /dev/urandom gave %i", len);
  2718. iov_consume(vq->dev, iov, in_num, NULL, len);
  2719. totlen += len;
  2720. }
  2721. /* Tell the Guest about the new input. */
  2722. add_used(vq, head, totlen);
  2723. }
  2724. /*L:199
  2725. * This creates a "hardware" random number device for the Guest.
  2726. */
  2727. static void setup_rng(void)
  2728. {
  2729. struct device *dev;
  2730. struct rng_info *rng_info = malloc(sizeof(*rng_info));
  2731. /* Our device's private info simply contains the /dev/urandom fd. */
  2732. rng_info->rfd = open_or_die("/dev/urandom", O_RDONLY);
  2733. /* Create the new device. */
  2734. dev = new_pci_device("rng", VIRTIO_ID_RNG, 0xff, 0);
  2735. dev->priv = rng_info;
  2736. /* The device has one virtqueue, where the Guest places inbufs. */
  2737. add_pci_virtqueue(dev, rng_input, "input");
  2738. /* We don't have any configuration space */
  2739. no_device_config(dev);
  2740. verbose("device %u: rng\n", devices.device_num);
  2741. }
  2742. /* That's the end of device setup. */
  2743. /*L:230 Reboot is pretty easy: clean up and exec() the Launcher afresh. */
  2744. static void __attribute__((noreturn)) restart_guest(void)
  2745. {
  2746. unsigned int i;
  2747. /*
  2748. * Since we don't track all open fds, we simply close everything beyond
  2749. * stderr.
  2750. */
  2751. for (i = 3; i < FD_SETSIZE; i++)
  2752. close(i);
  2753. /* Reset all the devices (kills all threads). */
  2754. cleanup_devices();
  2755. execv(main_args[0], main_args);
  2756. err(1, "Could not exec %s", main_args[0]);
  2757. }
  2758. /*L:220
  2759. * Finally we reach the core of the Launcher which runs the Guest, serves
  2760. * its input and output, and finally, lays it to rest.
  2761. */
  2762. static void __attribute__((noreturn)) run_guest(void)
  2763. {
  2764. for (;;) {
  2765. struct lguest_pending notify;
  2766. int readval;
  2767. /* We read from the /dev/lguest device to run the Guest. */
  2768. readval = pread(lguest_fd, &notify, sizeof(notify), cpu_id);
  2769. if (readval == sizeof(notify)) {
  2770. if (notify.trap == 13) {
  2771. verbose("Emulating instruction at %#x\n",
  2772. getreg(eip));
  2773. emulate_insn(notify.insn);
  2774. } else if (notify.trap == 14) {
  2775. verbose("Emulating MMIO at %#x\n",
  2776. getreg(eip));
  2777. emulate_mmio(notify.addr, notify.insn);
  2778. } else
  2779. errx(1, "Unknown trap %i addr %#08x\n",
  2780. notify.trap, notify.addr);
  2781. /* ENOENT means the Guest died. Reading tells us why. */
  2782. } else if (errno == ENOENT) {
  2783. char reason[1024] = { 0 };
  2784. pread(lguest_fd, reason, sizeof(reason)-1, cpu_id);
  2785. errx(1, "%s", reason);
  2786. /* ERESTART means that we need to reboot the guest */
  2787. } else if (errno == ERESTART) {
  2788. restart_guest();
  2789. /* Anything else means a bug or incompatible change. */
  2790. } else
  2791. err(1, "Running guest failed");
  2792. }
  2793. }
  2794. /*L:240
  2795. * This is the end of the Launcher. The good news: we are over halfway
  2796. * through! The bad news: the most fiendish part of the code still lies ahead
  2797. * of us.
  2798. *
  2799. * Are you ready? Take a deep breath and join me in the core of the Host, in
  2800. * "make Host".
  2801. :*/
  2802. static struct option opts[] = {
  2803. { "verbose", 0, NULL, 'v' },
  2804. { "tunnet", 1, NULL, 't' },
  2805. { "block", 1, NULL, 'b' },
  2806. { "rng", 0, NULL, 'r' },
  2807. { "initrd", 1, NULL, 'i' },
  2808. { "username", 1, NULL, 'u' },
  2809. { "chroot", 1, NULL, 'c' },
  2810. { NULL },
  2811. };
  2812. static void usage(void)
  2813. {
  2814. errx(1, "Usage: lguest [--verbose] "
  2815. "[--tunnet=(<ipaddr>:<macaddr>|bridge:<bridgename>:<macaddr>)\n"
  2816. "|--block=<filename>|--initrd=<filename>]...\n"
  2817. "<mem-in-mb> vmlinux [args...]");
  2818. }
  2819. /*L:105 The main routine is where the real work begins: */
  2820. int main(int argc, char *argv[])
  2821. {
  2822. /* Memory, code startpoint and size of the (optional) initrd. */
  2823. unsigned long mem = 0, start, initrd_size = 0;
  2824. /* Two temporaries. */
  2825. int i, c;
  2826. /* The boot information for the Guest. */
  2827. struct boot_params *boot;
  2828. /* If they specify an initrd file to load. */
  2829. const char *initrd_name = NULL;
  2830. /* Password structure for initgroups/setres[gu]id */
  2831. struct passwd *user_details = NULL;
  2832. /* Directory to chroot to */
  2833. char *chroot_path = NULL;
  2834. /* Save the args: we "reboot" by execing ourselves again. */
  2835. main_args = argv;
  2836. /*
  2837. * First we initialize the device list. We remember next interrupt
  2838. * number to use for devices (1: remember that 0 is used by the timer).
  2839. */
  2840. devices.next_irq = 1;
  2841. /* We're CPU 0. In fact, that's the only CPU possible right now. */
  2842. cpu_id = 0;
  2843. /*
  2844. * We need to know how much memory so we can set up the device
  2845. * descriptor and memory pages for the devices as we parse the command
  2846. * line. So we quickly look through the arguments to find the amount
  2847. * of memory now.
  2848. */
  2849. for (i = 1; i < argc; i++) {
  2850. if (argv[i][0] != '-') {
  2851. mem = atoi(argv[i]) * 1024 * 1024;
  2852. /*
  2853. * We start by mapping anonymous pages over all of
  2854. * guest-physical memory range. This fills it with 0,
  2855. * and ensures that the Guest won't be killed when it
  2856. * tries to access it.
  2857. */
  2858. guest_base = map_zeroed_pages(mem / getpagesize()
  2859. + DEVICE_PAGES);
  2860. guest_limit = mem;
  2861. guest_max = guest_mmio = mem + DEVICE_PAGES*getpagesize();
  2862. break;
  2863. }
  2864. }
  2865. /* We always have a console device, and it's always device 1. */
  2866. setup_console();
  2867. /* The options are fairly straight-forward */
  2868. while ((c = getopt_long(argc, argv, "v", opts, NULL)) != EOF) {
  2869. switch (c) {
  2870. case 'v':
  2871. verbose = true;
  2872. break;
  2873. case 't':
  2874. setup_tun_net(optarg);
  2875. break;
  2876. case 'b':
  2877. setup_block_file(optarg);
  2878. break;
  2879. case 'r':
  2880. setup_rng();
  2881. break;
  2882. case 'i':
  2883. initrd_name = optarg;
  2884. break;
  2885. case 'u':
  2886. user_details = getpwnam(optarg);
  2887. if (!user_details)
  2888. err(1, "getpwnam failed, incorrect username?");
  2889. break;
  2890. case 'c':
  2891. chroot_path = optarg;
  2892. break;
  2893. default:
  2894. warnx("Unknown argument %s", argv[optind]);
  2895. usage();
  2896. }
  2897. }
  2898. /*
  2899. * After the other arguments we expect memory and kernel image name,
  2900. * followed by command line arguments for the kernel.
  2901. */
  2902. if (optind + 2 > argc)
  2903. usage();
  2904. verbose("Guest base is at %p\n", guest_base);
  2905. /* Initialize the (fake) PCI host bridge device. */
  2906. init_pci_host_bridge();
  2907. /* Now we load the kernel */
  2908. start = load_kernel(open_or_die(argv[optind+1], O_RDONLY));
  2909. /* Boot information is stashed at physical address 0 */
  2910. boot = from_guest_phys(0);
  2911. /* Map the initrd image if requested (at top of physical memory) */
  2912. if (initrd_name) {
  2913. initrd_size = load_initrd(initrd_name, mem);
  2914. /*
  2915. * These are the location in the Linux boot header where the
  2916. * start and size of the initrd are expected to be found.
  2917. */
  2918. boot->hdr.ramdisk_image = mem - initrd_size;
  2919. boot->hdr.ramdisk_size = initrd_size;
  2920. /* The bootloader type 0xFF means "unknown"; that's OK. */
  2921. boot->hdr.type_of_loader = 0xFF;
  2922. }
  2923. /*
  2924. * The Linux boot header contains an "E820" memory map: ours is a
  2925. * simple, single region.
  2926. */
  2927. boot->e820_entries = 1;
  2928. boot->e820_map[0] = ((struct e820entry) { 0, mem, E820_RAM });
  2929. /*
  2930. * The boot header contains a command line pointer: we put the command
  2931. * line after the boot header.
  2932. */
  2933. boot->hdr.cmd_line_ptr = to_guest_phys(boot + 1);
  2934. /* We use a simple helper to copy the arguments separated by spaces. */
  2935. concat((char *)(boot + 1), argv+optind+2);
  2936. /* Set kernel alignment to 16M (CONFIG_PHYSICAL_ALIGN) */
  2937. boot->hdr.kernel_alignment = 0x1000000;
  2938. /* Boot protocol version: 2.07 supports the fields for lguest. */
  2939. boot->hdr.version = 0x207;
  2940. /* The hardware_subarch value of "1" tells the Guest it's an lguest. */
  2941. boot->hdr.hardware_subarch = 1;
  2942. /* Tell the entry path not to try to reload segment registers. */
  2943. boot->hdr.loadflags |= KEEP_SEGMENTS;
  2944. /* We tell the kernel to initialize the Guest. */
  2945. tell_kernel(start);
  2946. /* Ensure that we terminate if a device-servicing child dies. */
  2947. signal(SIGCHLD, kill_launcher);
  2948. /* If we exit via err(), this kills all the threads, restores tty. */
  2949. atexit(cleanup_devices);
  2950. /* If requested, chroot to a directory */
  2951. if (chroot_path) {
  2952. if (chroot(chroot_path) != 0)
  2953. err(1, "chroot(\"%s\") failed", chroot_path);
  2954. if (chdir("/") != 0)
  2955. err(1, "chdir(\"/\") failed");
  2956. verbose("chroot done\n");
  2957. }
  2958. /* If requested, drop privileges */
  2959. if (user_details) {
  2960. uid_t u;
  2961. gid_t g;
  2962. u = user_details->pw_uid;
  2963. g = user_details->pw_gid;
  2964. if (initgroups(user_details->pw_name, g) != 0)
  2965. err(1, "initgroups failed");
  2966. if (setresgid(g, g, g) != 0)
  2967. err(1, "setresgid failed");
  2968. if (setresuid(u, u, u) != 0)
  2969. err(1, "setresuid failed");
  2970. verbose("Dropping privileges completed\n");
  2971. }
  2972. /* Finally, run the Guest. This doesn't return. */
  2973. run_guest();
  2974. }
  2975. /*:*/
  2976. /*M:999
  2977. * Mastery is done: you now know everything I do.
  2978. *
  2979. * But surely you have seen code, features and bugs in your wanderings which
  2980. * you now yearn to attack? That is the real game, and I look forward to you
  2981. * patching and forking lguest into the Your-Name-Here-visor.
  2982. *
  2983. * Farewell, and good coding!
  2984. * Rusty Russell.
  2985. */