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