Merge tag 'vfio-v5.4-rc1' of git://github.com/awilliam/linux-vfio
[linux-2.6-block.git] / drivers / vfio / vfio_iommu_type1.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * VFIO: IOMMU DMA mapping support for Type1 IOMMU
4  *
5  * Copyright (C) 2012 Red Hat, Inc.  All rights reserved.
6  *     Author: Alex Williamson <alex.williamson@redhat.com>
7  *
8  * Derived from original vfio:
9  * Copyright 2010 Cisco Systems, Inc.  All rights reserved.
10  * Author: Tom Lyon, pugs@cisco.com
11  *
12  * We arbitrarily define a Type1 IOMMU as one matching the below code.
13  * It could be called the x86 IOMMU as it's designed for AMD-Vi & Intel
14  * VT-d, but that makes it harder to re-use as theoretically anyone
15  * implementing a similar IOMMU could make use of this.  We expect the
16  * IOMMU to support the IOMMU API and have few to no restrictions around
17  * the IOVA range that can be mapped.  The Type1 IOMMU is currently
18  * optimized for relatively static mappings of a userspace process with
19  * userpsace pages pinned into memory.  We also assume devices and IOMMU
20  * domains are PCI based as the IOMMU API is still centered around a
21  * device/bus interface rather than a group interface.
22  */
23
24 #include <linux/compat.h>
25 #include <linux/device.h>
26 #include <linux/fs.h>
27 #include <linux/iommu.h>
28 #include <linux/module.h>
29 #include <linux/mm.h>
30 #include <linux/rbtree.h>
31 #include <linux/sched/signal.h>
32 #include <linux/sched/mm.h>
33 #include <linux/slab.h>
34 #include <linux/uaccess.h>
35 #include <linux/vfio.h>
36 #include <linux/workqueue.h>
37 #include <linux/mdev.h>
38 #include <linux/notifier.h>
39 #include <linux/dma-iommu.h>
40 #include <linux/irqdomain.h>
41
42 #define DRIVER_VERSION  "0.2"
43 #define DRIVER_AUTHOR   "Alex Williamson <alex.williamson@redhat.com>"
44 #define DRIVER_DESC     "Type1 IOMMU driver for VFIO"
45
46 static bool allow_unsafe_interrupts;
47 module_param_named(allow_unsafe_interrupts,
48                    allow_unsafe_interrupts, bool, S_IRUGO | S_IWUSR);
49 MODULE_PARM_DESC(allow_unsafe_interrupts,
50                  "Enable VFIO IOMMU support for on platforms without interrupt remapping support.");
51
52 static bool disable_hugepages;
53 module_param_named(disable_hugepages,
54                    disable_hugepages, bool, S_IRUGO | S_IWUSR);
55 MODULE_PARM_DESC(disable_hugepages,
56                  "Disable VFIO IOMMU support for IOMMU hugepages.");
57
58 static unsigned int dma_entry_limit __read_mostly = U16_MAX;
59 module_param_named(dma_entry_limit, dma_entry_limit, uint, 0644);
60 MODULE_PARM_DESC(dma_entry_limit,
61                  "Maximum number of user DMA mappings per container (65535).");
62
63 struct vfio_iommu {
64         struct list_head        domain_list;
65         struct list_head        iova_list;
66         struct vfio_domain      *external_domain; /* domain for external user */
67         struct mutex            lock;
68         struct rb_root          dma_list;
69         struct blocking_notifier_head notifier;
70         unsigned int            dma_avail;
71         bool                    v2;
72         bool                    nesting;
73 };
74
75 struct vfio_domain {
76         struct iommu_domain     *domain;
77         struct list_head        next;
78         struct list_head        group_list;
79         int                     prot;           /* IOMMU_CACHE */
80         bool                    fgsp;           /* Fine-grained super pages */
81 };
82
83 struct vfio_dma {
84         struct rb_node          node;
85         dma_addr_t              iova;           /* Device address */
86         unsigned long           vaddr;          /* Process virtual addr */
87         size_t                  size;           /* Map size (bytes) */
88         int                     prot;           /* IOMMU_READ/WRITE */
89         bool                    iommu_mapped;
90         bool                    lock_cap;       /* capable(CAP_IPC_LOCK) */
91         struct task_struct      *task;
92         struct rb_root          pfn_list;       /* Ex-user pinned pfn list */
93 };
94
95 struct vfio_group {
96         struct iommu_group      *iommu_group;
97         struct list_head        next;
98         bool                    mdev_group;     /* An mdev group */
99 };
100
101 struct vfio_iova {
102         struct list_head        list;
103         dma_addr_t              start;
104         dma_addr_t              end;
105 };
106
107 /*
108  * Guest RAM pinning working set or DMA target
109  */
110 struct vfio_pfn {
111         struct rb_node          node;
112         dma_addr_t              iova;           /* Device address */
113         unsigned long           pfn;            /* Host pfn */
114         atomic_t                ref_count;
115 };
116
117 struct vfio_regions {
118         struct list_head list;
119         dma_addr_t iova;
120         phys_addr_t phys;
121         size_t len;
122 };
123
124 #define IS_IOMMU_CAP_DOMAIN_IN_CONTAINER(iommu) \
125                                         (!list_empty(&iommu->domain_list))
126
127 static int put_pfn(unsigned long pfn, int prot);
128
129 /*
130  * This code handles mapping and unmapping of user data buffers
131  * into DMA'ble space using the IOMMU
132  */
133
134 static struct vfio_dma *vfio_find_dma(struct vfio_iommu *iommu,
135                                       dma_addr_t start, size_t size)
136 {
137         struct rb_node *node = iommu->dma_list.rb_node;
138
139         while (node) {
140                 struct vfio_dma *dma = rb_entry(node, struct vfio_dma, node);
141
142                 if (start + size <= dma->iova)
143                         node = node->rb_left;
144                 else if (start >= dma->iova + dma->size)
145                         node = node->rb_right;
146                 else
147                         return dma;
148         }
149
150         return NULL;
151 }
152
153 static void vfio_link_dma(struct vfio_iommu *iommu, struct vfio_dma *new)
154 {
155         struct rb_node **link = &iommu->dma_list.rb_node, *parent = NULL;
156         struct vfio_dma *dma;
157
158         while (*link) {
159                 parent = *link;
160                 dma = rb_entry(parent, struct vfio_dma, node);
161
162                 if (new->iova + new->size <= dma->iova)
163                         link = &(*link)->rb_left;
164                 else
165                         link = &(*link)->rb_right;
166         }
167
168         rb_link_node(&new->node, parent, link);
169         rb_insert_color(&new->node, &iommu->dma_list);
170 }
171
172 static void vfio_unlink_dma(struct vfio_iommu *iommu, struct vfio_dma *old)
173 {
174         rb_erase(&old->node, &iommu->dma_list);
175 }
176
177 /*
178  * Helper Functions for host iova-pfn list
179  */
180 static struct vfio_pfn *vfio_find_vpfn(struct vfio_dma *dma, dma_addr_t iova)
181 {
182         struct vfio_pfn *vpfn;
183         struct rb_node *node = dma->pfn_list.rb_node;
184
185         while (node) {
186                 vpfn = rb_entry(node, struct vfio_pfn, node);
187
188                 if (iova < vpfn->iova)
189                         node = node->rb_left;
190                 else if (iova > vpfn->iova)
191                         node = node->rb_right;
192                 else
193                         return vpfn;
194         }
195         return NULL;
196 }
197
198 static void vfio_link_pfn(struct vfio_dma *dma,
199                           struct vfio_pfn *new)
200 {
201         struct rb_node **link, *parent = NULL;
202         struct vfio_pfn *vpfn;
203
204         link = &dma->pfn_list.rb_node;
205         while (*link) {
206                 parent = *link;
207                 vpfn = rb_entry(parent, struct vfio_pfn, node);
208
209                 if (new->iova < vpfn->iova)
210                         link = &(*link)->rb_left;
211                 else
212                         link = &(*link)->rb_right;
213         }
214
215         rb_link_node(&new->node, parent, link);
216         rb_insert_color(&new->node, &dma->pfn_list);
217 }
218
219 static void vfio_unlink_pfn(struct vfio_dma *dma, struct vfio_pfn *old)
220 {
221         rb_erase(&old->node, &dma->pfn_list);
222 }
223
224 static int vfio_add_to_pfn_list(struct vfio_dma *dma, dma_addr_t iova,
225                                 unsigned long pfn)
226 {
227         struct vfio_pfn *vpfn;
228
229         vpfn = kzalloc(sizeof(*vpfn), GFP_KERNEL);
230         if (!vpfn)
231                 return -ENOMEM;
232
233         vpfn->iova = iova;
234         vpfn->pfn = pfn;
235         atomic_set(&vpfn->ref_count, 1);
236         vfio_link_pfn(dma, vpfn);
237         return 0;
238 }
239
240 static void vfio_remove_from_pfn_list(struct vfio_dma *dma,
241                                       struct vfio_pfn *vpfn)
242 {
243         vfio_unlink_pfn(dma, vpfn);
244         kfree(vpfn);
245 }
246
247 static struct vfio_pfn *vfio_iova_get_vfio_pfn(struct vfio_dma *dma,
248                                                unsigned long iova)
249 {
250         struct vfio_pfn *vpfn = vfio_find_vpfn(dma, iova);
251
252         if (vpfn)
253                 atomic_inc(&vpfn->ref_count);
254         return vpfn;
255 }
256
257 static int vfio_iova_put_vfio_pfn(struct vfio_dma *dma, struct vfio_pfn *vpfn)
258 {
259         int ret = 0;
260
261         if (atomic_dec_and_test(&vpfn->ref_count)) {
262                 ret = put_pfn(vpfn->pfn, dma->prot);
263                 vfio_remove_from_pfn_list(dma, vpfn);
264         }
265         return ret;
266 }
267
268 static int vfio_lock_acct(struct vfio_dma *dma, long npage, bool async)
269 {
270         struct mm_struct *mm;
271         int ret;
272
273         if (!npage)
274                 return 0;
275
276         mm = async ? get_task_mm(dma->task) : dma->task->mm;
277         if (!mm)
278                 return -ESRCH; /* process exited */
279
280         ret = down_write_killable(&mm->mmap_sem);
281         if (!ret) {
282                 ret = __account_locked_vm(mm, abs(npage), npage > 0, dma->task,
283                                           dma->lock_cap);
284                 up_write(&mm->mmap_sem);
285         }
286
287         if (async)
288                 mmput(mm);
289
290         return ret;
291 }
292
293 /*
294  * Some mappings aren't backed by a struct page, for example an mmap'd
295  * MMIO range for our own or another device.  These use a different
296  * pfn conversion and shouldn't be tracked as locked pages.
297  */
298 static bool is_invalid_reserved_pfn(unsigned long pfn)
299 {
300         if (pfn_valid(pfn)) {
301                 bool reserved;
302                 struct page *tail = pfn_to_page(pfn);
303                 struct page *head = compound_head(tail);
304                 reserved = !!(PageReserved(head));
305                 if (head != tail) {
306                         /*
307                          * "head" is not a dangling pointer
308                          * (compound_head takes care of that)
309                          * but the hugepage may have been split
310                          * from under us (and we may not hold a
311                          * reference count on the head page so it can
312                          * be reused before we run PageReferenced), so
313                          * we've to check PageTail before returning
314                          * what we just read.
315                          */
316                         smp_rmb();
317                         if (PageTail(tail))
318                                 return reserved;
319                 }
320                 return PageReserved(tail);
321         }
322
323         return true;
324 }
325
326 static int put_pfn(unsigned long pfn, int prot)
327 {
328         if (!is_invalid_reserved_pfn(pfn)) {
329                 struct page *page = pfn_to_page(pfn);
330                 if (prot & IOMMU_WRITE)
331                         SetPageDirty(page);
332                 put_page(page);
333                 return 1;
334         }
335         return 0;
336 }
337
338 static int vaddr_get_pfn(struct mm_struct *mm, unsigned long vaddr,
339                          int prot, unsigned long *pfn)
340 {
341         struct page *page[1];
342         struct vm_area_struct *vma;
343         struct vm_area_struct *vmas[1];
344         unsigned int flags = 0;
345         int ret;
346
347         if (prot & IOMMU_WRITE)
348                 flags |= FOLL_WRITE;
349
350         down_read(&mm->mmap_sem);
351         if (mm == current->mm) {
352                 ret = get_user_pages(vaddr, 1, flags | FOLL_LONGTERM, page,
353                                      vmas);
354         } else {
355                 ret = get_user_pages_remote(NULL, mm, vaddr, 1, flags, page,
356                                             vmas, NULL);
357                 /*
358                  * The lifetime of a vaddr_get_pfn() page pin is
359                  * userspace-controlled. In the fs-dax case this could
360                  * lead to indefinite stalls in filesystem operations.
361                  * Disallow attempts to pin fs-dax pages via this
362                  * interface.
363                  */
364                 if (ret > 0 && vma_is_fsdax(vmas[0])) {
365                         ret = -EOPNOTSUPP;
366                         put_page(page[0]);
367                 }
368         }
369         up_read(&mm->mmap_sem);
370
371         if (ret == 1) {
372                 *pfn = page_to_pfn(page[0]);
373                 return 0;
374         }
375
376         down_read(&mm->mmap_sem);
377
378         vma = find_vma_intersection(mm, vaddr, vaddr + 1);
379
380         if (vma && vma->vm_flags & VM_PFNMAP) {
381                 *pfn = ((vaddr - vma->vm_start) >> PAGE_SHIFT) + vma->vm_pgoff;
382                 if (is_invalid_reserved_pfn(*pfn))
383                         ret = 0;
384         }
385
386         up_read(&mm->mmap_sem);
387         return ret;
388 }
389
390 /*
391  * Attempt to pin pages.  We really don't want to track all the pfns and
392  * the iommu can only map chunks of consecutive pfns anyway, so get the
393  * first page and all consecutive pages with the same locking.
394  */
395 static long vfio_pin_pages_remote(struct vfio_dma *dma, unsigned long vaddr,
396                                   long npage, unsigned long *pfn_base,
397                                   unsigned long limit)
398 {
399         unsigned long pfn = 0;
400         long ret, pinned = 0, lock_acct = 0;
401         bool rsvd;
402         dma_addr_t iova = vaddr - dma->vaddr + dma->iova;
403
404         /* This code path is only user initiated */
405         if (!current->mm)
406                 return -ENODEV;
407
408         ret = vaddr_get_pfn(current->mm, vaddr, dma->prot, pfn_base);
409         if (ret)
410                 return ret;
411
412         pinned++;
413         rsvd = is_invalid_reserved_pfn(*pfn_base);
414
415         /*
416          * Reserved pages aren't counted against the user, externally pinned
417          * pages are already counted against the user.
418          */
419         if (!rsvd && !vfio_find_vpfn(dma, iova)) {
420                 if (!dma->lock_cap && current->mm->locked_vm + 1 > limit) {
421                         put_pfn(*pfn_base, dma->prot);
422                         pr_warn("%s: RLIMIT_MEMLOCK (%ld) exceeded\n", __func__,
423                                         limit << PAGE_SHIFT);
424                         return -ENOMEM;
425                 }
426                 lock_acct++;
427         }
428
429         if (unlikely(disable_hugepages))
430                 goto out;
431
432         /* Lock all the consecutive pages from pfn_base */
433         for (vaddr += PAGE_SIZE, iova += PAGE_SIZE; pinned < npage;
434              pinned++, vaddr += PAGE_SIZE, iova += PAGE_SIZE) {
435                 ret = vaddr_get_pfn(current->mm, vaddr, dma->prot, &pfn);
436                 if (ret)
437                         break;
438
439                 if (pfn != *pfn_base + pinned ||
440                     rsvd != is_invalid_reserved_pfn(pfn)) {
441                         put_pfn(pfn, dma->prot);
442                         break;
443                 }
444
445                 if (!rsvd && !vfio_find_vpfn(dma, iova)) {
446                         if (!dma->lock_cap &&
447                             current->mm->locked_vm + lock_acct + 1 > limit) {
448                                 put_pfn(pfn, dma->prot);
449                                 pr_warn("%s: RLIMIT_MEMLOCK (%ld) exceeded\n",
450                                         __func__, limit << PAGE_SHIFT);
451                                 ret = -ENOMEM;
452                                 goto unpin_out;
453                         }
454                         lock_acct++;
455                 }
456         }
457
458 out:
459         ret = vfio_lock_acct(dma, lock_acct, false);
460
461 unpin_out:
462         if (ret) {
463                 if (!rsvd) {
464                         for (pfn = *pfn_base ; pinned ; pfn++, pinned--)
465                                 put_pfn(pfn, dma->prot);
466                 }
467
468                 return ret;
469         }
470
471         return pinned;
472 }
473
474 static long vfio_unpin_pages_remote(struct vfio_dma *dma, dma_addr_t iova,
475                                     unsigned long pfn, long npage,
476                                     bool do_accounting)
477 {
478         long unlocked = 0, locked = 0;
479         long i;
480
481         for (i = 0; i < npage; i++, iova += PAGE_SIZE) {
482                 if (put_pfn(pfn++, dma->prot)) {
483                         unlocked++;
484                         if (vfio_find_vpfn(dma, iova))
485                                 locked++;
486                 }
487         }
488
489         if (do_accounting)
490                 vfio_lock_acct(dma, locked - unlocked, true);
491
492         return unlocked;
493 }
494
495 static int vfio_pin_page_external(struct vfio_dma *dma, unsigned long vaddr,
496                                   unsigned long *pfn_base, bool do_accounting)
497 {
498         struct mm_struct *mm;
499         int ret;
500
501         mm = get_task_mm(dma->task);
502         if (!mm)
503                 return -ENODEV;
504
505         ret = vaddr_get_pfn(mm, vaddr, dma->prot, pfn_base);
506         if (!ret && do_accounting && !is_invalid_reserved_pfn(*pfn_base)) {
507                 ret = vfio_lock_acct(dma, 1, true);
508                 if (ret) {
509                         put_pfn(*pfn_base, dma->prot);
510                         if (ret == -ENOMEM)
511                                 pr_warn("%s: Task %s (%d) RLIMIT_MEMLOCK "
512                                         "(%ld) exceeded\n", __func__,
513                                         dma->task->comm, task_pid_nr(dma->task),
514                                         task_rlimit(dma->task, RLIMIT_MEMLOCK));
515                 }
516         }
517
518         mmput(mm);
519         return ret;
520 }
521
522 static int vfio_unpin_page_external(struct vfio_dma *dma, dma_addr_t iova,
523                                     bool do_accounting)
524 {
525         int unlocked;
526         struct vfio_pfn *vpfn = vfio_find_vpfn(dma, iova);
527
528         if (!vpfn)
529                 return 0;
530
531         unlocked = vfio_iova_put_vfio_pfn(dma, vpfn);
532
533         if (do_accounting)
534                 vfio_lock_acct(dma, -unlocked, true);
535
536         return unlocked;
537 }
538
539 static int vfio_iommu_type1_pin_pages(void *iommu_data,
540                                       unsigned long *user_pfn,
541                                       int npage, int prot,
542                                       unsigned long *phys_pfn)
543 {
544         struct vfio_iommu *iommu = iommu_data;
545         int i, j, ret;
546         unsigned long remote_vaddr;
547         struct vfio_dma *dma;
548         bool do_accounting;
549
550         if (!iommu || !user_pfn || !phys_pfn)
551                 return -EINVAL;
552
553         /* Supported for v2 version only */
554         if (!iommu->v2)
555                 return -EACCES;
556
557         mutex_lock(&iommu->lock);
558
559         /* Fail if notifier list is empty */
560         if (!iommu->notifier.head) {
561                 ret = -EINVAL;
562                 goto pin_done;
563         }
564
565         /*
566          * If iommu capable domain exist in the container then all pages are
567          * already pinned and accounted. Accouting should be done if there is no
568          * iommu capable domain in the container.
569          */
570         do_accounting = !IS_IOMMU_CAP_DOMAIN_IN_CONTAINER(iommu);
571
572         for (i = 0; i < npage; i++) {
573                 dma_addr_t iova;
574                 struct vfio_pfn *vpfn;
575
576                 iova = user_pfn[i] << PAGE_SHIFT;
577                 dma = vfio_find_dma(iommu, iova, PAGE_SIZE);
578                 if (!dma) {
579                         ret = -EINVAL;
580                         goto pin_unwind;
581                 }
582
583                 if ((dma->prot & prot) != prot) {
584                         ret = -EPERM;
585                         goto pin_unwind;
586                 }
587
588                 vpfn = vfio_iova_get_vfio_pfn(dma, iova);
589                 if (vpfn) {
590                         phys_pfn[i] = vpfn->pfn;
591                         continue;
592                 }
593
594                 remote_vaddr = dma->vaddr + iova - dma->iova;
595                 ret = vfio_pin_page_external(dma, remote_vaddr, &phys_pfn[i],
596                                              do_accounting);
597                 if (ret)
598                         goto pin_unwind;
599
600                 ret = vfio_add_to_pfn_list(dma, iova, phys_pfn[i]);
601                 if (ret) {
602                         vfio_unpin_page_external(dma, iova, do_accounting);
603                         goto pin_unwind;
604                 }
605         }
606
607         ret = i;
608         goto pin_done;
609
610 pin_unwind:
611         phys_pfn[i] = 0;
612         for (j = 0; j < i; j++) {
613                 dma_addr_t iova;
614
615                 iova = user_pfn[j] << PAGE_SHIFT;
616                 dma = vfio_find_dma(iommu, iova, PAGE_SIZE);
617                 vfio_unpin_page_external(dma, iova, do_accounting);
618                 phys_pfn[j] = 0;
619         }
620 pin_done:
621         mutex_unlock(&iommu->lock);
622         return ret;
623 }
624
625 static int vfio_iommu_type1_unpin_pages(void *iommu_data,
626                                         unsigned long *user_pfn,
627                                         int npage)
628 {
629         struct vfio_iommu *iommu = iommu_data;
630         bool do_accounting;
631         int i;
632
633         if (!iommu || !user_pfn)
634                 return -EINVAL;
635
636         /* Supported for v2 version only */
637         if (!iommu->v2)
638                 return -EACCES;
639
640         mutex_lock(&iommu->lock);
641
642         do_accounting = !IS_IOMMU_CAP_DOMAIN_IN_CONTAINER(iommu);
643         for (i = 0; i < npage; i++) {
644                 struct vfio_dma *dma;
645                 dma_addr_t iova;
646
647                 iova = user_pfn[i] << PAGE_SHIFT;
648                 dma = vfio_find_dma(iommu, iova, PAGE_SIZE);
649                 if (!dma)
650                         goto unpin_exit;
651                 vfio_unpin_page_external(dma, iova, do_accounting);
652         }
653
654 unpin_exit:
655         mutex_unlock(&iommu->lock);
656         return i > npage ? npage : (i > 0 ? i : -EINVAL);
657 }
658
659 static long vfio_sync_unpin(struct vfio_dma *dma, struct vfio_domain *domain,
660                             struct list_head *regions,
661                             struct iommu_iotlb_gather *iotlb_gather)
662 {
663         long unlocked = 0;
664         struct vfio_regions *entry, *next;
665
666         iommu_tlb_sync(domain->domain, iotlb_gather);
667
668         list_for_each_entry_safe(entry, next, regions, list) {
669                 unlocked += vfio_unpin_pages_remote(dma,
670                                                     entry->iova,
671                                                     entry->phys >> PAGE_SHIFT,
672                                                     entry->len >> PAGE_SHIFT,
673                                                     false);
674                 list_del(&entry->list);
675                 kfree(entry);
676         }
677
678         cond_resched();
679
680         return unlocked;
681 }
682
683 /*
684  * Generally, VFIO needs to unpin remote pages after each IOTLB flush.
685  * Therefore, when using IOTLB flush sync interface, VFIO need to keep track
686  * of these regions (currently using a list).
687  *
688  * This value specifies maximum number of regions for each IOTLB flush sync.
689  */
690 #define VFIO_IOMMU_TLB_SYNC_MAX         512
691
692 static size_t unmap_unpin_fast(struct vfio_domain *domain,
693                                struct vfio_dma *dma, dma_addr_t *iova,
694                                size_t len, phys_addr_t phys, long *unlocked,
695                                struct list_head *unmapped_list,
696                                int *unmapped_cnt,
697                                struct iommu_iotlb_gather *iotlb_gather)
698 {
699         size_t unmapped = 0;
700         struct vfio_regions *entry = kzalloc(sizeof(*entry), GFP_KERNEL);
701
702         if (entry) {
703                 unmapped = iommu_unmap_fast(domain->domain, *iova, len,
704                                             iotlb_gather);
705
706                 if (!unmapped) {
707                         kfree(entry);
708                 } else {
709                         entry->iova = *iova;
710                         entry->phys = phys;
711                         entry->len  = unmapped;
712                         list_add_tail(&entry->list, unmapped_list);
713
714                         *iova += unmapped;
715                         (*unmapped_cnt)++;
716                 }
717         }
718
719         /*
720          * Sync if the number of fast-unmap regions hits the limit
721          * or in case of errors.
722          */
723         if (*unmapped_cnt >= VFIO_IOMMU_TLB_SYNC_MAX || !unmapped) {
724                 *unlocked += vfio_sync_unpin(dma, domain, unmapped_list,
725                                              iotlb_gather);
726                 *unmapped_cnt = 0;
727         }
728
729         return unmapped;
730 }
731
732 static size_t unmap_unpin_slow(struct vfio_domain *domain,
733                                struct vfio_dma *dma, dma_addr_t *iova,
734                                size_t len, phys_addr_t phys,
735                                long *unlocked)
736 {
737         size_t unmapped = iommu_unmap(domain->domain, *iova, len);
738
739         if (unmapped) {
740                 *unlocked += vfio_unpin_pages_remote(dma, *iova,
741                                                      phys >> PAGE_SHIFT,
742                                                      unmapped >> PAGE_SHIFT,
743                                                      false);
744                 *iova += unmapped;
745                 cond_resched();
746         }
747         return unmapped;
748 }
749
750 static long vfio_unmap_unpin(struct vfio_iommu *iommu, struct vfio_dma *dma,
751                              bool do_accounting)
752 {
753         dma_addr_t iova = dma->iova, end = dma->iova + dma->size;
754         struct vfio_domain *domain, *d;
755         LIST_HEAD(unmapped_region_list);
756         struct iommu_iotlb_gather iotlb_gather;
757         int unmapped_region_cnt = 0;
758         long unlocked = 0;
759
760         if (!dma->size)
761                 return 0;
762
763         if (!IS_IOMMU_CAP_DOMAIN_IN_CONTAINER(iommu))
764                 return 0;
765
766         /*
767          * We use the IOMMU to track the physical addresses, otherwise we'd
768          * need a much more complicated tracking system.  Unfortunately that
769          * means we need to use one of the iommu domains to figure out the
770          * pfns to unpin.  The rest need to be unmapped in advance so we have
771          * no iommu translations remaining when the pages are unpinned.
772          */
773         domain = d = list_first_entry(&iommu->domain_list,
774                                       struct vfio_domain, next);
775
776         list_for_each_entry_continue(d, &iommu->domain_list, next) {
777                 iommu_unmap(d->domain, dma->iova, dma->size);
778                 cond_resched();
779         }
780
781         iommu_iotlb_gather_init(&iotlb_gather);
782         while (iova < end) {
783                 size_t unmapped, len;
784                 phys_addr_t phys, next;
785
786                 phys = iommu_iova_to_phys(domain->domain, iova);
787                 if (WARN_ON(!phys)) {
788                         iova += PAGE_SIZE;
789                         continue;
790                 }
791
792                 /*
793                  * To optimize for fewer iommu_unmap() calls, each of which
794                  * may require hardware cache flushing, try to find the
795                  * largest contiguous physical memory chunk to unmap.
796                  */
797                 for (len = PAGE_SIZE;
798                      !domain->fgsp && iova + len < end; len += PAGE_SIZE) {
799                         next = iommu_iova_to_phys(domain->domain, iova + len);
800                         if (next != phys + len)
801                                 break;
802                 }
803
804                 /*
805                  * First, try to use fast unmap/unpin. In case of failure,
806                  * switch to slow unmap/unpin path.
807                  */
808                 unmapped = unmap_unpin_fast(domain, dma, &iova, len, phys,
809                                             &unlocked, &unmapped_region_list,
810                                             &unmapped_region_cnt,
811                                             &iotlb_gather);
812                 if (!unmapped) {
813                         unmapped = unmap_unpin_slow(domain, dma, &iova, len,
814                                                     phys, &unlocked);
815                         if (WARN_ON(!unmapped))
816                                 break;
817                 }
818         }
819
820         dma->iommu_mapped = false;
821
822         if (unmapped_region_cnt) {
823                 unlocked += vfio_sync_unpin(dma, domain, &unmapped_region_list,
824                                             &iotlb_gather);
825         }
826
827         if (do_accounting) {
828                 vfio_lock_acct(dma, -unlocked, true);
829                 return 0;
830         }
831         return unlocked;
832 }
833
834 static void vfio_remove_dma(struct vfio_iommu *iommu, struct vfio_dma *dma)
835 {
836         vfio_unmap_unpin(iommu, dma, true);
837         vfio_unlink_dma(iommu, dma);
838         put_task_struct(dma->task);
839         kfree(dma);
840         iommu->dma_avail++;
841 }
842
843 static unsigned long vfio_pgsize_bitmap(struct vfio_iommu *iommu)
844 {
845         struct vfio_domain *domain;
846         unsigned long bitmap = ULONG_MAX;
847
848         mutex_lock(&iommu->lock);
849         list_for_each_entry(domain, &iommu->domain_list, next)
850                 bitmap &= domain->domain->pgsize_bitmap;
851         mutex_unlock(&iommu->lock);
852
853         /*
854          * In case the IOMMU supports page sizes smaller than PAGE_SIZE
855          * we pretend PAGE_SIZE is supported and hide sub-PAGE_SIZE sizes.
856          * That way the user will be able to map/unmap buffers whose size/
857          * start address is aligned with PAGE_SIZE. Pinning code uses that
858          * granularity while iommu driver can use the sub-PAGE_SIZE size
859          * to map the buffer.
860          */
861         if (bitmap & ~PAGE_MASK) {
862                 bitmap &= PAGE_MASK;
863                 bitmap |= PAGE_SIZE;
864         }
865
866         return bitmap;
867 }
868
869 static int vfio_dma_do_unmap(struct vfio_iommu *iommu,
870                              struct vfio_iommu_type1_dma_unmap *unmap)
871 {
872         uint64_t mask;
873         struct vfio_dma *dma, *dma_last = NULL;
874         size_t unmapped = 0;
875         int ret = 0, retries = 0;
876
877         mask = ((uint64_t)1 << __ffs(vfio_pgsize_bitmap(iommu))) - 1;
878
879         if (unmap->iova & mask)
880                 return -EINVAL;
881         if (!unmap->size || unmap->size & mask)
882                 return -EINVAL;
883         if (unmap->iova + unmap->size - 1 < unmap->iova ||
884             unmap->size > SIZE_MAX)
885                 return -EINVAL;
886
887         WARN_ON(mask & PAGE_MASK);
888 again:
889         mutex_lock(&iommu->lock);
890
891         /*
892          * vfio-iommu-type1 (v1) - User mappings were coalesced together to
893          * avoid tracking individual mappings.  This means that the granularity
894          * of the original mapping was lost and the user was allowed to attempt
895          * to unmap any range.  Depending on the contiguousness of physical
896          * memory and page sizes supported by the IOMMU, arbitrary unmaps may
897          * or may not have worked.  We only guaranteed unmap granularity
898          * matching the original mapping; even though it was untracked here,
899          * the original mappings are reflected in IOMMU mappings.  This
900          * resulted in a couple unusual behaviors.  First, if a range is not
901          * able to be unmapped, ex. a set of 4k pages that was mapped as a
902          * 2M hugepage into the IOMMU, the unmap ioctl returns success but with
903          * a zero sized unmap.  Also, if an unmap request overlaps the first
904          * address of a hugepage, the IOMMU will unmap the entire hugepage.
905          * This also returns success and the returned unmap size reflects the
906          * actual size unmapped.
907          *
908          * We attempt to maintain compatibility with this "v1" interface, but
909          * we take control out of the hands of the IOMMU.  Therefore, an unmap
910          * request offset from the beginning of the original mapping will
911          * return success with zero sized unmap.  And an unmap request covering
912          * the first iova of mapping will unmap the entire range.
913          *
914          * The v2 version of this interface intends to be more deterministic.
915          * Unmap requests must fully cover previous mappings.  Multiple
916          * mappings may still be unmaped by specifying large ranges, but there
917          * must not be any previous mappings bisected by the range.  An error
918          * will be returned if these conditions are not met.  The v2 interface
919          * will only return success and a size of zero if there were no
920          * mappings within the range.
921          */
922         if (iommu->v2) {
923                 dma = vfio_find_dma(iommu, unmap->iova, 1);
924                 if (dma && dma->iova != unmap->iova) {
925                         ret = -EINVAL;
926                         goto unlock;
927                 }
928                 dma = vfio_find_dma(iommu, unmap->iova + unmap->size - 1, 0);
929                 if (dma && dma->iova + dma->size != unmap->iova + unmap->size) {
930                         ret = -EINVAL;
931                         goto unlock;
932                 }
933         }
934
935         while ((dma = vfio_find_dma(iommu, unmap->iova, unmap->size))) {
936                 if (!iommu->v2 && unmap->iova > dma->iova)
937                         break;
938                 /*
939                  * Task with same address space who mapped this iova range is
940                  * allowed to unmap the iova range.
941                  */
942                 if (dma->task->mm != current->mm)
943                         break;
944
945                 if (!RB_EMPTY_ROOT(&dma->pfn_list)) {
946                         struct vfio_iommu_type1_dma_unmap nb_unmap;
947
948                         if (dma_last == dma) {
949                                 BUG_ON(++retries > 10);
950                         } else {
951                                 dma_last = dma;
952                                 retries = 0;
953                         }
954
955                         nb_unmap.iova = dma->iova;
956                         nb_unmap.size = dma->size;
957
958                         /*
959                          * Notify anyone (mdev vendor drivers) to invalidate and
960                          * unmap iovas within the range we're about to unmap.
961                          * Vendor drivers MUST unpin pages in response to an
962                          * invalidation.
963                          */
964                         mutex_unlock(&iommu->lock);
965                         blocking_notifier_call_chain(&iommu->notifier,
966                                                     VFIO_IOMMU_NOTIFY_DMA_UNMAP,
967                                                     &nb_unmap);
968                         goto again;
969                 }
970                 unmapped += dma->size;
971                 vfio_remove_dma(iommu, dma);
972         }
973
974 unlock:
975         mutex_unlock(&iommu->lock);
976
977         /* Report how much was unmapped */
978         unmap->size = unmapped;
979
980         return ret;
981 }
982
983 static int vfio_iommu_map(struct vfio_iommu *iommu, dma_addr_t iova,
984                           unsigned long pfn, long npage, int prot)
985 {
986         struct vfio_domain *d;
987         int ret;
988
989         list_for_each_entry(d, &iommu->domain_list, next) {
990                 ret = iommu_map(d->domain, iova, (phys_addr_t)pfn << PAGE_SHIFT,
991                                 npage << PAGE_SHIFT, prot | d->prot);
992                 if (ret)
993                         goto unwind;
994
995                 cond_resched();
996         }
997
998         return 0;
999
1000 unwind:
1001         list_for_each_entry_continue_reverse(d, &iommu->domain_list, next)
1002                 iommu_unmap(d->domain, iova, npage << PAGE_SHIFT);
1003
1004         return ret;
1005 }
1006
1007 static int vfio_pin_map_dma(struct vfio_iommu *iommu, struct vfio_dma *dma,
1008                             size_t map_size)
1009 {
1010         dma_addr_t iova = dma->iova;
1011         unsigned long vaddr = dma->vaddr;
1012         size_t size = map_size;
1013         long npage;
1014         unsigned long pfn, limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
1015         int ret = 0;
1016
1017         while (size) {
1018                 /* Pin a contiguous chunk of memory */
1019                 npage = vfio_pin_pages_remote(dma, vaddr + dma->size,
1020                                               size >> PAGE_SHIFT, &pfn, limit);
1021                 if (npage <= 0) {
1022                         WARN_ON(!npage);
1023                         ret = (int)npage;
1024                         break;
1025                 }
1026
1027                 /* Map it! */
1028                 ret = vfio_iommu_map(iommu, iova + dma->size, pfn, npage,
1029                                      dma->prot);
1030                 if (ret) {
1031                         vfio_unpin_pages_remote(dma, iova + dma->size, pfn,
1032                                                 npage, true);
1033                         break;
1034                 }
1035
1036                 size -= npage << PAGE_SHIFT;
1037                 dma->size += npage << PAGE_SHIFT;
1038         }
1039
1040         dma->iommu_mapped = true;
1041
1042         if (ret)
1043                 vfio_remove_dma(iommu, dma);
1044
1045         return ret;
1046 }
1047
1048 /*
1049  * Check dma map request is within a valid iova range
1050  */
1051 static bool vfio_iommu_iova_dma_valid(struct vfio_iommu *iommu,
1052                                       dma_addr_t start, dma_addr_t end)
1053 {
1054         struct list_head *iova = &iommu->iova_list;
1055         struct vfio_iova *node;
1056
1057         list_for_each_entry(node, iova, list) {
1058                 if (start >= node->start && end <= node->end)
1059                         return true;
1060         }
1061
1062         /*
1063          * Check for list_empty() as well since a container with
1064          * a single mdev device will have an empty list.
1065          */
1066         return list_empty(iova);
1067 }
1068
1069 static int vfio_dma_do_map(struct vfio_iommu *iommu,
1070                            struct vfio_iommu_type1_dma_map *map)
1071 {
1072         dma_addr_t iova = map->iova;
1073         unsigned long vaddr = map->vaddr;
1074         size_t size = map->size;
1075         int ret = 0, prot = 0;
1076         uint64_t mask;
1077         struct vfio_dma *dma;
1078
1079         /* Verify that none of our __u64 fields overflow */
1080         if (map->size != size || map->vaddr != vaddr || map->iova != iova)
1081                 return -EINVAL;
1082
1083         mask = ((uint64_t)1 << __ffs(vfio_pgsize_bitmap(iommu))) - 1;
1084
1085         WARN_ON(mask & PAGE_MASK);
1086
1087         /* READ/WRITE from device perspective */
1088         if (map->flags & VFIO_DMA_MAP_FLAG_WRITE)
1089                 prot |= IOMMU_WRITE;
1090         if (map->flags & VFIO_DMA_MAP_FLAG_READ)
1091                 prot |= IOMMU_READ;
1092
1093         if (!prot || !size || (size | iova | vaddr) & mask)
1094                 return -EINVAL;
1095
1096         /* Don't allow IOVA or virtual address wrap */
1097         if (iova + size - 1 < iova || vaddr + size - 1 < vaddr)
1098                 return -EINVAL;
1099
1100         mutex_lock(&iommu->lock);
1101
1102         if (vfio_find_dma(iommu, iova, size)) {
1103                 ret = -EEXIST;
1104                 goto out_unlock;
1105         }
1106
1107         if (!iommu->dma_avail) {
1108                 ret = -ENOSPC;
1109                 goto out_unlock;
1110         }
1111
1112         if (!vfio_iommu_iova_dma_valid(iommu, iova, iova + size - 1)) {
1113                 ret = -EINVAL;
1114                 goto out_unlock;
1115         }
1116
1117         dma = kzalloc(sizeof(*dma), GFP_KERNEL);
1118         if (!dma) {
1119                 ret = -ENOMEM;
1120                 goto out_unlock;
1121         }
1122
1123         iommu->dma_avail--;
1124         dma->iova = iova;
1125         dma->vaddr = vaddr;
1126         dma->prot = prot;
1127
1128         /*
1129          * We need to be able to both add to a task's locked memory and test
1130          * against the locked memory limit and we need to be able to do both
1131          * outside of this call path as pinning can be asynchronous via the
1132          * external interfaces for mdev devices.  RLIMIT_MEMLOCK requires a
1133          * task_struct and VM locked pages requires an mm_struct, however
1134          * holding an indefinite mm reference is not recommended, therefore we
1135          * only hold a reference to a task.  We could hold a reference to
1136          * current, however QEMU uses this call path through vCPU threads,
1137          * which can be killed resulting in a NULL mm and failure in the unmap
1138          * path when called via a different thread.  Avoid this problem by
1139          * using the group_leader as threads within the same group require
1140          * both CLONE_THREAD and CLONE_VM and will therefore use the same
1141          * mm_struct.
1142          *
1143          * Previously we also used the task for testing CAP_IPC_LOCK at the
1144          * time of pinning and accounting, however has_capability() makes use
1145          * of real_cred, a copy-on-write field, so we can't guarantee that it
1146          * matches group_leader, or in fact that it might not change by the
1147          * time it's evaluated.  If a process were to call MAP_DMA with
1148          * CAP_IPC_LOCK but later drop it, it doesn't make sense that they
1149          * possibly see different results for an iommu_mapped vfio_dma vs
1150          * externally mapped.  Therefore track CAP_IPC_LOCK in vfio_dma at the
1151          * time of calling MAP_DMA.
1152          */
1153         get_task_struct(current->group_leader);
1154         dma->task = current->group_leader;
1155         dma->lock_cap = capable(CAP_IPC_LOCK);
1156
1157         dma->pfn_list = RB_ROOT;
1158
1159         /* Insert zero-sized and grow as we map chunks of it */
1160         vfio_link_dma(iommu, dma);
1161
1162         /* Don't pin and map if container doesn't contain IOMMU capable domain*/
1163         if (!IS_IOMMU_CAP_DOMAIN_IN_CONTAINER(iommu))
1164                 dma->size = size;
1165         else
1166                 ret = vfio_pin_map_dma(iommu, dma, size);
1167
1168 out_unlock:
1169         mutex_unlock(&iommu->lock);
1170         return ret;
1171 }
1172
1173 static int vfio_bus_type(struct device *dev, void *data)
1174 {
1175         struct bus_type **bus = data;
1176
1177         if (*bus && *bus != dev->bus)
1178                 return -EINVAL;
1179
1180         *bus = dev->bus;
1181
1182         return 0;
1183 }
1184
1185 static int vfio_iommu_replay(struct vfio_iommu *iommu,
1186                              struct vfio_domain *domain)
1187 {
1188         struct vfio_domain *d;
1189         struct rb_node *n;
1190         unsigned long limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
1191         int ret;
1192
1193         /* Arbitrarily pick the first domain in the list for lookups */
1194         d = list_first_entry(&iommu->domain_list, struct vfio_domain, next);
1195         n = rb_first(&iommu->dma_list);
1196
1197         for (; n; n = rb_next(n)) {
1198                 struct vfio_dma *dma;
1199                 dma_addr_t iova;
1200
1201                 dma = rb_entry(n, struct vfio_dma, node);
1202                 iova = dma->iova;
1203
1204                 while (iova < dma->iova + dma->size) {
1205                         phys_addr_t phys;
1206                         size_t size;
1207
1208                         if (dma->iommu_mapped) {
1209                                 phys_addr_t p;
1210                                 dma_addr_t i;
1211
1212                                 phys = iommu_iova_to_phys(d->domain, iova);
1213
1214                                 if (WARN_ON(!phys)) {
1215                                         iova += PAGE_SIZE;
1216                                         continue;
1217                                 }
1218
1219                                 size = PAGE_SIZE;
1220                                 p = phys + size;
1221                                 i = iova + size;
1222                                 while (i < dma->iova + dma->size &&
1223                                        p == iommu_iova_to_phys(d->domain, i)) {
1224                                         size += PAGE_SIZE;
1225                                         p += PAGE_SIZE;
1226                                         i += PAGE_SIZE;
1227                                 }
1228                         } else {
1229                                 unsigned long pfn;
1230                                 unsigned long vaddr = dma->vaddr +
1231                                                      (iova - dma->iova);
1232                                 size_t n = dma->iova + dma->size - iova;
1233                                 long npage;
1234
1235                                 npage = vfio_pin_pages_remote(dma, vaddr,
1236                                                               n >> PAGE_SHIFT,
1237                                                               &pfn, limit);
1238                                 if (npage <= 0) {
1239                                         WARN_ON(!npage);
1240                                         ret = (int)npage;
1241                                         return ret;
1242                                 }
1243
1244                                 phys = pfn << PAGE_SHIFT;
1245                                 size = npage << PAGE_SHIFT;
1246                         }
1247
1248                         ret = iommu_map(domain->domain, iova, phys,
1249                                         size, dma->prot | domain->prot);
1250                         if (ret)
1251                                 return ret;
1252
1253                         iova += size;
1254                 }
1255                 dma->iommu_mapped = true;
1256         }
1257         return 0;
1258 }
1259
1260 /*
1261  * We change our unmap behavior slightly depending on whether the IOMMU
1262  * supports fine-grained superpages.  IOMMUs like AMD-Vi will use a superpage
1263  * for practically any contiguous power-of-two mapping we give it.  This means
1264  * we don't need to look for contiguous chunks ourselves to make unmapping
1265  * more efficient.  On IOMMUs with coarse-grained super pages, like Intel VT-d
1266  * with discrete 2M/1G/512G/1T superpages, identifying contiguous chunks
1267  * significantly boosts non-hugetlbfs mappings and doesn't seem to hurt when
1268  * hugetlbfs is in use.
1269  */
1270 static void vfio_test_domain_fgsp(struct vfio_domain *domain)
1271 {
1272         struct page *pages;
1273         int ret, order = get_order(PAGE_SIZE * 2);
1274
1275         pages = alloc_pages(GFP_KERNEL | __GFP_ZERO, order);
1276         if (!pages)
1277                 return;
1278
1279         ret = iommu_map(domain->domain, 0, page_to_phys(pages), PAGE_SIZE * 2,
1280                         IOMMU_READ | IOMMU_WRITE | domain->prot);
1281         if (!ret) {
1282                 size_t unmapped = iommu_unmap(domain->domain, 0, PAGE_SIZE);
1283
1284                 if (unmapped == PAGE_SIZE)
1285                         iommu_unmap(domain->domain, PAGE_SIZE, PAGE_SIZE);
1286                 else
1287                         domain->fgsp = true;
1288         }
1289
1290         __free_pages(pages, order);
1291 }
1292
1293 static struct vfio_group *find_iommu_group(struct vfio_domain *domain,
1294                                            struct iommu_group *iommu_group)
1295 {
1296         struct vfio_group *g;
1297
1298         list_for_each_entry(g, &domain->group_list, next) {
1299                 if (g->iommu_group == iommu_group)
1300                         return g;
1301         }
1302
1303         return NULL;
1304 }
1305
1306 static bool vfio_iommu_has_sw_msi(struct list_head *group_resv_regions,
1307                                   phys_addr_t *base)
1308 {
1309         struct iommu_resv_region *region;
1310         bool ret = false;
1311
1312         list_for_each_entry(region, group_resv_regions, list) {
1313                 /*
1314                  * The presence of any 'real' MSI regions should take
1315                  * precedence over the software-managed one if the
1316                  * IOMMU driver happens to advertise both types.
1317                  */
1318                 if (region->type == IOMMU_RESV_MSI) {
1319                         ret = false;
1320                         break;
1321                 }
1322
1323                 if (region->type == IOMMU_RESV_SW_MSI) {
1324                         *base = region->start;
1325                         ret = true;
1326                 }
1327         }
1328
1329         return ret;
1330 }
1331
1332 static struct device *vfio_mdev_get_iommu_device(struct device *dev)
1333 {
1334         struct device *(*fn)(struct device *dev);
1335         struct device *iommu_device;
1336
1337         fn = symbol_get(mdev_get_iommu_device);
1338         if (fn) {
1339                 iommu_device = fn(dev);
1340                 symbol_put(mdev_get_iommu_device);
1341
1342                 return iommu_device;
1343         }
1344
1345         return NULL;
1346 }
1347
1348 static int vfio_mdev_attach_domain(struct device *dev, void *data)
1349 {
1350         struct iommu_domain *domain = data;
1351         struct device *iommu_device;
1352
1353         iommu_device = vfio_mdev_get_iommu_device(dev);
1354         if (iommu_device) {
1355                 if (iommu_dev_feature_enabled(iommu_device, IOMMU_DEV_FEAT_AUX))
1356                         return iommu_aux_attach_device(domain, iommu_device);
1357                 else
1358                         return iommu_attach_device(domain, iommu_device);
1359         }
1360
1361         return -EINVAL;
1362 }
1363
1364 static int vfio_mdev_detach_domain(struct device *dev, void *data)
1365 {
1366         struct iommu_domain *domain = data;
1367         struct device *iommu_device;
1368
1369         iommu_device = vfio_mdev_get_iommu_device(dev);
1370         if (iommu_device) {
1371                 if (iommu_dev_feature_enabled(iommu_device, IOMMU_DEV_FEAT_AUX))
1372                         iommu_aux_detach_device(domain, iommu_device);
1373                 else
1374                         iommu_detach_device(domain, iommu_device);
1375         }
1376
1377         return 0;
1378 }
1379
1380 static int vfio_iommu_attach_group(struct vfio_domain *domain,
1381                                    struct vfio_group *group)
1382 {
1383         if (group->mdev_group)
1384                 return iommu_group_for_each_dev(group->iommu_group,
1385                                                 domain->domain,
1386                                                 vfio_mdev_attach_domain);
1387         else
1388                 return iommu_attach_group(domain->domain, group->iommu_group);
1389 }
1390
1391 static void vfio_iommu_detach_group(struct vfio_domain *domain,
1392                                     struct vfio_group *group)
1393 {
1394         if (group->mdev_group)
1395                 iommu_group_for_each_dev(group->iommu_group, domain->domain,
1396                                          vfio_mdev_detach_domain);
1397         else
1398                 iommu_detach_group(domain->domain, group->iommu_group);
1399 }
1400
1401 static bool vfio_bus_is_mdev(struct bus_type *bus)
1402 {
1403         struct bus_type *mdev_bus;
1404         bool ret = false;
1405
1406         mdev_bus = symbol_get(mdev_bus_type);
1407         if (mdev_bus) {
1408                 ret = (bus == mdev_bus);
1409                 symbol_put(mdev_bus_type);
1410         }
1411
1412         return ret;
1413 }
1414
1415 static int vfio_mdev_iommu_device(struct device *dev, void *data)
1416 {
1417         struct device **old = data, *new;
1418
1419         new = vfio_mdev_get_iommu_device(dev);
1420         if (!new || (*old && *old != new))
1421                 return -EINVAL;
1422
1423         *old = new;
1424
1425         return 0;
1426 }
1427
1428 /*
1429  * This is a helper function to insert an address range to iova list.
1430  * The list is initially created with a single entry corresponding to
1431  * the IOMMU domain geometry to which the device group is attached.
1432  * The list aperture gets modified when a new domain is added to the
1433  * container if the new aperture doesn't conflict with the current one
1434  * or with any existing dma mappings. The list is also modified to
1435  * exclude any reserved regions associated with the device group.
1436  */
1437 static int vfio_iommu_iova_insert(struct list_head *head,
1438                                   dma_addr_t start, dma_addr_t end)
1439 {
1440         struct vfio_iova *region;
1441
1442         region = kmalloc(sizeof(*region), GFP_KERNEL);
1443         if (!region)
1444                 return -ENOMEM;
1445
1446         INIT_LIST_HEAD(&region->list);
1447         region->start = start;
1448         region->end = end;
1449
1450         list_add_tail(&region->list, head);
1451         return 0;
1452 }
1453
1454 /*
1455  * Check the new iommu aperture conflicts with existing aper or with any
1456  * existing dma mappings.
1457  */
1458 static bool vfio_iommu_aper_conflict(struct vfio_iommu *iommu,
1459                                      dma_addr_t start, dma_addr_t end)
1460 {
1461         struct vfio_iova *first, *last;
1462         struct list_head *iova = &iommu->iova_list;
1463
1464         if (list_empty(iova))
1465                 return false;
1466
1467         /* Disjoint sets, return conflict */
1468         first = list_first_entry(iova, struct vfio_iova, list);
1469         last = list_last_entry(iova, struct vfio_iova, list);
1470         if (start > last->end || end < first->start)
1471                 return true;
1472
1473         /* Check for any existing dma mappings below the new start */
1474         if (start > first->start) {
1475                 if (vfio_find_dma(iommu, first->start, start - first->start))
1476                         return true;
1477         }
1478
1479         /* Check for any existing dma mappings beyond the new end */
1480         if (end < last->end) {
1481                 if (vfio_find_dma(iommu, end + 1, last->end - end))
1482                         return true;
1483         }
1484
1485         return false;
1486 }
1487
1488 /*
1489  * Resize iommu iova aperture window. This is called only if the new
1490  * aperture has no conflict with existing aperture and dma mappings.
1491  */
1492 static int vfio_iommu_aper_resize(struct list_head *iova,
1493                                   dma_addr_t start, dma_addr_t end)
1494 {
1495         struct vfio_iova *node, *next;
1496
1497         if (list_empty(iova))
1498                 return vfio_iommu_iova_insert(iova, start, end);
1499
1500         /* Adjust iova list start */
1501         list_for_each_entry_safe(node, next, iova, list) {
1502                 if (start < node->start)
1503                         break;
1504                 if (start >= node->start && start < node->end) {
1505                         node->start = start;
1506                         break;
1507                 }
1508                 /* Delete nodes before new start */
1509                 list_del(&node->list);
1510                 kfree(node);
1511         }
1512
1513         /* Adjust iova list end */
1514         list_for_each_entry_safe(node, next, iova, list) {
1515                 if (end > node->end)
1516                         continue;
1517                 if (end > node->start && end <= node->end) {
1518                         node->end = end;
1519                         continue;
1520                 }
1521                 /* Delete nodes after new end */
1522                 list_del(&node->list);
1523                 kfree(node);
1524         }
1525
1526         return 0;
1527 }
1528
1529 /*
1530  * Check reserved region conflicts with existing dma mappings
1531  */
1532 static bool vfio_iommu_resv_conflict(struct vfio_iommu *iommu,
1533                                      struct list_head *resv_regions)
1534 {
1535         struct iommu_resv_region *region;
1536
1537         /* Check for conflict with existing dma mappings */
1538         list_for_each_entry(region, resv_regions, list) {
1539                 if (region->type == IOMMU_RESV_DIRECT_RELAXABLE)
1540                         continue;
1541
1542                 if (vfio_find_dma(iommu, region->start, region->length))
1543                         return true;
1544         }
1545
1546         return false;
1547 }
1548
1549 /*
1550  * Check iova region overlap with  reserved regions and
1551  * exclude them from the iommu iova range
1552  */
1553 static int vfio_iommu_resv_exclude(struct list_head *iova,
1554                                    struct list_head *resv_regions)
1555 {
1556         struct iommu_resv_region *resv;
1557         struct vfio_iova *n, *next;
1558
1559         list_for_each_entry(resv, resv_regions, list) {
1560                 phys_addr_t start, end;
1561
1562                 if (resv->type == IOMMU_RESV_DIRECT_RELAXABLE)
1563                         continue;
1564
1565                 start = resv->start;
1566                 end = resv->start + resv->length - 1;
1567
1568                 list_for_each_entry_safe(n, next, iova, list) {
1569                         int ret = 0;
1570
1571                         /* No overlap */
1572                         if (start > n->end || end < n->start)
1573                                 continue;
1574                         /*
1575                          * Insert a new node if current node overlaps with the
1576                          * reserve region to exlude that from valid iova range.
1577                          * Note that, new node is inserted before the current
1578                          * node and finally the current node is deleted keeping
1579                          * the list updated and sorted.
1580                          */
1581                         if (start > n->start)
1582                                 ret = vfio_iommu_iova_insert(&n->list, n->start,
1583                                                              start - 1);
1584                         if (!ret && end < n->end)
1585                                 ret = vfio_iommu_iova_insert(&n->list, end + 1,
1586                                                              n->end);
1587                         if (ret)
1588                                 return ret;
1589
1590                         list_del(&n->list);
1591                         kfree(n);
1592                 }
1593         }
1594
1595         if (list_empty(iova))
1596                 return -EINVAL;
1597
1598         return 0;
1599 }
1600
1601 static void vfio_iommu_resv_free(struct list_head *resv_regions)
1602 {
1603         struct iommu_resv_region *n, *next;
1604
1605         list_for_each_entry_safe(n, next, resv_regions, list) {
1606                 list_del(&n->list);
1607                 kfree(n);
1608         }
1609 }
1610
1611 static void vfio_iommu_iova_free(struct list_head *iova)
1612 {
1613         struct vfio_iova *n, *next;
1614
1615         list_for_each_entry_safe(n, next, iova, list) {
1616                 list_del(&n->list);
1617                 kfree(n);
1618         }
1619 }
1620
1621 static int vfio_iommu_iova_get_copy(struct vfio_iommu *iommu,
1622                                     struct list_head *iova_copy)
1623 {
1624         struct list_head *iova = &iommu->iova_list;
1625         struct vfio_iova *n;
1626         int ret;
1627
1628         list_for_each_entry(n, iova, list) {
1629                 ret = vfio_iommu_iova_insert(iova_copy, n->start, n->end);
1630                 if (ret)
1631                         goto out_free;
1632         }
1633
1634         return 0;
1635
1636 out_free:
1637         vfio_iommu_iova_free(iova_copy);
1638         return ret;
1639 }
1640
1641 static void vfio_iommu_iova_insert_copy(struct vfio_iommu *iommu,
1642                                         struct list_head *iova_copy)
1643 {
1644         struct list_head *iova = &iommu->iova_list;
1645
1646         vfio_iommu_iova_free(iova);
1647
1648         list_splice_tail(iova_copy, iova);
1649 }
1650 static int vfio_iommu_type1_attach_group(void *iommu_data,
1651                                          struct iommu_group *iommu_group)
1652 {
1653         struct vfio_iommu *iommu = iommu_data;
1654         struct vfio_group *group;
1655         struct vfio_domain *domain, *d;
1656         struct bus_type *bus = NULL;
1657         int ret;
1658         bool resv_msi, msi_remap;
1659         phys_addr_t resv_msi_base;
1660         struct iommu_domain_geometry geo;
1661         LIST_HEAD(iova_copy);
1662         LIST_HEAD(group_resv_regions);
1663
1664         mutex_lock(&iommu->lock);
1665
1666         list_for_each_entry(d, &iommu->domain_list, next) {
1667                 if (find_iommu_group(d, iommu_group)) {
1668                         mutex_unlock(&iommu->lock);
1669                         return -EINVAL;
1670                 }
1671         }
1672
1673         if (iommu->external_domain) {
1674                 if (find_iommu_group(iommu->external_domain, iommu_group)) {
1675                         mutex_unlock(&iommu->lock);
1676                         return -EINVAL;
1677                 }
1678         }
1679
1680         group = kzalloc(sizeof(*group), GFP_KERNEL);
1681         domain = kzalloc(sizeof(*domain), GFP_KERNEL);
1682         if (!group || !domain) {
1683                 ret = -ENOMEM;
1684                 goto out_free;
1685         }
1686
1687         group->iommu_group = iommu_group;
1688
1689         /* Determine bus_type in order to allocate a domain */
1690         ret = iommu_group_for_each_dev(iommu_group, &bus, vfio_bus_type);
1691         if (ret)
1692                 goto out_free;
1693
1694         if (vfio_bus_is_mdev(bus)) {
1695                 struct device *iommu_device = NULL;
1696
1697                 group->mdev_group = true;
1698
1699                 /* Determine the isolation type */
1700                 ret = iommu_group_for_each_dev(iommu_group, &iommu_device,
1701                                                vfio_mdev_iommu_device);
1702                 if (ret || !iommu_device) {
1703                         if (!iommu->external_domain) {
1704                                 INIT_LIST_HEAD(&domain->group_list);
1705                                 iommu->external_domain = domain;
1706                         } else {
1707                                 kfree(domain);
1708                         }
1709
1710                         list_add(&group->next,
1711                                  &iommu->external_domain->group_list);
1712                         mutex_unlock(&iommu->lock);
1713
1714                         return 0;
1715                 }
1716
1717                 bus = iommu_device->bus;
1718         }
1719
1720         domain->domain = iommu_domain_alloc(bus);
1721         if (!domain->domain) {
1722                 ret = -EIO;
1723                 goto out_free;
1724         }
1725
1726         if (iommu->nesting) {
1727                 int attr = 1;
1728
1729                 ret = iommu_domain_set_attr(domain->domain, DOMAIN_ATTR_NESTING,
1730                                             &attr);
1731                 if (ret)
1732                         goto out_domain;
1733         }
1734
1735         ret = vfio_iommu_attach_group(domain, group);
1736         if (ret)
1737                 goto out_domain;
1738
1739         /* Get aperture info */
1740         iommu_domain_get_attr(domain->domain, DOMAIN_ATTR_GEOMETRY, &geo);
1741
1742         if (vfio_iommu_aper_conflict(iommu, geo.aperture_start,
1743                                      geo.aperture_end)) {
1744                 ret = -EINVAL;
1745                 goto out_detach;
1746         }
1747
1748         ret = iommu_get_group_resv_regions(iommu_group, &group_resv_regions);
1749         if (ret)
1750                 goto out_detach;
1751
1752         if (vfio_iommu_resv_conflict(iommu, &group_resv_regions)) {
1753                 ret = -EINVAL;
1754                 goto out_detach;
1755         }
1756
1757         /*
1758          * We don't want to work on the original iova list as the list
1759          * gets modified and in case of failure we have to retain the
1760          * original list. Get a copy here.
1761          */
1762         ret = vfio_iommu_iova_get_copy(iommu, &iova_copy);
1763         if (ret)
1764                 goto out_detach;
1765
1766         ret = vfio_iommu_aper_resize(&iova_copy, geo.aperture_start,
1767                                      geo.aperture_end);
1768         if (ret)
1769                 goto out_detach;
1770
1771         ret = vfio_iommu_resv_exclude(&iova_copy, &group_resv_regions);
1772         if (ret)
1773                 goto out_detach;
1774
1775         resv_msi = vfio_iommu_has_sw_msi(&group_resv_regions, &resv_msi_base);
1776
1777         INIT_LIST_HEAD(&domain->group_list);
1778         list_add(&group->next, &domain->group_list);
1779
1780         msi_remap = irq_domain_check_msi_remap() ||
1781                     iommu_capable(bus, IOMMU_CAP_INTR_REMAP);
1782
1783         if (!allow_unsafe_interrupts && !msi_remap) {
1784                 pr_warn("%s: No interrupt remapping support.  Use the module param \"allow_unsafe_interrupts\" to enable VFIO IOMMU support on this platform\n",
1785                        __func__);
1786                 ret = -EPERM;
1787                 goto out_detach;
1788         }
1789
1790         if (iommu_capable(bus, IOMMU_CAP_CACHE_COHERENCY))
1791                 domain->prot |= IOMMU_CACHE;
1792
1793         /*
1794          * Try to match an existing compatible domain.  We don't want to
1795          * preclude an IOMMU driver supporting multiple bus_types and being
1796          * able to include different bus_types in the same IOMMU domain, so
1797          * we test whether the domains use the same iommu_ops rather than
1798          * testing if they're on the same bus_type.
1799          */
1800         list_for_each_entry(d, &iommu->domain_list, next) {
1801                 if (d->domain->ops == domain->domain->ops &&
1802                     d->prot == domain->prot) {
1803                         vfio_iommu_detach_group(domain, group);
1804                         if (!vfio_iommu_attach_group(d, group)) {
1805                                 list_add(&group->next, &d->group_list);
1806                                 iommu_domain_free(domain->domain);
1807                                 kfree(domain);
1808                                 goto done;
1809                         }
1810
1811                         ret = vfio_iommu_attach_group(domain, group);
1812                         if (ret)
1813                                 goto out_domain;
1814                 }
1815         }
1816
1817         vfio_test_domain_fgsp(domain);
1818
1819         /* replay mappings on new domains */
1820         ret = vfio_iommu_replay(iommu, domain);
1821         if (ret)
1822                 goto out_detach;
1823
1824         if (resv_msi) {
1825                 ret = iommu_get_msi_cookie(domain->domain, resv_msi_base);
1826                 if (ret)
1827                         goto out_detach;
1828         }
1829
1830         list_add(&domain->next, &iommu->domain_list);
1831 done:
1832         /* Delete the old one and insert new iova list */
1833         vfio_iommu_iova_insert_copy(iommu, &iova_copy);
1834         mutex_unlock(&iommu->lock);
1835         vfio_iommu_resv_free(&group_resv_regions);
1836
1837         return 0;
1838
1839 out_detach:
1840         vfio_iommu_detach_group(domain, group);
1841 out_domain:
1842         iommu_domain_free(domain->domain);
1843         vfio_iommu_iova_free(&iova_copy);
1844         vfio_iommu_resv_free(&group_resv_regions);
1845 out_free:
1846         kfree(domain);
1847         kfree(group);
1848         mutex_unlock(&iommu->lock);
1849         return ret;
1850 }
1851
1852 static void vfio_iommu_unmap_unpin_all(struct vfio_iommu *iommu)
1853 {
1854         struct rb_node *node;
1855
1856         while ((node = rb_first(&iommu->dma_list)))
1857                 vfio_remove_dma(iommu, rb_entry(node, struct vfio_dma, node));
1858 }
1859
1860 static void vfio_iommu_unmap_unpin_reaccount(struct vfio_iommu *iommu)
1861 {
1862         struct rb_node *n, *p;
1863
1864         n = rb_first(&iommu->dma_list);
1865         for (; n; n = rb_next(n)) {
1866                 struct vfio_dma *dma;
1867                 long locked = 0, unlocked = 0;
1868
1869                 dma = rb_entry(n, struct vfio_dma, node);
1870                 unlocked += vfio_unmap_unpin(iommu, dma, false);
1871                 p = rb_first(&dma->pfn_list);
1872                 for (; p; p = rb_next(p)) {
1873                         struct vfio_pfn *vpfn = rb_entry(p, struct vfio_pfn,
1874                                                          node);
1875
1876                         if (!is_invalid_reserved_pfn(vpfn->pfn))
1877                                 locked++;
1878                 }
1879                 vfio_lock_acct(dma, locked - unlocked, true);
1880         }
1881 }
1882
1883 static void vfio_sanity_check_pfn_list(struct vfio_iommu *iommu)
1884 {
1885         struct rb_node *n;
1886
1887         n = rb_first(&iommu->dma_list);
1888         for (; n; n = rb_next(n)) {
1889                 struct vfio_dma *dma;
1890
1891                 dma = rb_entry(n, struct vfio_dma, node);
1892
1893                 if (WARN_ON(!RB_EMPTY_ROOT(&dma->pfn_list)))
1894                         break;
1895         }
1896         /* mdev vendor driver must unregister notifier */
1897         WARN_ON(iommu->notifier.head);
1898 }
1899
1900 /*
1901  * Called when a domain is removed in detach. It is possible that
1902  * the removed domain decided the iova aperture window. Modify the
1903  * iova aperture with the smallest window among existing domains.
1904  */
1905 static void vfio_iommu_aper_expand(struct vfio_iommu *iommu,
1906                                    struct list_head *iova_copy)
1907 {
1908         struct vfio_domain *domain;
1909         struct iommu_domain_geometry geo;
1910         struct vfio_iova *node;
1911         dma_addr_t start = 0;
1912         dma_addr_t end = (dma_addr_t)~0;
1913
1914         if (list_empty(iova_copy))
1915                 return;
1916
1917         list_for_each_entry(domain, &iommu->domain_list, next) {
1918                 iommu_domain_get_attr(domain->domain, DOMAIN_ATTR_GEOMETRY,
1919                                       &geo);
1920                 if (geo.aperture_start > start)
1921                         start = geo.aperture_start;
1922                 if (geo.aperture_end < end)
1923                         end = geo.aperture_end;
1924         }
1925
1926         /* Modify aperture limits. The new aper is either same or bigger */
1927         node = list_first_entry(iova_copy, struct vfio_iova, list);
1928         node->start = start;
1929         node = list_last_entry(iova_copy, struct vfio_iova, list);
1930         node->end = end;
1931 }
1932
1933 /*
1934  * Called when a group is detached. The reserved regions for that
1935  * group can be part of valid iova now. But since reserved regions
1936  * may be duplicated among groups, populate the iova valid regions
1937  * list again.
1938  */
1939 static int vfio_iommu_resv_refresh(struct vfio_iommu *iommu,
1940                                    struct list_head *iova_copy)
1941 {
1942         struct vfio_domain *d;
1943         struct vfio_group *g;
1944         struct vfio_iova *node;
1945         dma_addr_t start, end;
1946         LIST_HEAD(resv_regions);
1947         int ret;
1948
1949         if (list_empty(iova_copy))
1950                 return -EINVAL;
1951
1952         list_for_each_entry(d, &iommu->domain_list, next) {
1953                 list_for_each_entry(g, &d->group_list, next) {
1954                         ret = iommu_get_group_resv_regions(g->iommu_group,
1955                                                            &resv_regions);
1956                         if (ret)
1957                                 goto done;
1958                 }
1959         }
1960
1961         node = list_first_entry(iova_copy, struct vfio_iova, list);
1962         start = node->start;
1963         node = list_last_entry(iova_copy, struct vfio_iova, list);
1964         end = node->end;
1965
1966         /* purge the iova list and create new one */
1967         vfio_iommu_iova_free(iova_copy);
1968
1969         ret = vfio_iommu_aper_resize(iova_copy, start, end);
1970         if (ret)
1971                 goto done;
1972
1973         /* Exclude current reserved regions from iova ranges */
1974         ret = vfio_iommu_resv_exclude(iova_copy, &resv_regions);
1975 done:
1976         vfio_iommu_resv_free(&resv_regions);
1977         return ret;
1978 }
1979
1980 static void vfio_iommu_type1_detach_group(void *iommu_data,
1981                                           struct iommu_group *iommu_group)
1982 {
1983         struct vfio_iommu *iommu = iommu_data;
1984         struct vfio_domain *domain;
1985         struct vfio_group *group;
1986         LIST_HEAD(iova_copy);
1987
1988         mutex_lock(&iommu->lock);
1989
1990         if (iommu->external_domain) {
1991                 group = find_iommu_group(iommu->external_domain, iommu_group);
1992                 if (group) {
1993                         list_del(&group->next);
1994                         kfree(group);
1995
1996                         if (list_empty(&iommu->external_domain->group_list)) {
1997                                 vfio_sanity_check_pfn_list(iommu);
1998
1999                                 if (!IS_IOMMU_CAP_DOMAIN_IN_CONTAINER(iommu))
2000                                         vfio_iommu_unmap_unpin_all(iommu);
2001
2002                                 kfree(iommu->external_domain);
2003                                 iommu->external_domain = NULL;
2004                         }
2005                         goto detach_group_done;
2006                 }
2007         }
2008
2009         /*
2010          * Get a copy of iova list. This will be used to update
2011          * and to replace the current one later. Please note that
2012          * we will leave the original list as it is if update fails.
2013          */
2014         vfio_iommu_iova_get_copy(iommu, &iova_copy);
2015
2016         list_for_each_entry(domain, &iommu->domain_list, next) {
2017                 group = find_iommu_group(domain, iommu_group);
2018                 if (!group)
2019                         continue;
2020
2021                 vfio_iommu_detach_group(domain, group);
2022                 list_del(&group->next);
2023                 kfree(group);
2024                 /*
2025                  * Group ownership provides privilege, if the group list is
2026                  * empty, the domain goes away. If it's the last domain with
2027                  * iommu and external domain doesn't exist, then all the
2028                  * mappings go away too. If it's the last domain with iommu and
2029                  * external domain exist, update accounting
2030                  */
2031                 if (list_empty(&domain->group_list)) {
2032                         if (list_is_singular(&iommu->domain_list)) {
2033                                 if (!iommu->external_domain)
2034                                         vfio_iommu_unmap_unpin_all(iommu);
2035                                 else
2036                                         vfio_iommu_unmap_unpin_reaccount(iommu);
2037                         }
2038                         iommu_domain_free(domain->domain);
2039                         list_del(&domain->next);
2040                         kfree(domain);
2041                         vfio_iommu_aper_expand(iommu, &iova_copy);
2042                 }
2043                 break;
2044         }
2045
2046         if (!vfio_iommu_resv_refresh(iommu, &iova_copy))
2047                 vfio_iommu_iova_insert_copy(iommu, &iova_copy);
2048         else
2049                 vfio_iommu_iova_free(&iova_copy);
2050
2051 detach_group_done:
2052         mutex_unlock(&iommu->lock);
2053 }
2054
2055 static void *vfio_iommu_type1_open(unsigned long arg)
2056 {
2057         struct vfio_iommu *iommu;
2058
2059         iommu = kzalloc(sizeof(*iommu), GFP_KERNEL);
2060         if (!iommu)
2061                 return ERR_PTR(-ENOMEM);
2062
2063         switch (arg) {
2064         case VFIO_TYPE1_IOMMU:
2065                 break;
2066         case VFIO_TYPE1_NESTING_IOMMU:
2067                 iommu->nesting = true;
2068                 /* fall through */
2069         case VFIO_TYPE1v2_IOMMU:
2070                 iommu->v2 = true;
2071                 break;
2072         default:
2073                 kfree(iommu);
2074                 return ERR_PTR(-EINVAL);
2075         }
2076
2077         INIT_LIST_HEAD(&iommu->domain_list);
2078         INIT_LIST_HEAD(&iommu->iova_list);
2079         iommu->dma_list = RB_ROOT;
2080         iommu->dma_avail = dma_entry_limit;
2081         mutex_init(&iommu->lock);
2082         BLOCKING_INIT_NOTIFIER_HEAD(&iommu->notifier);
2083
2084         return iommu;
2085 }
2086
2087 static void vfio_release_domain(struct vfio_domain *domain, bool external)
2088 {
2089         struct vfio_group *group, *group_tmp;
2090
2091         list_for_each_entry_safe(group, group_tmp,
2092                                  &domain->group_list, next) {
2093                 if (!external)
2094                         vfio_iommu_detach_group(domain, group);
2095                 list_del(&group->next);
2096                 kfree(group);
2097         }
2098
2099         if (!external)
2100                 iommu_domain_free(domain->domain);
2101 }
2102
2103 static void vfio_iommu_type1_release(void *iommu_data)
2104 {
2105         struct vfio_iommu *iommu = iommu_data;
2106         struct vfio_domain *domain, *domain_tmp;
2107
2108         if (iommu->external_domain) {
2109                 vfio_release_domain(iommu->external_domain, true);
2110                 vfio_sanity_check_pfn_list(iommu);
2111                 kfree(iommu->external_domain);
2112         }
2113
2114         vfio_iommu_unmap_unpin_all(iommu);
2115
2116         list_for_each_entry_safe(domain, domain_tmp,
2117                                  &iommu->domain_list, next) {
2118                 vfio_release_domain(domain, false);
2119                 list_del(&domain->next);
2120                 kfree(domain);
2121         }
2122
2123         vfio_iommu_iova_free(&iommu->iova_list);
2124
2125         kfree(iommu);
2126 }
2127
2128 static int vfio_domains_have_iommu_cache(struct vfio_iommu *iommu)
2129 {
2130         struct vfio_domain *domain;
2131         int ret = 1;
2132
2133         mutex_lock(&iommu->lock);
2134         list_for_each_entry(domain, &iommu->domain_list, next) {
2135                 if (!(domain->prot & IOMMU_CACHE)) {
2136                         ret = 0;
2137                         break;
2138                 }
2139         }
2140         mutex_unlock(&iommu->lock);
2141
2142         return ret;
2143 }
2144
2145 static int vfio_iommu_iova_add_cap(struct vfio_info_cap *caps,
2146                  struct vfio_iommu_type1_info_cap_iova_range *cap_iovas,
2147                  size_t size)
2148 {
2149         struct vfio_info_cap_header *header;
2150         struct vfio_iommu_type1_info_cap_iova_range *iova_cap;
2151
2152         header = vfio_info_cap_add(caps, size,
2153                                    VFIO_IOMMU_TYPE1_INFO_CAP_IOVA_RANGE, 1);
2154         if (IS_ERR(header))
2155                 return PTR_ERR(header);
2156
2157         iova_cap = container_of(header,
2158                                 struct vfio_iommu_type1_info_cap_iova_range,
2159                                 header);
2160         iova_cap->nr_iovas = cap_iovas->nr_iovas;
2161         memcpy(iova_cap->iova_ranges, cap_iovas->iova_ranges,
2162                cap_iovas->nr_iovas * sizeof(*cap_iovas->iova_ranges));
2163         return 0;
2164 }
2165
2166 static int vfio_iommu_iova_build_caps(struct vfio_iommu *iommu,
2167                                       struct vfio_info_cap *caps)
2168 {
2169         struct vfio_iommu_type1_info_cap_iova_range *cap_iovas;
2170         struct vfio_iova *iova;
2171         size_t size;
2172         int iovas = 0, i = 0, ret;
2173
2174         mutex_lock(&iommu->lock);
2175
2176         list_for_each_entry(iova, &iommu->iova_list, list)
2177                 iovas++;
2178
2179         if (!iovas) {
2180                 /*
2181                  * Return 0 as a container with a single mdev device
2182                  * will have an empty list
2183                  */
2184                 ret = 0;
2185                 goto out_unlock;
2186         }
2187
2188         size = sizeof(*cap_iovas) + (iovas * sizeof(*cap_iovas->iova_ranges));
2189
2190         cap_iovas = kzalloc(size, GFP_KERNEL);
2191         if (!cap_iovas) {
2192                 ret = -ENOMEM;
2193                 goto out_unlock;
2194         }
2195
2196         cap_iovas->nr_iovas = iovas;
2197
2198         list_for_each_entry(iova, &iommu->iova_list, list) {
2199                 cap_iovas->iova_ranges[i].start = iova->start;
2200                 cap_iovas->iova_ranges[i].end = iova->end;
2201                 i++;
2202         }
2203
2204         ret = vfio_iommu_iova_add_cap(caps, cap_iovas, size);
2205
2206         kfree(cap_iovas);
2207 out_unlock:
2208         mutex_unlock(&iommu->lock);
2209         return ret;
2210 }
2211
2212 static long vfio_iommu_type1_ioctl(void *iommu_data,
2213                                    unsigned int cmd, unsigned long arg)
2214 {
2215         struct vfio_iommu *iommu = iommu_data;
2216         unsigned long minsz;
2217
2218         if (cmd == VFIO_CHECK_EXTENSION) {
2219                 switch (arg) {
2220                 case VFIO_TYPE1_IOMMU:
2221                 case VFIO_TYPE1v2_IOMMU:
2222                 case VFIO_TYPE1_NESTING_IOMMU:
2223                         return 1;
2224                 case VFIO_DMA_CC_IOMMU:
2225                         if (!iommu)
2226                                 return 0;
2227                         return vfio_domains_have_iommu_cache(iommu);
2228                 default:
2229                         return 0;
2230                 }
2231         } else if (cmd == VFIO_IOMMU_GET_INFO) {
2232                 struct vfio_iommu_type1_info info;
2233                 struct vfio_info_cap caps = { .buf = NULL, .size = 0 };
2234                 unsigned long capsz;
2235                 int ret;
2236
2237                 minsz = offsetofend(struct vfio_iommu_type1_info, iova_pgsizes);
2238
2239                 /* For backward compatibility, cannot require this */
2240                 capsz = offsetofend(struct vfio_iommu_type1_info, cap_offset);
2241
2242                 if (copy_from_user(&info, (void __user *)arg, minsz))
2243                         return -EFAULT;
2244
2245                 if (info.argsz < minsz)
2246                         return -EINVAL;
2247
2248                 if (info.argsz >= capsz) {
2249                         minsz = capsz;
2250                         info.cap_offset = 0; /* output, no-recopy necessary */
2251                 }
2252
2253                 info.flags = VFIO_IOMMU_INFO_PGSIZES;
2254
2255                 info.iova_pgsizes = vfio_pgsize_bitmap(iommu);
2256
2257                 ret = vfio_iommu_iova_build_caps(iommu, &caps);
2258                 if (ret)
2259                         return ret;
2260
2261                 if (caps.size) {
2262                         info.flags |= VFIO_IOMMU_INFO_CAPS;
2263
2264                         if (info.argsz < sizeof(info) + caps.size) {
2265                                 info.argsz = sizeof(info) + caps.size;
2266                         } else {
2267                                 vfio_info_cap_shift(&caps, sizeof(info));
2268                                 if (copy_to_user((void __user *)arg +
2269                                                 sizeof(info), caps.buf,
2270                                                 caps.size)) {
2271                                         kfree(caps.buf);
2272                                         return -EFAULT;
2273                                 }
2274                                 info.cap_offset = sizeof(info);
2275                         }
2276
2277                         kfree(caps.buf);
2278                 }
2279
2280                 return copy_to_user((void __user *)arg, &info, minsz) ?
2281                         -EFAULT : 0;
2282
2283         } else if (cmd == VFIO_IOMMU_MAP_DMA) {
2284                 struct vfio_iommu_type1_dma_map map;
2285                 uint32_t mask = VFIO_DMA_MAP_FLAG_READ |
2286                                 VFIO_DMA_MAP_FLAG_WRITE;
2287
2288                 minsz = offsetofend(struct vfio_iommu_type1_dma_map, size);
2289
2290                 if (copy_from_user(&map, (void __user *)arg, minsz))
2291                         return -EFAULT;
2292
2293                 if (map.argsz < minsz || map.flags & ~mask)
2294                         return -EINVAL;
2295
2296                 return vfio_dma_do_map(iommu, &map);
2297
2298         } else if (cmd == VFIO_IOMMU_UNMAP_DMA) {
2299                 struct vfio_iommu_type1_dma_unmap unmap;
2300                 long ret;
2301
2302                 minsz = offsetofend(struct vfio_iommu_type1_dma_unmap, size);
2303
2304                 if (copy_from_user(&unmap, (void __user *)arg, minsz))
2305                         return -EFAULT;
2306
2307                 if (unmap.argsz < minsz || unmap.flags)
2308                         return -EINVAL;
2309
2310                 ret = vfio_dma_do_unmap(iommu, &unmap);
2311                 if (ret)
2312                         return ret;
2313
2314                 return copy_to_user((void __user *)arg, &unmap, minsz) ?
2315                         -EFAULT : 0;
2316         }
2317
2318         return -ENOTTY;
2319 }
2320
2321 static int vfio_iommu_type1_register_notifier(void *iommu_data,
2322                                               unsigned long *events,
2323                                               struct notifier_block *nb)
2324 {
2325         struct vfio_iommu *iommu = iommu_data;
2326
2327         /* clear known events */
2328         *events &= ~VFIO_IOMMU_NOTIFY_DMA_UNMAP;
2329
2330         /* refuse to register if still events remaining */
2331         if (*events)
2332                 return -EINVAL;
2333
2334         return blocking_notifier_chain_register(&iommu->notifier, nb);
2335 }
2336
2337 static int vfio_iommu_type1_unregister_notifier(void *iommu_data,
2338                                                 struct notifier_block *nb)
2339 {
2340         struct vfio_iommu *iommu = iommu_data;
2341
2342         return blocking_notifier_chain_unregister(&iommu->notifier, nb);
2343 }
2344
2345 static const struct vfio_iommu_driver_ops vfio_iommu_driver_ops_type1 = {
2346         .name                   = "vfio-iommu-type1",
2347         .owner                  = THIS_MODULE,
2348         .open                   = vfio_iommu_type1_open,
2349         .release                = vfio_iommu_type1_release,
2350         .ioctl                  = vfio_iommu_type1_ioctl,
2351         .attach_group           = vfio_iommu_type1_attach_group,
2352         .detach_group           = vfio_iommu_type1_detach_group,
2353         .pin_pages              = vfio_iommu_type1_pin_pages,
2354         .unpin_pages            = vfio_iommu_type1_unpin_pages,
2355         .register_notifier      = vfio_iommu_type1_register_notifier,
2356         .unregister_notifier    = vfio_iommu_type1_unregister_notifier,
2357 };
2358
2359 static int __init vfio_iommu_type1_init(void)
2360 {
2361         return vfio_register_iommu_driver(&vfio_iommu_driver_ops_type1);
2362 }
2363
2364 static void __exit vfio_iommu_type1_cleanup(void)
2365 {
2366         vfio_unregister_iommu_driver(&vfio_iommu_driver_ops_type1);
2367 }
2368
2369 module_init(vfio_iommu_type1_init);
2370 module_exit(vfio_iommu_type1_cleanup);
2371
2372 MODULE_VERSION(DRIVER_VERSION);
2373 MODULE_LICENSE("GPL v2");
2374 MODULE_AUTHOR(DRIVER_AUTHOR);
2375 MODULE_DESCRIPTION(DRIVER_DESC);