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