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