virtio-spec.txt 97 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210
  1. [Generated file: see http://ozlabs.org/~rusty/virtio-spec/]
  2. Virtio PCI Card Specification
  3. v0.9.5 DRAFT
  4. -
  5. Rusty Russell <rusty@rustcorp.com.au> IBM Corporation (Editor)
  6. 2012 May 7.
  7. Purpose and Description
  8. This document describes the specifications of the “virtio” family
  9. of PCI[LaTeX Command: nomenclature] devices. These are devices
  10. are found in virtual environments[LaTeX Command: nomenclature],
  11. yet by design they are not all that different from physical PCI
  12. devices, and this document treats them as such. This allows the
  13. guest to use standard PCI drivers and discovery mechanisms.
  14. The purpose of virtio and this specification is that virtual
  15. environments and guests should have a straightforward, efficient,
  16. standard and extensible mechanism for virtual devices, rather
  17. than boutique per-environment or per-OS mechanisms.
  18. Straightforward: Virtio PCI devices use normal PCI mechanisms
  19. of interrupts and DMA which should be familiar to any device
  20. driver author. There is no exotic page-flipping or COW
  21. mechanism: it's just a PCI device.[footnote:
  22. This lack of page-sharing implies that the implementation of the
  23. device (e.g. the hypervisor or host) needs full access to the
  24. guest memory. Communication with untrusted parties (i.e.
  25. inter-guest communication) requires copying.
  26. ]
  27. Efficient: Virtio PCI devices consist of rings of descriptors
  28. for input and output, which are neatly separated to avoid cache
  29. effects from both guest and device writing to the same cache
  30. lines.
  31. Standard: Virtio PCI makes no assumptions about the environment
  32. in which it operates, beyond supporting PCI. In fact the virtio
  33. devices specified in the appendices do not require PCI at all:
  34. they have been implemented on non-PCI buses.[footnote:
  35. The Linux implementation further separates the PCI virtio code
  36. from the specific virtio drivers: these drivers are shared with
  37. the non-PCI implementations (currently lguest and S/390).
  38. ]
  39. Extensible: Virtio PCI devices contain feature bits which are
  40. acknowledged by the guest operating system during device setup.
  41. This allows forwards and backwards compatibility: the device
  42. offers all the features it knows about, and the driver
  43. acknowledges those it understands and wishes to use.
  44. Virtqueues
  45. The mechanism for bulk data transport on virtio PCI devices is
  46. pretentiously called a virtqueue. Each device can have zero or
  47. more virtqueues: for example, the network device has one for
  48. transmit and one for receive.
  49. Each virtqueue occupies two or more physically-contiguous pages
  50. (defined, for the purposes of this specification, as 4096 bytes),
  51. and consists of three parts:
  52. +-------------------+-----------------------------------+-----------+
  53. | Descriptor Table | Available Ring (padding) | Used Ring |
  54. +-------------------+-----------------------------------+-----------+
  55. When the driver wants to send a buffer to the device, it fills in
  56. a slot in the descriptor table (or chains several together), and
  57. writes the descriptor index into the available ring. It then
  58. notifies the device. When the device has finished a buffer, it
  59. writes the descriptor into the used ring, and sends an interrupt.
  60. Specification
  61. PCI Discovery
  62. Any PCI device with Vendor ID 0x1AF4, and Device ID 0x1000
  63. through 0x103F inclusive is a virtio device[footnote:
  64. The actual value within this range is ignored
  65. ]. The device must also have a Revision ID of 0 to match this
  66. specification.
  67. The Subsystem Device ID indicates which virtio device is
  68. supported by the device. The Subsystem Vendor ID should reflect
  69. the PCI Vendor ID of the environment (it's currently only used
  70. for informational purposes by the guest).
  71. +----------------------+--------------------+---------------+
  72. | Subsystem Device ID | Virtio Device | Specification |
  73. +----------------------+--------------------+---------------+
  74. +----------------------+--------------------+---------------+
  75. | 1 | network card | Appendix C |
  76. +----------------------+--------------------+---------------+
  77. | 2 | block device | Appendix D |
  78. +----------------------+--------------------+---------------+
  79. | 3 | console | Appendix E |
  80. +----------------------+--------------------+---------------+
  81. | 4 | entropy source | Appendix F |
  82. +----------------------+--------------------+---------------+
  83. | 5 | memory ballooning | Appendix G |
  84. +----------------------+--------------------+---------------+
  85. | 6 | ioMemory | - |
  86. +----------------------+--------------------+---------------+
  87. | 7 | rpmsg | Appendix H |
  88. +----------------------+--------------------+---------------+
  89. | 8 | SCSI host | Appendix I |
  90. +----------------------+--------------------+---------------+
  91. | 9 | 9P transport | - |
  92. +----------------------+--------------------+---------------+
  93. | 10 | mac80211 wlan | - |
  94. +----------------------+--------------------+---------------+
  95. Device Configuration
  96. To configure the device, we use the first I/O region of the PCI
  97. device. This contains a virtio header followed by a
  98. device-specific region.
  99. There may be different widths of accesses to the I/O region; the “
  100. natural” access method for each field in the virtio header must
  101. be used (i.e. 32-bit accesses for 32-bit fields, etc), but the
  102. device-specific region can be accessed using any width accesses,
  103. and should obtain the same results.
  104. Note that this is possible because while the virtio header is PCI
  105. (i.e. little) endian, the device-specific region is encoded in
  106. the native endian of the guest (where such distinction is
  107. applicable).
  108. Device Initialization Sequence<sub:Device-Initialization-Sequence>
  109. We start with an overview of device initialization, then expand
  110. on the details of the device and how each step is preformed.
  111. Reset the device. This is not required on initial start up.
  112. The ACKNOWLEDGE status bit is set: we have noticed the device.
  113. The DRIVER status bit is set: we know how to drive the device.
  114. Device-specific setup, including reading the Device Feature
  115. Bits, discovery of virtqueues for the device, optional MSI-X
  116. setup, and reading and possibly writing the virtio
  117. configuration space.
  118. The subset of Device Feature Bits understood by the driver is
  119. written to the device.
  120. The DRIVER_OK status bit is set.
  121. The device can now be used (ie. buffers added to the
  122. virtqueues)[footnote:
  123. Historically, drivers have used the device before steps 5 and 6.
  124. This is only allowed if the driver does not use any features
  125. which would alter this early use of the device.
  126. ]
  127. If any of these steps go irrecoverably wrong, the guest should
  128. set the FAILED status bit to indicate that it has given up on the
  129. device (it can reset the device later to restart if desired).
  130. We now cover the fields required for general setup in detail.
  131. Virtio Header
  132. The virtio header looks as follows:
  133. +------------++---------------------+---------------------+----------+--------+---------+---------+---------+--------+
  134. | Bits || 32 | 32 | 32 | 16 | 16 | 16 | 8 | 8 |
  135. +------------++---------------------+---------------------+----------+--------+---------+---------+---------+--------+
  136. | Read/Write || R | R+W | R+W | R | R+W | R+W | R+W | R |
  137. +------------++---------------------+---------------------+----------+--------+---------+---------+---------+--------+
  138. | Purpose || Device | Guest | Queue | Queue | Queue | Queue | Device | ISR |
  139. | || Features bits 0:31 | Features bits 0:31 | Address | Size | Select | Notify | Status | Status |
  140. +------------++---------------------+---------------------+----------+--------+---------+---------+---------+--------+
  141. If MSI-X is enabled for the device, two additional fields
  142. immediately follow this header:[footnote:
  143. ie. once you enable MSI-X on the device, the other fields move.
  144. If you turn it off again, they move back!
  145. ]
  146. +------------++----------------+--------+
  147. | Bits || 16 | 16 |
  148. +----------------+--------+
  149. +------------++----------------+--------+
  150. | Read/Write || R+W | R+W |
  151. +------------++----------------+--------+
  152. | Purpose || Configuration | Queue |
  153. | (MSI-X) || Vector | Vector |
  154. +------------++----------------+--------+
  155. Immediately following these general headers, there may be
  156. device-specific headers:
  157. +------------++--------------------+
  158. | Bits || Device Specific |
  159. +--------------------+
  160. +------------++--------------------+
  161. | Read/Write || Device Specific |
  162. +------------++--------------------+
  163. | Purpose || Device Specific... |
  164. | || |
  165. +------------++--------------------+
  166. Device Status
  167. The Device Status field is updated by the guest to indicate its
  168. progress. This provides a simple low-level diagnostic: it's most
  169. useful to imagine them hooked up to traffic lights on the console
  170. indicating the status of each device.
  171. The device can be reset by writing a 0 to this field, otherwise
  172. at least one bit should be set:
  173. ACKNOWLEDGE (1) Indicates that the guest OS has found the
  174. device and recognized it as a valid virtio device.
  175. DRIVER (2) Indicates that the guest OS knows how to drive the
  176. device. Under Linux, drivers can be loadable modules so there
  177. may be a significant (or infinite) delay before setting this
  178. bit.
  179. DRIVER_OK (4) Indicates that the driver is set up and ready to
  180. drive the device.
  181. FAILED (128) Indicates that something went wrong in the guest,
  182. and it has given up on the device. This could be an internal
  183. error, or the driver didn't like the device for some reason, or
  184. even a fatal error during device operation. The device must be
  185. reset before attempting to re-initialize.
  186. Feature Bits<sub:Feature-Bits>
  187. Thefirst configuration field indicates the features that the
  188. device supports. The bits are allocated as follows:
  189. 0 to 23 Feature bits for the specific device type
  190. 24 to 32 Feature bits reserved for extensions to the queue and
  191. feature negotiation mechanisms
  192. For example, feature bit 0 for a network device (i.e. Subsystem
  193. Device ID 1) indicates that the device supports checksumming of
  194. packets.
  195. The feature bits are negotiated: the device lists all the
  196. features it understands in the Device Features field, and the
  197. guest writes the subset that it understands into the Guest
  198. Features field. The only way to renegotiate is to reset the
  199. device.
  200. In particular, new fields in the device configuration header are
  201. indicated by offering a feature bit, so the guest can check
  202. before accessing that part of the configuration space.
  203. This allows for forwards and backwards compatibility: if the
  204. device is enhanced with a new feature bit, older guests will not
  205. write that feature bit back to the Guest Features field and it
  206. can go into backwards compatibility mode. Similarly, if a guest
  207. is enhanced with a feature that the device doesn't support, it
  208. will not see that feature bit in the Device Features field and
  209. can go into backwards compatibility mode (or, for poor
  210. implementations, set the FAILED Device Status bit).
  211. Configuration/Queue Vectors
  212. When MSI-X capability is present and enabled in the device
  213. (through standard PCI configuration space) 4 bytes at byte offset
  214. 20 are used to map configuration change and queue interrupts to
  215. MSI-X vectors. In this case, the ISR Status field is unused, and
  216. device specific configuration starts at byte offset 24 in virtio
  217. header structure. When MSI-X capability is not enabled, device
  218. specific configuration starts at byte offset 20 in virtio header.
  219. Writing a valid MSI-X Table entry number, 0 to 0x7FF, to one of
  220. Configuration/Queue Vector registers, maps interrupts triggered
  221. by the configuration change/selected queue events respectively to
  222. the corresponding MSI-X vector. To disable interrupts for a
  223. specific event type, unmap it by writing a special NO_VECTOR
  224. value:
  225. /* Vector value used to disable MSI for queue */
  226. #define VIRTIO_MSI_NO_VECTOR 0xffff
  227. Reading these registers returns vector mapped to a given event,
  228. or NO_VECTOR if unmapped. All queue and configuration change
  229. events are unmapped by default.
  230. Note that mapping an event to vector might require allocating
  231. internal device resources, and might fail. Devices report such
  232. failures by returning the NO_VECTOR value when the relevant
  233. Vector field is read. After mapping an event to vector, the
  234. driver must verify success by reading the Vector field value: on
  235. success, the previously written value is returned, and on
  236. failure, NO_VECTOR is returned. If a mapping failure is detected,
  237. the driver can retry mapping with fewervectors, or disable MSI-X.
  238. Virtqueue Configuration<sec:Virtqueue-Configuration>
  239. As a device can have zero or more virtqueues for bulk data
  240. transport (for example, the network driver has two), the driver
  241. needs to configure them as part of the device-specific
  242. configuration.
  243. This is done as follows, for each virtqueue a device has:
  244. Write the virtqueue index (first queue is 0) to the Queue
  245. Select field.
  246. Read the virtqueue size from the Queue Size field, which is
  247. always a power of 2. This controls how big the virtqueue is
  248. (see below). If this field is 0, the virtqueue does not exist.
  249. Allocate and zero virtqueue in contiguous physical memory, on a
  250. 4096 byte alignment. Write the physical address, divided by
  251. 4096 to the Queue Address field.[footnote:
  252. The 4096 is based on the x86 page size, but it's also large
  253. enough to ensure that the separate parts of the virtqueue are on
  254. separate cache lines.
  255. ]
  256. Optionally, if MSI-X capability is present and enabled on the
  257. device, select a vector to use to request interrupts triggered
  258. by virtqueue events. Write the MSI-X Table entry number
  259. corresponding to this vector in Queue Vector field. Read the
  260. Queue Vector field: on success, previously written value is
  261. returned; on failure, NO_VECTOR value is returned.
  262. The Queue Size field controls the total number of bytes required
  263. for the virtqueue according to the following formula:
  264. #define ALIGN(x) (((x) + 4095) & ~4095)
  265. static inline unsigned vring_size(unsigned int qsz)
  266. {
  267. return ALIGN(sizeof(struct vring_desc)*qsz + sizeof(u16)*(2
  268. + qsz))
  269. + ALIGN(sizeof(struct vring_used_elem)*qsz);
  270. }
  271. This currently wastes some space with padding, but also allows
  272. future extensions. The virtqueue layout structure looks like this
  273. (qsz is the Queue Size field, which is a variable, so this code
  274. won't compile):
  275. struct vring {
  276. /* The actual descriptors (16 bytes each) */
  277. struct vring_desc desc[qsz];
  278. /* A ring of available descriptor heads with free-running
  279. index. */
  280. struct vring_avail avail;
  281. // Padding to the next 4096 boundary.
  282. char pad[];
  283. // A ring of used descriptor heads with free-running index.
  284. struct vring_used used;
  285. };
  286. A Note on Virtqueue Endianness
  287. Note that the endian of these fields and everything else in the
  288. virtqueue is the native endian of the guest, not little-endian as
  289. PCI normally is. This makes for simpler guest code, and it is
  290. assumed that the host already has to be deeply aware of the guest
  291. endian so such an “endian-aware” device is not a significant
  292. issue.
  293. Descriptor Table
  294. The descriptor table refers to the buffers the guest is using for
  295. the device. The addresses are physical addresses, and the buffers
  296. can be chained via the next field. Each descriptor describes a
  297. buffer which is read-only or write-only, but a chain of
  298. descriptors can contain both read-only and write-only buffers.
  299. No descriptor chain may be more than 2^32 bytes long in total.struct vring_desc {
  300. /* Address (guest-physical). */
  301. u64 addr;
  302. /* Length. */
  303. u32 len;
  304. /* This marks a buffer as continuing via the next field. */
  305. #define VRING_DESC_F_NEXT 1
  306. /* This marks a buffer as write-only (otherwise read-only). */
  307. #define VRING_DESC_F_WRITE 2
  308. /* This means the buffer contains a list of buffer descriptors.
  309. */
  310. #define VRING_DESC_F_INDIRECT 4
  311. /* The flags as indicated above. */
  312. u16 flags;
  313. /* Next field if flags & NEXT */
  314. u16 next;
  315. };
  316. The number of descriptors in the table is specified by the Queue
  317. Size field for this virtqueue.
  318. <sub:Indirect-Descriptors>Indirect Descriptors
  319. Some devices benefit by concurrently dispatching a large number
  320. of large requests. The VIRTIO_RING_F_INDIRECT_DESC feature can be
  321. used to allow this (see [cha:Reserved-Feature-Bits]). To increase
  322. ring capacity it is possible to store a table of indirect
  323. descriptors anywhere in memory, and insert a descriptor in main
  324. virtqueue (with flags&INDIRECT on) that refers to memory buffer
  325. containing this indirect descriptor table; fields addr and len
  326. refer to the indirect table address and length in bytes,
  327. respectively. The indirect table layout structure looks like this
  328. (len is the length of the descriptor that refers to this table,
  329. which is a variable, so this code won't compile):
  330. struct indirect_descriptor_table {
  331. /* The actual descriptors (16 bytes each) */
  332. struct vring_desc desc[len / 16];
  333. };
  334. The first indirect descriptor is located at start of the indirect
  335. descriptor table (index 0), additional indirect descriptors are
  336. chained by next field. An indirect descriptor without next field
  337. (with flags&NEXT off) signals the end of the indirect descriptor
  338. table, and transfers control back to the main virtqueue. An
  339. indirect descriptor can not refer to another indirect descriptor
  340. table (flags&INDIRECT must be off). A single indirect descriptor
  341. table can include both read-only and write-only descriptors;
  342. write-only flag (flags&WRITE) in the descriptor that refers to it
  343. is ignored.
  344. Available Ring
  345. The available ring refers to what descriptors we are offering the
  346. device: it refers to the head of a descriptor chain. The “flags”
  347. field is currently 0 or 1: 1 indicating that we do not need an
  348. interrupt when the device consumes a descriptor from the
  349. available ring. Alternatively, the guest can ask the device to
  350. delay interrupts until an entry with an index specified by the “
  351. used_event” field is written in the used ring (equivalently,
  352. until the idx field in the used ring will reach the value
  353. used_event + 1). The method employed by the device is controlled
  354. by the VIRTIO_RING_F_EVENT_IDX feature bit (see [cha:Reserved-Feature-Bits]
  355. ). This interrupt suppression is merely an optimization; it may
  356. not suppress interrupts entirely.
  357. The “idx” field indicates where we would put the next descriptor
  358. entry (modulo the ring size). This starts at 0, and increases.
  359. struct vring_avail {
  360. #define VRING_AVAIL_F_NO_INTERRUPT 1
  361. u16 flags;
  362. u16 idx;
  363. u16 ring[qsz]; /* qsz is the Queue Size field read from device
  364. */
  365. u16 used_event;
  366. };
  367. Used Ring
  368. The used ring is where the device returns buffers once it is done
  369. with them. The flags field can be used by the device to hint that
  370. no notification is necessary when the guest adds to the available
  371. ring. Alternatively, the “avail_event” field can be used by the
  372. device to hint that no notification is necessary until an entry
  373. with an index specified by the “avail_event” is written in the
  374. available ring (equivalently, until the idx field in the
  375. available ring will reach the value avail_event + 1). The method
  376. employed by the device is controlled by the guest through the
  377. VIRTIO_RING_F_EVENT_IDX feature bit (see [cha:Reserved-Feature-Bits]
  378. ). [footnote:
  379. These fields are kept here because this is the only part of the
  380. virtqueue written by the device
  381. ].
  382. Each entry in the ring is a pair: the head entry of the
  383. descriptor chain describing the buffer (this matches an entry
  384. placed in the available ring by the guest earlier), and the total
  385. of bytes written into the buffer. The latter is extremely useful
  386. for guests using untrusted buffers: if you do not know exactly
  387. how much has been written by the device, you usually have to zero
  388. the buffer to ensure no data leakage occurs.
  389. /* u32 is used here for ids for padding reasons. */
  390. struct vring_used_elem {
  391. /* Index of start of used descriptor chain. */
  392. u32 id;
  393. /* Total length of the descriptor chain which was used
  394. (written to) */
  395. u32 len;
  396. };
  397. struct vring_used {
  398. #define VRING_USED_F_NO_NOTIFY 1
  399. u16 flags;
  400. u16 idx;
  401. struct vring_used_elem ring[qsz];
  402. u16 avail_event;
  403. };
  404. Helpers for Managing Virtqueues
  405. The Linux Kernel Source code contains the definitions above and
  406. helper routines in a more usable form, in
  407. include/linux/virtio_ring.h. This was explicitly licensed by IBM
  408. and Red Hat under the (3-clause) BSD license so that it can be
  409. freely used by all other projects, and is reproduced (with slight
  410. variation to remove Linux assumptions) in Appendix A.
  411. Device Operation<sec:Device-Operation>
  412. There are two parts to device operation: supplying new buffers to
  413. the device, and processing used buffers from the device. As an
  414. example, the virtio network device has two virtqueues: the
  415. transmit virtqueue and the receive virtqueue. The driver adds
  416. outgoing (read-only) packets to the transmit virtqueue, and then
  417. frees them after they are used. Similarly, incoming (write-only)
  418. buffers are added to the receive virtqueue, and processed after
  419. they are used.
  420. Supplying Buffers to The Device
  421. Actual transfer of buffers from the guest OS to the device
  422. operates as follows:
  423. Place the buffer(s) into free descriptor(s).
  424. If there are no free descriptors, the guest may choose to
  425. notify the device even if notifications are suppressed (to
  426. reduce latency).[footnote:
  427. The Linux drivers do this only for read-only buffers: for
  428. write-only buffers, it is assumed that the driver is merely
  429. trying to keep the receive buffer ring full, and no notification
  430. of this expected condition is necessary.
  431. ]
  432. Place the id of the buffer in the next ring entry of the
  433. available ring.
  434. The steps (1) and (2) may be performed repeatedly if batching
  435. is possible.
  436. A memory barrier should be executed to ensure the device sees
  437. the updated descriptor table and available ring before the next
  438. step.
  439. The available “idx” field should be increased by the number of
  440. entries added to the available ring.
  441. A memory barrier should be executed to ensure that we update
  442. the idx field before checking for notification suppression.
  443. If notifications are not suppressed, the device should be
  444. notified of the new buffers.
  445. Note that the above code does not take precautions against the
  446. available ring buffer wrapping around: this is not possible since
  447. the ring buffer is the same size as the descriptor table, so step
  448. (1) will prevent such a condition.
  449. In addition, the maximum queue size is 32768 (it must be a power
  450. of 2 which fits in 16 bits), so the 16-bit “idx” value can always
  451. distinguish between a full and empty buffer.
  452. Here is a description of each stage in more detail.
  453. Placing Buffers Into The Descriptor Table
  454. A buffer consists of zero or more read-only physically-contiguous
  455. elements followed by zero or more physically-contiguous
  456. write-only elements (it must have at least one element). This
  457. algorithm maps it into the descriptor table:
  458. for each buffer element, b:
  459. Get the next free descriptor table entry, d
  460. Set d.addr to the physical address of the start of b
  461. Set d.len to the length of b.
  462. If b is write-only, set d.flags to VRING_DESC_F_WRITE,
  463. otherwise 0.
  464. If there is a buffer element after this:
  465. Set d.next to the index of the next free descriptor element.
  466. Set the VRING_DESC_F_NEXT bit in d.flags.
  467. In practice, the d.next fields are usually used to chain free
  468. descriptors, and a separate count kept to check there are enough
  469. free descriptors before beginning the mappings.
  470. Updating The Available Ring
  471. The head of the buffer we mapped is the first d in the algorithm
  472. above. A naive implementation would do the following:
  473. avail->ring[avail->idx % qsz] = head;
  474. However, in general we can add many descriptors before we update
  475. the “idx” field (at which point they become visible to the
  476. device), so we keep a counter of how many we've added:
  477. avail->ring[(avail->idx + added++) % qsz] = head;
  478. Updating The Index Field
  479. Once the idx field of the virtqueue is updated, the device will
  480. be able to access the descriptor entries we've created and the
  481. memory they refer to. This is why a memory barrier is generally
  482. used before the idx update, to ensure it sees the most up-to-date
  483. copy.
  484. The idx field always increments, and we let it wrap naturally at
  485. 65536:
  486. avail->idx += added;
  487. <sub:Notifying-The-Device>Notifying The Device
  488. Device notification occurs by writing the 16-bit virtqueue index
  489. of this virtqueue to the Queue Notify field of the virtio header
  490. in the first I/O region of the PCI device. This can be expensive,
  491. however, so the device can suppress such notifications if it
  492. doesn't need them. We have to be careful to expose the new idx
  493. value before checking the suppression flag: it's OK to notify
  494. gratuitously, but not to omit a required notification. So again,
  495. we use a memory barrier here before reading the flags or the
  496. avail_event field.
  497. If the VIRTIO_F_RING_EVENT_IDX feature is not negotiated, and if
  498. the VRING_USED_F_NOTIFY flag is not set, we go ahead and write to
  499. the PCI configuration space.
  500. If the VIRTIO_F_RING_EVENT_IDX feature is negotiated, we read the
  501. avail_event field in the available ring structure. If the
  502. available index crossed_the avail_event field value since the
  503. last notification, we go ahead and write to the PCI configuration
  504. space. The avail_event field wraps naturally at 65536 as well:
  505. (u16)(new_idx - avail_event - 1) < (u16)(new_idx - old_idx)
  506. <sub:Receiving-Used-Buffers>Receiving Used Buffers From The
  507. Device
  508. Once the device has used a buffer (read from or written to it, or
  509. parts of both, depending on the nature of the virtqueue and the
  510. device), it sends an interrupt, following an algorithm very
  511. similar to the algorithm used for the driver to send the device a
  512. buffer:
  513. Write the head descriptor number to the next field in the used
  514. ring.
  515. Update the used ring idx.
  516. Determine whether an interrupt is necessary:
  517. If the VIRTIO_F_RING_EVENT_IDX feature is not negotiated: check
  518. if f the VRING_AVAIL_F_NO_INTERRUPT flag is not set in avail-
  519. >flags
  520. If the VIRTIO_F_RING_EVENT_IDX feature is negotiated: check
  521. whether the used index crossed the used_event field value
  522. since the last update. The used_event field wraps naturally
  523. at 65536 as well:(u16)(new_idx - used_event - 1) < (u16)(new_idx - old_idx)
  524. If an interrupt is necessary:
  525. If MSI-X capability is disabled:
  526. Set the lower bit of the ISR Status field for the device.
  527. Send the appropriate PCI interrupt for the device.
  528. If MSI-X capability is enabled:
  529. Request the appropriate MSI-X interrupt message for the
  530. device, Queue Vector field sets the MSI-X Table entry
  531. number.
  532. If Queue Vector field value is NO_VECTOR, no interrupt
  533. message is requested for this event.
  534. The guest interrupt handler should:
  535. If MSI-X capability is disabled: read the ISR Status field,
  536. which will reset it to zero. If the lower bit is zero, the
  537. interrupt was not for this device. Otherwise, the guest driver
  538. should look through the used rings of each virtqueue for the
  539. device, to see if any progress has been made by the device
  540. which requires servicing.
  541. If MSI-X capability is enabled: look through the used rings of
  542. each virtqueue mapped to the specific MSI-X vector for the
  543. device, to see if any progress has been made by the device
  544. which requires servicing.
  545. For each ring, guest should then disable interrupts by writing
  546. VRING_AVAIL_F_NO_INTERRUPT flag in avail structure, if required.
  547. It can then process used ring entries finally enabling interrupts
  548. by clearing the VRING_AVAIL_F_NO_INTERRUPT flag or updating the
  549. EVENT_IDX field in the available structure, Guest should then
  550. execute a memory barrier, and then recheck the ring empty
  551. condition. This is necessary to handle the case where, after the
  552. last check and before enabling interrupts, an interrupt has been
  553. suppressed by the device:
  554. vring_disable_interrupts(vq);
  555. for (;;) {
  556. if (vq->last_seen_used != vring->used.idx) {
  557. vring_enable_interrupts(vq);
  558. mb();
  559. if (vq->last_seen_used != vring->used.idx)
  560. break;
  561. }
  562. struct vring_used_elem *e =
  563. vring.used->ring[vq->last_seen_used%vsz];
  564. process_buffer(e);
  565. vq->last_seen_used++;
  566. }
  567. Dealing With Configuration Changes<sub:Dealing-With-Configuration>
  568. Some virtio PCI devices can change the device configuration
  569. state, as reflected in the virtio header in the PCI configuration
  570. space. In this case:
  571. If MSI-X capability is disabled: an interrupt is delivered and
  572. the second highest bit is set in the ISR Status field to
  573. indicate that the driver should re-examine the configuration
  574. space.Note that a single interrupt can indicate both that one
  575. or more virtqueue has been used and that the configuration
  576. space has changed: even if the config bit is set, virtqueues
  577. must be scanned.
  578. If MSI-X capability is enabled: an interrupt message is
  579. requested. The Configuration Vector field sets the MSI-X Table
  580. entry number to use. If Configuration Vector field value is
  581. NO_VECTOR, no interrupt message is requested for this event.
  582. Creating New Device Types
  583. Various considerations are necessary when creating a new device
  584. type:
  585. How Many Virtqueues?
  586. It is possible that a very simple device will operate entirely
  587. through its configuration space, but most will need at least one
  588. virtqueue in which it will place requests. A device with both
  589. input and output (eg. console and network devices described here)
  590. need two queues: one which the driver fills with buffers to
  591. receive input, and one which the driver places buffers to
  592. transmit output.
  593. What Configuration Space Layout?
  594. Configuration space is generally used for rarely-changing or
  595. initialization-time parameters. But it is a limited resource, so
  596. it might be better to use a virtqueue to update configuration
  597. information (the network device does this for filtering,
  598. otherwise the table in the config space could potentially be very
  599. large).
  600. Note that this space is generally the guest's native endian,
  601. rather than PCI's little-endian.
  602. What Device Number?
  603. Currently device numbers are assigned quite freely: a simple
  604. request mail to the author of this document or the Linux
  605. virtualization mailing list[footnote:
  606. https://lists.linux-foundation.org/mailman/listinfo/virtualization
  607. ] will be sufficient to secure a unique one.
  608. Meanwhile for experimental drivers, use 65535 and work backwards.
  609. How many MSI-X vectors?
  610. Using the optional MSI-X capability devices can speed up
  611. interrupt processing by removing the need to read ISR Status
  612. register by guest driver (which might be an expensive operation),
  613. reducing interrupt sharing between devices and queues within the
  614. device, and handling interrupts from multiple CPUs. However, some
  615. systems impose a limit (which might be as low as 256) on the
  616. total number of MSI-X vectors that can be allocated to all
  617. devices. Devices and/or device drivers should take this into
  618. account, limiting the number of vectors used unless the device is
  619. expected to cause a high volume of interrupts. Devices can
  620. control the number of vectors used by limiting the MSI-X Table
  621. Size or not presenting MSI-X capability in PCI configuration
  622. space. Drivers can control this by mapping events to as small
  623. number of vectors as possible, or disabling MSI-X capability
  624. altogether.
  625. Message Framing
  626. The descriptors used for a buffer should not effect the semantics
  627. of the message, except for the total length of the buffer. For
  628. example, a network buffer consists of a 10 byte header followed
  629. by the network packet. Whether this is presented in the ring
  630. descriptor chain as (say) a 10 byte buffer and a 1514 byte
  631. buffer, or a single 1524 byte buffer, or even three buffers,
  632. should have no effect.
  633. In particular, no implementation should use the descriptor
  634. boundaries to determine the size of any header in a request.[footnote:
  635. The current qemu device implementations mistakenly insist that
  636. the first descriptor cover the header in these cases exactly, so
  637. a cautious driver should arrange it so.
  638. ]
  639. Device Improvements
  640. Any change to configuration space, or new virtqueues, or
  641. behavioural changes, should be indicated by negotiation of a new
  642. feature bit. This establishes clarity[footnote:
  643. Even if it does mean documenting design or implementation
  644. mistakes!
  645. ] and avoids future expansion problems.
  646. Clusters of functionality which are always implemented together
  647. can use a single bit, but if one feature makes sense without the
  648. others they should not be gratuitously grouped together to
  649. conserve feature bits. We can always extend the spec when the
  650. first person needs more than 24 feature bits for their device.
  651. [LaTeX Command: printnomenclature]
  652. Appendix A: virtio_ring.h
  653. #ifndef VIRTIO_RING_H
  654. #define VIRTIO_RING_H
  655. /* An interface for efficient virtio implementation.
  656. *
  657. * This header is BSD licensed so anyone can use the definitions
  658. * to implement compatible drivers/servers.
  659. *
  660. * Copyright 2007, 2009, IBM Corporation
  661. * Copyright 2011, Red Hat, Inc
  662. * All rights reserved.
  663. *
  664. * Redistribution and use in source and binary forms, with or
  665. without
  666. * modification, are permitted provided that the following
  667. conditions
  668. * are met:
  669. * 1. Redistributions of source code must retain the above
  670. copyright
  671. * notice, this list of conditions and the following
  672. disclaimer.
  673. * 2. Redistributions in binary form must reproduce the above
  674. copyright
  675. * notice, this list of conditions and the following
  676. disclaimer in the
  677. * documentation and/or other materials provided with the
  678. distribution.
  679. * 3. Neither the name of IBM nor the names of its contributors
  680. * may be used to endorse or promote products derived from
  681. this software
  682. * without specific prior written permission.
  683. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  684. CONTRIBUTORS ``AS IS'' AND
  685. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
  686. TO, THE
  687. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
  688. PARTICULAR PURPOSE
  689. * ARE DISCLAIMED. IN NO EVENT SHALL IBM OR CONTRIBUTORS BE
  690. LIABLE
  691. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  692. CONSEQUENTIAL
  693. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  694. SUBSTITUTE GOODS
  695. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  696. INTERRUPTION)
  697. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  698. CONTRACT, STRICT
  699. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
  700. IN ANY WAY
  701. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  702. POSSIBILITY OF
  703. * SUCH DAMAGE.
  704. */
  705. /* This marks a buffer as continuing via the next field. */
  706. #define VRING_DESC_F_NEXT 1
  707. /* This marks a buffer as write-only (otherwise read-only). */
  708. #define VRING_DESC_F_WRITE 2
  709. /* The Host uses this in used->flags to advise the Guest: don't
  710. kick me
  711. * when you add a buffer. It's unreliable, so it's simply an
  712. * optimization. Guest will still kick if it's out of buffers.
  713. */
  714. #define VRING_USED_F_NO_NOTIFY 1
  715. /* The Guest uses this in avail->flags to advise the Host: don't
  716. * interrupt me when you consume a buffer. It's unreliable, so
  717. it's
  718. * simply an optimization. */
  719. #define VRING_AVAIL_F_NO_INTERRUPT 1
  720. /* Virtio ring descriptors: 16 bytes.
  721. * These can chain together via "next". */
  722. struct vring_desc {
  723. /* Address (guest-physical). */
  724. uint64_t addr;
  725. /* Length. */
  726. uint32_t len;
  727. /* The flags as indicated above. */
  728. uint16_t flags;
  729. /* We chain unused descriptors via this, too */
  730. uint16_t next;
  731. };
  732. struct vring_avail {
  733. uint16_t flags;
  734. uint16_t idx;
  735. uint16_t ring[];
  736. uint16_t used_event;
  737. };
  738. /* u32 is used here for ids for padding reasons. */
  739. struct vring_used_elem {
  740. /* Index of start of used descriptor chain. */
  741. uint32_t id;
  742. /* Total length of the descriptor chain which was written
  743. to. */
  744. uint32_t len;
  745. };
  746. struct vring_used {
  747. uint16_t flags;
  748. uint16_t idx;
  749. struct vring_used_elem ring[];
  750. uint16_t avail_event;
  751. };
  752. struct vring {
  753. unsigned int num;
  754. struct vring_desc *desc;
  755. struct vring_avail *avail;
  756. struct vring_used *used;
  757. };
  758. /* The standard layout for the ring is a continuous chunk of
  759. memory which
  760. * looks like this. We assume num is a power of 2.
  761. *
  762. * struct vring {
  763. * // The actual descriptors (16 bytes each)
  764. * struct vring_desc desc[num];
  765. *
  766. * // A ring of available descriptor heads with free-running
  767. index.
  768. * __u16 avail_flags;
  769. * __u16 avail_idx;
  770. * __u16 available[num];
  771. *
  772. * // Padding to the next align boundary.
  773. * char pad[];
  774. *
  775. * // A ring of used descriptor heads with free-running
  776. index.
  777. * __u16 used_flags;
  778. * __u16 EVENT_IDX;
  779. * struct vring_used_elem used[num];
  780. * };
  781. * Note: for virtio PCI, align is 4096.
  782. */
  783. static inline void vring_init(struct vring *vr, unsigned int num,
  784. void *p,
  785. unsigned long align)
  786. {
  787. vr->num = num;
  788. vr->desc = p;
  789. vr->avail = p + num*sizeof(struct vring_desc);
  790. vr->used = (void *)(((unsigned long)&vr->avail->ring[num]
  791. + align-1)
  792. & ~(align - 1));
  793. }
  794. static inline unsigned vring_size(unsigned int num, unsigned long
  795. align)
  796. {
  797. return ((sizeof(struct vring_desc)*num +
  798. sizeof(uint16_t)*(2+num)
  799. + align - 1) & ~(align - 1))
  800. + sizeof(uint16_t)*3 + sizeof(struct
  801. vring_used_elem)*num;
  802. }
  803. static inline int vring_need_event(uint16_t event_idx, uint16_t
  804. new_idx, uint16_t old_idx)
  805. {
  806. return (uint16_t)(new_idx - event_idx - 1) <
  807. (uint16_t)(new_idx - old_idx);
  808. }
  809. #endif /* VIRTIO_RING_H */
  810. <cha:Reserved-Feature-Bits>Appendix B: Reserved Feature Bits
  811. Currently there are five device-independent feature bits defined:
  812. VIRTIO_F_NOTIFY_ON_EMPTY (24) Negotiating this feature
  813. indicates that the driver wants an interrupt if the device runs
  814. out of available descriptors on a virtqueue, even though
  815. interrupts are suppressed using the VRING_AVAIL_F_NO_INTERRUPT
  816. flag or the used_event field. An example of this is the
  817. networking driver: it doesn't need to know every time a packet
  818. is transmitted, but it does need to free the transmitted
  819. packets a finite time after they are transmitted. It can avoid
  820. using a timer if the device interrupts it when all the packets
  821. are transmitted.
  822. VIRTIO_F_RING_INDIRECT_DESC (28) Negotiating this feature
  823. indicates that the driver can use descriptors with the
  824. VRING_DESC_F_INDIRECT flag set, as described in [sub:Indirect-Descriptors]
  825. .
  826. VIRTIO_F_RING_EVENT_IDX(29) This feature enables the used_event
  827. and the avail_event fields. If set, it indicates that the
  828. device should ignore the flags field in the available ring
  829. structure. Instead, the used_event field in this structure is
  830. used by guest to suppress device interrupts. Further, the
  831. driver should ignore the flags field in the used ring
  832. structure. Instead, the avail_event field in this structure is
  833. used by the device to suppress notifications. If unset, the
  834. driver should ignore the used_event field; the device should
  835. ignore the avail_event field; the flags field is used
  836. Appendix C: Network Device
  837. The virtio network device is a virtual ethernet card, and is the
  838. most complex of the devices supported so far by virtio. It has
  839. enhanced rapidly and demonstrates clearly how support for new
  840. features should be added to an existing device. Empty buffers are
  841. placed in one virtqueue for receiving packets, and outgoing
  842. packets are enqueued into another for transmission in that order.
  843. A third command queue is used to control advanced filtering
  844. features.
  845. Configuration
  846. Subsystem Device ID 1
  847. Virtqueues 0:receiveq. 1:transmitq. 2:controlq[footnote:
  848. Only if VIRTIO_NET_F_CTRL_VQ set
  849. ]
  850. Feature bits
  851. VIRTIO_NET_F_CSUM (0) Device handles packets with partial
  852. checksum
  853. VIRTIO_NET_F_GUEST_CSUM (1) Guest handles packets with partial
  854. checksum
  855. VIRTIO_NET_F_MAC (5) Device has given MAC address.
  856. VIRTIO_NET_F_GSO (6) (Deprecated) device handles packets with
  857. any GSO type.[footnote:
  858. It was supposed to indicate segmentation offload support, but
  859. upon further investigation it became clear that multiple bits
  860. were required.
  861. ]
  862. VIRTIO_NET_F_GUEST_TSO4 (7) Guest can receive TSOv4.
  863. VIRTIO_NET_F_GUEST_TSO6 (8) Guest can receive TSOv6.
  864. VIRTIO_NET_F_GUEST_ECN (9) Guest can receive TSO with ECN.
  865. VIRTIO_NET_F_GUEST_UFO (10) Guest can receive UFO.
  866. VIRTIO_NET_F_HOST_TSO4 (11) Device can receive TSOv4.
  867. VIRTIO_NET_F_HOST_TSO6 (12) Device can receive TSOv6.
  868. VIRTIO_NET_F_HOST_ECN (13) Device can receive TSO with ECN.
  869. VIRTIO_NET_F_HOST_UFO (14) Device can receive UFO.
  870. VIRTIO_NET_F_MRG_RXBUF (15) Guest can merge receive buffers.
  871. VIRTIO_NET_F_STATUS (16) Configuration status field is
  872. available.
  873. VIRTIO_NET_F_CTRL_VQ (17) Control channel is available.
  874. VIRTIO_NET_F_CTRL_RX (18) Control channel RX mode support.
  875. VIRTIO_NET_F_CTRL_VLAN (19) Control channel VLAN filtering.
  876. VIRTIO_NET_F_GUEST_ANNOUNCE(21) Guest can send gratuitous
  877. packets.
  878. Device configuration layout Two configuration fields are
  879. currently defined. The mac address field always exists (though
  880. is only valid if VIRTIO_NET_F_MAC is set), and the status field
  881. only exists if VIRTIO_NET_F_STATUS is set. Two read-only bits
  882. are currently defined for the status field:
  883. VIRTIO_NET_S_LINK_UP and VIRTIO_NET_S_ANNOUNCE. #define VIRTIO_NET_S_LINK_UP 1
  884. #define VIRTIO_NET_S_ANNOUNCE 2
  885. struct virtio_net_config {
  886. u8 mac[6];
  887. u16 status;
  888. };
  889. Device Initialization
  890. The initialization routine should identify the receive and
  891. transmission virtqueues.
  892. If the VIRTIO_NET_F_MAC feature bit is set, the configuration
  893. space “mac” entry indicates the “physical” address of the the
  894. network card, otherwise a private MAC address should be
  895. assigned. All guests are expected to negotiate this feature if
  896. it is set.
  897. If the VIRTIO_NET_F_CTRL_VQ feature bit is negotiated, identify
  898. the control virtqueue.
  899. If the VIRTIO_NET_F_STATUS feature bit is negotiated, the link
  900. status can be read from the bottom bit of the “status” config
  901. field. Otherwise, the link should be assumed active.
  902. The receive virtqueue should be filled with receive buffers.
  903. This is described in detail below in “Setting Up Receive
  904. Buffers”.
  905. A driver can indicate that it will generate checksumless
  906. packets by negotating the VIRTIO_NET_F_CSUM feature. This “
  907. checksum offload” is a common feature on modern network cards.
  908. If that feature is negotiated[footnote:
  909. ie. VIRTIO_NET_F_HOST_TSO* and VIRTIO_NET_F_HOST_UFO are
  910. dependent on VIRTIO_NET_F_CSUM; a dvice which offers the offload
  911. features must offer the checksum feature, and a driver which
  912. accepts the offload features must accept the checksum feature.
  913. Similar logic applies to the VIRTIO_NET_F_GUEST_TSO4 features
  914. depending on VIRTIO_NET_F_GUEST_CSUM.
  915. ], a driver can use TCP or UDP segmentation offload by
  916. negotiating the VIRTIO_NET_F_HOST_TSO4 (IPv4 TCP),
  917. VIRTIO_NET_F_HOST_TSO6 (IPv6 TCP) and VIRTIO_NET_F_HOST_UFO
  918. (UDP fragmentation) features. It should not send TCP packets
  919. requiring segmentation offload which have the Explicit
  920. Congestion Notification bit set, unless the
  921. VIRTIO_NET_F_HOST_ECN feature is negotiated.[footnote:
  922. This is a common restriction in real, older network cards.
  923. ]
  924. The converse features are also available: a driver can save the
  925. virtual device some work by negotiating these features.[footnote:
  926. For example, a network packet transported between two guests on
  927. the same system may not require checksumming at all, nor
  928. segmentation, if both guests are amenable.
  929. ] The VIRTIO_NET_F_GUEST_CSUM feature indicates that partially
  930. checksummed packets can be received, and if it can do that then
  931. the VIRTIO_NET_F_GUEST_TSO4, VIRTIO_NET_F_GUEST_TSO6,
  932. VIRTIO_NET_F_GUEST_UFO and VIRTIO_NET_F_GUEST_ECN are the input
  933. equivalents of the features described above. See “Receiving
  934. Packets” below.
  935. Device Operation
  936. Packets are transmitted by placing them in the transmitq, and
  937. buffers for incoming packets are placed in the receiveq. In each
  938. case, the packet itself is preceeded by a header:
  939. struct virtio_net_hdr {
  940. #define VIRTIO_NET_HDR_F_NEEDS_CSUM 1
  941. u8 flags;
  942. #define VIRTIO_NET_HDR_GSO_NONE 0
  943. #define VIRTIO_NET_HDR_GSO_TCPV4 1
  944. #define VIRTIO_NET_HDR_GSO_UDP 3
  945. #define VIRTIO_NET_HDR_GSO_TCPV6 4
  946. #define VIRTIO_NET_HDR_GSO_ECN 0x80
  947. u8 gso_type;
  948. u16 hdr_len;
  949. u16 gso_size;
  950. u16 csum_start;
  951. u16 csum_offset;
  952. /* Only if VIRTIO_NET_F_MRG_RXBUF: */
  953. u16 num_buffers
  954. };
  955. The controlq is used to control device features such as
  956. filtering.
  957. Packet Transmission
  958. Transmitting a single packet is simple, but varies depending on
  959. the different features the driver negotiated.
  960. If the driver negotiated VIRTIO_NET_F_CSUM, and the packet has
  961. not been fully checksummed, then the virtio_net_hdr's fields
  962. are set as follows. Otherwise, the packet must be fully
  963. checksummed, and flags is zero.
  964. flags has the VIRTIO_NET_HDR_F_NEEDS_CSUM set,
  965. <ite:csum_start-is-set>csum_start is set to the offset within
  966. the packet to begin checksumming, and
  967. csum_offset indicates how many bytes after the csum_start the
  968. new (16 bit ones' complement) checksum should be placed.[footnote:
  969. For example, consider a partially checksummed TCP (IPv4) packet.
  970. It will have a 14 byte ethernet header and 20 byte IP header
  971. followed by the TCP header (with the TCP checksum field 16 bytes
  972. into that header). csum_start will be 14+20 = 34 (the TCP
  973. checksum includes the header), and csum_offset will be 16. The
  974. value in the TCP checksum field should be initialized to the sum
  975. of the TCP pseudo header, so that replacing it by the ones'
  976. complement checksum of the TCP header and body will give the
  977. correct result.
  978. ]
  979. <enu:If-the-driver>If the driver negotiated
  980. VIRTIO_NET_F_HOST_TSO4, TSO6 or UFO, and the packet requires
  981. TCP segmentation or UDP fragmentation, then the “gso_type”
  982. field is set to VIRTIO_NET_HDR_GSO_TCPV4, TCPV6 or UDP.
  983. (Otherwise, it is set to VIRTIO_NET_HDR_GSO_NONE). In this
  984. case, packets larger than 1514 bytes can be transmitted: the
  985. metadata indicates how to replicate the packet header to cut it
  986. into smaller packets. The other gso fields are set:
  987. hdr_len is a hint to the device as to how much of the header
  988. needs to be kept to copy into each packet, usually set to the
  989. length of the headers, including the transport header.[footnote:
  990. Due to various bugs in implementations, this field is not useful
  991. as a guarantee of the transport header size.
  992. ]
  993. gso_size is the maximum size of each packet beyond that header
  994. (ie. MSS).
  995. If the driver negotiated the VIRTIO_NET_F_HOST_ECN feature, the
  996. VIRTIO_NET_HDR_GSO_ECN bit may be set in “gso_type” as well,
  997. indicating that the TCP packet has the ECN bit set.[footnote:
  998. This case is not handled by some older hardware, so is called out
  999. specifically in the protocol.
  1000. ]
  1001. If the driver negotiated the VIRTIO_NET_F_MRG_RXBUF feature,
  1002. the num_buffers field is set to zero.
  1003. The header and packet are added as one output buffer to the
  1004. transmitq, and the device is notified of the new entry (see [sub:Notifying-The-Device]
  1005. ).[footnote:
  1006. Note that the header will be two bytes longer for the
  1007. VIRTIO_NET_F_MRG_RXBUF case.
  1008. ]
  1009. Packet Transmission Interrupt
  1010. Often a driver will suppress transmission interrupts using the
  1011. VRING_AVAIL_F_NO_INTERRUPT flag (see [sub:Receiving-Used-Buffers]
  1012. ) and check for used packets in the transmit path of following
  1013. packets. However, it will still receive interrupts if the
  1014. VIRTIO_F_NOTIFY_ON_EMPTY feature is negotiated, indicating that
  1015. the transmission queue is completely emptied.
  1016. The normal behavior in this interrupt handler is to retrieve and
  1017. new descriptors from the used ring and free the corresponding
  1018. headers and packets.
  1019. Setting Up Receive Buffers
  1020. It is generally a good idea to keep the receive virtqueue as
  1021. fully populated as possible: if it runs out, network performance
  1022. will suffer.
  1023. If the VIRTIO_NET_F_GUEST_TSO4, VIRTIO_NET_F_GUEST_TSO6 or
  1024. VIRTIO_NET_F_GUEST_UFO features are used, the Guest will need to
  1025. accept packets of up to 65550 bytes long (the maximum size of a
  1026. TCP or UDP packet, plus the 14 byte ethernet header), otherwise
  1027. 1514 bytes. So unless VIRTIO_NET_F_MRG_RXBUF is negotiated, every
  1028. buffer in the receive queue needs to be at least this length [footnote:
  1029. Obviously each one can be split across multiple descriptor
  1030. elements.
  1031. ].
  1032. If VIRTIO_NET_F_MRG_RXBUF is negotiated, each buffer must be at
  1033. least the size of the struct virtio_net_hdr.
  1034. Packet Receive Interrupt
  1035. When a packet is copied into a buffer in the receiveq, the
  1036. optimal path is to disable further interrupts for the receiveq
  1037. (see [sub:Receiving-Used-Buffers]) and process packets until no
  1038. more are found, then re-enable them.
  1039. Processing packet involves:
  1040. If the driver negotiated the VIRTIO_NET_F_MRG_RXBUF feature,
  1041. then the “num_buffers” field indicates how many descriptors
  1042. this packet is spread over (including this one). This allows
  1043. receipt of large packets without having to allocate large
  1044. buffers. In this case, there will be at least “num_buffers” in
  1045. the used ring, and they should be chained together to form a
  1046. single packet. The other buffers will not begin with a struct
  1047. virtio_net_hdr.
  1048. If the VIRTIO_NET_F_MRG_RXBUF feature was not negotiated, or
  1049. the “num_buffers” field is one, then the entire packet will be
  1050. contained within this buffer, immediately following the struct
  1051. virtio_net_hdr.
  1052. If the VIRTIO_NET_F_GUEST_CSUM feature was negotiated, the
  1053. VIRTIO_NET_HDR_F_NEEDS_CSUM bit in the “flags” field may be
  1054. set: if so, the checksum on the packet is incomplete and the “
  1055. csum_start” and “csum_offset” fields indicate how to calculate
  1056. it (see [ite:csum_start-is-set]).
  1057. If the VIRTIO_NET_F_GUEST_TSO4, TSO6 or UFO options were
  1058. negotiated, then the “gso_type” may be something other than
  1059. VIRTIO_NET_HDR_GSO_NONE, and the “gso_size” field indicates the
  1060. desired MSS (see [enu:If-the-driver]).
  1061. Control Virtqueue
  1062. The driver uses the control virtqueue (if VIRTIO_NET_F_VTRL_VQ is
  1063. negotiated) to send commands to manipulate various features of
  1064. the device which would not easily map into the configuration
  1065. space.
  1066. All commands are of the following form:
  1067. struct virtio_net_ctrl {
  1068. u8 class;
  1069. u8 command;
  1070. u8 command-specific-data[];
  1071. u8 ack;
  1072. };
  1073. /* ack values */
  1074. #define VIRTIO_NET_OK 0
  1075. #define VIRTIO_NET_ERR 1
  1076. The class, command and command-specific-data are set by the
  1077. driver, and the device sets the ack byte. There is little it can
  1078. do except issue a diagnostic if the ack byte is not
  1079. VIRTIO_NET_OK.
  1080. Packet Receive Filtering
  1081. If the VIRTIO_NET_F_CTRL_RX feature is negotiated, the driver can
  1082. send control commands for promiscuous mode, multicast receiving,
  1083. and filtering of MAC addresses.
  1084. Note that in general, these commands are best-effort: unwanted
  1085. packets may still arrive.
  1086. Setting Promiscuous Mode
  1087. #define VIRTIO_NET_CTRL_RX 0
  1088. #define VIRTIO_NET_CTRL_RX_PROMISC 0
  1089. #define VIRTIO_NET_CTRL_RX_ALLMULTI 1
  1090. The class VIRTIO_NET_CTRL_RX has two commands:
  1091. VIRTIO_NET_CTRL_RX_PROMISC turns promiscuous mode on and off, and
  1092. VIRTIO_NET_CTRL_RX_ALLMULTI turns all-multicast receive on and
  1093. off. The command-specific-data is one byte containing 0 (off) or
  1094. 1 (on).
  1095. Setting MAC Address Filtering
  1096. struct virtio_net_ctrl_mac {
  1097. u32 entries;
  1098. u8 macs[entries][ETH_ALEN];
  1099. };
  1100. #define VIRTIO_NET_CTRL_MAC 1
  1101. #define VIRTIO_NET_CTRL_MAC_TABLE_SET 0
  1102. The device can filter incoming packets by any number of
  1103. destination MAC addresses.[footnote:
  1104. Since there are no guarentees, it can use a hash filter
  1105. orsilently switch to allmulti or promiscuous mode if it is given
  1106. too many addresses.
  1107. ] This table is set using the class VIRTIO_NET_CTRL_MAC and the
  1108. command VIRTIO_NET_CTRL_MAC_TABLE_SET. The command-specific-data
  1109. is two variable length tables of 6-byte MAC addresses. The first
  1110. table contains unicast addresses, and the second contains
  1111. multicast addresses.
  1112. VLAN Filtering
  1113. If the driver negotiates the VIRTION_NET_F_CTRL_VLAN feature, it
  1114. can control a VLAN filter table in the device.
  1115. #define VIRTIO_NET_CTRL_VLAN 2
  1116. #define VIRTIO_NET_CTRL_VLAN_ADD 0
  1117. #define VIRTIO_NET_CTRL_VLAN_DEL 1
  1118. Both the VIRTIO_NET_CTRL_VLAN_ADD and VIRTIO_NET_CTRL_VLAN_DEL
  1119. command take a 16-bit VLAN id as the command-specific-data.
  1120. Gratuitous Packet Sending
  1121. If the driver negotiates the VIRTIO_NET_F_GUEST_ANNOUNCE (depends
  1122. on VIRTIO_NET_F_CTRL_VQ), it can ask the guest to send gratuitous
  1123. packets; this is usually done after the guest has been physically
  1124. migrated, and needs to announce its presence on the new network
  1125. links. (As hypervisor does not have the knowledge of guest
  1126. network configuration (eg. tagged vlan) it is simplest to prod
  1127. the guest in this way).
  1128. #define VIRTIO_NET_CTRL_ANNOUNCE 3
  1129. #define VIRTIO_NET_CTRL_ANNOUNCE_ACK 0
  1130. The Guest needs to check VIRTIO_NET_S_ANNOUNCE bit in status
  1131. field when it notices the changes of device configuration. The
  1132. command VIRTIO_NET_CTRL_ANNOUNCE_ACK is used to indicate that
  1133. driver has recevied the notification and device would clear the
  1134. VIRTIO_NET_S_ANNOUNCE bit in the status filed after it received
  1135. this command.
  1136. Processing this notification involves:
  1137. Sending the gratuitous packets or marking there are pending
  1138. gratuitous packets to be sent and letting deferred routine to
  1139. send them.
  1140. Sending VIRTIO_NET_CTRL_ANNOUNCE_ACK command through control
  1141. vq.
  1142. .
  1143. Appendix D: Block Device
  1144. The virtio block device is a simple virtual block device (ie.
  1145. disk). Read and write requests (and other exotic requests) are
  1146. placed in the queue, and serviced (probably out of order) by the
  1147. device except where noted.
  1148. Configuration
  1149. Subsystem Device ID 2
  1150. Virtqueues 0:requestq.
  1151. Feature bits
  1152. VIRTIO_BLK_F_BARRIER (0) Host supports request barriers.
  1153. VIRTIO_BLK_F_SIZE_MAX (1) Maximum size of any single segment is
  1154. in “size_max”.
  1155. VIRTIO_BLK_F_SEG_MAX (2) Maximum number of segments in a
  1156. request is in “seg_max”.
  1157. VIRTIO_BLK_F_GEOMETRY (4) Disk-style geometry specified in “
  1158. geometry”.
  1159. VIRTIO_BLK_F_RO (5) Device is read-only.
  1160. VIRTIO_BLK_F_BLK_SIZE (6) Block size of disk is in “blk_size”.
  1161. VIRTIO_BLK_F_SCSI (7) Device supports scsi packet commands.
  1162. VIRTIO_BLK_F_FLUSH (9) Cache flush command support.
  1163. Device configuration layout The capacity of the device
  1164. (expressed in 512-byte sectors) is always present. The
  1165. availability of the others all depend on various feature bits
  1166. as indicated above. struct virtio_blk_config {
  1167. u64 capacity;
  1168. u32 size_max;
  1169. u32 seg_max;
  1170. struct virtio_blk_geometry {
  1171. u16 cylinders;
  1172. u8 heads;
  1173. u8 sectors;
  1174. } geometry;
  1175. u32 blk_size;
  1176. };
  1177. Device Initialization
  1178. The device size should be read from the “capacity”
  1179. configuration field. No requests should be submitted which goes
  1180. beyond this limit.
  1181. If the VIRTIO_BLK_F_BLK_SIZE feature is negotiated, the
  1182. blk_size field can be read to determine the optimal sector size
  1183. for the driver to use. This does not effect the units used in
  1184. the protocol (always 512 bytes), but awareness of the correct
  1185. value can effect performance.
  1186. If the VIRTIO_BLK_F_RO feature is set by the device, any write
  1187. requests will fail.
  1188. Device Operation
  1189. The driver queues requests to the virtqueue, and they are used by
  1190. the device (not necessarily in order). Each request is of form:
  1191. struct virtio_blk_req {
  1192. u32 type;
  1193. u32 ioprio;
  1194. u64 sector;
  1195. char data[][512];
  1196. u8 status;
  1197. };
  1198. If the device has VIRTIO_BLK_F_SCSI feature, it can also support
  1199. scsi packet command requests, each of these requests is of form:struct virtio_scsi_pc_req {
  1200. u32 type;
  1201. u32 ioprio;
  1202. u64 sector;
  1203. char cmd[];
  1204. char data[][512];
  1205. #define SCSI_SENSE_BUFFERSIZE 96
  1206. u8 sense[SCSI_SENSE_BUFFERSIZE];
  1207. u32 errors;
  1208. u32 data_len;
  1209. u32 sense_len;
  1210. u32 residual;
  1211. u8 status;
  1212. };
  1213. The type of the request is either a read (VIRTIO_BLK_T_IN), a
  1214. write (VIRTIO_BLK_T_OUT), a scsi packet command
  1215. (VIRTIO_BLK_T_SCSI_CMD or VIRTIO_BLK_T_SCSI_CMD_OUT[footnote:
  1216. the SCSI_CMD and SCSI_CMD_OUT types are equivalent, the device
  1217. does not distinguish between them
  1218. ]) or a flush (VIRTIO_BLK_T_FLUSH or VIRTIO_BLK_T_FLUSH_OUT[footnote:
  1219. the FLUSH and FLUSH_OUT types are equivalent, the device does not
  1220. distinguish between them
  1221. ]). If the device has VIRTIO_BLK_F_BARRIER feature the high bit
  1222. (VIRTIO_BLK_T_BARRIER) indicates that this request acts as a
  1223. barrier and that all preceeding requests must be complete before
  1224. this one, and all following requests must not be started until
  1225. this is complete. Note that a barrier does not flush caches in
  1226. the underlying backend device in host, and thus does not serve as
  1227. data consistency guarantee. Driver must use FLUSH request to
  1228. flush the host cache.
  1229. #define VIRTIO_BLK_T_IN 0
  1230. #define VIRTIO_BLK_T_OUT 1
  1231. #define VIRTIO_BLK_T_SCSI_CMD 2
  1232. #define VIRTIO_BLK_T_SCSI_CMD_OUT 3
  1233. #define VIRTIO_BLK_T_FLUSH 4
  1234. #define VIRTIO_BLK_T_FLUSH_OUT 5
  1235. #define VIRTIO_BLK_T_BARRIER 0x80000000
  1236. The ioprio field is a hint about the relative priorities of
  1237. requests to the device: higher numbers indicate more important
  1238. requests.
  1239. The sector number indicates the offset (multiplied by 512) where
  1240. the read or write is to occur. This field is unused and set to 0
  1241. for scsi packet commands and for flush commands.
  1242. The cmd field is only present for scsi packet command requests,
  1243. and indicates the command to perform. This field must reside in a
  1244. single, separate read-only buffer; command length can be derived
  1245. from the length of this buffer.
  1246. Note that these first three (four for scsi packet commands)
  1247. fields are always read-only: the data field is either read-only
  1248. or write-only, depending on the request. The size of the read or
  1249. write can be derived from the total size of the request buffers.
  1250. The sense field is only present for scsi packet command requests,
  1251. and indicates the buffer for scsi sense data.
  1252. The data_len field is only present for scsi packet command
  1253. requests, this field is deprecated, and should be ignored by the
  1254. driver. Historically, devices copied data length there.
  1255. The sense_len field is only present for scsi packet command
  1256. requests and indicates the number of bytes actually written to
  1257. the sense buffer.
  1258. The residual field is only present for scsi packet command
  1259. requests and indicates the residual size, calculated as data
  1260. length - number of bytes actually transferred.
  1261. The final status byte is written by the device: either
  1262. VIRTIO_BLK_S_OK for success, VIRTIO_BLK_S_IOERR for host or guest
  1263. error or VIRTIO_BLK_S_UNSUPP for a request unsupported by host:#define VIRTIO_BLK_S_OK 0
  1264. #define VIRTIO_BLK_S_IOERR 1
  1265. #define VIRTIO_BLK_S_UNSUPP 2
  1266. Historically, devices assumed that the fields type, ioprio and
  1267. sector reside in a single, separate read-only buffer; the fields
  1268. errors, data_len, sense_len and residual reside in a single,
  1269. separate write-only buffer; the sense field in a separate
  1270. write-only buffer of size 96 bytes, by itself; the fields errors,
  1271. data_len, sense_len and residual in a single write-only buffer;
  1272. and the status field is a separate read-only buffer of size 1
  1273. byte, by itself.
  1274. Appendix E: Console Device
  1275. The virtio console device is a simple device for data input and
  1276. output. A device may have one or more ports. Each port has a pair
  1277. of input and output virtqueues. Moreover, a device has a pair of
  1278. control IO virtqueues. The control virtqueues are used to
  1279. communicate information between the device and the driver about
  1280. ports being opened and closed on either side of the connection,
  1281. indication from the host about whether a particular port is a
  1282. console port, adding new ports, port hot-plug/unplug, etc., and
  1283. indication from the guest about whether a port or a device was
  1284. successfully added, port open/close, etc.. For data IO, one or
  1285. more empty buffers are placed in the receive queue for incoming
  1286. data and outgoing characters are placed in the transmit queue.
  1287. Configuration
  1288. Subsystem Device ID 3
  1289. Virtqueues 0:receiveq(port0). 1:transmitq(port0), 2:control
  1290. receiveq[footnote:
  1291. Ports 2 onwards only if VIRTIO_CONSOLE_F_MULTIPORT is set
  1292. ], 3:control transmitq, 4:receiveq(port1), 5:transmitq(port1),
  1293. ...
  1294. Feature bits
  1295. VIRTIO_CONSOLE_F_SIZE (0) Configuration cols and rows fields
  1296. are valid.
  1297. VIRTIO_CONSOLE_F_MULTIPORT(1) Device has support for multiple
  1298. ports; configuration fields nr_ports and max_nr_ports are
  1299. valid and control virtqueues will be used.
  1300. Device configuration layout The size of the console is supplied
  1301. in the configuration space if the VIRTIO_CONSOLE_F_SIZE feature
  1302. is set. Furthermore, if the VIRTIO_CONSOLE_F_MULTIPORT feature
  1303. is set, the maximum number of ports supported by the device can
  1304. be fetched.struct virtio_console_config {
  1305. u16 cols;
  1306. u16 rows;
  1307. u32 max_nr_ports;
  1308. };
  1309. Device Initialization
  1310. If the VIRTIO_CONSOLE_F_SIZE feature is negotiated, the driver
  1311. can read the console dimensions from the configuration fields.
  1312. If the VIRTIO_CONSOLE_F_MULTIPORT feature is negotiated, the
  1313. driver can spawn multiple ports, not all of which may be
  1314. attached to a console. Some could be generic ports. In this
  1315. case, the control virtqueues are enabled and according to the
  1316. max_nr_ports configuration-space value, the appropriate number
  1317. of virtqueues are created. A control message indicating the
  1318. driver is ready is sent to the host. The host can then send
  1319. control messages for adding new ports to the device. After
  1320. creating and initializing each port, a
  1321. VIRTIO_CONSOLE_PORT_READY control message is sent to the host
  1322. for that port so the host can let us know of any additional
  1323. configuration options set for that port.
  1324. The receiveq for each port is populated with one or more
  1325. receive buffers.
  1326. Device Operation
  1327. For output, a buffer containing the characters is placed in the
  1328. port's transmitq.[footnote:
  1329. Because this is high importance and low bandwidth, the current
  1330. Linux implementation polls for the buffer to be used, rather than
  1331. waiting for an interrupt, simplifying the implementation
  1332. significantly. However, for generic serial ports with the
  1333. O_NONBLOCK flag set, the polling limitation is relaxed and the
  1334. consumed buffers are freed upon the next write or poll call or
  1335. when a port is closed or hot-unplugged.
  1336. ]
  1337. When a buffer is used in the receiveq (signalled by an
  1338. interrupt), the contents is the input to the port associated
  1339. with the virtqueue for which the notification was received.
  1340. If the driver negotiated the VIRTIO_CONSOLE_F_SIZE feature, a
  1341. configuration change interrupt may occur. The updated size can
  1342. be read from the configuration fields.
  1343. If the driver negotiated the VIRTIO_CONSOLE_F_MULTIPORT
  1344. feature, active ports are announced by the host using the
  1345. VIRTIO_CONSOLE_PORT_ADD control message. The same message is
  1346. used for port hot-plug as well.
  1347. If the host specified a port `name', a sysfs attribute is
  1348. created with the name filled in, so that udev rules can be
  1349. written that can create a symlink from the port's name to the
  1350. char device for port discovery by applications in the guest.
  1351. Changes to ports' state are effected by control messages.
  1352. Appropriate action is taken on the port indicated in the
  1353. control message. The layout of the structure of the control
  1354. buffer and the events associated are:struct virtio_console_control {
  1355. uint32_t id; /* Port number */
  1356. uint16_t event; /* The kind of control event */
  1357. uint16_t value; /* Extra information for the event */
  1358. };
  1359. /* Some events for the internal messages (control packets) */
  1360. #define VIRTIO_CONSOLE_DEVICE_READY 0
  1361. #define VIRTIO_CONSOLE_PORT_ADD 1
  1362. #define VIRTIO_CONSOLE_PORT_REMOVE 2
  1363. #define VIRTIO_CONSOLE_PORT_READY 3
  1364. #define VIRTIO_CONSOLE_CONSOLE_PORT 4
  1365. #define VIRTIO_CONSOLE_RESIZE 5
  1366. #define VIRTIO_CONSOLE_PORT_OPEN 6
  1367. #define VIRTIO_CONSOLE_PORT_NAME 7
  1368. Appendix F: Entropy Device
  1369. The virtio entropy device supplies high-quality randomness for
  1370. guest use.
  1371. Configuration
  1372. Subsystem Device ID 4
  1373. Virtqueues 0:requestq.
  1374. Feature bits None currently defined
  1375. Device configuration layout None currently defined.
  1376. Device Initialization
  1377. The virtqueue is initialized
  1378. Device Operation
  1379. When the driver requires random bytes, it places the descriptor
  1380. of one or more buffers in the queue. It will be completely filled
  1381. by random data by the device.
  1382. Appendix G: Memory Balloon Device
  1383. The virtio memory balloon device is a primitive device for
  1384. managing guest memory: the device asks for a certain amount of
  1385. memory, and the guest supplies it (or withdraws it, if the device
  1386. has more than it asks for). This allows the guest to adapt to
  1387. changes in allowance of underlying physical memory. If the
  1388. feature is negotiated, the device can also be used to communicate
  1389. guest memory statistics to the host.
  1390. Configuration
  1391. Subsystem Device ID 5
  1392. Virtqueues 0:inflateq. 1:deflateq. 2:statsq.[footnote:
  1393. Only if VIRTIO_BALLON_F_STATS_VQ set
  1394. ]
  1395. Feature bits
  1396. VIRTIO_BALLOON_F_MUST_TELL_HOST (0) Host must be told before
  1397. pages from the balloon are used.
  1398. VIRTIO_BALLOON_F_STATS_VQ (1) A virtqueue for reporting guest
  1399. memory statistics is present.
  1400. Device configuration layout Both fields of this configuration
  1401. are always available. Note that they are little endian, despite
  1402. convention that device fields are guest endian:struct virtio_balloon_config {
  1403. u32 num_pages;
  1404. u32 actual;
  1405. };
  1406. Device Initialization
  1407. The inflate and deflate virtqueues are identified.
  1408. If the VIRTIO_BALLOON_F_STATS_VQ feature bit is negotiated:
  1409. Identify the stats virtqueue.
  1410. Add one empty buffer to the stats virtqueue and notify the
  1411. host.
  1412. Device operation begins immediately.
  1413. Device Operation
  1414. Memory Ballooning The device is driven by the receipt of a
  1415. configuration change interrupt.
  1416. The “num_pages” configuration field is examined. If this is
  1417. greater than the “actual” number of pages, memory must be given
  1418. to the balloon. If it is less than the “actual” number of
  1419. pages, memory may be taken back from the balloon for general
  1420. use.
  1421. To supply memory to the balloon (aka. inflate):
  1422. The driver constructs an array of addresses of unused memory
  1423. pages. These addresses are divided by 4096[footnote:
  1424. This is historical, and independent of the guest page size
  1425. ] and the descriptor describing the resulting 32-bit array is
  1426. added to the inflateq.
  1427. To remove memory from the balloon (aka. deflate):
  1428. The driver constructs an array of addresses of memory pages it
  1429. has previously given to the balloon, as described above. This
  1430. descriptor is added to the deflateq.
  1431. If the VIRTIO_BALLOON_F_MUST_TELL_HOST feature is set, the
  1432. guest may not use these requested pages until that descriptor
  1433. in the deflateq has been used by the device.
  1434. Otherwise, the guest may begin to re-use pages previously given
  1435. to the balloon before the device has acknowledged their
  1436. withdrawl. [footnote:
  1437. In this case, deflation advice is merely a courtesy
  1438. ]
  1439. In either case, once the device has completed the inflation or
  1440. deflation, the “actual” field of the configuration should be
  1441. updated to reflect the new number of pages in the balloon.[footnote:
  1442. As updates to configuration space are not atomic, this field
  1443. isn't particularly reliable, but can be used to diagnose buggy
  1444. guests.
  1445. ]
  1446. Memory Statistics
  1447. The stats virtqueue is atypical because communication is driven
  1448. by the device (not the driver). The channel becomes active at
  1449. driver initialization time when the driver adds an empty buffer
  1450. and notifies the device. A request for memory statistics proceeds
  1451. as follows:
  1452. The device pushes the buffer onto the used ring and sends an
  1453. interrupt.
  1454. The driver pops the used buffer and discards it.
  1455. The driver collects memory statistics and writes them into a
  1456. new buffer.
  1457. The driver adds the buffer to the virtqueue and notifies the
  1458. device.
  1459. The device pops the buffer (retaining it to initiate a
  1460. subsequent request) and consumes the statistics.
  1461. Memory Statistics Format Each statistic consists of a 16 bit
  1462. tag and a 64 bit value. Both quantities are represented in the
  1463. native endian of the guest. All statistics are optional and the
  1464. driver may choose which ones to supply. To guarantee backwards
  1465. compatibility, unsupported statistics should be omitted.
  1466. struct virtio_balloon_stat {
  1467. #define VIRTIO_BALLOON_S_SWAP_IN 0
  1468. #define VIRTIO_BALLOON_S_SWAP_OUT 1
  1469. #define VIRTIO_BALLOON_S_MAJFLT 2
  1470. #define VIRTIO_BALLOON_S_MINFLT 3
  1471. #define VIRTIO_BALLOON_S_MEMFREE 4
  1472. #define VIRTIO_BALLOON_S_MEMTOT 5
  1473. u16 tag;
  1474. u64 val;
  1475. } __attribute__((packed));
  1476. Tags
  1477. VIRTIO_BALLOON_S_SWAP_IN The amount of memory that has been
  1478. swapped in (in bytes).
  1479. VIRTIO_BALLOON_S_SWAP_OUT The amount of memory that has been
  1480. swapped out to disk (in bytes).
  1481. VIRTIO_BALLOON_S_MAJFLT The number of major page faults that
  1482. have occurred.
  1483. VIRTIO_BALLOON_S_MINFLT The number of minor page faults that
  1484. have occurred.
  1485. VIRTIO_BALLOON_S_MEMFREE The amount of memory not being used
  1486. for any purpose (in bytes).
  1487. VIRTIO_BALLOON_S_MEMTOT The total amount of memory available
  1488. (in bytes).
  1489. Appendix H: Rpmsg: Remote Processor Messaging
  1490. Virtio rpmsg devices represent remote processors on the system
  1491. which run in asymmetric multi-processing (AMP) configuration, and
  1492. which are usually used to offload cpu-intensive tasks from the
  1493. main application processor (a typical SoC methodology).
  1494. Virtio is being used to communicate with those remote processors;
  1495. empty buffers are placed in one virtqueue for receiving messages,
  1496. and non-empty buffers, containing outbound messages, are enqueued
  1497. in a second virtqueue for transmission.
  1498. Numerous communication channels can be multiplexed over those two
  1499. virtqueues, so different entities, running on the application and
  1500. remote processor, can directly communicate in a point-to-point
  1501. fashion.
  1502. Configuration
  1503. Subsystem Device ID 7
  1504. Virtqueues 0:receiveq. 1:transmitq.
  1505. Feature bits
  1506. VIRTIO_RPMSG_F_NS (0) Device sends (and capable of receiving)
  1507. name service messages announcing the creation (or
  1508. destruction) of a channel:/**
  1509. * struct rpmsg_ns_msg - dynamic name service announcement
  1510. message
  1511. * @name: name of remote service that is published
  1512. * @addr: address of remote service that is published
  1513. * @flags: indicates whether service is created or destroyed
  1514. *
  1515. * This message is sent across to publish a new service (or
  1516. announce
  1517. * about its removal). When we receives these messages, an
  1518. appropriate
  1519. * rpmsg channel (i.e device) is created/destroyed.
  1520. */
  1521. struct rpmsg_ns_msgoon_config {
  1522. char name[RPMSG_NAME_SIZE];
  1523. u32 addr;
  1524. u32 flags;
  1525. } __packed;
  1526. /**
  1527. * enum rpmsg_ns_flags - dynamic name service announcement flags
  1528. *
  1529. * @RPMSG_NS_CREATE: a new remote service was just created
  1530. * @RPMSG_NS_DESTROY: a remote service was just destroyed
  1531. */
  1532. enum rpmsg_ns_flags {
  1533. RPMSG_NS_CREATE = 0,
  1534. RPMSG_NS_DESTROY = 1,
  1535. };
  1536. Device configuration layout
  1537. At his point none currently defined.
  1538. Device Initialization
  1539. The initialization routine should identify the receive and
  1540. transmission virtqueues.
  1541. The receive virtqueue should be filled with receive buffers.
  1542. Device Operation
  1543. Messages are transmitted by placing them in the transmitq, and
  1544. buffers for inbound messages are placed in the receiveq. In any
  1545. case, messages are always preceded by the following header: /**
  1546. * struct rpmsg_hdr - common header for all rpmsg messages
  1547. * @src: source address
  1548. * @dst: destination address
  1549. * @reserved: reserved for future use
  1550. * @len: length of payload (in bytes)
  1551. * @flags: message flags
  1552. * @data: @len bytes of message payload data
  1553. *
  1554. * Every message sent(/received) on the rpmsg bus begins with
  1555. this header.
  1556. */
  1557. struct rpmsg_hdr {
  1558. u32 src;
  1559. u32 dst;
  1560. u32 reserved;
  1561. u16 len;
  1562. u16 flags;
  1563. u8 data[0];
  1564. } __packed;
  1565. Appendix I: SCSI Host Device
  1566. The virtio SCSI host device groups together one or more virtual
  1567. logical units (such as disks), and allows communicating to them
  1568. using the SCSI protocol. An instance of the device represents a
  1569. SCSI host to which many targets and LUNs are attached.
  1570. The virtio SCSI device services two kinds of requests:
  1571. command requests for a logical unit;
  1572. task management functions related to a logical unit, target or
  1573. command.
  1574. The device is also able to send out notifications about added and
  1575. removed logical units. Together, these capabilities provide a
  1576. SCSI transport protocol that uses virtqueues as the transfer
  1577. medium. In the transport protocol, the virtio driver acts as the
  1578. initiator, while the virtio SCSI host provides one or more
  1579. targets that receive and process the requests.
  1580. Configuration
  1581. Subsystem Device ID 8
  1582. Virtqueues 0:controlq; 1:eventq; 2..n:request queues.
  1583. Feature bits
  1584. VIRTIO_SCSI_F_INOUT (0) A single request can include both
  1585. read-only and write-only data buffers.
  1586. VIRTIO_SCSI_F_HOTPLUG (1) The host should enable
  1587. hot-plug/hot-unplug of new LUNs and targets on the SCSI bus.
  1588. Device configuration layout All fields of this configuration
  1589. are always available. sense_size and cdb_size are writable by
  1590. the guest.struct virtio_scsi_config {
  1591. u32 num_queues;
  1592. u32 seg_max;
  1593. u32 max_sectors;
  1594. u32 cmd_per_lun;
  1595. u32 event_info_size;
  1596. u32 sense_size;
  1597. u32 cdb_size;
  1598. u16 max_channel;
  1599. u16 max_target;
  1600. u32 max_lun;
  1601. };
  1602. num_queues is the total number of request virtqueues exposed by
  1603. the device. The driver is free to use only one request queue,
  1604. or it can use more to achieve better performance.
  1605. seg_max is the maximum number of segments that can be in a
  1606. command. A bidirectional command can include seg_max input
  1607. segments and seg_max output segments.
  1608. max_sectors is a hint to the guest about the maximum transfer
  1609. size it should use.
  1610. cmd_per_lun is a hint to the guest about the maximum number of
  1611. linked commands it should send to one LUN. The actual value
  1612. to be used is the minimum of cmd_per_lun and the virtqueue
  1613. size.
  1614. event_info_size is the maximum size that the device will fill
  1615. for buffers that the driver places in the eventq. The driver
  1616. should always put buffers at least of this size. It is
  1617. written by the device depending on the set of negotated
  1618. features.
  1619. sense_size is the maximum size of the sense data that the
  1620. device will write. The default value is written by the device
  1621. and will always be 96, but the driver can modify it. It is
  1622. restored to the default when the device is reset.
  1623. cdb_size is the maximum size of the CDB that the driver will
  1624. write. The default value is written by the device and will
  1625. always be 32, but the driver can likewise modify it. It is
  1626. restored to the default when the device is reset.
  1627. max_channel, max_target and max_lun can be used by the driver
  1628. as hints to constrain scanning the logical units on the
  1629. host.h
  1630. Device Initialization
  1631. The initialization routine should first of all discover the
  1632. device's virtqueues.
  1633. If the driver uses the eventq, it should then place at least a
  1634. buffer in the eventq.
  1635. The driver can immediately issue requests (for example, INQUIRY
  1636. or REPORT LUNS) or task management functions (for example, I_T
  1637. RESET).
  1638. Device Operation: request queues
  1639. The driver queues requests to an arbitrary request queue, and
  1640. they are used by the device on that same queue. It is the
  1641. responsibility of the driver to ensure strict request ordering
  1642. for commands placed on different queues, because they will be
  1643. consumed with no order constraints.
  1644. Requests have the following format:
  1645. struct virtio_scsi_req_cmd {
  1646. // Read-only
  1647. u8 lun[8];
  1648. u64 id;
  1649. u8 task_attr;
  1650. u8 prio;
  1651. u8 crn;
  1652. char cdb[cdb_size];
  1653. char dataout[];
  1654. // Write-only part
  1655. u32 sense_len;
  1656. u32 residual;
  1657. u16 status_qualifier;
  1658. u8 status;
  1659. u8 response;
  1660. u8 sense[sense_size];
  1661. char datain[];
  1662. };
  1663. /* command-specific response values */
  1664. #define VIRTIO_SCSI_S_OK 0
  1665. #define VIRTIO_SCSI_S_OVERRUN 1
  1666. #define VIRTIO_SCSI_S_ABORTED 2
  1667. #define VIRTIO_SCSI_S_BAD_TARGET 3
  1668. #define VIRTIO_SCSI_S_RESET 4
  1669. #define VIRTIO_SCSI_S_BUSY 5
  1670. #define VIRTIO_SCSI_S_TRANSPORT_FAILURE 6
  1671. #define VIRTIO_SCSI_S_TARGET_FAILURE 7
  1672. #define VIRTIO_SCSI_S_NEXUS_FAILURE 8
  1673. #define VIRTIO_SCSI_S_FAILURE 9
  1674. /* task_attr */
  1675. #define VIRTIO_SCSI_S_SIMPLE 0
  1676. #define VIRTIO_SCSI_S_ORDERED 1
  1677. #define VIRTIO_SCSI_S_HEAD 2
  1678. #define VIRTIO_SCSI_S_ACA 3
  1679. The lun field addresses a target and logical unit in the
  1680. virtio-scsi device's SCSI domain. The only supported format for
  1681. the LUN field is: first byte set to 1, second byte set to target,
  1682. third and fourth byte representing a single level LUN structure,
  1683. followed by four zero bytes. With this representation, a
  1684. virtio-scsi device can serve up to 256 targets and 16384 LUNs per
  1685. target.
  1686. The id field is the command identifier (“tag”).
  1687. task_attr, prio and crn should be left to zero. task_attr defines
  1688. the task attribute as in the table above, but all task attributes
  1689. may be mapped to SIMPLE by the device; crn may also be provided
  1690. by clients, but is generally expected to be 0. The maximum CRN
  1691. value defined by the protocol is 255, since CRN is stored in an
  1692. 8-bit integer.
  1693. All of these fields are defined in SAM. They are always
  1694. read-only, as are the cdb and dataout field. The cdb_size is
  1695. taken from the configuration space.
  1696. sense and subsequent fields are always write-only. The sense_len
  1697. field indicates the number of bytes actually written to the sense
  1698. buffer. The residual field indicates the residual size,
  1699. calculated as “data_length - number_of_transferred_bytes”, for
  1700. read or write operations. For bidirectional commands, the
  1701. number_of_transferred_bytes includes both read and written bytes.
  1702. A residual field that is less than the size of datain means that
  1703. the dataout field was processed entirely. A residual field that
  1704. exceeds the size of datain means that the dataout field was
  1705. processed partially and the datain field was not processed at
  1706. all.
  1707. The status byte is written by the device to be the status code as
  1708. defined in SAM.
  1709. The response byte is written by the device to be one of the
  1710. following:
  1711. VIRTIO_SCSI_S_OK when the request was completed and the status
  1712. byte is filled with a SCSI status code (not necessarily
  1713. "GOOD").
  1714. VIRTIO_SCSI_S_OVERRUN if the content of the CDB requires
  1715. transferring more data than is available in the data buffers.
  1716. VIRTIO_SCSI_S_ABORTED if the request was cancelled due to an
  1717. ABORT TASK or ABORT TASK SET task management function.
  1718. VIRTIO_SCSI_S_BAD_TARGET if the request was never processed
  1719. because the target indicated by the lun field does not exist.
  1720. VIRTIO_SCSI_S_RESET if the request was cancelled due to a bus
  1721. or device reset (including a task management function).
  1722. VIRTIO_SCSI_S_TRANSPORT_FAILURE if the request failed due to a
  1723. problem in the connection between the host and the target
  1724. (severed link).
  1725. VIRTIO_SCSI_S_TARGET_FAILURE if the target is suffering a
  1726. failure and the guest should not retry on other paths.
  1727. VIRTIO_SCSI_S_NEXUS_FAILURE if the nexus is suffering a failure
  1728. but retrying on other paths might yield a different result.
  1729. VIRTIO_SCSI_S_BUSY if the request failed but retrying on the
  1730. same path should work.
  1731. VIRTIO_SCSI_S_FAILURE for other host or guest error. In
  1732. particular, if neither dataout nor datain is empty, and the
  1733. VIRTIO_SCSI_F_INOUT feature has not been negotiated, the
  1734. request will be immediately returned with a response equal to
  1735. VIRTIO_SCSI_S_FAILURE.
  1736. Device Operation: controlq
  1737. The controlq is used for other SCSI transport operations.
  1738. Requests have the following format:
  1739. struct virtio_scsi_ctrl {
  1740. u32 type;
  1741. ...
  1742. u8 response;
  1743. };
  1744. /* response values valid for all commands */
  1745. #define VIRTIO_SCSI_S_OK 0
  1746. #define VIRTIO_SCSI_S_BAD_TARGET 3
  1747. #define VIRTIO_SCSI_S_BUSY 5
  1748. #define VIRTIO_SCSI_S_TRANSPORT_FAILURE 6
  1749. #define VIRTIO_SCSI_S_TARGET_FAILURE 7
  1750. #define VIRTIO_SCSI_S_NEXUS_FAILURE 8
  1751. #define VIRTIO_SCSI_S_FAILURE 9
  1752. #define VIRTIO_SCSI_S_INCORRECT_LUN 12
  1753. The type identifies the remaining fields.
  1754. The following commands are defined:
  1755. Task management function
  1756. #define VIRTIO_SCSI_T_TMF 0
  1757. #define VIRTIO_SCSI_T_TMF_ABORT_TASK 0
  1758. #define VIRTIO_SCSI_T_TMF_ABORT_TASK_SET 1
  1759. #define VIRTIO_SCSI_T_TMF_CLEAR_ACA 2
  1760. #define VIRTIO_SCSI_T_TMF_CLEAR_TASK_SET 3
  1761. #define VIRTIO_SCSI_T_TMF_I_T_NEXUS_RESET 4
  1762. #define VIRTIO_SCSI_T_TMF_LOGICAL_UNIT_RESET 5
  1763. #define VIRTIO_SCSI_T_TMF_QUERY_TASK 6
  1764. #define VIRTIO_SCSI_T_TMF_QUERY_TASK_SET 7
  1765. struct virtio_scsi_ctrl_tmf
  1766. {
  1767. // Read-only part
  1768. u32 type;
  1769. u32 subtype;
  1770. u8 lun[8];
  1771. u64 id;
  1772. // Write-only part
  1773. u8 response;
  1774. }
  1775. /* command-specific response values */
  1776. #define VIRTIO_SCSI_S_FUNCTION_COMPLETE 0
  1777. #define VIRTIO_SCSI_S_FUNCTION_SUCCEEDED 10
  1778. #define VIRTIO_SCSI_S_FUNCTION_REJECTED 11
  1779. The type is VIRTIO_SCSI_T_TMF; the subtype field defines. All
  1780. fields except response are filled by the driver. The subtype
  1781. field must always be specified and identifies the requested
  1782. task management function.
  1783. Other fields may be irrelevant for the requested TMF; if so,
  1784. they are ignored but they should still be present. The lun
  1785. field is in the same format specified for request queues; the
  1786. single level LUN is ignored when the task management function
  1787. addresses a whole I_T nexus. When relevant, the value of the id
  1788. field is matched against the id values passed on the requestq.
  1789. The outcome of the task management function is written by the
  1790. device in the response field. The command-specific response
  1791. values map 1-to-1 with those defined in SAM.
  1792. Asynchronous notification query
  1793. #define VIRTIO_SCSI_T_AN_QUERY 1
  1794. struct virtio_scsi_ctrl_an {
  1795. // Read-only part
  1796. u32 type;
  1797. u8 lun[8];
  1798. u32 event_requested;
  1799. // Write-only part
  1800. u32 event_actual;
  1801. u8 response;
  1802. }
  1803. #define VIRTIO_SCSI_EVT_ASYNC_OPERATIONAL_CHANGE 2
  1804. #define VIRTIO_SCSI_EVT_ASYNC_POWER_MGMT 4
  1805. #define VIRTIO_SCSI_EVT_ASYNC_EXTERNAL_REQUEST 8
  1806. #define VIRTIO_SCSI_EVT_ASYNC_MEDIA_CHANGE 16
  1807. #define VIRTIO_SCSI_EVT_ASYNC_MULTI_HOST 32
  1808. #define VIRTIO_SCSI_EVT_ASYNC_DEVICE_BUSY 64
  1809. By sending this command, the driver asks the device which
  1810. events the given LUN can report, as described in paragraphs 6.6
  1811. and A.6 of the SCSI MMC specification. The driver writes the
  1812. events it is interested in into the event_requested; the device
  1813. responds by writing the events that it supports into
  1814. event_actual.
  1815. The type is VIRTIO_SCSI_T_AN_QUERY. The lun and event_requested
  1816. fields are written by the driver. The event_actual and response
  1817. fields are written by the device.
  1818. No command-specific values are defined for the response byte.
  1819. Asynchronous notification subscription
  1820. #define VIRTIO_SCSI_T_AN_SUBSCRIBE 2
  1821. struct virtio_scsi_ctrl_an {
  1822. // Read-only part
  1823. u32 type;
  1824. u8 lun[8];
  1825. u32 event_requested;
  1826. // Write-only part
  1827. u32 event_actual;
  1828. u8 response;
  1829. }
  1830. By sending this command, the driver asks the specified LUN to
  1831. report events for its physical interface, again as described in
  1832. the SCSI MMC specification. The driver writes the events it is
  1833. interested in into the event_requested; the device responds by
  1834. writing the events that it supports into event_actual.
  1835. Event types are the same as for the asynchronous notification
  1836. query message.
  1837. The type is VIRTIO_SCSI_T_AN_SUBSCRIBE. The lun and
  1838. event_requested fields are written by the driver. The
  1839. event_actual and response fields are written by the device.
  1840. No command-specific values are defined for the response byte.
  1841. Device Operation: eventq
  1842. The eventq is used by the device to report information on logical
  1843. units that are attached to it. The driver should always leave a
  1844. few buffers ready in the eventq. In general, the device will not
  1845. queue events to cope with an empty eventq, and will end up
  1846. dropping events if it finds no buffer ready. However, when
  1847. reporting events for many LUNs (e.g. when a whole target
  1848. disappears), the device can throttle events to avoid dropping
  1849. them. For this reason, placing 10-15 buffers on the event queue
  1850. should be enough.
  1851. Buffers are placed in the eventq and filled by the device when
  1852. interesting events occur. The buffers should be strictly
  1853. write-only (device-filled) and the size of the buffers should be
  1854. at least the value given in the device's configuration
  1855. information.
  1856. Buffers returned by the device on the eventq will be referred to
  1857. as "events" in the rest of this section. Events have the
  1858. following format:
  1859. #define VIRTIO_SCSI_T_EVENTS_MISSED 0x80000000
  1860. struct virtio_scsi_event {
  1861. // Write-only part
  1862. u32 event;
  1863. ...
  1864. }
  1865. If bit 31 is set in the event field, the device failed to report
  1866. an event due to missing buffers. In this case, the driver should
  1867. poll the logical units for unit attention conditions, and/or do
  1868. whatever form of bus scan is appropriate for the guest operating
  1869. system.
  1870. Other data that the device writes to the buffer depends on the
  1871. contents of the event field. The following events are defined:
  1872. No event
  1873. #define VIRTIO_SCSI_T_NO_EVENT 0
  1874. This event is fired in the following cases:
  1875. When the device detects in the eventq a buffer that is shorter
  1876. than what is indicated in the configuration field, it might
  1877. use it immediately and put this dummy value in the event
  1878. field. A well-written driver will never observe this
  1879. situation.
  1880. When events are dropped, the device may signal this event as
  1881. soon as the drivers makes a buffer available, in order to
  1882. request action from the driver. In this case, of course, this
  1883. event will be reported with the VIRTIO_SCSI_T_EVENTS_MISSED
  1884. flag.
  1885. Transport reset
  1886. #define VIRTIO_SCSI_T_TRANSPORT_RESET 1
  1887. struct virtio_scsi_event_reset {
  1888. // Write-only part
  1889. u32 event;
  1890. u8 lun[8];
  1891. u32 reason;
  1892. }
  1893. #define VIRTIO_SCSI_EVT_RESET_HARD 0
  1894. #define VIRTIO_SCSI_EVT_RESET_RESCAN 1
  1895. #define VIRTIO_SCSI_EVT_RESET_REMOVED 2
  1896. By sending this event, the device signals that a logical unit
  1897. on a target has been reset, including the case of a new device
  1898. appearing or disappearing on the bus.The device fills in all
  1899. fields. The event field is set to
  1900. VIRTIO_SCSI_T_TRANSPORT_RESET. The lun field addresses a
  1901. logical unit in the SCSI host.
  1902. The reason value is one of the three #define values appearing
  1903. above:
  1904. VIRTIO_SCSI_EVT_RESET_REMOVED (“LUN/target removed”) is used if
  1905. the target or logical unit is no longer able to receive
  1906. commands.
  1907. VIRTIO_SCSI_EVT_RESET_HARD (“LUN hard reset”) is used if the
  1908. logical unit has been reset, but is still present.
  1909. VIRTIO_SCSI_EVT_RESET_RESCAN (“rescan LUN/target”) is used if a
  1910. target or logical unit has just appeared on the device.
  1911. The “removed” and “rescan” events, when sent for LUN 0, may
  1912. apply to the entire target. After receiving them the driver
  1913. should ask the initiator to rescan the target, in order to
  1914. detect the case when an entire target has appeared or
  1915. disappeared. These two events will never be reported unless the
  1916. VIRTIO_SCSI_F_HOTPLUG feature was negotiated between the host
  1917. and the guest.
  1918. Events will also be reported via sense codes (this obviously
  1919. does not apply to newly appeared buses or targets, since the
  1920. application has never discovered them):
  1921. “LUN/target removed” maps to sense key ILLEGAL REQUEST, asc
  1922. 0x25, ascq 0x00 (LOGICAL UNIT NOT SUPPORTED)
  1923. “LUN hard reset” maps to sense key UNIT ATTENTION, asc 0x29
  1924. (POWER ON, RESET OR BUS DEVICE RESET OCCURRED)
  1925. “rescan LUN/target” maps to sense key UNIT ATTENTION, asc 0x3f,
  1926. ascq 0x0e (REPORTED LUNS DATA HAS CHANGED)
  1927. The preferred way to detect transport reset is always to use
  1928. events, because sense codes are only seen by the driver when it
  1929. sends a SCSI command to the logical unit or target. However, in
  1930. case events are dropped, the initiator will still be able to
  1931. synchronize with the actual state of the controller if the
  1932. driver asks the initiator to rescan of the SCSI bus. During the
  1933. rescan, the initiator will be able to observe the above sense
  1934. codes, and it will process them as if it the driver had
  1935. received the equivalent event.
  1936. Asynchronous notification
  1937. #define VIRTIO_SCSI_T_ASYNC_NOTIFY 2
  1938. struct virtio_scsi_event_an {
  1939. // Write-only part
  1940. u32 event;
  1941. u8 lun[8];
  1942. u32 reason;
  1943. }
  1944. By sending this event, the device signals that an asynchronous
  1945. event was fired from a physical interface.
  1946. All fields are written by the device. The event field is set to
  1947. VIRTIO_SCSI_T_ASYNC_NOTIFY. The lun field addresses a logical
  1948. unit in the SCSI host. The reason field is a subset of the
  1949. events that the driver has subscribed to via the "Asynchronous
  1950. notification subscription" command.
  1951. When dropped events are reported, the driver should poll for
  1952. asynchronous events manually using SCSI commands.
  1953. Appendix X: virtio-mmio
  1954. Virtual environments without PCI support (a common situation in
  1955. embedded devices models) might use simple memory mapped device (“
  1956. virtio-mmio”) instead of the PCI device.
  1957. The memory mapped virtio device behaviour is based on the PCI
  1958. device specification. Therefore most of operations like device
  1959. initialization, queues configuration and buffer transfers are
  1960. nearly identical. Existing differences are described in the
  1961. following sections.
  1962. Device Initialization
  1963. Instead of using the PCI IO space for virtio header, the “
  1964. virtio-mmio” device provides a set of memory mapped control
  1965. registers, all 32 bits wide, followed by device-specific
  1966. configuration space. The following list presents their layout:
  1967. Offset from the device base address | Direction | Name
  1968. Description
  1969. 0x000 | R | MagicValue
  1970. “virt” string.
  1971. 0x004 | R | Version
  1972. Device version number. Currently must be 1.
  1973. 0x008 | R | DeviceID
  1974. Virtio Subsystem Device ID (ie. 1 for network card).
  1975. 0x00c | R | VendorID
  1976. Virtio Subsystem Vendor ID.
  1977. 0x010 | R | HostFeatures
  1978. Flags representing features the device supports.
  1979. Reading from this register returns 32 consecutive flag bits,
  1980. first bit depending on the last value written to
  1981. HostFeaturesSel register. Access to this register returns bits HostFeaturesSel*32
  1982. to (HostFeaturesSel*32)+31
  1983. , eg. feature bits 0 to 31 if
  1984. HostFeaturesSel is set to 0 and features bits 32 to 63 if
  1985. HostFeaturesSel is set to 1. Also see [sub:Feature-Bits]
  1986. 0x014 | W | HostFeaturesSel
  1987. Device (Host) features word selection.
  1988. Writing to this register selects a set of 32 device feature bits
  1989. accessible by reading from HostFeatures register. Device driver
  1990. must write a value to the HostFeaturesSel register before
  1991. reading from the HostFeatures register.
  1992. 0x020 | W | GuestFeatures
  1993. Flags representing device features understood and activated by
  1994. the driver.
  1995. Writing to this register sets 32 consecutive flag bits, first
  1996. bit depending on the last value written to GuestFeaturesSel
  1997. register. Access to this register sets bits GuestFeaturesSel*32
  1998. to (GuestFeaturesSel*32)+31
  1999. , eg. feature bits 0 to 31 if
  2000. GuestFeaturesSel is set to 0 and features bits 32 to 63 if
  2001. GuestFeaturesSel is set to 1. Also see [sub:Feature-Bits]
  2002. 0x024 | W | GuestFeaturesSel
  2003. Activated (Guest) features word selection.
  2004. Writing to this register selects a set of 32 activated feature
  2005. bits accessible by writing to the GuestFeatures register.
  2006. Device driver must write a value to the GuestFeaturesSel
  2007. register before writing to the GuestFeatures register.
  2008. 0x028 | W | GuestPageSize
  2009. Guest page size.
  2010. Device driver must write the guest page size in bytes to the
  2011. register during initialization, before any queues are used.
  2012. This value must be a power of 2 and is used by the Host to
  2013. calculate Guest address of the first queue page (see QueuePFN).
  2014. 0x030 | W | QueueSel
  2015. Virtual queue index (first queue is 0).
  2016. Writing to this register selects the virtual queue that the
  2017. following operations on QueueNum, QueueAlign and QueuePFN apply
  2018. to.
  2019. 0x034 | R | QueueNumMax
  2020. Maximum virtual queue size.
  2021. Reading from the register returns the maximum size of the queue
  2022. the Host is ready to process or zero (0x0) if the queue is not
  2023. available. This applies to the queue selected by writing to
  2024. QueueSel and is allowed only when QueuePFN is set to zero
  2025. (0x0), so when the queue is not actively used.
  2026. 0x038 | W | QueueNum
  2027. Virtual queue size.
  2028. Queue size is a number of elements in the queue, therefore size
  2029. of the descriptor table and both available and used rings.
  2030. Writing to this register notifies the Host what size of the
  2031. queue the Guest will use. This applies to the queue selected by
  2032. writing to QueueSel.
  2033. 0x03c | W | QueueAlign
  2034. Used Ring alignment in the virtual queue.
  2035. Writing to this register notifies the Host about alignment
  2036. boundary of the Used Ring in bytes. This value must be a power
  2037. of 2 and applies to the queue selected by writing to QueueSel.
  2038. 0x040 | RW | QueuePFN
  2039. Guest physical page number of the virtual queue.
  2040. Writing to this register notifies the host about location of the
  2041. virtual queue in the Guest's physical address space. This value
  2042. is the index number of a page starting with the queue
  2043. Descriptor Table. Value zero (0x0) means physical address zero
  2044. (0x00000000) and is illegal. When the Guest stops using the
  2045. queue it must write zero (0x0) to this register.
  2046. Reading from this register returns the currently used page
  2047. number of the queue, therefore a value other than zero (0x0)
  2048. means that the queue is in use.
  2049. Both read and write accesses apply to the queue selected by
  2050. writing to QueueSel.
  2051. 0x050 | W | QueueNotify
  2052. Queue notifier.
  2053. Writing a queue index to this register notifies the Host that
  2054. there are new buffers to process in the queue.
  2055. 0x60 | R | InterruptStatus
  2056. Interrupt status.
  2057. Reading from this register returns a bit mask of interrupts
  2058. asserted by the device. An interrupt is asserted if the
  2059. corresponding bit is set, ie. equals one (1).
  2060. Bit 0 | Used Ring Update
  2061. This interrupt is asserted when the Host has updated the Used
  2062. Ring in at least one of the active virtual queues.
  2063. Bit 1 | Configuration change
  2064. This interrupt is asserted when configuration of the device has
  2065. changed.
  2066. 0x064 | W | InterruptACK
  2067. Interrupt acknowledge.
  2068. Writing to this register notifies the Host that the Guest
  2069. finished handling interrupts. Set bits in the value clear the
  2070. corresponding bits of the InterruptStatus register.
  2071. 0x070 | RW | Status
  2072. Device status.
  2073. Reading from this register returns the current device status
  2074. flags.
  2075. Writing non-zero values to this register sets the status flags,
  2076. indicating the Guest progress. Writing zero (0x0) to this
  2077. register triggers a device reset.
  2078. Also see [sub:Device-Initialization-Sequence]
  2079. 0x100+ | RW | Config
  2080. Device-specific configuration space starts at an offset 0x100
  2081. and is accessed with byte alignment. Its meaning and size
  2082. depends on the device and the driver.
  2083. Virtual queue size is a number of elements in the queue,
  2084. therefore size of the descriptor table and both available and
  2085. used rings.
  2086. The endianness of the registers follows the native endianness of
  2087. the Guest. Writing to registers described as “R” and reading from
  2088. registers described as “W” is not permitted and can cause
  2089. undefined behavior.
  2090. The device initialization is performed as described in [sub:Device-Initialization-Sequence]
  2091. with one exception: the Guest must notify the Host about its
  2092. page size, writing the size in bytes to GuestPageSize register
  2093. before the initialization is finished.
  2094. The memory mapped virtio devices generate single interrupt only,
  2095. therefore no special configuration is required.
  2096. Virtqueue Configuration
  2097. The virtual queue configuration is performed in a similar way to
  2098. the one described in [sec:Virtqueue-Configuration] with a few
  2099. additional operations:
  2100. Select the queue writing its index (first queue is 0) to the
  2101. QueueSel register.
  2102. Check if the queue is not already in use: read QueuePFN
  2103. register, returned value should be zero (0x0).
  2104. Read maximum queue size (number of elements) from the
  2105. QueueNumMax register. If the returned value is zero (0x0) the
  2106. queue is not available.
  2107. Allocate and zero the queue pages in contiguous virtual memory,
  2108. aligning the Used Ring to an optimal boundary (usually page
  2109. size). Size of the allocated queue may be smaller than or equal
  2110. to the maximum size returned by the Host.
  2111. Notify the Host about the queue size by writing the size to
  2112. QueueNum register.
  2113. Notify the Host about the used alignment by writing its value
  2114. in bytes to QueueAlign register.
  2115. Write the physical number of the first page of the queue to the
  2116. QueuePFN register.
  2117. The queue and the device are ready to begin normal operations
  2118. now.
  2119. Device Operation
  2120. The memory mapped virtio device behaves in the same way as
  2121. described in [sec:Device-Operation], with the following
  2122. exceptions:
  2123. The device is notified about new buffers available in a queue
  2124. by writing the queue index to register QueueNum instead of the
  2125. virtio header in PCI I/O space ([sub:Notifying-The-Device]).
  2126. The memory mapped virtio device is using single, dedicated
  2127. interrupt signal, which is raised when at least one of the
  2128. interrupts described in the InterruptStatus register
  2129. description is asserted. After receiving an interrupt, the
  2130. driver must read the InterruptStatus register to check what
  2131. caused the interrupt (see the register description). After the
  2132. interrupt is handled, the driver must acknowledge it by writing
  2133. a bit mask corresponding to the serviced interrupt to the
  2134. InterruptACK register.