mem: allow memseg lists to be marked as external
[dpdk.git] / lib / librte_eal / linuxapp / eal / eal_vfio.c
1 /* SPDX-License-Identifier: BSD-3-Clause
2  * Copyright(c) 2010-2018 Intel Corporation
3  */
4
5 #include <inttypes.h>
6 #include <string.h>
7 #include <fcntl.h>
8 #include <unistd.h>
9 #include <sys/ioctl.h>
10
11 #include <rte_errno.h>
12 #include <rte_log.h>
13 #include <rte_memory.h>
14 #include <rte_eal_memconfig.h>
15 #include <rte_vfio.h>
16
17 #include "eal_filesystem.h"
18 #include "eal_vfio.h"
19 #include "eal_private.h"
20
21 #ifdef VFIO_PRESENT
22
23 #define VFIO_MEM_EVENT_CLB_NAME "vfio_mem_event_clb"
24
25 /* hot plug/unplug of VFIO groups may cause all DMA maps to be dropped. we can
26  * recreate the mappings for DPDK segments, but we cannot do so for memory that
27  * was registered by the user themselves, so we need to store the user mappings
28  * somewhere, to recreate them later.
29  */
30 #define VFIO_MAX_USER_MEM_MAPS 256
31 struct user_mem_map {
32         uint64_t addr;
33         uint64_t iova;
34         uint64_t len;
35 };
36
37 struct user_mem_maps {
38         rte_spinlock_recursive_t lock;
39         int n_maps;
40         struct user_mem_map maps[VFIO_MAX_USER_MEM_MAPS];
41 };
42
43 struct vfio_config {
44         int vfio_enabled;
45         int vfio_container_fd;
46         int vfio_active_groups;
47         const struct vfio_iommu_type *vfio_iommu_type;
48         struct vfio_group vfio_groups[VFIO_MAX_GROUPS];
49         struct user_mem_maps mem_maps;
50 };
51
52 /* per-process VFIO config */
53 static struct vfio_config vfio_cfgs[VFIO_MAX_CONTAINERS];
54 static struct vfio_config *default_vfio_cfg = &vfio_cfgs[0];
55
56 static int vfio_type1_dma_map(int);
57 static int vfio_type1_dma_mem_map(int, uint64_t, uint64_t, uint64_t, int);
58 static int vfio_spapr_dma_map(int);
59 static int vfio_spapr_dma_mem_map(int, uint64_t, uint64_t, uint64_t, int);
60 static int vfio_noiommu_dma_map(int);
61 static int vfio_noiommu_dma_mem_map(int, uint64_t, uint64_t, uint64_t, int);
62 static int vfio_dma_mem_map(struct vfio_config *vfio_cfg, uint64_t vaddr,
63                 uint64_t iova, uint64_t len, int do_map);
64
65 /* IOMMU types we support */
66 static const struct vfio_iommu_type iommu_types[] = {
67         /* x86 IOMMU, otherwise known as type 1 */
68         {
69                 .type_id = RTE_VFIO_TYPE1,
70                 .name = "Type 1",
71                 .dma_map_func = &vfio_type1_dma_map,
72                 .dma_user_map_func = &vfio_type1_dma_mem_map
73         },
74         /* ppc64 IOMMU, otherwise known as spapr */
75         {
76                 .type_id = RTE_VFIO_SPAPR,
77                 .name = "sPAPR",
78                 .dma_map_func = &vfio_spapr_dma_map,
79                 .dma_user_map_func = &vfio_spapr_dma_mem_map
80         },
81         /* IOMMU-less mode */
82         {
83                 .type_id = RTE_VFIO_NOIOMMU,
84                 .name = "No-IOMMU",
85                 .dma_map_func = &vfio_noiommu_dma_map,
86                 .dma_user_map_func = &vfio_noiommu_dma_mem_map
87         },
88 };
89
90 static int
91 is_null_map(const struct user_mem_map *map)
92 {
93         return map->addr == 0 && map->iova == 0 && map->len == 0;
94 }
95
96 /* we may need to merge user mem maps together in case of user mapping/unmapping
97  * chunks of memory, so we'll need a comparator function to sort segments.
98  */
99 static int
100 user_mem_map_cmp(const void *a, const void *b)
101 {
102         const struct user_mem_map *umm_a = a;
103         const struct user_mem_map *umm_b = b;
104
105         /* move null entries to end */
106         if (is_null_map(umm_a))
107                 return 1;
108         if (is_null_map(umm_b))
109                 return -1;
110
111         /* sort by iova first */
112         if (umm_a->iova < umm_b->iova)
113                 return -1;
114         if (umm_a->iova > umm_b->iova)
115                 return 1;
116
117         if (umm_a->addr < umm_b->addr)
118                 return -1;
119         if (umm_a->addr > umm_b->addr)
120                 return 1;
121
122         if (umm_a->len < umm_b->len)
123                 return -1;
124         if (umm_a->len > umm_b->len)
125                 return 1;
126
127         return 0;
128 }
129
130 /* adjust user map entry. this may result in shortening of existing map, or in
131  * splitting existing map in two pieces.
132  */
133 static void
134 adjust_map(struct user_mem_map *src, struct user_mem_map *end,
135                 uint64_t remove_va_start, uint64_t remove_len)
136 {
137         /* if va start is same as start address, we're simply moving start */
138         if (remove_va_start == src->addr) {
139                 src->addr += remove_len;
140                 src->iova += remove_len;
141                 src->len -= remove_len;
142         } else if (remove_va_start + remove_len == src->addr + src->len) {
143                 /* we're shrinking mapping from the end */
144                 src->len -= remove_len;
145         } else {
146                 /* we're blowing a hole in the middle */
147                 struct user_mem_map tmp;
148                 uint64_t total_len = src->len;
149
150                 /* adjust source segment length */
151                 src->len = remove_va_start - src->addr;
152
153                 /* create temporary segment in the middle */
154                 tmp.addr = src->addr + src->len;
155                 tmp.iova = src->iova + src->len;
156                 tmp.len = remove_len;
157
158                 /* populate end segment - this one we will be keeping */
159                 end->addr = tmp.addr + tmp.len;
160                 end->iova = tmp.iova + tmp.len;
161                 end->len = total_len - src->len - tmp.len;
162         }
163 }
164
165 /* try merging two maps into one, return 1 if succeeded */
166 static int
167 merge_map(struct user_mem_map *left, struct user_mem_map *right)
168 {
169         if (left->addr + left->len != right->addr)
170                 return 0;
171         if (left->iova + left->len != right->iova)
172                 return 0;
173
174         left->len += right->len;
175
176         memset(right, 0, sizeof(*right));
177
178         return 1;
179 }
180
181 static struct user_mem_map *
182 find_user_mem_map(struct user_mem_maps *user_mem_maps, uint64_t addr,
183                 uint64_t iova, uint64_t len)
184 {
185         uint64_t va_end = addr + len;
186         uint64_t iova_end = iova + len;
187         int i;
188
189         for (i = 0; i < user_mem_maps->n_maps; i++) {
190                 struct user_mem_map *map = &user_mem_maps->maps[i];
191                 uint64_t map_va_end = map->addr + map->len;
192                 uint64_t map_iova_end = map->iova + map->len;
193
194                 /* check start VA */
195                 if (addr < map->addr || addr >= map_va_end)
196                         continue;
197                 /* check if VA end is within boundaries */
198                 if (va_end <= map->addr || va_end > map_va_end)
199                         continue;
200
201                 /* check start IOVA */
202                 if (iova < map->iova || iova >= map_iova_end)
203                         continue;
204                 /* check if IOVA end is within boundaries */
205                 if (iova_end <= map->iova || iova_end > map_iova_end)
206                         continue;
207
208                 /* we've found our map */
209                 return map;
210         }
211         return NULL;
212 }
213
214 /* this will sort all user maps, and merge/compact any adjacent maps */
215 static void
216 compact_user_maps(struct user_mem_maps *user_mem_maps)
217 {
218         int i, n_merged, cur_idx;
219
220         qsort(user_mem_maps->maps, user_mem_maps->n_maps,
221                         sizeof(user_mem_maps->maps[0]), user_mem_map_cmp);
222
223         /* we'll go over the list backwards when merging */
224         n_merged = 0;
225         for (i = user_mem_maps->n_maps - 2; i >= 0; i--) {
226                 struct user_mem_map *l, *r;
227
228                 l = &user_mem_maps->maps[i];
229                 r = &user_mem_maps->maps[i + 1];
230
231                 if (is_null_map(l) || is_null_map(r))
232                         continue;
233
234                 if (merge_map(l, r))
235                         n_merged++;
236         }
237
238         /* the entries are still sorted, but now they have holes in them, so
239          * walk through the list and remove the holes
240          */
241         if (n_merged > 0) {
242                 cur_idx = 0;
243                 for (i = 0; i < user_mem_maps->n_maps; i++) {
244                         if (!is_null_map(&user_mem_maps->maps[i])) {
245                                 struct user_mem_map *src, *dst;
246
247                                 src = &user_mem_maps->maps[i];
248                                 dst = &user_mem_maps->maps[cur_idx++];
249
250                                 if (src != dst) {
251                                         memcpy(dst, src, sizeof(*src));
252                                         memset(src, 0, sizeof(*src));
253                                 }
254                         }
255                 }
256                 user_mem_maps->n_maps = cur_idx;
257         }
258 }
259
260 static int
261 vfio_open_group_fd(int iommu_group_num)
262 {
263         int vfio_group_fd;
264         char filename[PATH_MAX];
265         struct rte_mp_msg mp_req, *mp_rep;
266         struct rte_mp_reply mp_reply;
267         struct timespec ts = {.tv_sec = 5, .tv_nsec = 0};
268         struct vfio_mp_param *p = (struct vfio_mp_param *)mp_req.param;
269
270         /* if primary, try to open the group */
271         if (internal_config.process_type == RTE_PROC_PRIMARY) {
272                 /* try regular group format */
273                 snprintf(filename, sizeof(filename),
274                                  VFIO_GROUP_FMT, iommu_group_num);
275                 vfio_group_fd = open(filename, O_RDWR);
276                 if (vfio_group_fd < 0) {
277                         /* if file not found, it's not an error */
278                         if (errno != ENOENT) {
279                                 RTE_LOG(ERR, EAL, "Cannot open %s: %s\n", filename,
280                                                 strerror(errno));
281                                 return -1;
282                         }
283
284                         /* special case: try no-IOMMU path as well */
285                         snprintf(filename, sizeof(filename),
286                                         VFIO_NOIOMMU_GROUP_FMT,
287                                         iommu_group_num);
288                         vfio_group_fd = open(filename, O_RDWR);
289                         if (vfio_group_fd < 0) {
290                                 if (errno != ENOENT) {
291                                         RTE_LOG(ERR, EAL, "Cannot open %s: %s\n", filename,
292                                                         strerror(errno));
293                                         return -1;
294                                 }
295                                 return 0;
296                         }
297                         /* noiommu group found */
298                 }
299
300                 return vfio_group_fd;
301         }
302         /* if we're in a secondary process, request group fd from the primary
303          * process via mp channel.
304          */
305         p->req = SOCKET_REQ_GROUP;
306         p->group_num = iommu_group_num;
307         strcpy(mp_req.name, EAL_VFIO_MP);
308         mp_req.len_param = sizeof(*p);
309         mp_req.num_fds = 0;
310
311         vfio_group_fd = -1;
312         if (rte_mp_request_sync(&mp_req, &mp_reply, &ts) == 0 &&
313             mp_reply.nb_received == 1) {
314                 mp_rep = &mp_reply.msgs[0];
315                 p = (struct vfio_mp_param *)mp_rep->param;
316                 if (p->result == SOCKET_OK && mp_rep->num_fds == 1) {
317                         vfio_group_fd = mp_rep->fds[0];
318                 } else if (p->result == SOCKET_NO_FD) {
319                         RTE_LOG(ERR, EAL, "  bad VFIO group fd\n");
320                         vfio_group_fd = 0;
321                 }
322                 free(mp_reply.msgs);
323         }
324
325         if (vfio_group_fd < 0)
326                 RTE_LOG(ERR, EAL, "  cannot request group fd\n");
327         return vfio_group_fd;
328 }
329
330 static struct vfio_config *
331 get_vfio_cfg_by_group_num(int iommu_group_num)
332 {
333         struct vfio_config *vfio_cfg;
334         int i, j;
335
336         for (i = 0; i < VFIO_MAX_CONTAINERS; i++) {
337                 vfio_cfg = &vfio_cfgs[i];
338                 for (j = 0; j < VFIO_MAX_GROUPS; j++) {
339                         if (vfio_cfg->vfio_groups[j].group_num ==
340                                         iommu_group_num)
341                                 return vfio_cfg;
342                 }
343         }
344
345         return NULL;
346 }
347
348 static struct vfio_config *
349 get_vfio_cfg_by_group_fd(int vfio_group_fd)
350 {
351         struct vfio_config *vfio_cfg;
352         int i, j;
353
354         for (i = 0; i < VFIO_MAX_CONTAINERS; i++) {
355                 vfio_cfg = &vfio_cfgs[i];
356                 for (j = 0; j < VFIO_MAX_GROUPS; j++)
357                         if (vfio_cfg->vfio_groups[j].fd == vfio_group_fd)
358                                 return vfio_cfg;
359         }
360
361         return NULL;
362 }
363
364 static struct vfio_config *
365 get_vfio_cfg_by_container_fd(int container_fd)
366 {
367         int i;
368
369         for (i = 0; i < VFIO_MAX_CONTAINERS; i++) {
370                 if (vfio_cfgs[i].vfio_container_fd == container_fd)
371                         return &vfio_cfgs[i];
372         }
373
374         return NULL;
375 }
376
377 int
378 rte_vfio_get_group_fd(int iommu_group_num)
379 {
380         int i;
381         int vfio_group_fd;
382         struct vfio_group *cur_grp;
383         struct vfio_config *vfio_cfg;
384
385         /* get the vfio_config it belongs to */
386         vfio_cfg = get_vfio_cfg_by_group_num(iommu_group_num);
387         vfio_cfg = vfio_cfg ? vfio_cfg : default_vfio_cfg;
388
389         /* check if we already have the group descriptor open */
390         for (i = 0; i < VFIO_MAX_GROUPS; i++)
391                 if (vfio_cfg->vfio_groups[i].group_num == iommu_group_num)
392                         return vfio_cfg->vfio_groups[i].fd;
393
394         /* Lets see first if there is room for a new group */
395         if (vfio_cfg->vfio_active_groups == VFIO_MAX_GROUPS) {
396                 RTE_LOG(ERR, EAL, "Maximum number of VFIO groups reached!\n");
397                 return -1;
398         }
399
400         /* Now lets get an index for the new group */
401         for (i = 0; i < VFIO_MAX_GROUPS; i++)
402                 if (vfio_cfg->vfio_groups[i].group_num == -1) {
403                         cur_grp = &vfio_cfg->vfio_groups[i];
404                         break;
405                 }
406
407         /* This should not happen */
408         if (i == VFIO_MAX_GROUPS) {
409                 RTE_LOG(ERR, EAL, "No VFIO group free slot found\n");
410                 return -1;
411         }
412
413         vfio_group_fd = vfio_open_group_fd(iommu_group_num);
414         if (vfio_group_fd < 0) {
415                 RTE_LOG(ERR, EAL, "Failed to open group %d\n", iommu_group_num);
416                 return -1;
417         }
418
419         cur_grp->group_num = iommu_group_num;
420         cur_grp->fd = vfio_group_fd;
421         vfio_cfg->vfio_active_groups++;
422
423         return vfio_group_fd;
424 }
425
426 static int
427 get_vfio_group_idx(int vfio_group_fd)
428 {
429         struct vfio_config *vfio_cfg;
430         int i, j;
431
432         for (i = 0; i < VFIO_MAX_CONTAINERS; i++) {
433                 vfio_cfg = &vfio_cfgs[i];
434                 for (j = 0; j < VFIO_MAX_GROUPS; j++)
435                         if (vfio_cfg->vfio_groups[j].fd == vfio_group_fd)
436                                 return j;
437         }
438
439         return -1;
440 }
441
442 static void
443 vfio_group_device_get(int vfio_group_fd)
444 {
445         struct vfio_config *vfio_cfg;
446         int i;
447
448         vfio_cfg = get_vfio_cfg_by_group_fd(vfio_group_fd);
449         if (vfio_cfg == NULL) {
450                 RTE_LOG(ERR, EAL, "  invalid group fd!\n");
451                 return;
452         }
453
454         i = get_vfio_group_idx(vfio_group_fd);
455         if (i < 0 || i > (VFIO_MAX_GROUPS - 1))
456                 RTE_LOG(ERR, EAL, "  wrong vfio_group index (%d)\n", i);
457         else
458                 vfio_cfg->vfio_groups[i].devices++;
459 }
460
461 static void
462 vfio_group_device_put(int vfio_group_fd)
463 {
464         struct vfio_config *vfio_cfg;
465         int i;
466
467         vfio_cfg = get_vfio_cfg_by_group_fd(vfio_group_fd);
468         if (vfio_cfg == NULL) {
469                 RTE_LOG(ERR, EAL, "  invalid group fd!\n");
470                 return;
471         }
472
473         i = get_vfio_group_idx(vfio_group_fd);
474         if (i < 0 || i > (VFIO_MAX_GROUPS - 1))
475                 RTE_LOG(ERR, EAL, "  wrong vfio_group index (%d)\n", i);
476         else
477                 vfio_cfg->vfio_groups[i].devices--;
478 }
479
480 static int
481 vfio_group_device_count(int vfio_group_fd)
482 {
483         struct vfio_config *vfio_cfg;
484         int i;
485
486         vfio_cfg = get_vfio_cfg_by_group_fd(vfio_group_fd);
487         if (vfio_cfg == NULL) {
488                 RTE_LOG(ERR, EAL, "  invalid group fd!\n");
489                 return -1;
490         }
491
492         i = get_vfio_group_idx(vfio_group_fd);
493         if (i < 0 || i > (VFIO_MAX_GROUPS - 1)) {
494                 RTE_LOG(ERR, EAL, "  wrong vfio_group index (%d)\n", i);
495                 return -1;
496         }
497
498         return vfio_cfg->vfio_groups[i].devices;
499 }
500
501 static void
502 vfio_mem_event_callback(enum rte_mem_event type, const void *addr, size_t len,
503                 void *arg __rte_unused)
504 {
505         struct rte_memseg_list *msl;
506         struct rte_memseg *ms;
507         size_t cur_len = 0;
508
509         msl = rte_mem_virt2memseg_list(addr);
510
511         /* for IOVA as VA mode, no need to care for IOVA addresses */
512         if (rte_eal_iova_mode() == RTE_IOVA_VA) {
513                 uint64_t vfio_va = (uint64_t)(uintptr_t)addr;
514                 if (type == RTE_MEM_EVENT_ALLOC)
515                         vfio_dma_mem_map(default_vfio_cfg, vfio_va, vfio_va,
516                                         len, 1);
517                 else
518                         vfio_dma_mem_map(default_vfio_cfg, vfio_va, vfio_va,
519                                         len, 0);
520                 return;
521         }
522
523         /* memsegs are contiguous in memory */
524         ms = rte_mem_virt2memseg(addr, msl);
525         while (cur_len < len) {
526                 if (type == RTE_MEM_EVENT_ALLOC)
527                         vfio_dma_mem_map(default_vfio_cfg, ms->addr_64,
528                                         ms->iova, ms->len, 1);
529                 else
530                         vfio_dma_mem_map(default_vfio_cfg, ms->addr_64,
531                                         ms->iova, ms->len, 0);
532
533                 cur_len += ms->len;
534                 ++ms;
535         }
536 }
537
538 int
539 rte_vfio_clear_group(int vfio_group_fd)
540 {
541         int i;
542         struct vfio_config *vfio_cfg;
543
544         vfio_cfg = get_vfio_cfg_by_group_fd(vfio_group_fd);
545         if (vfio_cfg == NULL) {
546                 RTE_LOG(ERR, EAL, "  invalid group fd!\n");
547                 return -1;
548         }
549
550         i = get_vfio_group_idx(vfio_group_fd);
551         if (i < 0)
552                 return -1;
553         vfio_cfg->vfio_groups[i].group_num = -1;
554         vfio_cfg->vfio_groups[i].fd = -1;
555         vfio_cfg->vfio_groups[i].devices = 0;
556         vfio_cfg->vfio_active_groups--;
557
558         return 0;
559 }
560
561 int
562 rte_vfio_setup_device(const char *sysfs_base, const char *dev_addr,
563                 int *vfio_dev_fd, struct vfio_device_info *device_info)
564 {
565         struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
566         rte_rwlock_t *mem_lock = &mcfg->memory_hotplug_lock;
567         struct vfio_group_status group_status = {
568                         .argsz = sizeof(group_status)
569         };
570         struct vfio_config *vfio_cfg;
571         struct user_mem_maps *user_mem_maps;
572         int vfio_container_fd;
573         int vfio_group_fd;
574         int iommu_group_num;
575         int i, ret;
576
577         /* get group number */
578         ret = rte_vfio_get_group_num(sysfs_base, dev_addr, &iommu_group_num);
579         if (ret == 0) {
580                 RTE_LOG(WARNING, EAL, "  %s not managed by VFIO driver, skipping\n",
581                         dev_addr);
582                 return 1;
583         }
584
585         /* if negative, something failed */
586         if (ret < 0)
587                 return -1;
588
589         /* get the actual group fd */
590         vfio_group_fd = rte_vfio_get_group_fd(iommu_group_num);
591         if (vfio_group_fd < 0)
592                 return -1;
593
594         /* if group_fd == 0, that means the device isn't managed by VFIO */
595         if (vfio_group_fd == 0) {
596                 RTE_LOG(WARNING, EAL, " %s not managed by VFIO driver, skipping\n",
597                                 dev_addr);
598                 return 1;
599         }
600
601         /*
602          * at this point, we know that this group is viable (meaning, all devices
603          * are either bound to VFIO or not bound to anything)
604          */
605
606         /* check if the group is viable */
607         ret = ioctl(vfio_group_fd, VFIO_GROUP_GET_STATUS, &group_status);
608         if (ret) {
609                 RTE_LOG(ERR, EAL, "  %s cannot get group status, "
610                                 "error %i (%s)\n", dev_addr, errno, strerror(errno));
611                 close(vfio_group_fd);
612                 rte_vfio_clear_group(vfio_group_fd);
613                 return -1;
614         } else if (!(group_status.flags & VFIO_GROUP_FLAGS_VIABLE)) {
615                 RTE_LOG(ERR, EAL, "  %s VFIO group is not viable!\n", dev_addr);
616                 close(vfio_group_fd);
617                 rte_vfio_clear_group(vfio_group_fd);
618                 return -1;
619         }
620
621         /* get the vfio_config it belongs to */
622         vfio_cfg = get_vfio_cfg_by_group_num(iommu_group_num);
623         vfio_cfg = vfio_cfg ? vfio_cfg : default_vfio_cfg;
624         vfio_container_fd = vfio_cfg->vfio_container_fd;
625         user_mem_maps = &vfio_cfg->mem_maps;
626
627         /* check if group does not have a container yet */
628         if (!(group_status.flags & VFIO_GROUP_FLAGS_CONTAINER_SET)) {
629
630                 /* add group to a container */
631                 ret = ioctl(vfio_group_fd, VFIO_GROUP_SET_CONTAINER,
632                                 &vfio_container_fd);
633                 if (ret) {
634                         RTE_LOG(ERR, EAL, "  %s cannot add VFIO group to container, "
635                                         "error %i (%s)\n", dev_addr, errno, strerror(errno));
636                         close(vfio_group_fd);
637                         rte_vfio_clear_group(vfio_group_fd);
638                         return -1;
639                 }
640
641                 /*
642                  * pick an IOMMU type and set up DMA mappings for container
643                  *
644                  * needs to be done only once, only when first group is
645                  * assigned to a container and only in primary process.
646                  * Note this can happen several times with the hotplug
647                  * functionality.
648                  */
649                 if (internal_config.process_type == RTE_PROC_PRIMARY &&
650                                 vfio_cfg->vfio_active_groups == 1 &&
651                                 vfio_group_device_count(vfio_group_fd) == 0) {
652                         const struct vfio_iommu_type *t;
653
654                         /* select an IOMMU type which we will be using */
655                         t = vfio_set_iommu_type(vfio_container_fd);
656                         if (!t) {
657                                 RTE_LOG(ERR, EAL,
658                                         "  %s failed to select IOMMU type\n",
659                                         dev_addr);
660                                 close(vfio_group_fd);
661                                 rte_vfio_clear_group(vfio_group_fd);
662                                 return -1;
663                         }
664                         /* lock memory hotplug before mapping and release it
665                          * after registering callback, to prevent races
666                          */
667                         rte_rwlock_read_lock(mem_lock);
668                         if (vfio_cfg == default_vfio_cfg)
669                                 ret = t->dma_map_func(vfio_container_fd);
670                         else
671                                 ret = 0;
672                         if (ret) {
673                                 RTE_LOG(ERR, EAL,
674                                         "  %s DMA remapping failed, error %i (%s)\n",
675                                         dev_addr, errno, strerror(errno));
676                                 close(vfio_group_fd);
677                                 rte_vfio_clear_group(vfio_group_fd);
678                                 rte_rwlock_read_unlock(mem_lock);
679                                 return -1;
680                         }
681
682                         vfio_cfg->vfio_iommu_type = t;
683
684                         /* re-map all user-mapped segments */
685                         rte_spinlock_recursive_lock(&user_mem_maps->lock);
686
687                         /* this IOMMU type may not support DMA mapping, but
688                          * if we have mappings in the list - that means we have
689                          * previously mapped something successfully, so we can
690                          * be sure that DMA mapping is supported.
691                          */
692                         for (i = 0; i < user_mem_maps->n_maps; i++) {
693                                 struct user_mem_map *map;
694                                 map = &user_mem_maps->maps[i];
695
696                                 ret = t->dma_user_map_func(
697                                                 vfio_container_fd,
698                                                 map->addr, map->iova, map->len,
699                                                 1);
700                                 if (ret) {
701                                         RTE_LOG(ERR, EAL, "Couldn't map user memory for DMA: "
702                                                         "va: 0x%" PRIx64 " "
703                                                         "iova: 0x%" PRIx64 " "
704                                                         "len: 0x%" PRIu64 "\n",
705                                                         map->addr, map->iova,
706                                                         map->len);
707                                         rte_spinlock_recursive_unlock(
708                                                         &user_mem_maps->lock);
709                                         rte_rwlock_read_unlock(mem_lock);
710                                         return -1;
711                                 }
712                         }
713                         rte_spinlock_recursive_unlock(&user_mem_maps->lock);
714
715                         /* register callback for mem events */
716                         if (vfio_cfg == default_vfio_cfg)
717                                 ret = rte_mem_event_callback_register(
718                                         VFIO_MEM_EVENT_CLB_NAME,
719                                         vfio_mem_event_callback, NULL);
720                         else
721                                 ret = 0;
722                         /* unlock memory hotplug */
723                         rte_rwlock_read_unlock(mem_lock);
724
725                         if (ret && rte_errno != ENOTSUP) {
726                                 RTE_LOG(ERR, EAL, "Could not install memory event callback for VFIO\n");
727                                 return -1;
728                         }
729                         if (ret)
730                                 RTE_LOG(DEBUG, EAL, "Memory event callbacks not supported\n");
731                         else
732                                 RTE_LOG(DEBUG, EAL, "Installed memory event callback for VFIO\n");
733                 }
734         }
735
736         /* get a file descriptor for the device */
737         *vfio_dev_fd = ioctl(vfio_group_fd, VFIO_GROUP_GET_DEVICE_FD, dev_addr);
738         if (*vfio_dev_fd < 0) {
739                 /* if we cannot get a device fd, this implies a problem with
740                  * the VFIO group or the container not having IOMMU configured.
741                  */
742
743                 RTE_LOG(WARNING, EAL, "Getting a vfio_dev_fd for %s failed\n",
744                                 dev_addr);
745                 close(vfio_group_fd);
746                 rte_vfio_clear_group(vfio_group_fd);
747                 return -1;
748         }
749
750         /* test and setup the device */
751         ret = ioctl(*vfio_dev_fd, VFIO_DEVICE_GET_INFO, device_info);
752         if (ret) {
753                 RTE_LOG(ERR, EAL, "  %s cannot get device info, "
754                                 "error %i (%s)\n", dev_addr, errno,
755                                 strerror(errno));
756                 close(*vfio_dev_fd);
757                 close(vfio_group_fd);
758                 rte_vfio_clear_group(vfio_group_fd);
759                 return -1;
760         }
761         vfio_group_device_get(vfio_group_fd);
762
763         return 0;
764 }
765
766 int
767 rte_vfio_release_device(const char *sysfs_base, const char *dev_addr,
768                     int vfio_dev_fd)
769 {
770         struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
771         rte_rwlock_t *mem_lock = &mcfg->memory_hotplug_lock;
772         struct vfio_group_status group_status = {
773                         .argsz = sizeof(group_status)
774         };
775         struct vfio_config *vfio_cfg;
776         int vfio_group_fd;
777         int iommu_group_num;
778         int ret;
779
780         /* we don't want any DMA mapping messages to come while we're detaching
781          * VFIO device, because this might be the last device and we might need
782          * to unregister the callback.
783          */
784         rte_rwlock_read_lock(mem_lock);
785
786         /* get group number */
787         ret = rte_vfio_get_group_num(sysfs_base, dev_addr, &iommu_group_num);
788         if (ret <= 0) {
789                 RTE_LOG(WARNING, EAL, "  %s not managed by VFIO driver\n",
790                         dev_addr);
791                 /* This is an error at this point. */
792                 ret = -1;
793                 goto out;
794         }
795
796         /* get the actual group fd */
797         vfio_group_fd = rte_vfio_get_group_fd(iommu_group_num);
798         if (vfio_group_fd <= 0) {
799                 RTE_LOG(INFO, EAL, "rte_vfio_get_group_fd failed for %s\n",
800                                    dev_addr);
801                 ret = -1;
802                 goto out;
803         }
804
805         /* get the vfio_config it belongs to */
806         vfio_cfg = get_vfio_cfg_by_group_num(iommu_group_num);
807         vfio_cfg = vfio_cfg ? vfio_cfg : default_vfio_cfg;
808
809         /* At this point we got an active group. Closing it will make the
810          * container detachment. If this is the last active group, VFIO kernel
811          * code will unset the container and the IOMMU mappings.
812          */
813
814         /* Closing a device */
815         if (close(vfio_dev_fd) < 0) {
816                 RTE_LOG(INFO, EAL, "Error when closing vfio_dev_fd for %s\n",
817                                    dev_addr);
818                 ret = -1;
819                 goto out;
820         }
821
822         /* An VFIO group can have several devices attached. Just when there is
823          * no devices remaining should the group be closed.
824          */
825         vfio_group_device_put(vfio_group_fd);
826         if (!vfio_group_device_count(vfio_group_fd)) {
827
828                 if (close(vfio_group_fd) < 0) {
829                         RTE_LOG(INFO, EAL, "Error when closing vfio_group_fd for %s\n",
830                                 dev_addr);
831                         ret = -1;
832                         goto out;
833                 }
834
835                 if (rte_vfio_clear_group(vfio_group_fd) < 0) {
836                         RTE_LOG(INFO, EAL, "Error when clearing group for %s\n",
837                                            dev_addr);
838                         ret = -1;
839                         goto out;
840                 }
841         }
842
843         /* if there are no active device groups, unregister the callback to
844          * avoid spurious attempts to map/unmap memory from VFIO.
845          */
846         if (vfio_cfg == default_vfio_cfg && vfio_cfg->vfio_active_groups == 0)
847                 rte_mem_event_callback_unregister(VFIO_MEM_EVENT_CLB_NAME,
848                                 NULL);
849
850         /* success */
851         ret = 0;
852
853 out:
854         rte_rwlock_read_unlock(mem_lock);
855         return ret;
856 }
857
858 int
859 rte_vfio_enable(const char *modname)
860 {
861         /* initialize group list */
862         int i, j;
863         int vfio_available;
864
865         rte_spinlock_recursive_t lock = RTE_SPINLOCK_RECURSIVE_INITIALIZER;
866
867         for (i = 0; i < VFIO_MAX_CONTAINERS; i++) {
868                 vfio_cfgs[i].vfio_container_fd = -1;
869                 vfio_cfgs[i].vfio_active_groups = 0;
870                 vfio_cfgs[i].vfio_iommu_type = NULL;
871                 vfio_cfgs[i].mem_maps.lock = lock;
872
873                 for (j = 0; j < VFIO_MAX_GROUPS; j++) {
874                         vfio_cfgs[i].vfio_groups[j].fd = -1;
875                         vfio_cfgs[i].vfio_groups[j].group_num = -1;
876                         vfio_cfgs[i].vfio_groups[j].devices = 0;
877                 }
878         }
879
880         /* inform the user that we are probing for VFIO */
881         RTE_LOG(INFO, EAL, "Probing VFIO support...\n");
882
883         /* check if vfio module is loaded */
884         vfio_available = rte_eal_check_module(modname);
885
886         /* return error directly */
887         if (vfio_available == -1) {
888                 RTE_LOG(INFO, EAL, "Could not get loaded module details!\n");
889                 return -1;
890         }
891
892         /* return 0 if VFIO modules not loaded */
893         if (vfio_available == 0) {
894                 RTE_LOG(DEBUG, EAL, "VFIO modules not loaded, "
895                         "skipping VFIO support...\n");
896                 return 0;
897         }
898
899         default_vfio_cfg->vfio_container_fd = rte_vfio_get_container_fd();
900
901         /* check if we have VFIO driver enabled */
902         if (default_vfio_cfg->vfio_container_fd != -1) {
903                 RTE_LOG(NOTICE, EAL, "VFIO support initialized\n");
904                 default_vfio_cfg->vfio_enabled = 1;
905         } else {
906                 RTE_LOG(NOTICE, EAL, "VFIO support could not be initialized\n");
907         }
908
909         return 0;
910 }
911
912 int
913 rte_vfio_is_enabled(const char *modname)
914 {
915         const int mod_available = rte_eal_check_module(modname) > 0;
916         return default_vfio_cfg->vfio_enabled && mod_available;
917 }
918
919 const struct vfio_iommu_type *
920 vfio_set_iommu_type(int vfio_container_fd)
921 {
922         unsigned idx;
923         for (idx = 0; idx < RTE_DIM(iommu_types); idx++) {
924                 const struct vfio_iommu_type *t = &iommu_types[idx];
925
926                 int ret = ioctl(vfio_container_fd, VFIO_SET_IOMMU,
927                                 t->type_id);
928                 if (!ret) {
929                         RTE_LOG(NOTICE, EAL, "  using IOMMU type %d (%s)\n",
930                                         t->type_id, t->name);
931                         return t;
932                 }
933                 /* not an error, there may be more supported IOMMU types */
934                 RTE_LOG(DEBUG, EAL, "  set IOMMU type %d (%s) failed, "
935                                 "error %i (%s)\n", t->type_id, t->name, errno,
936                                 strerror(errno));
937         }
938         /* if we didn't find a suitable IOMMU type, fail */
939         return NULL;
940 }
941
942 int
943 vfio_has_supported_extensions(int vfio_container_fd)
944 {
945         int ret;
946         unsigned idx, n_extensions = 0;
947         for (idx = 0; idx < RTE_DIM(iommu_types); idx++) {
948                 const struct vfio_iommu_type *t = &iommu_types[idx];
949
950                 ret = ioctl(vfio_container_fd, VFIO_CHECK_EXTENSION,
951                                 t->type_id);
952                 if (ret < 0) {
953                         RTE_LOG(ERR, EAL, "  could not get IOMMU type, "
954                                 "error %i (%s)\n", errno,
955                                 strerror(errno));
956                         close(vfio_container_fd);
957                         return -1;
958                 } else if (ret == 1) {
959                         /* we found a supported extension */
960                         n_extensions++;
961                 }
962                 RTE_LOG(DEBUG, EAL, "  IOMMU type %d (%s) is %s\n",
963                                 t->type_id, t->name,
964                                 ret ? "supported" : "not supported");
965         }
966
967         /* if we didn't find any supported IOMMU types, fail */
968         if (!n_extensions) {
969                 close(vfio_container_fd);
970                 return -1;
971         }
972
973         return 0;
974 }
975
976 int
977 rte_vfio_get_container_fd(void)
978 {
979         int ret, vfio_container_fd;
980         struct rte_mp_msg mp_req, *mp_rep;
981         struct rte_mp_reply mp_reply;
982         struct timespec ts = {.tv_sec = 5, .tv_nsec = 0};
983         struct vfio_mp_param *p = (struct vfio_mp_param *)mp_req.param;
984
985
986         /* if we're in a primary process, try to open the container */
987         if (internal_config.process_type == RTE_PROC_PRIMARY) {
988                 vfio_container_fd = open(VFIO_CONTAINER_PATH, O_RDWR);
989                 if (vfio_container_fd < 0) {
990                         RTE_LOG(ERR, EAL, "  cannot open VFIO container, "
991                                         "error %i (%s)\n", errno, strerror(errno));
992                         return -1;
993                 }
994
995                 /* check VFIO API version */
996                 ret = ioctl(vfio_container_fd, VFIO_GET_API_VERSION);
997                 if (ret != VFIO_API_VERSION) {
998                         if (ret < 0)
999                                 RTE_LOG(ERR, EAL, "  could not get VFIO API version, "
1000                                                 "error %i (%s)\n", errno, strerror(errno));
1001                         else
1002                                 RTE_LOG(ERR, EAL, "  unsupported VFIO API version!\n");
1003                         close(vfio_container_fd);
1004                         return -1;
1005                 }
1006
1007                 ret = vfio_has_supported_extensions(vfio_container_fd);
1008                 if (ret) {
1009                         RTE_LOG(ERR, EAL, "  no supported IOMMU "
1010                                         "extensions found!\n");
1011                         return -1;
1012                 }
1013
1014                 return vfio_container_fd;
1015         }
1016         /*
1017          * if we're in a secondary process, request container fd from the
1018          * primary process via mp channel
1019          */
1020         p->req = SOCKET_REQ_CONTAINER;
1021         strcpy(mp_req.name, EAL_VFIO_MP);
1022         mp_req.len_param = sizeof(*p);
1023         mp_req.num_fds = 0;
1024
1025         vfio_container_fd = -1;
1026         if (rte_mp_request_sync(&mp_req, &mp_reply, &ts) == 0 &&
1027             mp_reply.nb_received == 1) {
1028                 mp_rep = &mp_reply.msgs[0];
1029                 p = (struct vfio_mp_param *)mp_rep->param;
1030                 if (p->result == SOCKET_OK && mp_rep->num_fds == 1) {
1031                         free(mp_reply.msgs);
1032                         return mp_rep->fds[0];
1033                 }
1034                 free(mp_reply.msgs);
1035         }
1036
1037         RTE_LOG(ERR, EAL, "  cannot request container fd\n");
1038         return -1;
1039 }
1040
1041 int
1042 rte_vfio_get_group_num(const char *sysfs_base,
1043                 const char *dev_addr, int *iommu_group_num)
1044 {
1045         char linkname[PATH_MAX];
1046         char filename[PATH_MAX];
1047         char *tok[16], *group_tok, *end;
1048         int ret;
1049
1050         memset(linkname, 0, sizeof(linkname));
1051         memset(filename, 0, sizeof(filename));
1052
1053         /* try to find out IOMMU group for this device */
1054         snprintf(linkname, sizeof(linkname),
1055                          "%s/%s/iommu_group", sysfs_base, dev_addr);
1056
1057         ret = readlink(linkname, filename, sizeof(filename));
1058
1059         /* if the link doesn't exist, no VFIO for us */
1060         if (ret < 0)
1061                 return 0;
1062
1063         ret = rte_strsplit(filename, sizeof(filename),
1064                         tok, RTE_DIM(tok), '/');
1065
1066         if (ret <= 0) {
1067                 RTE_LOG(ERR, EAL, "  %s cannot get IOMMU group\n", dev_addr);
1068                 return -1;
1069         }
1070
1071         /* IOMMU group is always the last token */
1072         errno = 0;
1073         group_tok = tok[ret - 1];
1074         end = group_tok;
1075         *iommu_group_num = strtol(group_tok, &end, 10);
1076         if ((end != group_tok && *end != '\0') || errno != 0) {
1077                 RTE_LOG(ERR, EAL, "  %s error parsing IOMMU number!\n", dev_addr);
1078                 return -1;
1079         }
1080
1081         return 1;
1082 }
1083
1084 static int
1085 type1_map(const struct rte_memseg_list *msl, const struct rte_memseg *ms,
1086                 void *arg)
1087 {
1088         int *vfio_container_fd = arg;
1089
1090         if (msl->external)
1091                 return 0;
1092
1093         return vfio_type1_dma_mem_map(*vfio_container_fd, ms->addr_64, ms->iova,
1094                         ms->len, 1);
1095 }
1096
1097 static int
1098 vfio_type1_dma_mem_map(int vfio_container_fd, uint64_t vaddr, uint64_t iova,
1099                 uint64_t len, int do_map)
1100 {
1101         struct vfio_iommu_type1_dma_map dma_map;
1102         struct vfio_iommu_type1_dma_unmap dma_unmap;
1103         int ret;
1104
1105         if (do_map != 0) {
1106                 memset(&dma_map, 0, sizeof(dma_map));
1107                 dma_map.argsz = sizeof(struct vfio_iommu_type1_dma_map);
1108                 dma_map.vaddr = vaddr;
1109                 dma_map.size = len;
1110                 dma_map.iova = iova;
1111                 dma_map.flags = VFIO_DMA_MAP_FLAG_READ |
1112                                 VFIO_DMA_MAP_FLAG_WRITE;
1113
1114                 ret = ioctl(vfio_container_fd, VFIO_IOMMU_MAP_DMA, &dma_map);
1115                 if (ret) {
1116                         RTE_LOG(ERR, EAL, "  cannot set up DMA remapping, error %i (%s)\n",
1117                                 errno, strerror(errno));
1118                                 return -1;
1119                 }
1120         } else {
1121                 memset(&dma_unmap, 0, sizeof(dma_unmap));
1122                 dma_unmap.argsz = sizeof(struct vfio_iommu_type1_dma_unmap);
1123                 dma_unmap.size = len;
1124                 dma_unmap.iova = iova;
1125
1126                 ret = ioctl(vfio_container_fd, VFIO_IOMMU_UNMAP_DMA,
1127                                 &dma_unmap);
1128                 if (ret) {
1129                         RTE_LOG(ERR, EAL, "  cannot clear DMA remapping, error %i (%s)\n",
1130                                         errno, strerror(errno));
1131                         return -1;
1132                 }
1133         }
1134
1135         return 0;
1136 }
1137
1138 static int
1139 vfio_type1_dma_map(int vfio_container_fd)
1140 {
1141         return rte_memseg_walk(type1_map, &vfio_container_fd);
1142 }
1143
1144 static int
1145 vfio_spapr_dma_do_map(int vfio_container_fd, uint64_t vaddr, uint64_t iova,
1146                 uint64_t len, int do_map)
1147 {
1148         struct vfio_iommu_type1_dma_map dma_map;
1149         struct vfio_iommu_type1_dma_unmap dma_unmap;
1150         int ret;
1151
1152         if (do_map != 0) {
1153                 memset(&dma_map, 0, sizeof(dma_map));
1154                 dma_map.argsz = sizeof(struct vfio_iommu_type1_dma_map);
1155                 dma_map.vaddr = vaddr;
1156                 dma_map.size = len;
1157                 dma_map.iova = iova;
1158                 dma_map.flags = VFIO_DMA_MAP_FLAG_READ |
1159                                 VFIO_DMA_MAP_FLAG_WRITE;
1160
1161                 ret = ioctl(vfio_container_fd, VFIO_IOMMU_MAP_DMA, &dma_map);
1162                 if (ret) {
1163                         RTE_LOG(ERR, EAL, "  cannot set up DMA remapping, error %i (%s)\n",
1164                                 errno, strerror(errno));
1165                                 return -1;
1166                 }
1167
1168         } else {
1169                 struct vfio_iommu_spapr_register_memory reg = {
1170                         .argsz = sizeof(reg),
1171                         .flags = 0
1172                 };
1173                 reg.vaddr = (uintptr_t) vaddr;
1174                 reg.size = len;
1175
1176                 ret = ioctl(vfio_container_fd,
1177                                 VFIO_IOMMU_SPAPR_UNREGISTER_MEMORY, &reg);
1178                 if (ret) {
1179                         RTE_LOG(ERR, EAL, "  cannot unregister vaddr for IOMMU, error %i (%s)\n",
1180                                         errno, strerror(errno));
1181                         return -1;
1182                 }
1183
1184                 memset(&dma_unmap, 0, sizeof(dma_unmap));
1185                 dma_unmap.argsz = sizeof(struct vfio_iommu_type1_dma_unmap);
1186                 dma_unmap.size = len;
1187                 dma_unmap.iova = iova;
1188
1189                 ret = ioctl(vfio_container_fd, VFIO_IOMMU_UNMAP_DMA,
1190                                 &dma_unmap);
1191                 if (ret) {
1192                         RTE_LOG(ERR, EAL, "  cannot clear DMA remapping, error %i (%s)\n",
1193                                         errno, strerror(errno));
1194                         return -1;
1195                 }
1196         }
1197
1198         return 0;
1199 }
1200
1201 static int
1202 vfio_spapr_map_walk(const struct rte_memseg_list *msl,
1203                 const struct rte_memseg *ms, void *arg)
1204 {
1205         int *vfio_container_fd = arg;
1206
1207         if (msl->external)
1208                 return 0;
1209
1210         return vfio_spapr_dma_mem_map(*vfio_container_fd, ms->addr_64, ms->iova,
1211                         ms->len, 1);
1212 }
1213
1214 struct spapr_walk_param {
1215         uint64_t window_size;
1216         uint64_t hugepage_sz;
1217 };
1218 static int
1219 vfio_spapr_window_size_walk(const struct rte_memseg_list *msl,
1220                 const struct rte_memseg *ms, void *arg)
1221 {
1222         struct spapr_walk_param *param = arg;
1223         uint64_t max = ms->iova + ms->len;
1224
1225         if (msl->external)
1226                 return 0;
1227
1228         if (max > param->window_size) {
1229                 param->hugepage_sz = ms->hugepage_sz;
1230                 param->window_size = max;
1231         }
1232
1233         return 0;
1234 }
1235
1236 static int
1237 vfio_spapr_create_new_dma_window(int vfio_container_fd,
1238                 struct vfio_iommu_spapr_tce_create *create) {
1239         struct vfio_iommu_spapr_tce_remove remove = {
1240                 .argsz = sizeof(remove),
1241         };
1242         struct vfio_iommu_spapr_tce_info info = {
1243                 .argsz = sizeof(info),
1244         };
1245         int ret;
1246
1247         /* query spapr iommu info */
1248         ret = ioctl(vfio_container_fd, VFIO_IOMMU_SPAPR_TCE_GET_INFO, &info);
1249         if (ret) {
1250                 RTE_LOG(ERR, EAL, "  cannot get iommu info, "
1251                                 "error %i (%s)\n", errno, strerror(errno));
1252                 return -1;
1253         }
1254
1255         /* remove default DMA of 32 bit window */
1256         remove.start_addr = info.dma32_window_start;
1257         ret = ioctl(vfio_container_fd, VFIO_IOMMU_SPAPR_TCE_REMOVE, &remove);
1258         if (ret) {
1259                 RTE_LOG(ERR, EAL, "  cannot remove default DMA window, "
1260                                 "error %i (%s)\n", errno, strerror(errno));
1261                 return -1;
1262         }
1263
1264         /* create new DMA window */
1265         ret = ioctl(vfio_container_fd, VFIO_IOMMU_SPAPR_TCE_CREATE, create);
1266         if (ret) {
1267                 RTE_LOG(ERR, EAL, "  cannot create new DMA window, "
1268                                 "error %i (%s)\n", errno, strerror(errno));
1269                 return -1;
1270         }
1271
1272         if (create->start_addr != 0) {
1273                 RTE_LOG(ERR, EAL, "  DMA window start address != 0\n");
1274                 return -1;
1275         }
1276
1277         return 0;
1278 }
1279
1280 static int
1281 vfio_spapr_dma_mem_map(int vfio_container_fd, uint64_t vaddr, uint64_t iova,
1282                 uint64_t len, int do_map)
1283 {
1284         struct spapr_walk_param param;
1285         struct vfio_iommu_spapr_tce_create create = {
1286                 .argsz = sizeof(create),
1287         };
1288         struct vfio_config *vfio_cfg;
1289         struct user_mem_maps *user_mem_maps;
1290         int i, ret = 0;
1291
1292         vfio_cfg = get_vfio_cfg_by_container_fd(vfio_container_fd);
1293         if (vfio_cfg == NULL) {
1294                 RTE_LOG(ERR, EAL, "  invalid container fd!\n");
1295                 return -1;
1296         }
1297
1298         user_mem_maps = &vfio_cfg->mem_maps;
1299         rte_spinlock_recursive_lock(&user_mem_maps->lock);
1300
1301         /* check if window size needs to be adjusted */
1302         memset(&param, 0, sizeof(param));
1303
1304         /* we're inside a callback so use thread-unsafe version */
1305         if (rte_memseg_walk_thread_unsafe(vfio_spapr_window_size_walk,
1306                                 &param) < 0) {
1307                 RTE_LOG(ERR, EAL, "Could not get window size\n");
1308                 ret = -1;
1309                 goto out;
1310         }
1311
1312         /* also check user maps */
1313         for (i = 0; i < user_mem_maps->n_maps; i++) {
1314                 uint64_t max = user_mem_maps->maps[i].iova +
1315                                 user_mem_maps->maps[i].len;
1316                 create.window_size = RTE_MAX(create.window_size, max);
1317         }
1318
1319         /* sPAPR requires window size to be a power of 2 */
1320         create.window_size = rte_align64pow2(param.window_size);
1321         create.page_shift = __builtin_ctzll(param.hugepage_sz);
1322         create.levels = 1;
1323
1324         if (do_map) {
1325                 void *addr;
1326                 /* re-create window and remap the entire memory */
1327                 if (iova > create.window_size) {
1328                         if (vfio_spapr_create_new_dma_window(vfio_container_fd,
1329                                         &create) < 0) {
1330                                 RTE_LOG(ERR, EAL, "Could not create new DMA window\n");
1331                                 ret = -1;
1332                                 goto out;
1333                         }
1334                         /* we're inside a callback, so use thread-unsafe version
1335                          */
1336                         if (rte_memseg_walk_thread_unsafe(vfio_spapr_map_walk,
1337                                         &vfio_container_fd) < 0) {
1338                                 RTE_LOG(ERR, EAL, "Could not recreate DMA maps\n");
1339                                 ret = -1;
1340                                 goto out;
1341                         }
1342                         /* remap all user maps */
1343                         for (i = 0; i < user_mem_maps->n_maps; i++) {
1344                                 struct user_mem_map *map =
1345                                                 &user_mem_maps->maps[i];
1346                                 if (vfio_spapr_dma_do_map(vfio_container_fd,
1347                                                 map->addr, map->iova, map->len,
1348                                                 1)) {
1349                                         RTE_LOG(ERR, EAL, "Could not recreate user DMA maps\n");
1350                                         ret = -1;
1351                                         goto out;
1352                                 }
1353                         }
1354                 }
1355
1356                 /* now that we've remapped all of the memory that was present
1357                  * before, map the segment that we were requested to map.
1358                  *
1359                  * however, if we were called by the callback, the memory we
1360                  * were called with was already in the memseg list, so previous
1361                  * mapping should've mapped that segment already.
1362                  *
1363                  * virt2memseg_list is a relatively cheap check, so use that. if
1364                  * memory is within any memseg list, it's a memseg, so it's
1365                  * already mapped.
1366                  */
1367                 addr = (void *)(uintptr_t)vaddr;
1368                 if (rte_mem_virt2memseg_list(addr) == NULL &&
1369                                 vfio_spapr_dma_do_map(vfio_container_fd,
1370                                         vaddr, iova, len, 1) < 0) {
1371                         RTE_LOG(ERR, EAL, "Could not map segment\n");
1372                         ret = -1;
1373                         goto out;
1374                 }
1375         } else {
1376                 /* for unmap, check if iova within DMA window */
1377                 if (iova > create.window_size) {
1378                         RTE_LOG(ERR, EAL, "iova beyond DMA window for unmap");
1379                         ret = -1;
1380                         goto out;
1381                 }
1382
1383                 vfio_spapr_dma_do_map(vfio_container_fd, vaddr, iova, len, 0);
1384         }
1385 out:
1386         rte_spinlock_recursive_unlock(&user_mem_maps->lock);
1387         return ret;
1388 }
1389
1390 static int
1391 vfio_spapr_dma_map(int vfio_container_fd)
1392 {
1393         struct vfio_iommu_spapr_tce_create create = {
1394                 .argsz = sizeof(create),
1395         };
1396         struct spapr_walk_param param;
1397
1398         memset(&param, 0, sizeof(param));
1399
1400         /* create DMA window from 0 to max(phys_addr + len) */
1401         rte_memseg_walk(vfio_spapr_window_size_walk, &param);
1402
1403         /* sPAPR requires window size to be a power of 2 */
1404         create.window_size = rte_align64pow2(param.window_size);
1405         create.page_shift = __builtin_ctzll(param.hugepage_sz);
1406         create.levels = 1;
1407
1408         if (vfio_spapr_create_new_dma_window(vfio_container_fd, &create) < 0) {
1409                 RTE_LOG(ERR, EAL, "Could not create new DMA window\n");
1410                 return -1;
1411         }
1412
1413         /* map all DPDK segments for DMA. use 1:1 PA to IOVA mapping */
1414         if (rte_memseg_walk(vfio_spapr_map_walk, &vfio_container_fd) < 0)
1415                 return -1;
1416
1417         return 0;
1418 }
1419
1420 static int
1421 vfio_noiommu_dma_map(int __rte_unused vfio_container_fd)
1422 {
1423         /* No-IOMMU mode does not need DMA mapping */
1424         return 0;
1425 }
1426
1427 static int
1428 vfio_noiommu_dma_mem_map(int __rte_unused vfio_container_fd,
1429                          uint64_t __rte_unused vaddr,
1430                          uint64_t __rte_unused iova, uint64_t __rte_unused len,
1431                          int __rte_unused do_map)
1432 {
1433         /* No-IOMMU mode does not need DMA mapping */
1434         return 0;
1435 }
1436
1437 static int
1438 vfio_dma_mem_map(struct vfio_config *vfio_cfg, uint64_t vaddr, uint64_t iova,
1439                 uint64_t len, int do_map)
1440 {
1441         const struct vfio_iommu_type *t = vfio_cfg->vfio_iommu_type;
1442
1443         if (!t) {
1444                 RTE_LOG(ERR, EAL, "  VFIO support not initialized\n");
1445                 rte_errno = ENODEV;
1446                 return -1;
1447         }
1448
1449         if (!t->dma_user_map_func) {
1450                 RTE_LOG(ERR, EAL,
1451                         "  VFIO custom DMA region maping not supported by IOMMU %s\n",
1452                         t->name);
1453                 rte_errno = ENOTSUP;
1454                 return -1;
1455         }
1456
1457         return t->dma_user_map_func(vfio_cfg->vfio_container_fd, vaddr, iova,
1458                         len, do_map);
1459 }
1460
1461 static int
1462 container_dma_map(struct vfio_config *vfio_cfg, uint64_t vaddr, uint64_t iova,
1463                 uint64_t len)
1464 {
1465         struct user_mem_map *new_map;
1466         struct user_mem_maps *user_mem_maps;
1467         int ret = 0;
1468
1469         user_mem_maps = &vfio_cfg->mem_maps;
1470         rte_spinlock_recursive_lock(&user_mem_maps->lock);
1471         if (user_mem_maps->n_maps == VFIO_MAX_USER_MEM_MAPS) {
1472                 RTE_LOG(ERR, EAL, "No more space for user mem maps\n");
1473                 rte_errno = ENOMEM;
1474                 ret = -1;
1475                 goto out;
1476         }
1477         /* map the entry */
1478         if (vfio_dma_mem_map(vfio_cfg, vaddr, iova, len, 1)) {
1479                 /* technically, this will fail if there are currently no devices
1480                  * plugged in, even if a device were added later, this mapping
1481                  * might have succeeded. however, since we cannot verify if this
1482                  * is a valid mapping without having a device attached, consider
1483                  * this to be unsupported, because we can't just store any old
1484                  * mapping and pollute list of active mappings willy-nilly.
1485                  */
1486                 RTE_LOG(ERR, EAL, "Couldn't map new region for DMA\n");
1487                 ret = -1;
1488                 goto out;
1489         }
1490         /* create new user mem map entry */
1491         new_map = &user_mem_maps->maps[user_mem_maps->n_maps++];
1492         new_map->addr = vaddr;
1493         new_map->iova = iova;
1494         new_map->len = len;
1495
1496         compact_user_maps(user_mem_maps);
1497 out:
1498         rte_spinlock_recursive_unlock(&user_mem_maps->lock);
1499         return ret;
1500 }
1501
1502 static int
1503 container_dma_unmap(struct vfio_config *vfio_cfg, uint64_t vaddr, uint64_t iova,
1504                 uint64_t len)
1505 {
1506         struct user_mem_map *map, *new_map = NULL;
1507         struct user_mem_maps *user_mem_maps;
1508         int ret = 0;
1509
1510         user_mem_maps = &vfio_cfg->mem_maps;
1511         rte_spinlock_recursive_lock(&user_mem_maps->lock);
1512
1513         /* find our mapping */
1514         map = find_user_mem_map(user_mem_maps, vaddr, iova, len);
1515         if (!map) {
1516                 RTE_LOG(ERR, EAL, "Couldn't find previously mapped region\n");
1517                 rte_errno = EINVAL;
1518                 ret = -1;
1519                 goto out;
1520         }
1521         if (map->addr != vaddr || map->iova != iova || map->len != len) {
1522                 /* we're partially unmapping a previously mapped region, so we
1523                  * need to split entry into two.
1524                  */
1525                 if (user_mem_maps->n_maps == VFIO_MAX_USER_MEM_MAPS) {
1526                         RTE_LOG(ERR, EAL, "Not enough space to store partial mapping\n");
1527                         rte_errno = ENOMEM;
1528                         ret = -1;
1529                         goto out;
1530                 }
1531                 new_map = &user_mem_maps->maps[user_mem_maps->n_maps++];
1532         }
1533
1534         /* unmap the entry */
1535         if (vfio_dma_mem_map(vfio_cfg, vaddr, iova, len, 0)) {
1536                 /* there may not be any devices plugged in, so unmapping will
1537                  * fail with ENODEV/ENOTSUP rte_errno values, but that doesn't
1538                  * stop us from removing the mapping, as the assumption is we
1539                  * won't be needing this memory any more and thus will want to
1540                  * prevent it from being remapped again on hotplug. so, only
1541                  * fail if we indeed failed to unmap (e.g. if the mapping was
1542                  * within our mapped range but had invalid alignment).
1543                  */
1544                 if (rte_errno != ENODEV && rte_errno != ENOTSUP) {
1545                         RTE_LOG(ERR, EAL, "Couldn't unmap region for DMA\n");
1546                         ret = -1;
1547                         goto out;
1548                 } else {
1549                         RTE_LOG(DEBUG, EAL, "DMA unmapping failed, but removing mappings anyway\n");
1550                 }
1551         }
1552         /* remove map from the list of active mappings */
1553         if (new_map != NULL) {
1554                 adjust_map(map, new_map, vaddr, len);
1555
1556                 /* if we've created a new map by splitting, sort everything */
1557                 if (!is_null_map(new_map)) {
1558                         compact_user_maps(user_mem_maps);
1559                 } else {
1560                         /* we've created a new mapping, but it was unused */
1561                         user_mem_maps->n_maps--;
1562                 }
1563         } else {
1564                 memset(map, 0, sizeof(*map));
1565                 compact_user_maps(user_mem_maps);
1566                 user_mem_maps->n_maps--;
1567         }
1568
1569 out:
1570         rte_spinlock_recursive_unlock(&user_mem_maps->lock);
1571         return ret;
1572 }
1573
1574 int
1575 rte_vfio_dma_map(uint64_t vaddr, uint64_t iova, uint64_t len)
1576 {
1577         if (len == 0) {
1578                 rte_errno = EINVAL;
1579                 return -1;
1580         }
1581
1582         return container_dma_map(default_vfio_cfg, vaddr, iova, len);
1583 }
1584
1585 int
1586 rte_vfio_dma_unmap(uint64_t vaddr, uint64_t iova, uint64_t len)
1587 {
1588         if (len == 0) {
1589                 rte_errno = EINVAL;
1590                 return -1;
1591         }
1592
1593         return container_dma_unmap(default_vfio_cfg, vaddr, iova, len);
1594 }
1595
1596 int
1597 rte_vfio_noiommu_is_enabled(void)
1598 {
1599         int fd;
1600         ssize_t cnt;
1601         char c;
1602
1603         fd = open(VFIO_NOIOMMU_MODE, O_RDONLY);
1604         if (fd < 0) {
1605                 if (errno != ENOENT) {
1606                         RTE_LOG(ERR, EAL, "  cannot open vfio noiommu file %i (%s)\n",
1607                                         errno, strerror(errno));
1608                         return -1;
1609                 }
1610                 /*
1611                  * else the file does not exists
1612                  * i.e. noiommu is not enabled
1613                  */
1614                 return 0;
1615         }
1616
1617         cnt = read(fd, &c, 1);
1618         close(fd);
1619         if (cnt != 1) {
1620                 RTE_LOG(ERR, EAL, "  unable to read from vfio noiommu "
1621                                 "file %i (%s)\n", errno, strerror(errno));
1622                 return -1;
1623         }
1624
1625         return c == 'Y';
1626 }
1627
1628 int
1629 rte_vfio_container_create(void)
1630 {
1631         int i;
1632
1633         /* Find an empty slot to store new vfio config */
1634         for (i = 1; i < VFIO_MAX_CONTAINERS; i++) {
1635                 if (vfio_cfgs[i].vfio_container_fd == -1)
1636                         break;
1637         }
1638
1639         if (i == VFIO_MAX_CONTAINERS) {
1640                 RTE_LOG(ERR, EAL, "exceed max vfio container limit\n");
1641                 return -1;
1642         }
1643
1644         vfio_cfgs[i].vfio_container_fd = rte_vfio_get_container_fd();
1645         if (vfio_cfgs[i].vfio_container_fd < 0) {
1646                 RTE_LOG(NOTICE, EAL, "fail to create a new container\n");
1647                 return -1;
1648         }
1649
1650         return vfio_cfgs[i].vfio_container_fd;
1651 }
1652
1653 int __rte_experimental
1654 rte_vfio_container_destroy(int container_fd)
1655 {
1656         struct vfio_config *vfio_cfg;
1657         int i;
1658
1659         vfio_cfg = get_vfio_cfg_by_container_fd(container_fd);
1660         if (vfio_cfg == NULL) {
1661                 RTE_LOG(ERR, EAL, "Invalid container fd\n");
1662                 return -1;
1663         }
1664
1665         for (i = 0; i < VFIO_MAX_GROUPS; i++)
1666                 if (vfio_cfg->vfio_groups[i].group_num != -1)
1667                         rte_vfio_container_group_unbind(container_fd,
1668                                 vfio_cfg->vfio_groups[i].group_num);
1669
1670         close(container_fd);
1671         vfio_cfg->vfio_container_fd = -1;
1672         vfio_cfg->vfio_active_groups = 0;
1673         vfio_cfg->vfio_iommu_type = NULL;
1674
1675         return 0;
1676 }
1677
1678 int
1679 rte_vfio_container_group_bind(int container_fd, int iommu_group_num)
1680 {
1681         struct vfio_config *vfio_cfg;
1682         struct vfio_group *cur_grp;
1683         int vfio_group_fd;
1684         int i;
1685
1686         vfio_cfg = get_vfio_cfg_by_container_fd(container_fd);
1687         if (vfio_cfg == NULL) {
1688                 RTE_LOG(ERR, EAL, "Invalid container fd\n");
1689                 return -1;
1690         }
1691
1692         /* Check room for new group */
1693         if (vfio_cfg->vfio_active_groups == VFIO_MAX_GROUPS) {
1694                 RTE_LOG(ERR, EAL, "Maximum number of VFIO groups reached!\n");
1695                 return -1;
1696         }
1697
1698         /* Get an index for the new group */
1699         for (i = 0; i < VFIO_MAX_GROUPS; i++)
1700                 if (vfio_cfg->vfio_groups[i].group_num == -1) {
1701                         cur_grp = &vfio_cfg->vfio_groups[i];
1702                         break;
1703                 }
1704
1705         /* This should not happen */
1706         if (i == VFIO_MAX_GROUPS) {
1707                 RTE_LOG(ERR, EAL, "No VFIO group free slot found\n");
1708                 return -1;
1709         }
1710
1711         vfio_group_fd = vfio_open_group_fd(iommu_group_num);
1712         if (vfio_group_fd < 0) {
1713                 RTE_LOG(ERR, EAL, "Failed to open group %d\n", iommu_group_num);
1714                 return -1;
1715         }
1716         cur_grp->group_num = iommu_group_num;
1717         cur_grp->fd = vfio_group_fd;
1718         cur_grp->devices = 0;
1719         vfio_cfg->vfio_active_groups++;
1720
1721         return vfio_group_fd;
1722 }
1723
1724 int
1725 rte_vfio_container_group_unbind(int container_fd, int iommu_group_num)
1726 {
1727         struct vfio_config *vfio_cfg;
1728         struct vfio_group *cur_grp = NULL;
1729         int i;
1730
1731         vfio_cfg = get_vfio_cfg_by_container_fd(container_fd);
1732         if (vfio_cfg == NULL) {
1733                 RTE_LOG(ERR, EAL, "Invalid container fd\n");
1734                 return -1;
1735         }
1736
1737         for (i = 0; i < VFIO_MAX_GROUPS; i++) {
1738                 if (vfio_cfg->vfio_groups[i].group_num == iommu_group_num) {
1739                         cur_grp = &vfio_cfg->vfio_groups[i];
1740                         break;
1741                 }
1742         }
1743
1744         /* This should not happen */
1745         if (i == VFIO_MAX_GROUPS || cur_grp == NULL) {
1746                 RTE_LOG(ERR, EAL, "Specified group number not found\n");
1747                 return -1;
1748         }
1749
1750         if (cur_grp->fd >= 0 && close(cur_grp->fd) < 0) {
1751                 RTE_LOG(ERR, EAL, "Error when closing vfio_group_fd for"
1752                         " iommu_group_num %d\n", iommu_group_num);
1753                 return -1;
1754         }
1755         cur_grp->group_num = -1;
1756         cur_grp->fd = -1;
1757         cur_grp->devices = 0;
1758         vfio_cfg->vfio_active_groups--;
1759
1760         return 0;
1761 }
1762
1763 int
1764 rte_vfio_container_dma_map(int container_fd, uint64_t vaddr, uint64_t iova,
1765                 uint64_t len)
1766 {
1767         struct vfio_config *vfio_cfg;
1768
1769         if (len == 0) {
1770                 rte_errno = EINVAL;
1771                 return -1;
1772         }
1773
1774         vfio_cfg = get_vfio_cfg_by_container_fd(container_fd);
1775         if (vfio_cfg == NULL) {
1776                 RTE_LOG(ERR, EAL, "Invalid container fd\n");
1777                 return -1;
1778         }
1779
1780         return container_dma_map(vfio_cfg, vaddr, iova, len);
1781 }
1782
1783 int
1784 rte_vfio_container_dma_unmap(int container_fd, uint64_t vaddr, uint64_t iova,
1785                 uint64_t len)
1786 {
1787         struct vfio_config *vfio_cfg;
1788
1789         if (len == 0) {
1790                 rte_errno = EINVAL;
1791                 return -1;
1792         }
1793
1794         vfio_cfg = get_vfio_cfg_by_container_fd(container_fd);
1795         if (vfio_cfg == NULL) {
1796                 RTE_LOG(ERR, EAL, "Invalid container fd\n");
1797                 return -1;
1798         }
1799
1800         return container_dma_unmap(vfio_cfg, vaddr, iova, len);
1801 }
1802
1803 #else
1804
1805 int
1806 rte_vfio_dma_map(uint64_t __rte_unused vaddr, __rte_unused uint64_t iova,
1807                   __rte_unused uint64_t len)
1808 {
1809         return -1;
1810 }
1811
1812 int
1813 rte_vfio_dma_unmap(uint64_t __rte_unused vaddr, uint64_t __rte_unused iova,
1814                     __rte_unused uint64_t len)
1815 {
1816         return -1;
1817 }
1818
1819 int
1820 rte_vfio_setup_device(__rte_unused const char *sysfs_base,
1821                 __rte_unused const char *dev_addr,
1822                 __rte_unused int *vfio_dev_fd,
1823                 __rte_unused struct vfio_device_info *device_info)
1824 {
1825         return -1;
1826 }
1827
1828 int
1829 rte_vfio_release_device(__rte_unused const char *sysfs_base,
1830                 __rte_unused const char *dev_addr, __rte_unused int fd)
1831 {
1832         return -1;
1833 }
1834
1835 int
1836 rte_vfio_enable(__rte_unused const char *modname)
1837 {
1838         return -1;
1839 }
1840
1841 int
1842 rte_vfio_is_enabled(__rte_unused const char *modname)
1843 {
1844         return -1;
1845 }
1846
1847 int
1848 rte_vfio_noiommu_is_enabled(void)
1849 {
1850         return -1;
1851 }
1852
1853 int
1854 rte_vfio_clear_group(__rte_unused int vfio_group_fd)
1855 {
1856         return -1;
1857 }
1858
1859 int
1860 rte_vfio_get_group_num(__rte_unused const char *sysfs_base,
1861                 __rte_unused const char *dev_addr,
1862                 __rte_unused int *iommu_group_num)
1863 {
1864         return -1;
1865 }
1866
1867 int
1868 rte_vfio_get_container_fd(void)
1869 {
1870         return -1;
1871 }
1872
1873 int
1874 rte_vfio_get_group_fd(__rte_unused int iommu_group_num)
1875 {
1876         return -1;
1877 }
1878
1879 int
1880 rte_vfio_container_create(void)
1881 {
1882         return -1;
1883 }
1884
1885 int
1886 rte_vfio_container_destroy(__rte_unused int container_fd)
1887 {
1888         return -1;
1889 }
1890
1891 int
1892 rte_vfio_container_group_bind(__rte_unused int container_fd,
1893                 __rte_unused int iommu_group_num)
1894 {
1895         return -1;
1896 }
1897
1898 int
1899 rte_vfio_container_group_unbind(__rte_unused int container_fd,
1900                 __rte_unused int iommu_group_num)
1901 {
1902         return -1;
1903 }
1904
1905 int
1906 rte_vfio_container_dma_map(__rte_unused int container_fd,
1907                 __rte_unused uint64_t vaddr,
1908                 __rte_unused uint64_t iova,
1909                 __rte_unused uint64_t len)
1910 {
1911         return -1;
1912 }
1913
1914 int
1915 rte_vfio_container_dma_unmap(__rte_unused int container_fd,
1916                 __rte_unused uint64_t vaddr,
1917                 __rte_unused uint64_t iova,
1918                 __rte_unused uint64_t len)
1919 {
1920         return -1;
1921 }
1922
1923 #endif /* VFIO_PRESENT */