iommu: Print default domain type on boot
[linux-2.6-microblaze.git] / drivers / iommu / iommu.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright (C) 2007-2008 Advanced Micro Devices, Inc.
4  * Author: Joerg Roedel <jroedel@suse.de>
5  */
6
7 #define pr_fmt(fmt)    "iommu: " fmt
8
9 #include <linux/device.h>
10 #include <linux/kernel.h>
11 #include <linux/bug.h>
12 #include <linux/types.h>
13 #include <linux/init.h>
14 #include <linux/export.h>
15 #include <linux/slab.h>
16 #include <linux/errno.h>
17 #include <linux/iommu.h>
18 #include <linux/idr.h>
19 #include <linux/notifier.h>
20 #include <linux/err.h>
21 #include <linux/pci.h>
22 #include <linux/bitops.h>
23 #include <linux/property.h>
24 #include <linux/fsl/mc.h>
25 #include <trace/events/iommu.h>
26
27 static struct kset *iommu_group_kset;
28 static DEFINE_IDA(iommu_group_ida);
29 #ifdef CONFIG_IOMMU_DEFAULT_PASSTHROUGH
30 static unsigned int iommu_def_domain_type = IOMMU_DOMAIN_IDENTITY;
31 #else
32 static unsigned int iommu_def_domain_type = IOMMU_DOMAIN_DMA;
33 #endif
34 static bool iommu_dma_strict __read_mostly = true;
35 static u32 iommu_cmd_line __read_mostly;
36
37 struct iommu_group {
38         struct kobject kobj;
39         struct kobject *devices_kobj;
40         struct list_head devices;
41         struct mutex mutex;
42         struct blocking_notifier_head notifier;
43         void *iommu_data;
44         void (*iommu_data_release)(void *iommu_data);
45         char *name;
46         int id;
47         struct iommu_domain *default_domain;
48         struct iommu_domain *domain;
49 };
50
51 struct group_device {
52         struct list_head list;
53         struct device *dev;
54         char *name;
55 };
56
57 struct iommu_group_attribute {
58         struct attribute attr;
59         ssize_t (*show)(struct iommu_group *group, char *buf);
60         ssize_t (*store)(struct iommu_group *group,
61                          const char *buf, size_t count);
62 };
63
64 static const char * const iommu_group_resv_type_string[] = {
65         [IOMMU_RESV_DIRECT]                     = "direct",
66         [IOMMU_RESV_DIRECT_RELAXABLE]           = "direct-relaxable",
67         [IOMMU_RESV_RESERVED]                   = "reserved",
68         [IOMMU_RESV_MSI]                        = "msi",
69         [IOMMU_RESV_SW_MSI]                     = "msi",
70 };
71
72 #define IOMMU_CMD_LINE_DMA_API          BIT(0)
73
74 static void iommu_set_cmd_line_dma_api(void)
75 {
76         iommu_cmd_line |= IOMMU_CMD_LINE_DMA_API;
77 }
78
79 static bool __maybe_unused iommu_cmd_line_dma_api(void)
80 {
81         return !!(iommu_cmd_line & IOMMU_CMD_LINE_DMA_API);
82 }
83
84 #define IOMMU_GROUP_ATTR(_name, _mode, _show, _store)           \
85 struct iommu_group_attribute iommu_group_attr_##_name =         \
86         __ATTR(_name, _mode, _show, _store)
87
88 #define to_iommu_group_attr(_attr)      \
89         container_of(_attr, struct iommu_group_attribute, attr)
90 #define to_iommu_group(_kobj)           \
91         container_of(_kobj, struct iommu_group, kobj)
92
93 static LIST_HEAD(iommu_device_list);
94 static DEFINE_SPINLOCK(iommu_device_lock);
95
96 /*
97  * Use a function instead of an array here because the domain-type is a
98  * bit-field, so an array would waste memory.
99  */
100 static const char *iommu_domain_type_str(unsigned int t)
101 {
102         switch (t) {
103         case IOMMU_DOMAIN_BLOCKED:
104                 return "Blocked";
105         case IOMMU_DOMAIN_IDENTITY:
106                 return "Passthrough";
107         case IOMMU_DOMAIN_UNMANAGED:
108                 return "Unmanaged";
109         case IOMMU_DOMAIN_DMA:
110                 return "Translated";
111         default:
112                 return "Unknown";
113         }
114 }
115
116 static int __init iommu_subsys_init(void)
117 {
118         pr_info("Default domain type: %s\n",
119                 iommu_domain_type_str(iommu_def_domain_type));
120
121         return 0;
122 }
123 subsys_initcall(iommu_subsys_init);
124
125 int iommu_device_register(struct iommu_device *iommu)
126 {
127         spin_lock(&iommu_device_lock);
128         list_add_tail(&iommu->list, &iommu_device_list);
129         spin_unlock(&iommu_device_lock);
130         return 0;
131 }
132
133 void iommu_device_unregister(struct iommu_device *iommu)
134 {
135         spin_lock(&iommu_device_lock);
136         list_del(&iommu->list);
137         spin_unlock(&iommu_device_lock);
138 }
139
140 static struct iommu_param *iommu_get_dev_param(struct device *dev)
141 {
142         struct iommu_param *param = dev->iommu_param;
143
144         if (param)
145                 return param;
146
147         param = kzalloc(sizeof(*param), GFP_KERNEL);
148         if (!param)
149                 return NULL;
150
151         mutex_init(&param->lock);
152         dev->iommu_param = param;
153         return param;
154 }
155
156 static void iommu_free_dev_param(struct device *dev)
157 {
158         kfree(dev->iommu_param);
159         dev->iommu_param = NULL;
160 }
161
162 int iommu_probe_device(struct device *dev)
163 {
164         const struct iommu_ops *ops = dev->bus->iommu_ops;
165         int ret;
166
167         WARN_ON(dev->iommu_group);
168         if (!ops)
169                 return -EINVAL;
170
171         if (!iommu_get_dev_param(dev))
172                 return -ENOMEM;
173
174         ret = ops->add_device(dev);
175         if (ret)
176                 iommu_free_dev_param(dev);
177
178         return ret;
179 }
180
181 void iommu_release_device(struct device *dev)
182 {
183         const struct iommu_ops *ops = dev->bus->iommu_ops;
184
185         if (dev->iommu_group)
186                 ops->remove_device(dev);
187
188         iommu_free_dev_param(dev);
189 }
190
191 static struct iommu_domain *__iommu_domain_alloc(struct bus_type *bus,
192                                                  unsigned type);
193 static int __iommu_attach_device(struct iommu_domain *domain,
194                                  struct device *dev);
195 static int __iommu_attach_group(struct iommu_domain *domain,
196                                 struct iommu_group *group);
197 static void __iommu_detach_group(struct iommu_domain *domain,
198                                  struct iommu_group *group);
199
200 static int __init iommu_set_def_domain_type(char *str)
201 {
202         bool pt;
203         int ret;
204
205         ret = kstrtobool(str, &pt);
206         if (ret)
207                 return ret;
208
209         if (pt)
210                 iommu_set_default_passthrough(true);
211         else
212                 iommu_set_default_translated(true);
213
214         return 0;
215 }
216 early_param("iommu.passthrough", iommu_set_def_domain_type);
217
218 static int __init iommu_dma_setup(char *str)
219 {
220         return kstrtobool(str, &iommu_dma_strict);
221 }
222 early_param("iommu.strict", iommu_dma_setup);
223
224 static ssize_t iommu_group_attr_show(struct kobject *kobj,
225                                      struct attribute *__attr, char *buf)
226 {
227         struct iommu_group_attribute *attr = to_iommu_group_attr(__attr);
228         struct iommu_group *group = to_iommu_group(kobj);
229         ssize_t ret = -EIO;
230
231         if (attr->show)
232                 ret = attr->show(group, buf);
233         return ret;
234 }
235
236 static ssize_t iommu_group_attr_store(struct kobject *kobj,
237                                       struct attribute *__attr,
238                                       const char *buf, size_t count)
239 {
240         struct iommu_group_attribute *attr = to_iommu_group_attr(__attr);
241         struct iommu_group *group = to_iommu_group(kobj);
242         ssize_t ret = -EIO;
243
244         if (attr->store)
245                 ret = attr->store(group, buf, count);
246         return ret;
247 }
248
249 static const struct sysfs_ops iommu_group_sysfs_ops = {
250         .show = iommu_group_attr_show,
251         .store = iommu_group_attr_store,
252 };
253
254 static int iommu_group_create_file(struct iommu_group *group,
255                                    struct iommu_group_attribute *attr)
256 {
257         return sysfs_create_file(&group->kobj, &attr->attr);
258 }
259
260 static void iommu_group_remove_file(struct iommu_group *group,
261                                     struct iommu_group_attribute *attr)
262 {
263         sysfs_remove_file(&group->kobj, &attr->attr);
264 }
265
266 static ssize_t iommu_group_show_name(struct iommu_group *group, char *buf)
267 {
268         return sprintf(buf, "%s\n", group->name);
269 }
270
271 /**
272  * iommu_insert_resv_region - Insert a new region in the
273  * list of reserved regions.
274  * @new: new region to insert
275  * @regions: list of regions
276  *
277  * The new element is sorted by address with respect to the other
278  * regions of the same type. In case it overlaps with another
279  * region of the same type, regions are merged. In case it
280  * overlaps with another region of different type, regions are
281  * not merged.
282  */
283 static int iommu_insert_resv_region(struct iommu_resv_region *new,
284                                     struct list_head *regions)
285 {
286         struct iommu_resv_region *region;
287         phys_addr_t start = new->start;
288         phys_addr_t end = new->start + new->length - 1;
289         struct list_head *pos = regions->next;
290
291         while (pos != regions) {
292                 struct iommu_resv_region *entry =
293                         list_entry(pos, struct iommu_resv_region, list);
294                 phys_addr_t a = entry->start;
295                 phys_addr_t b = entry->start + entry->length - 1;
296                 int type = entry->type;
297
298                 if (end < a) {
299                         goto insert;
300                 } else if (start > b) {
301                         pos = pos->next;
302                 } else if ((start >= a) && (end <= b)) {
303                         if (new->type == type)
304                                 return 0;
305                         else
306                                 pos = pos->next;
307                 } else {
308                         if (new->type == type) {
309                                 phys_addr_t new_start = min(a, start);
310                                 phys_addr_t new_end = max(b, end);
311                                 int ret;
312
313                                 list_del(&entry->list);
314                                 entry->start = new_start;
315                                 entry->length = new_end - new_start + 1;
316                                 ret = iommu_insert_resv_region(entry, regions);
317                                 kfree(entry);
318                                 return ret;
319                         } else {
320                                 pos = pos->next;
321                         }
322                 }
323         }
324 insert:
325         region = iommu_alloc_resv_region(new->start, new->length,
326                                          new->prot, new->type);
327         if (!region)
328                 return -ENOMEM;
329
330         list_add_tail(&region->list, pos);
331         return 0;
332 }
333
334 static int
335 iommu_insert_device_resv_regions(struct list_head *dev_resv_regions,
336                                  struct list_head *group_resv_regions)
337 {
338         struct iommu_resv_region *entry;
339         int ret = 0;
340
341         list_for_each_entry(entry, dev_resv_regions, list) {
342                 ret = iommu_insert_resv_region(entry, group_resv_regions);
343                 if (ret)
344                         break;
345         }
346         return ret;
347 }
348
349 int iommu_get_group_resv_regions(struct iommu_group *group,
350                                  struct list_head *head)
351 {
352         struct group_device *device;
353         int ret = 0;
354
355         mutex_lock(&group->mutex);
356         list_for_each_entry(device, &group->devices, list) {
357                 struct list_head dev_resv_regions;
358
359                 INIT_LIST_HEAD(&dev_resv_regions);
360                 iommu_get_resv_regions(device->dev, &dev_resv_regions);
361                 ret = iommu_insert_device_resv_regions(&dev_resv_regions, head);
362                 iommu_put_resv_regions(device->dev, &dev_resv_regions);
363                 if (ret)
364                         break;
365         }
366         mutex_unlock(&group->mutex);
367         return ret;
368 }
369 EXPORT_SYMBOL_GPL(iommu_get_group_resv_regions);
370
371 static ssize_t iommu_group_show_resv_regions(struct iommu_group *group,
372                                              char *buf)
373 {
374         struct iommu_resv_region *region, *next;
375         struct list_head group_resv_regions;
376         char *str = buf;
377
378         INIT_LIST_HEAD(&group_resv_regions);
379         iommu_get_group_resv_regions(group, &group_resv_regions);
380
381         list_for_each_entry_safe(region, next, &group_resv_regions, list) {
382                 str += sprintf(str, "0x%016llx 0x%016llx %s\n",
383                                (long long int)region->start,
384                                (long long int)(region->start +
385                                                 region->length - 1),
386                                iommu_group_resv_type_string[region->type]);
387                 kfree(region);
388         }
389
390         return (str - buf);
391 }
392
393 static ssize_t iommu_group_show_type(struct iommu_group *group,
394                                      char *buf)
395 {
396         char *type = "unknown\n";
397
398         if (group->default_domain) {
399                 switch (group->default_domain->type) {
400                 case IOMMU_DOMAIN_BLOCKED:
401                         type = "blocked\n";
402                         break;
403                 case IOMMU_DOMAIN_IDENTITY:
404                         type = "identity\n";
405                         break;
406                 case IOMMU_DOMAIN_UNMANAGED:
407                         type = "unmanaged\n";
408                         break;
409                 case IOMMU_DOMAIN_DMA:
410                         type = "DMA\n";
411                         break;
412                 }
413         }
414         strcpy(buf, type);
415
416         return strlen(type);
417 }
418
419 static IOMMU_GROUP_ATTR(name, S_IRUGO, iommu_group_show_name, NULL);
420
421 static IOMMU_GROUP_ATTR(reserved_regions, 0444,
422                         iommu_group_show_resv_regions, NULL);
423
424 static IOMMU_GROUP_ATTR(type, 0444, iommu_group_show_type, NULL);
425
426 static void iommu_group_release(struct kobject *kobj)
427 {
428         struct iommu_group *group = to_iommu_group(kobj);
429
430         pr_debug("Releasing group %d\n", group->id);
431
432         if (group->iommu_data_release)
433                 group->iommu_data_release(group->iommu_data);
434
435         ida_simple_remove(&iommu_group_ida, group->id);
436
437         if (group->default_domain)
438                 iommu_domain_free(group->default_domain);
439
440         kfree(group->name);
441         kfree(group);
442 }
443
444 static struct kobj_type iommu_group_ktype = {
445         .sysfs_ops = &iommu_group_sysfs_ops,
446         .release = iommu_group_release,
447 };
448
449 /**
450  * iommu_group_alloc - Allocate a new group
451  *
452  * This function is called by an iommu driver to allocate a new iommu
453  * group.  The iommu group represents the minimum granularity of the iommu.
454  * Upon successful return, the caller holds a reference to the supplied
455  * group in order to hold the group until devices are added.  Use
456  * iommu_group_put() to release this extra reference count, allowing the
457  * group to be automatically reclaimed once it has no devices or external
458  * references.
459  */
460 struct iommu_group *iommu_group_alloc(void)
461 {
462         struct iommu_group *group;
463         int ret;
464
465         group = kzalloc(sizeof(*group), GFP_KERNEL);
466         if (!group)
467                 return ERR_PTR(-ENOMEM);
468
469         group->kobj.kset = iommu_group_kset;
470         mutex_init(&group->mutex);
471         INIT_LIST_HEAD(&group->devices);
472         BLOCKING_INIT_NOTIFIER_HEAD(&group->notifier);
473
474         ret = ida_simple_get(&iommu_group_ida, 0, 0, GFP_KERNEL);
475         if (ret < 0) {
476                 kfree(group);
477                 return ERR_PTR(ret);
478         }
479         group->id = ret;
480
481         ret = kobject_init_and_add(&group->kobj, &iommu_group_ktype,
482                                    NULL, "%d", group->id);
483         if (ret) {
484                 ida_simple_remove(&iommu_group_ida, group->id);
485                 kfree(group);
486                 return ERR_PTR(ret);
487         }
488
489         group->devices_kobj = kobject_create_and_add("devices", &group->kobj);
490         if (!group->devices_kobj) {
491                 kobject_put(&group->kobj); /* triggers .release & free */
492                 return ERR_PTR(-ENOMEM);
493         }
494
495         /*
496          * The devices_kobj holds a reference on the group kobject, so
497          * as long as that exists so will the group.  We can therefore
498          * use the devices_kobj for reference counting.
499          */
500         kobject_put(&group->kobj);
501
502         ret = iommu_group_create_file(group,
503                                       &iommu_group_attr_reserved_regions);
504         if (ret)
505                 return ERR_PTR(ret);
506
507         ret = iommu_group_create_file(group, &iommu_group_attr_type);
508         if (ret)
509                 return ERR_PTR(ret);
510
511         pr_debug("Allocated group %d\n", group->id);
512
513         return group;
514 }
515 EXPORT_SYMBOL_GPL(iommu_group_alloc);
516
517 struct iommu_group *iommu_group_get_by_id(int id)
518 {
519         struct kobject *group_kobj;
520         struct iommu_group *group;
521         const char *name;
522
523         if (!iommu_group_kset)
524                 return NULL;
525
526         name = kasprintf(GFP_KERNEL, "%d", id);
527         if (!name)
528                 return NULL;
529
530         group_kobj = kset_find_obj(iommu_group_kset, name);
531         kfree(name);
532
533         if (!group_kobj)
534                 return NULL;
535
536         group = container_of(group_kobj, struct iommu_group, kobj);
537         BUG_ON(group->id != id);
538
539         kobject_get(group->devices_kobj);
540         kobject_put(&group->kobj);
541
542         return group;
543 }
544 EXPORT_SYMBOL_GPL(iommu_group_get_by_id);
545
546 /**
547  * iommu_group_get_iommudata - retrieve iommu_data registered for a group
548  * @group: the group
549  *
550  * iommu drivers can store data in the group for use when doing iommu
551  * operations.  This function provides a way to retrieve it.  Caller
552  * should hold a group reference.
553  */
554 void *iommu_group_get_iommudata(struct iommu_group *group)
555 {
556         return group->iommu_data;
557 }
558 EXPORT_SYMBOL_GPL(iommu_group_get_iommudata);
559
560 /**
561  * iommu_group_set_iommudata - set iommu_data for a group
562  * @group: the group
563  * @iommu_data: new data
564  * @release: release function for iommu_data
565  *
566  * iommu drivers can store data in the group for use when doing iommu
567  * operations.  This function provides a way to set the data after
568  * the group has been allocated.  Caller should hold a group reference.
569  */
570 void iommu_group_set_iommudata(struct iommu_group *group, void *iommu_data,
571                                void (*release)(void *iommu_data))
572 {
573         group->iommu_data = iommu_data;
574         group->iommu_data_release = release;
575 }
576 EXPORT_SYMBOL_GPL(iommu_group_set_iommudata);
577
578 /**
579  * iommu_group_set_name - set name for a group
580  * @group: the group
581  * @name: name
582  *
583  * Allow iommu driver to set a name for a group.  When set it will
584  * appear in a name attribute file under the group in sysfs.
585  */
586 int iommu_group_set_name(struct iommu_group *group, const char *name)
587 {
588         int ret;
589
590         if (group->name) {
591                 iommu_group_remove_file(group, &iommu_group_attr_name);
592                 kfree(group->name);
593                 group->name = NULL;
594                 if (!name)
595                         return 0;
596         }
597
598         group->name = kstrdup(name, GFP_KERNEL);
599         if (!group->name)
600                 return -ENOMEM;
601
602         ret = iommu_group_create_file(group, &iommu_group_attr_name);
603         if (ret) {
604                 kfree(group->name);
605                 group->name = NULL;
606                 return ret;
607         }
608
609         return 0;
610 }
611 EXPORT_SYMBOL_GPL(iommu_group_set_name);
612
613 static int iommu_group_create_direct_mappings(struct iommu_group *group,
614                                               struct device *dev)
615 {
616         struct iommu_domain *domain = group->default_domain;
617         struct iommu_resv_region *entry;
618         struct list_head mappings;
619         unsigned long pg_size;
620         int ret = 0;
621
622         if (!domain || domain->type != IOMMU_DOMAIN_DMA)
623                 return 0;
624
625         BUG_ON(!domain->pgsize_bitmap);
626
627         pg_size = 1UL << __ffs(domain->pgsize_bitmap);
628         INIT_LIST_HEAD(&mappings);
629
630         iommu_get_resv_regions(dev, &mappings);
631
632         /* We need to consider overlapping regions for different devices */
633         list_for_each_entry(entry, &mappings, list) {
634                 dma_addr_t start, end, addr;
635
636                 if (domain->ops->apply_resv_region)
637                         domain->ops->apply_resv_region(dev, domain, entry);
638
639                 start = ALIGN(entry->start, pg_size);
640                 end   = ALIGN(entry->start + entry->length, pg_size);
641
642                 if (entry->type != IOMMU_RESV_DIRECT &&
643                     entry->type != IOMMU_RESV_DIRECT_RELAXABLE)
644                         continue;
645
646                 for (addr = start; addr < end; addr += pg_size) {
647                         phys_addr_t phys_addr;
648
649                         phys_addr = iommu_iova_to_phys(domain, addr);
650                         if (phys_addr)
651                                 continue;
652
653                         ret = iommu_map(domain, addr, addr, pg_size, entry->prot);
654                         if (ret)
655                                 goto out;
656                 }
657
658         }
659
660         iommu_flush_tlb_all(domain);
661
662 out:
663         iommu_put_resv_regions(dev, &mappings);
664
665         return ret;
666 }
667
668 /**
669  * iommu_group_add_device - add a device to an iommu group
670  * @group: the group into which to add the device (reference should be held)
671  * @dev: the device
672  *
673  * This function is called by an iommu driver to add a device into a
674  * group.  Adding a device increments the group reference count.
675  */
676 int iommu_group_add_device(struct iommu_group *group, struct device *dev)
677 {
678         int ret, i = 0;
679         struct group_device *device;
680
681         device = kzalloc(sizeof(*device), GFP_KERNEL);
682         if (!device)
683                 return -ENOMEM;
684
685         device->dev = dev;
686
687         ret = sysfs_create_link(&dev->kobj, &group->kobj, "iommu_group");
688         if (ret)
689                 goto err_free_device;
690
691         device->name = kasprintf(GFP_KERNEL, "%s", kobject_name(&dev->kobj));
692 rename:
693         if (!device->name) {
694                 ret = -ENOMEM;
695                 goto err_remove_link;
696         }
697
698         ret = sysfs_create_link_nowarn(group->devices_kobj,
699                                        &dev->kobj, device->name);
700         if (ret) {
701                 if (ret == -EEXIST && i >= 0) {
702                         /*
703                          * Account for the slim chance of collision
704                          * and append an instance to the name.
705                          */
706                         kfree(device->name);
707                         device->name = kasprintf(GFP_KERNEL, "%s.%d",
708                                                  kobject_name(&dev->kobj), i++);
709                         goto rename;
710                 }
711                 goto err_free_name;
712         }
713
714         kobject_get(group->devices_kobj);
715
716         dev->iommu_group = group;
717
718         iommu_group_create_direct_mappings(group, dev);
719
720         mutex_lock(&group->mutex);
721         list_add_tail(&device->list, &group->devices);
722         if (group->domain)
723                 ret = __iommu_attach_device(group->domain, dev);
724         mutex_unlock(&group->mutex);
725         if (ret)
726                 goto err_put_group;
727
728         /* Notify any listeners about change to group. */
729         blocking_notifier_call_chain(&group->notifier,
730                                      IOMMU_GROUP_NOTIFY_ADD_DEVICE, dev);
731
732         trace_add_device_to_group(group->id, dev);
733
734         dev_info(dev, "Adding to iommu group %d\n", group->id);
735
736         return 0;
737
738 err_put_group:
739         mutex_lock(&group->mutex);
740         list_del(&device->list);
741         mutex_unlock(&group->mutex);
742         dev->iommu_group = NULL;
743         kobject_put(group->devices_kobj);
744 err_free_name:
745         kfree(device->name);
746 err_remove_link:
747         sysfs_remove_link(&dev->kobj, "iommu_group");
748 err_free_device:
749         kfree(device);
750         dev_err(dev, "Failed to add to iommu group %d: %d\n", group->id, ret);
751         return ret;
752 }
753 EXPORT_SYMBOL_GPL(iommu_group_add_device);
754
755 /**
756  * iommu_group_remove_device - remove a device from it's current group
757  * @dev: device to be removed
758  *
759  * This function is called by an iommu driver to remove the device from
760  * it's current group.  This decrements the iommu group reference count.
761  */
762 void iommu_group_remove_device(struct device *dev)
763 {
764         struct iommu_group *group = dev->iommu_group;
765         struct group_device *tmp_device, *device = NULL;
766
767         dev_info(dev, "Removing from iommu group %d\n", group->id);
768
769         /* Pre-notify listeners that a device is being removed. */
770         blocking_notifier_call_chain(&group->notifier,
771                                      IOMMU_GROUP_NOTIFY_DEL_DEVICE, dev);
772
773         mutex_lock(&group->mutex);
774         list_for_each_entry(tmp_device, &group->devices, list) {
775                 if (tmp_device->dev == dev) {
776                         device = tmp_device;
777                         list_del(&device->list);
778                         break;
779                 }
780         }
781         mutex_unlock(&group->mutex);
782
783         if (!device)
784                 return;
785
786         sysfs_remove_link(group->devices_kobj, device->name);
787         sysfs_remove_link(&dev->kobj, "iommu_group");
788
789         trace_remove_device_from_group(group->id, dev);
790
791         kfree(device->name);
792         kfree(device);
793         dev->iommu_group = NULL;
794         kobject_put(group->devices_kobj);
795 }
796 EXPORT_SYMBOL_GPL(iommu_group_remove_device);
797
798 static int iommu_group_device_count(struct iommu_group *group)
799 {
800         struct group_device *entry;
801         int ret = 0;
802
803         list_for_each_entry(entry, &group->devices, list)
804                 ret++;
805
806         return ret;
807 }
808
809 /**
810  * iommu_group_for_each_dev - iterate over each device in the group
811  * @group: the group
812  * @data: caller opaque data to be passed to callback function
813  * @fn: caller supplied callback function
814  *
815  * This function is called by group users to iterate over group devices.
816  * Callers should hold a reference count to the group during callback.
817  * The group->mutex is held across callbacks, which will block calls to
818  * iommu_group_add/remove_device.
819  */
820 static int __iommu_group_for_each_dev(struct iommu_group *group, void *data,
821                                       int (*fn)(struct device *, void *))
822 {
823         struct group_device *device;
824         int ret = 0;
825
826         list_for_each_entry(device, &group->devices, list) {
827                 ret = fn(device->dev, data);
828                 if (ret)
829                         break;
830         }
831         return ret;
832 }
833
834
835 int iommu_group_for_each_dev(struct iommu_group *group, void *data,
836                              int (*fn)(struct device *, void *))
837 {
838         int ret;
839
840         mutex_lock(&group->mutex);
841         ret = __iommu_group_for_each_dev(group, data, fn);
842         mutex_unlock(&group->mutex);
843
844         return ret;
845 }
846 EXPORT_SYMBOL_GPL(iommu_group_for_each_dev);
847
848 /**
849  * iommu_group_get - Return the group for a device and increment reference
850  * @dev: get the group that this device belongs to
851  *
852  * This function is called by iommu drivers and users to get the group
853  * for the specified device.  If found, the group is returned and the group
854  * reference in incremented, else NULL.
855  */
856 struct iommu_group *iommu_group_get(struct device *dev)
857 {
858         struct iommu_group *group = dev->iommu_group;
859
860         if (group)
861                 kobject_get(group->devices_kobj);
862
863         return group;
864 }
865 EXPORT_SYMBOL_GPL(iommu_group_get);
866
867 /**
868  * iommu_group_ref_get - Increment reference on a group
869  * @group: the group to use, must not be NULL
870  *
871  * This function is called by iommu drivers to take additional references on an
872  * existing group.  Returns the given group for convenience.
873  */
874 struct iommu_group *iommu_group_ref_get(struct iommu_group *group)
875 {
876         kobject_get(group->devices_kobj);
877         return group;
878 }
879
880 /**
881  * iommu_group_put - Decrement group reference
882  * @group: the group to use
883  *
884  * This function is called by iommu drivers and users to release the
885  * iommu group.  Once the reference count is zero, the group is released.
886  */
887 void iommu_group_put(struct iommu_group *group)
888 {
889         if (group)
890                 kobject_put(group->devices_kobj);
891 }
892 EXPORT_SYMBOL_GPL(iommu_group_put);
893
894 /**
895  * iommu_group_register_notifier - Register a notifier for group changes
896  * @group: the group to watch
897  * @nb: notifier block to signal
898  *
899  * This function allows iommu group users to track changes in a group.
900  * See include/linux/iommu.h for actions sent via this notifier.  Caller
901  * should hold a reference to the group throughout notifier registration.
902  */
903 int iommu_group_register_notifier(struct iommu_group *group,
904                                   struct notifier_block *nb)
905 {
906         return blocking_notifier_chain_register(&group->notifier, nb);
907 }
908 EXPORT_SYMBOL_GPL(iommu_group_register_notifier);
909
910 /**
911  * iommu_group_unregister_notifier - Unregister a notifier
912  * @group: the group to watch
913  * @nb: notifier block to signal
914  *
915  * Unregister a previously registered group notifier block.
916  */
917 int iommu_group_unregister_notifier(struct iommu_group *group,
918                                     struct notifier_block *nb)
919 {
920         return blocking_notifier_chain_unregister(&group->notifier, nb);
921 }
922 EXPORT_SYMBOL_GPL(iommu_group_unregister_notifier);
923
924 /**
925  * iommu_register_device_fault_handler() - Register a device fault handler
926  * @dev: the device
927  * @handler: the fault handler
928  * @data: private data passed as argument to the handler
929  *
930  * When an IOMMU fault event is received, this handler gets called with the
931  * fault event and data as argument. The handler should return 0 on success. If
932  * the fault is recoverable (IOMMU_FAULT_PAGE_REQ), the consumer should also
933  * complete the fault by calling iommu_page_response() with one of the following
934  * response code:
935  * - IOMMU_PAGE_RESP_SUCCESS: retry the translation
936  * - IOMMU_PAGE_RESP_INVALID: terminate the fault
937  * - IOMMU_PAGE_RESP_FAILURE: terminate the fault and stop reporting
938  *   page faults if possible.
939  *
940  * Return 0 if the fault handler was installed successfully, or an error.
941  */
942 int iommu_register_device_fault_handler(struct device *dev,
943                                         iommu_dev_fault_handler_t handler,
944                                         void *data)
945 {
946         struct iommu_param *param = dev->iommu_param;
947         int ret = 0;
948
949         if (!param)
950                 return -EINVAL;
951
952         mutex_lock(&param->lock);
953         /* Only allow one fault handler registered for each device */
954         if (param->fault_param) {
955                 ret = -EBUSY;
956                 goto done_unlock;
957         }
958
959         get_device(dev);
960         param->fault_param = kzalloc(sizeof(*param->fault_param), GFP_KERNEL);
961         if (!param->fault_param) {
962                 put_device(dev);
963                 ret = -ENOMEM;
964                 goto done_unlock;
965         }
966         param->fault_param->handler = handler;
967         param->fault_param->data = data;
968         mutex_init(&param->fault_param->lock);
969         INIT_LIST_HEAD(&param->fault_param->faults);
970
971 done_unlock:
972         mutex_unlock(&param->lock);
973
974         return ret;
975 }
976 EXPORT_SYMBOL_GPL(iommu_register_device_fault_handler);
977
978 /**
979  * iommu_unregister_device_fault_handler() - Unregister the device fault handler
980  * @dev: the device
981  *
982  * Remove the device fault handler installed with
983  * iommu_register_device_fault_handler().
984  *
985  * Return 0 on success, or an error.
986  */
987 int iommu_unregister_device_fault_handler(struct device *dev)
988 {
989         struct iommu_param *param = dev->iommu_param;
990         int ret = 0;
991
992         if (!param)
993                 return -EINVAL;
994
995         mutex_lock(&param->lock);
996
997         if (!param->fault_param)
998                 goto unlock;
999
1000         /* we cannot unregister handler if there are pending faults */
1001         if (!list_empty(&param->fault_param->faults)) {
1002                 ret = -EBUSY;
1003                 goto unlock;
1004         }
1005
1006         kfree(param->fault_param);
1007         param->fault_param = NULL;
1008         put_device(dev);
1009 unlock:
1010         mutex_unlock(&param->lock);
1011
1012         return ret;
1013 }
1014 EXPORT_SYMBOL_GPL(iommu_unregister_device_fault_handler);
1015
1016 /**
1017  * iommu_report_device_fault() - Report fault event to device driver
1018  * @dev: the device
1019  * @evt: fault event data
1020  *
1021  * Called by IOMMU drivers when a fault is detected, typically in a threaded IRQ
1022  * handler. When this function fails and the fault is recoverable, it is the
1023  * caller's responsibility to complete the fault.
1024  *
1025  * Return 0 on success, or an error.
1026  */
1027 int iommu_report_device_fault(struct device *dev, struct iommu_fault_event *evt)
1028 {
1029         struct iommu_param *param = dev->iommu_param;
1030         struct iommu_fault_event *evt_pending = NULL;
1031         struct iommu_fault_param *fparam;
1032         int ret = 0;
1033
1034         if (!param || !evt)
1035                 return -EINVAL;
1036
1037         /* we only report device fault if there is a handler registered */
1038         mutex_lock(&param->lock);
1039         fparam = param->fault_param;
1040         if (!fparam || !fparam->handler) {
1041                 ret = -EINVAL;
1042                 goto done_unlock;
1043         }
1044
1045         if (evt->fault.type == IOMMU_FAULT_PAGE_REQ &&
1046             (evt->fault.prm.flags & IOMMU_FAULT_PAGE_REQUEST_LAST_PAGE)) {
1047                 evt_pending = kmemdup(evt, sizeof(struct iommu_fault_event),
1048                                       GFP_KERNEL);
1049                 if (!evt_pending) {
1050                         ret = -ENOMEM;
1051                         goto done_unlock;
1052                 }
1053                 mutex_lock(&fparam->lock);
1054                 list_add_tail(&evt_pending->list, &fparam->faults);
1055                 mutex_unlock(&fparam->lock);
1056         }
1057
1058         ret = fparam->handler(&evt->fault, fparam->data);
1059         if (ret && evt_pending) {
1060                 mutex_lock(&fparam->lock);
1061                 list_del(&evt_pending->list);
1062                 mutex_unlock(&fparam->lock);
1063                 kfree(evt_pending);
1064         }
1065 done_unlock:
1066         mutex_unlock(&param->lock);
1067         return ret;
1068 }
1069 EXPORT_SYMBOL_GPL(iommu_report_device_fault);
1070
1071 int iommu_page_response(struct device *dev,
1072                         struct iommu_page_response *msg)
1073 {
1074         bool pasid_valid;
1075         int ret = -EINVAL;
1076         struct iommu_fault_event *evt;
1077         struct iommu_fault_page_request *prm;
1078         struct iommu_param *param = dev->iommu_param;
1079         struct iommu_domain *domain = iommu_get_domain_for_dev(dev);
1080
1081         if (!domain || !domain->ops->page_response)
1082                 return -ENODEV;
1083
1084         if (!param || !param->fault_param)
1085                 return -EINVAL;
1086
1087         if (msg->version != IOMMU_PAGE_RESP_VERSION_1 ||
1088             msg->flags & ~IOMMU_PAGE_RESP_PASID_VALID)
1089                 return -EINVAL;
1090
1091         /* Only send response if there is a fault report pending */
1092         mutex_lock(&param->fault_param->lock);
1093         if (list_empty(&param->fault_param->faults)) {
1094                 dev_warn_ratelimited(dev, "no pending PRQ, drop response\n");
1095                 goto done_unlock;
1096         }
1097         /*
1098          * Check if we have a matching page request pending to respond,
1099          * otherwise return -EINVAL
1100          */
1101         list_for_each_entry(evt, &param->fault_param->faults, list) {
1102                 prm = &evt->fault.prm;
1103                 pasid_valid = prm->flags & IOMMU_FAULT_PAGE_REQUEST_PASID_VALID;
1104
1105                 if ((pasid_valid && prm->pasid != msg->pasid) ||
1106                     prm->grpid != msg->grpid)
1107                         continue;
1108
1109                 /* Sanitize the reply */
1110                 msg->flags = pasid_valid ? IOMMU_PAGE_RESP_PASID_VALID : 0;
1111
1112                 ret = domain->ops->page_response(dev, evt, msg);
1113                 list_del(&evt->list);
1114                 kfree(evt);
1115                 break;
1116         }
1117
1118 done_unlock:
1119         mutex_unlock(&param->fault_param->lock);
1120         return ret;
1121 }
1122 EXPORT_SYMBOL_GPL(iommu_page_response);
1123
1124 /**
1125  * iommu_group_id - Return ID for a group
1126  * @group: the group to ID
1127  *
1128  * Return the unique ID for the group matching the sysfs group number.
1129  */
1130 int iommu_group_id(struct iommu_group *group)
1131 {
1132         return group->id;
1133 }
1134 EXPORT_SYMBOL_GPL(iommu_group_id);
1135
1136 static struct iommu_group *get_pci_alias_group(struct pci_dev *pdev,
1137                                                unsigned long *devfns);
1138
1139 /*
1140  * To consider a PCI device isolated, we require ACS to support Source
1141  * Validation, Request Redirection, Completer Redirection, and Upstream
1142  * Forwarding.  This effectively means that devices cannot spoof their
1143  * requester ID, requests and completions cannot be redirected, and all
1144  * transactions are forwarded upstream, even as it passes through a
1145  * bridge where the target device is downstream.
1146  */
1147 #define REQ_ACS_FLAGS   (PCI_ACS_SV | PCI_ACS_RR | PCI_ACS_CR | PCI_ACS_UF)
1148
1149 /*
1150  * For multifunction devices which are not isolated from each other, find
1151  * all the other non-isolated functions and look for existing groups.  For
1152  * each function, we also need to look for aliases to or from other devices
1153  * that may already have a group.
1154  */
1155 static struct iommu_group *get_pci_function_alias_group(struct pci_dev *pdev,
1156                                                         unsigned long *devfns)
1157 {
1158         struct pci_dev *tmp = NULL;
1159         struct iommu_group *group;
1160
1161         if (!pdev->multifunction || pci_acs_enabled(pdev, REQ_ACS_FLAGS))
1162                 return NULL;
1163
1164         for_each_pci_dev(tmp) {
1165                 if (tmp == pdev || tmp->bus != pdev->bus ||
1166                     PCI_SLOT(tmp->devfn) != PCI_SLOT(pdev->devfn) ||
1167                     pci_acs_enabled(tmp, REQ_ACS_FLAGS))
1168                         continue;
1169
1170                 group = get_pci_alias_group(tmp, devfns);
1171                 if (group) {
1172                         pci_dev_put(tmp);
1173                         return group;
1174                 }
1175         }
1176
1177         return NULL;
1178 }
1179
1180 /*
1181  * Look for aliases to or from the given device for existing groups. DMA
1182  * aliases are only supported on the same bus, therefore the search
1183  * space is quite small (especially since we're really only looking at pcie
1184  * device, and therefore only expect multiple slots on the root complex or
1185  * downstream switch ports).  It's conceivable though that a pair of
1186  * multifunction devices could have aliases between them that would cause a
1187  * loop.  To prevent this, we use a bitmap to track where we've been.
1188  */
1189 static struct iommu_group *get_pci_alias_group(struct pci_dev *pdev,
1190                                                unsigned long *devfns)
1191 {
1192         struct pci_dev *tmp = NULL;
1193         struct iommu_group *group;
1194
1195         if (test_and_set_bit(pdev->devfn & 0xff, devfns))
1196                 return NULL;
1197
1198         group = iommu_group_get(&pdev->dev);
1199         if (group)
1200                 return group;
1201
1202         for_each_pci_dev(tmp) {
1203                 if (tmp == pdev || tmp->bus != pdev->bus)
1204                         continue;
1205
1206                 /* We alias them or they alias us */
1207                 if (pci_devs_are_dma_aliases(pdev, tmp)) {
1208                         group = get_pci_alias_group(tmp, devfns);
1209                         if (group) {
1210                                 pci_dev_put(tmp);
1211                                 return group;
1212                         }
1213
1214                         group = get_pci_function_alias_group(tmp, devfns);
1215                         if (group) {
1216                                 pci_dev_put(tmp);
1217                                 return group;
1218                         }
1219                 }
1220         }
1221
1222         return NULL;
1223 }
1224
1225 struct group_for_pci_data {
1226         struct pci_dev *pdev;
1227         struct iommu_group *group;
1228 };
1229
1230 /*
1231  * DMA alias iterator callback, return the last seen device.  Stop and return
1232  * the IOMMU group if we find one along the way.
1233  */
1234 static int get_pci_alias_or_group(struct pci_dev *pdev, u16 alias, void *opaque)
1235 {
1236         struct group_for_pci_data *data = opaque;
1237
1238         data->pdev = pdev;
1239         data->group = iommu_group_get(&pdev->dev);
1240
1241         return data->group != NULL;
1242 }
1243
1244 /*
1245  * Generic device_group call-back function. It just allocates one
1246  * iommu-group per device.
1247  */
1248 struct iommu_group *generic_device_group(struct device *dev)
1249 {
1250         return iommu_group_alloc();
1251 }
1252
1253 /*
1254  * Use standard PCI bus topology, isolation features, and DMA alias quirks
1255  * to find or create an IOMMU group for a device.
1256  */
1257 struct iommu_group *pci_device_group(struct device *dev)
1258 {
1259         struct pci_dev *pdev = to_pci_dev(dev);
1260         struct group_for_pci_data data;
1261         struct pci_bus *bus;
1262         struct iommu_group *group = NULL;
1263         u64 devfns[4] = { 0 };
1264
1265         if (WARN_ON(!dev_is_pci(dev)))
1266                 return ERR_PTR(-EINVAL);
1267
1268         /*
1269          * Find the upstream DMA alias for the device.  A device must not
1270          * be aliased due to topology in order to have its own IOMMU group.
1271          * If we find an alias along the way that already belongs to a
1272          * group, use it.
1273          */
1274         if (pci_for_each_dma_alias(pdev, get_pci_alias_or_group, &data))
1275                 return data.group;
1276
1277         pdev = data.pdev;
1278
1279         /*
1280          * Continue upstream from the point of minimum IOMMU granularity
1281          * due to aliases to the point where devices are protected from
1282          * peer-to-peer DMA by PCI ACS.  Again, if we find an existing
1283          * group, use it.
1284          */
1285         for (bus = pdev->bus; !pci_is_root_bus(bus); bus = bus->parent) {
1286                 if (!bus->self)
1287                         continue;
1288
1289                 if (pci_acs_path_enabled(bus->self, NULL, REQ_ACS_FLAGS))
1290                         break;
1291
1292                 pdev = bus->self;
1293
1294                 group = iommu_group_get(&pdev->dev);
1295                 if (group)
1296                         return group;
1297         }
1298
1299         /*
1300          * Look for existing groups on device aliases.  If we alias another
1301          * device or another device aliases us, use the same group.
1302          */
1303         group = get_pci_alias_group(pdev, (unsigned long *)devfns);
1304         if (group)
1305                 return group;
1306
1307         /*
1308          * Look for existing groups on non-isolated functions on the same
1309          * slot and aliases of those funcions, if any.  No need to clear
1310          * the search bitmap, the tested devfns are still valid.
1311          */
1312         group = get_pci_function_alias_group(pdev, (unsigned long *)devfns);
1313         if (group)
1314                 return group;
1315
1316         /* No shared group found, allocate new */
1317         return iommu_group_alloc();
1318 }
1319
1320 /* Get the IOMMU group for device on fsl-mc bus */
1321 struct iommu_group *fsl_mc_device_group(struct device *dev)
1322 {
1323         struct device *cont_dev = fsl_mc_cont_dev(dev);
1324         struct iommu_group *group;
1325
1326         group = iommu_group_get(cont_dev);
1327         if (!group)
1328                 group = iommu_group_alloc();
1329         return group;
1330 }
1331
1332 /**
1333  * iommu_group_get_for_dev - Find or create the IOMMU group for a device
1334  * @dev: target device
1335  *
1336  * This function is intended to be called by IOMMU drivers and extended to
1337  * support common, bus-defined algorithms when determining or creating the
1338  * IOMMU group for a device.  On success, the caller will hold a reference
1339  * to the returned IOMMU group, which will already include the provided
1340  * device.  The reference should be released with iommu_group_put().
1341  */
1342 struct iommu_group *iommu_group_get_for_dev(struct device *dev)
1343 {
1344         const struct iommu_ops *ops = dev->bus->iommu_ops;
1345         struct iommu_group *group;
1346         int ret;
1347
1348         group = iommu_group_get(dev);
1349         if (group)
1350                 return group;
1351
1352         if (!ops)
1353                 return ERR_PTR(-EINVAL);
1354
1355         group = ops->device_group(dev);
1356         if (WARN_ON_ONCE(group == NULL))
1357                 return ERR_PTR(-EINVAL);
1358
1359         if (IS_ERR(group))
1360                 return group;
1361
1362         /*
1363          * Try to allocate a default domain - needs support from the
1364          * IOMMU driver.
1365          */
1366         if (!group->default_domain) {
1367                 struct iommu_domain *dom;
1368
1369                 dom = __iommu_domain_alloc(dev->bus, iommu_def_domain_type);
1370                 if (!dom && iommu_def_domain_type != IOMMU_DOMAIN_DMA) {
1371                         dom = __iommu_domain_alloc(dev->bus, IOMMU_DOMAIN_DMA);
1372                         if (dom) {
1373                                 dev_warn(dev,
1374                                          "failed to allocate default IOMMU domain of type %u; falling back to IOMMU_DOMAIN_DMA",
1375                                          iommu_def_domain_type);
1376                         }
1377                 }
1378
1379                 group->default_domain = dom;
1380                 if (!group->domain)
1381                         group->domain = dom;
1382
1383                 if (dom && !iommu_dma_strict) {
1384                         int attr = 1;
1385                         iommu_domain_set_attr(dom,
1386                                               DOMAIN_ATTR_DMA_USE_FLUSH_QUEUE,
1387                                               &attr);
1388                 }
1389         }
1390
1391         ret = iommu_group_add_device(group, dev);
1392         if (ret) {
1393                 iommu_group_put(group);
1394                 return ERR_PTR(ret);
1395         }
1396
1397         return group;
1398 }
1399
1400 struct iommu_domain *iommu_group_default_domain(struct iommu_group *group)
1401 {
1402         return group->default_domain;
1403 }
1404
1405 static int add_iommu_group(struct device *dev, void *data)
1406 {
1407         int ret = iommu_probe_device(dev);
1408
1409         /*
1410          * We ignore -ENODEV errors for now, as they just mean that the
1411          * device is not translated by an IOMMU. We still care about
1412          * other errors and fail to initialize when they happen.
1413          */
1414         if (ret == -ENODEV)
1415                 ret = 0;
1416
1417         return ret;
1418 }
1419
1420 static int remove_iommu_group(struct device *dev, void *data)
1421 {
1422         iommu_release_device(dev);
1423
1424         return 0;
1425 }
1426
1427 static int iommu_bus_notifier(struct notifier_block *nb,
1428                               unsigned long action, void *data)
1429 {
1430         unsigned long group_action = 0;
1431         struct device *dev = data;
1432         struct iommu_group *group;
1433
1434         /*
1435          * ADD/DEL call into iommu driver ops if provided, which may
1436          * result in ADD/DEL notifiers to group->notifier
1437          */
1438         if (action == BUS_NOTIFY_ADD_DEVICE) {
1439                 int ret;
1440
1441                 ret = iommu_probe_device(dev);
1442                 return (ret) ? NOTIFY_DONE : NOTIFY_OK;
1443         } else if (action == BUS_NOTIFY_REMOVED_DEVICE) {
1444                 iommu_release_device(dev);
1445                 return NOTIFY_OK;
1446         }
1447
1448         /*
1449          * Remaining BUS_NOTIFYs get filtered and republished to the
1450          * group, if anyone is listening
1451          */
1452         group = iommu_group_get(dev);
1453         if (!group)
1454                 return 0;
1455
1456         switch (action) {
1457         case BUS_NOTIFY_BIND_DRIVER:
1458                 group_action = IOMMU_GROUP_NOTIFY_BIND_DRIVER;
1459                 break;
1460         case BUS_NOTIFY_BOUND_DRIVER:
1461                 group_action = IOMMU_GROUP_NOTIFY_BOUND_DRIVER;
1462                 break;
1463         case BUS_NOTIFY_UNBIND_DRIVER:
1464                 group_action = IOMMU_GROUP_NOTIFY_UNBIND_DRIVER;
1465                 break;
1466         case BUS_NOTIFY_UNBOUND_DRIVER:
1467                 group_action = IOMMU_GROUP_NOTIFY_UNBOUND_DRIVER;
1468                 break;
1469         }
1470
1471         if (group_action)
1472                 blocking_notifier_call_chain(&group->notifier,
1473                                              group_action, dev);
1474
1475         iommu_group_put(group);
1476         return 0;
1477 }
1478
1479 static int iommu_bus_init(struct bus_type *bus, const struct iommu_ops *ops)
1480 {
1481         int err;
1482         struct notifier_block *nb;
1483
1484         nb = kzalloc(sizeof(struct notifier_block), GFP_KERNEL);
1485         if (!nb)
1486                 return -ENOMEM;
1487
1488         nb->notifier_call = iommu_bus_notifier;
1489
1490         err = bus_register_notifier(bus, nb);
1491         if (err)
1492                 goto out_free;
1493
1494         err = bus_for_each_dev(bus, NULL, NULL, add_iommu_group);
1495         if (err)
1496                 goto out_err;
1497
1498
1499         return 0;
1500
1501 out_err:
1502         /* Clean up */
1503         bus_for_each_dev(bus, NULL, NULL, remove_iommu_group);
1504         bus_unregister_notifier(bus, nb);
1505
1506 out_free:
1507         kfree(nb);
1508
1509         return err;
1510 }
1511
1512 /**
1513  * bus_set_iommu - set iommu-callbacks for the bus
1514  * @bus: bus.
1515  * @ops: the callbacks provided by the iommu-driver
1516  *
1517  * This function is called by an iommu driver to set the iommu methods
1518  * used for a particular bus. Drivers for devices on that bus can use
1519  * the iommu-api after these ops are registered.
1520  * This special function is needed because IOMMUs are usually devices on
1521  * the bus itself, so the iommu drivers are not initialized when the bus
1522  * is set up. With this function the iommu-driver can set the iommu-ops
1523  * afterwards.
1524  */
1525 int bus_set_iommu(struct bus_type *bus, const struct iommu_ops *ops)
1526 {
1527         int err;
1528
1529         if (bus->iommu_ops != NULL)
1530                 return -EBUSY;
1531
1532         bus->iommu_ops = ops;
1533
1534         /* Do IOMMU specific setup for this bus-type */
1535         err = iommu_bus_init(bus, ops);
1536         if (err)
1537                 bus->iommu_ops = NULL;
1538
1539         return err;
1540 }
1541 EXPORT_SYMBOL_GPL(bus_set_iommu);
1542
1543 bool iommu_present(struct bus_type *bus)
1544 {
1545         return bus->iommu_ops != NULL;
1546 }
1547 EXPORT_SYMBOL_GPL(iommu_present);
1548
1549 bool iommu_capable(struct bus_type *bus, enum iommu_cap cap)
1550 {
1551         if (!bus->iommu_ops || !bus->iommu_ops->capable)
1552                 return false;
1553
1554         return bus->iommu_ops->capable(cap);
1555 }
1556 EXPORT_SYMBOL_GPL(iommu_capable);
1557
1558 /**
1559  * iommu_set_fault_handler() - set a fault handler for an iommu domain
1560  * @domain: iommu domain
1561  * @handler: fault handler
1562  * @token: user data, will be passed back to the fault handler
1563  *
1564  * This function should be used by IOMMU users which want to be notified
1565  * whenever an IOMMU fault happens.
1566  *
1567  * The fault handler itself should return 0 on success, and an appropriate
1568  * error code otherwise.
1569  */
1570 void iommu_set_fault_handler(struct iommu_domain *domain,
1571                                         iommu_fault_handler_t handler,
1572                                         void *token)
1573 {
1574         BUG_ON(!domain);
1575
1576         domain->handler = handler;
1577         domain->handler_token = token;
1578 }
1579 EXPORT_SYMBOL_GPL(iommu_set_fault_handler);
1580
1581 static struct iommu_domain *__iommu_domain_alloc(struct bus_type *bus,
1582                                                  unsigned type)
1583 {
1584         struct iommu_domain *domain;
1585
1586         if (bus == NULL || bus->iommu_ops == NULL)
1587                 return NULL;
1588
1589         domain = bus->iommu_ops->domain_alloc(type);
1590         if (!domain)
1591                 return NULL;
1592
1593         domain->ops  = bus->iommu_ops;
1594         domain->type = type;
1595         /* Assume all sizes by default; the driver may override this later */
1596         domain->pgsize_bitmap  = bus->iommu_ops->pgsize_bitmap;
1597
1598         return domain;
1599 }
1600
1601 struct iommu_domain *iommu_domain_alloc(struct bus_type *bus)
1602 {
1603         return __iommu_domain_alloc(bus, IOMMU_DOMAIN_UNMANAGED);
1604 }
1605 EXPORT_SYMBOL_GPL(iommu_domain_alloc);
1606
1607 void iommu_domain_free(struct iommu_domain *domain)
1608 {
1609         domain->ops->domain_free(domain);
1610 }
1611 EXPORT_SYMBOL_GPL(iommu_domain_free);
1612
1613 static int __iommu_attach_device(struct iommu_domain *domain,
1614                                  struct device *dev)
1615 {
1616         int ret;
1617         if ((domain->ops->is_attach_deferred != NULL) &&
1618             domain->ops->is_attach_deferred(domain, dev))
1619                 return 0;
1620
1621         if (unlikely(domain->ops->attach_dev == NULL))
1622                 return -ENODEV;
1623
1624         ret = domain->ops->attach_dev(domain, dev);
1625         if (!ret)
1626                 trace_attach_device_to_domain(dev);
1627         return ret;
1628 }
1629
1630 int iommu_attach_device(struct iommu_domain *domain, struct device *dev)
1631 {
1632         struct iommu_group *group;
1633         int ret;
1634
1635         group = iommu_group_get(dev);
1636         if (!group)
1637                 return -ENODEV;
1638
1639         /*
1640          * Lock the group to make sure the device-count doesn't
1641          * change while we are attaching
1642          */
1643         mutex_lock(&group->mutex);
1644         ret = -EINVAL;
1645         if (iommu_group_device_count(group) != 1)
1646                 goto out_unlock;
1647
1648         ret = __iommu_attach_group(domain, group);
1649
1650 out_unlock:
1651         mutex_unlock(&group->mutex);
1652         iommu_group_put(group);
1653
1654         return ret;
1655 }
1656 EXPORT_SYMBOL_GPL(iommu_attach_device);
1657
1658 static void __iommu_detach_device(struct iommu_domain *domain,
1659                                   struct device *dev)
1660 {
1661         if ((domain->ops->is_attach_deferred != NULL) &&
1662             domain->ops->is_attach_deferred(domain, dev))
1663                 return;
1664
1665         if (unlikely(domain->ops->detach_dev == NULL))
1666                 return;
1667
1668         domain->ops->detach_dev(domain, dev);
1669         trace_detach_device_from_domain(dev);
1670 }
1671
1672 void iommu_detach_device(struct iommu_domain *domain, struct device *dev)
1673 {
1674         struct iommu_group *group;
1675
1676         group = iommu_group_get(dev);
1677         if (!group)
1678                 return;
1679
1680         mutex_lock(&group->mutex);
1681         if (iommu_group_device_count(group) != 1) {
1682                 WARN_ON(1);
1683                 goto out_unlock;
1684         }
1685
1686         __iommu_detach_group(domain, group);
1687
1688 out_unlock:
1689         mutex_unlock(&group->mutex);
1690         iommu_group_put(group);
1691 }
1692 EXPORT_SYMBOL_GPL(iommu_detach_device);
1693
1694 struct iommu_domain *iommu_get_domain_for_dev(struct device *dev)
1695 {
1696         struct iommu_domain *domain;
1697         struct iommu_group *group;
1698
1699         group = iommu_group_get(dev);
1700         if (!group)
1701                 return NULL;
1702
1703         domain = group->domain;
1704
1705         iommu_group_put(group);
1706
1707         return domain;
1708 }
1709 EXPORT_SYMBOL_GPL(iommu_get_domain_for_dev);
1710
1711 /*
1712  * For IOMMU_DOMAIN_DMA implementations which already provide their own
1713  * guarantees that the group and its default domain are valid and correct.
1714  */
1715 struct iommu_domain *iommu_get_dma_domain(struct device *dev)
1716 {
1717         return dev->iommu_group->default_domain;
1718 }
1719
1720 /*
1721  * IOMMU groups are really the natural working unit of the IOMMU, but
1722  * the IOMMU API works on domains and devices.  Bridge that gap by
1723  * iterating over the devices in a group.  Ideally we'd have a single
1724  * device which represents the requestor ID of the group, but we also
1725  * allow IOMMU drivers to create policy defined minimum sets, where
1726  * the physical hardware may be able to distiguish members, but we
1727  * wish to group them at a higher level (ex. untrusted multi-function
1728  * PCI devices).  Thus we attach each device.
1729  */
1730 static int iommu_group_do_attach_device(struct device *dev, void *data)
1731 {
1732         struct iommu_domain *domain = data;
1733
1734         return __iommu_attach_device(domain, dev);
1735 }
1736
1737 static int __iommu_attach_group(struct iommu_domain *domain,
1738                                 struct iommu_group *group)
1739 {
1740         int ret;
1741
1742         if (group->default_domain && group->domain != group->default_domain)
1743                 return -EBUSY;
1744
1745         ret = __iommu_group_for_each_dev(group, domain,
1746                                          iommu_group_do_attach_device);
1747         if (ret == 0)
1748                 group->domain = domain;
1749
1750         return ret;
1751 }
1752
1753 int iommu_attach_group(struct iommu_domain *domain, struct iommu_group *group)
1754 {
1755         int ret;
1756
1757         mutex_lock(&group->mutex);
1758         ret = __iommu_attach_group(domain, group);
1759         mutex_unlock(&group->mutex);
1760
1761         return ret;
1762 }
1763 EXPORT_SYMBOL_GPL(iommu_attach_group);
1764
1765 static int iommu_group_do_detach_device(struct device *dev, void *data)
1766 {
1767         struct iommu_domain *domain = data;
1768
1769         __iommu_detach_device(domain, dev);
1770
1771         return 0;
1772 }
1773
1774 static void __iommu_detach_group(struct iommu_domain *domain,
1775                                  struct iommu_group *group)
1776 {
1777         int ret;
1778
1779         if (!group->default_domain) {
1780                 __iommu_group_for_each_dev(group, domain,
1781                                            iommu_group_do_detach_device);
1782                 group->domain = NULL;
1783                 return;
1784         }
1785
1786         if (group->domain == group->default_domain)
1787                 return;
1788
1789         /* Detach by re-attaching to the default domain */
1790         ret = __iommu_group_for_each_dev(group, group->default_domain,
1791                                          iommu_group_do_attach_device);
1792         if (ret != 0)
1793                 WARN_ON(1);
1794         else
1795                 group->domain = group->default_domain;
1796 }
1797
1798 void iommu_detach_group(struct iommu_domain *domain, struct iommu_group *group)
1799 {
1800         mutex_lock(&group->mutex);
1801         __iommu_detach_group(domain, group);
1802         mutex_unlock(&group->mutex);
1803 }
1804 EXPORT_SYMBOL_GPL(iommu_detach_group);
1805
1806 phys_addr_t iommu_iova_to_phys(struct iommu_domain *domain, dma_addr_t iova)
1807 {
1808         if (unlikely(domain->ops->iova_to_phys == NULL))
1809                 return 0;
1810
1811         return domain->ops->iova_to_phys(domain, iova);
1812 }
1813 EXPORT_SYMBOL_GPL(iommu_iova_to_phys);
1814
1815 static size_t iommu_pgsize(struct iommu_domain *domain,
1816                            unsigned long addr_merge, size_t size)
1817 {
1818         unsigned int pgsize_idx;
1819         size_t pgsize;
1820
1821         /* Max page size that still fits into 'size' */
1822         pgsize_idx = __fls(size);
1823
1824         /* need to consider alignment requirements ? */
1825         if (likely(addr_merge)) {
1826                 /* Max page size allowed by address */
1827                 unsigned int align_pgsize_idx = __ffs(addr_merge);
1828                 pgsize_idx = min(pgsize_idx, align_pgsize_idx);
1829         }
1830
1831         /* build a mask of acceptable page sizes */
1832         pgsize = (1UL << (pgsize_idx + 1)) - 1;
1833
1834         /* throw away page sizes not supported by the hardware */
1835         pgsize &= domain->pgsize_bitmap;
1836
1837         /* make sure we're still sane */
1838         BUG_ON(!pgsize);
1839
1840         /* pick the biggest page */
1841         pgsize_idx = __fls(pgsize);
1842         pgsize = 1UL << pgsize_idx;
1843
1844         return pgsize;
1845 }
1846
1847 int iommu_map(struct iommu_domain *domain, unsigned long iova,
1848               phys_addr_t paddr, size_t size, int prot)
1849 {
1850         const struct iommu_ops *ops = domain->ops;
1851         unsigned long orig_iova = iova;
1852         unsigned int min_pagesz;
1853         size_t orig_size = size;
1854         phys_addr_t orig_paddr = paddr;
1855         int ret = 0;
1856
1857         if (unlikely(ops->map == NULL ||
1858                      domain->pgsize_bitmap == 0UL))
1859                 return -ENODEV;
1860
1861         if (unlikely(!(domain->type & __IOMMU_DOMAIN_PAGING)))
1862                 return -EINVAL;
1863
1864         /* find out the minimum page size supported */
1865         min_pagesz = 1 << __ffs(domain->pgsize_bitmap);
1866
1867         /*
1868          * both the virtual address and the physical one, as well as
1869          * the size of the mapping, must be aligned (at least) to the
1870          * size of the smallest page supported by the hardware
1871          */
1872         if (!IS_ALIGNED(iova | paddr | size, min_pagesz)) {
1873                 pr_err("unaligned: iova 0x%lx pa %pa size 0x%zx min_pagesz 0x%x\n",
1874                        iova, &paddr, size, min_pagesz);
1875                 return -EINVAL;
1876         }
1877
1878         pr_debug("map: iova 0x%lx pa %pa size 0x%zx\n", iova, &paddr, size);
1879
1880         while (size) {
1881                 size_t pgsize = iommu_pgsize(domain, iova | paddr, size);
1882
1883                 pr_debug("mapping: iova 0x%lx pa %pa pgsize 0x%zx\n",
1884                          iova, &paddr, pgsize);
1885
1886                 ret = ops->map(domain, iova, paddr, pgsize, prot);
1887                 if (ret)
1888                         break;
1889
1890                 iova += pgsize;
1891                 paddr += pgsize;
1892                 size -= pgsize;
1893         }
1894
1895         if (ops->iotlb_sync_map)
1896                 ops->iotlb_sync_map(domain);
1897
1898         /* unroll mapping in case something went wrong */
1899         if (ret)
1900                 iommu_unmap(domain, orig_iova, orig_size - size);
1901         else
1902                 trace_map(orig_iova, orig_paddr, orig_size);
1903
1904         return ret;
1905 }
1906 EXPORT_SYMBOL_GPL(iommu_map);
1907
1908 static size_t __iommu_unmap(struct iommu_domain *domain,
1909                             unsigned long iova, size_t size,
1910                             struct iommu_iotlb_gather *iotlb_gather)
1911 {
1912         const struct iommu_ops *ops = domain->ops;
1913         size_t unmapped_page, unmapped = 0;
1914         unsigned long orig_iova = iova;
1915         unsigned int min_pagesz;
1916
1917         if (unlikely(ops->unmap == NULL ||
1918                      domain->pgsize_bitmap == 0UL))
1919                 return 0;
1920
1921         if (unlikely(!(domain->type & __IOMMU_DOMAIN_PAGING)))
1922                 return 0;
1923
1924         /* find out the minimum page size supported */
1925         min_pagesz = 1 << __ffs(domain->pgsize_bitmap);
1926
1927         /*
1928          * The virtual address, as well as the size of the mapping, must be
1929          * aligned (at least) to the size of the smallest page supported
1930          * by the hardware
1931          */
1932         if (!IS_ALIGNED(iova | size, min_pagesz)) {
1933                 pr_err("unaligned: iova 0x%lx size 0x%zx min_pagesz 0x%x\n",
1934                        iova, size, min_pagesz);
1935                 return 0;
1936         }
1937
1938         pr_debug("unmap this: iova 0x%lx size 0x%zx\n", iova, size);
1939
1940         /*
1941          * Keep iterating until we either unmap 'size' bytes (or more)
1942          * or we hit an area that isn't mapped.
1943          */
1944         while (unmapped < size) {
1945                 size_t pgsize = iommu_pgsize(domain, iova, size - unmapped);
1946
1947                 unmapped_page = ops->unmap(domain, iova, pgsize, iotlb_gather);
1948                 if (!unmapped_page)
1949                         break;
1950
1951                 pr_debug("unmapped: iova 0x%lx size 0x%zx\n",
1952                          iova, unmapped_page);
1953
1954                 iova += unmapped_page;
1955                 unmapped += unmapped_page;
1956         }
1957
1958         trace_unmap(orig_iova, size, unmapped);
1959         return unmapped;
1960 }
1961
1962 size_t iommu_unmap(struct iommu_domain *domain,
1963                    unsigned long iova, size_t size)
1964 {
1965         struct iommu_iotlb_gather iotlb_gather;
1966         size_t ret;
1967
1968         iommu_iotlb_gather_init(&iotlb_gather);
1969         ret = __iommu_unmap(domain, iova, size, &iotlb_gather);
1970         iommu_tlb_sync(domain, &iotlb_gather);
1971
1972         return ret;
1973 }
1974 EXPORT_SYMBOL_GPL(iommu_unmap);
1975
1976 size_t iommu_unmap_fast(struct iommu_domain *domain,
1977                         unsigned long iova, size_t size,
1978                         struct iommu_iotlb_gather *iotlb_gather)
1979 {
1980         return __iommu_unmap(domain, iova, size, iotlb_gather);
1981 }
1982 EXPORT_SYMBOL_GPL(iommu_unmap_fast);
1983
1984 size_t iommu_map_sg(struct iommu_domain *domain, unsigned long iova,
1985                     struct scatterlist *sg, unsigned int nents, int prot)
1986 {
1987         size_t len = 0, mapped = 0;
1988         phys_addr_t start;
1989         unsigned int i = 0;
1990         int ret;
1991
1992         while (i <= nents) {
1993                 phys_addr_t s_phys = sg_phys(sg);
1994
1995                 if (len && s_phys != start + len) {
1996                         ret = iommu_map(domain, iova + mapped, start, len, prot);
1997                         if (ret)
1998                                 goto out_err;
1999
2000                         mapped += len;
2001                         len = 0;
2002                 }
2003
2004                 if (len) {
2005                         len += sg->length;
2006                 } else {
2007                         len = sg->length;
2008                         start = s_phys;
2009                 }
2010
2011                 if (++i < nents)
2012                         sg = sg_next(sg);
2013         }
2014
2015         return mapped;
2016
2017 out_err:
2018         /* undo mappings already done */
2019         iommu_unmap(domain, iova, mapped);
2020
2021         return 0;
2022
2023 }
2024 EXPORT_SYMBOL_GPL(iommu_map_sg);
2025
2026 int iommu_domain_window_enable(struct iommu_domain *domain, u32 wnd_nr,
2027                                phys_addr_t paddr, u64 size, int prot)
2028 {
2029         if (unlikely(domain->ops->domain_window_enable == NULL))
2030                 return -ENODEV;
2031
2032         return domain->ops->domain_window_enable(domain, wnd_nr, paddr, size,
2033                                                  prot);
2034 }
2035 EXPORT_SYMBOL_GPL(iommu_domain_window_enable);
2036
2037 void iommu_domain_window_disable(struct iommu_domain *domain, u32 wnd_nr)
2038 {
2039         if (unlikely(domain->ops->domain_window_disable == NULL))
2040                 return;
2041
2042         return domain->ops->domain_window_disable(domain, wnd_nr);
2043 }
2044 EXPORT_SYMBOL_GPL(iommu_domain_window_disable);
2045
2046 /**
2047  * report_iommu_fault() - report about an IOMMU fault to the IOMMU framework
2048  * @domain: the iommu domain where the fault has happened
2049  * @dev: the device where the fault has happened
2050  * @iova: the faulting address
2051  * @flags: mmu fault flags (e.g. IOMMU_FAULT_READ/IOMMU_FAULT_WRITE/...)
2052  *
2053  * This function should be called by the low-level IOMMU implementations
2054  * whenever IOMMU faults happen, to allow high-level users, that are
2055  * interested in such events, to know about them.
2056  *
2057  * This event may be useful for several possible use cases:
2058  * - mere logging of the event
2059  * - dynamic TLB/PTE loading
2060  * - if restarting of the faulting device is required
2061  *
2062  * Returns 0 on success and an appropriate error code otherwise (if dynamic
2063  * PTE/TLB loading will one day be supported, implementations will be able
2064  * to tell whether it succeeded or not according to this return value).
2065  *
2066  * Specifically, -ENOSYS is returned if a fault handler isn't installed
2067  * (though fault handlers can also return -ENOSYS, in case they want to
2068  * elicit the default behavior of the IOMMU drivers).
2069  */
2070 int report_iommu_fault(struct iommu_domain *domain, struct device *dev,
2071                        unsigned long iova, int flags)
2072 {
2073         int ret = -ENOSYS;
2074
2075         /*
2076          * if upper layers showed interest and installed a fault handler,
2077          * invoke it.
2078          */
2079         if (domain->handler)
2080                 ret = domain->handler(domain, dev, iova, flags,
2081                                                 domain->handler_token);
2082
2083         trace_io_page_fault(dev, iova, flags);
2084         return ret;
2085 }
2086 EXPORT_SYMBOL_GPL(report_iommu_fault);
2087
2088 static int __init iommu_init(void)
2089 {
2090         iommu_group_kset = kset_create_and_add("iommu_groups",
2091                                                NULL, kernel_kobj);
2092         BUG_ON(!iommu_group_kset);
2093
2094         iommu_debugfs_setup();
2095
2096         return 0;
2097 }
2098 core_initcall(iommu_init);
2099
2100 int iommu_domain_get_attr(struct iommu_domain *domain,
2101                           enum iommu_attr attr, void *data)
2102 {
2103         struct iommu_domain_geometry *geometry;
2104         bool *paging;
2105         int ret = 0;
2106
2107         switch (attr) {
2108         case DOMAIN_ATTR_GEOMETRY:
2109                 geometry  = data;
2110                 *geometry = domain->geometry;
2111
2112                 break;
2113         case DOMAIN_ATTR_PAGING:
2114                 paging  = data;
2115                 *paging = (domain->pgsize_bitmap != 0UL);
2116                 break;
2117         default:
2118                 if (!domain->ops->domain_get_attr)
2119                         return -EINVAL;
2120
2121                 ret = domain->ops->domain_get_attr(domain, attr, data);
2122         }
2123
2124         return ret;
2125 }
2126 EXPORT_SYMBOL_GPL(iommu_domain_get_attr);
2127
2128 int iommu_domain_set_attr(struct iommu_domain *domain,
2129                           enum iommu_attr attr, void *data)
2130 {
2131         int ret = 0;
2132
2133         switch (attr) {
2134         default:
2135                 if (domain->ops->domain_set_attr == NULL)
2136                         return -EINVAL;
2137
2138                 ret = domain->ops->domain_set_attr(domain, attr, data);
2139         }
2140
2141         return ret;
2142 }
2143 EXPORT_SYMBOL_GPL(iommu_domain_set_attr);
2144
2145 void iommu_get_resv_regions(struct device *dev, struct list_head *list)
2146 {
2147         const struct iommu_ops *ops = dev->bus->iommu_ops;
2148
2149         if (ops && ops->get_resv_regions)
2150                 ops->get_resv_regions(dev, list);
2151 }
2152
2153 void iommu_put_resv_regions(struct device *dev, struct list_head *list)
2154 {
2155         const struct iommu_ops *ops = dev->bus->iommu_ops;
2156
2157         if (ops && ops->put_resv_regions)
2158                 ops->put_resv_regions(dev, list);
2159 }
2160
2161 struct iommu_resv_region *iommu_alloc_resv_region(phys_addr_t start,
2162                                                   size_t length, int prot,
2163                                                   enum iommu_resv_type type)
2164 {
2165         struct iommu_resv_region *region;
2166
2167         region = kzalloc(sizeof(*region), GFP_KERNEL);
2168         if (!region)
2169                 return NULL;
2170
2171         INIT_LIST_HEAD(&region->list);
2172         region->start = start;
2173         region->length = length;
2174         region->prot = prot;
2175         region->type = type;
2176         return region;
2177 }
2178
2179 static int
2180 request_default_domain_for_dev(struct device *dev, unsigned long type)
2181 {
2182         struct iommu_domain *domain;
2183         struct iommu_group *group;
2184         int ret;
2185
2186         /* Device must already be in a group before calling this function */
2187         group = iommu_group_get(dev);
2188         if (!group)
2189                 return -EINVAL;
2190
2191         mutex_lock(&group->mutex);
2192
2193         /* Check if the default domain is already direct mapped */
2194         ret = 0;
2195         if (group->default_domain && group->default_domain->type == type)
2196                 goto out;
2197
2198         /* Don't change mappings of existing devices */
2199         ret = -EBUSY;
2200         if (iommu_group_device_count(group) != 1)
2201                 goto out;
2202
2203         /* Allocate a direct mapped domain */
2204         ret = -ENOMEM;
2205         domain = __iommu_domain_alloc(dev->bus, type);
2206         if (!domain)
2207                 goto out;
2208
2209         /* Attach the device to the domain */
2210         ret = __iommu_attach_group(domain, group);
2211         if (ret) {
2212                 iommu_domain_free(domain);
2213                 goto out;
2214         }
2215
2216         iommu_group_create_direct_mappings(group, dev);
2217
2218         /* Make the direct mapped domain the default for this group */
2219         if (group->default_domain)
2220                 iommu_domain_free(group->default_domain);
2221         group->default_domain = domain;
2222
2223         dev_info(dev, "Using iommu %s mapping\n",
2224                  type == IOMMU_DOMAIN_DMA ? "dma" : "direct");
2225
2226         ret = 0;
2227 out:
2228         mutex_unlock(&group->mutex);
2229         iommu_group_put(group);
2230
2231         return ret;
2232 }
2233
2234 /* Request that a device is direct mapped by the IOMMU */
2235 int iommu_request_dm_for_dev(struct device *dev)
2236 {
2237         return request_default_domain_for_dev(dev, IOMMU_DOMAIN_IDENTITY);
2238 }
2239
2240 /* Request that a device can't be direct mapped by the IOMMU */
2241 int iommu_request_dma_domain_for_dev(struct device *dev)
2242 {
2243         return request_default_domain_for_dev(dev, IOMMU_DOMAIN_DMA);
2244 }
2245
2246 void iommu_set_default_passthrough(bool cmd_line)
2247 {
2248         if (cmd_line)
2249                 iommu_set_cmd_line_dma_api();
2250
2251         iommu_def_domain_type = IOMMU_DOMAIN_IDENTITY;
2252 }
2253
2254 void iommu_set_default_translated(bool cmd_line)
2255 {
2256         if (cmd_line)
2257                 iommu_set_cmd_line_dma_api();
2258
2259         iommu_def_domain_type = IOMMU_DOMAIN_DMA;
2260 }
2261
2262 bool iommu_default_passthrough(void)
2263 {
2264         return iommu_def_domain_type == IOMMU_DOMAIN_IDENTITY;
2265 }
2266 EXPORT_SYMBOL_GPL(iommu_default_passthrough);
2267
2268 const struct iommu_ops *iommu_ops_from_fwnode(struct fwnode_handle *fwnode)
2269 {
2270         const struct iommu_ops *ops = NULL;
2271         struct iommu_device *iommu;
2272
2273         spin_lock(&iommu_device_lock);
2274         list_for_each_entry(iommu, &iommu_device_list, list)
2275                 if (iommu->fwnode == fwnode) {
2276                         ops = iommu->ops;
2277                         break;
2278                 }
2279         spin_unlock(&iommu_device_lock);
2280         return ops;
2281 }
2282
2283 int iommu_fwspec_init(struct device *dev, struct fwnode_handle *iommu_fwnode,
2284                       const struct iommu_ops *ops)
2285 {
2286         struct iommu_fwspec *fwspec = dev_iommu_fwspec_get(dev);
2287
2288         if (fwspec)
2289                 return ops == fwspec->ops ? 0 : -EINVAL;
2290
2291         fwspec = kzalloc(sizeof(*fwspec), GFP_KERNEL);
2292         if (!fwspec)
2293                 return -ENOMEM;
2294
2295         of_node_get(to_of_node(iommu_fwnode));
2296         fwspec->iommu_fwnode = iommu_fwnode;
2297         fwspec->ops = ops;
2298         dev_iommu_fwspec_set(dev, fwspec);
2299         return 0;
2300 }
2301 EXPORT_SYMBOL_GPL(iommu_fwspec_init);
2302
2303 void iommu_fwspec_free(struct device *dev)
2304 {
2305         struct iommu_fwspec *fwspec = dev_iommu_fwspec_get(dev);
2306
2307         if (fwspec) {
2308                 fwnode_handle_put(fwspec->iommu_fwnode);
2309                 kfree(fwspec);
2310                 dev_iommu_fwspec_set(dev, NULL);
2311         }
2312 }
2313 EXPORT_SYMBOL_GPL(iommu_fwspec_free);
2314
2315 int iommu_fwspec_add_ids(struct device *dev, u32 *ids, int num_ids)
2316 {
2317         struct iommu_fwspec *fwspec = dev_iommu_fwspec_get(dev);
2318         size_t size;
2319         int i;
2320
2321         if (!fwspec)
2322                 return -EINVAL;
2323
2324         size = offsetof(struct iommu_fwspec, ids[fwspec->num_ids + num_ids]);
2325         if (size > sizeof(*fwspec)) {
2326                 fwspec = krealloc(fwspec, size, GFP_KERNEL);
2327                 if (!fwspec)
2328                         return -ENOMEM;
2329
2330                 dev_iommu_fwspec_set(dev, fwspec);
2331         }
2332
2333         for (i = 0; i < num_ids; i++)
2334                 fwspec->ids[fwspec->num_ids + i] = ids[i];
2335
2336         fwspec->num_ids += num_ids;
2337         return 0;
2338 }
2339 EXPORT_SYMBOL_GPL(iommu_fwspec_add_ids);
2340
2341 /*
2342  * Per device IOMMU features.
2343  */
2344 bool iommu_dev_has_feature(struct device *dev, enum iommu_dev_features feat)
2345 {
2346         const struct iommu_ops *ops = dev->bus->iommu_ops;
2347
2348         if (ops && ops->dev_has_feat)
2349                 return ops->dev_has_feat(dev, feat);
2350
2351         return false;
2352 }
2353 EXPORT_SYMBOL_GPL(iommu_dev_has_feature);
2354
2355 int iommu_dev_enable_feature(struct device *dev, enum iommu_dev_features feat)
2356 {
2357         const struct iommu_ops *ops = dev->bus->iommu_ops;
2358
2359         if (ops && ops->dev_enable_feat)
2360                 return ops->dev_enable_feat(dev, feat);
2361
2362         return -ENODEV;
2363 }
2364 EXPORT_SYMBOL_GPL(iommu_dev_enable_feature);
2365
2366 /*
2367  * The device drivers should do the necessary cleanups before calling this.
2368  * For example, before disabling the aux-domain feature, the device driver
2369  * should detach all aux-domains. Otherwise, this will return -EBUSY.
2370  */
2371 int iommu_dev_disable_feature(struct device *dev, enum iommu_dev_features feat)
2372 {
2373         const struct iommu_ops *ops = dev->bus->iommu_ops;
2374
2375         if (ops && ops->dev_disable_feat)
2376                 return ops->dev_disable_feat(dev, feat);
2377
2378         return -EBUSY;
2379 }
2380 EXPORT_SYMBOL_GPL(iommu_dev_disable_feature);
2381
2382 bool iommu_dev_feature_enabled(struct device *dev, enum iommu_dev_features feat)
2383 {
2384         const struct iommu_ops *ops = dev->bus->iommu_ops;
2385
2386         if (ops && ops->dev_feat_enabled)
2387                 return ops->dev_feat_enabled(dev, feat);
2388
2389         return false;
2390 }
2391 EXPORT_SYMBOL_GPL(iommu_dev_feature_enabled);
2392
2393 /*
2394  * Aux-domain specific attach/detach.
2395  *
2396  * Only works if iommu_dev_feature_enabled(dev, IOMMU_DEV_FEAT_AUX) returns
2397  * true. Also, as long as domains are attached to a device through this
2398  * interface, any tries to call iommu_attach_device() should fail
2399  * (iommu_detach_device() can't fail, so we fail when trying to re-attach).
2400  * This should make us safe against a device being attached to a guest as a
2401  * whole while there are still pasid users on it (aux and sva).
2402  */
2403 int iommu_aux_attach_device(struct iommu_domain *domain, struct device *dev)
2404 {
2405         int ret = -ENODEV;
2406
2407         if (domain->ops->aux_attach_dev)
2408                 ret = domain->ops->aux_attach_dev(domain, dev);
2409
2410         if (!ret)
2411                 trace_attach_device_to_domain(dev);
2412
2413         return ret;
2414 }
2415 EXPORT_SYMBOL_GPL(iommu_aux_attach_device);
2416
2417 void iommu_aux_detach_device(struct iommu_domain *domain, struct device *dev)
2418 {
2419         if (domain->ops->aux_detach_dev) {
2420                 domain->ops->aux_detach_dev(domain, dev);
2421                 trace_detach_device_from_domain(dev);
2422         }
2423 }
2424 EXPORT_SYMBOL_GPL(iommu_aux_detach_device);
2425
2426 int iommu_aux_get_pasid(struct iommu_domain *domain, struct device *dev)
2427 {
2428         int ret = -ENODEV;
2429
2430         if (domain->ops->aux_get_pasid)
2431                 ret = domain->ops->aux_get_pasid(domain, dev);
2432
2433         return ret;
2434 }
2435 EXPORT_SYMBOL_GPL(iommu_aux_get_pasid);
2436
2437 /**
2438  * iommu_sva_bind_device() - Bind a process address space to a device
2439  * @dev: the device
2440  * @mm: the mm to bind, caller must hold a reference to it
2441  *
2442  * Create a bond between device and address space, allowing the device to access
2443  * the mm using the returned PASID. If a bond already exists between @device and
2444  * @mm, it is returned and an additional reference is taken. Caller must call
2445  * iommu_sva_unbind_device() to release each reference.
2446  *
2447  * iommu_dev_enable_feature(dev, IOMMU_DEV_FEAT_SVA) must be called first, to
2448  * initialize the required SVA features.
2449  *
2450  * On error, returns an ERR_PTR value.
2451  */
2452 struct iommu_sva *
2453 iommu_sva_bind_device(struct device *dev, struct mm_struct *mm, void *drvdata)
2454 {
2455         struct iommu_group *group;
2456         struct iommu_sva *handle = ERR_PTR(-EINVAL);
2457         const struct iommu_ops *ops = dev->bus->iommu_ops;
2458
2459         if (!ops || !ops->sva_bind)
2460                 return ERR_PTR(-ENODEV);
2461
2462         group = iommu_group_get(dev);
2463         if (!group)
2464                 return ERR_PTR(-ENODEV);
2465
2466         /* Ensure device count and domain don't change while we're binding */
2467         mutex_lock(&group->mutex);
2468
2469         /*
2470          * To keep things simple, SVA currently doesn't support IOMMU groups
2471          * with more than one device. Existing SVA-capable systems are not
2472          * affected by the problems that required IOMMU groups (lack of ACS
2473          * isolation, device ID aliasing and other hardware issues).
2474          */
2475         if (iommu_group_device_count(group) != 1)
2476                 goto out_unlock;
2477
2478         handle = ops->sva_bind(dev, mm, drvdata);
2479
2480 out_unlock:
2481         mutex_unlock(&group->mutex);
2482         iommu_group_put(group);
2483
2484         return handle;
2485 }
2486 EXPORT_SYMBOL_GPL(iommu_sva_bind_device);
2487
2488 /**
2489  * iommu_sva_unbind_device() - Remove a bond created with iommu_sva_bind_device
2490  * @handle: the handle returned by iommu_sva_bind_device()
2491  *
2492  * Put reference to a bond between device and address space. The device should
2493  * not be issuing any more transaction for this PASID. All outstanding page
2494  * requests for this PASID must have been flushed to the IOMMU.
2495  *
2496  * Returns 0 on success, or an error value
2497  */
2498 void iommu_sva_unbind_device(struct iommu_sva *handle)
2499 {
2500         struct iommu_group *group;
2501         struct device *dev = handle->dev;
2502         const struct iommu_ops *ops = dev->bus->iommu_ops;
2503
2504         if (!ops || !ops->sva_unbind)
2505                 return;
2506
2507         group = iommu_group_get(dev);
2508         if (!group)
2509                 return;
2510
2511         mutex_lock(&group->mutex);
2512         ops->sva_unbind(handle);
2513         mutex_unlock(&group->mutex);
2514
2515         iommu_group_put(group);
2516 }
2517 EXPORT_SYMBOL_GPL(iommu_sva_unbind_device);
2518
2519 int iommu_sva_set_ops(struct iommu_sva *handle,
2520                       const struct iommu_sva_ops *sva_ops)
2521 {
2522         if (handle->ops && handle->ops != sva_ops)
2523                 return -EEXIST;
2524
2525         handle->ops = sva_ops;
2526         return 0;
2527 }
2528 EXPORT_SYMBOL_GPL(iommu_sva_set_ops);
2529
2530 int iommu_sva_get_pasid(struct iommu_sva *handle)
2531 {
2532         const struct iommu_ops *ops = handle->dev->bus->iommu_ops;
2533
2534         if (!ops || !ops->sva_get_pasid)
2535                 return IOMMU_PASID_INVALID;
2536
2537         return ops->sva_get_pasid(handle);
2538 }
2539 EXPORT_SYMBOL_GPL(iommu_sva_get_pasid);