xref: /openbmc/qemu/hw/misc/ivshmem.c (revision 84a3a53c)
1 /*
2  * Inter-VM Shared Memory PCI device.
3  *
4  * Author:
5  *      Cam Macdonell <cam@cs.ualberta.ca>
6  *
7  * Based On: cirrus_vga.c
8  *          Copyright (c) 2004 Fabrice Bellard
9  *          Copyright (c) 2004 Makoto Suzuki (suzu)
10  *
11  *      and rtl8139.c
12  *          Copyright (c) 2006 Igor Kovalenko
13  *
14  * This code is licensed under the GNU GPL v2.
15  *
16  * Contributions after 2012-01-13 are licensed under the terms of the
17  * GNU GPL, version 2 or (at your option) any later version.
18  */
19 #include "hw/hw.h"
20 #include "hw/i386/pc.h"
21 #include "hw/pci/pci.h"
22 #include "hw/pci/msi.h"
23 #include "hw/pci/msix.h"
24 #include "sysemu/kvm.h"
25 #include "migration/migration.h"
26 #include "qemu/error-report.h"
27 #include "qemu/event_notifier.h"
28 #include "qemu/fifo8.h"
29 #include "sysemu/char.h"
30 #include "sysemu/hostmem.h"
31 #include "qapi/visitor.h"
32 #include "exec/ram_addr.h"
33 
34 #include "hw/misc/ivshmem.h"
35 
36 #include <sys/mman.h>
37 #include <sys/types.h>
38 #include <limits.h>
39 
40 #define PCI_VENDOR_ID_IVSHMEM   PCI_VENDOR_ID_REDHAT_QUMRANET
41 #define PCI_DEVICE_ID_IVSHMEM   0x1110
42 
43 #define IVSHMEM_MAX_PEERS G_MAXUINT16
44 #define IVSHMEM_IOEVENTFD   0
45 #define IVSHMEM_MSI     1
46 
47 #define IVSHMEM_PEER    0
48 #define IVSHMEM_MASTER  1
49 
50 #define IVSHMEM_REG_BAR_SIZE 0x100
51 
52 //#define DEBUG_IVSHMEM
53 #ifdef DEBUG_IVSHMEM
54 #define IVSHMEM_DPRINTF(fmt, ...)        \
55     do {printf("IVSHMEM: " fmt, ## __VA_ARGS__); } while (0)
56 #else
57 #define IVSHMEM_DPRINTF(fmt, ...)
58 #endif
59 
60 #define TYPE_IVSHMEM "ivshmem"
61 #define IVSHMEM(obj) \
62     OBJECT_CHECK(IVShmemState, (obj), TYPE_IVSHMEM)
63 
64 typedef struct Peer {
65     int nb_eventfds;
66     EventNotifier *eventfds;
67 } Peer;
68 
69 typedef struct MSIVector {
70     PCIDevice *pdev;
71     int virq;
72 } MSIVector;
73 
74 typedef struct IVShmemState {
75     /*< private >*/
76     PCIDevice parent_obj;
77     /*< public >*/
78 
79     HostMemoryBackend *hostmem;
80     uint32_t intrmask;
81     uint32_t intrstatus;
82 
83     CharDriverState **eventfd_chr;
84     CharDriverState *server_chr;
85     Fifo8 incoming_fifo;
86     MemoryRegion ivshmem_mmio;
87 
88     /* We might need to register the BAR before we actually have the memory.
89      * So prepare a container MemoryRegion for the BAR immediately and
90      * add a subregion when we have the memory.
91      */
92     MemoryRegion bar;
93     MemoryRegion ivshmem;
94     uint64_t ivshmem_size; /* size of shared memory region */
95     uint32_t ivshmem_64bit;
96 
97     Peer *peers;
98     int nb_peers; /* how many peers we have space for */
99 
100     int vm_id;
101     uint32_t vectors;
102     uint32_t features;
103     MSIVector *msi_vectors;
104 
105     Error *migration_blocker;
106 
107     char * shmobj;
108     char * sizearg;
109     char * role;
110     int role_val;   /* scalar to avoid multiple string comparisons */
111 } IVShmemState;
112 
113 /* registers for the Inter-VM shared memory device */
114 enum ivshmem_registers {
115     INTRMASK = 0,
116     INTRSTATUS = 4,
117     IVPOSITION = 8,
118     DOORBELL = 12,
119 };
120 
121 static inline uint32_t ivshmem_has_feature(IVShmemState *ivs,
122                                                     unsigned int feature) {
123     return (ivs->features & (1 << feature));
124 }
125 
126 /* accessing registers - based on rtl8139 */
127 static void ivshmem_update_irq(IVShmemState *s)
128 {
129     PCIDevice *d = PCI_DEVICE(s);
130     int isr;
131     isr = (s->intrstatus & s->intrmask) & 0xffffffff;
132 
133     /* don't print ISR resets */
134     if (isr) {
135         IVSHMEM_DPRINTF("Set IRQ to %d (%04x %04x)\n",
136                         isr ? 1 : 0, s->intrstatus, s->intrmask);
137     }
138 
139     pci_set_irq(d, (isr != 0));
140 }
141 
142 static void ivshmem_IntrMask_write(IVShmemState *s, uint32_t val)
143 {
144     IVSHMEM_DPRINTF("IntrMask write(w) val = 0x%04x\n", val);
145 
146     s->intrmask = val;
147 
148     ivshmem_update_irq(s);
149 }
150 
151 static uint32_t ivshmem_IntrMask_read(IVShmemState *s)
152 {
153     uint32_t ret = s->intrmask;
154 
155     IVSHMEM_DPRINTF("intrmask read(w) val = 0x%04x\n", ret);
156 
157     return ret;
158 }
159 
160 static void ivshmem_IntrStatus_write(IVShmemState *s, uint32_t val)
161 {
162     IVSHMEM_DPRINTF("IntrStatus write(w) val = 0x%04x\n", val);
163 
164     s->intrstatus = val;
165 
166     ivshmem_update_irq(s);
167 }
168 
169 static uint32_t ivshmem_IntrStatus_read(IVShmemState *s)
170 {
171     uint32_t ret = s->intrstatus;
172 
173     /* reading ISR clears all interrupts */
174     s->intrstatus = 0;
175 
176     ivshmem_update_irq(s);
177 
178     return ret;
179 }
180 
181 static void ivshmem_io_write(void *opaque, hwaddr addr,
182                              uint64_t val, unsigned size)
183 {
184     IVShmemState *s = opaque;
185 
186     uint16_t dest = val >> 16;
187     uint16_t vector = val & 0xff;
188 
189     addr &= 0xfc;
190 
191     IVSHMEM_DPRINTF("writing to addr " TARGET_FMT_plx "\n", addr);
192     switch (addr)
193     {
194         case INTRMASK:
195             ivshmem_IntrMask_write(s, val);
196             break;
197 
198         case INTRSTATUS:
199             ivshmem_IntrStatus_write(s, val);
200             break;
201 
202         case DOORBELL:
203             /* check that dest VM ID is reasonable */
204             if (dest >= s->nb_peers) {
205                 IVSHMEM_DPRINTF("Invalid destination VM ID (%d)\n", dest);
206                 break;
207             }
208 
209             /* check doorbell range */
210             if (vector < s->peers[dest].nb_eventfds) {
211                 IVSHMEM_DPRINTF("Notifying VM %d on vector %d\n", dest, vector);
212                 event_notifier_set(&s->peers[dest].eventfds[vector]);
213             } else {
214                 IVSHMEM_DPRINTF("Invalid destination vector %d on VM %d\n",
215                                 vector, dest);
216             }
217             break;
218         default:
219             IVSHMEM_DPRINTF("Unhandled write " TARGET_FMT_plx "\n", addr);
220     }
221 }
222 
223 static uint64_t ivshmem_io_read(void *opaque, hwaddr addr,
224                                 unsigned size)
225 {
226 
227     IVShmemState *s = opaque;
228     uint32_t ret;
229 
230     switch (addr)
231     {
232         case INTRMASK:
233             ret = ivshmem_IntrMask_read(s);
234             break;
235 
236         case INTRSTATUS:
237             ret = ivshmem_IntrStatus_read(s);
238             break;
239 
240         case IVPOSITION:
241             /* return my VM ID if the memory is mapped */
242             if (memory_region_is_mapped(&s->ivshmem)) {
243                 ret = s->vm_id;
244             } else {
245                 ret = -1;
246             }
247             break;
248 
249         default:
250             IVSHMEM_DPRINTF("why are we reading " TARGET_FMT_plx "\n", addr);
251             ret = 0;
252     }
253 
254     return ret;
255 }
256 
257 static const MemoryRegionOps ivshmem_mmio_ops = {
258     .read = ivshmem_io_read,
259     .write = ivshmem_io_write,
260     .endianness = DEVICE_NATIVE_ENDIAN,
261     .impl = {
262         .min_access_size = 4,
263         .max_access_size = 4,
264     },
265 };
266 
267 static void ivshmem_receive(void *opaque, const uint8_t *buf, int size)
268 {
269     IVShmemState *s = opaque;
270 
271     IVSHMEM_DPRINTF("ivshmem_receive 0x%02x size: %d\n", *buf, size);
272 
273     ivshmem_IntrStatus_write(s, *buf);
274 }
275 
276 static int ivshmem_can_receive(void * opaque)
277 {
278     return sizeof(int64_t);
279 }
280 
281 static void ivshmem_event(void *opaque, int event)
282 {
283     IVSHMEM_DPRINTF("ivshmem_event %d\n", event);
284 }
285 
286 static void fake_irqfd(void *opaque, const uint8_t *buf, int size) {
287 
288     MSIVector *entry = opaque;
289     PCIDevice *pdev = entry->pdev;
290     IVShmemState *s = IVSHMEM(pdev);
291     int vector = entry - s->msi_vectors;
292 
293     IVSHMEM_DPRINTF("interrupt on vector %p %d\n", pdev, vector);
294     msix_notify(pdev, vector);
295 }
296 
297 static int ivshmem_vector_unmask(PCIDevice *dev, unsigned vector,
298                                  MSIMessage msg)
299 {
300     IVShmemState *s = IVSHMEM(dev);
301     EventNotifier *n = &s->peers[s->vm_id].eventfds[vector];
302     MSIVector *v = &s->msi_vectors[vector];
303     int ret;
304 
305     IVSHMEM_DPRINTF("vector unmask %p %d\n", dev, vector);
306 
307     ret = kvm_irqchip_update_msi_route(kvm_state, v->virq, msg, dev);
308     if (ret < 0) {
309         return ret;
310     }
311 
312     return kvm_irqchip_add_irqfd_notifier_gsi(kvm_state, n, NULL, v->virq);
313 }
314 
315 static void ivshmem_vector_mask(PCIDevice *dev, unsigned vector)
316 {
317     IVShmemState *s = IVSHMEM(dev);
318     EventNotifier *n = &s->peers[s->vm_id].eventfds[vector];
319     int ret;
320 
321     IVSHMEM_DPRINTF("vector mask %p %d\n", dev, vector);
322 
323     ret = kvm_irqchip_remove_irqfd_notifier_gsi(kvm_state, n,
324                                                 s->msi_vectors[vector].virq);
325     if (ret != 0) {
326         error_report("remove_irqfd_notifier_gsi failed");
327     }
328 }
329 
330 static void ivshmem_vector_poll(PCIDevice *dev,
331                                 unsigned int vector_start,
332                                 unsigned int vector_end)
333 {
334     IVShmemState *s = IVSHMEM(dev);
335     unsigned int vector;
336 
337     IVSHMEM_DPRINTF("vector poll %p %d-%d\n", dev, vector_start, vector_end);
338 
339     vector_end = MIN(vector_end, s->vectors);
340 
341     for (vector = vector_start; vector < vector_end; vector++) {
342         EventNotifier *notifier = &s->peers[s->vm_id].eventfds[vector];
343 
344         if (!msix_is_masked(dev, vector)) {
345             continue;
346         }
347 
348         if (event_notifier_test_and_clear(notifier)) {
349             msix_set_pending(dev, vector);
350         }
351     }
352 }
353 
354 static CharDriverState* create_eventfd_chr_device(void * opaque, EventNotifier *n,
355                                                   int vector)
356 {
357     /* create a event character device based on the passed eventfd */
358     IVShmemState *s = opaque;
359     PCIDevice *pdev = PCI_DEVICE(s);
360     int eventfd = event_notifier_get_fd(n);
361     CharDriverState *chr;
362 
363     s->msi_vectors[vector].pdev = pdev;
364 
365     chr = qemu_chr_open_eventfd(eventfd);
366 
367     if (chr == NULL) {
368         error_report("creating chardriver for eventfd %d failed", eventfd);
369         return NULL;
370     }
371     qemu_chr_fe_claim_no_fail(chr);
372 
373     /* if MSI is supported we need multiple interrupts */
374     if (ivshmem_has_feature(s, IVSHMEM_MSI)) {
375         s->msi_vectors[vector].pdev = PCI_DEVICE(s);
376 
377         qemu_chr_add_handlers(chr, ivshmem_can_receive, fake_irqfd,
378                       ivshmem_event, &s->msi_vectors[vector]);
379     } else {
380         qemu_chr_add_handlers(chr, ivshmem_can_receive, ivshmem_receive,
381                       ivshmem_event, s);
382     }
383 
384     return chr;
385 
386 }
387 
388 static int check_shm_size(IVShmemState *s, int fd, Error **errp)
389 {
390     /* check that the guest isn't going to try and map more memory than the
391      * the object has allocated return -1 to indicate error */
392 
393     struct stat buf;
394 
395     if (fstat(fd, &buf) < 0) {
396         error_setg(errp, "exiting: fstat on fd %d failed: %s",
397                    fd, strerror(errno));
398         return -1;
399     }
400 
401     if (s->ivshmem_size > buf.st_size) {
402         error_setg(errp, "Requested memory size greater"
403                    " than shared object size (%" PRIu64 " > %" PRIu64")",
404                    s->ivshmem_size, (uint64_t)buf.st_size);
405         return -1;
406     } else {
407         return 0;
408     }
409 }
410 
411 /* create the shared memory BAR when we are not using the server, so we can
412  * create the BAR and map the memory immediately */
413 static int create_shared_memory_BAR(IVShmemState *s, int fd, uint8_t attr,
414                                     Error **errp)
415 {
416     void * ptr;
417 
418     ptr = mmap(0, s->ivshmem_size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
419     if (ptr == MAP_FAILED) {
420         error_setg_errno(errp, errno, "Failed to mmap shared memory");
421         return -1;
422     }
423 
424     memory_region_init_ram_ptr(&s->ivshmem, OBJECT(s), "ivshmem.bar2",
425                                s->ivshmem_size, ptr);
426     qemu_set_ram_fd(s->ivshmem.ram_addr, fd);
427     vmstate_register_ram(&s->ivshmem, DEVICE(s));
428     memory_region_add_subregion(&s->bar, 0, &s->ivshmem);
429 
430     /* region for shared memory */
431     pci_register_bar(PCI_DEVICE(s), 2, attr, &s->bar);
432 
433     return 0;
434 }
435 
436 static void ivshmem_add_eventfd(IVShmemState *s, int posn, int i)
437 {
438     memory_region_add_eventfd(&s->ivshmem_mmio,
439                               DOORBELL,
440                               4,
441                               true,
442                               (posn << 16) | i,
443                               &s->peers[posn].eventfds[i]);
444 }
445 
446 static void ivshmem_del_eventfd(IVShmemState *s, int posn, int i)
447 {
448     memory_region_del_eventfd(&s->ivshmem_mmio,
449                               DOORBELL,
450                               4,
451                               true,
452                               (posn << 16) | i,
453                               &s->peers[posn].eventfds[i]);
454 }
455 
456 static void close_peer_eventfds(IVShmemState *s, int posn)
457 {
458     int i, n;
459 
460     if (!ivshmem_has_feature(s, IVSHMEM_IOEVENTFD)) {
461         return;
462     }
463     if (posn < 0 || posn >= s->nb_peers) {
464         error_report("invalid peer %d", posn);
465         return;
466     }
467 
468     n = s->peers[posn].nb_eventfds;
469 
470     memory_region_transaction_begin();
471     for (i = 0; i < n; i++) {
472         ivshmem_del_eventfd(s, posn, i);
473     }
474     memory_region_transaction_commit();
475     for (i = 0; i < n; i++) {
476         event_notifier_cleanup(&s->peers[posn].eventfds[i]);
477     }
478 
479     g_free(s->peers[posn].eventfds);
480     s->peers[posn].nb_eventfds = 0;
481 }
482 
483 /* this function increase the dynamic storage need to store data about other
484  * peers */
485 static int resize_peers(IVShmemState *s, int new_min_size)
486 {
487 
488     int j, old_size;
489 
490     /* limit number of max peers */
491     if (new_min_size <= 0 || new_min_size > IVSHMEM_MAX_PEERS) {
492         return -1;
493     }
494     if (new_min_size <= s->nb_peers) {
495         return 0;
496     }
497 
498     old_size = s->nb_peers;
499     s->nb_peers = new_min_size;
500 
501     IVSHMEM_DPRINTF("bumping storage to %d peers\n", s->nb_peers);
502 
503     s->peers = g_realloc(s->peers, s->nb_peers * sizeof(Peer));
504 
505     for (j = old_size; j < s->nb_peers; j++) {
506         s->peers[j].eventfds = g_new0(EventNotifier, s->vectors);
507         s->peers[j].nb_eventfds = 0;
508     }
509 
510     return 0;
511 }
512 
513 static bool fifo_update_and_get(IVShmemState *s, const uint8_t *buf, int size,
514                                 void *data, size_t len)
515 {
516     const uint8_t *p;
517     uint32_t num;
518 
519     assert(len <= sizeof(int64_t)); /* limitation of the fifo */
520     if (fifo8_is_empty(&s->incoming_fifo) && size == len) {
521         memcpy(data, buf, size);
522         return true;
523     }
524 
525     IVSHMEM_DPRINTF("short read of %d bytes\n", size);
526 
527     num = MIN(size, sizeof(int64_t) - fifo8_num_used(&s->incoming_fifo));
528     fifo8_push_all(&s->incoming_fifo, buf, num);
529 
530     if (fifo8_num_used(&s->incoming_fifo) < len) {
531         assert(num == 0);
532         return false;
533     }
534 
535     size -= num;
536     buf += num;
537     p = fifo8_pop_buf(&s->incoming_fifo, len, &num);
538     assert(num == len);
539 
540     memcpy(data, p, len);
541 
542     if (size > 0) {
543         fifo8_push_all(&s->incoming_fifo, buf, size);
544     }
545 
546     return true;
547 }
548 
549 static bool fifo_update_and_get_i64(IVShmemState *s,
550                                     const uint8_t *buf, int size, int64_t *i64)
551 {
552     if (fifo_update_and_get(s, buf, size, i64, sizeof(*i64))) {
553         *i64 = GINT64_FROM_LE(*i64);
554         return true;
555     }
556 
557     return false;
558 }
559 
560 static int ivshmem_add_kvm_msi_virq(IVShmemState *s, int vector)
561 {
562     PCIDevice *pdev = PCI_DEVICE(s);
563     MSIMessage msg = msix_get_message(pdev, vector);
564     int ret;
565 
566     IVSHMEM_DPRINTF("ivshmem_add_kvm_msi_virq vector:%d\n", vector);
567 
568     if (s->msi_vectors[vector].pdev != NULL) {
569         return 0;
570     }
571 
572     ret = kvm_irqchip_add_msi_route(kvm_state, msg, pdev);
573     if (ret < 0) {
574         error_report("ivshmem: kvm_irqchip_add_msi_route failed");
575         return -1;
576     }
577 
578     s->msi_vectors[vector].virq = ret;
579     s->msi_vectors[vector].pdev = pdev;
580 
581     return 0;
582 }
583 
584 static void setup_interrupt(IVShmemState *s, int vector)
585 {
586     EventNotifier *n = &s->peers[s->vm_id].eventfds[vector];
587     bool with_irqfd = kvm_msi_via_irqfd_enabled() &&
588         ivshmem_has_feature(s, IVSHMEM_MSI);
589     PCIDevice *pdev = PCI_DEVICE(s);
590 
591     IVSHMEM_DPRINTF("setting up interrupt for vector: %d\n", vector);
592 
593     if (!with_irqfd) {
594         IVSHMEM_DPRINTF("with eventfd");
595         s->eventfd_chr[vector] = create_eventfd_chr_device(s, n, vector);
596     } else if (msix_enabled(pdev)) {
597         IVSHMEM_DPRINTF("with irqfd");
598         if (ivshmem_add_kvm_msi_virq(s, vector) < 0) {
599             return;
600         }
601 
602         if (!msix_is_masked(pdev, vector)) {
603             kvm_irqchip_add_irqfd_notifier_gsi(kvm_state, n, NULL,
604                                                s->msi_vectors[vector].virq);
605         }
606     } else {
607         /* it will be delayed until msix is enabled, in write_config */
608         IVSHMEM_DPRINTF("with irqfd, delayed until msix enabled");
609     }
610 }
611 
612 static void ivshmem_read(void *opaque, const uint8_t *buf, int size)
613 {
614     IVShmemState *s = opaque;
615     int incoming_fd;
616     int new_eventfd;
617     int64_t incoming_posn;
618     Error *err = NULL;
619     Peer *peer;
620 
621     if (!fifo_update_and_get_i64(s, buf, size, &incoming_posn)) {
622         return;
623     }
624 
625     if (incoming_posn < -1) {
626         IVSHMEM_DPRINTF("invalid incoming_posn %" PRId64 "\n", incoming_posn);
627         return;
628     }
629 
630     /* pick off s->server_chr->msgfd and store it, posn should accompany msg */
631     incoming_fd = qemu_chr_fe_get_msgfd(s->server_chr);
632     IVSHMEM_DPRINTF("posn is %" PRId64 ", fd is %d\n",
633                     incoming_posn, incoming_fd);
634 
635     /* make sure we have enough space for this peer */
636     if (incoming_posn >= s->nb_peers) {
637         if (resize_peers(s, incoming_posn + 1) < 0) {
638             error_report("failed to resize peers array");
639             if (incoming_fd != -1) {
640                 close(incoming_fd);
641             }
642             return;
643         }
644     }
645 
646     peer = &s->peers[incoming_posn];
647 
648     if (incoming_fd == -1) {
649         /* if posn is positive and unseen before then this is our posn*/
650         if (incoming_posn >= 0 && s->vm_id == -1) {
651             /* receive our posn */
652             s->vm_id = incoming_posn;
653         } else {
654             /* otherwise an fd == -1 means an existing peer has gone away */
655             IVSHMEM_DPRINTF("posn %" PRId64 " has gone away\n", incoming_posn);
656             close_peer_eventfds(s, incoming_posn);
657         }
658         return;
659     }
660 
661     /* if the position is -1, then it's shared memory region fd */
662     if (incoming_posn == -1) {
663         void * map_ptr;
664 
665         if (memory_region_is_mapped(&s->ivshmem)) {
666             error_report("shm already initialized");
667             close(incoming_fd);
668             return;
669         }
670 
671         if (check_shm_size(s, incoming_fd, &err) == -1) {
672             error_report_err(err);
673             close(incoming_fd);
674             return;
675         }
676 
677         /* mmap the region and map into the BAR2 */
678         map_ptr = mmap(0, s->ivshmem_size, PROT_READ|PROT_WRITE, MAP_SHARED,
679                                                             incoming_fd, 0);
680         if (map_ptr == MAP_FAILED) {
681             error_report("Failed to mmap shared memory %s", strerror(errno));
682             close(incoming_fd);
683             return;
684         }
685         memory_region_init_ram_ptr(&s->ivshmem, OBJECT(s),
686                                    "ivshmem.bar2", s->ivshmem_size, map_ptr);
687         qemu_set_ram_fd(s->ivshmem.ram_addr, incoming_fd);
688         vmstate_register_ram(&s->ivshmem, DEVICE(s));
689 
690         IVSHMEM_DPRINTF("guest h/w addr = %p, size = %" PRIu64 "\n",
691                         map_ptr, s->ivshmem_size);
692 
693         memory_region_add_subregion(&s->bar, 0, &s->ivshmem);
694 
695         return;
696     }
697 
698     /* each peer has an associated array of eventfds, and we keep
699      * track of how many eventfds received so far */
700     /* get a new eventfd: */
701     if (peer->nb_eventfds >= s->vectors) {
702         error_report("Too many eventfd received, device has %d vectors",
703                      s->vectors);
704         close(incoming_fd);
705         return;
706     }
707 
708     new_eventfd = peer->nb_eventfds++;
709 
710     /* this is an eventfd for a particular peer VM */
711     IVSHMEM_DPRINTF("eventfds[%" PRId64 "][%d] = %d\n", incoming_posn,
712                     new_eventfd, incoming_fd);
713     event_notifier_init_fd(&peer->eventfds[new_eventfd], incoming_fd);
714     fcntl_setfl(incoming_fd, O_NONBLOCK); /* msix/irqfd poll non block */
715 
716     if (incoming_posn == s->vm_id) {
717         setup_interrupt(s, new_eventfd);
718     }
719 
720     if (ivshmem_has_feature(s, IVSHMEM_IOEVENTFD)) {
721         ivshmem_add_eventfd(s, incoming_posn, new_eventfd);
722     }
723 }
724 
725 static void ivshmem_check_version(void *opaque, const uint8_t * buf, int size)
726 {
727     IVShmemState *s = opaque;
728     int tmp;
729     int64_t version;
730 
731     if (!fifo_update_and_get_i64(s, buf, size, &version)) {
732         return;
733     }
734 
735     tmp = qemu_chr_fe_get_msgfd(s->server_chr);
736     if (tmp != -1 || version != IVSHMEM_PROTOCOL_VERSION) {
737         fprintf(stderr, "incompatible version, you are connecting to a ivshmem-"
738                 "server using a different protocol please check your setup\n");
739         qemu_chr_delete(s->server_chr);
740         s->server_chr = NULL;
741         return;
742     }
743 
744     IVSHMEM_DPRINTF("version check ok, switch to real chardev handler\n");
745     qemu_chr_add_handlers(s->server_chr, ivshmem_can_receive, ivshmem_read,
746                           ivshmem_event, s);
747 }
748 
749 /* Select the MSI-X vectors used by device.
750  * ivshmem maps events to vectors statically, so
751  * we just enable all vectors on init and after reset. */
752 static void ivshmem_use_msix(IVShmemState * s)
753 {
754     PCIDevice *d = PCI_DEVICE(s);
755     int i;
756 
757     IVSHMEM_DPRINTF("%s, msix present: %d\n", __func__, msix_present(d));
758     if (!msix_present(d)) {
759         return;
760     }
761 
762     for (i = 0; i < s->vectors; i++) {
763         msix_vector_use(d, i);
764     }
765 }
766 
767 static void ivshmem_reset(DeviceState *d)
768 {
769     IVShmemState *s = IVSHMEM(d);
770 
771     s->intrstatus = 0;
772     s->intrmask = 0;
773     ivshmem_use_msix(s);
774 }
775 
776 static int ivshmem_setup_msi(IVShmemState * s)
777 {
778     if (msix_init_exclusive_bar(PCI_DEVICE(s), s->vectors, 1)) {
779         return -1;
780     }
781 
782     IVSHMEM_DPRINTF("msix initialized (%d vectors)\n", s->vectors);
783 
784     /* allocate QEMU char devices for receiving interrupts */
785     s->msi_vectors = g_malloc0(s->vectors * sizeof(MSIVector));
786 
787     ivshmem_use_msix(s);
788     return 0;
789 }
790 
791 static void ivshmem_enable_irqfd(IVShmemState *s)
792 {
793     PCIDevice *pdev = PCI_DEVICE(s);
794     int i;
795 
796     for (i = 0; i < s->peers[s->vm_id].nb_eventfds; i++) {
797         ivshmem_add_kvm_msi_virq(s, i);
798     }
799 
800     if (msix_set_vector_notifiers(pdev,
801                                   ivshmem_vector_unmask,
802                                   ivshmem_vector_mask,
803                                   ivshmem_vector_poll)) {
804         error_report("ivshmem: msix_set_vector_notifiers failed");
805     }
806 }
807 
808 static void ivshmem_remove_kvm_msi_virq(IVShmemState *s, int vector)
809 {
810     IVSHMEM_DPRINTF("ivshmem_remove_kvm_msi_virq vector:%d\n", vector);
811 
812     if (s->msi_vectors[vector].pdev == NULL) {
813         return;
814     }
815 
816     /* it was cleaned when masked in the frontend. */
817     kvm_irqchip_release_virq(kvm_state, s->msi_vectors[vector].virq);
818 
819     s->msi_vectors[vector].pdev = NULL;
820 }
821 
822 static void ivshmem_disable_irqfd(IVShmemState *s)
823 {
824     PCIDevice *pdev = PCI_DEVICE(s);
825     int i;
826 
827     for (i = 0; i < s->peers[s->vm_id].nb_eventfds; i++) {
828         ivshmem_remove_kvm_msi_virq(s, i);
829     }
830 
831     msix_unset_vector_notifiers(pdev);
832 }
833 
834 static void ivshmem_write_config(PCIDevice *pdev, uint32_t address,
835                                  uint32_t val, int len)
836 {
837     IVShmemState *s = IVSHMEM(pdev);
838     int is_enabled, was_enabled = msix_enabled(pdev);
839 
840     pci_default_write_config(pdev, address, val, len);
841     is_enabled = msix_enabled(pdev);
842 
843     if (kvm_msi_via_irqfd_enabled() && s->vm_id != -1) {
844         if (!was_enabled && is_enabled) {
845             ivshmem_enable_irqfd(s);
846         } else if (was_enabled && !is_enabled) {
847             ivshmem_disable_irqfd(s);
848         }
849     }
850 }
851 
852 static void pci_ivshmem_realize(PCIDevice *dev, Error **errp)
853 {
854     IVShmemState *s = IVSHMEM(dev);
855     uint8_t *pci_conf;
856     uint8_t attr = PCI_BASE_ADDRESS_SPACE_MEMORY |
857         PCI_BASE_ADDRESS_MEM_PREFETCH;
858 
859     if (!!s->server_chr + !!s->shmobj + !!s->hostmem != 1) {
860         error_setg(errp,
861                    "You must specify either 'shm', 'chardev' or 'x-memdev'");
862         return;
863     }
864 
865     if (s->hostmem) {
866         MemoryRegion *mr;
867 
868         if (s->sizearg) {
869             g_warning("size argument ignored with hostmem");
870         }
871 
872         mr = host_memory_backend_get_memory(s->hostmem, errp);
873         s->ivshmem_size = memory_region_size(mr);
874     } else if (s->sizearg == NULL) {
875         s->ivshmem_size = 4 << 20; /* 4 MB default */
876     } else {
877         char *end;
878         int64_t size = qemu_strtosz(s->sizearg, &end);
879         if (size < 0 || *end != '\0' || !is_power_of_2(size)) {
880             error_setg(errp, "Invalid size %s", s->sizearg);
881             return;
882         }
883         s->ivshmem_size = size;
884     }
885 
886     fifo8_create(&s->incoming_fifo, sizeof(int64_t));
887 
888     /* IRQFD requires MSI */
889     if (ivshmem_has_feature(s, IVSHMEM_IOEVENTFD) &&
890         !ivshmem_has_feature(s, IVSHMEM_MSI)) {
891         error_setg(errp, "ioeventfd/irqfd requires MSI");
892         return;
893     }
894 
895     /* check that role is reasonable */
896     if (s->role) {
897         if (strncmp(s->role, "peer", 5) == 0) {
898             s->role_val = IVSHMEM_PEER;
899         } else if (strncmp(s->role, "master", 7) == 0) {
900             s->role_val = IVSHMEM_MASTER;
901         } else {
902             error_setg(errp, "'role' must be 'peer' or 'master'");
903             return;
904         }
905     } else {
906         s->role_val = IVSHMEM_MASTER; /* default */
907     }
908 
909     if (s->role_val == IVSHMEM_PEER) {
910         error_setg(&s->migration_blocker,
911                    "Migration is disabled when using feature 'peer mode' in device 'ivshmem'");
912         migrate_add_blocker(s->migration_blocker);
913     }
914 
915     pci_conf = dev->config;
916     pci_conf[PCI_COMMAND] = PCI_COMMAND_IO | PCI_COMMAND_MEMORY;
917 
918     pci_config_set_interrupt_pin(pci_conf, 1);
919 
920     memory_region_init_io(&s->ivshmem_mmio, OBJECT(s), &ivshmem_mmio_ops, s,
921                           "ivshmem-mmio", IVSHMEM_REG_BAR_SIZE);
922 
923     /* region for registers*/
924     pci_register_bar(dev, 0, PCI_BASE_ADDRESS_SPACE_MEMORY,
925                      &s->ivshmem_mmio);
926 
927     memory_region_init(&s->bar, OBJECT(s), "ivshmem-bar2-container", s->ivshmem_size);
928     if (s->ivshmem_64bit) {
929         attr |= PCI_BASE_ADDRESS_MEM_TYPE_64;
930     }
931 
932     if (s->hostmem != NULL) {
933         MemoryRegion *mr;
934 
935         IVSHMEM_DPRINTF("using hostmem\n");
936 
937         mr = host_memory_backend_get_memory(MEMORY_BACKEND(s->hostmem), errp);
938         vmstate_register_ram(mr, DEVICE(s));
939         memory_region_add_subregion(&s->bar, 0, mr);
940         pci_register_bar(PCI_DEVICE(s), 2, attr, &s->bar);
941     } else if (s->server_chr != NULL) {
942         /* FIXME do not rely on what chr drivers put into filename */
943         if (strncmp(s->server_chr->filename, "unix:", 5)) {
944             error_setg(errp, "chardev is not a unix client socket");
945             return;
946         }
947 
948         /* if we get a UNIX socket as the parameter we will talk
949          * to the ivshmem server to receive the memory region */
950 
951         IVSHMEM_DPRINTF("using shared memory server (socket = %s)\n",
952                         s->server_chr->filename);
953 
954         if (ivshmem_has_feature(s, IVSHMEM_MSI) &&
955             ivshmem_setup_msi(s)) {
956             error_setg(errp, "msix initialization failed");
957             return;
958         }
959 
960         /* we allocate enough space for 16 peers and grow as needed */
961         resize_peers(s, 16);
962         s->vm_id = -1;
963 
964         pci_register_bar(dev, 2, attr, &s->bar);
965 
966         s->eventfd_chr = g_malloc0(s->vectors * sizeof(CharDriverState *));
967 
968         qemu_chr_add_handlers(s->server_chr, ivshmem_can_receive,
969                               ivshmem_check_version, ivshmem_event, s);
970     } else {
971         /* just map the file immediately, we're not using a server */
972         int fd;
973 
974         IVSHMEM_DPRINTF("using shm_open (shm object = %s)\n", s->shmobj);
975 
976         /* try opening with O_EXCL and if it succeeds zero the memory
977          * by truncating to 0 */
978         if ((fd = shm_open(s->shmobj, O_CREAT|O_RDWR|O_EXCL,
979                         S_IRWXU|S_IRWXG|S_IRWXO)) > 0) {
980            /* truncate file to length PCI device's memory */
981             if (ftruncate(fd, s->ivshmem_size) != 0) {
982                 error_report("could not truncate shared file");
983             }
984 
985         } else if ((fd = shm_open(s->shmobj, O_CREAT|O_RDWR,
986                         S_IRWXU|S_IRWXG|S_IRWXO)) < 0) {
987             error_setg(errp, "could not open shared file");
988             return;
989         }
990 
991         if (check_shm_size(s, fd, errp) == -1) {
992             return;
993         }
994 
995         create_shared_memory_BAR(s, fd, attr, errp);
996     }
997 }
998 
999 static void pci_ivshmem_exit(PCIDevice *dev)
1000 {
1001     IVShmemState *s = IVSHMEM(dev);
1002     int i;
1003 
1004     fifo8_destroy(&s->incoming_fifo);
1005 
1006     if (s->migration_blocker) {
1007         migrate_del_blocker(s->migration_blocker);
1008         error_free(s->migration_blocker);
1009     }
1010 
1011     if (memory_region_is_mapped(&s->ivshmem)) {
1012         if (!s->hostmem) {
1013             void *addr = memory_region_get_ram_ptr(&s->ivshmem);
1014             int fd;
1015 
1016             if (munmap(addr, s->ivshmem_size) == -1) {
1017                 error_report("Failed to munmap shared memory %s",
1018                              strerror(errno));
1019             }
1020 
1021             if ((fd = qemu_get_ram_fd(s->ivshmem.ram_addr)) != -1)
1022                 close(fd);
1023         }
1024 
1025         vmstate_unregister_ram(&s->ivshmem, DEVICE(dev));
1026         memory_region_del_subregion(&s->bar, &s->ivshmem);
1027     }
1028 
1029     if (s->eventfd_chr) {
1030         for (i = 0; i < s->vectors; i++) {
1031             if (s->eventfd_chr[i]) {
1032                 qemu_chr_free(s->eventfd_chr[i]);
1033             }
1034         }
1035         g_free(s->eventfd_chr);
1036     }
1037 
1038     if (s->peers) {
1039         for (i = 0; i < s->nb_peers; i++) {
1040             close_peer_eventfds(s, i);
1041         }
1042         g_free(s->peers);
1043     }
1044 
1045     if (ivshmem_has_feature(s, IVSHMEM_MSI)) {
1046         msix_uninit_exclusive_bar(dev);
1047     }
1048 
1049     g_free(s->msi_vectors);
1050 }
1051 
1052 static bool test_msix(void *opaque, int version_id)
1053 {
1054     IVShmemState *s = opaque;
1055 
1056     return ivshmem_has_feature(s, IVSHMEM_MSI);
1057 }
1058 
1059 static bool test_no_msix(void *opaque, int version_id)
1060 {
1061     return !test_msix(opaque, version_id);
1062 }
1063 
1064 static int ivshmem_pre_load(void *opaque)
1065 {
1066     IVShmemState *s = opaque;
1067 
1068     if (s->role_val == IVSHMEM_PEER) {
1069         error_report("'peer' devices are not migratable");
1070         return -EINVAL;
1071     }
1072 
1073     return 0;
1074 }
1075 
1076 static int ivshmem_post_load(void *opaque, int version_id)
1077 {
1078     IVShmemState *s = opaque;
1079 
1080     if (ivshmem_has_feature(s, IVSHMEM_MSI)) {
1081         ivshmem_use_msix(s);
1082     }
1083 
1084     return 0;
1085 }
1086 
1087 static int ivshmem_load_old(QEMUFile *f, void *opaque, int version_id)
1088 {
1089     IVShmemState *s = opaque;
1090     PCIDevice *pdev = PCI_DEVICE(s);
1091     int ret;
1092 
1093     IVSHMEM_DPRINTF("ivshmem_load_old\n");
1094 
1095     if (version_id != 0) {
1096         return -EINVAL;
1097     }
1098 
1099     if (s->role_val == IVSHMEM_PEER) {
1100         error_report("'peer' devices are not migratable");
1101         return -EINVAL;
1102     }
1103 
1104     ret = pci_device_load(pdev, f);
1105     if (ret) {
1106         return ret;
1107     }
1108 
1109     if (ivshmem_has_feature(s, IVSHMEM_MSI)) {
1110         msix_load(pdev, f);
1111         ivshmem_use_msix(s);
1112     } else {
1113         s->intrstatus = qemu_get_be32(f);
1114         s->intrmask = qemu_get_be32(f);
1115     }
1116 
1117     return 0;
1118 }
1119 
1120 static const VMStateDescription ivshmem_vmsd = {
1121     .name = "ivshmem",
1122     .version_id = 1,
1123     .minimum_version_id = 1,
1124     .pre_load = ivshmem_pre_load,
1125     .post_load = ivshmem_post_load,
1126     .fields = (VMStateField[]) {
1127         VMSTATE_PCI_DEVICE(parent_obj, IVShmemState),
1128 
1129         VMSTATE_MSIX_TEST(parent_obj, IVShmemState, test_msix),
1130         VMSTATE_UINT32_TEST(intrstatus, IVShmemState, test_no_msix),
1131         VMSTATE_UINT32_TEST(intrmask, IVShmemState, test_no_msix),
1132 
1133         VMSTATE_END_OF_LIST()
1134     },
1135     .load_state_old = ivshmem_load_old,
1136     .minimum_version_id_old = 0
1137 };
1138 
1139 static Property ivshmem_properties[] = {
1140     DEFINE_PROP_CHR("chardev", IVShmemState, server_chr),
1141     DEFINE_PROP_STRING("size", IVShmemState, sizearg),
1142     DEFINE_PROP_UINT32("vectors", IVShmemState, vectors, 1),
1143     DEFINE_PROP_BIT("ioeventfd", IVShmemState, features, IVSHMEM_IOEVENTFD, false),
1144     DEFINE_PROP_BIT("msi", IVShmemState, features, IVSHMEM_MSI, true),
1145     DEFINE_PROP_STRING("shm", IVShmemState, shmobj),
1146     DEFINE_PROP_STRING("role", IVShmemState, role),
1147     DEFINE_PROP_UINT32("use64", IVShmemState, ivshmem_64bit, 1),
1148     DEFINE_PROP_END_OF_LIST(),
1149 };
1150 
1151 static void ivshmem_class_init(ObjectClass *klass, void *data)
1152 {
1153     DeviceClass *dc = DEVICE_CLASS(klass);
1154     PCIDeviceClass *k = PCI_DEVICE_CLASS(klass);
1155 
1156     k->realize = pci_ivshmem_realize;
1157     k->exit = pci_ivshmem_exit;
1158     k->config_write = ivshmem_write_config;
1159     k->vendor_id = PCI_VENDOR_ID_IVSHMEM;
1160     k->device_id = PCI_DEVICE_ID_IVSHMEM;
1161     k->class_id = PCI_CLASS_MEMORY_RAM;
1162     dc->reset = ivshmem_reset;
1163     dc->props = ivshmem_properties;
1164     dc->vmsd = &ivshmem_vmsd;
1165     set_bit(DEVICE_CATEGORY_MISC, dc->categories);
1166     dc->desc = "Inter-VM shared memory";
1167 }
1168 
1169 static void ivshmem_check_memdev_is_busy(Object *obj, const char *name,
1170                                          Object *val, Error **errp)
1171 {
1172     MemoryRegion *mr;
1173 
1174     mr = host_memory_backend_get_memory(MEMORY_BACKEND(val), errp);
1175     if (memory_region_is_mapped(mr)) {
1176         char *path = object_get_canonical_path_component(val);
1177         error_setg(errp, "can't use already busy memdev: %s", path);
1178         g_free(path);
1179     } else {
1180         qdev_prop_allow_set_link_before_realize(obj, name, val, errp);
1181     }
1182 }
1183 
1184 static void ivshmem_init(Object *obj)
1185 {
1186     IVShmemState *s = IVSHMEM(obj);
1187 
1188     object_property_add_link(obj, "x-memdev", TYPE_MEMORY_BACKEND,
1189                              (Object **)&s->hostmem,
1190                              ivshmem_check_memdev_is_busy,
1191                              OBJ_PROP_LINK_UNREF_ON_RELEASE,
1192                              &error_abort);
1193 }
1194 
1195 static const TypeInfo ivshmem_info = {
1196     .name          = TYPE_IVSHMEM,
1197     .parent        = TYPE_PCI_DEVICE,
1198     .instance_size = sizeof(IVShmemState),
1199     .instance_init = ivshmem_init,
1200     .class_init    = ivshmem_class_init,
1201 };
1202 
1203 static void ivshmem_register_types(void)
1204 {
1205     type_register_static(&ivshmem_info);
1206 }
1207 
1208 type_init(ivshmem_register_types)
1209