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