master
c 941 lines 28.2 KB
Raw
1 /*
2 * vhost shadow virtqueue
3 *
4 * SPDX-FileCopyrightText: Red Hat, Inc. 2021
5 * SPDX-FileContributor: Author: Eugenio Pérez <eperezma@redhat.com>
6 *
7 * SPDX-License-Identifier: GPL-2.0-or-later
8 */
9
10 #include "qemu/osdep.h"
11 #include "hw/virtio/vhost-shadow-virtqueue.h"
12
13 #include "qemu/error-report.h"
14 #include "qapi/error.h"
15 #include "qemu/iov.h"
16 #include "qemu/main-loop.h"
17 #include "qemu/log.h"
18 #include "qemu/memalign.h"
19 #include "linux-headers/linux/vhost.h"
20
21 #define VIRTIO_RING_NOT_IN_BATCH UINT16_MAX
22
23 /**
24 * Validate the transport device features that both guests can use with the SVQ
25 * and SVQs can use with the device.
26 *
27 * @dev_features: The features
28 * @errp: Error pointer
29 */
30 bool vhost_svq_valid_features(uint64_t features, Error **errp)
31 {
32 bool ok = true;
33 uint64_t svq_features = features;
34
35 for (uint64_t b = VIRTIO_TRANSPORT_F_START; b <= VIRTIO_TRANSPORT_F_END;
36 ++b) {
37 switch (b) {
38 case VIRTIO_F_ANY_LAYOUT:
39 case VIRTIO_RING_F_EVENT_IDX:
40 case VIRTIO_RING_F_INDIRECT_DESC:
41 case VIRTIO_F_IN_ORDER:
42 continue;
43
44 case VIRTIO_F_ACCESS_PLATFORM:
45 /* SVQ trust in the host's IOMMU to translate addresses */
46 case VIRTIO_F_VERSION_1:
47 /* SVQ trust that the guest vring is little endian */
48 if (!(svq_features & BIT_ULL(b))) {
49 svq_features |= BIT_ULL(b);
50 ok = false;
51 }
52 continue;
53
54 default:
55 if (svq_features & BIT_ULL(b)) {
56 svq_features &= ~BIT_ULL(b);
57 ok = false;
58 }
59 }
60 }
61
62 if (!ok) {
63 error_setg(errp, "SVQ Invalid device feature flags, offer: 0x%"PRIx64
64 ", ok: 0x%"PRIx64, features, svq_features);
65 }
66 return ok;
67 }
68
69 /**
70 * Number of descriptors that the SVQ can make available from the guest.
71 *
72 * @svq: The svq
73 */
74 uint16_t vhost_svq_available_slots(const VhostShadowVirtqueue *svq)
75 {
76 return svq->num_free;
77 }
78
79 /**
80 * Translate addresses between the qemu's virtual address and the SVQ IOVA
81 *
82 * @svq: Shadow VirtQueue
83 * @vaddr: Translated IOVA addresses
84 * @iovec: Source qemu's VA addresses
85 * @num: Length of iovec and minimum length of vaddr
86 * @gpas: Descriptors' GPAs, if backed by guest memory
87 */
88 static bool vhost_svq_translate_addr(const VhostShadowVirtqueue *svq,
89 hwaddr *addrs, const struct iovec *iovec,
90 size_t num, const hwaddr *gpas)
91 {
92 if (num == 0) {
93 return true;
94 }
95
96 for (size_t i = 0; i < num; ++i) {
97 Int128 needle_last, map_last;
98 size_t off;
99 const DMAMap *map;
100 DMAMap needle;
101
102 /* Check if the descriptor is backed by guest memory */
103 if (gpas) {
104 /* Search the GPA->IOVA tree */
105 needle = (DMAMap) {
106 .translated_addr = gpas[i],
107 .size = iovec[i].iov_len,
108 };
109 map = vhost_iova_tree_find_gpa(svq->iova_tree, &needle);
110 } else {
111 /* Search the IOVA->HVA tree */
112 needle = (DMAMap) {
113 .translated_addr = (hwaddr)(uintptr_t)iovec[i].iov_base,
114 .size = iovec[i].iov_len,
115 };
116 map = vhost_iova_tree_find_iova(svq->iova_tree, &needle);
117 }
118
119 /*
120 * Map cannot be NULL since iova map contains all guest space and
121 * qemu already has a physical address mapped
122 */
123 if (unlikely(!map)) {
124 qemu_log_mask(LOG_GUEST_ERROR,
125 "Invalid address 0x%"HWADDR_PRIx" given by guest",
126 needle.translated_addr);
127 return false;
128 }
129
130 off = needle.translated_addr - map->translated_addr;
131 addrs[i] = map->iova + off;
132
133 needle_last = int128_add(int128_make64(needle.translated_addr),
134 int128_makes64(iovec[i].iov_len - 1));
135 map_last = int128_make64(map->translated_addr + map->size);
136 if (unlikely(int128_gt(needle_last, map_last))) {
137 qemu_log_mask(LOG_GUEST_ERROR,
138 "Guest buffer expands over iova range");
139 return false;
140 }
141 }
142
143 return true;
144 }
145
146 /**
147 * Get the next descriptor in the chain in SVQ vring from a descriptor id
148 *
149 * @svq Shadow Virtqueue
150 * @id ID of the descriptor
151 *
152 * Return the id of the next descriptor.
153 */
154 static uint16_t vhost_svq_next_desc(const VhostShadowVirtqueue *svq,
155 uint16_t id)
156 {
157 if (virtio_vdev_has_feature(svq->vdev, VIRTIO_F_IN_ORDER)) {
158 return (id == svq->vring.num) ? 0 : ++id;
159 } else {
160 return svq->desc_state[id].next;
161 }
162 }
163
164 /**
165 * Updates the SVQ free_head member after adding them to the SVQ avail ring.
166 * The new free_head is the next descriptor that SVQ will make available by
167 * forwarding a new guest descriptor.
168 *
169 * @svq Shadow Virtqueue
170 * @num Number of descriptors added
171 * @id ID of the last descriptor added to the SVQ avail ring.
172 */
173 static void vhost_svq_update_free_head(VhostShadowVirtqueue *svq,
174 size_t num, uint16_t id)
175 {
176 if (virtio_vdev_has_feature(svq->vdev, VIRTIO_F_IN_ORDER)) {
177 svq->free_head += num;
178 if (svq->free_head >= svq->vring.num) {
179 svq->free_head -= svq->vring.num;
180 }
181 } else {
182 svq->free_head = vhost_svq_next_desc(svq, id);
183 }
184 }
185
186 /**
187 * Write descriptors to SVQ vring
188 *
189 * @svq: The shadow virtqueue
190 * @sg: Cache for hwaddr
191 * @iovec: The iovec from the guest
192 * @num: iovec length
193 * @addr: Descriptors' GPAs, if backed by guest memory
194 * @more_descs: True if more descriptors come in the chain
195 * @write: True if they are writeable descriptors
196 *
197 * Return true if success, false otherwise and print error.
198 */
199 static bool vhost_svq_vring_write_descs(VhostShadowVirtqueue *svq, hwaddr *sg,
200 const struct iovec *iovec, size_t num,
201 const hwaddr *addr, bool more_descs,
202 bool write)
203 {
204 uint16_t i = svq->free_head, last = svq->free_head;
205 unsigned n;
206 uint16_t flags = write ? cpu_to_le16(VRING_DESC_F_WRITE) : 0;
207 vring_desc_t *descs = svq->vring.desc;
208 bool ok;
209
210 if (num == 0) {
211 return true;
212 }
213
214 ok = vhost_svq_translate_addr(svq, sg, iovec, num, addr);
215 if (unlikely(!ok)) {
216 return false;
217 }
218
219 for (n = 0; n < num; n++) {
220 uint16_t next = vhost_svq_next_desc(svq, i);
221
222 if (more_descs || (n + 1 < num)) {
223 descs[i].flags = flags | cpu_to_le16(VRING_DESC_F_NEXT);
224 descs[i].next = cpu_to_le16(next);
225 } else {
226 descs[i].flags = flags;
227 }
228 descs[i].addr = cpu_to_le64(sg[n]);
229 descs[i].len = cpu_to_le32(iovec[n].iov_len);
230
231 last = i;
232 i = next;
233 }
234
235 vhost_svq_update_free_head(svq, num, last);
236 return true;
237 }
238
239 static bool vhost_svq_add_split(VhostShadowVirtqueue *svq,
240 const struct iovec *out_sg, size_t out_num,
241 const hwaddr *out_addr,
242 const struct iovec *in_sg, size_t in_num,
243 const hwaddr *in_addr, unsigned *head)
244 {
245 unsigned avail_idx;
246 vring_avail_t *avail = svq->vring.avail;
247 bool ok;
248 g_autofree hwaddr *sgs = g_new(hwaddr, MAX(out_num, in_num));
249
250 *head = svq->free_head;
251
252 /* We need some descriptors here */
253 if (unlikely(!out_num && !in_num)) {
254 qemu_log_mask(LOG_GUEST_ERROR,
255 "Guest provided element with no descriptors");
256 return false;
257 }
258
259 ok = vhost_svq_vring_write_descs(svq, sgs, out_sg, out_num, out_addr,
260 in_num > 0, false);
261 if (unlikely(!ok)) {
262 return false;
263 }
264
265 ok = vhost_svq_vring_write_descs(svq, sgs, in_sg, in_num, in_addr, false,
266 true);
267 if (unlikely(!ok)) {
268 return false;
269 }
270
271 /*
272 * Put the entry in the available array (but don't update avail->idx until
273 * they do sync).
274 */
275 avail_idx = svq->shadow_avail_idx & (svq->vring.num - 1);
276 avail->ring[avail_idx] = cpu_to_le16(*head);
277 svq->shadow_avail_idx++;
278
279 /* Update the avail index after write the descriptor */
280 smp_wmb();
281 avail->idx = cpu_to_le16(svq->shadow_avail_idx);
282
283 return true;
284 }
285
286 static void vhost_svq_kick(VhostShadowVirtqueue *svq)
287 {
288 bool needs_kick;
289
290 /*
291 * We need to expose the available array entries before checking the used
292 * flags
293 */
294 smp_mb();
295
296 if (virtio_vdev_has_feature(svq->vdev, VIRTIO_RING_F_EVENT_IDX)) {
297 uint16_t avail_event = le16_to_cpu(
298 *(uint16_t *)(&svq->vring.used->ring[svq->vring.num]));
299 needs_kick = vring_need_event(avail_event, svq->shadow_avail_idx, svq->shadow_avail_idx - 1);
300 } else {
301 needs_kick =
302 !(svq->vring.used->flags & cpu_to_le16(VRING_USED_F_NO_NOTIFY));
303 }
304
305 if (!needs_kick) {
306 return;
307 }
308
309 event_notifier_set(&svq->hdev_kick);
310 }
311
312 /**
313 * Add an element to a SVQ.
314 *
315 * Return -EINVAL if element is invalid, -ENOSPC if dev queue is full
316 */
317 int vhost_svq_add(VhostShadowVirtqueue *svq, const struct iovec *out_sg,
318 size_t out_num, const hwaddr *out_addr,
319 const struct iovec *in_sg, size_t in_num,
320 const hwaddr *in_addr, VirtQueueElement *elem)
321 {
322 unsigned qemu_head;
323 unsigned ndescs = in_num + out_num;
324 bool ok;
325
326 if (unlikely(ndescs > vhost_svq_available_slots(svq))) {
327 return -ENOSPC;
328 }
329
330 ok = vhost_svq_add_split(svq, out_sg, out_num, out_addr, in_sg, in_num,
331 in_addr, &qemu_head);
332 if (unlikely(!ok)) {
333 return -EINVAL;
334 }
335
336 svq->num_free -= ndescs;
337 svq->desc_state[qemu_head].elem = elem;
338 svq->desc_state[qemu_head].ndescs = ndescs;
339 if (virtio_vdev_has_feature(svq->vdev, VIRTIO_F_IN_ORDER)) {
340 svq->desc_state[qemu_head].in_bytes = iov_size(in_sg, in_num);
341 }
342 vhost_svq_kick(svq);
343 return 0;
344 }
345
346 /* Convenience wrapper to add a guest's element to SVQ */
347 static int vhost_svq_add_element(VhostShadowVirtqueue *svq,
348 VirtQueueElement *elem)
349 {
350 return vhost_svq_add(svq, elem->out_sg, elem->out_num, elem->out_addr,
351 elem->in_sg, elem->in_num, elem->in_addr, elem);
352 }
353
354 /**
355 * Forward available buffers.
356 *
357 * @svq: Shadow VirtQueue
358 *
359 * Note that this function does not guarantee that all guest's available
360 * buffers are available to the device in SVQ avail ring. The guest may have
361 * exposed a GPA / GIOVA contiguous buffer, but it may not be contiguous in
362 * qemu vaddr.
363 *
364 * If that happens, guest's kick notifications will be disabled until the
365 * device uses some buffers.
366 */
367 static void vhost_handle_guest_kick(VhostShadowVirtqueue *svq)
368 {
369 /* Clear event notifier */
370 event_notifier_test_and_clear(&svq->svq_kick);
371
372 /* Forward to the device as many available buffers as possible */
373 do {
374 virtio_queue_set_notification(svq->vq, false);
375
376 while (true) {
377 g_autofree VirtQueueElement *elem = NULL;
378 int r;
379
380 if (svq->next_guest_avail_elem) {
381 elem = g_steal_pointer(&svq->next_guest_avail_elem);
382 } else {
383 elem = virtqueue_pop(svq->vq, sizeof(*elem));
384 }
385
386 if (!elem) {
387 break;
388 }
389
390 if (svq->ops) {
391 r = svq->ops->avail_handler(svq, elem, svq->ops_opaque);
392 } else {
393 r = vhost_svq_add_element(svq, elem);
394 }
395 if (unlikely(r != 0)) {
396 if (r == -ENOSPC) {
397 /*
398 * This condition is possible since a contiguous buffer in
399 * GPA does not imply a contiguous buffer in qemu's VA
400 * scatter-gather segments. If that happens, the buffer
401 * exposed to the device needs to be a chain of descriptors
402 * at this moment.
403 *
404 * SVQ cannot hold more available buffers if we are here:
405 * queue the current guest descriptor and ignore kicks
406 * until some elements are used.
407 */
408 svq->next_guest_avail_elem = g_steal_pointer(&elem);
409 }
410
411 /* VQ is full or broken, just return and ignore kicks */
412 return;
413 }
414 /* elem belongs to SVQ or external caller now */
415 elem = NULL;
416 }
417
418 virtio_queue_set_notification(svq->vq, true);
419 } while (!virtio_queue_empty(svq->vq));
420 }
421
422 /**
423 * Handle guest's kick.
424 *
425 * @n: guest kick event notifier, the one that guest set to notify svq.
426 */
427 static void vhost_handle_guest_kick_notifier(EventNotifier *n)
428 {
429 VhostShadowVirtqueue *svq = container_of(n, VhostShadowVirtqueue, svq_kick);
430 event_notifier_test_and_clear(n);
431 vhost_handle_guest_kick(svq);
432 }
433
434 static bool vhost_svq_more_used(VhostShadowVirtqueue *svq)
435 {
436 uint16_t *used_idx = &svq->vring.used->idx;
437
438 if (virtio_vdev_has_feature(svq->vdev, VIRTIO_F_IN_ORDER) &&
439 svq->batch_last.id != VIRTIO_RING_NOT_IN_BATCH) {
440 return true;
441 }
442
443 if (svq->last_used_idx != svq->shadow_used_idx) {
444 return true;
445 }
446
447 svq->shadow_used_idx = le16_to_cpu(*(volatile uint16_t *)used_idx);
448
449 return svq->last_used_idx != svq->shadow_used_idx;
450 }
451
452 /**
453 * Enable vhost device calls after disable them.
454 *
455 * @svq: The svq
456 *
457 * It returns false if there are pending used buffers from the vhost device,
458 * avoiding the possible races between SVQ checking for more work and enabling
459 * callbacks. True if SVQ used vring has no more pending buffers.
460 */
461 static bool vhost_svq_enable_notification(VhostShadowVirtqueue *svq)
462 {
463 if (virtio_vdev_has_feature(svq->vdev, VIRTIO_RING_F_EVENT_IDX)) {
464 uint16_t *used_event = (uint16_t *)&svq->vring.avail->ring[svq->vring.num];
465 *used_event = cpu_to_le16(svq->shadow_used_idx);
466 } else {
467 svq->vring.avail->flags &= ~cpu_to_le16(VRING_AVAIL_F_NO_INTERRUPT);
468 }
469
470 /* Make sure the event is enabled before the read of used_idx */
471 smp_mb();
472 return !vhost_svq_more_used(svq);
473 }
474
475 static void vhost_svq_disable_notification(VhostShadowVirtqueue *svq)
476 {
477 /*
478 * No need to disable notification in the event idx case, since used event
479 * index is already an index too far away.
480 */
481 if (!virtio_vdev_has_feature(svq->vdev, VIRTIO_RING_F_EVENT_IDX)) {
482 svq->vring.avail->flags |= cpu_to_le16(VRING_AVAIL_F_NO_INTERRUPT);
483 }
484 }
485
486 /*
487 * Gets the next buffer id and moves forward the used idx, so the next time
488 * SVQ calls this function will get the next one.
489 *
490 * @svq: Shadow VirtQueue
491 * @len: Consumed length by the device.
492 *
493 * Return the next descriptor consumed by the device.
494 */
495 static uint16_t vhost_svq_get_last_used_split(VhostShadowVirtqueue *svq,
496 uint32_t *len)
497 {
498 const vring_used_t *used = svq->vring.used;
499 uint16_t last_used = svq->last_used_idx++ & (svq->vring.num - 1);
500
501 *len = le32_to_cpu(used->ring[last_used].len);
502 return le32_to_cpu(used->ring[last_used].id);
503 }
504
505 /*
506 * Gets the next buffer id and moves forward the used idx, so the next time
507 * SVQ calls this function will get the next one. IN_ORDER version
508 *
509 * @svq: Shadow VirtQueue
510 * @len: Consumed length by the device.
511 *
512 * Return the next descriptor consumed by the device.
513 */
514 static int32_t vhost_svq_get_last_used_split_in_order(
515 VhostShadowVirtqueue *svq,
516 uint32_t *len)
517 {
518 unsigned num = svq->vring.num;
519 const vring_used_t *used = svq->vring.used;
520 uint16_t last_used = svq->last_used & (num - 1);
521 uint16_t last_used_idx = svq->last_used_idx & (num - 1);
522
523 if (svq->batch_last.id == VIRTIO_RING_NOT_IN_BATCH) {
524 svq->batch_last.id = le32_to_cpu(used->ring[last_used_idx].id);
525 svq->batch_last.len = le32_to_cpu(used->ring[last_used_idx].len);
526 }
527
528 if (unlikely(last_used >= num)) {
529 qemu_log_mask(LOG_GUEST_ERROR, "Device %s says index %u is used",
530 svq->vdev->name, last_used);
531 return -1;
532 }
533
534 if (svq->batch_last.id == last_used) {
535 svq->batch_last.id = VIRTIO_RING_NOT_IN_BATCH;
536 *len = svq->batch_last.len;
537 } else {
538 *len = svq->desc_state[last_used].in_bytes;
539 }
540
541 svq->last_used += svq->desc_state[last_used].ndescs;
542 svq->last_used_idx++;
543 return last_used;
544 }
545
546 static uint16_t vhost_svq_last_desc_of_chain(const VhostShadowVirtqueue *svq,
547 uint16_t num, uint16_t i)
548 {
549 for (uint16_t j = 0; j < (num - 1); ++j) {
550 i = vhost_svq_next_desc(svq, i);
551 }
552
553 return i;
554 }
555
556 G_GNUC_WARN_UNUSED_RESULT
557 static VirtQueueElement *vhost_svq_detach_buf_split(VhostShadowVirtqueue *svq,
558 uint16_t id)
559 {
560 uint16_t num = svq->desc_state[id].ndescs;
561 uint16_t last_used_chain = vhost_svq_last_desc_of_chain(svq, num, id);
562
563 svq->desc_state[last_used_chain].next = svq->free_head;
564 svq->free_head = id;
565
566 return g_steal_pointer(&svq->desc_state[id].elem);
567 }
568
569 G_GNUC_WARN_UNUSED_RESULT
570 static VirtQueueElement *vhost_svq_detach_buf_split_in_order(
571 VhostShadowVirtqueue *svq,
572 uint16_t id)
573 {
574 return g_steal_pointer(&svq->desc_state[id].elem);
575 }
576
577 /*
578 * Return the descriptor id (and the chain of ids) to the free list
579 *
580 * @svq: Shadow Virtqueue
581 * @id: Id of the buffer to return.
582 *
583 * Return the element associated to the buffer if any.
584 */
585 G_GNUC_WARN_UNUSED_RESULT
586 static VirtQueueElement *vhost_svq_detach_buf(VhostShadowVirtqueue *svq,
587 uint16_t id)
588 {
589 if (virtio_vdev_has_feature(svq->vdev, VIRTIO_F_IN_ORDER)) {
590 return vhost_svq_detach_buf_split_in_order(svq, id);
591 } else {
592 return vhost_svq_detach_buf_split(svq, id);
593 }
594 }
595
596 G_GNUC_WARN_UNUSED_RESULT
597 static VirtQueueElement *vhost_svq_get_buf(VhostShadowVirtqueue *svq,
598 uint32_t *len)
599 {
600 uint16_t last_used;
601
602 if (!vhost_svq_more_used(svq)) {
603 return NULL;
604 }
605
606 /* Only get used array entries after they have been exposed by dev */
607 smp_rmb();
608
609 if (virtio_vdev_has_feature(svq->vdev, VIRTIO_F_IN_ORDER)) {
610 int32_t r;
611 r = vhost_svq_get_last_used_split_in_order(svq, len);
612 if (r < 0) {
613 return NULL;
614 }
615
616 last_used = r;
617 } else {
618 last_used = vhost_svq_get_last_used_split(svq, len);
619 }
620
621 if (unlikely(last_used >= svq->vring.num)) {
622 qemu_log_mask(LOG_GUEST_ERROR, "Device %s says index %u is used",
623 svq->vdev->name, last_used);
624 return NULL;
625 }
626
627 if (unlikely(!svq->desc_state[last_used].ndescs)) {
628 qemu_log_mask(LOG_GUEST_ERROR,
629 "Device %s says index %u is used, but it was not available",
630 svq->vdev->name, last_used);
631 return NULL;
632 }
633
634 svq->num_free += svq->desc_state[last_used].ndescs;
635 svq->desc_state[last_used].ndescs = 0;
636 return vhost_svq_detach_buf(svq, last_used);
637 }
638
639 /**
640 * Push an element to SVQ, returning it to the guest.
641 */
642 void vhost_svq_push_elem(VhostShadowVirtqueue *svq,
643 const VirtQueueElement *elem, uint32_t len)
644 {
645 virtqueue_push(svq->vq, elem, len);
646 if (svq->next_guest_avail_elem) {
647 /*
648 * Avail ring was full when vhost_svq_flush was called, so it's a
649 * good moment to make more descriptors available if possible.
650 */
651 vhost_handle_guest_kick(svq);
652 }
653 }
654
655 static void vhost_svq_flush(VhostShadowVirtqueue *svq,
656 bool check_for_avail_queue)
657 {
658 VirtQueue *vq = svq->vq;
659
660 /* Forward as many used buffers as possible. */
661 do {
662 unsigned i = 0;
663
664 vhost_svq_disable_notification(svq);
665 while (true) {
666 uint32_t len;
667 g_autofree VirtQueueElement *elem = vhost_svq_get_buf(svq, &len);
668 if (!elem) {
669 break;
670 }
671
672 if (unlikely(i >= svq->vring.num)) {
673 qemu_log_mask(LOG_GUEST_ERROR,
674 "More than %u used buffers obtained in a %u size SVQ",
675 i, svq->vring.num);
676 virtqueue_fill(vq, elem, len, i);
677 virtqueue_flush(vq, i);
678 return;
679 }
680 virtqueue_fill(vq, elem, len, i++);
681 }
682
683 virtqueue_flush(vq, i);
684 event_notifier_set(&svq->svq_call);
685
686 if (check_for_avail_queue && svq->next_guest_avail_elem) {
687 /*
688 * Avail ring was full when vhost_svq_flush was called, so it's a
689 * good moment to make more descriptors available if possible.
690 */
691 vhost_handle_guest_kick(svq);
692 }
693 } while (!vhost_svq_enable_notification(svq));
694 }
695
696 /**
697 * Poll the SVQ to wait for the device to use the specified number
698 * of elements and return the total length written by the device.
699 *
700 * This function race with main event loop SVQ polling, so extra
701 * synchronization is needed.
702 *
703 * @svq: The svq
704 * @num: The number of elements that need to be used
705 */
706 size_t vhost_svq_poll(VhostShadowVirtqueue *svq, size_t num)
707 {
708 size_t len = 0;
709
710 while (num--) {
711 g_autofree VirtQueueElement *elem = NULL;
712 int64_t start_us = g_get_monotonic_time();
713 uint32_t r = 0;
714
715 do {
716 if (vhost_svq_more_used(svq)) {
717 break;
718 }
719
720 if (unlikely(g_get_monotonic_time() - start_us > 10e6)) {
721 return len;
722 }
723 } while (true);
724
725 elem = vhost_svq_get_buf(svq, &r);
726 len += r;
727 }
728
729 return len;
730 }
731
732 /**
733 * Forward used buffers.
734 *
735 * @n: hdev call event notifier, the one that device set to notify svq.
736 *
737 * Note that we are not making any buffers available in the loop, there is no
738 * way that it runs more than virtqueue size times.
739 */
740 static void vhost_svq_handle_call(EventNotifier *n)
741 {
742 VhostShadowVirtqueue *svq = container_of(n, VhostShadowVirtqueue,
743 hdev_call);
744 event_notifier_test_and_clear(n);
745 vhost_svq_flush(svq, true);
746 }
747
748 /**
749 * Set the call notifier for the SVQ to call the guest
750 *
751 * @svq: Shadow virtqueue
752 * @call_fd: call notifier
753 *
754 * Called on BQL context.
755 */
756 void vhost_svq_set_svq_call_fd(VhostShadowVirtqueue *svq, int call_fd)
757 {
758 if (call_fd == VHOST_FILE_UNBIND) {
759 /*
760 * Fail event_notifier_set if called handling device call.
761 *
762 * SVQ still needs device notifications, since it needs to keep
763 * forwarding used buffers even with the unbind.
764 */
765 memset(&svq->svq_call, 0, sizeof(svq->svq_call));
766 } else {
767 event_notifier_init_fd(&svq->svq_call, call_fd);
768 }
769 }
770
771 /**
772 * Get the shadow vq vring address.
773 * @svq: Shadow virtqueue
774 * @addr: Destination to store address
775 */
776 void vhost_svq_get_vring_addr(const VhostShadowVirtqueue *svq,
777 struct vhost_vring_addr *addr)
778 {
779 addr->desc_user_addr = (uint64_t)(uintptr_t)svq->vring.desc;
780 addr->avail_user_addr = (uint64_t)(uintptr_t)svq->vring.avail;
781 addr->used_user_addr = (uint64_t)(uintptr_t)svq->vring.used;
782 }
783
784 size_t vhost_svq_driver_area_size(const VhostShadowVirtqueue *svq)
785 {
786 size_t desc_size = sizeof(vring_desc_t) * svq->vring.num;
787 size_t avail_size = offsetof(vring_avail_t, ring[svq->vring.num]) +
788 sizeof(uint16_t);
789
790 return ROUND_UP(desc_size + avail_size, qemu_real_host_page_size());
791 }
792
793 size_t vhost_svq_device_area_size(const VhostShadowVirtqueue *svq)
794 {
795 size_t used_size = offsetof(vring_used_t, ring[svq->vring.num]) +
796 sizeof(uint16_t);
797 return ROUND_UP(used_size, qemu_real_host_page_size());
798 }
799
800 /**
801 * Set a new file descriptor for the guest to kick the SVQ and notify for avail
802 *
803 * @svq: The svq
804 * @svq_kick_fd: The svq kick fd
805 *
806 * Note that the SVQ will never close the old file descriptor.
807 */
808 void vhost_svq_set_svq_kick_fd(VhostShadowVirtqueue *svq, int svq_kick_fd)
809 {
810 EventNotifier *svq_kick = &svq->svq_kick;
811 bool poll_stop = VHOST_FILE_UNBIND != event_notifier_get_fd(svq_kick);
812 bool poll_start = svq_kick_fd != VHOST_FILE_UNBIND;
813
814 if (poll_stop) {
815 event_notifier_set_handler(svq_kick, NULL);
816 }
817
818 event_notifier_init_fd(svq_kick, svq_kick_fd);
819 /*
820 * event_notifier_set_handler already checks for guest's notifications if
821 * they arrive at the new file descriptor in the switch, so there is no
822 * need to explicitly check for them.
823 */
824 if (poll_start) {
825 event_notifier_set(svq_kick);
826 event_notifier_set_handler(svq_kick, vhost_handle_guest_kick_notifier);
827 }
828 }
829
830 /**
831 * Start the shadow virtqueue operation.
832 *
833 * @svq: Shadow Virtqueue
834 * @vdev: VirtIO device
835 * @vq: Virtqueue to shadow
836 * @iova_tree: Tree to perform descriptors translations
837 */
838 void vhost_svq_start(VhostShadowVirtqueue *svq, VirtIODevice *vdev,
839 VirtQueue *vq, VhostIOVATree *iova_tree)
840 {
841 size_t desc_size;
842
843 event_notifier_set_handler(&svq->hdev_call, vhost_svq_handle_call);
844 svq->next_guest_avail_elem = NULL;
845 svq->shadow_avail_idx = 0;
846 svq->shadow_used_idx = 0;
847 memset(&svq->batch_last, 0, sizeof(svq->batch_last));
848 svq->last_used = 0;
849 svq->last_used_idx = 0;
850 svq->vdev = vdev;
851 svq->vq = vq;
852 svq->iova_tree = iova_tree;
853
854 svq->vring.num = virtio_queue_get_num(vdev, virtio_get_queue_index(vq));
855 svq->num_free = svq->vring.num;
856 svq->vring.desc = mmap(NULL, vhost_svq_driver_area_size(svq),
857 PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS,
858 -1, 0);
859 desc_size = sizeof(vring_desc_t) * svq->vring.num;
860 svq->vring.avail = (void *)((char *)svq->vring.desc + desc_size);
861 svq->vring.used = mmap(NULL, vhost_svq_device_area_size(svq),
862 PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS,
863 -1, 0);
864 svq->desc_state = g_new0(SVQDescState, svq->vring.num);
865 if (virtio_vdev_has_feature(svq->vdev, VIRTIO_F_IN_ORDER)) {
866 svq->batch_last.id = VIRTIO_RING_NOT_IN_BATCH;
867 } else {
868 for (unsigned i = 0; i < svq->vring.num - 1; i++) {
869 svq->desc_state[i].next = i + 1;
870 }
871 }
872 }
873
874 /**
875 * Stop the shadow virtqueue operation.
876 * @svq: Shadow Virtqueue
877 */
878 void vhost_svq_stop(VhostShadowVirtqueue *svq)
879 {
880 vhost_svq_set_svq_kick_fd(svq, VHOST_FILE_UNBIND);
881 g_autofree VirtQueueElement *next_avail_elem = NULL;
882
883 if (!svq->vq) {
884 return;
885 }
886
887 /* Send all pending used descriptors to guest */
888 vhost_svq_flush(svq, false);
889
890 for (unsigned i = 0; i < svq->vring.num; ++i) {
891 g_autofree VirtQueueElement *elem = NULL;
892 elem = g_steal_pointer(&svq->desc_state[i].elem);
893 if (elem) {
894 /*
895 * TODO: This is ok for networking, but other kinds of devices
896 * might have problems with just unpop these.
897 */
898 virtqueue_unpop(svq->vq, elem, 0);
899 }
900 }
901
902 next_avail_elem = g_steal_pointer(&svq->next_guest_avail_elem);
903 if (next_avail_elem) {
904 virtqueue_unpop(svq->vq, next_avail_elem, 0);
905 }
906 svq->vq = NULL;
907 g_free(svq->desc_state);
908 munmap(svq->vring.desc, vhost_svq_driver_area_size(svq));
909 munmap(svq->vring.used, vhost_svq_device_area_size(svq));
910 event_notifier_set_handler(&svq->hdev_call, NULL);
911 }
912
913 /**
914 * Creates vhost shadow virtqueue, and instructs the vhost device to use the
915 * shadow methods and file descriptors.
916 *
917 * @ops: SVQ owner callbacks
918 * @ops_opaque: ops opaque pointer
919 */
920 VhostShadowVirtqueue *vhost_svq_new(const VhostShadowVirtqueueOps *ops,
921 void *ops_opaque)
922 {
923 VhostShadowVirtqueue *svq = g_new0(VhostShadowVirtqueue, 1);
924
925 event_notifier_init_fd(&svq->svq_kick, VHOST_FILE_UNBIND);
926 svq->ops = ops;
927 svq->ops_opaque = ops_opaque;
928 return svq;
929 }
930
931 /**
932 * Free the resources of the shadow virtqueue.
933 *
934 * @pvq: gpointer to SVQ so it can be used by autofree functions.
935 */
936 void vhost_svq_free(gpointer pvq)
937 {
938 VhostShadowVirtqueue *vq = pvq;
939 vhost_svq_stop(vq);
940 g_free(vq);
941 }