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