Linux-libre 4.4.222-gnu
[librecmc/linux-libre.git] / drivers / vfio / vfio_iommu_type1.c
1 /*
2  * VFIO: IOMMU DMA mapping support for Type1 IOMMU
3  *
4  * Copyright (C) 2012 Red Hat, Inc.  All rights reserved.
5  *     Author: Alex Williamson <alex.williamson@redhat.com>
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License version 2 as
9  * published by the Free Software Foundation.
10  *
11  * Derived from original vfio:
12  * Copyright 2010 Cisco Systems, Inc.  All rights reserved.
13  * Author: Tom Lyon, pugs@cisco.com
14  *
15  * We arbitrarily define a Type1 IOMMU as one matching the below code.
16  * It could be called the x86 IOMMU as it's designed for AMD-Vi & Intel
17  * VT-d, but that makes it harder to re-use as theoretically anyone
18  * implementing a similar IOMMU could make use of this.  We expect the
19  * IOMMU to support the IOMMU API and have few to no restrictions around
20  * the IOVA range that can be mapped.  The Type1 IOMMU is currently
21  * optimized for relatively static mappings of a userspace process with
22  * userpsace pages pinned into memory.  We also assume devices and IOMMU
23  * domains are PCI based as the IOMMU API is still centered around a
24  * device/bus interface rather than a group interface.
25  */
26
27 #include <linux/compat.h>
28 #include <linux/device.h>
29 #include <linux/fs.h>
30 #include <linux/iommu.h>
31 #include <linux/module.h>
32 #include <linux/mm.h>
33 #include <linux/rbtree.h>
34 #include <linux/sched.h>
35 #include <linux/slab.h>
36 #include <linux/uaccess.h>
37 #include <linux/vfio.h>
38 #include <linux/workqueue.h>
39
40 #define DRIVER_VERSION  "0.2"
41 #define DRIVER_AUTHOR   "Alex Williamson <alex.williamson@redhat.com>"
42 #define DRIVER_DESC     "Type1 IOMMU driver for VFIO"
43
44 static bool allow_unsafe_interrupts;
45 module_param_named(allow_unsafe_interrupts,
46                    allow_unsafe_interrupts, bool, S_IRUGO | S_IWUSR);
47 MODULE_PARM_DESC(allow_unsafe_interrupts,
48                  "Enable VFIO IOMMU support for on platforms without interrupt remapping support.");
49
50 static bool disable_hugepages;
51 module_param_named(disable_hugepages,
52                    disable_hugepages, bool, S_IRUGO | S_IWUSR);
53 MODULE_PARM_DESC(disable_hugepages,
54                  "Disable VFIO IOMMU support for IOMMU hugepages.");
55
56 static unsigned int dma_entry_limit __read_mostly = U16_MAX;
57 module_param_named(dma_entry_limit, dma_entry_limit, uint, 0644);
58 MODULE_PARM_DESC(dma_entry_limit,
59                  "Maximum number of user DMA mappings per container (65535).");
60
61 struct vfio_iommu {
62         struct list_head        domain_list;
63         struct mutex            lock;
64         struct rb_root          dma_list;
65         unsigned int            dma_avail;
66         bool                    v2;
67         bool                    nesting;
68 };
69
70 struct vfio_domain {
71         struct iommu_domain     *domain;
72         struct list_head        next;
73         struct list_head        group_list;
74         int                     prot;           /* IOMMU_CACHE */
75         bool                    fgsp;           /* Fine-grained super pages */
76 };
77
78 struct vfio_dma {
79         struct rb_node          node;
80         dma_addr_t              iova;           /* Device address */
81         unsigned long           vaddr;          /* Process virtual addr */
82         size_t                  size;           /* Map size (bytes) */
83         int                     prot;           /* IOMMU_READ/WRITE */
84 };
85
86 struct vfio_group {
87         struct iommu_group      *iommu_group;
88         struct list_head        next;
89 };
90
91 /*
92  * This code handles mapping and unmapping of user data buffers
93  * into DMA'ble space using the IOMMU
94  */
95
96 static struct vfio_dma *vfio_find_dma(struct vfio_iommu *iommu,
97                                       dma_addr_t start, size_t size)
98 {
99         struct rb_node *node = iommu->dma_list.rb_node;
100
101         while (node) {
102                 struct vfio_dma *dma = rb_entry(node, struct vfio_dma, node);
103
104                 if (start + size <= dma->iova)
105                         node = node->rb_left;
106                 else if (start >= dma->iova + dma->size)
107                         node = node->rb_right;
108                 else
109                         return dma;
110         }
111
112         return NULL;
113 }
114
115 static void vfio_link_dma(struct vfio_iommu *iommu, struct vfio_dma *new)
116 {
117         struct rb_node **link = &iommu->dma_list.rb_node, *parent = NULL;
118         struct vfio_dma *dma;
119
120         while (*link) {
121                 parent = *link;
122                 dma = rb_entry(parent, struct vfio_dma, node);
123
124                 if (new->iova + new->size <= dma->iova)
125                         link = &(*link)->rb_left;
126                 else
127                         link = &(*link)->rb_right;
128         }
129
130         rb_link_node(&new->node, parent, link);
131         rb_insert_color(&new->node, &iommu->dma_list);
132 }
133
134 static void vfio_unlink_dma(struct vfio_iommu *iommu, struct vfio_dma *old)
135 {
136         rb_erase(&old->node, &iommu->dma_list);
137 }
138
139 static int vfio_lock_acct(long npage, bool *lock_cap)
140 {
141         int ret = 0;
142
143         if (!npage)
144                 return 0;
145
146         if (!current->mm)
147                 return -ESRCH; /* process exited */
148
149         down_write(&current->mm->mmap_sem);
150         if (npage > 0) {
151                 if (lock_cap ? !*lock_cap : !capable(CAP_IPC_LOCK)) {
152                         unsigned long limit;
153
154                         limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
155
156                         if (current->mm->locked_vm + npage > limit)
157                                 ret = -ENOMEM;
158                 }
159         }
160
161         if (!ret)
162                 current->mm->locked_vm += npage;
163
164         up_write(&current->mm->mmap_sem);
165
166         return ret;
167 }
168
169 /*
170  * Some mappings aren't backed by a struct page, for example an mmap'd
171  * MMIO range for our own or another device.  These use a different
172  * pfn conversion and shouldn't be tracked as locked pages.
173  */
174 static bool is_invalid_reserved_pfn(unsigned long pfn)
175 {
176         if (pfn_valid(pfn)) {
177                 bool reserved;
178                 struct page *tail = pfn_to_page(pfn);
179                 struct page *head = compound_head(tail);
180                 reserved = !!(PageReserved(head));
181                 if (head != tail) {
182                         /*
183                          * "head" is not a dangling pointer
184                          * (compound_head takes care of that)
185                          * but the hugepage may have been split
186                          * from under us (and we may not hold a
187                          * reference count on the head page so it can
188                          * be reused before we run PageReferenced), so
189                          * we've to check PageTail before returning
190                          * what we just read.
191                          */
192                         smp_rmb();
193                         if (PageTail(tail))
194                                 return reserved;
195                 }
196                 return PageReserved(tail);
197         }
198
199         return true;
200 }
201
202 static int put_pfn(unsigned long pfn, int prot)
203 {
204         if (!is_invalid_reserved_pfn(pfn)) {
205                 struct page *page = pfn_to_page(pfn);
206                 if (prot & IOMMU_WRITE)
207                         SetPageDirty(page);
208                 put_page(page);
209                 return 1;
210         }
211         return 0;
212 }
213
214 static int vaddr_get_pfn(unsigned long vaddr, int prot, unsigned long *pfn)
215 {
216         struct page *page[1];
217         struct vm_area_struct *vma;
218         int ret = -EFAULT;
219
220         if (get_user_pages_fast(vaddr, 1, !!(prot & IOMMU_WRITE), page) == 1) {
221                 *pfn = page_to_pfn(page[0]);
222                 return 0;
223         }
224
225         down_read(&current->mm->mmap_sem);
226
227         vma = find_vma_intersection(current->mm, vaddr, vaddr + 1);
228
229         if (vma && vma->vm_flags & VM_PFNMAP) {
230                 if (!follow_pfn(vma, vaddr, pfn) &&
231                     is_invalid_reserved_pfn(*pfn))
232                         ret = 0;
233         }
234
235         up_read(&current->mm->mmap_sem);
236
237         return ret;
238 }
239
240 /*
241  * Attempt to pin pages.  We really don't want to track all the pfns and
242  * the iommu can only map chunks of consecutive pfns anyway, so get the
243  * first page and all consecutive pages with the same locking.
244  */
245 static long vfio_pin_pages(unsigned long vaddr, long npage,
246                            int prot, unsigned long *pfn_base)
247 {
248         unsigned long pfn = 0, limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
249         bool lock_cap = capable(CAP_IPC_LOCK);
250         long ret, i = 1;
251         bool rsvd;
252
253         if (!current->mm)
254                 return -ENODEV;
255
256         ret = vaddr_get_pfn(vaddr, prot, pfn_base);
257         if (ret)
258                 return ret;
259
260         rsvd = is_invalid_reserved_pfn(*pfn_base);
261
262         if (!rsvd && !lock_cap && current->mm->locked_vm + 1 > limit) {
263                 put_pfn(*pfn_base, prot);
264                 pr_warn("%s: RLIMIT_MEMLOCK (%ld) exceeded\n", __func__,
265                         limit << PAGE_SHIFT);
266                 return -ENOMEM;
267         }
268
269         if (unlikely(disable_hugepages))
270                 goto out;
271
272         /* Lock all the consecutive pages from pfn_base */
273         for (vaddr += PAGE_SIZE; i < npage; i++, vaddr += PAGE_SIZE) {
274                 ret = vaddr_get_pfn(vaddr, prot, &pfn);
275                 if (ret)
276                         break;
277
278                 if (pfn != *pfn_base + i ||
279                     rsvd != is_invalid_reserved_pfn(pfn)) {
280                         put_pfn(pfn, prot);
281                         break;
282                 }
283
284                 if (!rsvd && !lock_cap &&
285                     current->mm->locked_vm + i + 1 > limit) {
286                         put_pfn(pfn, prot);
287                         pr_warn("%s: RLIMIT_MEMLOCK (%ld) exceeded\n",
288                                 __func__, limit << PAGE_SHIFT);
289                         ret = -ENOMEM;
290                         goto unpin_out;
291                 }
292         }
293
294 out:
295         if (!rsvd)
296                 ret = vfio_lock_acct(i, &lock_cap);
297
298 unpin_out:
299         if (ret) {
300                 if (!rsvd) {
301                         for (pfn = *pfn_base ; i ; pfn++, i--)
302                                 put_pfn(pfn, prot);
303                 }
304
305                 return ret;
306         }
307
308         return i;
309 }
310
311 static long vfio_unpin_pages(unsigned long pfn, long npage,
312                              int prot, bool do_accounting)
313 {
314         unsigned long unlocked = 0;
315         long i;
316
317         for (i = 0; i < npage; i++)
318                 unlocked += put_pfn(pfn++, prot);
319
320         if (do_accounting)
321                 vfio_lock_acct(-unlocked, NULL);
322
323         return unlocked;
324 }
325
326 static void vfio_unmap_unpin(struct vfio_iommu *iommu, struct vfio_dma *dma)
327 {
328         dma_addr_t iova = dma->iova, end = dma->iova + dma->size;
329         struct vfio_domain *domain, *d;
330         long unlocked = 0;
331
332         if (!dma->size)
333                 return;
334         /*
335          * We use the IOMMU to track the physical addresses, otherwise we'd
336          * need a much more complicated tracking system.  Unfortunately that
337          * means we need to use one of the iommu domains to figure out the
338          * pfns to unpin.  The rest need to be unmapped in advance so we have
339          * no iommu translations remaining when the pages are unpinned.
340          */
341         domain = d = list_first_entry(&iommu->domain_list,
342                                       struct vfio_domain, next);
343
344         list_for_each_entry_continue(d, &iommu->domain_list, next) {
345                 iommu_unmap(d->domain, dma->iova, dma->size);
346                 cond_resched();
347         }
348
349         while (iova < end) {
350                 size_t unmapped, len;
351                 phys_addr_t phys, next;
352
353                 phys = iommu_iova_to_phys(domain->domain, iova);
354                 if (WARN_ON(!phys)) {
355                         iova += PAGE_SIZE;
356                         continue;
357                 }
358
359                 /*
360                  * To optimize for fewer iommu_unmap() calls, each of which
361                  * may require hardware cache flushing, try to find the
362                  * largest contiguous physical memory chunk to unmap.
363                  */
364                 for (len = PAGE_SIZE;
365                      !domain->fgsp && iova + len < end; len += PAGE_SIZE) {
366                         next = iommu_iova_to_phys(domain->domain, iova + len);
367                         if (next != phys + len)
368                                 break;
369                 }
370
371                 unmapped = iommu_unmap(domain->domain, iova, len);
372                 if (WARN_ON(!unmapped))
373                         break;
374
375                 unlocked += vfio_unpin_pages(phys >> PAGE_SHIFT,
376                                              unmapped >> PAGE_SHIFT,
377                                              dma->prot, false);
378                 iova += unmapped;
379
380                 cond_resched();
381         }
382
383         vfio_lock_acct(-unlocked, NULL);
384 }
385
386 static void vfio_remove_dma(struct vfio_iommu *iommu, struct vfio_dma *dma)
387 {
388         vfio_unmap_unpin(iommu, dma);
389         vfio_unlink_dma(iommu, dma);
390         kfree(dma);
391         iommu->dma_avail++;
392 }
393
394 static unsigned long vfio_pgsize_bitmap(struct vfio_iommu *iommu)
395 {
396         struct vfio_domain *domain;
397         unsigned long bitmap = ULONG_MAX;
398
399         mutex_lock(&iommu->lock);
400         list_for_each_entry(domain, &iommu->domain_list, next)
401                 bitmap &= domain->domain->ops->pgsize_bitmap;
402         mutex_unlock(&iommu->lock);
403
404         /*
405          * In case the IOMMU supports page sizes smaller than PAGE_SIZE
406          * we pretend PAGE_SIZE is supported and hide sub-PAGE_SIZE sizes.
407          * That way the user will be able to map/unmap buffers whose size/
408          * start address is aligned with PAGE_SIZE. Pinning code uses that
409          * granularity while iommu driver can use the sub-PAGE_SIZE size
410          * to map the buffer.
411          */
412         if (bitmap & ~PAGE_MASK) {
413                 bitmap &= PAGE_MASK;
414                 bitmap |= PAGE_SIZE;
415         }
416
417         return bitmap;
418 }
419
420 static int vfio_dma_do_unmap(struct vfio_iommu *iommu,
421                              struct vfio_iommu_type1_dma_unmap *unmap)
422 {
423         uint64_t mask;
424         struct vfio_dma *dma;
425         size_t unmapped = 0;
426         int ret = 0;
427
428         mask = ((uint64_t)1 << __ffs(vfio_pgsize_bitmap(iommu))) - 1;
429
430         if (unmap->iova & mask)
431                 return -EINVAL;
432         if (!unmap->size || unmap->size & mask)
433                 return -EINVAL;
434
435         WARN_ON(mask & PAGE_MASK);
436
437         mutex_lock(&iommu->lock);
438
439         /*
440          * vfio-iommu-type1 (v1) - User mappings were coalesced together to
441          * avoid tracking individual mappings.  This means that the granularity
442          * of the original mapping was lost and the user was allowed to attempt
443          * to unmap any range.  Depending on the contiguousness of physical
444          * memory and page sizes supported by the IOMMU, arbitrary unmaps may
445          * or may not have worked.  We only guaranteed unmap granularity
446          * matching the original mapping; even though it was untracked here,
447          * the original mappings are reflected in IOMMU mappings.  This
448          * resulted in a couple unusual behaviors.  First, if a range is not
449          * able to be unmapped, ex. a set of 4k pages that was mapped as a
450          * 2M hugepage into the IOMMU, the unmap ioctl returns success but with
451          * a zero sized unmap.  Also, if an unmap request overlaps the first
452          * address of a hugepage, the IOMMU will unmap the entire hugepage.
453          * This also returns success and the returned unmap size reflects the
454          * actual size unmapped.
455          *
456          * We attempt to maintain compatibility with this "v1" interface, but
457          * we take control out of the hands of the IOMMU.  Therefore, an unmap
458          * request offset from the beginning of the original mapping will
459          * return success with zero sized unmap.  And an unmap request covering
460          * the first iova of mapping will unmap the entire range.
461          *
462          * The v2 version of this interface intends to be more deterministic.
463          * Unmap requests must fully cover previous mappings.  Multiple
464          * mappings may still be unmaped by specifying large ranges, but there
465          * must not be any previous mappings bisected by the range.  An error
466          * will be returned if these conditions are not met.  The v2 interface
467          * will only return success and a size of zero if there were no
468          * mappings within the range.
469          */
470         if (iommu->v2) {
471                 dma = vfio_find_dma(iommu, unmap->iova, 0);
472                 if (dma && dma->iova != unmap->iova) {
473                         ret = -EINVAL;
474                         goto unlock;
475                 }
476                 dma = vfio_find_dma(iommu, unmap->iova + unmap->size - 1, 0);
477                 if (dma && dma->iova + dma->size != unmap->iova + unmap->size) {
478                         ret = -EINVAL;
479                         goto unlock;
480                 }
481         }
482
483         while ((dma = vfio_find_dma(iommu, unmap->iova, unmap->size))) {
484                 if (!iommu->v2 && unmap->iova > dma->iova)
485                         break;
486                 unmapped += dma->size;
487                 vfio_remove_dma(iommu, dma);
488         }
489
490 unlock:
491         mutex_unlock(&iommu->lock);
492
493         /* Report how much was unmapped */
494         unmap->size = unmapped;
495
496         return ret;
497 }
498
499 /*
500  * Turns out AMD IOMMU has a page table bug where it won't map large pages
501  * to a region that previously mapped smaller pages.  This should be fixed
502  * soon, so this is just a temporary workaround to break mappings down into
503  * PAGE_SIZE.  Better to map smaller pages than nothing.
504  */
505 static int map_try_harder(struct vfio_domain *domain, dma_addr_t iova,
506                           unsigned long pfn, long npage, int prot)
507 {
508         long i;
509         int ret;
510
511         for (i = 0; i < npage; i++, pfn++, iova += PAGE_SIZE) {
512                 ret = iommu_map(domain->domain, iova,
513                                 (phys_addr_t)pfn << PAGE_SHIFT,
514                                 PAGE_SIZE, prot | domain->prot);
515                 if (ret)
516                         break;
517         }
518
519         for (; i < npage && i > 0; i--, iova -= PAGE_SIZE)
520                 iommu_unmap(domain->domain, iova, PAGE_SIZE);
521
522         return ret;
523 }
524
525 static int vfio_iommu_map(struct vfio_iommu *iommu, dma_addr_t iova,
526                           unsigned long pfn, long npage, int prot)
527 {
528         struct vfio_domain *d;
529         int ret;
530
531         list_for_each_entry(d, &iommu->domain_list, next) {
532                 ret = iommu_map(d->domain, iova, (phys_addr_t)pfn << PAGE_SHIFT,
533                                 npage << PAGE_SHIFT, prot | d->prot);
534                 if (ret) {
535                         if (ret != -EBUSY ||
536                             map_try_harder(d, iova, pfn, npage, prot))
537                                 goto unwind;
538                 }
539
540                 cond_resched();
541         }
542
543         return 0;
544
545 unwind:
546         list_for_each_entry_continue_reverse(d, &iommu->domain_list, next)
547                 iommu_unmap(d->domain, iova, npage << PAGE_SHIFT);
548
549         return ret;
550 }
551
552 static int vfio_dma_do_map(struct vfio_iommu *iommu,
553                            struct vfio_iommu_type1_dma_map *map)
554 {
555         dma_addr_t iova = map->iova;
556         unsigned long vaddr = map->vaddr;
557         size_t size = map->size;
558         long npage;
559         int ret = 0, prot = 0;
560         uint64_t mask;
561         struct vfio_dma *dma;
562         unsigned long pfn;
563
564         /* Verify that none of our __u64 fields overflow */
565         if (map->size != size || map->vaddr != vaddr || map->iova != iova)
566                 return -EINVAL;
567
568         mask = ((uint64_t)1 << __ffs(vfio_pgsize_bitmap(iommu))) - 1;
569
570         WARN_ON(mask & PAGE_MASK);
571
572         /* READ/WRITE from device perspective */
573         if (map->flags & VFIO_DMA_MAP_FLAG_WRITE)
574                 prot |= IOMMU_WRITE;
575         if (map->flags & VFIO_DMA_MAP_FLAG_READ)
576                 prot |= IOMMU_READ;
577
578         if (!prot || !size || (size | iova | vaddr) & mask)
579                 return -EINVAL;
580
581         /* Don't allow IOVA or virtual address wrap */
582         if (iova + size - 1 < iova || vaddr + size - 1 < vaddr)
583                 return -EINVAL;
584
585         mutex_lock(&iommu->lock);
586
587         if (vfio_find_dma(iommu, iova, size)) {
588                 mutex_unlock(&iommu->lock);
589                 return -EEXIST;
590         }
591
592         if (!iommu->dma_avail) {
593                 mutex_unlock(&iommu->lock);
594                 return -ENOSPC;
595         }
596
597         dma = kzalloc(sizeof(*dma), GFP_KERNEL);
598         if (!dma) {
599                 mutex_unlock(&iommu->lock);
600                 return -ENOMEM;
601         }
602
603         iommu->dma_avail--;
604         dma->iova = iova;
605         dma->vaddr = vaddr;
606         dma->prot = prot;
607
608         /* Insert zero-sized and grow as we map chunks of it */
609         vfio_link_dma(iommu, dma);
610
611         while (size) {
612                 /* Pin a contiguous chunk of memory */
613                 npage = vfio_pin_pages(vaddr + dma->size,
614                                        size >> PAGE_SHIFT, prot, &pfn);
615                 if (npage <= 0) {
616                         WARN_ON(!npage);
617                         ret = (int)npage;
618                         break;
619                 }
620
621                 /* Map it! */
622                 ret = vfio_iommu_map(iommu, iova + dma->size, pfn, npage, prot);
623                 if (ret) {
624                         vfio_unpin_pages(pfn, npage, prot, true);
625                         break;
626                 }
627
628                 size -= npage << PAGE_SHIFT;
629                 dma->size += npage << PAGE_SHIFT;
630         }
631
632         if (ret)
633                 vfio_remove_dma(iommu, dma);
634
635         mutex_unlock(&iommu->lock);
636         return ret;
637 }
638
639 static int vfio_bus_type(struct device *dev, void *data)
640 {
641         struct bus_type **bus = data;
642
643         if (*bus && *bus != dev->bus)
644                 return -EINVAL;
645
646         *bus = dev->bus;
647
648         return 0;
649 }
650
651 static int vfio_iommu_replay(struct vfio_iommu *iommu,
652                              struct vfio_domain *domain)
653 {
654         struct vfio_domain *d;
655         struct rb_node *n;
656         int ret;
657
658         /* Arbitrarily pick the first domain in the list for lookups */
659         d = list_first_entry(&iommu->domain_list, struct vfio_domain, next);
660         n = rb_first(&iommu->dma_list);
661
662         /* If there's not a domain, there better not be any mappings */
663         if (WARN_ON(n && !d))
664                 return -EINVAL;
665
666         for (; n; n = rb_next(n)) {
667                 struct vfio_dma *dma;
668                 dma_addr_t iova;
669
670                 dma = rb_entry(n, struct vfio_dma, node);
671                 iova = dma->iova;
672
673                 while (iova < dma->iova + dma->size) {
674                         phys_addr_t phys = iommu_iova_to_phys(d->domain, iova);
675                         size_t size;
676
677                         if (WARN_ON(!phys)) {
678                                 iova += PAGE_SIZE;
679                                 continue;
680                         }
681
682                         size = PAGE_SIZE;
683
684                         while (iova + size < dma->iova + dma->size &&
685                                phys + size == iommu_iova_to_phys(d->domain,
686                                                                  iova + size))
687                                 size += PAGE_SIZE;
688
689                         ret = iommu_map(domain->domain, iova, phys,
690                                         size, dma->prot | domain->prot);
691                         if (ret)
692                                 return ret;
693
694                         iova += size;
695                 }
696         }
697
698         return 0;
699 }
700
701 /*
702  * We change our unmap behavior slightly depending on whether the IOMMU
703  * supports fine-grained superpages.  IOMMUs like AMD-Vi will use a superpage
704  * for practically any contiguous power-of-two mapping we give it.  This means
705  * we don't need to look for contiguous chunks ourselves to make unmapping
706  * more efficient.  On IOMMUs with coarse-grained super pages, like Intel VT-d
707  * with discrete 2M/1G/512G/1T superpages, identifying contiguous chunks
708  * significantly boosts non-hugetlbfs mappings and doesn't seem to hurt when
709  * hugetlbfs is in use.
710  */
711 static void vfio_test_domain_fgsp(struct vfio_domain *domain)
712 {
713         struct page *pages;
714         int ret, order = get_order(PAGE_SIZE * 2);
715
716         pages = alloc_pages(GFP_KERNEL | __GFP_ZERO, order);
717         if (!pages)
718                 return;
719
720         ret = iommu_map(domain->domain, 0, page_to_phys(pages), PAGE_SIZE * 2,
721                         IOMMU_READ | IOMMU_WRITE | domain->prot);
722         if (!ret) {
723                 size_t unmapped = iommu_unmap(domain->domain, 0, PAGE_SIZE);
724
725                 if (unmapped == PAGE_SIZE)
726                         iommu_unmap(domain->domain, PAGE_SIZE, PAGE_SIZE);
727                 else
728                         domain->fgsp = true;
729         }
730
731         __free_pages(pages, order);
732 }
733
734 static int vfio_iommu_type1_attach_group(void *iommu_data,
735                                          struct iommu_group *iommu_group)
736 {
737         struct vfio_iommu *iommu = iommu_data;
738         struct vfio_group *group, *g;
739         struct vfio_domain *domain, *d;
740         struct bus_type *bus = NULL;
741         int ret;
742
743         mutex_lock(&iommu->lock);
744
745         list_for_each_entry(d, &iommu->domain_list, next) {
746                 list_for_each_entry(g, &d->group_list, next) {
747                         if (g->iommu_group != iommu_group)
748                                 continue;
749
750                         mutex_unlock(&iommu->lock);
751                         return -EINVAL;
752                 }
753         }
754
755         group = kzalloc(sizeof(*group), GFP_KERNEL);
756         domain = kzalloc(sizeof(*domain), GFP_KERNEL);
757         if (!group || !domain) {
758                 ret = -ENOMEM;
759                 goto out_free;
760         }
761
762         group->iommu_group = iommu_group;
763
764         /* Determine bus_type in order to allocate a domain */
765         ret = iommu_group_for_each_dev(iommu_group, &bus, vfio_bus_type);
766         if (ret)
767                 goto out_free;
768
769         domain->domain = iommu_domain_alloc(bus);
770         if (!domain->domain) {
771                 ret = -EIO;
772                 goto out_free;
773         }
774
775         if (iommu->nesting) {
776                 int attr = 1;
777
778                 ret = iommu_domain_set_attr(domain->domain, DOMAIN_ATTR_NESTING,
779                                             &attr);
780                 if (ret)
781                         goto out_domain;
782         }
783
784         ret = iommu_attach_group(domain->domain, iommu_group);
785         if (ret)
786                 goto out_domain;
787
788         INIT_LIST_HEAD(&domain->group_list);
789         list_add(&group->next, &domain->group_list);
790
791         if (!allow_unsafe_interrupts &&
792             !iommu_capable(bus, IOMMU_CAP_INTR_REMAP)) {
793                 pr_warn("%s: No interrupt remapping support.  Use the module param \"allow_unsafe_interrupts\" to enable VFIO IOMMU support on this platform\n",
794                        __func__);
795                 ret = -EPERM;
796                 goto out_detach;
797         }
798
799         if (iommu_capable(bus, IOMMU_CAP_CACHE_COHERENCY))
800                 domain->prot |= IOMMU_CACHE;
801
802         /*
803          * Try to match an existing compatible domain.  We don't want to
804          * preclude an IOMMU driver supporting multiple bus_types and being
805          * able to include different bus_types in the same IOMMU domain, so
806          * we test whether the domains use the same iommu_ops rather than
807          * testing if they're on the same bus_type.
808          */
809         list_for_each_entry(d, &iommu->domain_list, next) {
810                 if (d->domain->ops == domain->domain->ops &&
811                     d->prot == domain->prot) {
812                         iommu_detach_group(domain->domain, iommu_group);
813                         if (!iommu_attach_group(d->domain, iommu_group)) {
814                                 list_add(&group->next, &d->group_list);
815                                 iommu_domain_free(domain->domain);
816                                 kfree(domain);
817                                 mutex_unlock(&iommu->lock);
818                                 return 0;
819                         }
820
821                         ret = iommu_attach_group(domain->domain, iommu_group);
822                         if (ret)
823                                 goto out_domain;
824                 }
825         }
826
827         vfio_test_domain_fgsp(domain);
828
829         /* replay mappings on new domains */
830         ret = vfio_iommu_replay(iommu, domain);
831         if (ret)
832                 goto out_detach;
833
834         list_add(&domain->next, &iommu->domain_list);
835
836         mutex_unlock(&iommu->lock);
837
838         return 0;
839
840 out_detach:
841         iommu_detach_group(domain->domain, iommu_group);
842 out_domain:
843         iommu_domain_free(domain->domain);
844 out_free:
845         kfree(domain);
846         kfree(group);
847         mutex_unlock(&iommu->lock);
848         return ret;
849 }
850
851 static void vfio_iommu_unmap_unpin_all(struct vfio_iommu *iommu)
852 {
853         struct rb_node *node;
854
855         while ((node = rb_first(&iommu->dma_list)))
856                 vfio_remove_dma(iommu, rb_entry(node, struct vfio_dma, node));
857 }
858
859 static void vfio_iommu_type1_detach_group(void *iommu_data,
860                                           struct iommu_group *iommu_group)
861 {
862         struct vfio_iommu *iommu = iommu_data;
863         struct vfio_domain *domain;
864         struct vfio_group *group;
865
866         mutex_lock(&iommu->lock);
867
868         list_for_each_entry(domain, &iommu->domain_list, next) {
869                 list_for_each_entry(group, &domain->group_list, next) {
870                         if (group->iommu_group != iommu_group)
871                                 continue;
872
873                         iommu_detach_group(domain->domain, iommu_group);
874                         list_del(&group->next);
875                         kfree(group);
876                         /*
877                          * Group ownership provides privilege, if the group
878                          * list is empty, the domain goes away.  If it's the
879                          * last domain, then all the mappings go away too.
880                          */
881                         if (list_empty(&domain->group_list)) {
882                                 if (list_is_singular(&iommu->domain_list))
883                                         vfio_iommu_unmap_unpin_all(iommu);
884                                 iommu_domain_free(domain->domain);
885                                 list_del(&domain->next);
886                                 kfree(domain);
887                         }
888                         goto done;
889                 }
890         }
891
892 done:
893         mutex_unlock(&iommu->lock);
894 }
895
896 static void *vfio_iommu_type1_open(unsigned long arg)
897 {
898         struct vfio_iommu *iommu;
899
900         iommu = kzalloc(sizeof(*iommu), GFP_KERNEL);
901         if (!iommu)
902                 return ERR_PTR(-ENOMEM);
903
904         switch (arg) {
905         case VFIO_TYPE1_IOMMU:
906                 break;
907         case VFIO_TYPE1_NESTING_IOMMU:
908                 iommu->nesting = true;
909         case VFIO_TYPE1v2_IOMMU:
910                 iommu->v2 = true;
911                 break;
912         default:
913                 kfree(iommu);
914                 return ERR_PTR(-EINVAL);
915         }
916
917         INIT_LIST_HEAD(&iommu->domain_list);
918         iommu->dma_list = RB_ROOT;
919         iommu->dma_avail = dma_entry_limit;
920         mutex_init(&iommu->lock);
921
922         return iommu;
923 }
924
925 static void vfio_iommu_type1_release(void *iommu_data)
926 {
927         struct vfio_iommu *iommu = iommu_data;
928         struct vfio_domain *domain, *domain_tmp;
929         struct vfio_group *group, *group_tmp;
930
931         vfio_iommu_unmap_unpin_all(iommu);
932
933         list_for_each_entry_safe(domain, domain_tmp,
934                                  &iommu->domain_list, next) {
935                 list_for_each_entry_safe(group, group_tmp,
936                                          &domain->group_list, next) {
937                         iommu_detach_group(domain->domain, group->iommu_group);
938                         list_del(&group->next);
939                         kfree(group);
940                 }
941                 iommu_domain_free(domain->domain);
942                 list_del(&domain->next);
943                 kfree(domain);
944         }
945
946         kfree(iommu);
947 }
948
949 static int vfio_domains_have_iommu_cache(struct vfio_iommu *iommu)
950 {
951         struct vfio_domain *domain;
952         int ret = 1;
953
954         mutex_lock(&iommu->lock);
955         list_for_each_entry(domain, &iommu->domain_list, next) {
956                 if (!(domain->prot & IOMMU_CACHE)) {
957                         ret = 0;
958                         break;
959                 }
960         }
961         mutex_unlock(&iommu->lock);
962
963         return ret;
964 }
965
966 static long vfio_iommu_type1_ioctl(void *iommu_data,
967                                    unsigned int cmd, unsigned long arg)
968 {
969         struct vfio_iommu *iommu = iommu_data;
970         unsigned long minsz;
971
972         if (cmd == VFIO_CHECK_EXTENSION) {
973                 switch (arg) {
974                 case VFIO_TYPE1_IOMMU:
975                 case VFIO_TYPE1v2_IOMMU:
976                 case VFIO_TYPE1_NESTING_IOMMU:
977                         return 1;
978                 case VFIO_DMA_CC_IOMMU:
979                         if (!iommu)
980                                 return 0;
981                         return vfio_domains_have_iommu_cache(iommu);
982                 default:
983                         return 0;
984                 }
985         } else if (cmd == VFIO_IOMMU_GET_INFO) {
986                 struct vfio_iommu_type1_info info;
987
988                 minsz = offsetofend(struct vfio_iommu_type1_info, iova_pgsizes);
989
990                 if (copy_from_user(&info, (void __user *)arg, minsz))
991                         return -EFAULT;
992
993                 if (info.argsz < minsz)
994                         return -EINVAL;
995
996                 info.flags = 0;
997
998                 info.iova_pgsizes = vfio_pgsize_bitmap(iommu);
999
1000                 return copy_to_user((void __user *)arg, &info, minsz) ?
1001                         -EFAULT : 0;
1002
1003         } else if (cmd == VFIO_IOMMU_MAP_DMA) {
1004                 struct vfio_iommu_type1_dma_map map;
1005                 uint32_t mask = VFIO_DMA_MAP_FLAG_READ |
1006                                 VFIO_DMA_MAP_FLAG_WRITE;
1007
1008                 minsz = offsetofend(struct vfio_iommu_type1_dma_map, size);
1009
1010                 if (copy_from_user(&map, (void __user *)arg, minsz))
1011                         return -EFAULT;
1012
1013                 if (map.argsz < minsz || map.flags & ~mask)
1014                         return -EINVAL;
1015
1016                 return vfio_dma_do_map(iommu, &map);
1017
1018         } else if (cmd == VFIO_IOMMU_UNMAP_DMA) {
1019                 struct vfio_iommu_type1_dma_unmap unmap;
1020                 long ret;
1021
1022                 minsz = offsetofend(struct vfio_iommu_type1_dma_unmap, size);
1023
1024                 if (copy_from_user(&unmap, (void __user *)arg, minsz))
1025                         return -EFAULT;
1026
1027                 if (unmap.argsz < minsz || unmap.flags)
1028                         return -EINVAL;
1029
1030                 ret = vfio_dma_do_unmap(iommu, &unmap);
1031                 if (ret)
1032                         return ret;
1033
1034                 return copy_to_user((void __user *)arg, &unmap, minsz) ?
1035                         -EFAULT : 0;
1036         }
1037
1038         return -ENOTTY;
1039 }
1040
1041 static const struct vfio_iommu_driver_ops vfio_iommu_driver_ops_type1 = {
1042         .name           = "vfio-iommu-type1",
1043         .owner          = THIS_MODULE,
1044         .open           = vfio_iommu_type1_open,
1045         .release        = vfio_iommu_type1_release,
1046         .ioctl          = vfio_iommu_type1_ioctl,
1047         .attach_group   = vfio_iommu_type1_attach_group,
1048         .detach_group   = vfio_iommu_type1_detach_group,
1049 };
1050
1051 static int __init vfio_iommu_type1_init(void)
1052 {
1053         return vfio_register_iommu_driver(&vfio_iommu_driver_ops_type1);
1054 }
1055
1056 static void __exit vfio_iommu_type1_cleanup(void)
1057 {
1058         vfio_unregister_iommu_driver(&vfio_iommu_driver_ops_type1);
1059 }
1060
1061 module_init(vfio_iommu_type1_init);
1062 module_exit(vfio_iommu_type1_cleanup);
1063
1064 MODULE_VERSION(DRIVER_VERSION);
1065 MODULE_LICENSE("GPL v2");
1066 MODULE_AUTHOR(DRIVER_AUTHOR);
1067 MODULE_DESCRIPTION(DRIVER_DESC);