virtio-spec.txt 68 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201
  1. [Generated file: see http://ozlabs.org/~rusty/virtio-spec/]
  2. Virtio PCI Card Specification
  3. v0.9.1 DRAFT
  4. -
  5. Rusty Russell <rusty@rustcorp.com.au>IBM Corporation (Editor)
  6. 2011 August 1.
  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 buffers to the device, it puts them
  56. in one or more slots in the descriptor table, and writes the
  57. descriptor indices into the available ring. It then notifies the
  58. device. When the device has finished with the buffers, it writes
  59. the descriptors 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. | 9 | 9P transport | - |
  88. +----------------------+--------------------+---------------+
  89. Device Configuration
  90. To configure the device, we use the first I/O region of the PCI
  91. device. This contains a virtio header followed by a
  92. device-specific region.
  93. There may be different widths of accesses to the I/O region; the “
  94. natural” access method for each field in the virtio header must
  95. be used (i.e. 32-bit accesses for 32-bit fields, etc), but the
  96. device-specific region can be accessed using any width accesses,
  97. and should obtain the same results.
  98. Note that this is possible because while the virtio header is PCI
  99. (i.e. little) endian, the device-specific region is encoded in
  100. the native endian of the guest (where such distinction is
  101. applicable).
  102. Device Initialization Sequence
  103. We start with an overview of device initialization, then expand
  104. on the details of the device and how each step is preformed.
  105. Reset the device. This is not required on initial start up.
  106. The ACKNOWLEDGE status bit is set: we have noticed the device.
  107. The DRIVER status bit is set: we know how to drive the device.
  108. Device-specific setup, including reading the Device Feature
  109. Bits, discovery of virtqueues for the device, optional MSI-X
  110. setup, and reading and possibly writing the virtio
  111. configuration space.
  112. The subset of Device Feature Bits understood by the driver is
  113. written to the device.
  114. The DRIVER_OK status bit is set.
  115. The device can now be used (ie. buffers added to the
  116. virtqueues)[footnote:
  117. Historically, drivers have used the device before steps 5 and 6.
  118. This is only allowed if the driver does not use any features
  119. which would alter this early use of the device.
  120. ]
  121. If any of these steps go irrecoverably wrong, the guest should
  122. set the FAILED status bit to indicate that it has given up on the
  123. device (it can reset the device later to restart if desired).
  124. We now cover the fields required for general setup in detail.
  125. Virtio Header
  126. The virtio header looks as follows:
  127. +------------++---------------------+---------------------+----------+--------+---------+---------+---------+--------+
  128. | Bits || 32 | 32 | 32 | 16 | 16 | 16 | 8 | 8 |
  129. +------------++---------------------+---------------------+----------+--------+---------+---------+---------+--------+
  130. | Read/Write || R | R+W | R+W | R | R+W | R+W | R+W | R |
  131. +------------++---------------------+---------------------+----------+--------+---------+---------+---------+--------+
  132. | Purpose || Device | Guest | Queue | Queue | Queue | Queue | Device | ISR |
  133. | || Features bits 0:31 | Features bits 0:31 | Address | Size | Select | Notify | Status | Status |
  134. +------------++---------------------+---------------------+----------+--------+---------+---------+---------+--------+
  135. If MSI-X is enabled for the device, two additional fields
  136. immediately follow this header:
  137. +------------++----------------+--------+
  138. | Bits || 16 | 16 |
  139. +----------------+--------+
  140. +------------++----------------+--------+
  141. | Read/Write || R+W | R+W |
  142. +------------++----------------+--------+
  143. | Purpose || Configuration | Queue |
  144. | (MSI-X) || Vector | Vector |
  145. +------------++----------------+--------+
  146. Finally, if feature bits (VIRTIO_F_FEATURES_HI) this is
  147. immediately followed by two additional fields:
  148. +------------++----------------------+----------------------
  149. | Bits || 32 | 32
  150. +------------++----------------------+----------------------
  151. | Read/Write || R | R+W
  152. +------------++----------------------+----------------------
  153. | Purpose || Device | Guest
  154. | || Features bits 32:63 | Features bits 32:63
  155. +------------++----------------------+----------------------
  156. Immediately following these general headers, there may be
  157. device-specific headers:
  158. +------------++--------------------+
  159. | Bits || Device Specific |
  160. +--------------------+
  161. +------------++--------------------+
  162. | Read/Write || Device Specific |
  163. +------------++--------------------+
  164. | Purpose || Device Specific... |
  165. | || |
  166. +------------++--------------------+
  167. Device Status
  168. The Device Status field is updated by the guest to indicate its
  169. progress. This provides a simple low-level diagnostic: it's most
  170. useful to imagine them hooked up to traffic lights on the console
  171. indicating the status of each device.
  172. The device can be reset by writing a 0 to this field, otherwise
  173. at least one bit should be set:
  174. ACKNOWLEDGE (1) Indicates that the guest OS has found the
  175. device and recognized it as a valid virtio device.
  176. DRIVER (2) Indicates that the guest OS knows how to drive the
  177. device. Under Linux, drivers can be loadable modules so there
  178. may be a significant (or infinite) delay before setting this
  179. bit.
  180. DRIVER_OK (3) Indicates that the driver is set up and ready to
  181. drive the device.
  182. FAILED (8) Indicates that something went wrong in the guest,
  183. and it has given up on the device. This could be an internal
  184. error, or the driver didn't like the device for some reason, or
  185. even a fatal error during device operation. The device must be
  186. reset before attempting to re-initialize.
  187. Feature Bits
  188. The least significant 31 bits of the first configuration field
  189. indicates the features that the device supports (the high bit is
  190. reserved, and will be used to indicate the presence of future
  191. feature bits elsewhere). If more than 31 feature bits are
  192. supported, the device indicates so by setting feature bit 31 (see
  193. [cha:Reserved-Feature-Bits]). The bits are allocated as follows:
  194. 0 to 23 Feature bits for the specific device type
  195. 24 to 40 Feature bits reserved for extensions to the queue and
  196. feature negotiation mechanisms
  197. 41 to 63 Feature bits reserved for future extensions
  198. For example, feature bit 0 for a network device (i.e. Subsystem
  199. Device ID 1) indicates that the device supports checksumming of
  200. packets.
  201. The feature bits are negotiated: the device lists all the
  202. features it understands in the Device Features field, and the
  203. guest writes the subset that it understands into the Guest
  204. Features field. The only way to renegotiate is to reset the
  205. device.
  206. In particular, new fields in the device configuration header are
  207. indicated by offering a feature bit, so the guest can check
  208. before accessing that part of the configuration space.
  209. This allows for forwards and backwards compatibility: if the
  210. device is enhanced with a new feature bit, older guests will not
  211. write that feature bit back to the Guest Features field and it
  212. can go into backwards compatibility mode. Similarly, if a guest
  213. is enhanced with a feature that the device doesn't support, it
  214. will not see that feature bit in the Device Features field and
  215. can go into backwards compatibility mode (or, for poor
  216. implementations, set the FAILED Device Status bit).
  217. Access to feature bits 32 to 63 is enabled by Guest by setting
  218. feature bit 31. If this bit is unset, Device must assume that all
  219. feature bits > 31 are unset.
  220. Configuration/Queue Vectors
  221. When MSI-X capability is present and enabled in the device
  222. (through standard PCI configuration space) 4 bytes at byte offset
  223. 20 are used to map configuration change and queue interrupts to
  224. MSI-X vectors. In this case, the ISR Status field is unused, and
  225. device specific configuration starts at byte offset 24 in virtio
  226. header structure. When MSI-X capability is not enabled, device
  227. specific configuration starts at byte offset 20 in virtio header.
  228. Writing a valid MSI-X Table entry number, 0 to 0x7FF, to one of
  229. Configuration/Queue Vector registers, maps interrupts triggered
  230. by the configuration change/selected queue events respectively to
  231. the corresponding MSI-X vector. To disable interrupts for a
  232. specific event type, unmap it by writing a special NO_VECTOR
  233. value:
  234. /* Vector value used to disable MSI for queue */
  235. #define VIRTIO_MSI_NO_VECTOR 0xffff
  236. Reading these registers returns vector mapped to a given event,
  237. or NO_VECTOR if unmapped. All queue and configuration change
  238. events are unmapped by default.
  239. Note that mapping an event to vector might require allocating
  240. internal device resources, and might fail. Devices report such
  241. failures by returning the NO_VECTOR value when the relevant
  242. Vector field is read. After mapping an event to vector, the
  243. driver must verify success by reading the Vector field value: on
  244. success, the previously written value is returned, and on
  245. failure, NO_VECTOR is returned. If a mapping failure is detected,
  246. the driver can retry mapping with fewervectors, or disable MSI-X.
  247. Virtqueue Configuration
  248. As a device can have zero or more virtqueues for bulk data
  249. transport (for example, the network driver has two), the driver
  250. needs to configure them as part of the device-specific
  251. configuration.
  252. This is done as follows, for each virtqueue a device has:
  253. Write the virtqueue index (first queue is 0) to the Queue
  254. Select field.
  255. Read the virtqueue size from the Queue Size field, which is
  256. always a power of 2. This controls how big the virtqueue is
  257. (see below). If this field is 0, the virtqueue does not exist.
  258. Allocate and zero virtqueue in contiguous physical memory, on a
  259. 4096 byte alignment. Write the physical address, divided by
  260. 4096 to the Queue Address field.[footnote:
  261. The 4096 is based on the x86 page size, but it's also large
  262. enough to ensure that the separate parts of the virtqueue are on
  263. separate cache lines.
  264. ]
  265. Optionally, if MSI-X capability is present and enabled on the
  266. device, select a vector to use to request interrupts triggered
  267. by virtqueue events. Write the MSI-X Table entry number
  268. corresponding to this vector in Queue Vector field. Read the
  269. Queue Vector field: on success, previously written value is
  270. returned; on failure, NO_VECTOR value is returned.
  271. The Queue Size field controls the total number of bytes required
  272. for the virtqueue according to the following formula:
  273. #define ALIGN(x) (((x) + 4095) & ~4095)
  274. static inline unsigned vring_size(unsigned int qsz)
  275. {
  276. return ALIGN(sizeof(struct vring_desc)*qsz + sizeof(u16)*(2
  277. + qsz))
  278. + ALIGN(sizeof(struct vring_used_elem)*qsz);
  279. }
  280. This currently wastes some space with padding, but also allows
  281. future extensions. The virtqueue layout structure looks like this
  282. (qsz is the Queue Size field, which is a variable, so this code
  283. won't compile):
  284. struct vring {
  285. /* The actual descriptors (16 bytes each) */
  286. struct vring_desc desc[qsz];
  287. /* A ring of available descriptor heads with free-running
  288. index. */
  289. struct vring_avail avail;
  290. // Padding to the next 4096 boundary.
  291. char pad[];
  292. // A ring of used descriptor heads with free-running index.
  293. struct vring_used used;
  294. };
  295. A Note on Virtqueue Endianness
  296. Note that the endian of these fields and everything else in the
  297. virtqueue is the native endian of the guest, not little-endian as
  298. PCI normally is. This makes for simpler guest code, and it is
  299. assumed that the host already has to be deeply aware of the guest
  300. endian so such an “endian-aware” device is not a significant
  301. issue.
  302. Descriptor Table
  303. The descriptor table refers to the buffers the guest is using for
  304. the device. The addresses are physical addresses, and the buffers
  305. can be chained via the next field. Each descriptor describes a
  306. buffer which is read-only or write-only, but a chain of
  307. descriptors can contain both read-only and write-only buffers.
  308. No descriptor chain may be more than 2^32 bytes long in total.struct vring_desc {
  309. /* Address (guest-physical). */
  310. u64 addr;
  311. /* Length. */
  312. u32 len;
  313. /* This marks a buffer as continuing via the next field. */
  314. #define VRING_DESC_F_NEXT 1
  315. /* This marks a buffer as write-only (otherwise read-only). */
  316. #define VRING_DESC_F_WRITE 2
  317. /* This means the buffer contains a list of buffer descriptors.
  318. */
  319. #define VRING_DESC_F_INDIRECT 4
  320. /* The flags as indicated above. */
  321. u16 flags;
  322. /* Next field if flags & NEXT */
  323. u16 next;
  324. };
  325. The number of descriptors in the table is specified by the Queue
  326. Size field for this virtqueue.
  327. <sub:Indirect-Descriptors>Indirect Descriptors
  328. Some devices benefit by concurrently dispatching a large number
  329. of large requests. The VIRTIO_RING_F_INDIRECT_DESC feature can be
  330. used to allow this (see [cha:Reserved-Feature-Bits]). To increase
  331. ring capacity it is possible to store a table of indirect
  332. descriptors anywhere in memory, and insert a descriptor in main
  333. virtqueue (with flags&INDIRECT on) that refers to memory buffer
  334. containing this indirect descriptor table; fields addr and len
  335. refer to the indirect table address and length in bytes,
  336. respectively. The indirect table layout structure looks like this
  337. (len is the length of the descriptor that refers to this table,
  338. which is a variable, so this code won't compile):
  339. struct indirect_descriptor_table {
  340. /* The actual descriptors (16 bytes each) */
  341. struct vring_desc desc[len / 16];
  342. };
  343. The first indirect descriptor is located at start of the indirect
  344. descriptor table (index 0), additional indirect descriptors are
  345. chained by next field. An indirect descriptor without next field
  346. (with flags&NEXT off) signals the end of the indirect descriptor
  347. table, and transfers control back to the main virtqueue. An
  348. indirect descriptor can not refer to another indirect descriptor
  349. table (flags&INDIRECT must be off). A single indirect descriptor
  350. table can include both read-only and write-only descriptors;
  351. write-only flag (flags&WRITE) in the descriptor that refers to it
  352. is ignored.
  353. Available Ring
  354. The available ring refers to what descriptors we are offering the
  355. device: it refers to the head of a descriptor chain. The “flags”
  356. field is currently 0 or 1: 1 indicating that we do not need an
  357. interrupt when the device consumes a descriptor from the
  358. available ring. Alternatively, the guest can ask the device to
  359. delay interrupts until an entry with an index specified by the “
  360. used_event” field is written in the used ring (equivalently,
  361. until the idx field in the used ring will reach the value
  362. used_event + 1). The method employed by the device is controlled
  363. by the VIRTIO_RING_F_EVENT_IDX feature bit (see [cha:Reserved-Feature-Bits]
  364. ). This interrupt suppression is merely an optimization; it may
  365. not suppress interrupts entirely.
  366. The “idx” field indicates where we would put the next descriptor
  367. entry (modulo the ring size). This starts at 0, and increases.
  368. struct vring_avail {
  369. #define VRING_AVAIL_F_NO_INTERRUPT 1
  370. u16 flags;
  371. u16 idx;
  372. u16 ring[qsz]; /* qsz is the Queue Size field read from device
  373. */
  374. u16 used_event;
  375. };
  376. Used Ring
  377. The used ring is where the device returns buffers once it is done
  378. with them. The flags field can be used by the device to hint that
  379. no notification is necessary when the guest adds to the available
  380. ring. Alternatively, the “avail_event” field can be used by the
  381. device to hint that no notification is necessary until an entry
  382. with an index specified by the “avail_event” is written in the
  383. available ring (equivalently, until the idx field in the
  384. available ring will reach the value avail_event + 1). The method
  385. employed by the device is controlled by the guest through the
  386. VIRTIO_RING_F_EVENT_IDX feature bit (see [cha:Reserved-Feature-Bits]
  387. ). [footnote:
  388. These fields are kept here because this is the only part of the
  389. virtqueue written by the device
  390. ].
  391. Each entry in the ring is a pair: the head entry of the
  392. descriptor chain describing the buffer (this matches an entry
  393. placed in the available ring by the guest earlier), and the total
  394. of bytes written into the buffer. The latter is extremely useful
  395. for guests using untrusted buffers: if you do not know exactly
  396. how much has been written by the device, you usually have to zero
  397. the buffer to ensure no data leakage occurs.
  398. /* u32 is used here for ids for padding reasons. */
  399. struct vring_used_elem {
  400. /* Index of start of used descriptor chain. */
  401. u32 id;
  402. /* Total length of the descriptor chain which was used
  403. (written to) */
  404. u32 len;
  405. };
  406. struct vring_used {
  407. #define VRING_USED_F_NO_NOTIFY 1
  408. u16 flags;
  409. u16 idx;
  410. struct vring_used_elem ring[qsz];
  411. u16 avail_event;
  412. };
  413. Helpers for Managing Virtqueues
  414. The Linux Kernel Source code contains the definitions above and
  415. helper routines in a more usable form, in
  416. include/linux/virtio_ring.h. This was explicitly licensed by IBM
  417. and Red Hat under the (3-clause) BSD license so that it can be
  418. freely used by all other projects, and is reproduced (with slight
  419. variation to remove Linux assumptions) in Appendix A.
  420. Device Operation
  421. There are two parts to device operation: supplying new buffers to
  422. the device, and processing used buffers from the device. As an
  423. example, the virtio network device has two virtqueues: the
  424. transmit virtqueue and the receive virtqueue. The driver adds
  425. outgoing (read-only) packets to the transmit virtqueue, and then
  426. frees them after they are used. Similarly, incoming (write-only)
  427. buffers are added to the receive virtqueue, and processed after
  428. they are used.
  429. Supplying Buffers to The Device
  430. Actual transfer of buffers from the guest OS to the device
  431. operates as follows:
  432. Place the buffer(s) into free descriptor(s).
  433. If there are no free descriptors, the guest may choose to
  434. notify the device even if notifications are suppressed (to
  435. reduce latency).[footnote:
  436. The Linux drivers do this only for read-only buffers: for
  437. write-only buffers, it is assumed that the driver is merely
  438. trying to keep the receive buffer ring full, and no notification
  439. of this expected condition is necessary.
  440. ]
  441. Place the id of the buffer in the next ring entry of the
  442. available ring.
  443. The steps (1) and (2) may be performed repeatedly if batching
  444. is possible.
  445. A memory barrier should be executed to ensure the device sees
  446. the updated descriptor table and available ring before the next
  447. step.
  448. The available “idx” field should be increased by the number of
  449. entries added to the available ring.
  450. A memory barrier should be executed to ensure that we update
  451. the idx field before checking for notification suppression.
  452. If notifications are not suppressed, the device should be
  453. notified of the new buffers.
  454. Note that the above code does not take precautions against the
  455. available ring buffer wrapping around: this is not possible since
  456. the ring buffer is the same size as the descriptor table, so step
  457. (1) will prevent such a condition.
  458. In addition, the maximum queue size is 32768 (it must be a power
  459. of 2 which fits in 16 bits), so the 16-bit “idx” value can always
  460. distinguish between a full and empty buffer.
  461. Here is a description of each stage in more detail.
  462. Placing Buffers Into The Descriptor Table
  463. A buffer consists of zero or more read-only physically-contiguous
  464. elements followed by zero or more physically-contiguous
  465. write-only elements (it must have at least one element). This
  466. algorithm maps it into the descriptor table:
  467. for each buffer element, b:
  468. Get the next free descriptor table entry, d
  469. Set d.addr to the physical address of the start of b
  470. Set d.len to the length of b.
  471. If b is write-only, set d.flags to VRING_DESC_F_WRITE,
  472. otherwise 0.
  473. If there is a buffer element after this:
  474. Set d.next to the index of the next free descriptor element.
  475. Set the VRING_DESC_F_NEXT bit in d.flags.
  476. In practice, the d.next fields are usually used to chain free
  477. descriptors, and a separate count kept to check there are enough
  478. free descriptors before beginning the mappings.
  479. Updating The Available Ring
  480. The head of the buffer we mapped is the first d in the algorithm
  481. above. A naive implementation would do the following:
  482. avail->ring[avail->idx % qsz] = head;
  483. However, in general we can add many descriptors before we update
  484. the “idx” field (at which point they become visible to the
  485. device), so we keep a counter of how many we've added:
  486. avail->ring[(avail->idx + added++) % qsz] = head;
  487. Updating The Index Field
  488. Once the idx field of the virtqueue is updated, the device will
  489. be able to access the descriptor entries we've created and the
  490. memory they refer to. This is why a memory barrier is generally
  491. used before the idx update, to ensure it sees the most up-to-date
  492. copy.
  493. The idx field always increments, and we let it wrap naturally at
  494. 65536:
  495. avail->idx += added;
  496. <sub:Notifying-The-Device>Notifying The Device
  497. Device notification occurs by writing the 16-bit virtqueue index
  498. of this virtqueue to the Queue Notify field of the virtio header
  499. in the first I/O region of the PCI device. This can be expensive,
  500. however, so the device can suppress such notifications if it
  501. doesn't need them. We have to be careful to expose the new idx
  502. value before checking the suppression flag: it's OK to notify
  503. gratuitously, but not to omit a required notification. So again,
  504. we use a memory barrier here before reading the flags or the
  505. avail_event field.
  506. If the VIRTIO_F_RING_EVENT_IDX feature is not negotiated, and if
  507. the VRING_USED_F_NOTIFY flag is not set, we go ahead and write to
  508. the PCI configuration space.
  509. If the VIRTIO_F_RING_EVENT_IDX feature is negotiated, we read the
  510. avail_event field in the available ring structure. If the
  511. available index crossed_the avail_event field value since the
  512. last notification, we go ahead and write to the PCI configuration
  513. space. The avail_event field wraps naturally at 65536 as well:
  514. (u16)(new_idx - avail_event - 1) < (u16)(new_idx - old_idx)
  515. <sub:Receiving-Used-Buffers>Receiving Used Buffers From The
  516. Device
  517. Once the device has used a buffer (read from or written to it, or
  518. parts of both, depending on the nature of the virtqueue and the
  519. device), it sends an interrupt, following an algorithm very
  520. similar to the algorithm used for the driver to send the device a
  521. buffer:
  522. Write the head descriptor number to the next field in the used
  523. ring.
  524. Update the used ring idx.
  525. Determine whether an interrupt is necessary:
  526. If the VIRTIO_F_RING_EVENT_IDX feature is not negotiated: check
  527. if f the VRING_AVAIL_F_NO_INTERRUPT flag is not set in avail-
  528. >flags
  529. If the VIRTIO_F_RING_EVENT_IDX feature is negotiated: check
  530. whether the used index crossed the used_event field value
  531. since the last update. The used_event field wraps naturally
  532. at 65536 as well:(u16)(new_idx - used_event - 1) < (u16)(new_idx - old_idx)
  533. If an interrupt is necessary:
  534. If MSI-X capability is disabled:
  535. Set the lower bit of the ISR Status field for the device.
  536. Send the appropriate PCI interrupt for the device.
  537. If MSI-X capability is enabled:
  538. Request the appropriate MSI-X interrupt message for the
  539. device, Queue Vector field sets the MSI-X Table entry
  540. number.
  541. If Queue Vector field value is NO_VECTOR, no interrupt
  542. message is requested for this event.
  543. The guest interrupt handler should:
  544. If MSI-X capability is disabled: read the ISR Status field,
  545. which will reset it to zero. If the lower bit is zero, the
  546. interrupt was not for this device. Otherwise, the guest driver
  547. should look through the used rings of each virtqueue for the
  548. device, to see if any progress has been made by the device
  549. which requires servicing.
  550. If MSI-X capability is enabled: look through the used rings of
  551. each virtqueue mapped to the specific MSI-X vector for the
  552. device, to see if any progress has been made by the device
  553. which requires servicing.
  554. For each ring, guest should then disable interrupts by writing
  555. VRING_AVAIL_F_NO_INTERRUPT flag in avail structure, if required.
  556. It can then process used ring entries finally enabling interrupts
  557. by clearing the VRING_AVAIL_F_NO_INTERRUPT flag or updating the
  558. EVENT_IDX field in the available structure, Guest should then
  559. execute a memory barrier, and then recheck the ring empty
  560. condition. This is necessary to handle the case where, after the
  561. last check and before enabling interrupts, an interrupt has been
  562. suppressed by the device:
  563. vring_disable_interrupts(vq);
  564. for (;;) {
  565. if (vq->last_seen_used != vring->used.idx) {
  566. vring_enable_interrupts(vq);
  567. mb();
  568. if (vq->last_seen_used != vring->used.idx)
  569. break;
  570. }
  571. struct vring_used_elem *e =
  572. vring.used->ring[vq->last_seen_used%vsz];
  573. process_buffer(e);
  574. vq->last_seen_used++;
  575. }
  576. Dealing With Configuration Changes
  577. Some virtio PCI devices can change the device configuration
  578. state, as reflected in the virtio header in the PCI configuration
  579. space. In this case:
  580. If MSI-X capability is disabled: an interrupt is delivered and
  581. the second highest bit is set in the ISR Status field to
  582. indicate that the driver should re-examine the configuration
  583. space.Note that a single interrupt can indicate both that one
  584. or more virtqueue has been used and that the configuration
  585. space has changed: even if the config bit is set, virtqueues
  586. must be scanned.
  587. If MSI-X capability is enabled: an interrupt message is
  588. requested. The Configuration Vector field sets the MSI-X Table
  589. entry number to use. If Configuration Vector field value is
  590. NO_VECTOR, no interrupt message is requested for this event.
  591. Creating New Device Types
  592. Various considerations are necessary when creating a new device
  593. type:
  594. How Many Virtqueues?
  595. It is possible that a very simple device will operate entirely
  596. through its configuration space, but most will need at least one
  597. virtqueue in which it will place requests. A device with both
  598. input and output (eg. console and network devices described here)
  599. need two queues: one which the driver fills with buffers to
  600. receive input, and one which the driver places buffers to
  601. transmit output.
  602. What Configuration Space Layout?
  603. Configuration space is generally used for rarely-changing or
  604. initialization-time parameters. But it is a limited resource, so
  605. it might be better to use a virtqueue to update configuration
  606. information (the network device does this for filtering,
  607. otherwise the table in the config space could potentially be very
  608. large).
  609. Note that this space is generally the guest's native endian,
  610. rather than PCI's little-endian.
  611. What Device Number?
  612. Currently device numbers are assigned quite freely: a simple
  613. request mail to the author of this document or the Linux
  614. virtualization mailing list[footnote:
  615. https://lists.linux-foundation.org/mailman/listinfo/virtualization
  616. ] will be sufficient to secure a unique one.
  617. Meanwhile for experimental drivers, use 65535 and work backwards.
  618. How many MSI-X vectors?
  619. Using the optional MSI-X capability devices can speed up
  620. interrupt processing by removing the need to read ISR Status
  621. register by guest driver (which might be an expensive operation),
  622. reducing interrupt sharing between devices and queues within the
  623. device, and handling interrupts from multiple CPUs. However, some
  624. systems impose a limit (which might be as low as 256) on the
  625. total number of MSI-X vectors that can be allocated to all
  626. devices. Devices and/or device drivers should take this into
  627. account, limiting the number of vectors used unless the device is
  628. expected to cause a high volume of interrupts. Devices can
  629. control the number of vectors used by limiting the MSI-X Table
  630. Size or not presenting MSI-X capability in PCI configuration
  631. space. Drivers can control this by mapping events to as small
  632. number of vectors as possible, or disabling MSI-X capability
  633. altogether.
  634. Message Framing
  635. The descriptors used for a buffer should not effect the semantics
  636. of the message, except for the total length of the buffer. For
  637. example, a network buffer consists of a 10 byte header followed
  638. by the network packet. Whether this is presented in the ring
  639. descriptor chain as (say) a 10 byte buffer and a 1514 byte
  640. buffer, or a single 1524 byte buffer, or even three buffers,
  641. should have no effect.
  642. In particular, no implementation should use the descriptor
  643. boundaries to determine the size of any header in a request.[footnote:
  644. The current qemu device implementations mistakenly insist that
  645. the first descriptor cover the header in these cases exactly, so
  646. a cautious driver should arrange it so.
  647. ]
  648. Device Improvements
  649. Any change to configuration space, or new virtqueues, or
  650. behavioural changes, should be indicated by negotiation of a new
  651. feature bit. This establishes clarity[footnote:
  652. Even if it does mean documenting design or implementation
  653. mistakes!
  654. ] and avoids future expansion problems.
  655. Clusters of functionality which are always implemented together
  656. can use a single bit, but if one feature makes sense without the
  657. others they should not be gratuitously grouped together to
  658. conserve feature bits. We can always extend the spec when the
  659. first person needs more than 24 feature bits for their device.
  660. [LaTeX Command: printnomenclature]
  661. Appendix A: virtio_ring.h
  662. #ifndef VIRTIO_RING_H
  663. #define VIRTIO_RING_H
  664. /* An interface for efficient virtio implementation.
  665. *
  666. * This header is BSD licensed so anyone can use the definitions
  667. * to implement compatible drivers/servers.
  668. *
  669. * Copyright 2007, 2009, IBM Corporation
  670. * Copyright 2011, Red Hat, Inc
  671. * All rights reserved.
  672. *
  673. * Redistribution and use in source and binary forms, with or
  674. without
  675. * modification, are permitted provided that the following
  676. conditions
  677. * are met:
  678. * 1. Redistributions of source code must retain the above
  679. copyright
  680. * notice, this list of conditions and the following
  681. disclaimer.
  682. * 2. Redistributions in binary form must reproduce the above
  683. copyright
  684. * notice, this list of conditions and the following
  685. disclaimer in the
  686. * documentation and/or other materials provided with the
  687. distribution.
  688. * 3. Neither the name of IBM nor the names of its contributors
  689. * may be used to endorse or promote products derived from
  690. this software
  691. * without specific prior written permission.
  692. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  693. CONTRIBUTORS ``AS IS'' AND
  694. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
  695. TO, THE
  696. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
  697. PARTICULAR PURPOSE
  698. * ARE DISCLAIMED. IN NO EVENT SHALL IBM OR CONTRIBUTORS BE
  699. LIABLE
  700. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  701. CONSEQUENTIAL
  702. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  703. SUBSTITUTE GOODS
  704. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  705. INTERRUPTION)
  706. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  707. CONTRACT, STRICT
  708. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
  709. IN ANY WAY
  710. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  711. POSSIBILITY OF
  712. * SUCH DAMAGE.
  713. */
  714. /* This marks a buffer as continuing via the next field. */
  715. #define VRING_DESC_F_NEXT 1
  716. /* This marks a buffer as write-only (otherwise read-only). */
  717. #define VRING_DESC_F_WRITE 2
  718. /* The Host uses this in used->flags to advise the Guest: don't
  719. kick me
  720. * when you add a buffer. It's unreliable, so it's simply an
  721. * optimization. Guest will still kick if it's out of buffers.
  722. */
  723. #define VRING_USED_F_NO_NOTIFY 1
  724. /* The Guest uses this in avail->flags to advise the Host: don't
  725. * interrupt me when you consume a buffer. It's unreliable, so
  726. it's
  727. * simply an optimization. */
  728. #define VRING_AVAIL_F_NO_INTERRUPT 1
  729. /* Virtio ring descriptors: 16 bytes.
  730. * These can chain together via "next". */
  731. struct vring_desc {
  732. /* Address (guest-physical). */
  733. uint64_t addr;
  734. /* Length. */
  735. uint32_t len;
  736. /* The flags as indicated above. */
  737. uint16_t flags;
  738. /* We chain unused descriptors via this, too */
  739. uint16_t next;
  740. };
  741. struct vring_avail {
  742. uint16_t flags;
  743. uint16_t idx;
  744. uint16_t ring[];
  745. uint16_t used_event;
  746. };
  747. /* u32 is used here for ids for padding reasons. */
  748. struct vring_used_elem {
  749. /* Index of start of used descriptor chain. */
  750. uint32_t id;
  751. /* Total length of the descriptor chain which was written
  752. to. */
  753. uint32_t len;
  754. };
  755. struct vring_used {
  756. uint16_t flags;
  757. uint16_t idx;
  758. struct vring_used_elem ring[];
  759. uint16_t avail_event;
  760. };
  761. struct vring {
  762. unsigned int num;
  763. struct vring_desc *desc;
  764. struct vring_avail *avail;
  765. struct vring_used *used;
  766. };
  767. /* The standard layout for the ring is a continuous chunk of
  768. memory which
  769. * looks like this. We assume num is a power of 2.
  770. *
  771. * struct vring {
  772. * // The actual descriptors (16 bytes each)
  773. * struct vring_desc desc[num];
  774. *
  775. * // A ring of available descriptor heads with free-running
  776. index.
  777. * __u16 avail_flags;
  778. * __u16 avail_idx;
  779. * __u16 available[num];
  780. *
  781. * // Padding to the next align boundary.
  782. * char pad[];
  783. *
  784. * // A ring of used descriptor heads with free-running
  785. index.
  786. * __u16 used_flags;
  787. * __u16 EVENT_IDX;
  788. * struct vring_used_elem used[num];
  789. * };
  790. * Note: for virtio PCI, align is 4096.
  791. */
  792. static inline void vring_init(struct vring *vr, unsigned int num,
  793. void *p,
  794. unsigned long align)
  795. {
  796. vr->num = num;
  797. vr->desc = p;
  798. vr->avail = p + num*sizeof(struct vring_desc);
  799. vr->used = (void *)(((unsigned long)&vr->avail->ring[num]
  800. + align-1)
  801. & ~(align - 1));
  802. }
  803. static inline unsigned vring_size(unsigned int num, unsigned long
  804. align)
  805. {
  806. return ((sizeof(struct vring_desc)*num +
  807. sizeof(uint16_t)*(2+num)
  808. + align - 1) & ~(align - 1))
  809. + sizeof(uint16_t)*3 + sizeof(struct
  810. vring_used_elem)*num;
  811. }
  812. static inline int vring_need_event(uint16_t event_idx, uint16_t
  813. new_idx, uint16_t old_idx)
  814. {
  815. return (uint16_t)(new_idx - event_idx - 1) <
  816. (uint16_t)(new_idx - old_idx);
  817. }
  818. #endif /* VIRTIO_RING_H */
  819. <cha:Reserved-Feature-Bits>Appendix B: Reserved Feature Bits
  820. Currently there are five device-independent feature bits defined:
  821. VIRTIO_F_NOTIFY_ON_EMPTY (24) Negotiating this feature
  822. indicates that the driver wants an interrupt if the device runs
  823. out of available descriptors on a virtqueue, even though
  824. interrupts are suppressed using the VRING_AVAIL_F_NO_INTERRUPT
  825. flag or the used_event field. An example of this is the
  826. networking driver: it doesn't need to know every time a packet
  827. is transmitted, but it does need to free the transmitted
  828. packets a finite time after they are transmitted. It can avoid
  829. using a timer if the device interrupts it when all the packets
  830. are transmitted.
  831. VIRTIO_F_RING_INDIRECT_DESC (28) Negotiating this feature
  832. indicates that the driver can use descriptors with the
  833. VRING_DESC_F_INDIRECT flag set, as described in [sub:Indirect-Descriptors]
  834. .
  835. VIRTIO_F_RING_EVENT_IDX(29) This feature enables the used_event
  836. and the avail_event fields. If set, it indicates that the
  837. device should ignore the flags field in the available ring
  838. structure. Instead, the used_event field in this structure is
  839. used by guest to suppress device interrupts. Further, the
  840. driver should ignore the flags field in the used ring
  841. structure. Instead, the avail_event field in this structure is
  842. used by the device to suppress notifications. If unset, the
  843. driver should ignore the used_event field; the device should
  844. ignore the avail_event field; the flags field is used
  845. VIRTIO_F_BAD_FEATURE(30) This feature should never be
  846. negotiated by the guest; doing so is an indication that the
  847. guest is faulty[footnote:
  848. An experimental virtio PCI driver contained in Linux version
  849. 2.6.25 had this problem, and this feature bit can be used to
  850. detect it.
  851. ]
  852. VIRTIO_F_FEATURES_HIGH(31) This feature indicates that the
  853. device supports feature bits 32:63. If unset, feature bits
  854. 32:63 are unset.
  855. Appendix C: Network Device
  856. The virtio network device is a virtual ethernet card, and is the
  857. most complex of the devices supported so far by virtio. It has
  858. enhanced rapidly and demonstrates clearly how support for new
  859. features should be added to an existing device. Empty buffers are
  860. placed in one virtqueue for receiving packets, and outgoing
  861. packets are enqueued into another for transmission in that order.
  862. A third command queue is used to control advanced filtering
  863. features.
  864. Configuration
  865. Subsystem Device ID 1
  866. Virtqueues 0:receiveq. 1:transmitq. 2:controlq[footnote:
  867. Only if VIRTIO_NET_F_CTRL_VQ set
  868. ]
  869. Feature bits
  870. VIRTIO_NET_F_CSUM (0) Device handles packets with partial
  871. checksum
  872. VIRTIO_NET_F_GUEST_CSUM (1) Guest handles packets with partial
  873. checksum
  874. VIRTIO_NET_F_MAC (5) Device has given MAC address.
  875. VIRTIO_NET_F_GSO (6) (Deprecated) device handles packets with
  876. any GSO type.[footnote:
  877. It was supposed to indicate segmentation offload support, but
  878. upon further investigation it became clear that multiple bits
  879. were required.
  880. ]
  881. VIRTIO_NET_F_GUEST_TSO4 (7) Guest can receive TSOv4.
  882. VIRTIO_NET_F_GUEST_TSO6 (8) Guest can receive TSOv6.
  883. VIRTIO_NET_F_GUEST_ECN (9) Guest can receive TSO with ECN.
  884. VIRTIO_NET_F_GUEST_UFO (10) Guest can receive UFO.
  885. VIRTIO_NET_F_HOST_TSO4 (11) Device can receive TSOv4.
  886. VIRTIO_NET_F_HOST_TSO6 (12) Device can receive TSOv6.
  887. VIRTIO_NET_F_HOST_ECN (13) Device can receive TSO with ECN.
  888. VIRTIO_NET_F_HOST_UFO (14) Device can receive UFO.
  889. VIRTIO_NET_F_MRG_RXBUF (15) Guest can merge receive buffers.
  890. VIRTIO_NET_F_STATUS (16) Configuration status field is
  891. available.
  892. VIRTIO_NET_F_CTRL_VQ (17) Control channel is available.
  893. VIRTIO_NET_F_CTRL_RX (18) Control channel RX mode support.
  894. VIRTIO_NET_F_CTRL_VLAN (19) Control channel VLAN filtering.
  895. Device configuration layout Two configuration fields are
  896. currently defined. The mac address field always exists (though
  897. is only valid if VIRTIO_NET_F_MAC is set), and the status field
  898. only exists if VIRTIO_NET_F_STATUS is set. Only one bit is
  899. currently defined for the status field: VIRTIO_NET_S_LINK_UP. #define VIRTIO_NET_S_LINK_UP 1
  900. struct virtio_net_config {
  901. u8 mac[6];
  902. u16 status;
  903. };
  904. Device Initialization
  905. The initialization routine should identify the receive and
  906. transmission virtqueues.
  907. If the VIRTIO_NET_F_MAC feature bit is set, the configuration
  908. space “mac” entry indicates the “physical” address of the the
  909. network card, otherwise a private MAC address should be
  910. assigned. All guests are expected to negotiate this feature if
  911. it is set.
  912. If the VIRTIO_NET_F_CTRL_VQ feature bit is negotiated, identify
  913. the control virtqueue.
  914. If the VIRTIO_NET_F_STATUS feature bit is negotiated, the link
  915. status can be read from the bottom bit of the “status” config
  916. field. Otherwise, the link should be assumed active.
  917. The receive virtqueue should be filled with receive buffers.
  918. This is described in detail below in “Setting Up Receive
  919. Buffers”.
  920. A driver can indicate that it will generate checksumless
  921. packets by negotating the VIRTIO_NET_F_CSUM feature. This “
  922. checksum offload” is a common feature on modern network cards.
  923. If that feature is negotiated, a driver can use TCP or UDP
  924. segmentation offload by negotiating the VIRTIO_NET_F_HOST_TSO4
  925. (IPv4 TCP), VIRTIO_NET_F_HOST_TSO6 (IPv6 TCP) and
  926. VIRTIO_NET_F_HOST_UFO (UDP fragmentation) features. It should
  927. not send TCP packets requiring segmentation offload which have
  928. the Explicit Congestion Notification bit set, unless the
  929. VIRTIO_NET_F_HOST_ECN feature is negotiated.[footnote:
  930. This is a common restriction in real, older network cards.
  931. ]
  932. The converse features are also available: a driver can save the
  933. virtual device some work by negotiating these features.[footnote:
  934. For example, a network packet transported between two guests on
  935. the same system may not require checksumming at all, nor
  936. segmentation, if both guests are amenable.
  937. ] The VIRTIO_NET_F_GUEST_CSUM feature indicates that partially
  938. checksummed packets can be received, and if it can do that then
  939. the VIRTIO_NET_F_GUEST_TSO4, VIRTIO_NET_F_GUEST_TSO6,
  940. VIRTIO_NET_F_GUEST_UFO and VIRTIO_NET_F_GUEST_ECN are the input
  941. equivalents of the features described above. See “Receiving
  942. Packets” below.
  943. Device Operation
  944. Packets are transmitted by placing them in the transmitq, and
  945. buffers for incoming packets are placed in the receiveq. In each
  946. case, the packet itself is preceded by a header:
  947. struct virtio_net_hdr {
  948. #define VIRTIO_NET_HDR_F_NEEDS_CSUM 1
  949. u8 flags;
  950. #define VIRTIO_NET_HDR_GSO_NONE 0
  951. #define VIRTIO_NET_HDR_GSO_TCPV4 1
  952. #define VIRTIO_NET_HDR_GSO_UDP 3
  953. #define VIRTIO_NET_HDR_GSO_TCPV6 4
  954. #define VIRTIO_NET_HDR_GSO_ECN 0x80
  955. u8 gso_type;
  956. u16 hdr_len;
  957. u16 gso_size;
  958. u16 csum_start;
  959. u16 csum_offset;
  960. /* Only if VIRTIO_NET_F_MRG_RXBUF: */
  961. u16 num_buffers
  962. };
  963. The controlq is used to control device features such as
  964. filtering.
  965. Packet Transmission
  966. Transmitting a single packet is simple, but varies depending on
  967. the different features the driver negotiated.
  968. If the driver negotiated VIRTIO_NET_F_CSUM, and the packet has
  969. not been fully checksummed, then the virtio_net_hdr's fields
  970. are set as follows. Otherwise, the packet must be fully
  971. checksummed, and flags is zero.
  972. flags has the VIRTIO_NET_HDR_F_NEEDS_CSUM set,
  973. <ite:csum_start-is-set>csum_start is set to the offset within
  974. the packet to begin checksumming, and
  975. csum_offset indicates how many bytes after the csum_start the
  976. new (16 bit ones' complement) checksum should be placed.[footnote:
  977. For example, consider a partially checksummed TCP (IPv4) packet.
  978. It will have a 14 byte ethernet header and 20 byte IP header
  979. followed by the TCP header (with the TCP checksum field 16 bytes
  980. into that header). csum_start will be 14+20 = 34 (the TCP
  981. checksum includes the header), and csum_offset will be 16. The
  982. value in the TCP checksum field will be the sum of the TCP pseudo
  983. header, so that replacing it by the ones' complement checksum of
  984. the TCP header and body will give the correct result.
  985. ]
  986. <enu:If-the-driver>If the driver negotiated
  987. VIRTIO_NET_F_HOST_TSO4, TSO6 or UFO, and the packet requires
  988. TCP segmentation or UDP fragmentation, then the “gso_type”
  989. field is set to VIRTIO_NET_HDR_GSO_TCPV4, TCPV6 or UDP.
  990. (Otherwise, it is set to VIRTIO_NET_HDR_GSO_NONE). In this
  991. case, packets larger than 1514 bytes can be transmitted: the
  992. metadata indicates how to replicate the packet header to cut it
  993. into smaller packets. The other gso fields are set:
  994. hdr_len is a hint to the device as to how much of the header
  995. needs to be kept to copy into each packet, usually set to the
  996. length of the headers, including the transport header.[footnote:
  997. Due to various bugs in implementations, this field is not useful
  998. as a guarantee of the transport header size.
  999. ]
  1000. gso_size is the size of the packet beyond that header (ie.
  1001. MSS).
  1002. If the driver negotiated the VIRTIO_NET_F_HOST_ECN feature, the
  1003. VIRTIO_NET_HDR_GSO_ECN bit may be set in “gso_type” as well,
  1004. indicating that the TCP packet has the ECN bit set.[footnote:
  1005. This case is not handled by some older hardware, so is called out
  1006. specifically in the protocol.
  1007. ]
  1008. If the driver negotiated the VIRTIO_NET_F_MRG_RXBUF feature,
  1009. the num_buffers field is set to zero.
  1010. The header and packet are added as one output buffer to the
  1011. transmitq, and the device is notified of the new entry (see [sub:Notifying-The-Device]
  1012. ).[footnote:
  1013. Note that the header will be two bytes longer for the
  1014. VIRTIO_NET_F_MRG_RXBUF case.
  1015. ]
  1016. Packet Transmission Interrupt
  1017. Often a driver will suppress transmission interrupts using the
  1018. VRING_AVAIL_F_NO_INTERRUPT flag (see [sub:Receiving-Used-Buffers]
  1019. ) and check for used packets in the transmit path of following
  1020. packets. However, it will still receive interrupts if the
  1021. VIRTIO_F_NOTIFY_ON_EMPTY feature is negotiated, indicating that
  1022. the transmission queue is completely emptied.
  1023. The normal behavior in this interrupt handler is to retrieve and
  1024. new descriptors from the used ring and free the corresponding
  1025. headers and packets.
  1026. Setting Up Receive Buffers
  1027. It is generally a good idea to keep the receive virtqueue as
  1028. fully populated as possible: if it runs out, network performance
  1029. will suffer.
  1030. If the VIRTIO_NET_F_GUEST_TSO4, VIRTIO_NET_F_GUEST_TSO6 or
  1031. VIRTIO_NET_F_GUEST_UFO features are used, the Guest will need to
  1032. accept packets of up to 65550 bytes long (the maximum size of a
  1033. TCP or UDP packet, plus the 14 byte ethernet header), otherwise
  1034. 1514 bytes. So unless VIRTIO_NET_F_MRG_RXBUF is negotiated, every
  1035. buffer in the receive queue needs to be at least this length [footnote:
  1036. Obviously each one can be split across multiple descriptor
  1037. elements.
  1038. ].
  1039. If VIRTIO_NET_F_MRG_RXBUF is negotiated, each buffer must be at
  1040. least the size of the struct virtio_net_hdr.
  1041. Packet Receive Interrupt
  1042. When a packet is copied into a buffer in the receiveq, the
  1043. optimal path is to disable further interrupts for the receiveq
  1044. (see [sub:Receiving-Used-Buffers]) and process packets until no
  1045. more are found, then re-enable them.
  1046. Processing packet involves:
  1047. If the driver negotiated the VIRTIO_NET_F_MRG_RXBUF feature,
  1048. then the “num_buffers” field indicates how many descriptors
  1049. this packet is spread over (including this one). This allows
  1050. receipt of large packets without having to allocate large
  1051. buffers. In this case, there will be at least “num_buffers” in
  1052. the used ring, and they should be chained together to form a
  1053. single packet. The other buffers will not begin with a struct
  1054. virtio_net_hdr.
  1055. If the VIRTIO_NET_F_MRG_RXBUF feature was not negotiated, or
  1056. the “num_buffers” field is one, then the entire packet will be
  1057. contained within this buffer, immediately following the struct
  1058. virtio_net_hdr.
  1059. If the VIRTIO_NET_F_GUEST_CSUM feature was negotiated, the
  1060. VIRTIO_NET_HDR_F_NEEDS_CSUM bit in the “flags” field may be
  1061. set: if so, the checksum on the packet is incomplete and the “
  1062. csum_start” and “csum_offset” fields indicate how to calculate
  1063. it (see [ite:csum_start-is-set]).
  1064. If the VIRTIO_NET_F_GUEST_TSO4, TSO6 or UFO options were
  1065. negotiated, then the “gso_type” may be something other than
  1066. VIRTIO_NET_HDR_GSO_NONE, and the “gso_size” field indicates the
  1067. desired MSS (see [enu:If-the-driver]).Control Virtqueue
  1068. The driver uses the control virtqueue (if VIRTIO_NET_F_VTRL_VQ is
  1069. negotiated) to send commands to manipulate various features of
  1070. the device which would not easily map into the configuration
  1071. space.
  1072. All commands are of the following form:
  1073. struct virtio_net_ctrl {
  1074. u8 class;
  1075. u8 command;
  1076. u8 command-specific-data[];
  1077. u8 ack;
  1078. };
  1079. /* ack values */
  1080. #define VIRTIO_NET_OK 0
  1081. #define VIRTIO_NET_ERR 1
  1082. The class, command and command-specific-data are set by the
  1083. driver, and the device sets the ack byte. There is little it can
  1084. do except issue a diagnostic if the ack byte is not
  1085. VIRTIO_NET_OK.
  1086. Packet Receive Filtering
  1087. If the VIRTIO_NET_F_CTRL_RX feature is negotiated, the driver can
  1088. send control commands for promiscuous mode, multicast receiving,
  1089. and filtering of MAC addresses.
  1090. Note that in general, these commands are best-effort: unwanted
  1091. packets may still arrive.
  1092. Setting Promiscuous Mode
  1093. #define VIRTIO_NET_CTRL_RX 0
  1094. #define VIRTIO_NET_CTRL_RX_PROMISC 0
  1095. #define VIRTIO_NET_CTRL_RX_ALLMULTI 1
  1096. The class VIRTIO_NET_CTRL_RX has two commands:
  1097. VIRTIO_NET_CTRL_RX_PROMISC turns promiscuous mode on and off, and
  1098. VIRTIO_NET_CTRL_RX_ALLMULTI turns all-multicast receive on and
  1099. off. The command-specific-data is one byte containing 0 (off) or
  1100. 1 (on).
  1101. Setting MAC Address Filtering
  1102. struct virtio_net_ctrl_mac {
  1103. u32 entries;
  1104. u8 macs[entries][ETH_ALEN];
  1105. };
  1106. #define VIRTIO_NET_CTRL_MAC 1
  1107. #define VIRTIO_NET_CTRL_MAC_TABLE_SET 0
  1108. The device can filter incoming packets by any number of
  1109. destination MAC addresses.[footnote:
  1110. Since there are no guarantees, it can use a hash filter
  1111. orsilently switch to allmulti or promiscuous mode if it is given
  1112. too many addresses.
  1113. ] This table is set using the class VIRTIO_NET_CTRL_MAC and the
  1114. command VIRTIO_NET_CTRL_MAC_TABLE_SET. The command-specific-data
  1115. is two variable length tables of 6-byte MAC addresses. The first
  1116. table contains unicast addresses, and the second contains
  1117. multicast addresses.
  1118. VLAN Filtering
  1119. If the driver negotiates the VIRTION_NET_F_CTRL_VLAN feature, it
  1120. can control a VLAN filter table in the device.
  1121. #define VIRTIO_NET_CTRL_VLAN 2
  1122. #define VIRTIO_NET_CTRL_VLAN_ADD 0
  1123. #define VIRTIO_NET_CTRL_VLAN_DEL 1
  1124. Both the VIRTIO_NET_CTRL_VLAN_ADD and VIRTIO_NET_CTRL_VLAN_DEL
  1125. command take a 16-bit VLAN id as the command-specific-data.
  1126. Appendix D: Block Device
  1127. The virtio block device is a simple virtual block device (ie.
  1128. disk). Read and write requests (and other exotic requests) are
  1129. placed in the queue, and serviced (probably out of order) by the
  1130. device except where noted.
  1131. Configuration
  1132. Subsystem Device ID 2
  1133. Virtqueues 0:requestq.
  1134. Feature bits
  1135. VIRTIO_BLK_F_BARRIER (0) Host supports request barriers.
  1136. VIRTIO_BLK_F_SIZE_MAX (1) Maximum size of any single segment is
  1137. in “size_max”.
  1138. VIRTIO_BLK_F_SEG_MAX (2) Maximum number of segments in a
  1139. request is in “seg_max”.
  1140. VIRTIO_BLK_F_GEOMETRY (4) Disk-style geometry specified in “
  1141. geometry”.
  1142. VIRTIO_BLK_F_RO (5) Device is read-only.
  1143. VIRTIO_BLK_F_BLK_SIZE (6) Block size of disk is in “blk_size”.
  1144. VIRTIO_BLK_F_SCSI (7) Device supports scsi packet commands.
  1145. VIRTIO_BLK_F_FLUSH (9) Cache flush command support.
  1146. Device configuration layout The capacity of the device
  1147. (expressed in 512-byte sectors) is always present. The
  1148. availability of the others all depend on various feature bits
  1149. as indicated above. struct virtio_blk_config {
  1150. u64 capacity;
  1151. u32 size_max;
  1152. u32 seg_max;
  1153. struct virtio_blk_geometry {
  1154. u16 cylinders;
  1155. u8 heads;
  1156. u8 sectors;
  1157. } geometry;
  1158. u32 blk_size;
  1159. };
  1160. Device Initialization
  1161. The device size should be read from the “capacity”
  1162. configuration field. No requests should be submitted which goes
  1163. beyond this limit.
  1164. If the VIRTIO_BLK_F_BLK_SIZE feature is negotiated, the
  1165. blk_size field can be read to determine the optimal sector size
  1166. for the driver to use. This does not effect the units used in
  1167. the protocol (always 512 bytes), but awareness of the correct
  1168. value can effect performance.
  1169. If the VIRTIO_BLK_F_RO feature is set by the device, any write
  1170. requests will fail.
  1171. Device Operation
  1172. The driver queues requests to the virtqueue, and they are used by
  1173. the device (not necessarily in order). Each request is of form:
  1174. struct virtio_blk_req {
  1175. u32 type;
  1176. u32 ioprio;
  1177. u64 sector;
  1178. char data[][512];
  1179. u8 status;
  1180. };
  1181. If the device has VIRTIO_BLK_F_SCSI feature, it can also support
  1182. scsi packet command requests, each of these requests is of form:struct virtio_scsi_pc_req {
  1183. u32 type;
  1184. u32 ioprio;
  1185. u64 sector;
  1186. char cmd[];
  1187. char data[][512];
  1188. #define SCSI_SENSE_BUFFERSIZE 96
  1189. u8 sense[SCSI_SENSE_BUFFERSIZE];
  1190. u32 errors;
  1191. u32 data_len;
  1192. u32 sense_len;
  1193. u32 residual;
  1194. u8 status;
  1195. };
  1196. The type of the request is either a read (VIRTIO_BLK_T_IN), a
  1197. write (VIRTIO_BLK_T_OUT), a scsi packet command
  1198. (VIRTIO_BLK_T_SCSI_CMD or VIRTIO_BLK_T_SCSI_CMD_OUT[footnote:
  1199. the SCSI_CMD and SCSI_CMD_OUT types are equivalent, the device
  1200. does not distinguish between them
  1201. ]) or a flush (VIRTIO_BLK_T_FLUSH or VIRTIO_BLK_T_FLUSH_OUT[footnote:
  1202. the FLUSH and FLUSH_OUT types are equivalent, the device does not
  1203. distinguish between them
  1204. ]). If the device has VIRTIO_BLK_F_BARRIER feature the high bit
  1205. (VIRTIO_BLK_T_BARRIER) indicates that this request acts as a
  1206. barrier and that all preceding requests must be complete before
  1207. this one, and all following requests must not be started until
  1208. this is complete. Note that a barrier does not flush caches in
  1209. the underlying backend device in host, and thus does not serve as
  1210. data consistency guarantee. Driver must use FLUSH request to
  1211. flush the host cache.
  1212. #define VIRTIO_BLK_T_IN 0
  1213. #define VIRTIO_BLK_T_OUT 1
  1214. #define VIRTIO_BLK_T_SCSI_CMD 2
  1215. #define VIRTIO_BLK_T_SCSI_CMD_OUT 3
  1216. #define VIRTIO_BLK_T_FLUSH 4
  1217. #define VIRTIO_BLK_T_FLUSH_OUT 5
  1218. #define VIRTIO_BLK_T_BARRIER 0x80000000
  1219. The ioprio field is a hint about the relative priorities of
  1220. requests to the device: higher numbers indicate more important
  1221. requests.
  1222. The sector number indicates the offset (multiplied by 512) where
  1223. the read or write is to occur. This field is unused and set to 0
  1224. for scsi packet commands and for flush commands.
  1225. The cmd field is only present for scsi packet command requests,
  1226. and indicates the command to perform. This field must reside in a
  1227. single, separate read-only buffer; command length can be derived
  1228. from the length of this buffer.
  1229. Note that these first three (four for scsi packet commands)
  1230. fields are always read-only: the data field is either read-only
  1231. or write-only, depending on the request. The size of the read or
  1232. write can be derived from the total size of the request buffers.
  1233. The sense field is only present for scsi packet command requests,
  1234. and indicates the buffer for scsi sense data.
  1235. The data_len field is only present for scsi packet command
  1236. requests, this field is deprecated, and should be ignored by the
  1237. driver. Historically, devices copied data length there.
  1238. The sense_len field is only present for scsi packet command
  1239. requests and indicates the number of bytes actually written to
  1240. the sense buffer.
  1241. The residual field is only present for scsi packet command
  1242. requests and indicates the residual size, calculated as data
  1243. length - number of bytes actually transferred.
  1244. The final status byte is written by the device: either
  1245. VIRTIO_BLK_S_OK for success, VIRTIO_BLK_S_IOERR for host or guest
  1246. error or VIRTIO_BLK_S_UNSUPP for a request unsupported by host:#define VIRTIO_BLK_S_OK 0
  1247. #define VIRTIO_BLK_S_IOERR 1
  1248. #define VIRTIO_BLK_S_UNSUPP 2
  1249. Historically, devices assumed that the fields type, ioprio and
  1250. sector reside in a single, separate read-only buffer; the fields
  1251. errors, data_len, sense_len and residual reside in a single,
  1252. separate write-only buffer; the sense field in a separate
  1253. write-only buffer of size 96 bytes, by itself; the fields errors,
  1254. data_len, sense_len and residual in a single write-only buffer;
  1255. and the status field is a separate read-only buffer of size 1
  1256. byte, by itself.
  1257. Appendix E: Console Device
  1258. The virtio console device is a simple device for data input and
  1259. output. A device may have one or more ports. Each port has a pair
  1260. of input and output virtqueues. Moreover, a device has a pair of
  1261. control IO virtqueues. The control virtqueues are used to
  1262. communicate information between the device and the driver about
  1263. ports being opened and closed on either side of the connection,
  1264. indication from the host about whether a particular port is a
  1265. console port, adding new ports, port hot-plug/unplug, etc., and
  1266. indication from the guest about whether a port or a device was
  1267. successfully added, port open/close, etc.. For data IO, one or
  1268. more empty buffers are placed in the receive queue for incoming
  1269. data and outgoing characters are placed in the transmit queue.
  1270. Configuration
  1271. Subsystem Device ID 3
  1272. Virtqueues 0:receiveq(port0). 1:transmitq(port0), 2:control
  1273. receiveq[footnote:
  1274. Ports 2 onwards only if VIRTIO_CONSOLE_F_MULTIPORT is set
  1275. ], 3:control transmitq, 4:receiveq(port1), 5:transmitq(port1),
  1276. ...
  1277. Feature bits
  1278. VIRTIO_CONSOLE_F_SIZE (0) Configuration cols and rows fields
  1279. are valid.
  1280. VIRTIO_CONSOLE_F_MULTIPORT(1) Device has support for multiple
  1281. ports; configuration fields nr_ports and max_nr_ports are
  1282. valid and control virtqueues will be used.
  1283. Device configuration layout The size of the console is supplied
  1284. in the configuration space if the VIRTIO_CONSOLE_F_SIZE feature
  1285. is set. Furthermore, if the VIRTIO_CONSOLE_F_MULTIPORT feature
  1286. is set, the maximum number of ports supported by the device can
  1287. be fetched.struct virtio_console_config {
  1288. u16 cols;
  1289. u16 rows;
  1290. u32 max_nr_ports;
  1291. };
  1292. Device Initialization
  1293. If the VIRTIO_CONSOLE_F_SIZE feature is negotiated, the driver
  1294. can read the console dimensions from the configuration fields.
  1295. If the VIRTIO_CONSOLE_F_MULTIPORT feature is negotiated, the
  1296. driver can spawn multiple ports, not all of which may be
  1297. attached to a console. Some could be generic ports. In this
  1298. case, the control virtqueues are enabled and according to the
  1299. max_nr_ports configuration-space value, the appropriate number
  1300. of virtqueues are created. A control message indicating the
  1301. driver is ready is sent to the host. The host can then send
  1302. control messages for adding new ports to the device. After
  1303. creating and initializing each port, a
  1304. VIRTIO_CONSOLE_PORT_READY control message is sent to the host
  1305. for that port so the host can let us know of any additional
  1306. configuration options set for that port.
  1307. The receiveq for each port is populated with one or more
  1308. receive buffers.
  1309. Device Operation
  1310. For output, a buffer containing the characters is placed in the
  1311. port's transmitq.[footnote:
  1312. Because this is high importance and low bandwidth, the current
  1313. Linux implementation polls for the buffer to be used, rather than
  1314. waiting for an interrupt, simplifying the implementation
  1315. significantly. However, for generic serial ports with the
  1316. O_NONBLOCK flag set, the polling limitation is relaxed and the
  1317. consumed buffers are freed upon the next write or poll call or
  1318. when a port is closed or hot-unplugged.
  1319. ]
  1320. When a buffer is used in the receiveq (signalled by an
  1321. interrupt), the contents is the input to the port associated
  1322. with the virtqueue for which the notification was received.
  1323. If the driver negotiated the VIRTIO_CONSOLE_F_SIZE feature, a
  1324. configuration change interrupt may occur. The updated size can
  1325. be read from the configuration fields.
  1326. If the driver negotiated the VIRTIO_CONSOLE_F_MULTIPORT
  1327. feature, active ports are announced by the host using the
  1328. VIRTIO_CONSOLE_PORT_ADD control message. The same message is
  1329. used for port hot-plug as well.
  1330. If the host specified a port `name', a sysfs attribute is
  1331. created with the name filled in, so that udev rules can be
  1332. written that can create a symlink from the port's name to the
  1333. char device for port discovery by applications in the guest.
  1334. Changes to ports' state are effected by control messages.
  1335. Appropriate action is taken on the port indicated in the
  1336. control message. The layout of the structure of the control
  1337. buffer and the events associated are:struct virtio_console_control {
  1338. uint32_t id; /* Port number */
  1339. uint16_t event; /* The kind of control event */
  1340. uint16_t value; /* Extra information for the event */
  1341. };
  1342. /* Some events for the internal messages (control packets) */
  1343. #define VIRTIO_CONSOLE_DEVICE_READY 0
  1344. #define VIRTIO_CONSOLE_PORT_ADD 1
  1345. #define VIRTIO_CONSOLE_PORT_REMOVE 2
  1346. #define VIRTIO_CONSOLE_PORT_READY 3
  1347. #define VIRTIO_CONSOLE_CONSOLE_PORT 4
  1348. #define VIRTIO_CONSOLE_RESIZE 5
  1349. #define VIRTIO_CONSOLE_PORT_OPEN 6
  1350. #define VIRTIO_CONSOLE_PORT_NAME 7
  1351. Appendix F: Entropy Device
  1352. The virtio entropy device supplies high-quality randomness for
  1353. guest use.
  1354. Configuration
  1355. Subsystem Device ID 4
  1356. Virtqueues 0:requestq.
  1357. Feature bits None currently defined
  1358. Device configuration layout None currently defined.
  1359. Device Initialization
  1360. The virtqueue is initialized
  1361. Device Operation
  1362. When the driver requires random bytes, it places the descriptor
  1363. of one or more buffers in the queue. It will be completely filled
  1364. by random data by the device.
  1365. Appendix G: Memory Balloon Device
  1366. The virtio memory balloon device is a primitive device for
  1367. managing guest memory: the device asks for a certain amount of
  1368. memory, and the guest supplies it (or withdraws it, if the device
  1369. has more than it asks for). This allows the guest to adapt to
  1370. changes in allowance of underlying physical memory. If the
  1371. feature is negotiated, the device can also be used to communicate
  1372. guest memory statistics to the host.
  1373. Configuration
  1374. Subsystem Device ID 5
  1375. Virtqueues 0:inflateq. 1:deflateq. 2:statsq.[footnote:
  1376. Only if VIRTIO_BALLON_F_STATS_VQ set
  1377. ]
  1378. Feature bits
  1379. VIRTIO_BALLOON_F_MUST_TELL_HOST (0) Host must be told before
  1380. pages from the balloon are used.
  1381. VIRTIO_BALLOON_F_STATS_VQ (1) A virtqueue for reporting guest
  1382. memory statistics is present.
  1383. Device configuration layout Both fields of this configuration
  1384. are always available. Note that they are little endian, despite
  1385. convention that device fields are guest endian:struct virtio_balloon_config {
  1386. u32 num_pages;
  1387. u32 actual;
  1388. };
  1389. Device Initialization
  1390. The inflate and deflate virtqueues are identified.
  1391. If the VIRTIO_BALLOON_F_STATS_VQ feature bit is negotiated:
  1392. Identify the stats virtqueue.
  1393. Add one empty buffer to the stats virtqueue and notify the
  1394. host.
  1395. Device operation begins immediately.
  1396. Device Operation
  1397. Memory Ballooning The device is driven by the receipt of a
  1398. configuration change interrupt.
  1399. The “num_pages” configuration field is examined. If this is
  1400. greater than the “actual” number of pages, memory must be given
  1401. to the balloon. If it is less than the “actual” number of
  1402. pages, memory may be taken back from the balloon for general
  1403. use.
  1404. To supply memory to the balloon (aka. inflate):
  1405. The driver constructs an array of addresses of unused memory
  1406. pages. These addresses are divided by 4096[footnote:
  1407. This is historical, and independent of the guest page size
  1408. ] and the descriptor describing the resulting 32-bit array is
  1409. added to the inflateq.
  1410. To remove memory from the balloon (aka. deflate):
  1411. The driver constructs an array of addresses of memory pages it
  1412. has previously given to the balloon, as described above. This
  1413. descriptor is added to the deflateq.
  1414. If the VIRTIO_BALLOON_F_MUST_TELL_HOST feature is set, the
  1415. guest may not use these requested pages until that descriptor
  1416. in the deflateq has been used by the device.
  1417. Otherwise, the guest may begin to re-use pages previously given
  1418. to the balloon before the device has acknowledged their
  1419. withdrawal. [footnote:
  1420. In this case, deflation advice is merely a courtesy
  1421. ]
  1422. In either case, once the device has completed the inflation or
  1423. deflation, the “actual” field of the configuration should be
  1424. updated to reflect the new number of pages in the balloon.[footnote:
  1425. As updates to configuration space are not atomic, this field
  1426. isn't particularly reliable, but can be used to diagnose buggy
  1427. guests.
  1428. ]
  1429. Memory Statistics
  1430. The stats virtqueue is atypical because communication is driven
  1431. by the device (not the driver). The channel becomes active at
  1432. driver initialization time when the driver adds an empty buffer
  1433. and notifies the device. A request for memory statistics proceeds
  1434. as follows:
  1435. The device pushes the buffer onto the used ring and sends an
  1436. interrupt.
  1437. The driver pops the used buffer and discards it.
  1438. The driver collects memory statistics and writes them into a
  1439. new buffer.
  1440. The driver adds the buffer to the virtqueue and notifies the
  1441. device.
  1442. The device pops the buffer (retaining it to initiate a
  1443. subsequent request) and consumes the statistics.
  1444. Memory Statistics Format Each statistic consists of a 16 bit
  1445. tag and a 64 bit value. Both quantities are represented in the
  1446. native endian of the guest. All statistics are optional and the
  1447. driver may choose which ones to supply. To guarantee backwards
  1448. compatibility, unsupported statistics should be omitted.
  1449. struct virtio_balloon_stat {
  1450. #define VIRTIO_BALLOON_S_SWAP_IN 0
  1451. #define VIRTIO_BALLOON_S_SWAP_OUT 1
  1452. #define VIRTIO_BALLOON_S_MAJFLT 2
  1453. #define VIRTIO_BALLOON_S_MINFLT 3
  1454. #define VIRTIO_BALLOON_S_MEMFREE 4
  1455. #define VIRTIO_BALLOON_S_MEMTOT 5
  1456. u16 tag;
  1457. u64 val;
  1458. } __attribute__((packed));
  1459. Tags
  1460. VIRTIO_BALLOON_S_SWAP_IN The amount of memory that has been
  1461. swapped in (in bytes).
  1462. VIRTIO_BALLOON_S_SWAP_OUT The amount of memory that has been
  1463. swapped out to disk (in bytes).
  1464. VIRTIO_BALLOON_S_MAJFLT The number of major page faults that
  1465. have occurred.
  1466. VIRTIO_BALLOON_S_MINFLT The number of minor page faults that
  1467. have occurred.
  1468. VIRTIO_BALLOON_S_MEMFREE The amount of memory not being used
  1469. for any purpose (in bytes).
  1470. VIRTIO_BALLOON_S_MEMTOT The total amount of memory available
  1471. (in bytes).