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