1 // SPDX-License-Identifier: GPL-2.0-only
3 * Copyright (C) 2007-2008 Advanced Micro Devices, Inc.
4 * Author: Joerg Roedel <jroedel@suse.de>
7 #define pr_fmt(fmt) "iommu: " fmt
9 #include <linux/device.h>
10 #include <linux/dma-iommu.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/iommu.h>
20 #include <linux/idr.h>
21 #include <linux/err.h>
22 #include <linux/pci.h>
23 #include <linux/bitops.h>
24 #include <linux/property.h>
25 #include <linux/fsl/mc.h>
26 #include <linux/module.h>
27 #include <linux/cc_platform.h>
28 #include <trace/events/iommu.h>
30 static struct kset *iommu_group_kset;
31 static DEFINE_IDA(iommu_group_ida);
33 static unsigned int iommu_def_domain_type __read_mostly;
34 static bool iommu_dma_strict __read_mostly = IS_ENABLED(CONFIG_IOMMU_DEFAULT_DMA_STRICT);
35 static u32 iommu_cmd_line __read_mostly;
39 struct kobject *devices_kobj;
40 struct list_head devices;
43 void (*iommu_data_release)(void *iommu_data);
46 struct iommu_domain *default_domain;
47 struct iommu_domain *blocking_domain;
48 struct iommu_domain *domain;
49 struct list_head entry;
50 unsigned int owner_cnt;
55 struct list_head list;
60 struct iommu_group_attribute {
61 struct attribute attr;
62 ssize_t (*show)(struct iommu_group *group, char *buf);
63 ssize_t (*store)(struct iommu_group *group,
64 const char *buf, size_t count);
67 static const char * const iommu_group_resv_type_string[] = {
68 [IOMMU_RESV_DIRECT] = "direct",
69 [IOMMU_RESV_DIRECT_RELAXABLE] = "direct-relaxable",
70 [IOMMU_RESV_RESERVED] = "reserved",
71 [IOMMU_RESV_MSI] = "msi",
72 [IOMMU_RESV_SW_MSI] = "msi",
75 #define IOMMU_CMD_LINE_DMA_API BIT(0)
76 #define IOMMU_CMD_LINE_STRICT BIT(1)
78 static int iommu_alloc_default_domain(struct iommu_group *group,
80 static struct iommu_domain *__iommu_domain_alloc(struct bus_type *bus,
82 static int __iommu_attach_device(struct iommu_domain *domain,
84 static int __iommu_attach_group(struct iommu_domain *domain,
85 struct iommu_group *group);
86 static int __iommu_group_set_domain(struct iommu_group *group,
87 struct iommu_domain *new_domain);
88 static int iommu_create_device_direct_mappings(struct iommu_group *group,
90 static struct iommu_group *iommu_group_get_for_dev(struct device *dev);
91 static ssize_t iommu_group_store_type(struct iommu_group *group,
92 const char *buf, size_t count);
94 #define IOMMU_GROUP_ATTR(_name, _mode, _show, _store) \
95 struct iommu_group_attribute iommu_group_attr_##_name = \
96 __ATTR(_name, _mode, _show, _store)
98 #define to_iommu_group_attr(_attr) \
99 container_of(_attr, struct iommu_group_attribute, attr)
100 #define to_iommu_group(_kobj) \
101 container_of(_kobj, struct iommu_group, kobj)
103 static LIST_HEAD(iommu_device_list);
104 static DEFINE_SPINLOCK(iommu_device_lock);
107 * Use a function instead of an array here because the domain-type is a
108 * bit-field, so an array would waste memory.
110 static const char *iommu_domain_type_str(unsigned int t)
113 case IOMMU_DOMAIN_BLOCKED:
115 case IOMMU_DOMAIN_IDENTITY:
116 return "Passthrough";
117 case IOMMU_DOMAIN_UNMANAGED:
119 case IOMMU_DOMAIN_DMA:
120 case IOMMU_DOMAIN_DMA_FQ:
127 static int __init iommu_subsys_init(void)
129 if (!(iommu_cmd_line & IOMMU_CMD_LINE_DMA_API)) {
130 if (IS_ENABLED(CONFIG_IOMMU_DEFAULT_PASSTHROUGH))
131 iommu_set_default_passthrough(false);
133 iommu_set_default_translated(false);
135 if (iommu_default_passthrough() && cc_platform_has(CC_ATTR_MEM_ENCRYPT)) {
136 pr_info("Memory encryption detected - Disabling default IOMMU Passthrough\n");
137 iommu_set_default_translated(false);
141 if (!iommu_default_passthrough() && !iommu_dma_strict)
142 iommu_def_domain_type = IOMMU_DOMAIN_DMA_FQ;
144 pr_info("Default domain type: %s %s\n",
145 iommu_domain_type_str(iommu_def_domain_type),
146 (iommu_cmd_line & IOMMU_CMD_LINE_DMA_API) ?
147 "(set via kernel command line)" : "");
149 if (!iommu_default_passthrough())
150 pr_info("DMA domain TLB invalidation policy: %s mode %s\n",
151 iommu_dma_strict ? "strict" : "lazy",
152 (iommu_cmd_line & IOMMU_CMD_LINE_STRICT) ?
153 "(set via kernel command line)" : "");
157 subsys_initcall(iommu_subsys_init);
160 * iommu_device_register() - Register an IOMMU hardware instance
161 * @iommu: IOMMU handle for the instance
162 * @ops: IOMMU ops to associate with the instance
163 * @hwdev: (optional) actual instance device, used for fwnode lookup
165 * Return: 0 on success, or an error.
167 int iommu_device_register(struct iommu_device *iommu,
168 const struct iommu_ops *ops, struct device *hwdev)
170 /* We need to be able to take module references appropriately */
171 if (WARN_ON(is_module_address((unsigned long)ops) && !ops->owner))
176 iommu->fwnode = hwdev->fwnode;
178 spin_lock(&iommu_device_lock);
179 list_add_tail(&iommu->list, &iommu_device_list);
180 spin_unlock(&iommu_device_lock);
183 EXPORT_SYMBOL_GPL(iommu_device_register);
185 void iommu_device_unregister(struct iommu_device *iommu)
187 spin_lock(&iommu_device_lock);
188 list_del(&iommu->list);
189 spin_unlock(&iommu_device_lock);
191 EXPORT_SYMBOL_GPL(iommu_device_unregister);
193 static struct dev_iommu *dev_iommu_get(struct device *dev)
195 struct dev_iommu *param = dev->iommu;
200 param = kzalloc(sizeof(*param), GFP_KERNEL);
204 mutex_init(¶m->lock);
209 static void dev_iommu_free(struct device *dev)
211 struct dev_iommu *param = dev->iommu;
215 fwnode_handle_put(param->fwspec->iommu_fwnode);
216 kfree(param->fwspec);
221 static int __iommu_probe_device(struct device *dev, struct list_head *group_list)
223 const struct iommu_ops *ops = dev->bus->iommu_ops;
224 struct iommu_device *iommu_dev;
225 struct iommu_group *group;
231 if (!dev_iommu_get(dev))
234 if (!try_module_get(ops->owner)) {
239 iommu_dev = ops->probe_device(dev);
240 if (IS_ERR(iommu_dev)) {
241 ret = PTR_ERR(iommu_dev);
245 dev->iommu->iommu_dev = iommu_dev;
247 group = iommu_group_get_for_dev(dev);
249 ret = PTR_ERR(group);
252 iommu_group_put(group);
254 if (group_list && !group->default_domain && list_empty(&group->entry))
255 list_add_tail(&group->entry, group_list);
257 iommu_device_link(iommu_dev, dev);
262 if (ops->release_device)
263 ops->release_device(dev);
266 module_put(ops->owner);
274 int iommu_probe_device(struct device *dev)
276 const struct iommu_ops *ops;
277 struct iommu_group *group;
280 ret = __iommu_probe_device(dev, NULL);
284 group = iommu_group_get(dev);
291 * Try to allocate a default domain - needs support from the
292 * IOMMU driver. There are still some drivers which don't
293 * support default domains, so the return value is not yet
296 mutex_lock(&group->mutex);
297 iommu_alloc_default_domain(group, dev);
300 * If device joined an existing group which has been claimed, don't
301 * attach the default domain.
303 if (group->default_domain && !group->owner) {
304 ret = __iommu_attach_device(group->default_domain, dev);
306 mutex_unlock(&group->mutex);
307 iommu_group_put(group);
312 iommu_create_device_direct_mappings(group, dev);
314 mutex_unlock(&group->mutex);
315 iommu_group_put(group);
317 ops = dev_iommu_ops(dev);
318 if (ops->probe_finalize)
319 ops->probe_finalize(dev);
324 iommu_release_device(dev);
331 void iommu_release_device(struct device *dev)
333 const struct iommu_ops *ops;
338 iommu_device_unlink(dev->iommu->iommu_dev, dev);
340 ops = dev_iommu_ops(dev);
341 if (ops->release_device)
342 ops->release_device(dev);
344 iommu_group_remove_device(dev);
345 module_put(ops->owner);
349 static int __init iommu_set_def_domain_type(char *str)
354 ret = kstrtobool(str, &pt);
359 iommu_set_default_passthrough(true);
361 iommu_set_default_translated(true);
365 early_param("iommu.passthrough", iommu_set_def_domain_type);
367 static int __init iommu_dma_setup(char *str)
369 int ret = kstrtobool(str, &iommu_dma_strict);
372 iommu_cmd_line |= IOMMU_CMD_LINE_STRICT;
375 early_param("iommu.strict", iommu_dma_setup);
377 void iommu_set_dma_strict(void)
379 iommu_dma_strict = true;
380 if (iommu_def_domain_type == IOMMU_DOMAIN_DMA_FQ)
381 iommu_def_domain_type = IOMMU_DOMAIN_DMA;
384 static ssize_t iommu_group_attr_show(struct kobject *kobj,
385 struct attribute *__attr, char *buf)
387 struct iommu_group_attribute *attr = to_iommu_group_attr(__attr);
388 struct iommu_group *group = to_iommu_group(kobj);
392 ret = attr->show(group, buf);
396 static ssize_t iommu_group_attr_store(struct kobject *kobj,
397 struct attribute *__attr,
398 const char *buf, size_t count)
400 struct iommu_group_attribute *attr = to_iommu_group_attr(__attr);
401 struct iommu_group *group = to_iommu_group(kobj);
405 ret = attr->store(group, buf, count);
409 static const struct sysfs_ops iommu_group_sysfs_ops = {
410 .show = iommu_group_attr_show,
411 .store = iommu_group_attr_store,
414 static int iommu_group_create_file(struct iommu_group *group,
415 struct iommu_group_attribute *attr)
417 return sysfs_create_file(&group->kobj, &attr->attr);
420 static void iommu_group_remove_file(struct iommu_group *group,
421 struct iommu_group_attribute *attr)
423 sysfs_remove_file(&group->kobj, &attr->attr);
426 static ssize_t iommu_group_show_name(struct iommu_group *group, char *buf)
428 return sprintf(buf, "%s\n", group->name);
432 * iommu_insert_resv_region - Insert a new region in the
433 * list of reserved regions.
434 * @new: new region to insert
435 * @regions: list of regions
437 * Elements are sorted by start address and overlapping segments
438 * of the same type are merged.
440 static int iommu_insert_resv_region(struct iommu_resv_region *new,
441 struct list_head *regions)
443 struct iommu_resv_region *iter, *tmp, *nr, *top;
446 nr = iommu_alloc_resv_region(new->start, new->length,
447 new->prot, new->type);
451 /* First add the new element based on start address sorting */
452 list_for_each_entry(iter, regions, list) {
453 if (nr->start < iter->start ||
454 (nr->start == iter->start && nr->type <= iter->type))
457 list_add_tail(&nr->list, &iter->list);
459 /* Merge overlapping segments of type nr->type in @regions, if any */
460 list_for_each_entry_safe(iter, tmp, regions, list) {
461 phys_addr_t top_end, iter_end = iter->start + iter->length - 1;
463 /* no merge needed on elements of different types than @new */
464 if (iter->type != new->type) {
465 list_move_tail(&iter->list, &stack);
469 /* look for the last stack element of same type as @iter */
470 list_for_each_entry_reverse(top, &stack, list)
471 if (top->type == iter->type)
474 list_move_tail(&iter->list, &stack);
478 top_end = top->start + top->length - 1;
480 if (iter->start > top_end + 1) {
481 list_move_tail(&iter->list, &stack);
483 top->length = max(top_end, iter_end) - top->start + 1;
484 list_del(&iter->list);
488 list_splice(&stack, regions);
493 iommu_insert_device_resv_regions(struct list_head *dev_resv_regions,
494 struct list_head *group_resv_regions)
496 struct iommu_resv_region *entry;
499 list_for_each_entry(entry, dev_resv_regions, list) {
500 ret = iommu_insert_resv_region(entry, group_resv_regions);
507 int iommu_get_group_resv_regions(struct iommu_group *group,
508 struct list_head *head)
510 struct group_device *device;
513 mutex_lock(&group->mutex);
514 list_for_each_entry(device, &group->devices, list) {
515 struct list_head dev_resv_regions;
518 * Non-API groups still expose reserved_regions in sysfs,
519 * so filter out calls that get here that way.
521 if (!device->dev->iommu)
524 INIT_LIST_HEAD(&dev_resv_regions);
525 iommu_get_resv_regions(device->dev, &dev_resv_regions);
526 ret = iommu_insert_device_resv_regions(&dev_resv_regions, head);
527 iommu_put_resv_regions(device->dev, &dev_resv_regions);
531 mutex_unlock(&group->mutex);
534 EXPORT_SYMBOL_GPL(iommu_get_group_resv_regions);
536 static ssize_t iommu_group_show_resv_regions(struct iommu_group *group,
539 struct iommu_resv_region *region, *next;
540 struct list_head group_resv_regions;
543 INIT_LIST_HEAD(&group_resv_regions);
544 iommu_get_group_resv_regions(group, &group_resv_regions);
546 list_for_each_entry_safe(region, next, &group_resv_regions, list) {
547 str += sprintf(str, "0x%016llx 0x%016llx %s\n",
548 (long long int)region->start,
549 (long long int)(region->start +
551 iommu_group_resv_type_string[region->type]);
558 static ssize_t iommu_group_show_type(struct iommu_group *group,
561 char *type = "unknown\n";
563 mutex_lock(&group->mutex);
564 if (group->default_domain) {
565 switch (group->default_domain->type) {
566 case IOMMU_DOMAIN_BLOCKED:
569 case IOMMU_DOMAIN_IDENTITY:
572 case IOMMU_DOMAIN_UNMANAGED:
573 type = "unmanaged\n";
575 case IOMMU_DOMAIN_DMA:
578 case IOMMU_DOMAIN_DMA_FQ:
583 mutex_unlock(&group->mutex);
589 static IOMMU_GROUP_ATTR(name, S_IRUGO, iommu_group_show_name, NULL);
591 static IOMMU_GROUP_ATTR(reserved_regions, 0444,
592 iommu_group_show_resv_regions, NULL);
594 static IOMMU_GROUP_ATTR(type, 0644, iommu_group_show_type,
595 iommu_group_store_type);
597 static void iommu_group_release(struct kobject *kobj)
599 struct iommu_group *group = to_iommu_group(kobj);
601 pr_debug("Releasing group %d\n", group->id);
603 if (group->iommu_data_release)
604 group->iommu_data_release(group->iommu_data);
606 ida_free(&iommu_group_ida, group->id);
608 if (group->default_domain)
609 iommu_domain_free(group->default_domain);
610 if (group->blocking_domain)
611 iommu_domain_free(group->blocking_domain);
617 static struct kobj_type iommu_group_ktype = {
618 .sysfs_ops = &iommu_group_sysfs_ops,
619 .release = iommu_group_release,
623 * iommu_group_alloc - Allocate a new group
625 * This function is called by an iommu driver to allocate a new iommu
626 * group. The iommu group represents the minimum granularity of the iommu.
627 * Upon successful return, the caller holds a reference to the supplied
628 * group in order to hold the group until devices are added. Use
629 * iommu_group_put() to release this extra reference count, allowing the
630 * group to be automatically reclaimed once it has no devices or external
633 struct iommu_group *iommu_group_alloc(void)
635 struct iommu_group *group;
638 group = kzalloc(sizeof(*group), GFP_KERNEL);
640 return ERR_PTR(-ENOMEM);
642 group->kobj.kset = iommu_group_kset;
643 mutex_init(&group->mutex);
644 INIT_LIST_HEAD(&group->devices);
645 INIT_LIST_HEAD(&group->entry);
647 ret = ida_alloc(&iommu_group_ida, GFP_KERNEL);
654 ret = kobject_init_and_add(&group->kobj, &iommu_group_ktype,
655 NULL, "%d", group->id);
657 ida_free(&iommu_group_ida, group->id);
658 kobject_put(&group->kobj);
662 group->devices_kobj = kobject_create_and_add("devices", &group->kobj);
663 if (!group->devices_kobj) {
664 kobject_put(&group->kobj); /* triggers .release & free */
665 return ERR_PTR(-ENOMEM);
669 * The devices_kobj holds a reference on the group kobject, so
670 * as long as that exists so will the group. We can therefore
671 * use the devices_kobj for reference counting.
673 kobject_put(&group->kobj);
675 ret = iommu_group_create_file(group,
676 &iommu_group_attr_reserved_regions);
680 ret = iommu_group_create_file(group, &iommu_group_attr_type);
684 pr_debug("Allocated group %d\n", group->id);
688 EXPORT_SYMBOL_GPL(iommu_group_alloc);
690 struct iommu_group *iommu_group_get_by_id(int id)
692 struct kobject *group_kobj;
693 struct iommu_group *group;
696 if (!iommu_group_kset)
699 name = kasprintf(GFP_KERNEL, "%d", id);
703 group_kobj = kset_find_obj(iommu_group_kset, name);
709 group = container_of(group_kobj, struct iommu_group, kobj);
710 BUG_ON(group->id != id);
712 kobject_get(group->devices_kobj);
713 kobject_put(&group->kobj);
717 EXPORT_SYMBOL_GPL(iommu_group_get_by_id);
720 * iommu_group_get_iommudata - retrieve iommu_data registered for a group
723 * iommu drivers can store data in the group for use when doing iommu
724 * operations. This function provides a way to retrieve it. Caller
725 * should hold a group reference.
727 void *iommu_group_get_iommudata(struct iommu_group *group)
729 return group->iommu_data;
731 EXPORT_SYMBOL_GPL(iommu_group_get_iommudata);
734 * iommu_group_set_iommudata - set iommu_data for a group
736 * @iommu_data: new data
737 * @release: release function for iommu_data
739 * iommu drivers can store data in the group for use when doing iommu
740 * operations. This function provides a way to set the data after
741 * the group has been allocated. Caller should hold a group reference.
743 void iommu_group_set_iommudata(struct iommu_group *group, void *iommu_data,
744 void (*release)(void *iommu_data))
746 group->iommu_data = iommu_data;
747 group->iommu_data_release = release;
749 EXPORT_SYMBOL_GPL(iommu_group_set_iommudata);
752 * iommu_group_set_name - set name for a group
756 * Allow iommu driver to set a name for a group. When set it will
757 * appear in a name attribute file under the group in sysfs.
759 int iommu_group_set_name(struct iommu_group *group, const char *name)
764 iommu_group_remove_file(group, &iommu_group_attr_name);
771 group->name = kstrdup(name, GFP_KERNEL);
775 ret = iommu_group_create_file(group, &iommu_group_attr_name);
784 EXPORT_SYMBOL_GPL(iommu_group_set_name);
786 static int iommu_create_device_direct_mappings(struct iommu_group *group,
789 struct iommu_domain *domain = group->default_domain;
790 struct iommu_resv_region *entry;
791 struct list_head mappings;
792 unsigned long pg_size;
795 if (!domain || !iommu_is_dma_domain(domain))
798 BUG_ON(!domain->pgsize_bitmap);
800 pg_size = 1UL << __ffs(domain->pgsize_bitmap);
801 INIT_LIST_HEAD(&mappings);
803 iommu_get_resv_regions(dev, &mappings);
805 /* We need to consider overlapping regions for different devices */
806 list_for_each_entry(entry, &mappings, list) {
807 dma_addr_t start, end, addr;
810 start = ALIGN(entry->start, pg_size);
811 end = ALIGN(entry->start + entry->length, pg_size);
813 if (entry->type != IOMMU_RESV_DIRECT &&
814 entry->type != IOMMU_RESV_DIRECT_RELAXABLE)
817 for (addr = start; addr <= end; addr += pg_size) {
818 phys_addr_t phys_addr;
823 phys_addr = iommu_iova_to_phys(domain, addr);
831 ret = iommu_map(domain, addr - map_size,
832 addr - map_size, map_size,
842 iommu_flush_iotlb_all(domain);
845 iommu_put_resv_regions(dev, &mappings);
850 static bool iommu_is_attach_deferred(struct device *dev)
852 const struct iommu_ops *ops = dev_iommu_ops(dev);
854 if (ops->is_attach_deferred)
855 return ops->is_attach_deferred(dev);
861 * iommu_group_add_device - add a device to an iommu group
862 * @group: the group into which to add the device (reference should be held)
865 * This function is called by an iommu driver to add a device into a
866 * group. Adding a device increments the group reference count.
868 int iommu_group_add_device(struct iommu_group *group, struct device *dev)
871 struct group_device *device;
873 device = kzalloc(sizeof(*device), GFP_KERNEL);
879 ret = sysfs_create_link(&dev->kobj, &group->kobj, "iommu_group");
881 goto err_free_device;
883 device->name = kasprintf(GFP_KERNEL, "%s", kobject_name(&dev->kobj));
887 goto err_remove_link;
890 ret = sysfs_create_link_nowarn(group->devices_kobj,
891 &dev->kobj, device->name);
893 if (ret == -EEXIST && i >= 0) {
895 * Account for the slim chance of collision
896 * and append an instance to the name.
899 device->name = kasprintf(GFP_KERNEL, "%s.%d",
900 kobject_name(&dev->kobj), i++);
906 kobject_get(group->devices_kobj);
908 dev->iommu_group = group;
910 mutex_lock(&group->mutex);
911 list_add_tail(&device->list, &group->devices);
912 if (group->domain && !iommu_is_attach_deferred(dev))
913 ret = __iommu_attach_device(group->domain, dev);
914 mutex_unlock(&group->mutex);
918 trace_add_device_to_group(group->id, dev);
920 dev_info(dev, "Adding to iommu group %d\n", group->id);
925 mutex_lock(&group->mutex);
926 list_del(&device->list);
927 mutex_unlock(&group->mutex);
928 dev->iommu_group = NULL;
929 kobject_put(group->devices_kobj);
930 sysfs_remove_link(group->devices_kobj, device->name);
934 sysfs_remove_link(&dev->kobj, "iommu_group");
937 dev_err(dev, "Failed to add to iommu group %d: %d\n", group->id, ret);
940 EXPORT_SYMBOL_GPL(iommu_group_add_device);
943 * iommu_group_remove_device - remove a device from it's current group
944 * @dev: device to be removed
946 * This function is called by an iommu driver to remove the device from
947 * it's current group. This decrements the iommu group reference count.
949 void iommu_group_remove_device(struct device *dev)
951 struct iommu_group *group = dev->iommu_group;
952 struct group_device *tmp_device, *device = NULL;
957 dev_info(dev, "Removing from iommu group %d\n", group->id);
959 mutex_lock(&group->mutex);
960 list_for_each_entry(tmp_device, &group->devices, list) {
961 if (tmp_device->dev == dev) {
963 list_del(&device->list);
967 mutex_unlock(&group->mutex);
972 sysfs_remove_link(group->devices_kobj, device->name);
973 sysfs_remove_link(&dev->kobj, "iommu_group");
975 trace_remove_device_from_group(group->id, dev);
979 dev->iommu_group = NULL;
980 kobject_put(group->devices_kobj);
982 EXPORT_SYMBOL_GPL(iommu_group_remove_device);
984 static int iommu_group_device_count(struct iommu_group *group)
986 struct group_device *entry;
989 list_for_each_entry(entry, &group->devices, list)
995 static int __iommu_group_for_each_dev(struct iommu_group *group, void *data,
996 int (*fn)(struct device *, void *))
998 struct group_device *device;
1001 list_for_each_entry(device, &group->devices, list) {
1002 ret = fn(device->dev, data);
1010 * iommu_group_for_each_dev - iterate over each device in the group
1012 * @data: caller opaque data to be passed to callback function
1013 * @fn: caller supplied callback function
1015 * This function is called by group users to iterate over group devices.
1016 * Callers should hold a reference count to the group during callback.
1017 * The group->mutex is held across callbacks, which will block calls to
1018 * iommu_group_add/remove_device.
1020 int iommu_group_for_each_dev(struct iommu_group *group, void *data,
1021 int (*fn)(struct device *, void *))
1025 mutex_lock(&group->mutex);
1026 ret = __iommu_group_for_each_dev(group, data, fn);
1027 mutex_unlock(&group->mutex);
1031 EXPORT_SYMBOL_GPL(iommu_group_for_each_dev);
1034 * iommu_group_get - Return the group for a device and increment reference
1035 * @dev: get the group that this device belongs to
1037 * This function is called by iommu drivers and users to get the group
1038 * for the specified device. If found, the group is returned and the group
1039 * reference in incremented, else NULL.
1041 struct iommu_group *iommu_group_get(struct device *dev)
1043 struct iommu_group *group = dev->iommu_group;
1046 kobject_get(group->devices_kobj);
1050 EXPORT_SYMBOL_GPL(iommu_group_get);
1053 * iommu_group_ref_get - Increment reference on a group
1054 * @group: the group to use, must not be NULL
1056 * This function is called by iommu drivers to take additional references on an
1057 * existing group. Returns the given group for convenience.
1059 struct iommu_group *iommu_group_ref_get(struct iommu_group *group)
1061 kobject_get(group->devices_kobj);
1064 EXPORT_SYMBOL_GPL(iommu_group_ref_get);
1067 * iommu_group_put - Decrement group reference
1068 * @group: the group to use
1070 * This function is called by iommu drivers and users to release the
1071 * iommu group. Once the reference count is zero, the group is released.
1073 void iommu_group_put(struct iommu_group *group)
1076 kobject_put(group->devices_kobj);
1078 EXPORT_SYMBOL_GPL(iommu_group_put);
1081 * iommu_register_device_fault_handler() - Register a device fault handler
1083 * @handler: the fault handler
1084 * @data: private data passed as argument to the handler
1086 * When an IOMMU fault event is received, this handler gets called with the
1087 * fault event and data as argument. The handler should return 0 on success. If
1088 * the fault is recoverable (IOMMU_FAULT_PAGE_REQ), the consumer should also
1089 * complete the fault by calling iommu_page_response() with one of the following
1091 * - IOMMU_PAGE_RESP_SUCCESS: retry the translation
1092 * - IOMMU_PAGE_RESP_INVALID: terminate the fault
1093 * - IOMMU_PAGE_RESP_FAILURE: terminate the fault and stop reporting
1094 * page faults if possible.
1096 * Return 0 if the fault handler was installed successfully, or an error.
1098 int iommu_register_device_fault_handler(struct device *dev,
1099 iommu_dev_fault_handler_t handler,
1102 struct dev_iommu *param = dev->iommu;
1108 mutex_lock(¶m->lock);
1109 /* Only allow one fault handler registered for each device */
1110 if (param->fault_param) {
1116 param->fault_param = kzalloc(sizeof(*param->fault_param), GFP_KERNEL);
1117 if (!param->fault_param) {
1122 param->fault_param->handler = handler;
1123 param->fault_param->data = data;
1124 mutex_init(¶m->fault_param->lock);
1125 INIT_LIST_HEAD(¶m->fault_param->faults);
1128 mutex_unlock(¶m->lock);
1132 EXPORT_SYMBOL_GPL(iommu_register_device_fault_handler);
1135 * iommu_unregister_device_fault_handler() - Unregister the device fault handler
1138 * Remove the device fault handler installed with
1139 * iommu_register_device_fault_handler().
1141 * Return 0 on success, or an error.
1143 int iommu_unregister_device_fault_handler(struct device *dev)
1145 struct dev_iommu *param = dev->iommu;
1151 mutex_lock(¶m->lock);
1153 if (!param->fault_param)
1156 /* we cannot unregister handler if there are pending faults */
1157 if (!list_empty(¶m->fault_param->faults)) {
1162 kfree(param->fault_param);
1163 param->fault_param = NULL;
1166 mutex_unlock(¶m->lock);
1170 EXPORT_SYMBOL_GPL(iommu_unregister_device_fault_handler);
1173 * iommu_report_device_fault() - Report fault event to device driver
1175 * @evt: fault event data
1177 * Called by IOMMU drivers when a fault is detected, typically in a threaded IRQ
1178 * handler. When this function fails and the fault is recoverable, it is the
1179 * caller's responsibility to complete the fault.
1181 * Return 0 on success, or an error.
1183 int iommu_report_device_fault(struct device *dev, struct iommu_fault_event *evt)
1185 struct dev_iommu *param = dev->iommu;
1186 struct iommu_fault_event *evt_pending = NULL;
1187 struct iommu_fault_param *fparam;
1193 /* we only report device fault if there is a handler registered */
1194 mutex_lock(¶m->lock);
1195 fparam = param->fault_param;
1196 if (!fparam || !fparam->handler) {
1201 if (evt->fault.type == IOMMU_FAULT_PAGE_REQ &&
1202 (evt->fault.prm.flags & IOMMU_FAULT_PAGE_REQUEST_LAST_PAGE)) {
1203 evt_pending = kmemdup(evt, sizeof(struct iommu_fault_event),
1209 mutex_lock(&fparam->lock);
1210 list_add_tail(&evt_pending->list, &fparam->faults);
1211 mutex_unlock(&fparam->lock);
1214 ret = fparam->handler(&evt->fault, fparam->data);
1215 if (ret && evt_pending) {
1216 mutex_lock(&fparam->lock);
1217 list_del(&evt_pending->list);
1218 mutex_unlock(&fparam->lock);
1222 mutex_unlock(¶m->lock);
1225 EXPORT_SYMBOL_GPL(iommu_report_device_fault);
1227 int iommu_page_response(struct device *dev,
1228 struct iommu_page_response *msg)
1232 struct iommu_fault_event *evt;
1233 struct iommu_fault_page_request *prm;
1234 struct dev_iommu *param = dev->iommu;
1235 const struct iommu_ops *ops = dev_iommu_ops(dev);
1236 bool has_pasid = msg->flags & IOMMU_PAGE_RESP_PASID_VALID;
1238 if (!ops->page_response)
1241 if (!param || !param->fault_param)
1244 if (msg->version != IOMMU_PAGE_RESP_VERSION_1 ||
1245 msg->flags & ~IOMMU_PAGE_RESP_PASID_VALID)
1248 /* Only send response if there is a fault report pending */
1249 mutex_lock(¶m->fault_param->lock);
1250 if (list_empty(¶m->fault_param->faults)) {
1251 dev_warn_ratelimited(dev, "no pending PRQ, drop response\n");
1255 * Check if we have a matching page request pending to respond,
1256 * otherwise return -EINVAL
1258 list_for_each_entry(evt, ¶m->fault_param->faults, list) {
1259 prm = &evt->fault.prm;
1260 if (prm->grpid != msg->grpid)
1264 * If the PASID is required, the corresponding request is
1265 * matched using the group ID, the PASID valid bit and the PASID
1266 * value. Otherwise only the group ID matches request and
1269 needs_pasid = prm->flags & IOMMU_FAULT_PAGE_RESPONSE_NEEDS_PASID;
1270 if (needs_pasid && (!has_pasid || msg->pasid != prm->pasid))
1273 if (!needs_pasid && has_pasid) {
1274 /* No big deal, just clear it. */
1275 msg->flags &= ~IOMMU_PAGE_RESP_PASID_VALID;
1279 ret = ops->page_response(dev, evt, msg);
1280 list_del(&evt->list);
1286 mutex_unlock(¶m->fault_param->lock);
1289 EXPORT_SYMBOL_GPL(iommu_page_response);
1292 * iommu_group_id - Return ID for a group
1293 * @group: the group to ID
1295 * Return the unique ID for the group matching the sysfs group number.
1297 int iommu_group_id(struct iommu_group *group)
1301 EXPORT_SYMBOL_GPL(iommu_group_id);
1303 static struct iommu_group *get_pci_alias_group(struct pci_dev *pdev,
1304 unsigned long *devfns);
1307 * To consider a PCI device isolated, we require ACS to support Source
1308 * Validation, Request Redirection, Completer Redirection, and Upstream
1309 * Forwarding. This effectively means that devices cannot spoof their
1310 * requester ID, requests and completions cannot be redirected, and all
1311 * transactions are forwarded upstream, even as it passes through a
1312 * bridge where the target device is downstream.
1314 #define REQ_ACS_FLAGS (PCI_ACS_SV | PCI_ACS_RR | PCI_ACS_CR | PCI_ACS_UF)
1317 * For multifunction devices which are not isolated from each other, find
1318 * all the other non-isolated functions and look for existing groups. For
1319 * each function, we also need to look for aliases to or from other devices
1320 * that may already have a group.
1322 static struct iommu_group *get_pci_function_alias_group(struct pci_dev *pdev,
1323 unsigned long *devfns)
1325 struct pci_dev *tmp = NULL;
1326 struct iommu_group *group;
1328 if (!pdev->multifunction || pci_acs_enabled(pdev, REQ_ACS_FLAGS))
1331 for_each_pci_dev(tmp) {
1332 if (tmp == pdev || tmp->bus != pdev->bus ||
1333 PCI_SLOT(tmp->devfn) != PCI_SLOT(pdev->devfn) ||
1334 pci_acs_enabled(tmp, REQ_ACS_FLAGS))
1337 group = get_pci_alias_group(tmp, devfns);
1348 * Look for aliases to or from the given device for existing groups. DMA
1349 * aliases are only supported on the same bus, therefore the search
1350 * space is quite small (especially since we're really only looking at pcie
1351 * device, and therefore only expect multiple slots on the root complex or
1352 * downstream switch ports). It's conceivable though that a pair of
1353 * multifunction devices could have aliases between them that would cause a
1354 * loop. To prevent this, we use a bitmap to track where we've been.
1356 static struct iommu_group *get_pci_alias_group(struct pci_dev *pdev,
1357 unsigned long *devfns)
1359 struct pci_dev *tmp = NULL;
1360 struct iommu_group *group;
1362 if (test_and_set_bit(pdev->devfn & 0xff, devfns))
1365 group = iommu_group_get(&pdev->dev);
1369 for_each_pci_dev(tmp) {
1370 if (tmp == pdev || tmp->bus != pdev->bus)
1373 /* We alias them or they alias us */
1374 if (pci_devs_are_dma_aliases(pdev, tmp)) {
1375 group = get_pci_alias_group(tmp, devfns);
1381 group = get_pci_function_alias_group(tmp, devfns);
1392 struct group_for_pci_data {
1393 struct pci_dev *pdev;
1394 struct iommu_group *group;
1398 * DMA alias iterator callback, return the last seen device. Stop and return
1399 * the IOMMU group if we find one along the way.
1401 static int get_pci_alias_or_group(struct pci_dev *pdev, u16 alias, void *opaque)
1403 struct group_for_pci_data *data = opaque;
1406 data->group = iommu_group_get(&pdev->dev);
1408 return data->group != NULL;
1412 * Generic device_group call-back function. It just allocates one
1413 * iommu-group per device.
1415 struct iommu_group *generic_device_group(struct device *dev)
1417 return iommu_group_alloc();
1419 EXPORT_SYMBOL_GPL(generic_device_group);
1422 * Use standard PCI bus topology, isolation features, and DMA alias quirks
1423 * to find or create an IOMMU group for a device.
1425 struct iommu_group *pci_device_group(struct device *dev)
1427 struct pci_dev *pdev = to_pci_dev(dev);
1428 struct group_for_pci_data data;
1429 struct pci_bus *bus;
1430 struct iommu_group *group = NULL;
1431 u64 devfns[4] = { 0 };
1433 if (WARN_ON(!dev_is_pci(dev)))
1434 return ERR_PTR(-EINVAL);
1437 * Find the upstream DMA alias for the device. A device must not
1438 * be aliased due to topology in order to have its own IOMMU group.
1439 * If we find an alias along the way that already belongs to a
1442 if (pci_for_each_dma_alias(pdev, get_pci_alias_or_group, &data))
1448 * Continue upstream from the point of minimum IOMMU granularity
1449 * due to aliases to the point where devices are protected from
1450 * peer-to-peer DMA by PCI ACS. Again, if we find an existing
1453 for (bus = pdev->bus; !pci_is_root_bus(bus); bus = bus->parent) {
1457 if (pci_acs_path_enabled(bus->self, NULL, REQ_ACS_FLAGS))
1462 group = iommu_group_get(&pdev->dev);
1468 * Look for existing groups on device aliases. If we alias another
1469 * device or another device aliases us, use the same group.
1471 group = get_pci_alias_group(pdev, (unsigned long *)devfns);
1476 * Look for existing groups on non-isolated functions on the same
1477 * slot and aliases of those funcions, if any. No need to clear
1478 * the search bitmap, the tested devfns are still valid.
1480 group = get_pci_function_alias_group(pdev, (unsigned long *)devfns);
1484 /* No shared group found, allocate new */
1485 return iommu_group_alloc();
1487 EXPORT_SYMBOL_GPL(pci_device_group);
1489 /* Get the IOMMU group for device on fsl-mc bus */
1490 struct iommu_group *fsl_mc_device_group(struct device *dev)
1492 struct device *cont_dev = fsl_mc_cont_dev(dev);
1493 struct iommu_group *group;
1495 group = iommu_group_get(cont_dev);
1497 group = iommu_group_alloc();
1500 EXPORT_SYMBOL_GPL(fsl_mc_device_group);
1502 static int iommu_get_def_domain_type(struct device *dev)
1504 const struct iommu_ops *ops = dev_iommu_ops(dev);
1506 if (dev_is_pci(dev) && to_pci_dev(dev)->untrusted)
1507 return IOMMU_DOMAIN_DMA;
1509 if (ops->def_domain_type)
1510 return ops->def_domain_type(dev);
1515 static int iommu_group_alloc_default_domain(struct bus_type *bus,
1516 struct iommu_group *group,
1519 struct iommu_domain *dom;
1521 dom = __iommu_domain_alloc(bus, type);
1522 if (!dom && type != IOMMU_DOMAIN_DMA) {
1523 dom = __iommu_domain_alloc(bus, IOMMU_DOMAIN_DMA);
1525 pr_warn("Failed to allocate default IOMMU domain of type %u for group %s - Falling back to IOMMU_DOMAIN_DMA",
1532 group->default_domain = dom;
1534 group->domain = dom;
1538 static int iommu_alloc_default_domain(struct iommu_group *group,
1543 if (group->default_domain)
1546 type = iommu_get_def_domain_type(dev) ? : iommu_def_domain_type;
1548 return iommu_group_alloc_default_domain(dev->bus, group, type);
1552 * iommu_group_get_for_dev - Find or create the IOMMU group for a device
1553 * @dev: target device
1555 * This function is intended to be called by IOMMU drivers and extended to
1556 * support common, bus-defined algorithms when determining or creating the
1557 * IOMMU group for a device. On success, the caller will hold a reference
1558 * to the returned IOMMU group, which will already include the provided
1559 * device. The reference should be released with iommu_group_put().
1561 static struct iommu_group *iommu_group_get_for_dev(struct device *dev)
1563 const struct iommu_ops *ops = dev_iommu_ops(dev);
1564 struct iommu_group *group;
1567 group = iommu_group_get(dev);
1571 group = ops->device_group(dev);
1572 if (WARN_ON_ONCE(group == NULL))
1573 return ERR_PTR(-EINVAL);
1578 ret = iommu_group_add_device(group, dev);
1585 iommu_group_put(group);
1587 return ERR_PTR(ret);
1590 struct iommu_domain *iommu_group_default_domain(struct iommu_group *group)
1592 return group->default_domain;
1595 static int probe_iommu_group(struct device *dev, void *data)
1597 struct list_head *group_list = data;
1598 struct iommu_group *group;
1601 /* Device is probed already if in a group */
1602 group = iommu_group_get(dev);
1604 iommu_group_put(group);
1608 ret = __iommu_probe_device(dev, group_list);
1615 static int remove_iommu_group(struct device *dev, void *data)
1617 iommu_release_device(dev);
1622 static int iommu_bus_notifier(struct notifier_block *nb,
1623 unsigned long action, void *data)
1625 struct device *dev = data;
1627 if (action == BUS_NOTIFY_ADD_DEVICE) {
1630 ret = iommu_probe_device(dev);
1631 return (ret) ? NOTIFY_DONE : NOTIFY_OK;
1632 } else if (action == BUS_NOTIFY_REMOVED_DEVICE) {
1633 iommu_release_device(dev);
1640 struct __group_domain_type {
1645 static int probe_get_default_domain_type(struct device *dev, void *data)
1647 struct __group_domain_type *gtype = data;
1648 unsigned int type = iommu_get_def_domain_type(dev);
1651 if (gtype->type && gtype->type != type) {
1652 dev_warn(dev, "Device needs domain type %s, but device %s in the same iommu group requires type %s - using default\n",
1653 iommu_domain_type_str(type),
1654 dev_name(gtype->dev),
1655 iommu_domain_type_str(gtype->type));
1668 static void probe_alloc_default_domain(struct bus_type *bus,
1669 struct iommu_group *group)
1671 struct __group_domain_type gtype;
1673 memset(>ype, 0, sizeof(gtype));
1675 /* Ask for default domain requirements of all devices in the group */
1676 __iommu_group_for_each_dev(group, >ype,
1677 probe_get_default_domain_type);
1680 gtype.type = iommu_def_domain_type;
1682 iommu_group_alloc_default_domain(bus, group, gtype.type);
1686 static int iommu_group_do_dma_attach(struct device *dev, void *data)
1688 struct iommu_domain *domain = data;
1691 if (!iommu_is_attach_deferred(dev))
1692 ret = __iommu_attach_device(domain, dev);
1697 static int __iommu_group_dma_attach(struct iommu_group *group)
1699 return __iommu_group_for_each_dev(group, group->default_domain,
1700 iommu_group_do_dma_attach);
1703 static int iommu_group_do_probe_finalize(struct device *dev, void *data)
1705 const struct iommu_ops *ops = dev_iommu_ops(dev);
1707 if (ops->probe_finalize)
1708 ops->probe_finalize(dev);
1713 static void __iommu_group_dma_finalize(struct iommu_group *group)
1715 __iommu_group_for_each_dev(group, group->default_domain,
1716 iommu_group_do_probe_finalize);
1719 static int iommu_do_create_direct_mappings(struct device *dev, void *data)
1721 struct iommu_group *group = data;
1723 iommu_create_device_direct_mappings(group, dev);
1728 static int iommu_group_create_direct_mappings(struct iommu_group *group)
1730 return __iommu_group_for_each_dev(group, group,
1731 iommu_do_create_direct_mappings);
1734 int bus_iommu_probe(struct bus_type *bus)
1736 struct iommu_group *group, *next;
1737 LIST_HEAD(group_list);
1741 * This code-path does not allocate the default domain when
1742 * creating the iommu group, so do it after the groups are
1745 ret = bus_for_each_dev(bus, NULL, &group_list, probe_iommu_group);
1749 list_for_each_entry_safe(group, next, &group_list, entry) {
1750 /* Remove item from the list */
1751 list_del_init(&group->entry);
1753 mutex_lock(&group->mutex);
1755 /* Try to allocate default domain */
1756 probe_alloc_default_domain(bus, group);
1758 if (!group->default_domain) {
1759 mutex_unlock(&group->mutex);
1763 iommu_group_create_direct_mappings(group);
1765 ret = __iommu_group_dma_attach(group);
1767 mutex_unlock(&group->mutex);
1772 __iommu_group_dma_finalize(group);
1778 static int iommu_bus_init(struct bus_type *bus, const struct iommu_ops *ops)
1780 struct notifier_block *nb;
1783 nb = kzalloc(sizeof(struct notifier_block), GFP_KERNEL);
1787 nb->notifier_call = iommu_bus_notifier;
1789 err = bus_register_notifier(bus, nb);
1793 err = bus_iommu_probe(bus);
1802 bus_for_each_dev(bus, NULL, NULL, remove_iommu_group);
1803 bus_unregister_notifier(bus, nb);
1812 * bus_set_iommu - set iommu-callbacks for the bus
1814 * @ops: the callbacks provided by the iommu-driver
1816 * This function is called by an iommu driver to set the iommu methods
1817 * used for a particular bus. Drivers for devices on that bus can use
1818 * the iommu-api after these ops are registered.
1819 * This special function is needed because IOMMUs are usually devices on
1820 * the bus itself, so the iommu drivers are not initialized when the bus
1821 * is set up. With this function the iommu-driver can set the iommu-ops
1824 int bus_set_iommu(struct bus_type *bus, const struct iommu_ops *ops)
1829 bus->iommu_ops = NULL;
1833 if (bus->iommu_ops != NULL)
1836 bus->iommu_ops = ops;
1838 /* Do IOMMU specific setup for this bus-type */
1839 err = iommu_bus_init(bus, ops);
1841 bus->iommu_ops = NULL;
1845 EXPORT_SYMBOL_GPL(bus_set_iommu);
1847 bool iommu_present(struct bus_type *bus)
1849 return bus->iommu_ops != NULL;
1851 EXPORT_SYMBOL_GPL(iommu_present);
1854 * device_iommu_capable() - check for a general IOMMU capability
1855 * @dev: device to which the capability would be relevant, if available
1856 * @cap: IOMMU capability
1858 * Return: true if an IOMMU is present and supports the given capability
1859 * for the given device, otherwise false.
1861 bool device_iommu_capable(struct device *dev, enum iommu_cap cap)
1863 const struct iommu_ops *ops;
1865 if (!dev->iommu || !dev->iommu->iommu_dev)
1868 ops = dev_iommu_ops(dev);
1872 return ops->capable(cap);
1874 EXPORT_SYMBOL_GPL(device_iommu_capable);
1876 bool iommu_capable(struct bus_type *bus, enum iommu_cap cap)
1878 if (!bus->iommu_ops || !bus->iommu_ops->capable)
1881 return bus->iommu_ops->capable(cap);
1883 EXPORT_SYMBOL_GPL(iommu_capable);
1886 * iommu_set_fault_handler() - set a fault handler for an iommu domain
1887 * @domain: iommu domain
1888 * @handler: fault handler
1889 * @token: user data, will be passed back to the fault handler
1891 * This function should be used by IOMMU users which want to be notified
1892 * whenever an IOMMU fault happens.
1894 * The fault handler itself should return 0 on success, and an appropriate
1895 * error code otherwise.
1897 void iommu_set_fault_handler(struct iommu_domain *domain,
1898 iommu_fault_handler_t handler,
1903 domain->handler = handler;
1904 domain->handler_token = token;
1906 EXPORT_SYMBOL_GPL(iommu_set_fault_handler);
1908 static struct iommu_domain *__iommu_domain_alloc(struct bus_type *bus,
1911 struct iommu_domain *domain;
1913 if (bus == NULL || bus->iommu_ops == NULL)
1916 domain = bus->iommu_ops->domain_alloc(type);
1920 domain->type = type;
1921 /* Assume all sizes by default; the driver may override this later */
1922 domain->pgsize_bitmap = bus->iommu_ops->pgsize_bitmap;
1924 domain->ops = bus->iommu_ops->default_domain_ops;
1926 if (iommu_is_dma_domain(domain) && iommu_get_dma_cookie(domain)) {
1927 iommu_domain_free(domain);
1933 struct iommu_domain *iommu_domain_alloc(struct bus_type *bus)
1935 return __iommu_domain_alloc(bus, IOMMU_DOMAIN_UNMANAGED);
1937 EXPORT_SYMBOL_GPL(iommu_domain_alloc);
1939 void iommu_domain_free(struct iommu_domain *domain)
1941 iommu_put_dma_cookie(domain);
1942 domain->ops->free(domain);
1944 EXPORT_SYMBOL_GPL(iommu_domain_free);
1947 * Put the group's domain back to the appropriate core-owned domain - either the
1948 * standard kernel-mode DMA configuration or an all-DMA-blocked domain.
1950 static void __iommu_group_set_core_domain(struct iommu_group *group)
1952 struct iommu_domain *new_domain;
1956 new_domain = group->blocking_domain;
1958 new_domain = group->default_domain;
1960 ret = __iommu_group_set_domain(group, new_domain);
1961 WARN(ret, "iommu driver failed to attach the default/blocking domain");
1964 static int __iommu_attach_device(struct iommu_domain *domain,
1969 if (unlikely(domain->ops->attach_dev == NULL))
1972 ret = domain->ops->attach_dev(domain, dev);
1974 trace_attach_device_to_domain(dev);
1978 int iommu_attach_device(struct iommu_domain *domain, struct device *dev)
1980 struct iommu_group *group;
1983 group = iommu_group_get(dev);
1988 * Lock the group to make sure the device-count doesn't
1989 * change while we are attaching
1991 mutex_lock(&group->mutex);
1993 if (iommu_group_device_count(group) != 1)
1996 ret = __iommu_attach_group(domain, group);
1999 mutex_unlock(&group->mutex);
2000 iommu_group_put(group);
2004 EXPORT_SYMBOL_GPL(iommu_attach_device);
2006 int iommu_deferred_attach(struct device *dev, struct iommu_domain *domain)
2008 if (iommu_is_attach_deferred(dev))
2009 return __iommu_attach_device(domain, dev);
2014 static void __iommu_detach_device(struct iommu_domain *domain,
2017 if (iommu_is_attach_deferred(dev))
2020 domain->ops->detach_dev(domain, dev);
2021 trace_detach_device_from_domain(dev);
2024 void iommu_detach_device(struct iommu_domain *domain, struct device *dev)
2026 struct iommu_group *group;
2028 group = iommu_group_get(dev);
2032 mutex_lock(&group->mutex);
2033 if (WARN_ON(domain != group->domain) ||
2034 WARN_ON(iommu_group_device_count(group) != 1))
2036 __iommu_group_set_core_domain(group);
2039 mutex_unlock(&group->mutex);
2040 iommu_group_put(group);
2042 EXPORT_SYMBOL_GPL(iommu_detach_device);
2044 struct iommu_domain *iommu_get_domain_for_dev(struct device *dev)
2046 struct iommu_domain *domain;
2047 struct iommu_group *group;
2049 group = iommu_group_get(dev);
2053 domain = group->domain;
2055 iommu_group_put(group);
2059 EXPORT_SYMBOL_GPL(iommu_get_domain_for_dev);
2062 * For IOMMU_DOMAIN_DMA implementations which already provide their own
2063 * guarantees that the group and its default domain are valid and correct.
2065 struct iommu_domain *iommu_get_dma_domain(struct device *dev)
2067 return dev->iommu_group->default_domain;
2071 * IOMMU groups are really the natural working unit of the IOMMU, but
2072 * the IOMMU API works on domains and devices. Bridge that gap by
2073 * iterating over the devices in a group. Ideally we'd have a single
2074 * device which represents the requestor ID of the group, but we also
2075 * allow IOMMU drivers to create policy defined minimum sets, where
2076 * the physical hardware may be able to distiguish members, but we
2077 * wish to group them at a higher level (ex. untrusted multi-function
2078 * PCI devices). Thus we attach each device.
2080 static int iommu_group_do_attach_device(struct device *dev, void *data)
2082 struct iommu_domain *domain = data;
2084 return __iommu_attach_device(domain, dev);
2087 static int __iommu_attach_group(struct iommu_domain *domain,
2088 struct iommu_group *group)
2092 if (group->domain && group->domain != group->default_domain &&
2093 group->domain != group->blocking_domain)
2096 ret = __iommu_group_for_each_dev(group, domain,
2097 iommu_group_do_attach_device);
2099 group->domain = domain;
2104 int iommu_attach_group(struct iommu_domain *domain, struct iommu_group *group)
2108 mutex_lock(&group->mutex);
2109 ret = __iommu_attach_group(domain, group);
2110 mutex_unlock(&group->mutex);
2114 EXPORT_SYMBOL_GPL(iommu_attach_group);
2116 static int iommu_group_do_detach_device(struct device *dev, void *data)
2118 struct iommu_domain *domain = data;
2120 __iommu_detach_device(domain, dev);
2125 static int __iommu_group_set_domain(struct iommu_group *group,
2126 struct iommu_domain *new_domain)
2130 if (group->domain == new_domain)
2134 * New drivers should support default domains and so the detach_dev() op
2135 * will never be called. Otherwise the NULL domain represents some
2136 * platform specific behavior.
2139 if (WARN_ON(!group->domain->ops->detach_dev))
2141 __iommu_group_for_each_dev(group, group->domain,
2142 iommu_group_do_detach_device);
2143 group->domain = NULL;
2148 * Changing the domain is done by calling attach_dev() on the new
2149 * domain. This switch does not have to be atomic and DMA can be
2150 * discarded during the transition. DMA must only be able to access
2151 * either new_domain or group->domain, never something else.
2153 * Note that this is called in error unwind paths, attaching to a
2154 * domain that has already been attached cannot fail.
2156 ret = __iommu_group_for_each_dev(group, new_domain,
2157 iommu_group_do_attach_device);
2160 group->domain = new_domain;
2164 void iommu_detach_group(struct iommu_domain *domain, struct iommu_group *group)
2166 mutex_lock(&group->mutex);
2167 __iommu_group_set_core_domain(group);
2168 mutex_unlock(&group->mutex);
2170 EXPORT_SYMBOL_GPL(iommu_detach_group);
2172 phys_addr_t iommu_iova_to_phys(struct iommu_domain *domain, dma_addr_t iova)
2174 if (domain->type == IOMMU_DOMAIN_IDENTITY)
2177 if (domain->type == IOMMU_DOMAIN_BLOCKED)
2180 return domain->ops->iova_to_phys(domain, iova);
2182 EXPORT_SYMBOL_GPL(iommu_iova_to_phys);
2184 static size_t iommu_pgsize(struct iommu_domain *domain, unsigned long iova,
2185 phys_addr_t paddr, size_t size, size_t *count)
2187 unsigned int pgsize_idx, pgsize_idx_next;
2188 unsigned long pgsizes;
2189 size_t offset, pgsize, pgsize_next;
2190 unsigned long addr_merge = paddr | iova;
2192 /* Page sizes supported by the hardware and small enough for @size */
2193 pgsizes = domain->pgsize_bitmap & GENMASK(__fls(size), 0);
2195 /* Constrain the page sizes further based on the maximum alignment */
2196 if (likely(addr_merge))
2197 pgsizes &= GENMASK(__ffs(addr_merge), 0);
2199 /* Make sure we have at least one suitable page size */
2202 /* Pick the biggest page size remaining */
2203 pgsize_idx = __fls(pgsizes);
2204 pgsize = BIT(pgsize_idx);
2208 /* Find the next biggest support page size, if it exists */
2209 pgsizes = domain->pgsize_bitmap & ~GENMASK(pgsize_idx, 0);
2213 pgsize_idx_next = __ffs(pgsizes);
2214 pgsize_next = BIT(pgsize_idx_next);
2217 * There's no point trying a bigger page size unless the virtual
2218 * and physical addresses are similarly offset within the larger page.
2220 if ((iova ^ paddr) & (pgsize_next - 1))
2223 /* Calculate the offset to the next page size alignment boundary */
2224 offset = pgsize_next - (addr_merge & (pgsize_next - 1));
2227 * If size is big enough to accommodate the larger page, reduce
2228 * the number of smaller pages.
2230 if (offset + pgsize_next <= size)
2234 *count = size >> pgsize_idx;
2238 static int __iommu_map_pages(struct iommu_domain *domain, unsigned long iova,
2239 phys_addr_t paddr, size_t size, int prot,
2240 gfp_t gfp, size_t *mapped)
2242 const struct iommu_domain_ops *ops = domain->ops;
2243 size_t pgsize, count;
2246 pgsize = iommu_pgsize(domain, iova, paddr, size, &count);
2248 pr_debug("mapping: iova 0x%lx pa %pa pgsize 0x%zx count %zu\n",
2249 iova, &paddr, pgsize, count);
2251 if (ops->map_pages) {
2252 ret = ops->map_pages(domain, iova, paddr, pgsize, count, prot,
2255 ret = ops->map(domain, iova, paddr, pgsize, prot, gfp);
2256 *mapped = ret ? 0 : pgsize;
2262 static int __iommu_map(struct iommu_domain *domain, unsigned long iova,
2263 phys_addr_t paddr, size_t size, int prot, gfp_t gfp)
2265 const struct iommu_domain_ops *ops = domain->ops;
2266 unsigned long orig_iova = iova;
2267 unsigned int min_pagesz;
2268 size_t orig_size = size;
2269 phys_addr_t orig_paddr = paddr;
2272 if (unlikely(!(ops->map || ops->map_pages) ||
2273 domain->pgsize_bitmap == 0UL))
2276 if (unlikely(!(domain->type & __IOMMU_DOMAIN_PAGING)))
2279 /* find out the minimum page size supported */
2280 min_pagesz = 1 << __ffs(domain->pgsize_bitmap);
2283 * both the virtual address and the physical one, as well as
2284 * the size of the mapping, must be aligned (at least) to the
2285 * size of the smallest page supported by the hardware
2287 if (!IS_ALIGNED(iova | paddr | size, min_pagesz)) {
2288 pr_err("unaligned: iova 0x%lx pa %pa size 0x%zx min_pagesz 0x%x\n",
2289 iova, &paddr, size, min_pagesz);
2293 pr_debug("map: iova 0x%lx pa %pa size 0x%zx\n", iova, &paddr, size);
2298 ret = __iommu_map_pages(domain, iova, paddr, size, prot, gfp,
2301 * Some pages may have been mapped, even if an error occurred,
2302 * so we should account for those so they can be unmapped.
2313 /* unroll mapping in case something went wrong */
2315 iommu_unmap(domain, orig_iova, orig_size - size);
2317 trace_map(orig_iova, orig_paddr, orig_size);
2322 static int _iommu_map(struct iommu_domain *domain, unsigned long iova,
2323 phys_addr_t paddr, size_t size, int prot, gfp_t gfp)
2325 const struct iommu_domain_ops *ops = domain->ops;
2328 ret = __iommu_map(domain, iova, paddr, size, prot, gfp);
2329 if (ret == 0 && ops->iotlb_sync_map)
2330 ops->iotlb_sync_map(domain, iova, size);
2335 int iommu_map(struct iommu_domain *domain, unsigned long iova,
2336 phys_addr_t paddr, size_t size, int prot)
2339 return _iommu_map(domain, iova, paddr, size, prot, GFP_KERNEL);
2341 EXPORT_SYMBOL_GPL(iommu_map);
2343 int iommu_map_atomic(struct iommu_domain *domain, unsigned long iova,
2344 phys_addr_t paddr, size_t size, int prot)
2346 return _iommu_map(domain, iova, paddr, size, prot, GFP_ATOMIC);
2348 EXPORT_SYMBOL_GPL(iommu_map_atomic);
2350 static size_t __iommu_unmap_pages(struct iommu_domain *domain,
2351 unsigned long iova, size_t size,
2352 struct iommu_iotlb_gather *iotlb_gather)
2354 const struct iommu_domain_ops *ops = domain->ops;
2355 size_t pgsize, count;
2357 pgsize = iommu_pgsize(domain, iova, iova, size, &count);
2358 return ops->unmap_pages ?
2359 ops->unmap_pages(domain, iova, pgsize, count, iotlb_gather) :
2360 ops->unmap(domain, iova, pgsize, iotlb_gather);
2363 static size_t __iommu_unmap(struct iommu_domain *domain,
2364 unsigned long iova, size_t size,
2365 struct iommu_iotlb_gather *iotlb_gather)
2367 const struct iommu_domain_ops *ops = domain->ops;
2368 size_t unmapped_page, unmapped = 0;
2369 unsigned long orig_iova = iova;
2370 unsigned int min_pagesz;
2372 if (unlikely(!(ops->unmap || ops->unmap_pages) ||
2373 domain->pgsize_bitmap == 0UL))
2376 if (unlikely(!(domain->type & __IOMMU_DOMAIN_PAGING)))
2379 /* find out the minimum page size supported */
2380 min_pagesz = 1 << __ffs(domain->pgsize_bitmap);
2383 * The virtual address, as well as the size of the mapping, must be
2384 * aligned (at least) to the size of the smallest page supported
2387 if (!IS_ALIGNED(iova | size, min_pagesz)) {
2388 pr_err("unaligned: iova 0x%lx size 0x%zx min_pagesz 0x%x\n",
2389 iova, size, min_pagesz);
2393 pr_debug("unmap this: iova 0x%lx size 0x%zx\n", iova, size);
2396 * Keep iterating until we either unmap 'size' bytes (or more)
2397 * or we hit an area that isn't mapped.
2399 while (unmapped < size) {
2400 unmapped_page = __iommu_unmap_pages(domain, iova,
2406 pr_debug("unmapped: iova 0x%lx size 0x%zx\n",
2407 iova, unmapped_page);
2409 iova += unmapped_page;
2410 unmapped += unmapped_page;
2413 trace_unmap(orig_iova, size, unmapped);
2417 size_t iommu_unmap(struct iommu_domain *domain,
2418 unsigned long iova, size_t size)
2420 struct iommu_iotlb_gather iotlb_gather;
2423 iommu_iotlb_gather_init(&iotlb_gather);
2424 ret = __iommu_unmap(domain, iova, size, &iotlb_gather);
2425 iommu_iotlb_sync(domain, &iotlb_gather);
2429 EXPORT_SYMBOL_GPL(iommu_unmap);
2431 size_t iommu_unmap_fast(struct iommu_domain *domain,
2432 unsigned long iova, size_t size,
2433 struct iommu_iotlb_gather *iotlb_gather)
2435 return __iommu_unmap(domain, iova, size, iotlb_gather);
2437 EXPORT_SYMBOL_GPL(iommu_unmap_fast);
2439 static ssize_t __iommu_map_sg(struct iommu_domain *domain, unsigned long iova,
2440 struct scatterlist *sg, unsigned int nents, int prot,
2443 const struct iommu_domain_ops *ops = domain->ops;
2444 size_t len = 0, mapped = 0;
2449 while (i <= nents) {
2450 phys_addr_t s_phys = sg_phys(sg);
2452 if (len && s_phys != start + len) {
2453 ret = __iommu_map(domain, iova + mapped, start,
2463 if (sg_is_dma_bus_address(sg))
2478 if (ops->iotlb_sync_map)
2479 ops->iotlb_sync_map(domain, iova, mapped);
2483 /* undo mappings already done */
2484 iommu_unmap(domain, iova, mapped);
2489 ssize_t iommu_map_sg(struct iommu_domain *domain, unsigned long iova,
2490 struct scatterlist *sg, unsigned int nents, int prot)
2493 return __iommu_map_sg(domain, iova, sg, nents, prot, GFP_KERNEL);
2495 EXPORT_SYMBOL_GPL(iommu_map_sg);
2497 ssize_t iommu_map_sg_atomic(struct iommu_domain *domain, unsigned long iova,
2498 struct scatterlist *sg, unsigned int nents, int prot)
2500 return __iommu_map_sg(domain, iova, sg, nents, prot, GFP_ATOMIC);
2504 * report_iommu_fault() - report about an IOMMU fault to the IOMMU framework
2505 * @domain: the iommu domain where the fault has happened
2506 * @dev: the device where the fault has happened
2507 * @iova: the faulting address
2508 * @flags: mmu fault flags (e.g. IOMMU_FAULT_READ/IOMMU_FAULT_WRITE/...)
2510 * This function should be called by the low-level IOMMU implementations
2511 * whenever IOMMU faults happen, to allow high-level users, that are
2512 * interested in such events, to know about them.
2514 * This event may be useful for several possible use cases:
2515 * - mere logging of the event
2516 * - dynamic TLB/PTE loading
2517 * - if restarting of the faulting device is required
2519 * Returns 0 on success and an appropriate error code otherwise (if dynamic
2520 * PTE/TLB loading will one day be supported, implementations will be able
2521 * to tell whether it succeeded or not according to this return value).
2523 * Specifically, -ENOSYS is returned if a fault handler isn't installed
2524 * (though fault handlers can also return -ENOSYS, in case they want to
2525 * elicit the default behavior of the IOMMU drivers).
2527 int report_iommu_fault(struct iommu_domain *domain, struct device *dev,
2528 unsigned long iova, int flags)
2533 * if upper layers showed interest and installed a fault handler,
2536 if (domain->handler)
2537 ret = domain->handler(domain, dev, iova, flags,
2538 domain->handler_token);
2540 trace_io_page_fault(dev, iova, flags);
2543 EXPORT_SYMBOL_GPL(report_iommu_fault);
2545 static int __init iommu_init(void)
2547 iommu_group_kset = kset_create_and_add("iommu_groups",
2549 BUG_ON(!iommu_group_kset);
2551 iommu_debugfs_setup();
2555 core_initcall(iommu_init);
2557 int iommu_enable_nesting(struct iommu_domain *domain)
2559 if (domain->type != IOMMU_DOMAIN_UNMANAGED)
2561 if (!domain->ops->enable_nesting)
2563 return domain->ops->enable_nesting(domain);
2565 EXPORT_SYMBOL_GPL(iommu_enable_nesting);
2567 int iommu_set_pgtable_quirks(struct iommu_domain *domain,
2568 unsigned long quirk)
2570 if (domain->type != IOMMU_DOMAIN_UNMANAGED)
2572 if (!domain->ops->set_pgtable_quirks)
2574 return domain->ops->set_pgtable_quirks(domain, quirk);
2576 EXPORT_SYMBOL_GPL(iommu_set_pgtable_quirks);
2578 void iommu_get_resv_regions(struct device *dev, struct list_head *list)
2580 const struct iommu_ops *ops = dev_iommu_ops(dev);
2582 if (ops->get_resv_regions)
2583 ops->get_resv_regions(dev, list);
2587 * iommu_put_resv_regions - release resered regions
2588 * @dev: device for which to free reserved regions
2589 * @list: reserved region list for device
2591 * This releases a reserved region list acquired by iommu_get_resv_regions().
2593 void iommu_put_resv_regions(struct device *dev, struct list_head *list)
2595 struct iommu_resv_region *entry, *next;
2597 list_for_each_entry_safe(entry, next, list, list) {
2599 entry->free(dev, entry);
2604 EXPORT_SYMBOL(iommu_put_resv_regions);
2606 struct iommu_resv_region *iommu_alloc_resv_region(phys_addr_t start,
2607 size_t length, int prot,
2608 enum iommu_resv_type type)
2610 struct iommu_resv_region *region;
2612 region = kzalloc(sizeof(*region), GFP_KERNEL);
2616 INIT_LIST_HEAD(®ion->list);
2617 region->start = start;
2618 region->length = length;
2619 region->prot = prot;
2620 region->type = type;
2623 EXPORT_SYMBOL_GPL(iommu_alloc_resv_region);
2625 void iommu_set_default_passthrough(bool cmd_line)
2628 iommu_cmd_line |= IOMMU_CMD_LINE_DMA_API;
2629 iommu_def_domain_type = IOMMU_DOMAIN_IDENTITY;
2632 void iommu_set_default_translated(bool cmd_line)
2635 iommu_cmd_line |= IOMMU_CMD_LINE_DMA_API;
2636 iommu_def_domain_type = IOMMU_DOMAIN_DMA;
2639 bool iommu_default_passthrough(void)
2641 return iommu_def_domain_type == IOMMU_DOMAIN_IDENTITY;
2643 EXPORT_SYMBOL_GPL(iommu_default_passthrough);
2645 const struct iommu_ops *iommu_ops_from_fwnode(struct fwnode_handle *fwnode)
2647 const struct iommu_ops *ops = NULL;
2648 struct iommu_device *iommu;
2650 spin_lock(&iommu_device_lock);
2651 list_for_each_entry(iommu, &iommu_device_list, list)
2652 if (iommu->fwnode == fwnode) {
2656 spin_unlock(&iommu_device_lock);
2660 int iommu_fwspec_init(struct device *dev, struct fwnode_handle *iommu_fwnode,
2661 const struct iommu_ops *ops)
2663 struct iommu_fwspec *fwspec = dev_iommu_fwspec_get(dev);
2666 return ops == fwspec->ops ? 0 : -EINVAL;
2668 if (!dev_iommu_get(dev))
2671 /* Preallocate for the overwhelmingly common case of 1 ID */
2672 fwspec = kzalloc(struct_size(fwspec, ids, 1), GFP_KERNEL);
2676 of_node_get(to_of_node(iommu_fwnode));
2677 fwspec->iommu_fwnode = iommu_fwnode;
2679 dev_iommu_fwspec_set(dev, fwspec);
2682 EXPORT_SYMBOL_GPL(iommu_fwspec_init);
2684 void iommu_fwspec_free(struct device *dev)
2686 struct iommu_fwspec *fwspec = dev_iommu_fwspec_get(dev);
2689 fwnode_handle_put(fwspec->iommu_fwnode);
2691 dev_iommu_fwspec_set(dev, NULL);
2694 EXPORT_SYMBOL_GPL(iommu_fwspec_free);
2696 int iommu_fwspec_add_ids(struct device *dev, u32 *ids, int num_ids)
2698 struct iommu_fwspec *fwspec = dev_iommu_fwspec_get(dev);
2704 new_num = fwspec->num_ids + num_ids;
2706 fwspec = krealloc(fwspec, struct_size(fwspec, ids, new_num),
2711 dev_iommu_fwspec_set(dev, fwspec);
2714 for (i = 0; i < num_ids; i++)
2715 fwspec->ids[fwspec->num_ids + i] = ids[i];
2717 fwspec->num_ids = new_num;
2720 EXPORT_SYMBOL_GPL(iommu_fwspec_add_ids);
2723 * Per device IOMMU features.
2725 int iommu_dev_enable_feature(struct device *dev, enum iommu_dev_features feat)
2727 if (dev->iommu && dev->iommu->iommu_dev) {
2728 const struct iommu_ops *ops = dev->iommu->iommu_dev->ops;
2730 if (ops->dev_enable_feat)
2731 return ops->dev_enable_feat(dev, feat);
2736 EXPORT_SYMBOL_GPL(iommu_dev_enable_feature);
2739 * The device drivers should do the necessary cleanups before calling this.
2741 int iommu_dev_disable_feature(struct device *dev, enum iommu_dev_features feat)
2743 if (dev->iommu && dev->iommu->iommu_dev) {
2744 const struct iommu_ops *ops = dev->iommu->iommu_dev->ops;
2746 if (ops->dev_disable_feat)
2747 return ops->dev_disable_feat(dev, feat);
2752 EXPORT_SYMBOL_GPL(iommu_dev_disable_feature);
2755 * iommu_sva_bind_device() - Bind a process address space to a device
2757 * @mm: the mm to bind, caller must hold a reference to it
2758 * @drvdata: opaque data pointer to pass to bind callback
2760 * Create a bond between device and address space, allowing the device to access
2761 * the mm using the returned PASID. If a bond already exists between @device and
2762 * @mm, it is returned and an additional reference is taken. Caller must call
2763 * iommu_sva_unbind_device() to release each reference.
2765 * iommu_dev_enable_feature(dev, IOMMU_DEV_FEAT_SVA) must be called first, to
2766 * initialize the required SVA features.
2768 * On error, returns an ERR_PTR value.
2771 iommu_sva_bind_device(struct device *dev, struct mm_struct *mm, void *drvdata)
2773 struct iommu_group *group;
2774 struct iommu_sva *handle = ERR_PTR(-EINVAL);
2775 const struct iommu_ops *ops = dev_iommu_ops(dev);
2778 return ERR_PTR(-ENODEV);
2780 group = iommu_group_get(dev);
2782 return ERR_PTR(-ENODEV);
2784 /* Ensure device count and domain don't change while we're binding */
2785 mutex_lock(&group->mutex);
2788 * To keep things simple, SVA currently doesn't support IOMMU groups
2789 * with more than one device. Existing SVA-capable systems are not
2790 * affected by the problems that required IOMMU groups (lack of ACS
2791 * isolation, device ID aliasing and other hardware issues).
2793 if (iommu_group_device_count(group) != 1)
2796 handle = ops->sva_bind(dev, mm, drvdata);
2799 mutex_unlock(&group->mutex);
2800 iommu_group_put(group);
2804 EXPORT_SYMBOL_GPL(iommu_sva_bind_device);
2807 * iommu_sva_unbind_device() - Remove a bond created with iommu_sva_bind_device
2808 * @handle: the handle returned by iommu_sva_bind_device()
2810 * Put reference to a bond between device and address space. The device should
2811 * not be issuing any more transaction for this PASID. All outstanding page
2812 * requests for this PASID must have been flushed to the IOMMU.
2814 void iommu_sva_unbind_device(struct iommu_sva *handle)
2816 struct iommu_group *group;
2817 struct device *dev = handle->dev;
2818 const struct iommu_ops *ops = dev_iommu_ops(dev);
2820 if (!ops->sva_unbind)
2823 group = iommu_group_get(dev);
2827 mutex_lock(&group->mutex);
2828 ops->sva_unbind(handle);
2829 mutex_unlock(&group->mutex);
2831 iommu_group_put(group);
2833 EXPORT_SYMBOL_GPL(iommu_sva_unbind_device);
2835 u32 iommu_sva_get_pasid(struct iommu_sva *handle)
2837 const struct iommu_ops *ops = dev_iommu_ops(handle->dev);
2839 if (!ops->sva_get_pasid)
2840 return IOMMU_PASID_INVALID;
2842 return ops->sva_get_pasid(handle);
2844 EXPORT_SYMBOL_GPL(iommu_sva_get_pasid);
2847 * Changes the default domain of an iommu group that has *only* one device
2849 * @group: The group for which the default domain should be changed
2850 * @prev_dev: The device in the group (this is used to make sure that the device
2851 * hasn't changed after the caller has called this function)
2852 * @type: The type of the new default domain that gets associated with the group
2854 * Returns 0 on success and error code on failure
2857 * 1. Presently, this function is called only when user requests to change the
2858 * group's default domain type through /sys/kernel/iommu_groups/<grp_id>/type
2859 * Please take a closer look if intended to use for other purposes.
2861 static int iommu_change_dev_def_domain(struct iommu_group *group,
2862 struct device *prev_dev, int type)
2864 struct iommu_domain *prev_dom;
2865 struct group_device *grp_dev;
2866 int ret, dev_def_dom;
2869 mutex_lock(&group->mutex);
2871 if (group->default_domain != group->domain) {
2872 dev_err_ratelimited(prev_dev, "Group not assigned to default domain\n");
2878 * iommu group wasn't locked while acquiring device lock in
2879 * iommu_group_store_type(). So, make sure that the device count hasn't
2880 * changed while acquiring device lock.
2882 * Changing default domain of an iommu group with two or more devices
2883 * isn't supported because there could be a potential deadlock. Consider
2884 * the following scenario. T1 is trying to acquire device locks of all
2885 * the devices in the group and before it could acquire all of them,
2886 * there could be another thread T2 (from different sub-system and use
2887 * case) that has already acquired some of the device locks and might be
2888 * waiting for T1 to release other device locks.
2890 if (iommu_group_device_count(group) != 1) {
2891 dev_err_ratelimited(prev_dev, "Cannot change default domain: Group has more than one device\n");
2896 /* Since group has only one device */
2897 grp_dev = list_first_entry(&group->devices, struct group_device, list);
2900 if (prev_dev != dev) {
2901 dev_err_ratelimited(prev_dev, "Cannot change default domain: Device has been changed\n");
2906 prev_dom = group->default_domain;
2912 dev_def_dom = iommu_get_def_domain_type(dev);
2915 * If the user hasn't requested any specific type of domain and
2916 * if the device supports both the domains, then default to the
2917 * domain the device was booted with
2919 type = dev_def_dom ? : iommu_def_domain_type;
2920 } else if (dev_def_dom && type != dev_def_dom) {
2921 dev_err_ratelimited(prev_dev, "Device cannot be in %s domain\n",
2922 iommu_domain_type_str(type));
2928 * Switch to a new domain only if the requested domain type is different
2929 * from the existing default domain type
2931 if (prev_dom->type == type) {
2936 /* We can bring up a flush queue without tearing down the domain */
2937 if (type == IOMMU_DOMAIN_DMA_FQ && prev_dom->type == IOMMU_DOMAIN_DMA) {
2938 ret = iommu_dma_init_fq(prev_dom);
2940 prev_dom->type = IOMMU_DOMAIN_DMA_FQ;
2944 /* Sets group->default_domain to the newly allocated domain */
2945 ret = iommu_group_alloc_default_domain(dev->bus, group, type);
2949 ret = iommu_create_device_direct_mappings(group, dev);
2951 goto free_new_domain;
2953 ret = __iommu_attach_device(group->default_domain, dev);
2955 goto free_new_domain;
2957 group->domain = group->default_domain;
2960 * Release the mutex here because ops->probe_finalize() call-back of
2961 * some vendor IOMMU drivers calls arm_iommu_attach_device() which
2962 * in-turn might call back into IOMMU core code, where it tries to take
2963 * group->mutex, resulting in a deadlock.
2965 mutex_unlock(&group->mutex);
2967 /* Make sure dma_ops is appropriatley set */
2968 iommu_group_do_probe_finalize(dev, group->default_domain);
2969 iommu_domain_free(prev_dom);
2973 iommu_domain_free(group->default_domain);
2974 group->default_domain = prev_dom;
2975 group->domain = prev_dom;
2978 mutex_unlock(&group->mutex);
2984 * Changing the default domain through sysfs requires the users to unbind the
2985 * drivers from the devices in the iommu group, except for a DMA -> DMA-FQ
2986 * transition. Return failure if this isn't met.
2988 * We need to consider the race between this and the device release path.
2989 * device_lock(dev) is used here to guarantee that the device release path
2990 * will not be entered at the same time.
2992 static ssize_t iommu_group_store_type(struct iommu_group *group,
2993 const char *buf, size_t count)
2995 struct group_device *grp_dev;
2999 if (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO))
3002 if (WARN_ON(!group) || !group->default_domain)
3005 if (sysfs_streq(buf, "identity"))
3006 req_type = IOMMU_DOMAIN_IDENTITY;
3007 else if (sysfs_streq(buf, "DMA"))
3008 req_type = IOMMU_DOMAIN_DMA;
3009 else if (sysfs_streq(buf, "DMA-FQ"))
3010 req_type = IOMMU_DOMAIN_DMA_FQ;
3011 else if (sysfs_streq(buf, "auto"))
3017 * Lock/Unlock the group mutex here before device lock to
3018 * 1. Make sure that the iommu group has only one device (this is a
3019 * prerequisite for step 2)
3020 * 2. Get struct *dev which is needed to lock device
3022 mutex_lock(&group->mutex);
3023 if (iommu_group_device_count(group) != 1) {
3024 mutex_unlock(&group->mutex);
3025 pr_err_ratelimited("Cannot change default domain: Group has more than one device\n");
3029 /* Since group has only one device */
3030 grp_dev = list_first_entry(&group->devices, struct group_device, list);
3035 * Don't hold the group mutex because taking group mutex first and then
3036 * the device lock could potentially cause a deadlock as below. Assume
3037 * two threads T1 and T2. T1 is trying to change default domain of an
3038 * iommu group and T2 is trying to hot unplug a device or release [1] VF
3039 * of a PCIe device which is in the same iommu group. T1 takes group
3040 * mutex and before it could take device lock assume T2 has taken device
3041 * lock and is yet to take group mutex. Now, both the threads will be
3042 * waiting for the other thread to release lock. Below, lock order was
3045 * mutex_lock(&group->mutex);
3046 * iommu_change_dev_def_domain();
3047 * mutex_unlock(&group->mutex);
3048 * device_unlock(dev);
3050 * [1] Typical device release path
3051 * device_lock() from device/driver core code
3053 * -> iommu_bus_notifier()
3054 * -> iommu_release_device()
3055 * -> ops->release_device() vendor driver calls back iommu core code
3056 * -> mutex_lock() from iommu core code
3058 mutex_unlock(&group->mutex);
3060 /* Check if the device in the group still has a driver bound to it */
3062 if (device_is_bound(dev) && !(req_type == IOMMU_DOMAIN_DMA_FQ &&
3063 group->default_domain->type == IOMMU_DOMAIN_DMA)) {
3064 pr_err_ratelimited("Device is still bound to driver\n");
3069 ret = iommu_change_dev_def_domain(group, dev, req_type);
3079 static bool iommu_is_default_domain(struct iommu_group *group)
3081 if (group->domain == group->default_domain)
3085 * If the default domain was set to identity and it is still an identity
3086 * domain then we consider this a pass. This happens because of
3087 * amd_iommu_init_device() replacing the default idenytity domain with an
3088 * identity domain that has a different configuration for AMDGPU.
3090 if (group->default_domain &&
3091 group->default_domain->type == IOMMU_DOMAIN_IDENTITY &&
3092 group->domain && group->domain->type == IOMMU_DOMAIN_IDENTITY)
3098 * iommu_device_use_default_domain() - Device driver wants to handle device
3099 * DMA through the kernel DMA API.
3102 * The device driver about to bind @dev wants to do DMA through the kernel
3103 * DMA API. Return 0 if it is allowed, otherwise an error.
3105 int iommu_device_use_default_domain(struct device *dev)
3107 struct iommu_group *group = iommu_group_get(dev);
3113 mutex_lock(&group->mutex);
3114 if (group->owner_cnt) {
3115 if (group->owner || !iommu_is_default_domain(group)) {
3124 mutex_unlock(&group->mutex);
3125 iommu_group_put(group);
3131 * iommu_device_unuse_default_domain() - Device driver stops handling device
3132 * DMA through the kernel DMA API.
3135 * The device driver doesn't want to do DMA through kernel DMA API anymore.
3136 * It must be called after iommu_device_use_default_domain().
3138 void iommu_device_unuse_default_domain(struct device *dev)
3140 struct iommu_group *group = iommu_group_get(dev);
3145 mutex_lock(&group->mutex);
3146 if (!WARN_ON(!group->owner_cnt))
3149 mutex_unlock(&group->mutex);
3150 iommu_group_put(group);
3153 static int __iommu_group_alloc_blocking_domain(struct iommu_group *group)
3155 struct group_device *dev =
3156 list_first_entry(&group->devices, struct group_device, list);
3158 if (group->blocking_domain)
3161 group->blocking_domain =
3162 __iommu_domain_alloc(dev->dev->bus, IOMMU_DOMAIN_BLOCKED);
3163 if (!group->blocking_domain) {
3165 * For drivers that do not yet understand IOMMU_DOMAIN_BLOCKED
3166 * create an empty domain instead.
3168 group->blocking_domain = __iommu_domain_alloc(
3169 dev->dev->bus, IOMMU_DOMAIN_UNMANAGED);
3170 if (!group->blocking_domain)
3177 * iommu_group_claim_dma_owner() - Set DMA ownership of a group
3178 * @group: The group.
3179 * @owner: Caller specified pointer. Used for exclusive ownership.
3181 * This is to support backward compatibility for vfio which manages
3182 * the dma ownership in iommu_group level. New invocations on this
3183 * interface should be prohibited.
3185 int iommu_group_claim_dma_owner(struct iommu_group *group, void *owner)
3189 mutex_lock(&group->mutex);
3190 if (group->owner_cnt) {
3194 if (group->domain && group->domain != group->default_domain) {
3199 ret = __iommu_group_alloc_blocking_domain(group);
3203 ret = __iommu_group_set_domain(group, group->blocking_domain);
3206 group->owner = owner;
3211 mutex_unlock(&group->mutex);
3215 EXPORT_SYMBOL_GPL(iommu_group_claim_dma_owner);
3218 * iommu_group_release_dma_owner() - Release DMA ownership of a group
3219 * @group: The group.
3221 * Release the DMA ownership claimed by iommu_group_claim_dma_owner().
3223 void iommu_group_release_dma_owner(struct iommu_group *group)
3227 mutex_lock(&group->mutex);
3228 if (WARN_ON(!group->owner_cnt || !group->owner))
3231 group->owner_cnt = 0;
3232 group->owner = NULL;
3233 ret = __iommu_group_set_domain(group, group->default_domain);
3234 WARN(ret, "iommu driver failed to attach the default domain");
3237 mutex_unlock(&group->mutex);
3239 EXPORT_SYMBOL_GPL(iommu_group_release_dma_owner);
3242 * iommu_group_dma_owner_claimed() - Query group dma ownership status
3243 * @group: The group.
3245 * This provides status query on a given group. It is racy and only for
3246 * non-binding status reporting.
3248 bool iommu_group_dma_owner_claimed(struct iommu_group *group)
3252 mutex_lock(&group->mutex);
3253 user = group->owner_cnt;
3254 mutex_unlock(&group->mutex);
3258 EXPORT_SYMBOL_GPL(iommu_group_dma_owner_claimed);