Imported Upstream version 16.04
[deb_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                         close(vfio_group_fd);
539                         return -1;
540                 }
541                 vfio_cfg.vfio_groups[vfio_cfg.vfio_group_idx].group_no = iommu_group_no;
542                 vfio_cfg.vfio_groups[vfio_cfg.vfio_group_idx].fd = vfio_group_fd;
543                 return vfio_group_fd;
544         }
545         /* if we're in a secondary process, request group fd from the primary
546          * process via our socket
547          */
548         else {
549                 int socket_fd, ret;
550
551                 socket_fd = vfio_mp_sync_connect_to_primary();
552
553                 if (socket_fd < 0) {
554                         RTE_LOG(ERR, EAL, "  cannot connect to primary process!\n");
555                         return -1;
556                 }
557                 if (vfio_mp_sync_send_request(socket_fd, SOCKET_REQ_GROUP) < 0) {
558                         RTE_LOG(ERR, EAL, "  cannot request container fd!\n");
559                         close(socket_fd);
560                         return -1;
561                 }
562                 if (vfio_mp_sync_send_request(socket_fd, iommu_group_no) < 0) {
563                         RTE_LOG(ERR, EAL, "  cannot send group number!\n");
564                         close(socket_fd);
565                         return -1;
566                 }
567                 ret = vfio_mp_sync_receive_request(socket_fd);
568                 switch (ret) {
569                 case SOCKET_NO_FD:
570                         close(socket_fd);
571                         return 0;
572                 case SOCKET_OK:
573                         vfio_group_fd = vfio_mp_sync_receive_fd(socket_fd);
574                         /* if we got the fd, return it */
575                         if (vfio_group_fd > 0) {
576                                 close(socket_fd);
577                                 return vfio_group_fd;
578                         }
579                         /* fall-through on error */
580                 default:
581                         RTE_LOG(ERR, EAL, "  cannot get container fd!\n");
582                         close(socket_fd);
583                         return -1;
584                 }
585         }
586         return -1;
587 }
588
589 /* parse IOMMU group number for a PCI device
590  * returns 1 on success, -1 for errors, 0 for non-existent group
591  */
592 static int
593 pci_vfio_get_group_no(const char *pci_addr, int *iommu_group_no)
594 {
595         char linkname[PATH_MAX];
596         char filename[PATH_MAX];
597         char *tok[16], *group_tok, *end;
598         int ret;
599
600         memset(linkname, 0, sizeof(linkname));
601         memset(filename, 0, sizeof(filename));
602
603         /* try to find out IOMMU group for this device */
604         snprintf(linkname, sizeof(linkname),
605                          SYSFS_PCI_DEVICES "/%s/iommu_group", pci_addr);
606
607         ret = readlink(linkname, filename, sizeof(filename));
608
609         /* if the link doesn't exist, no VFIO for us */
610         if (ret < 0)
611                 return 0;
612
613         ret = rte_strsplit(filename, sizeof(filename),
614                         tok, RTE_DIM(tok), '/');
615
616         if (ret <= 0) {
617                 RTE_LOG(ERR, EAL, "  %s cannot get IOMMU group\n", pci_addr);
618                 return -1;
619         }
620
621         /* IOMMU group is always the last token */
622         errno = 0;
623         group_tok = tok[ret - 1];
624         end = group_tok;
625         *iommu_group_no = strtol(group_tok, &end, 10);
626         if ((end != group_tok && *end != '\0') || errno != 0) {
627                 RTE_LOG(ERR, EAL, "  %s error parsing IOMMU number!\n", pci_addr);
628                 return -1;
629         }
630
631         return 1;
632 }
633
634 static void
635 clear_current_group(void)
636 {
637         vfio_cfg.vfio_groups[vfio_cfg.vfio_group_idx].group_no = 0;
638         vfio_cfg.vfio_groups[vfio_cfg.vfio_group_idx].fd = -1;
639 }
640
641
642 /*
643  * map the PCI resources of a PCI device in virtual memory (VFIO version).
644  * primary and secondary processes follow almost exactly the same path
645  */
646 int
647 pci_vfio_map_resource(struct rte_pci_device *dev)
648 {
649         struct vfio_group_status group_status = {
650                         .argsz = sizeof(group_status)
651         };
652         struct vfio_device_info device_info = { .argsz = sizeof(device_info) };
653         int vfio_group_fd, vfio_dev_fd;
654         int iommu_group_no;
655         char pci_addr[PATH_MAX] = {0};
656         struct rte_pci_addr *loc = &dev->addr;
657         int i, ret, msix_bar;
658         struct mapped_pci_resource *vfio_res = NULL;
659         struct mapped_pci_res_list *vfio_res_list = RTE_TAILQ_CAST(rte_vfio_tailq.head, mapped_pci_res_list);
660
661         struct pci_map *maps;
662         uint32_t msix_table_offset = 0;
663         uint32_t msix_table_size = 0;
664         uint32_t ioport_bar;
665
666         dev->intr_handle.fd = -1;
667         dev->intr_handle.type = RTE_INTR_HANDLE_UNKNOWN;
668
669         /* store PCI address string */
670         snprintf(pci_addr, sizeof(pci_addr), PCI_PRI_FMT,
671                         loc->domain, loc->bus, loc->devid, loc->function);
672
673         /* get group number */
674         ret = pci_vfio_get_group_no(pci_addr, &iommu_group_no);
675         if (ret == 0) {
676                 RTE_LOG(WARNING, EAL, "  %s not managed by VFIO driver, skipping\n",
677                         pci_addr);
678                 return 1;
679         }
680
681         /* if negative, something failed */
682         if (ret < 0)
683                 return -1;
684
685         /* get the actual group fd */
686         vfio_group_fd = pci_vfio_get_group_fd(iommu_group_no);
687         if (vfio_group_fd < 0)
688                 return -1;
689
690         /* store group fd */
691         vfio_cfg.vfio_groups[vfio_cfg.vfio_group_idx].group_no = iommu_group_no;
692         vfio_cfg.vfio_groups[vfio_cfg.vfio_group_idx].fd = vfio_group_fd;
693
694         /* if group_fd == 0, that means the device isn't managed by VFIO */
695         if (vfio_group_fd == 0) {
696                 RTE_LOG(WARNING, EAL, "  %s not managed by VFIO driver, skipping\n",
697                                 pci_addr);
698                 /* we store 0 as group fd to distinguish between existing but
699                  * unbound VFIO groups, and groups that don't exist at all.
700                  */
701                 vfio_cfg.vfio_group_idx++;
702                 return 1;
703         }
704
705         /*
706          * at this point, we know at least one port on this device is bound to VFIO,
707          * so we can proceed to try and set this particular port up
708          */
709
710         /* check if the group is viable */
711         ret = ioctl(vfio_group_fd, VFIO_GROUP_GET_STATUS, &group_status);
712         if (ret) {
713                 RTE_LOG(ERR, EAL, "  %s cannot get group status, "
714                                 "error %i (%s)\n", pci_addr, errno, strerror(errno));
715                 close(vfio_group_fd);
716                 clear_current_group();
717                 return -1;
718         } else if (!(group_status.flags & VFIO_GROUP_FLAGS_VIABLE)) {
719                 RTE_LOG(ERR, EAL, "  %s VFIO group is not viable!\n", pci_addr);
720                 close(vfio_group_fd);
721                 clear_current_group();
722                 return -1;
723         }
724
725         /*
726          * at this point, we know that this group is viable (meaning, all devices
727          * are either bound to VFIO or not bound to anything)
728          */
729
730         /* check if group does not have a container yet */
731         if (!(group_status.flags & VFIO_GROUP_FLAGS_CONTAINER_SET)) {
732
733                 /* add group to a container */
734                 ret = ioctl(vfio_group_fd, VFIO_GROUP_SET_CONTAINER,
735                                 &vfio_cfg.vfio_container_fd);
736                 if (ret) {
737                         RTE_LOG(ERR, EAL, "  %s cannot add VFIO group to container, "
738                                         "error %i (%s)\n", pci_addr, errno, strerror(errno));
739                         close(vfio_group_fd);
740                         clear_current_group();
741                         return -1;
742                 }
743                 /*
744                  * at this point we know that this group has been successfully
745                  * initialized, so we increment vfio_group_idx to indicate that we can
746                  * add new groups.
747                  */
748                 vfio_cfg.vfio_group_idx++;
749         }
750
751         /*
752          * pick an IOMMU type and set up DMA mappings for container
753          *
754          * needs to be done only once, only when at least one group is assigned to
755          * a container and only in primary process
756          */
757         if (internal_config.process_type == RTE_PROC_PRIMARY &&
758                         vfio_cfg.vfio_container_has_dma == 0) {
759                 /* select an IOMMU type which we will be using */
760                 const struct vfio_iommu_type *t =
761                                 pci_vfio_set_iommu_type(vfio_cfg.vfio_container_fd);
762                 if (!t) {
763                         RTE_LOG(ERR, EAL, "  %s failed to select IOMMU type\n", pci_addr);
764                         return -1;
765                 }
766                 ret = t->dma_map_func(vfio_cfg.vfio_container_fd);
767                 if (ret) {
768                         RTE_LOG(ERR, EAL, "  %s DMA remapping failed, "
769                                         "error %i (%s)\n", pci_addr, errno, strerror(errno));
770                         return -1;
771                 }
772                 vfio_cfg.vfio_container_has_dma = 1;
773         }
774
775         /* get a file descriptor for the device */
776         vfio_dev_fd = ioctl(vfio_group_fd, VFIO_GROUP_GET_DEVICE_FD, pci_addr);
777         if (vfio_dev_fd < 0) {
778                 /* if we cannot get a device fd, this simply means that this
779                  * particular port is not bound to VFIO
780                  */
781                 RTE_LOG(WARNING, EAL, "  %s not managed by VFIO driver, skipping\n",
782                                 pci_addr);
783                 return 1;
784         }
785
786         /* test and setup the device */
787         ret = ioctl(vfio_dev_fd, VFIO_DEVICE_GET_INFO, &device_info);
788         if (ret) {
789                 RTE_LOG(ERR, EAL, "  %s cannot get device info, "
790                                 "error %i (%s)\n", pci_addr, errno, strerror(errno));
791                 close(vfio_dev_fd);
792                 return -1;
793         }
794
795         /* get MSI-X BAR, if any (we have to know where it is because we can't
796          * easily mmap it when using VFIO) */
797         msix_bar = -1;
798         ret = pci_vfio_get_msix_bar(vfio_dev_fd, &msix_bar,
799                                     &msix_table_offset, &msix_table_size);
800         if (ret < 0) {
801                 RTE_LOG(ERR, EAL, "  %s cannot get MSI-X BAR number!\n", pci_addr);
802                 close(vfio_dev_fd);
803                 return -1;
804         }
805
806         /* if we're in a primary process, allocate vfio_res and get region info */
807         if (internal_config.process_type == RTE_PROC_PRIMARY) {
808                 vfio_res = rte_zmalloc("VFIO_RES", sizeof(*vfio_res), 0);
809                 if (vfio_res == NULL) {
810                         RTE_LOG(ERR, EAL,
811                                 "%s(): cannot store uio mmap details\n", __func__);
812                         close(vfio_dev_fd);
813                         return -1;
814                 }
815                 memcpy(&vfio_res->pci_addr, &dev->addr, sizeof(vfio_res->pci_addr));
816
817                 /* get number of registers (up to BAR5) */
818                 vfio_res->nb_maps = RTE_MIN((int) device_info.num_regions,
819                                 VFIO_PCI_BAR5_REGION_INDEX + 1);
820         } else {
821                 /* if we're in a secondary process, just find our tailq entry */
822                 TAILQ_FOREACH(vfio_res, vfio_res_list, next) {
823                         if (memcmp(&vfio_res->pci_addr, &dev->addr, sizeof(dev->addr)))
824                                 continue;
825                         break;
826                 }
827                 /* if we haven't found our tailq entry, something's wrong */
828                 if (vfio_res == NULL) {
829                         RTE_LOG(ERR, EAL, "  %s cannot find TAILQ entry for PCI device!\n",
830                                         pci_addr);
831                         close(vfio_dev_fd);
832                         return -1;
833                 }
834         }
835
836         /* map BARs */
837         maps = vfio_res->maps;
838
839         for (i = 0; i < (int) vfio_res->nb_maps; i++) {
840                 struct vfio_region_info reg = { .argsz = sizeof(reg) };
841                 void *bar_addr;
842                 struct memreg {
843                         unsigned long offset, size;
844                 } memreg[2] = {};
845
846                 reg.index = i;
847
848                 ret = ioctl(vfio_dev_fd, VFIO_DEVICE_GET_REGION_INFO, &reg);
849
850                 if (ret) {
851                         RTE_LOG(ERR, EAL, "  %s cannot get device region info "
852                                         "error %i (%s)\n", pci_addr, errno, strerror(errno));
853                         close(vfio_dev_fd);
854                         if (internal_config.process_type == RTE_PROC_PRIMARY)
855                                 rte_free(vfio_res);
856                         return -1;
857                 }
858
859                 /* chk for io port region */
860                 ret = pread64(vfio_dev_fd, &ioport_bar, sizeof(ioport_bar),
861                               VFIO_GET_REGION_ADDR(VFIO_PCI_CONFIG_REGION_INDEX)
862                               + PCI_BASE_ADDRESS_0 + i*4);
863
864                 if (ret != sizeof(ioport_bar)) {
865                         RTE_LOG(ERR, EAL,
866                                 "Cannot read command (%x) from config space!\n",
867                                 PCI_BASE_ADDRESS_0 + i*4);
868                         return -1;
869                 }
870
871                 if (ioport_bar & PCI_BASE_ADDRESS_SPACE_IO) {
872                         RTE_LOG(INFO, EAL,
873                                 "Ignore mapping IO port bar(%d) addr: %x\n",
874                                  i, ioport_bar);
875                         continue;
876                 }
877
878                 /* skip non-mmapable BARs */
879                 if ((reg.flags & VFIO_REGION_INFO_FLAG_MMAP) == 0)
880                         continue;
881
882                 if (i == msix_bar) {
883                         /*
884                          * VFIO will not let us map the MSI-X table,
885                          * but we can map around it.
886                          */
887                         uint32_t table_start = msix_table_offset;
888                         uint32_t table_end = table_start + msix_table_size;
889                         table_end = (table_end + ~PAGE_MASK) & PAGE_MASK;
890                         table_start &= PAGE_MASK;
891
892                         if (table_start == 0 && table_end >= reg.size) {
893                                 /* Cannot map this BAR */
894                                 RTE_LOG(DEBUG, EAL, "Skipping BAR %d\n", i);
895                                 continue;
896                         } else {
897                                 memreg[0].offset = reg.offset;
898                                 memreg[0].size = table_start;
899                                 memreg[1].offset = table_end;
900                                 memreg[1].size = reg.size - table_end;
901
902                                 RTE_LOG(DEBUG, EAL,
903                                         "Trying to map BAR %d that contains the MSI-X "
904                                         "table. Trying offsets: "
905                                         "0x%04lx:0x%04lx, 0x%04lx:0x%04lx\n", i,
906                                         memreg[0].offset, memreg[0].size,
907                                         memreg[1].offset, memreg[1].size);
908                         }
909                 } else {
910                         memreg[0].offset = reg.offset;
911                         memreg[0].size = reg.size;
912                 }
913
914                 /* try to figure out an address */
915                 if (internal_config.process_type == RTE_PROC_PRIMARY) {
916                         /* try mapping somewhere close to the end of hugepages */
917                         if (pci_map_addr == NULL)
918                                 pci_map_addr = pci_find_max_end_va();
919
920                         bar_addr = pci_map_addr;
921                         pci_map_addr = RTE_PTR_ADD(bar_addr, (size_t) reg.size);
922                 } else {
923                         bar_addr = maps[i].addr;
924                 }
925
926                 /* reserve the address using an inaccessible mapping */
927                 bar_addr = mmap(bar_addr, reg.size, 0, MAP_PRIVATE |
928                                 MAP_ANONYMOUS, -1, 0);
929                 if (bar_addr != MAP_FAILED) {
930                         void *map_addr = NULL;
931                         if (memreg[0].size) {
932                                 /* actual map of first part */
933                                 map_addr = pci_map_resource(bar_addr, vfio_dev_fd,
934                                                             memreg[0].offset,
935                                                             memreg[0].size,
936                                                             MAP_FIXED);
937                         }
938
939                         /* if there's a second part, try to map it */
940                         if (map_addr != MAP_FAILED
941                             && memreg[1].offset && memreg[1].size) {
942                                 void *second_addr = RTE_PTR_ADD(bar_addr, memreg[1].offset);
943                                 map_addr = pci_map_resource(second_addr,
944                                                             vfio_dev_fd, memreg[1].offset,
945                                                             memreg[1].size,
946                                                             MAP_FIXED);
947                         }
948
949                         if (map_addr == MAP_FAILED || !map_addr) {
950                                 munmap(bar_addr, reg.size);
951                                 bar_addr = MAP_FAILED;
952                         }
953                 }
954
955                 if (bar_addr == MAP_FAILED ||
956                                 (internal_config.process_type == RTE_PROC_SECONDARY &&
957                                                 bar_addr != maps[i].addr)) {
958                         RTE_LOG(ERR, EAL, "  %s mapping BAR%i failed: %s\n", pci_addr, i,
959                                         strerror(errno));
960                         close(vfio_dev_fd);
961                         if (internal_config.process_type == RTE_PROC_PRIMARY)
962                                 rte_free(vfio_res);
963                         return -1;
964                 }
965
966                 maps[i].addr = bar_addr;
967                 maps[i].offset = reg.offset;
968                 maps[i].size = reg.size;
969                 maps[i].path = NULL; /* vfio doesn't have per-resource paths */
970                 dev->mem_resource[i].addr = bar_addr;
971         }
972
973         /* if secondary process, do not set up interrupts */
974         if (internal_config.process_type == RTE_PROC_PRIMARY) {
975                 if (pci_vfio_setup_interrupts(dev, vfio_dev_fd) != 0) {
976                         RTE_LOG(ERR, EAL, "  %s error setting up interrupts!\n", pci_addr);
977                         close(vfio_dev_fd);
978                         rte_free(vfio_res);
979                         return -1;
980                 }
981
982                 /* set bus mastering for the device */
983                 if (pci_vfio_set_bus_master(vfio_dev_fd)) {
984                         RTE_LOG(ERR, EAL, "  %s cannot set up bus mastering!\n", pci_addr);
985                         close(vfio_dev_fd);
986                         rte_free(vfio_res);
987                         return -1;
988                 }
989
990                 /* Reset the device */
991                 ioctl(vfio_dev_fd, VFIO_DEVICE_RESET);
992         }
993
994         if (internal_config.process_type == RTE_PROC_PRIMARY)
995                 TAILQ_INSERT_TAIL(vfio_res_list, vfio_res, next);
996
997         return 0;
998 }
999
1000 int
1001 pci_vfio_ioport_map(struct rte_pci_device *dev, int bar,
1002                     struct rte_pci_ioport *p)
1003 {
1004         if (bar < VFIO_PCI_BAR0_REGION_INDEX ||
1005             bar > VFIO_PCI_BAR5_REGION_INDEX) {
1006                 RTE_LOG(ERR, EAL, "invalid bar (%d)!\n", bar);
1007                 return -1;
1008         }
1009
1010         p->dev = dev;
1011         p->base = VFIO_GET_REGION_ADDR(bar);
1012         return 0;
1013 }
1014
1015 void
1016 pci_vfio_ioport_read(struct rte_pci_ioport *p,
1017                      void *data, size_t len, off_t offset)
1018 {
1019         const struct rte_intr_handle *intr_handle = &p->dev->intr_handle;
1020
1021         if (pread64(intr_handle->vfio_dev_fd, data,
1022                     len, p->base + offset) <= 0)
1023                 RTE_LOG(ERR, EAL,
1024                         "Can't read from PCI bar (%" PRIu64 ") : offset (%x)\n",
1025                         VFIO_GET_REGION_IDX(p->base), (int)offset);
1026 }
1027
1028 void
1029 pci_vfio_ioport_write(struct rte_pci_ioport *p,
1030                       const void *data, size_t len, off_t offset)
1031 {
1032         const struct rte_intr_handle *intr_handle = &p->dev->intr_handle;
1033
1034         if (pwrite64(intr_handle->vfio_dev_fd, data,
1035                      len, p->base + offset) <= 0)
1036                 RTE_LOG(ERR, EAL,
1037                         "Can't write to PCI bar (%" PRIu64 ") : offset (%x)\n",
1038                         VFIO_GET_REGION_IDX(p->base), (int)offset);
1039 }
1040
1041 int
1042 pci_vfio_ioport_unmap(struct rte_pci_ioport *p)
1043 {
1044         RTE_SET_USED(p);
1045         return -1;
1046 }
1047
1048 int
1049 pci_vfio_enable(void)
1050 {
1051         /* initialize group list */
1052         int i;
1053         int vfio_available;
1054
1055         for (i = 0; i < VFIO_MAX_GROUPS; i++) {
1056                 vfio_cfg.vfio_groups[i].fd = -1;
1057                 vfio_cfg.vfio_groups[i].group_no = -1;
1058         }
1059
1060         /* inform the user that we are probing for VFIO */
1061         RTE_LOG(INFO, EAL, "Probing VFIO support...\n");
1062
1063         /* check if vfio-pci module is loaded */
1064         vfio_available = rte_eal_check_module("vfio_pci");
1065
1066         /* return error directly */
1067         if (vfio_available == -1) {
1068                 RTE_LOG(INFO, EAL, "Could not get loaded module details!\n");
1069                 return -1;
1070         }
1071
1072         /* return 0 if VFIO modules not loaded */
1073         if (vfio_available == 0) {
1074                 RTE_LOG(DEBUG, EAL, "VFIO modules not loaded, "
1075                         "skipping VFIO support...\n");
1076                 return 0;
1077         }
1078
1079         vfio_cfg.vfio_container_fd = pci_vfio_get_container_fd();
1080
1081         /* check if we have VFIO driver enabled */
1082         if (vfio_cfg.vfio_container_fd != -1) {
1083                 RTE_LOG(NOTICE, EAL, "VFIO support initialized\n");
1084                 vfio_cfg.vfio_enabled = 1;
1085         } else {
1086                 RTE_LOG(NOTICE, EAL, "VFIO support could not be initialized\n");
1087         }
1088
1089         return 0;
1090 }
1091
1092 int
1093 pci_vfio_is_enabled(void)
1094 {
1095         return vfio_cfg.vfio_enabled;
1096 }
1097 #endif