xref: /qemu/hw/virtio/vhost.c (revision ff4776147e960b128ee68f94c728659f662f4378)
1 /*
2  * vhost support
3  *
4  * Copyright Red Hat, Inc. 2010
5  *
6  * Authors:
7  *  Michael S. Tsirkin <mst@redhat.com>
8  *
9  * This work is licensed under the terms of the GNU GPL, version 2.  See
10  * the COPYING file in the top-level directory.
11  *
12  * Contributions after 2012-01-13 are licensed under the terms of the
13  * GNU GPL, version 2 or (at your option) any later version.
14  */
15 
16 #include "qemu/osdep.h"
17 #include "qapi/error.h"
18 #include "hw/virtio/vhost.h"
19 #include "qemu/atomic.h"
20 #include "qemu/range.h"
21 #include "qemu/error-report.h"
22 #include "qemu/memfd.h"
23 #include "standard-headers/linux/vhost_types.h"
24 #include "exec/address-spaces.h"
25 #include "hw/virtio/virtio-bus.h"
26 #include "hw/virtio/virtio-access.h"
27 #include "migration/blocker.h"
28 #include "migration/qemu-file-types.h"
29 #include "sysemu/dma.h"
30 #include "trace.h"
31 
32 /* enabled until disconnected backend stabilizes */
33 #define _VHOST_DEBUG 1
34 
35 #ifdef _VHOST_DEBUG
36 #define VHOST_OPS_DEBUG(fmt, ...) \
37     do { error_report(fmt ": %s (%d)", ## __VA_ARGS__, \
38                       strerror(errno), errno); } while (0)
39 #else
40 #define VHOST_OPS_DEBUG(fmt, ...) \
41     do { } while (0)
42 #endif
43 
44 static struct vhost_log *vhost_log;
45 static struct vhost_log *vhost_log_shm;
46 
47 static unsigned int used_memslots;
48 static QLIST_HEAD(, vhost_dev) vhost_devices =
49     QLIST_HEAD_INITIALIZER(vhost_devices);
50 
51 bool vhost_has_free_slot(void)
52 {
53     unsigned int slots_limit = ~0U;
54     struct vhost_dev *hdev;
55 
56     QLIST_FOREACH(hdev, &vhost_devices, entry) {
57         unsigned int r = hdev->vhost_ops->vhost_backend_memslots_limit(hdev);
58         slots_limit = MIN(slots_limit, r);
59     }
60     return slots_limit > used_memslots;
61 }
62 
63 static void vhost_dev_sync_region(struct vhost_dev *dev,
64                                   MemoryRegionSection *section,
65                                   uint64_t mfirst, uint64_t mlast,
66                                   uint64_t rfirst, uint64_t rlast)
67 {
68     vhost_log_chunk_t *log = dev->log->log;
69 
70     uint64_t start = MAX(mfirst, rfirst);
71     uint64_t end = MIN(mlast, rlast);
72     vhost_log_chunk_t *from = log + start / VHOST_LOG_CHUNK;
73     vhost_log_chunk_t *to = log + end / VHOST_LOG_CHUNK + 1;
74     uint64_t addr = QEMU_ALIGN_DOWN(start, VHOST_LOG_CHUNK);
75 
76     if (end < start) {
77         return;
78     }
79     assert(end / VHOST_LOG_CHUNK < dev->log_size);
80     assert(start / VHOST_LOG_CHUNK < dev->log_size);
81 
82     for (;from < to; ++from) {
83         vhost_log_chunk_t log;
84         /* We first check with non-atomic: much cheaper,
85          * and we expect non-dirty to be the common case. */
86         if (!*from) {
87             addr += VHOST_LOG_CHUNK;
88             continue;
89         }
90         /* Data must be read atomically. We don't really need barrier semantics
91          * but it's easier to use atomic_* than roll our own. */
92         log = atomic_xchg(from, 0);
93         while (log) {
94             int bit = ctzl(log);
95             hwaddr page_addr;
96             hwaddr section_offset;
97             hwaddr mr_offset;
98             page_addr = addr + bit * VHOST_LOG_PAGE;
99             section_offset = page_addr - section->offset_within_address_space;
100             mr_offset = section_offset + section->offset_within_region;
101             memory_region_set_dirty(section->mr, mr_offset, VHOST_LOG_PAGE);
102             log &= ~(0x1ull << bit);
103         }
104         addr += VHOST_LOG_CHUNK;
105     }
106 }
107 
108 static int vhost_sync_dirty_bitmap(struct vhost_dev *dev,
109                                    MemoryRegionSection *section,
110                                    hwaddr first,
111                                    hwaddr last)
112 {
113     int i;
114     hwaddr start_addr;
115     hwaddr end_addr;
116 
117     if (!dev->log_enabled || !dev->started) {
118         return 0;
119     }
120     start_addr = section->offset_within_address_space;
121     end_addr = range_get_last(start_addr, int128_get64(section->size));
122     start_addr = MAX(first, start_addr);
123     end_addr = MIN(last, end_addr);
124 
125     for (i = 0; i < dev->mem->nregions; ++i) {
126         struct vhost_memory_region *reg = dev->mem->regions + i;
127         vhost_dev_sync_region(dev, section, start_addr, end_addr,
128                               reg->guest_phys_addr,
129                               range_get_last(reg->guest_phys_addr,
130                                              reg->memory_size));
131     }
132     for (i = 0; i < dev->nvqs; ++i) {
133         struct vhost_virtqueue *vq = dev->vqs + i;
134 
135         if (!vq->used_phys && !vq->used_size) {
136             continue;
137         }
138 
139         vhost_dev_sync_region(dev, section, start_addr, end_addr, vq->used_phys,
140                               range_get_last(vq->used_phys, vq->used_size));
141     }
142     return 0;
143 }
144 
145 static void vhost_log_sync(MemoryListener *listener,
146                           MemoryRegionSection *section)
147 {
148     struct vhost_dev *dev = container_of(listener, struct vhost_dev,
149                                          memory_listener);
150     vhost_sync_dirty_bitmap(dev, section, 0x0, ~0x0ULL);
151 }
152 
153 static void vhost_log_sync_range(struct vhost_dev *dev,
154                                  hwaddr first, hwaddr last)
155 {
156     int i;
157     /* FIXME: this is N^2 in number of sections */
158     for (i = 0; i < dev->n_mem_sections; ++i) {
159         MemoryRegionSection *section = &dev->mem_sections[i];
160         vhost_sync_dirty_bitmap(dev, section, first, last);
161     }
162 }
163 
164 static uint64_t vhost_get_log_size(struct vhost_dev *dev)
165 {
166     uint64_t log_size = 0;
167     int i;
168     for (i = 0; i < dev->mem->nregions; ++i) {
169         struct vhost_memory_region *reg = dev->mem->regions + i;
170         uint64_t last = range_get_last(reg->guest_phys_addr,
171                                        reg->memory_size);
172         log_size = MAX(log_size, last / VHOST_LOG_CHUNK + 1);
173     }
174     for (i = 0; i < dev->nvqs; ++i) {
175         struct vhost_virtqueue *vq = dev->vqs + i;
176 
177         if (!vq->used_phys && !vq->used_size) {
178             continue;
179         }
180 
181         uint64_t last = vq->used_phys + vq->used_size - 1;
182         log_size = MAX(log_size, last / VHOST_LOG_CHUNK + 1);
183     }
184     return log_size;
185 }
186 
187 static struct vhost_log *vhost_log_alloc(uint64_t size, bool share)
188 {
189     Error *err = NULL;
190     struct vhost_log *log;
191     uint64_t logsize = size * sizeof(*(log->log));
192     int fd = -1;
193 
194     log = g_new0(struct vhost_log, 1);
195     if (share) {
196         log->log = qemu_memfd_alloc("vhost-log", logsize,
197                                     F_SEAL_GROW | F_SEAL_SHRINK | F_SEAL_SEAL,
198                                     &fd, &err);
199         if (err) {
200             error_report_err(err);
201             g_free(log);
202             return NULL;
203         }
204         memset(log->log, 0, logsize);
205     } else {
206         log->log = g_malloc0(logsize);
207     }
208 
209     log->size = size;
210     log->refcnt = 1;
211     log->fd = fd;
212 
213     return log;
214 }
215 
216 static struct vhost_log *vhost_log_get(uint64_t size, bool share)
217 {
218     struct vhost_log *log = share ? vhost_log_shm : vhost_log;
219 
220     if (!log || log->size != size) {
221         log = vhost_log_alloc(size, share);
222         if (share) {
223             vhost_log_shm = log;
224         } else {
225             vhost_log = log;
226         }
227     } else {
228         ++log->refcnt;
229     }
230 
231     return log;
232 }
233 
234 static void vhost_log_put(struct vhost_dev *dev, bool sync)
235 {
236     struct vhost_log *log = dev->log;
237 
238     if (!log) {
239         return;
240     }
241 
242     --log->refcnt;
243     if (log->refcnt == 0) {
244         /* Sync only the range covered by the old log */
245         if (dev->log_size && sync) {
246             vhost_log_sync_range(dev, 0, dev->log_size * VHOST_LOG_CHUNK - 1);
247         }
248 
249         if (vhost_log == log) {
250             g_free(log->log);
251             vhost_log = NULL;
252         } else if (vhost_log_shm == log) {
253             qemu_memfd_free(log->log, log->size * sizeof(*(log->log)),
254                             log->fd);
255             vhost_log_shm = NULL;
256         }
257 
258         g_free(log);
259     }
260 
261     dev->log = NULL;
262     dev->log_size = 0;
263 }
264 
265 static bool vhost_dev_log_is_shared(struct vhost_dev *dev)
266 {
267     return dev->vhost_ops->vhost_requires_shm_log &&
268            dev->vhost_ops->vhost_requires_shm_log(dev);
269 }
270 
271 static inline void vhost_dev_log_resize(struct vhost_dev *dev, uint64_t size)
272 {
273     struct vhost_log *log = vhost_log_get(size, vhost_dev_log_is_shared(dev));
274     uint64_t log_base = (uintptr_t)log->log;
275     int r;
276 
277     /* inform backend of log switching, this must be done before
278        releasing the current log, to ensure no logging is lost */
279     r = dev->vhost_ops->vhost_set_log_base(dev, log_base, log);
280     if (r < 0) {
281         VHOST_OPS_DEBUG("vhost_set_log_base failed");
282     }
283 
284     vhost_log_put(dev, true);
285     dev->log = log;
286     dev->log_size = size;
287 }
288 
289 static int vhost_dev_has_iommu(struct vhost_dev *dev)
290 {
291     VirtIODevice *vdev = dev->vdev;
292 
293     return virtio_host_has_feature(vdev, VIRTIO_F_IOMMU_PLATFORM);
294 }
295 
296 static void *vhost_memory_map(struct vhost_dev *dev, hwaddr addr,
297                               hwaddr *plen, int is_write)
298 {
299     if (!vhost_dev_has_iommu(dev)) {
300         return cpu_physical_memory_map(addr, plen, is_write);
301     } else {
302         return (void *)(uintptr_t)addr;
303     }
304 }
305 
306 static void vhost_memory_unmap(struct vhost_dev *dev, void *buffer,
307                                hwaddr len, int is_write,
308                                hwaddr access_len)
309 {
310     if (!vhost_dev_has_iommu(dev)) {
311         cpu_physical_memory_unmap(buffer, len, is_write, access_len);
312     }
313 }
314 
315 static int vhost_verify_ring_part_mapping(void *ring_hva,
316                                           uint64_t ring_gpa,
317                                           uint64_t ring_size,
318                                           void *reg_hva,
319                                           uint64_t reg_gpa,
320                                           uint64_t reg_size)
321 {
322     uint64_t hva_ring_offset;
323     uint64_t ring_last = range_get_last(ring_gpa, ring_size);
324     uint64_t reg_last = range_get_last(reg_gpa, reg_size);
325 
326     if (ring_last < reg_gpa || ring_gpa > reg_last) {
327         return 0;
328     }
329     /* check that whole ring's is mapped */
330     if (ring_last > reg_last) {
331         return -ENOMEM;
332     }
333     /* check that ring's MemoryRegion wasn't replaced */
334     hva_ring_offset = ring_gpa - reg_gpa;
335     if (ring_hva != reg_hva + hva_ring_offset) {
336         return -EBUSY;
337     }
338 
339     return 0;
340 }
341 
342 static int vhost_verify_ring_mappings(struct vhost_dev *dev,
343                                       void *reg_hva,
344                                       uint64_t reg_gpa,
345                                       uint64_t reg_size)
346 {
347     int i, j;
348     int r = 0;
349     const char *part_name[] = {
350         "descriptor table",
351         "available ring",
352         "used ring"
353     };
354 
355     if (vhost_dev_has_iommu(dev)) {
356         return 0;
357     }
358 
359     for (i = 0; i < dev->nvqs; ++i) {
360         struct vhost_virtqueue *vq = dev->vqs + i;
361 
362         if (vq->desc_phys == 0) {
363             continue;
364         }
365 
366         j = 0;
367         r = vhost_verify_ring_part_mapping(
368                 vq->desc, vq->desc_phys, vq->desc_size,
369                 reg_hva, reg_gpa, reg_size);
370         if (r) {
371             break;
372         }
373 
374         j++;
375         r = vhost_verify_ring_part_mapping(
376                 vq->avail, vq->avail_phys, vq->avail_size,
377                 reg_hva, reg_gpa, reg_size);
378         if (r) {
379             break;
380         }
381 
382         j++;
383         r = vhost_verify_ring_part_mapping(
384                 vq->used, vq->used_phys, vq->used_size,
385                 reg_hva, reg_gpa, reg_size);
386         if (r) {
387             break;
388         }
389     }
390 
391     if (r == -ENOMEM) {
392         error_report("Unable to map %s for ring %d", part_name[j], i);
393     } else if (r == -EBUSY) {
394         error_report("%s relocated for ring %d", part_name[j], i);
395     }
396     return r;
397 }
398 
399 static bool vhost_section(struct vhost_dev *dev, MemoryRegionSection *section)
400 {
401     bool result;
402     bool log_dirty = memory_region_get_dirty_log_mask(section->mr) &
403                      ~(1 << DIRTY_MEMORY_MIGRATION);
404     result = memory_region_is_ram(section->mr) &&
405         !memory_region_is_rom(section->mr);
406 
407     /* Vhost doesn't handle any block which is doing dirty-tracking other
408      * than migration; this typically fires on VGA areas.
409      */
410     result &= !log_dirty;
411 
412     if (result && dev->vhost_ops->vhost_backend_mem_section_filter) {
413         result &=
414             dev->vhost_ops->vhost_backend_mem_section_filter(dev, section);
415     }
416 
417     trace_vhost_section(section->mr->name, result);
418     return result;
419 }
420 
421 static void vhost_begin(MemoryListener *listener)
422 {
423     struct vhost_dev *dev = container_of(listener, struct vhost_dev,
424                                          memory_listener);
425     dev->tmp_sections = NULL;
426     dev->n_tmp_sections = 0;
427 }
428 
429 static void vhost_commit(MemoryListener *listener)
430 {
431     struct vhost_dev *dev = container_of(listener, struct vhost_dev,
432                                          memory_listener);
433     MemoryRegionSection *old_sections;
434     int n_old_sections;
435     uint64_t log_size;
436     size_t regions_size;
437     int r;
438     int i;
439     bool changed = false;
440 
441     /* Note we can be called before the device is started, but then
442      * starting the device calls set_mem_table, so we need to have
443      * built the data structures.
444      */
445     old_sections = dev->mem_sections;
446     n_old_sections = dev->n_mem_sections;
447     dev->mem_sections = dev->tmp_sections;
448     dev->n_mem_sections = dev->n_tmp_sections;
449 
450     if (dev->n_mem_sections != n_old_sections) {
451         changed = true;
452     } else {
453         /* Same size, lets check the contents */
454         for (int i = 0; i < n_old_sections; i++) {
455             if (!MemoryRegionSection_eq(&old_sections[i],
456                                         &dev->mem_sections[i])) {
457                 changed = true;
458                 break;
459             }
460         }
461     }
462 
463     trace_vhost_commit(dev->started, changed);
464     if (!changed) {
465         goto out;
466     }
467 
468     /* Rebuild the regions list from the new sections list */
469     regions_size = offsetof(struct vhost_memory, regions) +
470                        dev->n_mem_sections * sizeof dev->mem->regions[0];
471     dev->mem = g_realloc(dev->mem, regions_size);
472     dev->mem->nregions = dev->n_mem_sections;
473     used_memslots = dev->mem->nregions;
474     for (i = 0; i < dev->n_mem_sections; i++) {
475         struct vhost_memory_region *cur_vmr = dev->mem->regions + i;
476         struct MemoryRegionSection *mrs = dev->mem_sections + i;
477 
478         cur_vmr->guest_phys_addr = mrs->offset_within_address_space;
479         cur_vmr->memory_size     = int128_get64(mrs->size);
480         cur_vmr->userspace_addr  =
481             (uintptr_t)memory_region_get_ram_ptr(mrs->mr) +
482             mrs->offset_within_region;
483         cur_vmr->flags_padding   = 0;
484     }
485 
486     if (!dev->started) {
487         goto out;
488     }
489 
490     for (i = 0; i < dev->mem->nregions; i++) {
491         if (vhost_verify_ring_mappings(dev,
492                        (void *)(uintptr_t)dev->mem->regions[i].userspace_addr,
493                        dev->mem->regions[i].guest_phys_addr,
494                        dev->mem->regions[i].memory_size)) {
495             error_report("Verify ring failure on region %d", i);
496             abort();
497         }
498     }
499 
500     if (!dev->log_enabled) {
501         r = dev->vhost_ops->vhost_set_mem_table(dev, dev->mem);
502         if (r < 0) {
503             VHOST_OPS_DEBUG("vhost_set_mem_table failed");
504         }
505         goto out;
506     }
507     log_size = vhost_get_log_size(dev);
508     /* We allocate an extra 4K bytes to log,
509      * to reduce the * number of reallocations. */
510 #define VHOST_LOG_BUFFER (0x1000 / sizeof *dev->log)
511     /* To log more, must increase log size before table update. */
512     if (dev->log_size < log_size) {
513         vhost_dev_log_resize(dev, log_size + VHOST_LOG_BUFFER);
514     }
515     r = dev->vhost_ops->vhost_set_mem_table(dev, dev->mem);
516     if (r < 0) {
517         VHOST_OPS_DEBUG("vhost_set_mem_table failed");
518     }
519     /* To log less, can only decrease log size after table update. */
520     if (dev->log_size > log_size + VHOST_LOG_BUFFER) {
521         vhost_dev_log_resize(dev, log_size);
522     }
523 
524 out:
525     /* Deref the old list of sections, this must happen _after_ the
526      * vhost_set_mem_table to ensure the client isn't still using the
527      * section we're about to unref.
528      */
529     while (n_old_sections--) {
530         memory_region_unref(old_sections[n_old_sections].mr);
531     }
532     g_free(old_sections);
533     return;
534 }
535 
536 /* Adds the section data to the tmp_section structure.
537  * It relies on the listener calling us in memory address order
538  * and for each region (via the _add and _nop methods) to
539  * join neighbours.
540  */
541 static void vhost_region_add_section(struct vhost_dev *dev,
542                                      MemoryRegionSection *section)
543 {
544     bool need_add = true;
545     uint64_t mrs_size = int128_get64(section->size);
546     uint64_t mrs_gpa = section->offset_within_address_space;
547     uintptr_t mrs_host = (uintptr_t)memory_region_get_ram_ptr(section->mr) +
548                          section->offset_within_region;
549     RAMBlock *mrs_rb = section->mr->ram_block;
550     size_t mrs_page = qemu_ram_pagesize(mrs_rb);
551 
552     trace_vhost_region_add_section(section->mr->name, mrs_gpa, mrs_size,
553                                    mrs_host);
554 
555     /* Round the section to it's page size */
556     /* First align the start down to a page boundary */
557     uint64_t alignage = mrs_host & (mrs_page - 1);
558     if (alignage) {
559         mrs_host -= alignage;
560         mrs_size += alignage;
561         mrs_gpa  -= alignage;
562     }
563     /* Now align the size up to a page boundary */
564     alignage = mrs_size & (mrs_page - 1);
565     if (alignage) {
566         mrs_size += mrs_page - alignage;
567     }
568     trace_vhost_region_add_section_aligned(section->mr->name, mrs_gpa, mrs_size,
569                                            mrs_host);
570 
571     if (dev->n_tmp_sections) {
572         /* Since we already have at least one section, lets see if
573          * this extends it; since we're scanning in order, we only
574          * have to look at the last one, and the FlatView that calls
575          * us shouldn't have overlaps.
576          */
577         MemoryRegionSection *prev_sec = dev->tmp_sections +
578                                                (dev->n_tmp_sections - 1);
579         uint64_t prev_gpa_start = prev_sec->offset_within_address_space;
580         uint64_t prev_size = int128_get64(prev_sec->size);
581         uint64_t prev_gpa_end   = range_get_last(prev_gpa_start, prev_size);
582         uint64_t prev_host_start =
583                         (uintptr_t)memory_region_get_ram_ptr(prev_sec->mr) +
584                         prev_sec->offset_within_region;
585         uint64_t prev_host_end   = range_get_last(prev_host_start, prev_size);
586 
587         if (mrs_gpa <= (prev_gpa_end + 1)) {
588             /* OK, looks like overlapping/intersecting - it's possible that
589              * the rounding to page sizes has made them overlap, but they should
590              * match up in the same RAMBlock if they do.
591              */
592             if (mrs_gpa < prev_gpa_start) {
593                 error_report("%s:Section '%s' rounded to %"PRIx64
594                              " prior to previous '%s' %"PRIx64,
595                              __func__, section->mr->name, mrs_gpa,
596                              prev_sec->mr->name, prev_gpa_start);
597                 /* A way to cleanly fail here would be better */
598                 return;
599             }
600             /* Offset from the start of the previous GPA to this GPA */
601             size_t offset = mrs_gpa - prev_gpa_start;
602 
603             if (prev_host_start + offset == mrs_host &&
604                 section->mr == prev_sec->mr &&
605                 (!dev->vhost_ops->vhost_backend_can_merge ||
606                  dev->vhost_ops->vhost_backend_can_merge(dev,
607                     mrs_host, mrs_size,
608                     prev_host_start, prev_size))) {
609                 uint64_t max_end = MAX(prev_host_end, mrs_host + mrs_size);
610                 need_add = false;
611                 prev_sec->offset_within_address_space =
612                     MIN(prev_gpa_start, mrs_gpa);
613                 prev_sec->offset_within_region =
614                     MIN(prev_host_start, mrs_host) -
615                     (uintptr_t)memory_region_get_ram_ptr(prev_sec->mr);
616                 prev_sec->size = int128_make64(max_end - MIN(prev_host_start,
617                                                mrs_host));
618                 trace_vhost_region_add_section_merge(section->mr->name,
619                                         int128_get64(prev_sec->size),
620                                         prev_sec->offset_within_address_space,
621                                         prev_sec->offset_within_region);
622             } else {
623                 /* adjoining regions are fine, but overlapping ones with
624                  * different blocks/offsets shouldn't happen
625                  */
626                 if (mrs_gpa != prev_gpa_end + 1) {
627                     error_report("%s: Overlapping but not coherent sections "
628                                  "at %"PRIx64,
629                                  __func__, mrs_gpa);
630                     return;
631                 }
632             }
633         }
634     }
635 
636     if (need_add) {
637         ++dev->n_tmp_sections;
638         dev->tmp_sections = g_renew(MemoryRegionSection, dev->tmp_sections,
639                                     dev->n_tmp_sections);
640         dev->tmp_sections[dev->n_tmp_sections - 1] = *section;
641         /* The flatview isn't stable and we don't use it, making it NULL
642          * means we can memcmp the list.
643          */
644         dev->tmp_sections[dev->n_tmp_sections - 1].fv = NULL;
645         memory_region_ref(section->mr);
646     }
647 }
648 
649 /* Used for both add and nop callbacks */
650 static void vhost_region_addnop(MemoryListener *listener,
651                                 MemoryRegionSection *section)
652 {
653     struct vhost_dev *dev = container_of(listener, struct vhost_dev,
654                                          memory_listener);
655 
656     if (!vhost_section(dev, section)) {
657         return;
658     }
659     vhost_region_add_section(dev, section);
660 }
661 
662 static void vhost_iommu_unmap_notify(IOMMUNotifier *n, IOMMUTLBEntry *iotlb)
663 {
664     struct vhost_iommu *iommu = container_of(n, struct vhost_iommu, n);
665     struct vhost_dev *hdev = iommu->hdev;
666     hwaddr iova = iotlb->iova + iommu->iommu_offset;
667 
668     if (vhost_backend_invalidate_device_iotlb(hdev, iova,
669                                               iotlb->addr_mask + 1)) {
670         error_report("Fail to invalidate device iotlb");
671     }
672 }
673 
674 static void vhost_iommu_region_add(MemoryListener *listener,
675                                    MemoryRegionSection *section)
676 {
677     struct vhost_dev *dev = container_of(listener, struct vhost_dev,
678                                          iommu_listener);
679     struct vhost_iommu *iommu;
680     Int128 end;
681     int iommu_idx, ret;
682     IOMMUMemoryRegion *iommu_mr;
683     Error *err = NULL;
684 
685     if (!memory_region_is_iommu(section->mr)) {
686         return;
687     }
688 
689     iommu_mr = IOMMU_MEMORY_REGION(section->mr);
690 
691     iommu = g_malloc0(sizeof(*iommu));
692     end = int128_add(int128_make64(section->offset_within_region),
693                      section->size);
694     end = int128_sub(end, int128_one());
695     iommu_idx = memory_region_iommu_attrs_to_index(iommu_mr,
696                                                    MEMTXATTRS_UNSPECIFIED);
697     iommu_notifier_init(&iommu->n, vhost_iommu_unmap_notify,
698                         IOMMU_NOTIFIER_UNMAP,
699                         section->offset_within_region,
700                         int128_get64(end),
701                         iommu_idx);
702     iommu->mr = section->mr;
703     iommu->iommu_offset = section->offset_within_address_space -
704                           section->offset_within_region;
705     iommu->hdev = dev;
706     ret = memory_region_register_iommu_notifier(section->mr, &iommu->n, &err);
707     if (ret) {
708         error_report_err(err);
709         exit(1);
710     }
711     QLIST_INSERT_HEAD(&dev->iommu_list, iommu, iommu_next);
712     /* TODO: can replay help performance here? */
713 }
714 
715 static void vhost_iommu_region_del(MemoryListener *listener,
716                                    MemoryRegionSection *section)
717 {
718     struct vhost_dev *dev = container_of(listener, struct vhost_dev,
719                                          iommu_listener);
720     struct vhost_iommu *iommu;
721 
722     if (!memory_region_is_iommu(section->mr)) {
723         return;
724     }
725 
726     QLIST_FOREACH(iommu, &dev->iommu_list, iommu_next) {
727         if (iommu->mr == section->mr &&
728             iommu->n.start == section->offset_within_region) {
729             memory_region_unregister_iommu_notifier(iommu->mr,
730                                                     &iommu->n);
731             QLIST_REMOVE(iommu, iommu_next);
732             g_free(iommu);
733             break;
734         }
735     }
736 }
737 
738 static int vhost_virtqueue_set_addr(struct vhost_dev *dev,
739                                     struct vhost_virtqueue *vq,
740                                     unsigned idx, bool enable_log)
741 {
742     struct vhost_vring_addr addr = {
743         .index = idx,
744         .desc_user_addr = (uint64_t)(unsigned long)vq->desc,
745         .avail_user_addr = (uint64_t)(unsigned long)vq->avail,
746         .used_user_addr = (uint64_t)(unsigned long)vq->used,
747         .log_guest_addr = vq->used_phys,
748         .flags = enable_log ? (1 << VHOST_VRING_F_LOG) : 0,
749     };
750     int r = dev->vhost_ops->vhost_set_vring_addr(dev, &addr);
751     if (r < 0) {
752         VHOST_OPS_DEBUG("vhost_set_vring_addr failed");
753         return -errno;
754     }
755     return 0;
756 }
757 
758 static int vhost_dev_set_features(struct vhost_dev *dev,
759                                   bool enable_log)
760 {
761     uint64_t features = dev->acked_features;
762     int r;
763     if (enable_log) {
764         features |= 0x1ULL << VHOST_F_LOG_ALL;
765     }
766     r = dev->vhost_ops->vhost_set_features(dev, features);
767     if (r < 0) {
768         VHOST_OPS_DEBUG("vhost_set_features failed");
769     }
770     return r < 0 ? -errno : 0;
771 }
772 
773 static int vhost_dev_set_log(struct vhost_dev *dev, bool enable_log)
774 {
775     int r, i, idx;
776     r = vhost_dev_set_features(dev, enable_log);
777     if (r < 0) {
778         goto err_features;
779     }
780     for (i = 0; i < dev->nvqs; ++i) {
781         idx = dev->vhost_ops->vhost_get_vq_index(dev, dev->vq_index + i);
782         r = vhost_virtqueue_set_addr(dev, dev->vqs + i, idx,
783                                      enable_log);
784         if (r < 0) {
785             goto err_vq;
786         }
787     }
788     return 0;
789 err_vq:
790     for (; i >= 0; --i) {
791         idx = dev->vhost_ops->vhost_get_vq_index(dev, dev->vq_index + i);
792         vhost_virtqueue_set_addr(dev, dev->vqs + i, idx,
793                                  dev->log_enabled);
794     }
795     vhost_dev_set_features(dev, dev->log_enabled);
796 err_features:
797     return r;
798 }
799 
800 static int vhost_migration_log(MemoryListener *listener, int enable)
801 {
802     struct vhost_dev *dev = container_of(listener, struct vhost_dev,
803                                          memory_listener);
804     int r;
805     if (!!enable == dev->log_enabled) {
806         return 0;
807     }
808     if (!dev->started) {
809         dev->log_enabled = enable;
810         return 0;
811     }
812     if (!enable) {
813         r = vhost_dev_set_log(dev, false);
814         if (r < 0) {
815             return r;
816         }
817         vhost_log_put(dev, false);
818     } else {
819         vhost_dev_log_resize(dev, vhost_get_log_size(dev));
820         r = vhost_dev_set_log(dev, true);
821         if (r < 0) {
822             return r;
823         }
824     }
825     dev->log_enabled = enable;
826     return 0;
827 }
828 
829 static void vhost_log_global_start(MemoryListener *listener)
830 {
831     int r;
832 
833     r = vhost_migration_log(listener, true);
834     if (r < 0) {
835         abort();
836     }
837 }
838 
839 static void vhost_log_global_stop(MemoryListener *listener)
840 {
841     int r;
842 
843     r = vhost_migration_log(listener, false);
844     if (r < 0) {
845         abort();
846     }
847 }
848 
849 static void vhost_log_start(MemoryListener *listener,
850                             MemoryRegionSection *section,
851                             int old, int new)
852 {
853     /* FIXME: implement */
854 }
855 
856 static void vhost_log_stop(MemoryListener *listener,
857                            MemoryRegionSection *section,
858                            int old, int new)
859 {
860     /* FIXME: implement */
861 }
862 
863 /* The vhost driver natively knows how to handle the vrings of non
864  * cross-endian legacy devices and modern devices. Only legacy devices
865  * exposed to a bi-endian guest may require the vhost driver to use a
866  * specific endianness.
867  */
868 static inline bool vhost_needs_vring_endian(VirtIODevice *vdev)
869 {
870     if (virtio_vdev_has_feature(vdev, VIRTIO_F_VERSION_1)) {
871         return false;
872     }
873 #ifdef HOST_WORDS_BIGENDIAN
874     return vdev->device_endian == VIRTIO_DEVICE_ENDIAN_LITTLE;
875 #else
876     return vdev->device_endian == VIRTIO_DEVICE_ENDIAN_BIG;
877 #endif
878 }
879 
880 static int vhost_virtqueue_set_vring_endian_legacy(struct vhost_dev *dev,
881                                                    bool is_big_endian,
882                                                    int vhost_vq_index)
883 {
884     struct vhost_vring_state s = {
885         .index = vhost_vq_index,
886         .num = is_big_endian
887     };
888 
889     if (!dev->vhost_ops->vhost_set_vring_endian(dev, &s)) {
890         return 0;
891     }
892 
893     VHOST_OPS_DEBUG("vhost_set_vring_endian failed");
894     if (errno == ENOTTY) {
895         error_report("vhost does not support cross-endian");
896         return -ENOSYS;
897     }
898 
899     return -errno;
900 }
901 
902 static int vhost_memory_region_lookup(struct vhost_dev *hdev,
903                                       uint64_t gpa, uint64_t *uaddr,
904                                       uint64_t *len)
905 {
906     int i;
907 
908     for (i = 0; i < hdev->mem->nregions; i++) {
909         struct vhost_memory_region *reg = hdev->mem->regions + i;
910 
911         if (gpa >= reg->guest_phys_addr &&
912             reg->guest_phys_addr + reg->memory_size > gpa) {
913             *uaddr = reg->userspace_addr + gpa - reg->guest_phys_addr;
914             *len = reg->guest_phys_addr + reg->memory_size - gpa;
915             return 0;
916         }
917     }
918 
919     return -EFAULT;
920 }
921 
922 int vhost_device_iotlb_miss(struct vhost_dev *dev, uint64_t iova, int write)
923 {
924     IOMMUTLBEntry iotlb;
925     uint64_t uaddr, len;
926     int ret = -EFAULT;
927 
928     RCU_READ_LOCK_GUARD();
929 
930     trace_vhost_iotlb_miss(dev, 1);
931 
932     iotlb = address_space_get_iotlb_entry(dev->vdev->dma_as,
933                                           iova, write,
934                                           MEMTXATTRS_UNSPECIFIED);
935     if (iotlb.target_as != NULL) {
936         ret = vhost_memory_region_lookup(dev, iotlb.translated_addr,
937                                          &uaddr, &len);
938         if (ret) {
939             trace_vhost_iotlb_miss(dev, 3);
940             error_report("Fail to lookup the translated address "
941                          "%"PRIx64, iotlb.translated_addr);
942             goto out;
943         }
944 
945         len = MIN(iotlb.addr_mask + 1, len);
946         iova = iova & ~iotlb.addr_mask;
947 
948         ret = vhost_backend_update_device_iotlb(dev, iova, uaddr,
949                                                 len, iotlb.perm);
950         if (ret) {
951             trace_vhost_iotlb_miss(dev, 4);
952             error_report("Fail to update device iotlb");
953             goto out;
954         }
955     }
956 
957     trace_vhost_iotlb_miss(dev, 2);
958 
959 out:
960     return ret;
961 }
962 
963 static int vhost_virtqueue_start(struct vhost_dev *dev,
964                                 struct VirtIODevice *vdev,
965                                 struct vhost_virtqueue *vq,
966                                 unsigned idx)
967 {
968     BusState *qbus = BUS(qdev_get_parent_bus(DEVICE(vdev)));
969     VirtioBusState *vbus = VIRTIO_BUS(qbus);
970     VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(vbus);
971     hwaddr s, l, a;
972     int r;
973     int vhost_vq_index = dev->vhost_ops->vhost_get_vq_index(dev, idx);
974     struct vhost_vring_file file = {
975         .index = vhost_vq_index
976     };
977     struct vhost_vring_state state = {
978         .index = vhost_vq_index
979     };
980     struct VirtQueue *vvq = virtio_get_queue(vdev, idx);
981 
982     a = virtio_queue_get_desc_addr(vdev, idx);
983     if (a == 0) {
984         /* Queue might not be ready for start */
985         return 0;
986     }
987 
988     vq->num = state.num = virtio_queue_get_num(vdev, idx);
989     r = dev->vhost_ops->vhost_set_vring_num(dev, &state);
990     if (r) {
991         VHOST_OPS_DEBUG("vhost_set_vring_num failed");
992         return -errno;
993     }
994 
995     state.num = virtio_queue_get_last_avail_idx(vdev, idx);
996     r = dev->vhost_ops->vhost_set_vring_base(dev, &state);
997     if (r) {
998         VHOST_OPS_DEBUG("vhost_set_vring_base failed");
999         return -errno;
1000     }
1001 
1002     if (vhost_needs_vring_endian(vdev)) {
1003         r = vhost_virtqueue_set_vring_endian_legacy(dev,
1004                                                     virtio_is_big_endian(vdev),
1005                                                     vhost_vq_index);
1006         if (r) {
1007             return -errno;
1008         }
1009     }
1010 
1011     vq->desc_size = s = l = virtio_queue_get_desc_size(vdev, idx);
1012     vq->desc_phys = a;
1013     vq->desc = vhost_memory_map(dev, a, &l, 0);
1014     if (!vq->desc || l != s) {
1015         r = -ENOMEM;
1016         goto fail_alloc_desc;
1017     }
1018     vq->avail_size = s = l = virtio_queue_get_avail_size(vdev, idx);
1019     vq->avail_phys = a = virtio_queue_get_avail_addr(vdev, idx);
1020     vq->avail = vhost_memory_map(dev, a, &l, 0);
1021     if (!vq->avail || l != s) {
1022         r = -ENOMEM;
1023         goto fail_alloc_avail;
1024     }
1025     vq->used_size = s = l = virtio_queue_get_used_size(vdev, idx);
1026     vq->used_phys = a = virtio_queue_get_used_addr(vdev, idx);
1027     vq->used = vhost_memory_map(dev, a, &l, 1);
1028     if (!vq->used || l != s) {
1029         r = -ENOMEM;
1030         goto fail_alloc_used;
1031     }
1032 
1033     r = vhost_virtqueue_set_addr(dev, vq, vhost_vq_index, dev->log_enabled);
1034     if (r < 0) {
1035         r = -errno;
1036         goto fail_alloc;
1037     }
1038 
1039     file.fd = event_notifier_get_fd(virtio_queue_get_host_notifier(vvq));
1040     r = dev->vhost_ops->vhost_set_vring_kick(dev, &file);
1041     if (r) {
1042         VHOST_OPS_DEBUG("vhost_set_vring_kick failed");
1043         r = -errno;
1044         goto fail_kick;
1045     }
1046 
1047     /* Clear and discard previous events if any. */
1048     event_notifier_test_and_clear(&vq->masked_notifier);
1049 
1050     /* Init vring in unmasked state, unless guest_notifier_mask
1051      * will do it later.
1052      */
1053     if (!vdev->use_guest_notifier_mask) {
1054         /* TODO: check and handle errors. */
1055         vhost_virtqueue_mask(dev, vdev, idx, false);
1056     }
1057 
1058     if (k->query_guest_notifiers &&
1059         k->query_guest_notifiers(qbus->parent) &&
1060         virtio_queue_vector(vdev, idx) == VIRTIO_NO_VECTOR) {
1061         file.fd = -1;
1062         r = dev->vhost_ops->vhost_set_vring_call(dev, &file);
1063         if (r) {
1064             goto fail_vector;
1065         }
1066     }
1067 
1068     return 0;
1069 
1070 fail_vector:
1071 fail_kick:
1072 fail_alloc:
1073     vhost_memory_unmap(dev, vq->used, virtio_queue_get_used_size(vdev, idx),
1074                        0, 0);
1075 fail_alloc_used:
1076     vhost_memory_unmap(dev, vq->avail, virtio_queue_get_avail_size(vdev, idx),
1077                        0, 0);
1078 fail_alloc_avail:
1079     vhost_memory_unmap(dev, vq->desc, virtio_queue_get_desc_size(vdev, idx),
1080                        0, 0);
1081 fail_alloc_desc:
1082     return r;
1083 }
1084 
1085 static void vhost_virtqueue_stop(struct vhost_dev *dev,
1086                                     struct VirtIODevice *vdev,
1087                                     struct vhost_virtqueue *vq,
1088                                     unsigned idx)
1089 {
1090     int vhost_vq_index = dev->vhost_ops->vhost_get_vq_index(dev, idx);
1091     struct vhost_vring_state state = {
1092         .index = vhost_vq_index,
1093     };
1094     int r;
1095 
1096     if (virtio_queue_get_desc_addr(vdev, idx) == 0) {
1097         /* Don't stop the virtqueue which might have not been started */
1098         return;
1099     }
1100 
1101     r = dev->vhost_ops->vhost_get_vring_base(dev, &state);
1102     if (r < 0) {
1103         VHOST_OPS_DEBUG("vhost VQ %u ring restore failed: %d", idx, r);
1104         /* Connection to the backend is broken, so let's sync internal
1105          * last avail idx to the device used idx.
1106          */
1107         virtio_queue_restore_last_avail_idx(vdev, idx);
1108     } else {
1109         virtio_queue_set_last_avail_idx(vdev, idx, state.num);
1110     }
1111     virtio_queue_invalidate_signalled_used(vdev, idx);
1112     virtio_queue_update_used_idx(vdev, idx);
1113 
1114     /* In the cross-endian case, we need to reset the vring endianness to
1115      * native as legacy devices expect so by default.
1116      */
1117     if (vhost_needs_vring_endian(vdev)) {
1118         vhost_virtqueue_set_vring_endian_legacy(dev,
1119                                                 !virtio_is_big_endian(vdev),
1120                                                 vhost_vq_index);
1121     }
1122 
1123     vhost_memory_unmap(dev, vq->used, virtio_queue_get_used_size(vdev, idx),
1124                        1, virtio_queue_get_used_size(vdev, idx));
1125     vhost_memory_unmap(dev, vq->avail, virtio_queue_get_avail_size(vdev, idx),
1126                        0, virtio_queue_get_avail_size(vdev, idx));
1127     vhost_memory_unmap(dev, vq->desc, virtio_queue_get_desc_size(vdev, idx),
1128                        0, virtio_queue_get_desc_size(vdev, idx));
1129 }
1130 
1131 static void vhost_eventfd_add(MemoryListener *listener,
1132                               MemoryRegionSection *section,
1133                               bool match_data, uint64_t data, EventNotifier *e)
1134 {
1135 }
1136 
1137 static void vhost_eventfd_del(MemoryListener *listener,
1138                               MemoryRegionSection *section,
1139                               bool match_data, uint64_t data, EventNotifier *e)
1140 {
1141 }
1142 
1143 static int vhost_virtqueue_set_busyloop_timeout(struct vhost_dev *dev,
1144                                                 int n, uint32_t timeout)
1145 {
1146     int vhost_vq_index = dev->vhost_ops->vhost_get_vq_index(dev, n);
1147     struct vhost_vring_state state = {
1148         .index = vhost_vq_index,
1149         .num = timeout,
1150     };
1151     int r;
1152 
1153     if (!dev->vhost_ops->vhost_set_vring_busyloop_timeout) {
1154         return -EINVAL;
1155     }
1156 
1157     r = dev->vhost_ops->vhost_set_vring_busyloop_timeout(dev, &state);
1158     if (r) {
1159         VHOST_OPS_DEBUG("vhost_set_vring_busyloop_timeout failed");
1160         return r;
1161     }
1162 
1163     return 0;
1164 }
1165 
1166 static int vhost_virtqueue_init(struct vhost_dev *dev,
1167                                 struct vhost_virtqueue *vq, int n)
1168 {
1169     int vhost_vq_index = dev->vhost_ops->vhost_get_vq_index(dev, n);
1170     struct vhost_vring_file file = {
1171         .index = vhost_vq_index,
1172     };
1173     int r = event_notifier_init(&vq->masked_notifier, 0);
1174     if (r < 0) {
1175         return r;
1176     }
1177 
1178     file.fd = event_notifier_get_fd(&vq->masked_notifier);
1179     r = dev->vhost_ops->vhost_set_vring_call(dev, &file);
1180     if (r) {
1181         VHOST_OPS_DEBUG("vhost_set_vring_call failed");
1182         r = -errno;
1183         goto fail_call;
1184     }
1185 
1186     vq->dev = dev;
1187 
1188     return 0;
1189 fail_call:
1190     event_notifier_cleanup(&vq->masked_notifier);
1191     return r;
1192 }
1193 
1194 static void vhost_virtqueue_cleanup(struct vhost_virtqueue *vq)
1195 {
1196     event_notifier_cleanup(&vq->masked_notifier);
1197 }
1198 
1199 int vhost_dev_init(struct vhost_dev *hdev, void *opaque,
1200                    VhostBackendType backend_type, uint32_t busyloop_timeout)
1201 {
1202     uint64_t features;
1203     int i, r, n_initialized_vqs = 0;
1204     Error *local_err = NULL;
1205 
1206     hdev->vdev = NULL;
1207     hdev->migration_blocker = NULL;
1208 
1209     r = vhost_set_backend_type(hdev, backend_type);
1210     assert(r >= 0);
1211 
1212     r = hdev->vhost_ops->vhost_backend_init(hdev, opaque);
1213     if (r < 0) {
1214         goto fail;
1215     }
1216 
1217     r = hdev->vhost_ops->vhost_set_owner(hdev);
1218     if (r < 0) {
1219         VHOST_OPS_DEBUG("vhost_set_owner failed");
1220         goto fail;
1221     }
1222 
1223     r = hdev->vhost_ops->vhost_get_features(hdev, &features);
1224     if (r < 0) {
1225         VHOST_OPS_DEBUG("vhost_get_features failed");
1226         goto fail;
1227     }
1228 
1229     for (i = 0; i < hdev->nvqs; ++i, ++n_initialized_vqs) {
1230         r = vhost_virtqueue_init(hdev, hdev->vqs + i, hdev->vq_index + i);
1231         if (r < 0) {
1232             goto fail;
1233         }
1234     }
1235 
1236     if (busyloop_timeout) {
1237         for (i = 0; i < hdev->nvqs; ++i) {
1238             r = vhost_virtqueue_set_busyloop_timeout(hdev, hdev->vq_index + i,
1239                                                      busyloop_timeout);
1240             if (r < 0) {
1241                 goto fail_busyloop;
1242             }
1243         }
1244     }
1245 
1246     hdev->features = features;
1247 
1248     hdev->memory_listener = (MemoryListener) {
1249         .begin = vhost_begin,
1250         .commit = vhost_commit,
1251         .region_add = vhost_region_addnop,
1252         .region_nop = vhost_region_addnop,
1253         .log_start = vhost_log_start,
1254         .log_stop = vhost_log_stop,
1255         .log_sync = vhost_log_sync,
1256         .log_global_start = vhost_log_global_start,
1257         .log_global_stop = vhost_log_global_stop,
1258         .eventfd_add = vhost_eventfd_add,
1259         .eventfd_del = vhost_eventfd_del,
1260         .priority = 10
1261     };
1262 
1263     hdev->iommu_listener = (MemoryListener) {
1264         .region_add = vhost_iommu_region_add,
1265         .region_del = vhost_iommu_region_del,
1266     };
1267 
1268     if (hdev->migration_blocker == NULL) {
1269         if (!(hdev->features & (0x1ULL << VHOST_F_LOG_ALL))) {
1270             error_setg(&hdev->migration_blocker,
1271                        "Migration disabled: vhost lacks VHOST_F_LOG_ALL feature.");
1272         } else if (vhost_dev_log_is_shared(hdev) && !qemu_memfd_alloc_check()) {
1273             error_setg(&hdev->migration_blocker,
1274                        "Migration disabled: failed to allocate shared memory");
1275         }
1276     }
1277 
1278     if (hdev->migration_blocker != NULL) {
1279         r = migrate_add_blocker(hdev->migration_blocker, &local_err);
1280         if (local_err) {
1281             error_report_err(local_err);
1282             error_free(hdev->migration_blocker);
1283             goto fail_busyloop;
1284         }
1285     }
1286 
1287     hdev->mem = g_malloc0(offsetof(struct vhost_memory, regions));
1288     hdev->n_mem_sections = 0;
1289     hdev->mem_sections = NULL;
1290     hdev->log = NULL;
1291     hdev->log_size = 0;
1292     hdev->log_enabled = false;
1293     hdev->started = false;
1294     memory_listener_register(&hdev->memory_listener, &address_space_memory);
1295     QLIST_INSERT_HEAD(&vhost_devices, hdev, entry);
1296 
1297     if (used_memslots > hdev->vhost_ops->vhost_backend_memslots_limit(hdev)) {
1298         error_report("vhost backend memory slots limit is less"
1299                 " than current number of present memory slots");
1300         r = -1;
1301         if (busyloop_timeout) {
1302             goto fail_busyloop;
1303         } else {
1304             goto fail;
1305         }
1306     }
1307 
1308     return 0;
1309 
1310 fail_busyloop:
1311     while (--i >= 0) {
1312         vhost_virtqueue_set_busyloop_timeout(hdev, hdev->vq_index + i, 0);
1313     }
1314 fail:
1315     hdev->nvqs = n_initialized_vqs;
1316     vhost_dev_cleanup(hdev);
1317     return r;
1318 }
1319 
1320 void vhost_dev_cleanup(struct vhost_dev *hdev)
1321 {
1322     int i;
1323 
1324     for (i = 0; i < hdev->nvqs; ++i) {
1325         vhost_virtqueue_cleanup(hdev->vqs + i);
1326     }
1327     if (hdev->mem) {
1328         /* those are only safe after successful init */
1329         memory_listener_unregister(&hdev->memory_listener);
1330         QLIST_REMOVE(hdev, entry);
1331     }
1332     if (hdev->migration_blocker) {
1333         migrate_del_blocker(hdev->migration_blocker);
1334         error_free(hdev->migration_blocker);
1335     }
1336     g_free(hdev->mem);
1337     g_free(hdev->mem_sections);
1338     if (hdev->vhost_ops) {
1339         hdev->vhost_ops->vhost_backend_cleanup(hdev);
1340     }
1341     assert(!hdev->log);
1342 
1343     memset(hdev, 0, sizeof(struct vhost_dev));
1344 }
1345 
1346 /* Stop processing guest IO notifications in qemu.
1347  * Start processing them in vhost in kernel.
1348  */
1349 int vhost_dev_enable_notifiers(struct vhost_dev *hdev, VirtIODevice *vdev)
1350 {
1351     BusState *qbus = BUS(qdev_get_parent_bus(DEVICE(vdev)));
1352     int i, r, e;
1353 
1354     /* We will pass the notifiers to the kernel, make sure that QEMU
1355      * doesn't interfere.
1356      */
1357     r = virtio_device_grab_ioeventfd(vdev);
1358     if (r < 0) {
1359         error_report("binding does not support host notifiers");
1360         goto fail;
1361     }
1362 
1363     for (i = 0; i < hdev->nvqs; ++i) {
1364         r = virtio_bus_set_host_notifier(VIRTIO_BUS(qbus), hdev->vq_index + i,
1365                                          true);
1366         if (r < 0) {
1367             error_report("vhost VQ %d notifier binding failed: %d", i, -r);
1368             goto fail_vq;
1369         }
1370     }
1371 
1372     return 0;
1373 fail_vq:
1374     while (--i >= 0) {
1375         e = virtio_bus_set_host_notifier(VIRTIO_BUS(qbus), hdev->vq_index + i,
1376                                          false);
1377         if (e < 0) {
1378             error_report("vhost VQ %d notifier cleanup error: %d", i, -r);
1379         }
1380         assert (e >= 0);
1381         virtio_bus_cleanup_host_notifier(VIRTIO_BUS(qbus), hdev->vq_index + i);
1382     }
1383     virtio_device_release_ioeventfd(vdev);
1384 fail:
1385     return r;
1386 }
1387 
1388 /* Stop processing guest IO notifications in vhost.
1389  * Start processing them in qemu.
1390  * This might actually run the qemu handlers right away,
1391  * so virtio in qemu must be completely setup when this is called.
1392  */
1393 void vhost_dev_disable_notifiers(struct vhost_dev *hdev, VirtIODevice *vdev)
1394 {
1395     BusState *qbus = BUS(qdev_get_parent_bus(DEVICE(vdev)));
1396     int i, r;
1397 
1398     for (i = 0; i < hdev->nvqs; ++i) {
1399         r = virtio_bus_set_host_notifier(VIRTIO_BUS(qbus), hdev->vq_index + i,
1400                                          false);
1401         if (r < 0) {
1402             error_report("vhost VQ %d notifier cleanup failed: %d", i, -r);
1403         }
1404         assert (r >= 0);
1405         virtio_bus_cleanup_host_notifier(VIRTIO_BUS(qbus), hdev->vq_index + i);
1406     }
1407     virtio_device_release_ioeventfd(vdev);
1408 }
1409 
1410 /* Test and clear event pending status.
1411  * Should be called after unmask to avoid losing events.
1412  */
1413 bool vhost_virtqueue_pending(struct vhost_dev *hdev, int n)
1414 {
1415     struct vhost_virtqueue *vq = hdev->vqs + n - hdev->vq_index;
1416     assert(n >= hdev->vq_index && n < hdev->vq_index + hdev->nvqs);
1417     return event_notifier_test_and_clear(&vq->masked_notifier);
1418 }
1419 
1420 /* Mask/unmask events from this vq. */
1421 void vhost_virtqueue_mask(struct vhost_dev *hdev, VirtIODevice *vdev, int n,
1422                          bool mask)
1423 {
1424     struct VirtQueue *vvq = virtio_get_queue(vdev, n);
1425     int r, index = n - hdev->vq_index;
1426     struct vhost_vring_file file;
1427 
1428     /* should only be called after backend is connected */
1429     assert(hdev->vhost_ops);
1430 
1431     if (mask) {
1432         assert(vdev->use_guest_notifier_mask);
1433         file.fd = event_notifier_get_fd(&hdev->vqs[index].masked_notifier);
1434     } else {
1435         file.fd = event_notifier_get_fd(virtio_queue_get_guest_notifier(vvq));
1436     }
1437 
1438     file.index = hdev->vhost_ops->vhost_get_vq_index(hdev, n);
1439     r = hdev->vhost_ops->vhost_set_vring_call(hdev, &file);
1440     if (r < 0) {
1441         VHOST_OPS_DEBUG("vhost_set_vring_call failed");
1442     }
1443 }
1444 
1445 uint64_t vhost_get_features(struct vhost_dev *hdev, const int *feature_bits,
1446                             uint64_t features)
1447 {
1448     const int *bit = feature_bits;
1449     while (*bit != VHOST_INVALID_FEATURE_BIT) {
1450         uint64_t bit_mask = (1ULL << *bit);
1451         if (!(hdev->features & bit_mask)) {
1452             features &= ~bit_mask;
1453         }
1454         bit++;
1455     }
1456     return features;
1457 }
1458 
1459 void vhost_ack_features(struct vhost_dev *hdev, const int *feature_bits,
1460                         uint64_t features)
1461 {
1462     const int *bit = feature_bits;
1463     while (*bit != VHOST_INVALID_FEATURE_BIT) {
1464         uint64_t bit_mask = (1ULL << *bit);
1465         if (features & bit_mask) {
1466             hdev->acked_features |= bit_mask;
1467         }
1468         bit++;
1469     }
1470 }
1471 
1472 int vhost_dev_get_config(struct vhost_dev *hdev, uint8_t *config,
1473                          uint32_t config_len)
1474 {
1475     assert(hdev->vhost_ops);
1476 
1477     if (hdev->vhost_ops->vhost_get_config) {
1478         return hdev->vhost_ops->vhost_get_config(hdev, config, config_len);
1479     }
1480 
1481     return -1;
1482 }
1483 
1484 int vhost_dev_set_config(struct vhost_dev *hdev, const uint8_t *data,
1485                          uint32_t offset, uint32_t size, uint32_t flags)
1486 {
1487     assert(hdev->vhost_ops);
1488 
1489     if (hdev->vhost_ops->vhost_set_config) {
1490         return hdev->vhost_ops->vhost_set_config(hdev, data, offset,
1491                                                  size, flags);
1492     }
1493 
1494     return -1;
1495 }
1496 
1497 void vhost_dev_set_config_notifier(struct vhost_dev *hdev,
1498                                    const VhostDevConfigOps *ops)
1499 {
1500     hdev->config_ops = ops;
1501 }
1502 
1503 void vhost_dev_free_inflight(struct vhost_inflight *inflight)
1504 {
1505     if (inflight->addr) {
1506         qemu_memfd_free(inflight->addr, inflight->size, inflight->fd);
1507         inflight->addr = NULL;
1508         inflight->fd = -1;
1509     }
1510 }
1511 
1512 static int vhost_dev_resize_inflight(struct vhost_inflight *inflight,
1513                                      uint64_t new_size)
1514 {
1515     Error *err = NULL;
1516     int fd = -1;
1517     void *addr = qemu_memfd_alloc("vhost-inflight", new_size,
1518                                   F_SEAL_GROW | F_SEAL_SHRINK | F_SEAL_SEAL,
1519                                   &fd, &err);
1520 
1521     if (err) {
1522         error_report_err(err);
1523         return -1;
1524     }
1525 
1526     vhost_dev_free_inflight(inflight);
1527     inflight->offset = 0;
1528     inflight->addr = addr;
1529     inflight->fd = fd;
1530     inflight->size = new_size;
1531 
1532     return 0;
1533 }
1534 
1535 void vhost_dev_save_inflight(struct vhost_inflight *inflight, QEMUFile *f)
1536 {
1537     if (inflight->addr) {
1538         qemu_put_be64(f, inflight->size);
1539         qemu_put_be16(f, inflight->queue_size);
1540         qemu_put_buffer(f, inflight->addr, inflight->size);
1541     } else {
1542         qemu_put_be64(f, 0);
1543     }
1544 }
1545 
1546 int vhost_dev_load_inflight(struct vhost_inflight *inflight, QEMUFile *f)
1547 {
1548     uint64_t size;
1549 
1550     size = qemu_get_be64(f);
1551     if (!size) {
1552         return 0;
1553     }
1554 
1555     if (inflight->size != size) {
1556         if (vhost_dev_resize_inflight(inflight, size)) {
1557             return -1;
1558         }
1559     }
1560     inflight->queue_size = qemu_get_be16(f);
1561 
1562     qemu_get_buffer(f, inflight->addr, size);
1563 
1564     return 0;
1565 }
1566 
1567 int vhost_dev_set_inflight(struct vhost_dev *dev,
1568                            struct vhost_inflight *inflight)
1569 {
1570     int r;
1571 
1572     if (dev->vhost_ops->vhost_set_inflight_fd && inflight->addr) {
1573         r = dev->vhost_ops->vhost_set_inflight_fd(dev, inflight);
1574         if (r) {
1575             VHOST_OPS_DEBUG("vhost_set_inflight_fd failed");
1576             return -errno;
1577         }
1578     }
1579 
1580     return 0;
1581 }
1582 
1583 int vhost_dev_get_inflight(struct vhost_dev *dev, uint16_t queue_size,
1584                            struct vhost_inflight *inflight)
1585 {
1586     int r;
1587 
1588     if (dev->vhost_ops->vhost_get_inflight_fd) {
1589         r = dev->vhost_ops->vhost_get_inflight_fd(dev, queue_size, inflight);
1590         if (r) {
1591             VHOST_OPS_DEBUG("vhost_get_inflight_fd failed");
1592             return -errno;
1593         }
1594     }
1595 
1596     return 0;
1597 }
1598 
1599 /* Host notifiers must be enabled at this point. */
1600 int vhost_dev_start(struct vhost_dev *hdev, VirtIODevice *vdev)
1601 {
1602     int i, r;
1603 
1604     /* should only be called after backend is connected */
1605     assert(hdev->vhost_ops);
1606 
1607     hdev->started = true;
1608     hdev->vdev = vdev;
1609 
1610     r = vhost_dev_set_features(hdev, hdev->log_enabled);
1611     if (r < 0) {
1612         goto fail_features;
1613     }
1614 
1615     if (vhost_dev_has_iommu(hdev)) {
1616         memory_listener_register(&hdev->iommu_listener, vdev->dma_as);
1617     }
1618 
1619     r = hdev->vhost_ops->vhost_set_mem_table(hdev, hdev->mem);
1620     if (r < 0) {
1621         VHOST_OPS_DEBUG("vhost_set_mem_table failed");
1622         r = -errno;
1623         goto fail_mem;
1624     }
1625     for (i = 0; i < hdev->nvqs; ++i) {
1626         r = vhost_virtqueue_start(hdev,
1627                                   vdev,
1628                                   hdev->vqs + i,
1629                                   hdev->vq_index + i);
1630         if (r < 0) {
1631             goto fail_vq;
1632         }
1633     }
1634 
1635     if (hdev->log_enabled) {
1636         uint64_t log_base;
1637 
1638         hdev->log_size = vhost_get_log_size(hdev);
1639         hdev->log = vhost_log_get(hdev->log_size,
1640                                   vhost_dev_log_is_shared(hdev));
1641         log_base = (uintptr_t)hdev->log->log;
1642         r = hdev->vhost_ops->vhost_set_log_base(hdev,
1643                                                 hdev->log_size ? log_base : 0,
1644                                                 hdev->log);
1645         if (r < 0) {
1646             VHOST_OPS_DEBUG("vhost_set_log_base failed");
1647             r = -errno;
1648             goto fail_log;
1649         }
1650     }
1651 
1652     if (vhost_dev_has_iommu(hdev)) {
1653         hdev->vhost_ops->vhost_set_iotlb_callback(hdev, true);
1654 
1655         /* Update used ring information for IOTLB to work correctly,
1656          * vhost-kernel code requires for this.*/
1657         for (i = 0; i < hdev->nvqs; ++i) {
1658             struct vhost_virtqueue *vq = hdev->vqs + i;
1659             vhost_device_iotlb_miss(hdev, vq->used_phys, true);
1660         }
1661     }
1662     return 0;
1663 fail_log:
1664     vhost_log_put(hdev, false);
1665 fail_vq:
1666     while (--i >= 0) {
1667         vhost_virtqueue_stop(hdev,
1668                              vdev,
1669                              hdev->vqs + i,
1670                              hdev->vq_index + i);
1671     }
1672 
1673 fail_mem:
1674 fail_features:
1675 
1676     hdev->started = false;
1677     return r;
1678 }
1679 
1680 /* Host notifiers must be enabled at this point. */
1681 void vhost_dev_stop(struct vhost_dev *hdev, VirtIODevice *vdev)
1682 {
1683     int i;
1684 
1685     /* should only be called after backend is connected */
1686     assert(hdev->vhost_ops);
1687 
1688     for (i = 0; i < hdev->nvqs; ++i) {
1689         vhost_virtqueue_stop(hdev,
1690                              vdev,
1691                              hdev->vqs + i,
1692                              hdev->vq_index + i);
1693     }
1694 
1695     if (vhost_dev_has_iommu(hdev)) {
1696         hdev->vhost_ops->vhost_set_iotlb_callback(hdev, false);
1697         memory_listener_unregister(&hdev->iommu_listener);
1698     }
1699     vhost_log_put(hdev, true);
1700     hdev->started = false;
1701     hdev->vdev = NULL;
1702 }
1703 
1704 int vhost_net_set_backend(struct vhost_dev *hdev,
1705                           struct vhost_vring_file *file)
1706 {
1707     if (hdev->vhost_ops->vhost_net_set_backend) {
1708         return hdev->vhost_ops->vhost_net_set_backend(hdev, file);
1709     }
1710 
1711     return -1;
1712 }
1713