serial: simplify tsr_retry reset
[qemu/ar7.git] / hw / misc / ivshmem.c
blobc4dde3a52e7fd8d7eef472bbdc4d9316b70cb33a
1 /*
2 * Inter-VM Shared Memory PCI device.
4 * Author:
5 * Cam Macdonell <cam@cs.ualberta.ca>
7 * Based On: cirrus_vga.c
8 * Copyright (c) 2004 Fabrice Bellard
9 * Copyright (c) 2004 Makoto Suzuki (suzu)
11 * and rtl8139.c
12 * Copyright (c) 2006 Igor Kovalenko
14 * This code is licensed under the GNU GPL v2.
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.
19 #include "qemu/osdep.h"
20 #include "qapi/error.h"
21 #include "qemu/cutils.h"
22 #include "hw/hw.h"
23 #include "hw/i386/pc.h"
24 #include "hw/pci/pci.h"
25 #include "hw/pci/msi.h"
26 #include "hw/pci/msix.h"
27 #include "sysemu/kvm.h"
28 #include "migration/migration.h"
29 #include "qemu/error-report.h"
30 #include "qemu/event_notifier.h"
31 #include "qom/object_interfaces.h"
32 #include "sysemu/char.h"
33 #include "sysemu/hostmem.h"
34 #include "sysemu/qtest.h"
35 #include "qapi/visitor.h"
37 #include "hw/misc/ivshmem.h"
39 #define PCI_VENDOR_ID_IVSHMEM PCI_VENDOR_ID_REDHAT_QUMRANET
40 #define PCI_DEVICE_ID_IVSHMEM 0x1110
42 #define IVSHMEM_MAX_PEERS UINT16_MAX
43 #define IVSHMEM_IOEVENTFD 0
44 #define IVSHMEM_MSI 1
46 #define IVSHMEM_REG_BAR_SIZE 0x100
48 #define IVSHMEM_DEBUG 0
49 #define IVSHMEM_DPRINTF(fmt, ...) \
50 do { \
51 if (IVSHMEM_DEBUG) { \
52 printf("IVSHMEM: " fmt, ## __VA_ARGS__); \
53 } \
54 } while (0)
56 #define TYPE_IVSHMEM_COMMON "ivshmem-common"
57 #define IVSHMEM_COMMON(obj) \
58 OBJECT_CHECK(IVShmemState, (obj), TYPE_IVSHMEM_COMMON)
60 #define TYPE_IVSHMEM_PLAIN "ivshmem-plain"
61 #define IVSHMEM_PLAIN(obj) \
62 OBJECT_CHECK(IVShmemState, (obj), TYPE_IVSHMEM_PLAIN)
64 #define TYPE_IVSHMEM_DOORBELL "ivshmem-doorbell"
65 #define IVSHMEM_DOORBELL(obj) \
66 OBJECT_CHECK(IVShmemState, (obj), TYPE_IVSHMEM_DOORBELL)
68 #define TYPE_IVSHMEM "ivshmem"
69 #define IVSHMEM(obj) \
70 OBJECT_CHECK(IVShmemState, (obj), TYPE_IVSHMEM)
72 typedef struct Peer {
73 int nb_eventfds;
74 EventNotifier *eventfds;
75 } Peer;
77 typedef struct MSIVector {
78 PCIDevice *pdev;
79 int virq;
80 } MSIVector;
82 typedef struct IVShmemState {
83 /*< private >*/
84 PCIDevice parent_obj;
85 /*< public >*/
87 uint32_t features;
89 /* exactly one of these two may be set */
90 HostMemoryBackend *hostmem; /* with interrupts */
91 CharDriverState *server_chr; /* without interrupts */
93 /* registers */
94 uint32_t intrmask;
95 uint32_t intrstatus;
96 int vm_id;
98 /* BARs */
99 MemoryRegion ivshmem_mmio; /* BAR 0 (registers) */
100 MemoryRegion *ivshmem_bar2; /* BAR 2 (shared memory) */
101 MemoryRegion server_bar2; /* used with server_chr */
103 /* interrupt support */
104 Peer *peers;
105 int nb_peers; /* space in @peers[] */
106 uint32_t vectors;
107 MSIVector *msi_vectors;
108 uint64_t msg_buf; /* buffer for receiving server messages */
109 int msg_buffered_bytes; /* #bytes in @msg_buf */
111 /* migration stuff */
112 OnOffAuto master;
113 Error *migration_blocker;
115 /* legacy cruft */
116 char *role;
117 char *shmobj;
118 char *sizearg;
119 size_t legacy_size;
120 uint32_t not_legacy_32bit;
121 } IVShmemState;
123 /* registers for the Inter-VM shared memory device */
124 enum ivshmem_registers {
125 INTRMASK = 0,
126 INTRSTATUS = 4,
127 IVPOSITION = 8,
128 DOORBELL = 12,
131 static inline uint32_t ivshmem_has_feature(IVShmemState *ivs,
132 unsigned int feature) {
133 return (ivs->features & (1 << feature));
136 static inline bool ivshmem_is_master(IVShmemState *s)
138 assert(s->master != ON_OFF_AUTO_AUTO);
139 return s->master == ON_OFF_AUTO_ON;
142 static void ivshmem_update_irq(IVShmemState *s)
144 PCIDevice *d = PCI_DEVICE(s);
145 uint32_t isr = s->intrstatus & s->intrmask;
148 * Do nothing unless the device actually uses INTx. Here's how
149 * the device variants signal interrupts, what they put in PCI
150 * config space:
151 * Device variant Interrupt Interrupt Pin MSI-X cap.
152 * ivshmem-plain none 0 no
153 * ivshmem-doorbell MSI-X 1 yes(1)
154 * ivshmem,msi=off INTx 1 no
155 * ivshmem,msi=on MSI-X 1(2) yes(1)
156 * (1) if guest enabled MSI-X
157 * (2) the device lies
158 * Leads to the condition for doing nothing:
160 if (ivshmem_has_feature(s, IVSHMEM_MSI)
161 || !d->config[PCI_INTERRUPT_PIN]) {
162 return;
165 /* don't print ISR resets */
166 if (isr) {
167 IVSHMEM_DPRINTF("Set IRQ to %d (%04x %04x)\n",
168 isr ? 1 : 0, s->intrstatus, s->intrmask);
171 pci_set_irq(d, isr != 0);
174 static void ivshmem_IntrMask_write(IVShmemState *s, uint32_t val)
176 IVSHMEM_DPRINTF("IntrMask write(w) val = 0x%04x\n", val);
178 s->intrmask = val;
179 ivshmem_update_irq(s);
182 static uint32_t ivshmem_IntrMask_read(IVShmemState *s)
184 uint32_t ret = s->intrmask;
186 IVSHMEM_DPRINTF("intrmask read(w) val = 0x%04x\n", ret);
187 return ret;
190 static void ivshmem_IntrStatus_write(IVShmemState *s, uint32_t val)
192 IVSHMEM_DPRINTF("IntrStatus write(w) val = 0x%04x\n", val);
194 s->intrstatus = val;
195 ivshmem_update_irq(s);
198 static uint32_t ivshmem_IntrStatus_read(IVShmemState *s)
200 uint32_t ret = s->intrstatus;
202 /* reading ISR clears all interrupts */
203 s->intrstatus = 0;
204 ivshmem_update_irq(s);
205 return ret;
208 static void ivshmem_io_write(void *opaque, hwaddr addr,
209 uint64_t val, unsigned size)
211 IVShmemState *s = opaque;
213 uint16_t dest = val >> 16;
214 uint16_t vector = val & 0xff;
216 addr &= 0xfc;
218 IVSHMEM_DPRINTF("writing to addr " TARGET_FMT_plx "\n", addr);
219 switch (addr)
221 case INTRMASK:
222 ivshmem_IntrMask_write(s, val);
223 break;
225 case INTRSTATUS:
226 ivshmem_IntrStatus_write(s, val);
227 break;
229 case DOORBELL:
230 /* check that dest VM ID is reasonable */
231 if (dest >= s->nb_peers) {
232 IVSHMEM_DPRINTF("Invalid destination VM ID (%d)\n", dest);
233 break;
236 /* check doorbell range */
237 if (vector < s->peers[dest].nb_eventfds) {
238 IVSHMEM_DPRINTF("Notifying VM %d on vector %d\n", dest, vector);
239 event_notifier_set(&s->peers[dest].eventfds[vector]);
240 } else {
241 IVSHMEM_DPRINTF("Invalid destination vector %d on VM %d\n",
242 vector, dest);
244 break;
245 default:
246 IVSHMEM_DPRINTF("Unhandled write " TARGET_FMT_plx "\n", addr);
250 static uint64_t ivshmem_io_read(void *opaque, hwaddr addr,
251 unsigned size)
254 IVShmemState *s = opaque;
255 uint32_t ret;
257 switch (addr)
259 case INTRMASK:
260 ret = ivshmem_IntrMask_read(s);
261 break;
263 case INTRSTATUS:
264 ret = ivshmem_IntrStatus_read(s);
265 break;
267 case IVPOSITION:
268 ret = s->vm_id;
269 break;
271 default:
272 IVSHMEM_DPRINTF("why are we reading " TARGET_FMT_plx "\n", addr);
273 ret = 0;
276 return ret;
279 static const MemoryRegionOps ivshmem_mmio_ops = {
280 .read = ivshmem_io_read,
281 .write = ivshmem_io_write,
282 .endianness = DEVICE_NATIVE_ENDIAN,
283 .impl = {
284 .min_access_size = 4,
285 .max_access_size = 4,
289 static void ivshmem_vector_notify(void *opaque)
291 MSIVector *entry = opaque;
292 PCIDevice *pdev = entry->pdev;
293 IVShmemState *s = IVSHMEM_COMMON(pdev);
294 int vector = entry - s->msi_vectors;
295 EventNotifier *n = &s->peers[s->vm_id].eventfds[vector];
297 if (!event_notifier_test_and_clear(n)) {
298 return;
301 IVSHMEM_DPRINTF("interrupt on vector %p %d\n", pdev, vector);
302 if (ivshmem_has_feature(s, IVSHMEM_MSI)) {
303 if (msix_enabled(pdev)) {
304 msix_notify(pdev, vector);
306 } else {
307 ivshmem_IntrStatus_write(s, 1);
311 static int ivshmem_vector_unmask(PCIDevice *dev, unsigned vector,
312 MSIMessage msg)
314 IVShmemState *s = IVSHMEM_COMMON(dev);
315 EventNotifier *n = &s->peers[s->vm_id].eventfds[vector];
316 MSIVector *v = &s->msi_vectors[vector];
317 int ret;
319 IVSHMEM_DPRINTF("vector unmask %p %d\n", dev, vector);
321 ret = kvm_irqchip_update_msi_route(kvm_state, v->virq, msg, dev);
322 if (ret < 0) {
323 return ret;
326 return kvm_irqchip_add_irqfd_notifier_gsi(kvm_state, n, NULL, v->virq);
329 static void ivshmem_vector_mask(PCIDevice *dev, unsigned vector)
331 IVShmemState *s = IVSHMEM_COMMON(dev);
332 EventNotifier *n = &s->peers[s->vm_id].eventfds[vector];
333 int ret;
335 IVSHMEM_DPRINTF("vector mask %p %d\n", dev, vector);
337 ret = kvm_irqchip_remove_irqfd_notifier_gsi(kvm_state, n,
338 s->msi_vectors[vector].virq);
339 if (ret != 0) {
340 error_report("remove_irqfd_notifier_gsi failed");
344 static void ivshmem_vector_poll(PCIDevice *dev,
345 unsigned int vector_start,
346 unsigned int vector_end)
348 IVShmemState *s = IVSHMEM_COMMON(dev);
349 unsigned int vector;
351 IVSHMEM_DPRINTF("vector poll %p %d-%d\n", dev, vector_start, vector_end);
353 vector_end = MIN(vector_end, s->vectors);
355 for (vector = vector_start; vector < vector_end; vector++) {
356 EventNotifier *notifier = &s->peers[s->vm_id].eventfds[vector];
358 if (!msix_is_masked(dev, vector)) {
359 continue;
362 if (event_notifier_test_and_clear(notifier)) {
363 msix_set_pending(dev, vector);
368 static void watch_vector_notifier(IVShmemState *s, EventNotifier *n,
369 int vector)
371 int eventfd = event_notifier_get_fd(n);
373 assert(!s->msi_vectors[vector].pdev);
374 s->msi_vectors[vector].pdev = PCI_DEVICE(s);
376 qemu_set_fd_handler(eventfd, ivshmem_vector_notify,
377 NULL, &s->msi_vectors[vector]);
380 static void ivshmem_add_eventfd(IVShmemState *s, int posn, int i)
382 memory_region_add_eventfd(&s->ivshmem_mmio,
383 DOORBELL,
385 true,
386 (posn << 16) | i,
387 &s->peers[posn].eventfds[i]);
390 static void ivshmem_del_eventfd(IVShmemState *s, int posn, int i)
392 memory_region_del_eventfd(&s->ivshmem_mmio,
393 DOORBELL,
395 true,
396 (posn << 16) | i,
397 &s->peers[posn].eventfds[i]);
400 static void close_peer_eventfds(IVShmemState *s, int posn)
402 int i, n;
404 assert(posn >= 0 && posn < s->nb_peers);
405 n = s->peers[posn].nb_eventfds;
407 if (ivshmem_has_feature(s, IVSHMEM_IOEVENTFD)) {
408 memory_region_transaction_begin();
409 for (i = 0; i < n; i++) {
410 ivshmem_del_eventfd(s, posn, i);
412 memory_region_transaction_commit();
415 for (i = 0; i < n; i++) {
416 event_notifier_cleanup(&s->peers[posn].eventfds[i]);
419 g_free(s->peers[posn].eventfds);
420 s->peers[posn].nb_eventfds = 0;
423 static void resize_peers(IVShmemState *s, int nb_peers)
425 int old_nb_peers = s->nb_peers;
426 int i;
428 assert(nb_peers > old_nb_peers);
429 IVSHMEM_DPRINTF("bumping storage to %d peers\n", nb_peers);
431 s->peers = g_realloc(s->peers, nb_peers * sizeof(Peer));
432 s->nb_peers = nb_peers;
434 for (i = old_nb_peers; i < nb_peers; i++) {
435 s->peers[i].eventfds = g_new0(EventNotifier, s->vectors);
436 s->peers[i].nb_eventfds = 0;
440 static void ivshmem_add_kvm_msi_virq(IVShmemState *s, int vector,
441 Error **errp)
443 PCIDevice *pdev = PCI_DEVICE(s);
444 MSIMessage msg = msix_get_message(pdev, vector);
445 int ret;
447 IVSHMEM_DPRINTF("ivshmem_add_kvm_msi_virq vector:%d\n", vector);
448 assert(!s->msi_vectors[vector].pdev);
450 ret = kvm_irqchip_add_msi_route(kvm_state, msg, pdev);
451 if (ret < 0) {
452 error_setg(errp, "kvm_irqchip_add_msi_route failed");
453 return;
456 s->msi_vectors[vector].virq = ret;
457 s->msi_vectors[vector].pdev = pdev;
460 static void setup_interrupt(IVShmemState *s, int vector, Error **errp)
462 EventNotifier *n = &s->peers[s->vm_id].eventfds[vector];
463 bool with_irqfd = kvm_msi_via_irqfd_enabled() &&
464 ivshmem_has_feature(s, IVSHMEM_MSI);
465 PCIDevice *pdev = PCI_DEVICE(s);
466 Error *err = NULL;
468 IVSHMEM_DPRINTF("setting up interrupt for vector: %d\n", vector);
470 if (!with_irqfd) {
471 IVSHMEM_DPRINTF("with eventfd\n");
472 watch_vector_notifier(s, n, vector);
473 } else if (msix_enabled(pdev)) {
474 IVSHMEM_DPRINTF("with irqfd\n");
475 ivshmem_add_kvm_msi_virq(s, vector, &err);
476 if (err) {
477 error_propagate(errp, err);
478 return;
481 if (!msix_is_masked(pdev, vector)) {
482 kvm_irqchip_add_irqfd_notifier_gsi(kvm_state, n, NULL,
483 s->msi_vectors[vector].virq);
484 /* TODO handle error */
486 } else {
487 /* it will be delayed until msix is enabled, in write_config */
488 IVSHMEM_DPRINTF("with irqfd, delayed until msix enabled\n");
492 static void process_msg_shmem(IVShmemState *s, int fd, Error **errp)
494 struct stat buf;
495 size_t size;
496 void *ptr;
498 if (s->ivshmem_bar2) {
499 error_setg(errp, "server sent unexpected shared memory message");
500 close(fd);
501 return;
504 if (fstat(fd, &buf) < 0) {
505 error_setg_errno(errp, errno,
506 "can't determine size of shared memory sent by server");
507 close(fd);
508 return;
511 size = buf.st_size;
513 /* Legacy cruft */
514 if (s->legacy_size != SIZE_MAX) {
515 if (size < s->legacy_size) {
516 error_setg(errp, "server sent only %zd bytes of shared memory",
517 (size_t)buf.st_size);
518 close(fd);
519 return;
521 size = s->legacy_size;
524 /* mmap the region and map into the BAR2 */
525 ptr = mmap(0, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
526 if (ptr == MAP_FAILED) {
527 error_setg_errno(errp, errno, "Failed to mmap shared memory");
528 close(fd);
529 return;
531 memory_region_init_ram_ptr(&s->server_bar2, OBJECT(s),
532 "ivshmem.bar2", size, ptr);
533 memory_region_set_fd(&s->server_bar2, fd);
534 s->ivshmem_bar2 = &s->server_bar2;
537 static void process_msg_disconnect(IVShmemState *s, uint16_t posn,
538 Error **errp)
540 IVSHMEM_DPRINTF("posn %d has gone away\n", posn);
541 if (posn >= s->nb_peers || posn == s->vm_id) {
542 error_setg(errp, "invalid peer %d", posn);
543 return;
545 close_peer_eventfds(s, posn);
548 static void process_msg_connect(IVShmemState *s, uint16_t posn, int fd,
549 Error **errp)
551 Peer *peer = &s->peers[posn];
552 int vector;
555 * The N-th connect message for this peer comes with the file
556 * descriptor for vector N-1. Count messages to find the vector.
558 if (peer->nb_eventfds >= s->vectors) {
559 error_setg(errp, "Too many eventfd received, device has %d vectors",
560 s->vectors);
561 close(fd);
562 return;
564 vector = peer->nb_eventfds++;
566 IVSHMEM_DPRINTF("eventfds[%d][%d] = %d\n", posn, vector, fd);
567 event_notifier_init_fd(&peer->eventfds[vector], fd);
568 fcntl_setfl(fd, O_NONBLOCK); /* msix/irqfd poll non block */
570 if (posn == s->vm_id) {
571 setup_interrupt(s, vector, errp);
572 /* TODO do we need to handle the error? */
575 if (ivshmem_has_feature(s, IVSHMEM_IOEVENTFD)) {
576 ivshmem_add_eventfd(s, posn, vector);
580 static void process_msg(IVShmemState *s, int64_t msg, int fd, Error **errp)
582 IVSHMEM_DPRINTF("posn is %" PRId64 ", fd is %d\n", msg, fd);
584 if (msg < -1 || msg > IVSHMEM_MAX_PEERS) {
585 error_setg(errp, "server sent invalid message %" PRId64, msg);
586 close(fd);
587 return;
590 if (msg == -1) {
591 process_msg_shmem(s, fd, errp);
592 return;
595 if (msg >= s->nb_peers) {
596 resize_peers(s, msg + 1);
599 if (fd >= 0) {
600 process_msg_connect(s, msg, fd, errp);
601 } else {
602 process_msg_disconnect(s, msg, errp);
606 static int ivshmem_can_receive(void *opaque)
608 IVShmemState *s = opaque;
610 assert(s->msg_buffered_bytes < sizeof(s->msg_buf));
611 return sizeof(s->msg_buf) - s->msg_buffered_bytes;
614 static void ivshmem_read(void *opaque, const uint8_t *buf, int size)
616 IVShmemState *s = opaque;
617 Error *err = NULL;
618 int fd;
619 int64_t msg;
621 assert(size >= 0 && s->msg_buffered_bytes + size <= sizeof(s->msg_buf));
622 memcpy((unsigned char *)&s->msg_buf + s->msg_buffered_bytes, buf, size);
623 s->msg_buffered_bytes += size;
624 if (s->msg_buffered_bytes < sizeof(s->msg_buf)) {
625 return;
627 msg = le64_to_cpu(s->msg_buf);
628 s->msg_buffered_bytes = 0;
630 fd = qemu_chr_fe_get_msgfd(s->server_chr);
631 IVSHMEM_DPRINTF("posn is %" PRId64 ", fd is %d\n", msg, fd);
633 process_msg(s, msg, fd, &err);
634 if (err) {
635 error_report_err(err);
639 static int64_t ivshmem_recv_msg(IVShmemState *s, int *pfd, Error **errp)
641 int64_t msg;
642 int n, ret;
644 n = 0;
645 do {
646 ret = qemu_chr_fe_read_all(s->server_chr, (uint8_t *)&msg + n,
647 sizeof(msg) - n);
648 if (ret < 0 && ret != -EINTR) {
649 error_setg_errno(errp, -ret, "read from server failed");
650 return INT64_MIN;
652 n += ret;
653 } while (n < sizeof(msg));
655 *pfd = qemu_chr_fe_get_msgfd(s->server_chr);
656 return msg;
659 static void ivshmem_recv_setup(IVShmemState *s, Error **errp)
661 Error *err = NULL;
662 int64_t msg;
663 int fd;
665 msg = ivshmem_recv_msg(s, &fd, &err);
666 if (err) {
667 error_propagate(errp, err);
668 return;
670 if (msg != IVSHMEM_PROTOCOL_VERSION) {
671 error_setg(errp, "server sent version %" PRId64 ", expecting %d",
672 msg, IVSHMEM_PROTOCOL_VERSION);
673 return;
675 if (fd != -1) {
676 error_setg(errp, "server sent invalid version message");
677 return;
681 * ivshmem-server sends the remaining initial messages in a fixed
682 * order, but the device has always accepted them in any order.
683 * Stay as compatible as practical, just in case people use
684 * servers that behave differently.
688 * ivshmem_device_spec.txt has always required the ID message
689 * right here, and ivshmem-server has always complied. However,
690 * older versions of the device accepted it out of order, but
691 * broke when an interrupt setup message arrived before it.
693 msg = ivshmem_recv_msg(s, &fd, &err);
694 if (err) {
695 error_propagate(errp, err);
696 return;
698 if (fd != -1 || msg < 0 || msg > IVSHMEM_MAX_PEERS) {
699 error_setg(errp, "server sent invalid ID message");
700 return;
702 s->vm_id = msg;
705 * Receive more messages until we got shared memory.
707 do {
708 msg = ivshmem_recv_msg(s, &fd, &err);
709 if (err) {
710 error_propagate(errp, err);
711 return;
713 process_msg(s, msg, fd, &err);
714 if (err) {
715 error_propagate(errp, err);
716 return;
718 } while (msg != -1);
721 * This function must either map the shared memory or fail. The
722 * loop above ensures that: it terminates normally only after it
723 * successfully processed the server's shared memory message.
724 * Assert that actually mapped the shared memory:
726 assert(s->ivshmem_bar2);
729 /* Select the MSI-X vectors used by device.
730 * ivshmem maps events to vectors statically, so
731 * we just enable all vectors on init and after reset. */
732 static void ivshmem_msix_vector_use(IVShmemState *s)
734 PCIDevice *d = PCI_DEVICE(s);
735 int i;
737 for (i = 0; i < s->vectors; i++) {
738 msix_vector_use(d, i);
742 static void ivshmem_reset(DeviceState *d)
744 IVShmemState *s = IVSHMEM_COMMON(d);
746 s->intrstatus = 0;
747 s->intrmask = 0;
748 if (ivshmem_has_feature(s, IVSHMEM_MSI)) {
749 ivshmem_msix_vector_use(s);
753 static int ivshmem_setup_interrupts(IVShmemState *s)
755 /* allocate QEMU callback data for receiving interrupts */
756 s->msi_vectors = g_malloc0(s->vectors * sizeof(MSIVector));
758 if (ivshmem_has_feature(s, IVSHMEM_MSI)) {
759 if (msix_init_exclusive_bar(PCI_DEVICE(s), s->vectors, 1)) {
760 return -1;
763 IVSHMEM_DPRINTF("msix initialized (%d vectors)\n", s->vectors);
764 ivshmem_msix_vector_use(s);
767 return 0;
770 static void ivshmem_enable_irqfd(IVShmemState *s)
772 PCIDevice *pdev = PCI_DEVICE(s);
773 int i;
775 for (i = 0; i < s->peers[s->vm_id].nb_eventfds; i++) {
776 Error *err = NULL;
778 ivshmem_add_kvm_msi_virq(s, i, &err);
779 if (err) {
780 error_report_err(err);
781 /* TODO do we need to handle the error? */
785 if (msix_set_vector_notifiers(pdev,
786 ivshmem_vector_unmask,
787 ivshmem_vector_mask,
788 ivshmem_vector_poll)) {
789 error_report("ivshmem: msix_set_vector_notifiers failed");
793 static void ivshmem_remove_kvm_msi_virq(IVShmemState *s, int vector)
795 IVSHMEM_DPRINTF("ivshmem_remove_kvm_msi_virq vector:%d\n", vector);
797 if (s->msi_vectors[vector].pdev == NULL) {
798 return;
801 /* it was cleaned when masked in the frontend. */
802 kvm_irqchip_release_virq(kvm_state, s->msi_vectors[vector].virq);
804 s->msi_vectors[vector].pdev = NULL;
807 static void ivshmem_disable_irqfd(IVShmemState *s)
809 PCIDevice *pdev = PCI_DEVICE(s);
810 int i;
812 for (i = 0; i < s->peers[s->vm_id].nb_eventfds; i++) {
813 ivshmem_remove_kvm_msi_virq(s, i);
816 msix_unset_vector_notifiers(pdev);
819 static void ivshmem_write_config(PCIDevice *pdev, uint32_t address,
820 uint32_t val, int len)
822 IVShmemState *s = IVSHMEM_COMMON(pdev);
823 int is_enabled, was_enabled = msix_enabled(pdev);
825 pci_default_write_config(pdev, address, val, len);
826 is_enabled = msix_enabled(pdev);
828 if (kvm_msi_via_irqfd_enabled()) {
829 if (!was_enabled && is_enabled) {
830 ivshmem_enable_irqfd(s);
831 } else if (was_enabled && !is_enabled) {
832 ivshmem_disable_irqfd(s);
837 static void ivshmem_common_realize(PCIDevice *dev, Error **errp)
839 IVShmemState *s = IVSHMEM_COMMON(dev);
840 Error *err = NULL;
841 uint8_t *pci_conf;
842 uint8_t attr = PCI_BASE_ADDRESS_SPACE_MEMORY |
843 PCI_BASE_ADDRESS_MEM_PREFETCH;
845 /* IRQFD requires MSI */
846 if (ivshmem_has_feature(s, IVSHMEM_IOEVENTFD) &&
847 !ivshmem_has_feature(s, IVSHMEM_MSI)) {
848 error_setg(errp, "ioeventfd/irqfd requires MSI");
849 return;
852 pci_conf = dev->config;
853 pci_conf[PCI_COMMAND] = PCI_COMMAND_IO | PCI_COMMAND_MEMORY;
855 memory_region_init_io(&s->ivshmem_mmio, OBJECT(s), &ivshmem_mmio_ops, s,
856 "ivshmem-mmio", IVSHMEM_REG_BAR_SIZE);
858 /* region for registers*/
859 pci_register_bar(dev, 0, PCI_BASE_ADDRESS_SPACE_MEMORY,
860 &s->ivshmem_mmio);
862 if (!s->not_legacy_32bit) {
863 attr |= PCI_BASE_ADDRESS_MEM_TYPE_64;
866 if (s->hostmem != NULL) {
867 IVSHMEM_DPRINTF("using hostmem\n");
869 s->ivshmem_bar2 = host_memory_backend_get_memory(s->hostmem,
870 &error_abort);
871 } else {
872 assert(s->server_chr);
874 IVSHMEM_DPRINTF("using shared memory server (socket = %s)\n",
875 s->server_chr->filename);
877 /* we allocate enough space for 16 peers and grow as needed */
878 resize_peers(s, 16);
881 * Receive setup messages from server synchronously.
882 * Older versions did it asynchronously, but that creates a
883 * number of entertaining race conditions.
885 ivshmem_recv_setup(s, &err);
886 if (err) {
887 error_propagate(errp, err);
888 return;
891 if (s->master == ON_OFF_AUTO_ON && s->vm_id != 0) {
892 error_setg(errp,
893 "master must connect to the server before any peers");
894 return;
897 qemu_chr_add_handlers(s->server_chr, ivshmem_can_receive,
898 ivshmem_read, NULL, s);
900 if (ivshmem_setup_interrupts(s) < 0) {
901 error_setg(errp, "failed to initialize interrupts");
902 return;
906 vmstate_register_ram(s->ivshmem_bar2, DEVICE(s));
907 pci_register_bar(PCI_DEVICE(s), 2, attr, s->ivshmem_bar2);
909 if (s->master == ON_OFF_AUTO_AUTO) {
910 s->master = s->vm_id == 0 ? ON_OFF_AUTO_ON : ON_OFF_AUTO_OFF;
913 if (!ivshmem_is_master(s)) {
914 error_setg(&s->migration_blocker,
915 "Migration is disabled when using feature 'peer mode' in device 'ivshmem'");
916 migrate_add_blocker(s->migration_blocker);
920 static void ivshmem_exit(PCIDevice *dev)
922 IVShmemState *s = IVSHMEM_COMMON(dev);
923 int i;
925 if (s->migration_blocker) {
926 migrate_del_blocker(s->migration_blocker);
927 error_free(s->migration_blocker);
930 if (memory_region_is_mapped(s->ivshmem_bar2)) {
931 if (!s->hostmem) {
932 void *addr = memory_region_get_ram_ptr(s->ivshmem_bar2);
933 int fd;
935 if (munmap(addr, memory_region_size(s->ivshmem_bar2) == -1)) {
936 error_report("Failed to munmap shared memory %s",
937 strerror(errno));
940 fd = memory_region_get_fd(s->ivshmem_bar2);
941 close(fd);
944 vmstate_unregister_ram(s->ivshmem_bar2, DEVICE(dev));
947 if (s->peers) {
948 for (i = 0; i < s->nb_peers; i++) {
949 close_peer_eventfds(s, i);
951 g_free(s->peers);
954 if (ivshmem_has_feature(s, IVSHMEM_MSI)) {
955 msix_uninit_exclusive_bar(dev);
958 g_free(s->msi_vectors);
961 static int ivshmem_pre_load(void *opaque)
963 IVShmemState *s = opaque;
965 if (!ivshmem_is_master(s)) {
966 error_report("'peer' devices are not migratable");
967 return -EINVAL;
970 return 0;
973 static int ivshmem_post_load(void *opaque, int version_id)
975 IVShmemState *s = opaque;
977 if (ivshmem_has_feature(s, IVSHMEM_MSI)) {
978 ivshmem_msix_vector_use(s);
980 return 0;
983 static void ivshmem_common_class_init(ObjectClass *klass, void *data)
985 DeviceClass *dc = DEVICE_CLASS(klass);
986 PCIDeviceClass *k = PCI_DEVICE_CLASS(klass);
988 k->realize = ivshmem_common_realize;
989 k->exit = ivshmem_exit;
990 k->config_write = ivshmem_write_config;
991 k->vendor_id = PCI_VENDOR_ID_IVSHMEM;
992 k->device_id = PCI_DEVICE_ID_IVSHMEM;
993 k->class_id = PCI_CLASS_MEMORY_RAM;
994 k->revision = 1;
995 dc->reset = ivshmem_reset;
996 set_bit(DEVICE_CATEGORY_MISC, dc->categories);
997 dc->desc = "Inter-VM shared memory";
1000 static const TypeInfo ivshmem_common_info = {
1001 .name = TYPE_IVSHMEM_COMMON,
1002 .parent = TYPE_PCI_DEVICE,
1003 .instance_size = sizeof(IVShmemState),
1004 .abstract = true,
1005 .class_init = ivshmem_common_class_init,
1008 static void ivshmem_check_memdev_is_busy(Object *obj, const char *name,
1009 Object *val, Error **errp)
1011 MemoryRegion *mr;
1013 mr = host_memory_backend_get_memory(MEMORY_BACKEND(val), &error_abort);
1014 if (memory_region_is_mapped(mr)) {
1015 char *path = object_get_canonical_path_component(val);
1016 error_setg(errp, "can't use already busy memdev: %s", path);
1017 g_free(path);
1018 } else {
1019 qdev_prop_allow_set_link_before_realize(obj, name, val, errp);
1023 static const VMStateDescription ivshmem_plain_vmsd = {
1024 .name = TYPE_IVSHMEM_PLAIN,
1025 .version_id = 0,
1026 .minimum_version_id = 0,
1027 .pre_load = ivshmem_pre_load,
1028 .post_load = ivshmem_post_load,
1029 .fields = (VMStateField[]) {
1030 VMSTATE_PCI_DEVICE(parent_obj, IVShmemState),
1031 VMSTATE_UINT32(intrstatus, IVShmemState),
1032 VMSTATE_UINT32(intrmask, IVShmemState),
1033 VMSTATE_END_OF_LIST()
1037 static Property ivshmem_plain_properties[] = {
1038 DEFINE_PROP_ON_OFF_AUTO("master", IVShmemState, master, ON_OFF_AUTO_OFF),
1039 DEFINE_PROP_END_OF_LIST(),
1042 static void ivshmem_plain_init(Object *obj)
1044 IVShmemState *s = IVSHMEM_PLAIN(obj);
1046 object_property_add_link(obj, "memdev", TYPE_MEMORY_BACKEND,
1047 (Object **)&s->hostmem,
1048 ivshmem_check_memdev_is_busy,
1049 OBJ_PROP_LINK_UNREF_ON_RELEASE,
1050 &error_abort);
1053 static void ivshmem_plain_realize(PCIDevice *dev, Error **errp)
1055 IVShmemState *s = IVSHMEM_COMMON(dev);
1057 if (!s->hostmem) {
1058 error_setg(errp, "You must specify a 'memdev'");
1059 return;
1062 ivshmem_common_realize(dev, errp);
1065 static void ivshmem_plain_class_init(ObjectClass *klass, void *data)
1067 DeviceClass *dc = DEVICE_CLASS(klass);
1068 PCIDeviceClass *k = PCI_DEVICE_CLASS(klass);
1070 k->realize = ivshmem_plain_realize;
1071 dc->props = ivshmem_plain_properties;
1072 dc->vmsd = &ivshmem_plain_vmsd;
1075 static const TypeInfo ivshmem_plain_info = {
1076 .name = TYPE_IVSHMEM_PLAIN,
1077 .parent = TYPE_IVSHMEM_COMMON,
1078 .instance_size = sizeof(IVShmemState),
1079 .instance_init = ivshmem_plain_init,
1080 .class_init = ivshmem_plain_class_init,
1083 static const VMStateDescription ivshmem_doorbell_vmsd = {
1084 .name = TYPE_IVSHMEM_DOORBELL,
1085 .version_id = 0,
1086 .minimum_version_id = 0,
1087 .pre_load = ivshmem_pre_load,
1088 .post_load = ivshmem_post_load,
1089 .fields = (VMStateField[]) {
1090 VMSTATE_PCI_DEVICE(parent_obj, IVShmemState),
1091 VMSTATE_MSIX(parent_obj, IVShmemState),
1092 VMSTATE_UINT32(intrstatus, IVShmemState),
1093 VMSTATE_UINT32(intrmask, IVShmemState),
1094 VMSTATE_END_OF_LIST()
1098 static Property ivshmem_doorbell_properties[] = {
1099 DEFINE_PROP_CHR("chardev", IVShmemState, server_chr),
1100 DEFINE_PROP_UINT32("vectors", IVShmemState, vectors, 1),
1101 DEFINE_PROP_BIT("ioeventfd", IVShmemState, features, IVSHMEM_IOEVENTFD,
1102 true),
1103 DEFINE_PROP_ON_OFF_AUTO("master", IVShmemState, master, ON_OFF_AUTO_OFF),
1104 DEFINE_PROP_END_OF_LIST(),
1107 static void ivshmem_doorbell_init(Object *obj)
1109 IVShmemState *s = IVSHMEM_DOORBELL(obj);
1111 s->features |= (1 << IVSHMEM_MSI);
1112 s->legacy_size = SIZE_MAX; /* whatever the server sends */
1115 static void ivshmem_doorbell_realize(PCIDevice *dev, Error **errp)
1117 IVShmemState *s = IVSHMEM_COMMON(dev);
1119 if (!s->server_chr) {
1120 error_setg(errp, "You must specify a 'chardev'");
1121 return;
1124 ivshmem_common_realize(dev, errp);
1127 static void ivshmem_doorbell_class_init(ObjectClass *klass, void *data)
1129 DeviceClass *dc = DEVICE_CLASS(klass);
1130 PCIDeviceClass *k = PCI_DEVICE_CLASS(klass);
1132 k->realize = ivshmem_doorbell_realize;
1133 dc->props = ivshmem_doorbell_properties;
1134 dc->vmsd = &ivshmem_doorbell_vmsd;
1137 static const TypeInfo ivshmem_doorbell_info = {
1138 .name = TYPE_IVSHMEM_DOORBELL,
1139 .parent = TYPE_IVSHMEM_COMMON,
1140 .instance_size = sizeof(IVShmemState),
1141 .instance_init = ivshmem_doorbell_init,
1142 .class_init = ivshmem_doorbell_class_init,
1145 static int ivshmem_load_old(QEMUFile *f, void *opaque, int version_id)
1147 IVShmemState *s = opaque;
1148 PCIDevice *pdev = PCI_DEVICE(s);
1149 int ret;
1151 IVSHMEM_DPRINTF("ivshmem_load_old\n");
1153 if (version_id != 0) {
1154 return -EINVAL;
1157 ret = ivshmem_pre_load(s);
1158 if (ret) {
1159 return ret;
1162 ret = pci_device_load(pdev, f);
1163 if (ret) {
1164 return ret;
1167 if (ivshmem_has_feature(s, IVSHMEM_MSI)) {
1168 msix_load(pdev, f);
1169 ivshmem_msix_vector_use(s);
1170 } else {
1171 s->intrstatus = qemu_get_be32(f);
1172 s->intrmask = qemu_get_be32(f);
1175 return 0;
1178 static bool test_msix(void *opaque, int version_id)
1180 IVShmemState *s = opaque;
1182 return ivshmem_has_feature(s, IVSHMEM_MSI);
1185 static bool test_no_msix(void *opaque, int version_id)
1187 return !test_msix(opaque, version_id);
1190 static const VMStateDescription ivshmem_vmsd = {
1191 .name = "ivshmem",
1192 .version_id = 1,
1193 .minimum_version_id = 1,
1194 .pre_load = ivshmem_pre_load,
1195 .post_load = ivshmem_post_load,
1196 .fields = (VMStateField[]) {
1197 VMSTATE_PCI_DEVICE(parent_obj, IVShmemState),
1199 VMSTATE_MSIX_TEST(parent_obj, IVShmemState, test_msix),
1200 VMSTATE_UINT32_TEST(intrstatus, IVShmemState, test_no_msix),
1201 VMSTATE_UINT32_TEST(intrmask, IVShmemState, test_no_msix),
1203 VMSTATE_END_OF_LIST()
1205 .load_state_old = ivshmem_load_old,
1206 .minimum_version_id_old = 0
1209 static Property ivshmem_properties[] = {
1210 DEFINE_PROP_CHR("chardev", IVShmemState, server_chr),
1211 DEFINE_PROP_STRING("size", IVShmemState, sizearg),
1212 DEFINE_PROP_UINT32("vectors", IVShmemState, vectors, 1),
1213 DEFINE_PROP_BIT("ioeventfd", IVShmemState, features, IVSHMEM_IOEVENTFD,
1214 false),
1215 DEFINE_PROP_BIT("msi", IVShmemState, features, IVSHMEM_MSI, true),
1216 DEFINE_PROP_STRING("shm", IVShmemState, shmobj),
1217 DEFINE_PROP_STRING("role", IVShmemState, role),
1218 DEFINE_PROP_UINT32("use64", IVShmemState, not_legacy_32bit, 1),
1219 DEFINE_PROP_END_OF_LIST(),
1222 static void desugar_shm(IVShmemState *s)
1224 Object *obj;
1225 char *path;
1227 obj = object_new("memory-backend-file");
1228 path = g_strdup_printf("/dev/shm/%s", s->shmobj);
1229 object_property_set_str(obj, path, "mem-path", &error_abort);
1230 g_free(path);
1231 object_property_set_int(obj, s->legacy_size, "size", &error_abort);
1232 object_property_set_bool(obj, true, "share", &error_abort);
1233 object_property_add_child(OBJECT(s), "internal-shm-backend", obj,
1234 &error_abort);
1235 user_creatable_complete(obj, &error_abort);
1236 s->hostmem = MEMORY_BACKEND(obj);
1239 static void ivshmem_realize(PCIDevice *dev, Error **errp)
1241 IVShmemState *s = IVSHMEM_COMMON(dev);
1243 if (!qtest_enabled()) {
1244 error_report("ivshmem is deprecated, please use ivshmem-plain"
1245 " or ivshmem-doorbell instead");
1248 if (!!s->server_chr + !!s->shmobj != 1) {
1249 error_setg(errp, "You must specify either 'shm' or 'chardev'");
1250 return;
1253 if (s->sizearg == NULL) {
1254 s->legacy_size = 4 << 20; /* 4 MB default */
1255 } else {
1256 char *end;
1257 int64_t size = qemu_strtosz(s->sizearg, &end);
1258 if (size < 0 || (size_t)size != size || *end != '\0'
1259 || !is_power_of_2(size)) {
1260 error_setg(errp, "Invalid size %s", s->sizearg);
1261 return;
1263 s->legacy_size = size;
1266 /* check that role is reasonable */
1267 if (s->role) {
1268 if (strncmp(s->role, "peer", 5) == 0) {
1269 s->master = ON_OFF_AUTO_OFF;
1270 } else if (strncmp(s->role, "master", 7) == 0) {
1271 s->master = ON_OFF_AUTO_ON;
1272 } else {
1273 error_setg(errp, "'role' must be 'peer' or 'master'");
1274 return;
1276 } else {
1277 s->master = ON_OFF_AUTO_AUTO;
1280 if (s->shmobj) {
1281 desugar_shm(s);
1285 * Note: we don't use INTx with IVSHMEM_MSI at all, so this is a
1286 * bald-faced lie then. But it's a backwards compatible lie.
1288 pci_config_set_interrupt_pin(dev->config, 1);
1290 ivshmem_common_realize(dev, errp);
1293 static void ivshmem_class_init(ObjectClass *klass, void *data)
1295 DeviceClass *dc = DEVICE_CLASS(klass);
1296 PCIDeviceClass *k = PCI_DEVICE_CLASS(klass);
1298 k->realize = ivshmem_realize;
1299 k->revision = 0;
1300 dc->desc = "Inter-VM shared memory (legacy)";
1301 dc->props = ivshmem_properties;
1302 dc->vmsd = &ivshmem_vmsd;
1305 static const TypeInfo ivshmem_info = {
1306 .name = TYPE_IVSHMEM,
1307 .parent = TYPE_IVSHMEM_COMMON,
1308 .instance_size = sizeof(IVShmemState),
1309 .class_init = ivshmem_class_init,
1312 static void ivshmem_register_types(void)
1314 type_register_static(&ivshmem_common_info);
1315 type_register_static(&ivshmem_plain_info);
1316 type_register_static(&ivshmem_doorbell_info);
1317 type_register_static(&ivshmem_info);
1320 type_init(ivshmem_register_types)