1 // SPDX-License-Identifier: GPL-2.0-only
3 * Copyright (C) 2007-2008 Advanced Micro Devices, Inc.
4 * Author: Joerg Roedel <jroedel@suse.de>
7 #define pr_fmt(fmt) "iommu: " fmt
9 #include <linux/amba/bus.h>
10 #include <linux/device.h>
11 #include <linux/kernel.h>
12 #include <linux/bits.h>
13 #include <linux/bug.h>
14 #include <linux/types.h>
15 #include <linux/init.h>
16 #include <linux/export.h>
17 #include <linux/slab.h>
18 #include <linux/errno.h>
19 #include <linux/host1x_context_bus.h>
20 #include <linux/iommu.h>
21 #include <linux/idr.h>
22 #include <linux/err.h>
23 #include <linux/pci.h>
24 #include <linux/bitops.h>
25 #include <linux/platform_device.h>
26 #include <linux/property.h>
27 #include <linux/fsl/mc.h>
28 #include <linux/module.h>
29 #include <linux/cc_platform.h>
30 #include <trace/events/iommu.h>
32 #include "dma-iommu.h"
34 static struct kset *iommu_group_kset;
35 static DEFINE_IDA(iommu_group_ida);
37 static unsigned int iommu_def_domain_type __read_mostly;
38 static bool iommu_dma_strict __read_mostly = IS_ENABLED(CONFIG_IOMMU_DEFAULT_DMA_STRICT);
39 static u32 iommu_cmd_line __read_mostly;
43 struct kobject *devices_kobj;
44 struct list_head devices;
47 void (*iommu_data_release)(void *iommu_data);
50 struct iommu_domain *default_domain;
51 struct iommu_domain *blocking_domain;
52 struct iommu_domain *domain;
53 struct list_head entry;
54 unsigned int owner_cnt;
59 struct list_head list;
64 struct iommu_group_attribute {
65 struct attribute attr;
66 ssize_t (*show)(struct iommu_group *group, char *buf);
67 ssize_t (*store)(struct iommu_group *group,
68 const char *buf, size_t count);
71 static const char * const iommu_group_resv_type_string[] = {
72 [IOMMU_RESV_DIRECT] = "direct",
73 [IOMMU_RESV_DIRECT_RELAXABLE] = "direct-relaxable",
74 [IOMMU_RESV_RESERVED] = "reserved",
75 [IOMMU_RESV_MSI] = "msi",
76 [IOMMU_RESV_SW_MSI] = "msi",
79 #define IOMMU_CMD_LINE_DMA_API BIT(0)
80 #define IOMMU_CMD_LINE_STRICT BIT(1)
82 static int iommu_bus_notifier(struct notifier_block *nb,
83 unsigned long action, void *data);
84 static int iommu_alloc_default_domain(struct iommu_group *group,
86 static struct iommu_domain *__iommu_domain_alloc(struct bus_type *bus,
88 static int __iommu_attach_device(struct iommu_domain *domain,
90 static int __iommu_attach_group(struct iommu_domain *domain,
91 struct iommu_group *group);
92 static int __iommu_group_set_domain(struct iommu_group *group,
93 struct iommu_domain *new_domain);
94 static int iommu_create_device_direct_mappings(struct iommu_group *group,
96 static struct iommu_group *iommu_group_get_for_dev(struct device *dev);
97 static ssize_t iommu_group_store_type(struct iommu_group *group,
98 const char *buf, size_t count);
100 #define IOMMU_GROUP_ATTR(_name, _mode, _show, _store) \
101 struct iommu_group_attribute iommu_group_attr_##_name = \
102 __ATTR(_name, _mode, _show, _store)
104 #define to_iommu_group_attr(_attr) \
105 container_of(_attr, struct iommu_group_attribute, attr)
106 #define to_iommu_group(_kobj) \
107 container_of(_kobj, struct iommu_group, kobj)
109 static LIST_HEAD(iommu_device_list);
110 static DEFINE_SPINLOCK(iommu_device_lock);
112 static struct bus_type * const iommu_buses[] = {
117 #ifdef CONFIG_ARM_AMBA
120 #ifdef CONFIG_FSL_MC_BUS
123 #ifdef CONFIG_TEGRA_HOST1X_CONTEXT_BUS
124 &host1x_context_device_bus_type,
129 * Use a function instead of an array here because the domain-type is a
130 * bit-field, so an array would waste memory.
132 static const char *iommu_domain_type_str(unsigned int t)
135 case IOMMU_DOMAIN_BLOCKED:
137 case IOMMU_DOMAIN_IDENTITY:
138 return "Passthrough";
139 case IOMMU_DOMAIN_UNMANAGED:
141 case IOMMU_DOMAIN_DMA:
142 case IOMMU_DOMAIN_DMA_FQ:
149 static int __init iommu_subsys_init(void)
151 struct notifier_block *nb;
153 if (!(iommu_cmd_line & IOMMU_CMD_LINE_DMA_API)) {
154 if (IS_ENABLED(CONFIG_IOMMU_DEFAULT_PASSTHROUGH))
155 iommu_set_default_passthrough(false);
157 iommu_set_default_translated(false);
159 if (iommu_default_passthrough() && cc_platform_has(CC_ATTR_MEM_ENCRYPT)) {
160 pr_info("Memory encryption detected - Disabling default IOMMU Passthrough\n");
161 iommu_set_default_translated(false);
165 if (!iommu_default_passthrough() && !iommu_dma_strict)
166 iommu_def_domain_type = IOMMU_DOMAIN_DMA_FQ;
168 pr_info("Default domain type: %s %s\n",
169 iommu_domain_type_str(iommu_def_domain_type),
170 (iommu_cmd_line & IOMMU_CMD_LINE_DMA_API) ?
171 "(set via kernel command line)" : "");
173 if (!iommu_default_passthrough())
174 pr_info("DMA domain TLB invalidation policy: %s mode %s\n",
175 iommu_dma_strict ? "strict" : "lazy",
176 (iommu_cmd_line & IOMMU_CMD_LINE_STRICT) ?
177 "(set via kernel command line)" : "");
179 nb = kcalloc(ARRAY_SIZE(iommu_buses), sizeof(*nb), GFP_KERNEL);
183 for (int i = 0; i < ARRAY_SIZE(iommu_buses); i++) {
184 nb[i].notifier_call = iommu_bus_notifier;
185 bus_register_notifier(iommu_buses[i], &nb[i]);
190 subsys_initcall(iommu_subsys_init);
192 static int remove_iommu_group(struct device *dev, void *data)
194 if (dev->iommu && dev->iommu->iommu_dev == data)
195 iommu_release_device(dev);
201 * iommu_device_register() - Register an IOMMU hardware instance
202 * @iommu: IOMMU handle for the instance
203 * @ops: IOMMU ops to associate with the instance
204 * @hwdev: (optional) actual instance device, used for fwnode lookup
206 * Return: 0 on success, or an error.
208 int iommu_device_register(struct iommu_device *iommu,
209 const struct iommu_ops *ops, struct device *hwdev)
213 /* We need to be able to take module references appropriately */
214 if (WARN_ON(is_module_address((unsigned long)ops) && !ops->owner))
217 * Temporarily enforce global restriction to a single driver. This was
218 * already the de-facto behaviour, since any possible combination of
219 * existing drivers would compete for at least the PCI or platform bus.
221 if (iommu_buses[0]->iommu_ops && iommu_buses[0]->iommu_ops != ops)
226 iommu->fwnode = dev_fwnode(hwdev);
228 spin_lock(&iommu_device_lock);
229 list_add_tail(&iommu->list, &iommu_device_list);
230 spin_unlock(&iommu_device_lock);
232 for (int i = 0; i < ARRAY_SIZE(iommu_buses) && !err; i++) {
233 iommu_buses[i]->iommu_ops = ops;
234 err = bus_iommu_probe(iommu_buses[i]);
237 iommu_device_unregister(iommu);
240 EXPORT_SYMBOL_GPL(iommu_device_register);
242 void iommu_device_unregister(struct iommu_device *iommu)
244 for (int i = 0; i < ARRAY_SIZE(iommu_buses); i++)
245 bus_for_each_dev(iommu_buses[i], NULL, iommu, remove_iommu_group);
247 spin_lock(&iommu_device_lock);
248 list_del(&iommu->list);
249 spin_unlock(&iommu_device_lock);
251 EXPORT_SYMBOL_GPL(iommu_device_unregister);
253 static struct dev_iommu *dev_iommu_get(struct device *dev)
255 struct dev_iommu *param = dev->iommu;
260 param = kzalloc(sizeof(*param), GFP_KERNEL);
264 mutex_init(¶m->lock);
269 static void dev_iommu_free(struct device *dev)
271 struct dev_iommu *param = dev->iommu;
275 fwnode_handle_put(param->fwspec->iommu_fwnode);
276 kfree(param->fwspec);
281 static int __iommu_probe_device(struct device *dev, struct list_head *group_list)
283 const struct iommu_ops *ops = dev->bus->iommu_ops;
284 struct iommu_device *iommu_dev;
285 struct iommu_group *group;
286 static DEFINE_MUTEX(iommu_probe_device_lock);
292 * Serialise to avoid races between IOMMU drivers registering in
293 * parallel and/or the "replay" calls from ACPI/OF code via client
294 * driver probe. Once the latter have been cleaned up we should
295 * probably be able to use device_lock() here to minimise the scope,
296 * but for now enforcing a simple global ordering is fine.
298 mutex_lock(&iommu_probe_device_lock);
299 if (!dev_iommu_get(dev)) {
304 if (!try_module_get(ops->owner)) {
309 iommu_dev = ops->probe_device(dev);
310 if (IS_ERR(iommu_dev)) {
311 ret = PTR_ERR(iommu_dev);
315 dev->iommu->iommu_dev = iommu_dev;
317 group = iommu_group_get_for_dev(dev);
319 ret = PTR_ERR(group);
323 mutex_lock(&group->mutex);
324 if (group_list && !group->default_domain && list_empty(&group->entry))
325 list_add_tail(&group->entry, group_list);
326 mutex_unlock(&group->mutex);
327 iommu_group_put(group);
329 mutex_unlock(&iommu_probe_device_lock);
330 iommu_device_link(iommu_dev, dev);
335 if (ops->release_device)
336 ops->release_device(dev);
339 module_put(ops->owner);
345 mutex_unlock(&iommu_probe_device_lock);
350 int iommu_probe_device(struct device *dev)
352 const struct iommu_ops *ops;
353 struct iommu_group *group;
356 ret = __iommu_probe_device(dev, NULL);
360 group = iommu_group_get(dev);
367 * Try to allocate a default domain - needs support from the
368 * IOMMU driver. There are still some drivers which don't
369 * support default domains, so the return value is not yet
372 mutex_lock(&group->mutex);
373 iommu_alloc_default_domain(group, dev);
376 * If device joined an existing group which has been claimed, don't
377 * attach the default domain.
379 if (group->default_domain && !group->owner) {
380 ret = __iommu_attach_device(group->default_domain, dev);
382 mutex_unlock(&group->mutex);
383 iommu_group_put(group);
388 iommu_create_device_direct_mappings(group, dev);
390 mutex_unlock(&group->mutex);
391 iommu_group_put(group);
393 ops = dev_iommu_ops(dev);
394 if (ops->probe_finalize)
395 ops->probe_finalize(dev);
400 iommu_release_device(dev);
407 void iommu_release_device(struct device *dev)
409 const struct iommu_ops *ops;
414 iommu_device_unlink(dev->iommu->iommu_dev, dev);
416 ops = dev_iommu_ops(dev);
417 if (ops->release_device)
418 ops->release_device(dev);
420 iommu_group_remove_device(dev);
421 module_put(ops->owner);
425 static int __init iommu_set_def_domain_type(char *str)
430 ret = kstrtobool(str, &pt);
435 iommu_set_default_passthrough(true);
437 iommu_set_default_translated(true);
441 early_param("iommu.passthrough", iommu_set_def_domain_type);
443 static int __init iommu_dma_setup(char *str)
445 int ret = kstrtobool(str, &iommu_dma_strict);
448 iommu_cmd_line |= IOMMU_CMD_LINE_STRICT;
451 early_param("iommu.strict", iommu_dma_setup);
453 void iommu_set_dma_strict(void)
455 iommu_dma_strict = true;
456 if (iommu_def_domain_type == IOMMU_DOMAIN_DMA_FQ)
457 iommu_def_domain_type = IOMMU_DOMAIN_DMA;
460 static ssize_t iommu_group_attr_show(struct kobject *kobj,
461 struct attribute *__attr, char *buf)
463 struct iommu_group_attribute *attr = to_iommu_group_attr(__attr);
464 struct iommu_group *group = to_iommu_group(kobj);
468 ret = attr->show(group, buf);
472 static ssize_t iommu_group_attr_store(struct kobject *kobj,
473 struct attribute *__attr,
474 const char *buf, size_t count)
476 struct iommu_group_attribute *attr = to_iommu_group_attr(__attr);
477 struct iommu_group *group = to_iommu_group(kobj);
481 ret = attr->store(group, buf, count);
485 static const struct sysfs_ops iommu_group_sysfs_ops = {
486 .show = iommu_group_attr_show,
487 .store = iommu_group_attr_store,
490 static int iommu_group_create_file(struct iommu_group *group,
491 struct iommu_group_attribute *attr)
493 return sysfs_create_file(&group->kobj, &attr->attr);
496 static void iommu_group_remove_file(struct iommu_group *group,
497 struct iommu_group_attribute *attr)
499 sysfs_remove_file(&group->kobj, &attr->attr);
502 static ssize_t iommu_group_show_name(struct iommu_group *group, char *buf)
504 return sprintf(buf, "%s\n", group->name);
508 * iommu_insert_resv_region - Insert a new region in the
509 * list of reserved regions.
510 * @new: new region to insert
511 * @regions: list of regions
513 * Elements are sorted by start address and overlapping segments
514 * of the same type are merged.
516 static int iommu_insert_resv_region(struct iommu_resv_region *new,
517 struct list_head *regions)
519 struct iommu_resv_region *iter, *tmp, *nr, *top;
522 nr = iommu_alloc_resv_region(new->start, new->length,
523 new->prot, new->type, GFP_KERNEL);
527 /* First add the new element based on start address sorting */
528 list_for_each_entry(iter, regions, list) {
529 if (nr->start < iter->start ||
530 (nr->start == iter->start && nr->type <= iter->type))
533 list_add_tail(&nr->list, &iter->list);
535 /* Merge overlapping segments of type nr->type in @regions, if any */
536 list_for_each_entry_safe(iter, tmp, regions, list) {
537 phys_addr_t top_end, iter_end = iter->start + iter->length - 1;
539 /* no merge needed on elements of different types than @new */
540 if (iter->type != new->type) {
541 list_move_tail(&iter->list, &stack);
545 /* look for the last stack element of same type as @iter */
546 list_for_each_entry_reverse(top, &stack, list)
547 if (top->type == iter->type)
550 list_move_tail(&iter->list, &stack);
554 top_end = top->start + top->length - 1;
556 if (iter->start > top_end + 1) {
557 list_move_tail(&iter->list, &stack);
559 top->length = max(top_end, iter_end) - top->start + 1;
560 list_del(&iter->list);
564 list_splice(&stack, regions);
569 iommu_insert_device_resv_regions(struct list_head *dev_resv_regions,
570 struct list_head *group_resv_regions)
572 struct iommu_resv_region *entry;
575 list_for_each_entry(entry, dev_resv_regions, list) {
576 ret = iommu_insert_resv_region(entry, group_resv_regions);
583 int iommu_get_group_resv_regions(struct iommu_group *group,
584 struct list_head *head)
586 struct group_device *device;
589 mutex_lock(&group->mutex);
590 list_for_each_entry(device, &group->devices, list) {
591 struct list_head dev_resv_regions;
594 * Non-API groups still expose reserved_regions in sysfs,
595 * so filter out calls that get here that way.
597 if (!device->dev->iommu)
600 INIT_LIST_HEAD(&dev_resv_regions);
601 iommu_get_resv_regions(device->dev, &dev_resv_regions);
602 ret = iommu_insert_device_resv_regions(&dev_resv_regions, head);
603 iommu_put_resv_regions(device->dev, &dev_resv_regions);
607 mutex_unlock(&group->mutex);
610 EXPORT_SYMBOL_GPL(iommu_get_group_resv_regions);
612 static ssize_t iommu_group_show_resv_regions(struct iommu_group *group,
615 struct iommu_resv_region *region, *next;
616 struct list_head group_resv_regions;
619 INIT_LIST_HEAD(&group_resv_regions);
620 iommu_get_group_resv_regions(group, &group_resv_regions);
622 list_for_each_entry_safe(region, next, &group_resv_regions, list) {
623 str += sprintf(str, "0x%016llx 0x%016llx %s\n",
624 (long long int)region->start,
625 (long long int)(region->start +
627 iommu_group_resv_type_string[region->type]);
634 static ssize_t iommu_group_show_type(struct iommu_group *group,
637 char *type = "unknown\n";
639 mutex_lock(&group->mutex);
640 if (group->default_domain) {
641 switch (group->default_domain->type) {
642 case IOMMU_DOMAIN_BLOCKED:
645 case IOMMU_DOMAIN_IDENTITY:
648 case IOMMU_DOMAIN_UNMANAGED:
649 type = "unmanaged\n";
651 case IOMMU_DOMAIN_DMA:
654 case IOMMU_DOMAIN_DMA_FQ:
659 mutex_unlock(&group->mutex);
665 static IOMMU_GROUP_ATTR(name, S_IRUGO, iommu_group_show_name, NULL);
667 static IOMMU_GROUP_ATTR(reserved_regions, 0444,
668 iommu_group_show_resv_regions, NULL);
670 static IOMMU_GROUP_ATTR(type, 0644, iommu_group_show_type,
671 iommu_group_store_type);
673 static void iommu_group_release(struct kobject *kobj)
675 struct iommu_group *group = to_iommu_group(kobj);
677 pr_debug("Releasing group %d\n", group->id);
679 if (group->iommu_data_release)
680 group->iommu_data_release(group->iommu_data);
682 ida_free(&iommu_group_ida, group->id);
684 if (group->default_domain)
685 iommu_domain_free(group->default_domain);
686 if (group->blocking_domain)
687 iommu_domain_free(group->blocking_domain);
693 static struct kobj_type iommu_group_ktype = {
694 .sysfs_ops = &iommu_group_sysfs_ops,
695 .release = iommu_group_release,
699 * iommu_group_alloc - Allocate a new group
701 * This function is called by an iommu driver to allocate a new iommu
702 * group. The iommu group represents the minimum granularity of the iommu.
703 * Upon successful return, the caller holds a reference to the supplied
704 * group in order to hold the group until devices are added. Use
705 * iommu_group_put() to release this extra reference count, allowing the
706 * group to be automatically reclaimed once it has no devices or external
709 struct iommu_group *iommu_group_alloc(void)
711 struct iommu_group *group;
714 group = kzalloc(sizeof(*group), GFP_KERNEL);
716 return ERR_PTR(-ENOMEM);
718 group->kobj.kset = iommu_group_kset;
719 mutex_init(&group->mutex);
720 INIT_LIST_HEAD(&group->devices);
721 INIT_LIST_HEAD(&group->entry);
723 ret = ida_alloc(&iommu_group_ida, GFP_KERNEL);
730 ret = kobject_init_and_add(&group->kobj, &iommu_group_ktype,
731 NULL, "%d", group->id);
733 kobject_put(&group->kobj);
737 group->devices_kobj = kobject_create_and_add("devices", &group->kobj);
738 if (!group->devices_kobj) {
739 kobject_put(&group->kobj); /* triggers .release & free */
740 return ERR_PTR(-ENOMEM);
744 * The devices_kobj holds a reference on the group kobject, so
745 * as long as that exists so will the group. We can therefore
746 * use the devices_kobj for reference counting.
748 kobject_put(&group->kobj);
750 ret = iommu_group_create_file(group,
751 &iommu_group_attr_reserved_regions);
755 ret = iommu_group_create_file(group, &iommu_group_attr_type);
759 pr_debug("Allocated group %d\n", group->id);
763 EXPORT_SYMBOL_GPL(iommu_group_alloc);
765 struct iommu_group *iommu_group_get_by_id(int id)
767 struct kobject *group_kobj;
768 struct iommu_group *group;
771 if (!iommu_group_kset)
774 name = kasprintf(GFP_KERNEL, "%d", id);
778 group_kobj = kset_find_obj(iommu_group_kset, name);
784 group = container_of(group_kobj, struct iommu_group, kobj);
785 BUG_ON(group->id != id);
787 kobject_get(group->devices_kobj);
788 kobject_put(&group->kobj);
792 EXPORT_SYMBOL_GPL(iommu_group_get_by_id);
795 * iommu_group_get_iommudata - retrieve iommu_data registered for a group
798 * iommu drivers can store data in the group for use when doing iommu
799 * operations. This function provides a way to retrieve it. Caller
800 * should hold a group reference.
802 void *iommu_group_get_iommudata(struct iommu_group *group)
804 return group->iommu_data;
806 EXPORT_SYMBOL_GPL(iommu_group_get_iommudata);
809 * iommu_group_set_iommudata - set iommu_data for a group
811 * @iommu_data: new data
812 * @release: release function for iommu_data
814 * iommu drivers can store data in the group for use when doing iommu
815 * operations. This function provides a way to set the data after
816 * the group has been allocated. Caller should hold a group reference.
818 void iommu_group_set_iommudata(struct iommu_group *group, void *iommu_data,
819 void (*release)(void *iommu_data))
821 group->iommu_data = iommu_data;
822 group->iommu_data_release = release;
824 EXPORT_SYMBOL_GPL(iommu_group_set_iommudata);
827 * iommu_group_set_name - set name for a group
831 * Allow iommu driver to set a name for a group. When set it will
832 * appear in a name attribute file under the group in sysfs.
834 int iommu_group_set_name(struct iommu_group *group, const char *name)
839 iommu_group_remove_file(group, &iommu_group_attr_name);
846 group->name = kstrdup(name, GFP_KERNEL);
850 ret = iommu_group_create_file(group, &iommu_group_attr_name);
859 EXPORT_SYMBOL_GPL(iommu_group_set_name);
861 static int iommu_create_device_direct_mappings(struct iommu_group *group,
864 struct iommu_domain *domain = group->default_domain;
865 struct iommu_resv_region *entry;
866 struct list_head mappings;
867 unsigned long pg_size;
870 if (!domain || !iommu_is_dma_domain(domain))
873 BUG_ON(!domain->pgsize_bitmap);
875 pg_size = 1UL << __ffs(domain->pgsize_bitmap);
876 INIT_LIST_HEAD(&mappings);
878 iommu_get_resv_regions(dev, &mappings);
880 /* We need to consider overlapping regions for different devices */
881 list_for_each_entry(entry, &mappings, list) {
882 dma_addr_t start, end, addr;
885 start = ALIGN(entry->start, pg_size);
886 end = ALIGN(entry->start + entry->length, pg_size);
888 if (entry->type != IOMMU_RESV_DIRECT &&
889 entry->type != IOMMU_RESV_DIRECT_RELAXABLE)
892 for (addr = start; addr <= end; addr += pg_size) {
893 phys_addr_t phys_addr;
898 phys_addr = iommu_iova_to_phys(domain, addr);
906 ret = iommu_map(domain, addr - map_size,
907 addr - map_size, map_size,
917 iommu_flush_iotlb_all(domain);
920 iommu_put_resv_regions(dev, &mappings);
925 static bool iommu_is_attach_deferred(struct device *dev)
927 const struct iommu_ops *ops = dev_iommu_ops(dev);
929 if (ops->is_attach_deferred)
930 return ops->is_attach_deferred(dev);
936 * iommu_group_add_device - add a device to an iommu group
937 * @group: the group into which to add the device (reference should be held)
940 * This function is called by an iommu driver to add a device into a
941 * group. Adding a device increments the group reference count.
943 int iommu_group_add_device(struct iommu_group *group, struct device *dev)
946 struct group_device *device;
948 device = kzalloc(sizeof(*device), GFP_KERNEL);
954 ret = sysfs_create_link(&dev->kobj, &group->kobj, "iommu_group");
956 goto err_free_device;
958 device->name = kasprintf(GFP_KERNEL, "%s", kobject_name(&dev->kobj));
962 goto err_remove_link;
965 ret = sysfs_create_link_nowarn(group->devices_kobj,
966 &dev->kobj, device->name);
968 if (ret == -EEXIST && i >= 0) {
970 * Account for the slim chance of collision
971 * and append an instance to the name.
974 device->name = kasprintf(GFP_KERNEL, "%s.%d",
975 kobject_name(&dev->kobj), i++);
981 kobject_get(group->devices_kobj);
983 dev->iommu_group = group;
985 mutex_lock(&group->mutex);
986 list_add_tail(&device->list, &group->devices);
987 if (group->domain && !iommu_is_attach_deferred(dev))
988 ret = __iommu_attach_device(group->domain, dev);
989 mutex_unlock(&group->mutex);
993 trace_add_device_to_group(group->id, dev);
995 dev_info(dev, "Adding to iommu group %d\n", group->id);
1000 mutex_lock(&group->mutex);
1001 list_del(&device->list);
1002 mutex_unlock(&group->mutex);
1003 dev->iommu_group = NULL;
1004 kobject_put(group->devices_kobj);
1005 sysfs_remove_link(group->devices_kobj, device->name);
1007 kfree(device->name);
1009 sysfs_remove_link(&dev->kobj, "iommu_group");
1012 dev_err(dev, "Failed to add to iommu group %d: %d\n", group->id, ret);
1015 EXPORT_SYMBOL_GPL(iommu_group_add_device);
1018 * iommu_group_remove_device - remove a device from it's current group
1019 * @dev: device to be removed
1021 * This function is called by an iommu driver to remove the device from
1022 * it's current group. This decrements the iommu group reference count.
1024 void iommu_group_remove_device(struct device *dev)
1026 struct iommu_group *group = dev->iommu_group;
1027 struct group_device *tmp_device, *device = NULL;
1032 dev_info(dev, "Removing from iommu group %d\n", group->id);
1034 mutex_lock(&group->mutex);
1035 list_for_each_entry(tmp_device, &group->devices, list) {
1036 if (tmp_device->dev == dev) {
1037 device = tmp_device;
1038 list_del(&device->list);
1042 mutex_unlock(&group->mutex);
1047 sysfs_remove_link(group->devices_kobj, device->name);
1048 sysfs_remove_link(&dev->kobj, "iommu_group");
1050 trace_remove_device_from_group(group->id, dev);
1052 kfree(device->name);
1054 dev->iommu_group = NULL;
1055 kobject_put(group->devices_kobj);
1057 EXPORT_SYMBOL_GPL(iommu_group_remove_device);
1059 static int iommu_group_device_count(struct iommu_group *group)
1061 struct group_device *entry;
1064 list_for_each_entry(entry, &group->devices, list)
1070 static int __iommu_group_for_each_dev(struct iommu_group *group, void *data,
1071 int (*fn)(struct device *, void *))
1073 struct group_device *device;
1076 list_for_each_entry(device, &group->devices, list) {
1077 ret = fn(device->dev, data);
1085 * iommu_group_for_each_dev - iterate over each device in the group
1087 * @data: caller opaque data to be passed to callback function
1088 * @fn: caller supplied callback function
1090 * This function is called by group users to iterate over group devices.
1091 * Callers should hold a reference count to the group during callback.
1092 * The group->mutex is held across callbacks, which will block calls to
1093 * iommu_group_add/remove_device.
1095 int iommu_group_for_each_dev(struct iommu_group *group, void *data,
1096 int (*fn)(struct device *, void *))
1100 mutex_lock(&group->mutex);
1101 ret = __iommu_group_for_each_dev(group, data, fn);
1102 mutex_unlock(&group->mutex);
1106 EXPORT_SYMBOL_GPL(iommu_group_for_each_dev);
1109 * iommu_group_get - Return the group for a device and increment reference
1110 * @dev: get the group that this device belongs to
1112 * This function is called by iommu drivers and users to get the group
1113 * for the specified device. If found, the group is returned and the group
1114 * reference in incremented, else NULL.
1116 struct iommu_group *iommu_group_get(struct device *dev)
1118 struct iommu_group *group = dev->iommu_group;
1121 kobject_get(group->devices_kobj);
1125 EXPORT_SYMBOL_GPL(iommu_group_get);
1128 * iommu_group_ref_get - Increment reference on a group
1129 * @group: the group to use, must not be NULL
1131 * This function is called by iommu drivers to take additional references on an
1132 * existing group. Returns the given group for convenience.
1134 struct iommu_group *iommu_group_ref_get(struct iommu_group *group)
1136 kobject_get(group->devices_kobj);
1139 EXPORT_SYMBOL_GPL(iommu_group_ref_get);
1142 * iommu_group_put - Decrement group reference
1143 * @group: the group to use
1145 * This function is called by iommu drivers and users to release the
1146 * iommu group. Once the reference count is zero, the group is released.
1148 void iommu_group_put(struct iommu_group *group)
1151 kobject_put(group->devices_kobj);
1153 EXPORT_SYMBOL_GPL(iommu_group_put);
1156 * iommu_register_device_fault_handler() - Register a device fault handler
1158 * @handler: the fault handler
1159 * @data: private data passed as argument to the handler
1161 * When an IOMMU fault event is received, this handler gets called with the
1162 * fault event and data as argument. The handler should return 0 on success. If
1163 * the fault is recoverable (IOMMU_FAULT_PAGE_REQ), the consumer should also
1164 * complete the fault by calling iommu_page_response() with one of the following
1166 * - IOMMU_PAGE_RESP_SUCCESS: retry the translation
1167 * - IOMMU_PAGE_RESP_INVALID: terminate the fault
1168 * - IOMMU_PAGE_RESP_FAILURE: terminate the fault and stop reporting
1169 * page faults if possible.
1171 * Return 0 if the fault handler was installed successfully, or an error.
1173 int iommu_register_device_fault_handler(struct device *dev,
1174 iommu_dev_fault_handler_t handler,
1177 struct dev_iommu *param = dev->iommu;
1183 mutex_lock(¶m->lock);
1184 /* Only allow one fault handler registered for each device */
1185 if (param->fault_param) {
1191 param->fault_param = kzalloc(sizeof(*param->fault_param), GFP_KERNEL);
1192 if (!param->fault_param) {
1197 param->fault_param->handler = handler;
1198 param->fault_param->data = data;
1199 mutex_init(¶m->fault_param->lock);
1200 INIT_LIST_HEAD(¶m->fault_param->faults);
1203 mutex_unlock(¶m->lock);
1207 EXPORT_SYMBOL_GPL(iommu_register_device_fault_handler);
1210 * iommu_unregister_device_fault_handler() - Unregister the device fault handler
1213 * Remove the device fault handler installed with
1214 * iommu_register_device_fault_handler().
1216 * Return 0 on success, or an error.
1218 int iommu_unregister_device_fault_handler(struct device *dev)
1220 struct dev_iommu *param = dev->iommu;
1226 mutex_lock(¶m->lock);
1228 if (!param->fault_param)
1231 /* we cannot unregister handler if there are pending faults */
1232 if (!list_empty(¶m->fault_param->faults)) {
1237 kfree(param->fault_param);
1238 param->fault_param = NULL;
1241 mutex_unlock(¶m->lock);
1245 EXPORT_SYMBOL_GPL(iommu_unregister_device_fault_handler);
1248 * iommu_report_device_fault() - Report fault event to device driver
1250 * @evt: fault event data
1252 * Called by IOMMU drivers when a fault is detected, typically in a threaded IRQ
1253 * handler. When this function fails and the fault is recoverable, it is the
1254 * caller's responsibility to complete the fault.
1256 * Return 0 on success, or an error.
1258 int iommu_report_device_fault(struct device *dev, struct iommu_fault_event *evt)
1260 struct dev_iommu *param = dev->iommu;
1261 struct iommu_fault_event *evt_pending = NULL;
1262 struct iommu_fault_param *fparam;
1268 /* we only report device fault if there is a handler registered */
1269 mutex_lock(¶m->lock);
1270 fparam = param->fault_param;
1271 if (!fparam || !fparam->handler) {
1276 if (evt->fault.type == IOMMU_FAULT_PAGE_REQ &&
1277 (evt->fault.prm.flags & IOMMU_FAULT_PAGE_REQUEST_LAST_PAGE)) {
1278 evt_pending = kmemdup(evt, sizeof(struct iommu_fault_event),
1284 mutex_lock(&fparam->lock);
1285 list_add_tail(&evt_pending->list, &fparam->faults);
1286 mutex_unlock(&fparam->lock);
1289 ret = fparam->handler(&evt->fault, fparam->data);
1290 if (ret && evt_pending) {
1291 mutex_lock(&fparam->lock);
1292 list_del(&evt_pending->list);
1293 mutex_unlock(&fparam->lock);
1297 mutex_unlock(¶m->lock);
1300 EXPORT_SYMBOL_GPL(iommu_report_device_fault);
1302 int iommu_page_response(struct device *dev,
1303 struct iommu_page_response *msg)
1307 struct iommu_fault_event *evt;
1308 struct iommu_fault_page_request *prm;
1309 struct dev_iommu *param = dev->iommu;
1310 const struct iommu_ops *ops = dev_iommu_ops(dev);
1311 bool has_pasid = msg->flags & IOMMU_PAGE_RESP_PASID_VALID;
1313 if (!ops->page_response)
1316 if (!param || !param->fault_param)
1319 if (msg->version != IOMMU_PAGE_RESP_VERSION_1 ||
1320 msg->flags & ~IOMMU_PAGE_RESP_PASID_VALID)
1323 /* Only send response if there is a fault report pending */
1324 mutex_lock(¶m->fault_param->lock);
1325 if (list_empty(¶m->fault_param->faults)) {
1326 dev_warn_ratelimited(dev, "no pending PRQ, drop response\n");
1330 * Check if we have a matching page request pending to respond,
1331 * otherwise return -EINVAL
1333 list_for_each_entry(evt, ¶m->fault_param->faults, list) {
1334 prm = &evt->fault.prm;
1335 if (prm->grpid != msg->grpid)
1339 * If the PASID is required, the corresponding request is
1340 * matched using the group ID, the PASID valid bit and the PASID
1341 * value. Otherwise only the group ID matches request and
1344 needs_pasid = prm->flags & IOMMU_FAULT_PAGE_RESPONSE_NEEDS_PASID;
1345 if (needs_pasid && (!has_pasid || msg->pasid != prm->pasid))
1348 if (!needs_pasid && has_pasid) {
1349 /* No big deal, just clear it. */
1350 msg->flags &= ~IOMMU_PAGE_RESP_PASID_VALID;
1354 ret = ops->page_response(dev, evt, msg);
1355 list_del(&evt->list);
1361 mutex_unlock(¶m->fault_param->lock);
1364 EXPORT_SYMBOL_GPL(iommu_page_response);
1367 * iommu_group_id - Return ID for a group
1368 * @group: the group to ID
1370 * Return the unique ID for the group matching the sysfs group number.
1372 int iommu_group_id(struct iommu_group *group)
1376 EXPORT_SYMBOL_GPL(iommu_group_id);
1378 static struct iommu_group *get_pci_alias_group(struct pci_dev *pdev,
1379 unsigned long *devfns);
1382 * To consider a PCI device isolated, we require ACS to support Source
1383 * Validation, Request Redirection, Completer Redirection, and Upstream
1384 * Forwarding. This effectively means that devices cannot spoof their
1385 * requester ID, requests and completions cannot be redirected, and all
1386 * transactions are forwarded upstream, even as it passes through a
1387 * bridge where the target device is downstream.
1389 #define REQ_ACS_FLAGS (PCI_ACS_SV | PCI_ACS_RR | PCI_ACS_CR | PCI_ACS_UF)
1392 * For multifunction devices which are not isolated from each other, find
1393 * all the other non-isolated functions and look for existing groups. For
1394 * each function, we also need to look for aliases to or from other devices
1395 * that may already have a group.
1397 static struct iommu_group *get_pci_function_alias_group(struct pci_dev *pdev,
1398 unsigned long *devfns)
1400 struct pci_dev *tmp = NULL;
1401 struct iommu_group *group;
1403 if (!pdev->multifunction || pci_acs_enabled(pdev, REQ_ACS_FLAGS))
1406 for_each_pci_dev(tmp) {
1407 if (tmp == pdev || tmp->bus != pdev->bus ||
1408 PCI_SLOT(tmp->devfn) != PCI_SLOT(pdev->devfn) ||
1409 pci_acs_enabled(tmp, REQ_ACS_FLAGS))
1412 group = get_pci_alias_group(tmp, devfns);
1423 * Look for aliases to or from the given device for existing groups. DMA
1424 * aliases are only supported on the same bus, therefore the search
1425 * space is quite small (especially since we're really only looking at pcie
1426 * device, and therefore only expect multiple slots on the root complex or
1427 * downstream switch ports). It's conceivable though that a pair of
1428 * multifunction devices could have aliases between them that would cause a
1429 * loop. To prevent this, we use a bitmap to track where we've been.
1431 static struct iommu_group *get_pci_alias_group(struct pci_dev *pdev,
1432 unsigned long *devfns)
1434 struct pci_dev *tmp = NULL;
1435 struct iommu_group *group;
1437 if (test_and_set_bit(pdev->devfn & 0xff, devfns))
1440 group = iommu_group_get(&pdev->dev);
1444 for_each_pci_dev(tmp) {
1445 if (tmp == pdev || tmp->bus != pdev->bus)
1448 /* We alias them or they alias us */
1449 if (pci_devs_are_dma_aliases(pdev, tmp)) {
1450 group = get_pci_alias_group(tmp, devfns);
1456 group = get_pci_function_alias_group(tmp, devfns);
1467 struct group_for_pci_data {
1468 struct pci_dev *pdev;
1469 struct iommu_group *group;
1473 * DMA alias iterator callback, return the last seen device. Stop and return
1474 * the IOMMU group if we find one along the way.
1476 static int get_pci_alias_or_group(struct pci_dev *pdev, u16 alias, void *opaque)
1478 struct group_for_pci_data *data = opaque;
1481 data->group = iommu_group_get(&pdev->dev);
1483 return data->group != NULL;
1487 * Generic device_group call-back function. It just allocates one
1488 * iommu-group per device.
1490 struct iommu_group *generic_device_group(struct device *dev)
1492 return iommu_group_alloc();
1494 EXPORT_SYMBOL_GPL(generic_device_group);
1497 * Use standard PCI bus topology, isolation features, and DMA alias quirks
1498 * to find or create an IOMMU group for a device.
1500 struct iommu_group *pci_device_group(struct device *dev)
1502 struct pci_dev *pdev = to_pci_dev(dev);
1503 struct group_for_pci_data data;
1504 struct pci_bus *bus;
1505 struct iommu_group *group = NULL;
1506 u64 devfns[4] = { 0 };
1508 if (WARN_ON(!dev_is_pci(dev)))
1509 return ERR_PTR(-EINVAL);
1512 * Find the upstream DMA alias for the device. A device must not
1513 * be aliased due to topology in order to have its own IOMMU group.
1514 * If we find an alias along the way that already belongs to a
1517 if (pci_for_each_dma_alias(pdev, get_pci_alias_or_group, &data))
1523 * Continue upstream from the point of minimum IOMMU granularity
1524 * due to aliases to the point where devices are protected from
1525 * peer-to-peer DMA by PCI ACS. Again, if we find an existing
1528 for (bus = pdev->bus; !pci_is_root_bus(bus); bus = bus->parent) {
1532 if (pci_acs_path_enabled(bus->self, NULL, REQ_ACS_FLAGS))
1537 group = iommu_group_get(&pdev->dev);
1543 * Look for existing groups on device aliases. If we alias another
1544 * device or another device aliases us, use the same group.
1546 group = get_pci_alias_group(pdev, (unsigned long *)devfns);
1551 * Look for existing groups on non-isolated functions on the same
1552 * slot and aliases of those funcions, if any. No need to clear
1553 * the search bitmap, the tested devfns are still valid.
1555 group = get_pci_function_alias_group(pdev, (unsigned long *)devfns);
1559 /* No shared group found, allocate new */
1560 return iommu_group_alloc();
1562 EXPORT_SYMBOL_GPL(pci_device_group);
1564 /* Get the IOMMU group for device on fsl-mc bus */
1565 struct iommu_group *fsl_mc_device_group(struct device *dev)
1567 struct device *cont_dev = fsl_mc_cont_dev(dev);
1568 struct iommu_group *group;
1570 group = iommu_group_get(cont_dev);
1572 group = iommu_group_alloc();
1575 EXPORT_SYMBOL_GPL(fsl_mc_device_group);
1577 static int iommu_get_def_domain_type(struct device *dev)
1579 const struct iommu_ops *ops = dev_iommu_ops(dev);
1581 if (dev_is_pci(dev) && to_pci_dev(dev)->untrusted)
1582 return IOMMU_DOMAIN_DMA;
1584 if (ops->def_domain_type)
1585 return ops->def_domain_type(dev);
1590 static int iommu_group_alloc_default_domain(struct bus_type *bus,
1591 struct iommu_group *group,
1594 struct iommu_domain *dom;
1596 dom = __iommu_domain_alloc(bus, type);
1597 if (!dom && type != IOMMU_DOMAIN_DMA) {
1598 dom = __iommu_domain_alloc(bus, IOMMU_DOMAIN_DMA);
1600 pr_warn("Failed to allocate default IOMMU domain of type %u for group %s - Falling back to IOMMU_DOMAIN_DMA",
1607 group->default_domain = dom;
1609 group->domain = dom;
1613 static int iommu_alloc_default_domain(struct iommu_group *group,
1618 if (group->default_domain)
1621 type = iommu_get_def_domain_type(dev) ? : iommu_def_domain_type;
1623 return iommu_group_alloc_default_domain(dev->bus, group, type);
1627 * iommu_group_get_for_dev - Find or create the IOMMU group for a device
1628 * @dev: target device
1630 * This function is intended to be called by IOMMU drivers and extended to
1631 * support common, bus-defined algorithms when determining or creating the
1632 * IOMMU group for a device. On success, the caller will hold a reference
1633 * to the returned IOMMU group, which will already include the provided
1634 * device. The reference should be released with iommu_group_put().
1636 static struct iommu_group *iommu_group_get_for_dev(struct device *dev)
1638 const struct iommu_ops *ops = dev_iommu_ops(dev);
1639 struct iommu_group *group;
1642 group = iommu_group_get(dev);
1646 group = ops->device_group(dev);
1647 if (WARN_ON_ONCE(group == NULL))
1648 return ERR_PTR(-EINVAL);
1653 ret = iommu_group_add_device(group, dev);
1660 iommu_group_put(group);
1662 return ERR_PTR(ret);
1665 struct iommu_domain *iommu_group_default_domain(struct iommu_group *group)
1667 return group->default_domain;
1670 static int probe_iommu_group(struct device *dev, void *data)
1672 struct list_head *group_list = data;
1673 struct iommu_group *group;
1676 /* Device is probed already if in a group */
1677 group = iommu_group_get(dev);
1679 iommu_group_put(group);
1683 ret = __iommu_probe_device(dev, group_list);
1690 static int iommu_bus_notifier(struct notifier_block *nb,
1691 unsigned long action, void *data)
1693 struct device *dev = data;
1695 if (action == BUS_NOTIFY_ADD_DEVICE) {
1698 ret = iommu_probe_device(dev);
1699 return (ret) ? NOTIFY_DONE : NOTIFY_OK;
1700 } else if (action == BUS_NOTIFY_REMOVED_DEVICE) {
1701 iommu_release_device(dev);
1708 struct __group_domain_type {
1713 static int probe_get_default_domain_type(struct device *dev, void *data)
1715 struct __group_domain_type *gtype = data;
1716 unsigned int type = iommu_get_def_domain_type(dev);
1719 if (gtype->type && gtype->type != type) {
1720 dev_warn(dev, "Device needs domain type %s, but device %s in the same iommu group requires type %s - using default\n",
1721 iommu_domain_type_str(type),
1722 dev_name(gtype->dev),
1723 iommu_domain_type_str(gtype->type));
1736 static void probe_alloc_default_domain(struct bus_type *bus,
1737 struct iommu_group *group)
1739 struct __group_domain_type gtype;
1741 memset(>ype, 0, sizeof(gtype));
1743 /* Ask for default domain requirements of all devices in the group */
1744 __iommu_group_for_each_dev(group, >ype,
1745 probe_get_default_domain_type);
1748 gtype.type = iommu_def_domain_type;
1750 iommu_group_alloc_default_domain(bus, group, gtype.type);
1754 static int iommu_group_do_dma_attach(struct device *dev, void *data)
1756 struct iommu_domain *domain = data;
1759 if (!iommu_is_attach_deferred(dev))
1760 ret = __iommu_attach_device(domain, dev);
1765 static int __iommu_group_dma_attach(struct iommu_group *group)
1767 return __iommu_group_for_each_dev(group, group->default_domain,
1768 iommu_group_do_dma_attach);
1771 static int iommu_group_do_probe_finalize(struct device *dev, void *data)
1773 const struct iommu_ops *ops = dev_iommu_ops(dev);
1775 if (ops->probe_finalize)
1776 ops->probe_finalize(dev);
1781 static void __iommu_group_dma_finalize(struct iommu_group *group)
1783 __iommu_group_for_each_dev(group, group->default_domain,
1784 iommu_group_do_probe_finalize);
1787 static int iommu_do_create_direct_mappings(struct device *dev, void *data)
1789 struct iommu_group *group = data;
1791 iommu_create_device_direct_mappings(group, dev);
1796 static int iommu_group_create_direct_mappings(struct iommu_group *group)
1798 return __iommu_group_for_each_dev(group, group,
1799 iommu_do_create_direct_mappings);
1802 int bus_iommu_probe(struct bus_type *bus)
1804 struct iommu_group *group, *next;
1805 LIST_HEAD(group_list);
1809 * This code-path does not allocate the default domain when
1810 * creating the iommu group, so do it after the groups are
1813 ret = bus_for_each_dev(bus, NULL, &group_list, probe_iommu_group);
1817 list_for_each_entry_safe(group, next, &group_list, entry) {
1818 mutex_lock(&group->mutex);
1820 /* Remove item from the list */
1821 list_del_init(&group->entry);
1823 /* Try to allocate default domain */
1824 probe_alloc_default_domain(bus, group);
1826 if (!group->default_domain) {
1827 mutex_unlock(&group->mutex);
1831 iommu_group_create_direct_mappings(group);
1833 ret = __iommu_group_dma_attach(group);
1835 mutex_unlock(&group->mutex);
1840 __iommu_group_dma_finalize(group);
1846 bool iommu_present(struct bus_type *bus)
1848 return bus->iommu_ops != NULL;
1850 EXPORT_SYMBOL_GPL(iommu_present);
1853 * device_iommu_capable() - check for a general IOMMU capability
1854 * @dev: device to which the capability would be relevant, if available
1855 * @cap: IOMMU capability
1857 * Return: true if an IOMMU is present and supports the given capability
1858 * for the given device, otherwise false.
1860 bool device_iommu_capable(struct device *dev, enum iommu_cap cap)
1862 const struct iommu_ops *ops;
1864 if (!dev->iommu || !dev->iommu->iommu_dev)
1867 ops = dev_iommu_ops(dev);
1871 return ops->capable(dev, cap);
1873 EXPORT_SYMBOL_GPL(device_iommu_capable);
1876 * iommu_set_fault_handler() - set a fault handler for an iommu domain
1877 * @domain: iommu domain
1878 * @handler: fault handler
1879 * @token: user data, will be passed back to the fault handler
1881 * This function should be used by IOMMU users which want to be notified
1882 * whenever an IOMMU fault happens.
1884 * The fault handler itself should return 0 on success, and an appropriate
1885 * error code otherwise.
1887 void iommu_set_fault_handler(struct iommu_domain *domain,
1888 iommu_fault_handler_t handler,
1893 domain->handler = handler;
1894 domain->handler_token = token;
1896 EXPORT_SYMBOL_GPL(iommu_set_fault_handler);
1898 static struct iommu_domain *__iommu_domain_alloc(struct bus_type *bus,
1901 struct iommu_domain *domain;
1903 if (bus == NULL || bus->iommu_ops == NULL)
1906 domain = bus->iommu_ops->domain_alloc(type);
1910 domain->type = type;
1911 /* Assume all sizes by default; the driver may override this later */
1912 domain->pgsize_bitmap = bus->iommu_ops->pgsize_bitmap;
1914 domain->ops = bus->iommu_ops->default_domain_ops;
1916 if (iommu_is_dma_domain(domain) && iommu_get_dma_cookie(domain)) {
1917 iommu_domain_free(domain);
1923 struct iommu_domain *iommu_domain_alloc(struct bus_type *bus)
1925 return __iommu_domain_alloc(bus, IOMMU_DOMAIN_UNMANAGED);
1927 EXPORT_SYMBOL_GPL(iommu_domain_alloc);
1929 void iommu_domain_free(struct iommu_domain *domain)
1931 iommu_put_dma_cookie(domain);
1932 domain->ops->free(domain);
1934 EXPORT_SYMBOL_GPL(iommu_domain_free);
1937 * Put the group's domain back to the appropriate core-owned domain - either the
1938 * standard kernel-mode DMA configuration or an all-DMA-blocked domain.
1940 static void __iommu_group_set_core_domain(struct iommu_group *group)
1942 struct iommu_domain *new_domain;
1946 new_domain = group->blocking_domain;
1948 new_domain = group->default_domain;
1950 ret = __iommu_group_set_domain(group, new_domain);
1951 WARN(ret, "iommu driver failed to attach the default/blocking domain");
1954 static int __iommu_attach_device(struct iommu_domain *domain,
1959 if (unlikely(domain->ops->attach_dev == NULL))
1962 ret = domain->ops->attach_dev(domain, dev);
1964 trace_attach_device_to_domain(dev);
1968 int iommu_attach_device(struct iommu_domain *domain, struct device *dev)
1970 struct iommu_group *group;
1973 group = iommu_group_get(dev);
1978 * Lock the group to make sure the device-count doesn't
1979 * change while we are attaching
1981 mutex_lock(&group->mutex);
1983 if (iommu_group_device_count(group) != 1)
1986 ret = __iommu_attach_group(domain, group);
1989 mutex_unlock(&group->mutex);
1990 iommu_group_put(group);
1994 EXPORT_SYMBOL_GPL(iommu_attach_device);
1996 int iommu_deferred_attach(struct device *dev, struct iommu_domain *domain)
1998 if (iommu_is_attach_deferred(dev))
1999 return __iommu_attach_device(domain, dev);
2004 static void __iommu_detach_device(struct iommu_domain *domain,
2007 if (iommu_is_attach_deferred(dev))
2010 domain->ops->detach_dev(domain, dev);
2011 trace_detach_device_from_domain(dev);
2014 void iommu_detach_device(struct iommu_domain *domain, struct device *dev)
2016 struct iommu_group *group;
2018 group = iommu_group_get(dev);
2022 mutex_lock(&group->mutex);
2023 if (WARN_ON(domain != group->domain) ||
2024 WARN_ON(iommu_group_device_count(group) != 1))
2026 __iommu_group_set_core_domain(group);
2029 mutex_unlock(&group->mutex);
2030 iommu_group_put(group);
2032 EXPORT_SYMBOL_GPL(iommu_detach_device);
2034 struct iommu_domain *iommu_get_domain_for_dev(struct device *dev)
2036 struct iommu_domain *domain;
2037 struct iommu_group *group;
2039 group = iommu_group_get(dev);
2043 domain = group->domain;
2045 iommu_group_put(group);
2049 EXPORT_SYMBOL_GPL(iommu_get_domain_for_dev);
2052 * For IOMMU_DOMAIN_DMA implementations which already provide their own
2053 * guarantees that the group and its default domain are valid and correct.
2055 struct iommu_domain *iommu_get_dma_domain(struct device *dev)
2057 return dev->iommu_group->default_domain;
2061 * IOMMU groups are really the natural working unit of the IOMMU, but
2062 * the IOMMU API works on domains and devices. Bridge that gap by
2063 * iterating over the devices in a group. Ideally we'd have a single
2064 * device which represents the requestor ID of the group, but we also
2065 * allow IOMMU drivers to create policy defined minimum sets, where
2066 * the physical hardware may be able to distiguish members, but we
2067 * wish to group them at a higher level (ex. untrusted multi-function
2068 * PCI devices). Thus we attach each device.
2070 static int iommu_group_do_attach_device(struct device *dev, void *data)
2072 struct iommu_domain *domain = data;
2074 return __iommu_attach_device(domain, dev);
2077 static int __iommu_attach_group(struct iommu_domain *domain,
2078 struct iommu_group *group)
2082 if (group->domain && group->domain != group->default_domain &&
2083 group->domain != group->blocking_domain)
2086 ret = __iommu_group_for_each_dev(group, domain,
2087 iommu_group_do_attach_device);
2089 group->domain = domain;
2094 int iommu_attach_group(struct iommu_domain *domain, struct iommu_group *group)
2098 mutex_lock(&group->mutex);
2099 ret = __iommu_attach_group(domain, group);
2100 mutex_unlock(&group->mutex);
2104 EXPORT_SYMBOL_GPL(iommu_attach_group);
2106 static int iommu_group_do_detach_device(struct device *dev, void *data)
2108 struct iommu_domain *domain = data;
2110 __iommu_detach_device(domain, dev);
2115 static int __iommu_group_set_domain(struct iommu_group *group,
2116 struct iommu_domain *new_domain)
2120 if (group->domain == new_domain)
2124 * New drivers should support default domains and so the detach_dev() op
2125 * will never be called. Otherwise the NULL domain represents some
2126 * platform specific behavior.
2129 if (WARN_ON(!group->domain->ops->detach_dev))
2131 __iommu_group_for_each_dev(group, group->domain,
2132 iommu_group_do_detach_device);
2133 group->domain = NULL;
2138 * Changing the domain is done by calling attach_dev() on the new
2139 * domain. This switch does not have to be atomic and DMA can be
2140 * discarded during the transition. DMA must only be able to access
2141 * either new_domain or group->domain, never something else.
2143 * Note that this is called in error unwind paths, attaching to a
2144 * domain that has already been attached cannot fail.
2146 ret = __iommu_group_for_each_dev(group, new_domain,
2147 iommu_group_do_attach_device);
2150 group->domain = new_domain;
2154 void iommu_detach_group(struct iommu_domain *domain, struct iommu_group *group)
2156 mutex_lock(&group->mutex);
2157 __iommu_group_set_core_domain(group);
2158 mutex_unlock(&group->mutex);
2160 EXPORT_SYMBOL_GPL(iommu_detach_group);
2162 phys_addr_t iommu_iova_to_phys(struct iommu_domain *domain, dma_addr_t iova)
2164 if (domain->type == IOMMU_DOMAIN_IDENTITY)
2167 if (domain->type == IOMMU_DOMAIN_BLOCKED)
2170 return domain->ops->iova_to_phys(domain, iova);
2172 EXPORT_SYMBOL_GPL(iommu_iova_to_phys);
2174 static size_t iommu_pgsize(struct iommu_domain *domain, unsigned long iova,
2175 phys_addr_t paddr, size_t size, size_t *count)
2177 unsigned int pgsize_idx, pgsize_idx_next;
2178 unsigned long pgsizes;
2179 size_t offset, pgsize, pgsize_next;
2180 unsigned long addr_merge = paddr | iova;
2182 /* Page sizes supported by the hardware and small enough for @size */
2183 pgsizes = domain->pgsize_bitmap & GENMASK(__fls(size), 0);
2185 /* Constrain the page sizes further based on the maximum alignment */
2186 if (likely(addr_merge))
2187 pgsizes &= GENMASK(__ffs(addr_merge), 0);
2189 /* Make sure we have at least one suitable page size */
2192 /* Pick the biggest page size remaining */
2193 pgsize_idx = __fls(pgsizes);
2194 pgsize = BIT(pgsize_idx);
2198 /* Find the next biggest support page size, if it exists */
2199 pgsizes = domain->pgsize_bitmap & ~GENMASK(pgsize_idx, 0);
2203 pgsize_idx_next = __ffs(pgsizes);
2204 pgsize_next = BIT(pgsize_idx_next);
2207 * There's no point trying a bigger page size unless the virtual
2208 * and physical addresses are similarly offset within the larger page.
2210 if ((iova ^ paddr) & (pgsize_next - 1))
2213 /* Calculate the offset to the next page size alignment boundary */
2214 offset = pgsize_next - (addr_merge & (pgsize_next - 1));
2217 * If size is big enough to accommodate the larger page, reduce
2218 * the number of smaller pages.
2220 if (offset + pgsize_next <= size)
2224 *count = size >> pgsize_idx;
2228 static int __iommu_map_pages(struct iommu_domain *domain, unsigned long iova,
2229 phys_addr_t paddr, size_t size, int prot,
2230 gfp_t gfp, size_t *mapped)
2232 const struct iommu_domain_ops *ops = domain->ops;
2233 size_t pgsize, count;
2236 pgsize = iommu_pgsize(domain, iova, paddr, size, &count);
2238 pr_debug("mapping: iova 0x%lx pa %pa pgsize 0x%zx count %zu\n",
2239 iova, &paddr, pgsize, count);
2241 if (ops->map_pages) {
2242 ret = ops->map_pages(domain, iova, paddr, pgsize, count, prot,
2245 ret = ops->map(domain, iova, paddr, pgsize, prot, gfp);
2246 *mapped = ret ? 0 : pgsize;
2252 static int __iommu_map(struct iommu_domain *domain, unsigned long iova,
2253 phys_addr_t paddr, size_t size, int prot, gfp_t gfp)
2255 const struct iommu_domain_ops *ops = domain->ops;
2256 unsigned long orig_iova = iova;
2257 unsigned int min_pagesz;
2258 size_t orig_size = size;
2259 phys_addr_t orig_paddr = paddr;
2262 if (unlikely(!(ops->map || ops->map_pages) ||
2263 domain->pgsize_bitmap == 0UL))
2266 if (unlikely(!(domain->type & __IOMMU_DOMAIN_PAGING)))
2269 /* find out the minimum page size supported */
2270 min_pagesz = 1 << __ffs(domain->pgsize_bitmap);
2273 * both the virtual address and the physical one, as well as
2274 * the size of the mapping, must be aligned (at least) to the
2275 * size of the smallest page supported by the hardware
2277 if (!IS_ALIGNED(iova | paddr | size, min_pagesz)) {
2278 pr_err("unaligned: iova 0x%lx pa %pa size 0x%zx min_pagesz 0x%x\n",
2279 iova, &paddr, size, min_pagesz);
2283 pr_debug("map: iova 0x%lx pa %pa size 0x%zx\n", iova, &paddr, size);
2288 ret = __iommu_map_pages(domain, iova, paddr, size, prot, gfp,
2291 * Some pages may have been mapped, even if an error occurred,
2292 * so we should account for those so they can be unmapped.
2303 /* unroll mapping in case something went wrong */
2305 iommu_unmap(domain, orig_iova, orig_size - size);
2307 trace_map(orig_iova, orig_paddr, orig_size);
2312 static int _iommu_map(struct iommu_domain *domain, unsigned long iova,
2313 phys_addr_t paddr, size_t size, int prot, gfp_t gfp)
2315 const struct iommu_domain_ops *ops = domain->ops;
2318 ret = __iommu_map(domain, iova, paddr, size, prot, gfp);
2319 if (ret == 0 && ops->iotlb_sync_map)
2320 ops->iotlb_sync_map(domain, iova, size);
2325 int iommu_map(struct iommu_domain *domain, unsigned long iova,
2326 phys_addr_t paddr, size_t size, int prot)
2329 return _iommu_map(domain, iova, paddr, size, prot, GFP_KERNEL);
2331 EXPORT_SYMBOL_GPL(iommu_map);
2333 int iommu_map_atomic(struct iommu_domain *domain, unsigned long iova,
2334 phys_addr_t paddr, size_t size, int prot)
2336 return _iommu_map(domain, iova, paddr, size, prot, GFP_ATOMIC);
2338 EXPORT_SYMBOL_GPL(iommu_map_atomic);
2340 static size_t __iommu_unmap_pages(struct iommu_domain *domain,
2341 unsigned long iova, size_t size,
2342 struct iommu_iotlb_gather *iotlb_gather)
2344 const struct iommu_domain_ops *ops = domain->ops;
2345 size_t pgsize, count;
2347 pgsize = iommu_pgsize(domain, iova, iova, size, &count);
2348 return ops->unmap_pages ?
2349 ops->unmap_pages(domain, iova, pgsize, count, iotlb_gather) :
2350 ops->unmap(domain, iova, pgsize, iotlb_gather);
2353 static size_t __iommu_unmap(struct iommu_domain *domain,
2354 unsigned long iova, size_t size,
2355 struct iommu_iotlb_gather *iotlb_gather)
2357 const struct iommu_domain_ops *ops = domain->ops;
2358 size_t unmapped_page, unmapped = 0;
2359 unsigned long orig_iova = iova;
2360 unsigned int min_pagesz;
2362 if (unlikely(!(ops->unmap || ops->unmap_pages) ||
2363 domain->pgsize_bitmap == 0UL))
2366 if (unlikely(!(domain->type & __IOMMU_DOMAIN_PAGING)))
2369 /* find out the minimum page size supported */
2370 min_pagesz = 1 << __ffs(domain->pgsize_bitmap);
2373 * The virtual address, as well as the size of the mapping, must be
2374 * aligned (at least) to the size of the smallest page supported
2377 if (!IS_ALIGNED(iova | size, min_pagesz)) {
2378 pr_err("unaligned: iova 0x%lx size 0x%zx min_pagesz 0x%x\n",
2379 iova, size, min_pagesz);
2383 pr_debug("unmap this: iova 0x%lx size 0x%zx\n", iova, size);
2386 * Keep iterating until we either unmap 'size' bytes (or more)
2387 * or we hit an area that isn't mapped.
2389 while (unmapped < size) {
2390 unmapped_page = __iommu_unmap_pages(domain, iova,
2396 pr_debug("unmapped: iova 0x%lx size 0x%zx\n",
2397 iova, unmapped_page);
2399 iova += unmapped_page;
2400 unmapped += unmapped_page;
2403 trace_unmap(orig_iova, size, unmapped);
2407 size_t iommu_unmap(struct iommu_domain *domain,
2408 unsigned long iova, size_t size)
2410 struct iommu_iotlb_gather iotlb_gather;
2413 iommu_iotlb_gather_init(&iotlb_gather);
2414 ret = __iommu_unmap(domain, iova, size, &iotlb_gather);
2415 iommu_iotlb_sync(domain, &iotlb_gather);
2419 EXPORT_SYMBOL_GPL(iommu_unmap);
2421 size_t iommu_unmap_fast(struct iommu_domain *domain,
2422 unsigned long iova, size_t size,
2423 struct iommu_iotlb_gather *iotlb_gather)
2425 return __iommu_unmap(domain, iova, size, iotlb_gather);
2427 EXPORT_SYMBOL_GPL(iommu_unmap_fast);
2429 static ssize_t __iommu_map_sg(struct iommu_domain *domain, unsigned long iova,
2430 struct scatterlist *sg, unsigned int nents, int prot,
2433 const struct iommu_domain_ops *ops = domain->ops;
2434 size_t len = 0, mapped = 0;
2439 while (i <= nents) {
2440 phys_addr_t s_phys = sg_phys(sg);
2442 if (len && s_phys != start + len) {
2443 ret = __iommu_map(domain, iova + mapped, start,
2453 if (sg_is_dma_bus_address(sg))
2468 if (ops->iotlb_sync_map)
2469 ops->iotlb_sync_map(domain, iova, mapped);
2473 /* undo mappings already done */
2474 iommu_unmap(domain, iova, mapped);
2479 ssize_t iommu_map_sg(struct iommu_domain *domain, unsigned long iova,
2480 struct scatterlist *sg, unsigned int nents, int prot)
2483 return __iommu_map_sg(domain, iova, sg, nents, prot, GFP_KERNEL);
2485 EXPORT_SYMBOL_GPL(iommu_map_sg);
2487 ssize_t iommu_map_sg_atomic(struct iommu_domain *domain, unsigned long iova,
2488 struct scatterlist *sg, unsigned int nents, int prot)
2490 return __iommu_map_sg(domain, iova, sg, nents, prot, GFP_ATOMIC);
2494 * report_iommu_fault() - report about an IOMMU fault to the IOMMU framework
2495 * @domain: the iommu domain where the fault has happened
2496 * @dev: the device where the fault has happened
2497 * @iova: the faulting address
2498 * @flags: mmu fault flags (e.g. IOMMU_FAULT_READ/IOMMU_FAULT_WRITE/...)
2500 * This function should be called by the low-level IOMMU implementations
2501 * whenever IOMMU faults happen, to allow high-level users, that are
2502 * interested in such events, to know about them.
2504 * This event may be useful for several possible use cases:
2505 * - mere logging of the event
2506 * - dynamic TLB/PTE loading
2507 * - if restarting of the faulting device is required
2509 * Returns 0 on success and an appropriate error code otherwise (if dynamic
2510 * PTE/TLB loading will one day be supported, implementations will be able
2511 * to tell whether it succeeded or not according to this return value).
2513 * Specifically, -ENOSYS is returned if a fault handler isn't installed
2514 * (though fault handlers can also return -ENOSYS, in case they want to
2515 * elicit the default behavior of the IOMMU drivers).
2517 int report_iommu_fault(struct iommu_domain *domain, struct device *dev,
2518 unsigned long iova, int flags)
2523 * if upper layers showed interest and installed a fault handler,
2526 if (domain->handler)
2527 ret = domain->handler(domain, dev, iova, flags,
2528 domain->handler_token);
2530 trace_io_page_fault(dev, iova, flags);
2533 EXPORT_SYMBOL_GPL(report_iommu_fault);
2535 static int __init iommu_init(void)
2537 iommu_group_kset = kset_create_and_add("iommu_groups",
2539 BUG_ON(!iommu_group_kset);
2541 iommu_debugfs_setup();
2545 core_initcall(iommu_init);
2547 int iommu_enable_nesting(struct iommu_domain *domain)
2549 if (domain->type != IOMMU_DOMAIN_UNMANAGED)
2551 if (!domain->ops->enable_nesting)
2553 return domain->ops->enable_nesting(domain);
2555 EXPORT_SYMBOL_GPL(iommu_enable_nesting);
2557 int iommu_set_pgtable_quirks(struct iommu_domain *domain,
2558 unsigned long quirk)
2560 if (domain->type != IOMMU_DOMAIN_UNMANAGED)
2562 if (!domain->ops->set_pgtable_quirks)
2564 return domain->ops->set_pgtable_quirks(domain, quirk);
2566 EXPORT_SYMBOL_GPL(iommu_set_pgtable_quirks);
2568 void iommu_get_resv_regions(struct device *dev, struct list_head *list)
2570 const struct iommu_ops *ops = dev_iommu_ops(dev);
2572 if (ops->get_resv_regions)
2573 ops->get_resv_regions(dev, list);
2577 * iommu_put_resv_regions - release resered regions
2578 * @dev: device for which to free reserved regions
2579 * @list: reserved region list for device
2581 * This releases a reserved region list acquired by iommu_get_resv_regions().
2583 void iommu_put_resv_regions(struct device *dev, struct list_head *list)
2585 struct iommu_resv_region *entry, *next;
2587 list_for_each_entry_safe(entry, next, list, list) {
2589 entry->free(dev, entry);
2594 EXPORT_SYMBOL(iommu_put_resv_regions);
2596 struct iommu_resv_region *iommu_alloc_resv_region(phys_addr_t start,
2597 size_t length, int prot,
2598 enum iommu_resv_type type,
2601 struct iommu_resv_region *region;
2603 region = kzalloc(sizeof(*region), gfp);
2607 INIT_LIST_HEAD(®ion->list);
2608 region->start = start;
2609 region->length = length;
2610 region->prot = prot;
2611 region->type = type;
2614 EXPORT_SYMBOL_GPL(iommu_alloc_resv_region);
2616 void iommu_set_default_passthrough(bool cmd_line)
2619 iommu_cmd_line |= IOMMU_CMD_LINE_DMA_API;
2620 iommu_def_domain_type = IOMMU_DOMAIN_IDENTITY;
2623 void iommu_set_default_translated(bool cmd_line)
2626 iommu_cmd_line |= IOMMU_CMD_LINE_DMA_API;
2627 iommu_def_domain_type = IOMMU_DOMAIN_DMA;
2630 bool iommu_default_passthrough(void)
2632 return iommu_def_domain_type == IOMMU_DOMAIN_IDENTITY;
2634 EXPORT_SYMBOL_GPL(iommu_default_passthrough);
2636 const struct iommu_ops *iommu_ops_from_fwnode(struct fwnode_handle *fwnode)
2638 const struct iommu_ops *ops = NULL;
2639 struct iommu_device *iommu;
2641 spin_lock(&iommu_device_lock);
2642 list_for_each_entry(iommu, &iommu_device_list, list)
2643 if (iommu->fwnode == fwnode) {
2647 spin_unlock(&iommu_device_lock);
2651 int iommu_fwspec_init(struct device *dev, struct fwnode_handle *iommu_fwnode,
2652 const struct iommu_ops *ops)
2654 struct iommu_fwspec *fwspec = dev_iommu_fwspec_get(dev);
2657 return ops == fwspec->ops ? 0 : -EINVAL;
2659 if (!dev_iommu_get(dev))
2662 /* Preallocate for the overwhelmingly common case of 1 ID */
2663 fwspec = kzalloc(struct_size(fwspec, ids, 1), GFP_KERNEL);
2667 of_node_get(to_of_node(iommu_fwnode));
2668 fwspec->iommu_fwnode = iommu_fwnode;
2670 dev_iommu_fwspec_set(dev, fwspec);
2673 EXPORT_SYMBOL_GPL(iommu_fwspec_init);
2675 void iommu_fwspec_free(struct device *dev)
2677 struct iommu_fwspec *fwspec = dev_iommu_fwspec_get(dev);
2680 fwnode_handle_put(fwspec->iommu_fwnode);
2682 dev_iommu_fwspec_set(dev, NULL);
2685 EXPORT_SYMBOL_GPL(iommu_fwspec_free);
2687 int iommu_fwspec_add_ids(struct device *dev, u32 *ids, int num_ids)
2689 struct iommu_fwspec *fwspec = dev_iommu_fwspec_get(dev);
2695 new_num = fwspec->num_ids + num_ids;
2697 fwspec = krealloc(fwspec, struct_size(fwspec, ids, new_num),
2702 dev_iommu_fwspec_set(dev, fwspec);
2705 for (i = 0; i < num_ids; i++)
2706 fwspec->ids[fwspec->num_ids + i] = ids[i];
2708 fwspec->num_ids = new_num;
2711 EXPORT_SYMBOL_GPL(iommu_fwspec_add_ids);
2714 * Per device IOMMU features.
2716 int iommu_dev_enable_feature(struct device *dev, enum iommu_dev_features feat)
2718 if (dev->iommu && dev->iommu->iommu_dev) {
2719 const struct iommu_ops *ops = dev->iommu->iommu_dev->ops;
2721 if (ops->dev_enable_feat)
2722 return ops->dev_enable_feat(dev, feat);
2727 EXPORT_SYMBOL_GPL(iommu_dev_enable_feature);
2730 * The device drivers should do the necessary cleanups before calling this.
2732 int iommu_dev_disable_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_disable_feat)
2738 return ops->dev_disable_feat(dev, feat);
2743 EXPORT_SYMBOL_GPL(iommu_dev_disable_feature);
2746 * iommu_sva_bind_device() - Bind a process address space to a device
2748 * @mm: the mm to bind, caller must hold a reference to it
2749 * @drvdata: opaque data pointer to pass to bind callback
2751 * Create a bond between device and address space, allowing the device to access
2752 * the mm using the returned PASID. If a bond already exists between @device and
2753 * @mm, it is returned and an additional reference is taken. Caller must call
2754 * iommu_sva_unbind_device() to release each reference.
2756 * iommu_dev_enable_feature(dev, IOMMU_DEV_FEAT_SVA) must be called first, to
2757 * initialize the required SVA features.
2759 * On error, returns an ERR_PTR value.
2762 iommu_sva_bind_device(struct device *dev, struct mm_struct *mm, void *drvdata)
2764 struct iommu_group *group;
2765 struct iommu_sva *handle = ERR_PTR(-EINVAL);
2766 const struct iommu_ops *ops = dev_iommu_ops(dev);
2769 return ERR_PTR(-ENODEV);
2771 group = iommu_group_get(dev);
2773 return ERR_PTR(-ENODEV);
2775 /* Ensure device count and domain don't change while we're binding */
2776 mutex_lock(&group->mutex);
2779 * To keep things simple, SVA currently doesn't support IOMMU groups
2780 * with more than one device. Existing SVA-capable systems are not
2781 * affected by the problems that required IOMMU groups (lack of ACS
2782 * isolation, device ID aliasing and other hardware issues).
2784 if (iommu_group_device_count(group) != 1)
2787 handle = ops->sva_bind(dev, mm, drvdata);
2790 mutex_unlock(&group->mutex);
2791 iommu_group_put(group);
2795 EXPORT_SYMBOL_GPL(iommu_sva_bind_device);
2798 * iommu_sva_unbind_device() - Remove a bond created with iommu_sva_bind_device
2799 * @handle: the handle returned by iommu_sva_bind_device()
2801 * Put reference to a bond between device and address space. The device should
2802 * not be issuing any more transaction for this PASID. All outstanding page
2803 * requests for this PASID must have been flushed to the IOMMU.
2805 void iommu_sva_unbind_device(struct iommu_sva *handle)
2807 struct iommu_group *group;
2808 struct device *dev = handle->dev;
2809 const struct iommu_ops *ops = dev_iommu_ops(dev);
2811 if (!ops->sva_unbind)
2814 group = iommu_group_get(dev);
2818 mutex_lock(&group->mutex);
2819 ops->sva_unbind(handle);
2820 mutex_unlock(&group->mutex);
2822 iommu_group_put(group);
2824 EXPORT_SYMBOL_GPL(iommu_sva_unbind_device);
2826 u32 iommu_sva_get_pasid(struct iommu_sva *handle)
2828 const struct iommu_ops *ops = dev_iommu_ops(handle->dev);
2830 if (!ops->sva_get_pasid)
2831 return IOMMU_PASID_INVALID;
2833 return ops->sva_get_pasid(handle);
2835 EXPORT_SYMBOL_GPL(iommu_sva_get_pasid);
2838 * Changes the default domain of an iommu group that has *only* one device
2840 * @group: The group for which the default domain should be changed
2841 * @prev_dev: The device in the group (this is used to make sure that the device
2842 * hasn't changed after the caller has called this function)
2843 * @type: The type of the new default domain that gets associated with the group
2845 * Returns 0 on success and error code on failure
2848 * 1. Presently, this function is called only when user requests to change the
2849 * group's default domain type through /sys/kernel/iommu_groups/<grp_id>/type
2850 * Please take a closer look if intended to use for other purposes.
2852 static int iommu_change_dev_def_domain(struct iommu_group *group,
2853 struct device *prev_dev, int type)
2855 struct iommu_domain *prev_dom;
2856 struct group_device *grp_dev;
2857 int ret, dev_def_dom;
2860 mutex_lock(&group->mutex);
2862 if (group->default_domain != group->domain) {
2863 dev_err_ratelimited(prev_dev, "Group not assigned to default domain\n");
2869 * iommu group wasn't locked while acquiring device lock in
2870 * iommu_group_store_type(). So, make sure that the device count hasn't
2871 * changed while acquiring device lock.
2873 * Changing default domain of an iommu group with two or more devices
2874 * isn't supported because there could be a potential deadlock. Consider
2875 * the following scenario. T1 is trying to acquire device locks of all
2876 * the devices in the group and before it could acquire all of them,
2877 * there could be another thread T2 (from different sub-system and use
2878 * case) that has already acquired some of the device locks and might be
2879 * waiting for T1 to release other device locks.
2881 if (iommu_group_device_count(group) != 1) {
2882 dev_err_ratelimited(prev_dev, "Cannot change default domain: Group has more than one device\n");
2887 /* Since group has only one device */
2888 grp_dev = list_first_entry(&group->devices, struct group_device, list);
2891 if (prev_dev != dev) {
2892 dev_err_ratelimited(prev_dev, "Cannot change default domain: Device has been changed\n");
2897 prev_dom = group->default_domain;
2903 dev_def_dom = iommu_get_def_domain_type(dev);
2906 * If the user hasn't requested any specific type of domain and
2907 * if the device supports both the domains, then default to the
2908 * domain the device was booted with
2910 type = dev_def_dom ? : iommu_def_domain_type;
2911 } else if (dev_def_dom && type != dev_def_dom) {
2912 dev_err_ratelimited(prev_dev, "Device cannot be in %s domain\n",
2913 iommu_domain_type_str(type));
2919 * Switch to a new domain only if the requested domain type is different
2920 * from the existing default domain type
2922 if (prev_dom->type == type) {
2927 /* We can bring up a flush queue without tearing down the domain */
2928 if (type == IOMMU_DOMAIN_DMA_FQ && prev_dom->type == IOMMU_DOMAIN_DMA) {
2929 ret = iommu_dma_init_fq(prev_dom);
2931 prev_dom->type = IOMMU_DOMAIN_DMA_FQ;
2935 /* Sets group->default_domain to the newly allocated domain */
2936 ret = iommu_group_alloc_default_domain(dev->bus, group, type);
2940 ret = iommu_create_device_direct_mappings(group, dev);
2942 goto free_new_domain;
2944 ret = __iommu_attach_device(group->default_domain, dev);
2946 goto free_new_domain;
2948 group->domain = group->default_domain;
2951 * Release the mutex here because ops->probe_finalize() call-back of
2952 * some vendor IOMMU drivers calls arm_iommu_attach_device() which
2953 * in-turn might call back into IOMMU core code, where it tries to take
2954 * group->mutex, resulting in a deadlock.
2956 mutex_unlock(&group->mutex);
2958 /* Make sure dma_ops is appropriatley set */
2959 iommu_group_do_probe_finalize(dev, group->default_domain);
2960 iommu_domain_free(prev_dom);
2964 iommu_domain_free(group->default_domain);
2965 group->default_domain = prev_dom;
2966 group->domain = prev_dom;
2969 mutex_unlock(&group->mutex);
2975 * Changing the default domain through sysfs requires the users to unbind the
2976 * drivers from the devices in the iommu group, except for a DMA -> DMA-FQ
2977 * transition. Return failure if this isn't met.
2979 * We need to consider the race between this and the device release path.
2980 * device_lock(dev) is used here to guarantee that the device release path
2981 * will not be entered at the same time.
2983 static ssize_t iommu_group_store_type(struct iommu_group *group,
2984 const char *buf, size_t count)
2986 struct group_device *grp_dev;
2990 if (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO))
2993 if (WARN_ON(!group) || !group->default_domain)
2996 if (sysfs_streq(buf, "identity"))
2997 req_type = IOMMU_DOMAIN_IDENTITY;
2998 else if (sysfs_streq(buf, "DMA"))
2999 req_type = IOMMU_DOMAIN_DMA;
3000 else if (sysfs_streq(buf, "DMA-FQ"))
3001 req_type = IOMMU_DOMAIN_DMA_FQ;
3002 else if (sysfs_streq(buf, "auto"))
3008 * Lock/Unlock the group mutex here before device lock to
3009 * 1. Make sure that the iommu group has only one device (this is a
3010 * prerequisite for step 2)
3011 * 2. Get struct *dev which is needed to lock device
3013 mutex_lock(&group->mutex);
3014 if (iommu_group_device_count(group) != 1) {
3015 mutex_unlock(&group->mutex);
3016 pr_err_ratelimited("Cannot change default domain: Group has more than one device\n");
3020 /* Since group has only one device */
3021 grp_dev = list_first_entry(&group->devices, struct group_device, list);
3026 * Don't hold the group mutex because taking group mutex first and then
3027 * the device lock could potentially cause a deadlock as below. Assume
3028 * two threads T1 and T2. T1 is trying to change default domain of an
3029 * iommu group and T2 is trying to hot unplug a device or release [1] VF
3030 * of a PCIe device which is in the same iommu group. T1 takes group
3031 * mutex and before it could take device lock assume T2 has taken device
3032 * lock and is yet to take group mutex. Now, both the threads will be
3033 * waiting for the other thread to release lock. Below, lock order was
3036 * mutex_lock(&group->mutex);
3037 * iommu_change_dev_def_domain();
3038 * mutex_unlock(&group->mutex);
3039 * device_unlock(dev);
3041 * [1] Typical device release path
3042 * device_lock() from device/driver core code
3044 * -> iommu_bus_notifier()
3045 * -> iommu_release_device()
3046 * -> ops->release_device() vendor driver calls back iommu core code
3047 * -> mutex_lock() from iommu core code
3049 mutex_unlock(&group->mutex);
3051 /* Check if the device in the group still has a driver bound to it */
3053 if (device_is_bound(dev) && !(req_type == IOMMU_DOMAIN_DMA_FQ &&
3054 group->default_domain->type == IOMMU_DOMAIN_DMA)) {
3055 pr_err_ratelimited("Device is still bound to driver\n");
3060 ret = iommu_change_dev_def_domain(group, dev, req_type);
3070 static bool iommu_is_default_domain(struct iommu_group *group)
3072 if (group->domain == group->default_domain)
3076 * If the default domain was set to identity and it is still an identity
3077 * domain then we consider this a pass. This happens because of
3078 * amd_iommu_init_device() replacing the default idenytity domain with an
3079 * identity domain that has a different configuration for AMDGPU.
3081 if (group->default_domain &&
3082 group->default_domain->type == IOMMU_DOMAIN_IDENTITY &&
3083 group->domain && group->domain->type == IOMMU_DOMAIN_IDENTITY)
3089 * iommu_device_use_default_domain() - Device driver wants to handle device
3090 * DMA through the kernel DMA API.
3093 * The device driver about to bind @dev wants to do DMA through the kernel
3094 * DMA API. Return 0 if it is allowed, otherwise an error.
3096 int iommu_device_use_default_domain(struct device *dev)
3098 struct iommu_group *group = iommu_group_get(dev);
3104 mutex_lock(&group->mutex);
3105 if (group->owner_cnt) {
3106 if (group->owner || !iommu_is_default_domain(group)) {
3115 mutex_unlock(&group->mutex);
3116 iommu_group_put(group);
3122 * iommu_device_unuse_default_domain() - Device driver stops handling device
3123 * DMA through the kernel DMA API.
3126 * The device driver doesn't want to do DMA through kernel DMA API anymore.
3127 * It must be called after iommu_device_use_default_domain().
3129 void iommu_device_unuse_default_domain(struct device *dev)
3131 struct iommu_group *group = iommu_group_get(dev);
3136 mutex_lock(&group->mutex);
3137 if (!WARN_ON(!group->owner_cnt))
3140 mutex_unlock(&group->mutex);
3141 iommu_group_put(group);
3144 static int __iommu_group_alloc_blocking_domain(struct iommu_group *group)
3146 struct group_device *dev =
3147 list_first_entry(&group->devices, struct group_device, list);
3149 if (group->blocking_domain)
3152 group->blocking_domain =
3153 __iommu_domain_alloc(dev->dev->bus, IOMMU_DOMAIN_BLOCKED);
3154 if (!group->blocking_domain) {
3156 * For drivers that do not yet understand IOMMU_DOMAIN_BLOCKED
3157 * create an empty domain instead.
3159 group->blocking_domain = __iommu_domain_alloc(
3160 dev->dev->bus, IOMMU_DOMAIN_UNMANAGED);
3161 if (!group->blocking_domain)
3168 * iommu_group_claim_dma_owner() - Set DMA ownership of a group
3169 * @group: The group.
3170 * @owner: Caller specified pointer. Used for exclusive ownership.
3172 * This is to support backward compatibility for vfio which manages
3173 * the dma ownership in iommu_group level. New invocations on this
3174 * interface should be prohibited.
3176 int iommu_group_claim_dma_owner(struct iommu_group *group, void *owner)
3180 mutex_lock(&group->mutex);
3181 if (group->owner_cnt) {
3185 if (group->domain && group->domain != group->default_domain) {
3190 ret = __iommu_group_alloc_blocking_domain(group);
3194 ret = __iommu_group_set_domain(group, group->blocking_domain);
3197 group->owner = owner;
3202 mutex_unlock(&group->mutex);
3206 EXPORT_SYMBOL_GPL(iommu_group_claim_dma_owner);
3209 * iommu_group_release_dma_owner() - Release DMA ownership of a group
3210 * @group: The group.
3212 * Release the DMA ownership claimed by iommu_group_claim_dma_owner().
3214 void iommu_group_release_dma_owner(struct iommu_group *group)
3218 mutex_lock(&group->mutex);
3219 if (WARN_ON(!group->owner_cnt || !group->owner))
3222 group->owner_cnt = 0;
3223 group->owner = NULL;
3224 ret = __iommu_group_set_domain(group, group->default_domain);
3225 WARN(ret, "iommu driver failed to attach the default domain");
3228 mutex_unlock(&group->mutex);
3230 EXPORT_SYMBOL_GPL(iommu_group_release_dma_owner);
3233 * iommu_group_dma_owner_claimed() - Query group dma ownership status
3234 * @group: The group.
3236 * This provides status query on a given group. It is racy and only for
3237 * non-binding status reporting.
3239 bool iommu_group_dma_owner_claimed(struct iommu_group *group)
3243 mutex_lock(&group->mutex);
3244 user = group->owner_cnt;
3245 mutex_unlock(&group->mutex);
3249 EXPORT_SYMBOL_GPL(iommu_group_dma_owner_claimed);