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