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/amba/bus.h>
10 #include <linux/device.h>
11 #include <linux/kernel.h>
12 #include <linux/bits.h>
13 #include <linux/bug.h>
14 #include <linux/types.h>
15 #include <linux/init.h>
16 #include <linux/export.h>
17 #include <linux/slab.h>
18 #include <linux/errno.h>
19 #include <linux/host1x_context_bus.h>
20 #include <linux/iommu.h>
21 #include <linux/idr.h>
22 #include <linux/err.h>
23 #include <linux/pci.h>
24 #include <linux/pci-ats.h>
25 #include <linux/bitops.h>
26 #include <linux/platform_device.h>
27 #include <linux/property.h>
28 #include <linux/fsl/mc.h>
29 #include <linux/module.h>
30 #include <linux/cc_platform.h>
31 #include <trace/events/iommu.h>
32 #include <linux/sched/mm.h>
33 #include <linux/msi.h>
35 #include "dma-iommu.h"
37 #include "iommu-sva.h"
39 static struct kset *iommu_group_kset;
40 static DEFINE_IDA(iommu_group_ida);
42 static unsigned int iommu_def_domain_type __read_mostly;
43 static bool iommu_dma_strict __read_mostly = IS_ENABLED(CONFIG_IOMMU_DEFAULT_DMA_STRICT);
44 static u32 iommu_cmd_line __read_mostly;
48 struct kobject *devices_kobj;
49 struct list_head devices;
50 struct xarray pasid_array;
53 void (*iommu_data_release)(void *iommu_data);
56 struct iommu_domain *default_domain;
57 struct iommu_domain *blocking_domain;
58 struct iommu_domain *domain;
59 struct list_head entry;
60 unsigned int owner_cnt;
65 struct list_head list;
70 struct iommu_group_attribute {
71 struct attribute attr;
72 ssize_t (*show)(struct iommu_group *group, char *buf);
73 ssize_t (*store)(struct iommu_group *group,
74 const char *buf, size_t count);
77 static const char * const iommu_group_resv_type_string[] = {
78 [IOMMU_RESV_DIRECT] = "direct",
79 [IOMMU_RESV_DIRECT_RELAXABLE] = "direct-relaxable",
80 [IOMMU_RESV_RESERVED] = "reserved",
81 [IOMMU_RESV_MSI] = "msi",
82 [IOMMU_RESV_SW_MSI] = "msi",
85 #define IOMMU_CMD_LINE_DMA_API BIT(0)
86 #define IOMMU_CMD_LINE_STRICT BIT(1)
88 static int iommu_bus_notifier(struct notifier_block *nb,
89 unsigned long action, void *data);
90 static int iommu_alloc_default_domain(struct iommu_group *group,
92 static struct iommu_domain *__iommu_domain_alloc(struct bus_type *bus,
94 static int __iommu_attach_device(struct iommu_domain *domain,
96 static int __iommu_attach_group(struct iommu_domain *domain,
97 struct iommu_group *group);
98 static int __iommu_group_set_domain(struct iommu_group *group,
99 struct iommu_domain *new_domain);
100 static int iommu_create_device_direct_mappings(struct iommu_group *group,
102 static struct iommu_group *iommu_group_get_for_dev(struct device *dev);
103 static ssize_t iommu_group_store_type(struct iommu_group *group,
104 const char *buf, size_t count);
106 #define IOMMU_GROUP_ATTR(_name, _mode, _show, _store) \
107 struct iommu_group_attribute iommu_group_attr_##_name = \
108 __ATTR(_name, _mode, _show, _store)
110 #define to_iommu_group_attr(_attr) \
111 container_of(_attr, struct iommu_group_attribute, attr)
112 #define to_iommu_group(_kobj) \
113 container_of(_kobj, struct iommu_group, kobj)
115 static LIST_HEAD(iommu_device_list);
116 static DEFINE_SPINLOCK(iommu_device_lock);
118 static struct bus_type * const iommu_buses[] = {
123 #ifdef CONFIG_ARM_AMBA
126 #ifdef CONFIG_FSL_MC_BUS
129 #ifdef CONFIG_TEGRA_HOST1X_CONTEXT_BUS
130 &host1x_context_device_bus_type,
135 * Use a function instead of an array here because the domain-type is a
136 * bit-field, so an array would waste memory.
138 static const char *iommu_domain_type_str(unsigned int t)
141 case IOMMU_DOMAIN_BLOCKED:
143 case IOMMU_DOMAIN_IDENTITY:
144 return "Passthrough";
145 case IOMMU_DOMAIN_UNMANAGED:
147 case IOMMU_DOMAIN_DMA:
148 case IOMMU_DOMAIN_DMA_FQ:
155 static int __init iommu_subsys_init(void)
157 struct notifier_block *nb;
159 if (!(iommu_cmd_line & IOMMU_CMD_LINE_DMA_API)) {
160 if (IS_ENABLED(CONFIG_IOMMU_DEFAULT_PASSTHROUGH))
161 iommu_set_default_passthrough(false);
163 iommu_set_default_translated(false);
165 if (iommu_default_passthrough() && cc_platform_has(CC_ATTR_MEM_ENCRYPT)) {
166 pr_info("Memory encryption detected - Disabling default IOMMU Passthrough\n");
167 iommu_set_default_translated(false);
171 if (!iommu_default_passthrough() && !iommu_dma_strict)
172 iommu_def_domain_type = IOMMU_DOMAIN_DMA_FQ;
174 pr_info("Default domain type: %s %s\n",
175 iommu_domain_type_str(iommu_def_domain_type),
176 (iommu_cmd_line & IOMMU_CMD_LINE_DMA_API) ?
177 "(set via kernel command line)" : "");
179 if (!iommu_default_passthrough())
180 pr_info("DMA domain TLB invalidation policy: %s mode %s\n",
181 iommu_dma_strict ? "strict" : "lazy",
182 (iommu_cmd_line & IOMMU_CMD_LINE_STRICT) ?
183 "(set via kernel command line)" : "");
185 nb = kcalloc(ARRAY_SIZE(iommu_buses), sizeof(*nb), GFP_KERNEL);
189 for (int i = 0; i < ARRAY_SIZE(iommu_buses); i++) {
190 nb[i].notifier_call = iommu_bus_notifier;
191 bus_register_notifier(iommu_buses[i], &nb[i]);
196 subsys_initcall(iommu_subsys_init);
198 static int remove_iommu_group(struct device *dev, void *data)
200 if (dev->iommu && dev->iommu->iommu_dev == data)
201 iommu_release_device(dev);
207 * iommu_device_register() - Register an IOMMU hardware instance
208 * @iommu: IOMMU handle for the instance
209 * @ops: IOMMU ops to associate with the instance
210 * @hwdev: (optional) actual instance device, used for fwnode lookup
212 * Return: 0 on success, or an error.
214 int iommu_device_register(struct iommu_device *iommu,
215 const struct iommu_ops *ops, struct device *hwdev)
219 /* We need to be able to take module references appropriately */
220 if (WARN_ON(is_module_address((unsigned long)ops) && !ops->owner))
223 * Temporarily enforce global restriction to a single driver. This was
224 * already the de-facto behaviour, since any possible combination of
225 * existing drivers would compete for at least the PCI or platform bus.
227 if (iommu_buses[0]->iommu_ops && iommu_buses[0]->iommu_ops != ops)
232 iommu->fwnode = dev_fwnode(hwdev);
234 spin_lock(&iommu_device_lock);
235 list_add_tail(&iommu->list, &iommu_device_list);
236 spin_unlock(&iommu_device_lock);
238 for (int i = 0; i < ARRAY_SIZE(iommu_buses) && !err; i++) {
239 iommu_buses[i]->iommu_ops = ops;
240 err = bus_iommu_probe(iommu_buses[i]);
243 iommu_device_unregister(iommu);
246 EXPORT_SYMBOL_GPL(iommu_device_register);
248 void iommu_device_unregister(struct iommu_device *iommu)
250 for (int i = 0; i < ARRAY_SIZE(iommu_buses); i++)
251 bus_for_each_dev(iommu_buses[i], NULL, iommu, remove_iommu_group);
253 spin_lock(&iommu_device_lock);
254 list_del(&iommu->list);
255 spin_unlock(&iommu_device_lock);
257 EXPORT_SYMBOL_GPL(iommu_device_unregister);
259 static struct dev_iommu *dev_iommu_get(struct device *dev)
261 struct dev_iommu *param = dev->iommu;
266 param = kzalloc(sizeof(*param), GFP_KERNEL);
270 mutex_init(¶m->lock);
275 static void dev_iommu_free(struct device *dev)
277 struct dev_iommu *param = dev->iommu;
281 fwnode_handle_put(param->fwspec->iommu_fwnode);
282 kfree(param->fwspec);
287 static u32 dev_iommu_get_max_pasids(struct device *dev)
289 u32 max_pasids = 0, bits = 0;
292 if (dev_is_pci(dev)) {
293 ret = pci_max_pasids(to_pci_dev(dev));
297 ret = device_property_read_u32(dev, "pasid-num-bits", &bits);
299 max_pasids = 1UL << bits;
302 return min_t(u32, max_pasids, dev->iommu->iommu_dev->max_pasids);
305 static int __iommu_probe_device(struct device *dev, struct list_head *group_list)
307 const struct iommu_ops *ops = dev->bus->iommu_ops;
308 struct iommu_device *iommu_dev;
309 struct iommu_group *group;
310 static DEFINE_MUTEX(iommu_probe_device_lock);
316 * Serialise to avoid races between IOMMU drivers registering in
317 * parallel and/or the "replay" calls from ACPI/OF code via client
318 * driver probe. Once the latter have been cleaned up we should
319 * probably be able to use device_lock() here to minimise the scope,
320 * but for now enforcing a simple global ordering is fine.
322 mutex_lock(&iommu_probe_device_lock);
323 if (!dev_iommu_get(dev)) {
328 if (!try_module_get(ops->owner)) {
333 iommu_dev = ops->probe_device(dev);
334 if (IS_ERR(iommu_dev)) {
335 ret = PTR_ERR(iommu_dev);
339 dev->iommu->iommu_dev = iommu_dev;
340 dev->iommu->max_pasids = dev_iommu_get_max_pasids(dev);
342 group = iommu_group_get_for_dev(dev);
344 ret = PTR_ERR(group);
348 mutex_lock(&group->mutex);
349 if (group_list && !group->default_domain && list_empty(&group->entry))
350 list_add_tail(&group->entry, group_list);
351 mutex_unlock(&group->mutex);
352 iommu_group_put(group);
354 mutex_unlock(&iommu_probe_device_lock);
355 iommu_device_link(iommu_dev, dev);
360 if (ops->release_device)
361 ops->release_device(dev);
364 module_put(ops->owner);
370 mutex_unlock(&iommu_probe_device_lock);
375 static bool iommu_is_attach_deferred(struct device *dev)
377 const struct iommu_ops *ops = dev_iommu_ops(dev);
379 if (ops->is_attach_deferred)
380 return ops->is_attach_deferred(dev);
385 static int iommu_group_do_dma_first_attach(struct device *dev, void *data)
387 struct iommu_domain *domain = data;
389 lockdep_assert_held(&dev->iommu_group->mutex);
391 if (iommu_is_attach_deferred(dev)) {
392 dev->iommu->attach_deferred = 1;
396 return __iommu_attach_device(domain, dev);
399 int iommu_probe_device(struct device *dev)
401 const struct iommu_ops *ops;
402 struct iommu_group *group;
405 ret = __iommu_probe_device(dev, NULL);
409 group = iommu_group_get(dev);
416 * Try to allocate a default domain - needs support from the
417 * IOMMU driver. There are still some drivers which don't
418 * support default domains, so the return value is not yet
421 mutex_lock(&group->mutex);
422 iommu_alloc_default_domain(group, dev);
425 * If device joined an existing group which has been claimed, don't
426 * attach the default domain.
428 if (group->default_domain && !group->owner) {
429 ret = iommu_group_do_dma_first_attach(dev, group->default_domain);
431 mutex_unlock(&group->mutex);
432 iommu_group_put(group);
437 iommu_create_device_direct_mappings(group, dev);
439 mutex_unlock(&group->mutex);
440 iommu_group_put(group);
442 ops = dev_iommu_ops(dev);
443 if (ops->probe_finalize)
444 ops->probe_finalize(dev);
449 iommu_release_device(dev);
456 void iommu_release_device(struct device *dev)
458 const struct iommu_ops *ops;
463 iommu_device_unlink(dev->iommu->iommu_dev, dev);
465 ops = dev_iommu_ops(dev);
466 if (ops->release_device)
467 ops->release_device(dev);
469 iommu_group_remove_device(dev);
470 module_put(ops->owner);
474 static int __init iommu_set_def_domain_type(char *str)
479 ret = kstrtobool(str, &pt);
484 iommu_set_default_passthrough(true);
486 iommu_set_default_translated(true);
490 early_param("iommu.passthrough", iommu_set_def_domain_type);
492 static int __init iommu_dma_setup(char *str)
494 int ret = kstrtobool(str, &iommu_dma_strict);
497 iommu_cmd_line |= IOMMU_CMD_LINE_STRICT;
500 early_param("iommu.strict", iommu_dma_setup);
502 void iommu_set_dma_strict(void)
504 iommu_dma_strict = true;
505 if (iommu_def_domain_type == IOMMU_DOMAIN_DMA_FQ)
506 iommu_def_domain_type = IOMMU_DOMAIN_DMA;
509 static ssize_t iommu_group_attr_show(struct kobject *kobj,
510 struct attribute *__attr, char *buf)
512 struct iommu_group_attribute *attr = to_iommu_group_attr(__attr);
513 struct iommu_group *group = to_iommu_group(kobj);
517 ret = attr->show(group, buf);
521 static ssize_t iommu_group_attr_store(struct kobject *kobj,
522 struct attribute *__attr,
523 const char *buf, size_t count)
525 struct iommu_group_attribute *attr = to_iommu_group_attr(__attr);
526 struct iommu_group *group = to_iommu_group(kobj);
530 ret = attr->store(group, buf, count);
534 static const struct sysfs_ops iommu_group_sysfs_ops = {
535 .show = iommu_group_attr_show,
536 .store = iommu_group_attr_store,
539 static int iommu_group_create_file(struct iommu_group *group,
540 struct iommu_group_attribute *attr)
542 return sysfs_create_file(&group->kobj, &attr->attr);
545 static void iommu_group_remove_file(struct iommu_group *group,
546 struct iommu_group_attribute *attr)
548 sysfs_remove_file(&group->kobj, &attr->attr);
551 static ssize_t iommu_group_show_name(struct iommu_group *group, char *buf)
553 return sprintf(buf, "%s\n", group->name);
557 * iommu_insert_resv_region - Insert a new region in the
558 * list of reserved regions.
559 * @new: new region to insert
560 * @regions: list of regions
562 * Elements are sorted by start address and overlapping segments
563 * of the same type are merged.
565 static int iommu_insert_resv_region(struct iommu_resv_region *new,
566 struct list_head *regions)
568 struct iommu_resv_region *iter, *tmp, *nr, *top;
571 nr = iommu_alloc_resv_region(new->start, new->length,
572 new->prot, new->type, GFP_KERNEL);
576 /* First add the new element based on start address sorting */
577 list_for_each_entry(iter, regions, list) {
578 if (nr->start < iter->start ||
579 (nr->start == iter->start && nr->type <= iter->type))
582 list_add_tail(&nr->list, &iter->list);
584 /* Merge overlapping segments of type nr->type in @regions, if any */
585 list_for_each_entry_safe(iter, tmp, regions, list) {
586 phys_addr_t top_end, iter_end = iter->start + iter->length - 1;
588 /* no merge needed on elements of different types than @new */
589 if (iter->type != new->type) {
590 list_move_tail(&iter->list, &stack);
594 /* look for the last stack element of same type as @iter */
595 list_for_each_entry_reverse(top, &stack, list)
596 if (top->type == iter->type)
599 list_move_tail(&iter->list, &stack);
603 top_end = top->start + top->length - 1;
605 if (iter->start > top_end + 1) {
606 list_move_tail(&iter->list, &stack);
608 top->length = max(top_end, iter_end) - top->start + 1;
609 list_del(&iter->list);
613 list_splice(&stack, regions);
618 iommu_insert_device_resv_regions(struct list_head *dev_resv_regions,
619 struct list_head *group_resv_regions)
621 struct iommu_resv_region *entry;
624 list_for_each_entry(entry, dev_resv_regions, list) {
625 ret = iommu_insert_resv_region(entry, group_resv_regions);
632 int iommu_get_group_resv_regions(struct iommu_group *group,
633 struct list_head *head)
635 struct group_device *device;
638 mutex_lock(&group->mutex);
639 list_for_each_entry(device, &group->devices, list) {
640 struct list_head dev_resv_regions;
643 * Non-API groups still expose reserved_regions in sysfs,
644 * so filter out calls that get here that way.
646 if (!device->dev->iommu)
649 INIT_LIST_HEAD(&dev_resv_regions);
650 iommu_get_resv_regions(device->dev, &dev_resv_regions);
651 ret = iommu_insert_device_resv_regions(&dev_resv_regions, head);
652 iommu_put_resv_regions(device->dev, &dev_resv_regions);
656 mutex_unlock(&group->mutex);
659 EXPORT_SYMBOL_GPL(iommu_get_group_resv_regions);
661 static ssize_t iommu_group_show_resv_regions(struct iommu_group *group,
664 struct iommu_resv_region *region, *next;
665 struct list_head group_resv_regions;
668 INIT_LIST_HEAD(&group_resv_regions);
669 iommu_get_group_resv_regions(group, &group_resv_regions);
671 list_for_each_entry_safe(region, next, &group_resv_regions, list) {
672 str += sprintf(str, "0x%016llx 0x%016llx %s\n",
673 (long long int)region->start,
674 (long long int)(region->start +
676 iommu_group_resv_type_string[region->type]);
683 static ssize_t iommu_group_show_type(struct iommu_group *group,
686 char *type = "unknown\n";
688 mutex_lock(&group->mutex);
689 if (group->default_domain) {
690 switch (group->default_domain->type) {
691 case IOMMU_DOMAIN_BLOCKED:
694 case IOMMU_DOMAIN_IDENTITY:
697 case IOMMU_DOMAIN_UNMANAGED:
698 type = "unmanaged\n";
700 case IOMMU_DOMAIN_DMA:
703 case IOMMU_DOMAIN_DMA_FQ:
708 mutex_unlock(&group->mutex);
714 static IOMMU_GROUP_ATTR(name, S_IRUGO, iommu_group_show_name, NULL);
716 static IOMMU_GROUP_ATTR(reserved_regions, 0444,
717 iommu_group_show_resv_regions, NULL);
719 static IOMMU_GROUP_ATTR(type, 0644, iommu_group_show_type,
720 iommu_group_store_type);
722 static void iommu_group_release(struct kobject *kobj)
724 struct iommu_group *group = to_iommu_group(kobj);
726 pr_debug("Releasing group %d\n", group->id);
728 if (group->iommu_data_release)
729 group->iommu_data_release(group->iommu_data);
731 ida_free(&iommu_group_ida, group->id);
733 if (group->default_domain)
734 iommu_domain_free(group->default_domain);
735 if (group->blocking_domain)
736 iommu_domain_free(group->blocking_domain);
742 static struct kobj_type iommu_group_ktype = {
743 .sysfs_ops = &iommu_group_sysfs_ops,
744 .release = iommu_group_release,
748 * iommu_group_alloc - Allocate a new group
750 * This function is called by an iommu driver to allocate a new iommu
751 * group. The iommu group represents the minimum granularity of the iommu.
752 * Upon successful return, the caller holds a reference to the supplied
753 * group in order to hold the group until devices are added. Use
754 * iommu_group_put() to release this extra reference count, allowing the
755 * group to be automatically reclaimed once it has no devices or external
758 struct iommu_group *iommu_group_alloc(void)
760 struct iommu_group *group;
763 group = kzalloc(sizeof(*group), GFP_KERNEL);
765 return ERR_PTR(-ENOMEM);
767 group->kobj.kset = iommu_group_kset;
768 mutex_init(&group->mutex);
769 INIT_LIST_HEAD(&group->devices);
770 INIT_LIST_HEAD(&group->entry);
771 xa_init(&group->pasid_array);
773 ret = ida_alloc(&iommu_group_ida, GFP_KERNEL);
780 ret = kobject_init_and_add(&group->kobj, &iommu_group_ktype,
781 NULL, "%d", group->id);
783 kobject_put(&group->kobj);
787 group->devices_kobj = kobject_create_and_add("devices", &group->kobj);
788 if (!group->devices_kobj) {
789 kobject_put(&group->kobj); /* triggers .release & free */
790 return ERR_PTR(-ENOMEM);
794 * The devices_kobj holds a reference on the group kobject, so
795 * as long as that exists so will the group. We can therefore
796 * use the devices_kobj for reference counting.
798 kobject_put(&group->kobj);
800 ret = iommu_group_create_file(group,
801 &iommu_group_attr_reserved_regions);
803 kobject_put(group->devices_kobj);
807 ret = iommu_group_create_file(group, &iommu_group_attr_type);
809 kobject_put(group->devices_kobj);
813 pr_debug("Allocated group %d\n", group->id);
817 EXPORT_SYMBOL_GPL(iommu_group_alloc);
819 struct iommu_group *iommu_group_get_by_id(int id)
821 struct kobject *group_kobj;
822 struct iommu_group *group;
825 if (!iommu_group_kset)
828 name = kasprintf(GFP_KERNEL, "%d", id);
832 group_kobj = kset_find_obj(iommu_group_kset, name);
838 group = container_of(group_kobj, struct iommu_group, kobj);
839 BUG_ON(group->id != id);
841 kobject_get(group->devices_kobj);
842 kobject_put(&group->kobj);
846 EXPORT_SYMBOL_GPL(iommu_group_get_by_id);
849 * iommu_group_get_iommudata - retrieve iommu_data registered for a group
852 * iommu drivers can store data in the group for use when doing iommu
853 * operations. This function provides a way to retrieve it. Caller
854 * should hold a group reference.
856 void *iommu_group_get_iommudata(struct iommu_group *group)
858 return group->iommu_data;
860 EXPORT_SYMBOL_GPL(iommu_group_get_iommudata);
863 * iommu_group_set_iommudata - set iommu_data for a group
865 * @iommu_data: new data
866 * @release: release function for iommu_data
868 * iommu drivers can store data in the group for use when doing iommu
869 * operations. This function provides a way to set the data after
870 * the group has been allocated. Caller should hold a group reference.
872 void iommu_group_set_iommudata(struct iommu_group *group, void *iommu_data,
873 void (*release)(void *iommu_data))
875 group->iommu_data = iommu_data;
876 group->iommu_data_release = release;
878 EXPORT_SYMBOL_GPL(iommu_group_set_iommudata);
881 * iommu_group_set_name - set name for a group
885 * Allow iommu driver to set a name for a group. When set it will
886 * appear in a name attribute file under the group in sysfs.
888 int iommu_group_set_name(struct iommu_group *group, const char *name)
893 iommu_group_remove_file(group, &iommu_group_attr_name);
900 group->name = kstrdup(name, GFP_KERNEL);
904 ret = iommu_group_create_file(group, &iommu_group_attr_name);
913 EXPORT_SYMBOL_GPL(iommu_group_set_name);
915 static int iommu_create_device_direct_mappings(struct iommu_group *group,
918 struct iommu_domain *domain = group->default_domain;
919 struct iommu_resv_region *entry;
920 struct list_head mappings;
921 unsigned long pg_size;
924 if (!domain || !iommu_is_dma_domain(domain))
927 BUG_ON(!domain->pgsize_bitmap);
929 pg_size = 1UL << __ffs(domain->pgsize_bitmap);
930 INIT_LIST_HEAD(&mappings);
932 iommu_get_resv_regions(dev, &mappings);
934 /* We need to consider overlapping regions for different devices */
935 list_for_each_entry(entry, &mappings, list) {
936 dma_addr_t start, end, addr;
939 start = ALIGN(entry->start, pg_size);
940 end = ALIGN(entry->start + entry->length, pg_size);
942 if (entry->type != IOMMU_RESV_DIRECT &&
943 entry->type != IOMMU_RESV_DIRECT_RELAXABLE)
946 for (addr = start; addr <= end; addr += pg_size) {
947 phys_addr_t phys_addr;
952 phys_addr = iommu_iova_to_phys(domain, addr);
960 ret = iommu_map(domain, addr - map_size,
961 addr - map_size, map_size,
962 entry->prot, GFP_KERNEL);
971 iommu_flush_iotlb_all(domain);
974 iommu_put_resv_regions(dev, &mappings);
980 * iommu_group_add_device - add a device to an iommu group
981 * @group: the group into which to add the device (reference should be held)
984 * This function is called by an iommu driver to add a device into a
985 * group. Adding a device increments the group reference count.
987 int iommu_group_add_device(struct iommu_group *group, struct device *dev)
990 struct group_device *device;
992 device = kzalloc(sizeof(*device), GFP_KERNEL);
998 ret = sysfs_create_link(&dev->kobj, &group->kobj, "iommu_group");
1000 goto err_free_device;
1002 device->name = kasprintf(GFP_KERNEL, "%s", kobject_name(&dev->kobj));
1004 if (!device->name) {
1006 goto err_remove_link;
1009 ret = sysfs_create_link_nowarn(group->devices_kobj,
1010 &dev->kobj, device->name);
1012 if (ret == -EEXIST && i >= 0) {
1014 * Account for the slim chance of collision
1015 * and append an instance to the name.
1017 kfree(device->name);
1018 device->name = kasprintf(GFP_KERNEL, "%s.%d",
1019 kobject_name(&dev->kobj), i++);
1025 kobject_get(group->devices_kobj);
1027 dev->iommu_group = group;
1029 mutex_lock(&group->mutex);
1030 list_add_tail(&device->list, &group->devices);
1032 ret = iommu_group_do_dma_first_attach(dev, group->domain);
1033 mutex_unlock(&group->mutex);
1037 trace_add_device_to_group(group->id, dev);
1039 dev_info(dev, "Adding to iommu group %d\n", group->id);
1044 mutex_lock(&group->mutex);
1045 list_del(&device->list);
1046 mutex_unlock(&group->mutex);
1047 dev->iommu_group = NULL;
1048 kobject_put(group->devices_kobj);
1049 sysfs_remove_link(group->devices_kobj, device->name);
1051 kfree(device->name);
1053 sysfs_remove_link(&dev->kobj, "iommu_group");
1056 dev_err(dev, "Failed to add to iommu group %d: %d\n", group->id, ret);
1059 EXPORT_SYMBOL_GPL(iommu_group_add_device);
1062 * iommu_group_remove_device - remove a device from it's current group
1063 * @dev: device to be removed
1065 * This function is called by an iommu driver to remove the device from
1066 * it's current group. This decrements the iommu group reference count.
1068 void iommu_group_remove_device(struct device *dev)
1070 struct iommu_group *group = dev->iommu_group;
1071 struct group_device *tmp_device, *device = NULL;
1076 dev_info(dev, "Removing from iommu group %d\n", group->id);
1078 mutex_lock(&group->mutex);
1079 list_for_each_entry(tmp_device, &group->devices, list) {
1080 if (tmp_device->dev == dev) {
1081 device = tmp_device;
1082 list_del(&device->list);
1086 mutex_unlock(&group->mutex);
1091 sysfs_remove_link(group->devices_kobj, device->name);
1092 sysfs_remove_link(&dev->kobj, "iommu_group");
1094 trace_remove_device_from_group(group->id, dev);
1096 kfree(device->name);
1098 dev->iommu_group = NULL;
1099 kobject_put(group->devices_kobj);
1101 EXPORT_SYMBOL_GPL(iommu_group_remove_device);
1103 static int iommu_group_device_count(struct iommu_group *group)
1105 struct group_device *entry;
1108 list_for_each_entry(entry, &group->devices, list)
1114 static int __iommu_group_for_each_dev(struct iommu_group *group, void *data,
1115 int (*fn)(struct device *, void *))
1117 struct group_device *device;
1120 list_for_each_entry(device, &group->devices, list) {
1121 ret = fn(device->dev, data);
1129 * iommu_group_for_each_dev - iterate over each device in the group
1131 * @data: caller opaque data to be passed to callback function
1132 * @fn: caller supplied callback function
1134 * This function is called by group users to iterate over group devices.
1135 * Callers should hold a reference count to the group during callback.
1136 * The group->mutex is held across callbacks, which will block calls to
1137 * iommu_group_add/remove_device.
1139 int iommu_group_for_each_dev(struct iommu_group *group, void *data,
1140 int (*fn)(struct device *, void *))
1144 mutex_lock(&group->mutex);
1145 ret = __iommu_group_for_each_dev(group, data, fn);
1146 mutex_unlock(&group->mutex);
1150 EXPORT_SYMBOL_GPL(iommu_group_for_each_dev);
1153 * iommu_group_get - Return the group for a device and increment reference
1154 * @dev: get the group that this device belongs to
1156 * This function is called by iommu drivers and users to get the group
1157 * for the specified device. If found, the group is returned and the group
1158 * reference in incremented, else NULL.
1160 struct iommu_group *iommu_group_get(struct device *dev)
1162 struct iommu_group *group = dev->iommu_group;
1165 kobject_get(group->devices_kobj);
1169 EXPORT_SYMBOL_GPL(iommu_group_get);
1172 * iommu_group_ref_get - Increment reference on a group
1173 * @group: the group to use, must not be NULL
1175 * This function is called by iommu drivers to take additional references on an
1176 * existing group. Returns the given group for convenience.
1178 struct iommu_group *iommu_group_ref_get(struct iommu_group *group)
1180 kobject_get(group->devices_kobj);
1183 EXPORT_SYMBOL_GPL(iommu_group_ref_get);
1186 * iommu_group_put - Decrement group reference
1187 * @group: the group to use
1189 * This function is called by iommu drivers and users to release the
1190 * iommu group. Once the reference count is zero, the group is released.
1192 void iommu_group_put(struct iommu_group *group)
1195 kobject_put(group->devices_kobj);
1197 EXPORT_SYMBOL_GPL(iommu_group_put);
1200 * iommu_register_device_fault_handler() - Register a device fault handler
1202 * @handler: the fault handler
1203 * @data: private data passed as argument to the handler
1205 * When an IOMMU fault event is received, this handler gets called with the
1206 * fault event and data as argument. The handler should return 0 on success. If
1207 * the fault is recoverable (IOMMU_FAULT_PAGE_REQ), the consumer should also
1208 * complete the fault by calling iommu_page_response() with one of the following
1210 * - IOMMU_PAGE_RESP_SUCCESS: retry the translation
1211 * - IOMMU_PAGE_RESP_INVALID: terminate the fault
1212 * - IOMMU_PAGE_RESP_FAILURE: terminate the fault and stop reporting
1213 * page faults if possible.
1215 * Return 0 if the fault handler was installed successfully, or an error.
1217 int iommu_register_device_fault_handler(struct device *dev,
1218 iommu_dev_fault_handler_t handler,
1221 struct dev_iommu *param = dev->iommu;
1227 mutex_lock(¶m->lock);
1228 /* Only allow one fault handler registered for each device */
1229 if (param->fault_param) {
1235 param->fault_param = kzalloc(sizeof(*param->fault_param), GFP_KERNEL);
1236 if (!param->fault_param) {
1241 param->fault_param->handler = handler;
1242 param->fault_param->data = data;
1243 mutex_init(¶m->fault_param->lock);
1244 INIT_LIST_HEAD(¶m->fault_param->faults);
1247 mutex_unlock(¶m->lock);
1251 EXPORT_SYMBOL_GPL(iommu_register_device_fault_handler);
1254 * iommu_unregister_device_fault_handler() - Unregister the device fault handler
1257 * Remove the device fault handler installed with
1258 * iommu_register_device_fault_handler().
1260 * Return 0 on success, or an error.
1262 int iommu_unregister_device_fault_handler(struct device *dev)
1264 struct dev_iommu *param = dev->iommu;
1270 mutex_lock(¶m->lock);
1272 if (!param->fault_param)
1275 /* we cannot unregister handler if there are pending faults */
1276 if (!list_empty(¶m->fault_param->faults)) {
1281 kfree(param->fault_param);
1282 param->fault_param = NULL;
1285 mutex_unlock(¶m->lock);
1289 EXPORT_SYMBOL_GPL(iommu_unregister_device_fault_handler);
1292 * iommu_report_device_fault() - Report fault event to device driver
1294 * @evt: fault event data
1296 * Called by IOMMU drivers when a fault is detected, typically in a threaded IRQ
1297 * handler. When this function fails and the fault is recoverable, it is the
1298 * caller's responsibility to complete the fault.
1300 * Return 0 on success, or an error.
1302 int iommu_report_device_fault(struct device *dev, struct iommu_fault_event *evt)
1304 struct dev_iommu *param = dev->iommu;
1305 struct iommu_fault_event *evt_pending = NULL;
1306 struct iommu_fault_param *fparam;
1312 /* we only report device fault if there is a handler registered */
1313 mutex_lock(¶m->lock);
1314 fparam = param->fault_param;
1315 if (!fparam || !fparam->handler) {
1320 if (evt->fault.type == IOMMU_FAULT_PAGE_REQ &&
1321 (evt->fault.prm.flags & IOMMU_FAULT_PAGE_REQUEST_LAST_PAGE)) {
1322 evt_pending = kmemdup(evt, sizeof(struct iommu_fault_event),
1328 mutex_lock(&fparam->lock);
1329 list_add_tail(&evt_pending->list, &fparam->faults);
1330 mutex_unlock(&fparam->lock);
1333 ret = fparam->handler(&evt->fault, fparam->data);
1334 if (ret && evt_pending) {
1335 mutex_lock(&fparam->lock);
1336 list_del(&evt_pending->list);
1337 mutex_unlock(&fparam->lock);
1341 mutex_unlock(¶m->lock);
1344 EXPORT_SYMBOL_GPL(iommu_report_device_fault);
1346 int iommu_page_response(struct device *dev,
1347 struct iommu_page_response *msg)
1351 struct iommu_fault_event *evt;
1352 struct iommu_fault_page_request *prm;
1353 struct dev_iommu *param = dev->iommu;
1354 const struct iommu_ops *ops = dev_iommu_ops(dev);
1355 bool has_pasid = msg->flags & IOMMU_PAGE_RESP_PASID_VALID;
1357 if (!ops->page_response)
1360 if (!param || !param->fault_param)
1363 if (msg->version != IOMMU_PAGE_RESP_VERSION_1 ||
1364 msg->flags & ~IOMMU_PAGE_RESP_PASID_VALID)
1367 /* Only send response if there is a fault report pending */
1368 mutex_lock(¶m->fault_param->lock);
1369 if (list_empty(¶m->fault_param->faults)) {
1370 dev_warn_ratelimited(dev, "no pending PRQ, drop response\n");
1374 * Check if we have a matching page request pending to respond,
1375 * otherwise return -EINVAL
1377 list_for_each_entry(evt, ¶m->fault_param->faults, list) {
1378 prm = &evt->fault.prm;
1379 if (prm->grpid != msg->grpid)
1383 * If the PASID is required, the corresponding request is
1384 * matched using the group ID, the PASID valid bit and the PASID
1385 * value. Otherwise only the group ID matches request and
1388 needs_pasid = prm->flags & IOMMU_FAULT_PAGE_RESPONSE_NEEDS_PASID;
1389 if (needs_pasid && (!has_pasid || msg->pasid != prm->pasid))
1392 if (!needs_pasid && has_pasid) {
1393 /* No big deal, just clear it. */
1394 msg->flags &= ~IOMMU_PAGE_RESP_PASID_VALID;
1398 ret = ops->page_response(dev, evt, msg);
1399 list_del(&evt->list);
1405 mutex_unlock(¶m->fault_param->lock);
1408 EXPORT_SYMBOL_GPL(iommu_page_response);
1411 * iommu_group_id - Return ID for a group
1412 * @group: the group to ID
1414 * Return the unique ID for the group matching the sysfs group number.
1416 int iommu_group_id(struct iommu_group *group)
1420 EXPORT_SYMBOL_GPL(iommu_group_id);
1422 static struct iommu_group *get_pci_alias_group(struct pci_dev *pdev,
1423 unsigned long *devfns);
1426 * To consider a PCI device isolated, we require ACS to support Source
1427 * Validation, Request Redirection, Completer Redirection, and Upstream
1428 * Forwarding. This effectively means that devices cannot spoof their
1429 * requester ID, requests and completions cannot be redirected, and all
1430 * transactions are forwarded upstream, even as it passes through a
1431 * bridge where the target device is downstream.
1433 #define REQ_ACS_FLAGS (PCI_ACS_SV | PCI_ACS_RR | PCI_ACS_CR | PCI_ACS_UF)
1436 * For multifunction devices which are not isolated from each other, find
1437 * all the other non-isolated functions and look for existing groups. For
1438 * each function, we also need to look for aliases to or from other devices
1439 * that may already have a group.
1441 static struct iommu_group *get_pci_function_alias_group(struct pci_dev *pdev,
1442 unsigned long *devfns)
1444 struct pci_dev *tmp = NULL;
1445 struct iommu_group *group;
1447 if (!pdev->multifunction || pci_acs_enabled(pdev, REQ_ACS_FLAGS))
1450 for_each_pci_dev(tmp) {
1451 if (tmp == pdev || tmp->bus != pdev->bus ||
1452 PCI_SLOT(tmp->devfn) != PCI_SLOT(pdev->devfn) ||
1453 pci_acs_enabled(tmp, REQ_ACS_FLAGS))
1456 group = get_pci_alias_group(tmp, devfns);
1467 * Look for aliases to or from the given device for existing groups. DMA
1468 * aliases are only supported on the same bus, therefore the search
1469 * space is quite small (especially since we're really only looking at pcie
1470 * device, and therefore only expect multiple slots on the root complex or
1471 * downstream switch ports). It's conceivable though that a pair of
1472 * multifunction devices could have aliases between them that would cause a
1473 * loop. To prevent this, we use a bitmap to track where we've been.
1475 static struct iommu_group *get_pci_alias_group(struct pci_dev *pdev,
1476 unsigned long *devfns)
1478 struct pci_dev *tmp = NULL;
1479 struct iommu_group *group;
1481 if (test_and_set_bit(pdev->devfn & 0xff, devfns))
1484 group = iommu_group_get(&pdev->dev);
1488 for_each_pci_dev(tmp) {
1489 if (tmp == pdev || tmp->bus != pdev->bus)
1492 /* We alias them or they alias us */
1493 if (pci_devs_are_dma_aliases(pdev, tmp)) {
1494 group = get_pci_alias_group(tmp, devfns);
1500 group = get_pci_function_alias_group(tmp, devfns);
1511 struct group_for_pci_data {
1512 struct pci_dev *pdev;
1513 struct iommu_group *group;
1517 * DMA alias iterator callback, return the last seen device. Stop and return
1518 * the IOMMU group if we find one along the way.
1520 static int get_pci_alias_or_group(struct pci_dev *pdev, u16 alias, void *opaque)
1522 struct group_for_pci_data *data = opaque;
1525 data->group = iommu_group_get(&pdev->dev);
1527 return data->group != NULL;
1531 * Generic device_group call-back function. It just allocates one
1532 * iommu-group per device.
1534 struct iommu_group *generic_device_group(struct device *dev)
1536 return iommu_group_alloc();
1538 EXPORT_SYMBOL_GPL(generic_device_group);
1541 * Use standard PCI bus topology, isolation features, and DMA alias quirks
1542 * to find or create an IOMMU group for a device.
1544 struct iommu_group *pci_device_group(struct device *dev)
1546 struct pci_dev *pdev = to_pci_dev(dev);
1547 struct group_for_pci_data data;
1548 struct pci_bus *bus;
1549 struct iommu_group *group = NULL;
1550 u64 devfns[4] = { 0 };
1552 if (WARN_ON(!dev_is_pci(dev)))
1553 return ERR_PTR(-EINVAL);
1556 * Find the upstream DMA alias for the device. A device must not
1557 * be aliased due to topology in order to have its own IOMMU group.
1558 * If we find an alias along the way that already belongs to a
1561 if (pci_for_each_dma_alias(pdev, get_pci_alias_or_group, &data))
1567 * Continue upstream from the point of minimum IOMMU granularity
1568 * due to aliases to the point where devices are protected from
1569 * peer-to-peer DMA by PCI ACS. Again, if we find an existing
1572 for (bus = pdev->bus; !pci_is_root_bus(bus); bus = bus->parent) {
1576 if (pci_acs_path_enabled(bus->self, NULL, REQ_ACS_FLAGS))
1581 group = iommu_group_get(&pdev->dev);
1587 * Look for existing groups on device aliases. If we alias another
1588 * device or another device aliases us, use the same group.
1590 group = get_pci_alias_group(pdev, (unsigned long *)devfns);
1595 * Look for existing groups on non-isolated functions on the same
1596 * slot and aliases of those funcions, if any. No need to clear
1597 * the search bitmap, the tested devfns are still valid.
1599 group = get_pci_function_alias_group(pdev, (unsigned long *)devfns);
1603 /* No shared group found, allocate new */
1604 return iommu_group_alloc();
1606 EXPORT_SYMBOL_GPL(pci_device_group);
1608 /* Get the IOMMU group for device on fsl-mc bus */
1609 struct iommu_group *fsl_mc_device_group(struct device *dev)
1611 struct device *cont_dev = fsl_mc_cont_dev(dev);
1612 struct iommu_group *group;
1614 group = iommu_group_get(cont_dev);
1616 group = iommu_group_alloc();
1619 EXPORT_SYMBOL_GPL(fsl_mc_device_group);
1621 static int iommu_get_def_domain_type(struct device *dev)
1623 const struct iommu_ops *ops = dev_iommu_ops(dev);
1625 if (dev_is_pci(dev) && to_pci_dev(dev)->untrusted)
1626 return IOMMU_DOMAIN_DMA;
1628 if (ops->def_domain_type)
1629 return ops->def_domain_type(dev);
1634 static int iommu_group_alloc_default_domain(struct bus_type *bus,
1635 struct iommu_group *group,
1638 struct iommu_domain *dom;
1640 dom = __iommu_domain_alloc(bus, type);
1641 if (!dom && type != IOMMU_DOMAIN_DMA) {
1642 dom = __iommu_domain_alloc(bus, IOMMU_DOMAIN_DMA);
1644 pr_warn("Failed to allocate default IOMMU domain of type %u for group %s - Falling back to IOMMU_DOMAIN_DMA",
1651 group->default_domain = dom;
1653 group->domain = dom;
1657 static int iommu_alloc_default_domain(struct iommu_group *group,
1662 if (group->default_domain)
1665 type = iommu_get_def_domain_type(dev) ? : iommu_def_domain_type;
1667 return iommu_group_alloc_default_domain(dev->bus, group, type);
1671 * iommu_group_get_for_dev - Find or create the IOMMU group for a device
1672 * @dev: target device
1674 * This function is intended to be called by IOMMU drivers and extended to
1675 * support common, bus-defined algorithms when determining or creating the
1676 * IOMMU group for a device. On success, the caller will hold a reference
1677 * to the returned IOMMU group, which will already include the provided
1678 * device. The reference should be released with iommu_group_put().
1680 static struct iommu_group *iommu_group_get_for_dev(struct device *dev)
1682 const struct iommu_ops *ops = dev_iommu_ops(dev);
1683 struct iommu_group *group;
1686 group = iommu_group_get(dev);
1690 group = ops->device_group(dev);
1691 if (WARN_ON_ONCE(group == NULL))
1692 return ERR_PTR(-EINVAL);
1697 ret = iommu_group_add_device(group, dev);
1704 iommu_group_put(group);
1706 return ERR_PTR(ret);
1709 struct iommu_domain *iommu_group_default_domain(struct iommu_group *group)
1711 return group->default_domain;
1714 static int probe_iommu_group(struct device *dev, void *data)
1716 struct list_head *group_list = data;
1717 struct iommu_group *group;
1720 /* Device is probed already if in a group */
1721 group = iommu_group_get(dev);
1723 iommu_group_put(group);
1727 ret = __iommu_probe_device(dev, group_list);
1734 static int iommu_bus_notifier(struct notifier_block *nb,
1735 unsigned long action, void *data)
1737 struct device *dev = data;
1739 if (action == BUS_NOTIFY_ADD_DEVICE) {
1742 ret = iommu_probe_device(dev);
1743 return (ret) ? NOTIFY_DONE : NOTIFY_OK;
1744 } else if (action == BUS_NOTIFY_REMOVED_DEVICE) {
1745 iommu_release_device(dev);
1752 struct __group_domain_type {
1757 static int probe_get_default_domain_type(struct device *dev, void *data)
1759 struct __group_domain_type *gtype = data;
1760 unsigned int type = iommu_get_def_domain_type(dev);
1763 if (gtype->type && gtype->type != type) {
1764 dev_warn(dev, "Device needs domain type %s, but device %s in the same iommu group requires type %s - using default\n",
1765 iommu_domain_type_str(type),
1766 dev_name(gtype->dev),
1767 iommu_domain_type_str(gtype->type));
1780 static void probe_alloc_default_domain(struct bus_type *bus,
1781 struct iommu_group *group)
1783 struct __group_domain_type gtype;
1785 memset(>ype, 0, sizeof(gtype));
1787 /* Ask for default domain requirements of all devices in the group */
1788 __iommu_group_for_each_dev(group, >ype,
1789 probe_get_default_domain_type);
1792 gtype.type = iommu_def_domain_type;
1794 iommu_group_alloc_default_domain(bus, group, gtype.type);
1798 static int __iommu_group_dma_first_attach(struct iommu_group *group)
1800 return __iommu_group_for_each_dev(group, group->default_domain,
1801 iommu_group_do_dma_first_attach);
1804 static int iommu_group_do_probe_finalize(struct device *dev, void *data)
1806 const struct iommu_ops *ops = dev_iommu_ops(dev);
1808 if (ops->probe_finalize)
1809 ops->probe_finalize(dev);
1814 static void __iommu_group_dma_finalize(struct iommu_group *group)
1816 __iommu_group_for_each_dev(group, group->default_domain,
1817 iommu_group_do_probe_finalize);
1820 static int iommu_do_create_direct_mappings(struct device *dev, void *data)
1822 struct iommu_group *group = data;
1824 iommu_create_device_direct_mappings(group, dev);
1829 static int iommu_group_create_direct_mappings(struct iommu_group *group)
1831 return __iommu_group_for_each_dev(group, group,
1832 iommu_do_create_direct_mappings);
1835 int bus_iommu_probe(struct bus_type *bus)
1837 struct iommu_group *group, *next;
1838 LIST_HEAD(group_list);
1842 * This code-path does not allocate the default domain when
1843 * creating the iommu group, so do it after the groups are
1846 ret = bus_for_each_dev(bus, NULL, &group_list, probe_iommu_group);
1850 list_for_each_entry_safe(group, next, &group_list, entry) {
1851 mutex_lock(&group->mutex);
1853 /* Remove item from the list */
1854 list_del_init(&group->entry);
1856 /* Try to allocate default domain */
1857 probe_alloc_default_domain(bus, group);
1859 if (!group->default_domain) {
1860 mutex_unlock(&group->mutex);
1864 iommu_group_create_direct_mappings(group);
1866 ret = __iommu_group_dma_first_attach(group);
1868 mutex_unlock(&group->mutex);
1873 __iommu_group_dma_finalize(group);
1879 bool iommu_present(struct bus_type *bus)
1881 return bus->iommu_ops != NULL;
1883 EXPORT_SYMBOL_GPL(iommu_present);
1886 * device_iommu_capable() - check for a general IOMMU capability
1887 * @dev: device to which the capability would be relevant, if available
1888 * @cap: IOMMU capability
1890 * Return: true if an IOMMU is present and supports the given capability
1891 * for the given device, otherwise false.
1893 bool device_iommu_capable(struct device *dev, enum iommu_cap cap)
1895 const struct iommu_ops *ops;
1897 if (!dev->iommu || !dev->iommu->iommu_dev)
1900 ops = dev_iommu_ops(dev);
1904 return ops->capable(dev, cap);
1906 EXPORT_SYMBOL_GPL(device_iommu_capable);
1909 * iommu_group_has_isolated_msi() - Compute msi_device_has_isolated_msi()
1911 * @group: Group to query
1913 * IOMMU groups should not have differing values of
1914 * msi_device_has_isolated_msi() for devices in a group. However nothing
1915 * directly prevents this, so ensure mistakes don't result in isolation failures
1916 * by checking that all the devices are the same.
1918 bool iommu_group_has_isolated_msi(struct iommu_group *group)
1920 struct group_device *group_dev;
1923 mutex_lock(&group->mutex);
1924 list_for_each_entry(group_dev, &group->devices, list)
1925 ret &= msi_device_has_isolated_msi(group_dev->dev);
1926 mutex_unlock(&group->mutex);
1929 EXPORT_SYMBOL_GPL(iommu_group_has_isolated_msi);
1932 * iommu_set_fault_handler() - set a fault handler for an iommu domain
1933 * @domain: iommu domain
1934 * @handler: fault handler
1935 * @token: user data, will be passed back to the fault handler
1937 * This function should be used by IOMMU users which want to be notified
1938 * whenever an IOMMU fault happens.
1940 * The fault handler itself should return 0 on success, and an appropriate
1941 * error code otherwise.
1943 void iommu_set_fault_handler(struct iommu_domain *domain,
1944 iommu_fault_handler_t handler,
1949 domain->handler = handler;
1950 domain->handler_token = token;
1952 EXPORT_SYMBOL_GPL(iommu_set_fault_handler);
1954 static struct iommu_domain *__iommu_domain_alloc(struct bus_type *bus,
1957 struct iommu_domain *domain;
1959 if (bus == NULL || bus->iommu_ops == NULL)
1962 domain = bus->iommu_ops->domain_alloc(type);
1966 domain->type = type;
1967 /* Assume all sizes by default; the driver may override this later */
1968 domain->pgsize_bitmap = bus->iommu_ops->pgsize_bitmap;
1970 domain->ops = bus->iommu_ops->default_domain_ops;
1972 if (iommu_is_dma_domain(domain) && iommu_get_dma_cookie(domain)) {
1973 iommu_domain_free(domain);
1979 struct iommu_domain *iommu_domain_alloc(struct bus_type *bus)
1981 return __iommu_domain_alloc(bus, IOMMU_DOMAIN_UNMANAGED);
1983 EXPORT_SYMBOL_GPL(iommu_domain_alloc);
1985 void iommu_domain_free(struct iommu_domain *domain)
1987 if (domain->type == IOMMU_DOMAIN_SVA)
1989 iommu_put_dma_cookie(domain);
1990 domain->ops->free(domain);
1992 EXPORT_SYMBOL_GPL(iommu_domain_free);
1995 * Put the group's domain back to the appropriate core-owned domain - either the
1996 * standard kernel-mode DMA configuration or an all-DMA-blocked domain.
1998 static void __iommu_group_set_core_domain(struct iommu_group *group)
2000 struct iommu_domain *new_domain;
2004 new_domain = group->blocking_domain;
2006 new_domain = group->default_domain;
2008 ret = __iommu_group_set_domain(group, new_domain);
2009 WARN(ret, "iommu driver failed to attach the default/blocking domain");
2012 static int __iommu_attach_device(struct iommu_domain *domain,
2017 if (unlikely(domain->ops->attach_dev == NULL))
2020 ret = domain->ops->attach_dev(domain, dev);
2023 dev->iommu->attach_deferred = 0;
2024 trace_attach_device_to_domain(dev);
2029 * iommu_attach_device - Attach an IOMMU domain to a device
2030 * @domain: IOMMU domain to attach
2031 * @dev: Device that will be attached
2033 * Returns 0 on success and error code on failure
2035 * Note that EINVAL can be treated as a soft failure, indicating
2036 * that certain configuration of the domain is incompatible with
2037 * the device. In this case attaching a different domain to the
2038 * device may succeed.
2040 int iommu_attach_device(struct iommu_domain *domain, struct device *dev)
2042 struct iommu_group *group;
2045 group = iommu_group_get(dev);
2050 * Lock the group to make sure the device-count doesn't
2051 * change while we are attaching
2053 mutex_lock(&group->mutex);
2055 if (iommu_group_device_count(group) != 1)
2058 ret = __iommu_attach_group(domain, group);
2061 mutex_unlock(&group->mutex);
2062 iommu_group_put(group);
2066 EXPORT_SYMBOL_GPL(iommu_attach_device);
2068 int iommu_deferred_attach(struct device *dev, struct iommu_domain *domain)
2070 if (dev->iommu && dev->iommu->attach_deferred)
2071 return __iommu_attach_device(domain, dev);
2076 void iommu_detach_device(struct iommu_domain *domain, struct device *dev)
2078 struct iommu_group *group;
2080 group = iommu_group_get(dev);
2084 mutex_lock(&group->mutex);
2085 if (WARN_ON(domain != group->domain) ||
2086 WARN_ON(iommu_group_device_count(group) != 1))
2088 __iommu_group_set_core_domain(group);
2091 mutex_unlock(&group->mutex);
2092 iommu_group_put(group);
2094 EXPORT_SYMBOL_GPL(iommu_detach_device);
2096 struct iommu_domain *iommu_get_domain_for_dev(struct device *dev)
2098 struct iommu_domain *domain;
2099 struct iommu_group *group;
2101 group = iommu_group_get(dev);
2105 domain = group->domain;
2107 iommu_group_put(group);
2111 EXPORT_SYMBOL_GPL(iommu_get_domain_for_dev);
2114 * For IOMMU_DOMAIN_DMA implementations which already provide their own
2115 * guarantees that the group and its default domain are valid and correct.
2117 struct iommu_domain *iommu_get_dma_domain(struct device *dev)
2119 return dev->iommu_group->default_domain;
2123 * IOMMU groups are really the natural working unit of the IOMMU, but
2124 * the IOMMU API works on domains and devices. Bridge that gap by
2125 * iterating over the devices in a group. Ideally we'd have a single
2126 * device which represents the requestor ID of the group, but we also
2127 * allow IOMMU drivers to create policy defined minimum sets, where
2128 * the physical hardware may be able to distiguish members, but we
2129 * wish to group them at a higher level (ex. untrusted multi-function
2130 * PCI devices). Thus we attach each device.
2132 static int iommu_group_do_attach_device(struct device *dev, void *data)
2134 struct iommu_domain *domain = data;
2136 return __iommu_attach_device(domain, dev);
2139 static int __iommu_attach_group(struct iommu_domain *domain,
2140 struct iommu_group *group)
2144 if (group->domain && group->domain != group->default_domain &&
2145 group->domain != group->blocking_domain)
2148 ret = __iommu_group_for_each_dev(group, domain,
2149 iommu_group_do_attach_device);
2151 group->domain = domain;
2154 * To recover from the case when certain device within the
2155 * group fails to attach to the new domain, we need force
2156 * attaching all devices back to the old domain. The old
2157 * domain is compatible for all devices in the group,
2158 * hence the iommu driver should always return success.
2160 struct iommu_domain *old_domain = group->domain;
2162 group->domain = NULL;
2163 WARN(__iommu_group_set_domain(group, old_domain),
2164 "iommu driver failed to attach a compatible domain");
2171 * iommu_attach_group - Attach an IOMMU domain to an IOMMU group
2172 * @domain: IOMMU domain to attach
2173 * @group: IOMMU group that will be attached
2175 * Returns 0 on success and error code on failure
2177 * Note that EINVAL can be treated as a soft failure, indicating
2178 * that certain configuration of the domain is incompatible with
2179 * the group. In this case attaching a different domain to the
2180 * group may succeed.
2182 int iommu_attach_group(struct iommu_domain *domain, struct iommu_group *group)
2186 mutex_lock(&group->mutex);
2187 ret = __iommu_attach_group(domain, group);
2188 mutex_unlock(&group->mutex);
2192 EXPORT_SYMBOL_GPL(iommu_attach_group);
2194 static int iommu_group_do_set_platform_dma(struct device *dev, void *data)
2196 const struct iommu_ops *ops = dev_iommu_ops(dev);
2198 if (!WARN_ON(!ops->set_platform_dma_ops))
2199 ops->set_platform_dma_ops(dev);
2204 static int __iommu_group_set_domain(struct iommu_group *group,
2205 struct iommu_domain *new_domain)
2209 if (group->domain == new_domain)
2213 * New drivers should support default domains, so set_platform_dma()
2214 * op will never be called. Otherwise the NULL domain represents some
2215 * platform specific behavior.
2218 __iommu_group_for_each_dev(group, NULL,
2219 iommu_group_do_set_platform_dma);
2220 group->domain = NULL;
2225 * Changing the domain is done by calling attach_dev() on the new
2226 * domain. This switch does not have to be atomic and DMA can be
2227 * discarded during the transition. DMA must only be able to access
2228 * either new_domain or group->domain, never something else.
2230 * Note that this is called in error unwind paths, attaching to a
2231 * domain that has already been attached cannot fail.
2233 ret = __iommu_group_for_each_dev(group, new_domain,
2234 iommu_group_do_attach_device);
2237 group->domain = new_domain;
2241 void iommu_detach_group(struct iommu_domain *domain, struct iommu_group *group)
2243 mutex_lock(&group->mutex);
2244 __iommu_group_set_core_domain(group);
2245 mutex_unlock(&group->mutex);
2247 EXPORT_SYMBOL_GPL(iommu_detach_group);
2249 phys_addr_t iommu_iova_to_phys(struct iommu_domain *domain, dma_addr_t iova)
2251 if (domain->type == IOMMU_DOMAIN_IDENTITY)
2254 if (domain->type == IOMMU_DOMAIN_BLOCKED)
2257 return domain->ops->iova_to_phys(domain, iova);
2259 EXPORT_SYMBOL_GPL(iommu_iova_to_phys);
2261 static size_t iommu_pgsize(struct iommu_domain *domain, unsigned long iova,
2262 phys_addr_t paddr, size_t size, size_t *count)
2264 unsigned int pgsize_idx, pgsize_idx_next;
2265 unsigned long pgsizes;
2266 size_t offset, pgsize, pgsize_next;
2267 unsigned long addr_merge = paddr | iova;
2269 /* Page sizes supported by the hardware and small enough for @size */
2270 pgsizes = domain->pgsize_bitmap & GENMASK(__fls(size), 0);
2272 /* Constrain the page sizes further based on the maximum alignment */
2273 if (likely(addr_merge))
2274 pgsizes &= GENMASK(__ffs(addr_merge), 0);
2276 /* Make sure we have at least one suitable page size */
2279 /* Pick the biggest page size remaining */
2280 pgsize_idx = __fls(pgsizes);
2281 pgsize = BIT(pgsize_idx);
2285 /* Find the next biggest support page size, if it exists */
2286 pgsizes = domain->pgsize_bitmap & ~GENMASK(pgsize_idx, 0);
2290 pgsize_idx_next = __ffs(pgsizes);
2291 pgsize_next = BIT(pgsize_idx_next);
2294 * There's no point trying a bigger page size unless the virtual
2295 * and physical addresses are similarly offset within the larger page.
2297 if ((iova ^ paddr) & (pgsize_next - 1))
2300 /* Calculate the offset to the next page size alignment boundary */
2301 offset = pgsize_next - (addr_merge & (pgsize_next - 1));
2304 * If size is big enough to accommodate the larger page, reduce
2305 * the number of smaller pages.
2307 if (offset + pgsize_next <= size)
2311 *count = size >> pgsize_idx;
2315 static int __iommu_map_pages(struct iommu_domain *domain, unsigned long iova,
2316 phys_addr_t paddr, size_t size, int prot,
2317 gfp_t gfp, size_t *mapped)
2319 const struct iommu_domain_ops *ops = domain->ops;
2320 size_t pgsize, count;
2323 pgsize = iommu_pgsize(domain, iova, paddr, size, &count);
2325 pr_debug("mapping: iova 0x%lx pa %pa pgsize 0x%zx count %zu\n",
2326 iova, &paddr, pgsize, count);
2328 if (ops->map_pages) {
2329 ret = ops->map_pages(domain, iova, paddr, pgsize, count, prot,
2332 ret = ops->map(domain, iova, paddr, pgsize, prot, gfp);
2333 *mapped = ret ? 0 : pgsize;
2339 static int __iommu_map(struct iommu_domain *domain, unsigned long iova,
2340 phys_addr_t paddr, size_t size, int prot, gfp_t gfp)
2342 const struct iommu_domain_ops *ops = domain->ops;
2343 unsigned long orig_iova = iova;
2344 unsigned int min_pagesz;
2345 size_t orig_size = size;
2346 phys_addr_t orig_paddr = paddr;
2349 if (unlikely(!(ops->map || ops->map_pages) ||
2350 domain->pgsize_bitmap == 0UL))
2353 if (unlikely(!(domain->type & __IOMMU_DOMAIN_PAGING)))
2356 /* find out the minimum page size supported */
2357 min_pagesz = 1 << __ffs(domain->pgsize_bitmap);
2360 * both the virtual address and the physical one, as well as
2361 * the size of the mapping, must be aligned (at least) to the
2362 * size of the smallest page supported by the hardware
2364 if (!IS_ALIGNED(iova | paddr | size, min_pagesz)) {
2365 pr_err("unaligned: iova 0x%lx pa %pa size 0x%zx min_pagesz 0x%x\n",
2366 iova, &paddr, size, min_pagesz);
2370 pr_debug("map: iova 0x%lx pa %pa size 0x%zx\n", iova, &paddr, size);
2375 ret = __iommu_map_pages(domain, iova, paddr, size, prot, gfp,
2378 * Some pages may have been mapped, even if an error occurred,
2379 * so we should account for those so they can be unmapped.
2390 /* unroll mapping in case something went wrong */
2392 iommu_unmap(domain, orig_iova, orig_size - size);
2394 trace_map(orig_iova, orig_paddr, orig_size);
2399 int iommu_map(struct iommu_domain *domain, unsigned long iova,
2400 phys_addr_t paddr, size_t size, int prot, gfp_t gfp)
2402 const struct iommu_domain_ops *ops = domain->ops;
2405 might_sleep_if(gfpflags_allow_blocking(gfp));
2407 /* Discourage passing strange GFP flags */
2408 if (WARN_ON_ONCE(gfp & (__GFP_COMP | __GFP_DMA | __GFP_DMA32 |
2412 ret = __iommu_map(domain, iova, paddr, size, prot, gfp);
2413 if (ret == 0 && ops->iotlb_sync_map)
2414 ops->iotlb_sync_map(domain, iova, size);
2418 EXPORT_SYMBOL_GPL(iommu_map);
2420 static size_t __iommu_unmap_pages(struct iommu_domain *domain,
2421 unsigned long iova, size_t size,
2422 struct iommu_iotlb_gather *iotlb_gather)
2424 const struct iommu_domain_ops *ops = domain->ops;
2425 size_t pgsize, count;
2427 pgsize = iommu_pgsize(domain, iova, iova, size, &count);
2428 return ops->unmap_pages ?
2429 ops->unmap_pages(domain, iova, pgsize, count, iotlb_gather) :
2430 ops->unmap(domain, iova, pgsize, iotlb_gather);
2433 static size_t __iommu_unmap(struct iommu_domain *domain,
2434 unsigned long iova, size_t size,
2435 struct iommu_iotlb_gather *iotlb_gather)
2437 const struct iommu_domain_ops *ops = domain->ops;
2438 size_t unmapped_page, unmapped = 0;
2439 unsigned long orig_iova = iova;
2440 unsigned int min_pagesz;
2442 if (unlikely(!(ops->unmap || ops->unmap_pages) ||
2443 domain->pgsize_bitmap == 0UL))
2446 if (unlikely(!(domain->type & __IOMMU_DOMAIN_PAGING)))
2449 /* find out the minimum page size supported */
2450 min_pagesz = 1 << __ffs(domain->pgsize_bitmap);
2453 * The virtual address, as well as the size of the mapping, must be
2454 * aligned (at least) to the size of the smallest page supported
2457 if (!IS_ALIGNED(iova | size, min_pagesz)) {
2458 pr_err("unaligned: iova 0x%lx size 0x%zx min_pagesz 0x%x\n",
2459 iova, size, min_pagesz);
2463 pr_debug("unmap this: iova 0x%lx size 0x%zx\n", iova, size);
2466 * Keep iterating until we either unmap 'size' bytes (or more)
2467 * or we hit an area that isn't mapped.
2469 while (unmapped < size) {
2470 unmapped_page = __iommu_unmap_pages(domain, iova,
2476 pr_debug("unmapped: iova 0x%lx size 0x%zx\n",
2477 iova, unmapped_page);
2479 iova += unmapped_page;
2480 unmapped += unmapped_page;
2483 trace_unmap(orig_iova, size, unmapped);
2487 size_t iommu_unmap(struct iommu_domain *domain,
2488 unsigned long iova, size_t size)
2490 struct iommu_iotlb_gather iotlb_gather;
2493 iommu_iotlb_gather_init(&iotlb_gather);
2494 ret = __iommu_unmap(domain, iova, size, &iotlb_gather);
2495 iommu_iotlb_sync(domain, &iotlb_gather);
2499 EXPORT_SYMBOL_GPL(iommu_unmap);
2501 size_t iommu_unmap_fast(struct iommu_domain *domain,
2502 unsigned long iova, size_t size,
2503 struct iommu_iotlb_gather *iotlb_gather)
2505 return __iommu_unmap(domain, iova, size, iotlb_gather);
2507 EXPORT_SYMBOL_GPL(iommu_unmap_fast);
2509 ssize_t iommu_map_sg(struct iommu_domain *domain, unsigned long iova,
2510 struct scatterlist *sg, unsigned int nents, int prot,
2513 const struct iommu_domain_ops *ops = domain->ops;
2514 size_t len = 0, mapped = 0;
2519 might_sleep_if(gfpflags_allow_blocking(gfp));
2521 /* Discourage passing strange GFP flags */
2522 if (WARN_ON_ONCE(gfp & (__GFP_COMP | __GFP_DMA | __GFP_DMA32 |
2526 while (i <= nents) {
2527 phys_addr_t s_phys = sg_phys(sg);
2529 if (len && s_phys != start + len) {
2530 ret = __iommu_map(domain, iova + mapped, start,
2540 if (sg_is_dma_bus_address(sg))
2555 if (ops->iotlb_sync_map)
2556 ops->iotlb_sync_map(domain, iova, mapped);
2560 /* undo mappings already done */
2561 iommu_unmap(domain, iova, mapped);
2565 EXPORT_SYMBOL_GPL(iommu_map_sg);
2568 * report_iommu_fault() - report about an IOMMU fault to the IOMMU framework
2569 * @domain: the iommu domain where the fault has happened
2570 * @dev: the device where the fault has happened
2571 * @iova: the faulting address
2572 * @flags: mmu fault flags (e.g. IOMMU_FAULT_READ/IOMMU_FAULT_WRITE/...)
2574 * This function should be called by the low-level IOMMU implementations
2575 * whenever IOMMU faults happen, to allow high-level users, that are
2576 * interested in such events, to know about them.
2578 * This event may be useful for several possible use cases:
2579 * - mere logging of the event
2580 * - dynamic TLB/PTE loading
2581 * - if restarting of the faulting device is required
2583 * Returns 0 on success and an appropriate error code otherwise (if dynamic
2584 * PTE/TLB loading will one day be supported, implementations will be able
2585 * to tell whether it succeeded or not according to this return value).
2587 * Specifically, -ENOSYS is returned if a fault handler isn't installed
2588 * (though fault handlers can also return -ENOSYS, in case they want to
2589 * elicit the default behavior of the IOMMU drivers).
2591 int report_iommu_fault(struct iommu_domain *domain, struct device *dev,
2592 unsigned long iova, int flags)
2597 * if upper layers showed interest and installed a fault handler,
2600 if (domain->handler)
2601 ret = domain->handler(domain, dev, iova, flags,
2602 domain->handler_token);
2604 trace_io_page_fault(dev, iova, flags);
2607 EXPORT_SYMBOL_GPL(report_iommu_fault);
2609 static int __init iommu_init(void)
2611 iommu_group_kset = kset_create_and_add("iommu_groups",
2613 BUG_ON(!iommu_group_kset);
2615 iommu_debugfs_setup();
2619 core_initcall(iommu_init);
2621 int iommu_enable_nesting(struct iommu_domain *domain)
2623 if (domain->type != IOMMU_DOMAIN_UNMANAGED)
2625 if (!domain->ops->enable_nesting)
2627 return domain->ops->enable_nesting(domain);
2629 EXPORT_SYMBOL_GPL(iommu_enable_nesting);
2631 int iommu_set_pgtable_quirks(struct iommu_domain *domain,
2632 unsigned long quirk)
2634 if (domain->type != IOMMU_DOMAIN_UNMANAGED)
2636 if (!domain->ops->set_pgtable_quirks)
2638 return domain->ops->set_pgtable_quirks(domain, quirk);
2640 EXPORT_SYMBOL_GPL(iommu_set_pgtable_quirks);
2642 void iommu_get_resv_regions(struct device *dev, struct list_head *list)
2644 const struct iommu_ops *ops = dev_iommu_ops(dev);
2646 if (ops->get_resv_regions)
2647 ops->get_resv_regions(dev, list);
2651 * iommu_put_resv_regions - release resered regions
2652 * @dev: device for which to free reserved regions
2653 * @list: reserved region list for device
2655 * This releases a reserved region list acquired by iommu_get_resv_regions().
2657 void iommu_put_resv_regions(struct device *dev, struct list_head *list)
2659 struct iommu_resv_region *entry, *next;
2661 list_for_each_entry_safe(entry, next, list, list) {
2663 entry->free(dev, entry);
2668 EXPORT_SYMBOL(iommu_put_resv_regions);
2670 struct iommu_resv_region *iommu_alloc_resv_region(phys_addr_t start,
2671 size_t length, int prot,
2672 enum iommu_resv_type type,
2675 struct iommu_resv_region *region;
2677 region = kzalloc(sizeof(*region), gfp);
2681 INIT_LIST_HEAD(®ion->list);
2682 region->start = start;
2683 region->length = length;
2684 region->prot = prot;
2685 region->type = type;
2688 EXPORT_SYMBOL_GPL(iommu_alloc_resv_region);
2690 void iommu_set_default_passthrough(bool cmd_line)
2693 iommu_cmd_line |= IOMMU_CMD_LINE_DMA_API;
2694 iommu_def_domain_type = IOMMU_DOMAIN_IDENTITY;
2697 void iommu_set_default_translated(bool cmd_line)
2700 iommu_cmd_line |= IOMMU_CMD_LINE_DMA_API;
2701 iommu_def_domain_type = IOMMU_DOMAIN_DMA;
2704 bool iommu_default_passthrough(void)
2706 return iommu_def_domain_type == IOMMU_DOMAIN_IDENTITY;
2708 EXPORT_SYMBOL_GPL(iommu_default_passthrough);
2710 const struct iommu_ops *iommu_ops_from_fwnode(struct fwnode_handle *fwnode)
2712 const struct iommu_ops *ops = NULL;
2713 struct iommu_device *iommu;
2715 spin_lock(&iommu_device_lock);
2716 list_for_each_entry(iommu, &iommu_device_list, list)
2717 if (iommu->fwnode == fwnode) {
2721 spin_unlock(&iommu_device_lock);
2725 int iommu_fwspec_init(struct device *dev, struct fwnode_handle *iommu_fwnode,
2726 const struct iommu_ops *ops)
2728 struct iommu_fwspec *fwspec = dev_iommu_fwspec_get(dev);
2731 return ops == fwspec->ops ? 0 : -EINVAL;
2733 if (!dev_iommu_get(dev))
2736 /* Preallocate for the overwhelmingly common case of 1 ID */
2737 fwspec = kzalloc(struct_size(fwspec, ids, 1), GFP_KERNEL);
2741 of_node_get(to_of_node(iommu_fwnode));
2742 fwspec->iommu_fwnode = iommu_fwnode;
2744 dev_iommu_fwspec_set(dev, fwspec);
2747 EXPORT_SYMBOL_GPL(iommu_fwspec_init);
2749 void iommu_fwspec_free(struct device *dev)
2751 struct iommu_fwspec *fwspec = dev_iommu_fwspec_get(dev);
2754 fwnode_handle_put(fwspec->iommu_fwnode);
2756 dev_iommu_fwspec_set(dev, NULL);
2759 EXPORT_SYMBOL_GPL(iommu_fwspec_free);
2761 int iommu_fwspec_add_ids(struct device *dev, u32 *ids, int num_ids)
2763 struct iommu_fwspec *fwspec = dev_iommu_fwspec_get(dev);
2769 new_num = fwspec->num_ids + num_ids;
2771 fwspec = krealloc(fwspec, struct_size(fwspec, ids, new_num),
2776 dev_iommu_fwspec_set(dev, fwspec);
2779 for (i = 0; i < num_ids; i++)
2780 fwspec->ids[fwspec->num_ids + i] = ids[i];
2782 fwspec->num_ids = new_num;
2785 EXPORT_SYMBOL_GPL(iommu_fwspec_add_ids);
2788 * Per device IOMMU features.
2790 int iommu_dev_enable_feature(struct device *dev, enum iommu_dev_features feat)
2792 if (dev->iommu && dev->iommu->iommu_dev) {
2793 const struct iommu_ops *ops = dev->iommu->iommu_dev->ops;
2795 if (ops->dev_enable_feat)
2796 return ops->dev_enable_feat(dev, feat);
2801 EXPORT_SYMBOL_GPL(iommu_dev_enable_feature);
2804 * The device drivers should do the necessary cleanups before calling this.
2806 int iommu_dev_disable_feature(struct device *dev, enum iommu_dev_features feat)
2808 if (dev->iommu && dev->iommu->iommu_dev) {
2809 const struct iommu_ops *ops = dev->iommu->iommu_dev->ops;
2811 if (ops->dev_disable_feat)
2812 return ops->dev_disable_feat(dev, feat);
2817 EXPORT_SYMBOL_GPL(iommu_dev_disable_feature);
2820 * Changes the default domain of an iommu group that has *only* one device
2822 * @group: The group for which the default domain should be changed
2823 * @prev_dev: The device in the group (this is used to make sure that the device
2824 * hasn't changed after the caller has called this function)
2825 * @type: The type of the new default domain that gets associated with the group
2827 * Returns 0 on success and error code on failure
2830 * 1. Presently, this function is called only when user requests to change the
2831 * group's default domain type through /sys/kernel/iommu_groups/<grp_id>/type
2832 * Please take a closer look if intended to use for other purposes.
2834 static int iommu_change_dev_def_domain(struct iommu_group *group,
2835 struct device *prev_dev, int type)
2837 struct iommu_domain *prev_dom;
2838 struct group_device *grp_dev;
2839 int ret, dev_def_dom;
2842 mutex_lock(&group->mutex);
2844 if (group->default_domain != group->domain) {
2845 dev_err_ratelimited(prev_dev, "Group not assigned to default domain\n");
2851 * iommu group wasn't locked while acquiring device lock in
2852 * iommu_group_store_type(). So, make sure that the device count hasn't
2853 * changed while acquiring device lock.
2855 * Changing default domain of an iommu group with two or more devices
2856 * isn't supported because there could be a potential deadlock. Consider
2857 * the following scenario. T1 is trying to acquire device locks of all
2858 * the devices in the group and before it could acquire all of them,
2859 * there could be another thread T2 (from different sub-system and use
2860 * case) that has already acquired some of the device locks and might be
2861 * waiting for T1 to release other device locks.
2863 if (iommu_group_device_count(group) != 1) {
2864 dev_err_ratelimited(prev_dev, "Cannot change default domain: Group has more than one device\n");
2869 /* Since group has only one device */
2870 grp_dev = list_first_entry(&group->devices, struct group_device, list);
2873 if (prev_dev != dev) {
2874 dev_err_ratelimited(prev_dev, "Cannot change default domain: Device has been changed\n");
2879 prev_dom = group->default_domain;
2885 dev_def_dom = iommu_get_def_domain_type(dev);
2888 * If the user hasn't requested any specific type of domain and
2889 * if the device supports both the domains, then default to the
2890 * domain the device was booted with
2892 type = dev_def_dom ? : iommu_def_domain_type;
2893 } else if (dev_def_dom && type != dev_def_dom) {
2894 dev_err_ratelimited(prev_dev, "Device cannot be in %s domain\n",
2895 iommu_domain_type_str(type));
2901 * Switch to a new domain only if the requested domain type is different
2902 * from the existing default domain type
2904 if (prev_dom->type == type) {
2909 /* We can bring up a flush queue without tearing down the domain */
2910 if (type == IOMMU_DOMAIN_DMA_FQ && prev_dom->type == IOMMU_DOMAIN_DMA) {
2911 ret = iommu_dma_init_fq(prev_dom);
2913 prev_dom->type = IOMMU_DOMAIN_DMA_FQ;
2917 /* Sets group->default_domain to the newly allocated domain */
2918 ret = iommu_group_alloc_default_domain(dev->bus, group, type);
2922 ret = iommu_create_device_direct_mappings(group, dev);
2924 goto free_new_domain;
2926 ret = __iommu_attach_device(group->default_domain, dev);
2928 goto free_new_domain;
2930 group->domain = group->default_domain;
2933 * Release the mutex here because ops->probe_finalize() call-back of
2934 * some vendor IOMMU drivers calls arm_iommu_attach_device() which
2935 * in-turn might call back into IOMMU core code, where it tries to take
2936 * group->mutex, resulting in a deadlock.
2938 mutex_unlock(&group->mutex);
2940 /* Make sure dma_ops is appropriatley set */
2941 iommu_group_do_probe_finalize(dev, group->default_domain);
2942 iommu_domain_free(prev_dom);
2946 iommu_domain_free(group->default_domain);
2947 group->default_domain = prev_dom;
2948 group->domain = prev_dom;
2951 mutex_unlock(&group->mutex);
2957 * Changing the default domain through sysfs requires the users to unbind the
2958 * drivers from the devices in the iommu group, except for a DMA -> DMA-FQ
2959 * transition. Return failure if this isn't met.
2961 * We need to consider the race between this and the device release path.
2962 * device_lock(dev) is used here to guarantee that the device release path
2963 * will not be entered at the same time.
2965 static ssize_t iommu_group_store_type(struct iommu_group *group,
2966 const char *buf, size_t count)
2968 struct group_device *grp_dev;
2972 if (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO))
2975 if (WARN_ON(!group) || !group->default_domain)
2978 if (sysfs_streq(buf, "identity"))
2979 req_type = IOMMU_DOMAIN_IDENTITY;
2980 else if (sysfs_streq(buf, "DMA"))
2981 req_type = IOMMU_DOMAIN_DMA;
2982 else if (sysfs_streq(buf, "DMA-FQ"))
2983 req_type = IOMMU_DOMAIN_DMA_FQ;
2984 else if (sysfs_streq(buf, "auto"))
2990 * Lock/Unlock the group mutex here before device lock to
2991 * 1. Make sure that the iommu group has only one device (this is a
2992 * prerequisite for step 2)
2993 * 2. Get struct *dev which is needed to lock device
2995 mutex_lock(&group->mutex);
2996 if (iommu_group_device_count(group) != 1) {
2997 mutex_unlock(&group->mutex);
2998 pr_err_ratelimited("Cannot change default domain: Group has more than one device\n");
3002 /* Since group has only one device */
3003 grp_dev = list_first_entry(&group->devices, struct group_device, list);
3008 * Don't hold the group mutex because taking group mutex first and then
3009 * the device lock could potentially cause a deadlock as below. Assume
3010 * two threads T1 and T2. T1 is trying to change default domain of an
3011 * iommu group and T2 is trying to hot unplug a device or release [1] VF
3012 * of a PCIe device which is in the same iommu group. T1 takes group
3013 * mutex and before it could take device lock assume T2 has taken device
3014 * lock and is yet to take group mutex. Now, both the threads will be
3015 * waiting for the other thread to release lock. Below, lock order was
3018 * mutex_lock(&group->mutex);
3019 * iommu_change_dev_def_domain();
3020 * mutex_unlock(&group->mutex);
3021 * device_unlock(dev);
3023 * [1] Typical device release path
3024 * device_lock() from device/driver core code
3026 * -> iommu_bus_notifier()
3027 * -> iommu_release_device()
3028 * -> ops->release_device() vendor driver calls back iommu core code
3029 * -> mutex_lock() from iommu core code
3031 mutex_unlock(&group->mutex);
3033 /* Check if the device in the group still has a driver bound to it */
3035 if (device_is_bound(dev) && !(req_type == IOMMU_DOMAIN_DMA_FQ &&
3036 group->default_domain->type == IOMMU_DOMAIN_DMA)) {
3037 pr_err_ratelimited("Device is still bound to driver\n");
3042 ret = iommu_change_dev_def_domain(group, dev, req_type);
3052 static bool iommu_is_default_domain(struct iommu_group *group)
3054 if (group->domain == group->default_domain)
3058 * If the default domain was set to identity and it is still an identity
3059 * domain then we consider this a pass. This happens because of
3060 * amd_iommu_init_device() replacing the default idenytity domain with an
3061 * identity domain that has a different configuration for AMDGPU.
3063 if (group->default_domain &&
3064 group->default_domain->type == IOMMU_DOMAIN_IDENTITY &&
3065 group->domain && group->domain->type == IOMMU_DOMAIN_IDENTITY)
3071 * iommu_device_use_default_domain() - Device driver wants to handle device
3072 * DMA through the kernel DMA API.
3075 * The device driver about to bind @dev wants to do DMA through the kernel
3076 * DMA API. Return 0 if it is allowed, otherwise an error.
3078 int iommu_device_use_default_domain(struct device *dev)
3080 struct iommu_group *group = iommu_group_get(dev);
3086 mutex_lock(&group->mutex);
3087 if (group->owner_cnt) {
3088 if (group->owner || !iommu_is_default_domain(group) ||
3089 !xa_empty(&group->pasid_array)) {
3098 mutex_unlock(&group->mutex);
3099 iommu_group_put(group);
3105 * iommu_device_unuse_default_domain() - Device driver stops handling device
3106 * DMA through the kernel DMA API.
3109 * The device driver doesn't want to do DMA through kernel DMA API anymore.
3110 * It must be called after iommu_device_use_default_domain().
3112 void iommu_device_unuse_default_domain(struct device *dev)
3114 struct iommu_group *group = iommu_group_get(dev);
3119 mutex_lock(&group->mutex);
3120 if (!WARN_ON(!group->owner_cnt || !xa_empty(&group->pasid_array)))
3123 mutex_unlock(&group->mutex);
3124 iommu_group_put(group);
3127 static int __iommu_group_alloc_blocking_domain(struct iommu_group *group)
3129 struct group_device *dev =
3130 list_first_entry(&group->devices, struct group_device, list);
3132 if (group->blocking_domain)
3135 group->blocking_domain =
3136 __iommu_domain_alloc(dev->dev->bus, IOMMU_DOMAIN_BLOCKED);
3137 if (!group->blocking_domain) {
3139 * For drivers that do not yet understand IOMMU_DOMAIN_BLOCKED
3140 * create an empty domain instead.
3142 group->blocking_domain = __iommu_domain_alloc(
3143 dev->dev->bus, IOMMU_DOMAIN_UNMANAGED);
3144 if (!group->blocking_domain)
3150 static int __iommu_take_dma_ownership(struct iommu_group *group, void *owner)
3154 if ((group->domain && group->domain != group->default_domain) ||
3155 !xa_empty(&group->pasid_array))
3158 ret = __iommu_group_alloc_blocking_domain(group);
3161 ret = __iommu_group_set_domain(group, group->blocking_domain);
3165 group->owner = owner;
3171 * iommu_group_claim_dma_owner() - Set DMA ownership of a group
3172 * @group: The group.
3173 * @owner: Caller specified pointer. Used for exclusive ownership.
3175 * This is to support backward compatibility for vfio which manages the dma
3176 * ownership in iommu_group level. New invocations on this interface should be
3177 * prohibited. Only a single owner may exist for a group.
3179 int iommu_group_claim_dma_owner(struct iommu_group *group, void *owner)
3183 if (WARN_ON(!owner))
3186 mutex_lock(&group->mutex);
3187 if (group->owner_cnt) {
3192 ret = __iommu_take_dma_ownership(group, owner);
3194 mutex_unlock(&group->mutex);
3198 EXPORT_SYMBOL_GPL(iommu_group_claim_dma_owner);
3201 * iommu_device_claim_dma_owner() - Set DMA ownership of a device
3203 * @owner: Caller specified pointer. Used for exclusive ownership.
3205 * Claim the DMA ownership of a device. Multiple devices in the same group may
3206 * concurrently claim ownership if they present the same owner value. Returns 0
3207 * on success and error code on failure
3209 int iommu_device_claim_dma_owner(struct device *dev, void *owner)
3211 struct iommu_group *group;
3214 if (WARN_ON(!owner))
3217 group = iommu_group_get(dev);
3221 mutex_lock(&group->mutex);
3222 if (group->owner_cnt) {
3223 if (group->owner != owner) {
3231 ret = __iommu_take_dma_ownership(group, owner);
3233 mutex_unlock(&group->mutex);
3234 iommu_group_put(group);
3238 EXPORT_SYMBOL_GPL(iommu_device_claim_dma_owner);
3240 static void __iommu_release_dma_ownership(struct iommu_group *group)
3244 if (WARN_ON(!group->owner_cnt || !group->owner ||
3245 !xa_empty(&group->pasid_array)))
3248 group->owner_cnt = 0;
3249 group->owner = NULL;
3250 ret = __iommu_group_set_domain(group, group->default_domain);
3251 WARN(ret, "iommu driver failed to attach the default domain");
3255 * iommu_group_release_dma_owner() - Release DMA ownership of a group
3258 * Release the DMA ownership claimed by iommu_group_claim_dma_owner().
3260 void iommu_group_release_dma_owner(struct iommu_group *group)
3262 mutex_lock(&group->mutex);
3263 __iommu_release_dma_ownership(group);
3264 mutex_unlock(&group->mutex);
3266 EXPORT_SYMBOL_GPL(iommu_group_release_dma_owner);
3269 * iommu_device_release_dma_owner() - Release DMA ownership of a device
3270 * @group: The device.
3272 * Release the DMA ownership claimed by iommu_device_claim_dma_owner().
3274 void iommu_device_release_dma_owner(struct device *dev)
3276 struct iommu_group *group = iommu_group_get(dev);
3278 mutex_lock(&group->mutex);
3279 if (group->owner_cnt > 1)
3282 __iommu_release_dma_ownership(group);
3283 mutex_unlock(&group->mutex);
3284 iommu_group_put(group);
3286 EXPORT_SYMBOL_GPL(iommu_device_release_dma_owner);
3289 * iommu_group_dma_owner_claimed() - Query group dma ownership status
3290 * @group: The group.
3292 * This provides status query on a given group. It is racy and only for
3293 * non-binding status reporting.
3295 bool iommu_group_dma_owner_claimed(struct iommu_group *group)
3299 mutex_lock(&group->mutex);
3300 user = group->owner_cnt;
3301 mutex_unlock(&group->mutex);
3305 EXPORT_SYMBOL_GPL(iommu_group_dma_owner_claimed);
3307 static int __iommu_set_group_pasid(struct iommu_domain *domain,
3308 struct iommu_group *group, ioasid_t pasid)
3310 struct group_device *device;
3313 list_for_each_entry(device, &group->devices, list) {
3314 ret = domain->ops->set_dev_pasid(domain, device->dev, pasid);
3322 static void __iommu_remove_group_pasid(struct iommu_group *group,
3325 struct group_device *device;
3326 const struct iommu_ops *ops;
3328 list_for_each_entry(device, &group->devices, list) {
3329 ops = dev_iommu_ops(device->dev);
3330 ops->remove_dev_pasid(device->dev, pasid);
3335 * iommu_attach_device_pasid() - Attach a domain to pasid of device
3336 * @domain: the iommu domain.
3337 * @dev: the attached device.
3338 * @pasid: the pasid of the device.
3340 * Return: 0 on success, or an error.
3342 int iommu_attach_device_pasid(struct iommu_domain *domain,
3343 struct device *dev, ioasid_t pasid)
3345 struct iommu_group *group;
3349 if (!domain->ops->set_dev_pasid)
3352 group = iommu_group_get(dev);
3356 mutex_lock(&group->mutex);
3357 curr = xa_cmpxchg(&group->pasid_array, pasid, NULL, domain, GFP_KERNEL);
3359 ret = xa_err(curr) ? : -EBUSY;
3363 ret = __iommu_set_group_pasid(domain, group, pasid);
3365 __iommu_remove_group_pasid(group, pasid);
3366 xa_erase(&group->pasid_array, pasid);
3369 mutex_unlock(&group->mutex);
3370 iommu_group_put(group);
3374 EXPORT_SYMBOL_GPL(iommu_attach_device_pasid);
3377 * iommu_detach_device_pasid() - Detach the domain from pasid of device
3378 * @domain: the iommu domain.
3379 * @dev: the attached device.
3380 * @pasid: the pasid of the device.
3382 * The @domain must have been attached to @pasid of the @dev with
3383 * iommu_attach_device_pasid().
3385 void iommu_detach_device_pasid(struct iommu_domain *domain, struct device *dev,
3388 struct iommu_group *group = iommu_group_get(dev);
3390 mutex_lock(&group->mutex);
3391 __iommu_remove_group_pasid(group, pasid);
3392 WARN_ON(xa_erase(&group->pasid_array, pasid) != domain);
3393 mutex_unlock(&group->mutex);
3395 iommu_group_put(group);
3397 EXPORT_SYMBOL_GPL(iommu_detach_device_pasid);
3400 * iommu_get_domain_for_dev_pasid() - Retrieve domain for @pasid of @dev
3401 * @dev: the queried device
3402 * @pasid: the pasid of the device
3403 * @type: matched domain type, 0 for any match
3405 * This is a variant of iommu_get_domain_for_dev(). It returns the existing
3406 * domain attached to pasid of a device. Callers must hold a lock around this
3407 * function, and both iommu_attach/detach_dev_pasid() whenever a domain of
3408 * type is being manipulated. This API does not internally resolve races with
3411 * Return: attached domain on success, NULL otherwise.
3413 struct iommu_domain *iommu_get_domain_for_dev_pasid(struct device *dev,
3417 struct iommu_domain *domain;
3418 struct iommu_group *group;
3420 group = iommu_group_get(dev);
3424 xa_lock(&group->pasid_array);
3425 domain = xa_load(&group->pasid_array, pasid);
3426 if (type && domain && domain->type != type)
3427 domain = ERR_PTR(-EBUSY);
3428 xa_unlock(&group->pasid_array);
3429 iommu_group_put(group);
3433 EXPORT_SYMBOL_GPL(iommu_get_domain_for_dev_pasid);
3435 struct iommu_domain *iommu_sva_domain_alloc(struct device *dev,
3436 struct mm_struct *mm)
3438 const struct iommu_ops *ops = dev_iommu_ops(dev);
3439 struct iommu_domain *domain;
3441 domain = ops->domain_alloc(IOMMU_DOMAIN_SVA);
3445 domain->type = IOMMU_DOMAIN_SVA;
3448 domain->iopf_handler = iommu_sva_handle_iopf;
3449 domain->fault_data = mm;