1 // SPDX-License-Identifier: GPL-2.0-only
3 * Copyright (C) 2007-2008 Advanced Micro Devices, Inc.
4 * Author: Joerg Roedel <jroedel@suse.de>
7 #define pr_fmt(fmt) "iommu: " fmt
9 #include <linux/device.h>
10 #include <linux/kernel.h>
11 #include <linux/bits.h>
12 #include <linux/bug.h>
13 #include <linux/types.h>
14 #include <linux/init.h>
15 #include <linux/export.h>
16 #include <linux/slab.h>
17 #include <linux/errno.h>
18 #include <linux/iommu.h>
19 #include <linux/idr.h>
20 #include <linux/notifier.h>
21 #include <linux/err.h>
22 #include <linux/pci.h>
23 #include <linux/bitops.h>
24 #include <linux/property.h>
25 #include <linux/fsl/mc.h>
26 #include <linux/module.h>
27 #include <trace/events/iommu.h>
29 static struct kset *iommu_group_kset;
30 static DEFINE_IDA(iommu_group_ida);
32 static unsigned int iommu_def_domain_type __read_mostly;
33 static bool iommu_dma_strict __read_mostly = IS_ENABLED(CONFIG_IOMMU_DEFAULT_STRICT);
34 static u32 iommu_cmd_line __read_mostly;
38 struct kobject *devices_kobj;
39 struct list_head devices;
41 struct blocking_notifier_head notifier;
43 void (*iommu_data_release)(void *iommu_data);
46 struct iommu_domain *default_domain;
47 struct iommu_domain *domain;
48 struct list_head entry;
52 struct list_head list;
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);
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",
72 #define IOMMU_CMD_LINE_DMA_API BIT(0)
73 #define IOMMU_CMD_LINE_STRICT BIT(1)
75 static int iommu_alloc_default_domain(struct iommu_group *group,
77 static struct iommu_domain *__iommu_domain_alloc(struct bus_type *bus,
79 static int __iommu_attach_device(struct iommu_domain *domain,
81 static int __iommu_attach_group(struct iommu_domain *domain,
82 struct iommu_group *group);
83 static void __iommu_detach_group(struct iommu_domain *domain,
84 struct iommu_group *group);
85 static int iommu_create_device_direct_mappings(struct iommu_group *group,
87 static struct iommu_group *iommu_group_get_for_dev(struct device *dev);
88 static ssize_t iommu_group_store_type(struct iommu_group *group,
89 const char *buf, size_t count);
91 #define IOMMU_GROUP_ATTR(_name, _mode, _show, _store) \
92 struct iommu_group_attribute iommu_group_attr_##_name = \
93 __ATTR(_name, _mode, _show, _store)
95 #define to_iommu_group_attr(_attr) \
96 container_of(_attr, struct iommu_group_attribute, attr)
97 #define to_iommu_group(_kobj) \
98 container_of(_kobj, struct iommu_group, kobj)
100 static LIST_HEAD(iommu_device_list);
101 static DEFINE_SPINLOCK(iommu_device_lock);
104 * Use a function instead of an array here because the domain-type is a
105 * bit-field, so an array would waste memory.
107 static const char *iommu_domain_type_str(unsigned int t)
110 case IOMMU_DOMAIN_BLOCKED:
112 case IOMMU_DOMAIN_IDENTITY:
113 return "Passthrough";
114 case IOMMU_DOMAIN_UNMANAGED:
116 case IOMMU_DOMAIN_DMA:
123 static int __init iommu_subsys_init(void)
125 if (!(iommu_cmd_line & IOMMU_CMD_LINE_DMA_API)) {
126 if (IS_ENABLED(CONFIG_IOMMU_DEFAULT_PASSTHROUGH))
127 iommu_set_default_passthrough(false);
129 iommu_set_default_translated(false);
131 if (iommu_default_passthrough() && mem_encrypt_active()) {
132 pr_info("Memory encryption detected - Disabling default IOMMU Passthrough\n");
133 iommu_set_default_translated(false);
137 pr_info("Default domain type: %s %s\n",
138 iommu_domain_type_str(iommu_def_domain_type),
139 (iommu_cmd_line & IOMMU_CMD_LINE_DMA_API) ?
140 "(set via kernel command line)" : "");
142 pr_info("DMA domain TLB invalidation policy: %s mode %s\n",
143 iommu_dma_strict ? "strict" : "lazy",
144 (iommu_cmd_line & IOMMU_CMD_LINE_STRICT) ?
145 "(set via kernel command line)" : "");
149 subsys_initcall(iommu_subsys_init);
152 * iommu_device_register() - Register an IOMMU hardware instance
153 * @iommu: IOMMU handle for the instance
154 * @ops: IOMMU ops to associate with the instance
155 * @hwdev: (optional) actual instance device, used for fwnode lookup
157 * Return: 0 on success, or an error.
159 int iommu_device_register(struct iommu_device *iommu,
160 const struct iommu_ops *ops, struct device *hwdev)
162 /* We need to be able to take module references appropriately */
163 if (WARN_ON(is_module_address((unsigned long)ops) && !ops->owner))
168 iommu->fwnode = hwdev->fwnode;
170 spin_lock(&iommu_device_lock);
171 list_add_tail(&iommu->list, &iommu_device_list);
172 spin_unlock(&iommu_device_lock);
175 EXPORT_SYMBOL_GPL(iommu_device_register);
177 void iommu_device_unregister(struct iommu_device *iommu)
179 spin_lock(&iommu_device_lock);
180 list_del(&iommu->list);
181 spin_unlock(&iommu_device_lock);
183 EXPORT_SYMBOL_GPL(iommu_device_unregister);
185 static struct dev_iommu *dev_iommu_get(struct device *dev)
187 struct dev_iommu *param = dev->iommu;
192 param = kzalloc(sizeof(*param), GFP_KERNEL);
196 mutex_init(¶m->lock);
201 static void dev_iommu_free(struct device *dev)
203 iommu_fwspec_free(dev);
208 static int __iommu_probe_device(struct device *dev, struct list_head *group_list)
210 const struct iommu_ops *ops = dev->bus->iommu_ops;
211 struct iommu_device *iommu_dev;
212 struct iommu_group *group;
218 if (!dev_iommu_get(dev))
221 if (!try_module_get(ops->owner)) {
226 iommu_dev = ops->probe_device(dev);
227 if (IS_ERR(iommu_dev)) {
228 ret = PTR_ERR(iommu_dev);
232 dev->iommu->iommu_dev = iommu_dev;
234 group = iommu_group_get_for_dev(dev);
236 ret = PTR_ERR(group);
239 iommu_group_put(group);
241 if (group_list && !group->default_domain && list_empty(&group->entry))
242 list_add_tail(&group->entry, group_list);
244 iommu_device_link(iommu_dev, dev);
249 ops->release_device(dev);
252 module_put(ops->owner);
260 int iommu_probe_device(struct device *dev)
262 const struct iommu_ops *ops = dev->bus->iommu_ops;
263 struct iommu_group *group;
266 ret = __iommu_probe_device(dev, NULL);
270 group = iommu_group_get(dev);
277 * Try to allocate a default domain - needs support from the
278 * IOMMU driver. There are still some drivers which don't
279 * support default domains, so the return value is not yet
282 iommu_alloc_default_domain(group, dev);
284 if (group->default_domain) {
285 ret = __iommu_attach_device(group->default_domain, dev);
287 iommu_group_put(group);
292 iommu_create_device_direct_mappings(group, dev);
294 iommu_group_put(group);
296 if (ops->probe_finalize)
297 ops->probe_finalize(dev);
302 iommu_release_device(dev);
309 void iommu_release_device(struct device *dev)
311 const struct iommu_ops *ops = dev->bus->iommu_ops;
316 iommu_device_unlink(dev->iommu->iommu_dev, dev);
318 ops->release_device(dev);
320 iommu_group_remove_device(dev);
321 module_put(ops->owner);
325 static int __init iommu_set_def_domain_type(char *str)
330 ret = kstrtobool(str, &pt);
335 iommu_set_default_passthrough(true);
337 iommu_set_default_translated(true);
341 early_param("iommu.passthrough", iommu_set_def_domain_type);
343 static int __init iommu_dma_setup(char *str)
345 int ret = kstrtobool(str, &iommu_dma_strict);
348 iommu_cmd_line |= IOMMU_CMD_LINE_STRICT;
351 early_param("iommu.strict", iommu_dma_setup);
353 void iommu_set_dma_strict(void)
355 iommu_dma_strict = true;
358 bool iommu_get_dma_strict(struct iommu_domain *domain)
360 /* only allow lazy flushing for DMA domains */
361 if (domain->type == IOMMU_DOMAIN_DMA)
362 return iommu_dma_strict;
365 EXPORT_SYMBOL_GPL(iommu_get_dma_strict);
367 static ssize_t iommu_group_attr_show(struct kobject *kobj,
368 struct attribute *__attr, char *buf)
370 struct iommu_group_attribute *attr = to_iommu_group_attr(__attr);
371 struct iommu_group *group = to_iommu_group(kobj);
375 ret = attr->show(group, buf);
379 static ssize_t iommu_group_attr_store(struct kobject *kobj,
380 struct attribute *__attr,
381 const char *buf, size_t count)
383 struct iommu_group_attribute *attr = to_iommu_group_attr(__attr);
384 struct iommu_group *group = to_iommu_group(kobj);
388 ret = attr->store(group, buf, count);
392 static const struct sysfs_ops iommu_group_sysfs_ops = {
393 .show = iommu_group_attr_show,
394 .store = iommu_group_attr_store,
397 static int iommu_group_create_file(struct iommu_group *group,
398 struct iommu_group_attribute *attr)
400 return sysfs_create_file(&group->kobj, &attr->attr);
403 static void iommu_group_remove_file(struct iommu_group *group,
404 struct iommu_group_attribute *attr)
406 sysfs_remove_file(&group->kobj, &attr->attr);
409 static ssize_t iommu_group_show_name(struct iommu_group *group, char *buf)
411 return sprintf(buf, "%s\n", group->name);
415 * iommu_insert_resv_region - Insert a new region in the
416 * list of reserved regions.
417 * @new: new region to insert
418 * @regions: list of regions
420 * Elements are sorted by start address and overlapping segments
421 * of the same type are merged.
423 static int iommu_insert_resv_region(struct iommu_resv_region *new,
424 struct list_head *regions)
426 struct iommu_resv_region *iter, *tmp, *nr, *top;
429 nr = iommu_alloc_resv_region(new->start, new->length,
430 new->prot, new->type);
434 /* First add the new element based on start address sorting */
435 list_for_each_entry(iter, regions, list) {
436 if (nr->start < iter->start ||
437 (nr->start == iter->start && nr->type <= iter->type))
440 list_add_tail(&nr->list, &iter->list);
442 /* Merge overlapping segments of type nr->type in @regions, if any */
443 list_for_each_entry_safe(iter, tmp, regions, list) {
444 phys_addr_t top_end, iter_end = iter->start + iter->length - 1;
446 /* no merge needed on elements of different types than @new */
447 if (iter->type != new->type) {
448 list_move_tail(&iter->list, &stack);
452 /* look for the last stack element of same type as @iter */
453 list_for_each_entry_reverse(top, &stack, list)
454 if (top->type == iter->type)
457 list_move_tail(&iter->list, &stack);
461 top_end = top->start + top->length - 1;
463 if (iter->start > top_end + 1) {
464 list_move_tail(&iter->list, &stack);
466 top->length = max(top_end, iter_end) - top->start + 1;
467 list_del(&iter->list);
471 list_splice(&stack, regions);
476 iommu_insert_device_resv_regions(struct list_head *dev_resv_regions,
477 struct list_head *group_resv_regions)
479 struct iommu_resv_region *entry;
482 list_for_each_entry(entry, dev_resv_regions, list) {
483 ret = iommu_insert_resv_region(entry, group_resv_regions);
490 int iommu_get_group_resv_regions(struct iommu_group *group,
491 struct list_head *head)
493 struct group_device *device;
496 mutex_lock(&group->mutex);
497 list_for_each_entry(device, &group->devices, list) {
498 struct list_head dev_resv_regions;
500 INIT_LIST_HEAD(&dev_resv_regions);
501 iommu_get_resv_regions(device->dev, &dev_resv_regions);
502 ret = iommu_insert_device_resv_regions(&dev_resv_regions, head);
503 iommu_put_resv_regions(device->dev, &dev_resv_regions);
507 mutex_unlock(&group->mutex);
510 EXPORT_SYMBOL_GPL(iommu_get_group_resv_regions);
512 static ssize_t iommu_group_show_resv_regions(struct iommu_group *group,
515 struct iommu_resv_region *region, *next;
516 struct list_head group_resv_regions;
519 INIT_LIST_HEAD(&group_resv_regions);
520 iommu_get_group_resv_regions(group, &group_resv_regions);
522 list_for_each_entry_safe(region, next, &group_resv_regions, list) {
523 str += sprintf(str, "0x%016llx 0x%016llx %s\n",
524 (long long int)region->start,
525 (long long int)(region->start +
527 iommu_group_resv_type_string[region->type]);
534 static ssize_t iommu_group_show_type(struct iommu_group *group,
537 char *type = "unknown\n";
539 mutex_lock(&group->mutex);
540 if (group->default_domain) {
541 switch (group->default_domain->type) {
542 case IOMMU_DOMAIN_BLOCKED:
545 case IOMMU_DOMAIN_IDENTITY:
548 case IOMMU_DOMAIN_UNMANAGED:
549 type = "unmanaged\n";
551 case IOMMU_DOMAIN_DMA:
556 mutex_unlock(&group->mutex);
562 static IOMMU_GROUP_ATTR(name, S_IRUGO, iommu_group_show_name, NULL);
564 static IOMMU_GROUP_ATTR(reserved_regions, 0444,
565 iommu_group_show_resv_regions, NULL);
567 static IOMMU_GROUP_ATTR(type, 0644, iommu_group_show_type,
568 iommu_group_store_type);
570 static void iommu_group_release(struct kobject *kobj)
572 struct iommu_group *group = to_iommu_group(kobj);
574 pr_debug("Releasing group %d\n", group->id);
576 if (group->iommu_data_release)
577 group->iommu_data_release(group->iommu_data);
579 ida_simple_remove(&iommu_group_ida, group->id);
581 if (group->default_domain)
582 iommu_domain_free(group->default_domain);
588 static struct kobj_type iommu_group_ktype = {
589 .sysfs_ops = &iommu_group_sysfs_ops,
590 .release = iommu_group_release,
594 * iommu_group_alloc - Allocate a new group
596 * This function is called by an iommu driver to allocate a new iommu
597 * group. The iommu group represents the minimum granularity of the iommu.
598 * Upon successful return, the caller holds a reference to the supplied
599 * group in order to hold the group until devices are added. Use
600 * iommu_group_put() to release this extra reference count, allowing the
601 * group to be automatically reclaimed once it has no devices or external
604 struct iommu_group *iommu_group_alloc(void)
606 struct iommu_group *group;
609 group = kzalloc(sizeof(*group), GFP_KERNEL);
611 return ERR_PTR(-ENOMEM);
613 group->kobj.kset = iommu_group_kset;
614 mutex_init(&group->mutex);
615 INIT_LIST_HEAD(&group->devices);
616 INIT_LIST_HEAD(&group->entry);
617 BLOCKING_INIT_NOTIFIER_HEAD(&group->notifier);
619 ret = ida_simple_get(&iommu_group_ida, 0, 0, GFP_KERNEL);
626 ret = kobject_init_and_add(&group->kobj, &iommu_group_ktype,
627 NULL, "%d", group->id);
629 ida_simple_remove(&iommu_group_ida, group->id);
630 kobject_put(&group->kobj);
634 group->devices_kobj = kobject_create_and_add("devices", &group->kobj);
635 if (!group->devices_kobj) {
636 kobject_put(&group->kobj); /* triggers .release & free */
637 return ERR_PTR(-ENOMEM);
641 * The devices_kobj holds a reference on the group kobject, so
642 * as long as that exists so will the group. We can therefore
643 * use the devices_kobj for reference counting.
645 kobject_put(&group->kobj);
647 ret = iommu_group_create_file(group,
648 &iommu_group_attr_reserved_regions);
652 ret = iommu_group_create_file(group, &iommu_group_attr_type);
656 pr_debug("Allocated group %d\n", group->id);
660 EXPORT_SYMBOL_GPL(iommu_group_alloc);
662 struct iommu_group *iommu_group_get_by_id(int id)
664 struct kobject *group_kobj;
665 struct iommu_group *group;
668 if (!iommu_group_kset)
671 name = kasprintf(GFP_KERNEL, "%d", id);
675 group_kobj = kset_find_obj(iommu_group_kset, name);
681 group = container_of(group_kobj, struct iommu_group, kobj);
682 BUG_ON(group->id != id);
684 kobject_get(group->devices_kobj);
685 kobject_put(&group->kobj);
689 EXPORT_SYMBOL_GPL(iommu_group_get_by_id);
692 * iommu_group_get_iommudata - retrieve iommu_data registered for a group
695 * iommu drivers can store data in the group for use when doing iommu
696 * operations. This function provides a way to retrieve it. Caller
697 * should hold a group reference.
699 void *iommu_group_get_iommudata(struct iommu_group *group)
701 return group->iommu_data;
703 EXPORT_SYMBOL_GPL(iommu_group_get_iommudata);
706 * iommu_group_set_iommudata - set iommu_data for a group
708 * @iommu_data: new data
709 * @release: release function for iommu_data
711 * iommu drivers can store data in the group for use when doing iommu
712 * operations. This function provides a way to set the data after
713 * the group has been allocated. Caller should hold a group reference.
715 void iommu_group_set_iommudata(struct iommu_group *group, void *iommu_data,
716 void (*release)(void *iommu_data))
718 group->iommu_data = iommu_data;
719 group->iommu_data_release = release;
721 EXPORT_SYMBOL_GPL(iommu_group_set_iommudata);
724 * iommu_group_set_name - set name for a group
728 * Allow iommu driver to set a name for a group. When set it will
729 * appear in a name attribute file under the group in sysfs.
731 int iommu_group_set_name(struct iommu_group *group, const char *name)
736 iommu_group_remove_file(group, &iommu_group_attr_name);
743 group->name = kstrdup(name, GFP_KERNEL);
747 ret = iommu_group_create_file(group, &iommu_group_attr_name);
756 EXPORT_SYMBOL_GPL(iommu_group_set_name);
758 static int iommu_create_device_direct_mappings(struct iommu_group *group,
761 struct iommu_domain *domain = group->default_domain;
762 struct iommu_resv_region *entry;
763 struct list_head mappings;
764 unsigned long pg_size;
767 if (!domain || domain->type != IOMMU_DOMAIN_DMA)
770 BUG_ON(!domain->pgsize_bitmap);
772 pg_size = 1UL << __ffs(domain->pgsize_bitmap);
773 INIT_LIST_HEAD(&mappings);
775 iommu_get_resv_regions(dev, &mappings);
777 /* We need to consider overlapping regions for different devices */
778 list_for_each_entry(entry, &mappings, list) {
779 dma_addr_t start, end, addr;
782 if (domain->ops->apply_resv_region)
783 domain->ops->apply_resv_region(dev, domain, entry);
785 start = ALIGN(entry->start, pg_size);
786 end = ALIGN(entry->start + entry->length, pg_size);
788 if (entry->type != IOMMU_RESV_DIRECT &&
789 entry->type != IOMMU_RESV_DIRECT_RELAXABLE)
792 for (addr = start; addr <= end; addr += pg_size) {
793 phys_addr_t phys_addr;
798 phys_addr = iommu_iova_to_phys(domain, addr);
806 ret = iommu_map(domain, addr - map_size,
807 addr - map_size, map_size,
817 iommu_flush_iotlb_all(domain);
820 iommu_put_resv_regions(dev, &mappings);
825 static bool iommu_is_attach_deferred(struct iommu_domain *domain,
828 if (domain->ops->is_attach_deferred)
829 return domain->ops->is_attach_deferred(domain, dev);
835 * iommu_group_add_device - add a device to an iommu group
836 * @group: the group into which to add the device (reference should be held)
839 * This function is called by an iommu driver to add a device into a
840 * group. Adding a device increments the group reference count.
842 int iommu_group_add_device(struct iommu_group *group, struct device *dev)
845 struct group_device *device;
847 device = kzalloc(sizeof(*device), GFP_KERNEL);
853 ret = sysfs_create_link(&dev->kobj, &group->kobj, "iommu_group");
855 goto err_free_device;
857 device->name = kasprintf(GFP_KERNEL, "%s", kobject_name(&dev->kobj));
861 goto err_remove_link;
864 ret = sysfs_create_link_nowarn(group->devices_kobj,
865 &dev->kobj, device->name);
867 if (ret == -EEXIST && i >= 0) {
869 * Account for the slim chance of collision
870 * and append an instance to the name.
873 device->name = kasprintf(GFP_KERNEL, "%s.%d",
874 kobject_name(&dev->kobj), i++);
880 kobject_get(group->devices_kobj);
882 dev->iommu_group = group;
884 mutex_lock(&group->mutex);
885 list_add_tail(&device->list, &group->devices);
886 if (group->domain && !iommu_is_attach_deferred(group->domain, dev))
887 ret = __iommu_attach_device(group->domain, dev);
888 mutex_unlock(&group->mutex);
892 /* Notify any listeners about change to group. */
893 blocking_notifier_call_chain(&group->notifier,
894 IOMMU_GROUP_NOTIFY_ADD_DEVICE, dev);
896 trace_add_device_to_group(group->id, dev);
898 dev_info(dev, "Adding to iommu group %d\n", group->id);
903 mutex_lock(&group->mutex);
904 list_del(&device->list);
905 mutex_unlock(&group->mutex);
906 dev->iommu_group = NULL;
907 kobject_put(group->devices_kobj);
908 sysfs_remove_link(group->devices_kobj, device->name);
912 sysfs_remove_link(&dev->kobj, "iommu_group");
915 dev_err(dev, "Failed to add to iommu group %d: %d\n", group->id, ret);
918 EXPORT_SYMBOL_GPL(iommu_group_add_device);
921 * iommu_group_remove_device - remove a device from it's current group
922 * @dev: device to be removed
924 * This function is called by an iommu driver to remove the device from
925 * it's current group. This decrements the iommu group reference count.
927 void iommu_group_remove_device(struct device *dev)
929 struct iommu_group *group = dev->iommu_group;
930 struct group_device *tmp_device, *device = NULL;
932 dev_info(dev, "Removing from iommu group %d\n", group->id);
934 /* Pre-notify listeners that a device is being removed. */
935 blocking_notifier_call_chain(&group->notifier,
936 IOMMU_GROUP_NOTIFY_DEL_DEVICE, dev);
938 mutex_lock(&group->mutex);
939 list_for_each_entry(tmp_device, &group->devices, list) {
940 if (tmp_device->dev == dev) {
942 list_del(&device->list);
946 mutex_unlock(&group->mutex);
951 sysfs_remove_link(group->devices_kobj, device->name);
952 sysfs_remove_link(&dev->kobj, "iommu_group");
954 trace_remove_device_from_group(group->id, dev);
958 dev->iommu_group = NULL;
959 kobject_put(group->devices_kobj);
961 EXPORT_SYMBOL_GPL(iommu_group_remove_device);
963 static int iommu_group_device_count(struct iommu_group *group)
965 struct group_device *entry;
968 list_for_each_entry(entry, &group->devices, list)
975 * iommu_group_for_each_dev - iterate over each device in the group
977 * @data: caller opaque data to be passed to callback function
978 * @fn: caller supplied callback function
980 * This function is called by group users to iterate over group devices.
981 * Callers should hold a reference count to the group during callback.
982 * The group->mutex is held across callbacks, which will block calls to
983 * iommu_group_add/remove_device.
985 static int __iommu_group_for_each_dev(struct iommu_group *group, void *data,
986 int (*fn)(struct device *, void *))
988 struct group_device *device;
991 list_for_each_entry(device, &group->devices, list) {
992 ret = fn(device->dev, data);
1000 int iommu_group_for_each_dev(struct iommu_group *group, void *data,
1001 int (*fn)(struct device *, void *))
1005 mutex_lock(&group->mutex);
1006 ret = __iommu_group_for_each_dev(group, data, fn);
1007 mutex_unlock(&group->mutex);
1011 EXPORT_SYMBOL_GPL(iommu_group_for_each_dev);
1014 * iommu_group_get - Return the group for a device and increment reference
1015 * @dev: get the group that this device belongs to
1017 * This function is called by iommu drivers and users to get the group
1018 * for the specified device. If found, the group is returned and the group
1019 * reference in incremented, else NULL.
1021 struct iommu_group *iommu_group_get(struct device *dev)
1023 struct iommu_group *group = dev->iommu_group;
1026 kobject_get(group->devices_kobj);
1030 EXPORT_SYMBOL_GPL(iommu_group_get);
1033 * iommu_group_ref_get - Increment reference on a group
1034 * @group: the group to use, must not be NULL
1036 * This function is called by iommu drivers to take additional references on an
1037 * existing group. Returns the given group for convenience.
1039 struct iommu_group *iommu_group_ref_get(struct iommu_group *group)
1041 kobject_get(group->devices_kobj);
1044 EXPORT_SYMBOL_GPL(iommu_group_ref_get);
1047 * iommu_group_put - Decrement group reference
1048 * @group: the group to use
1050 * This function is called by iommu drivers and users to release the
1051 * iommu group. Once the reference count is zero, the group is released.
1053 void iommu_group_put(struct iommu_group *group)
1056 kobject_put(group->devices_kobj);
1058 EXPORT_SYMBOL_GPL(iommu_group_put);
1061 * iommu_group_register_notifier - Register a notifier for group changes
1062 * @group: the group to watch
1063 * @nb: notifier block to signal
1065 * This function allows iommu group users to track changes in a group.
1066 * See include/linux/iommu.h for actions sent via this notifier. Caller
1067 * should hold a reference to the group throughout notifier registration.
1069 int iommu_group_register_notifier(struct iommu_group *group,
1070 struct notifier_block *nb)
1072 return blocking_notifier_chain_register(&group->notifier, nb);
1074 EXPORT_SYMBOL_GPL(iommu_group_register_notifier);
1077 * iommu_group_unregister_notifier - Unregister a notifier
1078 * @group: the group to watch
1079 * @nb: notifier block to signal
1081 * Unregister a previously registered group notifier block.
1083 int iommu_group_unregister_notifier(struct iommu_group *group,
1084 struct notifier_block *nb)
1086 return blocking_notifier_chain_unregister(&group->notifier, nb);
1088 EXPORT_SYMBOL_GPL(iommu_group_unregister_notifier);
1091 * iommu_register_device_fault_handler() - Register a device fault handler
1093 * @handler: the fault handler
1094 * @data: private data passed as argument to the handler
1096 * When an IOMMU fault event is received, this handler gets called with the
1097 * fault event and data as argument. The handler should return 0 on success. If
1098 * the fault is recoverable (IOMMU_FAULT_PAGE_REQ), the consumer should also
1099 * complete the fault by calling iommu_page_response() with one of the following
1101 * - IOMMU_PAGE_RESP_SUCCESS: retry the translation
1102 * - IOMMU_PAGE_RESP_INVALID: terminate the fault
1103 * - IOMMU_PAGE_RESP_FAILURE: terminate the fault and stop reporting
1104 * page faults if possible.
1106 * Return 0 if the fault handler was installed successfully, or an error.
1108 int iommu_register_device_fault_handler(struct device *dev,
1109 iommu_dev_fault_handler_t handler,
1112 struct dev_iommu *param = dev->iommu;
1118 mutex_lock(¶m->lock);
1119 /* Only allow one fault handler registered for each device */
1120 if (param->fault_param) {
1126 param->fault_param = kzalloc(sizeof(*param->fault_param), GFP_KERNEL);
1127 if (!param->fault_param) {
1132 param->fault_param->handler = handler;
1133 param->fault_param->data = data;
1134 mutex_init(¶m->fault_param->lock);
1135 INIT_LIST_HEAD(¶m->fault_param->faults);
1138 mutex_unlock(¶m->lock);
1142 EXPORT_SYMBOL_GPL(iommu_register_device_fault_handler);
1145 * iommu_unregister_device_fault_handler() - Unregister the device fault handler
1148 * Remove the device fault handler installed with
1149 * iommu_register_device_fault_handler().
1151 * Return 0 on success, or an error.
1153 int iommu_unregister_device_fault_handler(struct device *dev)
1155 struct dev_iommu *param = dev->iommu;
1161 mutex_lock(¶m->lock);
1163 if (!param->fault_param)
1166 /* we cannot unregister handler if there are pending faults */
1167 if (!list_empty(¶m->fault_param->faults)) {
1172 kfree(param->fault_param);
1173 param->fault_param = NULL;
1176 mutex_unlock(¶m->lock);
1180 EXPORT_SYMBOL_GPL(iommu_unregister_device_fault_handler);
1183 * iommu_report_device_fault() - Report fault event to device driver
1185 * @evt: fault event data
1187 * Called by IOMMU drivers when a fault is detected, typically in a threaded IRQ
1188 * handler. When this function fails and the fault is recoverable, it is the
1189 * caller's responsibility to complete the fault.
1191 * Return 0 on success, or an error.
1193 int iommu_report_device_fault(struct device *dev, struct iommu_fault_event *evt)
1195 struct dev_iommu *param = dev->iommu;
1196 struct iommu_fault_event *evt_pending = NULL;
1197 struct iommu_fault_param *fparam;
1203 /* we only report device fault if there is a handler registered */
1204 mutex_lock(¶m->lock);
1205 fparam = param->fault_param;
1206 if (!fparam || !fparam->handler) {
1211 if (evt->fault.type == IOMMU_FAULT_PAGE_REQ &&
1212 (evt->fault.prm.flags & IOMMU_FAULT_PAGE_REQUEST_LAST_PAGE)) {
1213 evt_pending = kmemdup(evt, sizeof(struct iommu_fault_event),
1219 mutex_lock(&fparam->lock);
1220 list_add_tail(&evt_pending->list, &fparam->faults);
1221 mutex_unlock(&fparam->lock);
1224 ret = fparam->handler(&evt->fault, fparam->data);
1225 if (ret && evt_pending) {
1226 mutex_lock(&fparam->lock);
1227 list_del(&evt_pending->list);
1228 mutex_unlock(&fparam->lock);
1232 mutex_unlock(¶m->lock);
1235 EXPORT_SYMBOL_GPL(iommu_report_device_fault);
1237 int iommu_page_response(struct device *dev,
1238 struct iommu_page_response *msg)
1242 struct iommu_fault_event *evt;
1243 struct iommu_fault_page_request *prm;
1244 struct dev_iommu *param = dev->iommu;
1245 bool has_pasid = msg->flags & IOMMU_PAGE_RESP_PASID_VALID;
1246 struct iommu_domain *domain = iommu_get_domain_for_dev(dev);
1248 if (!domain || !domain->ops->page_response)
1251 if (!param || !param->fault_param)
1254 if (msg->version != IOMMU_PAGE_RESP_VERSION_1 ||
1255 msg->flags & ~IOMMU_PAGE_RESP_PASID_VALID)
1258 /* Only send response if there is a fault report pending */
1259 mutex_lock(¶m->fault_param->lock);
1260 if (list_empty(¶m->fault_param->faults)) {
1261 dev_warn_ratelimited(dev, "no pending PRQ, drop response\n");
1265 * Check if we have a matching page request pending to respond,
1266 * otherwise return -EINVAL
1268 list_for_each_entry(evt, ¶m->fault_param->faults, list) {
1269 prm = &evt->fault.prm;
1270 if (prm->grpid != msg->grpid)
1274 * If the PASID is required, the corresponding request is
1275 * matched using the group ID, the PASID valid bit and the PASID
1276 * value. Otherwise only the group ID matches request and
1279 needs_pasid = prm->flags & IOMMU_FAULT_PAGE_RESPONSE_NEEDS_PASID;
1280 if (needs_pasid && (!has_pasid || msg->pasid != prm->pasid))
1283 if (!needs_pasid && has_pasid) {
1284 /* No big deal, just clear it. */
1285 msg->flags &= ~IOMMU_PAGE_RESP_PASID_VALID;
1289 ret = domain->ops->page_response(dev, evt, msg);
1290 list_del(&evt->list);
1296 mutex_unlock(¶m->fault_param->lock);
1299 EXPORT_SYMBOL_GPL(iommu_page_response);
1302 * iommu_group_id - Return ID for a group
1303 * @group: the group to ID
1305 * Return the unique ID for the group matching the sysfs group number.
1307 int iommu_group_id(struct iommu_group *group)
1311 EXPORT_SYMBOL_GPL(iommu_group_id);
1313 static struct iommu_group *get_pci_alias_group(struct pci_dev *pdev,
1314 unsigned long *devfns);
1317 * To consider a PCI device isolated, we require ACS to support Source
1318 * Validation, Request Redirection, Completer Redirection, and Upstream
1319 * Forwarding. This effectively means that devices cannot spoof their
1320 * requester ID, requests and completions cannot be redirected, and all
1321 * transactions are forwarded upstream, even as it passes through a
1322 * bridge where the target device is downstream.
1324 #define REQ_ACS_FLAGS (PCI_ACS_SV | PCI_ACS_RR | PCI_ACS_CR | PCI_ACS_UF)
1327 * For multifunction devices which are not isolated from each other, find
1328 * all the other non-isolated functions and look for existing groups. For
1329 * each function, we also need to look for aliases to or from other devices
1330 * that may already have a group.
1332 static struct iommu_group *get_pci_function_alias_group(struct pci_dev *pdev,
1333 unsigned long *devfns)
1335 struct pci_dev *tmp = NULL;
1336 struct iommu_group *group;
1338 if (!pdev->multifunction || pci_acs_enabled(pdev, REQ_ACS_FLAGS))
1341 for_each_pci_dev(tmp) {
1342 if (tmp == pdev || tmp->bus != pdev->bus ||
1343 PCI_SLOT(tmp->devfn) != PCI_SLOT(pdev->devfn) ||
1344 pci_acs_enabled(tmp, REQ_ACS_FLAGS))
1347 group = get_pci_alias_group(tmp, devfns);
1358 * Look for aliases to or from the given device for existing groups. DMA
1359 * aliases are only supported on the same bus, therefore the search
1360 * space is quite small (especially since we're really only looking at pcie
1361 * device, and therefore only expect multiple slots on the root complex or
1362 * downstream switch ports). It's conceivable though that a pair of
1363 * multifunction devices could have aliases between them that would cause a
1364 * loop. To prevent this, we use a bitmap to track where we've been.
1366 static struct iommu_group *get_pci_alias_group(struct pci_dev *pdev,
1367 unsigned long *devfns)
1369 struct pci_dev *tmp = NULL;
1370 struct iommu_group *group;
1372 if (test_and_set_bit(pdev->devfn & 0xff, devfns))
1375 group = iommu_group_get(&pdev->dev);
1379 for_each_pci_dev(tmp) {
1380 if (tmp == pdev || tmp->bus != pdev->bus)
1383 /* We alias them or they alias us */
1384 if (pci_devs_are_dma_aliases(pdev, tmp)) {
1385 group = get_pci_alias_group(tmp, devfns);
1391 group = get_pci_function_alias_group(tmp, devfns);
1402 struct group_for_pci_data {
1403 struct pci_dev *pdev;
1404 struct iommu_group *group;
1408 * DMA alias iterator callback, return the last seen device. Stop and return
1409 * the IOMMU group if we find one along the way.
1411 static int get_pci_alias_or_group(struct pci_dev *pdev, u16 alias, void *opaque)
1413 struct group_for_pci_data *data = opaque;
1416 data->group = iommu_group_get(&pdev->dev);
1418 return data->group != NULL;
1422 * Generic device_group call-back function. It just allocates one
1423 * iommu-group per device.
1425 struct iommu_group *generic_device_group(struct device *dev)
1427 return iommu_group_alloc();
1429 EXPORT_SYMBOL_GPL(generic_device_group);
1432 * Use standard PCI bus topology, isolation features, and DMA alias quirks
1433 * to find or create an IOMMU group for a device.
1435 struct iommu_group *pci_device_group(struct device *dev)
1437 struct pci_dev *pdev = to_pci_dev(dev);
1438 struct group_for_pci_data data;
1439 struct pci_bus *bus;
1440 struct iommu_group *group = NULL;
1441 u64 devfns[4] = { 0 };
1443 if (WARN_ON(!dev_is_pci(dev)))
1444 return ERR_PTR(-EINVAL);
1447 * Find the upstream DMA alias for the device. A device must not
1448 * be aliased due to topology in order to have its own IOMMU group.
1449 * If we find an alias along the way that already belongs to a
1452 if (pci_for_each_dma_alias(pdev, get_pci_alias_or_group, &data))
1458 * Continue upstream from the point of minimum IOMMU granularity
1459 * due to aliases to the point where devices are protected from
1460 * peer-to-peer DMA by PCI ACS. Again, if we find an existing
1463 for (bus = pdev->bus; !pci_is_root_bus(bus); bus = bus->parent) {
1467 if (pci_acs_path_enabled(bus->self, NULL, REQ_ACS_FLAGS))
1472 group = iommu_group_get(&pdev->dev);
1478 * Look for existing groups on device aliases. If we alias another
1479 * device or another device aliases us, use the same group.
1481 group = get_pci_alias_group(pdev, (unsigned long *)devfns);
1486 * Look for existing groups on non-isolated functions on the same
1487 * slot and aliases of those funcions, if any. No need to clear
1488 * the search bitmap, the tested devfns are still valid.
1490 group = get_pci_function_alias_group(pdev, (unsigned long *)devfns);
1494 /* No shared group found, allocate new */
1495 return iommu_group_alloc();
1497 EXPORT_SYMBOL_GPL(pci_device_group);
1499 /* Get the IOMMU group for device on fsl-mc bus */
1500 struct iommu_group *fsl_mc_device_group(struct device *dev)
1502 struct device *cont_dev = fsl_mc_cont_dev(dev);
1503 struct iommu_group *group;
1505 group = iommu_group_get(cont_dev);
1507 group = iommu_group_alloc();
1510 EXPORT_SYMBOL_GPL(fsl_mc_device_group);
1512 static int iommu_get_def_domain_type(struct device *dev)
1514 const struct iommu_ops *ops = dev->bus->iommu_ops;
1516 if (dev_is_pci(dev) && to_pci_dev(dev)->untrusted)
1517 return IOMMU_DOMAIN_DMA;
1519 if (ops->def_domain_type)
1520 return ops->def_domain_type(dev);
1525 static int iommu_group_alloc_default_domain(struct bus_type *bus,
1526 struct iommu_group *group,
1529 struct iommu_domain *dom;
1531 dom = __iommu_domain_alloc(bus, type);
1532 if (!dom && type != IOMMU_DOMAIN_DMA) {
1533 dom = __iommu_domain_alloc(bus, IOMMU_DOMAIN_DMA);
1535 pr_warn("Failed to allocate default IOMMU domain of type %u for group %s - Falling back to IOMMU_DOMAIN_DMA",
1542 group->default_domain = dom;
1544 group->domain = dom;
1548 static int iommu_alloc_default_domain(struct iommu_group *group,
1553 if (group->default_domain)
1556 type = iommu_get_def_domain_type(dev) ? : iommu_def_domain_type;
1558 return iommu_group_alloc_default_domain(dev->bus, group, type);
1562 * iommu_group_get_for_dev - Find or create the IOMMU group for a device
1563 * @dev: target device
1565 * This function is intended to be called by IOMMU drivers and extended to
1566 * support common, bus-defined algorithms when determining or creating the
1567 * IOMMU group for a device. On success, the caller will hold a reference
1568 * to the returned IOMMU group, which will already include the provided
1569 * device. The reference should be released with iommu_group_put().
1571 static struct iommu_group *iommu_group_get_for_dev(struct device *dev)
1573 const struct iommu_ops *ops = dev->bus->iommu_ops;
1574 struct iommu_group *group;
1577 group = iommu_group_get(dev);
1582 return ERR_PTR(-EINVAL);
1584 group = ops->device_group(dev);
1585 if (WARN_ON_ONCE(group == NULL))
1586 return ERR_PTR(-EINVAL);
1591 ret = iommu_group_add_device(group, dev);
1598 iommu_group_put(group);
1600 return ERR_PTR(ret);
1603 struct iommu_domain *iommu_group_default_domain(struct iommu_group *group)
1605 return group->default_domain;
1608 static int probe_iommu_group(struct device *dev, void *data)
1610 struct list_head *group_list = data;
1611 struct iommu_group *group;
1614 /* Device is probed already if in a group */
1615 group = iommu_group_get(dev);
1617 iommu_group_put(group);
1621 ret = __iommu_probe_device(dev, group_list);
1628 static int remove_iommu_group(struct device *dev, void *data)
1630 iommu_release_device(dev);
1635 static int iommu_bus_notifier(struct notifier_block *nb,
1636 unsigned long action, void *data)
1638 unsigned long group_action = 0;
1639 struct device *dev = data;
1640 struct iommu_group *group;
1643 * ADD/DEL call into iommu driver ops if provided, which may
1644 * result in ADD/DEL notifiers to group->notifier
1646 if (action == BUS_NOTIFY_ADD_DEVICE) {
1649 ret = iommu_probe_device(dev);
1650 return (ret) ? NOTIFY_DONE : NOTIFY_OK;
1651 } else if (action == BUS_NOTIFY_REMOVED_DEVICE) {
1652 iommu_release_device(dev);
1657 * Remaining BUS_NOTIFYs get filtered and republished to the
1658 * group, if anyone is listening
1660 group = iommu_group_get(dev);
1665 case BUS_NOTIFY_BIND_DRIVER:
1666 group_action = IOMMU_GROUP_NOTIFY_BIND_DRIVER;
1668 case BUS_NOTIFY_BOUND_DRIVER:
1669 group_action = IOMMU_GROUP_NOTIFY_BOUND_DRIVER;
1671 case BUS_NOTIFY_UNBIND_DRIVER:
1672 group_action = IOMMU_GROUP_NOTIFY_UNBIND_DRIVER;
1674 case BUS_NOTIFY_UNBOUND_DRIVER:
1675 group_action = IOMMU_GROUP_NOTIFY_UNBOUND_DRIVER;
1680 blocking_notifier_call_chain(&group->notifier,
1683 iommu_group_put(group);
1687 struct __group_domain_type {
1692 static int probe_get_default_domain_type(struct device *dev, void *data)
1694 struct __group_domain_type *gtype = data;
1695 unsigned int type = iommu_get_def_domain_type(dev);
1698 if (gtype->type && gtype->type != type) {
1699 dev_warn(dev, "Device needs domain type %s, but device %s in the same iommu group requires type %s - using default\n",
1700 iommu_domain_type_str(type),
1701 dev_name(gtype->dev),
1702 iommu_domain_type_str(gtype->type));
1715 static void probe_alloc_default_domain(struct bus_type *bus,
1716 struct iommu_group *group)
1718 struct __group_domain_type gtype;
1720 memset(>ype, 0, sizeof(gtype));
1722 /* Ask for default domain requirements of all devices in the group */
1723 __iommu_group_for_each_dev(group, >ype,
1724 probe_get_default_domain_type);
1727 gtype.type = iommu_def_domain_type;
1729 iommu_group_alloc_default_domain(bus, group, gtype.type);
1733 static int iommu_group_do_dma_attach(struct device *dev, void *data)
1735 struct iommu_domain *domain = data;
1738 if (!iommu_is_attach_deferred(domain, dev))
1739 ret = __iommu_attach_device(domain, dev);
1744 static int __iommu_group_dma_attach(struct iommu_group *group)
1746 return __iommu_group_for_each_dev(group, group->default_domain,
1747 iommu_group_do_dma_attach);
1750 static int iommu_group_do_probe_finalize(struct device *dev, void *data)
1752 struct iommu_domain *domain = data;
1754 if (domain->ops->probe_finalize)
1755 domain->ops->probe_finalize(dev);
1760 static void __iommu_group_dma_finalize(struct iommu_group *group)
1762 __iommu_group_for_each_dev(group, group->default_domain,
1763 iommu_group_do_probe_finalize);
1766 static int iommu_do_create_direct_mappings(struct device *dev, void *data)
1768 struct iommu_group *group = data;
1770 iommu_create_device_direct_mappings(group, dev);
1775 static int iommu_group_create_direct_mappings(struct iommu_group *group)
1777 return __iommu_group_for_each_dev(group, group,
1778 iommu_do_create_direct_mappings);
1781 int bus_iommu_probe(struct bus_type *bus)
1783 struct iommu_group *group, *next;
1784 LIST_HEAD(group_list);
1788 * This code-path does not allocate the default domain when
1789 * creating the iommu group, so do it after the groups are
1792 ret = bus_for_each_dev(bus, NULL, &group_list, probe_iommu_group);
1796 list_for_each_entry_safe(group, next, &group_list, entry) {
1797 /* Remove item from the list */
1798 list_del_init(&group->entry);
1800 mutex_lock(&group->mutex);
1802 /* Try to allocate default domain */
1803 probe_alloc_default_domain(bus, group);
1805 if (!group->default_domain) {
1806 mutex_unlock(&group->mutex);
1810 iommu_group_create_direct_mappings(group);
1812 ret = __iommu_group_dma_attach(group);
1814 mutex_unlock(&group->mutex);
1819 __iommu_group_dma_finalize(group);
1825 static int iommu_bus_init(struct bus_type *bus, const struct iommu_ops *ops)
1827 struct notifier_block *nb;
1830 nb = kzalloc(sizeof(struct notifier_block), GFP_KERNEL);
1834 nb->notifier_call = iommu_bus_notifier;
1836 err = bus_register_notifier(bus, nb);
1840 err = bus_iommu_probe(bus);
1849 bus_for_each_dev(bus, NULL, NULL, remove_iommu_group);
1850 bus_unregister_notifier(bus, nb);
1859 * bus_set_iommu - set iommu-callbacks for the bus
1861 * @ops: the callbacks provided by the iommu-driver
1863 * This function is called by an iommu driver to set the iommu methods
1864 * used for a particular bus. Drivers for devices on that bus can use
1865 * the iommu-api after these ops are registered.
1866 * This special function is needed because IOMMUs are usually devices on
1867 * the bus itself, so the iommu drivers are not initialized when the bus
1868 * is set up. With this function the iommu-driver can set the iommu-ops
1871 int bus_set_iommu(struct bus_type *bus, const struct iommu_ops *ops)
1876 bus->iommu_ops = NULL;
1880 if (bus->iommu_ops != NULL)
1883 bus->iommu_ops = ops;
1885 /* Do IOMMU specific setup for this bus-type */
1886 err = iommu_bus_init(bus, ops);
1888 bus->iommu_ops = NULL;
1892 EXPORT_SYMBOL_GPL(bus_set_iommu);
1894 bool iommu_present(struct bus_type *bus)
1896 return bus->iommu_ops != NULL;
1898 EXPORT_SYMBOL_GPL(iommu_present);
1900 bool iommu_capable(struct bus_type *bus, enum iommu_cap cap)
1902 if (!bus->iommu_ops || !bus->iommu_ops->capable)
1905 return bus->iommu_ops->capable(cap);
1907 EXPORT_SYMBOL_GPL(iommu_capable);
1910 * iommu_set_fault_handler() - set a fault handler for an iommu domain
1911 * @domain: iommu domain
1912 * @handler: fault handler
1913 * @token: user data, will be passed back to the fault handler
1915 * This function should be used by IOMMU users which want to be notified
1916 * whenever an IOMMU fault happens.
1918 * The fault handler itself should return 0 on success, and an appropriate
1919 * error code otherwise.
1921 void iommu_set_fault_handler(struct iommu_domain *domain,
1922 iommu_fault_handler_t handler,
1927 domain->handler = handler;
1928 domain->handler_token = token;
1930 EXPORT_SYMBOL_GPL(iommu_set_fault_handler);
1932 static struct iommu_domain *__iommu_domain_alloc(struct bus_type *bus,
1935 struct iommu_domain *domain;
1937 if (bus == NULL || bus->iommu_ops == NULL)
1940 domain = bus->iommu_ops->domain_alloc(type);
1944 domain->ops = bus->iommu_ops;
1945 domain->type = type;
1946 /* Assume all sizes by default; the driver may override this later */
1947 domain->pgsize_bitmap = bus->iommu_ops->pgsize_bitmap;
1952 struct iommu_domain *iommu_domain_alloc(struct bus_type *bus)
1954 return __iommu_domain_alloc(bus, IOMMU_DOMAIN_UNMANAGED);
1956 EXPORT_SYMBOL_GPL(iommu_domain_alloc);
1958 void iommu_domain_free(struct iommu_domain *domain)
1960 domain->ops->domain_free(domain);
1962 EXPORT_SYMBOL_GPL(iommu_domain_free);
1964 static int __iommu_attach_device(struct iommu_domain *domain,
1969 if (unlikely(domain->ops->attach_dev == NULL))
1972 ret = domain->ops->attach_dev(domain, dev);
1974 trace_attach_device_to_domain(dev);
1978 int iommu_attach_device(struct iommu_domain *domain, struct device *dev)
1980 struct iommu_group *group;
1983 group = iommu_group_get(dev);
1988 * Lock the group to make sure the device-count doesn't
1989 * change while we are attaching
1991 mutex_lock(&group->mutex);
1993 if (iommu_group_device_count(group) != 1)
1996 ret = __iommu_attach_group(domain, group);
1999 mutex_unlock(&group->mutex);
2000 iommu_group_put(group);
2004 EXPORT_SYMBOL_GPL(iommu_attach_device);
2006 int iommu_deferred_attach(struct device *dev, struct iommu_domain *domain)
2008 const struct iommu_ops *ops = domain->ops;
2010 if (ops->is_attach_deferred && ops->is_attach_deferred(domain, dev))
2011 return __iommu_attach_device(domain, dev);
2017 * Check flags and other user provided data for valid combinations. We also
2018 * make sure no reserved fields or unused flags are set. This is to ensure
2019 * not breaking userspace in the future when these fields or flags are used.
2021 static int iommu_check_cache_invl_data(struct iommu_cache_invalidate_info *info)
2026 if (info->version != IOMMU_CACHE_INVALIDATE_INFO_VERSION_1)
2029 mask = (1 << IOMMU_CACHE_INV_TYPE_NR) - 1;
2030 if (info->cache & ~mask)
2033 if (info->granularity >= IOMMU_INV_GRANU_NR)
2036 switch (info->granularity) {
2037 case IOMMU_INV_GRANU_ADDR:
2038 if (info->cache & IOMMU_CACHE_INV_TYPE_PASID)
2041 mask = IOMMU_INV_ADDR_FLAGS_PASID |
2042 IOMMU_INV_ADDR_FLAGS_ARCHID |
2043 IOMMU_INV_ADDR_FLAGS_LEAF;
2045 if (info->granu.addr_info.flags & ~mask)
2048 case IOMMU_INV_GRANU_PASID:
2049 mask = IOMMU_INV_PASID_FLAGS_PASID |
2050 IOMMU_INV_PASID_FLAGS_ARCHID;
2051 if (info->granu.pasid_info.flags & ~mask)
2055 case IOMMU_INV_GRANU_DOMAIN:
2056 if (info->cache & IOMMU_CACHE_INV_TYPE_DEV_IOTLB)
2063 /* Check reserved padding fields */
2064 for (i = 0; i < sizeof(info->padding); i++) {
2065 if (info->padding[i])
2072 int iommu_uapi_cache_invalidate(struct iommu_domain *domain, struct device *dev,
2075 struct iommu_cache_invalidate_info inv_info = { 0 };
2079 if (unlikely(!domain->ops->cache_invalidate))
2083 * No new spaces can be added before the variable sized union, the
2084 * minimum size is the offset to the union.
2086 minsz = offsetof(struct iommu_cache_invalidate_info, granu);
2088 /* Copy minsz from user to get flags and argsz */
2089 if (copy_from_user(&inv_info, uinfo, minsz))
2092 /* Fields before the variable size union are mandatory */
2093 if (inv_info.argsz < minsz)
2096 /* PASID and address granu require additional info beyond minsz */
2097 if (inv_info.granularity == IOMMU_INV_GRANU_PASID &&
2098 inv_info.argsz < offsetofend(struct iommu_cache_invalidate_info, granu.pasid_info))
2101 if (inv_info.granularity == IOMMU_INV_GRANU_ADDR &&
2102 inv_info.argsz < offsetofend(struct iommu_cache_invalidate_info, granu.addr_info))
2106 * User might be using a newer UAPI header which has a larger data
2107 * size, we shall support the existing flags within the current
2108 * size. Copy the remaining user data _after_ minsz but not more
2109 * than the current kernel supported size.
2111 if (copy_from_user((void *)&inv_info + minsz, uinfo + minsz,
2112 min_t(u32, inv_info.argsz, sizeof(inv_info)) - minsz))
2115 /* Now the argsz is validated, check the content */
2116 ret = iommu_check_cache_invl_data(&inv_info);
2120 return domain->ops->cache_invalidate(domain, dev, &inv_info);
2122 EXPORT_SYMBOL_GPL(iommu_uapi_cache_invalidate);
2124 static int iommu_check_bind_data(struct iommu_gpasid_bind_data *data)
2129 if (data->version != IOMMU_GPASID_BIND_VERSION_1)
2132 /* Check the range of supported formats */
2133 if (data->format >= IOMMU_PASID_FORMAT_LAST)
2136 /* Check all flags */
2137 mask = IOMMU_SVA_GPASID_VAL;
2138 if (data->flags & ~mask)
2141 /* Check reserved padding fields */
2142 for (i = 0; i < sizeof(data->padding); i++) {
2143 if (data->padding[i])
2150 static int iommu_sva_prepare_bind_data(void __user *udata,
2151 struct iommu_gpasid_bind_data *data)
2156 * No new spaces can be added before the variable sized union, the
2157 * minimum size is the offset to the union.
2159 minsz = offsetof(struct iommu_gpasid_bind_data, vendor);
2161 /* Copy minsz from user to get flags and argsz */
2162 if (copy_from_user(data, udata, minsz))
2165 /* Fields before the variable size union are mandatory */
2166 if (data->argsz < minsz)
2169 * User might be using a newer UAPI header, we shall let IOMMU vendor
2170 * driver decide on what size it needs. Since the guest PASID bind data
2171 * can be vendor specific, larger argsz could be the result of extension
2172 * for one vendor but it should not affect another vendor.
2173 * Copy the remaining user data _after_ minsz
2175 if (copy_from_user((void *)data + minsz, udata + minsz,
2176 min_t(u32, data->argsz, sizeof(*data)) - minsz))
2179 return iommu_check_bind_data(data);
2182 int iommu_uapi_sva_bind_gpasid(struct iommu_domain *domain, struct device *dev,
2185 struct iommu_gpasid_bind_data data = { 0 };
2188 if (unlikely(!domain->ops->sva_bind_gpasid))
2191 ret = iommu_sva_prepare_bind_data(udata, &data);
2195 return domain->ops->sva_bind_gpasid(domain, dev, &data);
2197 EXPORT_SYMBOL_GPL(iommu_uapi_sva_bind_gpasid);
2199 int iommu_sva_unbind_gpasid(struct iommu_domain *domain, struct device *dev,
2202 if (unlikely(!domain->ops->sva_unbind_gpasid))
2205 return domain->ops->sva_unbind_gpasid(dev, pasid);
2207 EXPORT_SYMBOL_GPL(iommu_sva_unbind_gpasid);
2209 int iommu_uapi_sva_unbind_gpasid(struct iommu_domain *domain, struct device *dev,
2212 struct iommu_gpasid_bind_data data = { 0 };
2215 if (unlikely(!domain->ops->sva_bind_gpasid))
2218 ret = iommu_sva_prepare_bind_data(udata, &data);
2222 return iommu_sva_unbind_gpasid(domain, dev, data.hpasid);
2224 EXPORT_SYMBOL_GPL(iommu_uapi_sva_unbind_gpasid);
2226 static void __iommu_detach_device(struct iommu_domain *domain,
2229 if (iommu_is_attach_deferred(domain, dev))
2232 if (unlikely(domain->ops->detach_dev == NULL))
2235 domain->ops->detach_dev(domain, dev);
2236 trace_detach_device_from_domain(dev);
2239 void iommu_detach_device(struct iommu_domain *domain, struct device *dev)
2241 struct iommu_group *group;
2243 group = iommu_group_get(dev);
2247 mutex_lock(&group->mutex);
2248 if (iommu_group_device_count(group) != 1) {
2253 __iommu_detach_group(domain, group);
2256 mutex_unlock(&group->mutex);
2257 iommu_group_put(group);
2259 EXPORT_SYMBOL_GPL(iommu_detach_device);
2261 struct iommu_domain *iommu_get_domain_for_dev(struct device *dev)
2263 struct iommu_domain *domain;
2264 struct iommu_group *group;
2266 group = iommu_group_get(dev);
2270 domain = group->domain;
2272 iommu_group_put(group);
2276 EXPORT_SYMBOL_GPL(iommu_get_domain_for_dev);
2279 * For IOMMU_DOMAIN_DMA implementations which already provide their own
2280 * guarantees that the group and its default domain are valid and correct.
2282 struct iommu_domain *iommu_get_dma_domain(struct device *dev)
2284 return dev->iommu_group->default_domain;
2288 * IOMMU groups are really the natural working unit of the IOMMU, but
2289 * the IOMMU API works on domains and devices. Bridge that gap by
2290 * iterating over the devices in a group. Ideally we'd have a single
2291 * device which represents the requestor ID of the group, but we also
2292 * allow IOMMU drivers to create policy defined minimum sets, where
2293 * the physical hardware may be able to distiguish members, but we
2294 * wish to group them at a higher level (ex. untrusted multi-function
2295 * PCI devices). Thus we attach each device.
2297 static int iommu_group_do_attach_device(struct device *dev, void *data)
2299 struct iommu_domain *domain = data;
2301 return __iommu_attach_device(domain, dev);
2304 static int __iommu_attach_group(struct iommu_domain *domain,
2305 struct iommu_group *group)
2309 if (group->default_domain && group->domain != group->default_domain)
2312 ret = __iommu_group_for_each_dev(group, domain,
2313 iommu_group_do_attach_device);
2315 group->domain = domain;
2320 int iommu_attach_group(struct iommu_domain *domain, struct iommu_group *group)
2324 mutex_lock(&group->mutex);
2325 ret = __iommu_attach_group(domain, group);
2326 mutex_unlock(&group->mutex);
2330 EXPORT_SYMBOL_GPL(iommu_attach_group);
2332 static int iommu_group_do_detach_device(struct device *dev, void *data)
2334 struct iommu_domain *domain = data;
2336 __iommu_detach_device(domain, dev);
2341 static void __iommu_detach_group(struct iommu_domain *domain,
2342 struct iommu_group *group)
2346 if (!group->default_domain) {
2347 __iommu_group_for_each_dev(group, domain,
2348 iommu_group_do_detach_device);
2349 group->domain = NULL;
2353 if (group->domain == group->default_domain)
2356 /* Detach by re-attaching to the default domain */
2357 ret = __iommu_group_for_each_dev(group, group->default_domain,
2358 iommu_group_do_attach_device);
2362 group->domain = group->default_domain;
2365 void iommu_detach_group(struct iommu_domain *domain, struct iommu_group *group)
2367 mutex_lock(&group->mutex);
2368 __iommu_detach_group(domain, group);
2369 mutex_unlock(&group->mutex);
2371 EXPORT_SYMBOL_GPL(iommu_detach_group);
2373 phys_addr_t iommu_iova_to_phys(struct iommu_domain *domain, dma_addr_t iova)
2375 if (unlikely(domain->ops->iova_to_phys == NULL))
2378 return domain->ops->iova_to_phys(domain, iova);
2380 EXPORT_SYMBOL_GPL(iommu_iova_to_phys);
2382 static size_t iommu_pgsize(struct iommu_domain *domain, unsigned long iova,
2383 phys_addr_t paddr, size_t size, size_t *count)
2385 unsigned int pgsize_idx, pgsize_idx_next;
2386 unsigned long pgsizes;
2387 size_t offset, pgsize, pgsize_next;
2388 unsigned long addr_merge = paddr | iova;
2390 /* Page sizes supported by the hardware and small enough for @size */
2391 pgsizes = domain->pgsize_bitmap & GENMASK(__fls(size), 0);
2393 /* Constrain the page sizes further based on the maximum alignment */
2394 if (likely(addr_merge))
2395 pgsizes &= GENMASK(__ffs(addr_merge), 0);
2397 /* Make sure we have at least one suitable page size */
2400 /* Pick the biggest page size remaining */
2401 pgsize_idx = __fls(pgsizes);
2402 pgsize = BIT(pgsize_idx);
2406 /* Find the next biggest support page size, if it exists */
2407 pgsizes = domain->pgsize_bitmap & ~GENMASK(pgsize_idx, 0);
2411 pgsize_idx_next = __ffs(pgsizes);
2412 pgsize_next = BIT(pgsize_idx_next);
2415 * There's no point trying a bigger page size unless the virtual
2416 * and physical addresses are similarly offset within the larger page.
2418 if ((iova ^ paddr) & (pgsize_next - 1))
2421 /* Calculate the offset to the next page size alignment boundary */
2422 offset = pgsize_next - (addr_merge & (pgsize_next - 1));
2425 * If size is big enough to accommodate the larger page, reduce
2426 * the number of smaller pages.
2428 if (offset + pgsize_next <= size)
2432 *count = size >> pgsize_idx;
2436 static int __iommu_map_pages(struct iommu_domain *domain, unsigned long iova,
2437 phys_addr_t paddr, size_t size, int prot,
2438 gfp_t gfp, size_t *mapped)
2440 const struct iommu_ops *ops = domain->ops;
2441 size_t pgsize, count;
2444 pgsize = iommu_pgsize(domain, iova, paddr, size, &count);
2446 pr_debug("mapping: iova 0x%lx pa %pa pgsize 0x%zx count %zu\n",
2447 iova, &paddr, pgsize, count);
2449 if (ops->map_pages) {
2450 ret = ops->map_pages(domain, iova, paddr, pgsize, count, prot,
2453 ret = ops->map(domain, iova, paddr, pgsize, prot, gfp);
2454 *mapped = ret ? 0 : pgsize;
2460 static int __iommu_map(struct iommu_domain *domain, unsigned long iova,
2461 phys_addr_t paddr, size_t size, int prot, gfp_t gfp)
2463 const struct iommu_ops *ops = domain->ops;
2464 unsigned long orig_iova = iova;
2465 unsigned int min_pagesz;
2466 size_t orig_size = size;
2467 phys_addr_t orig_paddr = paddr;
2470 if (unlikely(!(ops->map || ops->map_pages) ||
2471 domain->pgsize_bitmap == 0UL))
2474 if (unlikely(!(domain->type & __IOMMU_DOMAIN_PAGING)))
2477 /* find out the minimum page size supported */
2478 min_pagesz = 1 << __ffs(domain->pgsize_bitmap);
2481 * both the virtual address and the physical one, as well as
2482 * the size of the mapping, must be aligned (at least) to the
2483 * size of the smallest page supported by the hardware
2485 if (!IS_ALIGNED(iova | paddr | size, min_pagesz)) {
2486 pr_err("unaligned: iova 0x%lx pa %pa size 0x%zx min_pagesz 0x%x\n",
2487 iova, &paddr, size, min_pagesz);
2491 pr_debug("map: iova 0x%lx pa %pa size 0x%zx\n", iova, &paddr, size);
2496 ret = __iommu_map_pages(domain, iova, paddr, size, prot, gfp,
2499 * Some pages may have been mapped, even if an error occurred,
2500 * so we should account for those so they can be unmapped.
2511 /* unroll mapping in case something went wrong */
2513 iommu_unmap(domain, orig_iova, orig_size - size);
2515 trace_map(orig_iova, orig_paddr, orig_size);
2520 static int _iommu_map(struct iommu_domain *domain, unsigned long iova,
2521 phys_addr_t paddr, size_t size, int prot, gfp_t gfp)
2523 const struct iommu_ops *ops = domain->ops;
2526 ret = __iommu_map(domain, iova, paddr, size, prot, gfp);
2527 if (ret == 0 && ops->iotlb_sync_map)
2528 ops->iotlb_sync_map(domain, iova, size);
2533 int iommu_map(struct iommu_domain *domain, unsigned long iova,
2534 phys_addr_t paddr, size_t size, int prot)
2537 return _iommu_map(domain, iova, paddr, size, prot, GFP_KERNEL);
2539 EXPORT_SYMBOL_GPL(iommu_map);
2541 int iommu_map_atomic(struct iommu_domain *domain, unsigned long iova,
2542 phys_addr_t paddr, size_t size, int prot)
2544 return _iommu_map(domain, iova, paddr, size, prot, GFP_ATOMIC);
2546 EXPORT_SYMBOL_GPL(iommu_map_atomic);
2548 static size_t __iommu_unmap_pages(struct iommu_domain *domain,
2549 unsigned long iova, size_t size,
2550 struct iommu_iotlb_gather *iotlb_gather)
2552 const struct iommu_ops *ops = domain->ops;
2553 size_t pgsize, count;
2555 pgsize = iommu_pgsize(domain, iova, iova, size, &count);
2556 return ops->unmap_pages ?
2557 ops->unmap_pages(domain, iova, pgsize, count, iotlb_gather) :
2558 ops->unmap(domain, iova, pgsize, iotlb_gather);
2561 static size_t __iommu_unmap(struct iommu_domain *domain,
2562 unsigned long iova, size_t size,
2563 struct iommu_iotlb_gather *iotlb_gather)
2565 const struct iommu_ops *ops = domain->ops;
2566 size_t unmapped_page, unmapped = 0;
2567 unsigned long orig_iova = iova;
2568 unsigned int min_pagesz;
2570 if (unlikely(!(ops->unmap || ops->unmap_pages) ||
2571 domain->pgsize_bitmap == 0UL))
2574 if (unlikely(!(domain->type & __IOMMU_DOMAIN_PAGING)))
2577 /* find out the minimum page size supported */
2578 min_pagesz = 1 << __ffs(domain->pgsize_bitmap);
2581 * The virtual address, as well as the size of the mapping, must be
2582 * aligned (at least) to the size of the smallest page supported
2585 if (!IS_ALIGNED(iova | size, min_pagesz)) {
2586 pr_err("unaligned: iova 0x%lx size 0x%zx min_pagesz 0x%x\n",
2587 iova, size, min_pagesz);
2591 pr_debug("unmap this: iova 0x%lx size 0x%zx\n", iova, size);
2594 * Keep iterating until we either unmap 'size' bytes (or more)
2595 * or we hit an area that isn't mapped.
2597 while (unmapped < size) {
2598 unmapped_page = __iommu_unmap_pages(domain, iova,
2604 pr_debug("unmapped: iova 0x%lx size 0x%zx\n",
2605 iova, unmapped_page);
2607 iova += unmapped_page;
2608 unmapped += unmapped_page;
2611 trace_unmap(orig_iova, size, unmapped);
2615 size_t iommu_unmap(struct iommu_domain *domain,
2616 unsigned long iova, size_t size)
2618 struct iommu_iotlb_gather iotlb_gather;
2621 iommu_iotlb_gather_init(&iotlb_gather);
2622 ret = __iommu_unmap(domain, iova, size, &iotlb_gather);
2623 iommu_iotlb_sync(domain, &iotlb_gather);
2627 EXPORT_SYMBOL_GPL(iommu_unmap);
2629 size_t iommu_unmap_fast(struct iommu_domain *domain,
2630 unsigned long iova, size_t size,
2631 struct iommu_iotlb_gather *iotlb_gather)
2633 return __iommu_unmap(domain, iova, size, iotlb_gather);
2635 EXPORT_SYMBOL_GPL(iommu_unmap_fast);
2637 static size_t __iommu_map_sg(struct iommu_domain *domain, unsigned long iova,
2638 struct scatterlist *sg, unsigned int nents, int prot,
2641 const struct iommu_ops *ops = domain->ops;
2642 size_t len = 0, mapped = 0;
2647 while (i <= nents) {
2648 phys_addr_t s_phys = sg_phys(sg);
2650 if (len && s_phys != start + len) {
2651 ret = __iommu_map(domain, iova + mapped, start,
2672 if (ops->iotlb_sync_map)
2673 ops->iotlb_sync_map(domain, iova, mapped);
2677 /* undo mappings already done */
2678 iommu_unmap(domain, iova, mapped);
2684 size_t iommu_map_sg(struct iommu_domain *domain, unsigned long iova,
2685 struct scatterlist *sg, unsigned int nents, int prot)
2688 return __iommu_map_sg(domain, iova, sg, nents, prot, GFP_KERNEL);
2690 EXPORT_SYMBOL_GPL(iommu_map_sg);
2692 size_t iommu_map_sg_atomic(struct iommu_domain *domain, unsigned long iova,
2693 struct scatterlist *sg, unsigned int nents, int prot)
2695 return __iommu_map_sg(domain, iova, sg, nents, prot, GFP_ATOMIC);
2699 * report_iommu_fault() - report about an IOMMU fault to the IOMMU framework
2700 * @domain: the iommu domain where the fault has happened
2701 * @dev: the device where the fault has happened
2702 * @iova: the faulting address
2703 * @flags: mmu fault flags (e.g. IOMMU_FAULT_READ/IOMMU_FAULT_WRITE/...)
2705 * This function should be called by the low-level IOMMU implementations
2706 * whenever IOMMU faults happen, to allow high-level users, that are
2707 * interested in such events, to know about them.
2709 * This event may be useful for several possible use cases:
2710 * - mere logging of the event
2711 * - dynamic TLB/PTE loading
2712 * - if restarting of the faulting device is required
2714 * Returns 0 on success and an appropriate error code otherwise (if dynamic
2715 * PTE/TLB loading will one day be supported, implementations will be able
2716 * to tell whether it succeeded or not according to this return value).
2718 * Specifically, -ENOSYS is returned if a fault handler isn't installed
2719 * (though fault handlers can also return -ENOSYS, in case they want to
2720 * elicit the default behavior of the IOMMU drivers).
2722 int report_iommu_fault(struct iommu_domain *domain, struct device *dev,
2723 unsigned long iova, int flags)
2728 * if upper layers showed interest and installed a fault handler,
2731 if (domain->handler)
2732 ret = domain->handler(domain, dev, iova, flags,
2733 domain->handler_token);
2735 trace_io_page_fault(dev, iova, flags);
2738 EXPORT_SYMBOL_GPL(report_iommu_fault);
2740 static int __init iommu_init(void)
2742 iommu_group_kset = kset_create_and_add("iommu_groups",
2744 BUG_ON(!iommu_group_kset);
2746 iommu_debugfs_setup();
2750 core_initcall(iommu_init);
2752 int iommu_enable_nesting(struct iommu_domain *domain)
2754 if (domain->type != IOMMU_DOMAIN_UNMANAGED)
2756 if (!domain->ops->enable_nesting)
2758 return domain->ops->enable_nesting(domain);
2760 EXPORT_SYMBOL_GPL(iommu_enable_nesting);
2762 int iommu_set_pgtable_quirks(struct iommu_domain *domain,
2763 unsigned long quirk)
2765 if (domain->type != IOMMU_DOMAIN_UNMANAGED)
2767 if (!domain->ops->set_pgtable_quirks)
2769 return domain->ops->set_pgtable_quirks(domain, quirk);
2771 EXPORT_SYMBOL_GPL(iommu_set_pgtable_quirks);
2773 void iommu_get_resv_regions(struct device *dev, struct list_head *list)
2775 const struct iommu_ops *ops = dev->bus->iommu_ops;
2777 if (ops && ops->get_resv_regions)
2778 ops->get_resv_regions(dev, list);
2781 void iommu_put_resv_regions(struct device *dev, struct list_head *list)
2783 const struct iommu_ops *ops = dev->bus->iommu_ops;
2785 if (ops && ops->put_resv_regions)
2786 ops->put_resv_regions(dev, list);
2790 * generic_iommu_put_resv_regions - Reserved region driver helper
2791 * @dev: device for which to free reserved regions
2792 * @list: reserved region list for device
2794 * IOMMU drivers can use this to implement their .put_resv_regions() callback
2795 * for simple reservations. Memory allocated for each reserved region will be
2796 * freed. If an IOMMU driver allocates additional resources per region, it is
2797 * going to have to implement a custom callback.
2799 void generic_iommu_put_resv_regions(struct device *dev, struct list_head *list)
2801 struct iommu_resv_region *entry, *next;
2803 list_for_each_entry_safe(entry, next, list, list)
2806 EXPORT_SYMBOL(generic_iommu_put_resv_regions);
2808 struct iommu_resv_region *iommu_alloc_resv_region(phys_addr_t start,
2809 size_t length, int prot,
2810 enum iommu_resv_type type)
2812 struct iommu_resv_region *region;
2814 region = kzalloc(sizeof(*region), GFP_KERNEL);
2818 INIT_LIST_HEAD(®ion->list);
2819 region->start = start;
2820 region->length = length;
2821 region->prot = prot;
2822 region->type = type;
2825 EXPORT_SYMBOL_GPL(iommu_alloc_resv_region);
2827 void iommu_set_default_passthrough(bool cmd_line)
2830 iommu_cmd_line |= IOMMU_CMD_LINE_DMA_API;
2831 iommu_def_domain_type = IOMMU_DOMAIN_IDENTITY;
2834 void iommu_set_default_translated(bool cmd_line)
2837 iommu_cmd_line |= IOMMU_CMD_LINE_DMA_API;
2838 iommu_def_domain_type = IOMMU_DOMAIN_DMA;
2841 bool iommu_default_passthrough(void)
2843 return iommu_def_domain_type == IOMMU_DOMAIN_IDENTITY;
2845 EXPORT_SYMBOL_GPL(iommu_default_passthrough);
2847 const struct iommu_ops *iommu_ops_from_fwnode(struct fwnode_handle *fwnode)
2849 const struct iommu_ops *ops = NULL;
2850 struct iommu_device *iommu;
2852 spin_lock(&iommu_device_lock);
2853 list_for_each_entry(iommu, &iommu_device_list, list)
2854 if (iommu->fwnode == fwnode) {
2858 spin_unlock(&iommu_device_lock);
2862 int iommu_fwspec_init(struct device *dev, struct fwnode_handle *iommu_fwnode,
2863 const struct iommu_ops *ops)
2865 struct iommu_fwspec *fwspec = dev_iommu_fwspec_get(dev);
2868 return ops == fwspec->ops ? 0 : -EINVAL;
2870 if (!dev_iommu_get(dev))
2873 /* Preallocate for the overwhelmingly common case of 1 ID */
2874 fwspec = kzalloc(struct_size(fwspec, ids, 1), GFP_KERNEL);
2878 of_node_get(to_of_node(iommu_fwnode));
2879 fwspec->iommu_fwnode = iommu_fwnode;
2881 dev_iommu_fwspec_set(dev, fwspec);
2884 EXPORT_SYMBOL_GPL(iommu_fwspec_init);
2886 void iommu_fwspec_free(struct device *dev)
2888 struct iommu_fwspec *fwspec = dev_iommu_fwspec_get(dev);
2891 fwnode_handle_put(fwspec->iommu_fwnode);
2893 dev_iommu_fwspec_set(dev, NULL);
2896 EXPORT_SYMBOL_GPL(iommu_fwspec_free);
2898 int iommu_fwspec_add_ids(struct device *dev, u32 *ids, int num_ids)
2900 struct iommu_fwspec *fwspec = dev_iommu_fwspec_get(dev);
2906 new_num = fwspec->num_ids + num_ids;
2908 fwspec = krealloc(fwspec, struct_size(fwspec, ids, new_num),
2913 dev_iommu_fwspec_set(dev, fwspec);
2916 for (i = 0; i < num_ids; i++)
2917 fwspec->ids[fwspec->num_ids + i] = ids[i];
2919 fwspec->num_ids = new_num;
2922 EXPORT_SYMBOL_GPL(iommu_fwspec_add_ids);
2925 * Per device IOMMU features.
2927 int iommu_dev_enable_feature(struct device *dev, enum iommu_dev_features feat)
2929 if (dev->iommu && dev->iommu->iommu_dev) {
2930 const struct iommu_ops *ops = dev->iommu->iommu_dev->ops;
2932 if (ops->dev_enable_feat)
2933 return ops->dev_enable_feat(dev, feat);
2938 EXPORT_SYMBOL_GPL(iommu_dev_enable_feature);
2941 * The device drivers should do the necessary cleanups before calling this.
2942 * For example, before disabling the aux-domain feature, the device driver
2943 * should detach all aux-domains. Otherwise, this will return -EBUSY.
2945 int iommu_dev_disable_feature(struct device *dev, enum iommu_dev_features feat)
2947 if (dev->iommu && dev->iommu->iommu_dev) {
2948 const struct iommu_ops *ops = dev->iommu->iommu_dev->ops;
2950 if (ops->dev_disable_feat)
2951 return ops->dev_disable_feat(dev, feat);
2956 EXPORT_SYMBOL_GPL(iommu_dev_disable_feature);
2958 bool iommu_dev_feature_enabled(struct device *dev, enum iommu_dev_features feat)
2960 if (dev->iommu && dev->iommu->iommu_dev) {
2961 const struct iommu_ops *ops = dev->iommu->iommu_dev->ops;
2963 if (ops->dev_feat_enabled)
2964 return ops->dev_feat_enabled(dev, feat);
2969 EXPORT_SYMBOL_GPL(iommu_dev_feature_enabled);
2972 * Aux-domain specific attach/detach.
2974 * Only works if iommu_dev_feature_enabled(dev, IOMMU_DEV_FEAT_AUX) returns
2975 * true. Also, as long as domains are attached to a device through this
2976 * interface, any tries to call iommu_attach_device() should fail
2977 * (iommu_detach_device() can't fail, so we fail when trying to re-attach).
2978 * This should make us safe against a device being attached to a guest as a
2979 * whole while there are still pasid users on it (aux and sva).
2981 int iommu_aux_attach_device(struct iommu_domain *domain, struct device *dev)
2985 if (domain->ops->aux_attach_dev)
2986 ret = domain->ops->aux_attach_dev(domain, dev);
2989 trace_attach_device_to_domain(dev);
2993 EXPORT_SYMBOL_GPL(iommu_aux_attach_device);
2995 void iommu_aux_detach_device(struct iommu_domain *domain, struct device *dev)
2997 if (domain->ops->aux_detach_dev) {
2998 domain->ops->aux_detach_dev(domain, dev);
2999 trace_detach_device_from_domain(dev);
3002 EXPORT_SYMBOL_GPL(iommu_aux_detach_device);
3004 int iommu_aux_get_pasid(struct iommu_domain *domain, struct device *dev)
3008 if (domain->ops->aux_get_pasid)
3009 ret = domain->ops->aux_get_pasid(domain, dev);
3013 EXPORT_SYMBOL_GPL(iommu_aux_get_pasid);
3016 * iommu_sva_bind_device() - Bind a process address space to a device
3018 * @mm: the mm to bind, caller must hold a reference to it
3020 * Create a bond between device and address space, allowing the device to access
3021 * the mm using the returned PASID. If a bond already exists between @device and
3022 * @mm, it is returned and an additional reference is taken. Caller must call
3023 * iommu_sva_unbind_device() to release each reference.
3025 * iommu_dev_enable_feature(dev, IOMMU_DEV_FEAT_SVA) must be called first, to
3026 * initialize the required SVA features.
3028 * On error, returns an ERR_PTR value.
3031 iommu_sva_bind_device(struct device *dev, struct mm_struct *mm, void *drvdata)
3033 struct iommu_group *group;
3034 struct iommu_sva *handle = ERR_PTR(-EINVAL);
3035 const struct iommu_ops *ops = dev->bus->iommu_ops;
3037 if (!ops || !ops->sva_bind)
3038 return ERR_PTR(-ENODEV);
3040 group = iommu_group_get(dev);
3042 return ERR_PTR(-ENODEV);
3044 /* Ensure device count and domain don't change while we're binding */
3045 mutex_lock(&group->mutex);
3048 * To keep things simple, SVA currently doesn't support IOMMU groups
3049 * with more than one device. Existing SVA-capable systems are not
3050 * affected by the problems that required IOMMU groups (lack of ACS
3051 * isolation, device ID aliasing and other hardware issues).
3053 if (iommu_group_device_count(group) != 1)
3056 handle = ops->sva_bind(dev, mm, drvdata);
3059 mutex_unlock(&group->mutex);
3060 iommu_group_put(group);
3064 EXPORT_SYMBOL_GPL(iommu_sva_bind_device);
3067 * iommu_sva_unbind_device() - Remove a bond created with iommu_sva_bind_device
3068 * @handle: the handle returned by iommu_sva_bind_device()
3070 * Put reference to a bond between device and address space. The device should
3071 * not be issuing any more transaction for this PASID. All outstanding page
3072 * requests for this PASID must have been flushed to the IOMMU.
3074 void iommu_sva_unbind_device(struct iommu_sva *handle)
3076 struct iommu_group *group;
3077 struct device *dev = handle->dev;
3078 const struct iommu_ops *ops = dev->bus->iommu_ops;
3080 if (!ops || !ops->sva_unbind)
3083 group = iommu_group_get(dev);
3087 mutex_lock(&group->mutex);
3088 ops->sva_unbind(handle);
3089 mutex_unlock(&group->mutex);
3091 iommu_group_put(group);
3093 EXPORT_SYMBOL_GPL(iommu_sva_unbind_device);
3095 u32 iommu_sva_get_pasid(struct iommu_sva *handle)
3097 const struct iommu_ops *ops = handle->dev->bus->iommu_ops;
3099 if (!ops || !ops->sva_get_pasid)
3100 return IOMMU_PASID_INVALID;
3102 return ops->sva_get_pasid(handle);
3104 EXPORT_SYMBOL_GPL(iommu_sva_get_pasid);
3107 * Changes the default domain of an iommu group that has *only* one device
3109 * @group: The group for which the default domain should be changed
3110 * @prev_dev: The device in the group (this is used to make sure that the device
3111 * hasn't changed after the caller has called this function)
3112 * @type: The type of the new default domain that gets associated with the group
3114 * Returns 0 on success and error code on failure
3117 * 1. Presently, this function is called only when user requests to change the
3118 * group's default domain type through /sys/kernel/iommu_groups/<grp_id>/type
3119 * Please take a closer look if intended to use for other purposes.
3121 static int iommu_change_dev_def_domain(struct iommu_group *group,
3122 struct device *prev_dev, int type)
3124 struct iommu_domain *prev_dom;
3125 struct group_device *grp_dev;
3126 int ret, dev_def_dom;
3129 mutex_lock(&group->mutex);
3131 if (group->default_domain != group->domain) {
3132 dev_err_ratelimited(prev_dev, "Group not assigned to default domain\n");
3138 * iommu group wasn't locked while acquiring device lock in
3139 * iommu_group_store_type(). So, make sure that the device count hasn't
3140 * changed while acquiring device lock.
3142 * Changing default domain of an iommu group with two or more devices
3143 * isn't supported because there could be a potential deadlock. Consider
3144 * the following scenario. T1 is trying to acquire device locks of all
3145 * the devices in the group and before it could acquire all of them,
3146 * there could be another thread T2 (from different sub-system and use
3147 * case) that has already acquired some of the device locks and might be
3148 * waiting for T1 to release other device locks.
3150 if (iommu_group_device_count(group) != 1) {
3151 dev_err_ratelimited(prev_dev, "Cannot change default domain: Group has more than one device\n");
3156 /* Since group has only one device */
3157 grp_dev = list_first_entry(&group->devices, struct group_device, list);
3160 if (prev_dev != dev) {
3161 dev_err_ratelimited(prev_dev, "Cannot change default domain: Device has been changed\n");
3166 prev_dom = group->default_domain;
3172 dev_def_dom = iommu_get_def_domain_type(dev);
3175 * If the user hasn't requested any specific type of domain and
3176 * if the device supports both the domains, then default to the
3177 * domain the device was booted with
3179 type = dev_def_dom ? : iommu_def_domain_type;
3180 } else if (dev_def_dom && type != dev_def_dom) {
3181 dev_err_ratelimited(prev_dev, "Device cannot be in %s domain\n",
3182 iommu_domain_type_str(type));
3188 * Switch to a new domain only if the requested domain type is different
3189 * from the existing default domain type
3191 if (prev_dom->type == type) {
3196 /* Sets group->default_domain to the newly allocated domain */
3197 ret = iommu_group_alloc_default_domain(dev->bus, group, type);
3201 ret = iommu_create_device_direct_mappings(group, dev);
3203 goto free_new_domain;
3205 ret = __iommu_attach_device(group->default_domain, dev);
3207 goto free_new_domain;
3209 group->domain = group->default_domain;
3212 * Release the mutex here because ops->probe_finalize() call-back of
3213 * some vendor IOMMU drivers calls arm_iommu_attach_device() which
3214 * in-turn might call back into IOMMU core code, where it tries to take
3215 * group->mutex, resulting in a deadlock.
3217 mutex_unlock(&group->mutex);
3219 /* Make sure dma_ops is appropriatley set */
3220 iommu_group_do_probe_finalize(dev, group->default_domain);
3221 iommu_domain_free(prev_dom);
3225 iommu_domain_free(group->default_domain);
3226 group->default_domain = prev_dom;
3227 group->domain = prev_dom;
3230 mutex_unlock(&group->mutex);
3236 * Changing the default domain through sysfs requires the users to ubind the
3237 * drivers from the devices in the iommu group. Return failure if this doesn't
3240 * We need to consider the race between this and the device release path.
3241 * device_lock(dev) is used here to guarantee that the device release path
3242 * will not be entered at the same time.
3244 static ssize_t iommu_group_store_type(struct iommu_group *group,
3245 const char *buf, size_t count)
3247 struct group_device *grp_dev;
3251 if (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO))
3254 if (WARN_ON(!group))
3257 if (sysfs_streq(buf, "identity"))
3258 req_type = IOMMU_DOMAIN_IDENTITY;
3259 else if (sysfs_streq(buf, "DMA"))
3260 req_type = IOMMU_DOMAIN_DMA;
3261 else if (sysfs_streq(buf, "auto"))
3267 * Lock/Unlock the group mutex here before device lock to
3268 * 1. Make sure that the iommu group has only one device (this is a
3269 * prerequisite for step 2)
3270 * 2. Get struct *dev which is needed to lock device
3272 mutex_lock(&group->mutex);
3273 if (iommu_group_device_count(group) != 1) {
3274 mutex_unlock(&group->mutex);
3275 pr_err_ratelimited("Cannot change default domain: Group has more than one device\n");
3279 /* Since group has only one device */
3280 grp_dev = list_first_entry(&group->devices, struct group_device, list);
3285 * Don't hold the group mutex because taking group mutex first and then
3286 * the device lock could potentially cause a deadlock as below. Assume
3287 * two threads T1 and T2. T1 is trying to change default domain of an
3288 * iommu group and T2 is trying to hot unplug a device or release [1] VF
3289 * of a PCIe device which is in the same iommu group. T1 takes group
3290 * mutex and before it could take device lock assume T2 has taken device
3291 * lock and is yet to take group mutex. Now, both the threads will be
3292 * waiting for the other thread to release lock. Below, lock order was
3295 * mutex_lock(&group->mutex);
3296 * iommu_change_dev_def_domain();
3297 * mutex_unlock(&group->mutex);
3298 * device_unlock(dev);
3300 * [1] Typical device release path
3301 * device_lock() from device/driver core code
3303 * -> iommu_bus_notifier()
3304 * -> iommu_release_device()
3305 * -> ops->release_device() vendor driver calls back iommu core code
3306 * -> mutex_lock() from iommu core code
3308 mutex_unlock(&group->mutex);
3310 /* Check if the device in the group still has a driver bound to it */
3312 if (device_is_bound(dev)) {
3313 pr_err_ratelimited("Device is still bound to driver\n");
3318 ret = iommu_change_dev_def_domain(group, dev, req_type);