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