iommu: Introduce wrappers around dev->iommu_fwspec
[linux-2.6-microblaze.git] / drivers / iommu / iommu.c
1 /*
2  * Copyright (C) 2007-2008 Advanced Micro Devices, Inc.
3  * Author: Joerg Roedel <jroedel@suse.de>
4  *
5  * This program is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License version 2 as published
7  * by the Free Software Foundation.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
17  */
18
19 #define pr_fmt(fmt)    "iommu: " fmt
20
21 #include <linux/device.h>
22 #include <linux/kernel.h>
23 #include <linux/bug.h>
24 #include <linux/types.h>
25 #include <linux/init.h>
26 #include <linux/export.h>
27 #include <linux/slab.h>
28 #include <linux/errno.h>
29 #include <linux/iommu.h>
30 #include <linux/idr.h>
31 #include <linux/notifier.h>
32 #include <linux/err.h>
33 #include <linux/pci.h>
34 #include <linux/bitops.h>
35 #include <linux/property.h>
36 #include <linux/fsl/mc.h>
37 #include <trace/events/iommu.h>
38
39 static struct kset *iommu_group_kset;
40 static DEFINE_IDA(iommu_group_ida);
41 #ifdef CONFIG_IOMMU_DEFAULT_PASSTHROUGH
42 static unsigned int iommu_def_domain_type = IOMMU_DOMAIN_IDENTITY;
43 #else
44 static unsigned int iommu_def_domain_type = IOMMU_DOMAIN_DMA;
45 #endif
46 static bool iommu_dma_strict __read_mostly = true;
47
48 struct iommu_callback_data {
49         const struct iommu_ops *ops;
50 };
51
52 struct iommu_group {
53         struct kobject kobj;
54         struct kobject *devices_kobj;
55         struct list_head devices;
56         struct mutex mutex;
57         struct blocking_notifier_head notifier;
58         void *iommu_data;
59         void (*iommu_data_release)(void *iommu_data);
60         char *name;
61         int id;
62         struct iommu_domain *default_domain;
63         struct iommu_domain *domain;
64 };
65
66 struct group_device {
67         struct list_head list;
68         struct device *dev;
69         char *name;
70 };
71
72 struct iommu_group_attribute {
73         struct attribute attr;
74         ssize_t (*show)(struct iommu_group *group, char *buf);
75         ssize_t (*store)(struct iommu_group *group,
76                          const char *buf, size_t count);
77 };
78
79 static const char * const iommu_group_resv_type_string[] = {
80         [IOMMU_RESV_DIRECT]     = "direct",
81         [IOMMU_RESV_RESERVED]   = "reserved",
82         [IOMMU_RESV_MSI]        = "msi",
83         [IOMMU_RESV_SW_MSI]     = "msi",
84 };
85
86 #define IOMMU_GROUP_ATTR(_name, _mode, _show, _store)           \
87 struct iommu_group_attribute iommu_group_attr_##_name =         \
88         __ATTR(_name, _mode, _show, _store)
89
90 #define to_iommu_group_attr(_attr)      \
91         container_of(_attr, struct iommu_group_attribute, attr)
92 #define to_iommu_group(_kobj)           \
93         container_of(_kobj, struct iommu_group, kobj)
94
95 static LIST_HEAD(iommu_device_list);
96 static DEFINE_SPINLOCK(iommu_device_lock);
97
98 int iommu_device_register(struct iommu_device *iommu)
99 {
100         spin_lock(&iommu_device_lock);
101         list_add_tail(&iommu->list, &iommu_device_list);
102         spin_unlock(&iommu_device_lock);
103
104         return 0;
105 }
106
107 void iommu_device_unregister(struct iommu_device *iommu)
108 {
109         spin_lock(&iommu_device_lock);
110         list_del(&iommu->list);
111         spin_unlock(&iommu_device_lock);
112 }
113
114 static struct iommu_domain *__iommu_domain_alloc(struct bus_type *bus,
115                                                  unsigned type);
116 static int __iommu_attach_device(struct iommu_domain *domain,
117                                  struct device *dev);
118 static int __iommu_attach_group(struct iommu_domain *domain,
119                                 struct iommu_group *group);
120 static void __iommu_detach_group(struct iommu_domain *domain,
121                                  struct iommu_group *group);
122
123 static int __init iommu_set_def_domain_type(char *str)
124 {
125         bool pt;
126         int ret;
127
128         ret = kstrtobool(str, &pt);
129         if (ret)
130                 return ret;
131
132         iommu_def_domain_type = pt ? IOMMU_DOMAIN_IDENTITY : IOMMU_DOMAIN_DMA;
133         return 0;
134 }
135 early_param("iommu.passthrough", iommu_set_def_domain_type);
136
137 static int __init iommu_dma_setup(char *str)
138 {
139         return kstrtobool(str, &iommu_dma_strict);
140 }
141 early_param("iommu.strict", iommu_dma_setup);
142
143 static ssize_t iommu_group_attr_show(struct kobject *kobj,
144                                      struct attribute *__attr, char *buf)
145 {
146         struct iommu_group_attribute *attr = to_iommu_group_attr(__attr);
147         struct iommu_group *group = to_iommu_group(kobj);
148         ssize_t ret = -EIO;
149
150         if (attr->show)
151                 ret = attr->show(group, buf);
152         return ret;
153 }
154
155 static ssize_t iommu_group_attr_store(struct kobject *kobj,
156                                       struct attribute *__attr,
157                                       const char *buf, size_t count)
158 {
159         struct iommu_group_attribute *attr = to_iommu_group_attr(__attr);
160         struct iommu_group *group = to_iommu_group(kobj);
161         ssize_t ret = -EIO;
162
163         if (attr->store)
164                 ret = attr->store(group, buf, count);
165         return ret;
166 }
167
168 static const struct sysfs_ops iommu_group_sysfs_ops = {
169         .show = iommu_group_attr_show,
170         .store = iommu_group_attr_store,
171 };
172
173 static int iommu_group_create_file(struct iommu_group *group,
174                                    struct iommu_group_attribute *attr)
175 {
176         return sysfs_create_file(&group->kobj, &attr->attr);
177 }
178
179 static void iommu_group_remove_file(struct iommu_group *group,
180                                     struct iommu_group_attribute *attr)
181 {
182         sysfs_remove_file(&group->kobj, &attr->attr);
183 }
184
185 static ssize_t iommu_group_show_name(struct iommu_group *group, char *buf)
186 {
187         return sprintf(buf, "%s\n", group->name);
188 }
189
190 /**
191  * iommu_insert_resv_region - Insert a new region in the
192  * list of reserved regions.
193  * @new: new region to insert
194  * @regions: list of regions
195  *
196  * The new element is sorted by address with respect to the other
197  * regions of the same type. In case it overlaps with another
198  * region of the same type, regions are merged. In case it
199  * overlaps with another region of different type, regions are
200  * not merged.
201  */
202 static int iommu_insert_resv_region(struct iommu_resv_region *new,
203                                     struct list_head *regions)
204 {
205         struct iommu_resv_region *region;
206         phys_addr_t start = new->start;
207         phys_addr_t end = new->start + new->length - 1;
208         struct list_head *pos = regions->next;
209
210         while (pos != regions) {
211                 struct iommu_resv_region *entry =
212                         list_entry(pos, struct iommu_resv_region, list);
213                 phys_addr_t a = entry->start;
214                 phys_addr_t b = entry->start + entry->length - 1;
215                 int type = entry->type;
216
217                 if (end < a) {
218                         goto insert;
219                 } else if (start > b) {
220                         pos = pos->next;
221                 } else if ((start >= a) && (end <= b)) {
222                         if (new->type == type)
223                                 goto done;
224                         else
225                                 pos = pos->next;
226                 } else {
227                         if (new->type == type) {
228                                 phys_addr_t new_start = min(a, start);
229                                 phys_addr_t new_end = max(b, end);
230
231                                 list_del(&entry->list);
232                                 entry->start = new_start;
233                                 entry->length = new_end - new_start + 1;
234                                 iommu_insert_resv_region(entry, regions);
235                         } else {
236                                 pos = pos->next;
237                         }
238                 }
239         }
240 insert:
241         region = iommu_alloc_resv_region(new->start, new->length,
242                                          new->prot, new->type);
243         if (!region)
244                 return -ENOMEM;
245
246         list_add_tail(&region->list, pos);
247 done:
248         return 0;
249 }
250
251 static int
252 iommu_insert_device_resv_regions(struct list_head *dev_resv_regions,
253                                  struct list_head *group_resv_regions)
254 {
255         struct iommu_resv_region *entry;
256         int ret = 0;
257
258         list_for_each_entry(entry, dev_resv_regions, list) {
259                 ret = iommu_insert_resv_region(entry, group_resv_regions);
260                 if (ret)
261                         break;
262         }
263         return ret;
264 }
265
266 int iommu_get_group_resv_regions(struct iommu_group *group,
267                                  struct list_head *head)
268 {
269         struct group_device *device;
270         int ret = 0;
271
272         mutex_lock(&group->mutex);
273         list_for_each_entry(device, &group->devices, list) {
274                 struct list_head dev_resv_regions;
275
276                 INIT_LIST_HEAD(&dev_resv_regions);
277                 iommu_get_resv_regions(device->dev, &dev_resv_regions);
278                 ret = iommu_insert_device_resv_regions(&dev_resv_regions, head);
279                 iommu_put_resv_regions(device->dev, &dev_resv_regions);
280                 if (ret)
281                         break;
282         }
283         mutex_unlock(&group->mutex);
284         return ret;
285 }
286 EXPORT_SYMBOL_GPL(iommu_get_group_resv_regions);
287
288 static ssize_t iommu_group_show_resv_regions(struct iommu_group *group,
289                                              char *buf)
290 {
291         struct iommu_resv_region *region, *next;
292         struct list_head group_resv_regions;
293         char *str = buf;
294
295         INIT_LIST_HEAD(&group_resv_regions);
296         iommu_get_group_resv_regions(group, &group_resv_regions);
297
298         list_for_each_entry_safe(region, next, &group_resv_regions, list) {
299                 str += sprintf(str, "0x%016llx 0x%016llx %s\n",
300                                (long long int)region->start,
301                                (long long int)(region->start +
302                                                 region->length - 1),
303                                iommu_group_resv_type_string[region->type]);
304                 kfree(region);
305         }
306
307         return (str - buf);
308 }
309
310 static ssize_t iommu_group_show_type(struct iommu_group *group,
311                                      char *buf)
312 {
313         char *type = "unknown\n";
314
315         if (group->default_domain) {
316                 switch (group->default_domain->type) {
317                 case IOMMU_DOMAIN_BLOCKED:
318                         type = "blocked\n";
319                         break;
320                 case IOMMU_DOMAIN_IDENTITY:
321                         type = "identity\n";
322                         break;
323                 case IOMMU_DOMAIN_UNMANAGED:
324                         type = "unmanaged\n";
325                         break;
326                 case IOMMU_DOMAIN_DMA:
327                         type = "DMA";
328                         break;
329                 }
330         }
331         strcpy(buf, type);
332
333         return strlen(type);
334 }
335
336 static IOMMU_GROUP_ATTR(name, S_IRUGO, iommu_group_show_name, NULL);
337
338 static IOMMU_GROUP_ATTR(reserved_regions, 0444,
339                         iommu_group_show_resv_regions, NULL);
340
341 static IOMMU_GROUP_ATTR(type, 0444, iommu_group_show_type, NULL);
342
343 static void iommu_group_release(struct kobject *kobj)
344 {
345         struct iommu_group *group = to_iommu_group(kobj);
346
347         pr_debug("Releasing group %d\n", group->id);
348
349         if (group->iommu_data_release)
350                 group->iommu_data_release(group->iommu_data);
351
352         ida_simple_remove(&iommu_group_ida, group->id);
353
354         if (group->default_domain)
355                 iommu_domain_free(group->default_domain);
356
357         kfree(group->name);
358         kfree(group);
359 }
360
361 static struct kobj_type iommu_group_ktype = {
362         .sysfs_ops = &iommu_group_sysfs_ops,
363         .release = iommu_group_release,
364 };
365
366 /**
367  * iommu_group_alloc - Allocate a new group
368  *
369  * This function is called by an iommu driver to allocate a new iommu
370  * group.  The iommu group represents the minimum granularity of the iommu.
371  * Upon successful return, the caller holds a reference to the supplied
372  * group in order to hold the group until devices are added.  Use
373  * iommu_group_put() to release this extra reference count, allowing the
374  * group to be automatically reclaimed once it has no devices or external
375  * references.
376  */
377 struct iommu_group *iommu_group_alloc(void)
378 {
379         struct iommu_group *group;
380         int ret;
381
382         group = kzalloc(sizeof(*group), GFP_KERNEL);
383         if (!group)
384                 return ERR_PTR(-ENOMEM);
385
386         group->kobj.kset = iommu_group_kset;
387         mutex_init(&group->mutex);
388         INIT_LIST_HEAD(&group->devices);
389         BLOCKING_INIT_NOTIFIER_HEAD(&group->notifier);
390
391         ret = ida_simple_get(&iommu_group_ida, 0, 0, GFP_KERNEL);
392         if (ret < 0) {
393                 kfree(group);
394                 return ERR_PTR(ret);
395         }
396         group->id = ret;
397
398         ret = kobject_init_and_add(&group->kobj, &iommu_group_ktype,
399                                    NULL, "%d", group->id);
400         if (ret) {
401                 ida_simple_remove(&iommu_group_ida, group->id);
402                 kfree(group);
403                 return ERR_PTR(ret);
404         }
405
406         group->devices_kobj = kobject_create_and_add("devices", &group->kobj);
407         if (!group->devices_kobj) {
408                 kobject_put(&group->kobj); /* triggers .release & free */
409                 return ERR_PTR(-ENOMEM);
410         }
411
412         /*
413          * The devices_kobj holds a reference on the group kobject, so
414          * as long as that exists so will the group.  We can therefore
415          * use the devices_kobj for reference counting.
416          */
417         kobject_put(&group->kobj);
418
419         ret = iommu_group_create_file(group,
420                                       &iommu_group_attr_reserved_regions);
421         if (ret)
422                 return ERR_PTR(ret);
423
424         ret = iommu_group_create_file(group, &iommu_group_attr_type);
425         if (ret)
426                 return ERR_PTR(ret);
427
428         pr_debug("Allocated group %d\n", group->id);
429
430         return group;
431 }
432 EXPORT_SYMBOL_GPL(iommu_group_alloc);
433
434 struct iommu_group *iommu_group_get_by_id(int id)
435 {
436         struct kobject *group_kobj;
437         struct iommu_group *group;
438         const char *name;
439
440         if (!iommu_group_kset)
441                 return NULL;
442
443         name = kasprintf(GFP_KERNEL, "%d", id);
444         if (!name)
445                 return NULL;
446
447         group_kobj = kset_find_obj(iommu_group_kset, name);
448         kfree(name);
449
450         if (!group_kobj)
451                 return NULL;
452
453         group = container_of(group_kobj, struct iommu_group, kobj);
454         BUG_ON(group->id != id);
455
456         kobject_get(group->devices_kobj);
457         kobject_put(&group->kobj);
458
459         return group;
460 }
461 EXPORT_SYMBOL_GPL(iommu_group_get_by_id);
462
463 /**
464  * iommu_group_get_iommudata - retrieve iommu_data registered for a group
465  * @group: the group
466  *
467  * iommu drivers can store data in the group for use when doing iommu
468  * operations.  This function provides a way to retrieve it.  Caller
469  * should hold a group reference.
470  */
471 void *iommu_group_get_iommudata(struct iommu_group *group)
472 {
473         return group->iommu_data;
474 }
475 EXPORT_SYMBOL_GPL(iommu_group_get_iommudata);
476
477 /**
478  * iommu_group_set_iommudata - set iommu_data for a group
479  * @group: the group
480  * @iommu_data: new data
481  * @release: release function for iommu_data
482  *
483  * iommu drivers can store data in the group for use when doing iommu
484  * operations.  This function provides a way to set the data after
485  * the group has been allocated.  Caller should hold a group reference.
486  */
487 void iommu_group_set_iommudata(struct iommu_group *group, void *iommu_data,
488                                void (*release)(void *iommu_data))
489 {
490         group->iommu_data = iommu_data;
491         group->iommu_data_release = release;
492 }
493 EXPORT_SYMBOL_GPL(iommu_group_set_iommudata);
494
495 /**
496  * iommu_group_set_name - set name for a group
497  * @group: the group
498  * @name: name
499  *
500  * Allow iommu driver to set a name for a group.  When set it will
501  * appear in a name attribute file under the group in sysfs.
502  */
503 int iommu_group_set_name(struct iommu_group *group, const char *name)
504 {
505         int ret;
506
507         if (group->name) {
508                 iommu_group_remove_file(group, &iommu_group_attr_name);
509                 kfree(group->name);
510                 group->name = NULL;
511                 if (!name)
512                         return 0;
513         }
514
515         group->name = kstrdup(name, GFP_KERNEL);
516         if (!group->name)
517                 return -ENOMEM;
518
519         ret = iommu_group_create_file(group, &iommu_group_attr_name);
520         if (ret) {
521                 kfree(group->name);
522                 group->name = NULL;
523                 return ret;
524         }
525
526         return 0;
527 }
528 EXPORT_SYMBOL_GPL(iommu_group_set_name);
529
530 static int iommu_group_create_direct_mappings(struct iommu_group *group,
531                                               struct device *dev)
532 {
533         struct iommu_domain *domain = group->default_domain;
534         struct iommu_resv_region *entry;
535         struct list_head mappings;
536         unsigned long pg_size;
537         int ret = 0;
538
539         if (!domain || domain->type != IOMMU_DOMAIN_DMA)
540                 return 0;
541
542         BUG_ON(!domain->pgsize_bitmap);
543
544         pg_size = 1UL << __ffs(domain->pgsize_bitmap);
545         INIT_LIST_HEAD(&mappings);
546
547         iommu_get_resv_regions(dev, &mappings);
548
549         /* We need to consider overlapping regions for different devices */
550         list_for_each_entry(entry, &mappings, list) {
551                 dma_addr_t start, end, addr;
552
553                 if (domain->ops->apply_resv_region)
554                         domain->ops->apply_resv_region(dev, domain, entry);
555
556                 start = ALIGN(entry->start, pg_size);
557                 end   = ALIGN(entry->start + entry->length, pg_size);
558
559                 if (entry->type != IOMMU_RESV_DIRECT)
560                         continue;
561
562                 for (addr = start; addr < end; addr += pg_size) {
563                         phys_addr_t phys_addr;
564
565                         phys_addr = iommu_iova_to_phys(domain, addr);
566                         if (phys_addr)
567                                 continue;
568
569                         ret = iommu_map(domain, addr, addr, pg_size, entry->prot);
570                         if (ret)
571                                 goto out;
572                 }
573
574         }
575
576         iommu_flush_tlb_all(domain);
577
578 out:
579         iommu_put_resv_regions(dev, &mappings);
580
581         return ret;
582 }
583
584 /**
585  * iommu_group_add_device - add a device to an iommu group
586  * @group: the group into which to add the device (reference should be held)
587  * @dev: the device
588  *
589  * This function is called by an iommu driver to add a device into a
590  * group.  Adding a device increments the group reference count.
591  */
592 int iommu_group_add_device(struct iommu_group *group, struct device *dev)
593 {
594         int ret, i = 0;
595         struct group_device *device;
596
597         device = kzalloc(sizeof(*device), GFP_KERNEL);
598         if (!device)
599                 return -ENOMEM;
600
601         device->dev = dev;
602
603         ret = sysfs_create_link(&dev->kobj, &group->kobj, "iommu_group");
604         if (ret)
605                 goto err_free_device;
606
607         device->name = kasprintf(GFP_KERNEL, "%s", kobject_name(&dev->kobj));
608 rename:
609         if (!device->name) {
610                 ret = -ENOMEM;
611                 goto err_remove_link;
612         }
613
614         ret = sysfs_create_link_nowarn(group->devices_kobj,
615                                        &dev->kobj, device->name);
616         if (ret) {
617                 if (ret == -EEXIST && i >= 0) {
618                         /*
619                          * Account for the slim chance of collision
620                          * and append an instance to the name.
621                          */
622                         kfree(device->name);
623                         device->name = kasprintf(GFP_KERNEL, "%s.%d",
624                                                  kobject_name(&dev->kobj), i++);
625                         goto rename;
626                 }
627                 goto err_free_name;
628         }
629
630         kobject_get(group->devices_kobj);
631
632         dev->iommu_group = group;
633
634         iommu_group_create_direct_mappings(group, dev);
635
636         mutex_lock(&group->mutex);
637         list_add_tail(&device->list, &group->devices);
638         if (group->domain)
639                 ret = __iommu_attach_device(group->domain, dev);
640         mutex_unlock(&group->mutex);
641         if (ret)
642                 goto err_put_group;
643
644         /* Notify any listeners about change to group. */
645         blocking_notifier_call_chain(&group->notifier,
646                                      IOMMU_GROUP_NOTIFY_ADD_DEVICE, dev);
647
648         trace_add_device_to_group(group->id, dev);
649
650         pr_info("Adding device %s to group %d\n", dev_name(dev), group->id);
651
652         return 0;
653
654 err_put_group:
655         mutex_lock(&group->mutex);
656         list_del(&device->list);
657         mutex_unlock(&group->mutex);
658         dev->iommu_group = NULL;
659         kobject_put(group->devices_kobj);
660 err_free_name:
661         kfree(device->name);
662 err_remove_link:
663         sysfs_remove_link(&dev->kobj, "iommu_group");
664 err_free_device:
665         kfree(device);
666         pr_err("Failed to add device %s to group %d: %d\n", dev_name(dev), group->id, ret);
667         return ret;
668 }
669 EXPORT_SYMBOL_GPL(iommu_group_add_device);
670
671 /**
672  * iommu_group_remove_device - remove a device from it's current group
673  * @dev: device to be removed
674  *
675  * This function is called by an iommu driver to remove the device from
676  * it's current group.  This decrements the iommu group reference count.
677  */
678 void iommu_group_remove_device(struct device *dev)
679 {
680         struct iommu_group *group = dev->iommu_group;
681         struct group_device *tmp_device, *device = NULL;
682
683         pr_info("Removing device %s from group %d\n", dev_name(dev), group->id);
684
685         /* Pre-notify listeners that a device is being removed. */
686         blocking_notifier_call_chain(&group->notifier,
687                                      IOMMU_GROUP_NOTIFY_DEL_DEVICE, dev);
688
689         mutex_lock(&group->mutex);
690         list_for_each_entry(tmp_device, &group->devices, list) {
691                 if (tmp_device->dev == dev) {
692                         device = tmp_device;
693                         list_del(&device->list);
694                         break;
695                 }
696         }
697         mutex_unlock(&group->mutex);
698
699         if (!device)
700                 return;
701
702         sysfs_remove_link(group->devices_kobj, device->name);
703         sysfs_remove_link(&dev->kobj, "iommu_group");
704
705         trace_remove_device_from_group(group->id, dev);
706
707         kfree(device->name);
708         kfree(device);
709         dev->iommu_group = NULL;
710         kobject_put(group->devices_kobj);
711 }
712 EXPORT_SYMBOL_GPL(iommu_group_remove_device);
713
714 static int iommu_group_device_count(struct iommu_group *group)
715 {
716         struct group_device *entry;
717         int ret = 0;
718
719         list_for_each_entry(entry, &group->devices, list)
720                 ret++;
721
722         return ret;
723 }
724
725 /**
726  * iommu_group_for_each_dev - iterate over each device in the group
727  * @group: the group
728  * @data: caller opaque data to be passed to callback function
729  * @fn: caller supplied callback function
730  *
731  * This function is called by group users to iterate over group devices.
732  * Callers should hold a reference count to the group during callback.
733  * The group->mutex is held across callbacks, which will block calls to
734  * iommu_group_add/remove_device.
735  */
736 static int __iommu_group_for_each_dev(struct iommu_group *group, void *data,
737                                       int (*fn)(struct device *, void *))
738 {
739         struct group_device *device;
740         int ret = 0;
741
742         list_for_each_entry(device, &group->devices, list) {
743                 ret = fn(device->dev, data);
744                 if (ret)
745                         break;
746         }
747         return ret;
748 }
749
750
751 int iommu_group_for_each_dev(struct iommu_group *group, void *data,
752                              int (*fn)(struct device *, void *))
753 {
754         int ret;
755
756         mutex_lock(&group->mutex);
757         ret = __iommu_group_for_each_dev(group, data, fn);
758         mutex_unlock(&group->mutex);
759
760         return ret;
761 }
762 EXPORT_SYMBOL_GPL(iommu_group_for_each_dev);
763
764 /**
765  * iommu_group_get - Return the group for a device and increment reference
766  * @dev: get the group that this device belongs to
767  *
768  * This function is called by iommu drivers and users to get the group
769  * for the specified device.  If found, the group is returned and the group
770  * reference in incremented, else NULL.
771  */
772 struct iommu_group *iommu_group_get(struct device *dev)
773 {
774         struct iommu_group *group = dev->iommu_group;
775
776         if (group)
777                 kobject_get(group->devices_kobj);
778
779         return group;
780 }
781 EXPORT_SYMBOL_GPL(iommu_group_get);
782
783 /**
784  * iommu_group_ref_get - Increment reference on a group
785  * @group: the group to use, must not be NULL
786  *
787  * This function is called by iommu drivers to take additional references on an
788  * existing group.  Returns the given group for convenience.
789  */
790 struct iommu_group *iommu_group_ref_get(struct iommu_group *group)
791 {
792         kobject_get(group->devices_kobj);
793         return group;
794 }
795
796 /**
797  * iommu_group_put - Decrement group reference
798  * @group: the group to use
799  *
800  * This function is called by iommu drivers and users to release the
801  * iommu group.  Once the reference count is zero, the group is released.
802  */
803 void iommu_group_put(struct iommu_group *group)
804 {
805         if (group)
806                 kobject_put(group->devices_kobj);
807 }
808 EXPORT_SYMBOL_GPL(iommu_group_put);
809
810 /**
811  * iommu_group_register_notifier - Register a notifier for group changes
812  * @group: the group to watch
813  * @nb: notifier block to signal
814  *
815  * This function allows iommu group users to track changes in a group.
816  * See include/linux/iommu.h for actions sent via this notifier.  Caller
817  * should hold a reference to the group throughout notifier registration.
818  */
819 int iommu_group_register_notifier(struct iommu_group *group,
820                                   struct notifier_block *nb)
821 {
822         return blocking_notifier_chain_register(&group->notifier, nb);
823 }
824 EXPORT_SYMBOL_GPL(iommu_group_register_notifier);
825
826 /**
827  * iommu_group_unregister_notifier - Unregister a notifier
828  * @group: the group to watch
829  * @nb: notifier block to signal
830  *
831  * Unregister a previously registered group notifier block.
832  */
833 int iommu_group_unregister_notifier(struct iommu_group *group,
834                                     struct notifier_block *nb)
835 {
836         return blocking_notifier_chain_unregister(&group->notifier, nb);
837 }
838 EXPORT_SYMBOL_GPL(iommu_group_unregister_notifier);
839
840 /**
841  * iommu_group_id - Return ID for a group
842  * @group: the group to ID
843  *
844  * Return the unique ID for the group matching the sysfs group number.
845  */
846 int iommu_group_id(struct iommu_group *group)
847 {
848         return group->id;
849 }
850 EXPORT_SYMBOL_GPL(iommu_group_id);
851
852 static struct iommu_group *get_pci_alias_group(struct pci_dev *pdev,
853                                                unsigned long *devfns);
854
855 /*
856  * To consider a PCI device isolated, we require ACS to support Source
857  * Validation, Request Redirection, Completer Redirection, and Upstream
858  * Forwarding.  This effectively means that devices cannot spoof their
859  * requester ID, requests and completions cannot be redirected, and all
860  * transactions are forwarded upstream, even as it passes through a
861  * bridge where the target device is downstream.
862  */
863 #define REQ_ACS_FLAGS   (PCI_ACS_SV | PCI_ACS_RR | PCI_ACS_CR | PCI_ACS_UF)
864
865 /*
866  * For multifunction devices which are not isolated from each other, find
867  * all the other non-isolated functions and look for existing groups.  For
868  * each function, we also need to look for aliases to or from other devices
869  * that may already have a group.
870  */
871 static struct iommu_group *get_pci_function_alias_group(struct pci_dev *pdev,
872                                                         unsigned long *devfns)
873 {
874         struct pci_dev *tmp = NULL;
875         struct iommu_group *group;
876
877         if (!pdev->multifunction || pci_acs_enabled(pdev, REQ_ACS_FLAGS))
878                 return NULL;
879
880         for_each_pci_dev(tmp) {
881                 if (tmp == pdev || tmp->bus != pdev->bus ||
882                     PCI_SLOT(tmp->devfn) != PCI_SLOT(pdev->devfn) ||
883                     pci_acs_enabled(tmp, REQ_ACS_FLAGS))
884                         continue;
885
886                 group = get_pci_alias_group(tmp, devfns);
887                 if (group) {
888                         pci_dev_put(tmp);
889                         return group;
890                 }
891         }
892
893         return NULL;
894 }
895
896 /*
897  * Look for aliases to or from the given device for existing groups. DMA
898  * aliases are only supported on the same bus, therefore the search
899  * space is quite small (especially since we're really only looking at pcie
900  * device, and therefore only expect multiple slots on the root complex or
901  * downstream switch ports).  It's conceivable though that a pair of
902  * multifunction devices could have aliases between them that would cause a
903  * loop.  To prevent this, we use a bitmap to track where we've been.
904  */
905 static struct iommu_group *get_pci_alias_group(struct pci_dev *pdev,
906                                                unsigned long *devfns)
907 {
908         struct pci_dev *tmp = NULL;
909         struct iommu_group *group;
910
911         if (test_and_set_bit(pdev->devfn & 0xff, devfns))
912                 return NULL;
913
914         group = iommu_group_get(&pdev->dev);
915         if (group)
916                 return group;
917
918         for_each_pci_dev(tmp) {
919                 if (tmp == pdev || tmp->bus != pdev->bus)
920                         continue;
921
922                 /* We alias them or they alias us */
923                 if (pci_devs_are_dma_aliases(pdev, tmp)) {
924                         group = get_pci_alias_group(tmp, devfns);
925                         if (group) {
926                                 pci_dev_put(tmp);
927                                 return group;
928                         }
929
930                         group = get_pci_function_alias_group(tmp, devfns);
931                         if (group) {
932                                 pci_dev_put(tmp);
933                                 return group;
934                         }
935                 }
936         }
937
938         return NULL;
939 }
940
941 struct group_for_pci_data {
942         struct pci_dev *pdev;
943         struct iommu_group *group;
944 };
945
946 /*
947  * DMA alias iterator callback, return the last seen device.  Stop and return
948  * the IOMMU group if we find one along the way.
949  */
950 static int get_pci_alias_or_group(struct pci_dev *pdev, u16 alias, void *opaque)
951 {
952         struct group_for_pci_data *data = opaque;
953
954         data->pdev = pdev;
955         data->group = iommu_group_get(&pdev->dev);
956
957         return data->group != NULL;
958 }
959
960 /*
961  * Generic device_group call-back function. It just allocates one
962  * iommu-group per device.
963  */
964 struct iommu_group *generic_device_group(struct device *dev)
965 {
966         return iommu_group_alloc();
967 }
968
969 /*
970  * Use standard PCI bus topology, isolation features, and DMA alias quirks
971  * to find or create an IOMMU group for a device.
972  */
973 struct iommu_group *pci_device_group(struct device *dev)
974 {
975         struct pci_dev *pdev = to_pci_dev(dev);
976         struct group_for_pci_data data;
977         struct pci_bus *bus;
978         struct iommu_group *group = NULL;
979         u64 devfns[4] = { 0 };
980
981         if (WARN_ON(!dev_is_pci(dev)))
982                 return ERR_PTR(-EINVAL);
983
984         /*
985          * Find the upstream DMA alias for the device.  A device must not
986          * be aliased due to topology in order to have its own IOMMU group.
987          * If we find an alias along the way that already belongs to a
988          * group, use it.
989          */
990         if (pci_for_each_dma_alias(pdev, get_pci_alias_or_group, &data))
991                 return data.group;
992
993         pdev = data.pdev;
994
995         /*
996          * Continue upstream from the point of minimum IOMMU granularity
997          * due to aliases to the point where devices are protected from
998          * peer-to-peer DMA by PCI ACS.  Again, if we find an existing
999          * group, use it.
1000          */
1001         for (bus = pdev->bus; !pci_is_root_bus(bus); bus = bus->parent) {
1002                 if (!bus->self)
1003                         continue;
1004
1005                 if (pci_acs_path_enabled(bus->self, NULL, REQ_ACS_FLAGS))
1006                         break;
1007
1008                 pdev = bus->self;
1009
1010                 group = iommu_group_get(&pdev->dev);
1011                 if (group)
1012                         return group;
1013         }
1014
1015         /*
1016          * Look for existing groups on device aliases.  If we alias another
1017          * device or another device aliases us, use the same group.
1018          */
1019         group = get_pci_alias_group(pdev, (unsigned long *)devfns);
1020         if (group)
1021                 return group;
1022
1023         /*
1024          * Look for existing groups on non-isolated functions on the same
1025          * slot and aliases of those funcions, if any.  No need to clear
1026          * the search bitmap, the tested devfns are still valid.
1027          */
1028         group = get_pci_function_alias_group(pdev, (unsigned long *)devfns);
1029         if (group)
1030                 return group;
1031
1032         /* No shared group found, allocate new */
1033         return iommu_group_alloc();
1034 }
1035
1036 /* Get the IOMMU group for device on fsl-mc bus */
1037 struct iommu_group *fsl_mc_device_group(struct device *dev)
1038 {
1039         struct device *cont_dev = fsl_mc_cont_dev(dev);
1040         struct iommu_group *group;
1041
1042         group = iommu_group_get(cont_dev);
1043         if (!group)
1044                 group = iommu_group_alloc();
1045         return group;
1046 }
1047
1048 /**
1049  * iommu_group_get_for_dev - Find or create the IOMMU group for a device
1050  * @dev: target device
1051  *
1052  * This function is intended to be called by IOMMU drivers and extended to
1053  * support common, bus-defined algorithms when determining or creating the
1054  * IOMMU group for a device.  On success, the caller will hold a reference
1055  * to the returned IOMMU group, which will already include the provided
1056  * device.  The reference should be released with iommu_group_put().
1057  */
1058 struct iommu_group *iommu_group_get_for_dev(struct device *dev)
1059 {
1060         const struct iommu_ops *ops = dev->bus->iommu_ops;
1061         struct iommu_group *group;
1062         int ret;
1063
1064         group = iommu_group_get(dev);
1065         if (group)
1066                 return group;
1067
1068         if (!ops)
1069                 return ERR_PTR(-EINVAL);
1070
1071         group = ops->device_group(dev);
1072         if (WARN_ON_ONCE(group == NULL))
1073                 return ERR_PTR(-EINVAL);
1074
1075         if (IS_ERR(group))
1076                 return group;
1077
1078         /*
1079          * Try to allocate a default domain - needs support from the
1080          * IOMMU driver.
1081          */
1082         if (!group->default_domain) {
1083                 struct iommu_domain *dom;
1084
1085                 dom = __iommu_domain_alloc(dev->bus, iommu_def_domain_type);
1086                 if (!dom && iommu_def_domain_type != IOMMU_DOMAIN_DMA) {
1087                         dev_warn(dev,
1088                                  "failed to allocate default IOMMU domain of type %u; falling back to IOMMU_DOMAIN_DMA",
1089                                  iommu_def_domain_type);
1090                         dom = __iommu_domain_alloc(dev->bus, IOMMU_DOMAIN_DMA);
1091                 }
1092
1093                 group->default_domain = dom;
1094                 if (!group->domain)
1095                         group->domain = dom;
1096
1097                 if (dom && !iommu_dma_strict) {
1098                         int attr = 1;
1099                         iommu_domain_set_attr(dom,
1100                                               DOMAIN_ATTR_DMA_USE_FLUSH_QUEUE,
1101                                               &attr);
1102                 }
1103         }
1104
1105         ret = iommu_group_add_device(group, dev);
1106         if (ret) {
1107                 iommu_group_put(group);
1108                 return ERR_PTR(ret);
1109         }
1110
1111         return group;
1112 }
1113
1114 struct iommu_domain *iommu_group_default_domain(struct iommu_group *group)
1115 {
1116         return group->default_domain;
1117 }
1118
1119 static int add_iommu_group(struct device *dev, void *data)
1120 {
1121         struct iommu_callback_data *cb = data;
1122         const struct iommu_ops *ops = cb->ops;
1123         int ret;
1124
1125         if (!ops->add_device)
1126                 return 0;
1127
1128         WARN_ON(dev->iommu_group);
1129
1130         ret = ops->add_device(dev);
1131
1132         /*
1133          * We ignore -ENODEV errors for now, as they just mean that the
1134          * device is not translated by an IOMMU. We still care about
1135          * other errors and fail to initialize when they happen.
1136          */
1137         if (ret == -ENODEV)
1138                 ret = 0;
1139
1140         return ret;
1141 }
1142
1143 static int remove_iommu_group(struct device *dev, void *data)
1144 {
1145         struct iommu_callback_data *cb = data;
1146         const struct iommu_ops *ops = cb->ops;
1147
1148         if (ops->remove_device && dev->iommu_group)
1149                 ops->remove_device(dev);
1150
1151         return 0;
1152 }
1153
1154 static int iommu_bus_notifier(struct notifier_block *nb,
1155                               unsigned long action, void *data)
1156 {
1157         struct device *dev = data;
1158         const struct iommu_ops *ops = dev->bus->iommu_ops;
1159         struct iommu_group *group;
1160         unsigned long group_action = 0;
1161
1162         /*
1163          * ADD/DEL call into iommu driver ops if provided, which may
1164          * result in ADD/DEL notifiers to group->notifier
1165          */
1166         if (action == BUS_NOTIFY_ADD_DEVICE) {
1167                 if (ops->add_device) {
1168                         int ret;
1169
1170                         ret = ops->add_device(dev);
1171                         return (ret) ? NOTIFY_DONE : NOTIFY_OK;
1172                 }
1173         } else if (action == BUS_NOTIFY_REMOVED_DEVICE) {
1174                 if (ops->remove_device && dev->iommu_group) {
1175                         ops->remove_device(dev);
1176                         return 0;
1177                 }
1178         }
1179
1180         /*
1181          * Remaining BUS_NOTIFYs get filtered and republished to the
1182          * group, if anyone is listening
1183          */
1184         group = iommu_group_get(dev);
1185         if (!group)
1186                 return 0;
1187
1188         switch (action) {
1189         case BUS_NOTIFY_BIND_DRIVER:
1190                 group_action = IOMMU_GROUP_NOTIFY_BIND_DRIVER;
1191                 break;
1192         case BUS_NOTIFY_BOUND_DRIVER:
1193                 group_action = IOMMU_GROUP_NOTIFY_BOUND_DRIVER;
1194                 break;
1195         case BUS_NOTIFY_UNBIND_DRIVER:
1196                 group_action = IOMMU_GROUP_NOTIFY_UNBIND_DRIVER;
1197                 break;
1198         case BUS_NOTIFY_UNBOUND_DRIVER:
1199                 group_action = IOMMU_GROUP_NOTIFY_UNBOUND_DRIVER;
1200                 break;
1201         }
1202
1203         if (group_action)
1204                 blocking_notifier_call_chain(&group->notifier,
1205                                              group_action, dev);
1206
1207         iommu_group_put(group);
1208         return 0;
1209 }
1210
1211 static int iommu_bus_init(struct bus_type *bus, const struct iommu_ops *ops)
1212 {
1213         int err;
1214         struct notifier_block *nb;
1215         struct iommu_callback_data cb = {
1216                 .ops = ops,
1217         };
1218
1219         nb = kzalloc(sizeof(struct notifier_block), GFP_KERNEL);
1220         if (!nb)
1221                 return -ENOMEM;
1222
1223         nb->notifier_call = iommu_bus_notifier;
1224
1225         err = bus_register_notifier(bus, nb);
1226         if (err)
1227                 goto out_free;
1228
1229         err = bus_for_each_dev(bus, NULL, &cb, add_iommu_group);
1230         if (err)
1231                 goto out_err;
1232
1233
1234         return 0;
1235
1236 out_err:
1237         /* Clean up */
1238         bus_for_each_dev(bus, NULL, &cb, remove_iommu_group);
1239         bus_unregister_notifier(bus, nb);
1240
1241 out_free:
1242         kfree(nb);
1243
1244         return err;
1245 }
1246
1247 /**
1248  * bus_set_iommu - set iommu-callbacks for the bus
1249  * @bus: bus.
1250  * @ops: the callbacks provided by the iommu-driver
1251  *
1252  * This function is called by an iommu driver to set the iommu methods
1253  * used for a particular bus. Drivers for devices on that bus can use
1254  * the iommu-api after these ops are registered.
1255  * This special function is needed because IOMMUs are usually devices on
1256  * the bus itself, so the iommu drivers are not initialized when the bus
1257  * is set up. With this function the iommu-driver can set the iommu-ops
1258  * afterwards.
1259  */
1260 int bus_set_iommu(struct bus_type *bus, const struct iommu_ops *ops)
1261 {
1262         int err;
1263
1264         if (bus->iommu_ops != NULL)
1265                 return -EBUSY;
1266
1267         bus->iommu_ops = ops;
1268
1269         /* Do IOMMU specific setup for this bus-type */
1270         err = iommu_bus_init(bus, ops);
1271         if (err)
1272                 bus->iommu_ops = NULL;
1273
1274         return err;
1275 }
1276 EXPORT_SYMBOL_GPL(bus_set_iommu);
1277
1278 bool iommu_present(struct bus_type *bus)
1279 {
1280         return bus->iommu_ops != NULL;
1281 }
1282 EXPORT_SYMBOL_GPL(iommu_present);
1283
1284 bool iommu_capable(struct bus_type *bus, enum iommu_cap cap)
1285 {
1286         if (!bus->iommu_ops || !bus->iommu_ops->capable)
1287                 return false;
1288
1289         return bus->iommu_ops->capable(cap);
1290 }
1291 EXPORT_SYMBOL_GPL(iommu_capable);
1292
1293 /**
1294  * iommu_set_fault_handler() - set a fault handler for an iommu domain
1295  * @domain: iommu domain
1296  * @handler: fault handler
1297  * @token: user data, will be passed back to the fault handler
1298  *
1299  * This function should be used by IOMMU users which want to be notified
1300  * whenever an IOMMU fault happens.
1301  *
1302  * The fault handler itself should return 0 on success, and an appropriate
1303  * error code otherwise.
1304  */
1305 void iommu_set_fault_handler(struct iommu_domain *domain,
1306                                         iommu_fault_handler_t handler,
1307                                         void *token)
1308 {
1309         BUG_ON(!domain);
1310
1311         domain->handler = handler;
1312         domain->handler_token = token;
1313 }
1314 EXPORT_SYMBOL_GPL(iommu_set_fault_handler);
1315
1316 static struct iommu_domain *__iommu_domain_alloc(struct bus_type *bus,
1317                                                  unsigned type)
1318 {
1319         struct iommu_domain *domain;
1320
1321         if (bus == NULL || bus->iommu_ops == NULL)
1322                 return NULL;
1323
1324         domain = bus->iommu_ops->domain_alloc(type);
1325         if (!domain)
1326                 return NULL;
1327
1328         domain->ops  = bus->iommu_ops;
1329         domain->type = type;
1330         /* Assume all sizes by default; the driver may override this later */
1331         domain->pgsize_bitmap  = bus->iommu_ops->pgsize_bitmap;
1332
1333         return domain;
1334 }
1335
1336 struct iommu_domain *iommu_domain_alloc(struct bus_type *bus)
1337 {
1338         return __iommu_domain_alloc(bus, IOMMU_DOMAIN_UNMANAGED);
1339 }
1340 EXPORT_SYMBOL_GPL(iommu_domain_alloc);
1341
1342 void iommu_domain_free(struct iommu_domain *domain)
1343 {
1344         domain->ops->domain_free(domain);
1345 }
1346 EXPORT_SYMBOL_GPL(iommu_domain_free);
1347
1348 static int __iommu_attach_device(struct iommu_domain *domain,
1349                                  struct device *dev)
1350 {
1351         int ret;
1352         if ((domain->ops->is_attach_deferred != NULL) &&
1353             domain->ops->is_attach_deferred(domain, dev))
1354                 return 0;
1355
1356         if (unlikely(domain->ops->attach_dev == NULL))
1357                 return -ENODEV;
1358
1359         ret = domain->ops->attach_dev(domain, dev);
1360         if (!ret)
1361                 trace_attach_device_to_domain(dev);
1362         return ret;
1363 }
1364
1365 int iommu_attach_device(struct iommu_domain *domain, struct device *dev)
1366 {
1367         struct iommu_group *group;
1368         int ret;
1369
1370         group = iommu_group_get(dev);
1371         if (!group)
1372                 return -ENODEV;
1373
1374         /*
1375          * Lock the group to make sure the device-count doesn't
1376          * change while we are attaching
1377          */
1378         mutex_lock(&group->mutex);
1379         ret = -EINVAL;
1380         if (iommu_group_device_count(group) != 1)
1381                 goto out_unlock;
1382
1383         ret = __iommu_attach_group(domain, group);
1384
1385 out_unlock:
1386         mutex_unlock(&group->mutex);
1387         iommu_group_put(group);
1388
1389         return ret;
1390 }
1391 EXPORT_SYMBOL_GPL(iommu_attach_device);
1392
1393 static void __iommu_detach_device(struct iommu_domain *domain,
1394                                   struct device *dev)
1395 {
1396         if ((domain->ops->is_attach_deferred != NULL) &&
1397             domain->ops->is_attach_deferred(domain, dev))
1398                 return;
1399
1400         if (unlikely(domain->ops->detach_dev == NULL))
1401                 return;
1402
1403         domain->ops->detach_dev(domain, dev);
1404         trace_detach_device_from_domain(dev);
1405 }
1406
1407 void iommu_detach_device(struct iommu_domain *domain, struct device *dev)
1408 {
1409         struct iommu_group *group;
1410
1411         group = iommu_group_get(dev);
1412         if (!group)
1413                 return;
1414
1415         mutex_lock(&group->mutex);
1416         if (iommu_group_device_count(group) != 1) {
1417                 WARN_ON(1);
1418                 goto out_unlock;
1419         }
1420
1421         __iommu_detach_group(domain, group);
1422
1423 out_unlock:
1424         mutex_unlock(&group->mutex);
1425         iommu_group_put(group);
1426 }
1427 EXPORT_SYMBOL_GPL(iommu_detach_device);
1428
1429 struct iommu_domain *iommu_get_domain_for_dev(struct device *dev)
1430 {
1431         struct iommu_domain *domain;
1432         struct iommu_group *group;
1433
1434         group = iommu_group_get(dev);
1435         if (!group)
1436                 return NULL;
1437
1438         domain = group->domain;
1439
1440         iommu_group_put(group);
1441
1442         return domain;
1443 }
1444 EXPORT_SYMBOL_GPL(iommu_get_domain_for_dev);
1445
1446 /*
1447  * For IOMMU_DOMAIN_DMA implementations which already provide their own
1448  * guarantees that the group and its default domain are valid and correct.
1449  */
1450 struct iommu_domain *iommu_get_dma_domain(struct device *dev)
1451 {
1452         return dev->iommu_group->default_domain;
1453 }
1454
1455 /*
1456  * IOMMU groups are really the natural working unit of the IOMMU, but
1457  * the IOMMU API works on domains and devices.  Bridge that gap by
1458  * iterating over the devices in a group.  Ideally we'd have a single
1459  * device which represents the requestor ID of the group, but we also
1460  * allow IOMMU drivers to create policy defined minimum sets, where
1461  * the physical hardware may be able to distiguish members, but we
1462  * wish to group them at a higher level (ex. untrusted multi-function
1463  * PCI devices).  Thus we attach each device.
1464  */
1465 static int iommu_group_do_attach_device(struct device *dev, void *data)
1466 {
1467         struct iommu_domain *domain = data;
1468
1469         return __iommu_attach_device(domain, dev);
1470 }
1471
1472 static int __iommu_attach_group(struct iommu_domain *domain,
1473                                 struct iommu_group *group)
1474 {
1475         int ret;
1476
1477         if (group->default_domain && group->domain != group->default_domain)
1478                 return -EBUSY;
1479
1480         ret = __iommu_group_for_each_dev(group, domain,
1481                                          iommu_group_do_attach_device);
1482         if (ret == 0)
1483                 group->domain = domain;
1484
1485         return ret;
1486 }
1487
1488 int iommu_attach_group(struct iommu_domain *domain, struct iommu_group *group)
1489 {
1490         int ret;
1491
1492         mutex_lock(&group->mutex);
1493         ret = __iommu_attach_group(domain, group);
1494         mutex_unlock(&group->mutex);
1495
1496         return ret;
1497 }
1498 EXPORT_SYMBOL_GPL(iommu_attach_group);
1499
1500 static int iommu_group_do_detach_device(struct device *dev, void *data)
1501 {
1502         struct iommu_domain *domain = data;
1503
1504         __iommu_detach_device(domain, dev);
1505
1506         return 0;
1507 }
1508
1509 static void __iommu_detach_group(struct iommu_domain *domain,
1510                                  struct iommu_group *group)
1511 {
1512         int ret;
1513
1514         if (!group->default_domain) {
1515                 __iommu_group_for_each_dev(group, domain,
1516                                            iommu_group_do_detach_device);
1517                 group->domain = NULL;
1518                 return;
1519         }
1520
1521         if (group->domain == group->default_domain)
1522                 return;
1523
1524         /* Detach by re-attaching to the default domain */
1525         ret = __iommu_group_for_each_dev(group, group->default_domain,
1526                                          iommu_group_do_attach_device);
1527         if (ret != 0)
1528                 WARN_ON(1);
1529         else
1530                 group->domain = group->default_domain;
1531 }
1532
1533 void iommu_detach_group(struct iommu_domain *domain, struct iommu_group *group)
1534 {
1535         mutex_lock(&group->mutex);
1536         __iommu_detach_group(domain, group);
1537         mutex_unlock(&group->mutex);
1538 }
1539 EXPORT_SYMBOL_GPL(iommu_detach_group);
1540
1541 phys_addr_t iommu_iova_to_phys(struct iommu_domain *domain, dma_addr_t iova)
1542 {
1543         if (unlikely(domain->ops->iova_to_phys == NULL))
1544                 return 0;
1545
1546         return domain->ops->iova_to_phys(domain, iova);
1547 }
1548 EXPORT_SYMBOL_GPL(iommu_iova_to_phys);
1549
1550 static size_t iommu_pgsize(struct iommu_domain *domain,
1551                            unsigned long addr_merge, size_t size)
1552 {
1553         unsigned int pgsize_idx;
1554         size_t pgsize;
1555
1556         /* Max page size that still fits into 'size' */
1557         pgsize_idx = __fls(size);
1558
1559         /* need to consider alignment requirements ? */
1560         if (likely(addr_merge)) {
1561                 /* Max page size allowed by address */
1562                 unsigned int align_pgsize_idx = __ffs(addr_merge);
1563                 pgsize_idx = min(pgsize_idx, align_pgsize_idx);
1564         }
1565
1566         /* build a mask of acceptable page sizes */
1567         pgsize = (1UL << (pgsize_idx + 1)) - 1;
1568
1569         /* throw away page sizes not supported by the hardware */
1570         pgsize &= domain->pgsize_bitmap;
1571
1572         /* make sure we're still sane */
1573         BUG_ON(!pgsize);
1574
1575         /* pick the biggest page */
1576         pgsize_idx = __fls(pgsize);
1577         pgsize = 1UL << pgsize_idx;
1578
1579         return pgsize;
1580 }
1581
1582 int iommu_map(struct iommu_domain *domain, unsigned long iova,
1583               phys_addr_t paddr, size_t size, int prot)
1584 {
1585         unsigned long orig_iova = iova;
1586         unsigned int min_pagesz;
1587         size_t orig_size = size;
1588         phys_addr_t orig_paddr = paddr;
1589         int ret = 0;
1590
1591         if (unlikely(domain->ops->map == NULL ||
1592                      domain->pgsize_bitmap == 0UL))
1593                 return -ENODEV;
1594
1595         if (unlikely(!(domain->type & __IOMMU_DOMAIN_PAGING)))
1596                 return -EINVAL;
1597
1598         /* find out the minimum page size supported */
1599         min_pagesz = 1 << __ffs(domain->pgsize_bitmap);
1600
1601         /*
1602          * both the virtual address and the physical one, as well as
1603          * the size of the mapping, must be aligned (at least) to the
1604          * size of the smallest page supported by the hardware
1605          */
1606         if (!IS_ALIGNED(iova | paddr | size, min_pagesz)) {
1607                 pr_err("unaligned: iova 0x%lx pa %pa size 0x%zx min_pagesz 0x%x\n",
1608                        iova, &paddr, size, min_pagesz);
1609                 return -EINVAL;
1610         }
1611
1612         pr_debug("map: iova 0x%lx pa %pa size 0x%zx\n", iova, &paddr, size);
1613
1614         while (size) {
1615                 size_t pgsize = iommu_pgsize(domain, iova | paddr, size);
1616
1617                 pr_debug("mapping: iova 0x%lx pa %pa pgsize 0x%zx\n",
1618                          iova, &paddr, pgsize);
1619
1620                 ret = domain->ops->map(domain, iova, paddr, pgsize, prot);
1621                 if (ret)
1622                         break;
1623
1624                 iova += pgsize;
1625                 paddr += pgsize;
1626                 size -= pgsize;
1627         }
1628
1629         /* unroll mapping in case something went wrong */
1630         if (ret)
1631                 iommu_unmap(domain, orig_iova, orig_size - size);
1632         else
1633                 trace_map(orig_iova, orig_paddr, orig_size);
1634
1635         return ret;
1636 }
1637 EXPORT_SYMBOL_GPL(iommu_map);
1638
1639 static size_t __iommu_unmap(struct iommu_domain *domain,
1640                             unsigned long iova, size_t size,
1641                             bool sync)
1642 {
1643         const struct iommu_ops *ops = domain->ops;
1644         size_t unmapped_page, unmapped = 0;
1645         unsigned long orig_iova = iova;
1646         unsigned int min_pagesz;
1647
1648         if (unlikely(ops->unmap == NULL ||
1649                      domain->pgsize_bitmap == 0UL))
1650                 return 0;
1651
1652         if (unlikely(!(domain->type & __IOMMU_DOMAIN_PAGING)))
1653                 return 0;
1654
1655         /* find out the minimum page size supported */
1656         min_pagesz = 1 << __ffs(domain->pgsize_bitmap);
1657
1658         /*
1659          * The virtual address, as well as the size of the mapping, must be
1660          * aligned (at least) to the size of the smallest page supported
1661          * by the hardware
1662          */
1663         if (!IS_ALIGNED(iova | size, min_pagesz)) {
1664                 pr_err("unaligned: iova 0x%lx size 0x%zx min_pagesz 0x%x\n",
1665                        iova, size, min_pagesz);
1666                 return 0;
1667         }
1668
1669         pr_debug("unmap this: iova 0x%lx size 0x%zx\n", iova, size);
1670
1671         /*
1672          * Keep iterating until we either unmap 'size' bytes (or more)
1673          * or we hit an area that isn't mapped.
1674          */
1675         while (unmapped < size) {
1676                 size_t pgsize = iommu_pgsize(domain, iova, size - unmapped);
1677
1678                 unmapped_page = ops->unmap(domain, iova, pgsize);
1679                 if (!unmapped_page)
1680                         break;
1681
1682                 if (sync && ops->iotlb_range_add)
1683                         ops->iotlb_range_add(domain, iova, pgsize);
1684
1685                 pr_debug("unmapped: iova 0x%lx size 0x%zx\n",
1686                          iova, unmapped_page);
1687
1688                 iova += unmapped_page;
1689                 unmapped += unmapped_page;
1690         }
1691
1692         if (sync && ops->iotlb_sync)
1693                 ops->iotlb_sync(domain);
1694
1695         trace_unmap(orig_iova, size, unmapped);
1696         return unmapped;
1697 }
1698
1699 size_t iommu_unmap(struct iommu_domain *domain,
1700                    unsigned long iova, size_t size)
1701 {
1702         return __iommu_unmap(domain, iova, size, true);
1703 }
1704 EXPORT_SYMBOL_GPL(iommu_unmap);
1705
1706 size_t iommu_unmap_fast(struct iommu_domain *domain,
1707                         unsigned long iova, size_t size)
1708 {
1709         return __iommu_unmap(domain, iova, size, false);
1710 }
1711 EXPORT_SYMBOL_GPL(iommu_unmap_fast);
1712
1713 size_t iommu_map_sg(struct iommu_domain *domain, unsigned long iova,
1714                     struct scatterlist *sg, unsigned int nents, int prot)
1715 {
1716         size_t len = 0, mapped = 0;
1717         phys_addr_t start;
1718         unsigned int i = 0;
1719         int ret;
1720
1721         while (i <= nents) {
1722                 phys_addr_t s_phys = sg_phys(sg);
1723
1724                 if (len && s_phys != start + len) {
1725                         ret = iommu_map(domain, iova + mapped, start, len, prot);
1726                         if (ret)
1727                                 goto out_err;
1728
1729                         mapped += len;
1730                         len = 0;
1731                 }
1732
1733                 if (len) {
1734                         len += sg->length;
1735                 } else {
1736                         len = sg->length;
1737                         start = s_phys;
1738                 }
1739
1740                 if (++i < nents)
1741                         sg = sg_next(sg);
1742         }
1743
1744         return mapped;
1745
1746 out_err:
1747         /* undo mappings already done */
1748         iommu_unmap(domain, iova, mapped);
1749
1750         return 0;
1751
1752 }
1753 EXPORT_SYMBOL_GPL(iommu_map_sg);
1754
1755 int iommu_domain_window_enable(struct iommu_domain *domain, u32 wnd_nr,
1756                                phys_addr_t paddr, u64 size, int prot)
1757 {
1758         if (unlikely(domain->ops->domain_window_enable == NULL))
1759                 return -ENODEV;
1760
1761         return domain->ops->domain_window_enable(domain, wnd_nr, paddr, size,
1762                                                  prot);
1763 }
1764 EXPORT_SYMBOL_GPL(iommu_domain_window_enable);
1765
1766 void iommu_domain_window_disable(struct iommu_domain *domain, u32 wnd_nr)
1767 {
1768         if (unlikely(domain->ops->domain_window_disable == NULL))
1769                 return;
1770
1771         return domain->ops->domain_window_disable(domain, wnd_nr);
1772 }
1773 EXPORT_SYMBOL_GPL(iommu_domain_window_disable);
1774
1775 /**
1776  * report_iommu_fault() - report about an IOMMU fault to the IOMMU framework
1777  * @domain: the iommu domain where the fault has happened
1778  * @dev: the device where the fault has happened
1779  * @iova: the faulting address
1780  * @flags: mmu fault flags (e.g. IOMMU_FAULT_READ/IOMMU_FAULT_WRITE/...)
1781  *
1782  * This function should be called by the low-level IOMMU implementations
1783  * whenever IOMMU faults happen, to allow high-level users, that are
1784  * interested in such events, to know about them.
1785  *
1786  * This event may be useful for several possible use cases:
1787  * - mere logging of the event
1788  * - dynamic TLB/PTE loading
1789  * - if restarting of the faulting device is required
1790  *
1791  * Returns 0 on success and an appropriate error code otherwise (if dynamic
1792  * PTE/TLB loading will one day be supported, implementations will be able
1793  * to tell whether it succeeded or not according to this return value).
1794  *
1795  * Specifically, -ENOSYS is returned if a fault handler isn't installed
1796  * (though fault handlers can also return -ENOSYS, in case they want to
1797  * elicit the default behavior of the IOMMU drivers).
1798  */
1799 int report_iommu_fault(struct iommu_domain *domain, struct device *dev,
1800                        unsigned long iova, int flags)
1801 {
1802         int ret = -ENOSYS;
1803
1804         /*
1805          * if upper layers showed interest and installed a fault handler,
1806          * invoke it.
1807          */
1808         if (domain->handler)
1809                 ret = domain->handler(domain, dev, iova, flags,
1810                                                 domain->handler_token);
1811
1812         trace_io_page_fault(dev, iova, flags);
1813         return ret;
1814 }
1815 EXPORT_SYMBOL_GPL(report_iommu_fault);
1816
1817 static int __init iommu_init(void)
1818 {
1819         iommu_group_kset = kset_create_and_add("iommu_groups",
1820                                                NULL, kernel_kobj);
1821         BUG_ON(!iommu_group_kset);
1822
1823         iommu_debugfs_setup();
1824
1825         return 0;
1826 }
1827 core_initcall(iommu_init);
1828
1829 int iommu_domain_get_attr(struct iommu_domain *domain,
1830                           enum iommu_attr attr, void *data)
1831 {
1832         struct iommu_domain_geometry *geometry;
1833         bool *paging;
1834         int ret = 0;
1835
1836         switch (attr) {
1837         case DOMAIN_ATTR_GEOMETRY:
1838                 geometry  = data;
1839                 *geometry = domain->geometry;
1840
1841                 break;
1842         case DOMAIN_ATTR_PAGING:
1843                 paging  = data;
1844                 *paging = (domain->pgsize_bitmap != 0UL);
1845                 break;
1846         default:
1847                 if (!domain->ops->domain_get_attr)
1848                         return -EINVAL;
1849
1850                 ret = domain->ops->domain_get_attr(domain, attr, data);
1851         }
1852
1853         return ret;
1854 }
1855 EXPORT_SYMBOL_GPL(iommu_domain_get_attr);
1856
1857 int iommu_domain_set_attr(struct iommu_domain *domain,
1858                           enum iommu_attr attr, void *data)
1859 {
1860         int ret = 0;
1861
1862         switch (attr) {
1863         default:
1864                 if (domain->ops->domain_set_attr == NULL)
1865                         return -EINVAL;
1866
1867                 ret = domain->ops->domain_set_attr(domain, attr, data);
1868         }
1869
1870         return ret;
1871 }
1872 EXPORT_SYMBOL_GPL(iommu_domain_set_attr);
1873
1874 void iommu_get_resv_regions(struct device *dev, struct list_head *list)
1875 {
1876         const struct iommu_ops *ops = dev->bus->iommu_ops;
1877
1878         if (ops && ops->get_resv_regions)
1879                 ops->get_resv_regions(dev, list);
1880 }
1881
1882 void iommu_put_resv_regions(struct device *dev, struct list_head *list)
1883 {
1884         const struct iommu_ops *ops = dev->bus->iommu_ops;
1885
1886         if (ops && ops->put_resv_regions)
1887                 ops->put_resv_regions(dev, list);
1888 }
1889
1890 struct iommu_resv_region *iommu_alloc_resv_region(phys_addr_t start,
1891                                                   size_t length, int prot,
1892                                                   enum iommu_resv_type type)
1893 {
1894         struct iommu_resv_region *region;
1895
1896         region = kzalloc(sizeof(*region), GFP_KERNEL);
1897         if (!region)
1898                 return NULL;
1899
1900         INIT_LIST_HEAD(&region->list);
1901         region->start = start;
1902         region->length = length;
1903         region->prot = prot;
1904         region->type = type;
1905         return region;
1906 }
1907
1908 /* Request that a device is direct mapped by the IOMMU */
1909 int iommu_request_dm_for_dev(struct device *dev)
1910 {
1911         struct iommu_domain *dm_domain;
1912         struct iommu_group *group;
1913         int ret;
1914
1915         /* Device must already be in a group before calling this function */
1916         group = iommu_group_get_for_dev(dev);
1917         if (IS_ERR(group))
1918                 return PTR_ERR(group);
1919
1920         mutex_lock(&group->mutex);
1921
1922         /* Check if the default domain is already direct mapped */
1923         ret = 0;
1924         if (group->default_domain &&
1925             group->default_domain->type == IOMMU_DOMAIN_IDENTITY)
1926                 goto out;
1927
1928         /* Don't change mappings of existing devices */
1929         ret = -EBUSY;
1930         if (iommu_group_device_count(group) != 1)
1931                 goto out;
1932
1933         /* Allocate a direct mapped domain */
1934         ret = -ENOMEM;
1935         dm_domain = __iommu_domain_alloc(dev->bus, IOMMU_DOMAIN_IDENTITY);
1936         if (!dm_domain)
1937                 goto out;
1938
1939         /* Attach the device to the domain */
1940         ret = __iommu_attach_group(dm_domain, group);
1941         if (ret) {
1942                 iommu_domain_free(dm_domain);
1943                 goto out;
1944         }
1945
1946         /* Make the direct mapped domain the default for this group */
1947         if (group->default_domain)
1948                 iommu_domain_free(group->default_domain);
1949         group->default_domain = dm_domain;
1950
1951         pr_info("Using direct mapping for device %s\n", dev_name(dev));
1952
1953         ret = 0;
1954 out:
1955         mutex_unlock(&group->mutex);
1956         iommu_group_put(group);
1957
1958         return ret;
1959 }
1960
1961 const struct iommu_ops *iommu_ops_from_fwnode(struct fwnode_handle *fwnode)
1962 {
1963         const struct iommu_ops *ops = NULL;
1964         struct iommu_device *iommu;
1965
1966         spin_lock(&iommu_device_lock);
1967         list_for_each_entry(iommu, &iommu_device_list, list)
1968                 if (iommu->fwnode == fwnode) {
1969                         ops = iommu->ops;
1970                         break;
1971                 }
1972         spin_unlock(&iommu_device_lock);
1973         return ops;
1974 }
1975
1976 int iommu_fwspec_init(struct device *dev, struct fwnode_handle *iommu_fwnode,
1977                       const struct iommu_ops *ops)
1978 {
1979         struct iommu_fwspec *fwspec = dev_iommu_fwspec_get(dev);
1980
1981         if (fwspec)
1982                 return ops == fwspec->ops ? 0 : -EINVAL;
1983
1984         fwspec = kzalloc(sizeof(*fwspec), GFP_KERNEL);
1985         if (!fwspec)
1986                 return -ENOMEM;
1987
1988         of_node_get(to_of_node(iommu_fwnode));
1989         fwspec->iommu_fwnode = iommu_fwnode;
1990         fwspec->ops = ops;
1991         dev_iommu_fwspec_set(dev, fwspec);
1992         return 0;
1993 }
1994 EXPORT_SYMBOL_GPL(iommu_fwspec_init);
1995
1996 void iommu_fwspec_free(struct device *dev)
1997 {
1998         struct iommu_fwspec *fwspec = dev_iommu_fwspec_get(dev);
1999
2000         if (fwspec) {
2001                 fwnode_handle_put(fwspec->iommu_fwnode);
2002                 kfree(fwspec);
2003                 dev_iommu_fwspec_set(dev, NULL);
2004         }
2005 }
2006 EXPORT_SYMBOL_GPL(iommu_fwspec_free);
2007
2008 int iommu_fwspec_add_ids(struct device *dev, u32 *ids, int num_ids)
2009 {
2010         struct iommu_fwspec *fwspec = dev_iommu_fwspec_get(dev);
2011         size_t size;
2012         int i;
2013
2014         if (!fwspec)
2015                 return -EINVAL;
2016
2017         size = offsetof(struct iommu_fwspec, ids[fwspec->num_ids + num_ids]);
2018         if (size > sizeof(*fwspec)) {
2019                 fwspec = krealloc(fwspec, size, GFP_KERNEL);
2020                 if (!fwspec)
2021                         return -ENOMEM;
2022
2023                 dev_iommu_fwspec_set(dev, fwspec);
2024         }
2025
2026         for (i = 0; i < num_ids; i++)
2027                 fwspec->ids[fwspec->num_ids + i] = ids[i];
2028
2029         fwspec->num_ids += num_ids;
2030         return 0;
2031 }
2032 EXPORT_SYMBOL_GPL(iommu_fwspec_add_ids);