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