xref: /qemu/hw/virtio/vhost.c (revision 162bba7fa84182e5dc07f94db9744fc80109592a)
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 "hw/hw.h"
20 #include "qemu/atomic.h"
21 #include "qemu/range.h"
22 #include "qemu/error-report.h"
23 #include "qemu/memfd.h"
24 #include <linux/vhost.h>
25 #include "exec/address-spaces.h"
26 #include "hw/virtio/virtio-bus.h"
27 #include "hw/virtio/virtio-access.h"
28 #include "migration/migration.h"
29 
30 /* enabled until disconnected backend stabilizes */
31 #define _VHOST_DEBUG 1
32 
33 #ifdef _VHOST_DEBUG
34 #define VHOST_OPS_DEBUG(fmt, ...) \
35     do { error_report(fmt ": %s (%d)", ## __VA_ARGS__, \
36                       strerror(errno), errno); } while (0)
37 #else
38 #define VHOST_OPS_DEBUG(fmt, ...) \
39     do { } while (0)
40 #endif
41 
42 static struct vhost_log *vhost_log;
43 static struct vhost_log *vhost_log_shm;
44 
45 static unsigned int used_memslots;
46 static QLIST_HEAD(, vhost_dev) vhost_devices =
47     QLIST_HEAD_INITIALIZER(vhost_devices);
48 
49 bool vhost_has_free_slot(void)
50 {
51     unsigned int slots_limit = ~0U;
52     struct vhost_dev *hdev;
53 
54     QLIST_FOREACH(hdev, &vhost_devices, entry) {
55         unsigned int r = hdev->vhost_ops->vhost_backend_memslots_limit(hdev);
56         slots_limit = MIN(slots_limit, r);
57     }
58     return slots_limit > used_memslots;
59 }
60 
61 static void vhost_dev_sync_region(struct vhost_dev *dev,
62                                   MemoryRegionSection *section,
63                                   uint64_t mfirst, uint64_t mlast,
64                                   uint64_t rfirst, uint64_t rlast)
65 {
66     vhost_log_chunk_t *log = dev->log->log;
67 
68     uint64_t start = MAX(mfirst, rfirst);
69     uint64_t end = MIN(mlast, rlast);
70     vhost_log_chunk_t *from = log + start / VHOST_LOG_CHUNK;
71     vhost_log_chunk_t *to = log + end / VHOST_LOG_CHUNK + 1;
72     uint64_t addr = (start / VHOST_LOG_CHUNK) * VHOST_LOG_CHUNK;
73 
74     if (end < start) {
75         return;
76     }
77     assert(end / VHOST_LOG_CHUNK < dev->log_size);
78     assert(start / VHOST_LOG_CHUNK < dev->log_size);
79 
80     for (;from < to; ++from) {
81         vhost_log_chunk_t log;
82         /* We first check with non-atomic: much cheaper,
83          * and we expect non-dirty to be the common case. */
84         if (!*from) {
85             addr += VHOST_LOG_CHUNK;
86             continue;
87         }
88         /* Data must be read atomically. We don't really need barrier semantics
89          * but it's easier to use atomic_* than roll our own. */
90         log = atomic_xchg(from, 0);
91         while (log) {
92             int bit = ctzl(log);
93             hwaddr page_addr;
94             hwaddr section_offset;
95             hwaddr mr_offset;
96             page_addr = addr + bit * VHOST_LOG_PAGE;
97             section_offset = page_addr - section->offset_within_address_space;
98             mr_offset = section_offset + section->offset_within_region;
99             memory_region_set_dirty(section->mr, mr_offset, VHOST_LOG_PAGE);
100             log &= ~(0x1ull << bit);
101         }
102         addr += VHOST_LOG_CHUNK;
103     }
104 }
105 
106 static int vhost_sync_dirty_bitmap(struct vhost_dev *dev,
107                                    MemoryRegionSection *section,
108                                    hwaddr first,
109                                    hwaddr last)
110 {
111     int i;
112     hwaddr start_addr;
113     hwaddr end_addr;
114 
115     if (!dev->log_enabled || !dev->started) {
116         return 0;
117     }
118     start_addr = section->offset_within_address_space;
119     end_addr = range_get_last(start_addr, int128_get64(section->size));
120     start_addr = MAX(first, start_addr);
121     end_addr = MIN(last, end_addr);
122 
123     for (i = 0; i < dev->mem->nregions; ++i) {
124         struct vhost_memory_region *reg = dev->mem->regions + i;
125         vhost_dev_sync_region(dev, section, start_addr, end_addr,
126                               reg->guest_phys_addr,
127                               range_get_last(reg->guest_phys_addr,
128                                              reg->memory_size));
129     }
130     for (i = 0; i < dev->nvqs; ++i) {
131         struct vhost_virtqueue *vq = dev->vqs + i;
132         vhost_dev_sync_region(dev, section, start_addr, end_addr, vq->used_phys,
133                               range_get_last(vq->used_phys, vq->used_size));
134     }
135     return 0;
136 }
137 
138 static void vhost_log_sync(MemoryListener *listener,
139                           MemoryRegionSection *section)
140 {
141     struct vhost_dev *dev = container_of(listener, struct vhost_dev,
142                                          memory_listener);
143     vhost_sync_dirty_bitmap(dev, section, 0x0, ~0x0ULL);
144 }
145 
146 static void vhost_log_sync_range(struct vhost_dev *dev,
147                                  hwaddr first, hwaddr last)
148 {
149     int i;
150     /* FIXME: this is N^2 in number of sections */
151     for (i = 0; i < dev->n_mem_sections; ++i) {
152         MemoryRegionSection *section = &dev->mem_sections[i];
153         vhost_sync_dirty_bitmap(dev, section, first, last);
154     }
155 }
156 
157 /* Assign/unassign. Keep an unsorted array of non-overlapping
158  * memory regions in dev->mem. */
159 static void vhost_dev_unassign_memory(struct vhost_dev *dev,
160                                       uint64_t start_addr,
161                                       uint64_t size)
162 {
163     int from, to, n = dev->mem->nregions;
164     /* Track overlapping/split regions for sanity checking. */
165     int overlap_start = 0, overlap_end = 0, overlap_middle = 0, split = 0;
166 
167     for (from = 0, to = 0; from < n; ++from, ++to) {
168         struct vhost_memory_region *reg = dev->mem->regions + to;
169         uint64_t reglast;
170         uint64_t memlast;
171         uint64_t change;
172 
173         /* clone old region */
174         if (to != from) {
175             memcpy(reg, dev->mem->regions + from, sizeof *reg);
176         }
177 
178         /* No overlap is simple */
179         if (!ranges_overlap(reg->guest_phys_addr, reg->memory_size,
180                             start_addr, size)) {
181             continue;
182         }
183 
184         /* Split only happens if supplied region
185          * is in the middle of an existing one. Thus it can not
186          * overlap with any other existing region. */
187         assert(!split);
188 
189         reglast = range_get_last(reg->guest_phys_addr, reg->memory_size);
190         memlast = range_get_last(start_addr, size);
191 
192         /* Remove whole region */
193         if (start_addr <= reg->guest_phys_addr && memlast >= reglast) {
194             --dev->mem->nregions;
195             --to;
196             ++overlap_middle;
197             continue;
198         }
199 
200         /* Shrink region */
201         if (memlast >= reglast) {
202             reg->memory_size = start_addr - reg->guest_phys_addr;
203             assert(reg->memory_size);
204             assert(!overlap_end);
205             ++overlap_end;
206             continue;
207         }
208 
209         /* Shift region */
210         if (start_addr <= reg->guest_phys_addr) {
211             change = memlast + 1 - reg->guest_phys_addr;
212             reg->memory_size -= change;
213             reg->guest_phys_addr += change;
214             reg->userspace_addr += change;
215             assert(reg->memory_size);
216             assert(!overlap_start);
217             ++overlap_start;
218             continue;
219         }
220 
221         /* This only happens if supplied region
222          * is in the middle of an existing one. Thus it can not
223          * overlap with any other existing region. */
224         assert(!overlap_start);
225         assert(!overlap_end);
226         assert(!overlap_middle);
227         /* Split region: shrink first part, shift second part. */
228         memcpy(dev->mem->regions + n, reg, sizeof *reg);
229         reg->memory_size = start_addr - reg->guest_phys_addr;
230         assert(reg->memory_size);
231         change = memlast + 1 - reg->guest_phys_addr;
232         reg = dev->mem->regions + n;
233         reg->memory_size -= change;
234         assert(reg->memory_size);
235         reg->guest_phys_addr += change;
236         reg->userspace_addr += change;
237         /* Never add more than 1 region */
238         assert(dev->mem->nregions == n);
239         ++dev->mem->nregions;
240         ++split;
241     }
242 }
243 
244 /* Called after unassign, so no regions overlap the given range. */
245 static void vhost_dev_assign_memory(struct vhost_dev *dev,
246                                     uint64_t start_addr,
247                                     uint64_t size,
248                                     uint64_t uaddr)
249 {
250     int from, to;
251     struct vhost_memory_region *merged = NULL;
252     for (from = 0, to = 0; from < dev->mem->nregions; ++from, ++to) {
253         struct vhost_memory_region *reg = dev->mem->regions + to;
254         uint64_t prlast, urlast;
255         uint64_t pmlast, umlast;
256         uint64_t s, e, u;
257 
258         /* clone old region */
259         if (to != from) {
260             memcpy(reg, dev->mem->regions + from, sizeof *reg);
261         }
262         prlast = range_get_last(reg->guest_phys_addr, reg->memory_size);
263         pmlast = range_get_last(start_addr, size);
264         urlast = range_get_last(reg->userspace_addr, reg->memory_size);
265         umlast = range_get_last(uaddr, size);
266 
267         /* check for overlapping regions: should never happen. */
268         assert(prlast < start_addr || pmlast < reg->guest_phys_addr);
269         /* Not an adjacent or overlapping region - do not merge. */
270         if ((prlast + 1 != start_addr || urlast + 1 != uaddr) &&
271             (pmlast + 1 != reg->guest_phys_addr ||
272              umlast + 1 != reg->userspace_addr)) {
273             continue;
274         }
275 
276         if (dev->vhost_ops->vhost_backend_can_merge &&
277             !dev->vhost_ops->vhost_backend_can_merge(dev, uaddr, size,
278                                                      reg->userspace_addr,
279                                                      reg->memory_size)) {
280             continue;
281         }
282 
283         if (merged) {
284             --to;
285             assert(to >= 0);
286         } else {
287             merged = reg;
288         }
289         u = MIN(uaddr, reg->userspace_addr);
290         s = MIN(start_addr, reg->guest_phys_addr);
291         e = MAX(pmlast, prlast);
292         uaddr = merged->userspace_addr = u;
293         start_addr = merged->guest_phys_addr = s;
294         size = merged->memory_size = e - s + 1;
295         assert(merged->memory_size);
296     }
297 
298     if (!merged) {
299         struct vhost_memory_region *reg = dev->mem->regions + to;
300         memset(reg, 0, sizeof *reg);
301         reg->memory_size = size;
302         assert(reg->memory_size);
303         reg->guest_phys_addr = start_addr;
304         reg->userspace_addr = uaddr;
305         ++to;
306     }
307     assert(to <= dev->mem->nregions + 1);
308     dev->mem->nregions = to;
309 }
310 
311 static uint64_t vhost_get_log_size(struct vhost_dev *dev)
312 {
313     uint64_t log_size = 0;
314     int i;
315     for (i = 0; i < dev->mem->nregions; ++i) {
316         struct vhost_memory_region *reg = dev->mem->regions + i;
317         uint64_t last = range_get_last(reg->guest_phys_addr,
318                                        reg->memory_size);
319         log_size = MAX(log_size, last / VHOST_LOG_CHUNK + 1);
320     }
321     for (i = 0; i < dev->nvqs; ++i) {
322         struct vhost_virtqueue *vq = dev->vqs + i;
323         uint64_t last = vq->used_phys + vq->used_size - 1;
324         log_size = MAX(log_size, last / VHOST_LOG_CHUNK + 1);
325     }
326     return log_size;
327 }
328 
329 static struct vhost_log *vhost_log_alloc(uint64_t size, bool share)
330 {
331     struct vhost_log *log;
332     uint64_t logsize = size * sizeof(*(log->log));
333     int fd = -1;
334 
335     log = g_new0(struct vhost_log, 1);
336     if (share) {
337         log->log = qemu_memfd_alloc("vhost-log", logsize,
338                                     F_SEAL_GROW | F_SEAL_SHRINK | F_SEAL_SEAL,
339                                     &fd);
340         memset(log->log, 0, logsize);
341     } else {
342         log->log = g_malloc0(logsize);
343     }
344 
345     log->size = size;
346     log->refcnt = 1;
347     log->fd = fd;
348 
349     return log;
350 }
351 
352 static struct vhost_log *vhost_log_get(uint64_t size, bool share)
353 {
354     struct vhost_log *log = share ? vhost_log_shm : vhost_log;
355 
356     if (!log || log->size != size) {
357         log = vhost_log_alloc(size, share);
358         if (share) {
359             vhost_log_shm = log;
360         } else {
361             vhost_log = log;
362         }
363     } else {
364         ++log->refcnt;
365     }
366 
367     return log;
368 }
369 
370 static void vhost_log_put(struct vhost_dev *dev, bool sync)
371 {
372     struct vhost_log *log = dev->log;
373 
374     if (!log) {
375         return;
376     }
377     dev->log = NULL;
378     dev->log_size = 0;
379 
380     --log->refcnt;
381     if (log->refcnt == 0) {
382         /* Sync only the range covered by the old log */
383         if (dev->log_size && sync) {
384             vhost_log_sync_range(dev, 0, dev->log_size * VHOST_LOG_CHUNK - 1);
385         }
386 
387         if (vhost_log == log) {
388             g_free(log->log);
389             vhost_log = NULL;
390         } else if (vhost_log_shm == log) {
391             qemu_memfd_free(log->log, log->size * sizeof(*(log->log)),
392                             log->fd);
393             vhost_log_shm = NULL;
394         }
395 
396         g_free(log);
397     }
398 }
399 
400 static bool vhost_dev_log_is_shared(struct vhost_dev *dev)
401 {
402     return dev->vhost_ops->vhost_requires_shm_log &&
403            dev->vhost_ops->vhost_requires_shm_log(dev);
404 }
405 
406 static inline void vhost_dev_log_resize(struct vhost_dev *dev, uint64_t size)
407 {
408     struct vhost_log *log = vhost_log_get(size, vhost_dev_log_is_shared(dev));
409     uint64_t log_base = (uintptr_t)log->log;
410     int r;
411 
412     /* inform backend of log switching, this must be done before
413        releasing the current log, to ensure no logging is lost */
414     r = dev->vhost_ops->vhost_set_log_base(dev, log_base, log);
415     if (r < 0) {
416         VHOST_OPS_DEBUG("vhost_set_log_base failed");
417     }
418 
419     vhost_log_put(dev, true);
420     dev->log = log;
421     dev->log_size = size;
422 }
423 
424 static int vhost_verify_ring_mappings(struct vhost_dev *dev,
425                                       uint64_t start_addr,
426                                       uint64_t size)
427 {
428     int i;
429     int r = 0;
430 
431     for (i = 0; !r && i < dev->nvqs; ++i) {
432         struct vhost_virtqueue *vq = dev->vqs + i;
433         hwaddr l;
434         void *p;
435 
436         if (!ranges_overlap(start_addr, size, vq->ring_phys, vq->ring_size)) {
437             continue;
438         }
439         l = vq->ring_size;
440         p = cpu_physical_memory_map(vq->ring_phys, &l, 1);
441         if (!p || l != vq->ring_size) {
442             fprintf(stderr, "Unable to map ring buffer for ring %d\n", i);
443             r = -ENOMEM;
444         }
445         if (p != vq->ring) {
446             fprintf(stderr, "Ring buffer relocated for ring %d\n", i);
447             r = -EBUSY;
448         }
449         cpu_physical_memory_unmap(p, l, 0, 0);
450     }
451     return r;
452 }
453 
454 static struct vhost_memory_region *vhost_dev_find_reg(struct vhost_dev *dev,
455 						      uint64_t start_addr,
456 						      uint64_t size)
457 {
458     int i, n = dev->mem->nregions;
459     for (i = 0; i < n; ++i) {
460         struct vhost_memory_region *reg = dev->mem->regions + i;
461         if (ranges_overlap(reg->guest_phys_addr, reg->memory_size,
462                            start_addr, size)) {
463             return reg;
464         }
465     }
466     return NULL;
467 }
468 
469 static bool vhost_dev_cmp_memory(struct vhost_dev *dev,
470                                  uint64_t start_addr,
471                                  uint64_t size,
472                                  uint64_t uaddr)
473 {
474     struct vhost_memory_region *reg = vhost_dev_find_reg(dev, start_addr, size);
475     uint64_t reglast;
476     uint64_t memlast;
477 
478     if (!reg) {
479         return true;
480     }
481 
482     reglast = range_get_last(reg->guest_phys_addr, reg->memory_size);
483     memlast = range_get_last(start_addr, size);
484 
485     /* Need to extend region? */
486     if (start_addr < reg->guest_phys_addr || memlast > reglast) {
487         return true;
488     }
489     /* userspace_addr changed? */
490     return uaddr != reg->userspace_addr + start_addr - reg->guest_phys_addr;
491 }
492 
493 static void vhost_set_memory(MemoryListener *listener,
494                              MemoryRegionSection *section,
495                              bool add)
496 {
497     struct vhost_dev *dev = container_of(listener, struct vhost_dev,
498                                          memory_listener);
499     hwaddr start_addr = section->offset_within_address_space;
500     ram_addr_t size = int128_get64(section->size);
501     bool log_dirty =
502         memory_region_get_dirty_log_mask(section->mr) & ~(1 << DIRTY_MEMORY_MIGRATION);
503     int s = offsetof(struct vhost_memory, regions) +
504         (dev->mem->nregions + 1) * sizeof dev->mem->regions[0];
505     void *ram;
506 
507     dev->mem = g_realloc(dev->mem, s);
508 
509     if (log_dirty) {
510         add = false;
511     }
512 
513     assert(size);
514 
515     /* Optimize no-change case. At least cirrus_vga does this a lot at this time. */
516     ram = memory_region_get_ram_ptr(section->mr) + section->offset_within_region;
517     if (add) {
518         if (!vhost_dev_cmp_memory(dev, start_addr, size, (uintptr_t)ram)) {
519             /* Region exists with same address. Nothing to do. */
520             return;
521         }
522     } else {
523         if (!vhost_dev_find_reg(dev, start_addr, size)) {
524             /* Removing region that we don't access. Nothing to do. */
525             return;
526         }
527     }
528 
529     vhost_dev_unassign_memory(dev, start_addr, size);
530     if (add) {
531         /* Add given mapping, merging adjacent regions if any */
532         vhost_dev_assign_memory(dev, start_addr, size, (uintptr_t)ram);
533     } else {
534         /* Remove old mapping for this memory, if any. */
535         vhost_dev_unassign_memory(dev, start_addr, size);
536     }
537     dev->mem_changed_start_addr = MIN(dev->mem_changed_start_addr, start_addr);
538     dev->mem_changed_end_addr = MAX(dev->mem_changed_end_addr, start_addr + size - 1);
539     dev->memory_changed = true;
540     used_memslots = dev->mem->nregions;
541 }
542 
543 static bool vhost_section(MemoryRegionSection *section)
544 {
545     return memory_region_is_ram(section->mr);
546 }
547 
548 static void vhost_begin(MemoryListener *listener)
549 {
550     struct vhost_dev *dev = container_of(listener, struct vhost_dev,
551                                          memory_listener);
552     dev->mem_changed_end_addr = 0;
553     dev->mem_changed_start_addr = -1;
554 }
555 
556 static void vhost_commit(MemoryListener *listener)
557 {
558     struct vhost_dev *dev = container_of(listener, struct vhost_dev,
559                                          memory_listener);
560     hwaddr start_addr = 0;
561     ram_addr_t size = 0;
562     uint64_t log_size;
563     int r;
564 
565     if (!dev->memory_changed) {
566         return;
567     }
568     if (!dev->started) {
569         return;
570     }
571     if (dev->mem_changed_start_addr > dev->mem_changed_end_addr) {
572         return;
573     }
574 
575     if (dev->started) {
576         start_addr = dev->mem_changed_start_addr;
577         size = dev->mem_changed_end_addr - dev->mem_changed_start_addr + 1;
578 
579         r = vhost_verify_ring_mappings(dev, start_addr, size);
580         assert(r >= 0);
581     }
582 
583     if (!dev->log_enabled) {
584         r = dev->vhost_ops->vhost_set_mem_table(dev, dev->mem);
585         if (r < 0) {
586             VHOST_OPS_DEBUG("vhost_set_mem_table failed");
587         }
588         dev->memory_changed = false;
589         return;
590     }
591     log_size = vhost_get_log_size(dev);
592     /* We allocate an extra 4K bytes to log,
593      * to reduce the * number of reallocations. */
594 #define VHOST_LOG_BUFFER (0x1000 / sizeof *dev->log)
595     /* To log more, must increase log size before table update. */
596     if (dev->log_size < log_size) {
597         vhost_dev_log_resize(dev, log_size + VHOST_LOG_BUFFER);
598     }
599     r = dev->vhost_ops->vhost_set_mem_table(dev, dev->mem);
600     if (r < 0) {
601         VHOST_OPS_DEBUG("vhost_set_mem_table failed");
602     }
603     /* To log less, can only decrease log size after table update. */
604     if (dev->log_size > log_size + VHOST_LOG_BUFFER) {
605         vhost_dev_log_resize(dev, log_size);
606     }
607     dev->memory_changed = false;
608 }
609 
610 static void vhost_region_add(MemoryListener *listener,
611                              MemoryRegionSection *section)
612 {
613     struct vhost_dev *dev = container_of(listener, struct vhost_dev,
614                                          memory_listener);
615 
616     if (!vhost_section(section)) {
617         return;
618     }
619 
620     ++dev->n_mem_sections;
621     dev->mem_sections = g_renew(MemoryRegionSection, dev->mem_sections,
622                                 dev->n_mem_sections);
623     dev->mem_sections[dev->n_mem_sections - 1] = *section;
624     memory_region_ref(section->mr);
625     vhost_set_memory(listener, section, true);
626 }
627 
628 static void vhost_region_del(MemoryListener *listener,
629                              MemoryRegionSection *section)
630 {
631     struct vhost_dev *dev = container_of(listener, struct vhost_dev,
632                                          memory_listener);
633     int i;
634 
635     if (!vhost_section(section)) {
636         return;
637     }
638 
639     vhost_set_memory(listener, section, false);
640     memory_region_unref(section->mr);
641     for (i = 0; i < dev->n_mem_sections; ++i) {
642         if (dev->mem_sections[i].offset_within_address_space
643             == section->offset_within_address_space) {
644             --dev->n_mem_sections;
645             memmove(&dev->mem_sections[i], &dev->mem_sections[i+1],
646                     (dev->n_mem_sections - i) * sizeof(*dev->mem_sections));
647             break;
648         }
649     }
650 }
651 
652 static void vhost_region_nop(MemoryListener *listener,
653                              MemoryRegionSection *section)
654 {
655 }
656 
657 static int vhost_virtqueue_set_addr(struct vhost_dev *dev,
658                                     struct vhost_virtqueue *vq,
659                                     unsigned idx, bool enable_log)
660 {
661     struct vhost_vring_addr addr = {
662         .index = idx,
663         .desc_user_addr = (uint64_t)(unsigned long)vq->desc,
664         .avail_user_addr = (uint64_t)(unsigned long)vq->avail,
665         .used_user_addr = (uint64_t)(unsigned long)vq->used,
666         .log_guest_addr = vq->used_phys,
667         .flags = enable_log ? (1 << VHOST_VRING_F_LOG) : 0,
668     };
669     int r = dev->vhost_ops->vhost_set_vring_addr(dev, &addr);
670     if (r < 0) {
671         return -errno;
672     }
673     return 0;
674 }
675 
676 static int vhost_dev_set_features(struct vhost_dev *dev, bool enable_log)
677 {
678     uint64_t features = dev->acked_features;
679     int r;
680     if (enable_log) {
681         features |= 0x1ULL << VHOST_F_LOG_ALL;
682     }
683     r = dev->vhost_ops->vhost_set_features(dev, features);
684     return r < 0 ? -errno : 0;
685 }
686 
687 static int vhost_dev_set_log(struct vhost_dev *dev, bool enable_log)
688 {
689     int r, i, idx;
690     r = vhost_dev_set_features(dev, enable_log);
691     if (r < 0) {
692         goto err_features;
693     }
694     for (i = 0; i < dev->nvqs; ++i) {
695         idx = dev->vhost_ops->vhost_get_vq_index(dev, dev->vq_index + i);
696         r = vhost_virtqueue_set_addr(dev, dev->vqs + i, idx,
697                                      enable_log);
698         if (r < 0) {
699             goto err_vq;
700         }
701     }
702     return 0;
703 err_vq:
704     for (; i >= 0; --i) {
705         idx = dev->vhost_ops->vhost_get_vq_index(dev, dev->vq_index + i);
706         vhost_virtqueue_set_addr(dev, dev->vqs + i, idx,
707                                  dev->log_enabled);
708     }
709     vhost_dev_set_features(dev, dev->log_enabled);
710 err_features:
711     return r;
712 }
713 
714 static int vhost_migration_log(MemoryListener *listener, int enable)
715 {
716     struct vhost_dev *dev = container_of(listener, struct vhost_dev,
717                                          memory_listener);
718     int r;
719     if (!!enable == dev->log_enabled) {
720         return 0;
721     }
722     if (!dev->started) {
723         dev->log_enabled = enable;
724         return 0;
725     }
726     if (!enable) {
727         r = vhost_dev_set_log(dev, false);
728         if (r < 0) {
729             return r;
730         }
731         vhost_log_put(dev, false);
732     } else {
733         vhost_dev_log_resize(dev, vhost_get_log_size(dev));
734         r = vhost_dev_set_log(dev, true);
735         if (r < 0) {
736             return r;
737         }
738     }
739     dev->log_enabled = enable;
740     return 0;
741 }
742 
743 static void vhost_log_global_start(MemoryListener *listener)
744 {
745     int r;
746 
747     r = vhost_migration_log(listener, true);
748     if (r < 0) {
749         abort();
750     }
751 }
752 
753 static void vhost_log_global_stop(MemoryListener *listener)
754 {
755     int r;
756 
757     r = vhost_migration_log(listener, false);
758     if (r < 0) {
759         abort();
760     }
761 }
762 
763 static void vhost_log_start(MemoryListener *listener,
764                             MemoryRegionSection *section,
765                             int old, int new)
766 {
767     /* FIXME: implement */
768 }
769 
770 static void vhost_log_stop(MemoryListener *listener,
771                            MemoryRegionSection *section,
772                            int old, int new)
773 {
774     /* FIXME: implement */
775 }
776 
777 /* The vhost driver natively knows how to handle the vrings of non
778  * cross-endian legacy devices and modern devices. Only legacy devices
779  * exposed to a bi-endian guest may require the vhost driver to use a
780  * specific endianness.
781  */
782 static inline bool vhost_needs_vring_endian(VirtIODevice *vdev)
783 {
784     if (virtio_vdev_has_feature(vdev, VIRTIO_F_VERSION_1)) {
785         return false;
786     }
787 #ifdef HOST_WORDS_BIGENDIAN
788     return vdev->device_endian == VIRTIO_DEVICE_ENDIAN_LITTLE;
789 #else
790     return vdev->device_endian == VIRTIO_DEVICE_ENDIAN_BIG;
791 #endif
792 }
793 
794 static int vhost_virtqueue_set_vring_endian_legacy(struct vhost_dev *dev,
795                                                    bool is_big_endian,
796                                                    int vhost_vq_index)
797 {
798     struct vhost_vring_state s = {
799         .index = vhost_vq_index,
800         .num = is_big_endian
801     };
802 
803     if (!dev->vhost_ops->vhost_set_vring_endian(dev, &s)) {
804         return 0;
805     }
806 
807     if (errno == ENOTTY) {
808         error_report("vhost does not support cross-endian");
809         return -ENOSYS;
810     }
811 
812     return -errno;
813 }
814 
815 static int vhost_virtqueue_start(struct vhost_dev *dev,
816                                 struct VirtIODevice *vdev,
817                                 struct vhost_virtqueue *vq,
818                                 unsigned idx)
819 {
820     hwaddr s, l, a;
821     int r;
822     int vhost_vq_index = dev->vhost_ops->vhost_get_vq_index(dev, idx);
823     struct vhost_vring_file file = {
824         .index = vhost_vq_index
825     };
826     struct vhost_vring_state state = {
827         .index = vhost_vq_index
828     };
829     struct VirtQueue *vvq = virtio_get_queue(vdev, idx);
830 
831 
832     vq->num = state.num = virtio_queue_get_num(vdev, idx);
833     r = dev->vhost_ops->vhost_set_vring_num(dev, &state);
834     if (r) {
835         return -errno;
836     }
837 
838     state.num = virtio_queue_get_last_avail_idx(vdev, idx);
839     r = dev->vhost_ops->vhost_set_vring_base(dev, &state);
840     if (r) {
841         return -errno;
842     }
843 
844     if (vhost_needs_vring_endian(vdev)) {
845         r = vhost_virtqueue_set_vring_endian_legacy(dev,
846                                                     virtio_is_big_endian(vdev),
847                                                     vhost_vq_index);
848         if (r) {
849             return -errno;
850         }
851     }
852 
853     s = l = virtio_queue_get_desc_size(vdev, idx);
854     a = virtio_queue_get_desc_addr(vdev, idx);
855     vq->desc = cpu_physical_memory_map(a, &l, 0);
856     if (!vq->desc || l != s) {
857         r = -ENOMEM;
858         goto fail_alloc_desc;
859     }
860     s = l = virtio_queue_get_avail_size(vdev, idx);
861     a = virtio_queue_get_avail_addr(vdev, idx);
862     vq->avail = cpu_physical_memory_map(a, &l, 0);
863     if (!vq->avail || l != s) {
864         r = -ENOMEM;
865         goto fail_alloc_avail;
866     }
867     vq->used_size = s = l = virtio_queue_get_used_size(vdev, idx);
868     vq->used_phys = a = virtio_queue_get_used_addr(vdev, idx);
869     vq->used = cpu_physical_memory_map(a, &l, 1);
870     if (!vq->used || l != s) {
871         r = -ENOMEM;
872         goto fail_alloc_used;
873     }
874 
875     vq->ring_size = s = l = virtio_queue_get_ring_size(vdev, idx);
876     vq->ring_phys = a = virtio_queue_get_ring_addr(vdev, idx);
877     vq->ring = cpu_physical_memory_map(a, &l, 1);
878     if (!vq->ring || l != s) {
879         r = -ENOMEM;
880         goto fail_alloc_ring;
881     }
882 
883     r = vhost_virtqueue_set_addr(dev, vq, vhost_vq_index, dev->log_enabled);
884     if (r < 0) {
885         r = -errno;
886         goto fail_alloc;
887     }
888 
889     file.fd = event_notifier_get_fd(virtio_queue_get_host_notifier(vvq));
890     r = dev->vhost_ops->vhost_set_vring_kick(dev, &file);
891     if (r) {
892         r = -errno;
893         goto fail_kick;
894     }
895 
896     /* Clear and discard previous events if any. */
897     event_notifier_test_and_clear(&vq->masked_notifier);
898 
899     /* Init vring in unmasked state, unless guest_notifier_mask
900      * will do it later.
901      */
902     if (!vdev->use_guest_notifier_mask) {
903         /* TODO: check and handle errors. */
904         vhost_virtqueue_mask(dev, vdev, idx, false);
905     }
906 
907     return 0;
908 
909 fail_kick:
910 fail_alloc:
911     cpu_physical_memory_unmap(vq->ring, virtio_queue_get_ring_size(vdev, idx),
912                               0, 0);
913 fail_alloc_ring:
914     cpu_physical_memory_unmap(vq->used, virtio_queue_get_used_size(vdev, idx),
915                               0, 0);
916 fail_alloc_used:
917     cpu_physical_memory_unmap(vq->avail, virtio_queue_get_avail_size(vdev, idx),
918                               0, 0);
919 fail_alloc_avail:
920     cpu_physical_memory_unmap(vq->desc, virtio_queue_get_desc_size(vdev, idx),
921                               0, 0);
922 fail_alloc_desc:
923     return r;
924 }
925 
926 static void vhost_virtqueue_stop(struct vhost_dev *dev,
927                                     struct VirtIODevice *vdev,
928                                     struct vhost_virtqueue *vq,
929                                     unsigned idx)
930 {
931     int vhost_vq_index = dev->vhost_ops->vhost_get_vq_index(dev, idx);
932     struct vhost_vring_state state = {
933         .index = vhost_vq_index,
934     };
935     int r;
936 
937     r = dev->vhost_ops->vhost_get_vring_base(dev, &state);
938     if (r < 0) {
939         fprintf(stderr, "vhost VQ %d ring restore failed: %d\n", idx, r);
940         fflush(stderr);
941     }
942     virtio_queue_set_last_avail_idx(vdev, idx, state.num);
943     virtio_queue_invalidate_signalled_used(vdev, idx);
944 
945     /* In the cross-endian case, we need to reset the vring endianness to
946      * native as legacy devices expect so by default.
947      */
948     if (vhost_needs_vring_endian(vdev)) {
949         vhost_virtqueue_set_vring_endian_legacy(dev,
950                                                 !virtio_is_big_endian(vdev),
951                                                 vhost_vq_index);
952     }
953 
954     cpu_physical_memory_unmap(vq->ring, virtio_queue_get_ring_size(vdev, idx),
955                               0, virtio_queue_get_ring_size(vdev, idx));
956     cpu_physical_memory_unmap(vq->used, virtio_queue_get_used_size(vdev, idx),
957                               1, virtio_queue_get_used_size(vdev, idx));
958     cpu_physical_memory_unmap(vq->avail, virtio_queue_get_avail_size(vdev, idx),
959                               0, virtio_queue_get_avail_size(vdev, idx));
960     cpu_physical_memory_unmap(vq->desc, virtio_queue_get_desc_size(vdev, idx),
961                               0, virtio_queue_get_desc_size(vdev, idx));
962 }
963 
964 static void vhost_eventfd_add(MemoryListener *listener,
965                               MemoryRegionSection *section,
966                               bool match_data, uint64_t data, EventNotifier *e)
967 {
968 }
969 
970 static void vhost_eventfd_del(MemoryListener *listener,
971                               MemoryRegionSection *section,
972                               bool match_data, uint64_t data, EventNotifier *e)
973 {
974 }
975 
976 static int vhost_virtqueue_set_busyloop_timeout(struct vhost_dev *dev,
977                                                 int n, uint32_t timeout)
978 {
979     int vhost_vq_index = dev->vhost_ops->vhost_get_vq_index(dev, n);
980     struct vhost_vring_state state = {
981         .index = vhost_vq_index,
982         .num = timeout,
983     };
984     int r;
985 
986     if (!dev->vhost_ops->vhost_set_vring_busyloop_timeout) {
987         return -EINVAL;
988     }
989 
990     r = dev->vhost_ops->vhost_set_vring_busyloop_timeout(dev, &state);
991     if (r) {
992         return r;
993     }
994 
995     return 0;
996 }
997 
998 static int vhost_virtqueue_init(struct vhost_dev *dev,
999                                 struct vhost_virtqueue *vq, int n)
1000 {
1001     int vhost_vq_index = dev->vhost_ops->vhost_get_vq_index(dev, n);
1002     struct vhost_vring_file file = {
1003         .index = vhost_vq_index,
1004     };
1005     int r = event_notifier_init(&vq->masked_notifier, 0);
1006     if (r < 0) {
1007         return r;
1008     }
1009 
1010     file.fd = event_notifier_get_fd(&vq->masked_notifier);
1011     r = dev->vhost_ops->vhost_set_vring_call(dev, &file);
1012     if (r) {
1013         r = -errno;
1014         goto fail_call;
1015     }
1016     return 0;
1017 fail_call:
1018     event_notifier_cleanup(&vq->masked_notifier);
1019     return r;
1020 }
1021 
1022 static void vhost_virtqueue_cleanup(struct vhost_virtqueue *vq)
1023 {
1024     event_notifier_cleanup(&vq->masked_notifier);
1025 }
1026 
1027 int vhost_dev_init(struct vhost_dev *hdev, void *opaque,
1028                    VhostBackendType backend_type, uint32_t busyloop_timeout)
1029 {
1030     uint64_t features;
1031     int i, r, n_initialized_vqs = 0;
1032 
1033     hdev->migration_blocker = NULL;
1034 
1035     r = vhost_set_backend_type(hdev, backend_type);
1036     assert(r >= 0);
1037 
1038     r = hdev->vhost_ops->vhost_backend_init(hdev, opaque);
1039     if (r < 0) {
1040         goto fail;
1041     }
1042 
1043     if (used_memslots > hdev->vhost_ops->vhost_backend_memslots_limit(hdev)) {
1044         fprintf(stderr, "vhost backend memory slots limit is less"
1045                 " than current number of present memory slots\n");
1046         r = -1;
1047         goto fail;
1048     }
1049 
1050     r = hdev->vhost_ops->vhost_set_owner(hdev);
1051     if (r < 0) {
1052         goto fail;
1053     }
1054 
1055     r = hdev->vhost_ops->vhost_get_features(hdev, &features);
1056     if (r < 0) {
1057         goto fail;
1058     }
1059 
1060     for (i = 0; i < hdev->nvqs; ++i, ++n_initialized_vqs) {
1061         r = vhost_virtqueue_init(hdev, hdev->vqs + i, hdev->vq_index + i);
1062         if (r < 0) {
1063             goto fail;
1064         }
1065     }
1066 
1067     if (busyloop_timeout) {
1068         for (i = 0; i < hdev->nvqs; ++i) {
1069             r = vhost_virtqueue_set_busyloop_timeout(hdev, hdev->vq_index + i,
1070                                                      busyloop_timeout);
1071             if (r < 0) {
1072                 goto fail_busyloop;
1073             }
1074         }
1075     }
1076 
1077     hdev->features = features;
1078 
1079     hdev->memory_listener = (MemoryListener) {
1080         .begin = vhost_begin,
1081         .commit = vhost_commit,
1082         .region_add = vhost_region_add,
1083         .region_del = vhost_region_del,
1084         .region_nop = vhost_region_nop,
1085         .log_start = vhost_log_start,
1086         .log_stop = vhost_log_stop,
1087         .log_sync = vhost_log_sync,
1088         .log_global_start = vhost_log_global_start,
1089         .log_global_stop = vhost_log_global_stop,
1090         .eventfd_add = vhost_eventfd_add,
1091         .eventfd_del = vhost_eventfd_del,
1092         .priority = 10
1093     };
1094 
1095     if (hdev->migration_blocker == NULL) {
1096         if (!(hdev->features & (0x1ULL << VHOST_F_LOG_ALL))) {
1097             error_setg(&hdev->migration_blocker,
1098                        "Migration disabled: vhost lacks VHOST_F_LOG_ALL feature.");
1099         } else if (!qemu_memfd_check()) {
1100             error_setg(&hdev->migration_blocker,
1101                        "Migration disabled: failed to allocate shared memory");
1102         }
1103     }
1104 
1105     if (hdev->migration_blocker != NULL) {
1106         migrate_add_blocker(hdev->migration_blocker);
1107     }
1108 
1109     hdev->mem = g_malloc0(offsetof(struct vhost_memory, regions));
1110     hdev->n_mem_sections = 0;
1111     hdev->mem_sections = NULL;
1112     hdev->log = NULL;
1113     hdev->log_size = 0;
1114     hdev->log_enabled = false;
1115     hdev->started = false;
1116     hdev->memory_changed = false;
1117     memory_listener_register(&hdev->memory_listener, &address_space_memory);
1118     QLIST_INSERT_HEAD(&vhost_devices, hdev, entry);
1119     return 0;
1120 
1121 fail_busyloop:
1122     while (--i >= 0) {
1123         vhost_virtqueue_set_busyloop_timeout(hdev, hdev->vq_index + i, 0);
1124     }
1125 fail:
1126     hdev->nvqs = n_initialized_vqs;
1127     vhost_dev_cleanup(hdev);
1128     return r;
1129 }
1130 
1131 void vhost_dev_cleanup(struct vhost_dev *hdev)
1132 {
1133     int i;
1134 
1135     for (i = 0; i < hdev->nvqs; ++i) {
1136         vhost_virtqueue_cleanup(hdev->vqs + i);
1137     }
1138     if (hdev->mem) {
1139         /* those are only safe after successful init */
1140         memory_listener_unregister(&hdev->memory_listener);
1141         QLIST_REMOVE(hdev, entry);
1142     }
1143     if (hdev->migration_blocker) {
1144         migrate_del_blocker(hdev->migration_blocker);
1145         error_free(hdev->migration_blocker);
1146     }
1147     g_free(hdev->mem);
1148     g_free(hdev->mem_sections);
1149     if (hdev->vhost_ops) {
1150         hdev->vhost_ops->vhost_backend_cleanup(hdev);
1151     }
1152     assert(!hdev->log);
1153 
1154     memset(hdev, 0, sizeof(struct vhost_dev));
1155 }
1156 
1157 /* Stop processing guest IO notifications in qemu.
1158  * Start processing them in vhost in kernel.
1159  */
1160 int vhost_dev_enable_notifiers(struct vhost_dev *hdev, VirtIODevice *vdev)
1161 {
1162     BusState *qbus = BUS(qdev_get_parent_bus(DEVICE(vdev)));
1163     VirtioBusState *vbus = VIRTIO_BUS(qbus);
1164     VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(vbus);
1165     int i, r, e;
1166     if (!k->ioeventfd_started) {
1167         fprintf(stderr, "binding does not support host notifiers\n");
1168         r = -ENOSYS;
1169         goto fail;
1170     }
1171 
1172     for (i = 0; i < hdev->nvqs; ++i) {
1173         r = virtio_bus_set_host_notifier(VIRTIO_BUS(qbus), hdev->vq_index + i,
1174                                          true);
1175         if (r < 0) {
1176             fprintf(stderr, "vhost VQ %d notifier binding failed: %d\n", i, -r);
1177             goto fail_vq;
1178         }
1179     }
1180 
1181     return 0;
1182 fail_vq:
1183     while (--i >= 0) {
1184         e = virtio_bus_set_host_notifier(VIRTIO_BUS(qbus), hdev->vq_index + i,
1185                                          false);
1186         if (e < 0) {
1187             fprintf(stderr, "vhost VQ %d notifier cleanup error: %d\n", i, -r);
1188             fflush(stderr);
1189         }
1190         assert (e >= 0);
1191     }
1192 fail:
1193     return r;
1194 }
1195 
1196 /* Stop processing guest IO notifications in vhost.
1197  * Start processing them in qemu.
1198  * This might actually run the qemu handlers right away,
1199  * so virtio in qemu must be completely setup when this is called.
1200  */
1201 void vhost_dev_disable_notifiers(struct vhost_dev *hdev, VirtIODevice *vdev)
1202 {
1203     BusState *qbus = BUS(qdev_get_parent_bus(DEVICE(vdev)));
1204     int i, r;
1205 
1206     for (i = 0; i < hdev->nvqs; ++i) {
1207         r = virtio_bus_set_host_notifier(VIRTIO_BUS(qbus), hdev->vq_index + i,
1208                                          false);
1209         if (r < 0) {
1210             fprintf(stderr, "vhost VQ %d notifier cleanup failed: %d\n", i, -r);
1211             fflush(stderr);
1212         }
1213         assert (r >= 0);
1214     }
1215 }
1216 
1217 /* Test and clear event pending status.
1218  * Should be called after unmask to avoid losing events.
1219  */
1220 bool vhost_virtqueue_pending(struct vhost_dev *hdev, int n)
1221 {
1222     struct vhost_virtqueue *vq = hdev->vqs + n - hdev->vq_index;
1223     assert(n >= hdev->vq_index && n < hdev->vq_index + hdev->nvqs);
1224     return event_notifier_test_and_clear(&vq->masked_notifier);
1225 }
1226 
1227 /* Mask/unmask events from this vq. */
1228 void vhost_virtqueue_mask(struct vhost_dev *hdev, VirtIODevice *vdev, int n,
1229                          bool mask)
1230 {
1231     struct VirtQueue *vvq = virtio_get_queue(vdev, n);
1232     int r, index = n - hdev->vq_index;
1233     struct vhost_vring_file file;
1234 
1235     if (mask) {
1236         assert(vdev->use_guest_notifier_mask);
1237         file.fd = event_notifier_get_fd(&hdev->vqs[index].masked_notifier);
1238     } else {
1239         file.fd = event_notifier_get_fd(virtio_queue_get_guest_notifier(vvq));
1240     }
1241 
1242     file.index = hdev->vhost_ops->vhost_get_vq_index(hdev, n);
1243     r = hdev->vhost_ops->vhost_set_vring_call(hdev, &file);
1244     if (r < 0) {
1245         VHOST_OPS_DEBUG("vhost_set_vring_call failed");
1246     }
1247 }
1248 
1249 uint64_t vhost_get_features(struct vhost_dev *hdev, const int *feature_bits,
1250                             uint64_t features)
1251 {
1252     const int *bit = feature_bits;
1253     while (*bit != VHOST_INVALID_FEATURE_BIT) {
1254         uint64_t bit_mask = (1ULL << *bit);
1255         if (!(hdev->features & bit_mask)) {
1256             features &= ~bit_mask;
1257         }
1258         bit++;
1259     }
1260     return features;
1261 }
1262 
1263 void vhost_ack_features(struct vhost_dev *hdev, const int *feature_bits,
1264                         uint64_t features)
1265 {
1266     const int *bit = feature_bits;
1267     while (*bit != VHOST_INVALID_FEATURE_BIT) {
1268         uint64_t bit_mask = (1ULL << *bit);
1269         if (features & bit_mask) {
1270             hdev->acked_features |= bit_mask;
1271         }
1272         bit++;
1273     }
1274 }
1275 
1276 /* Host notifiers must be enabled at this point. */
1277 int vhost_dev_start(struct vhost_dev *hdev, VirtIODevice *vdev)
1278 {
1279     int i, r;
1280 
1281     hdev->started = true;
1282 
1283     r = vhost_dev_set_features(hdev, hdev->log_enabled);
1284     if (r < 0) {
1285         goto fail_features;
1286     }
1287     r = hdev->vhost_ops->vhost_set_mem_table(hdev, hdev->mem);
1288     if (r < 0) {
1289         r = -errno;
1290         goto fail_mem;
1291     }
1292     for (i = 0; i < hdev->nvqs; ++i) {
1293         r = vhost_virtqueue_start(hdev,
1294                                   vdev,
1295                                   hdev->vqs + i,
1296                                   hdev->vq_index + i);
1297         if (r < 0) {
1298             goto fail_vq;
1299         }
1300     }
1301 
1302     if (hdev->log_enabled) {
1303         uint64_t log_base;
1304 
1305         hdev->log_size = vhost_get_log_size(hdev);
1306         hdev->log = vhost_log_get(hdev->log_size,
1307                                   vhost_dev_log_is_shared(hdev));
1308         log_base = (uintptr_t)hdev->log->log;
1309         r = hdev->vhost_ops->vhost_set_log_base(hdev,
1310                                                 hdev->log_size ? log_base : 0,
1311                                                 hdev->log);
1312         if (r < 0) {
1313             r = -errno;
1314             goto fail_log;
1315         }
1316     }
1317 
1318     return 0;
1319 fail_log:
1320     vhost_log_put(hdev, false);
1321 fail_vq:
1322     while (--i >= 0) {
1323         vhost_virtqueue_stop(hdev,
1324                              vdev,
1325                              hdev->vqs + i,
1326                              hdev->vq_index + i);
1327     }
1328     i = hdev->nvqs;
1329 fail_mem:
1330 fail_features:
1331 
1332     hdev->started = false;
1333     return r;
1334 }
1335 
1336 /* Host notifiers must be enabled at this point. */
1337 void vhost_dev_stop(struct vhost_dev *hdev, VirtIODevice *vdev)
1338 {
1339     int i;
1340 
1341     for (i = 0; i < hdev->nvqs; ++i) {
1342         vhost_virtqueue_stop(hdev,
1343                              vdev,
1344                              hdev->vqs + i,
1345                              hdev->vq_index + i);
1346     }
1347 
1348     vhost_log_put(hdev, true);
1349     hdev->started = false;
1350 }
1351