virtio_ring.c 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187
  1. /* Virtio ring implementation.
  2. *
  3. * Copyright 2007 Rusty Russell IBM Corporation
  4. *
  5. * This program is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation; either version 2 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program; if not, write to the Free Software
  17. * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
  18. */
  19. #include <linux/virtio.h>
  20. #include <linux/virtio_ring.h>
  21. #include <linux/virtio_config.h>
  22. #include <linux/device.h>
  23. #include <linux/slab.h>
  24. #include <linux/module.h>
  25. #include <linux/hrtimer.h>
  26. #include <linux/kmemleak.h>
  27. #include <linux/dma-mapping.h>
  28. #include <xen/xen.h>
  29. #ifdef DEBUG
  30. /* For development, we want to crash whenever the ring is screwed. */
  31. #define BAD_RING(_vq, fmt, args...) \
  32. do { \
  33. dev_err(&(_vq)->vq.vdev->dev, \
  34. "%s:"fmt, (_vq)->vq.name, ##args); \
  35. BUG(); \
  36. } while (0)
  37. /* Caller is supposed to guarantee no reentry. */
  38. #define START_USE(_vq) \
  39. do { \
  40. if ((_vq)->in_use) \
  41. panic("%s:in_use = %i\n", \
  42. (_vq)->vq.name, (_vq)->in_use); \
  43. (_vq)->in_use = __LINE__; \
  44. } while (0)
  45. #define END_USE(_vq) \
  46. do { BUG_ON(!(_vq)->in_use); (_vq)->in_use = 0; } while(0)
  47. #else
  48. #define BAD_RING(_vq, fmt, args...) \
  49. do { \
  50. dev_err(&_vq->vq.vdev->dev, \
  51. "%s:"fmt, (_vq)->vq.name, ##args); \
  52. (_vq)->broken = true; \
  53. } while (0)
  54. #define START_USE(vq)
  55. #define END_USE(vq)
  56. #endif
  57. struct vring_desc_state {
  58. void *data; /* Data for callback. */
  59. struct vring_desc *indir_desc; /* Indirect descriptor, if any. */
  60. };
  61. struct vring_virtqueue {
  62. struct virtqueue vq;
  63. /* Actual memory layout for this queue */
  64. struct vring vring;
  65. /* Can we use weak barriers? */
  66. bool weak_barriers;
  67. /* Other side has made a mess, don't try any more. */
  68. bool broken;
  69. /* Host supports indirect buffers */
  70. bool indirect;
  71. /* Host publishes avail event idx */
  72. bool event;
  73. /* Head of free buffer list. */
  74. unsigned int free_head;
  75. /* Number we've added since last sync. */
  76. unsigned int num_added;
  77. /* Last used index we've seen. */
  78. u16 last_used_idx;
  79. /* Last written value to avail->flags */
  80. u16 avail_flags_shadow;
  81. /* Last written value to avail->idx in guest byte order */
  82. u16 avail_idx_shadow;
  83. /* How to notify other side. FIXME: commonalize hcalls! */
  84. bool (*notify)(struct virtqueue *vq);
  85. /* DMA, allocation, and size information */
  86. bool we_own_ring;
  87. size_t queue_size_in_bytes;
  88. dma_addr_t queue_dma_addr;
  89. #ifdef DEBUG
  90. /* They're supposed to lock for us. */
  91. unsigned int in_use;
  92. /* Figure out if their kicks are too delayed. */
  93. bool last_add_time_valid;
  94. ktime_t last_add_time;
  95. #endif
  96. /* Per-descriptor state. */
  97. struct vring_desc_state desc_state[];
  98. };
  99. #define to_vvq(_vq) container_of(_vq, struct vring_virtqueue, vq)
  100. /*
  101. * The interaction between virtio and a possible IOMMU is a mess.
  102. *
  103. * On most systems with virtio, physical addresses match bus addresses,
  104. * and it doesn't particularly matter whether we use the DMA API.
  105. *
  106. * On some systems, including Xen and any system with a physical device
  107. * that speaks virtio behind a physical IOMMU, we must use the DMA API
  108. * for virtio DMA to work at all.
  109. *
  110. * On other systems, including SPARC and PPC64, virtio-pci devices are
  111. * enumerated as though they are behind an IOMMU, but the virtio host
  112. * ignores the IOMMU, so we must either pretend that the IOMMU isn't
  113. * there or somehow map everything as the identity.
  114. *
  115. * For the time being, we preserve historic behavior and bypass the DMA
  116. * API.
  117. */
  118. static bool vring_use_dma_api(struct virtio_device *vdev)
  119. {
  120. /*
  121. * In theory, it's possible to have a buggy QEMU-supposed
  122. * emulated Q35 IOMMU and Xen enabled at the same time. On
  123. * such a configuration, virtio has never worked and will
  124. * not work without an even larger kludge. Instead, enable
  125. * the DMA API if we're a Xen guest, which at least allows
  126. * all of the sensible Xen configurations to work correctly.
  127. */
  128. if (xen_domain())
  129. return true;
  130. return false;
  131. }
  132. /*
  133. * The DMA ops on various arches are rather gnarly right now, and
  134. * making all of the arch DMA ops work on the vring device itself
  135. * is a mess. For now, we use the parent device for DMA ops.
  136. */
  137. struct device *vring_dma_dev(const struct vring_virtqueue *vq)
  138. {
  139. return vq->vq.vdev->dev.parent;
  140. }
  141. /* Map one sg entry. */
  142. static dma_addr_t vring_map_one_sg(const struct vring_virtqueue *vq,
  143. struct scatterlist *sg,
  144. enum dma_data_direction direction)
  145. {
  146. if (!vring_use_dma_api(vq->vq.vdev))
  147. return (dma_addr_t)sg_phys(sg);
  148. /*
  149. * We can't use dma_map_sg, because we don't use scatterlists in
  150. * the way it expects (we don't guarantee that the scatterlist
  151. * will exist for the lifetime of the mapping).
  152. */
  153. return dma_map_page(vring_dma_dev(vq),
  154. sg_page(sg), sg->offset, sg->length,
  155. direction);
  156. }
  157. static dma_addr_t vring_map_single(const struct vring_virtqueue *vq,
  158. void *cpu_addr, size_t size,
  159. enum dma_data_direction direction)
  160. {
  161. if (!vring_use_dma_api(vq->vq.vdev))
  162. return (dma_addr_t)virt_to_phys(cpu_addr);
  163. return dma_map_single(vring_dma_dev(vq),
  164. cpu_addr, size, direction);
  165. }
  166. static void vring_unmap_one(const struct vring_virtqueue *vq,
  167. struct vring_desc *desc)
  168. {
  169. u16 flags;
  170. if (!vring_use_dma_api(vq->vq.vdev))
  171. return;
  172. flags = virtio16_to_cpu(vq->vq.vdev, desc->flags);
  173. if (flags & VRING_DESC_F_INDIRECT) {
  174. dma_unmap_single(vring_dma_dev(vq),
  175. virtio64_to_cpu(vq->vq.vdev, desc->addr),
  176. virtio32_to_cpu(vq->vq.vdev, desc->len),
  177. (flags & VRING_DESC_F_WRITE) ?
  178. DMA_FROM_DEVICE : DMA_TO_DEVICE);
  179. } else {
  180. dma_unmap_page(vring_dma_dev(vq),
  181. virtio64_to_cpu(vq->vq.vdev, desc->addr),
  182. virtio32_to_cpu(vq->vq.vdev, desc->len),
  183. (flags & VRING_DESC_F_WRITE) ?
  184. DMA_FROM_DEVICE : DMA_TO_DEVICE);
  185. }
  186. }
  187. static int vring_mapping_error(const struct vring_virtqueue *vq,
  188. dma_addr_t addr)
  189. {
  190. if (!vring_use_dma_api(vq->vq.vdev))
  191. return 0;
  192. return dma_mapping_error(vring_dma_dev(vq), addr);
  193. }
  194. static struct vring_desc *alloc_indirect(struct virtqueue *_vq,
  195. unsigned int total_sg, gfp_t gfp)
  196. {
  197. struct vring_desc *desc;
  198. unsigned int i;
  199. /*
  200. * We require lowmem mappings for the descriptors because
  201. * otherwise virt_to_phys will give us bogus addresses in the
  202. * virtqueue.
  203. */
  204. gfp &= ~__GFP_HIGHMEM;
  205. desc = kmalloc(total_sg * sizeof(struct vring_desc), gfp);
  206. if (!desc)
  207. return NULL;
  208. for (i = 0; i < total_sg; i++)
  209. desc[i].next = cpu_to_virtio16(_vq->vdev, i + 1);
  210. return desc;
  211. }
  212. static inline int virtqueue_add(struct virtqueue *_vq,
  213. struct scatterlist *sgs[],
  214. unsigned int total_sg,
  215. unsigned int out_sgs,
  216. unsigned int in_sgs,
  217. void *data,
  218. gfp_t gfp)
  219. {
  220. struct vring_virtqueue *vq = to_vvq(_vq);
  221. struct scatterlist *sg;
  222. struct vring_desc *desc;
  223. unsigned int i, n, avail, descs_used, uninitialized_var(prev), err_idx;
  224. int head;
  225. bool indirect;
  226. START_USE(vq);
  227. BUG_ON(data == NULL);
  228. if (unlikely(vq->broken)) {
  229. END_USE(vq);
  230. return -EIO;
  231. }
  232. #ifdef DEBUG
  233. {
  234. ktime_t now = ktime_get();
  235. /* No kick or get, with .1 second between? Warn. */
  236. if (vq->last_add_time_valid)
  237. WARN_ON(ktime_to_ms(ktime_sub(now, vq->last_add_time))
  238. > 100);
  239. vq->last_add_time = now;
  240. vq->last_add_time_valid = true;
  241. }
  242. #endif
  243. BUG_ON(total_sg > vq->vring.num);
  244. BUG_ON(total_sg == 0);
  245. head = vq->free_head;
  246. /* If the host supports indirect descriptor tables, and we have multiple
  247. * buffers, then go indirect. FIXME: tune this threshold */
  248. if (vq->indirect && total_sg > 1 && vq->vq.num_free)
  249. desc = alloc_indirect(_vq, total_sg, gfp);
  250. else
  251. desc = NULL;
  252. if (desc) {
  253. /* Use a single buffer which doesn't continue */
  254. indirect = true;
  255. /* Set up rest to use this indirect table. */
  256. i = 0;
  257. descs_used = 1;
  258. } else {
  259. indirect = false;
  260. desc = vq->vring.desc;
  261. i = head;
  262. descs_used = total_sg;
  263. }
  264. if (vq->vq.num_free < descs_used) {
  265. pr_debug("Can't add buf len %i - avail = %i\n",
  266. descs_used, vq->vq.num_free);
  267. /* FIXME: for historical reasons, we force a notify here if
  268. * there are outgoing parts to the buffer. Presumably the
  269. * host should service the ring ASAP. */
  270. if (out_sgs)
  271. vq->notify(&vq->vq);
  272. END_USE(vq);
  273. return -ENOSPC;
  274. }
  275. for (n = 0; n < out_sgs; n++) {
  276. for (sg = sgs[n]; sg; sg = sg_next(sg)) {
  277. dma_addr_t addr = vring_map_one_sg(vq, sg, DMA_TO_DEVICE);
  278. if (vring_mapping_error(vq, addr))
  279. goto unmap_release;
  280. desc[i].flags = cpu_to_virtio16(_vq->vdev, VRING_DESC_F_NEXT);
  281. desc[i].addr = cpu_to_virtio64(_vq->vdev, addr);
  282. desc[i].len = cpu_to_virtio32(_vq->vdev, sg->length);
  283. prev = i;
  284. i = virtio16_to_cpu(_vq->vdev, desc[i].next);
  285. }
  286. }
  287. for (; n < (out_sgs + in_sgs); n++) {
  288. for (sg = sgs[n]; sg; sg = sg_next(sg)) {
  289. dma_addr_t addr = vring_map_one_sg(vq, sg, DMA_FROM_DEVICE);
  290. if (vring_mapping_error(vq, addr))
  291. goto unmap_release;
  292. desc[i].flags = cpu_to_virtio16(_vq->vdev, VRING_DESC_F_NEXT | VRING_DESC_F_WRITE);
  293. desc[i].addr = cpu_to_virtio64(_vq->vdev, addr);
  294. desc[i].len = cpu_to_virtio32(_vq->vdev, sg->length);
  295. prev = i;
  296. i = virtio16_to_cpu(_vq->vdev, desc[i].next);
  297. }
  298. }
  299. /* Last one doesn't continue. */
  300. desc[prev].flags &= cpu_to_virtio16(_vq->vdev, ~VRING_DESC_F_NEXT);
  301. if (indirect) {
  302. /* Now that the indirect table is filled in, map it. */
  303. dma_addr_t addr = vring_map_single(
  304. vq, desc, total_sg * sizeof(struct vring_desc),
  305. DMA_TO_DEVICE);
  306. if (vring_mapping_error(vq, addr))
  307. goto unmap_release;
  308. vq->vring.desc[head].flags = cpu_to_virtio16(_vq->vdev, VRING_DESC_F_INDIRECT);
  309. vq->vring.desc[head].addr = cpu_to_virtio64(_vq->vdev, addr);
  310. vq->vring.desc[head].len = cpu_to_virtio32(_vq->vdev, total_sg * sizeof(struct vring_desc));
  311. }
  312. /* We're using some buffers from the free list. */
  313. vq->vq.num_free -= descs_used;
  314. /* Update free pointer */
  315. if (indirect)
  316. vq->free_head = virtio16_to_cpu(_vq->vdev, vq->vring.desc[head].next);
  317. else
  318. vq->free_head = i;
  319. /* Store token and indirect buffer state. */
  320. vq->desc_state[head].data = data;
  321. if (indirect)
  322. vq->desc_state[head].indir_desc = desc;
  323. /* Put entry in available array (but don't update avail->idx until they
  324. * do sync). */
  325. avail = vq->avail_idx_shadow & (vq->vring.num - 1);
  326. vq->vring.avail->ring[avail] = cpu_to_virtio16(_vq->vdev, head);
  327. /* Descriptors and available array need to be set before we expose the
  328. * new available array entries. */
  329. virtio_wmb(vq->weak_barriers);
  330. vq->avail_idx_shadow++;
  331. vq->vring.avail->idx = cpu_to_virtio16(_vq->vdev, vq->avail_idx_shadow);
  332. vq->num_added++;
  333. pr_debug("Added buffer head %i to %p\n", head, vq);
  334. END_USE(vq);
  335. /* This is very unlikely, but theoretically possible. Kick
  336. * just in case. */
  337. if (unlikely(vq->num_added == (1 << 16) - 1))
  338. virtqueue_kick(_vq);
  339. return 0;
  340. unmap_release:
  341. err_idx = i;
  342. i = head;
  343. for (n = 0; n < total_sg; n++) {
  344. if (i == err_idx)
  345. break;
  346. vring_unmap_one(vq, &desc[i]);
  347. i = vq->vring.desc[i].next;
  348. }
  349. vq->vq.num_free += total_sg;
  350. if (indirect)
  351. kfree(desc);
  352. return -EIO;
  353. }
  354. /**
  355. * virtqueue_add_sgs - expose buffers to other end
  356. * @vq: the struct virtqueue we're talking about.
  357. * @sgs: array of terminated scatterlists.
  358. * @out_num: the number of scatterlists readable by other side
  359. * @in_num: the number of scatterlists which are writable (after readable ones)
  360. * @data: the token identifying the buffer.
  361. * @gfp: how to do memory allocations (if necessary).
  362. *
  363. * Caller must ensure we don't call this with other virtqueue operations
  364. * at the same time (except where noted).
  365. *
  366. * Returns zero or a negative error (ie. ENOSPC, ENOMEM, EIO).
  367. */
  368. int virtqueue_add_sgs(struct virtqueue *_vq,
  369. struct scatterlist *sgs[],
  370. unsigned int out_sgs,
  371. unsigned int in_sgs,
  372. void *data,
  373. gfp_t gfp)
  374. {
  375. unsigned int i, total_sg = 0;
  376. /* Count them first. */
  377. for (i = 0; i < out_sgs + in_sgs; i++) {
  378. struct scatterlist *sg;
  379. for (sg = sgs[i]; sg; sg = sg_next(sg))
  380. total_sg++;
  381. }
  382. return virtqueue_add(_vq, sgs, total_sg, out_sgs, in_sgs, data, gfp);
  383. }
  384. EXPORT_SYMBOL_GPL(virtqueue_add_sgs);
  385. /**
  386. * virtqueue_add_outbuf - expose output buffers to other end
  387. * @vq: the struct virtqueue we're talking about.
  388. * @sg: scatterlist (must be well-formed and terminated!)
  389. * @num: the number of entries in @sg readable by other side
  390. * @data: the token identifying the buffer.
  391. * @gfp: how to do memory allocations (if necessary).
  392. *
  393. * Caller must ensure we don't call this with other virtqueue operations
  394. * at the same time (except where noted).
  395. *
  396. * Returns zero or a negative error (ie. ENOSPC, ENOMEM, EIO).
  397. */
  398. int virtqueue_add_outbuf(struct virtqueue *vq,
  399. struct scatterlist *sg, unsigned int num,
  400. void *data,
  401. gfp_t gfp)
  402. {
  403. return virtqueue_add(vq, &sg, num, 1, 0, data, gfp);
  404. }
  405. EXPORT_SYMBOL_GPL(virtqueue_add_outbuf);
  406. /**
  407. * virtqueue_add_inbuf - expose input buffers to other end
  408. * @vq: the struct virtqueue we're talking about.
  409. * @sg: scatterlist (must be well-formed and terminated!)
  410. * @num: the number of entries in @sg writable by other side
  411. * @data: the token identifying the buffer.
  412. * @gfp: how to do memory allocations (if necessary).
  413. *
  414. * Caller must ensure we don't call this with other virtqueue operations
  415. * at the same time (except where noted).
  416. *
  417. * Returns zero or a negative error (ie. ENOSPC, ENOMEM, EIO).
  418. */
  419. int virtqueue_add_inbuf(struct virtqueue *vq,
  420. struct scatterlist *sg, unsigned int num,
  421. void *data,
  422. gfp_t gfp)
  423. {
  424. return virtqueue_add(vq, &sg, num, 0, 1, data, gfp);
  425. }
  426. EXPORT_SYMBOL_GPL(virtqueue_add_inbuf);
  427. /**
  428. * virtqueue_kick_prepare - first half of split virtqueue_kick call.
  429. * @vq: the struct virtqueue
  430. *
  431. * Instead of virtqueue_kick(), you can do:
  432. * if (virtqueue_kick_prepare(vq))
  433. * virtqueue_notify(vq);
  434. *
  435. * This is sometimes useful because the virtqueue_kick_prepare() needs
  436. * to be serialized, but the actual virtqueue_notify() call does not.
  437. */
  438. bool virtqueue_kick_prepare(struct virtqueue *_vq)
  439. {
  440. struct vring_virtqueue *vq = to_vvq(_vq);
  441. u16 new, old;
  442. bool needs_kick;
  443. START_USE(vq);
  444. /* We need to expose available array entries before checking avail
  445. * event. */
  446. virtio_mb(vq->weak_barriers);
  447. old = vq->avail_idx_shadow - vq->num_added;
  448. new = vq->avail_idx_shadow;
  449. vq->num_added = 0;
  450. #ifdef DEBUG
  451. if (vq->last_add_time_valid) {
  452. WARN_ON(ktime_to_ms(ktime_sub(ktime_get(),
  453. vq->last_add_time)) > 100);
  454. }
  455. vq->last_add_time_valid = false;
  456. #endif
  457. if (vq->event) {
  458. needs_kick = vring_need_event(virtio16_to_cpu(_vq->vdev, vring_avail_event(&vq->vring)),
  459. new, old);
  460. } else {
  461. needs_kick = !(vq->vring.used->flags & cpu_to_virtio16(_vq->vdev, VRING_USED_F_NO_NOTIFY));
  462. }
  463. END_USE(vq);
  464. return needs_kick;
  465. }
  466. EXPORT_SYMBOL_GPL(virtqueue_kick_prepare);
  467. /**
  468. * virtqueue_notify - second half of split virtqueue_kick call.
  469. * @vq: the struct virtqueue
  470. *
  471. * This does not need to be serialized.
  472. *
  473. * Returns false if host notify failed or queue is broken, otherwise true.
  474. */
  475. bool virtqueue_notify(struct virtqueue *_vq)
  476. {
  477. struct vring_virtqueue *vq = to_vvq(_vq);
  478. if (unlikely(vq->broken))
  479. return false;
  480. /* Prod other side to tell it about changes. */
  481. if (!vq->notify(_vq)) {
  482. vq->broken = true;
  483. return false;
  484. }
  485. return true;
  486. }
  487. EXPORT_SYMBOL_GPL(virtqueue_notify);
  488. /**
  489. * virtqueue_kick - update after add_buf
  490. * @vq: the struct virtqueue
  491. *
  492. * After one or more virtqueue_add_* calls, invoke this to kick
  493. * the other side.
  494. *
  495. * Caller must ensure we don't call this with other virtqueue
  496. * operations at the same time (except where noted).
  497. *
  498. * Returns false if kick failed, otherwise true.
  499. */
  500. bool virtqueue_kick(struct virtqueue *vq)
  501. {
  502. if (virtqueue_kick_prepare(vq))
  503. return virtqueue_notify(vq);
  504. return true;
  505. }
  506. EXPORT_SYMBOL_GPL(virtqueue_kick);
  507. static void detach_buf(struct vring_virtqueue *vq, unsigned int head)
  508. {
  509. unsigned int i, j;
  510. u16 nextflag = cpu_to_virtio16(vq->vq.vdev, VRING_DESC_F_NEXT);
  511. /* Clear data ptr. */
  512. vq->desc_state[head].data = NULL;
  513. /* Put back on free list: unmap first-level descriptors and find end */
  514. i = head;
  515. while (vq->vring.desc[i].flags & nextflag) {
  516. vring_unmap_one(vq, &vq->vring.desc[i]);
  517. i = virtio16_to_cpu(vq->vq.vdev, vq->vring.desc[i].next);
  518. vq->vq.num_free++;
  519. }
  520. vring_unmap_one(vq, &vq->vring.desc[i]);
  521. vq->vring.desc[i].next = cpu_to_virtio16(vq->vq.vdev, vq->free_head);
  522. vq->free_head = head;
  523. /* Plus final descriptor */
  524. vq->vq.num_free++;
  525. /* Free the indirect table, if any, now that it's unmapped. */
  526. if (vq->desc_state[head].indir_desc) {
  527. struct vring_desc *indir_desc = vq->desc_state[head].indir_desc;
  528. u32 len = virtio32_to_cpu(vq->vq.vdev, vq->vring.desc[head].len);
  529. BUG_ON(!(vq->vring.desc[head].flags &
  530. cpu_to_virtio16(vq->vq.vdev, VRING_DESC_F_INDIRECT)));
  531. BUG_ON(len == 0 || len % sizeof(struct vring_desc));
  532. for (j = 0; j < len / sizeof(struct vring_desc); j++)
  533. vring_unmap_one(vq, &indir_desc[j]);
  534. kfree(vq->desc_state[head].indir_desc);
  535. vq->desc_state[head].indir_desc = NULL;
  536. }
  537. }
  538. static inline bool more_used(const struct vring_virtqueue *vq)
  539. {
  540. return vq->last_used_idx != virtio16_to_cpu(vq->vq.vdev, vq->vring.used->idx);
  541. }
  542. /**
  543. * virtqueue_get_buf - get the next used buffer
  544. * @vq: the struct virtqueue we're talking about.
  545. * @len: the length written into the buffer
  546. *
  547. * If the driver wrote data into the buffer, @len will be set to the
  548. * amount written. This means you don't need to clear the buffer
  549. * beforehand to ensure there's no data leakage in the case of short
  550. * writes.
  551. *
  552. * Caller must ensure we don't call this with other virtqueue
  553. * operations at the same time (except where noted).
  554. *
  555. * Returns NULL if there are no used buffers, or the "data" token
  556. * handed to virtqueue_add_*().
  557. */
  558. void *virtqueue_get_buf(struct virtqueue *_vq, unsigned int *len)
  559. {
  560. struct vring_virtqueue *vq = to_vvq(_vq);
  561. void *ret;
  562. unsigned int i;
  563. u16 last_used;
  564. START_USE(vq);
  565. if (unlikely(vq->broken)) {
  566. END_USE(vq);
  567. return NULL;
  568. }
  569. if (!more_used(vq)) {
  570. pr_debug("No more buffers in queue\n");
  571. END_USE(vq);
  572. return NULL;
  573. }
  574. /* Only get used array entries after they have been exposed by host. */
  575. virtio_rmb(vq->weak_barriers);
  576. last_used = (vq->last_used_idx & (vq->vring.num - 1));
  577. i = virtio32_to_cpu(_vq->vdev, vq->vring.used->ring[last_used].id);
  578. *len = virtio32_to_cpu(_vq->vdev, vq->vring.used->ring[last_used].len);
  579. if (unlikely(i >= vq->vring.num)) {
  580. BAD_RING(vq, "id %u out of range\n", i);
  581. return NULL;
  582. }
  583. if (unlikely(!vq->desc_state[i].data)) {
  584. BAD_RING(vq, "id %u is not a head!\n", i);
  585. return NULL;
  586. }
  587. /* detach_buf clears data, so grab it now. */
  588. ret = vq->desc_state[i].data;
  589. detach_buf(vq, i);
  590. vq->last_used_idx++;
  591. /* If we expect an interrupt for the next entry, tell host
  592. * by writing event index and flush out the write before
  593. * the read in the next get_buf call. */
  594. if (!(vq->avail_flags_shadow & VRING_AVAIL_F_NO_INTERRUPT))
  595. virtio_store_mb(vq->weak_barriers,
  596. &vring_used_event(&vq->vring),
  597. cpu_to_virtio16(_vq->vdev, vq->last_used_idx));
  598. #ifdef DEBUG
  599. vq->last_add_time_valid = false;
  600. #endif
  601. END_USE(vq);
  602. return ret;
  603. }
  604. EXPORT_SYMBOL_GPL(virtqueue_get_buf);
  605. /**
  606. * virtqueue_disable_cb - disable callbacks
  607. * @vq: the struct virtqueue we're talking about.
  608. *
  609. * Note that this is not necessarily synchronous, hence unreliable and only
  610. * useful as an optimization.
  611. *
  612. * Unlike other operations, this need not be serialized.
  613. */
  614. void virtqueue_disable_cb(struct virtqueue *_vq)
  615. {
  616. struct vring_virtqueue *vq = to_vvq(_vq);
  617. if (!(vq->avail_flags_shadow & VRING_AVAIL_F_NO_INTERRUPT)) {
  618. vq->avail_flags_shadow |= VRING_AVAIL_F_NO_INTERRUPT;
  619. vq->vring.avail->flags = cpu_to_virtio16(_vq->vdev, vq->avail_flags_shadow);
  620. }
  621. }
  622. EXPORT_SYMBOL_GPL(virtqueue_disable_cb);
  623. /**
  624. * virtqueue_enable_cb_prepare - restart callbacks after disable_cb
  625. * @vq: the struct virtqueue we're talking about.
  626. *
  627. * This re-enables callbacks; it returns current queue state
  628. * in an opaque unsigned value. This value should be later tested by
  629. * virtqueue_poll, to detect a possible race between the driver checking for
  630. * more work, and enabling callbacks.
  631. *
  632. * Caller must ensure we don't call this with other virtqueue
  633. * operations at the same time (except where noted).
  634. */
  635. unsigned virtqueue_enable_cb_prepare(struct virtqueue *_vq)
  636. {
  637. struct vring_virtqueue *vq = to_vvq(_vq);
  638. u16 last_used_idx;
  639. START_USE(vq);
  640. /* We optimistically turn back on interrupts, then check if there was
  641. * more to do. */
  642. /* Depending on the VIRTIO_RING_F_EVENT_IDX feature, we need to
  643. * either clear the flags bit or point the event index at the next
  644. * entry. Always do both to keep code simple. */
  645. if (vq->avail_flags_shadow & VRING_AVAIL_F_NO_INTERRUPT) {
  646. vq->avail_flags_shadow &= ~VRING_AVAIL_F_NO_INTERRUPT;
  647. vq->vring.avail->flags = cpu_to_virtio16(_vq->vdev, vq->avail_flags_shadow);
  648. }
  649. vring_used_event(&vq->vring) = cpu_to_virtio16(_vq->vdev, last_used_idx = vq->last_used_idx);
  650. END_USE(vq);
  651. return last_used_idx;
  652. }
  653. EXPORT_SYMBOL_GPL(virtqueue_enable_cb_prepare);
  654. /**
  655. * virtqueue_poll - query pending used buffers
  656. * @vq: the struct virtqueue we're talking about.
  657. * @last_used_idx: virtqueue state (from call to virtqueue_enable_cb_prepare).
  658. *
  659. * Returns "true" if there are pending used buffers in the queue.
  660. *
  661. * This does not need to be serialized.
  662. */
  663. bool virtqueue_poll(struct virtqueue *_vq, unsigned last_used_idx)
  664. {
  665. struct vring_virtqueue *vq = to_vvq(_vq);
  666. virtio_mb(vq->weak_barriers);
  667. return (u16)last_used_idx != virtio16_to_cpu(_vq->vdev, vq->vring.used->idx);
  668. }
  669. EXPORT_SYMBOL_GPL(virtqueue_poll);
  670. /**
  671. * virtqueue_enable_cb - restart callbacks after disable_cb.
  672. * @vq: the struct virtqueue we're talking about.
  673. *
  674. * This re-enables callbacks; it returns "false" if there are pending
  675. * buffers in the queue, to detect a possible race between the driver
  676. * checking for more work, and enabling callbacks.
  677. *
  678. * Caller must ensure we don't call this with other virtqueue
  679. * operations at the same time (except where noted).
  680. */
  681. bool virtqueue_enable_cb(struct virtqueue *_vq)
  682. {
  683. unsigned last_used_idx = virtqueue_enable_cb_prepare(_vq);
  684. return !virtqueue_poll(_vq, last_used_idx);
  685. }
  686. EXPORT_SYMBOL_GPL(virtqueue_enable_cb);
  687. /**
  688. * virtqueue_enable_cb_delayed - restart callbacks after disable_cb.
  689. * @vq: the struct virtqueue we're talking about.
  690. *
  691. * This re-enables callbacks but hints to the other side to delay
  692. * interrupts until most of the available buffers have been processed;
  693. * it returns "false" if there are many pending buffers in the queue,
  694. * to detect a possible race between the driver checking for more work,
  695. * and enabling callbacks.
  696. *
  697. * Caller must ensure we don't call this with other virtqueue
  698. * operations at the same time (except where noted).
  699. */
  700. bool virtqueue_enable_cb_delayed(struct virtqueue *_vq)
  701. {
  702. struct vring_virtqueue *vq = to_vvq(_vq);
  703. u16 bufs;
  704. START_USE(vq);
  705. /* We optimistically turn back on interrupts, then check if there was
  706. * more to do. */
  707. /* Depending on the VIRTIO_RING_F_USED_EVENT_IDX feature, we need to
  708. * either clear the flags bit or point the event index at the next
  709. * entry. Always do both to keep code simple. */
  710. if (vq->avail_flags_shadow & VRING_AVAIL_F_NO_INTERRUPT) {
  711. vq->avail_flags_shadow &= ~VRING_AVAIL_F_NO_INTERRUPT;
  712. vq->vring.avail->flags = cpu_to_virtio16(_vq->vdev, vq->avail_flags_shadow);
  713. }
  714. /* TODO: tune this threshold */
  715. bufs = (u16)(vq->avail_idx_shadow - vq->last_used_idx) * 3 / 4;
  716. virtio_store_mb(vq->weak_barriers,
  717. &vring_used_event(&vq->vring),
  718. cpu_to_virtio16(_vq->vdev, vq->last_used_idx + bufs));
  719. if (unlikely((u16)(virtio16_to_cpu(_vq->vdev, vq->vring.used->idx) - vq->last_used_idx) > bufs)) {
  720. END_USE(vq);
  721. return false;
  722. }
  723. END_USE(vq);
  724. return true;
  725. }
  726. EXPORT_SYMBOL_GPL(virtqueue_enable_cb_delayed);
  727. /**
  728. * virtqueue_detach_unused_buf - detach first unused buffer
  729. * @vq: the struct virtqueue we're talking about.
  730. *
  731. * Returns NULL or the "data" token handed to virtqueue_add_*().
  732. * This is not valid on an active queue; it is useful only for device
  733. * shutdown.
  734. */
  735. void *virtqueue_detach_unused_buf(struct virtqueue *_vq)
  736. {
  737. struct vring_virtqueue *vq = to_vvq(_vq);
  738. unsigned int i;
  739. void *buf;
  740. START_USE(vq);
  741. for (i = 0; i < vq->vring.num; i++) {
  742. if (!vq->desc_state[i].data)
  743. continue;
  744. /* detach_buf clears data, so grab it now. */
  745. buf = vq->desc_state[i].data;
  746. detach_buf(vq, i);
  747. vq->avail_idx_shadow--;
  748. vq->vring.avail->idx = cpu_to_virtio16(_vq->vdev, vq->avail_idx_shadow);
  749. END_USE(vq);
  750. return buf;
  751. }
  752. /* That should have freed everything. */
  753. BUG_ON(vq->vq.num_free != vq->vring.num);
  754. END_USE(vq);
  755. return NULL;
  756. }
  757. EXPORT_SYMBOL_GPL(virtqueue_detach_unused_buf);
  758. irqreturn_t vring_interrupt(int irq, void *_vq)
  759. {
  760. struct vring_virtqueue *vq = to_vvq(_vq);
  761. if (!more_used(vq)) {
  762. pr_debug("virtqueue interrupt with no work for %p\n", vq);
  763. return IRQ_NONE;
  764. }
  765. if (unlikely(vq->broken))
  766. return IRQ_HANDLED;
  767. pr_debug("virtqueue callback for %p (%p)\n", vq, vq->vq.callback);
  768. if (vq->vq.callback)
  769. vq->vq.callback(&vq->vq);
  770. return IRQ_HANDLED;
  771. }
  772. EXPORT_SYMBOL_GPL(vring_interrupt);
  773. struct virtqueue *__vring_new_virtqueue(unsigned int index,
  774. struct vring vring,
  775. struct virtio_device *vdev,
  776. bool weak_barriers,
  777. bool (*notify)(struct virtqueue *),
  778. void (*callback)(struct virtqueue *),
  779. const char *name)
  780. {
  781. unsigned int i;
  782. struct vring_virtqueue *vq;
  783. vq = kmalloc(sizeof(*vq) + vring.num * sizeof(struct vring_desc_state),
  784. GFP_KERNEL);
  785. if (!vq)
  786. return NULL;
  787. vq->vring = vring;
  788. vq->vq.callback = callback;
  789. vq->vq.vdev = vdev;
  790. vq->vq.name = name;
  791. vq->vq.num_free = vring.num;
  792. vq->vq.index = index;
  793. vq->we_own_ring = false;
  794. vq->queue_dma_addr = 0;
  795. vq->queue_size_in_bytes = 0;
  796. vq->notify = notify;
  797. vq->weak_barriers = weak_barriers;
  798. vq->broken = false;
  799. vq->last_used_idx = 0;
  800. vq->avail_flags_shadow = 0;
  801. vq->avail_idx_shadow = 0;
  802. vq->num_added = 0;
  803. list_add_tail(&vq->vq.list, &vdev->vqs);
  804. #ifdef DEBUG
  805. vq->in_use = false;
  806. vq->last_add_time_valid = false;
  807. #endif
  808. vq->indirect = virtio_has_feature(vdev, VIRTIO_RING_F_INDIRECT_DESC);
  809. vq->event = virtio_has_feature(vdev, VIRTIO_RING_F_EVENT_IDX);
  810. /* No callback? Tell other side not to bother us. */
  811. if (!callback) {
  812. vq->avail_flags_shadow |= VRING_AVAIL_F_NO_INTERRUPT;
  813. vq->vring.avail->flags = cpu_to_virtio16(vdev, vq->avail_flags_shadow);
  814. }
  815. /* Put everything in free lists. */
  816. vq->free_head = 0;
  817. for (i = 0; i < vring.num-1; i++)
  818. vq->vring.desc[i].next = cpu_to_virtio16(vdev, i + 1);
  819. memset(vq->desc_state, 0, vring.num * sizeof(struct vring_desc_state));
  820. return &vq->vq;
  821. }
  822. EXPORT_SYMBOL_GPL(__vring_new_virtqueue);
  823. static void *vring_alloc_queue(struct virtio_device *vdev, size_t size,
  824. dma_addr_t *dma_handle, gfp_t flag)
  825. {
  826. if (vring_use_dma_api(vdev)) {
  827. return dma_alloc_coherent(vdev->dev.parent, size,
  828. dma_handle, flag);
  829. } else {
  830. void *queue = alloc_pages_exact(PAGE_ALIGN(size), flag);
  831. if (queue) {
  832. phys_addr_t phys_addr = virt_to_phys(queue);
  833. *dma_handle = (dma_addr_t)phys_addr;
  834. /*
  835. * Sanity check: make sure we dind't truncate
  836. * the address. The only arches I can find that
  837. * have 64-bit phys_addr_t but 32-bit dma_addr_t
  838. * are certain non-highmem MIPS and x86
  839. * configurations, but these configurations
  840. * should never allocate physical pages above 32
  841. * bits, so this is fine. Just in case, throw a
  842. * warning and abort if we end up with an
  843. * unrepresentable address.
  844. */
  845. if (WARN_ON_ONCE(*dma_handle != phys_addr)) {
  846. free_pages_exact(queue, PAGE_ALIGN(size));
  847. return NULL;
  848. }
  849. }
  850. return queue;
  851. }
  852. }
  853. static void vring_free_queue(struct virtio_device *vdev, size_t size,
  854. void *queue, dma_addr_t dma_handle)
  855. {
  856. if (vring_use_dma_api(vdev)) {
  857. dma_free_coherent(vdev->dev.parent, size, queue, dma_handle);
  858. } else {
  859. free_pages_exact(queue, PAGE_ALIGN(size));
  860. }
  861. }
  862. struct virtqueue *vring_create_virtqueue(
  863. unsigned int index,
  864. unsigned int num,
  865. unsigned int vring_align,
  866. struct virtio_device *vdev,
  867. bool weak_barriers,
  868. bool may_reduce_num,
  869. bool (*notify)(struct virtqueue *),
  870. void (*callback)(struct virtqueue *),
  871. const char *name)
  872. {
  873. struct virtqueue *vq;
  874. void *queue;
  875. dma_addr_t dma_addr;
  876. size_t queue_size_in_bytes;
  877. struct vring vring;
  878. /* We assume num is a power of 2. */
  879. if (num & (num - 1)) {
  880. dev_warn(&vdev->dev, "Bad virtqueue length %u\n", num);
  881. return NULL;
  882. }
  883. /* TODO: allocate each queue chunk individually */
  884. for (; num && vring_size(num, vring_align) > PAGE_SIZE; num /= 2) {
  885. queue = vring_alloc_queue(vdev, vring_size(num, vring_align),
  886. &dma_addr,
  887. GFP_KERNEL|__GFP_NOWARN|__GFP_ZERO);
  888. if (queue)
  889. break;
  890. }
  891. if (!num)
  892. return NULL;
  893. if (!queue) {
  894. /* Try to get a single page. You are my only hope! */
  895. queue = vring_alloc_queue(vdev, vring_size(num, vring_align),
  896. &dma_addr, GFP_KERNEL|__GFP_ZERO);
  897. }
  898. if (!queue)
  899. return NULL;
  900. queue_size_in_bytes = vring_size(num, vring_align);
  901. vring_init(&vring, num, queue, vring_align);
  902. vq = __vring_new_virtqueue(index, vring, vdev, weak_barriers,
  903. notify, callback, name);
  904. if (!vq) {
  905. vring_free_queue(vdev, queue_size_in_bytes, queue,
  906. dma_addr);
  907. return NULL;
  908. }
  909. to_vvq(vq)->queue_dma_addr = dma_addr;
  910. to_vvq(vq)->queue_size_in_bytes = queue_size_in_bytes;
  911. to_vvq(vq)->we_own_ring = true;
  912. return vq;
  913. }
  914. EXPORT_SYMBOL_GPL(vring_create_virtqueue);
  915. struct virtqueue *vring_new_virtqueue(unsigned int index,
  916. unsigned int num,
  917. unsigned int vring_align,
  918. struct virtio_device *vdev,
  919. bool weak_barriers,
  920. void *pages,
  921. bool (*notify)(struct virtqueue *vq),
  922. void (*callback)(struct virtqueue *vq),
  923. const char *name)
  924. {
  925. struct vring vring;
  926. vring_init(&vring, num, pages, vring_align);
  927. return __vring_new_virtqueue(index, vring, vdev, weak_barriers,
  928. notify, callback, name);
  929. }
  930. EXPORT_SYMBOL_GPL(vring_new_virtqueue);
  931. void vring_del_virtqueue(struct virtqueue *_vq)
  932. {
  933. struct vring_virtqueue *vq = to_vvq(_vq);
  934. if (vq->we_own_ring) {
  935. vring_free_queue(vq->vq.vdev, vq->queue_size_in_bytes,
  936. vq->vring.desc, vq->queue_dma_addr);
  937. }
  938. list_del(&_vq->list);
  939. kfree(vq);
  940. }
  941. EXPORT_SYMBOL_GPL(vring_del_virtqueue);
  942. /* Manipulates transport-specific feature bits. */
  943. void vring_transport_features(struct virtio_device *vdev)
  944. {
  945. unsigned int i;
  946. for (i = VIRTIO_TRANSPORT_F_START; i < VIRTIO_TRANSPORT_F_END; i++) {
  947. switch (i) {
  948. case VIRTIO_RING_F_INDIRECT_DESC:
  949. break;
  950. case VIRTIO_RING_F_EVENT_IDX:
  951. break;
  952. case VIRTIO_F_VERSION_1:
  953. break;
  954. default:
  955. /* We don't understand this bit. */
  956. __virtio_clear_bit(vdev, i);
  957. }
  958. }
  959. }
  960. EXPORT_SYMBOL_GPL(vring_transport_features);
  961. /**
  962. * virtqueue_get_vring_size - return the size of the virtqueue's vring
  963. * @vq: the struct virtqueue containing the vring of interest.
  964. *
  965. * Returns the size of the vring. This is mainly used for boasting to
  966. * userspace. Unlike other operations, this need not be serialized.
  967. */
  968. unsigned int virtqueue_get_vring_size(struct virtqueue *_vq)
  969. {
  970. struct vring_virtqueue *vq = to_vvq(_vq);
  971. return vq->vring.num;
  972. }
  973. EXPORT_SYMBOL_GPL(virtqueue_get_vring_size);
  974. bool virtqueue_is_broken(struct virtqueue *_vq)
  975. {
  976. struct vring_virtqueue *vq = to_vvq(_vq);
  977. return vq->broken;
  978. }
  979. EXPORT_SYMBOL_GPL(virtqueue_is_broken);
  980. /*
  981. * This should prevent the device from being used, allowing drivers to
  982. * recover. You may need to grab appropriate locks to flush.
  983. */
  984. void virtio_break_device(struct virtio_device *dev)
  985. {
  986. struct virtqueue *_vq;
  987. list_for_each_entry(_vq, &dev->vqs, list) {
  988. struct vring_virtqueue *vq = to_vvq(_vq);
  989. vq->broken = true;
  990. }
  991. }
  992. EXPORT_SYMBOL_GPL(virtio_break_device);
  993. dma_addr_t virtqueue_get_desc_addr(struct virtqueue *_vq)
  994. {
  995. struct vring_virtqueue *vq = to_vvq(_vq);
  996. BUG_ON(!vq->we_own_ring);
  997. return vq->queue_dma_addr;
  998. }
  999. EXPORT_SYMBOL_GPL(virtqueue_get_desc_addr);
  1000. dma_addr_t virtqueue_get_avail_addr(struct virtqueue *_vq)
  1001. {
  1002. struct vring_virtqueue *vq = to_vvq(_vq);
  1003. BUG_ON(!vq->we_own_ring);
  1004. return vq->queue_dma_addr +
  1005. ((char *)vq->vring.avail - (char *)vq->vring.desc);
  1006. }
  1007. EXPORT_SYMBOL_GPL(virtqueue_get_avail_addr);
  1008. dma_addr_t virtqueue_get_used_addr(struct virtqueue *_vq)
  1009. {
  1010. struct vring_virtqueue *vq = to_vvq(_vq);
  1011. BUG_ON(!vq->we_own_ring);
  1012. return vq->queue_dma_addr +
  1013. ((char *)vq->vring.used - (char *)vq->vring.desc);
  1014. }
  1015. EXPORT_SYMBOL_GPL(virtqueue_get_used_addr);
  1016. const struct vring *virtqueue_get_vring(struct virtqueue *vq)
  1017. {
  1018. return &to_vvq(vq)->vring;
  1019. }
  1020. EXPORT_SYMBOL_GPL(virtqueue_get_vring);
  1021. MODULE_LICENSE("GPL");