xref: /openbmc/qemu/hw/s390x/s390-pci-vfio.c (revision 37fa32de707340f3a93959ad5a1ebc41ba1520ee)
1 /*
2  * s390 vfio-pci interfaces
3  *
4  * Copyright 2020 IBM Corp.
5  * Author(s): Matthew Rosato <mjrosato@linux.ibm.com>
6  *
7  * This work is licensed under the terms of the GNU GPL, version 2 or (at
8  * your option) any later version. See the COPYING file in the top-level
9  * directory.
10  */
11 
12 #include <sys/ioctl.h>
13 
14 #include "qemu/osdep.h"
15 #include "hw/s390x/s390-pci-bus.h"
16 #include "hw/s390x/s390-pci-vfio.h"
17 #include "hw/vfio/pci.h"
18 #include "hw/vfio/vfio-common.h"
19 
20 /*
21  * Get the current DMA available count from vfio.  Returns true if vfio is
22  * limiting DMA requests, false otherwise.  The current available count read
23  * from vfio is returned in avail.
24  */
25 bool s390_pci_update_dma_avail(int fd, unsigned int *avail)
26 {
27     g_autofree struct vfio_iommu_type1_info *info;
28     uint32_t argsz;
29 
30     assert(avail);
31 
32     argsz = sizeof(struct vfio_iommu_type1_info);
33     info = g_malloc0(argsz);
34 
35     /*
36      * If the specified argsz is not large enough to contain all capabilities
37      * it will be updated upon return from the ioctl.  Retry until we have
38      * a big enough buffer to hold the entire capability chain.
39      */
40 retry:
41     info->argsz = argsz;
42 
43     if (ioctl(fd, VFIO_IOMMU_GET_INFO, info)) {
44         return false;
45     }
46 
47     if (info->argsz > argsz) {
48         argsz = info->argsz;
49         info = g_realloc(info, argsz);
50         goto retry;
51     }
52 
53     /* If the capability exists, update with the current value */
54     return vfio_get_info_dma_avail(info, avail);
55 }
56 
57 S390PCIDMACount *s390_pci_start_dma_count(S390pciState *s,
58                                           S390PCIBusDevice *pbdev)
59 {
60     S390PCIDMACount *cnt;
61     uint32_t avail;
62     VFIOPCIDevice *vpdev = container_of(pbdev->pdev, VFIOPCIDevice, pdev);
63     int id;
64 
65     assert(vpdev);
66 
67     id = vpdev->vbasedev.group->container->fd;
68 
69     if (!s390_pci_update_dma_avail(id, &avail)) {
70         return NULL;
71     }
72 
73     QTAILQ_FOREACH(cnt, &s->zpci_dma_limit, link) {
74         if (cnt->id  == id) {
75             cnt->users++;
76             return cnt;
77         }
78     }
79 
80     cnt = g_new0(S390PCIDMACount, 1);
81     cnt->id = id;
82     cnt->users = 1;
83     cnt->avail = avail;
84     QTAILQ_INSERT_TAIL(&s->zpci_dma_limit, cnt, link);
85     return cnt;
86 }
87 
88 void s390_pci_end_dma_count(S390pciState *s, S390PCIDMACount *cnt)
89 {
90     assert(cnt);
91 
92     cnt->users--;
93     if (cnt->users == 0) {
94         QTAILQ_REMOVE(&s->zpci_dma_limit, cnt, link);
95     }
96 }
97