vfio: support PCI ioport
[dpdk.git] / lib / librte_eal / linuxapp / eal / eal_pci_vfio.c
1 /*-
2  *   BSD LICENSE
3  *
4  *   Copyright(c) 2010-2014 Intel Corporation. All rights reserved.
5  *   All rights reserved.
6  *
7  *   Redistribution and use in source and binary forms, with or without
8  *   modification, are permitted provided that the following conditions
9  *   are met:
10  *
11  *     * Redistributions of source code must retain the above copyright
12  *       notice, this list of conditions and the following disclaimer.
13  *     * Redistributions in binary form must reproduce the above copyright
14  *       notice, this list of conditions and the following disclaimer in
15  *       the documentation and/or other materials provided with the
16  *       distribution.
17  *     * Neither the name of Intel Corporation nor the names of its
18  *       contributors may be used to endorse or promote products derived
19  *       from this software without specific prior written permission.
20  *
21  *   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22  *   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23  *   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24  *   A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25  *   OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26  *   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27  *   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28  *   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29  *   THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30  *   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
31  *   OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32  */
33
34 #include <string.h>
35 #include <fcntl.h>
36 #include <linux/pci_regs.h>
37 #include <sys/eventfd.h>
38 #include <sys/socket.h>
39 #include <sys/ioctl.h>
40 #include <sys/mman.h>
41
42 #include <rte_log.h>
43 #include <rte_pci.h>
44 #include <rte_eal_memconfig.h>
45 #include <rte_malloc.h>
46 #include <eal_private.h>
47
48 #include "eal_filesystem.h"
49 #include "eal_pci_init.h"
50 #include "eal_vfio.h"
51
52 /**
53  * @file
54  * PCI probing under linux (VFIO version)
55  *
56  * This code tries to determine if the PCI device is bound to VFIO driver,
57  * and initialize it (map BARs, set up interrupts) if that's the case.
58  *
59  * This file is only compiled if CONFIG_RTE_EAL_VFIO is set to "y".
60  */
61
62 #ifdef VFIO_PRESENT
63
64 #define PAGE_SIZE   (sysconf(_SC_PAGESIZE))
65 #define PAGE_MASK   (~(PAGE_SIZE - 1))
66
67 static struct rte_tailq_elem rte_vfio_tailq = {
68         .name = "VFIO_RESOURCE_LIST",
69 };
70 EAL_REGISTER_TAILQ(rte_vfio_tailq)
71
72 #define VFIO_DIR "/dev/vfio"
73 #define VFIO_CONTAINER_PATH "/dev/vfio/vfio"
74 #define VFIO_GROUP_FMT "/dev/vfio/%u"
75 #define VFIO_NOIOMMU_GROUP_FMT "/dev/vfio/noiommu-%u"
76 #define VFIO_GET_REGION_ADDR(x) ((uint64_t) x << 40ULL)
77 #define VFIO_GET_REGION_IDX(x) (x >> 40)
78
79 /* per-process VFIO config */
80 static struct vfio_config vfio_cfg;
81
82 /* DMA mapping function prototype.
83  * Takes VFIO container fd as a parameter.
84  * Returns 0 on success, -1 on error.
85  * */
86 typedef int (*vfio_dma_func_t)(int);
87
88 struct vfio_iommu_type {
89         int type_id;
90         const char *name;
91         vfio_dma_func_t dma_map_func;
92 };
93
94 static int vfio_type1_dma_map(int);
95 static int vfio_noiommu_dma_map(int);
96
97 /* IOMMU types we support */
98 static const struct vfio_iommu_type iommu_types[] = {
99         /* x86 IOMMU, otherwise known as type 1 */
100         { RTE_VFIO_TYPE1, "Type 1", &vfio_type1_dma_map},
101         /* IOMMU-less mode */
102         { RTE_VFIO_NOIOMMU, "No-IOMMU", &vfio_noiommu_dma_map},
103 };
104
105 int
106 vfio_type1_dma_map(int vfio_container_fd)
107 {
108         const struct rte_memseg *ms = rte_eal_get_physmem_layout();
109         int i, ret;
110
111         /* map all DPDK segments for DMA. use 1:1 PA to IOVA mapping */
112         for (i = 0; i < RTE_MAX_MEMSEG; i++) {
113                 struct vfio_iommu_type1_dma_map dma_map;
114
115                 if (ms[i].addr == NULL)
116                         break;
117
118                 memset(&dma_map, 0, sizeof(dma_map));
119                 dma_map.argsz = sizeof(struct vfio_iommu_type1_dma_map);
120                 dma_map.vaddr = ms[i].addr_64;
121                 dma_map.size = ms[i].len;
122                 dma_map.iova = ms[i].phys_addr;
123                 dma_map.flags = VFIO_DMA_MAP_FLAG_READ | VFIO_DMA_MAP_FLAG_WRITE;
124
125                 ret = ioctl(vfio_container_fd, VFIO_IOMMU_MAP_DMA, &dma_map);
126
127                 if (ret) {
128                         RTE_LOG(ERR, EAL, "  cannot set up DMA remapping, "
129                                         "error %i (%s)\n", errno, strerror(errno));
130                         return -1;
131                 }
132         }
133
134         return 0;
135 }
136
137 int
138 vfio_noiommu_dma_map(int __rte_unused vfio_container_fd)
139 {
140         /* No-IOMMU mode does not need DMA mapping */
141         return 0;
142 }
143
144 int
145 pci_vfio_read_config(const struct rte_intr_handle *intr_handle,
146                     void *buf, size_t len, off_t offs)
147 {
148         return pread64(intr_handle->vfio_dev_fd, buf, len,
149                VFIO_GET_REGION_ADDR(VFIO_PCI_CONFIG_REGION_INDEX) + offs);
150 }
151
152 int
153 pci_vfio_write_config(const struct rte_intr_handle *intr_handle,
154                     const void *buf, size_t len, off_t offs)
155 {
156         return pwrite64(intr_handle->vfio_dev_fd, buf, len,
157                VFIO_GET_REGION_ADDR(VFIO_PCI_CONFIG_REGION_INDEX) + offs);
158 }
159
160 /* get PCI BAR number where MSI-X interrupts are */
161 static int
162 pci_vfio_get_msix_bar(int fd, int *msix_bar, uint32_t *msix_table_offset,
163                       uint32_t *msix_table_size)
164 {
165         int ret;
166         uint32_t reg;
167         uint16_t flags;
168         uint8_t cap_id, cap_offset;
169
170         /* read PCI capability pointer from config space */
171         ret = pread64(fd, &reg, sizeof(reg),
172                         VFIO_GET_REGION_ADDR(VFIO_PCI_CONFIG_REGION_INDEX) +
173                         PCI_CAPABILITY_LIST);
174         if (ret != sizeof(reg)) {
175                 RTE_LOG(ERR, EAL, "Cannot read capability pointer from PCI "
176                                 "config space!\n");
177                 return -1;
178         }
179
180         /* we need first byte */
181         cap_offset = reg & 0xFF;
182
183         while (cap_offset) {
184
185                 /* read PCI capability ID */
186                 ret = pread64(fd, &reg, sizeof(reg),
187                                 VFIO_GET_REGION_ADDR(VFIO_PCI_CONFIG_REGION_INDEX) +
188                                 cap_offset);
189                 if (ret != sizeof(reg)) {
190                         RTE_LOG(ERR, EAL, "Cannot read capability ID from PCI "
191                                         "config space!\n");
192                         return -1;
193                 }
194
195                 /* we need first byte */
196                 cap_id = reg & 0xFF;
197
198                 /* if we haven't reached MSI-X, check next capability */
199                 if (cap_id != PCI_CAP_ID_MSIX) {
200                         ret = pread64(fd, &reg, sizeof(reg),
201                                         VFIO_GET_REGION_ADDR(VFIO_PCI_CONFIG_REGION_INDEX) +
202                                         cap_offset);
203                         if (ret != sizeof(reg)) {
204                                 RTE_LOG(ERR, EAL, "Cannot read capability pointer from PCI "
205                                                 "config space!\n");
206                                 return -1;
207                         }
208
209                         /* we need second byte */
210                         cap_offset = (reg & 0xFF00) >> 8;
211
212                         continue;
213                 }
214                 /* else, read table offset */
215                 else {
216                         /* table offset resides in the next 4 bytes */
217                         ret = pread64(fd, &reg, sizeof(reg),
218                                         VFIO_GET_REGION_ADDR(VFIO_PCI_CONFIG_REGION_INDEX) +
219                                         cap_offset + 4);
220                         if (ret != sizeof(reg)) {
221                                 RTE_LOG(ERR, EAL, "Cannot read table offset from PCI config "
222                                                 "space!\n");
223                                 return -1;
224                         }
225
226                         ret = pread64(fd, &flags, sizeof(flags),
227                                         VFIO_GET_REGION_ADDR(VFIO_PCI_CONFIG_REGION_INDEX) +
228                                         cap_offset + 2);
229                         if (ret != sizeof(flags)) {
230                                 RTE_LOG(ERR, EAL, "Cannot read table flags from PCI config "
231                                                 "space!\n");
232                                 return -1;
233                         }
234
235                         *msix_bar = reg & RTE_PCI_MSIX_TABLE_BIR;
236                         *msix_table_offset = reg & RTE_PCI_MSIX_TABLE_OFFSET;
237                         *msix_table_size = 16 * (1 + (flags & RTE_PCI_MSIX_FLAGS_QSIZE));
238
239                         return 0;
240                 }
241         }
242         return 0;
243 }
244
245 /* set PCI bus mastering */
246 static int
247 pci_vfio_set_bus_master(int dev_fd)
248 {
249         uint16_t reg;
250         int ret;
251
252         ret = pread64(dev_fd, &reg, sizeof(reg),
253                         VFIO_GET_REGION_ADDR(VFIO_PCI_CONFIG_REGION_INDEX) +
254                         PCI_COMMAND);
255         if (ret != sizeof(reg)) {
256                 RTE_LOG(ERR, EAL, "Cannot read command from PCI config space!\n");
257                 return -1;
258         }
259
260         /* set the master bit */
261         reg |= PCI_COMMAND_MASTER;
262
263         ret = pwrite64(dev_fd, &reg, sizeof(reg),
264                         VFIO_GET_REGION_ADDR(VFIO_PCI_CONFIG_REGION_INDEX) +
265                         PCI_COMMAND);
266
267         if (ret != sizeof(reg)) {
268                 RTE_LOG(ERR, EAL, "Cannot write command to PCI config space!\n");
269                 return -1;
270         }
271
272         return 0;
273 }
274
275 /* pick IOMMU type. returns a pointer to vfio_iommu_type or NULL for error */
276 static const struct vfio_iommu_type *
277 pci_vfio_set_iommu_type(int vfio_container_fd) {
278         unsigned idx;
279         for (idx = 0; idx < RTE_DIM(iommu_types); idx++) {
280                 const struct vfio_iommu_type *t = &iommu_types[idx];
281
282                 int ret = ioctl(vfio_container_fd, VFIO_SET_IOMMU,
283                                 t->type_id);
284                 if (!ret) {
285                         RTE_LOG(NOTICE, EAL, "  using IOMMU type %d (%s)\n",
286                                         t->type_id, t->name);
287                         return t;
288                 }
289                 /* not an error, there may be more supported IOMMU types */
290                 RTE_LOG(DEBUG, EAL, "  set IOMMU type %d (%s) failed, "
291                                 "error %i (%s)\n", t->type_id, t->name, errno,
292                                 strerror(errno));
293         }
294         /* if we didn't find a suitable IOMMU type, fail */
295         return NULL;
296 }
297
298 /* check if we have any supported extensions */
299 static int
300 pci_vfio_has_supported_extensions(int vfio_container_fd) {
301         int ret;
302         unsigned idx, n_extensions = 0;
303         for (idx = 0; idx < RTE_DIM(iommu_types); idx++) {
304                 const struct vfio_iommu_type *t = &iommu_types[idx];
305
306                 ret = ioctl(vfio_container_fd, VFIO_CHECK_EXTENSION,
307                                 t->type_id);
308                 if (ret < 0) {
309                         RTE_LOG(ERR, EAL, "  could not get IOMMU type, "
310                                 "error %i (%s)\n", errno,
311                                 strerror(errno));
312                         close(vfio_container_fd);
313                         return -1;
314                 } else if (ret == 1) {
315                         /* we found a supported extension */
316                         n_extensions++;
317                 }
318                 RTE_LOG(DEBUG, EAL, "  IOMMU type %d (%s) is %s\n",
319                                 t->type_id, t->name,
320                                 ret ? "supported" : "not supported");
321         }
322
323         /* if we didn't find any supported IOMMU types, fail */
324         if (!n_extensions) {
325                 close(vfio_container_fd);
326                 return -1;
327         }
328
329         return 0;
330 }
331
332 /* set up interrupt support (but not enable interrupts) */
333 static int
334 pci_vfio_setup_interrupts(struct rte_pci_device *dev, int vfio_dev_fd)
335 {
336         int i, ret, intr_idx;
337
338         /* default to invalid index */
339         intr_idx = VFIO_PCI_NUM_IRQS;
340
341         /* get interrupt type from internal config (MSI-X by default, can be
342          * overriden from the command line
343          */
344         switch (internal_config.vfio_intr_mode) {
345         case RTE_INTR_MODE_MSIX:
346                 intr_idx = VFIO_PCI_MSIX_IRQ_INDEX;
347                 break;
348         case RTE_INTR_MODE_MSI:
349                 intr_idx = VFIO_PCI_MSI_IRQ_INDEX;
350                 break;
351         case RTE_INTR_MODE_LEGACY:
352                 intr_idx = VFIO_PCI_INTX_IRQ_INDEX;
353                 break;
354         /* don't do anything if we want to automatically determine interrupt type */
355         case RTE_INTR_MODE_NONE:
356                 break;
357         default:
358                 RTE_LOG(ERR, EAL, "  unknown default interrupt type!\n");
359                 return -1;
360         }
361
362         /* start from MSI-X interrupt type */
363         for (i = VFIO_PCI_MSIX_IRQ_INDEX; i >= 0; i--) {
364                 struct vfio_irq_info irq = { .argsz = sizeof(irq) };
365                 int fd = -1;
366
367                 /* skip interrupt modes we don't want */
368                 if (internal_config.vfio_intr_mode != RTE_INTR_MODE_NONE &&
369                                 i != intr_idx)
370                         continue;
371
372                 irq.index = i;
373
374                 ret = ioctl(vfio_dev_fd, VFIO_DEVICE_GET_IRQ_INFO, &irq);
375                 if (ret < 0) {
376                         RTE_LOG(ERR, EAL, "  cannot get IRQ info, "
377                                         "error %i (%s)\n", errno, strerror(errno));
378                         return -1;
379                 }
380
381                 /* if this vector cannot be used with eventfd, fail if we explicitly
382                  * specified interrupt type, otherwise continue */
383                 if ((irq.flags & VFIO_IRQ_INFO_EVENTFD) == 0) {
384                         if (internal_config.vfio_intr_mode != RTE_INTR_MODE_NONE) {
385                                 RTE_LOG(ERR, EAL,
386                                                 "  interrupt vector does not support eventfd!\n");
387                                 return -1;
388                         } else
389                                 continue;
390                 }
391
392                 /* set up an eventfd for interrupts */
393                 fd = eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC);
394                 if (fd < 0) {
395                         RTE_LOG(ERR, EAL, "  cannot set up eventfd, "
396                                         "error %i (%s)\n", errno, strerror(errno));
397                         return -1;
398                 }
399
400                 dev->intr_handle.fd = fd;
401                 dev->intr_handle.vfio_dev_fd = vfio_dev_fd;
402
403                 switch (i) {
404                 case VFIO_PCI_MSIX_IRQ_INDEX:
405                         internal_config.vfio_intr_mode = RTE_INTR_MODE_MSIX;
406                         dev->intr_handle.type = RTE_INTR_HANDLE_VFIO_MSIX;
407                         break;
408                 case VFIO_PCI_MSI_IRQ_INDEX:
409                         internal_config.vfio_intr_mode = RTE_INTR_MODE_MSI;
410                         dev->intr_handle.type = RTE_INTR_HANDLE_VFIO_MSI;
411                         break;
412                 case VFIO_PCI_INTX_IRQ_INDEX:
413                         internal_config.vfio_intr_mode = RTE_INTR_MODE_LEGACY;
414                         dev->intr_handle.type = RTE_INTR_HANDLE_VFIO_LEGACY;
415                         break;
416                 default:
417                         RTE_LOG(ERR, EAL, "  unknown interrupt type!\n");
418                         return -1;
419                 }
420
421                 return 0;
422         }
423
424         /* if we're here, we haven't found a suitable interrupt vector */
425         return -1;
426 }
427
428 /* open container fd or get an existing one */
429 int
430 pci_vfio_get_container_fd(void)
431 {
432         int ret, vfio_container_fd;
433
434         /* if we're in a primary process, try to open the container */
435         if (internal_config.process_type == RTE_PROC_PRIMARY) {
436                 vfio_container_fd = open(VFIO_CONTAINER_PATH, O_RDWR);
437                 if (vfio_container_fd < 0) {
438                         RTE_LOG(ERR, EAL, "  cannot open VFIO container, "
439                                         "error %i (%s)\n", errno, strerror(errno));
440                         return -1;
441                 }
442
443                 /* check VFIO API version */
444                 ret = ioctl(vfio_container_fd, VFIO_GET_API_VERSION);
445                 if (ret != VFIO_API_VERSION) {
446                         if (ret < 0)
447                                 RTE_LOG(ERR, EAL, "  could not get VFIO API version, "
448                                                 "error %i (%s)\n", errno, strerror(errno));
449                         else
450                                 RTE_LOG(ERR, EAL, "  unsupported VFIO API version!\n");
451                         close(vfio_container_fd);
452                         return -1;
453                 }
454
455                 ret = pci_vfio_has_supported_extensions(vfio_container_fd);
456                 if (ret) {
457                         RTE_LOG(ERR, EAL, "  no supported IOMMU "
458                                         "extensions found!\n");
459                         return -1;
460                 }
461
462                 return vfio_container_fd;
463         } else {
464                 /*
465                  * if we're in a secondary process, request container fd from the
466                  * primary process via our socket
467                  */
468                 int socket_fd;
469
470                 socket_fd = vfio_mp_sync_connect_to_primary();
471                 if (socket_fd < 0) {
472                         RTE_LOG(ERR, EAL, "  cannot connect to primary process!\n");
473                         return -1;
474                 }
475                 if (vfio_mp_sync_send_request(socket_fd, SOCKET_REQ_CONTAINER) < 0) {
476                         RTE_LOG(ERR, EAL, "  cannot request container fd!\n");
477                         close(socket_fd);
478                         return -1;
479                 }
480                 vfio_container_fd = vfio_mp_sync_receive_fd(socket_fd);
481                 if (vfio_container_fd < 0) {
482                         RTE_LOG(ERR, EAL, "  cannot get container fd!\n");
483                         close(socket_fd);
484                         return -1;
485                 }
486                 close(socket_fd);
487                 return vfio_container_fd;
488         }
489
490         return -1;
491 }
492
493 /* open group fd or get an existing one */
494 int
495 pci_vfio_get_group_fd(int iommu_group_no)
496 {
497         int i;
498         int vfio_group_fd;
499         char filename[PATH_MAX];
500
501         /* check if we already have the group descriptor open */
502         for (i = 0; i < vfio_cfg.vfio_group_idx; i++)
503                 if (vfio_cfg.vfio_groups[i].group_no == iommu_group_no)
504                         return vfio_cfg.vfio_groups[i].fd;
505
506         /* if primary, try to open the group */
507         if (internal_config.process_type == RTE_PROC_PRIMARY) {
508                 /* try regular group format */
509                 snprintf(filename, sizeof(filename),
510                                  VFIO_GROUP_FMT, iommu_group_no);
511                 vfio_group_fd = open(filename, O_RDWR);
512                 if (vfio_group_fd < 0) {
513                         /* if file not found, it's not an error */
514                         if (errno != ENOENT) {
515                                 RTE_LOG(ERR, EAL, "Cannot open %s: %s\n", filename,
516                                                 strerror(errno));
517                                 return -1;
518                         }
519
520                         /* special case: try no-IOMMU path as well */
521                         snprintf(filename, sizeof(filename),
522                                         VFIO_NOIOMMU_GROUP_FMT, iommu_group_no);
523                         vfio_group_fd = open(filename, O_RDWR);
524                         if (vfio_group_fd < 0) {
525                                 if (errno != ENOENT) {
526                                         RTE_LOG(ERR, EAL, "Cannot open %s: %s\n", filename,
527                                                         strerror(errno));
528                                         return -1;
529                                 }
530                                 return 0;
531                         }
532                         /* noiommu group found */
533                 }
534
535                 /* if the fd is valid, create a new group for it */
536                 if (vfio_cfg.vfio_group_idx == VFIO_MAX_GROUPS) {
537                         RTE_LOG(ERR, EAL, "Maximum number of VFIO groups reached!\n");
538                         return -1;
539                 }
540                 vfio_cfg.vfio_groups[vfio_cfg.vfio_group_idx].group_no = iommu_group_no;
541                 vfio_cfg.vfio_groups[vfio_cfg.vfio_group_idx].fd = vfio_group_fd;
542                 return vfio_group_fd;
543         }
544         /* if we're in a secondary process, request group fd from the primary
545          * process via our socket
546          */
547         else {
548                 int socket_fd, ret;
549
550                 socket_fd = vfio_mp_sync_connect_to_primary();
551
552                 if (socket_fd < 0) {
553                         RTE_LOG(ERR, EAL, "  cannot connect to primary process!\n");
554                         return -1;
555                 }
556                 if (vfio_mp_sync_send_request(socket_fd, SOCKET_REQ_GROUP) < 0) {
557                         RTE_LOG(ERR, EAL, "  cannot request container fd!\n");
558                         close(socket_fd);
559                         return -1;
560                 }
561                 if (vfio_mp_sync_send_request(socket_fd, iommu_group_no) < 0) {
562                         RTE_LOG(ERR, EAL, "  cannot send group number!\n");
563                         close(socket_fd);
564                         return -1;
565                 }
566                 ret = vfio_mp_sync_receive_request(socket_fd);
567                 switch (ret) {
568                 case SOCKET_NO_FD:
569                         close(socket_fd);
570                         return 0;
571                 case SOCKET_OK:
572                         vfio_group_fd = vfio_mp_sync_receive_fd(socket_fd);
573                         /* if we got the fd, return it */
574                         if (vfio_group_fd > 0) {
575                                 close(socket_fd);
576                                 return vfio_group_fd;
577                         }
578                         /* fall-through on error */
579                 default:
580                         RTE_LOG(ERR, EAL, "  cannot get container fd!\n");
581                         close(socket_fd);
582                         return -1;
583                 }
584         }
585         return -1;
586 }
587
588 /* parse IOMMU group number for a PCI device
589  * returns 1 on success, -1 for errors, 0 for non-existent group
590  */
591 static int
592 pci_vfio_get_group_no(const char *pci_addr, int *iommu_group_no)
593 {
594         char linkname[PATH_MAX];
595         char filename[PATH_MAX];
596         char *tok[16], *group_tok, *end;
597         int ret;
598
599         memset(linkname, 0, sizeof(linkname));
600         memset(filename, 0, sizeof(filename));
601
602         /* try to find out IOMMU group for this device */
603         snprintf(linkname, sizeof(linkname),
604                          SYSFS_PCI_DEVICES "/%s/iommu_group", pci_addr);
605
606         ret = readlink(linkname, filename, sizeof(filename));
607
608         /* if the link doesn't exist, no VFIO for us */
609         if (ret < 0)
610                 return 0;
611
612         ret = rte_strsplit(filename, sizeof(filename),
613                         tok, RTE_DIM(tok), '/');
614
615         if (ret <= 0) {
616                 RTE_LOG(ERR, EAL, "  %s cannot get IOMMU group\n", pci_addr);
617                 return -1;
618         }
619
620         /* IOMMU group is always the last token */
621         errno = 0;
622         group_tok = tok[ret - 1];
623         end = group_tok;
624         *iommu_group_no = strtol(group_tok, &end, 10);
625         if ((end != group_tok && *end != '\0') || errno != 0) {
626                 RTE_LOG(ERR, EAL, "  %s error parsing IOMMU number!\n", pci_addr);
627                 return -1;
628         }
629
630         return 1;
631 }
632
633 static void
634 clear_current_group(void)
635 {
636         vfio_cfg.vfio_groups[vfio_cfg.vfio_group_idx].group_no = 0;
637         vfio_cfg.vfio_groups[vfio_cfg.vfio_group_idx].fd = -1;
638 }
639
640
641 /*
642  * map the PCI resources of a PCI device in virtual memory (VFIO version).
643  * primary and secondary processes follow almost exactly the same path
644  */
645 int
646 pci_vfio_map_resource(struct rte_pci_device *dev)
647 {
648         struct vfio_group_status group_status = {
649                         .argsz = sizeof(group_status)
650         };
651         struct vfio_device_info device_info = { .argsz = sizeof(device_info) };
652         int vfio_group_fd, vfio_dev_fd;
653         int iommu_group_no;
654         char pci_addr[PATH_MAX] = {0};
655         struct rte_pci_addr *loc = &dev->addr;
656         int i, ret, msix_bar;
657         struct mapped_pci_resource *vfio_res = NULL;
658         struct mapped_pci_res_list *vfio_res_list = RTE_TAILQ_CAST(rte_vfio_tailq.head, mapped_pci_res_list);
659
660         struct pci_map *maps;
661         uint32_t msix_table_offset = 0;
662         uint32_t msix_table_size = 0;
663         uint32_t ioport_bar;
664
665         dev->intr_handle.fd = -1;
666         dev->intr_handle.type = RTE_INTR_HANDLE_UNKNOWN;
667
668         /* store PCI address string */
669         snprintf(pci_addr, sizeof(pci_addr), PCI_PRI_FMT,
670                         loc->domain, loc->bus, loc->devid, loc->function);
671
672         /* get group number */
673         ret = pci_vfio_get_group_no(pci_addr, &iommu_group_no);
674         if (ret == 0) {
675                 RTE_LOG(WARNING, EAL, "  %s not managed by VFIO driver, skipping\n",
676                         pci_addr);
677                 return 1;
678         }
679
680         /* if negative, something failed */
681         if (ret < 0)
682                 return -1;
683
684         /* get the actual group fd */
685         vfio_group_fd = pci_vfio_get_group_fd(iommu_group_no);
686         if (vfio_group_fd < 0)
687                 return -1;
688
689         /* store group fd */
690         vfio_cfg.vfio_groups[vfio_cfg.vfio_group_idx].group_no = iommu_group_no;
691         vfio_cfg.vfio_groups[vfio_cfg.vfio_group_idx].fd = vfio_group_fd;
692
693         /* if group_fd == 0, that means the device isn't managed by VFIO */
694         if (vfio_group_fd == 0) {
695                 RTE_LOG(WARNING, EAL, "  %s not managed by VFIO driver, skipping\n",
696                                 pci_addr);
697                 /* we store 0 as group fd to distinguish between existing but
698                  * unbound VFIO groups, and groups that don't exist at all.
699                  */
700                 vfio_cfg.vfio_group_idx++;
701                 return 1;
702         }
703
704         /*
705          * at this point, we know at least one port on this device is bound to VFIO,
706          * so we can proceed to try and set this particular port up
707          */
708
709         /* check if the group is viable */
710         ret = ioctl(vfio_group_fd, VFIO_GROUP_GET_STATUS, &group_status);
711         if (ret) {
712                 RTE_LOG(ERR, EAL, "  %s cannot get group status, "
713                                 "error %i (%s)\n", pci_addr, errno, strerror(errno));
714                 close(vfio_group_fd);
715                 clear_current_group();
716                 return -1;
717         } else if (!(group_status.flags & VFIO_GROUP_FLAGS_VIABLE)) {
718                 RTE_LOG(ERR, EAL, "  %s VFIO group is not viable!\n", pci_addr);
719                 close(vfio_group_fd);
720                 clear_current_group();
721                 return -1;
722         }
723
724         /*
725          * at this point, we know that this group is viable (meaning, all devices
726          * are either bound to VFIO or not bound to anything)
727          */
728
729         /* check if group does not have a container yet */
730         if (!(group_status.flags & VFIO_GROUP_FLAGS_CONTAINER_SET)) {
731
732                 /* add group to a container */
733                 ret = ioctl(vfio_group_fd, VFIO_GROUP_SET_CONTAINER,
734                                 &vfio_cfg.vfio_container_fd);
735                 if (ret) {
736                         RTE_LOG(ERR, EAL, "  %s cannot add VFIO group to container, "
737                                         "error %i (%s)\n", pci_addr, errno, strerror(errno));
738                         close(vfio_group_fd);
739                         clear_current_group();
740                         return -1;
741                 }
742                 /*
743                  * at this point we know that this group has been successfully
744                  * initialized, so we increment vfio_group_idx to indicate that we can
745                  * add new groups.
746                  */
747                 vfio_cfg.vfio_group_idx++;
748         }
749
750         /*
751          * pick an IOMMU type and set up DMA mappings for container
752          *
753          * needs to be done only once, only when at least one group is assigned to
754          * a container and only in primary process
755          */
756         if (internal_config.process_type == RTE_PROC_PRIMARY &&
757                         vfio_cfg.vfio_container_has_dma == 0) {
758                 /* select an IOMMU type which we will be using */
759                 const struct vfio_iommu_type *t =
760                                 pci_vfio_set_iommu_type(vfio_cfg.vfio_container_fd);
761                 if (!t) {
762                         RTE_LOG(ERR, EAL, "  %s failed to select IOMMU type\n", pci_addr);
763                         return -1;
764                 }
765                 ret = t->dma_map_func(vfio_cfg.vfio_container_fd);
766                 if (ret) {
767                         RTE_LOG(ERR, EAL, "  %s DMA remapping failed, "
768                                         "error %i (%s)\n", pci_addr, errno, strerror(errno));
769                         return -1;
770                 }
771                 vfio_cfg.vfio_container_has_dma = 1;
772         }
773
774         /* get a file descriptor for the device */
775         vfio_dev_fd = ioctl(vfio_group_fd, VFIO_GROUP_GET_DEVICE_FD, pci_addr);
776         if (vfio_dev_fd < 0) {
777                 /* if we cannot get a device fd, this simply means that this
778                  * particular port is not bound to VFIO
779                  */
780                 RTE_LOG(WARNING, EAL, "  %s not managed by VFIO driver, skipping\n",
781                                 pci_addr);
782                 return 1;
783         }
784
785         /* test and setup the device */
786         ret = ioctl(vfio_dev_fd, VFIO_DEVICE_GET_INFO, &device_info);
787         if (ret) {
788                 RTE_LOG(ERR, EAL, "  %s cannot get device info, "
789                                 "error %i (%s)\n", pci_addr, errno, strerror(errno));
790                 close(vfio_dev_fd);
791                 return -1;
792         }
793
794         /* get MSI-X BAR, if any (we have to know where it is because we can't
795          * easily mmap it when using VFIO) */
796         msix_bar = -1;
797         ret = pci_vfio_get_msix_bar(vfio_dev_fd, &msix_bar,
798                                     &msix_table_offset, &msix_table_size);
799         if (ret < 0) {
800                 RTE_LOG(ERR, EAL, "  %s cannot get MSI-X BAR number!\n", pci_addr);
801                 close(vfio_dev_fd);
802                 return -1;
803         }
804
805         /* if we're in a primary process, allocate vfio_res and get region info */
806         if (internal_config.process_type == RTE_PROC_PRIMARY) {
807                 vfio_res = rte_zmalloc("VFIO_RES", sizeof(*vfio_res), 0);
808                 if (vfio_res == NULL) {
809                         RTE_LOG(ERR, EAL,
810                                 "%s(): cannot store uio mmap details\n", __func__);
811                         close(vfio_dev_fd);
812                         return -1;
813                 }
814                 memcpy(&vfio_res->pci_addr, &dev->addr, sizeof(vfio_res->pci_addr));
815
816                 /* get number of registers (up to BAR5) */
817                 vfio_res->nb_maps = RTE_MIN((int) device_info.num_regions,
818                                 VFIO_PCI_BAR5_REGION_INDEX + 1);
819         } else {
820                 /* if we're in a secondary process, just find our tailq entry */
821                 TAILQ_FOREACH(vfio_res, vfio_res_list, next) {
822                         if (memcmp(&vfio_res->pci_addr, &dev->addr, sizeof(dev->addr)))
823                                 continue;
824                         break;
825                 }
826                 /* if we haven't found our tailq entry, something's wrong */
827                 if (vfio_res == NULL) {
828                         RTE_LOG(ERR, EAL, "  %s cannot find TAILQ entry for PCI device!\n",
829                                         pci_addr);
830                         close(vfio_dev_fd);
831                         return -1;
832                 }
833         }
834
835         /* map BARs */
836         maps = vfio_res->maps;
837
838         for (i = 0; i < (int) vfio_res->nb_maps; i++) {
839                 struct vfio_region_info reg = { .argsz = sizeof(reg) };
840                 void *bar_addr;
841                 struct memreg {
842                         unsigned long offset, size;
843                 } memreg[2] = {};
844
845                 reg.index = i;
846
847                 ret = ioctl(vfio_dev_fd, VFIO_DEVICE_GET_REGION_INFO, &reg);
848
849                 if (ret) {
850                         RTE_LOG(ERR, EAL, "  %s cannot get device region info "
851                                         "error %i (%s)\n", pci_addr, errno, strerror(errno));
852                         close(vfio_dev_fd);
853                         if (internal_config.process_type == RTE_PROC_PRIMARY)
854                                 rte_free(vfio_res);
855                         return -1;
856                 }
857
858                 /* chk for io port region */
859                 ret = pread64(vfio_dev_fd, &ioport_bar, sizeof(ioport_bar),
860                               VFIO_GET_REGION_ADDR(VFIO_PCI_CONFIG_REGION_INDEX)
861                               + PCI_BASE_ADDRESS_0 + i*4);
862
863                 if (ret != sizeof(ioport_bar)) {
864                         RTE_LOG(ERR, EAL,
865                                 "Cannot read command (%x) from config space!\n",
866                                 PCI_BASE_ADDRESS_0 + i*4);
867                         return -1;
868                 }
869
870                 if (ioport_bar & PCI_BASE_ADDRESS_SPACE_IO) {
871                         RTE_LOG(INFO, EAL,
872                                 "Ignore mapping IO port bar(%d) addr: %x\n",
873                                  i, ioport_bar);
874                         continue;
875                 }
876
877                 /* skip non-mmapable BARs */
878                 if ((reg.flags & VFIO_REGION_INFO_FLAG_MMAP) == 0)
879                         continue;
880
881                 if (i == msix_bar) {
882                         /*
883                          * VFIO will not let us map the MSI-X table,
884                          * but we can map around it.
885                          */
886                         uint32_t table_start = msix_table_offset;
887                         uint32_t table_end = table_start + msix_table_size;
888                         table_end = (table_end + ~PAGE_MASK) & PAGE_MASK;
889                         table_start &= PAGE_MASK;
890
891                         if (table_start == 0 && table_end >= reg.size) {
892                                 /* Cannot map this BAR */
893                                 RTE_LOG(DEBUG, EAL, "Skipping BAR %d\n", i);
894                                 continue;
895                         } else {
896                                 memreg[0].offset = reg.offset;
897                                 memreg[0].size = table_start;
898                                 memreg[1].offset = table_end;
899                                 memreg[1].size = reg.size - table_end;
900
901                                 RTE_LOG(DEBUG, EAL,
902                                         "Trying to map BAR %d that contains the MSI-X "
903                                         "table. Trying offsets: "
904                                         "0x%04lx:0x%04lx, 0x%04lx:0x%04lx\n", i,
905                                         memreg[0].offset, memreg[0].size,
906                                         memreg[1].offset, memreg[1].size);
907                         }
908                 } else {
909                         memreg[0].offset = reg.offset;
910                         memreg[0].size = reg.size;
911                 }
912
913                 /* try to figure out an address */
914                 if (internal_config.process_type == RTE_PROC_PRIMARY) {
915                         /* try mapping somewhere close to the end of hugepages */
916                         if (pci_map_addr == NULL)
917                                 pci_map_addr = pci_find_max_end_va();
918
919                         bar_addr = pci_map_addr;
920                         pci_map_addr = RTE_PTR_ADD(bar_addr, (size_t) reg.size);
921                 } else {
922                         bar_addr = maps[i].addr;
923                 }
924
925                 /* reserve the address using an inaccessible mapping */
926                 bar_addr = mmap(bar_addr, reg.size, 0, MAP_PRIVATE |
927                                 MAP_ANONYMOUS, -1, 0);
928                 if (bar_addr != MAP_FAILED) {
929                         void *map_addr = NULL;
930                         if (memreg[0].size) {
931                                 /* actual map of first part */
932                                 map_addr = pci_map_resource(bar_addr, vfio_dev_fd,
933                                                             memreg[0].offset,
934                                                             memreg[0].size,
935                                                             MAP_FIXED);
936                         }
937
938                         /* if there's a second part, try to map it */
939                         if (map_addr != MAP_FAILED
940                             && memreg[1].offset && memreg[1].size) {
941                                 void *second_addr = RTE_PTR_ADD(bar_addr, memreg[1].offset);
942                                 map_addr = pci_map_resource(second_addr,
943                                                             vfio_dev_fd, memreg[1].offset,
944                                                             memreg[1].size,
945                                                             MAP_FIXED);
946                         }
947
948                         if (map_addr == MAP_FAILED || !map_addr) {
949                                 munmap(bar_addr, reg.size);
950                                 bar_addr = MAP_FAILED;
951                         }
952                 }
953
954                 if (bar_addr == MAP_FAILED ||
955                                 (internal_config.process_type == RTE_PROC_SECONDARY &&
956                                                 bar_addr != maps[i].addr)) {
957                         RTE_LOG(ERR, EAL, "  %s mapping BAR%i failed: %s\n", pci_addr, i,
958                                         strerror(errno));
959                         close(vfio_dev_fd);
960                         if (internal_config.process_type == RTE_PROC_PRIMARY)
961                                 rte_free(vfio_res);
962                         return -1;
963                 }
964
965                 maps[i].addr = bar_addr;
966                 maps[i].offset = reg.offset;
967                 maps[i].size = reg.size;
968                 maps[i].path = NULL; /* vfio doesn't have per-resource paths */
969                 dev->mem_resource[i].addr = bar_addr;
970         }
971
972         /* if secondary process, do not set up interrupts */
973         if (internal_config.process_type == RTE_PROC_PRIMARY) {
974                 if (pci_vfio_setup_interrupts(dev, vfio_dev_fd) != 0) {
975                         RTE_LOG(ERR, EAL, "  %s error setting up interrupts!\n", pci_addr);
976                         close(vfio_dev_fd);
977                         rte_free(vfio_res);
978                         return -1;
979                 }
980
981                 /* set bus mastering for the device */
982                 if (pci_vfio_set_bus_master(vfio_dev_fd)) {
983                         RTE_LOG(ERR, EAL, "  %s cannot set up bus mastering!\n", pci_addr);
984                         close(vfio_dev_fd);
985                         rte_free(vfio_res);
986                         return -1;
987                 }
988
989                 /* Reset the device */
990                 ioctl(vfio_dev_fd, VFIO_DEVICE_RESET);
991         }
992
993         if (internal_config.process_type == RTE_PROC_PRIMARY)
994                 TAILQ_INSERT_TAIL(vfio_res_list, vfio_res, next);
995
996         return 0;
997 }
998
999 int
1000 pci_vfio_ioport_map(struct rte_pci_device *dev, int bar,
1001                     struct rte_pci_ioport *p)
1002 {
1003         if (bar < VFIO_PCI_BAR0_REGION_INDEX ||
1004             bar > VFIO_PCI_BAR5_REGION_INDEX) {
1005                 RTE_LOG(ERR, EAL, "invalid bar (%d)!\n", bar);
1006                 return -1;
1007         }
1008
1009         p->dev = dev;
1010         p->base = VFIO_GET_REGION_ADDR(bar);
1011         return 0;
1012 }
1013
1014 void
1015 pci_vfio_ioport_read(struct rte_pci_ioport *p,
1016                      void *data, size_t len, off_t offset)
1017 {
1018         const struct rte_intr_handle *intr_handle = &p->dev->intr_handle;
1019
1020         if (pread64(intr_handle->vfio_dev_fd, data,
1021                     len, p->base + offset) <= 0)
1022                 RTE_LOG(ERR, EAL,
1023                         "Can't read from PCI bar (%" PRIu64 ") : offset (%x)\n",
1024                         VFIO_GET_REGION_IDX(p->base), (int)offset);
1025 }
1026
1027 void
1028 pci_vfio_ioport_write(struct rte_pci_ioport *p,
1029                       const void *data, size_t len, off_t offset)
1030 {
1031         const struct rte_intr_handle *intr_handle = &p->dev->intr_handle;
1032
1033         if (pwrite64(intr_handle->vfio_dev_fd, data,
1034                      len, p->base + offset) <= 0)
1035                 RTE_LOG(ERR, EAL,
1036                         "Can't write to PCI bar (%" PRIu64 ") : offset (%x)\n",
1037                         VFIO_GET_REGION_IDX(p->base), (int)offset);
1038 }
1039
1040 int
1041 pci_vfio_ioport_unmap(struct rte_pci_ioport *p)
1042 {
1043         RTE_SET_USED(p);
1044         return -1;
1045 }
1046
1047 int
1048 pci_vfio_enable(void)
1049 {
1050         /* initialize group list */
1051         int i;
1052         int vfio_available;
1053
1054         for (i = 0; i < VFIO_MAX_GROUPS; i++) {
1055                 vfio_cfg.vfio_groups[i].fd = -1;
1056                 vfio_cfg.vfio_groups[i].group_no = -1;
1057         }
1058
1059         /* inform the user that we are probing for VFIO */
1060         RTE_LOG(INFO, EAL, "Probing VFIO support...\n");
1061
1062         /* check if vfio-pci module is loaded */
1063         vfio_available = rte_eal_check_module("vfio_pci");
1064
1065         /* return error directly */
1066         if (vfio_available == -1) {
1067                 RTE_LOG(INFO, EAL, "Could not get loaded module details!\n");
1068                 return -1;
1069         }
1070
1071         /* return 0 if VFIO modules not loaded */
1072         if (vfio_available == 0) {
1073                 RTE_LOG(INFO, EAL, "VFIO modules not loaded, "
1074                         "skipping VFIO support...\n");
1075                 return 0;
1076         }
1077
1078         vfio_cfg.vfio_container_fd = pci_vfio_get_container_fd();
1079
1080         /* check if we have VFIO driver enabled */
1081         if (vfio_cfg.vfio_container_fd != -1) {
1082                 RTE_LOG(NOTICE, EAL, "VFIO support initialized\n");
1083                 vfio_cfg.vfio_enabled = 1;
1084         } else {
1085                 RTE_LOG(NOTICE, EAL, "VFIO support could not be initialized\n");
1086         }
1087
1088         return 0;
1089 }
1090
1091 int
1092 pci_vfio_is_enabled(void)
1093 {
1094         return vfio_cfg.vfio_enabled;
1095 }
1096 #endif