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