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