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 ops->release_device(dev);
265 module_put(ops->owner);
273 int iommu_probe_device(struct device *dev)
275 const struct iommu_ops *ops;
276 struct iommu_group *group;
279 ret = __iommu_probe_device(dev, NULL);
283 group = iommu_group_get(dev);
290 * Try to allocate a default domain - needs support from the
291 * IOMMU driver. There are still some drivers which don't
292 * support default domains, so the return value is not yet
295 mutex_lock(&group->mutex);
296 iommu_alloc_default_domain(group, dev);
299 * If device joined an existing group which has been claimed, don't
300 * attach the default domain.
302 if (group->default_domain && !group->owner) {
303 ret = __iommu_attach_device(group->default_domain, dev);
305 mutex_unlock(&group->mutex);
306 iommu_group_put(group);
311 iommu_create_device_direct_mappings(group, dev);
313 mutex_unlock(&group->mutex);
314 iommu_group_put(group);
316 ops = dev_iommu_ops(dev);
317 if (ops->probe_finalize)
318 ops->probe_finalize(dev);
323 iommu_release_device(dev);
330 void iommu_release_device(struct device *dev)
332 const struct iommu_ops *ops;
337 iommu_device_unlink(dev->iommu->iommu_dev, dev);
339 ops = dev_iommu_ops(dev);
340 ops->release_device(dev);
342 iommu_group_remove_device(dev);
343 module_put(ops->owner);
347 static int __init iommu_set_def_domain_type(char *str)
352 ret = kstrtobool(str, &pt);
357 iommu_set_default_passthrough(true);
359 iommu_set_default_translated(true);
363 early_param("iommu.passthrough", iommu_set_def_domain_type);
365 static int __init iommu_dma_setup(char *str)
367 int ret = kstrtobool(str, &iommu_dma_strict);
370 iommu_cmd_line |= IOMMU_CMD_LINE_STRICT;
373 early_param("iommu.strict", iommu_dma_setup);
375 void iommu_set_dma_strict(void)
377 iommu_dma_strict = true;
378 if (iommu_def_domain_type == IOMMU_DOMAIN_DMA_FQ)
379 iommu_def_domain_type = IOMMU_DOMAIN_DMA;
382 static ssize_t iommu_group_attr_show(struct kobject *kobj,
383 struct attribute *__attr, char *buf)
385 struct iommu_group_attribute *attr = to_iommu_group_attr(__attr);
386 struct iommu_group *group = to_iommu_group(kobj);
390 ret = attr->show(group, buf);
394 static ssize_t iommu_group_attr_store(struct kobject *kobj,
395 struct attribute *__attr,
396 const char *buf, size_t count)
398 struct iommu_group_attribute *attr = to_iommu_group_attr(__attr);
399 struct iommu_group *group = to_iommu_group(kobj);
403 ret = attr->store(group, buf, count);
407 static const struct sysfs_ops iommu_group_sysfs_ops = {
408 .show = iommu_group_attr_show,
409 .store = iommu_group_attr_store,
412 static int iommu_group_create_file(struct iommu_group *group,
413 struct iommu_group_attribute *attr)
415 return sysfs_create_file(&group->kobj, &attr->attr);
418 static void iommu_group_remove_file(struct iommu_group *group,
419 struct iommu_group_attribute *attr)
421 sysfs_remove_file(&group->kobj, &attr->attr);
424 static ssize_t iommu_group_show_name(struct iommu_group *group, char *buf)
426 return sprintf(buf, "%s\n", group->name);
430 * iommu_insert_resv_region - Insert a new region in the
431 * list of reserved regions.
432 * @new: new region to insert
433 * @regions: list of regions
435 * Elements are sorted by start address and overlapping segments
436 * of the same type are merged.
438 static int iommu_insert_resv_region(struct iommu_resv_region *new,
439 struct list_head *regions)
441 struct iommu_resv_region *iter, *tmp, *nr, *top;
444 nr = iommu_alloc_resv_region(new->start, new->length,
445 new->prot, new->type);
449 /* First add the new element based on start address sorting */
450 list_for_each_entry(iter, regions, list) {
451 if (nr->start < iter->start ||
452 (nr->start == iter->start && nr->type <= iter->type))
455 list_add_tail(&nr->list, &iter->list);
457 /* Merge overlapping segments of type nr->type in @regions, if any */
458 list_for_each_entry_safe(iter, tmp, regions, list) {
459 phys_addr_t top_end, iter_end = iter->start + iter->length - 1;
461 /* no merge needed on elements of different types than @new */
462 if (iter->type != new->type) {
463 list_move_tail(&iter->list, &stack);
467 /* look for the last stack element of same type as @iter */
468 list_for_each_entry_reverse(top, &stack, list)
469 if (top->type == iter->type)
472 list_move_tail(&iter->list, &stack);
476 top_end = top->start + top->length - 1;
478 if (iter->start > top_end + 1) {
479 list_move_tail(&iter->list, &stack);
481 top->length = max(top_end, iter_end) - top->start + 1;
482 list_del(&iter->list);
486 list_splice(&stack, regions);
491 iommu_insert_device_resv_regions(struct list_head *dev_resv_regions,
492 struct list_head *group_resv_regions)
494 struct iommu_resv_region *entry;
497 list_for_each_entry(entry, dev_resv_regions, list) {
498 ret = iommu_insert_resv_region(entry, group_resv_regions);
505 int iommu_get_group_resv_regions(struct iommu_group *group,
506 struct list_head *head)
508 struct group_device *device;
511 mutex_lock(&group->mutex);
512 list_for_each_entry(device, &group->devices, list) {
513 struct list_head dev_resv_regions;
516 * Non-API groups still expose reserved_regions in sysfs,
517 * so filter out calls that get here that way.
519 if (!device->dev->iommu)
522 INIT_LIST_HEAD(&dev_resv_regions);
523 iommu_get_resv_regions(device->dev, &dev_resv_regions);
524 ret = iommu_insert_device_resv_regions(&dev_resv_regions, head);
525 iommu_put_resv_regions(device->dev, &dev_resv_regions);
529 mutex_unlock(&group->mutex);
532 EXPORT_SYMBOL_GPL(iommu_get_group_resv_regions);
534 static ssize_t iommu_group_show_resv_regions(struct iommu_group *group,
537 struct iommu_resv_region *region, *next;
538 struct list_head group_resv_regions;
541 INIT_LIST_HEAD(&group_resv_regions);
542 iommu_get_group_resv_regions(group, &group_resv_regions);
544 list_for_each_entry_safe(region, next, &group_resv_regions, list) {
545 str += sprintf(str, "0x%016llx 0x%016llx %s\n",
546 (long long int)region->start,
547 (long long int)(region->start +
549 iommu_group_resv_type_string[region->type]);
556 static ssize_t iommu_group_show_type(struct iommu_group *group,
559 char *type = "unknown\n";
561 mutex_lock(&group->mutex);
562 if (group->default_domain) {
563 switch (group->default_domain->type) {
564 case IOMMU_DOMAIN_BLOCKED:
567 case IOMMU_DOMAIN_IDENTITY:
570 case IOMMU_DOMAIN_UNMANAGED:
571 type = "unmanaged\n";
573 case IOMMU_DOMAIN_DMA:
576 case IOMMU_DOMAIN_DMA_FQ:
581 mutex_unlock(&group->mutex);
587 static IOMMU_GROUP_ATTR(name, S_IRUGO, iommu_group_show_name, NULL);
589 static IOMMU_GROUP_ATTR(reserved_regions, 0444,
590 iommu_group_show_resv_regions, NULL);
592 static IOMMU_GROUP_ATTR(type, 0644, iommu_group_show_type,
593 iommu_group_store_type);
595 static void iommu_group_release(struct kobject *kobj)
597 struct iommu_group *group = to_iommu_group(kobj);
599 pr_debug("Releasing group %d\n", group->id);
601 if (group->iommu_data_release)
602 group->iommu_data_release(group->iommu_data);
604 ida_free(&iommu_group_ida, group->id);
606 if (group->default_domain)
607 iommu_domain_free(group->default_domain);
608 if (group->blocking_domain)
609 iommu_domain_free(group->blocking_domain);
615 static struct kobj_type iommu_group_ktype = {
616 .sysfs_ops = &iommu_group_sysfs_ops,
617 .release = iommu_group_release,
621 * iommu_group_alloc - Allocate a new group
623 * This function is called by an iommu driver to allocate a new iommu
624 * group. The iommu group represents the minimum granularity of the iommu.
625 * Upon successful return, the caller holds a reference to the supplied
626 * group in order to hold the group until devices are added. Use
627 * iommu_group_put() to release this extra reference count, allowing the
628 * group to be automatically reclaimed once it has no devices or external
631 struct iommu_group *iommu_group_alloc(void)
633 struct iommu_group *group;
636 group = kzalloc(sizeof(*group), GFP_KERNEL);
638 return ERR_PTR(-ENOMEM);
640 group->kobj.kset = iommu_group_kset;
641 mutex_init(&group->mutex);
642 INIT_LIST_HEAD(&group->devices);
643 INIT_LIST_HEAD(&group->entry);
645 ret = ida_alloc(&iommu_group_ida, GFP_KERNEL);
652 ret = kobject_init_and_add(&group->kobj, &iommu_group_ktype,
653 NULL, "%d", group->id);
655 ida_free(&iommu_group_ida, group->id);
656 kobject_put(&group->kobj);
660 group->devices_kobj = kobject_create_and_add("devices", &group->kobj);
661 if (!group->devices_kobj) {
662 kobject_put(&group->kobj); /* triggers .release & free */
663 return ERR_PTR(-ENOMEM);
667 * The devices_kobj holds a reference on the group kobject, so
668 * as long as that exists so will the group. We can therefore
669 * use the devices_kobj for reference counting.
671 kobject_put(&group->kobj);
673 ret = iommu_group_create_file(group,
674 &iommu_group_attr_reserved_regions);
678 ret = iommu_group_create_file(group, &iommu_group_attr_type);
682 pr_debug("Allocated group %d\n", group->id);
686 EXPORT_SYMBOL_GPL(iommu_group_alloc);
688 struct iommu_group *iommu_group_get_by_id(int id)
690 struct kobject *group_kobj;
691 struct iommu_group *group;
694 if (!iommu_group_kset)
697 name = kasprintf(GFP_KERNEL, "%d", id);
701 group_kobj = kset_find_obj(iommu_group_kset, name);
707 group = container_of(group_kobj, struct iommu_group, kobj);
708 BUG_ON(group->id != id);
710 kobject_get(group->devices_kobj);
711 kobject_put(&group->kobj);
715 EXPORT_SYMBOL_GPL(iommu_group_get_by_id);
718 * iommu_group_get_iommudata - retrieve iommu_data registered for a group
721 * iommu drivers can store data in the group for use when doing iommu
722 * operations. This function provides a way to retrieve it. Caller
723 * should hold a group reference.
725 void *iommu_group_get_iommudata(struct iommu_group *group)
727 return group->iommu_data;
729 EXPORT_SYMBOL_GPL(iommu_group_get_iommudata);
732 * iommu_group_set_iommudata - set iommu_data for a group
734 * @iommu_data: new data
735 * @release: release function for iommu_data
737 * iommu drivers can store data in the group for use when doing iommu
738 * operations. This function provides a way to set the data after
739 * the group has been allocated. Caller should hold a group reference.
741 void iommu_group_set_iommudata(struct iommu_group *group, void *iommu_data,
742 void (*release)(void *iommu_data))
744 group->iommu_data = iommu_data;
745 group->iommu_data_release = release;
747 EXPORT_SYMBOL_GPL(iommu_group_set_iommudata);
750 * iommu_group_set_name - set name for a group
754 * Allow iommu driver to set a name for a group. When set it will
755 * appear in a name attribute file under the group in sysfs.
757 int iommu_group_set_name(struct iommu_group *group, const char *name)
762 iommu_group_remove_file(group, &iommu_group_attr_name);
769 group->name = kstrdup(name, GFP_KERNEL);
773 ret = iommu_group_create_file(group, &iommu_group_attr_name);
782 EXPORT_SYMBOL_GPL(iommu_group_set_name);
784 static int iommu_create_device_direct_mappings(struct iommu_group *group,
787 struct iommu_domain *domain = group->default_domain;
788 struct iommu_resv_region *entry;
789 struct list_head mappings;
790 unsigned long pg_size;
793 if (!domain || !iommu_is_dma_domain(domain))
796 BUG_ON(!domain->pgsize_bitmap);
798 pg_size = 1UL << __ffs(domain->pgsize_bitmap);
799 INIT_LIST_HEAD(&mappings);
801 iommu_get_resv_regions(dev, &mappings);
803 /* We need to consider overlapping regions for different devices */
804 list_for_each_entry(entry, &mappings, list) {
805 dma_addr_t start, end, addr;
808 start = ALIGN(entry->start, pg_size);
809 end = ALIGN(entry->start + entry->length, pg_size);
811 if (entry->type != IOMMU_RESV_DIRECT &&
812 entry->type != IOMMU_RESV_DIRECT_RELAXABLE)
815 for (addr = start; addr <= end; addr += pg_size) {
816 phys_addr_t phys_addr;
821 phys_addr = iommu_iova_to_phys(domain, addr);
829 ret = iommu_map(domain, addr - map_size,
830 addr - map_size, map_size,
840 iommu_flush_iotlb_all(domain);
843 iommu_put_resv_regions(dev, &mappings);
848 static bool iommu_is_attach_deferred(struct device *dev)
850 const struct iommu_ops *ops = dev_iommu_ops(dev);
852 if (ops->is_attach_deferred)
853 return ops->is_attach_deferred(dev);
859 * iommu_group_add_device - add a device to an iommu group
860 * @group: the group into which to add the device (reference should be held)
863 * This function is called by an iommu driver to add a device into a
864 * group. Adding a device increments the group reference count.
866 int iommu_group_add_device(struct iommu_group *group, struct device *dev)
869 struct group_device *device;
871 device = kzalloc(sizeof(*device), GFP_KERNEL);
877 ret = sysfs_create_link(&dev->kobj, &group->kobj, "iommu_group");
879 goto err_free_device;
881 device->name = kasprintf(GFP_KERNEL, "%s", kobject_name(&dev->kobj));
885 goto err_remove_link;
888 ret = sysfs_create_link_nowarn(group->devices_kobj,
889 &dev->kobj, device->name);
891 if (ret == -EEXIST && i >= 0) {
893 * Account for the slim chance of collision
894 * and append an instance to the name.
897 device->name = kasprintf(GFP_KERNEL, "%s.%d",
898 kobject_name(&dev->kobj), i++);
904 kobject_get(group->devices_kobj);
906 dev->iommu_group = group;
908 mutex_lock(&group->mutex);
909 list_add_tail(&device->list, &group->devices);
910 if (group->domain && !iommu_is_attach_deferred(dev))
911 ret = __iommu_attach_device(group->domain, dev);
912 mutex_unlock(&group->mutex);
916 trace_add_device_to_group(group->id, dev);
918 dev_info(dev, "Adding to iommu group %d\n", group->id);
923 mutex_lock(&group->mutex);
924 list_del(&device->list);
925 mutex_unlock(&group->mutex);
926 dev->iommu_group = NULL;
927 kobject_put(group->devices_kobj);
928 sysfs_remove_link(group->devices_kobj, device->name);
932 sysfs_remove_link(&dev->kobj, "iommu_group");
935 dev_err(dev, "Failed to add to iommu group %d: %d\n", group->id, ret);
938 EXPORT_SYMBOL_GPL(iommu_group_add_device);
941 * iommu_group_remove_device - remove a device from it's current group
942 * @dev: device to be removed
944 * This function is called by an iommu driver to remove the device from
945 * it's current group. This decrements the iommu group reference count.
947 void iommu_group_remove_device(struct device *dev)
949 struct iommu_group *group = dev->iommu_group;
950 struct group_device *tmp_device, *device = NULL;
955 dev_info(dev, "Removing from iommu group %d\n", group->id);
957 mutex_lock(&group->mutex);
958 list_for_each_entry(tmp_device, &group->devices, list) {
959 if (tmp_device->dev == dev) {
961 list_del(&device->list);
965 mutex_unlock(&group->mutex);
970 sysfs_remove_link(group->devices_kobj, device->name);
971 sysfs_remove_link(&dev->kobj, "iommu_group");
973 trace_remove_device_from_group(group->id, dev);
977 dev->iommu_group = NULL;
978 kobject_put(group->devices_kobj);
980 EXPORT_SYMBOL_GPL(iommu_group_remove_device);
982 static int iommu_group_device_count(struct iommu_group *group)
984 struct group_device *entry;
987 list_for_each_entry(entry, &group->devices, list)
993 static int __iommu_group_for_each_dev(struct iommu_group *group, void *data,
994 int (*fn)(struct device *, void *))
996 struct group_device *device;
999 list_for_each_entry(device, &group->devices, list) {
1000 ret = fn(device->dev, data);
1008 * iommu_group_for_each_dev - iterate over each device in the group
1010 * @data: caller opaque data to be passed to callback function
1011 * @fn: caller supplied callback function
1013 * This function is called by group users to iterate over group devices.
1014 * Callers should hold a reference count to the group during callback.
1015 * The group->mutex is held across callbacks, which will block calls to
1016 * iommu_group_add/remove_device.
1018 int iommu_group_for_each_dev(struct iommu_group *group, void *data,
1019 int (*fn)(struct device *, void *))
1023 mutex_lock(&group->mutex);
1024 ret = __iommu_group_for_each_dev(group, data, fn);
1025 mutex_unlock(&group->mutex);
1029 EXPORT_SYMBOL_GPL(iommu_group_for_each_dev);
1032 * iommu_group_get - Return the group for a device and increment reference
1033 * @dev: get the group that this device belongs to
1035 * This function is called by iommu drivers and users to get the group
1036 * for the specified device. If found, the group is returned and the group
1037 * reference in incremented, else NULL.
1039 struct iommu_group *iommu_group_get(struct device *dev)
1041 struct iommu_group *group = dev->iommu_group;
1044 kobject_get(group->devices_kobj);
1048 EXPORT_SYMBOL_GPL(iommu_group_get);
1051 * iommu_group_ref_get - Increment reference on a group
1052 * @group: the group to use, must not be NULL
1054 * This function is called by iommu drivers to take additional references on an
1055 * existing group. Returns the given group for convenience.
1057 struct iommu_group *iommu_group_ref_get(struct iommu_group *group)
1059 kobject_get(group->devices_kobj);
1062 EXPORT_SYMBOL_GPL(iommu_group_ref_get);
1065 * iommu_group_put - Decrement group reference
1066 * @group: the group to use
1068 * This function is called by iommu drivers and users to release the
1069 * iommu group. Once the reference count is zero, the group is released.
1071 void iommu_group_put(struct iommu_group *group)
1074 kobject_put(group->devices_kobj);
1076 EXPORT_SYMBOL_GPL(iommu_group_put);
1079 * iommu_register_device_fault_handler() - Register a device fault handler
1081 * @handler: the fault handler
1082 * @data: private data passed as argument to the handler
1084 * When an IOMMU fault event is received, this handler gets called with the
1085 * fault event and data as argument. The handler should return 0 on success. If
1086 * the fault is recoverable (IOMMU_FAULT_PAGE_REQ), the consumer should also
1087 * complete the fault by calling iommu_page_response() with one of the following
1089 * - IOMMU_PAGE_RESP_SUCCESS: retry the translation
1090 * - IOMMU_PAGE_RESP_INVALID: terminate the fault
1091 * - IOMMU_PAGE_RESP_FAILURE: terminate the fault and stop reporting
1092 * page faults if possible.
1094 * Return 0 if the fault handler was installed successfully, or an error.
1096 int iommu_register_device_fault_handler(struct device *dev,
1097 iommu_dev_fault_handler_t handler,
1100 struct dev_iommu *param = dev->iommu;
1106 mutex_lock(¶m->lock);
1107 /* Only allow one fault handler registered for each device */
1108 if (param->fault_param) {
1114 param->fault_param = kzalloc(sizeof(*param->fault_param), GFP_KERNEL);
1115 if (!param->fault_param) {
1120 param->fault_param->handler = handler;
1121 param->fault_param->data = data;
1122 mutex_init(¶m->fault_param->lock);
1123 INIT_LIST_HEAD(¶m->fault_param->faults);
1126 mutex_unlock(¶m->lock);
1130 EXPORT_SYMBOL_GPL(iommu_register_device_fault_handler);
1133 * iommu_unregister_device_fault_handler() - Unregister the device fault handler
1136 * Remove the device fault handler installed with
1137 * iommu_register_device_fault_handler().
1139 * Return 0 on success, or an error.
1141 int iommu_unregister_device_fault_handler(struct device *dev)
1143 struct dev_iommu *param = dev->iommu;
1149 mutex_lock(¶m->lock);
1151 if (!param->fault_param)
1154 /* we cannot unregister handler if there are pending faults */
1155 if (!list_empty(¶m->fault_param->faults)) {
1160 kfree(param->fault_param);
1161 param->fault_param = NULL;
1164 mutex_unlock(¶m->lock);
1168 EXPORT_SYMBOL_GPL(iommu_unregister_device_fault_handler);
1171 * iommu_report_device_fault() - Report fault event to device driver
1173 * @evt: fault event data
1175 * Called by IOMMU drivers when a fault is detected, typically in a threaded IRQ
1176 * handler. When this function fails and the fault is recoverable, it is the
1177 * caller's responsibility to complete the fault.
1179 * Return 0 on success, or an error.
1181 int iommu_report_device_fault(struct device *dev, struct iommu_fault_event *evt)
1183 struct dev_iommu *param = dev->iommu;
1184 struct iommu_fault_event *evt_pending = NULL;
1185 struct iommu_fault_param *fparam;
1191 /* we only report device fault if there is a handler registered */
1192 mutex_lock(¶m->lock);
1193 fparam = param->fault_param;
1194 if (!fparam || !fparam->handler) {
1199 if (evt->fault.type == IOMMU_FAULT_PAGE_REQ &&
1200 (evt->fault.prm.flags & IOMMU_FAULT_PAGE_REQUEST_LAST_PAGE)) {
1201 evt_pending = kmemdup(evt, sizeof(struct iommu_fault_event),
1207 mutex_lock(&fparam->lock);
1208 list_add_tail(&evt_pending->list, &fparam->faults);
1209 mutex_unlock(&fparam->lock);
1212 ret = fparam->handler(&evt->fault, fparam->data);
1213 if (ret && evt_pending) {
1214 mutex_lock(&fparam->lock);
1215 list_del(&evt_pending->list);
1216 mutex_unlock(&fparam->lock);
1220 mutex_unlock(¶m->lock);
1223 EXPORT_SYMBOL_GPL(iommu_report_device_fault);
1225 int iommu_page_response(struct device *dev,
1226 struct iommu_page_response *msg)
1230 struct iommu_fault_event *evt;
1231 struct iommu_fault_page_request *prm;
1232 struct dev_iommu *param = dev->iommu;
1233 const struct iommu_ops *ops = dev_iommu_ops(dev);
1234 bool has_pasid = msg->flags & IOMMU_PAGE_RESP_PASID_VALID;
1236 if (!ops->page_response)
1239 if (!param || !param->fault_param)
1242 if (msg->version != IOMMU_PAGE_RESP_VERSION_1 ||
1243 msg->flags & ~IOMMU_PAGE_RESP_PASID_VALID)
1246 /* Only send response if there is a fault report pending */
1247 mutex_lock(¶m->fault_param->lock);
1248 if (list_empty(¶m->fault_param->faults)) {
1249 dev_warn_ratelimited(dev, "no pending PRQ, drop response\n");
1253 * Check if we have a matching page request pending to respond,
1254 * otherwise return -EINVAL
1256 list_for_each_entry(evt, ¶m->fault_param->faults, list) {
1257 prm = &evt->fault.prm;
1258 if (prm->grpid != msg->grpid)
1262 * If the PASID is required, the corresponding request is
1263 * matched using the group ID, the PASID valid bit and the PASID
1264 * value. Otherwise only the group ID matches request and
1267 needs_pasid = prm->flags & IOMMU_FAULT_PAGE_RESPONSE_NEEDS_PASID;
1268 if (needs_pasid && (!has_pasid || msg->pasid != prm->pasid))
1271 if (!needs_pasid && has_pasid) {
1272 /* No big deal, just clear it. */
1273 msg->flags &= ~IOMMU_PAGE_RESP_PASID_VALID;
1277 ret = ops->page_response(dev, evt, msg);
1278 list_del(&evt->list);
1284 mutex_unlock(¶m->fault_param->lock);
1287 EXPORT_SYMBOL_GPL(iommu_page_response);
1290 * iommu_group_id - Return ID for a group
1291 * @group: the group to ID
1293 * Return the unique ID for the group matching the sysfs group number.
1295 int iommu_group_id(struct iommu_group *group)
1299 EXPORT_SYMBOL_GPL(iommu_group_id);
1301 static struct iommu_group *get_pci_alias_group(struct pci_dev *pdev,
1302 unsigned long *devfns);
1305 * To consider a PCI device isolated, we require ACS to support Source
1306 * Validation, Request Redirection, Completer Redirection, and Upstream
1307 * Forwarding. This effectively means that devices cannot spoof their
1308 * requester ID, requests and completions cannot be redirected, and all
1309 * transactions are forwarded upstream, even as it passes through a
1310 * bridge where the target device is downstream.
1312 #define REQ_ACS_FLAGS (PCI_ACS_SV | PCI_ACS_RR | PCI_ACS_CR | PCI_ACS_UF)
1315 * For multifunction devices which are not isolated from each other, find
1316 * all the other non-isolated functions and look for existing groups. For
1317 * each function, we also need to look for aliases to or from other devices
1318 * that may already have a group.
1320 static struct iommu_group *get_pci_function_alias_group(struct pci_dev *pdev,
1321 unsigned long *devfns)
1323 struct pci_dev *tmp = NULL;
1324 struct iommu_group *group;
1326 if (!pdev->multifunction || pci_acs_enabled(pdev, REQ_ACS_FLAGS))
1329 for_each_pci_dev(tmp) {
1330 if (tmp == pdev || tmp->bus != pdev->bus ||
1331 PCI_SLOT(tmp->devfn) != PCI_SLOT(pdev->devfn) ||
1332 pci_acs_enabled(tmp, REQ_ACS_FLAGS))
1335 group = get_pci_alias_group(tmp, devfns);
1346 * Look for aliases to or from the given device for existing groups. DMA
1347 * aliases are only supported on the same bus, therefore the search
1348 * space is quite small (especially since we're really only looking at pcie
1349 * device, and therefore only expect multiple slots on the root complex or
1350 * downstream switch ports). It's conceivable though that a pair of
1351 * multifunction devices could have aliases between them that would cause a
1352 * loop. To prevent this, we use a bitmap to track where we've been.
1354 static struct iommu_group *get_pci_alias_group(struct pci_dev *pdev,
1355 unsigned long *devfns)
1357 struct pci_dev *tmp = NULL;
1358 struct iommu_group *group;
1360 if (test_and_set_bit(pdev->devfn & 0xff, devfns))
1363 group = iommu_group_get(&pdev->dev);
1367 for_each_pci_dev(tmp) {
1368 if (tmp == pdev || tmp->bus != pdev->bus)
1371 /* We alias them or they alias us */
1372 if (pci_devs_are_dma_aliases(pdev, tmp)) {
1373 group = get_pci_alias_group(tmp, devfns);
1379 group = get_pci_function_alias_group(tmp, devfns);
1390 struct group_for_pci_data {
1391 struct pci_dev *pdev;
1392 struct iommu_group *group;
1396 * DMA alias iterator callback, return the last seen device. Stop and return
1397 * the IOMMU group if we find one along the way.
1399 static int get_pci_alias_or_group(struct pci_dev *pdev, u16 alias, void *opaque)
1401 struct group_for_pci_data *data = opaque;
1404 data->group = iommu_group_get(&pdev->dev);
1406 return data->group != NULL;
1410 * Generic device_group call-back function. It just allocates one
1411 * iommu-group per device.
1413 struct iommu_group *generic_device_group(struct device *dev)
1415 return iommu_group_alloc();
1417 EXPORT_SYMBOL_GPL(generic_device_group);
1420 * Use standard PCI bus topology, isolation features, and DMA alias quirks
1421 * to find or create an IOMMU group for a device.
1423 struct iommu_group *pci_device_group(struct device *dev)
1425 struct pci_dev *pdev = to_pci_dev(dev);
1426 struct group_for_pci_data data;
1427 struct pci_bus *bus;
1428 struct iommu_group *group = NULL;
1429 u64 devfns[4] = { 0 };
1431 if (WARN_ON(!dev_is_pci(dev)))
1432 return ERR_PTR(-EINVAL);
1435 * Find the upstream DMA alias for the device. A device must not
1436 * be aliased due to topology in order to have its own IOMMU group.
1437 * If we find an alias along the way that already belongs to a
1440 if (pci_for_each_dma_alias(pdev, get_pci_alias_or_group, &data))
1446 * Continue upstream from the point of minimum IOMMU granularity
1447 * due to aliases to the point where devices are protected from
1448 * peer-to-peer DMA by PCI ACS. Again, if we find an existing
1451 for (bus = pdev->bus; !pci_is_root_bus(bus); bus = bus->parent) {
1455 if (pci_acs_path_enabled(bus->self, NULL, REQ_ACS_FLAGS))
1460 group = iommu_group_get(&pdev->dev);
1466 * Look for existing groups on device aliases. If we alias another
1467 * device or another device aliases us, use the same group.
1469 group = get_pci_alias_group(pdev, (unsigned long *)devfns);
1474 * Look for existing groups on non-isolated functions on the same
1475 * slot and aliases of those funcions, if any. No need to clear
1476 * the search bitmap, the tested devfns are still valid.
1478 group = get_pci_function_alias_group(pdev, (unsigned long *)devfns);
1482 /* No shared group found, allocate new */
1483 return iommu_group_alloc();
1485 EXPORT_SYMBOL_GPL(pci_device_group);
1487 /* Get the IOMMU group for device on fsl-mc bus */
1488 struct iommu_group *fsl_mc_device_group(struct device *dev)
1490 struct device *cont_dev = fsl_mc_cont_dev(dev);
1491 struct iommu_group *group;
1493 group = iommu_group_get(cont_dev);
1495 group = iommu_group_alloc();
1498 EXPORT_SYMBOL_GPL(fsl_mc_device_group);
1500 static int iommu_get_def_domain_type(struct device *dev)
1502 const struct iommu_ops *ops = dev_iommu_ops(dev);
1504 if (dev_is_pci(dev) && to_pci_dev(dev)->untrusted)
1505 return IOMMU_DOMAIN_DMA;
1507 if (ops->def_domain_type)
1508 return ops->def_domain_type(dev);
1513 static int iommu_group_alloc_default_domain(struct bus_type *bus,
1514 struct iommu_group *group,
1517 struct iommu_domain *dom;
1519 dom = __iommu_domain_alloc(bus, type);
1520 if (!dom && type != IOMMU_DOMAIN_DMA) {
1521 dom = __iommu_domain_alloc(bus, IOMMU_DOMAIN_DMA);
1523 pr_warn("Failed to allocate default IOMMU domain of type %u for group %s - Falling back to IOMMU_DOMAIN_DMA",
1530 group->default_domain = dom;
1532 group->domain = dom;
1536 static int iommu_alloc_default_domain(struct iommu_group *group,
1541 if (group->default_domain)
1544 type = iommu_get_def_domain_type(dev) ? : iommu_def_domain_type;
1546 return iommu_group_alloc_default_domain(dev->bus, group, type);
1550 * iommu_group_get_for_dev - Find or create the IOMMU group for a device
1551 * @dev: target device
1553 * This function is intended to be called by IOMMU drivers and extended to
1554 * support common, bus-defined algorithms when determining or creating the
1555 * IOMMU group for a device. On success, the caller will hold a reference
1556 * to the returned IOMMU group, which will already include the provided
1557 * device. The reference should be released with iommu_group_put().
1559 static struct iommu_group *iommu_group_get_for_dev(struct device *dev)
1561 const struct iommu_ops *ops = dev_iommu_ops(dev);
1562 struct iommu_group *group;
1565 group = iommu_group_get(dev);
1569 group = ops->device_group(dev);
1570 if (WARN_ON_ONCE(group == NULL))
1571 return ERR_PTR(-EINVAL);
1576 ret = iommu_group_add_device(group, dev);
1583 iommu_group_put(group);
1585 return ERR_PTR(ret);
1588 struct iommu_domain *iommu_group_default_domain(struct iommu_group *group)
1590 return group->default_domain;
1593 static int probe_iommu_group(struct device *dev, void *data)
1595 struct list_head *group_list = data;
1596 struct iommu_group *group;
1599 /* Device is probed already if in a group */
1600 group = iommu_group_get(dev);
1602 iommu_group_put(group);
1606 ret = __iommu_probe_device(dev, group_list);
1613 static int remove_iommu_group(struct device *dev, void *data)
1615 iommu_release_device(dev);
1620 static int iommu_bus_notifier(struct notifier_block *nb,
1621 unsigned long action, void *data)
1623 struct device *dev = data;
1625 if (action == BUS_NOTIFY_ADD_DEVICE) {
1628 ret = iommu_probe_device(dev);
1629 return (ret) ? NOTIFY_DONE : NOTIFY_OK;
1630 } else if (action == BUS_NOTIFY_REMOVED_DEVICE) {
1631 iommu_release_device(dev);
1638 struct __group_domain_type {
1643 static int probe_get_default_domain_type(struct device *dev, void *data)
1645 struct __group_domain_type *gtype = data;
1646 unsigned int type = iommu_get_def_domain_type(dev);
1649 if (gtype->type && gtype->type != type) {
1650 dev_warn(dev, "Device needs domain type %s, but device %s in the same iommu group requires type %s - using default\n",
1651 iommu_domain_type_str(type),
1652 dev_name(gtype->dev),
1653 iommu_domain_type_str(gtype->type));
1666 static void probe_alloc_default_domain(struct bus_type *bus,
1667 struct iommu_group *group)
1669 struct __group_domain_type gtype;
1671 memset(>ype, 0, sizeof(gtype));
1673 /* Ask for default domain requirements of all devices in the group */
1674 __iommu_group_for_each_dev(group, >ype,
1675 probe_get_default_domain_type);
1678 gtype.type = iommu_def_domain_type;
1680 iommu_group_alloc_default_domain(bus, group, gtype.type);
1684 static int iommu_group_do_dma_attach(struct device *dev, void *data)
1686 struct iommu_domain *domain = data;
1689 if (!iommu_is_attach_deferred(dev))
1690 ret = __iommu_attach_device(domain, dev);
1695 static int __iommu_group_dma_attach(struct iommu_group *group)
1697 return __iommu_group_for_each_dev(group, group->default_domain,
1698 iommu_group_do_dma_attach);
1701 static int iommu_group_do_probe_finalize(struct device *dev, void *data)
1703 const struct iommu_ops *ops = dev_iommu_ops(dev);
1705 if (ops->probe_finalize)
1706 ops->probe_finalize(dev);
1711 static void __iommu_group_dma_finalize(struct iommu_group *group)
1713 __iommu_group_for_each_dev(group, group->default_domain,
1714 iommu_group_do_probe_finalize);
1717 static int iommu_do_create_direct_mappings(struct device *dev, void *data)
1719 struct iommu_group *group = data;
1721 iommu_create_device_direct_mappings(group, dev);
1726 static int iommu_group_create_direct_mappings(struct iommu_group *group)
1728 return __iommu_group_for_each_dev(group, group,
1729 iommu_do_create_direct_mappings);
1732 int bus_iommu_probe(struct bus_type *bus)
1734 struct iommu_group *group, *next;
1735 LIST_HEAD(group_list);
1739 * This code-path does not allocate the default domain when
1740 * creating the iommu group, so do it after the groups are
1743 ret = bus_for_each_dev(bus, NULL, &group_list, probe_iommu_group);
1747 list_for_each_entry_safe(group, next, &group_list, entry) {
1748 /* Remove item from the list */
1749 list_del_init(&group->entry);
1751 mutex_lock(&group->mutex);
1753 /* Try to allocate default domain */
1754 probe_alloc_default_domain(bus, group);
1756 if (!group->default_domain) {
1757 mutex_unlock(&group->mutex);
1761 iommu_group_create_direct_mappings(group);
1763 ret = __iommu_group_dma_attach(group);
1765 mutex_unlock(&group->mutex);
1770 __iommu_group_dma_finalize(group);
1776 static int iommu_bus_init(struct bus_type *bus, const struct iommu_ops *ops)
1778 struct notifier_block *nb;
1781 nb = kzalloc(sizeof(struct notifier_block), GFP_KERNEL);
1785 nb->notifier_call = iommu_bus_notifier;
1787 err = bus_register_notifier(bus, nb);
1791 err = bus_iommu_probe(bus);
1800 bus_for_each_dev(bus, NULL, NULL, remove_iommu_group);
1801 bus_unregister_notifier(bus, nb);
1810 * bus_set_iommu - set iommu-callbacks for the bus
1812 * @ops: the callbacks provided by the iommu-driver
1814 * This function is called by an iommu driver to set the iommu methods
1815 * used for a particular bus. Drivers for devices on that bus can use
1816 * the iommu-api after these ops are registered.
1817 * This special function is needed because IOMMUs are usually devices on
1818 * the bus itself, so the iommu drivers are not initialized when the bus
1819 * is set up. With this function the iommu-driver can set the iommu-ops
1822 int bus_set_iommu(struct bus_type *bus, const struct iommu_ops *ops)
1827 bus->iommu_ops = NULL;
1831 if (bus->iommu_ops != NULL)
1834 bus->iommu_ops = ops;
1836 /* Do IOMMU specific setup for this bus-type */
1837 err = iommu_bus_init(bus, ops);
1839 bus->iommu_ops = NULL;
1843 EXPORT_SYMBOL_GPL(bus_set_iommu);
1845 bool iommu_present(struct bus_type *bus)
1847 return bus->iommu_ops != NULL;
1849 EXPORT_SYMBOL_GPL(iommu_present);
1852 * device_iommu_capable() - check for a general IOMMU capability
1853 * @dev: device to which the capability would be relevant, if available
1854 * @cap: IOMMU capability
1856 * Return: true if an IOMMU is present and supports the given capability
1857 * for the given device, otherwise false.
1859 bool device_iommu_capable(struct device *dev, enum iommu_cap cap)
1861 const struct iommu_ops *ops;
1863 if (!dev->iommu || !dev->iommu->iommu_dev)
1866 ops = dev_iommu_ops(dev);
1870 return ops->capable(cap);
1872 EXPORT_SYMBOL_GPL(device_iommu_capable);
1874 bool iommu_capable(struct bus_type *bus, enum iommu_cap cap)
1876 if (!bus->iommu_ops || !bus->iommu_ops->capable)
1879 return bus->iommu_ops->capable(cap);
1881 EXPORT_SYMBOL_GPL(iommu_capable);
1884 * iommu_set_fault_handler() - set a fault handler for an iommu domain
1885 * @domain: iommu domain
1886 * @handler: fault handler
1887 * @token: user data, will be passed back to the fault handler
1889 * This function should be used by IOMMU users which want to be notified
1890 * whenever an IOMMU fault happens.
1892 * The fault handler itself should return 0 on success, and an appropriate
1893 * error code otherwise.
1895 void iommu_set_fault_handler(struct iommu_domain *domain,
1896 iommu_fault_handler_t handler,
1901 domain->handler = handler;
1902 domain->handler_token = token;
1904 EXPORT_SYMBOL_GPL(iommu_set_fault_handler);
1906 static struct iommu_domain *__iommu_domain_alloc(struct bus_type *bus,
1909 struct iommu_domain *domain;
1911 if (bus == NULL || bus->iommu_ops == NULL)
1914 domain = bus->iommu_ops->domain_alloc(type);
1918 domain->type = type;
1919 /* Assume all sizes by default; the driver may override this later */
1920 domain->pgsize_bitmap = bus->iommu_ops->pgsize_bitmap;
1922 domain->ops = bus->iommu_ops->default_domain_ops;
1924 if (iommu_is_dma_domain(domain) && iommu_get_dma_cookie(domain)) {
1925 iommu_domain_free(domain);
1931 struct iommu_domain *iommu_domain_alloc(struct bus_type *bus)
1933 return __iommu_domain_alloc(bus, IOMMU_DOMAIN_UNMANAGED);
1935 EXPORT_SYMBOL_GPL(iommu_domain_alloc);
1937 void iommu_domain_free(struct iommu_domain *domain)
1939 iommu_put_dma_cookie(domain);
1940 domain->ops->free(domain);
1942 EXPORT_SYMBOL_GPL(iommu_domain_free);
1945 * Put the group's domain back to the appropriate core-owned domain - either the
1946 * standard kernel-mode DMA configuration or an all-DMA-blocked domain.
1948 static void __iommu_group_set_core_domain(struct iommu_group *group)
1950 struct iommu_domain *new_domain;
1954 new_domain = group->blocking_domain;
1956 new_domain = group->default_domain;
1958 ret = __iommu_group_set_domain(group, new_domain);
1959 WARN(ret, "iommu driver failed to attach the default/blocking domain");
1962 static int __iommu_attach_device(struct iommu_domain *domain,
1967 if (unlikely(domain->ops->attach_dev == NULL))
1970 ret = domain->ops->attach_dev(domain, dev);
1972 trace_attach_device_to_domain(dev);
1976 int iommu_attach_device(struct iommu_domain *domain, struct device *dev)
1978 struct iommu_group *group;
1981 group = iommu_group_get(dev);
1986 * Lock the group to make sure the device-count doesn't
1987 * change while we are attaching
1989 mutex_lock(&group->mutex);
1991 if (iommu_group_device_count(group) != 1)
1994 ret = __iommu_attach_group(domain, group);
1997 mutex_unlock(&group->mutex);
1998 iommu_group_put(group);
2002 EXPORT_SYMBOL_GPL(iommu_attach_device);
2004 int iommu_deferred_attach(struct device *dev, struct iommu_domain *domain)
2006 if (iommu_is_attach_deferred(dev))
2007 return __iommu_attach_device(domain, dev);
2012 static void __iommu_detach_device(struct iommu_domain *domain,
2015 if (iommu_is_attach_deferred(dev))
2018 domain->ops->detach_dev(domain, dev);
2019 trace_detach_device_from_domain(dev);
2022 void iommu_detach_device(struct iommu_domain *domain, struct device *dev)
2024 struct iommu_group *group;
2026 group = iommu_group_get(dev);
2030 mutex_lock(&group->mutex);
2031 if (WARN_ON(domain != group->domain) ||
2032 WARN_ON(iommu_group_device_count(group) != 1))
2034 __iommu_group_set_core_domain(group);
2037 mutex_unlock(&group->mutex);
2038 iommu_group_put(group);
2040 EXPORT_SYMBOL_GPL(iommu_detach_device);
2042 struct iommu_domain *iommu_get_domain_for_dev(struct device *dev)
2044 struct iommu_domain *domain;
2045 struct iommu_group *group;
2047 group = iommu_group_get(dev);
2051 domain = group->domain;
2053 iommu_group_put(group);
2057 EXPORT_SYMBOL_GPL(iommu_get_domain_for_dev);
2060 * For IOMMU_DOMAIN_DMA implementations which already provide their own
2061 * guarantees that the group and its default domain are valid and correct.
2063 struct iommu_domain *iommu_get_dma_domain(struct device *dev)
2065 return dev->iommu_group->default_domain;
2069 * IOMMU groups are really the natural working unit of the IOMMU, but
2070 * the IOMMU API works on domains and devices. Bridge that gap by
2071 * iterating over the devices in a group. Ideally we'd have a single
2072 * device which represents the requestor ID of the group, but we also
2073 * allow IOMMU drivers to create policy defined minimum sets, where
2074 * the physical hardware may be able to distiguish members, but we
2075 * wish to group them at a higher level (ex. untrusted multi-function
2076 * PCI devices). Thus we attach each device.
2078 static int iommu_group_do_attach_device(struct device *dev, void *data)
2080 struct iommu_domain *domain = data;
2082 return __iommu_attach_device(domain, dev);
2085 static int __iommu_attach_group(struct iommu_domain *domain,
2086 struct iommu_group *group)
2090 if (group->domain && group->domain != group->default_domain &&
2091 group->domain != group->blocking_domain)
2094 ret = __iommu_group_for_each_dev(group, domain,
2095 iommu_group_do_attach_device);
2097 group->domain = domain;
2102 int iommu_attach_group(struct iommu_domain *domain, struct iommu_group *group)
2106 mutex_lock(&group->mutex);
2107 ret = __iommu_attach_group(domain, group);
2108 mutex_unlock(&group->mutex);
2112 EXPORT_SYMBOL_GPL(iommu_attach_group);
2114 static int iommu_group_do_detach_device(struct device *dev, void *data)
2116 struct iommu_domain *domain = data;
2118 __iommu_detach_device(domain, dev);
2123 static int __iommu_group_set_domain(struct iommu_group *group,
2124 struct iommu_domain *new_domain)
2128 if (group->domain == new_domain)
2132 * New drivers should support default domains and so the detach_dev() op
2133 * will never be called. Otherwise the NULL domain represents some
2134 * platform specific behavior.
2137 if (WARN_ON(!group->domain->ops->detach_dev))
2139 __iommu_group_for_each_dev(group, group->domain,
2140 iommu_group_do_detach_device);
2141 group->domain = NULL;
2146 * Changing the domain is done by calling attach_dev() on the new
2147 * domain. This switch does not have to be atomic and DMA can be
2148 * discarded during the transition. DMA must only be able to access
2149 * either new_domain or group->domain, never something else.
2151 * Note that this is called in error unwind paths, attaching to a
2152 * domain that has already been attached cannot fail.
2154 ret = __iommu_group_for_each_dev(group, new_domain,
2155 iommu_group_do_attach_device);
2158 group->domain = new_domain;
2162 void iommu_detach_group(struct iommu_domain *domain, struct iommu_group *group)
2164 mutex_lock(&group->mutex);
2165 __iommu_group_set_core_domain(group);
2166 mutex_unlock(&group->mutex);
2168 EXPORT_SYMBOL_GPL(iommu_detach_group);
2170 phys_addr_t iommu_iova_to_phys(struct iommu_domain *domain, dma_addr_t iova)
2172 if (domain->type == IOMMU_DOMAIN_IDENTITY)
2175 if (domain->type == IOMMU_DOMAIN_BLOCKED)
2178 return domain->ops->iova_to_phys(domain, iova);
2180 EXPORT_SYMBOL_GPL(iommu_iova_to_phys);
2182 static size_t iommu_pgsize(struct iommu_domain *domain, unsigned long iova,
2183 phys_addr_t paddr, size_t size, size_t *count)
2185 unsigned int pgsize_idx, pgsize_idx_next;
2186 unsigned long pgsizes;
2187 size_t offset, pgsize, pgsize_next;
2188 unsigned long addr_merge = paddr | iova;
2190 /* Page sizes supported by the hardware and small enough for @size */
2191 pgsizes = domain->pgsize_bitmap & GENMASK(__fls(size), 0);
2193 /* Constrain the page sizes further based on the maximum alignment */
2194 if (likely(addr_merge))
2195 pgsizes &= GENMASK(__ffs(addr_merge), 0);
2197 /* Make sure we have at least one suitable page size */
2200 /* Pick the biggest page size remaining */
2201 pgsize_idx = __fls(pgsizes);
2202 pgsize = BIT(pgsize_idx);
2206 /* Find the next biggest support page size, if it exists */
2207 pgsizes = domain->pgsize_bitmap & ~GENMASK(pgsize_idx, 0);
2211 pgsize_idx_next = __ffs(pgsizes);
2212 pgsize_next = BIT(pgsize_idx_next);
2215 * There's no point trying a bigger page size unless the virtual
2216 * and physical addresses are similarly offset within the larger page.
2218 if ((iova ^ paddr) & (pgsize_next - 1))
2221 /* Calculate the offset to the next page size alignment boundary */
2222 offset = pgsize_next - (addr_merge & (pgsize_next - 1));
2225 * If size is big enough to accommodate the larger page, reduce
2226 * the number of smaller pages.
2228 if (offset + pgsize_next <= size)
2232 *count = size >> pgsize_idx;
2236 static int __iommu_map_pages(struct iommu_domain *domain, unsigned long iova,
2237 phys_addr_t paddr, size_t size, int prot,
2238 gfp_t gfp, size_t *mapped)
2240 const struct iommu_domain_ops *ops = domain->ops;
2241 size_t pgsize, count;
2244 pgsize = iommu_pgsize(domain, iova, paddr, size, &count);
2246 pr_debug("mapping: iova 0x%lx pa %pa pgsize 0x%zx count %zu\n",
2247 iova, &paddr, pgsize, count);
2249 if (ops->map_pages) {
2250 ret = ops->map_pages(domain, iova, paddr, pgsize, count, prot,
2253 ret = ops->map(domain, iova, paddr, pgsize, prot, gfp);
2254 *mapped = ret ? 0 : pgsize;
2260 static int __iommu_map(struct iommu_domain *domain, unsigned long iova,
2261 phys_addr_t paddr, size_t size, int prot, gfp_t gfp)
2263 const struct iommu_domain_ops *ops = domain->ops;
2264 unsigned long orig_iova = iova;
2265 unsigned int min_pagesz;
2266 size_t orig_size = size;
2267 phys_addr_t orig_paddr = paddr;
2270 if (unlikely(!(ops->map || ops->map_pages) ||
2271 domain->pgsize_bitmap == 0UL))
2274 if (unlikely(!(domain->type & __IOMMU_DOMAIN_PAGING)))
2277 /* find out the minimum page size supported */
2278 min_pagesz = 1 << __ffs(domain->pgsize_bitmap);
2281 * both the virtual address and the physical one, as well as
2282 * the size of the mapping, must be aligned (at least) to the
2283 * size of the smallest page supported by the hardware
2285 if (!IS_ALIGNED(iova | paddr | size, min_pagesz)) {
2286 pr_err("unaligned: iova 0x%lx pa %pa size 0x%zx min_pagesz 0x%x\n",
2287 iova, &paddr, size, min_pagesz);
2291 pr_debug("map: iova 0x%lx pa %pa size 0x%zx\n", iova, &paddr, size);
2296 ret = __iommu_map_pages(domain, iova, paddr, size, prot, gfp,
2299 * Some pages may have been mapped, even if an error occurred,
2300 * so we should account for those so they can be unmapped.
2311 /* unroll mapping in case something went wrong */
2313 iommu_unmap(domain, orig_iova, orig_size - size);
2315 trace_map(orig_iova, orig_paddr, orig_size);
2320 static int _iommu_map(struct iommu_domain *domain, unsigned long iova,
2321 phys_addr_t paddr, size_t size, int prot, gfp_t gfp)
2323 const struct iommu_domain_ops *ops = domain->ops;
2326 ret = __iommu_map(domain, iova, paddr, size, prot, gfp);
2327 if (ret == 0 && ops->iotlb_sync_map)
2328 ops->iotlb_sync_map(domain, iova, size);
2333 int iommu_map(struct iommu_domain *domain, unsigned long iova,
2334 phys_addr_t paddr, size_t size, int prot)
2337 return _iommu_map(domain, iova, paddr, size, prot, GFP_KERNEL);
2339 EXPORT_SYMBOL_GPL(iommu_map);
2341 int iommu_map_atomic(struct iommu_domain *domain, unsigned long iova,
2342 phys_addr_t paddr, size_t size, int prot)
2344 return _iommu_map(domain, iova, paddr, size, prot, GFP_ATOMIC);
2346 EXPORT_SYMBOL_GPL(iommu_map_atomic);
2348 static size_t __iommu_unmap_pages(struct iommu_domain *domain,
2349 unsigned long iova, size_t size,
2350 struct iommu_iotlb_gather *iotlb_gather)
2352 const struct iommu_domain_ops *ops = domain->ops;
2353 size_t pgsize, count;
2355 pgsize = iommu_pgsize(domain, iova, iova, size, &count);
2356 return ops->unmap_pages ?
2357 ops->unmap_pages(domain, iova, pgsize, count, iotlb_gather) :
2358 ops->unmap(domain, iova, pgsize, iotlb_gather);
2361 static size_t __iommu_unmap(struct iommu_domain *domain,
2362 unsigned long iova, size_t size,
2363 struct iommu_iotlb_gather *iotlb_gather)
2365 const struct iommu_domain_ops *ops = domain->ops;
2366 size_t unmapped_page, unmapped = 0;
2367 unsigned long orig_iova = iova;
2368 unsigned int min_pagesz;
2370 if (unlikely(!(ops->unmap || ops->unmap_pages) ||
2371 domain->pgsize_bitmap == 0UL))
2374 if (unlikely(!(domain->type & __IOMMU_DOMAIN_PAGING)))
2377 /* find out the minimum page size supported */
2378 min_pagesz = 1 << __ffs(domain->pgsize_bitmap);
2381 * The virtual address, as well as the size of the mapping, must be
2382 * aligned (at least) to the size of the smallest page supported
2385 if (!IS_ALIGNED(iova | size, min_pagesz)) {
2386 pr_err("unaligned: iova 0x%lx size 0x%zx min_pagesz 0x%x\n",
2387 iova, size, min_pagesz);
2391 pr_debug("unmap this: iova 0x%lx size 0x%zx\n", iova, size);
2394 * Keep iterating until we either unmap 'size' bytes (or more)
2395 * or we hit an area that isn't mapped.
2397 while (unmapped < size) {
2398 unmapped_page = __iommu_unmap_pages(domain, iova,
2404 pr_debug("unmapped: iova 0x%lx size 0x%zx\n",
2405 iova, unmapped_page);
2407 iova += unmapped_page;
2408 unmapped += unmapped_page;
2411 trace_unmap(orig_iova, size, unmapped);
2415 size_t iommu_unmap(struct iommu_domain *domain,
2416 unsigned long iova, size_t size)
2418 struct iommu_iotlb_gather iotlb_gather;
2421 iommu_iotlb_gather_init(&iotlb_gather);
2422 ret = __iommu_unmap(domain, iova, size, &iotlb_gather);
2423 iommu_iotlb_sync(domain, &iotlb_gather);
2427 EXPORT_SYMBOL_GPL(iommu_unmap);
2429 size_t iommu_unmap_fast(struct iommu_domain *domain,
2430 unsigned long iova, size_t size,
2431 struct iommu_iotlb_gather *iotlb_gather)
2433 return __iommu_unmap(domain, iova, size, iotlb_gather);
2435 EXPORT_SYMBOL_GPL(iommu_unmap_fast);
2437 static ssize_t __iommu_map_sg(struct iommu_domain *domain, unsigned long iova,
2438 struct scatterlist *sg, unsigned int nents, int prot,
2441 const struct iommu_domain_ops *ops = domain->ops;
2442 size_t len = 0, mapped = 0;
2447 while (i <= nents) {
2448 phys_addr_t s_phys = sg_phys(sg);
2450 if (len && s_phys != start + len) {
2451 ret = __iommu_map(domain, iova + mapped, start,
2472 if (ops->iotlb_sync_map)
2473 ops->iotlb_sync_map(domain, iova, mapped);
2477 /* undo mappings already done */
2478 iommu_unmap(domain, iova, mapped);
2483 ssize_t iommu_map_sg(struct iommu_domain *domain, unsigned long iova,
2484 struct scatterlist *sg, unsigned int nents, int prot)
2487 return __iommu_map_sg(domain, iova, sg, nents, prot, GFP_KERNEL);
2489 EXPORT_SYMBOL_GPL(iommu_map_sg);
2491 ssize_t iommu_map_sg_atomic(struct iommu_domain *domain, unsigned long iova,
2492 struct scatterlist *sg, unsigned int nents, int prot)
2494 return __iommu_map_sg(domain, iova, sg, nents, prot, GFP_ATOMIC);
2498 * report_iommu_fault() - report about an IOMMU fault to the IOMMU framework
2499 * @domain: the iommu domain where the fault has happened
2500 * @dev: the device where the fault has happened
2501 * @iova: the faulting address
2502 * @flags: mmu fault flags (e.g. IOMMU_FAULT_READ/IOMMU_FAULT_WRITE/...)
2504 * This function should be called by the low-level IOMMU implementations
2505 * whenever IOMMU faults happen, to allow high-level users, that are
2506 * interested in such events, to know about them.
2508 * This event may be useful for several possible use cases:
2509 * - mere logging of the event
2510 * - dynamic TLB/PTE loading
2511 * - if restarting of the faulting device is required
2513 * Returns 0 on success and an appropriate error code otherwise (if dynamic
2514 * PTE/TLB loading will one day be supported, implementations will be able
2515 * to tell whether it succeeded or not according to this return value).
2517 * Specifically, -ENOSYS is returned if a fault handler isn't installed
2518 * (though fault handlers can also return -ENOSYS, in case they want to
2519 * elicit the default behavior of the IOMMU drivers).
2521 int report_iommu_fault(struct iommu_domain *domain, struct device *dev,
2522 unsigned long iova, int flags)
2527 * if upper layers showed interest and installed a fault handler,
2530 if (domain->handler)
2531 ret = domain->handler(domain, dev, iova, flags,
2532 domain->handler_token);
2534 trace_io_page_fault(dev, iova, flags);
2537 EXPORT_SYMBOL_GPL(report_iommu_fault);
2539 static int __init iommu_init(void)
2541 iommu_group_kset = kset_create_and_add("iommu_groups",
2543 BUG_ON(!iommu_group_kset);
2545 iommu_debugfs_setup();
2549 core_initcall(iommu_init);
2551 int iommu_enable_nesting(struct iommu_domain *domain)
2553 if (domain->type != IOMMU_DOMAIN_UNMANAGED)
2555 if (!domain->ops->enable_nesting)
2557 return domain->ops->enable_nesting(domain);
2559 EXPORT_SYMBOL_GPL(iommu_enable_nesting);
2561 int iommu_set_pgtable_quirks(struct iommu_domain *domain,
2562 unsigned long quirk)
2564 if (domain->type != IOMMU_DOMAIN_UNMANAGED)
2566 if (!domain->ops->set_pgtable_quirks)
2568 return domain->ops->set_pgtable_quirks(domain, quirk);
2570 EXPORT_SYMBOL_GPL(iommu_set_pgtable_quirks);
2572 void iommu_get_resv_regions(struct device *dev, struct list_head *list)
2574 const struct iommu_ops *ops = dev_iommu_ops(dev);
2576 if (ops->get_resv_regions)
2577 ops->get_resv_regions(dev, list);
2580 void iommu_put_resv_regions(struct device *dev, struct list_head *list)
2582 const struct iommu_ops *ops = dev_iommu_ops(dev);
2584 if (ops->put_resv_regions)
2585 ops->put_resv_regions(dev, list);
2589 * generic_iommu_put_resv_regions - Reserved region driver helper
2590 * @dev: device for which to free reserved regions
2591 * @list: reserved region list for device
2593 * IOMMU drivers can use this to implement their .put_resv_regions() callback
2594 * for simple reservations. If a per region callback is provided that will be
2595 * used to free all memory allocations associated with the reserved region or
2596 * else just free up the memory for the regions. If an IOMMU driver allocates
2597 * additional resources per region, it is going to have to implement a custom
2600 void generic_iommu_put_resv_regions(struct device *dev, struct list_head *list)
2602 struct iommu_resv_region *entry, *next;
2604 list_for_each_entry_safe(entry, next, list, list) {
2606 entry->free(dev, entry);
2611 EXPORT_SYMBOL(generic_iommu_put_resv_regions);
2613 struct iommu_resv_region *iommu_alloc_resv_region(phys_addr_t start,
2614 size_t length, int prot,
2615 enum iommu_resv_type type)
2617 struct iommu_resv_region *region;
2619 region = kzalloc(sizeof(*region), GFP_KERNEL);
2623 INIT_LIST_HEAD(®ion->list);
2624 region->start = start;
2625 region->length = length;
2626 region->prot = prot;
2627 region->type = type;
2630 EXPORT_SYMBOL_GPL(iommu_alloc_resv_region);
2632 void iommu_set_default_passthrough(bool cmd_line)
2635 iommu_cmd_line |= IOMMU_CMD_LINE_DMA_API;
2636 iommu_def_domain_type = IOMMU_DOMAIN_IDENTITY;
2639 void iommu_set_default_translated(bool cmd_line)
2642 iommu_cmd_line |= IOMMU_CMD_LINE_DMA_API;
2643 iommu_def_domain_type = IOMMU_DOMAIN_DMA;
2646 bool iommu_default_passthrough(void)
2648 return iommu_def_domain_type == IOMMU_DOMAIN_IDENTITY;
2650 EXPORT_SYMBOL_GPL(iommu_default_passthrough);
2652 const struct iommu_ops *iommu_ops_from_fwnode(struct fwnode_handle *fwnode)
2654 const struct iommu_ops *ops = NULL;
2655 struct iommu_device *iommu;
2657 spin_lock(&iommu_device_lock);
2658 list_for_each_entry(iommu, &iommu_device_list, list)
2659 if (iommu->fwnode == fwnode) {
2663 spin_unlock(&iommu_device_lock);
2667 int iommu_fwspec_init(struct device *dev, struct fwnode_handle *iommu_fwnode,
2668 const struct iommu_ops *ops)
2670 struct iommu_fwspec *fwspec = dev_iommu_fwspec_get(dev);
2673 return ops == fwspec->ops ? 0 : -EINVAL;
2675 if (!dev_iommu_get(dev))
2678 /* Preallocate for the overwhelmingly common case of 1 ID */
2679 fwspec = kzalloc(struct_size(fwspec, ids, 1), GFP_KERNEL);
2683 of_node_get(to_of_node(iommu_fwnode));
2684 fwspec->iommu_fwnode = iommu_fwnode;
2686 dev_iommu_fwspec_set(dev, fwspec);
2689 EXPORT_SYMBOL_GPL(iommu_fwspec_init);
2691 void iommu_fwspec_free(struct device *dev)
2693 struct iommu_fwspec *fwspec = dev_iommu_fwspec_get(dev);
2696 fwnode_handle_put(fwspec->iommu_fwnode);
2698 dev_iommu_fwspec_set(dev, NULL);
2701 EXPORT_SYMBOL_GPL(iommu_fwspec_free);
2703 int iommu_fwspec_add_ids(struct device *dev, u32 *ids, int num_ids)
2705 struct iommu_fwspec *fwspec = dev_iommu_fwspec_get(dev);
2711 new_num = fwspec->num_ids + num_ids;
2713 fwspec = krealloc(fwspec, struct_size(fwspec, ids, new_num),
2718 dev_iommu_fwspec_set(dev, fwspec);
2721 for (i = 0; i < num_ids; i++)
2722 fwspec->ids[fwspec->num_ids + i] = ids[i];
2724 fwspec->num_ids = new_num;
2727 EXPORT_SYMBOL_GPL(iommu_fwspec_add_ids);
2730 * Per device IOMMU features.
2732 int iommu_dev_enable_feature(struct device *dev, enum iommu_dev_features feat)
2734 if (dev->iommu && dev->iommu->iommu_dev) {
2735 const struct iommu_ops *ops = dev->iommu->iommu_dev->ops;
2737 if (ops->dev_enable_feat)
2738 return ops->dev_enable_feat(dev, feat);
2743 EXPORT_SYMBOL_GPL(iommu_dev_enable_feature);
2746 * The device drivers should do the necessary cleanups before calling this.
2748 int iommu_dev_disable_feature(struct device *dev, enum iommu_dev_features feat)
2750 if (dev->iommu && dev->iommu->iommu_dev) {
2751 const struct iommu_ops *ops = dev->iommu->iommu_dev->ops;
2753 if (ops->dev_disable_feat)
2754 return ops->dev_disable_feat(dev, feat);
2759 EXPORT_SYMBOL_GPL(iommu_dev_disable_feature);
2761 bool iommu_dev_feature_enabled(struct device *dev, enum iommu_dev_features feat)
2763 if (dev->iommu && dev->iommu->iommu_dev) {
2764 const struct iommu_ops *ops = dev->iommu->iommu_dev->ops;
2766 if (ops->dev_feat_enabled)
2767 return ops->dev_feat_enabled(dev, feat);
2772 EXPORT_SYMBOL_GPL(iommu_dev_feature_enabled);
2775 * iommu_sva_bind_device() - Bind a process address space to a device
2777 * @mm: the mm to bind, caller must hold a reference to it
2778 * @drvdata: opaque data pointer to pass to bind callback
2780 * Create a bond between device and address space, allowing the device to access
2781 * the mm using the returned PASID. If a bond already exists between @device and
2782 * @mm, it is returned and an additional reference is taken. Caller must call
2783 * iommu_sva_unbind_device() to release each reference.
2785 * iommu_dev_enable_feature(dev, IOMMU_DEV_FEAT_SVA) must be called first, to
2786 * initialize the required SVA features.
2788 * On error, returns an ERR_PTR value.
2791 iommu_sva_bind_device(struct device *dev, struct mm_struct *mm, void *drvdata)
2793 struct iommu_group *group;
2794 struct iommu_sva *handle = ERR_PTR(-EINVAL);
2795 const struct iommu_ops *ops = dev_iommu_ops(dev);
2798 return ERR_PTR(-ENODEV);
2800 group = iommu_group_get(dev);
2802 return ERR_PTR(-ENODEV);
2804 /* Ensure device count and domain don't change while we're binding */
2805 mutex_lock(&group->mutex);
2808 * To keep things simple, SVA currently doesn't support IOMMU groups
2809 * with more than one device. Existing SVA-capable systems are not
2810 * affected by the problems that required IOMMU groups (lack of ACS
2811 * isolation, device ID aliasing and other hardware issues).
2813 if (iommu_group_device_count(group) != 1)
2816 handle = ops->sva_bind(dev, mm, drvdata);
2819 mutex_unlock(&group->mutex);
2820 iommu_group_put(group);
2824 EXPORT_SYMBOL_GPL(iommu_sva_bind_device);
2827 * iommu_sva_unbind_device() - Remove a bond created with iommu_sva_bind_device
2828 * @handle: the handle returned by iommu_sva_bind_device()
2830 * Put reference to a bond between device and address space. The device should
2831 * not be issuing any more transaction for this PASID. All outstanding page
2832 * requests for this PASID must have been flushed to the IOMMU.
2834 void iommu_sva_unbind_device(struct iommu_sva *handle)
2836 struct iommu_group *group;
2837 struct device *dev = handle->dev;
2838 const struct iommu_ops *ops = dev_iommu_ops(dev);
2840 if (!ops->sva_unbind)
2843 group = iommu_group_get(dev);
2847 mutex_lock(&group->mutex);
2848 ops->sva_unbind(handle);
2849 mutex_unlock(&group->mutex);
2851 iommu_group_put(group);
2853 EXPORT_SYMBOL_GPL(iommu_sva_unbind_device);
2855 u32 iommu_sva_get_pasid(struct iommu_sva *handle)
2857 const struct iommu_ops *ops = dev_iommu_ops(handle->dev);
2859 if (!ops->sva_get_pasid)
2860 return IOMMU_PASID_INVALID;
2862 return ops->sva_get_pasid(handle);
2864 EXPORT_SYMBOL_GPL(iommu_sva_get_pasid);
2867 * Changes the default domain of an iommu group that has *only* one device
2869 * @group: The group for which the default domain should be changed
2870 * @prev_dev: The device in the group (this is used to make sure that the device
2871 * hasn't changed after the caller has called this function)
2872 * @type: The type of the new default domain that gets associated with the group
2874 * Returns 0 on success and error code on failure
2877 * 1. Presently, this function is called only when user requests to change the
2878 * group's default domain type through /sys/kernel/iommu_groups/<grp_id>/type
2879 * Please take a closer look if intended to use for other purposes.
2881 static int iommu_change_dev_def_domain(struct iommu_group *group,
2882 struct device *prev_dev, int type)
2884 struct iommu_domain *prev_dom;
2885 struct group_device *grp_dev;
2886 int ret, dev_def_dom;
2889 mutex_lock(&group->mutex);
2891 if (group->default_domain != group->domain) {
2892 dev_err_ratelimited(prev_dev, "Group not assigned to default domain\n");
2898 * iommu group wasn't locked while acquiring device lock in
2899 * iommu_group_store_type(). So, make sure that the device count hasn't
2900 * changed while acquiring device lock.
2902 * Changing default domain of an iommu group with two or more devices
2903 * isn't supported because there could be a potential deadlock. Consider
2904 * the following scenario. T1 is trying to acquire device locks of all
2905 * the devices in the group and before it could acquire all of them,
2906 * there could be another thread T2 (from different sub-system and use
2907 * case) that has already acquired some of the device locks and might be
2908 * waiting for T1 to release other device locks.
2910 if (iommu_group_device_count(group) != 1) {
2911 dev_err_ratelimited(prev_dev, "Cannot change default domain: Group has more than one device\n");
2916 /* Since group has only one device */
2917 grp_dev = list_first_entry(&group->devices, struct group_device, list);
2920 if (prev_dev != dev) {
2921 dev_err_ratelimited(prev_dev, "Cannot change default domain: Device has been changed\n");
2926 prev_dom = group->default_domain;
2932 dev_def_dom = iommu_get_def_domain_type(dev);
2935 * If the user hasn't requested any specific type of domain and
2936 * if the device supports both the domains, then default to the
2937 * domain the device was booted with
2939 type = dev_def_dom ? : iommu_def_domain_type;
2940 } else if (dev_def_dom && type != dev_def_dom) {
2941 dev_err_ratelimited(prev_dev, "Device cannot be in %s domain\n",
2942 iommu_domain_type_str(type));
2948 * Switch to a new domain only if the requested domain type is different
2949 * from the existing default domain type
2951 if (prev_dom->type == type) {
2956 /* We can bring up a flush queue without tearing down the domain */
2957 if (type == IOMMU_DOMAIN_DMA_FQ && prev_dom->type == IOMMU_DOMAIN_DMA) {
2958 ret = iommu_dma_init_fq(prev_dom);
2960 prev_dom->type = IOMMU_DOMAIN_DMA_FQ;
2964 /* Sets group->default_domain to the newly allocated domain */
2965 ret = iommu_group_alloc_default_domain(dev->bus, group, type);
2969 ret = iommu_create_device_direct_mappings(group, dev);
2971 goto free_new_domain;
2973 ret = __iommu_attach_device(group->default_domain, dev);
2975 goto free_new_domain;
2977 group->domain = group->default_domain;
2980 * Release the mutex here because ops->probe_finalize() call-back of
2981 * some vendor IOMMU drivers calls arm_iommu_attach_device() which
2982 * in-turn might call back into IOMMU core code, where it tries to take
2983 * group->mutex, resulting in a deadlock.
2985 mutex_unlock(&group->mutex);
2987 /* Make sure dma_ops is appropriatley set */
2988 iommu_group_do_probe_finalize(dev, group->default_domain);
2989 iommu_domain_free(prev_dom);
2993 iommu_domain_free(group->default_domain);
2994 group->default_domain = prev_dom;
2995 group->domain = prev_dom;
2998 mutex_unlock(&group->mutex);
3004 * Changing the default domain through sysfs requires the users to unbind the
3005 * drivers from the devices in the iommu group, except for a DMA -> DMA-FQ
3006 * transition. Return failure if this isn't met.
3008 * We need to consider the race between this and the device release path.
3009 * device_lock(dev) is used here to guarantee that the device release path
3010 * will not be entered at the same time.
3012 static ssize_t iommu_group_store_type(struct iommu_group *group,
3013 const char *buf, size_t count)
3015 struct group_device *grp_dev;
3019 if (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO))
3022 if (WARN_ON(!group) || !group->default_domain)
3025 if (sysfs_streq(buf, "identity"))
3026 req_type = IOMMU_DOMAIN_IDENTITY;
3027 else if (sysfs_streq(buf, "DMA"))
3028 req_type = IOMMU_DOMAIN_DMA;
3029 else if (sysfs_streq(buf, "DMA-FQ"))
3030 req_type = IOMMU_DOMAIN_DMA_FQ;
3031 else if (sysfs_streq(buf, "auto"))
3037 * Lock/Unlock the group mutex here before device lock to
3038 * 1. Make sure that the iommu group has only one device (this is a
3039 * prerequisite for step 2)
3040 * 2. Get struct *dev which is needed to lock device
3042 mutex_lock(&group->mutex);
3043 if (iommu_group_device_count(group) != 1) {
3044 mutex_unlock(&group->mutex);
3045 pr_err_ratelimited("Cannot change default domain: Group has more than one device\n");
3049 /* Since group has only one device */
3050 grp_dev = list_first_entry(&group->devices, struct group_device, list);
3055 * Don't hold the group mutex because taking group mutex first and then
3056 * the device lock could potentially cause a deadlock as below. Assume
3057 * two threads T1 and T2. T1 is trying to change default domain of an
3058 * iommu group and T2 is trying to hot unplug a device or release [1] VF
3059 * of a PCIe device which is in the same iommu group. T1 takes group
3060 * mutex and before it could take device lock assume T2 has taken device
3061 * lock and is yet to take group mutex. Now, both the threads will be
3062 * waiting for the other thread to release lock. Below, lock order was
3065 * mutex_lock(&group->mutex);
3066 * iommu_change_dev_def_domain();
3067 * mutex_unlock(&group->mutex);
3068 * device_unlock(dev);
3070 * [1] Typical device release path
3071 * device_lock() from device/driver core code
3073 * -> iommu_bus_notifier()
3074 * -> iommu_release_device()
3075 * -> ops->release_device() vendor driver calls back iommu core code
3076 * -> mutex_lock() from iommu core code
3078 mutex_unlock(&group->mutex);
3080 /* Check if the device in the group still has a driver bound to it */
3082 if (device_is_bound(dev) && !(req_type == IOMMU_DOMAIN_DMA_FQ &&
3083 group->default_domain->type == IOMMU_DOMAIN_DMA)) {
3084 pr_err_ratelimited("Device is still bound to driver\n");
3089 ret = iommu_change_dev_def_domain(group, dev, req_type);
3100 * iommu_device_use_default_domain() - Device driver wants to handle device
3101 * DMA through the kernel DMA API.
3104 * The device driver about to bind @dev wants to do DMA through the kernel
3105 * DMA API. Return 0 if it is allowed, otherwise an error.
3107 int iommu_device_use_default_domain(struct device *dev)
3109 struct iommu_group *group = iommu_group_get(dev);
3115 mutex_lock(&group->mutex);
3116 if (group->owner_cnt) {
3117 if (group->domain != group->default_domain ||
3127 mutex_unlock(&group->mutex);
3128 iommu_group_put(group);
3134 * iommu_device_unuse_default_domain() - Device driver stops handling device
3135 * DMA through the kernel DMA API.
3138 * The device driver doesn't want to do DMA through kernel DMA API anymore.
3139 * It must be called after iommu_device_use_default_domain().
3141 void iommu_device_unuse_default_domain(struct device *dev)
3143 struct iommu_group *group = iommu_group_get(dev);
3148 mutex_lock(&group->mutex);
3149 if (!WARN_ON(!group->owner_cnt))
3152 mutex_unlock(&group->mutex);
3153 iommu_group_put(group);
3156 static int __iommu_group_alloc_blocking_domain(struct iommu_group *group)
3158 struct group_device *dev =
3159 list_first_entry(&group->devices, struct group_device, list);
3161 if (group->blocking_domain)
3164 group->blocking_domain =
3165 __iommu_domain_alloc(dev->dev->bus, IOMMU_DOMAIN_BLOCKED);
3166 if (!group->blocking_domain) {
3168 * For drivers that do not yet understand IOMMU_DOMAIN_BLOCKED
3169 * create an empty domain instead.
3171 group->blocking_domain = __iommu_domain_alloc(
3172 dev->dev->bus, IOMMU_DOMAIN_UNMANAGED);
3173 if (!group->blocking_domain)
3180 * iommu_group_claim_dma_owner() - Set DMA ownership of a group
3181 * @group: The group.
3182 * @owner: Caller specified pointer. Used for exclusive ownership.
3184 * This is to support backward compatibility for vfio which manages
3185 * the dma ownership in iommu_group level. New invocations on this
3186 * interface should be prohibited.
3188 int iommu_group_claim_dma_owner(struct iommu_group *group, void *owner)
3192 mutex_lock(&group->mutex);
3193 if (group->owner_cnt) {
3197 if (group->domain && group->domain != group->default_domain) {
3202 ret = __iommu_group_alloc_blocking_domain(group);
3206 ret = __iommu_group_set_domain(group, group->blocking_domain);
3209 group->owner = owner;
3214 mutex_unlock(&group->mutex);
3218 EXPORT_SYMBOL_GPL(iommu_group_claim_dma_owner);
3221 * iommu_group_release_dma_owner() - Release DMA ownership of a group
3222 * @group: The group.
3224 * Release the DMA ownership claimed by iommu_group_claim_dma_owner().
3226 void iommu_group_release_dma_owner(struct iommu_group *group)
3230 mutex_lock(&group->mutex);
3231 if (WARN_ON(!group->owner_cnt || !group->owner))
3234 group->owner_cnt = 0;
3235 group->owner = NULL;
3236 ret = __iommu_group_set_domain(group, group->default_domain);
3237 WARN(ret, "iommu driver failed to attach the default domain");
3240 mutex_unlock(&group->mutex);
3242 EXPORT_SYMBOL_GPL(iommu_group_release_dma_owner);
3245 * iommu_group_dma_owner_claimed() - Query group dma ownership status
3246 * @group: The group.
3248 * This provides status query on a given group. It is racy and only for
3249 * non-binding status reporting.
3251 bool iommu_group_dma_owner_claimed(struct iommu_group *group)
3255 mutex_lock(&group->mutex);
3256 user = group->owner_cnt;
3257 mutex_unlock(&group->mutex);
3261 EXPORT_SYMBOL_GPL(iommu_group_dma_owner_claimed);