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