lguest.c 95 KB

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