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