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