589d7d47875d607398cbd2bc5da994791a6a8153
[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 vfio_get_group_fd(int iommu_group_no)
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_no == iommu_group_no)
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_no == -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_no);
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, iommu_group_no);
334                         vfio_group_fd = open(filename, O_RDWR);
335                         if (vfio_group_fd < 0) {
336                                 if (errno != ENOENT) {
337                                         RTE_LOG(ERR, EAL, "Cannot open %s: %s\n", filename,
338                                                         strerror(errno));
339                                         return -1;
340                                 }
341                                 return 0;
342                         }
343                         /* noiommu group found */
344                 }
345
346                 cur_grp->group_no = iommu_group_no;
347                 cur_grp->fd = vfio_group_fd;
348                 vfio_cfg.vfio_active_groups++;
349                 return vfio_group_fd;
350         }
351         /* if we're in a secondary process, request group fd from the primary
352          * process via our socket
353          */
354         else {
355                 int socket_fd, ret;
356
357                 socket_fd = vfio_mp_sync_connect_to_primary();
358
359                 if (socket_fd < 0) {
360                         RTE_LOG(ERR, EAL, "  cannot connect to primary process!\n");
361                         return -1;
362                 }
363                 if (vfio_mp_sync_send_request(socket_fd, SOCKET_REQ_GROUP) < 0) {
364                         RTE_LOG(ERR, EAL, "  cannot request container fd!\n");
365                         close(socket_fd);
366                         return -1;
367                 }
368                 if (vfio_mp_sync_send_request(socket_fd, iommu_group_no) < 0) {
369                         RTE_LOG(ERR, EAL, "  cannot send group number!\n");
370                         close(socket_fd);
371                         return -1;
372                 }
373                 ret = vfio_mp_sync_receive_request(socket_fd);
374                 switch (ret) {
375                 case SOCKET_NO_FD:
376                         close(socket_fd);
377                         return 0;
378                 case SOCKET_OK:
379                         vfio_group_fd = vfio_mp_sync_receive_fd(socket_fd);
380                         /* if we got the fd, store it and return it */
381                         if (vfio_group_fd > 0) {
382                                 close(socket_fd);
383                                 cur_grp->group_no = iommu_group_no;
384                                 cur_grp->fd = vfio_group_fd;
385                                 vfio_cfg.vfio_active_groups++;
386                                 return vfio_group_fd;
387                         }
388                         /* fall-through on error */
389                 default:
390                         RTE_LOG(ERR, EAL, "  cannot get container fd!\n");
391                         close(socket_fd);
392                         return -1;
393                 }
394         }
395         return -1;
396 }
397
398
399 static int
400 get_vfio_group_idx(int vfio_group_fd)
401 {
402         int i;
403         for (i = 0; i < VFIO_MAX_GROUPS; i++)
404                 if (vfio_cfg.vfio_groups[i].fd == vfio_group_fd)
405                         return i;
406         return -1;
407 }
408
409 static void
410 vfio_group_device_get(int vfio_group_fd)
411 {
412         int i;
413
414         i = get_vfio_group_idx(vfio_group_fd);
415         if (i < 0 || i > (VFIO_MAX_GROUPS - 1))
416                 RTE_LOG(ERR, EAL, "  wrong vfio_group index (%d)\n", i);
417         else
418                 vfio_cfg.vfio_groups[i].devices++;
419 }
420
421 static void
422 vfio_group_device_put(int vfio_group_fd)
423 {
424         int i;
425
426         i = get_vfio_group_idx(vfio_group_fd);
427         if (i < 0 || i > (VFIO_MAX_GROUPS - 1))
428                 RTE_LOG(ERR, EAL, "  wrong vfio_group index (%d)\n", i);
429         else
430                 vfio_cfg.vfio_groups[i].devices--;
431 }
432
433 static int
434 vfio_group_device_count(int vfio_group_fd)
435 {
436         int i;
437
438         i = get_vfio_group_idx(vfio_group_fd);
439         if (i < 0 || i > (VFIO_MAX_GROUPS - 1)) {
440                 RTE_LOG(ERR, EAL, "  wrong vfio_group index (%d)\n", i);
441                 return -1;
442         }
443
444         return vfio_cfg.vfio_groups[i].devices;
445 }
446
447 static void
448 vfio_mem_event_callback(enum rte_mem_event type, const void *addr, size_t len)
449 {
450         struct rte_memseg_list *msl;
451         struct rte_memseg *ms;
452         size_t cur_len = 0;
453
454         msl = rte_mem_virt2memseg_list(addr);
455
456         /* for IOVA as VA mode, no need to care for IOVA addresses */
457         if (rte_eal_iova_mode() == RTE_IOVA_VA) {
458                 uint64_t vfio_va = (uint64_t)(uintptr_t)addr;
459                 if (type == RTE_MEM_EVENT_ALLOC)
460                         vfio_dma_mem_map(vfio_va, vfio_va, len, 1);
461                 else
462                         vfio_dma_mem_map(vfio_va, vfio_va, len, 0);
463                 return;
464         }
465
466         /* memsegs are contiguous in memory */
467         ms = rte_mem_virt2memseg(addr, msl);
468         while (cur_len < len) {
469                 if (type == RTE_MEM_EVENT_ALLOC)
470                         vfio_dma_mem_map(ms->addr_64, ms->iova, ms->len, 1);
471                 else
472                         vfio_dma_mem_map(ms->addr_64, ms->iova, ms->len, 0);
473
474                 cur_len += ms->len;
475                 ++ms;
476         }
477 }
478
479 int
480 rte_vfio_clear_group(int vfio_group_fd)
481 {
482         int i;
483         int socket_fd, ret;
484
485         if (internal_config.process_type == RTE_PROC_PRIMARY) {
486
487                 i = get_vfio_group_idx(vfio_group_fd);
488                 if (i < 0)
489                         return -1;
490                 vfio_cfg.vfio_groups[i].group_no = -1;
491                 vfio_cfg.vfio_groups[i].fd = -1;
492                 vfio_cfg.vfio_groups[i].devices = 0;
493                 vfio_cfg.vfio_active_groups--;
494                 return 0;
495         }
496
497         /* This is just for SECONDARY processes */
498         socket_fd = vfio_mp_sync_connect_to_primary();
499
500         if (socket_fd < 0) {
501                 RTE_LOG(ERR, EAL, "  cannot connect to primary process!\n");
502                 return -1;
503         }
504
505         if (vfio_mp_sync_send_request(socket_fd, SOCKET_CLR_GROUP) < 0) {
506                 RTE_LOG(ERR, EAL, "  cannot request container fd!\n");
507                 close(socket_fd);
508                 return -1;
509         }
510
511         if (vfio_mp_sync_send_request(socket_fd, vfio_group_fd) < 0) {
512                 RTE_LOG(ERR, EAL, "  cannot send group fd!\n");
513                 close(socket_fd);
514                 return -1;
515         }
516
517         ret = vfio_mp_sync_receive_request(socket_fd);
518         switch (ret) {
519         case SOCKET_NO_FD:
520                 RTE_LOG(ERR, EAL, "  BAD VFIO group fd!\n");
521                 close(socket_fd);
522                 break;
523         case SOCKET_OK:
524                 close(socket_fd);
525                 return 0;
526         case SOCKET_ERR:
527                 RTE_LOG(ERR, EAL, "  Socket error\n");
528                 close(socket_fd);
529                 break;
530         default:
531                 RTE_LOG(ERR, EAL, "  UNKNOWN reply, %d\n", ret);
532                 close(socket_fd);
533         }
534         return -1;
535 }
536
537 int
538 rte_vfio_setup_device(const char *sysfs_base, const char *dev_addr,
539                 int *vfio_dev_fd, struct vfio_device_info *device_info)
540 {
541         struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
542         rte_rwlock_t *mem_lock = &mcfg->memory_hotplug_lock;
543         struct vfio_group_status group_status = {
544                         .argsz = sizeof(group_status)
545         };
546         int vfio_group_fd;
547         int iommu_group_no;
548         int i, ret;
549
550         /* get group number */
551         ret = vfio_get_group_no(sysfs_base, dev_addr, &iommu_group_no);
552         if (ret == 0) {
553                 RTE_LOG(WARNING, EAL, "  %s not managed by VFIO driver, skipping\n",
554                         dev_addr);
555                 return 1;
556         }
557
558         /* if negative, something failed */
559         if (ret < 0)
560                 return -1;
561
562         /* get the actual group fd */
563         vfio_group_fd = vfio_get_group_fd(iommu_group_no);
564         if (vfio_group_fd < 0)
565                 return -1;
566
567         /* if group_fd == 0, that means the device isn't managed by VFIO */
568         if (vfio_group_fd == 0) {
569                 RTE_LOG(WARNING, EAL, " %s not managed by VFIO driver, skipping\n",
570                                 dev_addr);
571                 return 1;
572         }
573
574         /*
575          * at this point, we know that this group is viable (meaning, all devices
576          * are either bound to VFIO or not bound to anything)
577          */
578
579         /* check if the group is viable */
580         ret = ioctl(vfio_group_fd, VFIO_GROUP_GET_STATUS, &group_status);
581         if (ret) {
582                 RTE_LOG(ERR, EAL, "  %s cannot get group status, "
583                                 "error %i (%s)\n", dev_addr, errno, strerror(errno));
584                 close(vfio_group_fd);
585                 rte_vfio_clear_group(vfio_group_fd);
586                 return -1;
587         } else if (!(group_status.flags & VFIO_GROUP_FLAGS_VIABLE)) {
588                 RTE_LOG(ERR, EAL, "  %s VFIO group is not viable!\n", dev_addr);
589                 close(vfio_group_fd);
590                 rte_vfio_clear_group(vfio_group_fd);
591                 return -1;
592         }
593
594         /* check if group does not have a container yet */
595         if (!(group_status.flags & VFIO_GROUP_FLAGS_CONTAINER_SET)) {
596
597                 /* add group to a container */
598                 ret = ioctl(vfio_group_fd, VFIO_GROUP_SET_CONTAINER,
599                                 &vfio_cfg.vfio_container_fd);
600                 if (ret) {
601                         RTE_LOG(ERR, EAL, "  %s cannot add VFIO group to container, "
602                                         "error %i (%s)\n", dev_addr, errno, strerror(errno));
603                         close(vfio_group_fd);
604                         rte_vfio_clear_group(vfio_group_fd);
605                         return -1;
606                 }
607
608                 /*
609                  * pick an IOMMU type and set up DMA mappings for container
610                  *
611                  * needs to be done only once, only when first group is
612                  * assigned to a container and only in primary process.
613                  * Note this can happen several times with the hotplug
614                  * functionality.
615                  */
616                 if (internal_config.process_type == RTE_PROC_PRIMARY &&
617                                 vfio_cfg.vfio_active_groups == 1) {
618                         const struct vfio_iommu_type *t;
619
620                         /* select an IOMMU type which we will be using */
621                         t = vfio_set_iommu_type(vfio_cfg.vfio_container_fd);
622                         if (!t) {
623                                 RTE_LOG(ERR, EAL,
624                                         "  %s failed to select IOMMU type\n",
625                                         dev_addr);
626                                 close(vfio_group_fd);
627                                 rte_vfio_clear_group(vfio_group_fd);
628                                 return -1;
629                         }
630                         /* lock memory hotplug before mapping and release it
631                          * after registering callback, to prevent races
632                          */
633                         rte_rwlock_read_lock(mem_lock);
634                         ret = t->dma_map_func(vfio_cfg.vfio_container_fd);
635                         if (ret) {
636                                 RTE_LOG(ERR, EAL,
637                                         "  %s DMA remapping failed, error %i (%s)\n",
638                                         dev_addr, errno, strerror(errno));
639                                 close(vfio_group_fd);
640                                 rte_vfio_clear_group(vfio_group_fd);
641                                 rte_rwlock_read_unlock(mem_lock);
642                                 return -1;
643                         }
644
645                         vfio_cfg.vfio_iommu_type = t;
646
647                         /* re-map all user-mapped segments */
648                         rte_spinlock_recursive_lock(&user_mem_maps.lock);
649
650                         /* this IOMMU type may not support DMA mapping, but
651                          * if we have mappings in the list - that means we have
652                          * previously mapped something successfully, so we can
653                          * be sure that DMA mapping is supported.
654                          */
655                         for (i = 0; i < user_mem_maps.n_maps; i++) {
656                                 struct user_mem_map *map;
657                                 map = &user_mem_maps.maps[i];
658
659                                 ret = t->dma_user_map_func(
660                                                 vfio_cfg.vfio_container_fd,
661                                                 map->addr, map->iova, map->len,
662                                                 1);
663                                 if (ret) {
664                                         RTE_LOG(ERR, EAL, "Couldn't map user memory for DMA: "
665                                                         "va: 0x%" PRIx64 " "
666                                                         "iova: 0x%" PRIx64 " "
667                                                         "len: 0x%" PRIu64 "\n",
668                                                         map->addr, map->iova,
669                                                         map->len);
670                                         rte_spinlock_recursive_unlock(
671                                                         &user_mem_maps.lock);
672                                         rte_rwlock_read_unlock(mem_lock);
673                                         return -1;
674                                 }
675                         }
676                         rte_spinlock_recursive_unlock(&user_mem_maps.lock);
677
678                         /* register callback for mem events */
679                         ret = rte_mem_event_callback_register(
680                                         VFIO_MEM_EVENT_CLB_NAME,
681                                         vfio_mem_event_callback);
682                         /* unlock memory hotplug */
683                         rte_rwlock_read_unlock(mem_lock);
684
685                         if (ret && rte_errno != ENOTSUP) {
686                                 RTE_LOG(ERR, EAL, "Could not install memory event callback for VFIO\n");
687                                 return -1;
688                         }
689                         if (ret)
690                                 RTE_LOG(DEBUG, EAL, "Memory event callbacks not supported\n");
691                         else
692                                 RTE_LOG(DEBUG, EAL, "Installed memory event callback for VFIO\n");
693                 }
694         }
695
696         /* get a file descriptor for the device */
697         *vfio_dev_fd = ioctl(vfio_group_fd, VFIO_GROUP_GET_DEVICE_FD, dev_addr);
698         if (*vfio_dev_fd < 0) {
699                 /* if we cannot get a device fd, this implies a problem with
700                  * the VFIO group or the container not having IOMMU configured.
701                  */
702
703                 RTE_LOG(WARNING, EAL, "Getting a vfio_dev_fd for %s failed\n",
704                                 dev_addr);
705                 close(vfio_group_fd);
706                 rte_vfio_clear_group(vfio_group_fd);
707                 return -1;
708         }
709
710         /* test and setup the device */
711         ret = ioctl(*vfio_dev_fd, VFIO_DEVICE_GET_INFO, device_info);
712         if (ret) {
713                 RTE_LOG(ERR, EAL, "  %s cannot get device info, "
714                                 "error %i (%s)\n", dev_addr, errno,
715                                 strerror(errno));
716                 close(*vfio_dev_fd);
717                 close(vfio_group_fd);
718                 rte_vfio_clear_group(vfio_group_fd);
719                 return -1;
720         }
721         vfio_group_device_get(vfio_group_fd);
722
723         return 0;
724 }
725
726 int
727 rte_vfio_release_device(const char *sysfs_base, const char *dev_addr,
728                     int vfio_dev_fd)
729 {
730         struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
731         rte_rwlock_t *mem_lock = &mcfg->memory_hotplug_lock;
732         struct vfio_group_status group_status = {
733                         .argsz = sizeof(group_status)
734         };
735         int vfio_group_fd;
736         int iommu_group_no;
737         int ret;
738
739         /* we don't want any DMA mapping messages to come while we're detaching
740          * VFIO device, because this might be the last device and we might need
741          * to unregister the callback.
742          */
743         rte_rwlock_read_lock(mem_lock);
744
745         /* get group number */
746         ret = vfio_get_group_no(sysfs_base, dev_addr, &iommu_group_no);
747         if (ret <= 0) {
748                 RTE_LOG(WARNING, EAL, "  %s not managed by VFIO driver\n",
749                         dev_addr);
750                 /* This is an error at this point. */
751                 ret = -1;
752                 goto out;
753         }
754
755         /* get the actual group fd */
756         vfio_group_fd = vfio_get_group_fd(iommu_group_no);
757         if (vfio_group_fd <= 0) {
758                 RTE_LOG(INFO, EAL, "vfio_get_group_fd failed for %s\n",
759                                    dev_addr);
760                 ret = -1;
761                 goto out;
762         }
763
764         /* At this point we got an active group. Closing it will make the
765          * container detachment. If this is the last active group, VFIO kernel
766          * code will unset the container and the IOMMU mappings.
767          */
768
769         /* Closing a device */
770         if (close(vfio_dev_fd) < 0) {
771                 RTE_LOG(INFO, EAL, "Error when closing vfio_dev_fd for %s\n",
772                                    dev_addr);
773                 ret = -1;
774                 goto out;
775         }
776
777         /* An VFIO group can have several devices attached. Just when there is
778          * no devices remaining should the group be closed.
779          */
780         vfio_group_device_put(vfio_group_fd);
781         if (!vfio_group_device_count(vfio_group_fd)) {
782
783                 if (close(vfio_group_fd) < 0) {
784                         RTE_LOG(INFO, EAL, "Error when closing vfio_group_fd for %s\n",
785                                 dev_addr);
786                         ret = -1;
787                         goto out;
788                 }
789
790                 if (rte_vfio_clear_group(vfio_group_fd) < 0) {
791                         RTE_LOG(INFO, EAL, "Error when clearing group for %s\n",
792                                            dev_addr);
793                         ret = -1;
794                         goto out;
795                 }
796         }
797
798         /* if there are no active device groups, unregister the callback to
799          * avoid spurious attempts to map/unmap memory from VFIO.
800          */
801         if (vfio_cfg.vfio_active_groups == 0)
802                 rte_mem_event_callback_unregister(VFIO_MEM_EVENT_CLB_NAME);
803
804         /* success */
805         ret = 0;
806
807 out:
808         rte_rwlock_read_unlock(mem_lock);
809         return ret;
810 }
811
812 int
813 rte_vfio_enable(const char *modname)
814 {
815         /* initialize group list */
816         int i;
817         int vfio_available;
818
819         for (i = 0; i < VFIO_MAX_GROUPS; i++) {
820                 vfio_cfg.vfio_groups[i].fd = -1;
821                 vfio_cfg.vfio_groups[i].group_no = -1;
822                 vfio_cfg.vfio_groups[i].devices = 0;
823         }
824
825         /* inform the user that we are probing for VFIO */
826         RTE_LOG(INFO, EAL, "Probing VFIO support...\n");
827
828         /* check if vfio module is loaded */
829         vfio_available = rte_eal_check_module(modname);
830
831         /* return error directly */
832         if (vfio_available == -1) {
833                 RTE_LOG(INFO, EAL, "Could not get loaded module details!\n");
834                 return -1;
835         }
836
837         /* return 0 if VFIO modules not loaded */
838         if (vfio_available == 0) {
839                 RTE_LOG(DEBUG, EAL, "VFIO modules not loaded, "
840                         "skipping VFIO support...\n");
841                 return 0;
842         }
843
844         vfio_cfg.vfio_container_fd = vfio_get_container_fd();
845
846         /* check if we have VFIO driver enabled */
847         if (vfio_cfg.vfio_container_fd != -1) {
848                 RTE_LOG(NOTICE, EAL, "VFIO support initialized\n");
849                 vfio_cfg.vfio_enabled = 1;
850         } else {
851                 RTE_LOG(NOTICE, EAL, "VFIO support could not be initialized\n");
852         }
853
854         return 0;
855 }
856
857 int
858 rte_vfio_is_enabled(const char *modname)
859 {
860         const int mod_available = rte_eal_check_module(modname) > 0;
861         return vfio_cfg.vfio_enabled && mod_available;
862 }
863
864 const struct vfio_iommu_type *
865 vfio_set_iommu_type(int vfio_container_fd)
866 {
867         unsigned idx;
868         for (idx = 0; idx < RTE_DIM(iommu_types); idx++) {
869                 const struct vfio_iommu_type *t = &iommu_types[idx];
870
871                 int ret = ioctl(vfio_container_fd, VFIO_SET_IOMMU,
872                                 t->type_id);
873                 if (!ret) {
874                         RTE_LOG(NOTICE, EAL, "  using IOMMU type %d (%s)\n",
875                                         t->type_id, t->name);
876                         return t;
877                 }
878                 /* not an error, there may be more supported IOMMU types */
879                 RTE_LOG(DEBUG, EAL, "  set IOMMU type %d (%s) failed, "
880                                 "error %i (%s)\n", t->type_id, t->name, errno,
881                                 strerror(errno));
882         }
883         /* if we didn't find a suitable IOMMU type, fail */
884         return NULL;
885 }
886
887 int
888 vfio_has_supported_extensions(int vfio_container_fd)
889 {
890         int ret;
891         unsigned idx, n_extensions = 0;
892         for (idx = 0; idx < RTE_DIM(iommu_types); idx++) {
893                 const struct vfio_iommu_type *t = &iommu_types[idx];
894
895                 ret = ioctl(vfio_container_fd, VFIO_CHECK_EXTENSION,
896                                 t->type_id);
897                 if (ret < 0) {
898                         RTE_LOG(ERR, EAL, "  could not get IOMMU type, "
899                                 "error %i (%s)\n", errno,
900                                 strerror(errno));
901                         close(vfio_container_fd);
902                         return -1;
903                 } else if (ret == 1) {
904                         /* we found a supported extension */
905                         n_extensions++;
906                 }
907                 RTE_LOG(DEBUG, EAL, "  IOMMU type %d (%s) is %s\n",
908                                 t->type_id, t->name,
909                                 ret ? "supported" : "not supported");
910         }
911
912         /* if we didn't find any supported IOMMU types, fail */
913         if (!n_extensions) {
914                 close(vfio_container_fd);
915                 return -1;
916         }
917
918         return 0;
919 }
920
921 int
922 vfio_get_container_fd(void)
923 {
924         int ret, vfio_container_fd;
925
926         /* if we're in a primary process, try to open the container */
927         if (internal_config.process_type == RTE_PROC_PRIMARY) {
928                 vfio_container_fd = open(VFIO_CONTAINER_PATH, O_RDWR);
929                 if (vfio_container_fd < 0) {
930                         RTE_LOG(ERR, EAL, "  cannot open VFIO container, "
931                                         "error %i (%s)\n", errno, strerror(errno));
932                         return -1;
933                 }
934
935                 /* check VFIO API version */
936                 ret = ioctl(vfio_container_fd, VFIO_GET_API_VERSION);
937                 if (ret != VFIO_API_VERSION) {
938                         if (ret < 0)
939                                 RTE_LOG(ERR, EAL, "  could not get VFIO API version, "
940                                                 "error %i (%s)\n", errno, strerror(errno));
941                         else
942                                 RTE_LOG(ERR, EAL, "  unsupported VFIO API version!\n");
943                         close(vfio_container_fd);
944                         return -1;
945                 }
946
947                 ret = vfio_has_supported_extensions(vfio_container_fd);
948                 if (ret) {
949                         RTE_LOG(ERR, EAL, "  no supported IOMMU "
950                                         "extensions found!\n");
951                         return -1;
952                 }
953
954                 return vfio_container_fd;
955         } else {
956                 /*
957                  * if we're in a secondary process, request container fd from the
958                  * primary process via our socket
959                  */
960                 int socket_fd;
961
962                 socket_fd = vfio_mp_sync_connect_to_primary();
963                 if (socket_fd < 0) {
964                         RTE_LOG(ERR, EAL, "  cannot connect to primary process!\n");
965                         return -1;
966                 }
967                 if (vfio_mp_sync_send_request(socket_fd, SOCKET_REQ_CONTAINER) < 0) {
968                         RTE_LOG(ERR, EAL, "  cannot request container fd!\n");
969                         close(socket_fd);
970                         return -1;
971                 }
972                 vfio_container_fd = vfio_mp_sync_receive_fd(socket_fd);
973                 if (vfio_container_fd < 0) {
974                         RTE_LOG(ERR, EAL, "  cannot get container fd!\n");
975                         close(socket_fd);
976                         return -1;
977                 }
978                 close(socket_fd);
979                 return vfio_container_fd;
980         }
981
982         return -1;
983 }
984
985 int
986 vfio_get_group_no(const char *sysfs_base,
987                 const char *dev_addr, int *iommu_group_no)
988 {
989         char linkname[PATH_MAX];
990         char filename[PATH_MAX];
991         char *tok[16], *group_tok, *end;
992         int ret;
993
994         memset(linkname, 0, sizeof(linkname));
995         memset(filename, 0, sizeof(filename));
996
997         /* try to find out IOMMU group for this device */
998         snprintf(linkname, sizeof(linkname),
999                          "%s/%s/iommu_group", sysfs_base, dev_addr);
1000
1001         ret = readlink(linkname, filename, sizeof(filename));
1002
1003         /* if the link doesn't exist, no VFIO for us */
1004         if (ret < 0)
1005                 return 0;
1006
1007         ret = rte_strsplit(filename, sizeof(filename),
1008                         tok, RTE_DIM(tok), '/');
1009
1010         if (ret <= 0) {
1011                 RTE_LOG(ERR, EAL, "  %s cannot get IOMMU group\n", dev_addr);
1012                 return -1;
1013         }
1014
1015         /* IOMMU group is always the last token */
1016         errno = 0;
1017         group_tok = tok[ret - 1];
1018         end = group_tok;
1019         *iommu_group_no = strtol(group_tok, &end, 10);
1020         if ((end != group_tok && *end != '\0') || errno != 0) {
1021                 RTE_LOG(ERR, EAL, "  %s error parsing IOMMU number!\n", dev_addr);
1022                 return -1;
1023         }
1024
1025         return 1;
1026 }
1027
1028 static int
1029 type1_map(const struct rte_memseg_list *msl __rte_unused,
1030                 const struct rte_memseg *ms, void *arg)
1031 {
1032         int *vfio_container_fd = arg;
1033
1034         return vfio_type1_dma_mem_map(*vfio_container_fd, ms->addr_64, ms->iova,
1035                         ms->len, 1);
1036 }
1037
1038 static int
1039 vfio_type1_dma_mem_map(int vfio_container_fd, uint64_t vaddr, uint64_t iova,
1040                 uint64_t len, int do_map)
1041 {
1042         struct vfio_iommu_type1_dma_map dma_map;
1043         struct vfio_iommu_type1_dma_unmap dma_unmap;
1044         int ret;
1045
1046         if (do_map != 0) {
1047                 memset(&dma_map, 0, sizeof(dma_map));
1048                 dma_map.argsz = sizeof(struct vfio_iommu_type1_dma_map);
1049                 dma_map.vaddr = vaddr;
1050                 dma_map.size = len;
1051                 dma_map.iova = iova;
1052                 dma_map.flags = VFIO_DMA_MAP_FLAG_READ |
1053                                 VFIO_DMA_MAP_FLAG_WRITE;
1054
1055                 ret = ioctl(vfio_container_fd, VFIO_IOMMU_MAP_DMA, &dma_map);
1056                 if (ret) {
1057                         RTE_LOG(ERR, EAL, "  cannot set up DMA remapping, error %i (%s)\n",
1058                                 errno, strerror(errno));
1059                                 return -1;
1060                 }
1061         } else {
1062                 memset(&dma_unmap, 0, sizeof(dma_unmap));
1063                 dma_unmap.argsz = sizeof(struct vfio_iommu_type1_dma_unmap);
1064                 dma_unmap.size = len;
1065                 dma_unmap.iova = iova;
1066
1067                 ret = ioctl(vfio_container_fd, VFIO_IOMMU_UNMAP_DMA,
1068                                 &dma_unmap);
1069                 if (ret) {
1070                         RTE_LOG(ERR, EAL, "  cannot clear DMA remapping, error %i (%s)\n",
1071                                         errno, strerror(errno));
1072                         return -1;
1073                 }
1074         }
1075
1076         return 0;
1077 }
1078
1079 static int
1080 vfio_type1_dma_map(int vfio_container_fd)
1081 {
1082         return rte_memseg_walk(type1_map, &vfio_container_fd);
1083 }
1084
1085 static int
1086 vfio_spapr_dma_do_map(int vfio_container_fd, uint64_t vaddr, uint64_t iova,
1087                 uint64_t len, int do_map)
1088 {
1089         struct vfio_iommu_type1_dma_map dma_map;
1090         struct vfio_iommu_type1_dma_unmap dma_unmap;
1091         int ret;
1092
1093         if (do_map != 0) {
1094                 memset(&dma_map, 0, sizeof(dma_map));
1095                 dma_map.argsz = sizeof(struct vfio_iommu_type1_dma_map);
1096                 dma_map.vaddr = vaddr;
1097                 dma_map.size = len;
1098                 dma_map.iova = iova;
1099                 dma_map.flags = VFIO_DMA_MAP_FLAG_READ |
1100                                 VFIO_DMA_MAP_FLAG_WRITE;
1101
1102                 ret = ioctl(vfio_container_fd, VFIO_IOMMU_MAP_DMA, &dma_map);
1103                 if (ret) {
1104                         RTE_LOG(ERR, EAL, "  cannot set up DMA remapping, error %i (%s)\n",
1105                                 errno, strerror(errno));
1106                                 return -1;
1107                 }
1108
1109         } else {
1110                 struct vfio_iommu_spapr_register_memory reg = {
1111                         .argsz = sizeof(reg),
1112                         .flags = 0
1113                 };
1114                 reg.vaddr = (uintptr_t) vaddr;
1115                 reg.size = len;
1116
1117                 ret = ioctl(vfio_container_fd,
1118                                 VFIO_IOMMU_SPAPR_UNREGISTER_MEMORY, &reg);
1119                 if (ret) {
1120                         RTE_LOG(ERR, EAL, "  cannot unregister vaddr for IOMMU, error %i (%s)\n",
1121                                         errno, strerror(errno));
1122                         return -1;
1123                 }
1124
1125                 memset(&dma_unmap, 0, sizeof(dma_unmap));
1126                 dma_unmap.argsz = sizeof(struct vfio_iommu_type1_dma_unmap);
1127                 dma_unmap.size = len;
1128                 dma_unmap.iova = iova;
1129
1130                 ret = ioctl(vfio_container_fd, VFIO_IOMMU_UNMAP_DMA,
1131                                 &dma_unmap);
1132                 if (ret) {
1133                         RTE_LOG(ERR, EAL, "  cannot clear DMA remapping, error %i (%s)\n",
1134                                         errno, strerror(errno));
1135                         return -1;
1136                 }
1137         }
1138
1139         return 0;
1140 }
1141
1142 static int
1143 vfio_spapr_map_walk(const struct rte_memseg_list *msl __rte_unused,
1144                 const struct rte_memseg *ms, void *arg)
1145 {
1146         int *vfio_container_fd = arg;
1147
1148         return vfio_spapr_dma_mem_map(*vfio_container_fd, ms->addr_64, ms->iova,
1149                         ms->len, 1);
1150 }
1151
1152 struct spapr_walk_param {
1153         uint64_t window_size;
1154         uint64_t hugepage_sz;
1155 };
1156 static int
1157 vfio_spapr_window_size_walk(const struct rte_memseg_list *msl __rte_unused,
1158                 const struct rte_memseg *ms, void *arg)
1159 {
1160         struct spapr_walk_param *param = arg;
1161         uint64_t max = ms->iova + ms->len;
1162
1163         if (max > param->window_size) {
1164                 param->hugepage_sz = ms->hugepage_sz;
1165                 param->window_size = max;
1166         }
1167
1168         return 0;
1169 }
1170
1171 static int
1172 vfio_spapr_create_new_dma_window(int vfio_container_fd,
1173                 struct vfio_iommu_spapr_tce_create *create) {
1174         struct vfio_iommu_spapr_tce_remove remove = {
1175                 .argsz = sizeof(remove),
1176         };
1177         struct vfio_iommu_spapr_tce_info info = {
1178                 .argsz = sizeof(info),
1179         };
1180         int ret;
1181
1182         /* query spapr iommu info */
1183         ret = ioctl(vfio_container_fd, VFIO_IOMMU_SPAPR_TCE_GET_INFO, &info);
1184         if (ret) {
1185                 RTE_LOG(ERR, EAL, "  cannot get iommu info, "
1186                                 "error %i (%s)\n", errno, strerror(errno));
1187                 return -1;
1188         }
1189
1190         /* remove default DMA of 32 bit window */
1191         remove.start_addr = info.dma32_window_start;
1192         ret = ioctl(vfio_container_fd, VFIO_IOMMU_SPAPR_TCE_REMOVE, &remove);
1193         if (ret) {
1194                 RTE_LOG(ERR, EAL, "  cannot remove default DMA window, "
1195                                 "error %i (%s)\n", errno, strerror(errno));
1196                 return -1;
1197         }
1198
1199         /* create new DMA window */
1200         ret = ioctl(vfio_container_fd, VFIO_IOMMU_SPAPR_TCE_CREATE, create);
1201         if (ret) {
1202                 RTE_LOG(ERR, EAL, "  cannot create new DMA window, "
1203                                 "error %i (%s)\n", errno, strerror(errno));
1204                 return -1;
1205         }
1206
1207         if (create->start_addr != 0) {
1208                 RTE_LOG(ERR, EAL, "  DMA window start address != 0\n");
1209                 return -1;
1210         }
1211
1212         return 0;
1213 }
1214
1215 static int
1216 vfio_spapr_dma_mem_map(int vfio_container_fd, uint64_t vaddr, uint64_t iova,
1217                 uint64_t len, int do_map)
1218 {
1219         struct spapr_walk_param param;
1220         struct vfio_iommu_spapr_tce_create create = {
1221                 .argsz = sizeof(create),
1222         };
1223         int i, ret = 0;
1224
1225         rte_spinlock_recursive_lock(&user_mem_maps.lock);
1226
1227         /* check if window size needs to be adjusted */
1228         memset(&param, 0, sizeof(param));
1229
1230         if (memseg_walk_thread_unsafe(vfio_spapr_window_size_walk,
1231                                 &param) < 0) {
1232                 RTE_LOG(ERR, EAL, "Could not get window size\n");
1233                 ret = -1;
1234                 goto out;
1235         }
1236
1237         /* also check user maps */
1238         for (i = 0; i < user_mem_maps.n_maps; i++) {
1239                 uint64_t max = user_mem_maps.maps[i].iova +
1240                                 user_mem_maps.maps[i].len;
1241                 create.window_size = RTE_MAX(create.window_size, max);
1242         }
1243
1244         /* sPAPR requires window size to be a power of 2 */
1245         create.window_size = rte_align64pow2(param.window_size);
1246         create.page_shift = __builtin_ctzll(param.hugepage_sz);
1247         create.levels = 1;
1248
1249         if (do_map) {
1250                 void *addr;
1251                 /* re-create window and remap the entire memory */
1252                 if (iova > create.window_size) {
1253                         if (vfio_spapr_create_new_dma_window(vfio_container_fd,
1254                                         &create) < 0) {
1255                                 RTE_LOG(ERR, EAL, "Could not create new DMA window\n");
1256                                 ret = -1;
1257                                 goto out;
1258                         }
1259                         if (memseg_walk_thread_unsafe(vfio_spapr_map_walk,
1260                                         &vfio_container_fd) < 0) {
1261                                 RTE_LOG(ERR, EAL, "Could not recreate DMA maps\n");
1262                                 ret = -1;
1263                                 goto out;
1264                         }
1265                         /* remap all user maps */
1266                         for (i = 0; i < user_mem_maps.n_maps; i++) {
1267                                 struct user_mem_map *map =
1268                                                 &user_mem_maps.maps[i];
1269                                 if (vfio_spapr_dma_do_map(vfio_container_fd,
1270                                                 map->addr, map->iova, map->len,
1271                                                 1)) {
1272                                         RTE_LOG(ERR, EAL, "Could not recreate user DMA maps\n");
1273                                         ret = -1;
1274                                         goto out;
1275                                 }
1276                         }
1277                 }
1278
1279                 /* now that we've remapped all of the memory that was present
1280                  * before, map the segment that we were requested to map.
1281                  *
1282                  * however, if we were called by the callback, the memory we
1283                  * were called with was already in the memseg list, so previous
1284                  * mapping should've mapped that segment already.
1285                  *
1286                  * virt2memseg_list is a relatively cheap check, so use that. if
1287                  * memory is within any memseg list, it's a memseg, so it's
1288                  * already mapped.
1289                  */
1290                 addr = (void *)(uintptr_t)vaddr;
1291                 if (rte_mem_virt2memseg_list(addr) == NULL &&
1292                                 vfio_spapr_dma_do_map(vfio_container_fd,
1293                                         vaddr, iova, len, 1) < 0) {
1294                         RTE_LOG(ERR, EAL, "Could not map segment\n");
1295                         ret = -1;
1296                         goto out;
1297                 }
1298         } else {
1299                 /* for unmap, check if iova within DMA window */
1300                 if (iova > create.window_size) {
1301                         RTE_LOG(ERR, EAL, "iova beyond DMA window for unmap");
1302                         ret = -1;
1303                         goto out;
1304                 }
1305
1306                 vfio_spapr_dma_do_map(vfio_container_fd, vaddr, iova, len, 0);
1307         }
1308 out:
1309         rte_spinlock_recursive_unlock(&user_mem_maps.lock);
1310         return ret;
1311 }
1312
1313 static int
1314 vfio_spapr_dma_map(int vfio_container_fd)
1315 {
1316         struct vfio_iommu_spapr_tce_create create = {
1317                 .argsz = sizeof(create),
1318         };
1319         struct spapr_walk_param param;
1320
1321         memset(&param, 0, sizeof(param));
1322
1323         /* create DMA window from 0 to max(phys_addr + len) */
1324         rte_memseg_walk(vfio_spapr_window_size_walk, &param);
1325
1326         /* sPAPR requires window size to be a power of 2 */
1327         create.window_size = rte_align64pow2(param.window_size);
1328         create.page_shift = __builtin_ctzll(param.hugepage_sz);
1329         create.levels = 1;
1330
1331         if (vfio_spapr_create_new_dma_window(vfio_container_fd, &create) < 0) {
1332                 RTE_LOG(ERR, EAL, "Could not create new DMA window\n");
1333                 return -1;
1334         }
1335
1336         /* map all DPDK segments for DMA. use 1:1 PA to IOVA mapping */
1337         if (rte_memseg_walk(vfio_spapr_map_walk, &vfio_container_fd) < 0)
1338                 return -1;
1339
1340         return 0;
1341 }
1342
1343 static int
1344 vfio_noiommu_dma_map(int __rte_unused vfio_container_fd)
1345 {
1346         /* No-IOMMU mode does not need DMA mapping */
1347         return 0;
1348 }
1349
1350 static int
1351 vfio_noiommu_dma_mem_map(int __rte_unused vfio_container_fd,
1352                          uint64_t __rte_unused vaddr,
1353                          uint64_t __rte_unused iova, uint64_t __rte_unused len,
1354                          int __rte_unused do_map)
1355 {
1356         /* No-IOMMU mode does not need DMA mapping */
1357         return 0;
1358 }
1359
1360 static int
1361 vfio_dma_mem_map(uint64_t vaddr, uint64_t iova, uint64_t len, int do_map)
1362 {
1363         const struct vfio_iommu_type *t = vfio_cfg.vfio_iommu_type;
1364
1365         if (!t) {
1366                 RTE_LOG(ERR, EAL, "  VFIO support not initialized\n");
1367                 rte_errno = ENODEV;
1368                 return -1;
1369         }
1370
1371         if (!t->dma_user_map_func) {
1372                 RTE_LOG(ERR, EAL,
1373                         "  VFIO custom DMA region maping not supported by IOMMU %s\n",
1374                         t->name);
1375                 rte_errno = ENOTSUP;
1376                 return -1;
1377         }
1378
1379         return t->dma_user_map_func(vfio_cfg.vfio_container_fd, vaddr, iova,
1380                         len, do_map);
1381 }
1382
1383 int __rte_experimental
1384 rte_vfio_dma_map(uint64_t vaddr, uint64_t iova, uint64_t len)
1385 {
1386         struct user_mem_map *new_map;
1387         int ret = 0;
1388
1389         if (len == 0) {
1390                 rte_errno = EINVAL;
1391                 return -1;
1392         }
1393
1394         rte_spinlock_recursive_lock(&user_mem_maps.lock);
1395         if (user_mem_maps.n_maps == VFIO_MAX_USER_MEM_MAPS) {
1396                 RTE_LOG(ERR, EAL, "No more space for user mem maps\n");
1397                 rte_errno = ENOMEM;
1398                 ret = -1;
1399                 goto out;
1400         }
1401         /* map the entry */
1402         if (vfio_dma_mem_map(vaddr, iova, len, 1)) {
1403                 /* technically, this will fail if there are currently no devices
1404                  * plugged in, even if a device were added later, this mapping
1405                  * might have succeeded. however, since we cannot verify if this
1406                  * is a valid mapping without having a device attached, consider
1407                  * this to be unsupported, because we can't just store any old
1408                  * mapping and pollute list of active mappings willy-nilly.
1409                  */
1410                 RTE_LOG(ERR, EAL, "Couldn't map new region for DMA\n");
1411                 ret = -1;
1412                 goto out;
1413         }
1414         /* create new user mem map entry */
1415         new_map = &user_mem_maps.maps[user_mem_maps.n_maps++];
1416         new_map->addr = vaddr;
1417         new_map->iova = iova;
1418         new_map->len = len;
1419
1420         compact_user_maps();
1421 out:
1422         rte_spinlock_recursive_unlock(&user_mem_maps.lock);
1423         return ret;
1424 }
1425
1426 int __rte_experimental
1427 rte_vfio_dma_unmap(uint64_t vaddr, uint64_t iova, uint64_t len)
1428 {
1429         struct user_mem_map *map, *new_map = NULL;
1430         int ret = 0;
1431
1432         if (len == 0) {
1433                 rte_errno = EINVAL;
1434                 return -1;
1435         }
1436
1437         rte_spinlock_recursive_lock(&user_mem_maps.lock);
1438
1439         /* find our mapping */
1440         map = find_user_mem_map(vaddr, iova, len);
1441         if (!map) {
1442                 RTE_LOG(ERR, EAL, "Couldn't find previously mapped region\n");
1443                 rte_errno = EINVAL;
1444                 ret = -1;
1445                 goto out;
1446         }
1447         if (map->addr != vaddr || map->iova != iova || map->len != len) {
1448                 /* we're partially unmapping a previously mapped region, so we
1449                  * need to split entry into two.
1450                  */
1451                 if (user_mem_maps.n_maps == VFIO_MAX_USER_MEM_MAPS) {
1452                         RTE_LOG(ERR, EAL, "Not enough space to store partial mapping\n");
1453                         rte_errno = ENOMEM;
1454                         ret = -1;
1455                         goto out;
1456                 }
1457                 new_map = &user_mem_maps.maps[user_mem_maps.n_maps++];
1458         }
1459
1460         /* unmap the entry */
1461         if (vfio_dma_mem_map(vaddr, iova, len, 0)) {
1462                 /* there may not be any devices plugged in, so unmapping will
1463                  * fail with ENODEV/ENOTSUP rte_errno values, but that doesn't
1464                  * stop us from removing the mapping, as the assumption is we
1465                  * won't be needing this memory any more and thus will want to
1466                  * prevent it from being remapped again on hotplug. so, only
1467                  * fail if we indeed failed to unmap (e.g. if the mapping was
1468                  * within our mapped range but had invalid alignment).
1469                  */
1470                 if (rte_errno != ENODEV && rte_errno != ENOTSUP) {
1471                         RTE_LOG(ERR, EAL, "Couldn't unmap region for DMA\n");
1472                         ret = -1;
1473                         goto out;
1474                 } else {
1475                         RTE_LOG(DEBUG, EAL, "DMA unmapping failed, but removing mappings anyway\n");
1476                 }
1477         }
1478         /* remove map from the list of active mappings */
1479         if (new_map != NULL) {
1480                 adjust_map(map, new_map, vaddr, len);
1481
1482                 /* if we've created a new map by splitting, sort everything */
1483                 if (!is_null_map(new_map)) {
1484                         compact_user_maps();
1485                 } else {
1486                         /* we've created a new mapping, but it was unused */
1487                         user_mem_maps.n_maps--;
1488                 }
1489         } else {
1490                 memset(map, 0, sizeof(*map));
1491                 compact_user_maps();
1492                 user_mem_maps.n_maps--;
1493         }
1494
1495 out:
1496         rte_spinlock_recursive_unlock(&user_mem_maps.lock);
1497         return ret;
1498 }
1499
1500 int
1501 rte_vfio_noiommu_is_enabled(void)
1502 {
1503         int fd;
1504         ssize_t cnt;
1505         char c;
1506
1507         fd = open(VFIO_NOIOMMU_MODE, O_RDONLY);
1508         if (fd < 0) {
1509                 if (errno != ENOENT) {
1510                         RTE_LOG(ERR, EAL, "  cannot open vfio noiommu file %i (%s)\n",
1511                                         errno, strerror(errno));
1512                         return -1;
1513                 }
1514                 /*
1515                  * else the file does not exists
1516                  * i.e. noiommu is not enabled
1517                  */
1518                 return 0;
1519         }
1520
1521         cnt = read(fd, &c, 1);
1522         close(fd);
1523         if (cnt != 1) {
1524                 RTE_LOG(ERR, EAL, "  unable to read from vfio noiommu "
1525                                 "file %i (%s)\n", errno, strerror(errno));
1526                 return -1;
1527         }
1528
1529         return c == 'Y';
1530 }
1531
1532 #else
1533
1534 int __rte_experimental
1535 rte_vfio_dma_map(uint64_t __rte_unused vaddr, __rte_unused uint64_t iova,
1536                   __rte_unused uint64_t len)
1537 {
1538         return -1;
1539 }
1540
1541 int __rte_experimental
1542 rte_vfio_dma_unmap(uint64_t __rte_unused vaddr, uint64_t __rte_unused iova,
1543                     __rte_unused uint64_t len)
1544 {
1545         return -1;
1546 }
1547
1548 #endif