1 // SPDX-License-Identifier: GPL-2.0-only
3 * Copyright (C) 2007-2008 Advanced Micro Devices, Inc.
4 * Author: Joerg Roedel <jroedel@suse.de>
7 #define pr_fmt(fmt) "iommu: " fmt
9 #include <linux/amba/bus.h>
10 #include <linux/device.h>
11 #include <linux/kernel.h>
12 #include <linux/bits.h>
13 #include <linux/bug.h>
14 #include <linux/types.h>
15 #include <linux/init.h>
16 #include <linux/export.h>
17 #include <linux/slab.h>
18 #include <linux/errno.h>
19 #include <linux/host1x_context_bus.h>
20 #include <linux/iommu.h>
21 #include <linux/idr.h>
22 #include <linux/err.h>
23 #include <linux/pci.h>
24 #include <linux/pci-ats.h>
25 #include <linux/bitops.h>
26 #include <linux/platform_device.h>
27 #include <linux/property.h>
28 #include <linux/fsl/mc.h>
29 #include <linux/module.h>
30 #include <linux/cc_platform.h>
31 #include <linux/cdx/cdx_bus.h>
32 #include <trace/events/iommu.h>
33 #include <linux/sched/mm.h>
34 #include <linux/msi.h>
36 #include "dma-iommu.h"
37 #include "iommu-priv.h"
39 #include "iommu-sva.h"
40 #include "iommu-priv.h"
42 static struct kset *iommu_group_kset;
43 static DEFINE_IDA(iommu_group_ida);
45 static unsigned int iommu_def_domain_type __read_mostly;
46 static bool iommu_dma_strict __read_mostly = IS_ENABLED(CONFIG_IOMMU_DEFAULT_DMA_STRICT);
47 static u32 iommu_cmd_line __read_mostly;
51 struct kobject *devices_kobj;
52 struct list_head devices;
53 struct xarray pasid_array;
56 void (*iommu_data_release)(void *iommu_data);
59 struct iommu_domain *default_domain;
60 struct iommu_domain *blocking_domain;
61 struct iommu_domain *domain;
62 struct list_head entry;
63 unsigned int owner_cnt;
68 struct list_head list;
73 /* Iterate over each struct group_device in a struct iommu_group */
74 #define for_each_group_device(group, pos) \
75 list_for_each_entry(pos, &(group)->devices, list)
77 struct iommu_group_attribute {
78 struct attribute attr;
79 ssize_t (*show)(struct iommu_group *group, char *buf);
80 ssize_t (*store)(struct iommu_group *group,
81 const char *buf, size_t count);
84 static const char * const iommu_group_resv_type_string[] = {
85 [IOMMU_RESV_DIRECT] = "direct",
86 [IOMMU_RESV_DIRECT_RELAXABLE] = "direct-relaxable",
87 [IOMMU_RESV_RESERVED] = "reserved",
88 [IOMMU_RESV_MSI] = "msi",
89 [IOMMU_RESV_SW_MSI] = "msi",
92 #define IOMMU_CMD_LINE_DMA_API BIT(0)
93 #define IOMMU_CMD_LINE_STRICT BIT(1)
95 static int iommu_bus_notifier(struct notifier_block *nb,
96 unsigned long action, void *data);
97 static void iommu_release_device(struct device *dev);
98 static struct iommu_domain *__iommu_domain_alloc(const struct bus_type *bus,
100 static int __iommu_attach_device(struct iommu_domain *domain,
102 static int __iommu_attach_group(struct iommu_domain *domain,
103 struct iommu_group *group);
106 IOMMU_SET_DOMAIN_MUST_SUCCEED = 1 << 0,
109 static int __iommu_device_set_domain(struct iommu_group *group,
111 struct iommu_domain *new_domain,
113 static int __iommu_group_set_domain_internal(struct iommu_group *group,
114 struct iommu_domain *new_domain,
116 static int __iommu_group_set_domain(struct iommu_group *group,
117 struct iommu_domain *new_domain)
119 return __iommu_group_set_domain_internal(group, new_domain, 0);
121 static void __iommu_group_set_domain_nofail(struct iommu_group *group,
122 struct iommu_domain *new_domain)
124 WARN_ON(__iommu_group_set_domain_internal(
125 group, new_domain, IOMMU_SET_DOMAIN_MUST_SUCCEED));
128 static int iommu_setup_default_domain(struct iommu_group *group,
130 static int iommu_create_device_direct_mappings(struct iommu_domain *domain,
132 static struct iommu_group *iommu_group_get_for_dev(struct device *dev);
133 static ssize_t iommu_group_store_type(struct iommu_group *group,
134 const char *buf, size_t count);
136 #define IOMMU_GROUP_ATTR(_name, _mode, _show, _store) \
137 struct iommu_group_attribute iommu_group_attr_##_name = \
138 __ATTR(_name, _mode, _show, _store)
140 #define to_iommu_group_attr(_attr) \
141 container_of(_attr, struct iommu_group_attribute, attr)
142 #define to_iommu_group(_kobj) \
143 container_of(_kobj, struct iommu_group, kobj)
145 static LIST_HEAD(iommu_device_list);
146 static DEFINE_SPINLOCK(iommu_device_lock);
148 static struct bus_type * const iommu_buses[] = {
153 #ifdef CONFIG_ARM_AMBA
156 #ifdef CONFIG_FSL_MC_BUS
159 #ifdef CONFIG_TEGRA_HOST1X_CONTEXT_BUS
160 &host1x_context_device_bus_type,
162 #ifdef CONFIG_CDX_BUS
168 * Use a function instead of an array here because the domain-type is a
169 * bit-field, so an array would waste memory.
171 static const char *iommu_domain_type_str(unsigned int t)
174 case IOMMU_DOMAIN_BLOCKED:
176 case IOMMU_DOMAIN_IDENTITY:
177 return "Passthrough";
178 case IOMMU_DOMAIN_UNMANAGED:
180 case IOMMU_DOMAIN_DMA:
181 case IOMMU_DOMAIN_DMA_FQ:
188 static int __init iommu_subsys_init(void)
190 struct notifier_block *nb;
192 if (!(iommu_cmd_line & IOMMU_CMD_LINE_DMA_API)) {
193 if (IS_ENABLED(CONFIG_IOMMU_DEFAULT_PASSTHROUGH))
194 iommu_set_default_passthrough(false);
196 iommu_set_default_translated(false);
198 if (iommu_default_passthrough() && cc_platform_has(CC_ATTR_MEM_ENCRYPT)) {
199 pr_info("Memory encryption detected - Disabling default IOMMU Passthrough\n");
200 iommu_set_default_translated(false);
204 if (!iommu_default_passthrough() && !iommu_dma_strict)
205 iommu_def_domain_type = IOMMU_DOMAIN_DMA_FQ;
207 pr_info("Default domain type: %s%s\n",
208 iommu_domain_type_str(iommu_def_domain_type),
209 (iommu_cmd_line & IOMMU_CMD_LINE_DMA_API) ?
210 " (set via kernel command line)" : "");
212 if (!iommu_default_passthrough())
213 pr_info("DMA domain TLB invalidation policy: %s mode%s\n",
214 iommu_dma_strict ? "strict" : "lazy",
215 (iommu_cmd_line & IOMMU_CMD_LINE_STRICT) ?
216 " (set via kernel command line)" : "");
218 nb = kcalloc(ARRAY_SIZE(iommu_buses), sizeof(*nb), GFP_KERNEL);
222 for (int i = 0; i < ARRAY_SIZE(iommu_buses); i++) {
223 nb[i].notifier_call = iommu_bus_notifier;
224 bus_register_notifier(iommu_buses[i], &nb[i]);
229 subsys_initcall(iommu_subsys_init);
231 static int remove_iommu_group(struct device *dev, void *data)
233 if (dev->iommu && dev->iommu->iommu_dev == data)
234 iommu_release_device(dev);
240 * iommu_device_register() - Register an IOMMU hardware instance
241 * @iommu: IOMMU handle for the instance
242 * @ops: IOMMU ops to associate with the instance
243 * @hwdev: (optional) actual instance device, used for fwnode lookup
245 * Return: 0 on success, or an error.
247 int iommu_device_register(struct iommu_device *iommu,
248 const struct iommu_ops *ops, struct device *hwdev)
252 /* We need to be able to take module references appropriately */
253 if (WARN_ON(is_module_address((unsigned long)ops) && !ops->owner))
256 * Temporarily enforce global restriction to a single driver. This was
257 * already the de-facto behaviour, since any possible combination of
258 * existing drivers would compete for at least the PCI or platform bus.
260 if (iommu_buses[0]->iommu_ops && iommu_buses[0]->iommu_ops != ops)
265 iommu->fwnode = dev_fwnode(hwdev);
267 spin_lock(&iommu_device_lock);
268 list_add_tail(&iommu->list, &iommu_device_list);
269 spin_unlock(&iommu_device_lock);
271 for (int i = 0; i < ARRAY_SIZE(iommu_buses) && !err; i++) {
272 iommu_buses[i]->iommu_ops = ops;
273 err = bus_iommu_probe(iommu_buses[i]);
276 iommu_device_unregister(iommu);
279 EXPORT_SYMBOL_GPL(iommu_device_register);
281 void iommu_device_unregister(struct iommu_device *iommu)
283 for (int i = 0; i < ARRAY_SIZE(iommu_buses); i++)
284 bus_for_each_dev(iommu_buses[i], NULL, iommu, remove_iommu_group);
286 spin_lock(&iommu_device_lock);
287 list_del(&iommu->list);
288 spin_unlock(&iommu_device_lock);
290 EXPORT_SYMBOL_GPL(iommu_device_unregister);
292 #if IS_ENABLED(CONFIG_IOMMUFD_TEST)
293 void iommu_device_unregister_bus(struct iommu_device *iommu,
294 struct bus_type *bus,
295 struct notifier_block *nb)
297 bus_unregister_notifier(bus, nb);
298 iommu_device_unregister(iommu);
300 EXPORT_SYMBOL_GPL(iommu_device_unregister_bus);
303 * Register an iommu driver against a single bus. This is only used by iommufd
304 * selftest to create a mock iommu driver. The caller must provide
305 * some memory to hold a notifier_block.
307 int iommu_device_register_bus(struct iommu_device *iommu,
308 const struct iommu_ops *ops, struct bus_type *bus,
309 struct notifier_block *nb)
314 nb->notifier_call = iommu_bus_notifier;
315 err = bus_register_notifier(bus, nb);
319 spin_lock(&iommu_device_lock);
320 list_add_tail(&iommu->list, &iommu_device_list);
321 spin_unlock(&iommu_device_lock);
323 bus->iommu_ops = ops;
324 err = bus_iommu_probe(bus);
326 iommu_device_unregister_bus(iommu, bus, nb);
331 EXPORT_SYMBOL_GPL(iommu_device_register_bus);
334 static struct dev_iommu *dev_iommu_get(struct device *dev)
336 struct dev_iommu *param = dev->iommu;
341 param = kzalloc(sizeof(*param), GFP_KERNEL);
345 mutex_init(¶m->lock);
350 static void dev_iommu_free(struct device *dev)
352 struct dev_iommu *param = dev->iommu;
356 fwnode_handle_put(param->fwspec->iommu_fwnode);
357 kfree(param->fwspec);
362 static u32 dev_iommu_get_max_pasids(struct device *dev)
364 u32 max_pasids = 0, bits = 0;
367 if (dev_is_pci(dev)) {
368 ret = pci_max_pasids(to_pci_dev(dev));
372 ret = device_property_read_u32(dev, "pasid-num-bits", &bits);
374 max_pasids = 1UL << bits;
377 return min_t(u32, max_pasids, dev->iommu->iommu_dev->max_pasids);
380 static int __iommu_probe_device(struct device *dev, struct list_head *group_list)
382 const struct iommu_ops *ops = dev->bus->iommu_ops;
383 struct iommu_device *iommu_dev;
384 struct iommu_group *group;
385 static DEFINE_MUTEX(iommu_probe_device_lock);
391 * Serialise to avoid races between IOMMU drivers registering in
392 * parallel and/or the "replay" calls from ACPI/OF code via client
393 * driver probe. Once the latter have been cleaned up we should
394 * probably be able to use device_lock() here to minimise the scope,
395 * but for now enforcing a simple global ordering is fine.
397 mutex_lock(&iommu_probe_device_lock);
398 if (!dev_iommu_get(dev)) {
403 if (!try_module_get(ops->owner)) {
408 iommu_dev = ops->probe_device(dev);
409 if (IS_ERR(iommu_dev)) {
410 ret = PTR_ERR(iommu_dev);
414 dev->iommu->iommu_dev = iommu_dev;
415 dev->iommu->max_pasids = dev_iommu_get_max_pasids(dev);
416 if (ops->is_attach_deferred)
417 dev->iommu->attach_deferred = ops->is_attach_deferred(dev);
419 group = iommu_group_get_for_dev(dev);
421 ret = PTR_ERR(group);
425 mutex_lock(&group->mutex);
426 if (group_list && !group->default_domain && list_empty(&group->entry))
427 list_add_tail(&group->entry, group_list);
428 mutex_unlock(&group->mutex);
429 iommu_group_put(group);
431 mutex_unlock(&iommu_probe_device_lock);
432 iommu_device_link(iommu_dev, dev);
437 if (ops->release_device)
438 ops->release_device(dev);
441 module_put(ops->owner);
447 mutex_unlock(&iommu_probe_device_lock);
452 int iommu_probe_device(struct device *dev)
454 const struct iommu_ops *ops;
455 struct iommu_group *group;
458 ret = __iommu_probe_device(dev, NULL);
462 group = iommu_group_get(dev);
468 mutex_lock(&group->mutex);
470 if (group->default_domain)
471 iommu_create_device_direct_mappings(group->default_domain, dev);
474 ret = __iommu_device_set_domain(group, dev, group->domain, 0);
477 } else if (!group->default_domain) {
478 ret = iommu_setup_default_domain(group, 0);
483 mutex_unlock(&group->mutex);
484 iommu_group_put(group);
486 ops = dev_iommu_ops(dev);
487 if (ops->probe_finalize)
488 ops->probe_finalize(dev);
493 mutex_unlock(&group->mutex);
494 iommu_group_put(group);
496 iommu_release_device(dev);
504 * Remove a device from a group's device list and return the group device
507 static struct group_device *
508 __iommu_group_remove_device(struct iommu_group *group, struct device *dev)
510 struct group_device *device;
512 lockdep_assert_held(&group->mutex);
513 for_each_group_device(group, device) {
514 if (device->dev == dev) {
515 list_del(&device->list);
524 * Release a device from its group and decrements the iommu group reference
527 static void __iommu_group_release_device(struct iommu_group *group,
528 struct group_device *grp_dev)
530 struct device *dev = grp_dev->dev;
532 sysfs_remove_link(group->devices_kobj, grp_dev->name);
533 sysfs_remove_link(&dev->kobj, "iommu_group");
535 trace_remove_device_from_group(group->id, dev);
537 kfree(grp_dev->name);
539 dev->iommu_group = NULL;
540 kobject_put(group->devices_kobj);
543 static void iommu_release_device(struct device *dev)
545 struct iommu_group *group = dev->iommu_group;
546 struct group_device *device;
547 const struct iommu_ops *ops;
549 if (!dev->iommu || !group)
552 iommu_device_unlink(dev->iommu->iommu_dev, dev);
554 mutex_lock(&group->mutex);
555 device = __iommu_group_remove_device(group, dev);
558 * If the group has become empty then ownership must have been released,
559 * and the current domain must be set back to NULL or the default
562 if (list_empty(&group->devices))
563 WARN_ON(group->owner_cnt ||
564 group->domain != group->default_domain);
567 * release_device() must stop using any attached domain on the device.
568 * If there are still other devices in the group they are not effected
571 * The IOMMU driver must set the device to either an identity or
572 * blocking translation and stop using any domain pointer, as it is
575 ops = dev_iommu_ops(dev);
576 if (ops->release_device)
577 ops->release_device(dev);
578 mutex_unlock(&group->mutex);
581 __iommu_group_release_device(group, device);
583 module_put(ops->owner);
587 static int __init iommu_set_def_domain_type(char *str)
592 ret = kstrtobool(str, &pt);
597 iommu_set_default_passthrough(true);
599 iommu_set_default_translated(true);
603 early_param("iommu.passthrough", iommu_set_def_domain_type);
605 static int __init iommu_dma_setup(char *str)
607 int ret = kstrtobool(str, &iommu_dma_strict);
610 iommu_cmd_line |= IOMMU_CMD_LINE_STRICT;
613 early_param("iommu.strict", iommu_dma_setup);
615 void iommu_set_dma_strict(void)
617 iommu_dma_strict = true;
618 if (iommu_def_domain_type == IOMMU_DOMAIN_DMA_FQ)
619 iommu_def_domain_type = IOMMU_DOMAIN_DMA;
622 static ssize_t iommu_group_attr_show(struct kobject *kobj,
623 struct attribute *__attr, char *buf)
625 struct iommu_group_attribute *attr = to_iommu_group_attr(__attr);
626 struct iommu_group *group = to_iommu_group(kobj);
630 ret = attr->show(group, buf);
634 static ssize_t iommu_group_attr_store(struct kobject *kobj,
635 struct attribute *__attr,
636 const char *buf, size_t count)
638 struct iommu_group_attribute *attr = to_iommu_group_attr(__attr);
639 struct iommu_group *group = to_iommu_group(kobj);
643 ret = attr->store(group, buf, count);
647 static const struct sysfs_ops iommu_group_sysfs_ops = {
648 .show = iommu_group_attr_show,
649 .store = iommu_group_attr_store,
652 static int iommu_group_create_file(struct iommu_group *group,
653 struct iommu_group_attribute *attr)
655 return sysfs_create_file(&group->kobj, &attr->attr);
658 static void iommu_group_remove_file(struct iommu_group *group,
659 struct iommu_group_attribute *attr)
661 sysfs_remove_file(&group->kobj, &attr->attr);
664 static ssize_t iommu_group_show_name(struct iommu_group *group, char *buf)
666 return sysfs_emit(buf, "%s\n", group->name);
670 * iommu_insert_resv_region - Insert a new region in the
671 * list of reserved regions.
672 * @new: new region to insert
673 * @regions: list of regions
675 * Elements are sorted by start address and overlapping segments
676 * of the same type are merged.
678 static int iommu_insert_resv_region(struct iommu_resv_region *new,
679 struct list_head *regions)
681 struct iommu_resv_region *iter, *tmp, *nr, *top;
684 nr = iommu_alloc_resv_region(new->start, new->length,
685 new->prot, new->type, GFP_KERNEL);
689 /* First add the new element based on start address sorting */
690 list_for_each_entry(iter, regions, list) {
691 if (nr->start < iter->start ||
692 (nr->start == iter->start && nr->type <= iter->type))
695 list_add_tail(&nr->list, &iter->list);
697 /* Merge overlapping segments of type nr->type in @regions, if any */
698 list_for_each_entry_safe(iter, tmp, regions, list) {
699 phys_addr_t top_end, iter_end = iter->start + iter->length - 1;
701 /* no merge needed on elements of different types than @new */
702 if (iter->type != new->type) {
703 list_move_tail(&iter->list, &stack);
707 /* look for the last stack element of same type as @iter */
708 list_for_each_entry_reverse(top, &stack, list)
709 if (top->type == iter->type)
712 list_move_tail(&iter->list, &stack);
716 top_end = top->start + top->length - 1;
718 if (iter->start > top_end + 1) {
719 list_move_tail(&iter->list, &stack);
721 top->length = max(top_end, iter_end) - top->start + 1;
722 list_del(&iter->list);
726 list_splice(&stack, regions);
731 iommu_insert_device_resv_regions(struct list_head *dev_resv_regions,
732 struct list_head *group_resv_regions)
734 struct iommu_resv_region *entry;
737 list_for_each_entry(entry, dev_resv_regions, list) {
738 ret = iommu_insert_resv_region(entry, group_resv_regions);
745 int iommu_get_group_resv_regions(struct iommu_group *group,
746 struct list_head *head)
748 struct group_device *device;
751 mutex_lock(&group->mutex);
752 for_each_group_device(group, device) {
753 struct list_head dev_resv_regions;
756 * Non-API groups still expose reserved_regions in sysfs,
757 * so filter out calls that get here that way.
759 if (!device->dev->iommu)
762 INIT_LIST_HEAD(&dev_resv_regions);
763 iommu_get_resv_regions(device->dev, &dev_resv_regions);
764 ret = iommu_insert_device_resv_regions(&dev_resv_regions, head);
765 iommu_put_resv_regions(device->dev, &dev_resv_regions);
769 mutex_unlock(&group->mutex);
772 EXPORT_SYMBOL_GPL(iommu_get_group_resv_regions);
774 static ssize_t iommu_group_show_resv_regions(struct iommu_group *group,
777 struct iommu_resv_region *region, *next;
778 struct list_head group_resv_regions;
781 INIT_LIST_HEAD(&group_resv_regions);
782 iommu_get_group_resv_regions(group, &group_resv_regions);
784 list_for_each_entry_safe(region, next, &group_resv_regions, list) {
785 offset += sysfs_emit_at(buf, offset, "0x%016llx 0x%016llx %s\n",
786 (long long)region->start,
787 (long long)(region->start +
789 iommu_group_resv_type_string[region->type]);
796 static ssize_t iommu_group_show_type(struct iommu_group *group,
799 char *type = "unknown";
801 mutex_lock(&group->mutex);
802 if (group->default_domain) {
803 switch (group->default_domain->type) {
804 case IOMMU_DOMAIN_BLOCKED:
807 case IOMMU_DOMAIN_IDENTITY:
810 case IOMMU_DOMAIN_UNMANAGED:
813 case IOMMU_DOMAIN_DMA:
816 case IOMMU_DOMAIN_DMA_FQ:
821 mutex_unlock(&group->mutex);
823 return sysfs_emit(buf, "%s\n", type);
826 static IOMMU_GROUP_ATTR(name, S_IRUGO, iommu_group_show_name, NULL);
828 static IOMMU_GROUP_ATTR(reserved_regions, 0444,
829 iommu_group_show_resv_regions, NULL);
831 static IOMMU_GROUP_ATTR(type, 0644, iommu_group_show_type,
832 iommu_group_store_type);
834 static void iommu_group_release(struct kobject *kobj)
836 struct iommu_group *group = to_iommu_group(kobj);
838 pr_debug("Releasing group %d\n", group->id);
840 if (group->iommu_data_release)
841 group->iommu_data_release(group->iommu_data);
843 ida_free(&iommu_group_ida, group->id);
845 if (group->default_domain)
846 iommu_domain_free(group->default_domain);
847 if (group->blocking_domain)
848 iommu_domain_free(group->blocking_domain);
854 static const struct kobj_type iommu_group_ktype = {
855 .sysfs_ops = &iommu_group_sysfs_ops,
856 .release = iommu_group_release,
860 * iommu_group_alloc - Allocate a new group
862 * This function is called by an iommu driver to allocate a new iommu
863 * group. The iommu group represents the minimum granularity of the iommu.
864 * Upon successful return, the caller holds a reference to the supplied
865 * group in order to hold the group until devices are added. Use
866 * iommu_group_put() to release this extra reference count, allowing the
867 * group to be automatically reclaimed once it has no devices or external
870 struct iommu_group *iommu_group_alloc(void)
872 struct iommu_group *group;
875 group = kzalloc(sizeof(*group), GFP_KERNEL);
877 return ERR_PTR(-ENOMEM);
879 group->kobj.kset = iommu_group_kset;
880 mutex_init(&group->mutex);
881 INIT_LIST_HEAD(&group->devices);
882 INIT_LIST_HEAD(&group->entry);
883 xa_init(&group->pasid_array);
885 ret = ida_alloc(&iommu_group_ida, GFP_KERNEL);
892 ret = kobject_init_and_add(&group->kobj, &iommu_group_ktype,
893 NULL, "%d", group->id);
895 kobject_put(&group->kobj);
899 group->devices_kobj = kobject_create_and_add("devices", &group->kobj);
900 if (!group->devices_kobj) {
901 kobject_put(&group->kobj); /* triggers .release & free */
902 return ERR_PTR(-ENOMEM);
906 * The devices_kobj holds a reference on the group kobject, so
907 * as long as that exists so will the group. We can therefore
908 * use the devices_kobj for reference counting.
910 kobject_put(&group->kobj);
912 ret = iommu_group_create_file(group,
913 &iommu_group_attr_reserved_regions);
915 kobject_put(group->devices_kobj);
919 ret = iommu_group_create_file(group, &iommu_group_attr_type);
921 kobject_put(group->devices_kobj);
925 pr_debug("Allocated group %d\n", group->id);
929 EXPORT_SYMBOL_GPL(iommu_group_alloc);
932 * iommu_group_get_iommudata - retrieve iommu_data registered for a group
935 * iommu drivers can store data in the group for use when doing iommu
936 * operations. This function provides a way to retrieve it. Caller
937 * should hold a group reference.
939 void *iommu_group_get_iommudata(struct iommu_group *group)
941 return group->iommu_data;
943 EXPORT_SYMBOL_GPL(iommu_group_get_iommudata);
946 * iommu_group_set_iommudata - set iommu_data for a group
948 * @iommu_data: new data
949 * @release: release function for iommu_data
951 * iommu drivers can store data in the group for use when doing iommu
952 * operations. This function provides a way to set the data after
953 * the group has been allocated. Caller should hold a group reference.
955 void iommu_group_set_iommudata(struct iommu_group *group, void *iommu_data,
956 void (*release)(void *iommu_data))
958 group->iommu_data = iommu_data;
959 group->iommu_data_release = release;
961 EXPORT_SYMBOL_GPL(iommu_group_set_iommudata);
964 * iommu_group_set_name - set name for a group
968 * Allow iommu driver to set a name for a group. When set it will
969 * appear in a name attribute file under the group in sysfs.
971 int iommu_group_set_name(struct iommu_group *group, const char *name)
976 iommu_group_remove_file(group, &iommu_group_attr_name);
983 group->name = kstrdup(name, GFP_KERNEL);
987 ret = iommu_group_create_file(group, &iommu_group_attr_name);
996 EXPORT_SYMBOL_GPL(iommu_group_set_name);
998 static int iommu_create_device_direct_mappings(struct iommu_domain *domain,
1001 struct iommu_resv_region *entry;
1002 struct list_head mappings;
1003 unsigned long pg_size;
1006 if (!iommu_is_dma_domain(domain))
1009 BUG_ON(!domain->pgsize_bitmap);
1011 pg_size = 1UL << __ffs(domain->pgsize_bitmap);
1012 INIT_LIST_HEAD(&mappings);
1014 iommu_get_resv_regions(dev, &mappings);
1016 /* We need to consider overlapping regions for different devices */
1017 list_for_each_entry(entry, &mappings, list) {
1018 dma_addr_t start, end, addr;
1019 size_t map_size = 0;
1021 start = ALIGN(entry->start, pg_size);
1022 end = ALIGN(entry->start + entry->length, pg_size);
1024 if (entry->type != IOMMU_RESV_DIRECT &&
1025 entry->type != IOMMU_RESV_DIRECT_RELAXABLE)
1028 for (addr = start; addr <= end; addr += pg_size) {
1029 phys_addr_t phys_addr;
1034 phys_addr = iommu_iova_to_phys(domain, addr);
1036 map_size += pg_size;
1042 ret = iommu_map(domain, addr - map_size,
1043 addr - map_size, map_size,
1044 entry->prot, GFP_KERNEL);
1053 iommu_flush_iotlb_all(domain);
1056 iommu_put_resv_regions(dev, &mappings);
1062 * iommu_group_add_device - add a device to an iommu group
1063 * @group: the group into which to add the device (reference should be held)
1066 * This function is called by an iommu driver to add a device into a
1067 * group. Adding a device increments the group reference count.
1069 int iommu_group_add_device(struct iommu_group *group, struct device *dev)
1072 struct group_device *device;
1074 device = kzalloc(sizeof(*device), GFP_KERNEL);
1080 ret = sysfs_create_link(&dev->kobj, &group->kobj, "iommu_group");
1082 goto err_free_device;
1084 device->name = kasprintf(GFP_KERNEL, "%s", kobject_name(&dev->kobj));
1086 if (!device->name) {
1088 goto err_remove_link;
1091 ret = sysfs_create_link_nowarn(group->devices_kobj,
1092 &dev->kobj, device->name);
1094 if (ret == -EEXIST && i >= 0) {
1096 * Account for the slim chance of collision
1097 * and append an instance to the name.
1099 kfree(device->name);
1100 device->name = kasprintf(GFP_KERNEL, "%s.%d",
1101 kobject_name(&dev->kobj), i++);
1107 kobject_get(group->devices_kobj);
1109 dev->iommu_group = group;
1111 mutex_lock(&group->mutex);
1112 list_add_tail(&device->list, &group->devices);
1113 mutex_unlock(&group->mutex);
1114 trace_add_device_to_group(group->id, dev);
1116 dev_info(dev, "Adding to iommu group %d\n", group->id);
1121 kfree(device->name);
1123 sysfs_remove_link(&dev->kobj, "iommu_group");
1126 dev_err(dev, "Failed to add to iommu group %d: %d\n", group->id, ret);
1129 EXPORT_SYMBOL_GPL(iommu_group_add_device);
1132 * iommu_group_remove_device - remove a device from it's current group
1133 * @dev: device to be removed
1135 * This function is called by an iommu driver to remove the device from
1136 * it's current group. This decrements the iommu group reference count.
1138 void iommu_group_remove_device(struct device *dev)
1140 struct iommu_group *group = dev->iommu_group;
1141 struct group_device *device;
1146 dev_info(dev, "Removing from iommu group %d\n", group->id);
1148 mutex_lock(&group->mutex);
1149 device = __iommu_group_remove_device(group, dev);
1150 mutex_unlock(&group->mutex);
1153 __iommu_group_release_device(group, device);
1155 EXPORT_SYMBOL_GPL(iommu_group_remove_device);
1158 * iommu_group_for_each_dev - iterate over each device in the group
1160 * @data: caller opaque data to be passed to callback function
1161 * @fn: caller supplied callback function
1163 * This function is called by group users to iterate over group devices.
1164 * Callers should hold a reference count to the group during callback.
1165 * The group->mutex is held across callbacks, which will block calls to
1166 * iommu_group_add/remove_device.
1168 int iommu_group_for_each_dev(struct iommu_group *group, void *data,
1169 int (*fn)(struct device *, void *))
1171 struct group_device *device;
1174 mutex_lock(&group->mutex);
1175 for_each_group_device(group, device) {
1176 ret = fn(device->dev, data);
1180 mutex_unlock(&group->mutex);
1184 EXPORT_SYMBOL_GPL(iommu_group_for_each_dev);
1187 * iommu_group_get - Return the group for a device and increment reference
1188 * @dev: get the group that this device belongs to
1190 * This function is called by iommu drivers and users to get the group
1191 * for the specified device. If found, the group is returned and the group
1192 * reference in incremented, else NULL.
1194 struct iommu_group *iommu_group_get(struct device *dev)
1196 struct iommu_group *group = dev->iommu_group;
1199 kobject_get(group->devices_kobj);
1203 EXPORT_SYMBOL_GPL(iommu_group_get);
1206 * iommu_group_ref_get - Increment reference on a group
1207 * @group: the group to use, must not be NULL
1209 * This function is called by iommu drivers to take additional references on an
1210 * existing group. Returns the given group for convenience.
1212 struct iommu_group *iommu_group_ref_get(struct iommu_group *group)
1214 kobject_get(group->devices_kobj);
1217 EXPORT_SYMBOL_GPL(iommu_group_ref_get);
1220 * iommu_group_put - Decrement group reference
1221 * @group: the group to use
1223 * This function is called by iommu drivers and users to release the
1224 * iommu group. Once the reference count is zero, the group is released.
1226 void iommu_group_put(struct iommu_group *group)
1229 kobject_put(group->devices_kobj);
1231 EXPORT_SYMBOL_GPL(iommu_group_put);
1234 * iommu_register_device_fault_handler() - Register a device fault handler
1236 * @handler: the fault handler
1237 * @data: private data passed as argument to the handler
1239 * When an IOMMU fault event is received, this handler gets called with the
1240 * fault event and data as argument. The handler should return 0 on success. If
1241 * the fault is recoverable (IOMMU_FAULT_PAGE_REQ), the consumer should also
1242 * complete the fault by calling iommu_page_response() with one of the following
1244 * - IOMMU_PAGE_RESP_SUCCESS: retry the translation
1245 * - IOMMU_PAGE_RESP_INVALID: terminate the fault
1246 * - IOMMU_PAGE_RESP_FAILURE: terminate the fault and stop reporting
1247 * page faults if possible.
1249 * Return 0 if the fault handler was installed successfully, or an error.
1251 int iommu_register_device_fault_handler(struct device *dev,
1252 iommu_dev_fault_handler_t handler,
1255 struct dev_iommu *param = dev->iommu;
1261 mutex_lock(¶m->lock);
1262 /* Only allow one fault handler registered for each device */
1263 if (param->fault_param) {
1269 param->fault_param = kzalloc(sizeof(*param->fault_param), GFP_KERNEL);
1270 if (!param->fault_param) {
1275 param->fault_param->handler = handler;
1276 param->fault_param->data = data;
1277 mutex_init(¶m->fault_param->lock);
1278 INIT_LIST_HEAD(¶m->fault_param->faults);
1281 mutex_unlock(¶m->lock);
1285 EXPORT_SYMBOL_GPL(iommu_register_device_fault_handler);
1288 * iommu_unregister_device_fault_handler() - Unregister the device fault handler
1291 * Remove the device fault handler installed with
1292 * iommu_register_device_fault_handler().
1294 * Return 0 on success, or an error.
1296 int iommu_unregister_device_fault_handler(struct device *dev)
1298 struct dev_iommu *param = dev->iommu;
1304 mutex_lock(¶m->lock);
1306 if (!param->fault_param)
1309 /* we cannot unregister handler if there are pending faults */
1310 if (!list_empty(¶m->fault_param->faults)) {
1315 kfree(param->fault_param);
1316 param->fault_param = NULL;
1319 mutex_unlock(¶m->lock);
1323 EXPORT_SYMBOL_GPL(iommu_unregister_device_fault_handler);
1326 * iommu_report_device_fault() - Report fault event to device driver
1328 * @evt: fault event data
1330 * Called by IOMMU drivers when a fault is detected, typically in a threaded IRQ
1331 * handler. When this function fails and the fault is recoverable, it is the
1332 * caller's responsibility to complete the fault.
1334 * Return 0 on success, or an error.
1336 int iommu_report_device_fault(struct device *dev, struct iommu_fault_event *evt)
1338 struct dev_iommu *param = dev->iommu;
1339 struct iommu_fault_event *evt_pending = NULL;
1340 struct iommu_fault_param *fparam;
1346 /* we only report device fault if there is a handler registered */
1347 mutex_lock(¶m->lock);
1348 fparam = param->fault_param;
1349 if (!fparam || !fparam->handler) {
1354 if (evt->fault.type == IOMMU_FAULT_PAGE_REQ &&
1355 (evt->fault.prm.flags & IOMMU_FAULT_PAGE_REQUEST_LAST_PAGE)) {
1356 evt_pending = kmemdup(evt, sizeof(struct iommu_fault_event),
1362 mutex_lock(&fparam->lock);
1363 list_add_tail(&evt_pending->list, &fparam->faults);
1364 mutex_unlock(&fparam->lock);
1367 ret = fparam->handler(&evt->fault, fparam->data);
1368 if (ret && evt_pending) {
1369 mutex_lock(&fparam->lock);
1370 list_del(&evt_pending->list);
1371 mutex_unlock(&fparam->lock);
1375 mutex_unlock(¶m->lock);
1378 EXPORT_SYMBOL_GPL(iommu_report_device_fault);
1380 int iommu_page_response(struct device *dev,
1381 struct iommu_page_response *msg)
1385 struct iommu_fault_event *evt;
1386 struct iommu_fault_page_request *prm;
1387 struct dev_iommu *param = dev->iommu;
1388 const struct iommu_ops *ops = dev_iommu_ops(dev);
1389 bool has_pasid = msg->flags & IOMMU_PAGE_RESP_PASID_VALID;
1391 if (!ops->page_response)
1394 if (!param || !param->fault_param)
1397 if (msg->version != IOMMU_PAGE_RESP_VERSION_1 ||
1398 msg->flags & ~IOMMU_PAGE_RESP_PASID_VALID)
1401 /* Only send response if there is a fault report pending */
1402 mutex_lock(¶m->fault_param->lock);
1403 if (list_empty(¶m->fault_param->faults)) {
1404 dev_warn_ratelimited(dev, "no pending PRQ, drop response\n");
1408 * Check if we have a matching page request pending to respond,
1409 * otherwise return -EINVAL
1411 list_for_each_entry(evt, ¶m->fault_param->faults, list) {
1412 prm = &evt->fault.prm;
1413 if (prm->grpid != msg->grpid)
1417 * If the PASID is required, the corresponding request is
1418 * matched using the group ID, the PASID valid bit and the PASID
1419 * value. Otherwise only the group ID matches request and
1422 needs_pasid = prm->flags & IOMMU_FAULT_PAGE_RESPONSE_NEEDS_PASID;
1423 if (needs_pasid && (!has_pasid || msg->pasid != prm->pasid))
1426 if (!needs_pasid && has_pasid) {
1427 /* No big deal, just clear it. */
1428 msg->flags &= ~IOMMU_PAGE_RESP_PASID_VALID;
1432 ret = ops->page_response(dev, evt, msg);
1433 list_del(&evt->list);
1439 mutex_unlock(¶m->fault_param->lock);
1442 EXPORT_SYMBOL_GPL(iommu_page_response);
1445 * iommu_group_id - Return ID for a group
1446 * @group: the group to ID
1448 * Return the unique ID for the group matching the sysfs group number.
1450 int iommu_group_id(struct iommu_group *group)
1454 EXPORT_SYMBOL_GPL(iommu_group_id);
1456 static struct iommu_group *get_pci_alias_group(struct pci_dev *pdev,
1457 unsigned long *devfns);
1460 * To consider a PCI device isolated, we require ACS to support Source
1461 * Validation, Request Redirection, Completer Redirection, and Upstream
1462 * Forwarding. This effectively means that devices cannot spoof their
1463 * requester ID, requests and completions cannot be redirected, and all
1464 * transactions are forwarded upstream, even as it passes through a
1465 * bridge where the target device is downstream.
1467 #define REQ_ACS_FLAGS (PCI_ACS_SV | PCI_ACS_RR | PCI_ACS_CR | PCI_ACS_UF)
1470 * For multifunction devices which are not isolated from each other, find
1471 * all the other non-isolated functions and look for existing groups. For
1472 * each function, we also need to look for aliases to or from other devices
1473 * that may already have a group.
1475 static struct iommu_group *get_pci_function_alias_group(struct pci_dev *pdev,
1476 unsigned long *devfns)
1478 struct pci_dev *tmp = NULL;
1479 struct iommu_group *group;
1481 if (!pdev->multifunction || pci_acs_enabled(pdev, REQ_ACS_FLAGS))
1484 for_each_pci_dev(tmp) {
1485 if (tmp == pdev || tmp->bus != pdev->bus ||
1486 PCI_SLOT(tmp->devfn) != PCI_SLOT(pdev->devfn) ||
1487 pci_acs_enabled(tmp, REQ_ACS_FLAGS))
1490 group = get_pci_alias_group(tmp, devfns);
1501 * Look for aliases to or from the given device for existing groups. DMA
1502 * aliases are only supported on the same bus, therefore the search
1503 * space is quite small (especially since we're really only looking at pcie
1504 * device, and therefore only expect multiple slots on the root complex or
1505 * downstream switch ports). It's conceivable though that a pair of
1506 * multifunction devices could have aliases between them that would cause a
1507 * loop. To prevent this, we use a bitmap to track where we've been.
1509 static struct iommu_group *get_pci_alias_group(struct pci_dev *pdev,
1510 unsigned long *devfns)
1512 struct pci_dev *tmp = NULL;
1513 struct iommu_group *group;
1515 if (test_and_set_bit(pdev->devfn & 0xff, devfns))
1518 group = iommu_group_get(&pdev->dev);
1522 for_each_pci_dev(tmp) {
1523 if (tmp == pdev || tmp->bus != pdev->bus)
1526 /* We alias them or they alias us */
1527 if (pci_devs_are_dma_aliases(pdev, tmp)) {
1528 group = get_pci_alias_group(tmp, devfns);
1534 group = get_pci_function_alias_group(tmp, devfns);
1545 struct group_for_pci_data {
1546 struct pci_dev *pdev;
1547 struct iommu_group *group;
1551 * DMA alias iterator callback, return the last seen device. Stop and return
1552 * the IOMMU group if we find one along the way.
1554 static int get_pci_alias_or_group(struct pci_dev *pdev, u16 alias, void *opaque)
1556 struct group_for_pci_data *data = opaque;
1559 data->group = iommu_group_get(&pdev->dev);
1561 return data->group != NULL;
1565 * Generic device_group call-back function. It just allocates one
1566 * iommu-group per device.
1568 struct iommu_group *generic_device_group(struct device *dev)
1570 return iommu_group_alloc();
1572 EXPORT_SYMBOL_GPL(generic_device_group);
1575 * Use standard PCI bus topology, isolation features, and DMA alias quirks
1576 * to find or create an IOMMU group for a device.
1578 struct iommu_group *pci_device_group(struct device *dev)
1580 struct pci_dev *pdev = to_pci_dev(dev);
1581 struct group_for_pci_data data;
1582 struct pci_bus *bus;
1583 struct iommu_group *group = NULL;
1584 u64 devfns[4] = { 0 };
1586 if (WARN_ON(!dev_is_pci(dev)))
1587 return ERR_PTR(-EINVAL);
1590 * Find the upstream DMA alias for the device. A device must not
1591 * be aliased due to topology in order to have its own IOMMU group.
1592 * If we find an alias along the way that already belongs to a
1595 if (pci_for_each_dma_alias(pdev, get_pci_alias_or_group, &data))
1601 * Continue upstream from the point of minimum IOMMU granularity
1602 * due to aliases to the point where devices are protected from
1603 * peer-to-peer DMA by PCI ACS. Again, if we find an existing
1606 for (bus = pdev->bus; !pci_is_root_bus(bus); bus = bus->parent) {
1610 if (pci_acs_path_enabled(bus->self, NULL, REQ_ACS_FLAGS))
1615 group = iommu_group_get(&pdev->dev);
1621 * Look for existing groups on device aliases. If we alias another
1622 * device or another device aliases us, use the same group.
1624 group = get_pci_alias_group(pdev, (unsigned long *)devfns);
1629 * Look for existing groups on non-isolated functions on the same
1630 * slot and aliases of those funcions, if any. No need to clear
1631 * the search bitmap, the tested devfns are still valid.
1633 group = get_pci_function_alias_group(pdev, (unsigned long *)devfns);
1637 /* No shared group found, allocate new */
1638 return iommu_group_alloc();
1640 EXPORT_SYMBOL_GPL(pci_device_group);
1642 /* Get the IOMMU group for device on fsl-mc bus */
1643 struct iommu_group *fsl_mc_device_group(struct device *dev)
1645 struct device *cont_dev = fsl_mc_cont_dev(dev);
1646 struct iommu_group *group;
1648 group = iommu_group_get(cont_dev);
1650 group = iommu_group_alloc();
1653 EXPORT_SYMBOL_GPL(fsl_mc_device_group);
1655 static int iommu_get_def_domain_type(struct device *dev)
1657 const struct iommu_ops *ops = dev_iommu_ops(dev);
1659 if (dev_is_pci(dev) && to_pci_dev(dev)->untrusted)
1660 return IOMMU_DOMAIN_DMA;
1662 if (ops->def_domain_type)
1663 return ops->def_domain_type(dev);
1668 static struct iommu_domain *
1669 __iommu_group_alloc_default_domain(const struct bus_type *bus,
1670 struct iommu_group *group, int req_type)
1672 if (group->default_domain && group->default_domain->type == req_type)
1673 return group->default_domain;
1674 return __iommu_domain_alloc(bus, req_type);
1678 * req_type of 0 means "auto" which means to select a domain based on
1679 * iommu_def_domain_type or what the driver actually supports.
1681 static struct iommu_domain *
1682 iommu_group_alloc_default_domain(struct iommu_group *group, int req_type)
1684 const struct bus_type *bus =
1685 list_first_entry(&group->devices, struct group_device, list)
1687 struct iommu_domain *dom;
1689 lockdep_assert_held(&group->mutex);
1692 return __iommu_group_alloc_default_domain(bus, group, req_type);
1694 /* The driver gave no guidance on what type to use, try the default */
1695 dom = __iommu_group_alloc_default_domain(bus, group, iommu_def_domain_type);
1699 /* Otherwise IDENTITY and DMA_FQ defaults will try DMA */
1700 if (iommu_def_domain_type == IOMMU_DOMAIN_DMA)
1702 dom = __iommu_group_alloc_default_domain(bus, group, IOMMU_DOMAIN_DMA);
1706 pr_warn("Failed to allocate default IOMMU domain of type %u for group %s - Falling back to IOMMU_DOMAIN_DMA",
1707 iommu_def_domain_type, group->name);
1712 * iommu_group_get_for_dev - Find or create the IOMMU group for a device
1713 * @dev: target device
1715 * This function is intended to be called by IOMMU drivers and extended to
1716 * support common, bus-defined algorithms when determining or creating the
1717 * IOMMU group for a device. On success, the caller will hold a reference
1718 * to the returned IOMMU group, which will already include the provided
1719 * device. The reference should be released with iommu_group_put().
1721 static struct iommu_group *iommu_group_get_for_dev(struct device *dev)
1723 const struct iommu_ops *ops = dev_iommu_ops(dev);
1724 struct iommu_group *group;
1727 group = iommu_group_get(dev);
1731 group = ops->device_group(dev);
1732 if (WARN_ON_ONCE(group == NULL))
1733 return ERR_PTR(-EINVAL);
1738 ret = iommu_group_add_device(group, dev);
1745 iommu_group_put(group);
1747 return ERR_PTR(ret);
1750 struct iommu_domain *iommu_group_default_domain(struct iommu_group *group)
1752 return group->default_domain;
1755 static int probe_iommu_group(struct device *dev, void *data)
1757 struct list_head *group_list = data;
1758 struct iommu_group *group;
1761 /* Device is probed already if in a group */
1762 group = iommu_group_get(dev);
1764 iommu_group_put(group);
1768 ret = __iommu_probe_device(dev, group_list);
1775 static int iommu_bus_notifier(struct notifier_block *nb,
1776 unsigned long action, void *data)
1778 struct device *dev = data;
1780 if (action == BUS_NOTIFY_ADD_DEVICE) {
1783 ret = iommu_probe_device(dev);
1784 return (ret) ? NOTIFY_DONE : NOTIFY_OK;
1785 } else if (action == BUS_NOTIFY_REMOVED_DEVICE) {
1786 iommu_release_device(dev);
1793 /* A target_type of 0 will select the best domain type and cannot fail */
1794 static int iommu_get_default_domain_type(struct iommu_group *group,
1797 int best_type = target_type;
1798 struct group_device *gdev;
1799 struct device *last_dev;
1801 lockdep_assert_held(&group->mutex);
1803 for_each_group_device(group, gdev) {
1804 unsigned int type = iommu_get_def_domain_type(gdev->dev);
1806 if (best_type && type && best_type != type) {
1808 dev_err_ratelimited(
1810 "Device cannot be in %s domain\n",
1811 iommu_domain_type_str(target_type));
1817 "Device needs domain type %s, but device %s in the same iommu group requires type %s - using default\n",
1818 iommu_domain_type_str(type), dev_name(last_dev),
1819 iommu_domain_type_str(best_type));
1824 last_dev = gdev->dev;
1829 static void iommu_group_do_probe_finalize(struct device *dev)
1831 const struct iommu_ops *ops = dev_iommu_ops(dev);
1833 if (ops->probe_finalize)
1834 ops->probe_finalize(dev);
1837 int bus_iommu_probe(const struct bus_type *bus)
1839 struct iommu_group *group, *next;
1840 LIST_HEAD(group_list);
1844 * This code-path does not allocate the default domain when
1845 * creating the iommu group, so do it after the groups are
1848 ret = bus_for_each_dev(bus, NULL, &group_list, probe_iommu_group);
1852 list_for_each_entry_safe(group, next, &group_list, entry) {
1853 struct group_device *gdev;
1855 mutex_lock(&group->mutex);
1857 /* Remove item from the list */
1858 list_del_init(&group->entry);
1860 ret = iommu_setup_default_domain(group, 0);
1862 mutex_unlock(&group->mutex);
1865 mutex_unlock(&group->mutex);
1868 * FIXME: Mis-locked because the ops->probe_finalize() call-back
1869 * of some IOMMU drivers calls arm_iommu_attach_device() which
1870 * in-turn might call back into IOMMU core code, where it tries
1871 * to take group->mutex, resulting in a deadlock.
1873 for_each_group_device(group, gdev)
1874 iommu_group_do_probe_finalize(gdev->dev);
1880 bool iommu_present(const struct bus_type *bus)
1882 return bus->iommu_ops != NULL;
1884 EXPORT_SYMBOL_GPL(iommu_present);
1887 * device_iommu_capable() - check for a general IOMMU capability
1888 * @dev: device to which the capability would be relevant, if available
1889 * @cap: IOMMU capability
1891 * Return: true if an IOMMU is present and supports the given capability
1892 * for the given device, otherwise false.
1894 bool device_iommu_capable(struct device *dev, enum iommu_cap cap)
1896 const struct iommu_ops *ops;
1898 if (!dev->iommu || !dev->iommu->iommu_dev)
1901 ops = dev_iommu_ops(dev);
1905 return ops->capable(dev, cap);
1907 EXPORT_SYMBOL_GPL(device_iommu_capable);
1910 * iommu_group_has_isolated_msi() - Compute msi_device_has_isolated_msi()
1912 * @group: Group to query
1914 * IOMMU groups should not have differing values of
1915 * msi_device_has_isolated_msi() for devices in a group. However nothing
1916 * directly prevents this, so ensure mistakes don't result in isolation failures
1917 * by checking that all the devices are the same.
1919 bool iommu_group_has_isolated_msi(struct iommu_group *group)
1921 struct group_device *group_dev;
1924 mutex_lock(&group->mutex);
1925 for_each_group_device(group, group_dev)
1926 ret &= msi_device_has_isolated_msi(group_dev->dev);
1927 mutex_unlock(&group->mutex);
1930 EXPORT_SYMBOL_GPL(iommu_group_has_isolated_msi);
1933 * iommu_set_fault_handler() - set a fault handler for an iommu domain
1934 * @domain: iommu domain
1935 * @handler: fault handler
1936 * @token: user data, will be passed back to the fault handler
1938 * This function should be used by IOMMU users which want to be notified
1939 * whenever an IOMMU fault happens.
1941 * The fault handler itself should return 0 on success, and an appropriate
1942 * error code otherwise.
1944 void iommu_set_fault_handler(struct iommu_domain *domain,
1945 iommu_fault_handler_t handler,
1950 domain->handler = handler;
1951 domain->handler_token = token;
1953 EXPORT_SYMBOL_GPL(iommu_set_fault_handler);
1955 static struct iommu_domain *__iommu_domain_alloc(const struct bus_type *bus,
1958 struct iommu_domain *domain;
1959 unsigned int alloc_type = type & IOMMU_DOMAIN_ALLOC_FLAGS;
1961 if (bus == NULL || bus->iommu_ops == NULL)
1964 domain = bus->iommu_ops->domain_alloc(alloc_type);
1968 domain->type = type;
1970 * If not already set, assume all sizes by default; the driver
1971 * may override this later
1973 if (!domain->pgsize_bitmap)
1974 domain->pgsize_bitmap = bus->iommu_ops->pgsize_bitmap;
1977 domain->ops = bus->iommu_ops->default_domain_ops;
1979 if (iommu_is_dma_domain(domain) && iommu_get_dma_cookie(domain)) {
1980 iommu_domain_free(domain);
1986 struct iommu_domain *iommu_domain_alloc(const struct bus_type *bus)
1988 return __iommu_domain_alloc(bus, IOMMU_DOMAIN_UNMANAGED);
1990 EXPORT_SYMBOL_GPL(iommu_domain_alloc);
1992 void iommu_domain_free(struct iommu_domain *domain)
1994 if (domain->type == IOMMU_DOMAIN_SVA)
1996 iommu_put_dma_cookie(domain);
1997 domain->ops->free(domain);
1999 EXPORT_SYMBOL_GPL(iommu_domain_free);
2002 * Put the group's domain back to the appropriate core-owned domain - either the
2003 * standard kernel-mode DMA configuration or an all-DMA-blocked domain.
2005 static void __iommu_group_set_core_domain(struct iommu_group *group)
2007 struct iommu_domain *new_domain;
2010 new_domain = group->blocking_domain;
2012 new_domain = group->default_domain;
2014 __iommu_group_set_domain_nofail(group, new_domain);
2017 static int __iommu_attach_device(struct iommu_domain *domain,
2022 if (unlikely(domain->ops->attach_dev == NULL))
2025 ret = domain->ops->attach_dev(domain, dev);
2028 dev->iommu->attach_deferred = 0;
2029 trace_attach_device_to_domain(dev);
2034 * iommu_attach_device - Attach an IOMMU domain to a device
2035 * @domain: IOMMU domain to attach
2036 * @dev: Device that will be attached
2038 * Returns 0 on success and error code on failure
2040 * Note that EINVAL can be treated as a soft failure, indicating
2041 * that certain configuration of the domain is incompatible with
2042 * the device. In this case attaching a different domain to the
2043 * device may succeed.
2045 int iommu_attach_device(struct iommu_domain *domain, struct device *dev)
2047 struct iommu_group *group;
2050 group = iommu_group_get(dev);
2055 * Lock the group to make sure the device-count doesn't
2056 * change while we are attaching
2058 mutex_lock(&group->mutex);
2060 if (list_count_nodes(&group->devices) != 1)
2063 ret = __iommu_attach_group(domain, group);
2066 mutex_unlock(&group->mutex);
2067 iommu_group_put(group);
2071 EXPORT_SYMBOL_GPL(iommu_attach_device);
2073 int iommu_deferred_attach(struct device *dev, struct iommu_domain *domain)
2075 if (dev->iommu && dev->iommu->attach_deferred)
2076 return __iommu_attach_device(domain, dev);
2081 void iommu_detach_device(struct iommu_domain *domain, struct device *dev)
2083 struct iommu_group *group;
2085 group = iommu_group_get(dev);
2089 mutex_lock(&group->mutex);
2090 if (WARN_ON(domain != group->domain) ||
2091 WARN_ON(list_count_nodes(&group->devices) != 1))
2093 __iommu_group_set_core_domain(group);
2096 mutex_unlock(&group->mutex);
2097 iommu_group_put(group);
2099 EXPORT_SYMBOL_GPL(iommu_detach_device);
2101 struct iommu_domain *iommu_get_domain_for_dev(struct device *dev)
2103 struct iommu_domain *domain;
2104 struct iommu_group *group;
2106 group = iommu_group_get(dev);
2110 domain = group->domain;
2112 iommu_group_put(group);
2116 EXPORT_SYMBOL_GPL(iommu_get_domain_for_dev);
2119 * For IOMMU_DOMAIN_DMA implementations which already provide their own
2120 * guarantees that the group and its default domain are valid and correct.
2122 struct iommu_domain *iommu_get_dma_domain(struct device *dev)
2124 return dev->iommu_group->default_domain;
2127 static int __iommu_attach_group(struct iommu_domain *domain,
2128 struct iommu_group *group)
2130 if (group->domain && group->domain != group->default_domain &&
2131 group->domain != group->blocking_domain)
2134 return __iommu_group_set_domain(group, domain);
2138 * iommu_attach_group - Attach an IOMMU domain to an IOMMU group
2139 * @domain: IOMMU domain to attach
2140 * @group: IOMMU group that will be attached
2142 * Returns 0 on success and error code on failure
2144 * Note that EINVAL can be treated as a soft failure, indicating
2145 * that certain configuration of the domain is incompatible with
2146 * the group. In this case attaching a different domain to the
2147 * group may succeed.
2149 int iommu_attach_group(struct iommu_domain *domain, struct iommu_group *group)
2153 mutex_lock(&group->mutex);
2154 ret = __iommu_attach_group(domain, group);
2155 mutex_unlock(&group->mutex);
2159 EXPORT_SYMBOL_GPL(iommu_attach_group);
2162 * iommu_group_replace_domain - replace the domain that a group is attached to
2163 * @new_domain: new IOMMU domain to replace with
2164 * @group: IOMMU group that will be attached to the new domain
2166 * This API allows the group to switch domains without being forced to go to
2167 * the blocking domain in-between.
2169 * If the currently attached domain is a core domain (e.g. a default_domain),
2170 * it will act just like the iommu_attach_group().
2172 int iommu_group_replace_domain(struct iommu_group *group,
2173 struct iommu_domain *new_domain)
2180 mutex_lock(&group->mutex);
2181 ret = __iommu_group_set_domain(group, new_domain);
2182 mutex_unlock(&group->mutex);
2185 EXPORT_SYMBOL_NS_GPL(iommu_group_replace_domain, IOMMUFD_INTERNAL);
2187 static int __iommu_device_set_domain(struct iommu_group *group,
2189 struct iommu_domain *new_domain,
2194 if (dev->iommu->attach_deferred) {
2195 if (new_domain == group->default_domain)
2197 dev->iommu->attach_deferred = 0;
2200 ret = __iommu_attach_device(new_domain, dev);
2203 * If we have a blocking domain then try to attach that in hopes
2204 * of avoiding a UAF. Modern drivers should implement blocking
2205 * domains as global statics that cannot fail.
2207 if ((flags & IOMMU_SET_DOMAIN_MUST_SUCCEED) &&
2208 group->blocking_domain &&
2209 group->blocking_domain != new_domain)
2210 __iommu_attach_device(group->blocking_domain, dev);
2217 * If 0 is returned the group's domain is new_domain. If an error is returned
2218 * then the group's domain will be set back to the existing domain unless
2219 * IOMMU_SET_DOMAIN_MUST_SUCCEED, otherwise an error is returned and the group's
2220 * domains is left inconsistent. This is a driver bug to fail attach with a
2221 * previously good domain. We try to avoid a kernel UAF because of this.
2223 * IOMMU groups are really the natural working unit of the IOMMU, but the IOMMU
2224 * API works on domains and devices. Bridge that gap by iterating over the
2225 * devices in a group. Ideally we'd have a single device which represents the
2226 * requestor ID of the group, but we also allow IOMMU drivers to create policy
2227 * defined minimum sets, where the physical hardware may be able to distiguish
2228 * members, but we wish to group them at a higher level (ex. untrusted
2229 * multi-function PCI devices). Thus we attach each device.
2231 static int __iommu_group_set_domain_internal(struct iommu_group *group,
2232 struct iommu_domain *new_domain,
2235 struct group_device *last_gdev;
2236 struct group_device *gdev;
2240 lockdep_assert_held(&group->mutex);
2242 if (group->domain == new_domain)
2246 * New drivers should support default domains, so set_platform_dma()
2247 * op will never be called. Otherwise the NULL domain represents some
2248 * platform specific behavior.
2251 for_each_group_device(group, gdev) {
2252 const struct iommu_ops *ops = dev_iommu_ops(gdev->dev);
2254 if (!WARN_ON(!ops->set_platform_dma_ops))
2255 ops->set_platform_dma_ops(gdev->dev);
2257 group->domain = NULL;
2262 * Changing the domain is done by calling attach_dev() on the new
2263 * domain. This switch does not have to be atomic and DMA can be
2264 * discarded during the transition. DMA must only be able to access
2265 * either new_domain or group->domain, never something else.
2268 for_each_group_device(group, gdev) {
2269 ret = __iommu_device_set_domain(group, gdev->dev, new_domain,
2274 * Keep trying the other devices in the group. If a
2275 * driver fails attach to an otherwise good domain, and
2276 * does not support blocking domains, it should at least
2277 * drop its reference on the current domain so we don't
2280 if (flags & IOMMU_SET_DOMAIN_MUST_SUCCEED)
2285 group->domain = new_domain;
2290 * This is called in error unwind paths. A well behaved driver should
2291 * always allow us to attach to a domain that was already attached.
2294 for_each_group_device(group, gdev) {
2295 const struct iommu_ops *ops = dev_iommu_ops(gdev->dev);
2298 * If set_platform_dma_ops is not present a NULL domain can
2299 * happen only for first probe, in which case we leave
2300 * group->domain as NULL and let release clean everything up.
2303 WARN_ON(__iommu_device_set_domain(
2304 group, gdev->dev, group->domain,
2305 IOMMU_SET_DOMAIN_MUST_SUCCEED));
2306 else if (ops->set_platform_dma_ops)
2307 ops->set_platform_dma_ops(gdev->dev);
2308 if (gdev == last_gdev)
2314 void iommu_detach_group(struct iommu_domain *domain, struct iommu_group *group)
2316 mutex_lock(&group->mutex);
2317 __iommu_group_set_core_domain(group);
2318 mutex_unlock(&group->mutex);
2320 EXPORT_SYMBOL_GPL(iommu_detach_group);
2322 phys_addr_t iommu_iova_to_phys(struct iommu_domain *domain, dma_addr_t iova)
2324 if (domain->type == IOMMU_DOMAIN_IDENTITY)
2327 if (domain->type == IOMMU_DOMAIN_BLOCKED)
2330 return domain->ops->iova_to_phys(domain, iova);
2332 EXPORT_SYMBOL_GPL(iommu_iova_to_phys);
2334 static size_t iommu_pgsize(struct iommu_domain *domain, unsigned long iova,
2335 phys_addr_t paddr, size_t size, size_t *count)
2337 unsigned int pgsize_idx, pgsize_idx_next;
2338 unsigned long pgsizes;
2339 size_t offset, pgsize, pgsize_next;
2340 unsigned long addr_merge = paddr | iova;
2342 /* Page sizes supported by the hardware and small enough for @size */
2343 pgsizes = domain->pgsize_bitmap & GENMASK(__fls(size), 0);
2345 /* Constrain the page sizes further based on the maximum alignment */
2346 if (likely(addr_merge))
2347 pgsizes &= GENMASK(__ffs(addr_merge), 0);
2349 /* Make sure we have at least one suitable page size */
2352 /* Pick the biggest page size remaining */
2353 pgsize_idx = __fls(pgsizes);
2354 pgsize = BIT(pgsize_idx);
2358 /* Find the next biggest support page size, if it exists */
2359 pgsizes = domain->pgsize_bitmap & ~GENMASK(pgsize_idx, 0);
2363 pgsize_idx_next = __ffs(pgsizes);
2364 pgsize_next = BIT(pgsize_idx_next);
2367 * There's no point trying a bigger page size unless the virtual
2368 * and physical addresses are similarly offset within the larger page.
2370 if ((iova ^ paddr) & (pgsize_next - 1))
2373 /* Calculate the offset to the next page size alignment boundary */
2374 offset = pgsize_next - (addr_merge & (pgsize_next - 1));
2377 * If size is big enough to accommodate the larger page, reduce
2378 * the number of smaller pages.
2380 if (offset + pgsize_next <= size)
2384 *count = size >> pgsize_idx;
2388 static int __iommu_map_pages(struct iommu_domain *domain, unsigned long iova,
2389 phys_addr_t paddr, size_t size, int prot,
2390 gfp_t gfp, size_t *mapped)
2392 const struct iommu_domain_ops *ops = domain->ops;
2393 size_t pgsize, count;
2396 pgsize = iommu_pgsize(domain, iova, paddr, size, &count);
2398 pr_debug("mapping: iova 0x%lx pa %pa pgsize 0x%zx count %zu\n",
2399 iova, &paddr, pgsize, count);
2401 if (ops->map_pages) {
2402 ret = ops->map_pages(domain, iova, paddr, pgsize, count, prot,
2405 ret = ops->map(domain, iova, paddr, pgsize, prot, gfp);
2406 *mapped = ret ? 0 : pgsize;
2412 static int __iommu_map(struct iommu_domain *domain, unsigned long iova,
2413 phys_addr_t paddr, size_t size, int prot, gfp_t gfp)
2415 const struct iommu_domain_ops *ops = domain->ops;
2416 unsigned long orig_iova = iova;
2417 unsigned int min_pagesz;
2418 size_t orig_size = size;
2419 phys_addr_t orig_paddr = paddr;
2422 if (unlikely(!(ops->map || ops->map_pages) ||
2423 domain->pgsize_bitmap == 0UL))
2426 if (unlikely(!(domain->type & __IOMMU_DOMAIN_PAGING)))
2429 /* find out the minimum page size supported */
2430 min_pagesz = 1 << __ffs(domain->pgsize_bitmap);
2433 * both the virtual address and the physical one, as well as
2434 * the size of the mapping, must be aligned (at least) to the
2435 * size of the smallest page supported by the hardware
2437 if (!IS_ALIGNED(iova | paddr | size, min_pagesz)) {
2438 pr_err("unaligned: iova 0x%lx pa %pa size 0x%zx min_pagesz 0x%x\n",
2439 iova, &paddr, size, min_pagesz);
2443 pr_debug("map: iova 0x%lx pa %pa size 0x%zx\n", iova, &paddr, size);
2448 ret = __iommu_map_pages(domain, iova, paddr, size, prot, gfp,
2451 * Some pages may have been mapped, even if an error occurred,
2452 * so we should account for those so they can be unmapped.
2463 /* unroll mapping in case something went wrong */
2465 iommu_unmap(domain, orig_iova, orig_size - size);
2467 trace_map(orig_iova, orig_paddr, orig_size);
2472 int iommu_map(struct iommu_domain *domain, unsigned long iova,
2473 phys_addr_t paddr, size_t size, int prot, gfp_t gfp)
2475 const struct iommu_domain_ops *ops = domain->ops;
2478 might_sleep_if(gfpflags_allow_blocking(gfp));
2480 /* Discourage passing strange GFP flags */
2481 if (WARN_ON_ONCE(gfp & (__GFP_COMP | __GFP_DMA | __GFP_DMA32 |
2485 ret = __iommu_map(domain, iova, paddr, size, prot, gfp);
2486 if (ret == 0 && ops->iotlb_sync_map)
2487 ops->iotlb_sync_map(domain, iova, size);
2491 EXPORT_SYMBOL_GPL(iommu_map);
2493 static size_t __iommu_unmap_pages(struct iommu_domain *domain,
2494 unsigned long iova, size_t size,
2495 struct iommu_iotlb_gather *iotlb_gather)
2497 const struct iommu_domain_ops *ops = domain->ops;
2498 size_t pgsize, count;
2500 pgsize = iommu_pgsize(domain, iova, iova, size, &count);
2501 return ops->unmap_pages ?
2502 ops->unmap_pages(domain, iova, pgsize, count, iotlb_gather) :
2503 ops->unmap(domain, iova, pgsize, iotlb_gather);
2506 static size_t __iommu_unmap(struct iommu_domain *domain,
2507 unsigned long iova, size_t size,
2508 struct iommu_iotlb_gather *iotlb_gather)
2510 const struct iommu_domain_ops *ops = domain->ops;
2511 size_t unmapped_page, unmapped = 0;
2512 unsigned long orig_iova = iova;
2513 unsigned int min_pagesz;
2515 if (unlikely(!(ops->unmap || ops->unmap_pages) ||
2516 domain->pgsize_bitmap == 0UL))
2519 if (unlikely(!(domain->type & __IOMMU_DOMAIN_PAGING)))
2522 /* find out the minimum page size supported */
2523 min_pagesz = 1 << __ffs(domain->pgsize_bitmap);
2526 * The virtual address, as well as the size of the mapping, must be
2527 * aligned (at least) to the size of the smallest page supported
2530 if (!IS_ALIGNED(iova | size, min_pagesz)) {
2531 pr_err("unaligned: iova 0x%lx size 0x%zx min_pagesz 0x%x\n",
2532 iova, size, min_pagesz);
2536 pr_debug("unmap this: iova 0x%lx size 0x%zx\n", iova, size);
2539 * Keep iterating until we either unmap 'size' bytes (or more)
2540 * or we hit an area that isn't mapped.
2542 while (unmapped < size) {
2543 unmapped_page = __iommu_unmap_pages(domain, iova,
2549 pr_debug("unmapped: iova 0x%lx size 0x%zx\n",
2550 iova, unmapped_page);
2552 iova += unmapped_page;
2553 unmapped += unmapped_page;
2556 trace_unmap(orig_iova, size, unmapped);
2560 size_t iommu_unmap(struct iommu_domain *domain,
2561 unsigned long iova, size_t size)
2563 struct iommu_iotlb_gather iotlb_gather;
2566 iommu_iotlb_gather_init(&iotlb_gather);
2567 ret = __iommu_unmap(domain, iova, size, &iotlb_gather);
2568 iommu_iotlb_sync(domain, &iotlb_gather);
2572 EXPORT_SYMBOL_GPL(iommu_unmap);
2574 size_t iommu_unmap_fast(struct iommu_domain *domain,
2575 unsigned long iova, size_t size,
2576 struct iommu_iotlb_gather *iotlb_gather)
2578 return __iommu_unmap(domain, iova, size, iotlb_gather);
2580 EXPORT_SYMBOL_GPL(iommu_unmap_fast);
2582 ssize_t iommu_map_sg(struct iommu_domain *domain, unsigned long iova,
2583 struct scatterlist *sg, unsigned int nents, int prot,
2586 const struct iommu_domain_ops *ops = domain->ops;
2587 size_t len = 0, mapped = 0;
2592 might_sleep_if(gfpflags_allow_blocking(gfp));
2594 /* Discourage passing strange GFP flags */
2595 if (WARN_ON_ONCE(gfp & (__GFP_COMP | __GFP_DMA | __GFP_DMA32 |
2599 while (i <= nents) {
2600 phys_addr_t s_phys = sg_phys(sg);
2602 if (len && s_phys != start + len) {
2603 ret = __iommu_map(domain, iova + mapped, start,
2613 if (sg_dma_is_bus_address(sg))
2628 if (ops->iotlb_sync_map)
2629 ops->iotlb_sync_map(domain, iova, mapped);
2633 /* undo mappings already done */
2634 iommu_unmap(domain, iova, mapped);
2638 EXPORT_SYMBOL_GPL(iommu_map_sg);
2641 * report_iommu_fault() - report about an IOMMU fault to the IOMMU framework
2642 * @domain: the iommu domain where the fault has happened
2643 * @dev: the device where the fault has happened
2644 * @iova: the faulting address
2645 * @flags: mmu fault flags (e.g. IOMMU_FAULT_READ/IOMMU_FAULT_WRITE/...)
2647 * This function should be called by the low-level IOMMU implementations
2648 * whenever IOMMU faults happen, to allow high-level users, that are
2649 * interested in such events, to know about them.
2651 * This event may be useful for several possible use cases:
2652 * - mere logging of the event
2653 * - dynamic TLB/PTE loading
2654 * - if restarting of the faulting device is required
2656 * Returns 0 on success and an appropriate error code otherwise (if dynamic
2657 * PTE/TLB loading will one day be supported, implementations will be able
2658 * to tell whether it succeeded or not according to this return value).
2660 * Specifically, -ENOSYS is returned if a fault handler isn't installed
2661 * (though fault handlers can also return -ENOSYS, in case they want to
2662 * elicit the default behavior of the IOMMU drivers).
2664 int report_iommu_fault(struct iommu_domain *domain, struct device *dev,
2665 unsigned long iova, int flags)
2670 * if upper layers showed interest and installed a fault handler,
2673 if (domain->handler)
2674 ret = domain->handler(domain, dev, iova, flags,
2675 domain->handler_token);
2677 trace_io_page_fault(dev, iova, flags);
2680 EXPORT_SYMBOL_GPL(report_iommu_fault);
2682 static int __init iommu_init(void)
2684 iommu_group_kset = kset_create_and_add("iommu_groups",
2686 BUG_ON(!iommu_group_kset);
2688 iommu_debugfs_setup();
2692 core_initcall(iommu_init);
2694 int iommu_enable_nesting(struct iommu_domain *domain)
2696 if (domain->type != IOMMU_DOMAIN_UNMANAGED)
2698 if (!domain->ops->enable_nesting)
2700 return domain->ops->enable_nesting(domain);
2702 EXPORT_SYMBOL_GPL(iommu_enable_nesting);
2704 int iommu_set_pgtable_quirks(struct iommu_domain *domain,
2705 unsigned long quirk)
2707 if (domain->type != IOMMU_DOMAIN_UNMANAGED)
2709 if (!domain->ops->set_pgtable_quirks)
2711 return domain->ops->set_pgtable_quirks(domain, quirk);
2713 EXPORT_SYMBOL_GPL(iommu_set_pgtable_quirks);
2716 * iommu_get_resv_regions - get reserved regions
2717 * @dev: device for which to get reserved regions
2718 * @list: reserved region list for device
2720 * This returns a list of reserved IOVA regions specific to this device.
2721 * A domain user should not map IOVA in these ranges.
2723 void iommu_get_resv_regions(struct device *dev, struct list_head *list)
2725 const struct iommu_ops *ops = dev_iommu_ops(dev);
2727 if (ops->get_resv_regions)
2728 ops->get_resv_regions(dev, list);
2730 EXPORT_SYMBOL_GPL(iommu_get_resv_regions);
2733 * iommu_put_resv_regions - release reserved regions
2734 * @dev: device for which to free reserved regions
2735 * @list: reserved region list for device
2737 * This releases a reserved region list acquired by iommu_get_resv_regions().
2739 void iommu_put_resv_regions(struct device *dev, struct list_head *list)
2741 struct iommu_resv_region *entry, *next;
2743 list_for_each_entry_safe(entry, next, list, list) {
2745 entry->free(dev, entry);
2750 EXPORT_SYMBOL(iommu_put_resv_regions);
2752 struct iommu_resv_region *iommu_alloc_resv_region(phys_addr_t start,
2753 size_t length, int prot,
2754 enum iommu_resv_type type,
2757 struct iommu_resv_region *region;
2759 region = kzalloc(sizeof(*region), gfp);
2763 INIT_LIST_HEAD(®ion->list);
2764 region->start = start;
2765 region->length = length;
2766 region->prot = prot;
2767 region->type = type;
2770 EXPORT_SYMBOL_GPL(iommu_alloc_resv_region);
2772 void iommu_set_default_passthrough(bool cmd_line)
2775 iommu_cmd_line |= IOMMU_CMD_LINE_DMA_API;
2776 iommu_def_domain_type = IOMMU_DOMAIN_IDENTITY;
2779 void iommu_set_default_translated(bool cmd_line)
2782 iommu_cmd_line |= IOMMU_CMD_LINE_DMA_API;
2783 iommu_def_domain_type = IOMMU_DOMAIN_DMA;
2786 bool iommu_default_passthrough(void)
2788 return iommu_def_domain_type == IOMMU_DOMAIN_IDENTITY;
2790 EXPORT_SYMBOL_GPL(iommu_default_passthrough);
2792 const struct iommu_ops *iommu_ops_from_fwnode(struct fwnode_handle *fwnode)
2794 const struct iommu_ops *ops = NULL;
2795 struct iommu_device *iommu;
2797 spin_lock(&iommu_device_lock);
2798 list_for_each_entry(iommu, &iommu_device_list, list)
2799 if (iommu->fwnode == fwnode) {
2803 spin_unlock(&iommu_device_lock);
2807 int iommu_fwspec_init(struct device *dev, struct fwnode_handle *iommu_fwnode,
2808 const struct iommu_ops *ops)
2810 struct iommu_fwspec *fwspec = dev_iommu_fwspec_get(dev);
2813 return ops == fwspec->ops ? 0 : -EINVAL;
2815 if (!dev_iommu_get(dev))
2818 /* Preallocate for the overwhelmingly common case of 1 ID */
2819 fwspec = kzalloc(struct_size(fwspec, ids, 1), GFP_KERNEL);
2823 of_node_get(to_of_node(iommu_fwnode));
2824 fwspec->iommu_fwnode = iommu_fwnode;
2826 dev_iommu_fwspec_set(dev, fwspec);
2829 EXPORT_SYMBOL_GPL(iommu_fwspec_init);
2831 void iommu_fwspec_free(struct device *dev)
2833 struct iommu_fwspec *fwspec = dev_iommu_fwspec_get(dev);
2836 fwnode_handle_put(fwspec->iommu_fwnode);
2838 dev_iommu_fwspec_set(dev, NULL);
2841 EXPORT_SYMBOL_GPL(iommu_fwspec_free);
2843 int iommu_fwspec_add_ids(struct device *dev, u32 *ids, int num_ids)
2845 struct iommu_fwspec *fwspec = dev_iommu_fwspec_get(dev);
2851 new_num = fwspec->num_ids + num_ids;
2853 fwspec = krealloc(fwspec, struct_size(fwspec, ids, new_num),
2858 dev_iommu_fwspec_set(dev, fwspec);
2861 for (i = 0; i < num_ids; i++)
2862 fwspec->ids[fwspec->num_ids + i] = ids[i];
2864 fwspec->num_ids = new_num;
2867 EXPORT_SYMBOL_GPL(iommu_fwspec_add_ids);
2870 * Per device IOMMU features.
2872 int iommu_dev_enable_feature(struct device *dev, enum iommu_dev_features feat)
2874 if (dev->iommu && dev->iommu->iommu_dev) {
2875 const struct iommu_ops *ops = dev->iommu->iommu_dev->ops;
2877 if (ops->dev_enable_feat)
2878 return ops->dev_enable_feat(dev, feat);
2883 EXPORT_SYMBOL_GPL(iommu_dev_enable_feature);
2886 * The device drivers should do the necessary cleanups before calling this.
2888 int iommu_dev_disable_feature(struct device *dev, enum iommu_dev_features feat)
2890 if (dev->iommu && dev->iommu->iommu_dev) {
2891 const struct iommu_ops *ops = dev->iommu->iommu_dev->ops;
2893 if (ops->dev_disable_feat)
2894 return ops->dev_disable_feat(dev, feat);
2899 EXPORT_SYMBOL_GPL(iommu_dev_disable_feature);
2902 * iommu_setup_default_domain - Set the default_domain for the group
2903 * @group: Group to change
2904 * @target_type: Domain type to set as the default_domain
2906 * Allocate a default domain and set it as the current domain on the group. If
2907 * the group already has a default domain it will be changed to the target_type.
2908 * When target_type is 0 the default domain is selected based on driver and
2909 * system preferences.
2911 static int iommu_setup_default_domain(struct iommu_group *group,
2914 struct iommu_domain *old_dom = group->default_domain;
2915 struct group_device *gdev;
2916 struct iommu_domain *dom;
2921 lockdep_assert_held(&group->mutex);
2923 req_type = iommu_get_default_domain_type(group, target_type);
2928 * There are still some drivers which don't support default domains, so
2929 * we ignore the failure and leave group->default_domain NULL.
2931 * We assume that the iommu driver starts up the device in
2932 * 'set_platform_dma_ops' mode if it does not support default domains.
2934 dom = iommu_group_alloc_default_domain(group, req_type);
2936 /* Once in default_domain mode we never leave */
2937 if (group->default_domain)
2939 group->default_domain = NULL;
2943 if (group->default_domain == dom)
2947 * IOMMU_RESV_DIRECT and IOMMU_RESV_DIRECT_RELAXABLE regions must be
2948 * mapped before their device is attached, in order to guarantee
2949 * continuity with any FW activity
2951 direct_failed = false;
2952 for_each_group_device(group, gdev) {
2953 if (iommu_create_device_direct_mappings(dom, gdev->dev)) {
2954 direct_failed = true;
2956 gdev->dev->iommu->iommu_dev->dev,
2957 "IOMMU driver was not able to establish FW requested direct mapping.");
2961 /* We must set default_domain early for __iommu_device_set_domain */
2962 group->default_domain = dom;
2963 if (!group->domain) {
2965 * Drivers are not allowed to fail the first domain attach.
2966 * The only way to recover from this is to fail attaching the
2967 * iommu driver and call ops->release_device. Put the domain
2968 * in group->default_domain so it is freed after.
2970 ret = __iommu_group_set_domain_internal(
2971 group, dom, IOMMU_SET_DOMAIN_MUST_SUCCEED);
2975 ret = __iommu_group_set_domain(group, dom);
2977 goto err_restore_def_domain;
2981 * Drivers are supposed to allow mappings to be installed in a domain
2982 * before device attachment, but some don't. Hack around this defect by
2983 * trying again after attaching. If this happens it means the device
2984 * will not continuously have the IOMMU_RESV_DIRECT map.
2986 if (direct_failed) {
2987 for_each_group_device(group, gdev) {
2988 ret = iommu_create_device_direct_mappings(dom, gdev->dev);
2990 goto err_restore_domain;
2996 iommu_domain_free(old_dom);
3001 __iommu_group_set_domain_internal(
3002 group, old_dom, IOMMU_SET_DOMAIN_MUST_SUCCEED);
3003 err_restore_def_domain:
3005 iommu_domain_free(dom);
3006 group->default_domain = old_dom;
3012 * Changing the default domain through sysfs requires the users to unbind the
3013 * drivers from the devices in the iommu group, except for a DMA -> DMA-FQ
3014 * transition. Return failure if this isn't met.
3016 * We need to consider the race between this and the device release path.
3017 * group->mutex is used here to guarantee that the device release path
3018 * will not be entered at the same time.
3020 static ssize_t iommu_group_store_type(struct iommu_group *group,
3021 const char *buf, size_t count)
3023 struct group_device *gdev;
3026 if (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO))
3029 if (WARN_ON(!group) || !group->default_domain)
3032 if (sysfs_streq(buf, "identity"))
3033 req_type = IOMMU_DOMAIN_IDENTITY;
3034 else if (sysfs_streq(buf, "DMA"))
3035 req_type = IOMMU_DOMAIN_DMA;
3036 else if (sysfs_streq(buf, "DMA-FQ"))
3037 req_type = IOMMU_DOMAIN_DMA_FQ;
3038 else if (sysfs_streq(buf, "auto"))
3043 mutex_lock(&group->mutex);
3044 /* We can bring up a flush queue without tearing down the domain. */
3045 if (req_type == IOMMU_DOMAIN_DMA_FQ &&
3046 group->default_domain->type == IOMMU_DOMAIN_DMA) {
3047 ret = iommu_dma_init_fq(group->default_domain);
3051 group->default_domain->type = IOMMU_DOMAIN_DMA_FQ;
3056 /* Otherwise, ensure that device exists and no driver is bound. */
3057 if (list_empty(&group->devices) || group->owner_cnt) {
3062 ret = iommu_setup_default_domain(group, req_type);
3067 * Release the mutex here because ops->probe_finalize() call-back of
3068 * some vendor IOMMU drivers calls arm_iommu_attach_device() which
3069 * in-turn might call back into IOMMU core code, where it tries to take
3070 * group->mutex, resulting in a deadlock.
3072 mutex_unlock(&group->mutex);
3074 /* Make sure dma_ops is appropriatley set */
3075 for_each_group_device(group, gdev)
3076 iommu_group_do_probe_finalize(gdev->dev);
3080 mutex_unlock(&group->mutex);
3081 return ret ?: count;
3084 static bool iommu_is_default_domain(struct iommu_group *group)
3086 if (group->domain == group->default_domain)
3090 * If the default domain was set to identity and it is still an identity
3091 * domain then we consider this a pass. This happens because of
3092 * amd_iommu_init_device() replacing the default idenytity domain with an
3093 * identity domain that has a different configuration for AMDGPU.
3095 if (group->default_domain &&
3096 group->default_domain->type == IOMMU_DOMAIN_IDENTITY &&
3097 group->domain && group->domain->type == IOMMU_DOMAIN_IDENTITY)
3103 * iommu_device_use_default_domain() - Device driver wants to handle device
3104 * DMA through the kernel DMA API.
3107 * The device driver about to bind @dev wants to do DMA through the kernel
3108 * DMA API. Return 0 if it is allowed, otherwise an error.
3110 int iommu_device_use_default_domain(struct device *dev)
3112 struct iommu_group *group = iommu_group_get(dev);
3118 mutex_lock(&group->mutex);
3119 if (group->owner_cnt) {
3120 if (group->owner || !iommu_is_default_domain(group) ||
3121 !xa_empty(&group->pasid_array)) {
3130 mutex_unlock(&group->mutex);
3131 iommu_group_put(group);
3137 * iommu_device_unuse_default_domain() - Device driver stops handling device
3138 * DMA through the kernel DMA API.
3141 * The device driver doesn't want to do DMA through kernel DMA API anymore.
3142 * It must be called after iommu_device_use_default_domain().
3144 void iommu_device_unuse_default_domain(struct device *dev)
3146 struct iommu_group *group = iommu_group_get(dev);
3151 mutex_lock(&group->mutex);
3152 if (!WARN_ON(!group->owner_cnt || !xa_empty(&group->pasid_array)))
3155 mutex_unlock(&group->mutex);
3156 iommu_group_put(group);
3159 static int __iommu_group_alloc_blocking_domain(struct iommu_group *group)
3161 struct group_device *dev =
3162 list_first_entry(&group->devices, struct group_device, list);
3164 if (group->blocking_domain)
3167 group->blocking_domain =
3168 __iommu_domain_alloc(dev->dev->bus, IOMMU_DOMAIN_BLOCKED);
3169 if (!group->blocking_domain) {
3171 * For drivers that do not yet understand IOMMU_DOMAIN_BLOCKED
3172 * create an empty domain instead.
3174 group->blocking_domain = __iommu_domain_alloc(
3175 dev->dev->bus, IOMMU_DOMAIN_UNMANAGED);
3176 if (!group->blocking_domain)
3182 static int __iommu_take_dma_ownership(struct iommu_group *group, void *owner)
3186 if ((group->domain && group->domain != group->default_domain) ||
3187 !xa_empty(&group->pasid_array))
3190 ret = __iommu_group_alloc_blocking_domain(group);
3193 ret = __iommu_group_set_domain(group, group->blocking_domain);
3197 group->owner = owner;
3203 * iommu_group_claim_dma_owner() - Set DMA ownership of a group
3204 * @group: The group.
3205 * @owner: Caller specified pointer. Used for exclusive ownership.
3207 * This is to support backward compatibility for vfio which manages the dma
3208 * ownership in iommu_group level. New invocations on this interface should be
3209 * prohibited. Only a single owner may exist for a group.
3211 int iommu_group_claim_dma_owner(struct iommu_group *group, void *owner)
3215 if (WARN_ON(!owner))
3218 mutex_lock(&group->mutex);
3219 if (group->owner_cnt) {
3224 ret = __iommu_take_dma_ownership(group, owner);
3226 mutex_unlock(&group->mutex);
3230 EXPORT_SYMBOL_GPL(iommu_group_claim_dma_owner);
3233 * iommu_device_claim_dma_owner() - Set DMA ownership of a device
3235 * @owner: Caller specified pointer. Used for exclusive ownership.
3237 * Claim the DMA ownership of a device. Multiple devices in the same group may
3238 * concurrently claim ownership if they present the same owner value. Returns 0
3239 * on success and error code on failure
3241 int iommu_device_claim_dma_owner(struct device *dev, void *owner)
3243 struct iommu_group *group;
3246 if (WARN_ON(!owner))
3249 group = iommu_group_get(dev);
3253 mutex_lock(&group->mutex);
3254 if (group->owner_cnt) {
3255 if (group->owner != owner) {
3263 ret = __iommu_take_dma_ownership(group, owner);
3265 mutex_unlock(&group->mutex);
3266 iommu_group_put(group);
3270 EXPORT_SYMBOL_GPL(iommu_device_claim_dma_owner);
3272 static void __iommu_release_dma_ownership(struct iommu_group *group)
3274 if (WARN_ON(!group->owner_cnt || !group->owner ||
3275 !xa_empty(&group->pasid_array)))
3278 group->owner_cnt = 0;
3279 group->owner = NULL;
3280 __iommu_group_set_domain_nofail(group, group->default_domain);
3284 * iommu_group_release_dma_owner() - Release DMA ownership of a group
3287 * Release the DMA ownership claimed by iommu_group_claim_dma_owner().
3289 void iommu_group_release_dma_owner(struct iommu_group *group)
3291 mutex_lock(&group->mutex);
3292 __iommu_release_dma_ownership(group);
3293 mutex_unlock(&group->mutex);
3295 EXPORT_SYMBOL_GPL(iommu_group_release_dma_owner);
3298 * iommu_device_release_dma_owner() - Release DMA ownership of a device
3299 * @group: The device.
3301 * Release the DMA ownership claimed by iommu_device_claim_dma_owner().
3303 void iommu_device_release_dma_owner(struct device *dev)
3305 struct iommu_group *group = iommu_group_get(dev);
3307 mutex_lock(&group->mutex);
3308 if (group->owner_cnt > 1)
3311 __iommu_release_dma_ownership(group);
3312 mutex_unlock(&group->mutex);
3313 iommu_group_put(group);
3315 EXPORT_SYMBOL_GPL(iommu_device_release_dma_owner);
3318 * iommu_group_dma_owner_claimed() - Query group dma ownership status
3319 * @group: The group.
3321 * This provides status query on a given group. It is racy and only for
3322 * non-binding status reporting.
3324 bool iommu_group_dma_owner_claimed(struct iommu_group *group)
3328 mutex_lock(&group->mutex);
3329 user = group->owner_cnt;
3330 mutex_unlock(&group->mutex);
3334 EXPORT_SYMBOL_GPL(iommu_group_dma_owner_claimed);
3336 static int __iommu_set_group_pasid(struct iommu_domain *domain,
3337 struct iommu_group *group, ioasid_t pasid)
3339 struct group_device *device;
3342 for_each_group_device(group, device) {
3343 ret = domain->ops->set_dev_pasid(domain, device->dev, pasid);
3351 static void __iommu_remove_group_pasid(struct iommu_group *group,
3354 struct group_device *device;
3355 const struct iommu_ops *ops;
3357 for_each_group_device(group, device) {
3358 ops = dev_iommu_ops(device->dev);
3359 ops->remove_dev_pasid(device->dev, pasid);
3364 * iommu_attach_device_pasid() - Attach a domain to pasid of device
3365 * @domain: the iommu domain.
3366 * @dev: the attached device.
3367 * @pasid: the pasid of the device.
3369 * Return: 0 on success, or an error.
3371 int iommu_attach_device_pasid(struct iommu_domain *domain,
3372 struct device *dev, ioasid_t pasid)
3374 struct iommu_group *group;
3378 if (!domain->ops->set_dev_pasid)
3381 group = iommu_group_get(dev);
3385 mutex_lock(&group->mutex);
3386 curr = xa_cmpxchg(&group->pasid_array, pasid, NULL, domain, GFP_KERNEL);
3388 ret = xa_err(curr) ? : -EBUSY;
3392 ret = __iommu_set_group_pasid(domain, group, pasid);
3394 __iommu_remove_group_pasid(group, pasid);
3395 xa_erase(&group->pasid_array, pasid);
3398 mutex_unlock(&group->mutex);
3399 iommu_group_put(group);
3403 EXPORT_SYMBOL_GPL(iommu_attach_device_pasid);
3406 * iommu_detach_device_pasid() - Detach the domain from pasid of device
3407 * @domain: the iommu domain.
3408 * @dev: the attached device.
3409 * @pasid: the pasid of the device.
3411 * The @domain must have been attached to @pasid of the @dev with
3412 * iommu_attach_device_pasid().
3414 void iommu_detach_device_pasid(struct iommu_domain *domain, struct device *dev,
3417 struct iommu_group *group = iommu_group_get(dev);
3419 mutex_lock(&group->mutex);
3420 __iommu_remove_group_pasid(group, pasid);
3421 WARN_ON(xa_erase(&group->pasid_array, pasid) != domain);
3422 mutex_unlock(&group->mutex);
3424 iommu_group_put(group);
3426 EXPORT_SYMBOL_GPL(iommu_detach_device_pasid);
3429 * iommu_get_domain_for_dev_pasid() - Retrieve domain for @pasid of @dev
3430 * @dev: the queried device
3431 * @pasid: the pasid of the device
3432 * @type: matched domain type, 0 for any match
3434 * This is a variant of iommu_get_domain_for_dev(). It returns the existing
3435 * domain attached to pasid of a device. Callers must hold a lock around this
3436 * function, and both iommu_attach/detach_dev_pasid() whenever a domain of
3437 * type is being manipulated. This API does not internally resolve races with
3440 * Return: attached domain on success, NULL otherwise.
3442 struct iommu_domain *iommu_get_domain_for_dev_pasid(struct device *dev,
3446 struct iommu_domain *domain;
3447 struct iommu_group *group;
3449 group = iommu_group_get(dev);
3453 xa_lock(&group->pasid_array);
3454 domain = xa_load(&group->pasid_array, pasid);
3455 if (type && domain && domain->type != type)
3456 domain = ERR_PTR(-EBUSY);
3457 xa_unlock(&group->pasid_array);
3458 iommu_group_put(group);
3462 EXPORT_SYMBOL_GPL(iommu_get_domain_for_dev_pasid);
3464 struct iommu_domain *iommu_sva_domain_alloc(struct device *dev,
3465 struct mm_struct *mm)
3467 const struct iommu_ops *ops = dev_iommu_ops(dev);
3468 struct iommu_domain *domain;
3470 domain = ops->domain_alloc(IOMMU_DOMAIN_SVA);
3474 domain->type = IOMMU_DOMAIN_SVA;
3477 domain->iopf_handler = iommu_sva_handle_iopf;
3478 domain->fault_data = mm;