Merge tag 'pci-v6.4-fixes-1' of git://git.kernel.org/pub/scm/linux/kernel/git/pci/pci
[linux.git] / drivers / vfio / vfio_iommu_type1.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * VFIO: IOMMU DMA mapping support for Type1 IOMMU
4  *
5  * Copyright (C) 2012 Red Hat, Inc.  All rights reserved.
6  *     Author: Alex Williamson <alex.williamson@redhat.com>
7  *
8  * Derived from original vfio:
9  * Copyright 2010 Cisco Systems, Inc.  All rights reserved.
10  * Author: Tom Lyon, pugs@cisco.com
11  *
12  * We arbitrarily define a Type1 IOMMU as one matching the below code.
13  * It could be called the x86 IOMMU as it's designed for AMD-Vi & Intel
14  * VT-d, but that makes it harder to re-use as theoretically anyone
15  * implementing a similar IOMMU could make use of this.  We expect the
16  * IOMMU to support the IOMMU API and have few to no restrictions around
17  * the IOVA range that can be mapped.  The Type1 IOMMU is currently
18  * optimized for relatively static mappings of a userspace process with
19  * userspace pages pinned into memory.  We also assume devices and IOMMU
20  * domains are PCI based as the IOMMU API is still centered around a
21  * device/bus interface rather than a group interface.
22  */
23
24 #include <linux/compat.h>
25 #include <linux/device.h>
26 #include <linux/fs.h>
27 #include <linux/highmem.h>
28 #include <linux/iommu.h>
29 #include <linux/module.h>
30 #include <linux/mm.h>
31 #include <linux/kthread.h>
32 #include <linux/rbtree.h>
33 #include <linux/sched/signal.h>
34 #include <linux/sched/mm.h>
35 #include <linux/slab.h>
36 #include <linux/uaccess.h>
37 #include <linux/vfio.h>
38 #include <linux/workqueue.h>
39 #include <linux/notifier.h>
40 #include "vfio.h"
41
42 #define DRIVER_VERSION  "0.2"
43 #define DRIVER_AUTHOR   "Alex Williamson <alex.williamson@redhat.com>"
44 #define DRIVER_DESC     "Type1 IOMMU driver for VFIO"
45
46 static bool allow_unsafe_interrupts;
47 module_param_named(allow_unsafe_interrupts,
48                    allow_unsafe_interrupts, bool, S_IRUGO | S_IWUSR);
49 MODULE_PARM_DESC(allow_unsafe_interrupts,
50                  "Enable VFIO IOMMU support for on platforms without interrupt remapping support.");
51
52 static bool disable_hugepages;
53 module_param_named(disable_hugepages,
54                    disable_hugepages, bool, S_IRUGO | S_IWUSR);
55 MODULE_PARM_DESC(disable_hugepages,
56                  "Disable VFIO IOMMU support for IOMMU hugepages.");
57
58 static unsigned int dma_entry_limit __read_mostly = U16_MAX;
59 module_param_named(dma_entry_limit, dma_entry_limit, uint, 0644);
60 MODULE_PARM_DESC(dma_entry_limit,
61                  "Maximum number of user DMA mappings per container (65535).");
62
63 struct vfio_iommu {
64         struct list_head        domain_list;
65         struct list_head        iova_list;
66         struct mutex            lock;
67         struct rb_root          dma_list;
68         struct list_head        device_list;
69         struct mutex            device_list_lock;
70         unsigned int            dma_avail;
71         unsigned int            vaddr_invalid_count;
72         uint64_t                pgsize_bitmap;
73         uint64_t                num_non_pinned_groups;
74         bool                    v2;
75         bool                    nesting;
76         bool                    dirty_page_tracking;
77         struct list_head        emulated_iommu_groups;
78 };
79
80 struct vfio_domain {
81         struct iommu_domain     *domain;
82         struct list_head        next;
83         struct list_head        group_list;
84         bool                    fgsp : 1;       /* Fine-grained super pages */
85         bool                    enforce_cache_coherency : 1;
86 };
87
88 struct vfio_dma {
89         struct rb_node          node;
90         dma_addr_t              iova;           /* Device address */
91         unsigned long           vaddr;          /* Process virtual addr */
92         size_t                  size;           /* Map size (bytes) */
93         int                     prot;           /* IOMMU_READ/WRITE */
94         bool                    iommu_mapped;
95         bool                    lock_cap;       /* capable(CAP_IPC_LOCK) */
96         bool                    vaddr_invalid;
97         struct task_struct      *task;
98         struct rb_root          pfn_list;       /* Ex-user pinned pfn list */
99         unsigned long           *bitmap;
100         struct mm_struct        *mm;
101         size_t                  locked_vm;
102 };
103
104 struct vfio_batch {
105         struct page             **pages;        /* for pin_user_pages_remote */
106         struct page             *fallback_page; /* if pages alloc fails */
107         int                     capacity;       /* length of pages array */
108         int                     size;           /* of batch currently */
109         int                     offset;         /* of next entry in pages */
110 };
111
112 struct vfio_iommu_group {
113         struct iommu_group      *iommu_group;
114         struct list_head        next;
115         bool                    pinned_page_dirty_scope;
116 };
117
118 struct vfio_iova {
119         struct list_head        list;
120         dma_addr_t              start;
121         dma_addr_t              end;
122 };
123
124 /*
125  * Guest RAM pinning working set or DMA target
126  */
127 struct vfio_pfn {
128         struct rb_node          node;
129         dma_addr_t              iova;           /* Device address */
130         unsigned long           pfn;            /* Host pfn */
131         unsigned int            ref_count;
132 };
133
134 struct vfio_regions {
135         struct list_head list;
136         dma_addr_t iova;
137         phys_addr_t phys;
138         size_t len;
139 };
140
141 #define DIRTY_BITMAP_BYTES(n)   (ALIGN(n, BITS_PER_TYPE(u64)) / BITS_PER_BYTE)
142
143 /*
144  * Input argument of number of bits to bitmap_set() is unsigned integer, which
145  * further casts to signed integer for unaligned multi-bit operation,
146  * __bitmap_set().
147  * Then maximum bitmap size supported is 2^31 bits divided by 2^3 bits/byte,
148  * that is 2^28 (256 MB) which maps to 2^31 * 2^12 = 2^43 (8TB) on 4K page
149  * system.
150  */
151 #define DIRTY_BITMAP_PAGES_MAX   ((u64)INT_MAX)
152 #define DIRTY_BITMAP_SIZE_MAX    DIRTY_BITMAP_BYTES(DIRTY_BITMAP_PAGES_MAX)
153
154 static int put_pfn(unsigned long pfn, int prot);
155
156 static struct vfio_iommu_group*
157 vfio_iommu_find_iommu_group(struct vfio_iommu *iommu,
158                             struct iommu_group *iommu_group);
159
160 /*
161  * This code handles mapping and unmapping of user data buffers
162  * into DMA'ble space using the IOMMU
163  */
164
165 static struct vfio_dma *vfio_find_dma(struct vfio_iommu *iommu,
166                                       dma_addr_t start, size_t size)
167 {
168         struct rb_node *node = iommu->dma_list.rb_node;
169
170         while (node) {
171                 struct vfio_dma *dma = rb_entry(node, struct vfio_dma, node);
172
173                 if (start + size <= dma->iova)
174                         node = node->rb_left;
175                 else if (start >= dma->iova + dma->size)
176                         node = node->rb_right;
177                 else
178                         return dma;
179         }
180
181         return NULL;
182 }
183
184 static struct rb_node *vfio_find_dma_first_node(struct vfio_iommu *iommu,
185                                                 dma_addr_t start, u64 size)
186 {
187         struct rb_node *res = NULL;
188         struct rb_node *node = iommu->dma_list.rb_node;
189         struct vfio_dma *dma_res = NULL;
190
191         while (node) {
192                 struct vfio_dma *dma = rb_entry(node, struct vfio_dma, node);
193
194                 if (start < dma->iova + dma->size) {
195                         res = node;
196                         dma_res = dma;
197                         if (start >= dma->iova)
198                                 break;
199                         node = node->rb_left;
200                 } else {
201                         node = node->rb_right;
202                 }
203         }
204         if (res && size && dma_res->iova >= start + size)
205                 res = NULL;
206         return res;
207 }
208
209 static void vfio_link_dma(struct vfio_iommu *iommu, struct vfio_dma *new)
210 {
211         struct rb_node **link = &iommu->dma_list.rb_node, *parent = NULL;
212         struct vfio_dma *dma;
213
214         while (*link) {
215                 parent = *link;
216                 dma = rb_entry(parent, struct vfio_dma, node);
217
218                 if (new->iova + new->size <= dma->iova)
219                         link = &(*link)->rb_left;
220                 else
221                         link = &(*link)->rb_right;
222         }
223
224         rb_link_node(&new->node, parent, link);
225         rb_insert_color(&new->node, &iommu->dma_list);
226 }
227
228 static void vfio_unlink_dma(struct vfio_iommu *iommu, struct vfio_dma *old)
229 {
230         rb_erase(&old->node, &iommu->dma_list);
231 }
232
233
234 static int vfio_dma_bitmap_alloc(struct vfio_dma *dma, size_t pgsize)
235 {
236         uint64_t npages = dma->size / pgsize;
237
238         if (npages > DIRTY_BITMAP_PAGES_MAX)
239                 return -EINVAL;
240
241         /*
242          * Allocate extra 64 bits that are used to calculate shift required for
243          * bitmap_shift_left() to manipulate and club unaligned number of pages
244          * in adjacent vfio_dma ranges.
245          */
246         dma->bitmap = kvzalloc(DIRTY_BITMAP_BYTES(npages) + sizeof(u64),
247                                GFP_KERNEL);
248         if (!dma->bitmap)
249                 return -ENOMEM;
250
251         return 0;
252 }
253
254 static void vfio_dma_bitmap_free(struct vfio_dma *dma)
255 {
256         kvfree(dma->bitmap);
257         dma->bitmap = NULL;
258 }
259
260 static void vfio_dma_populate_bitmap(struct vfio_dma *dma, size_t pgsize)
261 {
262         struct rb_node *p;
263         unsigned long pgshift = __ffs(pgsize);
264
265         for (p = rb_first(&dma->pfn_list); p; p = rb_next(p)) {
266                 struct vfio_pfn *vpfn = rb_entry(p, struct vfio_pfn, node);
267
268                 bitmap_set(dma->bitmap, (vpfn->iova - dma->iova) >> pgshift, 1);
269         }
270 }
271
272 static void vfio_iommu_populate_bitmap_full(struct vfio_iommu *iommu)
273 {
274         struct rb_node *n;
275         unsigned long pgshift = __ffs(iommu->pgsize_bitmap);
276
277         for (n = rb_first(&iommu->dma_list); n; n = rb_next(n)) {
278                 struct vfio_dma *dma = rb_entry(n, struct vfio_dma, node);
279
280                 bitmap_set(dma->bitmap, 0, dma->size >> pgshift);
281         }
282 }
283
284 static int vfio_dma_bitmap_alloc_all(struct vfio_iommu *iommu, size_t pgsize)
285 {
286         struct rb_node *n;
287
288         for (n = rb_first(&iommu->dma_list); n; n = rb_next(n)) {
289                 struct vfio_dma *dma = rb_entry(n, struct vfio_dma, node);
290                 int ret;
291
292                 ret = vfio_dma_bitmap_alloc(dma, pgsize);
293                 if (ret) {
294                         struct rb_node *p;
295
296                         for (p = rb_prev(n); p; p = rb_prev(p)) {
297                                 struct vfio_dma *dma = rb_entry(n,
298                                                         struct vfio_dma, node);
299
300                                 vfio_dma_bitmap_free(dma);
301                         }
302                         return ret;
303                 }
304                 vfio_dma_populate_bitmap(dma, pgsize);
305         }
306         return 0;
307 }
308
309 static void vfio_dma_bitmap_free_all(struct vfio_iommu *iommu)
310 {
311         struct rb_node *n;
312
313         for (n = rb_first(&iommu->dma_list); n; n = rb_next(n)) {
314                 struct vfio_dma *dma = rb_entry(n, struct vfio_dma, node);
315
316                 vfio_dma_bitmap_free(dma);
317         }
318 }
319
320 /*
321  * Helper Functions for host iova-pfn list
322  */
323 static struct vfio_pfn *vfio_find_vpfn(struct vfio_dma *dma, dma_addr_t iova)
324 {
325         struct vfio_pfn *vpfn;
326         struct rb_node *node = dma->pfn_list.rb_node;
327
328         while (node) {
329                 vpfn = rb_entry(node, struct vfio_pfn, node);
330
331                 if (iova < vpfn->iova)
332                         node = node->rb_left;
333                 else if (iova > vpfn->iova)
334                         node = node->rb_right;
335                 else
336                         return vpfn;
337         }
338         return NULL;
339 }
340
341 static void vfio_link_pfn(struct vfio_dma *dma,
342                           struct vfio_pfn *new)
343 {
344         struct rb_node **link, *parent = NULL;
345         struct vfio_pfn *vpfn;
346
347         link = &dma->pfn_list.rb_node;
348         while (*link) {
349                 parent = *link;
350                 vpfn = rb_entry(parent, struct vfio_pfn, node);
351
352                 if (new->iova < vpfn->iova)
353                         link = &(*link)->rb_left;
354                 else
355                         link = &(*link)->rb_right;
356         }
357
358         rb_link_node(&new->node, parent, link);
359         rb_insert_color(&new->node, &dma->pfn_list);
360 }
361
362 static void vfio_unlink_pfn(struct vfio_dma *dma, struct vfio_pfn *old)
363 {
364         rb_erase(&old->node, &dma->pfn_list);
365 }
366
367 static int vfio_add_to_pfn_list(struct vfio_dma *dma, dma_addr_t iova,
368                                 unsigned long pfn)
369 {
370         struct vfio_pfn *vpfn;
371
372         vpfn = kzalloc(sizeof(*vpfn), GFP_KERNEL);
373         if (!vpfn)
374                 return -ENOMEM;
375
376         vpfn->iova = iova;
377         vpfn->pfn = pfn;
378         vpfn->ref_count = 1;
379         vfio_link_pfn(dma, vpfn);
380         return 0;
381 }
382
383 static void vfio_remove_from_pfn_list(struct vfio_dma *dma,
384                                       struct vfio_pfn *vpfn)
385 {
386         vfio_unlink_pfn(dma, vpfn);
387         kfree(vpfn);
388 }
389
390 static struct vfio_pfn *vfio_iova_get_vfio_pfn(struct vfio_dma *dma,
391                                                unsigned long iova)
392 {
393         struct vfio_pfn *vpfn = vfio_find_vpfn(dma, iova);
394
395         if (vpfn)
396                 vpfn->ref_count++;
397         return vpfn;
398 }
399
400 static int vfio_iova_put_vfio_pfn(struct vfio_dma *dma, struct vfio_pfn *vpfn)
401 {
402         int ret = 0;
403
404         vpfn->ref_count--;
405         if (!vpfn->ref_count) {
406                 ret = put_pfn(vpfn->pfn, dma->prot);
407                 vfio_remove_from_pfn_list(dma, vpfn);
408         }
409         return ret;
410 }
411
412 static int mm_lock_acct(struct task_struct *task, struct mm_struct *mm,
413                         bool lock_cap, long npage)
414 {
415         int ret = mmap_write_lock_killable(mm);
416
417         if (ret)
418                 return ret;
419
420         ret = __account_locked_vm(mm, abs(npage), npage > 0, task, lock_cap);
421         mmap_write_unlock(mm);
422         return ret;
423 }
424
425 static int vfio_lock_acct(struct vfio_dma *dma, long npage, bool async)
426 {
427         struct mm_struct *mm;
428         int ret;
429
430         if (!npage)
431                 return 0;
432
433         mm = dma->mm;
434         if (async && !mmget_not_zero(mm))
435                 return -ESRCH; /* process exited */
436
437         ret = mm_lock_acct(dma->task, mm, dma->lock_cap, npage);
438         if (!ret)
439                 dma->locked_vm += npage;
440
441         if (async)
442                 mmput(mm);
443
444         return ret;
445 }
446
447 /*
448  * Some mappings aren't backed by a struct page, for example an mmap'd
449  * MMIO range for our own or another device.  These use a different
450  * pfn conversion and shouldn't be tracked as locked pages.
451  * For compound pages, any driver that sets the reserved bit in head
452  * page needs to set the reserved bit in all subpages to be safe.
453  */
454 static bool is_invalid_reserved_pfn(unsigned long pfn)
455 {
456         if (pfn_valid(pfn))
457                 return PageReserved(pfn_to_page(pfn));
458
459         return true;
460 }
461
462 static int put_pfn(unsigned long pfn, int prot)
463 {
464         if (!is_invalid_reserved_pfn(pfn)) {
465                 struct page *page = pfn_to_page(pfn);
466
467                 unpin_user_pages_dirty_lock(&page, 1, prot & IOMMU_WRITE);
468                 return 1;
469         }
470         return 0;
471 }
472
473 #define VFIO_BATCH_MAX_CAPACITY (PAGE_SIZE / sizeof(struct page *))
474
475 static void vfio_batch_init(struct vfio_batch *batch)
476 {
477         batch->size = 0;
478         batch->offset = 0;
479
480         if (unlikely(disable_hugepages))
481                 goto fallback;
482
483         batch->pages = (struct page **) __get_free_page(GFP_KERNEL);
484         if (!batch->pages)
485                 goto fallback;
486
487         batch->capacity = VFIO_BATCH_MAX_CAPACITY;
488         return;
489
490 fallback:
491         batch->pages = &batch->fallback_page;
492         batch->capacity = 1;
493 }
494
495 static void vfio_batch_unpin(struct vfio_batch *batch, struct vfio_dma *dma)
496 {
497         while (batch->size) {
498                 unsigned long pfn = page_to_pfn(batch->pages[batch->offset]);
499
500                 put_pfn(pfn, dma->prot);
501                 batch->offset++;
502                 batch->size--;
503         }
504 }
505
506 static void vfio_batch_fini(struct vfio_batch *batch)
507 {
508         if (batch->capacity == VFIO_BATCH_MAX_CAPACITY)
509                 free_page((unsigned long)batch->pages);
510 }
511
512 static int follow_fault_pfn(struct vm_area_struct *vma, struct mm_struct *mm,
513                             unsigned long vaddr, unsigned long *pfn,
514                             bool write_fault)
515 {
516         pte_t *ptep;
517         spinlock_t *ptl;
518         int ret;
519
520         ret = follow_pte(vma->vm_mm, vaddr, &ptep, &ptl);
521         if (ret) {
522                 bool unlocked = false;
523
524                 ret = fixup_user_fault(mm, vaddr,
525                                        FAULT_FLAG_REMOTE |
526                                        (write_fault ?  FAULT_FLAG_WRITE : 0),
527                                        &unlocked);
528                 if (unlocked)
529                         return -EAGAIN;
530
531                 if (ret)
532                         return ret;
533
534                 ret = follow_pte(vma->vm_mm, vaddr, &ptep, &ptl);
535                 if (ret)
536                         return ret;
537         }
538
539         if (write_fault && !pte_write(*ptep))
540                 ret = -EFAULT;
541         else
542                 *pfn = pte_pfn(*ptep);
543
544         pte_unmap_unlock(ptep, ptl);
545         return ret;
546 }
547
548 /*
549  * Returns the positive number of pfns successfully obtained or a negative
550  * error code.
551  */
552 static int vaddr_get_pfns(struct mm_struct *mm, unsigned long vaddr,
553                           long npages, int prot, unsigned long *pfn,
554                           struct page **pages)
555 {
556         struct vm_area_struct *vma;
557         unsigned int flags = 0;
558         int ret;
559
560         if (prot & IOMMU_WRITE)
561                 flags |= FOLL_WRITE;
562
563         mmap_read_lock(mm);
564         ret = pin_user_pages_remote(mm, vaddr, npages, flags | FOLL_LONGTERM,
565                                     pages, NULL, NULL);
566         if (ret > 0) {
567                 int i;
568
569                 /*
570                  * The zero page is always resident, we don't need to pin it
571                  * and it falls into our invalid/reserved test so we don't
572                  * unpin in put_pfn().  Unpin all zero pages in the batch here.
573                  */
574                 for (i = 0 ; i < ret; i++) {
575                         if (unlikely(is_zero_pfn(page_to_pfn(pages[i]))))
576                                 unpin_user_page(pages[i]);
577                 }
578
579                 *pfn = page_to_pfn(pages[0]);
580                 goto done;
581         }
582
583         vaddr = untagged_addr_remote(mm, vaddr);
584
585 retry:
586         vma = vma_lookup(mm, vaddr);
587
588         if (vma && vma->vm_flags & VM_PFNMAP) {
589                 ret = follow_fault_pfn(vma, mm, vaddr, pfn, prot & IOMMU_WRITE);
590                 if (ret == -EAGAIN)
591                         goto retry;
592
593                 if (!ret) {
594                         if (is_invalid_reserved_pfn(*pfn))
595                                 ret = 1;
596                         else
597                                 ret = -EFAULT;
598                 }
599         }
600 done:
601         mmap_read_unlock(mm);
602         return ret;
603 }
604
605 /*
606  * Attempt to pin pages.  We really don't want to track all the pfns and
607  * the iommu can only map chunks of consecutive pfns anyway, so get the
608  * first page and all consecutive pages with the same locking.
609  */
610 static long vfio_pin_pages_remote(struct vfio_dma *dma, unsigned long vaddr,
611                                   long npage, unsigned long *pfn_base,
612                                   unsigned long limit, struct vfio_batch *batch)
613 {
614         unsigned long pfn;
615         struct mm_struct *mm = current->mm;
616         long ret, pinned = 0, lock_acct = 0;
617         bool rsvd;
618         dma_addr_t iova = vaddr - dma->vaddr + dma->iova;
619
620         /* This code path is only user initiated */
621         if (!mm)
622                 return -ENODEV;
623
624         if (batch->size) {
625                 /* Leftover pages in batch from an earlier call. */
626                 *pfn_base = page_to_pfn(batch->pages[batch->offset]);
627                 pfn = *pfn_base;
628                 rsvd = is_invalid_reserved_pfn(*pfn_base);
629         } else {
630                 *pfn_base = 0;
631         }
632
633         while (npage) {
634                 if (!batch->size) {
635                         /* Empty batch, so refill it. */
636                         long req_pages = min_t(long, npage, batch->capacity);
637
638                         ret = vaddr_get_pfns(mm, vaddr, req_pages, dma->prot,
639                                              &pfn, batch->pages);
640                         if (ret < 0)
641                                 goto unpin_out;
642
643                         batch->size = ret;
644                         batch->offset = 0;
645
646                         if (!*pfn_base) {
647                                 *pfn_base = pfn;
648                                 rsvd = is_invalid_reserved_pfn(*pfn_base);
649                         }
650                 }
651
652                 /*
653                  * pfn is preset for the first iteration of this inner loop and
654                  * updated at the end to handle a VM_PFNMAP pfn.  In that case,
655                  * batch->pages isn't valid (there's no struct page), so allow
656                  * batch->pages to be touched only when there's more than one
657                  * pfn to check, which guarantees the pfns are from a
658                  * !VM_PFNMAP vma.
659                  */
660                 while (true) {
661                         if (pfn != *pfn_base + pinned ||
662                             rsvd != is_invalid_reserved_pfn(pfn))
663                                 goto out;
664
665                         /*
666                          * Reserved pages aren't counted against the user,
667                          * externally pinned pages are already counted against
668                          * the user.
669                          */
670                         if (!rsvd && !vfio_find_vpfn(dma, iova)) {
671                                 if (!dma->lock_cap &&
672                                     mm->locked_vm + lock_acct + 1 > limit) {
673                                         pr_warn("%s: RLIMIT_MEMLOCK (%ld) exceeded\n",
674                                                 __func__, limit << PAGE_SHIFT);
675                                         ret = -ENOMEM;
676                                         goto unpin_out;
677                                 }
678                                 lock_acct++;
679                         }
680
681                         pinned++;
682                         npage--;
683                         vaddr += PAGE_SIZE;
684                         iova += PAGE_SIZE;
685                         batch->offset++;
686                         batch->size--;
687
688                         if (!batch->size)
689                                 break;
690
691                         pfn = page_to_pfn(batch->pages[batch->offset]);
692                 }
693
694                 if (unlikely(disable_hugepages))
695                         break;
696         }
697
698 out:
699         ret = vfio_lock_acct(dma, lock_acct, false);
700
701 unpin_out:
702         if (batch->size == 1 && !batch->offset) {
703                 /* May be a VM_PFNMAP pfn, which the batch can't remember. */
704                 put_pfn(pfn, dma->prot);
705                 batch->size = 0;
706         }
707
708         if (ret < 0) {
709                 if (pinned && !rsvd) {
710                         for (pfn = *pfn_base ; pinned ; pfn++, pinned--)
711                                 put_pfn(pfn, dma->prot);
712                 }
713                 vfio_batch_unpin(batch, dma);
714
715                 return ret;
716         }
717
718         return pinned;
719 }
720
721 static long vfio_unpin_pages_remote(struct vfio_dma *dma, dma_addr_t iova,
722                                     unsigned long pfn, long npage,
723                                     bool do_accounting)
724 {
725         long unlocked = 0, locked = 0;
726         long i;
727
728         for (i = 0; i < npage; i++, iova += PAGE_SIZE) {
729                 if (put_pfn(pfn++, dma->prot)) {
730                         unlocked++;
731                         if (vfio_find_vpfn(dma, iova))
732                                 locked++;
733                 }
734         }
735
736         if (do_accounting)
737                 vfio_lock_acct(dma, locked - unlocked, true);
738
739         return unlocked;
740 }
741
742 static int vfio_pin_page_external(struct vfio_dma *dma, unsigned long vaddr,
743                                   unsigned long *pfn_base, bool do_accounting)
744 {
745         struct page *pages[1];
746         struct mm_struct *mm;
747         int ret;
748
749         mm = dma->mm;
750         if (!mmget_not_zero(mm))
751                 return -ENODEV;
752
753         ret = vaddr_get_pfns(mm, vaddr, 1, dma->prot, pfn_base, pages);
754         if (ret != 1)
755                 goto out;
756
757         ret = 0;
758
759         if (do_accounting && !is_invalid_reserved_pfn(*pfn_base)) {
760                 ret = vfio_lock_acct(dma, 1, false);
761                 if (ret) {
762                         put_pfn(*pfn_base, dma->prot);
763                         if (ret == -ENOMEM)
764                                 pr_warn("%s: Task %s (%d) RLIMIT_MEMLOCK "
765                                         "(%ld) exceeded\n", __func__,
766                                         dma->task->comm, task_pid_nr(dma->task),
767                                         task_rlimit(dma->task, RLIMIT_MEMLOCK));
768                 }
769         }
770
771 out:
772         mmput(mm);
773         return ret;
774 }
775
776 static int vfio_unpin_page_external(struct vfio_dma *dma, dma_addr_t iova,
777                                     bool do_accounting)
778 {
779         int unlocked;
780         struct vfio_pfn *vpfn = vfio_find_vpfn(dma, iova);
781
782         if (!vpfn)
783                 return 0;
784
785         unlocked = vfio_iova_put_vfio_pfn(dma, vpfn);
786
787         if (do_accounting)
788                 vfio_lock_acct(dma, -unlocked, true);
789
790         return unlocked;
791 }
792
793 static int vfio_iommu_type1_pin_pages(void *iommu_data,
794                                       struct iommu_group *iommu_group,
795                                       dma_addr_t user_iova,
796                                       int npage, int prot,
797                                       struct page **pages)
798 {
799         struct vfio_iommu *iommu = iommu_data;
800         struct vfio_iommu_group *group;
801         int i, j, ret;
802         unsigned long remote_vaddr;
803         struct vfio_dma *dma;
804         bool do_accounting;
805
806         if (!iommu || !pages)
807                 return -EINVAL;
808
809         /* Supported for v2 version only */
810         if (!iommu->v2)
811                 return -EACCES;
812
813         mutex_lock(&iommu->lock);
814
815         if (WARN_ONCE(iommu->vaddr_invalid_count,
816                       "vfio_pin_pages not allowed with VFIO_UPDATE_VADDR\n")) {
817                 ret = -EBUSY;
818                 goto pin_done;
819         }
820
821         /* Fail if no dma_umap notifier is registered */
822         if (list_empty(&iommu->device_list)) {
823                 ret = -EINVAL;
824                 goto pin_done;
825         }
826
827         /*
828          * If iommu capable domain exist in the container then all pages are
829          * already pinned and accounted. Accounting should be done if there is no
830          * iommu capable domain in the container.
831          */
832         do_accounting = list_empty(&iommu->domain_list);
833
834         for (i = 0; i < npage; i++) {
835                 unsigned long phys_pfn;
836                 dma_addr_t iova;
837                 struct vfio_pfn *vpfn;
838
839                 iova = user_iova + PAGE_SIZE * i;
840                 dma = vfio_find_dma(iommu, iova, PAGE_SIZE);
841                 if (!dma) {
842                         ret = -EINVAL;
843                         goto pin_unwind;
844                 }
845
846                 if ((dma->prot & prot) != prot) {
847                         ret = -EPERM;
848                         goto pin_unwind;
849                 }
850
851                 vpfn = vfio_iova_get_vfio_pfn(dma, iova);
852                 if (vpfn) {
853                         pages[i] = pfn_to_page(vpfn->pfn);
854                         continue;
855                 }
856
857                 remote_vaddr = dma->vaddr + (iova - dma->iova);
858                 ret = vfio_pin_page_external(dma, remote_vaddr, &phys_pfn,
859                                              do_accounting);
860                 if (ret)
861                         goto pin_unwind;
862
863                 if (!pfn_valid(phys_pfn)) {
864                         ret = -EINVAL;
865                         goto pin_unwind;
866                 }
867
868                 ret = vfio_add_to_pfn_list(dma, iova, phys_pfn);
869                 if (ret) {
870                         if (put_pfn(phys_pfn, dma->prot) && do_accounting)
871                                 vfio_lock_acct(dma, -1, true);
872                         goto pin_unwind;
873                 }
874
875                 pages[i] = pfn_to_page(phys_pfn);
876
877                 if (iommu->dirty_page_tracking) {
878                         unsigned long pgshift = __ffs(iommu->pgsize_bitmap);
879
880                         /*
881                          * Bitmap populated with the smallest supported page
882                          * size
883                          */
884                         bitmap_set(dma->bitmap,
885                                    (iova - dma->iova) >> pgshift, 1);
886                 }
887         }
888         ret = i;
889
890         group = vfio_iommu_find_iommu_group(iommu, iommu_group);
891         if (!group->pinned_page_dirty_scope) {
892                 group->pinned_page_dirty_scope = true;
893                 iommu->num_non_pinned_groups--;
894         }
895
896         goto pin_done;
897
898 pin_unwind:
899         pages[i] = NULL;
900         for (j = 0; j < i; j++) {
901                 dma_addr_t iova;
902
903                 iova = user_iova + PAGE_SIZE * j;
904                 dma = vfio_find_dma(iommu, iova, PAGE_SIZE);
905                 vfio_unpin_page_external(dma, iova, do_accounting);
906                 pages[j] = NULL;
907         }
908 pin_done:
909         mutex_unlock(&iommu->lock);
910         return ret;
911 }
912
913 static void vfio_iommu_type1_unpin_pages(void *iommu_data,
914                                          dma_addr_t user_iova, int npage)
915 {
916         struct vfio_iommu *iommu = iommu_data;
917         bool do_accounting;
918         int i;
919
920         /* Supported for v2 version only */
921         if (WARN_ON(!iommu->v2))
922                 return;
923
924         mutex_lock(&iommu->lock);
925
926         do_accounting = list_empty(&iommu->domain_list);
927         for (i = 0; i < npage; i++) {
928                 dma_addr_t iova = user_iova + PAGE_SIZE * i;
929                 struct vfio_dma *dma;
930
931                 dma = vfio_find_dma(iommu, iova, PAGE_SIZE);
932                 if (!dma)
933                         break;
934
935                 vfio_unpin_page_external(dma, iova, do_accounting);
936         }
937
938         mutex_unlock(&iommu->lock);
939
940         WARN_ON(i != npage);
941 }
942
943 static long vfio_sync_unpin(struct vfio_dma *dma, struct vfio_domain *domain,
944                             struct list_head *regions,
945                             struct iommu_iotlb_gather *iotlb_gather)
946 {
947         long unlocked = 0;
948         struct vfio_regions *entry, *next;
949
950         iommu_iotlb_sync(domain->domain, iotlb_gather);
951
952         list_for_each_entry_safe(entry, next, regions, list) {
953                 unlocked += vfio_unpin_pages_remote(dma,
954                                                     entry->iova,
955                                                     entry->phys >> PAGE_SHIFT,
956                                                     entry->len >> PAGE_SHIFT,
957                                                     false);
958                 list_del(&entry->list);
959                 kfree(entry);
960         }
961
962         cond_resched();
963
964         return unlocked;
965 }
966
967 /*
968  * Generally, VFIO needs to unpin remote pages after each IOTLB flush.
969  * Therefore, when using IOTLB flush sync interface, VFIO need to keep track
970  * of these regions (currently using a list).
971  *
972  * This value specifies maximum number of regions for each IOTLB flush sync.
973  */
974 #define VFIO_IOMMU_TLB_SYNC_MAX         512
975
976 static size_t unmap_unpin_fast(struct vfio_domain *domain,
977                                struct vfio_dma *dma, dma_addr_t *iova,
978                                size_t len, phys_addr_t phys, long *unlocked,
979                                struct list_head *unmapped_list,
980                                int *unmapped_cnt,
981                                struct iommu_iotlb_gather *iotlb_gather)
982 {
983         size_t unmapped = 0;
984         struct vfio_regions *entry = kzalloc(sizeof(*entry), GFP_KERNEL);
985
986         if (entry) {
987                 unmapped = iommu_unmap_fast(domain->domain, *iova, len,
988                                             iotlb_gather);
989
990                 if (!unmapped) {
991                         kfree(entry);
992                 } else {
993                         entry->iova = *iova;
994                         entry->phys = phys;
995                         entry->len  = unmapped;
996                         list_add_tail(&entry->list, unmapped_list);
997
998                         *iova += unmapped;
999                         (*unmapped_cnt)++;
1000                 }
1001         }
1002
1003         /*
1004          * Sync if the number of fast-unmap regions hits the limit
1005          * or in case of errors.
1006          */
1007         if (*unmapped_cnt >= VFIO_IOMMU_TLB_SYNC_MAX || !unmapped) {
1008                 *unlocked += vfio_sync_unpin(dma, domain, unmapped_list,
1009                                              iotlb_gather);
1010                 *unmapped_cnt = 0;
1011         }
1012
1013         return unmapped;
1014 }
1015
1016 static size_t unmap_unpin_slow(struct vfio_domain *domain,
1017                                struct vfio_dma *dma, dma_addr_t *iova,
1018                                size_t len, phys_addr_t phys,
1019                                long *unlocked)
1020 {
1021         size_t unmapped = iommu_unmap(domain->domain, *iova, len);
1022
1023         if (unmapped) {
1024                 *unlocked += vfio_unpin_pages_remote(dma, *iova,
1025                                                      phys >> PAGE_SHIFT,
1026                                                      unmapped >> PAGE_SHIFT,
1027                                                      false);
1028                 *iova += unmapped;
1029                 cond_resched();
1030         }
1031         return unmapped;
1032 }
1033
1034 static long vfio_unmap_unpin(struct vfio_iommu *iommu, struct vfio_dma *dma,
1035                              bool do_accounting)
1036 {
1037         dma_addr_t iova = dma->iova, end = dma->iova + dma->size;
1038         struct vfio_domain *domain, *d;
1039         LIST_HEAD(unmapped_region_list);
1040         struct iommu_iotlb_gather iotlb_gather;
1041         int unmapped_region_cnt = 0;
1042         long unlocked = 0;
1043
1044         if (!dma->size)
1045                 return 0;
1046
1047         if (list_empty(&iommu->domain_list))
1048                 return 0;
1049
1050         /*
1051          * We use the IOMMU to track the physical addresses, otherwise we'd
1052          * need a much more complicated tracking system.  Unfortunately that
1053          * means we need to use one of the iommu domains to figure out the
1054          * pfns to unpin.  The rest need to be unmapped in advance so we have
1055          * no iommu translations remaining when the pages are unpinned.
1056          */
1057         domain = d = list_first_entry(&iommu->domain_list,
1058                                       struct vfio_domain, next);
1059
1060         list_for_each_entry_continue(d, &iommu->domain_list, next) {
1061                 iommu_unmap(d->domain, dma->iova, dma->size);
1062                 cond_resched();
1063         }
1064
1065         iommu_iotlb_gather_init(&iotlb_gather);
1066         while (iova < end) {
1067                 size_t unmapped, len;
1068                 phys_addr_t phys, next;
1069
1070                 phys = iommu_iova_to_phys(domain->domain, iova);
1071                 if (WARN_ON(!phys)) {
1072                         iova += PAGE_SIZE;
1073                         continue;
1074                 }
1075
1076                 /*
1077                  * To optimize for fewer iommu_unmap() calls, each of which
1078                  * may require hardware cache flushing, try to find the
1079                  * largest contiguous physical memory chunk to unmap.
1080                  */
1081                 for (len = PAGE_SIZE;
1082                      !domain->fgsp && iova + len < end; len += PAGE_SIZE) {
1083                         next = iommu_iova_to_phys(domain->domain, iova + len);
1084                         if (next != phys + len)
1085                                 break;
1086                 }
1087
1088                 /*
1089                  * First, try to use fast unmap/unpin. In case of failure,
1090                  * switch to slow unmap/unpin path.
1091                  */
1092                 unmapped = unmap_unpin_fast(domain, dma, &iova, len, phys,
1093                                             &unlocked, &unmapped_region_list,
1094                                             &unmapped_region_cnt,
1095                                             &iotlb_gather);
1096                 if (!unmapped) {
1097                         unmapped = unmap_unpin_slow(domain, dma, &iova, len,
1098                                                     phys, &unlocked);
1099                         if (WARN_ON(!unmapped))
1100                                 break;
1101                 }
1102         }
1103
1104         dma->iommu_mapped = false;
1105
1106         if (unmapped_region_cnt) {
1107                 unlocked += vfio_sync_unpin(dma, domain, &unmapped_region_list,
1108                                             &iotlb_gather);
1109         }
1110
1111         if (do_accounting) {
1112                 vfio_lock_acct(dma, -unlocked, true);
1113                 return 0;
1114         }
1115         return unlocked;
1116 }
1117
1118 static void vfio_remove_dma(struct vfio_iommu *iommu, struct vfio_dma *dma)
1119 {
1120         WARN_ON(!RB_EMPTY_ROOT(&dma->pfn_list));
1121         vfio_unmap_unpin(iommu, dma, true);
1122         vfio_unlink_dma(iommu, dma);
1123         put_task_struct(dma->task);
1124         mmdrop(dma->mm);
1125         vfio_dma_bitmap_free(dma);
1126         if (dma->vaddr_invalid)
1127                 iommu->vaddr_invalid_count--;
1128         kfree(dma);
1129         iommu->dma_avail++;
1130 }
1131
1132 static void vfio_update_pgsize_bitmap(struct vfio_iommu *iommu)
1133 {
1134         struct vfio_domain *domain;
1135
1136         iommu->pgsize_bitmap = ULONG_MAX;
1137
1138         list_for_each_entry(domain, &iommu->domain_list, next)
1139                 iommu->pgsize_bitmap &= domain->domain->pgsize_bitmap;
1140
1141         /*
1142          * In case the IOMMU supports page sizes smaller than PAGE_SIZE
1143          * we pretend PAGE_SIZE is supported and hide sub-PAGE_SIZE sizes.
1144          * That way the user will be able to map/unmap buffers whose size/
1145          * start address is aligned with PAGE_SIZE. Pinning code uses that
1146          * granularity while iommu driver can use the sub-PAGE_SIZE size
1147          * to map the buffer.
1148          */
1149         if (iommu->pgsize_bitmap & ~PAGE_MASK) {
1150                 iommu->pgsize_bitmap &= PAGE_MASK;
1151                 iommu->pgsize_bitmap |= PAGE_SIZE;
1152         }
1153 }
1154
1155 static int update_user_bitmap(u64 __user *bitmap, struct vfio_iommu *iommu,
1156                               struct vfio_dma *dma, dma_addr_t base_iova,
1157                               size_t pgsize)
1158 {
1159         unsigned long pgshift = __ffs(pgsize);
1160         unsigned long nbits = dma->size >> pgshift;
1161         unsigned long bit_offset = (dma->iova - base_iova) >> pgshift;
1162         unsigned long copy_offset = bit_offset / BITS_PER_LONG;
1163         unsigned long shift = bit_offset % BITS_PER_LONG;
1164         unsigned long leftover;
1165
1166         /*
1167          * mark all pages dirty if any IOMMU capable device is not able
1168          * to report dirty pages and all pages are pinned and mapped.
1169          */
1170         if (iommu->num_non_pinned_groups && dma->iommu_mapped)
1171                 bitmap_set(dma->bitmap, 0, nbits);
1172
1173         if (shift) {
1174                 bitmap_shift_left(dma->bitmap, dma->bitmap, shift,
1175                                   nbits + shift);
1176
1177                 if (copy_from_user(&leftover,
1178                                    (void __user *)(bitmap + copy_offset),
1179                                    sizeof(leftover)))
1180                         return -EFAULT;
1181
1182                 bitmap_or(dma->bitmap, dma->bitmap, &leftover, shift);
1183         }
1184
1185         if (copy_to_user((void __user *)(bitmap + copy_offset), dma->bitmap,
1186                          DIRTY_BITMAP_BYTES(nbits + shift)))
1187                 return -EFAULT;
1188
1189         return 0;
1190 }
1191
1192 static int vfio_iova_dirty_bitmap(u64 __user *bitmap, struct vfio_iommu *iommu,
1193                                   dma_addr_t iova, size_t size, size_t pgsize)
1194 {
1195         struct vfio_dma *dma;
1196         struct rb_node *n;
1197         unsigned long pgshift = __ffs(pgsize);
1198         int ret;
1199
1200         /*
1201          * GET_BITMAP request must fully cover vfio_dma mappings.  Multiple
1202          * vfio_dma mappings may be clubbed by specifying large ranges, but
1203          * there must not be any previous mappings bisected by the range.
1204          * An error will be returned if these conditions are not met.
1205          */
1206         dma = vfio_find_dma(iommu, iova, 1);
1207         if (dma && dma->iova != iova)
1208                 return -EINVAL;
1209
1210         dma = vfio_find_dma(iommu, iova + size - 1, 0);
1211         if (dma && dma->iova + dma->size != iova + size)
1212                 return -EINVAL;
1213
1214         for (n = rb_first(&iommu->dma_list); n; n = rb_next(n)) {
1215                 struct vfio_dma *dma = rb_entry(n, struct vfio_dma, node);
1216
1217                 if (dma->iova < iova)
1218                         continue;
1219
1220                 if (dma->iova > iova + size - 1)
1221                         break;
1222
1223                 ret = update_user_bitmap(bitmap, iommu, dma, iova, pgsize);
1224                 if (ret)
1225                         return ret;
1226
1227                 /*
1228                  * Re-populate bitmap to include all pinned pages which are
1229                  * considered as dirty but exclude pages which are unpinned and
1230                  * pages which are marked dirty by vfio_dma_rw()
1231                  */
1232                 bitmap_clear(dma->bitmap, 0, dma->size >> pgshift);
1233                 vfio_dma_populate_bitmap(dma, pgsize);
1234         }
1235         return 0;
1236 }
1237
1238 static int verify_bitmap_size(uint64_t npages, uint64_t bitmap_size)
1239 {
1240         if (!npages || !bitmap_size || (bitmap_size > DIRTY_BITMAP_SIZE_MAX) ||
1241             (bitmap_size < DIRTY_BITMAP_BYTES(npages)))
1242                 return -EINVAL;
1243
1244         return 0;
1245 }
1246
1247 /*
1248  * Notify VFIO drivers using vfio_register_emulated_iommu_dev() to invalidate
1249  * and unmap iovas within the range we're about to unmap. Drivers MUST unpin
1250  * pages in response to an invalidation.
1251  */
1252 static void vfio_notify_dma_unmap(struct vfio_iommu *iommu,
1253                                   struct vfio_dma *dma)
1254 {
1255         struct vfio_device *device;
1256
1257         if (list_empty(&iommu->device_list))
1258                 return;
1259
1260         /*
1261          * The device is expected to call vfio_unpin_pages() for any IOVA it has
1262          * pinned within the range. Since vfio_unpin_pages() will eventually
1263          * call back down to this code and try to obtain the iommu->lock we must
1264          * drop it.
1265          */
1266         mutex_lock(&iommu->device_list_lock);
1267         mutex_unlock(&iommu->lock);
1268
1269         list_for_each_entry(device, &iommu->device_list, iommu_entry)
1270                 device->ops->dma_unmap(device, dma->iova, dma->size);
1271
1272         mutex_unlock(&iommu->device_list_lock);
1273         mutex_lock(&iommu->lock);
1274 }
1275
1276 static int vfio_dma_do_unmap(struct vfio_iommu *iommu,
1277                              struct vfio_iommu_type1_dma_unmap *unmap,
1278                              struct vfio_bitmap *bitmap)
1279 {
1280         struct vfio_dma *dma, *dma_last = NULL;
1281         size_t unmapped = 0, pgsize;
1282         int ret = -EINVAL, retries = 0;
1283         unsigned long pgshift;
1284         dma_addr_t iova = unmap->iova;
1285         u64 size = unmap->size;
1286         bool unmap_all = unmap->flags & VFIO_DMA_UNMAP_FLAG_ALL;
1287         bool invalidate_vaddr = unmap->flags & VFIO_DMA_UNMAP_FLAG_VADDR;
1288         struct rb_node *n, *first_n;
1289
1290         mutex_lock(&iommu->lock);
1291
1292         /* Cannot update vaddr if mdev is present. */
1293         if (invalidate_vaddr && !list_empty(&iommu->emulated_iommu_groups)) {
1294                 ret = -EBUSY;
1295                 goto unlock;
1296         }
1297
1298         pgshift = __ffs(iommu->pgsize_bitmap);
1299         pgsize = (size_t)1 << pgshift;
1300
1301         if (iova & (pgsize - 1))
1302                 goto unlock;
1303
1304         if (unmap_all) {
1305                 if (iova || size)
1306                         goto unlock;
1307                 size = U64_MAX;
1308         } else if (!size || size & (pgsize - 1) ||
1309                    iova + size - 1 < iova || size > SIZE_MAX) {
1310                 goto unlock;
1311         }
1312
1313         /* When dirty tracking is enabled, allow only min supported pgsize */
1314         if ((unmap->flags & VFIO_DMA_UNMAP_FLAG_GET_DIRTY_BITMAP) &&
1315             (!iommu->dirty_page_tracking || (bitmap->pgsize != pgsize))) {
1316                 goto unlock;
1317         }
1318
1319         WARN_ON((pgsize - 1) & PAGE_MASK);
1320 again:
1321         /*
1322          * vfio-iommu-type1 (v1) - User mappings were coalesced together to
1323          * avoid tracking individual mappings.  This means that the granularity
1324          * of the original mapping was lost and the user was allowed to attempt
1325          * to unmap any range.  Depending on the contiguousness of physical
1326          * memory and page sizes supported by the IOMMU, arbitrary unmaps may
1327          * or may not have worked.  We only guaranteed unmap granularity
1328          * matching the original mapping; even though it was untracked here,
1329          * the original mappings are reflected in IOMMU mappings.  This
1330          * resulted in a couple unusual behaviors.  First, if a range is not
1331          * able to be unmapped, ex. a set of 4k pages that was mapped as a
1332          * 2M hugepage into the IOMMU, the unmap ioctl returns success but with
1333          * a zero sized unmap.  Also, if an unmap request overlaps the first
1334          * address of a hugepage, the IOMMU will unmap the entire hugepage.
1335          * This also returns success and the returned unmap size reflects the
1336          * actual size unmapped.
1337          *
1338          * We attempt to maintain compatibility with this "v1" interface, but
1339          * we take control out of the hands of the IOMMU.  Therefore, an unmap
1340          * request offset from the beginning of the original mapping will
1341          * return success with zero sized unmap.  And an unmap request covering
1342          * the first iova of mapping will unmap the entire range.
1343          *
1344          * The v2 version of this interface intends to be more deterministic.
1345          * Unmap requests must fully cover previous mappings.  Multiple
1346          * mappings may still be unmaped by specifying large ranges, but there
1347          * must not be any previous mappings bisected by the range.  An error
1348          * will be returned if these conditions are not met.  The v2 interface
1349          * will only return success and a size of zero if there were no
1350          * mappings within the range.
1351          */
1352         if (iommu->v2 && !unmap_all) {
1353                 dma = vfio_find_dma(iommu, iova, 1);
1354                 if (dma && dma->iova != iova)
1355                         goto unlock;
1356
1357                 dma = vfio_find_dma(iommu, iova + size - 1, 0);
1358                 if (dma && dma->iova + dma->size != iova + size)
1359                         goto unlock;
1360         }
1361
1362         ret = 0;
1363         n = first_n = vfio_find_dma_first_node(iommu, iova, size);
1364
1365         while (n) {
1366                 dma = rb_entry(n, struct vfio_dma, node);
1367                 if (dma->iova >= iova + size)
1368                         break;
1369
1370                 if (!iommu->v2 && iova > dma->iova)
1371                         break;
1372
1373                 if (invalidate_vaddr) {
1374                         if (dma->vaddr_invalid) {
1375                                 struct rb_node *last_n = n;
1376
1377                                 for (n = first_n; n != last_n; n = rb_next(n)) {
1378                                         dma = rb_entry(n,
1379                                                        struct vfio_dma, node);
1380                                         dma->vaddr_invalid = false;
1381                                         iommu->vaddr_invalid_count--;
1382                                 }
1383                                 ret = -EINVAL;
1384                                 unmapped = 0;
1385                                 break;
1386                         }
1387                         dma->vaddr_invalid = true;
1388                         iommu->vaddr_invalid_count++;
1389                         unmapped += dma->size;
1390                         n = rb_next(n);
1391                         continue;
1392                 }
1393
1394                 if (!RB_EMPTY_ROOT(&dma->pfn_list)) {
1395                         if (dma_last == dma) {
1396                                 BUG_ON(++retries > 10);
1397                         } else {
1398                                 dma_last = dma;
1399                                 retries = 0;
1400                         }
1401
1402                         vfio_notify_dma_unmap(iommu, dma);
1403                         goto again;
1404                 }
1405
1406                 if (unmap->flags & VFIO_DMA_UNMAP_FLAG_GET_DIRTY_BITMAP) {
1407                         ret = update_user_bitmap(bitmap->data, iommu, dma,
1408                                                  iova, pgsize);
1409                         if (ret)
1410                                 break;
1411                 }
1412
1413                 unmapped += dma->size;
1414                 n = rb_next(n);
1415                 vfio_remove_dma(iommu, dma);
1416         }
1417
1418 unlock:
1419         mutex_unlock(&iommu->lock);
1420
1421         /* Report how much was unmapped */
1422         unmap->size = unmapped;
1423
1424         return ret;
1425 }
1426
1427 static int vfio_iommu_map(struct vfio_iommu *iommu, dma_addr_t iova,
1428                           unsigned long pfn, long npage, int prot)
1429 {
1430         struct vfio_domain *d;
1431         int ret;
1432
1433         list_for_each_entry(d, &iommu->domain_list, next) {
1434                 ret = iommu_map(d->domain, iova, (phys_addr_t)pfn << PAGE_SHIFT,
1435                                 npage << PAGE_SHIFT, prot | IOMMU_CACHE,
1436                                 GFP_KERNEL);
1437                 if (ret)
1438                         goto unwind;
1439
1440                 cond_resched();
1441         }
1442
1443         return 0;
1444
1445 unwind:
1446         list_for_each_entry_continue_reverse(d, &iommu->domain_list, next) {
1447                 iommu_unmap(d->domain, iova, npage << PAGE_SHIFT);
1448                 cond_resched();
1449         }
1450
1451         return ret;
1452 }
1453
1454 static int vfio_pin_map_dma(struct vfio_iommu *iommu, struct vfio_dma *dma,
1455                             size_t map_size)
1456 {
1457         dma_addr_t iova = dma->iova;
1458         unsigned long vaddr = dma->vaddr;
1459         struct vfio_batch batch;
1460         size_t size = map_size;
1461         long npage;
1462         unsigned long pfn, limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
1463         int ret = 0;
1464
1465         vfio_batch_init(&batch);
1466
1467         while (size) {
1468                 /* Pin a contiguous chunk of memory */
1469                 npage = vfio_pin_pages_remote(dma, vaddr + dma->size,
1470                                               size >> PAGE_SHIFT, &pfn, limit,
1471                                               &batch);
1472                 if (npage <= 0) {
1473                         WARN_ON(!npage);
1474                         ret = (int)npage;
1475                         break;
1476                 }
1477
1478                 /* Map it! */
1479                 ret = vfio_iommu_map(iommu, iova + dma->size, pfn, npage,
1480                                      dma->prot);
1481                 if (ret) {
1482                         vfio_unpin_pages_remote(dma, iova + dma->size, pfn,
1483                                                 npage, true);
1484                         vfio_batch_unpin(&batch, dma);
1485                         break;
1486                 }
1487
1488                 size -= npage << PAGE_SHIFT;
1489                 dma->size += npage << PAGE_SHIFT;
1490         }
1491
1492         vfio_batch_fini(&batch);
1493         dma->iommu_mapped = true;
1494
1495         if (ret)
1496                 vfio_remove_dma(iommu, dma);
1497
1498         return ret;
1499 }
1500
1501 /*
1502  * Check dma map request is within a valid iova range
1503  */
1504 static bool vfio_iommu_iova_dma_valid(struct vfio_iommu *iommu,
1505                                       dma_addr_t start, dma_addr_t end)
1506 {
1507         struct list_head *iova = &iommu->iova_list;
1508         struct vfio_iova *node;
1509
1510         list_for_each_entry(node, iova, list) {
1511                 if (start >= node->start && end <= node->end)
1512                         return true;
1513         }
1514
1515         /*
1516          * Check for list_empty() as well since a container with
1517          * a single mdev device will have an empty list.
1518          */
1519         return list_empty(iova);
1520 }
1521
1522 static int vfio_change_dma_owner(struct vfio_dma *dma)
1523 {
1524         struct task_struct *task = current->group_leader;
1525         struct mm_struct *mm = current->mm;
1526         long npage = dma->locked_vm;
1527         bool lock_cap;
1528         int ret;
1529
1530         if (mm == dma->mm)
1531                 return 0;
1532
1533         lock_cap = capable(CAP_IPC_LOCK);
1534         ret = mm_lock_acct(task, mm, lock_cap, npage);
1535         if (ret)
1536                 return ret;
1537
1538         if (mmget_not_zero(dma->mm)) {
1539                 mm_lock_acct(dma->task, dma->mm, dma->lock_cap, -npage);
1540                 mmput(dma->mm);
1541         }
1542
1543         if (dma->task != task) {
1544                 put_task_struct(dma->task);
1545                 dma->task = get_task_struct(task);
1546         }
1547         mmdrop(dma->mm);
1548         dma->mm = mm;
1549         mmgrab(dma->mm);
1550         dma->lock_cap = lock_cap;
1551         return 0;
1552 }
1553
1554 static int vfio_dma_do_map(struct vfio_iommu *iommu,
1555                            struct vfio_iommu_type1_dma_map *map)
1556 {
1557         bool set_vaddr = map->flags & VFIO_DMA_MAP_FLAG_VADDR;
1558         dma_addr_t iova = map->iova;
1559         unsigned long vaddr = map->vaddr;
1560         size_t size = map->size;
1561         int ret = 0, prot = 0;
1562         size_t pgsize;
1563         struct vfio_dma *dma;
1564
1565         /* Verify that none of our __u64 fields overflow */
1566         if (map->size != size || map->vaddr != vaddr || map->iova != iova)
1567                 return -EINVAL;
1568
1569         /* READ/WRITE from device perspective */
1570         if (map->flags & VFIO_DMA_MAP_FLAG_WRITE)
1571                 prot |= IOMMU_WRITE;
1572         if (map->flags & VFIO_DMA_MAP_FLAG_READ)
1573                 prot |= IOMMU_READ;
1574
1575         if ((prot && set_vaddr) || (!prot && !set_vaddr))
1576                 return -EINVAL;
1577
1578         mutex_lock(&iommu->lock);
1579
1580         pgsize = (size_t)1 << __ffs(iommu->pgsize_bitmap);
1581
1582         WARN_ON((pgsize - 1) & PAGE_MASK);
1583
1584         if (!size || (size | iova | vaddr) & (pgsize - 1)) {
1585                 ret = -EINVAL;
1586                 goto out_unlock;
1587         }
1588
1589         /* Don't allow IOVA or virtual address wrap */
1590         if (iova + size - 1 < iova || vaddr + size - 1 < vaddr) {
1591                 ret = -EINVAL;
1592                 goto out_unlock;
1593         }
1594
1595         dma = vfio_find_dma(iommu, iova, size);
1596         if (set_vaddr) {
1597                 if (!dma) {
1598                         ret = -ENOENT;
1599                 } else if (!dma->vaddr_invalid || dma->iova != iova ||
1600                            dma->size != size) {
1601                         ret = -EINVAL;
1602                 } else {
1603                         ret = vfio_change_dma_owner(dma);
1604                         if (ret)
1605                                 goto out_unlock;
1606                         dma->vaddr = vaddr;
1607                         dma->vaddr_invalid = false;
1608                         iommu->vaddr_invalid_count--;
1609                 }
1610                 goto out_unlock;
1611         } else if (dma) {
1612                 ret = -EEXIST;
1613                 goto out_unlock;
1614         }
1615
1616         if (!iommu->dma_avail) {
1617                 ret = -ENOSPC;
1618                 goto out_unlock;
1619         }
1620
1621         if (!vfio_iommu_iova_dma_valid(iommu, iova, iova + size - 1)) {
1622                 ret = -EINVAL;
1623                 goto out_unlock;
1624         }
1625
1626         dma = kzalloc(sizeof(*dma), GFP_KERNEL);
1627         if (!dma) {
1628                 ret = -ENOMEM;
1629                 goto out_unlock;
1630         }
1631
1632         iommu->dma_avail--;
1633         dma->iova = iova;
1634         dma->vaddr = vaddr;
1635         dma->prot = prot;
1636
1637         /*
1638          * We need to be able to both add to a task's locked memory and test
1639          * against the locked memory limit and we need to be able to do both
1640          * outside of this call path as pinning can be asynchronous via the
1641          * external interfaces for mdev devices.  RLIMIT_MEMLOCK requires a
1642          * task_struct. Save the group_leader so that all DMA tracking uses
1643          * the same task, to make debugging easier.  VM locked pages requires
1644          * an mm_struct, so grab the mm in case the task dies.
1645          */
1646         get_task_struct(current->group_leader);
1647         dma->task = current->group_leader;
1648         dma->lock_cap = capable(CAP_IPC_LOCK);
1649         dma->mm = current->mm;
1650         mmgrab(dma->mm);
1651
1652         dma->pfn_list = RB_ROOT;
1653
1654         /* Insert zero-sized and grow as we map chunks of it */
1655         vfio_link_dma(iommu, dma);
1656
1657         /* Don't pin and map if container doesn't contain IOMMU capable domain*/
1658         if (list_empty(&iommu->domain_list))
1659                 dma->size = size;
1660         else
1661                 ret = vfio_pin_map_dma(iommu, dma, size);
1662
1663         if (!ret && iommu->dirty_page_tracking) {
1664                 ret = vfio_dma_bitmap_alloc(dma, pgsize);
1665                 if (ret)
1666                         vfio_remove_dma(iommu, dma);
1667         }
1668
1669 out_unlock:
1670         mutex_unlock(&iommu->lock);
1671         return ret;
1672 }
1673
1674 static int vfio_iommu_replay(struct vfio_iommu *iommu,
1675                              struct vfio_domain *domain)
1676 {
1677         struct vfio_batch batch;
1678         struct vfio_domain *d = NULL;
1679         struct rb_node *n;
1680         unsigned long limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
1681         int ret;
1682
1683         /* Arbitrarily pick the first domain in the list for lookups */
1684         if (!list_empty(&iommu->domain_list))
1685                 d = list_first_entry(&iommu->domain_list,
1686                                      struct vfio_domain, next);
1687
1688         vfio_batch_init(&batch);
1689
1690         n = rb_first(&iommu->dma_list);
1691
1692         for (; n; n = rb_next(n)) {
1693                 struct vfio_dma *dma;
1694                 dma_addr_t iova;
1695
1696                 dma = rb_entry(n, struct vfio_dma, node);
1697                 iova = dma->iova;
1698
1699                 while (iova < dma->iova + dma->size) {
1700                         phys_addr_t phys;
1701                         size_t size;
1702
1703                         if (dma->iommu_mapped) {
1704                                 phys_addr_t p;
1705                                 dma_addr_t i;
1706
1707                                 if (WARN_ON(!d)) { /* mapped w/o a domain?! */
1708                                         ret = -EINVAL;
1709                                         goto unwind;
1710                                 }
1711
1712                                 phys = iommu_iova_to_phys(d->domain, iova);
1713
1714                                 if (WARN_ON(!phys)) {
1715                                         iova += PAGE_SIZE;
1716                                         continue;
1717                                 }
1718
1719                                 size = PAGE_SIZE;
1720                                 p = phys + size;
1721                                 i = iova + size;
1722                                 while (i < dma->iova + dma->size &&
1723                                        p == iommu_iova_to_phys(d->domain, i)) {
1724                                         size += PAGE_SIZE;
1725                                         p += PAGE_SIZE;
1726                                         i += PAGE_SIZE;
1727                                 }
1728                         } else {
1729                                 unsigned long pfn;
1730                                 unsigned long vaddr = dma->vaddr +
1731                                                      (iova - dma->iova);
1732                                 size_t n = dma->iova + dma->size - iova;
1733                                 long npage;
1734
1735                                 npage = vfio_pin_pages_remote(dma, vaddr,
1736                                                               n >> PAGE_SHIFT,
1737                                                               &pfn, limit,
1738                                                               &batch);
1739                                 if (npage <= 0) {
1740                                         WARN_ON(!npage);
1741                                         ret = (int)npage;
1742                                         goto unwind;
1743                                 }
1744
1745                                 phys = pfn << PAGE_SHIFT;
1746                                 size = npage << PAGE_SHIFT;
1747                         }
1748
1749                         ret = iommu_map(domain->domain, iova, phys, size,
1750                                         dma->prot | IOMMU_CACHE, GFP_KERNEL);
1751                         if (ret) {
1752                                 if (!dma->iommu_mapped) {
1753                                         vfio_unpin_pages_remote(dma, iova,
1754                                                         phys >> PAGE_SHIFT,
1755                                                         size >> PAGE_SHIFT,
1756                                                         true);
1757                                         vfio_batch_unpin(&batch, dma);
1758                                 }
1759                                 goto unwind;
1760                         }
1761
1762                         iova += size;
1763                 }
1764         }
1765
1766         /* All dmas are now mapped, defer to second tree walk for unwind */
1767         for (n = rb_first(&iommu->dma_list); n; n = rb_next(n)) {
1768                 struct vfio_dma *dma = rb_entry(n, struct vfio_dma, node);
1769
1770                 dma->iommu_mapped = true;
1771         }
1772
1773         vfio_batch_fini(&batch);
1774         return 0;
1775
1776 unwind:
1777         for (; n; n = rb_prev(n)) {
1778                 struct vfio_dma *dma = rb_entry(n, struct vfio_dma, node);
1779                 dma_addr_t iova;
1780
1781                 if (dma->iommu_mapped) {
1782                         iommu_unmap(domain->domain, dma->iova, dma->size);
1783                         continue;
1784                 }
1785
1786                 iova = dma->iova;
1787                 while (iova < dma->iova + dma->size) {
1788                         phys_addr_t phys, p;
1789                         size_t size;
1790                         dma_addr_t i;
1791
1792                         phys = iommu_iova_to_phys(domain->domain, iova);
1793                         if (!phys) {
1794                                 iova += PAGE_SIZE;
1795                                 continue;
1796                         }
1797
1798                         size = PAGE_SIZE;
1799                         p = phys + size;
1800                         i = iova + size;
1801                         while (i < dma->iova + dma->size &&
1802                                p == iommu_iova_to_phys(domain->domain, i)) {
1803                                 size += PAGE_SIZE;
1804                                 p += PAGE_SIZE;
1805                                 i += PAGE_SIZE;
1806                         }
1807
1808                         iommu_unmap(domain->domain, iova, size);
1809                         vfio_unpin_pages_remote(dma, iova, phys >> PAGE_SHIFT,
1810                                                 size >> PAGE_SHIFT, true);
1811                 }
1812         }
1813
1814         vfio_batch_fini(&batch);
1815         return ret;
1816 }
1817
1818 /*
1819  * We change our unmap behavior slightly depending on whether the IOMMU
1820  * supports fine-grained superpages.  IOMMUs like AMD-Vi will use a superpage
1821  * for practically any contiguous power-of-two mapping we give it.  This means
1822  * we don't need to look for contiguous chunks ourselves to make unmapping
1823  * more efficient.  On IOMMUs with coarse-grained super pages, like Intel VT-d
1824  * with discrete 2M/1G/512G/1T superpages, identifying contiguous chunks
1825  * significantly boosts non-hugetlbfs mappings and doesn't seem to hurt when
1826  * hugetlbfs is in use.
1827  */
1828 static void vfio_test_domain_fgsp(struct vfio_domain *domain, struct list_head *regions)
1829 {
1830         int ret, order = get_order(PAGE_SIZE * 2);
1831         struct vfio_iova *region;
1832         struct page *pages;
1833         dma_addr_t start;
1834
1835         pages = alloc_pages(GFP_KERNEL | __GFP_ZERO, order);
1836         if (!pages)
1837                 return;
1838
1839         list_for_each_entry(region, regions, list) {
1840                 start = ALIGN(region->start, PAGE_SIZE * 2);
1841                 if (start >= region->end || (region->end - start < PAGE_SIZE * 2))
1842                         continue;
1843
1844                 ret = iommu_map(domain->domain, start, page_to_phys(pages), PAGE_SIZE * 2,
1845                                 IOMMU_READ | IOMMU_WRITE | IOMMU_CACHE, GFP_KERNEL);
1846                 if (!ret) {
1847                         size_t unmapped = iommu_unmap(domain->domain, start, PAGE_SIZE);
1848
1849                         if (unmapped == PAGE_SIZE)
1850                                 iommu_unmap(domain->domain, start + PAGE_SIZE, PAGE_SIZE);
1851                         else
1852                                 domain->fgsp = true;
1853                 }
1854                 break;
1855         }
1856
1857         __free_pages(pages, order);
1858 }
1859
1860 static struct vfio_iommu_group *find_iommu_group(struct vfio_domain *domain,
1861                                                  struct iommu_group *iommu_group)
1862 {
1863         struct vfio_iommu_group *g;
1864
1865         list_for_each_entry(g, &domain->group_list, next) {
1866                 if (g->iommu_group == iommu_group)
1867                         return g;
1868         }
1869
1870         return NULL;
1871 }
1872
1873 static struct vfio_iommu_group*
1874 vfio_iommu_find_iommu_group(struct vfio_iommu *iommu,
1875                             struct iommu_group *iommu_group)
1876 {
1877         struct vfio_iommu_group *group;
1878         struct vfio_domain *domain;
1879
1880         list_for_each_entry(domain, &iommu->domain_list, next) {
1881                 group = find_iommu_group(domain, iommu_group);
1882                 if (group)
1883                         return group;
1884         }
1885
1886         list_for_each_entry(group, &iommu->emulated_iommu_groups, next)
1887                 if (group->iommu_group == iommu_group)
1888                         return group;
1889         return NULL;
1890 }
1891
1892 static bool vfio_iommu_has_sw_msi(struct list_head *group_resv_regions,
1893                                   phys_addr_t *base)
1894 {
1895         struct iommu_resv_region *region;
1896         bool ret = false;
1897
1898         list_for_each_entry(region, group_resv_regions, list) {
1899                 /*
1900                  * The presence of any 'real' MSI regions should take
1901                  * precedence over the software-managed one if the
1902                  * IOMMU driver happens to advertise both types.
1903                  */
1904                 if (region->type == IOMMU_RESV_MSI) {
1905                         ret = false;
1906                         break;
1907                 }
1908
1909                 if (region->type == IOMMU_RESV_SW_MSI) {
1910                         *base = region->start;
1911                         ret = true;
1912                 }
1913         }
1914
1915         return ret;
1916 }
1917
1918 /*
1919  * This is a helper function to insert an address range to iova list.
1920  * The list is initially created with a single entry corresponding to
1921  * the IOMMU domain geometry to which the device group is attached.
1922  * The list aperture gets modified when a new domain is added to the
1923  * container if the new aperture doesn't conflict with the current one
1924  * or with any existing dma mappings. The list is also modified to
1925  * exclude any reserved regions associated with the device group.
1926  */
1927 static int vfio_iommu_iova_insert(struct list_head *head,
1928                                   dma_addr_t start, dma_addr_t end)
1929 {
1930         struct vfio_iova *region;
1931
1932         region = kmalloc(sizeof(*region), GFP_KERNEL);
1933         if (!region)
1934                 return -ENOMEM;
1935
1936         INIT_LIST_HEAD(&region->list);
1937         region->start = start;
1938         region->end = end;
1939
1940         list_add_tail(&region->list, head);
1941         return 0;
1942 }
1943
1944 /*
1945  * Check the new iommu aperture conflicts with existing aper or with any
1946  * existing dma mappings.
1947  */
1948 static bool vfio_iommu_aper_conflict(struct vfio_iommu *iommu,
1949                                      dma_addr_t start, dma_addr_t end)
1950 {
1951         struct vfio_iova *first, *last;
1952         struct list_head *iova = &iommu->iova_list;
1953
1954         if (list_empty(iova))
1955                 return false;
1956
1957         /* Disjoint sets, return conflict */
1958         first = list_first_entry(iova, struct vfio_iova, list);
1959         last = list_last_entry(iova, struct vfio_iova, list);
1960         if (start > last->end || end < first->start)
1961                 return true;
1962
1963         /* Check for any existing dma mappings below the new start */
1964         if (start > first->start) {
1965                 if (vfio_find_dma(iommu, first->start, start - first->start))
1966                         return true;
1967         }
1968
1969         /* Check for any existing dma mappings beyond the new end */
1970         if (end < last->end) {
1971                 if (vfio_find_dma(iommu, end + 1, last->end - end))
1972                         return true;
1973         }
1974
1975         return false;
1976 }
1977
1978 /*
1979  * Resize iommu iova aperture window. This is called only if the new
1980  * aperture has no conflict with existing aperture and dma mappings.
1981  */
1982 static int vfio_iommu_aper_resize(struct list_head *iova,
1983                                   dma_addr_t start, dma_addr_t end)
1984 {
1985         struct vfio_iova *node, *next;
1986
1987         if (list_empty(iova))
1988                 return vfio_iommu_iova_insert(iova, start, end);
1989
1990         /* Adjust iova list start */
1991         list_for_each_entry_safe(node, next, iova, list) {
1992                 if (start < node->start)
1993                         break;
1994                 if (start >= node->start && start < node->end) {
1995                         node->start = start;
1996                         break;
1997                 }
1998                 /* Delete nodes before new start */
1999                 list_del(&node->list);
2000                 kfree(node);
2001         }
2002
2003         /* Adjust iova list end */
2004         list_for_each_entry_safe(node, next, iova, list) {
2005                 if (end > node->end)
2006                         continue;
2007                 if (end > node->start && end <= node->end) {
2008                         node->end = end;
2009                         continue;
2010                 }
2011                 /* Delete nodes after new end */
2012                 list_del(&node->list);
2013                 kfree(node);
2014         }
2015
2016         return 0;
2017 }
2018
2019 /*
2020  * Check reserved region conflicts with existing dma mappings
2021  */
2022 static bool vfio_iommu_resv_conflict(struct vfio_iommu *iommu,
2023                                      struct list_head *resv_regions)
2024 {
2025         struct iommu_resv_region *region;
2026
2027         /* Check for conflict with existing dma mappings */
2028         list_for_each_entry(region, resv_regions, list) {
2029                 if (region->type == IOMMU_RESV_DIRECT_RELAXABLE)
2030                         continue;
2031
2032                 if (vfio_find_dma(iommu, region->start, region->length))
2033                         return true;
2034         }
2035
2036         return false;
2037 }
2038
2039 /*
2040  * Check iova region overlap with  reserved regions and
2041  * exclude them from the iommu iova range
2042  */
2043 static int vfio_iommu_resv_exclude(struct list_head *iova,
2044                                    struct list_head *resv_regions)
2045 {
2046         struct iommu_resv_region *resv;
2047         struct vfio_iova *n, *next;
2048
2049         list_for_each_entry(resv, resv_regions, list) {
2050                 phys_addr_t start, end;
2051
2052                 if (resv->type == IOMMU_RESV_DIRECT_RELAXABLE)
2053                         continue;
2054
2055                 start = resv->start;
2056                 end = resv->start + resv->length - 1;
2057
2058                 list_for_each_entry_safe(n, next, iova, list) {
2059                         int ret = 0;
2060
2061                         /* No overlap */
2062                         if (start > n->end || end < n->start)
2063                                 continue;
2064                         /*
2065                          * Insert a new node if current node overlaps with the
2066                          * reserve region to exclude that from valid iova range.
2067                          * Note that, new node is inserted before the current
2068                          * node and finally the current node is deleted keeping
2069                          * the list updated and sorted.
2070                          */
2071                         if (start > n->start)
2072                                 ret = vfio_iommu_iova_insert(&n->list, n->start,
2073                                                              start - 1);
2074                         if (!ret && end < n->end)
2075                                 ret = vfio_iommu_iova_insert(&n->list, end + 1,
2076                                                              n->end);
2077                         if (ret)
2078                                 return ret;
2079
2080                         list_del(&n->list);
2081                         kfree(n);
2082                 }
2083         }
2084
2085         if (list_empty(iova))
2086                 return -EINVAL;
2087
2088         return 0;
2089 }
2090
2091 static void vfio_iommu_resv_free(struct list_head *resv_regions)
2092 {
2093         struct iommu_resv_region *n, *next;
2094
2095         list_for_each_entry_safe(n, next, resv_regions, list) {
2096                 list_del(&n->list);
2097                 kfree(n);
2098         }
2099 }
2100
2101 static void vfio_iommu_iova_free(struct list_head *iova)
2102 {
2103         struct vfio_iova *n, *next;
2104
2105         list_for_each_entry_safe(n, next, iova, list) {
2106                 list_del(&n->list);
2107                 kfree(n);
2108         }
2109 }
2110
2111 static int vfio_iommu_iova_get_copy(struct vfio_iommu *iommu,
2112                                     struct list_head *iova_copy)
2113 {
2114         struct list_head *iova = &iommu->iova_list;
2115         struct vfio_iova *n;
2116         int ret;
2117
2118         list_for_each_entry(n, iova, list) {
2119                 ret = vfio_iommu_iova_insert(iova_copy, n->start, n->end);
2120                 if (ret)
2121                         goto out_free;
2122         }
2123
2124         return 0;
2125
2126 out_free:
2127         vfio_iommu_iova_free(iova_copy);
2128         return ret;
2129 }
2130
2131 static void vfio_iommu_iova_insert_copy(struct vfio_iommu *iommu,
2132                                         struct list_head *iova_copy)
2133 {
2134         struct list_head *iova = &iommu->iova_list;
2135
2136         vfio_iommu_iova_free(iova);
2137
2138         list_splice_tail(iova_copy, iova);
2139 }
2140
2141 static int vfio_iommu_domain_alloc(struct device *dev, void *data)
2142 {
2143         struct iommu_domain **domain = data;
2144
2145         *domain = iommu_domain_alloc(dev->bus);
2146         return 1; /* Don't iterate */
2147 }
2148
2149 static int vfio_iommu_type1_attach_group(void *iommu_data,
2150                 struct iommu_group *iommu_group, enum vfio_group_type type)
2151 {
2152         struct vfio_iommu *iommu = iommu_data;
2153         struct vfio_iommu_group *group;
2154         struct vfio_domain *domain, *d;
2155         bool resv_msi;
2156         phys_addr_t resv_msi_base = 0;
2157         struct iommu_domain_geometry *geo;
2158         LIST_HEAD(iova_copy);
2159         LIST_HEAD(group_resv_regions);
2160         int ret = -EBUSY;
2161
2162         mutex_lock(&iommu->lock);
2163
2164         /* Attach could require pinning, so disallow while vaddr is invalid. */
2165         if (iommu->vaddr_invalid_count)
2166                 goto out_unlock;
2167
2168         /* Check for duplicates */
2169         ret = -EINVAL;
2170         if (vfio_iommu_find_iommu_group(iommu, iommu_group))
2171                 goto out_unlock;
2172
2173         ret = -ENOMEM;
2174         group = kzalloc(sizeof(*group), GFP_KERNEL);
2175         if (!group)
2176                 goto out_unlock;
2177         group->iommu_group = iommu_group;
2178
2179         if (type == VFIO_EMULATED_IOMMU) {
2180                 list_add(&group->next, &iommu->emulated_iommu_groups);
2181                 /*
2182                  * An emulated IOMMU group cannot dirty memory directly, it can
2183                  * only use interfaces that provide dirty tracking.
2184                  * The iommu scope can only be promoted with the addition of a
2185                  * dirty tracking group.
2186                  */
2187                 group->pinned_page_dirty_scope = true;
2188                 ret = 0;
2189                 goto out_unlock;
2190         }
2191
2192         ret = -ENOMEM;
2193         domain = kzalloc(sizeof(*domain), GFP_KERNEL);
2194         if (!domain)
2195                 goto out_free_group;
2196
2197         /*
2198          * Going via the iommu_group iterator avoids races, and trivially gives
2199          * us a representative device for the IOMMU API call. We don't actually
2200          * want to iterate beyond the first device (if any).
2201          */
2202         ret = -EIO;
2203         iommu_group_for_each_dev(iommu_group, &domain->domain,
2204                                  vfio_iommu_domain_alloc);
2205         if (!domain->domain)
2206                 goto out_free_domain;
2207
2208         if (iommu->nesting) {
2209                 ret = iommu_enable_nesting(domain->domain);
2210                 if (ret)
2211                         goto out_domain;
2212         }
2213
2214         ret = iommu_attach_group(domain->domain, group->iommu_group);
2215         if (ret)
2216                 goto out_domain;
2217
2218         /* Get aperture info */
2219         geo = &domain->domain->geometry;
2220         if (vfio_iommu_aper_conflict(iommu, geo->aperture_start,
2221                                      geo->aperture_end)) {
2222                 ret = -EINVAL;
2223                 goto out_detach;
2224         }
2225
2226         ret = iommu_get_group_resv_regions(iommu_group, &group_resv_regions);
2227         if (ret)
2228                 goto out_detach;
2229
2230         if (vfio_iommu_resv_conflict(iommu, &group_resv_regions)) {
2231                 ret = -EINVAL;
2232                 goto out_detach;
2233         }
2234
2235         /*
2236          * We don't want to work on the original iova list as the list
2237          * gets modified and in case of failure we have to retain the
2238          * original list. Get a copy here.
2239          */
2240         ret = vfio_iommu_iova_get_copy(iommu, &iova_copy);
2241         if (ret)
2242                 goto out_detach;
2243
2244         ret = vfio_iommu_aper_resize(&iova_copy, geo->aperture_start,
2245                                      geo->aperture_end);
2246         if (ret)
2247                 goto out_detach;
2248
2249         ret = vfio_iommu_resv_exclude(&iova_copy, &group_resv_regions);
2250         if (ret)
2251                 goto out_detach;
2252
2253         resv_msi = vfio_iommu_has_sw_msi(&group_resv_regions, &resv_msi_base);
2254
2255         INIT_LIST_HEAD(&domain->group_list);
2256         list_add(&group->next, &domain->group_list);
2257
2258         if (!allow_unsafe_interrupts &&
2259             !iommu_group_has_isolated_msi(iommu_group)) {
2260                 pr_warn("%s: No interrupt remapping support.  Use the module param \"allow_unsafe_interrupts\" to enable VFIO IOMMU support on this platform\n",
2261                        __func__);
2262                 ret = -EPERM;
2263                 goto out_detach;
2264         }
2265
2266         /*
2267          * If the IOMMU can block non-coherent operations (ie PCIe TLPs with
2268          * no-snoop set) then VFIO always turns this feature on because on Intel
2269          * platforms it optimizes KVM to disable wbinvd emulation.
2270          */
2271         if (domain->domain->ops->enforce_cache_coherency)
2272                 domain->enforce_cache_coherency =
2273                         domain->domain->ops->enforce_cache_coherency(
2274                                 domain->domain);
2275
2276         /*
2277          * Try to match an existing compatible domain.  We don't want to
2278          * preclude an IOMMU driver supporting multiple bus_types and being
2279          * able to include different bus_types in the same IOMMU domain, so
2280          * we test whether the domains use the same iommu_ops rather than
2281          * testing if they're on the same bus_type.
2282          */
2283         list_for_each_entry(d, &iommu->domain_list, next) {
2284                 if (d->domain->ops == domain->domain->ops &&
2285                     d->enforce_cache_coherency ==
2286                             domain->enforce_cache_coherency) {
2287                         iommu_detach_group(domain->domain, group->iommu_group);
2288                         if (!iommu_attach_group(d->domain,
2289                                                 group->iommu_group)) {
2290                                 list_add(&group->next, &d->group_list);
2291                                 iommu_domain_free(domain->domain);
2292                                 kfree(domain);
2293                                 goto done;
2294                         }
2295
2296                         ret = iommu_attach_group(domain->domain,
2297                                                  group->iommu_group);
2298                         if (ret)
2299                                 goto out_domain;
2300                 }
2301         }
2302
2303         vfio_test_domain_fgsp(domain, &iova_copy);
2304
2305         /* replay mappings on new domains */
2306         ret = vfio_iommu_replay(iommu, domain);
2307         if (ret)
2308                 goto out_detach;
2309
2310         if (resv_msi) {
2311                 ret = iommu_get_msi_cookie(domain->domain, resv_msi_base);
2312                 if (ret && ret != -ENODEV)
2313                         goto out_detach;
2314         }
2315
2316         list_add(&domain->next, &iommu->domain_list);
2317         vfio_update_pgsize_bitmap(iommu);
2318 done:
2319         /* Delete the old one and insert new iova list */
2320         vfio_iommu_iova_insert_copy(iommu, &iova_copy);
2321
2322         /*
2323          * An iommu backed group can dirty memory directly and therefore
2324          * demotes the iommu scope until it declares itself dirty tracking
2325          * capable via the page pinning interface.
2326          */
2327         iommu->num_non_pinned_groups++;
2328         mutex_unlock(&iommu->lock);
2329         vfio_iommu_resv_free(&group_resv_regions);
2330
2331         return 0;
2332
2333 out_detach:
2334         iommu_detach_group(domain->domain, group->iommu_group);
2335 out_domain:
2336         iommu_domain_free(domain->domain);
2337         vfio_iommu_iova_free(&iova_copy);
2338         vfio_iommu_resv_free(&group_resv_regions);
2339 out_free_domain:
2340         kfree(domain);
2341 out_free_group:
2342         kfree(group);
2343 out_unlock:
2344         mutex_unlock(&iommu->lock);
2345         return ret;
2346 }
2347
2348 static void vfio_iommu_unmap_unpin_all(struct vfio_iommu *iommu)
2349 {
2350         struct rb_node *node;
2351
2352         while ((node = rb_first(&iommu->dma_list)))
2353                 vfio_remove_dma(iommu, rb_entry(node, struct vfio_dma, node));
2354 }
2355
2356 static void vfio_iommu_unmap_unpin_reaccount(struct vfio_iommu *iommu)
2357 {
2358         struct rb_node *n, *p;
2359
2360         n = rb_first(&iommu->dma_list);
2361         for (; n; n = rb_next(n)) {
2362                 struct vfio_dma *dma;
2363                 long locked = 0, unlocked = 0;
2364
2365                 dma = rb_entry(n, struct vfio_dma, node);
2366                 unlocked += vfio_unmap_unpin(iommu, dma, false);
2367                 p = rb_first(&dma->pfn_list);
2368                 for (; p; p = rb_next(p)) {
2369                         struct vfio_pfn *vpfn = rb_entry(p, struct vfio_pfn,
2370                                                          node);
2371
2372                         if (!is_invalid_reserved_pfn(vpfn->pfn))
2373                                 locked++;
2374                 }
2375                 vfio_lock_acct(dma, locked - unlocked, true);
2376         }
2377 }
2378
2379 /*
2380  * Called when a domain is removed in detach. It is possible that
2381  * the removed domain decided the iova aperture window. Modify the
2382  * iova aperture with the smallest window among existing domains.
2383  */
2384 static void vfio_iommu_aper_expand(struct vfio_iommu *iommu,
2385                                    struct list_head *iova_copy)
2386 {
2387         struct vfio_domain *domain;
2388         struct vfio_iova *node;
2389         dma_addr_t start = 0;
2390         dma_addr_t end = (dma_addr_t)~0;
2391
2392         if (list_empty(iova_copy))
2393                 return;
2394
2395         list_for_each_entry(domain, &iommu->domain_list, next) {
2396                 struct iommu_domain_geometry *geo = &domain->domain->geometry;
2397
2398                 if (geo->aperture_start > start)
2399                         start = geo->aperture_start;
2400                 if (geo->aperture_end < end)
2401                         end = geo->aperture_end;
2402         }
2403
2404         /* Modify aperture limits. The new aper is either same or bigger */
2405         node = list_first_entry(iova_copy, struct vfio_iova, list);
2406         node->start = start;
2407         node = list_last_entry(iova_copy, struct vfio_iova, list);
2408         node->end = end;
2409 }
2410
2411 /*
2412  * Called when a group is detached. The reserved regions for that
2413  * group can be part of valid iova now. But since reserved regions
2414  * may be duplicated among groups, populate the iova valid regions
2415  * list again.
2416  */
2417 static int vfio_iommu_resv_refresh(struct vfio_iommu *iommu,
2418                                    struct list_head *iova_copy)
2419 {
2420         struct vfio_domain *d;
2421         struct vfio_iommu_group *g;
2422         struct vfio_iova *node;
2423         dma_addr_t start, end;
2424         LIST_HEAD(resv_regions);
2425         int ret;
2426
2427         if (list_empty(iova_copy))
2428                 return -EINVAL;
2429
2430         list_for_each_entry(d, &iommu->domain_list, next) {
2431                 list_for_each_entry(g, &d->group_list, next) {
2432                         ret = iommu_get_group_resv_regions(g->iommu_group,
2433                                                            &resv_regions);
2434                         if (ret)
2435                                 goto done;
2436                 }
2437         }
2438
2439         node = list_first_entry(iova_copy, struct vfio_iova, list);
2440         start = node->start;
2441         node = list_last_entry(iova_copy, struct vfio_iova, list);
2442         end = node->end;
2443
2444         /* purge the iova list and create new one */
2445         vfio_iommu_iova_free(iova_copy);
2446
2447         ret = vfio_iommu_aper_resize(iova_copy, start, end);
2448         if (ret)
2449                 goto done;
2450
2451         /* Exclude current reserved regions from iova ranges */
2452         ret = vfio_iommu_resv_exclude(iova_copy, &resv_regions);
2453 done:
2454         vfio_iommu_resv_free(&resv_regions);
2455         return ret;
2456 }
2457
2458 static void vfio_iommu_type1_detach_group(void *iommu_data,
2459                                           struct iommu_group *iommu_group)
2460 {
2461         struct vfio_iommu *iommu = iommu_data;
2462         struct vfio_domain *domain;
2463         struct vfio_iommu_group *group;
2464         bool update_dirty_scope = false;
2465         LIST_HEAD(iova_copy);
2466
2467         mutex_lock(&iommu->lock);
2468         list_for_each_entry(group, &iommu->emulated_iommu_groups, next) {
2469                 if (group->iommu_group != iommu_group)
2470                         continue;
2471                 update_dirty_scope = !group->pinned_page_dirty_scope;
2472                 list_del(&group->next);
2473                 kfree(group);
2474
2475                 if (list_empty(&iommu->emulated_iommu_groups) &&
2476                     list_empty(&iommu->domain_list)) {
2477                         WARN_ON(!list_empty(&iommu->device_list));
2478                         vfio_iommu_unmap_unpin_all(iommu);
2479                 }
2480                 goto detach_group_done;
2481         }
2482
2483         /*
2484          * Get a copy of iova list. This will be used to update
2485          * and to replace the current one later. Please note that
2486          * we will leave the original list as it is if update fails.
2487          */
2488         vfio_iommu_iova_get_copy(iommu, &iova_copy);
2489
2490         list_for_each_entry(domain, &iommu->domain_list, next) {
2491                 group = find_iommu_group(domain, iommu_group);
2492                 if (!group)
2493                         continue;
2494
2495                 iommu_detach_group(domain->domain, group->iommu_group);
2496                 update_dirty_scope = !group->pinned_page_dirty_scope;
2497                 list_del(&group->next);
2498                 kfree(group);
2499                 /*
2500                  * Group ownership provides privilege, if the group list is
2501                  * empty, the domain goes away. If it's the last domain with
2502                  * iommu and external domain doesn't exist, then all the
2503                  * mappings go away too. If it's the last domain with iommu and
2504                  * external domain exist, update accounting
2505                  */
2506                 if (list_empty(&domain->group_list)) {
2507                         if (list_is_singular(&iommu->domain_list)) {
2508                                 if (list_empty(&iommu->emulated_iommu_groups)) {
2509                                         WARN_ON(!list_empty(
2510                                                 &iommu->device_list));
2511                                         vfio_iommu_unmap_unpin_all(iommu);
2512                                 } else {
2513                                         vfio_iommu_unmap_unpin_reaccount(iommu);
2514                                 }
2515                         }
2516                         iommu_domain_free(domain->domain);
2517                         list_del(&domain->next);
2518                         kfree(domain);
2519                         vfio_iommu_aper_expand(iommu, &iova_copy);
2520                         vfio_update_pgsize_bitmap(iommu);
2521                 }
2522                 break;
2523         }
2524
2525         if (!vfio_iommu_resv_refresh(iommu, &iova_copy))
2526                 vfio_iommu_iova_insert_copy(iommu, &iova_copy);
2527         else
2528                 vfio_iommu_iova_free(&iova_copy);
2529
2530 detach_group_done:
2531         /*
2532          * Removal of a group without dirty tracking may allow the iommu scope
2533          * to be promoted.
2534          */
2535         if (update_dirty_scope) {
2536                 iommu->num_non_pinned_groups--;
2537                 if (iommu->dirty_page_tracking)
2538                         vfio_iommu_populate_bitmap_full(iommu);
2539         }
2540         mutex_unlock(&iommu->lock);
2541 }
2542
2543 static void *vfio_iommu_type1_open(unsigned long arg)
2544 {
2545         struct vfio_iommu *iommu;
2546
2547         iommu = kzalloc(sizeof(*iommu), GFP_KERNEL);
2548         if (!iommu)
2549                 return ERR_PTR(-ENOMEM);
2550
2551         switch (arg) {
2552         case VFIO_TYPE1_IOMMU:
2553                 break;
2554         case VFIO_TYPE1_NESTING_IOMMU:
2555                 iommu->nesting = true;
2556                 fallthrough;
2557         case VFIO_TYPE1v2_IOMMU:
2558                 iommu->v2 = true;
2559                 break;
2560         default:
2561                 kfree(iommu);
2562                 return ERR_PTR(-EINVAL);
2563         }
2564
2565         INIT_LIST_HEAD(&iommu->domain_list);
2566         INIT_LIST_HEAD(&iommu->iova_list);
2567         iommu->dma_list = RB_ROOT;
2568         iommu->dma_avail = dma_entry_limit;
2569         mutex_init(&iommu->lock);
2570         mutex_init(&iommu->device_list_lock);
2571         INIT_LIST_HEAD(&iommu->device_list);
2572         iommu->pgsize_bitmap = PAGE_MASK;
2573         INIT_LIST_HEAD(&iommu->emulated_iommu_groups);
2574
2575         return iommu;
2576 }
2577
2578 static void vfio_release_domain(struct vfio_domain *domain)
2579 {
2580         struct vfio_iommu_group *group, *group_tmp;
2581
2582         list_for_each_entry_safe(group, group_tmp,
2583                                  &domain->group_list, next) {
2584                 iommu_detach_group(domain->domain, group->iommu_group);
2585                 list_del(&group->next);
2586                 kfree(group);
2587         }
2588
2589         iommu_domain_free(domain->domain);
2590 }
2591
2592 static void vfio_iommu_type1_release(void *iommu_data)
2593 {
2594         struct vfio_iommu *iommu = iommu_data;
2595         struct vfio_domain *domain, *domain_tmp;
2596         struct vfio_iommu_group *group, *next_group;
2597
2598         list_for_each_entry_safe(group, next_group,
2599                         &iommu->emulated_iommu_groups, next) {
2600                 list_del(&group->next);
2601                 kfree(group);
2602         }
2603
2604         vfio_iommu_unmap_unpin_all(iommu);
2605
2606         list_for_each_entry_safe(domain, domain_tmp,
2607                                  &iommu->domain_list, next) {
2608                 vfio_release_domain(domain);
2609                 list_del(&domain->next);
2610                 kfree(domain);
2611         }
2612
2613         vfio_iommu_iova_free(&iommu->iova_list);
2614
2615         kfree(iommu);
2616 }
2617
2618 static int vfio_domains_have_enforce_cache_coherency(struct vfio_iommu *iommu)
2619 {
2620         struct vfio_domain *domain;
2621         int ret = 1;
2622
2623         mutex_lock(&iommu->lock);
2624         list_for_each_entry(domain, &iommu->domain_list, next) {
2625                 if (!(domain->enforce_cache_coherency)) {
2626                         ret = 0;
2627                         break;
2628                 }
2629         }
2630         mutex_unlock(&iommu->lock);
2631
2632         return ret;
2633 }
2634
2635 static bool vfio_iommu_has_emulated(struct vfio_iommu *iommu)
2636 {
2637         bool ret;
2638
2639         mutex_lock(&iommu->lock);
2640         ret = !list_empty(&iommu->emulated_iommu_groups);
2641         mutex_unlock(&iommu->lock);
2642         return ret;
2643 }
2644
2645 static int vfio_iommu_type1_check_extension(struct vfio_iommu *iommu,
2646                                             unsigned long arg)
2647 {
2648         switch (arg) {
2649         case VFIO_TYPE1_IOMMU:
2650         case VFIO_TYPE1v2_IOMMU:
2651         case VFIO_TYPE1_NESTING_IOMMU:
2652         case VFIO_UNMAP_ALL:
2653                 return 1;
2654         case VFIO_UPDATE_VADDR:
2655                 /*
2656                  * Disable this feature if mdevs are present.  They cannot
2657                  * safely pin/unpin/rw while vaddrs are being updated.
2658                  */
2659                 return iommu && !vfio_iommu_has_emulated(iommu);
2660         case VFIO_DMA_CC_IOMMU:
2661                 if (!iommu)
2662                         return 0;
2663                 return vfio_domains_have_enforce_cache_coherency(iommu);
2664         default:
2665                 return 0;
2666         }
2667 }
2668
2669 static int vfio_iommu_iova_add_cap(struct vfio_info_cap *caps,
2670                  struct vfio_iommu_type1_info_cap_iova_range *cap_iovas,
2671                  size_t size)
2672 {
2673         struct vfio_info_cap_header *header;
2674         struct vfio_iommu_type1_info_cap_iova_range *iova_cap;
2675
2676         header = vfio_info_cap_add(caps, size,
2677                                    VFIO_IOMMU_TYPE1_INFO_CAP_IOVA_RANGE, 1);
2678         if (IS_ERR(header))
2679                 return PTR_ERR(header);
2680
2681         iova_cap = container_of(header,
2682                                 struct vfio_iommu_type1_info_cap_iova_range,
2683                                 header);
2684         iova_cap->nr_iovas = cap_iovas->nr_iovas;
2685         memcpy(iova_cap->iova_ranges, cap_iovas->iova_ranges,
2686                cap_iovas->nr_iovas * sizeof(*cap_iovas->iova_ranges));
2687         return 0;
2688 }
2689
2690 static int vfio_iommu_iova_build_caps(struct vfio_iommu *iommu,
2691                                       struct vfio_info_cap *caps)
2692 {
2693         struct vfio_iommu_type1_info_cap_iova_range *cap_iovas;
2694         struct vfio_iova *iova;
2695         size_t size;
2696         int iovas = 0, i = 0, ret;
2697
2698         list_for_each_entry(iova, &iommu->iova_list, list)
2699                 iovas++;
2700
2701         if (!iovas) {
2702                 /*
2703                  * Return 0 as a container with a single mdev device
2704                  * will have an empty list
2705                  */
2706                 return 0;
2707         }
2708
2709         size = struct_size(cap_iovas, iova_ranges, iovas);
2710
2711         cap_iovas = kzalloc(size, GFP_KERNEL);
2712         if (!cap_iovas)
2713                 return -ENOMEM;
2714
2715         cap_iovas->nr_iovas = iovas;
2716
2717         list_for_each_entry(iova, &iommu->iova_list, list) {
2718                 cap_iovas->iova_ranges[i].start = iova->start;
2719                 cap_iovas->iova_ranges[i].end = iova->end;
2720                 i++;
2721         }
2722
2723         ret = vfio_iommu_iova_add_cap(caps, cap_iovas, size);
2724
2725         kfree(cap_iovas);
2726         return ret;
2727 }
2728
2729 static int vfio_iommu_migration_build_caps(struct vfio_iommu *iommu,
2730                                            struct vfio_info_cap *caps)
2731 {
2732         struct vfio_iommu_type1_info_cap_migration cap_mig;
2733
2734         cap_mig.header.id = VFIO_IOMMU_TYPE1_INFO_CAP_MIGRATION;
2735         cap_mig.header.version = 1;
2736
2737         cap_mig.flags = 0;
2738         /* support minimum pgsize */
2739         cap_mig.pgsize_bitmap = (size_t)1 << __ffs(iommu->pgsize_bitmap);
2740         cap_mig.max_dirty_bitmap_size = DIRTY_BITMAP_SIZE_MAX;
2741
2742         return vfio_info_add_capability(caps, &cap_mig.header, sizeof(cap_mig));
2743 }
2744
2745 static int vfio_iommu_dma_avail_build_caps(struct vfio_iommu *iommu,
2746                                            struct vfio_info_cap *caps)
2747 {
2748         struct vfio_iommu_type1_info_dma_avail cap_dma_avail;
2749
2750         cap_dma_avail.header.id = VFIO_IOMMU_TYPE1_INFO_DMA_AVAIL;
2751         cap_dma_avail.header.version = 1;
2752
2753         cap_dma_avail.avail = iommu->dma_avail;
2754
2755         return vfio_info_add_capability(caps, &cap_dma_avail.header,
2756                                         sizeof(cap_dma_avail));
2757 }
2758
2759 static int vfio_iommu_type1_get_info(struct vfio_iommu *iommu,
2760                                      unsigned long arg)
2761 {
2762         struct vfio_iommu_type1_info info;
2763         unsigned long minsz;
2764         struct vfio_info_cap caps = { .buf = NULL, .size = 0 };
2765         unsigned long capsz;
2766         int ret;
2767
2768         minsz = offsetofend(struct vfio_iommu_type1_info, iova_pgsizes);
2769
2770         /* For backward compatibility, cannot require this */
2771         capsz = offsetofend(struct vfio_iommu_type1_info, cap_offset);
2772
2773         if (copy_from_user(&info, (void __user *)arg, minsz))
2774                 return -EFAULT;
2775
2776         if (info.argsz < minsz)
2777                 return -EINVAL;
2778
2779         if (info.argsz >= capsz) {
2780                 minsz = capsz;
2781                 info.cap_offset = 0; /* output, no-recopy necessary */
2782         }
2783
2784         mutex_lock(&iommu->lock);
2785         info.flags = VFIO_IOMMU_INFO_PGSIZES;
2786
2787         info.iova_pgsizes = iommu->pgsize_bitmap;
2788
2789         ret = vfio_iommu_migration_build_caps(iommu, &caps);
2790
2791         if (!ret)
2792                 ret = vfio_iommu_dma_avail_build_caps(iommu, &caps);
2793
2794         if (!ret)
2795                 ret = vfio_iommu_iova_build_caps(iommu, &caps);
2796
2797         mutex_unlock(&iommu->lock);
2798
2799         if (ret)
2800                 return ret;
2801
2802         if (caps.size) {
2803                 info.flags |= VFIO_IOMMU_INFO_CAPS;
2804
2805                 if (info.argsz < sizeof(info) + caps.size) {
2806                         info.argsz = sizeof(info) + caps.size;
2807                 } else {
2808                         vfio_info_cap_shift(&caps, sizeof(info));
2809                         if (copy_to_user((void __user *)arg +
2810                                         sizeof(info), caps.buf,
2811                                         caps.size)) {
2812                                 kfree(caps.buf);
2813                                 return -EFAULT;
2814                         }
2815                         info.cap_offset = sizeof(info);
2816                 }
2817
2818                 kfree(caps.buf);
2819         }
2820
2821         return copy_to_user((void __user *)arg, &info, minsz) ?
2822                         -EFAULT : 0;
2823 }
2824
2825 static int vfio_iommu_type1_map_dma(struct vfio_iommu *iommu,
2826                                     unsigned long arg)
2827 {
2828         struct vfio_iommu_type1_dma_map map;
2829         unsigned long minsz;
2830         uint32_t mask = VFIO_DMA_MAP_FLAG_READ | VFIO_DMA_MAP_FLAG_WRITE |
2831                         VFIO_DMA_MAP_FLAG_VADDR;
2832
2833         minsz = offsetofend(struct vfio_iommu_type1_dma_map, size);
2834
2835         if (copy_from_user(&map, (void __user *)arg, minsz))
2836                 return -EFAULT;
2837
2838         if (map.argsz < minsz || map.flags & ~mask)
2839                 return -EINVAL;
2840
2841         return vfio_dma_do_map(iommu, &map);
2842 }
2843
2844 static int vfio_iommu_type1_unmap_dma(struct vfio_iommu *iommu,
2845                                       unsigned long arg)
2846 {
2847         struct vfio_iommu_type1_dma_unmap unmap;
2848         struct vfio_bitmap bitmap = { 0 };
2849         uint32_t mask = VFIO_DMA_UNMAP_FLAG_GET_DIRTY_BITMAP |
2850                         VFIO_DMA_UNMAP_FLAG_VADDR |
2851                         VFIO_DMA_UNMAP_FLAG_ALL;
2852         unsigned long minsz;
2853         int ret;
2854
2855         minsz = offsetofend(struct vfio_iommu_type1_dma_unmap, size);
2856
2857         if (copy_from_user(&unmap, (void __user *)arg, minsz))
2858                 return -EFAULT;
2859
2860         if (unmap.argsz < minsz || unmap.flags & ~mask)
2861                 return -EINVAL;
2862
2863         if ((unmap.flags & VFIO_DMA_UNMAP_FLAG_GET_DIRTY_BITMAP) &&
2864             (unmap.flags & (VFIO_DMA_UNMAP_FLAG_ALL |
2865                             VFIO_DMA_UNMAP_FLAG_VADDR)))
2866                 return -EINVAL;
2867
2868         if (unmap.flags & VFIO_DMA_UNMAP_FLAG_GET_DIRTY_BITMAP) {
2869                 unsigned long pgshift;
2870
2871                 if (unmap.argsz < (minsz + sizeof(bitmap)))
2872                         return -EINVAL;
2873
2874                 if (copy_from_user(&bitmap,
2875                                    (void __user *)(arg + minsz),
2876                                    sizeof(bitmap)))
2877                         return -EFAULT;
2878
2879                 if (!access_ok((void __user *)bitmap.data, bitmap.size))
2880                         return -EINVAL;
2881
2882                 pgshift = __ffs(bitmap.pgsize);
2883                 ret = verify_bitmap_size(unmap.size >> pgshift,
2884                                          bitmap.size);
2885                 if (ret)
2886                         return ret;
2887         }
2888
2889         ret = vfio_dma_do_unmap(iommu, &unmap, &bitmap);
2890         if (ret)
2891                 return ret;
2892
2893         return copy_to_user((void __user *)arg, &unmap, minsz) ?
2894                         -EFAULT : 0;
2895 }
2896
2897 static int vfio_iommu_type1_dirty_pages(struct vfio_iommu *iommu,
2898                                         unsigned long arg)
2899 {
2900         struct vfio_iommu_type1_dirty_bitmap dirty;
2901         uint32_t mask = VFIO_IOMMU_DIRTY_PAGES_FLAG_START |
2902                         VFIO_IOMMU_DIRTY_PAGES_FLAG_STOP |
2903                         VFIO_IOMMU_DIRTY_PAGES_FLAG_GET_BITMAP;
2904         unsigned long minsz;
2905         int ret = 0;
2906
2907         if (!iommu->v2)
2908                 return -EACCES;
2909
2910         minsz = offsetofend(struct vfio_iommu_type1_dirty_bitmap, flags);
2911
2912         if (copy_from_user(&dirty, (void __user *)arg, minsz))
2913                 return -EFAULT;
2914
2915         if (dirty.argsz < minsz || dirty.flags & ~mask)
2916                 return -EINVAL;
2917
2918         /* only one flag should be set at a time */
2919         if (__ffs(dirty.flags) != __fls(dirty.flags))
2920                 return -EINVAL;
2921
2922         if (dirty.flags & VFIO_IOMMU_DIRTY_PAGES_FLAG_START) {
2923                 size_t pgsize;
2924
2925                 mutex_lock(&iommu->lock);
2926                 pgsize = 1 << __ffs(iommu->pgsize_bitmap);
2927                 if (!iommu->dirty_page_tracking) {
2928                         ret = vfio_dma_bitmap_alloc_all(iommu, pgsize);
2929                         if (!ret)
2930                                 iommu->dirty_page_tracking = true;
2931                 }
2932                 mutex_unlock(&iommu->lock);
2933                 return ret;
2934         } else if (dirty.flags & VFIO_IOMMU_DIRTY_PAGES_FLAG_STOP) {
2935                 mutex_lock(&iommu->lock);
2936                 if (iommu->dirty_page_tracking) {
2937                         iommu->dirty_page_tracking = false;
2938                         vfio_dma_bitmap_free_all(iommu);
2939                 }
2940                 mutex_unlock(&iommu->lock);
2941                 return 0;
2942         } else if (dirty.flags & VFIO_IOMMU_DIRTY_PAGES_FLAG_GET_BITMAP) {
2943                 struct vfio_iommu_type1_dirty_bitmap_get range;
2944                 unsigned long pgshift;
2945                 size_t data_size = dirty.argsz - minsz;
2946                 size_t iommu_pgsize;
2947
2948                 if (!data_size || data_size < sizeof(range))
2949                         return -EINVAL;
2950
2951                 if (copy_from_user(&range, (void __user *)(arg + minsz),
2952                                    sizeof(range)))
2953                         return -EFAULT;
2954
2955                 if (range.iova + range.size < range.iova)
2956                         return -EINVAL;
2957                 if (!access_ok((void __user *)range.bitmap.data,
2958                                range.bitmap.size))
2959                         return -EINVAL;
2960
2961                 pgshift = __ffs(range.bitmap.pgsize);
2962                 ret = verify_bitmap_size(range.size >> pgshift,
2963                                          range.bitmap.size);
2964                 if (ret)
2965                         return ret;
2966
2967                 mutex_lock(&iommu->lock);
2968
2969                 iommu_pgsize = (size_t)1 << __ffs(iommu->pgsize_bitmap);
2970
2971                 /* allow only smallest supported pgsize */
2972                 if (range.bitmap.pgsize != iommu_pgsize) {
2973                         ret = -EINVAL;
2974                         goto out_unlock;
2975                 }
2976                 if (range.iova & (iommu_pgsize - 1)) {
2977                         ret = -EINVAL;
2978                         goto out_unlock;
2979                 }
2980                 if (!range.size || range.size & (iommu_pgsize - 1)) {
2981                         ret = -EINVAL;
2982                         goto out_unlock;
2983                 }
2984
2985                 if (iommu->dirty_page_tracking)
2986                         ret = vfio_iova_dirty_bitmap(range.bitmap.data,
2987                                                      iommu, range.iova,
2988                                                      range.size,
2989                                                      range.bitmap.pgsize);
2990                 else
2991                         ret = -EINVAL;
2992 out_unlock:
2993                 mutex_unlock(&iommu->lock);
2994
2995                 return ret;
2996         }
2997
2998         return -EINVAL;
2999 }
3000
3001 static long vfio_iommu_type1_ioctl(void *iommu_data,
3002                                    unsigned int cmd, unsigned long arg)
3003 {
3004         struct vfio_iommu *iommu = iommu_data;
3005
3006         switch (cmd) {
3007         case VFIO_CHECK_EXTENSION:
3008                 return vfio_iommu_type1_check_extension(iommu, arg);
3009         case VFIO_IOMMU_GET_INFO:
3010                 return vfio_iommu_type1_get_info(iommu, arg);
3011         case VFIO_IOMMU_MAP_DMA:
3012                 return vfio_iommu_type1_map_dma(iommu, arg);
3013         case VFIO_IOMMU_UNMAP_DMA:
3014                 return vfio_iommu_type1_unmap_dma(iommu, arg);
3015         case VFIO_IOMMU_DIRTY_PAGES:
3016                 return vfio_iommu_type1_dirty_pages(iommu, arg);
3017         default:
3018                 return -ENOTTY;
3019         }
3020 }
3021
3022 static void vfio_iommu_type1_register_device(void *iommu_data,
3023                                              struct vfio_device *vdev)
3024 {
3025         struct vfio_iommu *iommu = iommu_data;
3026
3027         if (!vdev->ops->dma_unmap)
3028                 return;
3029
3030         /*
3031          * list_empty(&iommu->device_list) is tested under the iommu->lock while
3032          * iteration for dma_unmap must be done under the device_list_lock.
3033          * Holding both locks here allows avoiding the device_list_lock in
3034          * several fast paths. See vfio_notify_dma_unmap()
3035          */
3036         mutex_lock(&iommu->lock);
3037         mutex_lock(&iommu->device_list_lock);
3038         list_add(&vdev->iommu_entry, &iommu->device_list);
3039         mutex_unlock(&iommu->device_list_lock);
3040         mutex_unlock(&iommu->lock);
3041 }
3042
3043 static void vfio_iommu_type1_unregister_device(void *iommu_data,
3044                                                struct vfio_device *vdev)
3045 {
3046         struct vfio_iommu *iommu = iommu_data;
3047
3048         if (!vdev->ops->dma_unmap)
3049                 return;
3050
3051         mutex_lock(&iommu->lock);
3052         mutex_lock(&iommu->device_list_lock);
3053         list_del(&vdev->iommu_entry);
3054         mutex_unlock(&iommu->device_list_lock);
3055         mutex_unlock(&iommu->lock);
3056 }
3057
3058 static int vfio_iommu_type1_dma_rw_chunk(struct vfio_iommu *iommu,
3059                                          dma_addr_t user_iova, void *data,
3060                                          size_t count, bool write,
3061                                          size_t *copied)
3062 {
3063         struct mm_struct *mm;
3064         unsigned long vaddr;
3065         struct vfio_dma *dma;
3066         bool kthread = current->mm == NULL;
3067         size_t offset;
3068
3069         *copied = 0;
3070
3071         dma = vfio_find_dma(iommu, user_iova, 1);
3072         if (!dma)
3073                 return -EINVAL;
3074
3075         if ((write && !(dma->prot & IOMMU_WRITE)) ||
3076                         !(dma->prot & IOMMU_READ))
3077                 return -EPERM;
3078
3079         mm = dma->mm;
3080         if (!mmget_not_zero(mm))
3081                 return -EPERM;
3082
3083         if (kthread)
3084                 kthread_use_mm(mm);
3085         else if (current->mm != mm)
3086                 goto out;
3087
3088         offset = user_iova - dma->iova;
3089
3090         if (count > dma->size - offset)
3091                 count = dma->size - offset;
3092
3093         vaddr = dma->vaddr + offset;
3094
3095         if (write) {
3096                 *copied = copy_to_user((void __user *)vaddr, data,
3097                                          count) ? 0 : count;
3098                 if (*copied && iommu->dirty_page_tracking) {
3099                         unsigned long pgshift = __ffs(iommu->pgsize_bitmap);
3100                         /*
3101                          * Bitmap populated with the smallest supported page
3102                          * size
3103                          */
3104                         bitmap_set(dma->bitmap, offset >> pgshift,
3105                                    ((offset + *copied - 1) >> pgshift) -
3106                                    (offset >> pgshift) + 1);
3107                 }
3108         } else
3109                 *copied = copy_from_user(data, (void __user *)vaddr,
3110                                            count) ? 0 : count;
3111         if (kthread)
3112                 kthread_unuse_mm(mm);
3113 out:
3114         mmput(mm);
3115         return *copied ? 0 : -EFAULT;
3116 }
3117
3118 static int vfio_iommu_type1_dma_rw(void *iommu_data, dma_addr_t user_iova,
3119                                    void *data, size_t count, bool write)
3120 {
3121         struct vfio_iommu *iommu = iommu_data;
3122         int ret = 0;
3123         size_t done;
3124
3125         mutex_lock(&iommu->lock);
3126
3127         if (WARN_ONCE(iommu->vaddr_invalid_count,
3128                       "vfio_dma_rw not allowed with VFIO_UPDATE_VADDR\n")) {
3129                 ret = -EBUSY;
3130                 goto out;
3131         }
3132
3133         while (count > 0) {
3134                 ret = vfio_iommu_type1_dma_rw_chunk(iommu, user_iova, data,
3135                                                     count, write, &done);
3136                 if (ret)
3137                         break;
3138
3139                 count -= done;
3140                 data += done;
3141                 user_iova += done;
3142         }
3143
3144 out:
3145         mutex_unlock(&iommu->lock);
3146         return ret;
3147 }
3148
3149 static struct iommu_domain *
3150 vfio_iommu_type1_group_iommu_domain(void *iommu_data,
3151                                     struct iommu_group *iommu_group)
3152 {
3153         struct iommu_domain *domain = ERR_PTR(-ENODEV);
3154         struct vfio_iommu *iommu = iommu_data;
3155         struct vfio_domain *d;
3156
3157         if (!iommu || !iommu_group)
3158                 return ERR_PTR(-EINVAL);
3159
3160         mutex_lock(&iommu->lock);
3161         list_for_each_entry(d, &iommu->domain_list, next) {
3162                 if (find_iommu_group(d, iommu_group)) {
3163                         domain = d->domain;
3164                         break;
3165                 }
3166         }
3167         mutex_unlock(&iommu->lock);
3168
3169         return domain;
3170 }
3171
3172 static const struct vfio_iommu_driver_ops vfio_iommu_driver_ops_type1 = {
3173         .name                   = "vfio-iommu-type1",
3174         .owner                  = THIS_MODULE,
3175         .open                   = vfio_iommu_type1_open,
3176         .release                = vfio_iommu_type1_release,
3177         .ioctl                  = vfio_iommu_type1_ioctl,
3178         .attach_group           = vfio_iommu_type1_attach_group,
3179         .detach_group           = vfio_iommu_type1_detach_group,
3180         .pin_pages              = vfio_iommu_type1_pin_pages,
3181         .unpin_pages            = vfio_iommu_type1_unpin_pages,
3182         .register_device        = vfio_iommu_type1_register_device,
3183         .unregister_device      = vfio_iommu_type1_unregister_device,
3184         .dma_rw                 = vfio_iommu_type1_dma_rw,
3185         .group_iommu_domain     = vfio_iommu_type1_group_iommu_domain,
3186 };
3187
3188 static int __init vfio_iommu_type1_init(void)
3189 {
3190         return vfio_register_iommu_driver(&vfio_iommu_driver_ops_type1);
3191 }
3192
3193 static void __exit vfio_iommu_type1_cleanup(void)
3194 {
3195         vfio_unregister_iommu_driver(&vfio_iommu_driver_ops_type1);
3196 }
3197
3198 module_init(vfio_iommu_type1_init);
3199 module_exit(vfio_iommu_type1_cleanup);
3200
3201 MODULE_VERSION(DRIVER_VERSION);
3202 MODULE_LICENSE("GPL v2");
3203 MODULE_AUTHOR(DRIVER_AUTHOR);
3204 MODULE_DESCRIPTION(DRIVER_DESC);