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