]> asedeno.scripts.mit.edu Git - linux.git/blob - drivers/vfio/vfio_iommu_type1.c
Merge drm/drm-next into drm-misc-next
[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  * userpsace 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/iommu.h>
28 #include <linux/module.h>
29 #include <linux/mm.h>
30 #include <linux/rbtree.h>
31 #include <linux/sched/signal.h>
32 #include <linux/sched/mm.h>
33 #include <linux/slab.h>
34 #include <linux/uaccess.h>
35 #include <linux/vfio.h>
36 #include <linux/workqueue.h>
37 #include <linux/mdev.h>
38 #include <linux/notifier.h>
39 #include <linux/dma-iommu.h>
40 #include <linux/irqdomain.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 vfio_domain      *external_domain; /* domain for external user */
67         struct mutex            lock;
68         struct rb_root          dma_list;
69         struct blocking_notifier_head notifier;
70         unsigned int            dma_avail;
71         bool                    v2;
72         bool                    nesting;
73 };
74
75 struct vfio_domain {
76         struct iommu_domain     *domain;
77         struct list_head        next;
78         struct list_head        group_list;
79         int                     prot;           /* IOMMU_CACHE */
80         bool                    fgsp;           /* Fine-grained super pages */
81 };
82
83 struct vfio_dma {
84         struct rb_node          node;
85         dma_addr_t              iova;           /* Device address */
86         unsigned long           vaddr;          /* Process virtual addr */
87         size_t                  size;           /* Map size (bytes) */
88         int                     prot;           /* IOMMU_READ/WRITE */
89         bool                    iommu_mapped;
90         bool                    lock_cap;       /* capable(CAP_IPC_LOCK) */
91         struct task_struct      *task;
92         struct rb_root          pfn_list;       /* Ex-user pinned pfn list */
93 };
94
95 struct vfio_group {
96         struct iommu_group      *iommu_group;
97         struct list_head        next;
98         bool                    mdev_group;     /* An mdev group */
99 };
100
101 struct vfio_iova {
102         struct list_head        list;
103         dma_addr_t              start;
104         dma_addr_t              end;
105 };
106
107 /*
108  * Guest RAM pinning working set or DMA target
109  */
110 struct vfio_pfn {
111         struct rb_node          node;
112         dma_addr_t              iova;           /* Device address */
113         unsigned long           pfn;            /* Host pfn */
114         atomic_t                ref_count;
115 };
116
117 struct vfio_regions {
118         struct list_head list;
119         dma_addr_t iova;
120         phys_addr_t phys;
121         size_t len;
122 };
123
124 #define IS_IOMMU_CAP_DOMAIN_IN_CONTAINER(iommu) \
125                                         (!list_empty(&iommu->domain_list))
126
127 static int put_pfn(unsigned long pfn, int prot);
128
129 /*
130  * This code handles mapping and unmapping of user data buffers
131  * into DMA'ble space using the IOMMU
132  */
133
134 static struct vfio_dma *vfio_find_dma(struct vfio_iommu *iommu,
135                                       dma_addr_t start, size_t size)
136 {
137         struct rb_node *node = iommu->dma_list.rb_node;
138
139         while (node) {
140                 struct vfio_dma *dma = rb_entry(node, struct vfio_dma, node);
141
142                 if (start + size <= dma->iova)
143                         node = node->rb_left;
144                 else if (start >= dma->iova + dma->size)
145                         node = node->rb_right;
146                 else
147                         return dma;
148         }
149
150         return NULL;
151 }
152
153 static void vfio_link_dma(struct vfio_iommu *iommu, struct vfio_dma *new)
154 {
155         struct rb_node **link = &iommu->dma_list.rb_node, *parent = NULL;
156         struct vfio_dma *dma;
157
158         while (*link) {
159                 parent = *link;
160                 dma = rb_entry(parent, struct vfio_dma, node);
161
162                 if (new->iova + new->size <= dma->iova)
163                         link = &(*link)->rb_left;
164                 else
165                         link = &(*link)->rb_right;
166         }
167
168         rb_link_node(&new->node, parent, link);
169         rb_insert_color(&new->node, &iommu->dma_list);
170 }
171
172 static void vfio_unlink_dma(struct vfio_iommu *iommu, struct vfio_dma *old)
173 {
174         rb_erase(&old->node, &iommu->dma_list);
175 }
176
177 /*
178  * Helper Functions for host iova-pfn list
179  */
180 static struct vfio_pfn *vfio_find_vpfn(struct vfio_dma *dma, dma_addr_t iova)
181 {
182         struct vfio_pfn *vpfn;
183         struct rb_node *node = dma->pfn_list.rb_node;
184
185         while (node) {
186                 vpfn = rb_entry(node, struct vfio_pfn, node);
187
188                 if (iova < vpfn->iova)
189                         node = node->rb_left;
190                 else if (iova > vpfn->iova)
191                         node = node->rb_right;
192                 else
193                         return vpfn;
194         }
195         return NULL;
196 }
197
198 static void vfio_link_pfn(struct vfio_dma *dma,
199                           struct vfio_pfn *new)
200 {
201         struct rb_node **link, *parent = NULL;
202         struct vfio_pfn *vpfn;
203
204         link = &dma->pfn_list.rb_node;
205         while (*link) {
206                 parent = *link;
207                 vpfn = rb_entry(parent, struct vfio_pfn, node);
208
209                 if (new->iova < vpfn->iova)
210                         link = &(*link)->rb_left;
211                 else
212                         link = &(*link)->rb_right;
213         }
214
215         rb_link_node(&new->node, parent, link);
216         rb_insert_color(&new->node, &dma->pfn_list);
217 }
218
219 static void vfio_unlink_pfn(struct vfio_dma *dma, struct vfio_pfn *old)
220 {
221         rb_erase(&old->node, &dma->pfn_list);
222 }
223
224 static int vfio_add_to_pfn_list(struct vfio_dma *dma, dma_addr_t iova,
225                                 unsigned long pfn)
226 {
227         struct vfio_pfn *vpfn;
228
229         vpfn = kzalloc(sizeof(*vpfn), GFP_KERNEL);
230         if (!vpfn)
231                 return -ENOMEM;
232
233         vpfn->iova = iova;
234         vpfn->pfn = pfn;
235         atomic_set(&vpfn->ref_count, 1);
236         vfio_link_pfn(dma, vpfn);
237         return 0;
238 }
239
240 static void vfio_remove_from_pfn_list(struct vfio_dma *dma,
241                                       struct vfio_pfn *vpfn)
242 {
243         vfio_unlink_pfn(dma, vpfn);
244         kfree(vpfn);
245 }
246
247 static struct vfio_pfn *vfio_iova_get_vfio_pfn(struct vfio_dma *dma,
248                                                unsigned long iova)
249 {
250         struct vfio_pfn *vpfn = vfio_find_vpfn(dma, iova);
251
252         if (vpfn)
253                 atomic_inc(&vpfn->ref_count);
254         return vpfn;
255 }
256
257 static int vfio_iova_put_vfio_pfn(struct vfio_dma *dma, struct vfio_pfn *vpfn)
258 {
259         int ret = 0;
260
261         if (atomic_dec_and_test(&vpfn->ref_count)) {
262                 ret = put_pfn(vpfn->pfn, dma->prot);
263                 vfio_remove_from_pfn_list(dma, vpfn);
264         }
265         return ret;
266 }
267
268 static int vfio_lock_acct(struct vfio_dma *dma, long npage, bool async)
269 {
270         struct mm_struct *mm;
271         int ret;
272
273         if (!npage)
274                 return 0;
275
276         mm = async ? get_task_mm(dma->task) : dma->task->mm;
277         if (!mm)
278                 return -ESRCH; /* process exited */
279
280         ret = down_write_killable(&mm->mmap_sem);
281         if (!ret) {
282                 ret = __account_locked_vm(mm, abs(npage), npage > 0, dma->task,
283                                           dma->lock_cap);
284                 up_write(&mm->mmap_sem);
285         }
286
287         if (async)
288                 mmput(mm);
289
290         return ret;
291 }
292
293 /*
294  * Some mappings aren't backed by a struct page, for example an mmap'd
295  * MMIO range for our own or another device.  These use a different
296  * pfn conversion and shouldn't be tracked as locked pages.
297  * For compound pages, any driver that sets the reserved bit in head
298  * page needs to set the reserved bit in all subpages to be safe.
299  */
300 static bool is_invalid_reserved_pfn(unsigned long pfn)
301 {
302         if (pfn_valid(pfn))
303                 return PageReserved(pfn_to_page(pfn));
304
305         return true;
306 }
307
308 static int put_pfn(unsigned long pfn, int prot)
309 {
310         if (!is_invalid_reserved_pfn(pfn)) {
311                 struct page *page = pfn_to_page(pfn);
312                 if (prot & IOMMU_WRITE)
313                         SetPageDirty(page);
314                 put_page(page);
315                 return 1;
316         }
317         return 0;
318 }
319
320 static int vaddr_get_pfn(struct mm_struct *mm, unsigned long vaddr,
321                          int prot, unsigned long *pfn)
322 {
323         struct page *page[1];
324         struct vm_area_struct *vma;
325         struct vm_area_struct *vmas[1];
326         unsigned int flags = 0;
327         int ret;
328
329         if (prot & IOMMU_WRITE)
330                 flags |= FOLL_WRITE;
331
332         down_read(&mm->mmap_sem);
333         if (mm == current->mm) {
334                 ret = get_user_pages(vaddr, 1, flags | FOLL_LONGTERM, page,
335                                      vmas);
336         } else {
337                 ret = get_user_pages_remote(NULL, mm, vaddr, 1, flags, page,
338                                             vmas, NULL);
339                 /*
340                  * The lifetime of a vaddr_get_pfn() page pin is
341                  * userspace-controlled. In the fs-dax case this could
342                  * lead to indefinite stalls in filesystem operations.
343                  * Disallow attempts to pin fs-dax pages via this
344                  * interface.
345                  */
346                 if (ret > 0 && vma_is_fsdax(vmas[0])) {
347                         ret = -EOPNOTSUPP;
348                         put_page(page[0]);
349                 }
350         }
351         up_read(&mm->mmap_sem);
352
353         if (ret == 1) {
354                 *pfn = page_to_pfn(page[0]);
355                 return 0;
356         }
357
358         down_read(&mm->mmap_sem);
359
360         vaddr = untagged_addr(vaddr);
361
362         vma = find_vma_intersection(mm, vaddr, vaddr + 1);
363
364         if (vma && vma->vm_flags & VM_PFNMAP) {
365                 *pfn = ((vaddr - vma->vm_start) >> PAGE_SHIFT) + vma->vm_pgoff;
366                 if (is_invalid_reserved_pfn(*pfn))
367                         ret = 0;
368         }
369
370         up_read(&mm->mmap_sem);
371         return ret;
372 }
373
374 /*
375  * Attempt to pin pages.  We really don't want to track all the pfns and
376  * the iommu can only map chunks of consecutive pfns anyway, so get the
377  * first page and all consecutive pages with the same locking.
378  */
379 static long vfio_pin_pages_remote(struct vfio_dma *dma, unsigned long vaddr,
380                                   long npage, unsigned long *pfn_base,
381                                   unsigned long limit)
382 {
383         unsigned long pfn = 0;
384         long ret, pinned = 0, lock_acct = 0;
385         bool rsvd;
386         dma_addr_t iova = vaddr - dma->vaddr + dma->iova;
387
388         /* This code path is only user initiated */
389         if (!current->mm)
390                 return -ENODEV;
391
392         ret = vaddr_get_pfn(current->mm, vaddr, dma->prot, pfn_base);
393         if (ret)
394                 return ret;
395
396         pinned++;
397         rsvd = is_invalid_reserved_pfn(*pfn_base);
398
399         /*
400          * Reserved pages aren't counted against the user, externally pinned
401          * pages are already counted against the user.
402          */
403         if (!rsvd && !vfio_find_vpfn(dma, iova)) {
404                 if (!dma->lock_cap && current->mm->locked_vm + 1 > limit) {
405                         put_pfn(*pfn_base, dma->prot);
406                         pr_warn("%s: RLIMIT_MEMLOCK (%ld) exceeded\n", __func__,
407                                         limit << PAGE_SHIFT);
408                         return -ENOMEM;
409                 }
410                 lock_acct++;
411         }
412
413         if (unlikely(disable_hugepages))
414                 goto out;
415
416         /* Lock all the consecutive pages from pfn_base */
417         for (vaddr += PAGE_SIZE, iova += PAGE_SIZE; pinned < npage;
418              pinned++, vaddr += PAGE_SIZE, iova += PAGE_SIZE) {
419                 ret = vaddr_get_pfn(current->mm, vaddr, dma->prot, &pfn);
420                 if (ret)
421                         break;
422
423                 if (pfn != *pfn_base + pinned ||
424                     rsvd != is_invalid_reserved_pfn(pfn)) {
425                         put_pfn(pfn, dma->prot);
426                         break;
427                 }
428
429                 if (!rsvd && !vfio_find_vpfn(dma, iova)) {
430                         if (!dma->lock_cap &&
431                             current->mm->locked_vm + lock_acct + 1 > limit) {
432                                 put_pfn(pfn, dma->prot);
433                                 pr_warn("%s: RLIMIT_MEMLOCK (%ld) exceeded\n",
434                                         __func__, limit << PAGE_SHIFT);
435                                 ret = -ENOMEM;
436                                 goto unpin_out;
437                         }
438                         lock_acct++;
439                 }
440         }
441
442 out:
443         ret = vfio_lock_acct(dma, lock_acct, false);
444
445 unpin_out:
446         if (ret) {
447                 if (!rsvd) {
448                         for (pfn = *pfn_base ; pinned ; pfn++, pinned--)
449                                 put_pfn(pfn, dma->prot);
450                 }
451
452                 return ret;
453         }
454
455         return pinned;
456 }
457
458 static long vfio_unpin_pages_remote(struct vfio_dma *dma, dma_addr_t iova,
459                                     unsigned long pfn, long npage,
460                                     bool do_accounting)
461 {
462         long unlocked = 0, locked = 0;
463         long i;
464
465         for (i = 0; i < npage; i++, iova += PAGE_SIZE) {
466                 if (put_pfn(pfn++, dma->prot)) {
467                         unlocked++;
468                         if (vfio_find_vpfn(dma, iova))
469                                 locked++;
470                 }
471         }
472
473         if (do_accounting)
474                 vfio_lock_acct(dma, locked - unlocked, true);
475
476         return unlocked;
477 }
478
479 static int vfio_pin_page_external(struct vfio_dma *dma, unsigned long vaddr,
480                                   unsigned long *pfn_base, bool do_accounting)
481 {
482         struct mm_struct *mm;
483         int ret;
484
485         mm = get_task_mm(dma->task);
486         if (!mm)
487                 return -ENODEV;
488
489         ret = vaddr_get_pfn(mm, vaddr, dma->prot, pfn_base);
490         if (!ret && do_accounting && !is_invalid_reserved_pfn(*pfn_base)) {
491                 ret = vfio_lock_acct(dma, 1, true);
492                 if (ret) {
493                         put_pfn(*pfn_base, dma->prot);
494                         if (ret == -ENOMEM)
495                                 pr_warn("%s: Task %s (%d) RLIMIT_MEMLOCK "
496                                         "(%ld) exceeded\n", __func__,
497                                         dma->task->comm, task_pid_nr(dma->task),
498                                         task_rlimit(dma->task, RLIMIT_MEMLOCK));
499                 }
500         }
501
502         mmput(mm);
503         return ret;
504 }
505
506 static int vfio_unpin_page_external(struct vfio_dma *dma, dma_addr_t iova,
507                                     bool do_accounting)
508 {
509         int unlocked;
510         struct vfio_pfn *vpfn = vfio_find_vpfn(dma, iova);
511
512         if (!vpfn)
513                 return 0;
514
515         unlocked = vfio_iova_put_vfio_pfn(dma, vpfn);
516
517         if (do_accounting)
518                 vfio_lock_acct(dma, -unlocked, true);
519
520         return unlocked;
521 }
522
523 static int vfio_iommu_type1_pin_pages(void *iommu_data,
524                                       unsigned long *user_pfn,
525                                       int npage, int prot,
526                                       unsigned long *phys_pfn)
527 {
528         struct vfio_iommu *iommu = iommu_data;
529         int i, j, ret;
530         unsigned long remote_vaddr;
531         struct vfio_dma *dma;
532         bool do_accounting;
533
534         if (!iommu || !user_pfn || !phys_pfn)
535                 return -EINVAL;
536
537         /* Supported for v2 version only */
538         if (!iommu->v2)
539                 return -EACCES;
540
541         mutex_lock(&iommu->lock);
542
543         /* Fail if notifier list is empty */
544         if (!iommu->notifier.head) {
545                 ret = -EINVAL;
546                 goto pin_done;
547         }
548
549         /*
550          * If iommu capable domain exist in the container then all pages are
551          * already pinned and accounted. Accouting should be done if there is no
552          * iommu capable domain in the container.
553          */
554         do_accounting = !IS_IOMMU_CAP_DOMAIN_IN_CONTAINER(iommu);
555
556         for (i = 0; i < npage; i++) {
557                 dma_addr_t iova;
558                 struct vfio_pfn *vpfn;
559
560                 iova = user_pfn[i] << PAGE_SHIFT;
561                 dma = vfio_find_dma(iommu, iova, PAGE_SIZE);
562                 if (!dma) {
563                         ret = -EINVAL;
564                         goto pin_unwind;
565                 }
566
567                 if ((dma->prot & prot) != prot) {
568                         ret = -EPERM;
569                         goto pin_unwind;
570                 }
571
572                 vpfn = vfio_iova_get_vfio_pfn(dma, iova);
573                 if (vpfn) {
574                         phys_pfn[i] = vpfn->pfn;
575                         continue;
576                 }
577
578                 remote_vaddr = dma->vaddr + iova - dma->iova;
579                 ret = vfio_pin_page_external(dma, remote_vaddr, &phys_pfn[i],
580                                              do_accounting);
581                 if (ret)
582                         goto pin_unwind;
583
584                 ret = vfio_add_to_pfn_list(dma, iova, phys_pfn[i]);
585                 if (ret) {
586                         vfio_unpin_page_external(dma, iova, do_accounting);
587                         goto pin_unwind;
588                 }
589         }
590
591         ret = i;
592         goto pin_done;
593
594 pin_unwind:
595         phys_pfn[i] = 0;
596         for (j = 0; j < i; j++) {
597                 dma_addr_t iova;
598
599                 iova = user_pfn[j] << PAGE_SHIFT;
600                 dma = vfio_find_dma(iommu, iova, PAGE_SIZE);
601                 vfio_unpin_page_external(dma, iova, do_accounting);
602                 phys_pfn[j] = 0;
603         }
604 pin_done:
605         mutex_unlock(&iommu->lock);
606         return ret;
607 }
608
609 static int vfio_iommu_type1_unpin_pages(void *iommu_data,
610                                         unsigned long *user_pfn,
611                                         int npage)
612 {
613         struct vfio_iommu *iommu = iommu_data;
614         bool do_accounting;
615         int i;
616
617         if (!iommu || !user_pfn)
618                 return -EINVAL;
619
620         /* Supported for v2 version only */
621         if (!iommu->v2)
622                 return -EACCES;
623
624         mutex_lock(&iommu->lock);
625
626         do_accounting = !IS_IOMMU_CAP_DOMAIN_IN_CONTAINER(iommu);
627         for (i = 0; i < npage; i++) {
628                 struct vfio_dma *dma;
629                 dma_addr_t iova;
630
631                 iova = user_pfn[i] << PAGE_SHIFT;
632                 dma = vfio_find_dma(iommu, iova, PAGE_SIZE);
633                 if (!dma)
634                         goto unpin_exit;
635                 vfio_unpin_page_external(dma, iova, do_accounting);
636         }
637
638 unpin_exit:
639         mutex_unlock(&iommu->lock);
640         return i > npage ? npage : (i > 0 ? i : -EINVAL);
641 }
642
643 static long vfio_sync_unpin(struct vfio_dma *dma, struct vfio_domain *domain,
644                             struct list_head *regions,
645                             struct iommu_iotlb_gather *iotlb_gather)
646 {
647         long unlocked = 0;
648         struct vfio_regions *entry, *next;
649
650         iommu_tlb_sync(domain->domain, iotlb_gather);
651
652         list_for_each_entry_safe(entry, next, regions, list) {
653                 unlocked += vfio_unpin_pages_remote(dma,
654                                                     entry->iova,
655                                                     entry->phys >> PAGE_SHIFT,
656                                                     entry->len >> PAGE_SHIFT,
657                                                     false);
658                 list_del(&entry->list);
659                 kfree(entry);
660         }
661
662         cond_resched();
663
664         return unlocked;
665 }
666
667 /*
668  * Generally, VFIO needs to unpin remote pages after each IOTLB flush.
669  * Therefore, when using IOTLB flush sync interface, VFIO need to keep track
670  * of these regions (currently using a list).
671  *
672  * This value specifies maximum number of regions for each IOTLB flush sync.
673  */
674 #define VFIO_IOMMU_TLB_SYNC_MAX         512
675
676 static size_t unmap_unpin_fast(struct vfio_domain *domain,
677                                struct vfio_dma *dma, dma_addr_t *iova,
678                                size_t len, phys_addr_t phys, long *unlocked,
679                                struct list_head *unmapped_list,
680                                int *unmapped_cnt,
681                                struct iommu_iotlb_gather *iotlb_gather)
682 {
683         size_t unmapped = 0;
684         struct vfio_regions *entry = kzalloc(sizeof(*entry), GFP_KERNEL);
685
686         if (entry) {
687                 unmapped = iommu_unmap_fast(domain->domain, *iova, len,
688                                             iotlb_gather);
689
690                 if (!unmapped) {
691                         kfree(entry);
692                 } else {
693                         entry->iova = *iova;
694                         entry->phys = phys;
695                         entry->len  = unmapped;
696                         list_add_tail(&entry->list, unmapped_list);
697
698                         *iova += unmapped;
699                         (*unmapped_cnt)++;
700                 }
701         }
702
703         /*
704          * Sync if the number of fast-unmap regions hits the limit
705          * or in case of errors.
706          */
707         if (*unmapped_cnt >= VFIO_IOMMU_TLB_SYNC_MAX || !unmapped) {
708                 *unlocked += vfio_sync_unpin(dma, domain, unmapped_list,
709                                              iotlb_gather);
710                 *unmapped_cnt = 0;
711         }
712
713         return unmapped;
714 }
715
716 static size_t unmap_unpin_slow(struct vfio_domain *domain,
717                                struct vfio_dma *dma, dma_addr_t *iova,
718                                size_t len, phys_addr_t phys,
719                                long *unlocked)
720 {
721         size_t unmapped = iommu_unmap(domain->domain, *iova, len);
722
723         if (unmapped) {
724                 *unlocked += vfio_unpin_pages_remote(dma, *iova,
725                                                      phys >> PAGE_SHIFT,
726                                                      unmapped >> PAGE_SHIFT,
727                                                      false);
728                 *iova += unmapped;
729                 cond_resched();
730         }
731         return unmapped;
732 }
733
734 static long vfio_unmap_unpin(struct vfio_iommu *iommu, struct vfio_dma *dma,
735                              bool do_accounting)
736 {
737         dma_addr_t iova = dma->iova, end = dma->iova + dma->size;
738         struct vfio_domain *domain, *d;
739         LIST_HEAD(unmapped_region_list);
740         struct iommu_iotlb_gather iotlb_gather;
741         int unmapped_region_cnt = 0;
742         long unlocked = 0;
743
744         if (!dma->size)
745                 return 0;
746
747         if (!IS_IOMMU_CAP_DOMAIN_IN_CONTAINER(iommu))
748                 return 0;
749
750         /*
751          * We use the IOMMU to track the physical addresses, otherwise we'd
752          * need a much more complicated tracking system.  Unfortunately that
753          * means we need to use one of the iommu domains to figure out the
754          * pfns to unpin.  The rest need to be unmapped in advance so we have
755          * no iommu translations remaining when the pages are unpinned.
756          */
757         domain = d = list_first_entry(&iommu->domain_list,
758                                       struct vfio_domain, next);
759
760         list_for_each_entry_continue(d, &iommu->domain_list, next) {
761                 iommu_unmap(d->domain, dma->iova, dma->size);
762                 cond_resched();
763         }
764
765         iommu_iotlb_gather_init(&iotlb_gather);
766         while (iova < end) {
767                 size_t unmapped, len;
768                 phys_addr_t phys, next;
769
770                 phys = iommu_iova_to_phys(domain->domain, iova);
771                 if (WARN_ON(!phys)) {
772                         iova += PAGE_SIZE;
773                         continue;
774                 }
775
776                 /*
777                  * To optimize for fewer iommu_unmap() calls, each of which
778                  * may require hardware cache flushing, try to find the
779                  * largest contiguous physical memory chunk to unmap.
780                  */
781                 for (len = PAGE_SIZE;
782                      !domain->fgsp && iova + len < end; len += PAGE_SIZE) {
783                         next = iommu_iova_to_phys(domain->domain, iova + len);
784                         if (next != phys + len)
785                                 break;
786                 }
787
788                 /*
789                  * First, try to use fast unmap/unpin. In case of failure,
790                  * switch to slow unmap/unpin path.
791                  */
792                 unmapped = unmap_unpin_fast(domain, dma, &iova, len, phys,
793                                             &unlocked, &unmapped_region_list,
794                                             &unmapped_region_cnt,
795                                             &iotlb_gather);
796                 if (!unmapped) {
797                         unmapped = unmap_unpin_slow(domain, dma, &iova, len,
798                                                     phys, &unlocked);
799                         if (WARN_ON(!unmapped))
800                                 break;
801                 }
802         }
803
804         dma->iommu_mapped = false;
805
806         if (unmapped_region_cnt) {
807                 unlocked += vfio_sync_unpin(dma, domain, &unmapped_region_list,
808                                             &iotlb_gather);
809         }
810
811         if (do_accounting) {
812                 vfio_lock_acct(dma, -unlocked, true);
813                 return 0;
814         }
815         return unlocked;
816 }
817
818 static void vfio_remove_dma(struct vfio_iommu *iommu, struct vfio_dma *dma)
819 {
820         vfio_unmap_unpin(iommu, dma, true);
821         vfio_unlink_dma(iommu, dma);
822         put_task_struct(dma->task);
823         kfree(dma);
824         iommu->dma_avail++;
825 }
826
827 static unsigned long vfio_pgsize_bitmap(struct vfio_iommu *iommu)
828 {
829         struct vfio_domain *domain;
830         unsigned long bitmap = ULONG_MAX;
831
832         mutex_lock(&iommu->lock);
833         list_for_each_entry(domain, &iommu->domain_list, next)
834                 bitmap &= domain->domain->pgsize_bitmap;
835         mutex_unlock(&iommu->lock);
836
837         /*
838          * In case the IOMMU supports page sizes smaller than PAGE_SIZE
839          * we pretend PAGE_SIZE is supported and hide sub-PAGE_SIZE sizes.
840          * That way the user will be able to map/unmap buffers whose size/
841          * start address is aligned with PAGE_SIZE. Pinning code uses that
842          * granularity while iommu driver can use the sub-PAGE_SIZE size
843          * to map the buffer.
844          */
845         if (bitmap & ~PAGE_MASK) {
846                 bitmap &= PAGE_MASK;
847                 bitmap |= PAGE_SIZE;
848         }
849
850         return bitmap;
851 }
852
853 static int vfio_dma_do_unmap(struct vfio_iommu *iommu,
854                              struct vfio_iommu_type1_dma_unmap *unmap)
855 {
856         uint64_t mask;
857         struct vfio_dma *dma, *dma_last = NULL;
858         size_t unmapped = 0;
859         int ret = 0, retries = 0;
860
861         mask = ((uint64_t)1 << __ffs(vfio_pgsize_bitmap(iommu))) - 1;
862
863         if (unmap->iova & mask)
864                 return -EINVAL;
865         if (!unmap->size || unmap->size & mask)
866                 return -EINVAL;
867         if (unmap->iova + unmap->size - 1 < unmap->iova ||
868             unmap->size > SIZE_MAX)
869                 return -EINVAL;
870
871         WARN_ON(mask & PAGE_MASK);
872 again:
873         mutex_lock(&iommu->lock);
874
875         /*
876          * vfio-iommu-type1 (v1) - User mappings were coalesced together to
877          * avoid tracking individual mappings.  This means that the granularity
878          * of the original mapping was lost and the user was allowed to attempt
879          * to unmap any range.  Depending on the contiguousness of physical
880          * memory and page sizes supported by the IOMMU, arbitrary unmaps may
881          * or may not have worked.  We only guaranteed unmap granularity
882          * matching the original mapping; even though it was untracked here,
883          * the original mappings are reflected in IOMMU mappings.  This
884          * resulted in a couple unusual behaviors.  First, if a range is not
885          * able to be unmapped, ex. a set of 4k pages that was mapped as a
886          * 2M hugepage into the IOMMU, the unmap ioctl returns success but with
887          * a zero sized unmap.  Also, if an unmap request overlaps the first
888          * address of a hugepage, the IOMMU will unmap the entire hugepage.
889          * This also returns success and the returned unmap size reflects the
890          * actual size unmapped.
891          *
892          * We attempt to maintain compatibility with this "v1" interface, but
893          * we take control out of the hands of the IOMMU.  Therefore, an unmap
894          * request offset from the beginning of the original mapping will
895          * return success with zero sized unmap.  And an unmap request covering
896          * the first iova of mapping will unmap the entire range.
897          *
898          * The v2 version of this interface intends to be more deterministic.
899          * Unmap requests must fully cover previous mappings.  Multiple
900          * mappings may still be unmaped by specifying large ranges, but there
901          * must not be any previous mappings bisected by the range.  An error
902          * will be returned if these conditions are not met.  The v2 interface
903          * will only return success and a size of zero if there were no
904          * mappings within the range.
905          */
906         if (iommu->v2) {
907                 dma = vfio_find_dma(iommu, unmap->iova, 1);
908                 if (dma && dma->iova != unmap->iova) {
909                         ret = -EINVAL;
910                         goto unlock;
911                 }
912                 dma = vfio_find_dma(iommu, unmap->iova + unmap->size - 1, 0);
913                 if (dma && dma->iova + dma->size != unmap->iova + unmap->size) {
914                         ret = -EINVAL;
915                         goto unlock;
916                 }
917         }
918
919         while ((dma = vfio_find_dma(iommu, unmap->iova, unmap->size))) {
920                 if (!iommu->v2 && unmap->iova > dma->iova)
921                         break;
922                 /*
923                  * Task with same address space who mapped this iova range is
924                  * allowed to unmap the iova range.
925                  */
926                 if (dma->task->mm != current->mm)
927                         break;
928
929                 if (!RB_EMPTY_ROOT(&dma->pfn_list)) {
930                         struct vfio_iommu_type1_dma_unmap nb_unmap;
931
932                         if (dma_last == dma) {
933                                 BUG_ON(++retries > 10);
934                         } else {
935                                 dma_last = dma;
936                                 retries = 0;
937                         }
938
939                         nb_unmap.iova = dma->iova;
940                         nb_unmap.size = dma->size;
941
942                         /*
943                          * Notify anyone (mdev vendor drivers) to invalidate and
944                          * unmap iovas within the range we're about to unmap.
945                          * Vendor drivers MUST unpin pages in response to an
946                          * invalidation.
947                          */
948                         mutex_unlock(&iommu->lock);
949                         blocking_notifier_call_chain(&iommu->notifier,
950                                                     VFIO_IOMMU_NOTIFY_DMA_UNMAP,
951                                                     &nb_unmap);
952                         goto again;
953                 }
954                 unmapped += dma->size;
955                 vfio_remove_dma(iommu, dma);
956         }
957
958 unlock:
959         mutex_unlock(&iommu->lock);
960
961         /* Report how much was unmapped */
962         unmap->size = unmapped;
963
964         return ret;
965 }
966
967 static int vfio_iommu_map(struct vfio_iommu *iommu, dma_addr_t iova,
968                           unsigned long pfn, long npage, int prot)
969 {
970         struct vfio_domain *d;
971         int ret;
972
973         list_for_each_entry(d, &iommu->domain_list, next) {
974                 ret = iommu_map(d->domain, iova, (phys_addr_t)pfn << PAGE_SHIFT,
975                                 npage << PAGE_SHIFT, prot | d->prot);
976                 if (ret)
977                         goto unwind;
978
979                 cond_resched();
980         }
981
982         return 0;
983
984 unwind:
985         list_for_each_entry_continue_reverse(d, &iommu->domain_list, next)
986                 iommu_unmap(d->domain, iova, npage << PAGE_SHIFT);
987
988         return ret;
989 }
990
991 static int vfio_pin_map_dma(struct vfio_iommu *iommu, struct vfio_dma *dma,
992                             size_t map_size)
993 {
994         dma_addr_t iova = dma->iova;
995         unsigned long vaddr = dma->vaddr;
996         size_t size = map_size;
997         long npage;
998         unsigned long pfn, limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
999         int ret = 0;
1000
1001         while (size) {
1002                 /* Pin a contiguous chunk of memory */
1003                 npage = vfio_pin_pages_remote(dma, vaddr + dma->size,
1004                                               size >> PAGE_SHIFT, &pfn, limit);
1005                 if (npage <= 0) {
1006                         WARN_ON(!npage);
1007                         ret = (int)npage;
1008                         break;
1009                 }
1010
1011                 /* Map it! */
1012                 ret = vfio_iommu_map(iommu, iova + dma->size, pfn, npage,
1013                                      dma->prot);
1014                 if (ret) {
1015                         vfio_unpin_pages_remote(dma, iova + dma->size, pfn,
1016                                                 npage, true);
1017                         break;
1018                 }
1019
1020                 size -= npage << PAGE_SHIFT;
1021                 dma->size += npage << PAGE_SHIFT;
1022         }
1023
1024         dma->iommu_mapped = true;
1025
1026         if (ret)
1027                 vfio_remove_dma(iommu, dma);
1028
1029         return ret;
1030 }
1031
1032 /*
1033  * Check dma map request is within a valid iova range
1034  */
1035 static bool vfio_iommu_iova_dma_valid(struct vfio_iommu *iommu,
1036                                       dma_addr_t start, dma_addr_t end)
1037 {
1038         struct list_head *iova = &iommu->iova_list;
1039         struct vfio_iova *node;
1040
1041         list_for_each_entry(node, iova, list) {
1042                 if (start >= node->start && end <= node->end)
1043                         return true;
1044         }
1045
1046         /*
1047          * Check for list_empty() as well since a container with
1048          * a single mdev device will have an empty list.
1049          */
1050         return list_empty(iova);
1051 }
1052
1053 static int vfio_dma_do_map(struct vfio_iommu *iommu,
1054                            struct vfio_iommu_type1_dma_map *map)
1055 {
1056         dma_addr_t iova = map->iova;
1057         unsigned long vaddr = map->vaddr;
1058         size_t size = map->size;
1059         int ret = 0, prot = 0;
1060         uint64_t mask;
1061         struct vfio_dma *dma;
1062
1063         /* Verify that none of our __u64 fields overflow */
1064         if (map->size != size || map->vaddr != vaddr || map->iova != iova)
1065                 return -EINVAL;
1066
1067         mask = ((uint64_t)1 << __ffs(vfio_pgsize_bitmap(iommu))) - 1;
1068
1069         WARN_ON(mask & PAGE_MASK);
1070
1071         /* READ/WRITE from device perspective */
1072         if (map->flags & VFIO_DMA_MAP_FLAG_WRITE)
1073                 prot |= IOMMU_WRITE;
1074         if (map->flags & VFIO_DMA_MAP_FLAG_READ)
1075                 prot |= IOMMU_READ;
1076
1077         if (!prot || !size || (size | iova | vaddr) & mask)
1078                 return -EINVAL;
1079
1080         /* Don't allow IOVA or virtual address wrap */
1081         if (iova + size - 1 < iova || vaddr + size - 1 < vaddr)
1082                 return -EINVAL;
1083
1084         mutex_lock(&iommu->lock);
1085
1086         if (vfio_find_dma(iommu, iova, size)) {
1087                 ret = -EEXIST;
1088                 goto out_unlock;
1089         }
1090
1091         if (!iommu->dma_avail) {
1092                 ret = -ENOSPC;
1093                 goto out_unlock;
1094         }
1095
1096         if (!vfio_iommu_iova_dma_valid(iommu, iova, iova + size - 1)) {
1097                 ret = -EINVAL;
1098                 goto out_unlock;
1099         }
1100
1101         dma = kzalloc(sizeof(*dma), GFP_KERNEL);
1102         if (!dma) {
1103                 ret = -ENOMEM;
1104                 goto out_unlock;
1105         }
1106
1107         iommu->dma_avail--;
1108         dma->iova = iova;
1109         dma->vaddr = vaddr;
1110         dma->prot = prot;
1111
1112         /*
1113          * We need to be able to both add to a task's locked memory and test
1114          * against the locked memory limit and we need to be able to do both
1115          * outside of this call path as pinning can be asynchronous via the
1116          * external interfaces for mdev devices.  RLIMIT_MEMLOCK requires a
1117          * task_struct and VM locked pages requires an mm_struct, however
1118          * holding an indefinite mm reference is not recommended, therefore we
1119          * only hold a reference to a task.  We could hold a reference to
1120          * current, however QEMU uses this call path through vCPU threads,
1121          * which can be killed resulting in a NULL mm and failure in the unmap
1122          * path when called via a different thread.  Avoid this problem by
1123          * using the group_leader as threads within the same group require
1124          * both CLONE_THREAD and CLONE_VM and will therefore use the same
1125          * mm_struct.
1126          *
1127          * Previously we also used the task for testing CAP_IPC_LOCK at the
1128          * time of pinning and accounting, however has_capability() makes use
1129          * of real_cred, a copy-on-write field, so we can't guarantee that it
1130          * matches group_leader, or in fact that it might not change by the
1131          * time it's evaluated.  If a process were to call MAP_DMA with
1132          * CAP_IPC_LOCK but later drop it, it doesn't make sense that they
1133          * possibly see different results for an iommu_mapped vfio_dma vs
1134          * externally mapped.  Therefore track CAP_IPC_LOCK in vfio_dma at the
1135          * time of calling MAP_DMA.
1136          */
1137         get_task_struct(current->group_leader);
1138         dma->task = current->group_leader;
1139         dma->lock_cap = capable(CAP_IPC_LOCK);
1140
1141         dma->pfn_list = RB_ROOT;
1142
1143         /* Insert zero-sized and grow as we map chunks of it */
1144         vfio_link_dma(iommu, dma);
1145
1146         /* Don't pin and map if container doesn't contain IOMMU capable domain*/
1147         if (!IS_IOMMU_CAP_DOMAIN_IN_CONTAINER(iommu))
1148                 dma->size = size;
1149         else
1150                 ret = vfio_pin_map_dma(iommu, dma, size);
1151
1152 out_unlock:
1153         mutex_unlock(&iommu->lock);
1154         return ret;
1155 }
1156
1157 static int vfio_bus_type(struct device *dev, void *data)
1158 {
1159         struct bus_type **bus = data;
1160
1161         if (*bus && *bus != dev->bus)
1162                 return -EINVAL;
1163
1164         *bus = dev->bus;
1165
1166         return 0;
1167 }
1168
1169 static int vfio_iommu_replay(struct vfio_iommu *iommu,
1170                              struct vfio_domain *domain)
1171 {
1172         struct vfio_domain *d;
1173         struct rb_node *n;
1174         unsigned long limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
1175         int ret;
1176
1177         /* Arbitrarily pick the first domain in the list for lookups */
1178         d = list_first_entry(&iommu->domain_list, struct vfio_domain, next);
1179         n = rb_first(&iommu->dma_list);
1180
1181         for (; n; n = rb_next(n)) {
1182                 struct vfio_dma *dma;
1183                 dma_addr_t iova;
1184
1185                 dma = rb_entry(n, struct vfio_dma, node);
1186                 iova = dma->iova;
1187
1188                 while (iova < dma->iova + dma->size) {
1189                         phys_addr_t phys;
1190                         size_t size;
1191
1192                         if (dma->iommu_mapped) {
1193                                 phys_addr_t p;
1194                                 dma_addr_t i;
1195
1196                                 phys = iommu_iova_to_phys(d->domain, iova);
1197
1198                                 if (WARN_ON(!phys)) {
1199                                         iova += PAGE_SIZE;
1200                                         continue;
1201                                 }
1202
1203                                 size = PAGE_SIZE;
1204                                 p = phys + size;
1205                                 i = iova + size;
1206                                 while (i < dma->iova + dma->size &&
1207                                        p == iommu_iova_to_phys(d->domain, i)) {
1208                                         size += PAGE_SIZE;
1209                                         p += PAGE_SIZE;
1210                                         i += PAGE_SIZE;
1211                                 }
1212                         } else {
1213                                 unsigned long pfn;
1214                                 unsigned long vaddr = dma->vaddr +
1215                                                      (iova - dma->iova);
1216                                 size_t n = dma->iova + dma->size - iova;
1217                                 long npage;
1218
1219                                 npage = vfio_pin_pages_remote(dma, vaddr,
1220                                                               n >> PAGE_SHIFT,
1221                                                               &pfn, limit);
1222                                 if (npage <= 0) {
1223                                         WARN_ON(!npage);
1224                                         ret = (int)npage;
1225                                         return ret;
1226                                 }
1227
1228                                 phys = pfn << PAGE_SHIFT;
1229                                 size = npage << PAGE_SHIFT;
1230                         }
1231
1232                         ret = iommu_map(domain->domain, iova, phys,
1233                                         size, dma->prot | domain->prot);
1234                         if (ret)
1235                                 return ret;
1236
1237                         iova += size;
1238                 }
1239                 dma->iommu_mapped = true;
1240         }
1241         return 0;
1242 }
1243
1244 /*
1245  * We change our unmap behavior slightly depending on whether the IOMMU
1246  * supports fine-grained superpages.  IOMMUs like AMD-Vi will use a superpage
1247  * for practically any contiguous power-of-two mapping we give it.  This means
1248  * we don't need to look for contiguous chunks ourselves to make unmapping
1249  * more efficient.  On IOMMUs with coarse-grained super pages, like Intel VT-d
1250  * with discrete 2M/1G/512G/1T superpages, identifying contiguous chunks
1251  * significantly boosts non-hugetlbfs mappings and doesn't seem to hurt when
1252  * hugetlbfs is in use.
1253  */
1254 static void vfio_test_domain_fgsp(struct vfio_domain *domain)
1255 {
1256         struct page *pages;
1257         int ret, order = get_order(PAGE_SIZE * 2);
1258
1259         pages = alloc_pages(GFP_KERNEL | __GFP_ZERO, order);
1260         if (!pages)
1261                 return;
1262
1263         ret = iommu_map(domain->domain, 0, page_to_phys(pages), PAGE_SIZE * 2,
1264                         IOMMU_READ | IOMMU_WRITE | domain->prot);
1265         if (!ret) {
1266                 size_t unmapped = iommu_unmap(domain->domain, 0, PAGE_SIZE);
1267
1268                 if (unmapped == PAGE_SIZE)
1269                         iommu_unmap(domain->domain, PAGE_SIZE, PAGE_SIZE);
1270                 else
1271                         domain->fgsp = true;
1272         }
1273
1274         __free_pages(pages, order);
1275 }
1276
1277 static struct vfio_group *find_iommu_group(struct vfio_domain *domain,
1278                                            struct iommu_group *iommu_group)
1279 {
1280         struct vfio_group *g;
1281
1282         list_for_each_entry(g, &domain->group_list, next) {
1283                 if (g->iommu_group == iommu_group)
1284                         return g;
1285         }
1286
1287         return NULL;
1288 }
1289
1290 static bool vfio_iommu_has_sw_msi(struct list_head *group_resv_regions,
1291                                   phys_addr_t *base)
1292 {
1293         struct iommu_resv_region *region;
1294         bool ret = false;
1295
1296         list_for_each_entry(region, group_resv_regions, list) {
1297                 /*
1298                  * The presence of any 'real' MSI regions should take
1299                  * precedence over the software-managed one if the
1300                  * IOMMU driver happens to advertise both types.
1301                  */
1302                 if (region->type == IOMMU_RESV_MSI) {
1303                         ret = false;
1304                         break;
1305                 }
1306
1307                 if (region->type == IOMMU_RESV_SW_MSI) {
1308                         *base = region->start;
1309                         ret = true;
1310                 }
1311         }
1312
1313         return ret;
1314 }
1315
1316 static struct device *vfio_mdev_get_iommu_device(struct device *dev)
1317 {
1318         struct device *(*fn)(struct device *dev);
1319         struct device *iommu_device;
1320
1321         fn = symbol_get(mdev_get_iommu_device);
1322         if (fn) {
1323                 iommu_device = fn(dev);
1324                 symbol_put(mdev_get_iommu_device);
1325
1326                 return iommu_device;
1327         }
1328
1329         return NULL;
1330 }
1331
1332 static int vfio_mdev_attach_domain(struct device *dev, void *data)
1333 {
1334         struct iommu_domain *domain = data;
1335         struct device *iommu_device;
1336
1337         iommu_device = vfio_mdev_get_iommu_device(dev);
1338         if (iommu_device) {
1339                 if (iommu_dev_feature_enabled(iommu_device, IOMMU_DEV_FEAT_AUX))
1340                         return iommu_aux_attach_device(domain, iommu_device);
1341                 else
1342                         return iommu_attach_device(domain, iommu_device);
1343         }
1344
1345         return -EINVAL;
1346 }
1347
1348 static int vfio_mdev_detach_domain(struct device *dev, void *data)
1349 {
1350         struct iommu_domain *domain = data;
1351         struct device *iommu_device;
1352
1353         iommu_device = vfio_mdev_get_iommu_device(dev);
1354         if (iommu_device) {
1355                 if (iommu_dev_feature_enabled(iommu_device, IOMMU_DEV_FEAT_AUX))
1356                         iommu_aux_detach_device(domain, iommu_device);
1357                 else
1358                         iommu_detach_device(domain, iommu_device);
1359         }
1360
1361         return 0;
1362 }
1363
1364 static int vfio_iommu_attach_group(struct vfio_domain *domain,
1365                                    struct vfio_group *group)
1366 {
1367         if (group->mdev_group)
1368                 return iommu_group_for_each_dev(group->iommu_group,
1369                                                 domain->domain,
1370                                                 vfio_mdev_attach_domain);
1371         else
1372                 return iommu_attach_group(domain->domain, group->iommu_group);
1373 }
1374
1375 static void vfio_iommu_detach_group(struct vfio_domain *domain,
1376                                     struct vfio_group *group)
1377 {
1378         if (group->mdev_group)
1379                 iommu_group_for_each_dev(group->iommu_group, domain->domain,
1380                                          vfio_mdev_detach_domain);
1381         else
1382                 iommu_detach_group(domain->domain, group->iommu_group);
1383 }
1384
1385 static bool vfio_bus_is_mdev(struct bus_type *bus)
1386 {
1387         struct bus_type *mdev_bus;
1388         bool ret = false;
1389
1390         mdev_bus = symbol_get(mdev_bus_type);
1391         if (mdev_bus) {
1392                 ret = (bus == mdev_bus);
1393                 symbol_put(mdev_bus_type);
1394         }
1395
1396         return ret;
1397 }
1398
1399 static int vfio_mdev_iommu_device(struct device *dev, void *data)
1400 {
1401         struct device **old = data, *new;
1402
1403         new = vfio_mdev_get_iommu_device(dev);
1404         if (!new || (*old && *old != new))
1405                 return -EINVAL;
1406
1407         *old = new;
1408
1409         return 0;
1410 }
1411
1412 /*
1413  * This is a helper function to insert an address range to iova list.
1414  * The list is initially created with a single entry corresponding to
1415  * the IOMMU domain geometry to which the device group is attached.
1416  * The list aperture gets modified when a new domain is added to the
1417  * container if the new aperture doesn't conflict with the current one
1418  * or with any existing dma mappings. The list is also modified to
1419  * exclude any reserved regions associated with the device group.
1420  */
1421 static int vfio_iommu_iova_insert(struct list_head *head,
1422                                   dma_addr_t start, dma_addr_t end)
1423 {
1424         struct vfio_iova *region;
1425
1426         region = kmalloc(sizeof(*region), GFP_KERNEL);
1427         if (!region)
1428                 return -ENOMEM;
1429
1430         INIT_LIST_HEAD(&region->list);
1431         region->start = start;
1432         region->end = end;
1433
1434         list_add_tail(&region->list, head);
1435         return 0;
1436 }
1437
1438 /*
1439  * Check the new iommu aperture conflicts with existing aper or with any
1440  * existing dma mappings.
1441  */
1442 static bool vfio_iommu_aper_conflict(struct vfio_iommu *iommu,
1443                                      dma_addr_t start, dma_addr_t end)
1444 {
1445         struct vfio_iova *first, *last;
1446         struct list_head *iova = &iommu->iova_list;
1447
1448         if (list_empty(iova))
1449                 return false;
1450
1451         /* Disjoint sets, return conflict */
1452         first = list_first_entry(iova, struct vfio_iova, list);
1453         last = list_last_entry(iova, struct vfio_iova, list);
1454         if (start > last->end || end < first->start)
1455                 return true;
1456
1457         /* Check for any existing dma mappings below the new start */
1458         if (start > first->start) {
1459                 if (vfio_find_dma(iommu, first->start, start - first->start))
1460                         return true;
1461         }
1462
1463         /* Check for any existing dma mappings beyond the new end */
1464         if (end < last->end) {
1465                 if (vfio_find_dma(iommu, end + 1, last->end - end))
1466                         return true;
1467         }
1468
1469         return false;
1470 }
1471
1472 /*
1473  * Resize iommu iova aperture window. This is called only if the new
1474  * aperture has no conflict with existing aperture and dma mappings.
1475  */
1476 static int vfio_iommu_aper_resize(struct list_head *iova,
1477                                   dma_addr_t start, dma_addr_t end)
1478 {
1479         struct vfio_iova *node, *next;
1480
1481         if (list_empty(iova))
1482                 return vfio_iommu_iova_insert(iova, start, end);
1483
1484         /* Adjust iova list start */
1485         list_for_each_entry_safe(node, next, iova, list) {
1486                 if (start < node->start)
1487                         break;
1488                 if (start >= node->start && start < node->end) {
1489                         node->start = start;
1490                         break;
1491                 }
1492                 /* Delete nodes before new start */
1493                 list_del(&node->list);
1494                 kfree(node);
1495         }
1496
1497         /* Adjust iova list end */
1498         list_for_each_entry_safe(node, next, iova, list) {
1499                 if (end > node->end)
1500                         continue;
1501                 if (end > node->start && end <= node->end) {
1502                         node->end = end;
1503                         continue;
1504                 }
1505                 /* Delete nodes after new end */
1506                 list_del(&node->list);
1507                 kfree(node);
1508         }
1509
1510         return 0;
1511 }
1512
1513 /*
1514  * Check reserved region conflicts with existing dma mappings
1515  */
1516 static bool vfio_iommu_resv_conflict(struct vfio_iommu *iommu,
1517                                      struct list_head *resv_regions)
1518 {
1519         struct iommu_resv_region *region;
1520
1521         /* Check for conflict with existing dma mappings */
1522         list_for_each_entry(region, resv_regions, list) {
1523                 if (region->type == IOMMU_RESV_DIRECT_RELAXABLE)
1524                         continue;
1525
1526                 if (vfio_find_dma(iommu, region->start, region->length))
1527                         return true;
1528         }
1529
1530         return false;
1531 }
1532
1533 /*
1534  * Check iova region overlap with  reserved regions and
1535  * exclude them from the iommu iova range
1536  */
1537 static int vfio_iommu_resv_exclude(struct list_head *iova,
1538                                    struct list_head *resv_regions)
1539 {
1540         struct iommu_resv_region *resv;
1541         struct vfio_iova *n, *next;
1542
1543         list_for_each_entry(resv, resv_regions, list) {
1544                 phys_addr_t start, end;
1545
1546                 if (resv->type == IOMMU_RESV_DIRECT_RELAXABLE)
1547                         continue;
1548
1549                 start = resv->start;
1550                 end = resv->start + resv->length - 1;
1551
1552                 list_for_each_entry_safe(n, next, iova, list) {
1553                         int ret = 0;
1554
1555                         /* No overlap */
1556                         if (start > n->end || end < n->start)
1557                                 continue;
1558                         /*
1559                          * Insert a new node if current node overlaps with the
1560                          * reserve region to exlude that from valid iova range.
1561                          * Note that, new node is inserted before the current
1562                          * node and finally the current node is deleted keeping
1563                          * the list updated and sorted.
1564                          */
1565                         if (start > n->start)
1566                                 ret = vfio_iommu_iova_insert(&n->list, n->start,
1567                                                              start - 1);
1568                         if (!ret && end < n->end)
1569                                 ret = vfio_iommu_iova_insert(&n->list, end + 1,
1570                                                              n->end);
1571                         if (ret)
1572                                 return ret;
1573
1574                         list_del(&n->list);
1575                         kfree(n);
1576                 }
1577         }
1578
1579         if (list_empty(iova))
1580                 return -EINVAL;
1581
1582         return 0;
1583 }
1584
1585 static void vfio_iommu_resv_free(struct list_head *resv_regions)
1586 {
1587         struct iommu_resv_region *n, *next;
1588
1589         list_for_each_entry_safe(n, next, resv_regions, list) {
1590                 list_del(&n->list);
1591                 kfree(n);
1592         }
1593 }
1594
1595 static void vfio_iommu_iova_free(struct list_head *iova)
1596 {
1597         struct vfio_iova *n, *next;
1598
1599         list_for_each_entry_safe(n, next, iova, list) {
1600                 list_del(&n->list);
1601                 kfree(n);
1602         }
1603 }
1604
1605 static int vfio_iommu_iova_get_copy(struct vfio_iommu *iommu,
1606                                     struct list_head *iova_copy)
1607 {
1608         struct list_head *iova = &iommu->iova_list;
1609         struct vfio_iova *n;
1610         int ret;
1611
1612         list_for_each_entry(n, iova, list) {
1613                 ret = vfio_iommu_iova_insert(iova_copy, n->start, n->end);
1614                 if (ret)
1615                         goto out_free;
1616         }
1617
1618         return 0;
1619
1620 out_free:
1621         vfio_iommu_iova_free(iova_copy);
1622         return ret;
1623 }
1624
1625 static void vfio_iommu_iova_insert_copy(struct vfio_iommu *iommu,
1626                                         struct list_head *iova_copy)
1627 {
1628         struct list_head *iova = &iommu->iova_list;
1629
1630         vfio_iommu_iova_free(iova);
1631
1632         list_splice_tail(iova_copy, iova);
1633 }
1634 static int vfio_iommu_type1_attach_group(void *iommu_data,
1635                                          struct iommu_group *iommu_group)
1636 {
1637         struct vfio_iommu *iommu = iommu_data;
1638         struct vfio_group *group;
1639         struct vfio_domain *domain, *d;
1640         struct bus_type *bus = NULL;
1641         int ret;
1642         bool resv_msi, msi_remap;
1643         phys_addr_t resv_msi_base = 0;
1644         struct iommu_domain_geometry geo;
1645         LIST_HEAD(iova_copy);
1646         LIST_HEAD(group_resv_regions);
1647
1648         mutex_lock(&iommu->lock);
1649
1650         list_for_each_entry(d, &iommu->domain_list, next) {
1651                 if (find_iommu_group(d, iommu_group)) {
1652                         mutex_unlock(&iommu->lock);
1653                         return -EINVAL;
1654                 }
1655         }
1656
1657         if (iommu->external_domain) {
1658                 if (find_iommu_group(iommu->external_domain, iommu_group)) {
1659                         mutex_unlock(&iommu->lock);
1660                         return -EINVAL;
1661                 }
1662         }
1663
1664         group = kzalloc(sizeof(*group), GFP_KERNEL);
1665         domain = kzalloc(sizeof(*domain), GFP_KERNEL);
1666         if (!group || !domain) {
1667                 ret = -ENOMEM;
1668                 goto out_free;
1669         }
1670
1671         group->iommu_group = iommu_group;
1672
1673         /* Determine bus_type in order to allocate a domain */
1674         ret = iommu_group_for_each_dev(iommu_group, &bus, vfio_bus_type);
1675         if (ret)
1676                 goto out_free;
1677
1678         if (vfio_bus_is_mdev(bus)) {
1679                 struct device *iommu_device = NULL;
1680
1681                 group->mdev_group = true;
1682
1683                 /* Determine the isolation type */
1684                 ret = iommu_group_for_each_dev(iommu_group, &iommu_device,
1685                                                vfio_mdev_iommu_device);
1686                 if (ret || !iommu_device) {
1687                         if (!iommu->external_domain) {
1688                                 INIT_LIST_HEAD(&domain->group_list);
1689                                 iommu->external_domain = domain;
1690                         } else {
1691                                 kfree(domain);
1692                         }
1693
1694                         list_add(&group->next,
1695                                  &iommu->external_domain->group_list);
1696                         mutex_unlock(&iommu->lock);
1697
1698                         return 0;
1699                 }
1700
1701                 bus = iommu_device->bus;
1702         }
1703
1704         domain->domain = iommu_domain_alloc(bus);
1705         if (!domain->domain) {
1706                 ret = -EIO;
1707                 goto out_free;
1708         }
1709
1710         if (iommu->nesting) {
1711                 int attr = 1;
1712
1713                 ret = iommu_domain_set_attr(domain->domain, DOMAIN_ATTR_NESTING,
1714                                             &attr);
1715                 if (ret)
1716                         goto out_domain;
1717         }
1718
1719         ret = vfio_iommu_attach_group(domain, group);
1720         if (ret)
1721                 goto out_domain;
1722
1723         /* Get aperture info */
1724         iommu_domain_get_attr(domain->domain, DOMAIN_ATTR_GEOMETRY, &geo);
1725
1726         if (vfio_iommu_aper_conflict(iommu, geo.aperture_start,
1727                                      geo.aperture_end)) {
1728                 ret = -EINVAL;
1729                 goto out_detach;
1730         }
1731
1732         ret = iommu_get_group_resv_regions(iommu_group, &group_resv_regions);
1733         if (ret)
1734                 goto out_detach;
1735
1736         if (vfio_iommu_resv_conflict(iommu, &group_resv_regions)) {
1737                 ret = -EINVAL;
1738                 goto out_detach;
1739         }
1740
1741         /*
1742          * We don't want to work on the original iova list as the list
1743          * gets modified and in case of failure we have to retain the
1744          * original list. Get a copy here.
1745          */
1746         ret = vfio_iommu_iova_get_copy(iommu, &iova_copy);
1747         if (ret)
1748                 goto out_detach;
1749
1750         ret = vfio_iommu_aper_resize(&iova_copy, geo.aperture_start,
1751                                      geo.aperture_end);
1752         if (ret)
1753                 goto out_detach;
1754
1755         ret = vfio_iommu_resv_exclude(&iova_copy, &group_resv_regions);
1756         if (ret)
1757                 goto out_detach;
1758
1759         resv_msi = vfio_iommu_has_sw_msi(&group_resv_regions, &resv_msi_base);
1760
1761         INIT_LIST_HEAD(&domain->group_list);
1762         list_add(&group->next, &domain->group_list);
1763
1764         msi_remap = irq_domain_check_msi_remap() ||
1765                     iommu_capable(bus, IOMMU_CAP_INTR_REMAP);
1766
1767         if (!allow_unsafe_interrupts && !msi_remap) {
1768                 pr_warn("%s: No interrupt remapping support.  Use the module param \"allow_unsafe_interrupts\" to enable VFIO IOMMU support on this platform\n",
1769                        __func__);
1770                 ret = -EPERM;
1771                 goto out_detach;
1772         }
1773
1774         if (iommu_capable(bus, IOMMU_CAP_CACHE_COHERENCY))
1775                 domain->prot |= IOMMU_CACHE;
1776
1777         /*
1778          * Try to match an existing compatible domain.  We don't want to
1779          * preclude an IOMMU driver supporting multiple bus_types and being
1780          * able to include different bus_types in the same IOMMU domain, so
1781          * we test whether the domains use the same iommu_ops rather than
1782          * testing if they're on the same bus_type.
1783          */
1784         list_for_each_entry(d, &iommu->domain_list, next) {
1785                 if (d->domain->ops == domain->domain->ops &&
1786                     d->prot == domain->prot) {
1787                         vfio_iommu_detach_group(domain, group);
1788                         if (!vfio_iommu_attach_group(d, group)) {
1789                                 list_add(&group->next, &d->group_list);
1790                                 iommu_domain_free(domain->domain);
1791                                 kfree(domain);
1792                                 goto done;
1793                         }
1794
1795                         ret = vfio_iommu_attach_group(domain, group);
1796                         if (ret)
1797                                 goto out_domain;
1798                 }
1799         }
1800
1801         vfio_test_domain_fgsp(domain);
1802
1803         /* replay mappings on new domains */
1804         ret = vfio_iommu_replay(iommu, domain);
1805         if (ret)
1806                 goto out_detach;
1807
1808         if (resv_msi) {
1809                 ret = iommu_get_msi_cookie(domain->domain, resv_msi_base);
1810                 if (ret)
1811                         goto out_detach;
1812         }
1813
1814         list_add(&domain->next, &iommu->domain_list);
1815 done:
1816         /* Delete the old one and insert new iova list */
1817         vfio_iommu_iova_insert_copy(iommu, &iova_copy);
1818         mutex_unlock(&iommu->lock);
1819         vfio_iommu_resv_free(&group_resv_regions);
1820
1821         return 0;
1822
1823 out_detach:
1824         vfio_iommu_detach_group(domain, group);
1825 out_domain:
1826         iommu_domain_free(domain->domain);
1827         vfio_iommu_iova_free(&iova_copy);
1828         vfio_iommu_resv_free(&group_resv_regions);
1829 out_free:
1830         kfree(domain);
1831         kfree(group);
1832         mutex_unlock(&iommu->lock);
1833         return ret;
1834 }
1835
1836 static void vfio_iommu_unmap_unpin_all(struct vfio_iommu *iommu)
1837 {
1838         struct rb_node *node;
1839
1840         while ((node = rb_first(&iommu->dma_list)))
1841                 vfio_remove_dma(iommu, rb_entry(node, struct vfio_dma, node));
1842 }
1843
1844 static void vfio_iommu_unmap_unpin_reaccount(struct vfio_iommu *iommu)
1845 {
1846         struct rb_node *n, *p;
1847
1848         n = rb_first(&iommu->dma_list);
1849         for (; n; n = rb_next(n)) {
1850                 struct vfio_dma *dma;
1851                 long locked = 0, unlocked = 0;
1852
1853                 dma = rb_entry(n, struct vfio_dma, node);
1854                 unlocked += vfio_unmap_unpin(iommu, dma, false);
1855                 p = rb_first(&dma->pfn_list);
1856                 for (; p; p = rb_next(p)) {
1857                         struct vfio_pfn *vpfn = rb_entry(p, struct vfio_pfn,
1858                                                          node);
1859
1860                         if (!is_invalid_reserved_pfn(vpfn->pfn))
1861                                 locked++;
1862                 }
1863                 vfio_lock_acct(dma, locked - unlocked, true);
1864         }
1865 }
1866
1867 static void vfio_sanity_check_pfn_list(struct vfio_iommu *iommu)
1868 {
1869         struct rb_node *n;
1870
1871         n = rb_first(&iommu->dma_list);
1872         for (; n; n = rb_next(n)) {
1873                 struct vfio_dma *dma;
1874
1875                 dma = rb_entry(n, struct vfio_dma, node);
1876
1877                 if (WARN_ON(!RB_EMPTY_ROOT(&dma->pfn_list)))
1878                         break;
1879         }
1880         /* mdev vendor driver must unregister notifier */
1881         WARN_ON(iommu->notifier.head);
1882 }
1883
1884 /*
1885  * Called when a domain is removed in detach. It is possible that
1886  * the removed domain decided the iova aperture window. Modify the
1887  * iova aperture with the smallest window among existing domains.
1888  */
1889 static void vfio_iommu_aper_expand(struct vfio_iommu *iommu,
1890                                    struct list_head *iova_copy)
1891 {
1892         struct vfio_domain *domain;
1893         struct iommu_domain_geometry geo;
1894         struct vfio_iova *node;
1895         dma_addr_t start = 0;
1896         dma_addr_t end = (dma_addr_t)~0;
1897
1898         if (list_empty(iova_copy))
1899                 return;
1900
1901         list_for_each_entry(domain, &iommu->domain_list, next) {
1902                 iommu_domain_get_attr(domain->domain, DOMAIN_ATTR_GEOMETRY,
1903                                       &geo);
1904                 if (geo.aperture_start > start)
1905                         start = geo.aperture_start;
1906                 if (geo.aperture_end < end)
1907                         end = geo.aperture_end;
1908         }
1909
1910         /* Modify aperture limits. The new aper is either same or bigger */
1911         node = list_first_entry(iova_copy, struct vfio_iova, list);
1912         node->start = start;
1913         node = list_last_entry(iova_copy, struct vfio_iova, list);
1914         node->end = end;
1915 }
1916
1917 /*
1918  * Called when a group is detached. The reserved regions for that
1919  * group can be part of valid iova now. But since reserved regions
1920  * may be duplicated among groups, populate the iova valid regions
1921  * list again.
1922  */
1923 static int vfio_iommu_resv_refresh(struct vfio_iommu *iommu,
1924                                    struct list_head *iova_copy)
1925 {
1926         struct vfio_domain *d;
1927         struct vfio_group *g;
1928         struct vfio_iova *node;
1929         dma_addr_t start, end;
1930         LIST_HEAD(resv_regions);
1931         int ret;
1932
1933         if (list_empty(iova_copy))
1934                 return -EINVAL;
1935
1936         list_for_each_entry(d, &iommu->domain_list, next) {
1937                 list_for_each_entry(g, &d->group_list, next) {
1938                         ret = iommu_get_group_resv_regions(g->iommu_group,
1939                                                            &resv_regions);
1940                         if (ret)
1941                                 goto done;
1942                 }
1943         }
1944
1945         node = list_first_entry(iova_copy, struct vfio_iova, list);
1946         start = node->start;
1947         node = list_last_entry(iova_copy, struct vfio_iova, list);
1948         end = node->end;
1949
1950         /* purge the iova list and create new one */
1951         vfio_iommu_iova_free(iova_copy);
1952
1953         ret = vfio_iommu_aper_resize(iova_copy, start, end);
1954         if (ret)
1955                 goto done;
1956
1957         /* Exclude current reserved regions from iova ranges */
1958         ret = vfio_iommu_resv_exclude(iova_copy, &resv_regions);
1959 done:
1960         vfio_iommu_resv_free(&resv_regions);
1961         return ret;
1962 }
1963
1964 static void vfio_iommu_type1_detach_group(void *iommu_data,
1965                                           struct iommu_group *iommu_group)
1966 {
1967         struct vfio_iommu *iommu = iommu_data;
1968         struct vfio_domain *domain;
1969         struct vfio_group *group;
1970         LIST_HEAD(iova_copy);
1971
1972         mutex_lock(&iommu->lock);
1973
1974         if (iommu->external_domain) {
1975                 group = find_iommu_group(iommu->external_domain, iommu_group);
1976                 if (group) {
1977                         list_del(&group->next);
1978                         kfree(group);
1979
1980                         if (list_empty(&iommu->external_domain->group_list)) {
1981                                 vfio_sanity_check_pfn_list(iommu);
1982
1983                                 if (!IS_IOMMU_CAP_DOMAIN_IN_CONTAINER(iommu))
1984                                         vfio_iommu_unmap_unpin_all(iommu);
1985
1986                                 kfree(iommu->external_domain);
1987                                 iommu->external_domain = NULL;
1988                         }
1989                         goto detach_group_done;
1990                 }
1991         }
1992
1993         /*
1994          * Get a copy of iova list. This will be used to update
1995          * and to replace the current one later. Please note that
1996          * we will leave the original list as it is if update fails.
1997          */
1998         vfio_iommu_iova_get_copy(iommu, &iova_copy);
1999
2000         list_for_each_entry(domain, &iommu->domain_list, next) {
2001                 group = find_iommu_group(domain, iommu_group);
2002                 if (!group)
2003                         continue;
2004
2005                 vfio_iommu_detach_group(domain, group);
2006                 list_del(&group->next);
2007                 kfree(group);
2008                 /*
2009                  * Group ownership provides privilege, if the group list is
2010                  * empty, the domain goes away. If it's the last domain with
2011                  * iommu and external domain doesn't exist, then all the
2012                  * mappings go away too. If it's the last domain with iommu and
2013                  * external domain exist, update accounting
2014                  */
2015                 if (list_empty(&domain->group_list)) {
2016                         if (list_is_singular(&iommu->domain_list)) {
2017                                 if (!iommu->external_domain)
2018                                         vfio_iommu_unmap_unpin_all(iommu);
2019                                 else
2020                                         vfio_iommu_unmap_unpin_reaccount(iommu);
2021                         }
2022                         iommu_domain_free(domain->domain);
2023                         list_del(&domain->next);
2024                         kfree(domain);
2025                         vfio_iommu_aper_expand(iommu, &iova_copy);
2026                 }
2027                 break;
2028         }
2029
2030         if (!vfio_iommu_resv_refresh(iommu, &iova_copy))
2031                 vfio_iommu_iova_insert_copy(iommu, &iova_copy);
2032         else
2033                 vfio_iommu_iova_free(&iova_copy);
2034
2035 detach_group_done:
2036         mutex_unlock(&iommu->lock);
2037 }
2038
2039 static void *vfio_iommu_type1_open(unsigned long arg)
2040 {
2041         struct vfio_iommu *iommu;
2042
2043         iommu = kzalloc(sizeof(*iommu), GFP_KERNEL);
2044         if (!iommu)
2045                 return ERR_PTR(-ENOMEM);
2046
2047         switch (arg) {
2048         case VFIO_TYPE1_IOMMU:
2049                 break;
2050         case VFIO_TYPE1_NESTING_IOMMU:
2051                 iommu->nesting = true;
2052                 /* fall through */
2053         case VFIO_TYPE1v2_IOMMU:
2054                 iommu->v2 = true;
2055                 break;
2056         default:
2057                 kfree(iommu);
2058                 return ERR_PTR(-EINVAL);
2059         }
2060
2061         INIT_LIST_HEAD(&iommu->domain_list);
2062         INIT_LIST_HEAD(&iommu->iova_list);
2063         iommu->dma_list = RB_ROOT;
2064         iommu->dma_avail = dma_entry_limit;
2065         mutex_init(&iommu->lock);
2066         BLOCKING_INIT_NOTIFIER_HEAD(&iommu->notifier);
2067
2068         return iommu;
2069 }
2070
2071 static void vfio_release_domain(struct vfio_domain *domain, bool external)
2072 {
2073         struct vfio_group *group, *group_tmp;
2074
2075         list_for_each_entry_safe(group, group_tmp,
2076                                  &domain->group_list, next) {
2077                 if (!external)
2078                         vfio_iommu_detach_group(domain, group);
2079                 list_del(&group->next);
2080                 kfree(group);
2081         }
2082
2083         if (!external)
2084                 iommu_domain_free(domain->domain);
2085 }
2086
2087 static void vfio_iommu_type1_release(void *iommu_data)
2088 {
2089         struct vfio_iommu *iommu = iommu_data;
2090         struct vfio_domain *domain, *domain_tmp;
2091
2092         if (iommu->external_domain) {
2093                 vfio_release_domain(iommu->external_domain, true);
2094                 vfio_sanity_check_pfn_list(iommu);
2095                 kfree(iommu->external_domain);
2096         }
2097
2098         vfio_iommu_unmap_unpin_all(iommu);
2099
2100         list_for_each_entry_safe(domain, domain_tmp,
2101                                  &iommu->domain_list, next) {
2102                 vfio_release_domain(domain, false);
2103                 list_del(&domain->next);
2104                 kfree(domain);
2105         }
2106
2107         vfio_iommu_iova_free(&iommu->iova_list);
2108
2109         kfree(iommu);
2110 }
2111
2112 static int vfio_domains_have_iommu_cache(struct vfio_iommu *iommu)
2113 {
2114         struct vfio_domain *domain;
2115         int ret = 1;
2116
2117         mutex_lock(&iommu->lock);
2118         list_for_each_entry(domain, &iommu->domain_list, next) {
2119                 if (!(domain->prot & IOMMU_CACHE)) {
2120                         ret = 0;
2121                         break;
2122                 }
2123         }
2124         mutex_unlock(&iommu->lock);
2125
2126         return ret;
2127 }
2128
2129 static int vfio_iommu_iova_add_cap(struct vfio_info_cap *caps,
2130                  struct vfio_iommu_type1_info_cap_iova_range *cap_iovas,
2131                  size_t size)
2132 {
2133         struct vfio_info_cap_header *header;
2134         struct vfio_iommu_type1_info_cap_iova_range *iova_cap;
2135
2136         header = vfio_info_cap_add(caps, size,
2137                                    VFIO_IOMMU_TYPE1_INFO_CAP_IOVA_RANGE, 1);
2138         if (IS_ERR(header))
2139                 return PTR_ERR(header);
2140
2141         iova_cap = container_of(header,
2142                                 struct vfio_iommu_type1_info_cap_iova_range,
2143                                 header);
2144         iova_cap->nr_iovas = cap_iovas->nr_iovas;
2145         memcpy(iova_cap->iova_ranges, cap_iovas->iova_ranges,
2146                cap_iovas->nr_iovas * sizeof(*cap_iovas->iova_ranges));
2147         return 0;
2148 }
2149
2150 static int vfio_iommu_iova_build_caps(struct vfio_iommu *iommu,
2151                                       struct vfio_info_cap *caps)
2152 {
2153         struct vfio_iommu_type1_info_cap_iova_range *cap_iovas;
2154         struct vfio_iova *iova;
2155         size_t size;
2156         int iovas = 0, i = 0, ret;
2157
2158         mutex_lock(&iommu->lock);
2159
2160         list_for_each_entry(iova, &iommu->iova_list, list)
2161                 iovas++;
2162
2163         if (!iovas) {
2164                 /*
2165                  * Return 0 as a container with a single mdev device
2166                  * will have an empty list
2167                  */
2168                 ret = 0;
2169                 goto out_unlock;
2170         }
2171
2172         size = sizeof(*cap_iovas) + (iovas * sizeof(*cap_iovas->iova_ranges));
2173
2174         cap_iovas = kzalloc(size, GFP_KERNEL);
2175         if (!cap_iovas) {
2176                 ret = -ENOMEM;
2177                 goto out_unlock;
2178         }
2179
2180         cap_iovas->nr_iovas = iovas;
2181
2182         list_for_each_entry(iova, &iommu->iova_list, list) {
2183                 cap_iovas->iova_ranges[i].start = iova->start;
2184                 cap_iovas->iova_ranges[i].end = iova->end;
2185                 i++;
2186         }
2187
2188         ret = vfio_iommu_iova_add_cap(caps, cap_iovas, size);
2189
2190         kfree(cap_iovas);
2191 out_unlock:
2192         mutex_unlock(&iommu->lock);
2193         return ret;
2194 }
2195
2196 static long vfio_iommu_type1_ioctl(void *iommu_data,
2197                                    unsigned int cmd, unsigned long arg)
2198 {
2199         struct vfio_iommu *iommu = iommu_data;
2200         unsigned long minsz;
2201
2202         if (cmd == VFIO_CHECK_EXTENSION) {
2203                 switch (arg) {
2204                 case VFIO_TYPE1_IOMMU:
2205                 case VFIO_TYPE1v2_IOMMU:
2206                 case VFIO_TYPE1_NESTING_IOMMU:
2207                         return 1;
2208                 case VFIO_DMA_CC_IOMMU:
2209                         if (!iommu)
2210                                 return 0;
2211                         return vfio_domains_have_iommu_cache(iommu);
2212                 default:
2213                         return 0;
2214                 }
2215         } else if (cmd == VFIO_IOMMU_GET_INFO) {
2216                 struct vfio_iommu_type1_info info;
2217                 struct vfio_info_cap caps = { .buf = NULL, .size = 0 };
2218                 unsigned long capsz;
2219                 int ret;
2220
2221                 minsz = offsetofend(struct vfio_iommu_type1_info, iova_pgsizes);
2222
2223                 /* For backward compatibility, cannot require this */
2224                 capsz = offsetofend(struct vfio_iommu_type1_info, cap_offset);
2225
2226                 if (copy_from_user(&info, (void __user *)arg, minsz))
2227                         return -EFAULT;
2228
2229                 if (info.argsz < minsz)
2230                         return -EINVAL;
2231
2232                 if (info.argsz >= capsz) {
2233                         minsz = capsz;
2234                         info.cap_offset = 0; /* output, no-recopy necessary */
2235                 }
2236
2237                 info.flags = VFIO_IOMMU_INFO_PGSIZES;
2238
2239                 info.iova_pgsizes = vfio_pgsize_bitmap(iommu);
2240
2241                 ret = vfio_iommu_iova_build_caps(iommu, &caps);
2242                 if (ret)
2243                         return ret;
2244
2245                 if (caps.size) {
2246                         info.flags |= VFIO_IOMMU_INFO_CAPS;
2247
2248                         if (info.argsz < sizeof(info) + caps.size) {
2249                                 info.argsz = sizeof(info) + caps.size;
2250                         } else {
2251                                 vfio_info_cap_shift(&caps, sizeof(info));
2252                                 if (copy_to_user((void __user *)arg +
2253                                                 sizeof(info), caps.buf,
2254                                                 caps.size)) {
2255                                         kfree(caps.buf);
2256                                         return -EFAULT;
2257                                 }
2258                                 info.cap_offset = sizeof(info);
2259                         }
2260
2261                         kfree(caps.buf);
2262                 }
2263
2264                 return copy_to_user((void __user *)arg, &info, minsz) ?
2265                         -EFAULT : 0;
2266
2267         } else if (cmd == VFIO_IOMMU_MAP_DMA) {
2268                 struct vfio_iommu_type1_dma_map map;
2269                 uint32_t mask = VFIO_DMA_MAP_FLAG_READ |
2270                                 VFIO_DMA_MAP_FLAG_WRITE;
2271
2272                 minsz = offsetofend(struct vfio_iommu_type1_dma_map, size);
2273
2274                 if (copy_from_user(&map, (void __user *)arg, minsz))
2275                         return -EFAULT;
2276
2277                 if (map.argsz < minsz || map.flags & ~mask)
2278                         return -EINVAL;
2279
2280                 return vfio_dma_do_map(iommu, &map);
2281
2282         } else if (cmd == VFIO_IOMMU_UNMAP_DMA) {
2283                 struct vfio_iommu_type1_dma_unmap unmap;
2284                 long ret;
2285
2286                 minsz = offsetofend(struct vfio_iommu_type1_dma_unmap, size);
2287
2288                 if (copy_from_user(&unmap, (void __user *)arg, minsz))
2289                         return -EFAULT;
2290
2291                 if (unmap.argsz < minsz || unmap.flags)
2292                         return -EINVAL;
2293
2294                 ret = vfio_dma_do_unmap(iommu, &unmap);
2295                 if (ret)
2296                         return ret;
2297
2298                 return copy_to_user((void __user *)arg, &unmap, minsz) ?
2299                         -EFAULT : 0;
2300         }
2301
2302         return -ENOTTY;
2303 }
2304
2305 static int vfio_iommu_type1_register_notifier(void *iommu_data,
2306                                               unsigned long *events,
2307                                               struct notifier_block *nb)
2308 {
2309         struct vfio_iommu *iommu = iommu_data;
2310
2311         /* clear known events */
2312         *events &= ~VFIO_IOMMU_NOTIFY_DMA_UNMAP;
2313
2314         /* refuse to register if still events remaining */
2315         if (*events)
2316                 return -EINVAL;
2317
2318         return blocking_notifier_chain_register(&iommu->notifier, nb);
2319 }
2320
2321 static int vfio_iommu_type1_unregister_notifier(void *iommu_data,
2322                                                 struct notifier_block *nb)
2323 {
2324         struct vfio_iommu *iommu = iommu_data;
2325
2326         return blocking_notifier_chain_unregister(&iommu->notifier, nb);
2327 }
2328
2329 static const struct vfio_iommu_driver_ops vfio_iommu_driver_ops_type1 = {
2330         .name                   = "vfio-iommu-type1",
2331         .owner                  = THIS_MODULE,
2332         .open                   = vfio_iommu_type1_open,
2333         .release                = vfio_iommu_type1_release,
2334         .ioctl                  = vfio_iommu_type1_ioctl,
2335         .attach_group           = vfio_iommu_type1_attach_group,
2336         .detach_group           = vfio_iommu_type1_detach_group,
2337         .pin_pages              = vfio_iommu_type1_pin_pages,
2338         .unpin_pages            = vfio_iommu_type1_unpin_pages,
2339         .register_notifier      = vfio_iommu_type1_register_notifier,
2340         .unregister_notifier    = vfio_iommu_type1_unregister_notifier,
2341 };
2342
2343 static int __init vfio_iommu_type1_init(void)
2344 {
2345         return vfio_register_iommu_driver(&vfio_iommu_driver_ops_type1);
2346 }
2347
2348 static void __exit vfio_iommu_type1_cleanup(void)
2349 {
2350         vfio_unregister_iommu_driver(&vfio_iommu_driver_ops_type1);
2351 }
2352
2353 module_init(vfio_iommu_type1_init);
2354 module_exit(vfio_iommu_type1_cleanup);
2355
2356 MODULE_VERSION(DRIVER_VERSION);
2357 MODULE_LICENSE("GPL v2");
2358 MODULE_AUTHOR(DRIVER_AUTHOR);
2359 MODULE_DESCRIPTION(DRIVER_DESC);