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/bitops.h>
25 #include <linux/platform_device.h>
26 #include <linux/property.h>
27 #include <linux/fsl/mc.h>
28 #include <linux/module.h>
29 #include <linux/cc_platform.h>
30 #include <trace/events/iommu.h>
32 #include "dma-iommu.h"
34 static struct kset *iommu_group_kset;
35 static DEFINE_IDA(iommu_group_ida);
37 static unsigned int iommu_def_domain_type __read_mostly;
38 static bool iommu_dma_strict __read_mostly = IS_ENABLED(CONFIG_IOMMU_DEFAULT_DMA_STRICT);
39 static u32 iommu_cmd_line __read_mostly;
43 struct kobject *devices_kobj;
44 struct list_head devices;
47 void (*iommu_data_release)(void *iommu_data);
50 struct iommu_domain *default_domain;
51 struct iommu_domain *blocking_domain;
52 struct iommu_domain *domain;
53 struct list_head entry;
54 unsigned int owner_cnt;
59 struct list_head list;
64 struct iommu_group_attribute {
65 struct attribute attr;
66 ssize_t (*show)(struct iommu_group *group, char *buf);
67 ssize_t (*store)(struct iommu_group *group,
68 const char *buf, size_t count);
71 static const char * const iommu_group_resv_type_string[] = {
72 [IOMMU_RESV_DIRECT] = "direct",
73 [IOMMU_RESV_DIRECT_RELAXABLE] = "direct-relaxable",
74 [IOMMU_RESV_RESERVED] = "reserved",
75 [IOMMU_RESV_MSI] = "msi",
76 [IOMMU_RESV_SW_MSI] = "msi",
79 #define IOMMU_CMD_LINE_DMA_API BIT(0)
80 #define IOMMU_CMD_LINE_STRICT BIT(1)
82 static int iommu_bus_notifier(struct notifier_block *nb,
83 unsigned long action, void *data);
84 static int iommu_alloc_default_domain(struct iommu_group *group,
86 static struct iommu_domain *__iommu_domain_alloc(struct bus_type *bus,
88 static int __iommu_attach_device(struct iommu_domain *domain,
90 static int __iommu_attach_group(struct iommu_domain *domain,
91 struct iommu_group *group);
92 static int __iommu_group_set_domain(struct iommu_group *group,
93 struct iommu_domain *new_domain);
94 static int iommu_create_device_direct_mappings(struct iommu_group *group,
96 static struct iommu_group *iommu_group_get_for_dev(struct device *dev);
97 static ssize_t iommu_group_store_type(struct iommu_group *group,
98 const char *buf, size_t count);
100 #define IOMMU_GROUP_ATTR(_name, _mode, _show, _store) \
101 struct iommu_group_attribute iommu_group_attr_##_name = \
102 __ATTR(_name, _mode, _show, _store)
104 #define to_iommu_group_attr(_attr) \
105 container_of(_attr, struct iommu_group_attribute, attr)
106 #define to_iommu_group(_kobj) \
107 container_of(_kobj, struct iommu_group, kobj)
109 static LIST_HEAD(iommu_device_list);
110 static DEFINE_SPINLOCK(iommu_device_lock);
112 static struct bus_type * const iommu_buses[] = {
117 #ifdef CONFIG_ARM_AMBA
120 #ifdef CONFIG_FSL_MC_BUS
123 #ifdef CONFIG_TEGRA_HOST1X_CONTEXT_BUS
124 &host1x_context_device_bus_type,
129 * Use a function instead of an array here because the domain-type is a
130 * bit-field, so an array would waste memory.
132 static const char *iommu_domain_type_str(unsigned int t)
135 case IOMMU_DOMAIN_BLOCKED:
137 case IOMMU_DOMAIN_IDENTITY:
138 return "Passthrough";
139 case IOMMU_DOMAIN_UNMANAGED:
141 case IOMMU_DOMAIN_DMA:
142 case IOMMU_DOMAIN_DMA_FQ:
149 static int __init iommu_subsys_init(void)
151 struct notifier_block *nb;
153 if (!(iommu_cmd_line & IOMMU_CMD_LINE_DMA_API)) {
154 if (IS_ENABLED(CONFIG_IOMMU_DEFAULT_PASSTHROUGH))
155 iommu_set_default_passthrough(false);
157 iommu_set_default_translated(false);
159 if (iommu_default_passthrough() && cc_platform_has(CC_ATTR_MEM_ENCRYPT)) {
160 pr_info("Memory encryption detected - Disabling default IOMMU Passthrough\n");
161 iommu_set_default_translated(false);
165 if (!iommu_default_passthrough() && !iommu_dma_strict)
166 iommu_def_domain_type = IOMMU_DOMAIN_DMA_FQ;
168 pr_info("Default domain type: %s %s\n",
169 iommu_domain_type_str(iommu_def_domain_type),
170 (iommu_cmd_line & IOMMU_CMD_LINE_DMA_API) ?
171 "(set via kernel command line)" : "");
173 if (!iommu_default_passthrough())
174 pr_info("DMA domain TLB invalidation policy: %s mode %s\n",
175 iommu_dma_strict ? "strict" : "lazy",
176 (iommu_cmd_line & IOMMU_CMD_LINE_STRICT) ?
177 "(set via kernel command line)" : "");
179 nb = kcalloc(ARRAY_SIZE(iommu_buses), sizeof(*nb), GFP_KERNEL);
183 for (int i = 0; i < ARRAY_SIZE(iommu_buses); i++) {
184 nb[i].notifier_call = iommu_bus_notifier;
185 bus_register_notifier(iommu_buses[i], &nb[i]);
190 subsys_initcall(iommu_subsys_init);
192 static int remove_iommu_group(struct device *dev, void *data)
194 if (dev->iommu && dev->iommu->iommu_dev == data)
195 iommu_release_device(dev);
201 * iommu_device_register() - Register an IOMMU hardware instance
202 * @iommu: IOMMU handle for the instance
203 * @ops: IOMMU ops to associate with the instance
204 * @hwdev: (optional) actual instance device, used for fwnode lookup
206 * Return: 0 on success, or an error.
208 int iommu_device_register(struct iommu_device *iommu,
209 const struct iommu_ops *ops, struct device *hwdev)
213 /* We need to be able to take module references appropriately */
214 if (WARN_ON(is_module_address((unsigned long)ops) && !ops->owner))
217 * Temporarily enforce global restriction to a single driver. This was
218 * already the de-facto behaviour, since any possible combination of
219 * existing drivers would compete for at least the PCI or platform bus.
221 if (iommu_buses[0]->iommu_ops && iommu_buses[0]->iommu_ops != ops)
226 iommu->fwnode = dev_fwnode(hwdev);
228 spin_lock(&iommu_device_lock);
229 list_add_tail(&iommu->list, &iommu_device_list);
230 spin_unlock(&iommu_device_lock);
232 for (int i = 0; i < ARRAY_SIZE(iommu_buses) && !err; i++) {
233 iommu_buses[i]->iommu_ops = ops;
234 err = bus_iommu_probe(iommu_buses[i]);
237 iommu_device_unregister(iommu);
240 EXPORT_SYMBOL_GPL(iommu_device_register);
242 void iommu_device_unregister(struct iommu_device *iommu)
244 for (int i = 0; i < ARRAY_SIZE(iommu_buses); i++)
245 bus_for_each_dev(iommu_buses[i], NULL, iommu, remove_iommu_group);
247 spin_lock(&iommu_device_lock);
248 list_del(&iommu->list);
249 spin_unlock(&iommu_device_lock);
251 EXPORT_SYMBOL_GPL(iommu_device_unregister);
253 static struct dev_iommu *dev_iommu_get(struct device *dev)
255 struct dev_iommu *param = dev->iommu;
260 param = kzalloc(sizeof(*param), GFP_KERNEL);
264 mutex_init(¶m->lock);
269 static void dev_iommu_free(struct device *dev)
271 struct dev_iommu *param = dev->iommu;
275 fwnode_handle_put(param->fwspec->iommu_fwnode);
276 kfree(param->fwspec);
281 static int __iommu_probe_device(struct device *dev, struct list_head *group_list)
283 const struct iommu_ops *ops = dev->bus->iommu_ops;
284 struct iommu_device *iommu_dev;
285 struct iommu_group *group;
291 if (!dev_iommu_get(dev))
294 if (!try_module_get(ops->owner)) {
299 iommu_dev = ops->probe_device(dev);
300 if (IS_ERR(iommu_dev)) {
301 ret = PTR_ERR(iommu_dev);
305 dev->iommu->iommu_dev = iommu_dev;
307 group = iommu_group_get_for_dev(dev);
309 ret = PTR_ERR(group);
312 iommu_group_put(group);
314 if (group_list && !group->default_domain && list_empty(&group->entry))
315 list_add_tail(&group->entry, group_list);
317 iommu_device_link(iommu_dev, dev);
322 if (ops->release_device)
323 ops->release_device(dev);
326 module_put(ops->owner);
334 int iommu_probe_device(struct device *dev)
336 const struct iommu_ops *ops;
337 struct iommu_group *group;
340 ret = __iommu_probe_device(dev, NULL);
344 group = iommu_group_get(dev);
351 * Try to allocate a default domain - needs support from the
352 * IOMMU driver. There are still some drivers which don't
353 * support default domains, so the return value is not yet
356 mutex_lock(&group->mutex);
357 iommu_alloc_default_domain(group, dev);
360 * If device joined an existing group which has been claimed, don't
361 * attach the default domain.
363 if (group->default_domain && !group->owner) {
364 ret = __iommu_attach_device(group->default_domain, dev);
366 mutex_unlock(&group->mutex);
367 iommu_group_put(group);
372 iommu_create_device_direct_mappings(group, dev);
374 mutex_unlock(&group->mutex);
375 iommu_group_put(group);
377 ops = dev_iommu_ops(dev);
378 if (ops->probe_finalize)
379 ops->probe_finalize(dev);
384 iommu_release_device(dev);
391 void iommu_release_device(struct device *dev)
393 const struct iommu_ops *ops;
398 iommu_device_unlink(dev->iommu->iommu_dev, dev);
400 ops = dev_iommu_ops(dev);
401 if (ops->release_device)
402 ops->release_device(dev);
404 iommu_group_remove_device(dev);
405 module_put(ops->owner);
409 static int __init iommu_set_def_domain_type(char *str)
414 ret = kstrtobool(str, &pt);
419 iommu_set_default_passthrough(true);
421 iommu_set_default_translated(true);
425 early_param("iommu.passthrough", iommu_set_def_domain_type);
427 static int __init iommu_dma_setup(char *str)
429 int ret = kstrtobool(str, &iommu_dma_strict);
432 iommu_cmd_line |= IOMMU_CMD_LINE_STRICT;
435 early_param("iommu.strict", iommu_dma_setup);
437 void iommu_set_dma_strict(void)
439 iommu_dma_strict = true;
440 if (iommu_def_domain_type == IOMMU_DOMAIN_DMA_FQ)
441 iommu_def_domain_type = IOMMU_DOMAIN_DMA;
444 static ssize_t iommu_group_attr_show(struct kobject *kobj,
445 struct attribute *__attr, char *buf)
447 struct iommu_group_attribute *attr = to_iommu_group_attr(__attr);
448 struct iommu_group *group = to_iommu_group(kobj);
452 ret = attr->show(group, buf);
456 static ssize_t iommu_group_attr_store(struct kobject *kobj,
457 struct attribute *__attr,
458 const char *buf, size_t count)
460 struct iommu_group_attribute *attr = to_iommu_group_attr(__attr);
461 struct iommu_group *group = to_iommu_group(kobj);
465 ret = attr->store(group, buf, count);
469 static const struct sysfs_ops iommu_group_sysfs_ops = {
470 .show = iommu_group_attr_show,
471 .store = iommu_group_attr_store,
474 static int iommu_group_create_file(struct iommu_group *group,
475 struct iommu_group_attribute *attr)
477 return sysfs_create_file(&group->kobj, &attr->attr);
480 static void iommu_group_remove_file(struct iommu_group *group,
481 struct iommu_group_attribute *attr)
483 sysfs_remove_file(&group->kobj, &attr->attr);
486 static ssize_t iommu_group_show_name(struct iommu_group *group, char *buf)
488 return sprintf(buf, "%s\n", group->name);
492 * iommu_insert_resv_region - Insert a new region in the
493 * list of reserved regions.
494 * @new: new region to insert
495 * @regions: list of regions
497 * Elements are sorted by start address and overlapping segments
498 * of the same type are merged.
500 static int iommu_insert_resv_region(struct iommu_resv_region *new,
501 struct list_head *regions)
503 struct iommu_resv_region *iter, *tmp, *nr, *top;
506 nr = iommu_alloc_resv_region(new->start, new->length,
507 new->prot, new->type, GFP_KERNEL);
511 /* First add the new element based on start address sorting */
512 list_for_each_entry(iter, regions, list) {
513 if (nr->start < iter->start ||
514 (nr->start == iter->start && nr->type <= iter->type))
517 list_add_tail(&nr->list, &iter->list);
519 /* Merge overlapping segments of type nr->type in @regions, if any */
520 list_for_each_entry_safe(iter, tmp, regions, list) {
521 phys_addr_t top_end, iter_end = iter->start + iter->length - 1;
523 /* no merge needed on elements of different types than @new */
524 if (iter->type != new->type) {
525 list_move_tail(&iter->list, &stack);
529 /* look for the last stack element of same type as @iter */
530 list_for_each_entry_reverse(top, &stack, list)
531 if (top->type == iter->type)
534 list_move_tail(&iter->list, &stack);
538 top_end = top->start + top->length - 1;
540 if (iter->start > top_end + 1) {
541 list_move_tail(&iter->list, &stack);
543 top->length = max(top_end, iter_end) - top->start + 1;
544 list_del(&iter->list);
548 list_splice(&stack, regions);
553 iommu_insert_device_resv_regions(struct list_head *dev_resv_regions,
554 struct list_head *group_resv_regions)
556 struct iommu_resv_region *entry;
559 list_for_each_entry(entry, dev_resv_regions, list) {
560 ret = iommu_insert_resv_region(entry, group_resv_regions);
567 int iommu_get_group_resv_regions(struct iommu_group *group,
568 struct list_head *head)
570 struct group_device *device;
573 mutex_lock(&group->mutex);
574 list_for_each_entry(device, &group->devices, list) {
575 struct list_head dev_resv_regions;
578 * Non-API groups still expose reserved_regions in sysfs,
579 * so filter out calls that get here that way.
581 if (!device->dev->iommu)
584 INIT_LIST_HEAD(&dev_resv_regions);
585 iommu_get_resv_regions(device->dev, &dev_resv_regions);
586 ret = iommu_insert_device_resv_regions(&dev_resv_regions, head);
587 iommu_put_resv_regions(device->dev, &dev_resv_regions);
591 mutex_unlock(&group->mutex);
594 EXPORT_SYMBOL_GPL(iommu_get_group_resv_regions);
596 static ssize_t iommu_group_show_resv_regions(struct iommu_group *group,
599 struct iommu_resv_region *region, *next;
600 struct list_head group_resv_regions;
603 INIT_LIST_HEAD(&group_resv_regions);
604 iommu_get_group_resv_regions(group, &group_resv_regions);
606 list_for_each_entry_safe(region, next, &group_resv_regions, list) {
607 str += sprintf(str, "0x%016llx 0x%016llx %s\n",
608 (long long int)region->start,
609 (long long int)(region->start +
611 iommu_group_resv_type_string[region->type]);
618 static ssize_t iommu_group_show_type(struct iommu_group *group,
621 char *type = "unknown\n";
623 mutex_lock(&group->mutex);
624 if (group->default_domain) {
625 switch (group->default_domain->type) {
626 case IOMMU_DOMAIN_BLOCKED:
629 case IOMMU_DOMAIN_IDENTITY:
632 case IOMMU_DOMAIN_UNMANAGED:
633 type = "unmanaged\n";
635 case IOMMU_DOMAIN_DMA:
638 case IOMMU_DOMAIN_DMA_FQ:
643 mutex_unlock(&group->mutex);
649 static IOMMU_GROUP_ATTR(name, S_IRUGO, iommu_group_show_name, NULL);
651 static IOMMU_GROUP_ATTR(reserved_regions, 0444,
652 iommu_group_show_resv_regions, NULL);
654 static IOMMU_GROUP_ATTR(type, 0644, iommu_group_show_type,
655 iommu_group_store_type);
657 static void iommu_group_release(struct kobject *kobj)
659 struct iommu_group *group = to_iommu_group(kobj);
661 pr_debug("Releasing group %d\n", group->id);
663 if (group->iommu_data_release)
664 group->iommu_data_release(group->iommu_data);
666 ida_free(&iommu_group_ida, group->id);
668 if (group->default_domain)
669 iommu_domain_free(group->default_domain);
670 if (group->blocking_domain)
671 iommu_domain_free(group->blocking_domain);
677 static struct kobj_type iommu_group_ktype = {
678 .sysfs_ops = &iommu_group_sysfs_ops,
679 .release = iommu_group_release,
683 * iommu_group_alloc - Allocate a new group
685 * This function is called by an iommu driver to allocate a new iommu
686 * group. The iommu group represents the minimum granularity of the iommu.
687 * Upon successful return, the caller holds a reference to the supplied
688 * group in order to hold the group until devices are added. Use
689 * iommu_group_put() to release this extra reference count, allowing the
690 * group to be automatically reclaimed once it has no devices or external
693 struct iommu_group *iommu_group_alloc(void)
695 struct iommu_group *group;
698 group = kzalloc(sizeof(*group), GFP_KERNEL);
700 return ERR_PTR(-ENOMEM);
702 group->kobj.kset = iommu_group_kset;
703 mutex_init(&group->mutex);
704 INIT_LIST_HEAD(&group->devices);
705 INIT_LIST_HEAD(&group->entry);
707 ret = ida_alloc(&iommu_group_ida, GFP_KERNEL);
714 ret = kobject_init_and_add(&group->kobj, &iommu_group_ktype,
715 NULL, "%d", group->id);
717 kobject_put(&group->kobj);
721 group->devices_kobj = kobject_create_and_add("devices", &group->kobj);
722 if (!group->devices_kobj) {
723 kobject_put(&group->kobj); /* triggers .release & free */
724 return ERR_PTR(-ENOMEM);
728 * The devices_kobj holds a reference on the group kobject, so
729 * as long as that exists so will the group. We can therefore
730 * use the devices_kobj for reference counting.
732 kobject_put(&group->kobj);
734 ret = iommu_group_create_file(group,
735 &iommu_group_attr_reserved_regions);
739 ret = iommu_group_create_file(group, &iommu_group_attr_type);
743 pr_debug("Allocated group %d\n", group->id);
747 EXPORT_SYMBOL_GPL(iommu_group_alloc);
749 struct iommu_group *iommu_group_get_by_id(int id)
751 struct kobject *group_kobj;
752 struct iommu_group *group;
755 if (!iommu_group_kset)
758 name = kasprintf(GFP_KERNEL, "%d", id);
762 group_kobj = kset_find_obj(iommu_group_kset, name);
768 group = container_of(group_kobj, struct iommu_group, kobj);
769 BUG_ON(group->id != id);
771 kobject_get(group->devices_kobj);
772 kobject_put(&group->kobj);
776 EXPORT_SYMBOL_GPL(iommu_group_get_by_id);
779 * iommu_group_get_iommudata - retrieve iommu_data registered for a group
782 * iommu drivers can store data in the group for use when doing iommu
783 * operations. This function provides a way to retrieve it. Caller
784 * should hold a group reference.
786 void *iommu_group_get_iommudata(struct iommu_group *group)
788 return group->iommu_data;
790 EXPORT_SYMBOL_GPL(iommu_group_get_iommudata);
793 * iommu_group_set_iommudata - set iommu_data for a group
795 * @iommu_data: new data
796 * @release: release function for iommu_data
798 * iommu drivers can store data in the group for use when doing iommu
799 * operations. This function provides a way to set the data after
800 * the group has been allocated. Caller should hold a group reference.
802 void iommu_group_set_iommudata(struct iommu_group *group, void *iommu_data,
803 void (*release)(void *iommu_data))
805 group->iommu_data = iommu_data;
806 group->iommu_data_release = release;
808 EXPORT_SYMBOL_GPL(iommu_group_set_iommudata);
811 * iommu_group_set_name - set name for a group
815 * Allow iommu driver to set a name for a group. When set it will
816 * appear in a name attribute file under the group in sysfs.
818 int iommu_group_set_name(struct iommu_group *group, const char *name)
823 iommu_group_remove_file(group, &iommu_group_attr_name);
830 group->name = kstrdup(name, GFP_KERNEL);
834 ret = iommu_group_create_file(group, &iommu_group_attr_name);
843 EXPORT_SYMBOL_GPL(iommu_group_set_name);
845 static int iommu_create_device_direct_mappings(struct iommu_group *group,
848 struct iommu_domain *domain = group->default_domain;
849 struct iommu_resv_region *entry;
850 struct list_head mappings;
851 unsigned long pg_size;
854 if (!domain || !iommu_is_dma_domain(domain))
857 BUG_ON(!domain->pgsize_bitmap);
859 pg_size = 1UL << __ffs(domain->pgsize_bitmap);
860 INIT_LIST_HEAD(&mappings);
862 iommu_get_resv_regions(dev, &mappings);
864 /* We need to consider overlapping regions for different devices */
865 list_for_each_entry(entry, &mappings, list) {
866 dma_addr_t start, end, addr;
869 start = ALIGN(entry->start, pg_size);
870 end = ALIGN(entry->start + entry->length, pg_size);
872 if (entry->type != IOMMU_RESV_DIRECT &&
873 entry->type != IOMMU_RESV_DIRECT_RELAXABLE)
876 for (addr = start; addr <= end; addr += pg_size) {
877 phys_addr_t phys_addr;
882 phys_addr = iommu_iova_to_phys(domain, addr);
890 ret = iommu_map(domain, addr - map_size,
891 addr - map_size, map_size,
901 iommu_flush_iotlb_all(domain);
904 iommu_put_resv_regions(dev, &mappings);
909 static bool iommu_is_attach_deferred(struct device *dev)
911 const struct iommu_ops *ops = dev_iommu_ops(dev);
913 if (ops->is_attach_deferred)
914 return ops->is_attach_deferred(dev);
920 * iommu_group_add_device - add a device to an iommu group
921 * @group: the group into which to add the device (reference should be held)
924 * This function is called by an iommu driver to add a device into a
925 * group. Adding a device increments the group reference count.
927 int iommu_group_add_device(struct iommu_group *group, struct device *dev)
930 struct group_device *device;
932 device = kzalloc(sizeof(*device), GFP_KERNEL);
938 ret = sysfs_create_link(&dev->kobj, &group->kobj, "iommu_group");
940 goto err_free_device;
942 device->name = kasprintf(GFP_KERNEL, "%s", kobject_name(&dev->kobj));
946 goto err_remove_link;
949 ret = sysfs_create_link_nowarn(group->devices_kobj,
950 &dev->kobj, device->name);
952 if (ret == -EEXIST && i >= 0) {
954 * Account for the slim chance of collision
955 * and append an instance to the name.
958 device->name = kasprintf(GFP_KERNEL, "%s.%d",
959 kobject_name(&dev->kobj), i++);
965 kobject_get(group->devices_kobj);
967 dev->iommu_group = group;
969 mutex_lock(&group->mutex);
970 list_add_tail(&device->list, &group->devices);
971 if (group->domain && !iommu_is_attach_deferred(dev))
972 ret = __iommu_attach_device(group->domain, dev);
973 mutex_unlock(&group->mutex);
977 trace_add_device_to_group(group->id, dev);
979 dev_info(dev, "Adding to iommu group %d\n", group->id);
984 mutex_lock(&group->mutex);
985 list_del(&device->list);
986 mutex_unlock(&group->mutex);
987 dev->iommu_group = NULL;
988 kobject_put(group->devices_kobj);
989 sysfs_remove_link(group->devices_kobj, device->name);
993 sysfs_remove_link(&dev->kobj, "iommu_group");
996 dev_err(dev, "Failed to add to iommu group %d: %d\n", group->id, ret);
999 EXPORT_SYMBOL_GPL(iommu_group_add_device);
1002 * iommu_group_remove_device - remove a device from it's current group
1003 * @dev: device to be removed
1005 * This function is called by an iommu driver to remove the device from
1006 * it's current group. This decrements the iommu group reference count.
1008 void iommu_group_remove_device(struct device *dev)
1010 struct iommu_group *group = dev->iommu_group;
1011 struct group_device *tmp_device, *device = NULL;
1016 dev_info(dev, "Removing from iommu group %d\n", group->id);
1018 mutex_lock(&group->mutex);
1019 list_for_each_entry(tmp_device, &group->devices, list) {
1020 if (tmp_device->dev == dev) {
1021 device = tmp_device;
1022 list_del(&device->list);
1026 mutex_unlock(&group->mutex);
1031 sysfs_remove_link(group->devices_kobj, device->name);
1032 sysfs_remove_link(&dev->kobj, "iommu_group");
1034 trace_remove_device_from_group(group->id, dev);
1036 kfree(device->name);
1038 dev->iommu_group = NULL;
1039 kobject_put(group->devices_kobj);
1041 EXPORT_SYMBOL_GPL(iommu_group_remove_device);
1043 static int iommu_group_device_count(struct iommu_group *group)
1045 struct group_device *entry;
1048 list_for_each_entry(entry, &group->devices, list)
1054 static int __iommu_group_for_each_dev(struct iommu_group *group, void *data,
1055 int (*fn)(struct device *, void *))
1057 struct group_device *device;
1060 list_for_each_entry(device, &group->devices, list) {
1061 ret = fn(device->dev, data);
1069 * iommu_group_for_each_dev - iterate over each device in the group
1071 * @data: caller opaque data to be passed to callback function
1072 * @fn: caller supplied callback function
1074 * This function is called by group users to iterate over group devices.
1075 * Callers should hold a reference count to the group during callback.
1076 * The group->mutex is held across callbacks, which will block calls to
1077 * iommu_group_add/remove_device.
1079 int iommu_group_for_each_dev(struct iommu_group *group, void *data,
1080 int (*fn)(struct device *, void *))
1084 mutex_lock(&group->mutex);
1085 ret = __iommu_group_for_each_dev(group, data, fn);
1086 mutex_unlock(&group->mutex);
1090 EXPORT_SYMBOL_GPL(iommu_group_for_each_dev);
1093 * iommu_group_get - Return the group for a device and increment reference
1094 * @dev: get the group that this device belongs to
1096 * This function is called by iommu drivers and users to get the group
1097 * for the specified device. If found, the group is returned and the group
1098 * reference in incremented, else NULL.
1100 struct iommu_group *iommu_group_get(struct device *dev)
1102 struct iommu_group *group = dev->iommu_group;
1105 kobject_get(group->devices_kobj);
1109 EXPORT_SYMBOL_GPL(iommu_group_get);
1112 * iommu_group_ref_get - Increment reference on a group
1113 * @group: the group to use, must not be NULL
1115 * This function is called by iommu drivers to take additional references on an
1116 * existing group. Returns the given group for convenience.
1118 struct iommu_group *iommu_group_ref_get(struct iommu_group *group)
1120 kobject_get(group->devices_kobj);
1123 EXPORT_SYMBOL_GPL(iommu_group_ref_get);
1126 * iommu_group_put - Decrement group reference
1127 * @group: the group to use
1129 * This function is called by iommu drivers and users to release the
1130 * iommu group. Once the reference count is zero, the group is released.
1132 void iommu_group_put(struct iommu_group *group)
1135 kobject_put(group->devices_kobj);
1137 EXPORT_SYMBOL_GPL(iommu_group_put);
1140 * iommu_register_device_fault_handler() - Register a device fault handler
1142 * @handler: the fault handler
1143 * @data: private data passed as argument to the handler
1145 * When an IOMMU fault event is received, this handler gets called with the
1146 * fault event and data as argument. The handler should return 0 on success. If
1147 * the fault is recoverable (IOMMU_FAULT_PAGE_REQ), the consumer should also
1148 * complete the fault by calling iommu_page_response() with one of the following
1150 * - IOMMU_PAGE_RESP_SUCCESS: retry the translation
1151 * - IOMMU_PAGE_RESP_INVALID: terminate the fault
1152 * - IOMMU_PAGE_RESP_FAILURE: terminate the fault and stop reporting
1153 * page faults if possible.
1155 * Return 0 if the fault handler was installed successfully, or an error.
1157 int iommu_register_device_fault_handler(struct device *dev,
1158 iommu_dev_fault_handler_t handler,
1161 struct dev_iommu *param = dev->iommu;
1167 mutex_lock(¶m->lock);
1168 /* Only allow one fault handler registered for each device */
1169 if (param->fault_param) {
1175 param->fault_param = kzalloc(sizeof(*param->fault_param), GFP_KERNEL);
1176 if (!param->fault_param) {
1181 param->fault_param->handler = handler;
1182 param->fault_param->data = data;
1183 mutex_init(¶m->fault_param->lock);
1184 INIT_LIST_HEAD(¶m->fault_param->faults);
1187 mutex_unlock(¶m->lock);
1191 EXPORT_SYMBOL_GPL(iommu_register_device_fault_handler);
1194 * iommu_unregister_device_fault_handler() - Unregister the device fault handler
1197 * Remove the device fault handler installed with
1198 * iommu_register_device_fault_handler().
1200 * Return 0 on success, or an error.
1202 int iommu_unregister_device_fault_handler(struct device *dev)
1204 struct dev_iommu *param = dev->iommu;
1210 mutex_lock(¶m->lock);
1212 if (!param->fault_param)
1215 /* we cannot unregister handler if there are pending faults */
1216 if (!list_empty(¶m->fault_param->faults)) {
1221 kfree(param->fault_param);
1222 param->fault_param = NULL;
1225 mutex_unlock(¶m->lock);
1229 EXPORT_SYMBOL_GPL(iommu_unregister_device_fault_handler);
1232 * iommu_report_device_fault() - Report fault event to device driver
1234 * @evt: fault event data
1236 * Called by IOMMU drivers when a fault is detected, typically in a threaded IRQ
1237 * handler. When this function fails and the fault is recoverable, it is the
1238 * caller's responsibility to complete the fault.
1240 * Return 0 on success, or an error.
1242 int iommu_report_device_fault(struct device *dev, struct iommu_fault_event *evt)
1244 struct dev_iommu *param = dev->iommu;
1245 struct iommu_fault_event *evt_pending = NULL;
1246 struct iommu_fault_param *fparam;
1252 /* we only report device fault if there is a handler registered */
1253 mutex_lock(¶m->lock);
1254 fparam = param->fault_param;
1255 if (!fparam || !fparam->handler) {
1260 if (evt->fault.type == IOMMU_FAULT_PAGE_REQ &&
1261 (evt->fault.prm.flags & IOMMU_FAULT_PAGE_REQUEST_LAST_PAGE)) {
1262 evt_pending = kmemdup(evt, sizeof(struct iommu_fault_event),
1268 mutex_lock(&fparam->lock);
1269 list_add_tail(&evt_pending->list, &fparam->faults);
1270 mutex_unlock(&fparam->lock);
1273 ret = fparam->handler(&evt->fault, fparam->data);
1274 if (ret && evt_pending) {
1275 mutex_lock(&fparam->lock);
1276 list_del(&evt_pending->list);
1277 mutex_unlock(&fparam->lock);
1281 mutex_unlock(¶m->lock);
1284 EXPORT_SYMBOL_GPL(iommu_report_device_fault);
1286 int iommu_page_response(struct device *dev,
1287 struct iommu_page_response *msg)
1291 struct iommu_fault_event *evt;
1292 struct iommu_fault_page_request *prm;
1293 struct dev_iommu *param = dev->iommu;
1294 const struct iommu_ops *ops = dev_iommu_ops(dev);
1295 bool has_pasid = msg->flags & IOMMU_PAGE_RESP_PASID_VALID;
1297 if (!ops->page_response)
1300 if (!param || !param->fault_param)
1303 if (msg->version != IOMMU_PAGE_RESP_VERSION_1 ||
1304 msg->flags & ~IOMMU_PAGE_RESP_PASID_VALID)
1307 /* Only send response if there is a fault report pending */
1308 mutex_lock(¶m->fault_param->lock);
1309 if (list_empty(¶m->fault_param->faults)) {
1310 dev_warn_ratelimited(dev, "no pending PRQ, drop response\n");
1314 * Check if we have a matching page request pending to respond,
1315 * otherwise return -EINVAL
1317 list_for_each_entry(evt, ¶m->fault_param->faults, list) {
1318 prm = &evt->fault.prm;
1319 if (prm->grpid != msg->grpid)
1323 * If the PASID is required, the corresponding request is
1324 * matched using the group ID, the PASID valid bit and the PASID
1325 * value. Otherwise only the group ID matches request and
1328 needs_pasid = prm->flags & IOMMU_FAULT_PAGE_RESPONSE_NEEDS_PASID;
1329 if (needs_pasid && (!has_pasid || msg->pasid != prm->pasid))
1332 if (!needs_pasid && has_pasid) {
1333 /* No big deal, just clear it. */
1334 msg->flags &= ~IOMMU_PAGE_RESP_PASID_VALID;
1338 ret = ops->page_response(dev, evt, msg);
1339 list_del(&evt->list);
1345 mutex_unlock(¶m->fault_param->lock);
1348 EXPORT_SYMBOL_GPL(iommu_page_response);
1351 * iommu_group_id - Return ID for a group
1352 * @group: the group to ID
1354 * Return the unique ID for the group matching the sysfs group number.
1356 int iommu_group_id(struct iommu_group *group)
1360 EXPORT_SYMBOL_GPL(iommu_group_id);
1362 static struct iommu_group *get_pci_alias_group(struct pci_dev *pdev,
1363 unsigned long *devfns);
1366 * To consider a PCI device isolated, we require ACS to support Source
1367 * Validation, Request Redirection, Completer Redirection, and Upstream
1368 * Forwarding. This effectively means that devices cannot spoof their
1369 * requester ID, requests and completions cannot be redirected, and all
1370 * transactions are forwarded upstream, even as it passes through a
1371 * bridge where the target device is downstream.
1373 #define REQ_ACS_FLAGS (PCI_ACS_SV | PCI_ACS_RR | PCI_ACS_CR | PCI_ACS_UF)
1376 * For multifunction devices which are not isolated from each other, find
1377 * all the other non-isolated functions and look for existing groups. For
1378 * each function, we also need to look for aliases to or from other devices
1379 * that may already have a group.
1381 static struct iommu_group *get_pci_function_alias_group(struct pci_dev *pdev,
1382 unsigned long *devfns)
1384 struct pci_dev *tmp = NULL;
1385 struct iommu_group *group;
1387 if (!pdev->multifunction || pci_acs_enabled(pdev, REQ_ACS_FLAGS))
1390 for_each_pci_dev(tmp) {
1391 if (tmp == pdev || tmp->bus != pdev->bus ||
1392 PCI_SLOT(tmp->devfn) != PCI_SLOT(pdev->devfn) ||
1393 pci_acs_enabled(tmp, REQ_ACS_FLAGS))
1396 group = get_pci_alias_group(tmp, devfns);
1407 * Look for aliases to or from the given device for existing groups. DMA
1408 * aliases are only supported on the same bus, therefore the search
1409 * space is quite small (especially since we're really only looking at pcie
1410 * device, and therefore only expect multiple slots on the root complex or
1411 * downstream switch ports). It's conceivable though that a pair of
1412 * multifunction devices could have aliases between them that would cause a
1413 * loop. To prevent this, we use a bitmap to track where we've been.
1415 static struct iommu_group *get_pci_alias_group(struct pci_dev *pdev,
1416 unsigned long *devfns)
1418 struct pci_dev *tmp = NULL;
1419 struct iommu_group *group;
1421 if (test_and_set_bit(pdev->devfn & 0xff, devfns))
1424 group = iommu_group_get(&pdev->dev);
1428 for_each_pci_dev(tmp) {
1429 if (tmp == pdev || tmp->bus != pdev->bus)
1432 /* We alias them or they alias us */
1433 if (pci_devs_are_dma_aliases(pdev, tmp)) {
1434 group = get_pci_alias_group(tmp, devfns);
1440 group = get_pci_function_alias_group(tmp, devfns);
1451 struct group_for_pci_data {
1452 struct pci_dev *pdev;
1453 struct iommu_group *group;
1457 * DMA alias iterator callback, return the last seen device. Stop and return
1458 * the IOMMU group if we find one along the way.
1460 static int get_pci_alias_or_group(struct pci_dev *pdev, u16 alias, void *opaque)
1462 struct group_for_pci_data *data = opaque;
1465 data->group = iommu_group_get(&pdev->dev);
1467 return data->group != NULL;
1471 * Generic device_group call-back function. It just allocates one
1472 * iommu-group per device.
1474 struct iommu_group *generic_device_group(struct device *dev)
1476 return iommu_group_alloc();
1478 EXPORT_SYMBOL_GPL(generic_device_group);
1481 * Use standard PCI bus topology, isolation features, and DMA alias quirks
1482 * to find or create an IOMMU group for a device.
1484 struct iommu_group *pci_device_group(struct device *dev)
1486 struct pci_dev *pdev = to_pci_dev(dev);
1487 struct group_for_pci_data data;
1488 struct pci_bus *bus;
1489 struct iommu_group *group = NULL;
1490 u64 devfns[4] = { 0 };
1492 if (WARN_ON(!dev_is_pci(dev)))
1493 return ERR_PTR(-EINVAL);
1496 * Find the upstream DMA alias for the device. A device must not
1497 * be aliased due to topology in order to have its own IOMMU group.
1498 * If we find an alias along the way that already belongs to a
1501 if (pci_for_each_dma_alias(pdev, get_pci_alias_or_group, &data))
1507 * Continue upstream from the point of minimum IOMMU granularity
1508 * due to aliases to the point where devices are protected from
1509 * peer-to-peer DMA by PCI ACS. Again, if we find an existing
1512 for (bus = pdev->bus; !pci_is_root_bus(bus); bus = bus->parent) {
1516 if (pci_acs_path_enabled(bus->self, NULL, REQ_ACS_FLAGS))
1521 group = iommu_group_get(&pdev->dev);
1527 * Look for existing groups on device aliases. If we alias another
1528 * device or another device aliases us, use the same group.
1530 group = get_pci_alias_group(pdev, (unsigned long *)devfns);
1535 * Look for existing groups on non-isolated functions on the same
1536 * slot and aliases of those funcions, if any. No need to clear
1537 * the search bitmap, the tested devfns are still valid.
1539 group = get_pci_function_alias_group(pdev, (unsigned long *)devfns);
1543 /* No shared group found, allocate new */
1544 return iommu_group_alloc();
1546 EXPORT_SYMBOL_GPL(pci_device_group);
1548 /* Get the IOMMU group for device on fsl-mc bus */
1549 struct iommu_group *fsl_mc_device_group(struct device *dev)
1551 struct device *cont_dev = fsl_mc_cont_dev(dev);
1552 struct iommu_group *group;
1554 group = iommu_group_get(cont_dev);
1556 group = iommu_group_alloc();
1559 EXPORT_SYMBOL_GPL(fsl_mc_device_group);
1561 static int iommu_get_def_domain_type(struct device *dev)
1563 const struct iommu_ops *ops = dev_iommu_ops(dev);
1565 if (dev_is_pci(dev) && to_pci_dev(dev)->untrusted)
1566 return IOMMU_DOMAIN_DMA;
1568 if (ops->def_domain_type)
1569 return ops->def_domain_type(dev);
1574 static int iommu_group_alloc_default_domain(struct bus_type *bus,
1575 struct iommu_group *group,
1578 struct iommu_domain *dom;
1580 dom = __iommu_domain_alloc(bus, type);
1581 if (!dom && type != IOMMU_DOMAIN_DMA) {
1582 dom = __iommu_domain_alloc(bus, IOMMU_DOMAIN_DMA);
1584 pr_warn("Failed to allocate default IOMMU domain of type %u for group %s - Falling back to IOMMU_DOMAIN_DMA",
1591 group->default_domain = dom;
1593 group->domain = dom;
1597 static int iommu_alloc_default_domain(struct iommu_group *group,
1602 if (group->default_domain)
1605 type = iommu_get_def_domain_type(dev) ? : iommu_def_domain_type;
1607 return iommu_group_alloc_default_domain(dev->bus, group, type);
1611 * iommu_group_get_for_dev - Find or create the IOMMU group for a device
1612 * @dev: target device
1614 * This function is intended to be called by IOMMU drivers and extended to
1615 * support common, bus-defined algorithms when determining or creating the
1616 * IOMMU group for a device. On success, the caller will hold a reference
1617 * to the returned IOMMU group, which will already include the provided
1618 * device. The reference should be released with iommu_group_put().
1620 static struct iommu_group *iommu_group_get_for_dev(struct device *dev)
1622 const struct iommu_ops *ops = dev_iommu_ops(dev);
1623 struct iommu_group *group;
1626 group = iommu_group_get(dev);
1630 group = ops->device_group(dev);
1631 if (WARN_ON_ONCE(group == NULL))
1632 return ERR_PTR(-EINVAL);
1637 ret = iommu_group_add_device(group, dev);
1644 iommu_group_put(group);
1646 return ERR_PTR(ret);
1649 struct iommu_domain *iommu_group_default_domain(struct iommu_group *group)
1651 return group->default_domain;
1654 static int probe_iommu_group(struct device *dev, void *data)
1656 struct list_head *group_list = data;
1657 struct iommu_group *group;
1660 /* Device is probed already if in a group */
1661 group = iommu_group_get(dev);
1663 iommu_group_put(group);
1667 ret = __iommu_probe_device(dev, group_list);
1674 static int iommu_bus_notifier(struct notifier_block *nb,
1675 unsigned long action, void *data)
1677 struct device *dev = data;
1679 if (action == BUS_NOTIFY_ADD_DEVICE) {
1682 ret = iommu_probe_device(dev);
1683 return (ret) ? NOTIFY_DONE : NOTIFY_OK;
1684 } else if (action == BUS_NOTIFY_REMOVED_DEVICE) {
1685 iommu_release_device(dev);
1692 struct __group_domain_type {
1697 static int probe_get_default_domain_type(struct device *dev, void *data)
1699 struct __group_domain_type *gtype = data;
1700 unsigned int type = iommu_get_def_domain_type(dev);
1703 if (gtype->type && gtype->type != type) {
1704 dev_warn(dev, "Device needs domain type %s, but device %s in the same iommu group requires type %s - using default\n",
1705 iommu_domain_type_str(type),
1706 dev_name(gtype->dev),
1707 iommu_domain_type_str(gtype->type));
1720 static void probe_alloc_default_domain(struct bus_type *bus,
1721 struct iommu_group *group)
1723 struct __group_domain_type gtype;
1725 memset(>ype, 0, sizeof(gtype));
1727 /* Ask for default domain requirements of all devices in the group */
1728 __iommu_group_for_each_dev(group, >ype,
1729 probe_get_default_domain_type);
1732 gtype.type = iommu_def_domain_type;
1734 iommu_group_alloc_default_domain(bus, group, gtype.type);
1738 static int iommu_group_do_dma_attach(struct device *dev, void *data)
1740 struct iommu_domain *domain = data;
1743 if (!iommu_is_attach_deferred(dev))
1744 ret = __iommu_attach_device(domain, dev);
1749 static int __iommu_group_dma_attach(struct iommu_group *group)
1751 return __iommu_group_for_each_dev(group, group->default_domain,
1752 iommu_group_do_dma_attach);
1755 static int iommu_group_do_probe_finalize(struct device *dev, void *data)
1757 const struct iommu_ops *ops = dev_iommu_ops(dev);
1759 if (ops->probe_finalize)
1760 ops->probe_finalize(dev);
1765 static void __iommu_group_dma_finalize(struct iommu_group *group)
1767 __iommu_group_for_each_dev(group, group->default_domain,
1768 iommu_group_do_probe_finalize);
1771 static int iommu_do_create_direct_mappings(struct device *dev, void *data)
1773 struct iommu_group *group = data;
1775 iommu_create_device_direct_mappings(group, dev);
1780 static int iommu_group_create_direct_mappings(struct iommu_group *group)
1782 return __iommu_group_for_each_dev(group, group,
1783 iommu_do_create_direct_mappings);
1786 int bus_iommu_probe(struct bus_type *bus)
1788 struct iommu_group *group, *next;
1789 LIST_HEAD(group_list);
1793 * This code-path does not allocate the default domain when
1794 * creating the iommu group, so do it after the groups are
1797 ret = bus_for_each_dev(bus, NULL, &group_list, probe_iommu_group);
1801 list_for_each_entry_safe(group, next, &group_list, entry) {
1802 /* Remove item from the list */
1803 list_del_init(&group->entry);
1805 mutex_lock(&group->mutex);
1807 /* Try to allocate default domain */
1808 probe_alloc_default_domain(bus, group);
1810 if (!group->default_domain) {
1811 mutex_unlock(&group->mutex);
1815 iommu_group_create_direct_mappings(group);
1817 ret = __iommu_group_dma_attach(group);
1819 mutex_unlock(&group->mutex);
1824 __iommu_group_dma_finalize(group);
1830 bool iommu_present(struct bus_type *bus)
1832 return bus->iommu_ops != NULL;
1834 EXPORT_SYMBOL_GPL(iommu_present);
1837 * device_iommu_capable() - check for a general IOMMU capability
1838 * @dev: device to which the capability would be relevant, if available
1839 * @cap: IOMMU capability
1841 * Return: true if an IOMMU is present and supports the given capability
1842 * for the given device, otherwise false.
1844 bool device_iommu_capable(struct device *dev, enum iommu_cap cap)
1846 const struct iommu_ops *ops;
1848 if (!dev->iommu || !dev->iommu->iommu_dev)
1851 ops = dev_iommu_ops(dev);
1855 return ops->capable(dev, cap);
1857 EXPORT_SYMBOL_GPL(device_iommu_capable);
1860 * iommu_set_fault_handler() - set a fault handler for an iommu domain
1861 * @domain: iommu domain
1862 * @handler: fault handler
1863 * @token: user data, will be passed back to the fault handler
1865 * This function should be used by IOMMU users which want to be notified
1866 * whenever an IOMMU fault happens.
1868 * The fault handler itself should return 0 on success, and an appropriate
1869 * error code otherwise.
1871 void iommu_set_fault_handler(struct iommu_domain *domain,
1872 iommu_fault_handler_t handler,
1877 domain->handler = handler;
1878 domain->handler_token = token;
1880 EXPORT_SYMBOL_GPL(iommu_set_fault_handler);
1882 static struct iommu_domain *__iommu_domain_alloc(struct bus_type *bus,
1885 struct iommu_domain *domain;
1887 if (bus == NULL || bus->iommu_ops == NULL)
1890 domain = bus->iommu_ops->domain_alloc(type);
1894 domain->type = type;
1895 /* Assume all sizes by default; the driver may override this later */
1896 domain->pgsize_bitmap = bus->iommu_ops->pgsize_bitmap;
1898 domain->ops = bus->iommu_ops->default_domain_ops;
1900 if (iommu_is_dma_domain(domain) && iommu_get_dma_cookie(domain)) {
1901 iommu_domain_free(domain);
1907 struct iommu_domain *iommu_domain_alloc(struct bus_type *bus)
1909 return __iommu_domain_alloc(bus, IOMMU_DOMAIN_UNMANAGED);
1911 EXPORT_SYMBOL_GPL(iommu_domain_alloc);
1913 void iommu_domain_free(struct iommu_domain *domain)
1915 iommu_put_dma_cookie(domain);
1916 domain->ops->free(domain);
1918 EXPORT_SYMBOL_GPL(iommu_domain_free);
1921 * Put the group's domain back to the appropriate core-owned domain - either the
1922 * standard kernel-mode DMA configuration or an all-DMA-blocked domain.
1924 static void __iommu_group_set_core_domain(struct iommu_group *group)
1926 struct iommu_domain *new_domain;
1930 new_domain = group->blocking_domain;
1932 new_domain = group->default_domain;
1934 ret = __iommu_group_set_domain(group, new_domain);
1935 WARN(ret, "iommu driver failed to attach the default/blocking domain");
1938 static int __iommu_attach_device(struct iommu_domain *domain,
1943 if (unlikely(domain->ops->attach_dev == NULL))
1946 ret = domain->ops->attach_dev(domain, dev);
1948 trace_attach_device_to_domain(dev);
1952 int iommu_attach_device(struct iommu_domain *domain, struct device *dev)
1954 struct iommu_group *group;
1957 group = iommu_group_get(dev);
1962 * Lock the group to make sure the device-count doesn't
1963 * change while we are attaching
1965 mutex_lock(&group->mutex);
1967 if (iommu_group_device_count(group) != 1)
1970 ret = __iommu_attach_group(domain, group);
1973 mutex_unlock(&group->mutex);
1974 iommu_group_put(group);
1978 EXPORT_SYMBOL_GPL(iommu_attach_device);
1980 int iommu_deferred_attach(struct device *dev, struct iommu_domain *domain)
1982 if (iommu_is_attach_deferred(dev))
1983 return __iommu_attach_device(domain, dev);
1988 static void __iommu_detach_device(struct iommu_domain *domain,
1991 if (iommu_is_attach_deferred(dev))
1994 domain->ops->detach_dev(domain, dev);
1995 trace_detach_device_from_domain(dev);
1998 void iommu_detach_device(struct iommu_domain *domain, struct device *dev)
2000 struct iommu_group *group;
2002 group = iommu_group_get(dev);
2006 mutex_lock(&group->mutex);
2007 if (WARN_ON(domain != group->domain) ||
2008 WARN_ON(iommu_group_device_count(group) != 1))
2010 __iommu_group_set_core_domain(group);
2013 mutex_unlock(&group->mutex);
2014 iommu_group_put(group);
2016 EXPORT_SYMBOL_GPL(iommu_detach_device);
2018 struct iommu_domain *iommu_get_domain_for_dev(struct device *dev)
2020 struct iommu_domain *domain;
2021 struct iommu_group *group;
2023 group = iommu_group_get(dev);
2027 domain = group->domain;
2029 iommu_group_put(group);
2033 EXPORT_SYMBOL_GPL(iommu_get_domain_for_dev);
2036 * For IOMMU_DOMAIN_DMA implementations which already provide their own
2037 * guarantees that the group and its default domain are valid and correct.
2039 struct iommu_domain *iommu_get_dma_domain(struct device *dev)
2041 return dev->iommu_group->default_domain;
2045 * IOMMU groups are really the natural working unit of the IOMMU, but
2046 * the IOMMU API works on domains and devices. Bridge that gap by
2047 * iterating over the devices in a group. Ideally we'd have a single
2048 * device which represents the requestor ID of the group, but we also
2049 * allow IOMMU drivers to create policy defined minimum sets, where
2050 * the physical hardware may be able to distiguish members, but we
2051 * wish to group them at a higher level (ex. untrusted multi-function
2052 * PCI devices). Thus we attach each device.
2054 static int iommu_group_do_attach_device(struct device *dev, void *data)
2056 struct iommu_domain *domain = data;
2058 return __iommu_attach_device(domain, dev);
2061 static int __iommu_attach_group(struct iommu_domain *domain,
2062 struct iommu_group *group)
2066 if (group->domain && group->domain != group->default_domain &&
2067 group->domain != group->blocking_domain)
2070 ret = __iommu_group_for_each_dev(group, domain,
2071 iommu_group_do_attach_device);
2073 group->domain = domain;
2078 int iommu_attach_group(struct iommu_domain *domain, struct iommu_group *group)
2082 mutex_lock(&group->mutex);
2083 ret = __iommu_attach_group(domain, group);
2084 mutex_unlock(&group->mutex);
2088 EXPORT_SYMBOL_GPL(iommu_attach_group);
2090 static int iommu_group_do_detach_device(struct device *dev, void *data)
2092 struct iommu_domain *domain = data;
2094 __iommu_detach_device(domain, dev);
2099 static int __iommu_group_set_domain(struct iommu_group *group,
2100 struct iommu_domain *new_domain)
2104 if (group->domain == new_domain)
2108 * New drivers should support default domains and so the detach_dev() op
2109 * will never be called. Otherwise the NULL domain represents some
2110 * platform specific behavior.
2113 if (WARN_ON(!group->domain->ops->detach_dev))
2115 __iommu_group_for_each_dev(group, group->domain,
2116 iommu_group_do_detach_device);
2117 group->domain = NULL;
2122 * Changing the domain is done by calling attach_dev() on the new
2123 * domain. This switch does not have to be atomic and DMA can be
2124 * discarded during the transition. DMA must only be able to access
2125 * either new_domain or group->domain, never something else.
2127 * Note that this is called in error unwind paths, attaching to a
2128 * domain that has already been attached cannot fail.
2130 ret = __iommu_group_for_each_dev(group, new_domain,
2131 iommu_group_do_attach_device);
2134 group->domain = new_domain;
2138 void iommu_detach_group(struct iommu_domain *domain, struct iommu_group *group)
2140 mutex_lock(&group->mutex);
2141 __iommu_group_set_core_domain(group);
2142 mutex_unlock(&group->mutex);
2144 EXPORT_SYMBOL_GPL(iommu_detach_group);
2146 phys_addr_t iommu_iova_to_phys(struct iommu_domain *domain, dma_addr_t iova)
2148 if (domain->type == IOMMU_DOMAIN_IDENTITY)
2151 if (domain->type == IOMMU_DOMAIN_BLOCKED)
2154 return domain->ops->iova_to_phys(domain, iova);
2156 EXPORT_SYMBOL_GPL(iommu_iova_to_phys);
2158 static size_t iommu_pgsize(struct iommu_domain *domain, unsigned long iova,
2159 phys_addr_t paddr, size_t size, size_t *count)
2161 unsigned int pgsize_idx, pgsize_idx_next;
2162 unsigned long pgsizes;
2163 size_t offset, pgsize, pgsize_next;
2164 unsigned long addr_merge = paddr | iova;
2166 /* Page sizes supported by the hardware and small enough for @size */
2167 pgsizes = domain->pgsize_bitmap & GENMASK(__fls(size), 0);
2169 /* Constrain the page sizes further based on the maximum alignment */
2170 if (likely(addr_merge))
2171 pgsizes &= GENMASK(__ffs(addr_merge), 0);
2173 /* Make sure we have at least one suitable page size */
2176 /* Pick the biggest page size remaining */
2177 pgsize_idx = __fls(pgsizes);
2178 pgsize = BIT(pgsize_idx);
2182 /* Find the next biggest support page size, if it exists */
2183 pgsizes = domain->pgsize_bitmap & ~GENMASK(pgsize_idx, 0);
2187 pgsize_idx_next = __ffs(pgsizes);
2188 pgsize_next = BIT(pgsize_idx_next);
2191 * There's no point trying a bigger page size unless the virtual
2192 * and physical addresses are similarly offset within the larger page.
2194 if ((iova ^ paddr) & (pgsize_next - 1))
2197 /* Calculate the offset to the next page size alignment boundary */
2198 offset = pgsize_next - (addr_merge & (pgsize_next - 1));
2201 * If size is big enough to accommodate the larger page, reduce
2202 * the number of smaller pages.
2204 if (offset + pgsize_next <= size)
2208 *count = size >> pgsize_idx;
2212 static int __iommu_map_pages(struct iommu_domain *domain, unsigned long iova,
2213 phys_addr_t paddr, size_t size, int prot,
2214 gfp_t gfp, size_t *mapped)
2216 const struct iommu_domain_ops *ops = domain->ops;
2217 size_t pgsize, count;
2220 pgsize = iommu_pgsize(domain, iova, paddr, size, &count);
2222 pr_debug("mapping: iova 0x%lx pa %pa pgsize 0x%zx count %zu\n",
2223 iova, &paddr, pgsize, count);
2225 if (ops->map_pages) {
2226 ret = ops->map_pages(domain, iova, paddr, pgsize, count, prot,
2229 ret = ops->map(domain, iova, paddr, pgsize, prot, gfp);
2230 *mapped = ret ? 0 : pgsize;
2236 static int __iommu_map(struct iommu_domain *domain, unsigned long iova,
2237 phys_addr_t paddr, size_t size, int prot, gfp_t gfp)
2239 const struct iommu_domain_ops *ops = domain->ops;
2240 unsigned long orig_iova = iova;
2241 unsigned int min_pagesz;
2242 size_t orig_size = size;
2243 phys_addr_t orig_paddr = paddr;
2246 if (unlikely(!(ops->map || ops->map_pages) ||
2247 domain->pgsize_bitmap == 0UL))
2250 if (unlikely(!(domain->type & __IOMMU_DOMAIN_PAGING)))
2253 /* find out the minimum page size supported */
2254 min_pagesz = 1 << __ffs(domain->pgsize_bitmap);
2257 * both the virtual address and the physical one, as well as
2258 * the size of the mapping, must be aligned (at least) to the
2259 * size of the smallest page supported by the hardware
2261 if (!IS_ALIGNED(iova | paddr | size, min_pagesz)) {
2262 pr_err("unaligned: iova 0x%lx pa %pa size 0x%zx min_pagesz 0x%x\n",
2263 iova, &paddr, size, min_pagesz);
2267 pr_debug("map: iova 0x%lx pa %pa size 0x%zx\n", iova, &paddr, size);
2272 ret = __iommu_map_pages(domain, iova, paddr, size, prot, gfp,
2275 * Some pages may have been mapped, even if an error occurred,
2276 * so we should account for those so they can be unmapped.
2287 /* unroll mapping in case something went wrong */
2289 iommu_unmap(domain, orig_iova, orig_size - size);
2291 trace_map(orig_iova, orig_paddr, orig_size);
2296 static int _iommu_map(struct iommu_domain *domain, unsigned long iova,
2297 phys_addr_t paddr, size_t size, int prot, gfp_t gfp)
2299 const struct iommu_domain_ops *ops = domain->ops;
2302 ret = __iommu_map(domain, iova, paddr, size, prot, gfp);
2303 if (ret == 0 && ops->iotlb_sync_map)
2304 ops->iotlb_sync_map(domain, iova, size);
2309 int iommu_map(struct iommu_domain *domain, unsigned long iova,
2310 phys_addr_t paddr, size_t size, int prot)
2313 return _iommu_map(domain, iova, paddr, size, prot, GFP_KERNEL);
2315 EXPORT_SYMBOL_GPL(iommu_map);
2317 int iommu_map_atomic(struct iommu_domain *domain, unsigned long iova,
2318 phys_addr_t paddr, size_t size, int prot)
2320 return _iommu_map(domain, iova, paddr, size, prot, GFP_ATOMIC);
2322 EXPORT_SYMBOL_GPL(iommu_map_atomic);
2324 static size_t __iommu_unmap_pages(struct iommu_domain *domain,
2325 unsigned long iova, size_t size,
2326 struct iommu_iotlb_gather *iotlb_gather)
2328 const struct iommu_domain_ops *ops = domain->ops;
2329 size_t pgsize, count;
2331 pgsize = iommu_pgsize(domain, iova, iova, size, &count);
2332 return ops->unmap_pages ?
2333 ops->unmap_pages(domain, iova, pgsize, count, iotlb_gather) :
2334 ops->unmap(domain, iova, pgsize, iotlb_gather);
2337 static size_t __iommu_unmap(struct iommu_domain *domain,
2338 unsigned long iova, size_t size,
2339 struct iommu_iotlb_gather *iotlb_gather)
2341 const struct iommu_domain_ops *ops = domain->ops;
2342 size_t unmapped_page, unmapped = 0;
2343 unsigned long orig_iova = iova;
2344 unsigned int min_pagesz;
2346 if (unlikely(!(ops->unmap || ops->unmap_pages) ||
2347 domain->pgsize_bitmap == 0UL))
2350 if (unlikely(!(domain->type & __IOMMU_DOMAIN_PAGING)))
2353 /* find out the minimum page size supported */
2354 min_pagesz = 1 << __ffs(domain->pgsize_bitmap);
2357 * The virtual address, as well as the size of the mapping, must be
2358 * aligned (at least) to the size of the smallest page supported
2361 if (!IS_ALIGNED(iova | size, min_pagesz)) {
2362 pr_err("unaligned: iova 0x%lx size 0x%zx min_pagesz 0x%x\n",
2363 iova, size, min_pagesz);
2367 pr_debug("unmap this: iova 0x%lx size 0x%zx\n", iova, size);
2370 * Keep iterating until we either unmap 'size' bytes (or more)
2371 * or we hit an area that isn't mapped.
2373 while (unmapped < size) {
2374 unmapped_page = __iommu_unmap_pages(domain, iova,
2380 pr_debug("unmapped: iova 0x%lx size 0x%zx\n",
2381 iova, unmapped_page);
2383 iova += unmapped_page;
2384 unmapped += unmapped_page;
2387 trace_unmap(orig_iova, size, unmapped);
2391 size_t iommu_unmap(struct iommu_domain *domain,
2392 unsigned long iova, size_t size)
2394 struct iommu_iotlb_gather iotlb_gather;
2397 iommu_iotlb_gather_init(&iotlb_gather);
2398 ret = __iommu_unmap(domain, iova, size, &iotlb_gather);
2399 iommu_iotlb_sync(domain, &iotlb_gather);
2403 EXPORT_SYMBOL_GPL(iommu_unmap);
2405 size_t iommu_unmap_fast(struct iommu_domain *domain,
2406 unsigned long iova, size_t size,
2407 struct iommu_iotlb_gather *iotlb_gather)
2409 return __iommu_unmap(domain, iova, size, iotlb_gather);
2411 EXPORT_SYMBOL_GPL(iommu_unmap_fast);
2413 static ssize_t __iommu_map_sg(struct iommu_domain *domain, unsigned long iova,
2414 struct scatterlist *sg, unsigned int nents, int prot,
2417 const struct iommu_domain_ops *ops = domain->ops;
2418 size_t len = 0, mapped = 0;
2423 while (i <= nents) {
2424 phys_addr_t s_phys = sg_phys(sg);
2426 if (len && s_phys != start + len) {
2427 ret = __iommu_map(domain, iova + mapped, start,
2437 if (sg_is_dma_bus_address(sg))
2452 if (ops->iotlb_sync_map)
2453 ops->iotlb_sync_map(domain, iova, mapped);
2457 /* undo mappings already done */
2458 iommu_unmap(domain, iova, mapped);
2463 ssize_t iommu_map_sg(struct iommu_domain *domain, unsigned long iova,
2464 struct scatterlist *sg, unsigned int nents, int prot)
2467 return __iommu_map_sg(domain, iova, sg, nents, prot, GFP_KERNEL);
2469 EXPORT_SYMBOL_GPL(iommu_map_sg);
2471 ssize_t iommu_map_sg_atomic(struct iommu_domain *domain, unsigned long iova,
2472 struct scatterlist *sg, unsigned int nents, int prot)
2474 return __iommu_map_sg(domain, iova, sg, nents, prot, GFP_ATOMIC);
2478 * report_iommu_fault() - report about an IOMMU fault to the IOMMU framework
2479 * @domain: the iommu domain where the fault has happened
2480 * @dev: the device where the fault has happened
2481 * @iova: the faulting address
2482 * @flags: mmu fault flags (e.g. IOMMU_FAULT_READ/IOMMU_FAULT_WRITE/...)
2484 * This function should be called by the low-level IOMMU implementations
2485 * whenever IOMMU faults happen, to allow high-level users, that are
2486 * interested in such events, to know about them.
2488 * This event may be useful for several possible use cases:
2489 * - mere logging of the event
2490 * - dynamic TLB/PTE loading
2491 * - if restarting of the faulting device is required
2493 * Returns 0 on success and an appropriate error code otherwise (if dynamic
2494 * PTE/TLB loading will one day be supported, implementations will be able
2495 * to tell whether it succeeded or not according to this return value).
2497 * Specifically, -ENOSYS is returned if a fault handler isn't installed
2498 * (though fault handlers can also return -ENOSYS, in case they want to
2499 * elicit the default behavior of the IOMMU drivers).
2501 int report_iommu_fault(struct iommu_domain *domain, struct device *dev,
2502 unsigned long iova, int flags)
2507 * if upper layers showed interest and installed a fault handler,
2510 if (domain->handler)
2511 ret = domain->handler(domain, dev, iova, flags,
2512 domain->handler_token);
2514 trace_io_page_fault(dev, iova, flags);
2517 EXPORT_SYMBOL_GPL(report_iommu_fault);
2519 static int __init iommu_init(void)
2521 iommu_group_kset = kset_create_and_add("iommu_groups",
2523 BUG_ON(!iommu_group_kset);
2525 iommu_debugfs_setup();
2529 core_initcall(iommu_init);
2531 int iommu_enable_nesting(struct iommu_domain *domain)
2533 if (domain->type != IOMMU_DOMAIN_UNMANAGED)
2535 if (!domain->ops->enable_nesting)
2537 return domain->ops->enable_nesting(domain);
2539 EXPORT_SYMBOL_GPL(iommu_enable_nesting);
2541 int iommu_set_pgtable_quirks(struct iommu_domain *domain,
2542 unsigned long quirk)
2544 if (domain->type != IOMMU_DOMAIN_UNMANAGED)
2546 if (!domain->ops->set_pgtable_quirks)
2548 return domain->ops->set_pgtable_quirks(domain, quirk);
2550 EXPORT_SYMBOL_GPL(iommu_set_pgtable_quirks);
2552 void iommu_get_resv_regions(struct device *dev, struct list_head *list)
2554 const struct iommu_ops *ops = dev_iommu_ops(dev);
2556 if (ops->get_resv_regions)
2557 ops->get_resv_regions(dev, list);
2561 * iommu_put_resv_regions - release resered regions
2562 * @dev: device for which to free reserved regions
2563 * @list: reserved region list for device
2565 * This releases a reserved region list acquired by iommu_get_resv_regions().
2567 void iommu_put_resv_regions(struct device *dev, struct list_head *list)
2569 struct iommu_resv_region *entry, *next;
2571 list_for_each_entry_safe(entry, next, list, list) {
2573 entry->free(dev, entry);
2578 EXPORT_SYMBOL(iommu_put_resv_regions);
2580 struct iommu_resv_region *iommu_alloc_resv_region(phys_addr_t start,
2581 size_t length, int prot,
2582 enum iommu_resv_type type,
2585 struct iommu_resv_region *region;
2587 region = kzalloc(sizeof(*region), gfp);
2591 INIT_LIST_HEAD(®ion->list);
2592 region->start = start;
2593 region->length = length;
2594 region->prot = prot;
2595 region->type = type;
2598 EXPORT_SYMBOL_GPL(iommu_alloc_resv_region);
2600 void iommu_set_default_passthrough(bool cmd_line)
2603 iommu_cmd_line |= IOMMU_CMD_LINE_DMA_API;
2604 iommu_def_domain_type = IOMMU_DOMAIN_IDENTITY;
2607 void iommu_set_default_translated(bool cmd_line)
2610 iommu_cmd_line |= IOMMU_CMD_LINE_DMA_API;
2611 iommu_def_domain_type = IOMMU_DOMAIN_DMA;
2614 bool iommu_default_passthrough(void)
2616 return iommu_def_domain_type == IOMMU_DOMAIN_IDENTITY;
2618 EXPORT_SYMBOL_GPL(iommu_default_passthrough);
2620 const struct iommu_ops *iommu_ops_from_fwnode(struct fwnode_handle *fwnode)
2622 const struct iommu_ops *ops = NULL;
2623 struct iommu_device *iommu;
2625 spin_lock(&iommu_device_lock);
2626 list_for_each_entry(iommu, &iommu_device_list, list)
2627 if (iommu->fwnode == fwnode) {
2631 spin_unlock(&iommu_device_lock);
2635 int iommu_fwspec_init(struct device *dev, struct fwnode_handle *iommu_fwnode,
2636 const struct iommu_ops *ops)
2638 struct iommu_fwspec *fwspec = dev_iommu_fwspec_get(dev);
2641 return ops == fwspec->ops ? 0 : -EINVAL;
2643 if (!dev_iommu_get(dev))
2646 /* Preallocate for the overwhelmingly common case of 1 ID */
2647 fwspec = kzalloc(struct_size(fwspec, ids, 1), GFP_KERNEL);
2651 of_node_get(to_of_node(iommu_fwnode));
2652 fwspec->iommu_fwnode = iommu_fwnode;
2654 dev_iommu_fwspec_set(dev, fwspec);
2657 EXPORT_SYMBOL_GPL(iommu_fwspec_init);
2659 void iommu_fwspec_free(struct device *dev)
2661 struct iommu_fwspec *fwspec = dev_iommu_fwspec_get(dev);
2664 fwnode_handle_put(fwspec->iommu_fwnode);
2666 dev_iommu_fwspec_set(dev, NULL);
2669 EXPORT_SYMBOL_GPL(iommu_fwspec_free);
2671 int iommu_fwspec_add_ids(struct device *dev, u32 *ids, int num_ids)
2673 struct iommu_fwspec *fwspec = dev_iommu_fwspec_get(dev);
2679 new_num = fwspec->num_ids + num_ids;
2681 fwspec = krealloc(fwspec, struct_size(fwspec, ids, new_num),
2686 dev_iommu_fwspec_set(dev, fwspec);
2689 for (i = 0; i < num_ids; i++)
2690 fwspec->ids[fwspec->num_ids + i] = ids[i];
2692 fwspec->num_ids = new_num;
2695 EXPORT_SYMBOL_GPL(iommu_fwspec_add_ids);
2698 * Per device IOMMU features.
2700 int iommu_dev_enable_feature(struct device *dev, enum iommu_dev_features feat)
2702 if (dev->iommu && dev->iommu->iommu_dev) {
2703 const struct iommu_ops *ops = dev->iommu->iommu_dev->ops;
2705 if (ops->dev_enable_feat)
2706 return ops->dev_enable_feat(dev, feat);
2711 EXPORT_SYMBOL_GPL(iommu_dev_enable_feature);
2714 * The device drivers should do the necessary cleanups before calling this.
2716 int iommu_dev_disable_feature(struct device *dev, enum iommu_dev_features feat)
2718 if (dev->iommu && dev->iommu->iommu_dev) {
2719 const struct iommu_ops *ops = dev->iommu->iommu_dev->ops;
2721 if (ops->dev_disable_feat)
2722 return ops->dev_disable_feat(dev, feat);
2727 EXPORT_SYMBOL_GPL(iommu_dev_disable_feature);
2730 * iommu_sva_bind_device() - Bind a process address space to a device
2732 * @mm: the mm to bind, caller must hold a reference to it
2733 * @drvdata: opaque data pointer to pass to bind callback
2735 * Create a bond between device and address space, allowing the device to access
2736 * the mm using the returned PASID. If a bond already exists between @device and
2737 * @mm, it is returned and an additional reference is taken. Caller must call
2738 * iommu_sva_unbind_device() to release each reference.
2740 * iommu_dev_enable_feature(dev, IOMMU_DEV_FEAT_SVA) must be called first, to
2741 * initialize the required SVA features.
2743 * On error, returns an ERR_PTR value.
2746 iommu_sva_bind_device(struct device *dev, struct mm_struct *mm, void *drvdata)
2748 struct iommu_group *group;
2749 struct iommu_sva *handle = ERR_PTR(-EINVAL);
2750 const struct iommu_ops *ops = dev_iommu_ops(dev);
2753 return ERR_PTR(-ENODEV);
2755 group = iommu_group_get(dev);
2757 return ERR_PTR(-ENODEV);
2759 /* Ensure device count and domain don't change while we're binding */
2760 mutex_lock(&group->mutex);
2763 * To keep things simple, SVA currently doesn't support IOMMU groups
2764 * with more than one device. Existing SVA-capable systems are not
2765 * affected by the problems that required IOMMU groups (lack of ACS
2766 * isolation, device ID aliasing and other hardware issues).
2768 if (iommu_group_device_count(group) != 1)
2771 handle = ops->sva_bind(dev, mm, drvdata);
2774 mutex_unlock(&group->mutex);
2775 iommu_group_put(group);
2779 EXPORT_SYMBOL_GPL(iommu_sva_bind_device);
2782 * iommu_sva_unbind_device() - Remove a bond created with iommu_sva_bind_device
2783 * @handle: the handle returned by iommu_sva_bind_device()
2785 * Put reference to a bond between device and address space. The device should
2786 * not be issuing any more transaction for this PASID. All outstanding page
2787 * requests for this PASID must have been flushed to the IOMMU.
2789 void iommu_sva_unbind_device(struct iommu_sva *handle)
2791 struct iommu_group *group;
2792 struct device *dev = handle->dev;
2793 const struct iommu_ops *ops = dev_iommu_ops(dev);
2795 if (!ops->sva_unbind)
2798 group = iommu_group_get(dev);
2802 mutex_lock(&group->mutex);
2803 ops->sva_unbind(handle);
2804 mutex_unlock(&group->mutex);
2806 iommu_group_put(group);
2808 EXPORT_SYMBOL_GPL(iommu_sva_unbind_device);
2810 u32 iommu_sva_get_pasid(struct iommu_sva *handle)
2812 const struct iommu_ops *ops = dev_iommu_ops(handle->dev);
2814 if (!ops->sva_get_pasid)
2815 return IOMMU_PASID_INVALID;
2817 return ops->sva_get_pasid(handle);
2819 EXPORT_SYMBOL_GPL(iommu_sva_get_pasid);
2822 * Changes the default domain of an iommu group that has *only* one device
2824 * @group: The group for which the default domain should be changed
2825 * @prev_dev: The device in the group (this is used to make sure that the device
2826 * hasn't changed after the caller has called this function)
2827 * @type: The type of the new default domain that gets associated with the group
2829 * Returns 0 on success and error code on failure
2832 * 1. Presently, this function is called only when user requests to change the
2833 * group's default domain type through /sys/kernel/iommu_groups/<grp_id>/type
2834 * Please take a closer look if intended to use for other purposes.
2836 static int iommu_change_dev_def_domain(struct iommu_group *group,
2837 struct device *prev_dev, int type)
2839 struct iommu_domain *prev_dom;
2840 struct group_device *grp_dev;
2841 int ret, dev_def_dom;
2844 mutex_lock(&group->mutex);
2846 if (group->default_domain != group->domain) {
2847 dev_err_ratelimited(prev_dev, "Group not assigned to default domain\n");
2853 * iommu group wasn't locked while acquiring device lock in
2854 * iommu_group_store_type(). So, make sure that the device count hasn't
2855 * changed while acquiring device lock.
2857 * Changing default domain of an iommu group with two or more devices
2858 * isn't supported because there could be a potential deadlock. Consider
2859 * the following scenario. T1 is trying to acquire device locks of all
2860 * the devices in the group and before it could acquire all of them,
2861 * there could be another thread T2 (from different sub-system and use
2862 * case) that has already acquired some of the device locks and might be
2863 * waiting for T1 to release other device locks.
2865 if (iommu_group_device_count(group) != 1) {
2866 dev_err_ratelimited(prev_dev, "Cannot change default domain: Group has more than one device\n");
2871 /* Since group has only one device */
2872 grp_dev = list_first_entry(&group->devices, struct group_device, list);
2875 if (prev_dev != dev) {
2876 dev_err_ratelimited(prev_dev, "Cannot change default domain: Device has been changed\n");
2881 prev_dom = group->default_domain;
2887 dev_def_dom = iommu_get_def_domain_type(dev);
2890 * If the user hasn't requested any specific type of domain and
2891 * if the device supports both the domains, then default to the
2892 * domain the device was booted with
2894 type = dev_def_dom ? : iommu_def_domain_type;
2895 } else if (dev_def_dom && type != dev_def_dom) {
2896 dev_err_ratelimited(prev_dev, "Device cannot be in %s domain\n",
2897 iommu_domain_type_str(type));
2903 * Switch to a new domain only if the requested domain type is different
2904 * from the existing default domain type
2906 if (prev_dom->type == type) {
2911 /* We can bring up a flush queue without tearing down the domain */
2912 if (type == IOMMU_DOMAIN_DMA_FQ && prev_dom->type == IOMMU_DOMAIN_DMA) {
2913 ret = iommu_dma_init_fq(prev_dom);
2915 prev_dom->type = IOMMU_DOMAIN_DMA_FQ;
2919 /* Sets group->default_domain to the newly allocated domain */
2920 ret = iommu_group_alloc_default_domain(dev->bus, group, type);
2924 ret = iommu_create_device_direct_mappings(group, dev);
2926 goto free_new_domain;
2928 ret = __iommu_attach_device(group->default_domain, dev);
2930 goto free_new_domain;
2932 group->domain = group->default_domain;
2935 * Release the mutex here because ops->probe_finalize() call-back of
2936 * some vendor IOMMU drivers calls arm_iommu_attach_device() which
2937 * in-turn might call back into IOMMU core code, where it tries to take
2938 * group->mutex, resulting in a deadlock.
2940 mutex_unlock(&group->mutex);
2942 /* Make sure dma_ops is appropriatley set */
2943 iommu_group_do_probe_finalize(dev, group->default_domain);
2944 iommu_domain_free(prev_dom);
2948 iommu_domain_free(group->default_domain);
2949 group->default_domain = prev_dom;
2950 group->domain = prev_dom;
2953 mutex_unlock(&group->mutex);
2959 * Changing the default domain through sysfs requires the users to unbind the
2960 * drivers from the devices in the iommu group, except for a DMA -> DMA-FQ
2961 * transition. Return failure if this isn't met.
2963 * We need to consider the race between this and the device release path.
2964 * device_lock(dev) is used here to guarantee that the device release path
2965 * will not be entered at the same time.
2967 static ssize_t iommu_group_store_type(struct iommu_group *group,
2968 const char *buf, size_t count)
2970 struct group_device *grp_dev;
2974 if (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO))
2977 if (WARN_ON(!group) || !group->default_domain)
2980 if (sysfs_streq(buf, "identity"))
2981 req_type = IOMMU_DOMAIN_IDENTITY;
2982 else if (sysfs_streq(buf, "DMA"))
2983 req_type = IOMMU_DOMAIN_DMA;
2984 else if (sysfs_streq(buf, "DMA-FQ"))
2985 req_type = IOMMU_DOMAIN_DMA_FQ;
2986 else if (sysfs_streq(buf, "auto"))
2992 * Lock/Unlock the group mutex here before device lock to
2993 * 1. Make sure that the iommu group has only one device (this is a
2994 * prerequisite for step 2)
2995 * 2. Get struct *dev which is needed to lock device
2997 mutex_lock(&group->mutex);
2998 if (iommu_group_device_count(group) != 1) {
2999 mutex_unlock(&group->mutex);
3000 pr_err_ratelimited("Cannot change default domain: Group has more than one device\n");
3004 /* Since group has only one device */
3005 grp_dev = list_first_entry(&group->devices, struct group_device, list);
3010 * Don't hold the group mutex because taking group mutex first and then
3011 * the device lock could potentially cause a deadlock as below. Assume
3012 * two threads T1 and T2. T1 is trying to change default domain of an
3013 * iommu group and T2 is trying to hot unplug a device or release [1] VF
3014 * of a PCIe device which is in the same iommu group. T1 takes group
3015 * mutex and before it could take device lock assume T2 has taken device
3016 * lock and is yet to take group mutex. Now, both the threads will be
3017 * waiting for the other thread to release lock. Below, lock order was
3020 * mutex_lock(&group->mutex);
3021 * iommu_change_dev_def_domain();
3022 * mutex_unlock(&group->mutex);
3023 * device_unlock(dev);
3025 * [1] Typical device release path
3026 * device_lock() from device/driver core code
3028 * -> iommu_bus_notifier()
3029 * -> iommu_release_device()
3030 * -> ops->release_device() vendor driver calls back iommu core code
3031 * -> mutex_lock() from iommu core code
3033 mutex_unlock(&group->mutex);
3035 /* Check if the device in the group still has a driver bound to it */
3037 if (device_is_bound(dev) && !(req_type == IOMMU_DOMAIN_DMA_FQ &&
3038 group->default_domain->type == IOMMU_DOMAIN_DMA)) {
3039 pr_err_ratelimited("Device is still bound to driver\n");
3044 ret = iommu_change_dev_def_domain(group, dev, req_type);
3054 static bool iommu_is_default_domain(struct iommu_group *group)
3056 if (group->domain == group->default_domain)
3060 * If the default domain was set to identity and it is still an identity
3061 * domain then we consider this a pass. This happens because of
3062 * amd_iommu_init_device() replacing the default idenytity domain with an
3063 * identity domain that has a different configuration for AMDGPU.
3065 if (group->default_domain &&
3066 group->default_domain->type == IOMMU_DOMAIN_IDENTITY &&
3067 group->domain && group->domain->type == IOMMU_DOMAIN_IDENTITY)
3073 * iommu_device_use_default_domain() - Device driver wants to handle device
3074 * DMA through the kernel DMA API.
3077 * The device driver about to bind @dev wants to do DMA through the kernel
3078 * DMA API. Return 0 if it is allowed, otherwise an error.
3080 int iommu_device_use_default_domain(struct device *dev)
3082 struct iommu_group *group = iommu_group_get(dev);
3088 mutex_lock(&group->mutex);
3089 if (group->owner_cnt) {
3090 if (group->owner || !iommu_is_default_domain(group)) {
3099 mutex_unlock(&group->mutex);
3100 iommu_group_put(group);
3106 * iommu_device_unuse_default_domain() - Device driver stops handling device
3107 * DMA through the kernel DMA API.
3110 * The device driver doesn't want to do DMA through kernel DMA API anymore.
3111 * It must be called after iommu_device_use_default_domain().
3113 void iommu_device_unuse_default_domain(struct device *dev)
3115 struct iommu_group *group = iommu_group_get(dev);
3120 mutex_lock(&group->mutex);
3121 if (!WARN_ON(!group->owner_cnt))
3124 mutex_unlock(&group->mutex);
3125 iommu_group_put(group);
3128 static int __iommu_group_alloc_blocking_domain(struct iommu_group *group)
3130 struct group_device *dev =
3131 list_first_entry(&group->devices, struct group_device, list);
3133 if (group->blocking_domain)
3136 group->blocking_domain =
3137 __iommu_domain_alloc(dev->dev->bus, IOMMU_DOMAIN_BLOCKED);
3138 if (!group->blocking_domain) {
3140 * For drivers that do not yet understand IOMMU_DOMAIN_BLOCKED
3141 * create an empty domain instead.
3143 group->blocking_domain = __iommu_domain_alloc(
3144 dev->dev->bus, IOMMU_DOMAIN_UNMANAGED);
3145 if (!group->blocking_domain)
3152 * iommu_group_claim_dma_owner() - Set DMA ownership of a group
3153 * @group: The group.
3154 * @owner: Caller specified pointer. Used for exclusive ownership.
3156 * This is to support backward compatibility for vfio which manages
3157 * the dma ownership in iommu_group level. New invocations on this
3158 * interface should be prohibited.
3160 int iommu_group_claim_dma_owner(struct iommu_group *group, void *owner)
3164 mutex_lock(&group->mutex);
3165 if (group->owner_cnt) {
3169 if (group->domain && group->domain != group->default_domain) {
3174 ret = __iommu_group_alloc_blocking_domain(group);
3178 ret = __iommu_group_set_domain(group, group->blocking_domain);
3181 group->owner = owner;
3186 mutex_unlock(&group->mutex);
3190 EXPORT_SYMBOL_GPL(iommu_group_claim_dma_owner);
3193 * iommu_group_release_dma_owner() - Release DMA ownership of a group
3194 * @group: The group.
3196 * Release the DMA ownership claimed by iommu_group_claim_dma_owner().
3198 void iommu_group_release_dma_owner(struct iommu_group *group)
3202 mutex_lock(&group->mutex);
3203 if (WARN_ON(!group->owner_cnt || !group->owner))
3206 group->owner_cnt = 0;
3207 group->owner = NULL;
3208 ret = __iommu_group_set_domain(group, group->default_domain);
3209 WARN(ret, "iommu driver failed to attach the default domain");
3212 mutex_unlock(&group->mutex);
3214 EXPORT_SYMBOL_GPL(iommu_group_release_dma_owner);
3217 * iommu_group_dma_owner_claimed() - Query group dma ownership status
3218 * @group: The group.
3220 * This provides status query on a given group. It is racy and only for
3221 * non-binding status reporting.
3223 bool iommu_group_dma_owner_claimed(struct iommu_group *group)
3227 mutex_lock(&group->mutex);
3228 user = group->owner_cnt;
3229 mutex_unlock(&group->mutex);
3233 EXPORT_SYMBOL_GPL(iommu_group_dma_owner_claimed);