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