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