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);
44 static DEFINE_IDA(iommu_global_pasid_ida);
46 static unsigned int iommu_def_domain_type __read_mostly;
47 static bool iommu_dma_strict __read_mostly = IS_ENABLED(CONFIG_IOMMU_DEFAULT_DMA_STRICT);
48 static u32 iommu_cmd_line __read_mostly;
52 struct kobject *devices_kobj;
53 struct list_head devices;
54 struct xarray pasid_array;
57 void (*iommu_data_release)(void *iommu_data);
60 struct iommu_domain *default_domain;
61 struct iommu_domain *blocking_domain;
62 struct iommu_domain *domain;
63 struct list_head entry;
64 unsigned int owner_cnt;
69 struct list_head list;
74 /* Iterate over each struct group_device in a struct iommu_group */
75 #define for_each_group_device(group, pos) \
76 list_for_each_entry(pos, &(group)->devices, list)
78 struct iommu_group_attribute {
79 struct attribute attr;
80 ssize_t (*show)(struct iommu_group *group, char *buf);
81 ssize_t (*store)(struct iommu_group *group,
82 const char *buf, size_t count);
85 static const char * const iommu_group_resv_type_string[] = {
86 [IOMMU_RESV_DIRECT] = "direct",
87 [IOMMU_RESV_DIRECT_RELAXABLE] = "direct-relaxable",
88 [IOMMU_RESV_RESERVED] = "reserved",
89 [IOMMU_RESV_MSI] = "msi",
90 [IOMMU_RESV_SW_MSI] = "msi",
93 #define IOMMU_CMD_LINE_DMA_API BIT(0)
94 #define IOMMU_CMD_LINE_STRICT BIT(1)
96 static int iommu_bus_notifier(struct notifier_block *nb,
97 unsigned long action, void *data);
98 static void iommu_release_device(struct device *dev);
99 static struct iommu_domain *__iommu_domain_alloc(const struct bus_type *bus,
101 static int __iommu_attach_device(struct iommu_domain *domain,
103 static int __iommu_attach_group(struct iommu_domain *domain,
104 struct iommu_group *group);
107 IOMMU_SET_DOMAIN_MUST_SUCCEED = 1 << 0,
110 static int __iommu_device_set_domain(struct iommu_group *group,
112 struct iommu_domain *new_domain,
114 static int __iommu_group_set_domain_internal(struct iommu_group *group,
115 struct iommu_domain *new_domain,
117 static int __iommu_group_set_domain(struct iommu_group *group,
118 struct iommu_domain *new_domain)
120 return __iommu_group_set_domain_internal(group, new_domain, 0);
122 static void __iommu_group_set_domain_nofail(struct iommu_group *group,
123 struct iommu_domain *new_domain)
125 WARN_ON(__iommu_group_set_domain_internal(
126 group, new_domain, IOMMU_SET_DOMAIN_MUST_SUCCEED));
129 static int iommu_setup_default_domain(struct iommu_group *group,
131 static int iommu_create_device_direct_mappings(struct iommu_domain *domain,
133 static ssize_t iommu_group_store_type(struct iommu_group *group,
134 const char *buf, size_t count);
135 static struct group_device *iommu_group_alloc_device(struct iommu_group *group,
137 static void __iommu_group_free_device(struct iommu_group *group,
138 struct group_device *grp_dev);
140 #define IOMMU_GROUP_ATTR(_name, _mode, _show, _store) \
141 struct iommu_group_attribute iommu_group_attr_##_name = \
142 __ATTR(_name, _mode, _show, _store)
144 #define to_iommu_group_attr(_attr) \
145 container_of(_attr, struct iommu_group_attribute, attr)
146 #define to_iommu_group(_kobj) \
147 container_of(_kobj, struct iommu_group, kobj)
149 static LIST_HEAD(iommu_device_list);
150 static DEFINE_SPINLOCK(iommu_device_lock);
152 static struct bus_type * const iommu_buses[] = {
157 #ifdef CONFIG_ARM_AMBA
160 #ifdef CONFIG_FSL_MC_BUS
163 #ifdef CONFIG_TEGRA_HOST1X_CONTEXT_BUS
164 &host1x_context_device_bus_type,
166 #ifdef CONFIG_CDX_BUS
172 * Use a function instead of an array here because the domain-type is a
173 * bit-field, so an array would waste memory.
175 static const char *iommu_domain_type_str(unsigned int t)
178 case IOMMU_DOMAIN_BLOCKED:
180 case IOMMU_DOMAIN_IDENTITY:
181 return "Passthrough";
182 case IOMMU_DOMAIN_UNMANAGED:
184 case IOMMU_DOMAIN_DMA:
185 case IOMMU_DOMAIN_DMA_FQ:
192 static int __init iommu_subsys_init(void)
194 struct notifier_block *nb;
196 if (!(iommu_cmd_line & IOMMU_CMD_LINE_DMA_API)) {
197 if (IS_ENABLED(CONFIG_IOMMU_DEFAULT_PASSTHROUGH))
198 iommu_set_default_passthrough(false);
200 iommu_set_default_translated(false);
202 if (iommu_default_passthrough() && cc_platform_has(CC_ATTR_MEM_ENCRYPT)) {
203 pr_info("Memory encryption detected - Disabling default IOMMU Passthrough\n");
204 iommu_set_default_translated(false);
208 if (!iommu_default_passthrough() && !iommu_dma_strict)
209 iommu_def_domain_type = IOMMU_DOMAIN_DMA_FQ;
211 pr_info("Default domain type: %s%s\n",
212 iommu_domain_type_str(iommu_def_domain_type),
213 (iommu_cmd_line & IOMMU_CMD_LINE_DMA_API) ?
214 " (set via kernel command line)" : "");
216 if (!iommu_default_passthrough())
217 pr_info("DMA domain TLB invalidation policy: %s mode%s\n",
218 iommu_dma_strict ? "strict" : "lazy",
219 (iommu_cmd_line & IOMMU_CMD_LINE_STRICT) ?
220 " (set via kernel command line)" : "");
222 nb = kcalloc(ARRAY_SIZE(iommu_buses), sizeof(*nb), GFP_KERNEL);
226 for (int i = 0; i < ARRAY_SIZE(iommu_buses); i++) {
227 nb[i].notifier_call = iommu_bus_notifier;
228 bus_register_notifier(iommu_buses[i], &nb[i]);
233 subsys_initcall(iommu_subsys_init);
235 static int remove_iommu_group(struct device *dev, void *data)
237 if (dev->iommu && dev->iommu->iommu_dev == data)
238 iommu_release_device(dev);
244 * iommu_device_register() - Register an IOMMU hardware instance
245 * @iommu: IOMMU handle for the instance
246 * @ops: IOMMU ops to associate with the instance
247 * @hwdev: (optional) actual instance device, used for fwnode lookup
249 * Return: 0 on success, or an error.
251 int iommu_device_register(struct iommu_device *iommu,
252 const struct iommu_ops *ops, struct device *hwdev)
256 /* We need to be able to take module references appropriately */
257 if (WARN_ON(is_module_address((unsigned long)ops) && !ops->owner))
260 * Temporarily enforce global restriction to a single driver. This was
261 * already the de-facto behaviour, since any possible combination of
262 * existing drivers would compete for at least the PCI or platform bus.
264 if (iommu_buses[0]->iommu_ops && iommu_buses[0]->iommu_ops != ops)
269 iommu->fwnode = dev_fwnode(hwdev);
271 spin_lock(&iommu_device_lock);
272 list_add_tail(&iommu->list, &iommu_device_list);
273 spin_unlock(&iommu_device_lock);
275 for (int i = 0; i < ARRAY_SIZE(iommu_buses) && !err; i++) {
276 iommu_buses[i]->iommu_ops = ops;
277 err = bus_iommu_probe(iommu_buses[i]);
280 iommu_device_unregister(iommu);
283 EXPORT_SYMBOL_GPL(iommu_device_register);
285 void iommu_device_unregister(struct iommu_device *iommu)
287 for (int i = 0; i < ARRAY_SIZE(iommu_buses); i++)
288 bus_for_each_dev(iommu_buses[i], NULL, iommu, remove_iommu_group);
290 spin_lock(&iommu_device_lock);
291 list_del(&iommu->list);
292 spin_unlock(&iommu_device_lock);
294 EXPORT_SYMBOL_GPL(iommu_device_unregister);
296 #if IS_ENABLED(CONFIG_IOMMUFD_TEST)
297 void iommu_device_unregister_bus(struct iommu_device *iommu,
298 struct bus_type *bus,
299 struct notifier_block *nb)
301 bus_unregister_notifier(bus, nb);
302 iommu_device_unregister(iommu);
304 EXPORT_SYMBOL_GPL(iommu_device_unregister_bus);
307 * Register an iommu driver against a single bus. This is only used by iommufd
308 * selftest to create a mock iommu driver. The caller must provide
309 * some memory to hold a notifier_block.
311 int iommu_device_register_bus(struct iommu_device *iommu,
312 const struct iommu_ops *ops, struct bus_type *bus,
313 struct notifier_block *nb)
318 nb->notifier_call = iommu_bus_notifier;
319 err = bus_register_notifier(bus, nb);
323 spin_lock(&iommu_device_lock);
324 list_add_tail(&iommu->list, &iommu_device_list);
325 spin_unlock(&iommu_device_lock);
327 bus->iommu_ops = ops;
328 err = bus_iommu_probe(bus);
330 iommu_device_unregister_bus(iommu, bus, nb);
335 EXPORT_SYMBOL_GPL(iommu_device_register_bus);
338 static struct dev_iommu *dev_iommu_get(struct device *dev)
340 struct dev_iommu *param = dev->iommu;
345 param = kzalloc(sizeof(*param), GFP_KERNEL);
349 mutex_init(¶m->lock);
354 static void dev_iommu_free(struct device *dev)
356 struct dev_iommu *param = dev->iommu;
360 fwnode_handle_put(param->fwspec->iommu_fwnode);
361 kfree(param->fwspec);
366 static u32 dev_iommu_get_max_pasids(struct device *dev)
368 u32 max_pasids = 0, bits = 0;
371 if (dev_is_pci(dev)) {
372 ret = pci_max_pasids(to_pci_dev(dev));
376 ret = device_property_read_u32(dev, "pasid-num-bits", &bits);
378 max_pasids = 1UL << bits;
381 return min_t(u32, max_pasids, dev->iommu->iommu_dev->max_pasids);
385 * Init the dev->iommu and dev->iommu_group in the struct device and get the
388 static int iommu_init_device(struct device *dev, const struct iommu_ops *ops)
390 struct iommu_device *iommu_dev;
391 struct iommu_group *group;
394 if (!dev_iommu_get(dev))
397 if (!try_module_get(ops->owner)) {
402 iommu_dev = ops->probe_device(dev);
403 if (IS_ERR(iommu_dev)) {
404 ret = PTR_ERR(iommu_dev);
408 ret = iommu_device_link(iommu_dev, dev);
412 group = ops->device_group(dev);
413 if (WARN_ON_ONCE(group == NULL))
414 group = ERR_PTR(-EINVAL);
416 ret = PTR_ERR(group);
419 dev->iommu_group = group;
421 dev->iommu->iommu_dev = iommu_dev;
422 dev->iommu->max_pasids = dev_iommu_get_max_pasids(dev);
423 if (ops->is_attach_deferred)
424 dev->iommu->attach_deferred = ops->is_attach_deferred(dev);
428 iommu_device_unlink(iommu_dev, dev);
430 if (ops->release_device)
431 ops->release_device(dev);
433 module_put(ops->owner);
439 static void iommu_deinit_device(struct device *dev)
441 struct iommu_group *group = dev->iommu_group;
442 const struct iommu_ops *ops = dev_iommu_ops(dev);
444 lockdep_assert_held(&group->mutex);
446 iommu_device_unlink(dev->iommu->iommu_dev, dev);
449 * release_device() must stop using any attached domain on the device.
450 * If there are still other devices in the group they are not effected
453 * The IOMMU driver must set the device to either an identity or
454 * blocking translation and stop using any domain pointer, as it is
457 if (ops->release_device)
458 ops->release_device(dev);
461 * If this is the last driver to use the group then we must free the
462 * domains before we do the module_put().
464 if (list_empty(&group->devices)) {
465 if (group->default_domain) {
466 iommu_domain_free(group->default_domain);
467 group->default_domain = NULL;
469 if (group->blocking_domain) {
470 iommu_domain_free(group->blocking_domain);
471 group->blocking_domain = NULL;
473 group->domain = NULL;
476 /* Caller must put iommu_group */
477 dev->iommu_group = NULL;
478 module_put(ops->owner);
482 static int __iommu_probe_device(struct device *dev, struct list_head *group_list)
484 const struct iommu_ops *ops = dev->bus->iommu_ops;
485 struct iommu_group *group;
486 static DEFINE_MUTEX(iommu_probe_device_lock);
487 struct group_device *gdev;
493 * Serialise to avoid races between IOMMU drivers registering in
494 * parallel and/or the "replay" calls from ACPI/OF code via client
495 * driver probe. Once the latter have been cleaned up we should
496 * probably be able to use device_lock() here to minimise the scope,
497 * but for now enforcing a simple global ordering is fine.
499 mutex_lock(&iommu_probe_device_lock);
501 /* Device is probed already if in a group */
502 if (dev->iommu_group) {
507 ret = iommu_init_device(dev, ops);
511 group = dev->iommu_group;
512 gdev = iommu_group_alloc_device(group, dev);
513 mutex_lock(&group->mutex);
520 * The gdev must be in the list before calling
521 * iommu_setup_default_domain()
523 list_add_tail(&gdev->list, &group->devices);
524 WARN_ON(group->default_domain && !group->domain);
525 if (group->default_domain)
526 iommu_create_device_direct_mappings(group->default_domain, dev);
528 ret = __iommu_device_set_domain(group, dev, group->domain, 0);
530 goto err_remove_gdev;
531 } else if (!group->default_domain && !group_list) {
532 ret = iommu_setup_default_domain(group, 0);
534 goto err_remove_gdev;
535 } else if (!group->default_domain) {
537 * With a group_list argument we defer the default_domain setup
538 * to the caller by providing a de-duplicated list of groups
539 * that need further setup.
541 if (list_empty(&group->entry))
542 list_add_tail(&group->entry, group_list);
544 mutex_unlock(&group->mutex);
545 mutex_unlock(&iommu_probe_device_lock);
548 iommu_dma_set_pci_32bit_workaround(dev);
553 list_del(&gdev->list);
554 __iommu_group_free_device(group, gdev);
556 iommu_deinit_device(dev);
557 mutex_unlock(&group->mutex);
558 iommu_group_put(group);
560 mutex_unlock(&iommu_probe_device_lock);
565 int iommu_probe_device(struct device *dev)
567 const struct iommu_ops *ops;
570 ret = __iommu_probe_device(dev, NULL);
574 ops = dev_iommu_ops(dev);
575 if (ops->probe_finalize)
576 ops->probe_finalize(dev);
581 static void __iommu_group_free_device(struct iommu_group *group,
582 struct group_device *grp_dev)
584 struct device *dev = grp_dev->dev;
586 sysfs_remove_link(group->devices_kobj, grp_dev->name);
587 sysfs_remove_link(&dev->kobj, "iommu_group");
589 trace_remove_device_from_group(group->id, dev);
592 * If the group has become empty then ownership must have been
593 * released, and the current domain must be set back to NULL or
594 * the default domain.
596 if (list_empty(&group->devices))
597 WARN_ON(group->owner_cnt ||
598 group->domain != group->default_domain);
600 kfree(grp_dev->name);
604 /* Remove the iommu_group from the struct device. */
605 static void __iommu_group_remove_device(struct device *dev)
607 struct iommu_group *group = dev->iommu_group;
608 struct group_device *device;
610 mutex_lock(&group->mutex);
611 for_each_group_device(group, device) {
612 if (device->dev != dev)
615 list_del(&device->list);
616 __iommu_group_free_device(group, device);
617 if (dev->iommu && dev->iommu->iommu_dev)
618 iommu_deinit_device(dev);
620 dev->iommu_group = NULL;
623 mutex_unlock(&group->mutex);
626 * Pairs with the get in iommu_init_device() or
627 * iommu_group_add_device()
629 iommu_group_put(group);
632 static void iommu_release_device(struct device *dev)
634 struct iommu_group *group = dev->iommu_group;
637 __iommu_group_remove_device(dev);
639 /* Free any fwspec if no iommu_driver was ever attached */
644 static int __init iommu_set_def_domain_type(char *str)
649 ret = kstrtobool(str, &pt);
654 iommu_set_default_passthrough(true);
656 iommu_set_default_translated(true);
660 early_param("iommu.passthrough", iommu_set_def_domain_type);
662 static int __init iommu_dma_setup(char *str)
664 int ret = kstrtobool(str, &iommu_dma_strict);
667 iommu_cmd_line |= IOMMU_CMD_LINE_STRICT;
670 early_param("iommu.strict", iommu_dma_setup);
672 void iommu_set_dma_strict(void)
674 iommu_dma_strict = true;
675 if (iommu_def_domain_type == IOMMU_DOMAIN_DMA_FQ)
676 iommu_def_domain_type = IOMMU_DOMAIN_DMA;
679 static ssize_t iommu_group_attr_show(struct kobject *kobj,
680 struct attribute *__attr, char *buf)
682 struct iommu_group_attribute *attr = to_iommu_group_attr(__attr);
683 struct iommu_group *group = to_iommu_group(kobj);
687 ret = attr->show(group, buf);
691 static ssize_t iommu_group_attr_store(struct kobject *kobj,
692 struct attribute *__attr,
693 const char *buf, size_t count)
695 struct iommu_group_attribute *attr = to_iommu_group_attr(__attr);
696 struct iommu_group *group = to_iommu_group(kobj);
700 ret = attr->store(group, buf, count);
704 static const struct sysfs_ops iommu_group_sysfs_ops = {
705 .show = iommu_group_attr_show,
706 .store = iommu_group_attr_store,
709 static int iommu_group_create_file(struct iommu_group *group,
710 struct iommu_group_attribute *attr)
712 return sysfs_create_file(&group->kobj, &attr->attr);
715 static void iommu_group_remove_file(struct iommu_group *group,
716 struct iommu_group_attribute *attr)
718 sysfs_remove_file(&group->kobj, &attr->attr);
721 static ssize_t iommu_group_show_name(struct iommu_group *group, char *buf)
723 return sysfs_emit(buf, "%s\n", group->name);
727 * iommu_insert_resv_region - Insert a new region in the
728 * list of reserved regions.
729 * @new: new region to insert
730 * @regions: list of regions
732 * Elements are sorted by start address and overlapping segments
733 * of the same type are merged.
735 static int iommu_insert_resv_region(struct iommu_resv_region *new,
736 struct list_head *regions)
738 struct iommu_resv_region *iter, *tmp, *nr, *top;
741 nr = iommu_alloc_resv_region(new->start, new->length,
742 new->prot, new->type, GFP_KERNEL);
746 /* First add the new element based on start address sorting */
747 list_for_each_entry(iter, regions, list) {
748 if (nr->start < iter->start ||
749 (nr->start == iter->start && nr->type <= iter->type))
752 list_add_tail(&nr->list, &iter->list);
754 /* Merge overlapping segments of type nr->type in @regions, if any */
755 list_for_each_entry_safe(iter, tmp, regions, list) {
756 phys_addr_t top_end, iter_end = iter->start + iter->length - 1;
758 /* no merge needed on elements of different types than @new */
759 if (iter->type != new->type) {
760 list_move_tail(&iter->list, &stack);
764 /* look for the last stack element of same type as @iter */
765 list_for_each_entry_reverse(top, &stack, list)
766 if (top->type == iter->type)
769 list_move_tail(&iter->list, &stack);
773 top_end = top->start + top->length - 1;
775 if (iter->start > top_end + 1) {
776 list_move_tail(&iter->list, &stack);
778 top->length = max(top_end, iter_end) - top->start + 1;
779 list_del(&iter->list);
783 list_splice(&stack, regions);
788 iommu_insert_device_resv_regions(struct list_head *dev_resv_regions,
789 struct list_head *group_resv_regions)
791 struct iommu_resv_region *entry;
794 list_for_each_entry(entry, dev_resv_regions, list) {
795 ret = iommu_insert_resv_region(entry, group_resv_regions);
802 int iommu_get_group_resv_regions(struct iommu_group *group,
803 struct list_head *head)
805 struct group_device *device;
808 mutex_lock(&group->mutex);
809 for_each_group_device(group, device) {
810 struct list_head dev_resv_regions;
813 * Non-API groups still expose reserved_regions in sysfs,
814 * so filter out calls that get here that way.
816 if (!device->dev->iommu)
819 INIT_LIST_HEAD(&dev_resv_regions);
820 iommu_get_resv_regions(device->dev, &dev_resv_regions);
821 ret = iommu_insert_device_resv_regions(&dev_resv_regions, head);
822 iommu_put_resv_regions(device->dev, &dev_resv_regions);
826 mutex_unlock(&group->mutex);
829 EXPORT_SYMBOL_GPL(iommu_get_group_resv_regions);
831 static ssize_t iommu_group_show_resv_regions(struct iommu_group *group,
834 struct iommu_resv_region *region, *next;
835 struct list_head group_resv_regions;
838 INIT_LIST_HEAD(&group_resv_regions);
839 iommu_get_group_resv_regions(group, &group_resv_regions);
841 list_for_each_entry_safe(region, next, &group_resv_regions, list) {
842 offset += sysfs_emit_at(buf, offset, "0x%016llx 0x%016llx %s\n",
843 (long long)region->start,
844 (long long)(region->start +
846 iommu_group_resv_type_string[region->type]);
853 static ssize_t iommu_group_show_type(struct iommu_group *group,
856 char *type = "unknown";
858 mutex_lock(&group->mutex);
859 if (group->default_domain) {
860 switch (group->default_domain->type) {
861 case IOMMU_DOMAIN_BLOCKED:
864 case IOMMU_DOMAIN_IDENTITY:
867 case IOMMU_DOMAIN_UNMANAGED:
870 case IOMMU_DOMAIN_DMA:
873 case IOMMU_DOMAIN_DMA_FQ:
878 mutex_unlock(&group->mutex);
880 return sysfs_emit(buf, "%s\n", type);
883 static IOMMU_GROUP_ATTR(name, S_IRUGO, iommu_group_show_name, NULL);
885 static IOMMU_GROUP_ATTR(reserved_regions, 0444,
886 iommu_group_show_resv_regions, NULL);
888 static IOMMU_GROUP_ATTR(type, 0644, iommu_group_show_type,
889 iommu_group_store_type);
891 static void iommu_group_release(struct kobject *kobj)
893 struct iommu_group *group = to_iommu_group(kobj);
895 pr_debug("Releasing group %d\n", group->id);
897 if (group->iommu_data_release)
898 group->iommu_data_release(group->iommu_data);
900 ida_free(&iommu_group_ida, group->id);
902 /* Domains are free'd by iommu_deinit_device() */
903 WARN_ON(group->default_domain);
904 WARN_ON(group->blocking_domain);
910 static const struct kobj_type iommu_group_ktype = {
911 .sysfs_ops = &iommu_group_sysfs_ops,
912 .release = iommu_group_release,
916 * iommu_group_alloc - Allocate a new group
918 * This function is called by an iommu driver to allocate a new iommu
919 * group. The iommu group represents the minimum granularity of the iommu.
920 * Upon successful return, the caller holds a reference to the supplied
921 * group in order to hold the group until devices are added. Use
922 * iommu_group_put() to release this extra reference count, allowing the
923 * group to be automatically reclaimed once it has no devices or external
926 struct iommu_group *iommu_group_alloc(void)
928 struct iommu_group *group;
931 group = kzalloc(sizeof(*group), GFP_KERNEL);
933 return ERR_PTR(-ENOMEM);
935 group->kobj.kset = iommu_group_kset;
936 mutex_init(&group->mutex);
937 INIT_LIST_HEAD(&group->devices);
938 INIT_LIST_HEAD(&group->entry);
939 xa_init(&group->pasid_array);
941 ret = ida_alloc(&iommu_group_ida, GFP_KERNEL);
948 ret = kobject_init_and_add(&group->kobj, &iommu_group_ktype,
949 NULL, "%d", group->id);
951 kobject_put(&group->kobj);
955 group->devices_kobj = kobject_create_and_add("devices", &group->kobj);
956 if (!group->devices_kobj) {
957 kobject_put(&group->kobj); /* triggers .release & free */
958 return ERR_PTR(-ENOMEM);
962 * The devices_kobj holds a reference on the group kobject, so
963 * as long as that exists so will the group. We can therefore
964 * use the devices_kobj for reference counting.
966 kobject_put(&group->kobj);
968 ret = iommu_group_create_file(group,
969 &iommu_group_attr_reserved_regions);
971 kobject_put(group->devices_kobj);
975 ret = iommu_group_create_file(group, &iommu_group_attr_type);
977 kobject_put(group->devices_kobj);
981 pr_debug("Allocated group %d\n", group->id);
985 EXPORT_SYMBOL_GPL(iommu_group_alloc);
988 * iommu_group_get_iommudata - retrieve iommu_data registered for a group
991 * iommu drivers can store data in the group for use when doing iommu
992 * operations. This function provides a way to retrieve it. Caller
993 * should hold a group reference.
995 void *iommu_group_get_iommudata(struct iommu_group *group)
997 return group->iommu_data;
999 EXPORT_SYMBOL_GPL(iommu_group_get_iommudata);
1002 * iommu_group_set_iommudata - set iommu_data for a group
1004 * @iommu_data: new data
1005 * @release: release function for iommu_data
1007 * iommu drivers can store data in the group for use when doing iommu
1008 * operations. This function provides a way to set the data after
1009 * the group has been allocated. Caller should hold a group reference.
1011 void iommu_group_set_iommudata(struct iommu_group *group, void *iommu_data,
1012 void (*release)(void *iommu_data))
1014 group->iommu_data = iommu_data;
1015 group->iommu_data_release = release;
1017 EXPORT_SYMBOL_GPL(iommu_group_set_iommudata);
1020 * iommu_group_set_name - set name for a group
1024 * Allow iommu driver to set a name for a group. When set it will
1025 * appear in a name attribute file under the group in sysfs.
1027 int iommu_group_set_name(struct iommu_group *group, const char *name)
1032 iommu_group_remove_file(group, &iommu_group_attr_name);
1039 group->name = kstrdup(name, GFP_KERNEL);
1043 ret = iommu_group_create_file(group, &iommu_group_attr_name);
1052 EXPORT_SYMBOL_GPL(iommu_group_set_name);
1054 static int iommu_create_device_direct_mappings(struct iommu_domain *domain,
1057 struct iommu_resv_region *entry;
1058 struct list_head mappings;
1059 unsigned long pg_size;
1062 pg_size = domain->pgsize_bitmap ? 1UL << __ffs(domain->pgsize_bitmap) : 0;
1063 INIT_LIST_HEAD(&mappings);
1065 if (WARN_ON_ONCE(iommu_is_dma_domain(domain) && !pg_size))
1068 iommu_get_resv_regions(dev, &mappings);
1070 /* We need to consider overlapping regions for different devices */
1071 list_for_each_entry(entry, &mappings, list) {
1072 dma_addr_t start, end, addr;
1073 size_t map_size = 0;
1075 if (entry->type == IOMMU_RESV_DIRECT)
1076 dev->iommu->require_direct = 1;
1078 if ((entry->type != IOMMU_RESV_DIRECT &&
1079 entry->type != IOMMU_RESV_DIRECT_RELAXABLE) ||
1080 !iommu_is_dma_domain(domain))
1083 start = ALIGN(entry->start, pg_size);
1084 end = ALIGN(entry->start + entry->length, pg_size);
1086 for (addr = start; addr <= end; addr += pg_size) {
1087 phys_addr_t phys_addr;
1092 phys_addr = iommu_iova_to_phys(domain, addr);
1094 map_size += pg_size;
1100 ret = iommu_map(domain, addr - map_size,
1101 addr - map_size, map_size,
1102 entry->prot, GFP_KERNEL);
1111 iommu_flush_iotlb_all(domain);
1114 iommu_put_resv_regions(dev, &mappings);
1119 /* This is undone by __iommu_group_free_device() */
1120 static struct group_device *iommu_group_alloc_device(struct iommu_group *group,
1124 struct group_device *device;
1126 device = kzalloc(sizeof(*device), GFP_KERNEL);
1128 return ERR_PTR(-ENOMEM);
1132 ret = sysfs_create_link(&dev->kobj, &group->kobj, "iommu_group");
1134 goto err_free_device;
1136 device->name = kasprintf(GFP_KERNEL, "%s", kobject_name(&dev->kobj));
1138 if (!device->name) {
1140 goto err_remove_link;
1143 ret = sysfs_create_link_nowarn(group->devices_kobj,
1144 &dev->kobj, device->name);
1146 if (ret == -EEXIST && i >= 0) {
1148 * Account for the slim chance of collision
1149 * and append an instance to the name.
1151 kfree(device->name);
1152 device->name = kasprintf(GFP_KERNEL, "%s.%d",
1153 kobject_name(&dev->kobj), i++);
1159 trace_add_device_to_group(group->id, dev);
1161 dev_info(dev, "Adding to iommu group %d\n", group->id);
1166 kfree(device->name);
1168 sysfs_remove_link(&dev->kobj, "iommu_group");
1171 dev_err(dev, "Failed to add to iommu group %d: %d\n", group->id, ret);
1172 return ERR_PTR(ret);
1176 * iommu_group_add_device - add a device to an iommu group
1177 * @group: the group into which to add the device (reference should be held)
1180 * This function is called by an iommu driver to add a device into a
1181 * group. Adding a device increments the group reference count.
1183 int iommu_group_add_device(struct iommu_group *group, struct device *dev)
1185 struct group_device *gdev;
1187 gdev = iommu_group_alloc_device(group, dev);
1189 return PTR_ERR(gdev);
1191 iommu_group_ref_get(group);
1192 dev->iommu_group = group;
1194 mutex_lock(&group->mutex);
1195 list_add_tail(&gdev->list, &group->devices);
1196 mutex_unlock(&group->mutex);
1199 EXPORT_SYMBOL_GPL(iommu_group_add_device);
1202 * iommu_group_remove_device - remove a device from it's current group
1203 * @dev: device to be removed
1205 * This function is called by an iommu driver to remove the device from
1206 * it's current group. This decrements the iommu group reference count.
1208 void iommu_group_remove_device(struct device *dev)
1210 struct iommu_group *group = dev->iommu_group;
1215 dev_info(dev, "Removing from iommu group %d\n", group->id);
1217 __iommu_group_remove_device(dev);
1219 EXPORT_SYMBOL_GPL(iommu_group_remove_device);
1222 * iommu_group_for_each_dev - iterate over each device in the group
1224 * @data: caller opaque data to be passed to callback function
1225 * @fn: caller supplied callback function
1227 * This function is called by group users to iterate over group devices.
1228 * Callers should hold a reference count to the group during callback.
1229 * The group->mutex is held across callbacks, which will block calls to
1230 * iommu_group_add/remove_device.
1232 int iommu_group_for_each_dev(struct iommu_group *group, void *data,
1233 int (*fn)(struct device *, void *))
1235 struct group_device *device;
1238 mutex_lock(&group->mutex);
1239 for_each_group_device(group, device) {
1240 ret = fn(device->dev, data);
1244 mutex_unlock(&group->mutex);
1248 EXPORT_SYMBOL_GPL(iommu_group_for_each_dev);
1251 * iommu_group_get - Return the group for a device and increment reference
1252 * @dev: get the group that this device belongs to
1254 * This function is called by iommu drivers and users to get the group
1255 * for the specified device. If found, the group is returned and the group
1256 * reference in incremented, else NULL.
1258 struct iommu_group *iommu_group_get(struct device *dev)
1260 struct iommu_group *group = dev->iommu_group;
1263 kobject_get(group->devices_kobj);
1267 EXPORT_SYMBOL_GPL(iommu_group_get);
1270 * iommu_group_ref_get - Increment reference on a group
1271 * @group: the group to use, must not be NULL
1273 * This function is called by iommu drivers to take additional references on an
1274 * existing group. Returns the given group for convenience.
1276 struct iommu_group *iommu_group_ref_get(struct iommu_group *group)
1278 kobject_get(group->devices_kobj);
1281 EXPORT_SYMBOL_GPL(iommu_group_ref_get);
1284 * iommu_group_put - Decrement group reference
1285 * @group: the group to use
1287 * This function is called by iommu drivers and users to release the
1288 * iommu group. Once the reference count is zero, the group is released.
1290 void iommu_group_put(struct iommu_group *group)
1293 kobject_put(group->devices_kobj);
1295 EXPORT_SYMBOL_GPL(iommu_group_put);
1298 * iommu_register_device_fault_handler() - Register a device fault handler
1300 * @handler: the fault handler
1301 * @data: private data passed as argument to the handler
1303 * When an IOMMU fault event is received, this handler gets called with the
1304 * fault event and data as argument. The handler should return 0 on success. If
1305 * the fault is recoverable (IOMMU_FAULT_PAGE_REQ), the consumer should also
1306 * complete the fault by calling iommu_page_response() with one of the following
1308 * - IOMMU_PAGE_RESP_SUCCESS: retry the translation
1309 * - IOMMU_PAGE_RESP_INVALID: terminate the fault
1310 * - IOMMU_PAGE_RESP_FAILURE: terminate the fault and stop reporting
1311 * page faults if possible.
1313 * Return 0 if the fault handler was installed successfully, or an error.
1315 int iommu_register_device_fault_handler(struct device *dev,
1316 iommu_dev_fault_handler_t handler,
1319 struct dev_iommu *param = dev->iommu;
1325 mutex_lock(¶m->lock);
1326 /* Only allow one fault handler registered for each device */
1327 if (param->fault_param) {
1333 param->fault_param = kzalloc(sizeof(*param->fault_param), GFP_KERNEL);
1334 if (!param->fault_param) {
1339 param->fault_param->handler = handler;
1340 param->fault_param->data = data;
1341 mutex_init(¶m->fault_param->lock);
1342 INIT_LIST_HEAD(¶m->fault_param->faults);
1345 mutex_unlock(¶m->lock);
1349 EXPORT_SYMBOL_GPL(iommu_register_device_fault_handler);
1352 * iommu_unregister_device_fault_handler() - Unregister the device fault handler
1355 * Remove the device fault handler installed with
1356 * iommu_register_device_fault_handler().
1358 * Return 0 on success, or an error.
1360 int iommu_unregister_device_fault_handler(struct device *dev)
1362 struct dev_iommu *param = dev->iommu;
1368 mutex_lock(¶m->lock);
1370 if (!param->fault_param)
1373 /* we cannot unregister handler if there are pending faults */
1374 if (!list_empty(¶m->fault_param->faults)) {
1379 kfree(param->fault_param);
1380 param->fault_param = NULL;
1383 mutex_unlock(¶m->lock);
1387 EXPORT_SYMBOL_GPL(iommu_unregister_device_fault_handler);
1390 * iommu_report_device_fault() - Report fault event to device driver
1392 * @evt: fault event data
1394 * Called by IOMMU drivers when a fault is detected, typically in a threaded IRQ
1395 * handler. When this function fails and the fault is recoverable, it is the
1396 * caller's responsibility to complete the fault.
1398 * Return 0 on success, or an error.
1400 int iommu_report_device_fault(struct device *dev, struct iommu_fault_event *evt)
1402 struct dev_iommu *param = dev->iommu;
1403 struct iommu_fault_event *evt_pending = NULL;
1404 struct iommu_fault_param *fparam;
1410 /* we only report device fault if there is a handler registered */
1411 mutex_lock(¶m->lock);
1412 fparam = param->fault_param;
1413 if (!fparam || !fparam->handler) {
1418 if (evt->fault.type == IOMMU_FAULT_PAGE_REQ &&
1419 (evt->fault.prm.flags & IOMMU_FAULT_PAGE_REQUEST_LAST_PAGE)) {
1420 evt_pending = kmemdup(evt, sizeof(struct iommu_fault_event),
1426 mutex_lock(&fparam->lock);
1427 list_add_tail(&evt_pending->list, &fparam->faults);
1428 mutex_unlock(&fparam->lock);
1431 ret = fparam->handler(&evt->fault, fparam->data);
1432 if (ret && evt_pending) {
1433 mutex_lock(&fparam->lock);
1434 list_del(&evt_pending->list);
1435 mutex_unlock(&fparam->lock);
1439 mutex_unlock(¶m->lock);
1442 EXPORT_SYMBOL_GPL(iommu_report_device_fault);
1444 int iommu_page_response(struct device *dev,
1445 struct iommu_page_response *msg)
1449 struct iommu_fault_event *evt;
1450 struct iommu_fault_page_request *prm;
1451 struct dev_iommu *param = dev->iommu;
1452 const struct iommu_ops *ops = dev_iommu_ops(dev);
1453 bool has_pasid = msg->flags & IOMMU_PAGE_RESP_PASID_VALID;
1455 if (!ops->page_response)
1458 if (!param || !param->fault_param)
1461 if (msg->version != IOMMU_PAGE_RESP_VERSION_1 ||
1462 msg->flags & ~IOMMU_PAGE_RESP_PASID_VALID)
1465 /* Only send response if there is a fault report pending */
1466 mutex_lock(¶m->fault_param->lock);
1467 if (list_empty(¶m->fault_param->faults)) {
1468 dev_warn_ratelimited(dev, "no pending PRQ, drop response\n");
1472 * Check if we have a matching page request pending to respond,
1473 * otherwise return -EINVAL
1475 list_for_each_entry(evt, ¶m->fault_param->faults, list) {
1476 prm = &evt->fault.prm;
1477 if (prm->grpid != msg->grpid)
1481 * If the PASID is required, the corresponding request is
1482 * matched using the group ID, the PASID valid bit and the PASID
1483 * value. Otherwise only the group ID matches request and
1486 needs_pasid = prm->flags & IOMMU_FAULT_PAGE_RESPONSE_NEEDS_PASID;
1487 if (needs_pasid && (!has_pasid || msg->pasid != prm->pasid))
1490 if (!needs_pasid && has_pasid) {
1491 /* No big deal, just clear it. */
1492 msg->flags &= ~IOMMU_PAGE_RESP_PASID_VALID;
1496 ret = ops->page_response(dev, evt, msg);
1497 list_del(&evt->list);
1503 mutex_unlock(¶m->fault_param->lock);
1506 EXPORT_SYMBOL_GPL(iommu_page_response);
1509 * iommu_group_id - Return ID for a group
1510 * @group: the group to ID
1512 * Return the unique ID for the group matching the sysfs group number.
1514 int iommu_group_id(struct iommu_group *group)
1518 EXPORT_SYMBOL_GPL(iommu_group_id);
1520 static struct iommu_group *get_pci_alias_group(struct pci_dev *pdev,
1521 unsigned long *devfns);
1524 * To consider a PCI device isolated, we require ACS to support Source
1525 * Validation, Request Redirection, Completer Redirection, and Upstream
1526 * Forwarding. This effectively means that devices cannot spoof their
1527 * requester ID, requests and completions cannot be redirected, and all
1528 * transactions are forwarded upstream, even as it passes through a
1529 * bridge where the target device is downstream.
1531 #define REQ_ACS_FLAGS (PCI_ACS_SV | PCI_ACS_RR | PCI_ACS_CR | PCI_ACS_UF)
1534 * For multifunction devices which are not isolated from each other, find
1535 * all the other non-isolated functions and look for existing groups. For
1536 * each function, we also need to look for aliases to or from other devices
1537 * that may already have a group.
1539 static struct iommu_group *get_pci_function_alias_group(struct pci_dev *pdev,
1540 unsigned long *devfns)
1542 struct pci_dev *tmp = NULL;
1543 struct iommu_group *group;
1545 if (!pdev->multifunction || pci_acs_enabled(pdev, REQ_ACS_FLAGS))
1548 for_each_pci_dev(tmp) {
1549 if (tmp == pdev || tmp->bus != pdev->bus ||
1550 PCI_SLOT(tmp->devfn) != PCI_SLOT(pdev->devfn) ||
1551 pci_acs_enabled(tmp, REQ_ACS_FLAGS))
1554 group = get_pci_alias_group(tmp, devfns);
1565 * Look for aliases to or from the given device for existing groups. DMA
1566 * aliases are only supported on the same bus, therefore the search
1567 * space is quite small (especially since we're really only looking at pcie
1568 * device, and therefore only expect multiple slots on the root complex or
1569 * downstream switch ports). It's conceivable though that a pair of
1570 * multifunction devices could have aliases between them that would cause a
1571 * loop. To prevent this, we use a bitmap to track where we've been.
1573 static struct iommu_group *get_pci_alias_group(struct pci_dev *pdev,
1574 unsigned long *devfns)
1576 struct pci_dev *tmp = NULL;
1577 struct iommu_group *group;
1579 if (test_and_set_bit(pdev->devfn & 0xff, devfns))
1582 group = iommu_group_get(&pdev->dev);
1586 for_each_pci_dev(tmp) {
1587 if (tmp == pdev || tmp->bus != pdev->bus)
1590 /* We alias them or they alias us */
1591 if (pci_devs_are_dma_aliases(pdev, tmp)) {
1592 group = get_pci_alias_group(tmp, devfns);
1598 group = get_pci_function_alias_group(tmp, devfns);
1609 struct group_for_pci_data {
1610 struct pci_dev *pdev;
1611 struct iommu_group *group;
1615 * DMA alias iterator callback, return the last seen device. Stop and return
1616 * the IOMMU group if we find one along the way.
1618 static int get_pci_alias_or_group(struct pci_dev *pdev, u16 alias, void *opaque)
1620 struct group_for_pci_data *data = opaque;
1623 data->group = iommu_group_get(&pdev->dev);
1625 return data->group != NULL;
1629 * Generic device_group call-back function. It just allocates one
1630 * iommu-group per device.
1632 struct iommu_group *generic_device_group(struct device *dev)
1634 return iommu_group_alloc();
1636 EXPORT_SYMBOL_GPL(generic_device_group);
1639 * Use standard PCI bus topology, isolation features, and DMA alias quirks
1640 * to find or create an IOMMU group for a device.
1642 struct iommu_group *pci_device_group(struct device *dev)
1644 struct pci_dev *pdev = to_pci_dev(dev);
1645 struct group_for_pci_data data;
1646 struct pci_bus *bus;
1647 struct iommu_group *group = NULL;
1648 u64 devfns[4] = { 0 };
1650 if (WARN_ON(!dev_is_pci(dev)))
1651 return ERR_PTR(-EINVAL);
1654 * Find the upstream DMA alias for the device. A device must not
1655 * be aliased due to topology in order to have its own IOMMU group.
1656 * If we find an alias along the way that already belongs to a
1659 if (pci_for_each_dma_alias(pdev, get_pci_alias_or_group, &data))
1665 * Continue upstream from the point of minimum IOMMU granularity
1666 * due to aliases to the point where devices are protected from
1667 * peer-to-peer DMA by PCI ACS. Again, if we find an existing
1670 for (bus = pdev->bus; !pci_is_root_bus(bus); bus = bus->parent) {
1674 if (pci_acs_path_enabled(bus->self, NULL, REQ_ACS_FLAGS))
1679 group = iommu_group_get(&pdev->dev);
1685 * Look for existing groups on device aliases. If we alias another
1686 * device or another device aliases us, use the same group.
1688 group = get_pci_alias_group(pdev, (unsigned long *)devfns);
1693 * Look for existing groups on non-isolated functions on the same
1694 * slot and aliases of those funcions, if any. No need to clear
1695 * the search bitmap, the tested devfns are still valid.
1697 group = get_pci_function_alias_group(pdev, (unsigned long *)devfns);
1701 /* No shared group found, allocate new */
1702 return iommu_group_alloc();
1704 EXPORT_SYMBOL_GPL(pci_device_group);
1706 /* Get the IOMMU group for device on fsl-mc bus */
1707 struct iommu_group *fsl_mc_device_group(struct device *dev)
1709 struct device *cont_dev = fsl_mc_cont_dev(dev);
1710 struct iommu_group *group;
1712 group = iommu_group_get(cont_dev);
1714 group = iommu_group_alloc();
1717 EXPORT_SYMBOL_GPL(fsl_mc_device_group);
1719 static int iommu_get_def_domain_type(struct device *dev)
1721 const struct iommu_ops *ops = dev_iommu_ops(dev);
1723 if (dev_is_pci(dev) && to_pci_dev(dev)->untrusted)
1724 return IOMMU_DOMAIN_DMA;
1726 if (ops->def_domain_type)
1727 return ops->def_domain_type(dev);
1732 static struct iommu_domain *
1733 __iommu_group_alloc_default_domain(const struct bus_type *bus,
1734 struct iommu_group *group, int req_type)
1736 if (group->default_domain && group->default_domain->type == req_type)
1737 return group->default_domain;
1738 return __iommu_domain_alloc(bus, req_type);
1742 * req_type of 0 means "auto" which means to select a domain based on
1743 * iommu_def_domain_type or what the driver actually supports.
1745 static struct iommu_domain *
1746 iommu_group_alloc_default_domain(struct iommu_group *group, int req_type)
1748 const struct bus_type *bus =
1749 list_first_entry(&group->devices, struct group_device, list)
1751 struct iommu_domain *dom;
1753 lockdep_assert_held(&group->mutex);
1756 return __iommu_group_alloc_default_domain(bus, group, req_type);
1758 /* The driver gave no guidance on what type to use, try the default */
1759 dom = __iommu_group_alloc_default_domain(bus, group, iommu_def_domain_type);
1763 /* Otherwise IDENTITY and DMA_FQ defaults will try DMA */
1764 if (iommu_def_domain_type == IOMMU_DOMAIN_DMA)
1766 dom = __iommu_group_alloc_default_domain(bus, group, IOMMU_DOMAIN_DMA);
1770 pr_warn("Failed to allocate default IOMMU domain of type %u for group %s - Falling back to IOMMU_DOMAIN_DMA",
1771 iommu_def_domain_type, group->name);
1775 struct iommu_domain *iommu_group_default_domain(struct iommu_group *group)
1777 return group->default_domain;
1780 static int probe_iommu_group(struct device *dev, void *data)
1782 struct list_head *group_list = data;
1785 ret = __iommu_probe_device(dev, group_list);
1792 static int iommu_bus_notifier(struct notifier_block *nb,
1793 unsigned long action, void *data)
1795 struct device *dev = data;
1797 if (action == BUS_NOTIFY_ADD_DEVICE) {
1800 ret = iommu_probe_device(dev);
1801 return (ret) ? NOTIFY_DONE : NOTIFY_OK;
1802 } else if (action == BUS_NOTIFY_REMOVED_DEVICE) {
1803 iommu_release_device(dev);
1810 /* A target_type of 0 will select the best domain type and cannot fail */
1811 static int iommu_get_default_domain_type(struct iommu_group *group,
1814 int best_type = target_type;
1815 struct group_device *gdev;
1816 struct device *last_dev;
1818 lockdep_assert_held(&group->mutex);
1820 for_each_group_device(group, gdev) {
1821 unsigned int type = iommu_get_def_domain_type(gdev->dev);
1823 if (best_type && type && best_type != type) {
1825 dev_err_ratelimited(
1827 "Device cannot be in %s domain\n",
1828 iommu_domain_type_str(target_type));
1834 "Device needs domain type %s, but device %s in the same iommu group requires type %s - using default\n",
1835 iommu_domain_type_str(type), dev_name(last_dev),
1836 iommu_domain_type_str(best_type));
1841 last_dev = gdev->dev;
1846 static void iommu_group_do_probe_finalize(struct device *dev)
1848 const struct iommu_ops *ops = dev_iommu_ops(dev);
1850 if (ops->probe_finalize)
1851 ops->probe_finalize(dev);
1854 int bus_iommu_probe(const struct bus_type *bus)
1856 struct iommu_group *group, *next;
1857 LIST_HEAD(group_list);
1860 ret = bus_for_each_dev(bus, NULL, &group_list, probe_iommu_group);
1864 list_for_each_entry_safe(group, next, &group_list, entry) {
1865 struct group_device *gdev;
1867 mutex_lock(&group->mutex);
1869 /* Remove item from the list */
1870 list_del_init(&group->entry);
1873 * We go to the trouble of deferred default domain creation so
1874 * that the cross-group default domain type and the setup of the
1875 * IOMMU_RESV_DIRECT will work correctly in non-hotpug scenarios.
1877 ret = iommu_setup_default_domain(group, 0);
1879 mutex_unlock(&group->mutex);
1882 mutex_unlock(&group->mutex);
1885 * FIXME: Mis-locked because the ops->probe_finalize() call-back
1886 * of some IOMMU drivers calls arm_iommu_attach_device() which
1887 * in-turn might call back into IOMMU core code, where it tries
1888 * to take group->mutex, resulting in a deadlock.
1890 for_each_group_device(group, gdev)
1891 iommu_group_do_probe_finalize(gdev->dev);
1897 bool iommu_present(const struct bus_type *bus)
1899 return bus->iommu_ops != NULL;
1901 EXPORT_SYMBOL_GPL(iommu_present);
1904 * device_iommu_capable() - check for a general IOMMU capability
1905 * @dev: device to which the capability would be relevant, if available
1906 * @cap: IOMMU capability
1908 * Return: true if an IOMMU is present and supports the given capability
1909 * for the given device, otherwise false.
1911 bool device_iommu_capable(struct device *dev, enum iommu_cap cap)
1913 const struct iommu_ops *ops;
1915 if (!dev->iommu || !dev->iommu->iommu_dev)
1918 ops = dev_iommu_ops(dev);
1922 return ops->capable(dev, cap);
1924 EXPORT_SYMBOL_GPL(device_iommu_capable);
1927 * iommu_group_has_isolated_msi() - Compute msi_device_has_isolated_msi()
1929 * @group: Group to query
1931 * IOMMU groups should not have differing values of
1932 * msi_device_has_isolated_msi() for devices in a group. However nothing
1933 * directly prevents this, so ensure mistakes don't result in isolation failures
1934 * by checking that all the devices are the same.
1936 bool iommu_group_has_isolated_msi(struct iommu_group *group)
1938 struct group_device *group_dev;
1941 mutex_lock(&group->mutex);
1942 for_each_group_device(group, group_dev)
1943 ret &= msi_device_has_isolated_msi(group_dev->dev);
1944 mutex_unlock(&group->mutex);
1947 EXPORT_SYMBOL_GPL(iommu_group_has_isolated_msi);
1950 * iommu_set_fault_handler() - set a fault handler for an iommu domain
1951 * @domain: iommu domain
1952 * @handler: fault handler
1953 * @token: user data, will be passed back to the fault handler
1955 * This function should be used by IOMMU users which want to be notified
1956 * whenever an IOMMU fault happens.
1958 * The fault handler itself should return 0 on success, and an appropriate
1959 * error code otherwise.
1961 void iommu_set_fault_handler(struct iommu_domain *domain,
1962 iommu_fault_handler_t handler,
1967 domain->handler = handler;
1968 domain->handler_token = token;
1970 EXPORT_SYMBOL_GPL(iommu_set_fault_handler);
1972 static struct iommu_domain *__iommu_domain_alloc(const struct bus_type *bus,
1975 struct iommu_domain *domain;
1976 unsigned int alloc_type = type & IOMMU_DOMAIN_ALLOC_FLAGS;
1978 if (bus == NULL || bus->iommu_ops == NULL)
1981 domain = bus->iommu_ops->domain_alloc(alloc_type);
1985 domain->type = type;
1987 * If not already set, assume all sizes by default; the driver
1988 * may override this later
1990 if (!domain->pgsize_bitmap)
1991 domain->pgsize_bitmap = bus->iommu_ops->pgsize_bitmap;
1994 domain->ops = bus->iommu_ops->default_domain_ops;
1996 if (iommu_is_dma_domain(domain) && iommu_get_dma_cookie(domain)) {
1997 iommu_domain_free(domain);
2003 struct iommu_domain *iommu_domain_alloc(const struct bus_type *bus)
2005 return __iommu_domain_alloc(bus, IOMMU_DOMAIN_UNMANAGED);
2007 EXPORT_SYMBOL_GPL(iommu_domain_alloc);
2009 void iommu_domain_free(struct iommu_domain *domain)
2011 if (domain->type == IOMMU_DOMAIN_SVA)
2013 iommu_put_dma_cookie(domain);
2014 domain->ops->free(domain);
2016 EXPORT_SYMBOL_GPL(iommu_domain_free);
2019 * Put the group's domain back to the appropriate core-owned domain - either the
2020 * standard kernel-mode DMA configuration or an all-DMA-blocked domain.
2022 static void __iommu_group_set_core_domain(struct iommu_group *group)
2024 struct iommu_domain *new_domain;
2027 new_domain = group->blocking_domain;
2029 new_domain = group->default_domain;
2031 __iommu_group_set_domain_nofail(group, new_domain);
2034 static int __iommu_attach_device(struct iommu_domain *domain,
2039 if (unlikely(domain->ops->attach_dev == NULL))
2042 ret = domain->ops->attach_dev(domain, dev);
2045 dev->iommu->attach_deferred = 0;
2046 trace_attach_device_to_domain(dev);
2051 * iommu_attach_device - Attach an IOMMU domain to a device
2052 * @domain: IOMMU domain to attach
2053 * @dev: Device that will be attached
2055 * Returns 0 on success and error code on failure
2057 * Note that EINVAL can be treated as a soft failure, indicating
2058 * that certain configuration of the domain is incompatible with
2059 * the device. In this case attaching a different domain to the
2060 * device may succeed.
2062 int iommu_attach_device(struct iommu_domain *domain, struct device *dev)
2064 struct iommu_group *group;
2067 group = iommu_group_get(dev);
2072 * Lock the group to make sure the device-count doesn't
2073 * change while we are attaching
2075 mutex_lock(&group->mutex);
2077 if (list_count_nodes(&group->devices) != 1)
2080 ret = __iommu_attach_group(domain, group);
2083 mutex_unlock(&group->mutex);
2084 iommu_group_put(group);
2088 EXPORT_SYMBOL_GPL(iommu_attach_device);
2090 int iommu_deferred_attach(struct device *dev, struct iommu_domain *domain)
2092 if (dev->iommu && dev->iommu->attach_deferred)
2093 return __iommu_attach_device(domain, dev);
2098 void iommu_detach_device(struct iommu_domain *domain, struct device *dev)
2100 struct iommu_group *group;
2102 group = iommu_group_get(dev);
2106 mutex_lock(&group->mutex);
2107 if (WARN_ON(domain != group->domain) ||
2108 WARN_ON(list_count_nodes(&group->devices) != 1))
2110 __iommu_group_set_core_domain(group);
2113 mutex_unlock(&group->mutex);
2114 iommu_group_put(group);
2116 EXPORT_SYMBOL_GPL(iommu_detach_device);
2118 struct iommu_domain *iommu_get_domain_for_dev(struct device *dev)
2120 struct iommu_domain *domain;
2121 struct iommu_group *group;
2123 group = iommu_group_get(dev);
2127 domain = group->domain;
2129 iommu_group_put(group);
2133 EXPORT_SYMBOL_GPL(iommu_get_domain_for_dev);
2136 * For IOMMU_DOMAIN_DMA implementations which already provide their own
2137 * guarantees that the group and its default domain are valid and correct.
2139 struct iommu_domain *iommu_get_dma_domain(struct device *dev)
2141 return dev->iommu_group->default_domain;
2144 static int __iommu_attach_group(struct iommu_domain *domain,
2145 struct iommu_group *group)
2147 if (group->domain && group->domain != group->default_domain &&
2148 group->domain != group->blocking_domain)
2151 return __iommu_group_set_domain(group, domain);
2155 * iommu_attach_group - Attach an IOMMU domain to an IOMMU group
2156 * @domain: IOMMU domain to attach
2157 * @group: IOMMU group that will be attached
2159 * Returns 0 on success and error code on failure
2161 * Note that EINVAL can be treated as a soft failure, indicating
2162 * that certain configuration of the domain is incompatible with
2163 * the group. In this case attaching a different domain to the
2164 * group may succeed.
2166 int iommu_attach_group(struct iommu_domain *domain, struct iommu_group *group)
2170 mutex_lock(&group->mutex);
2171 ret = __iommu_attach_group(domain, group);
2172 mutex_unlock(&group->mutex);
2176 EXPORT_SYMBOL_GPL(iommu_attach_group);
2179 * iommu_group_replace_domain - replace the domain that a group is attached to
2180 * @new_domain: new IOMMU domain to replace with
2181 * @group: IOMMU group that will be attached to the new domain
2183 * This API allows the group to switch domains without being forced to go to
2184 * the blocking domain in-between.
2186 * If the currently attached domain is a core domain (e.g. a default_domain),
2187 * it will act just like the iommu_attach_group().
2189 int iommu_group_replace_domain(struct iommu_group *group,
2190 struct iommu_domain *new_domain)
2197 mutex_lock(&group->mutex);
2198 ret = __iommu_group_set_domain(group, new_domain);
2199 mutex_unlock(&group->mutex);
2202 EXPORT_SYMBOL_NS_GPL(iommu_group_replace_domain, IOMMUFD_INTERNAL);
2204 static int __iommu_device_set_domain(struct iommu_group *group,
2206 struct iommu_domain *new_domain,
2212 * If the device requires IOMMU_RESV_DIRECT then we cannot allow
2213 * the blocking domain to be attached as it does not contain the
2214 * required 1:1 mapping. This test effectively excludes the device
2215 * being used with iommu_group_claim_dma_owner() which will block
2216 * vfio and iommufd as well.
2218 if (dev->iommu->require_direct &&
2219 (new_domain->type == IOMMU_DOMAIN_BLOCKED ||
2220 new_domain == group->blocking_domain)) {
2222 "Firmware has requested this device have a 1:1 IOMMU mapping, rejecting configuring the device without a 1:1 mapping. Contact your platform vendor.\n");
2226 if (dev->iommu->attach_deferred) {
2227 if (new_domain == group->default_domain)
2229 dev->iommu->attach_deferred = 0;
2232 ret = __iommu_attach_device(new_domain, dev);
2235 * If we have a blocking domain then try to attach that in hopes
2236 * of avoiding a UAF. Modern drivers should implement blocking
2237 * domains as global statics that cannot fail.
2239 if ((flags & IOMMU_SET_DOMAIN_MUST_SUCCEED) &&
2240 group->blocking_domain &&
2241 group->blocking_domain != new_domain)
2242 __iommu_attach_device(group->blocking_domain, dev);
2249 * If 0 is returned the group's domain is new_domain. If an error is returned
2250 * then the group's domain will be set back to the existing domain unless
2251 * IOMMU_SET_DOMAIN_MUST_SUCCEED, otherwise an error is returned and the group's
2252 * domains is left inconsistent. This is a driver bug to fail attach with a
2253 * previously good domain. We try to avoid a kernel UAF because of this.
2255 * IOMMU groups are really the natural working unit of the IOMMU, but the IOMMU
2256 * API works on domains and devices. Bridge that gap by iterating over the
2257 * devices in a group. Ideally we'd have a single device which represents the
2258 * requestor ID of the group, but we also allow IOMMU drivers to create policy
2259 * defined minimum sets, where the physical hardware may be able to distiguish
2260 * members, but we wish to group them at a higher level (ex. untrusted
2261 * multi-function PCI devices). Thus we attach each device.
2263 static int __iommu_group_set_domain_internal(struct iommu_group *group,
2264 struct iommu_domain *new_domain,
2267 struct group_device *last_gdev;
2268 struct group_device *gdev;
2272 lockdep_assert_held(&group->mutex);
2274 if (group->domain == new_domain)
2278 * New drivers should support default domains, so set_platform_dma()
2279 * op will never be called. Otherwise the NULL domain represents some
2280 * platform specific behavior.
2283 for_each_group_device(group, gdev) {
2284 const struct iommu_ops *ops = dev_iommu_ops(gdev->dev);
2286 if (!WARN_ON(!ops->set_platform_dma_ops))
2287 ops->set_platform_dma_ops(gdev->dev);
2289 group->domain = NULL;
2294 * Changing the domain is done by calling attach_dev() on the new
2295 * domain. This switch does not have to be atomic and DMA can be
2296 * discarded during the transition. DMA must only be able to access
2297 * either new_domain or group->domain, never something else.
2300 for_each_group_device(group, gdev) {
2301 ret = __iommu_device_set_domain(group, gdev->dev, new_domain,
2306 * Keep trying the other devices in the group. If a
2307 * driver fails attach to an otherwise good domain, and
2308 * does not support blocking domains, it should at least
2309 * drop its reference on the current domain so we don't
2312 if (flags & IOMMU_SET_DOMAIN_MUST_SUCCEED)
2317 group->domain = new_domain;
2322 * This is called in error unwind paths. A well behaved driver should
2323 * always allow us to attach to a domain that was already attached.
2326 for_each_group_device(group, gdev) {
2327 const struct iommu_ops *ops = dev_iommu_ops(gdev->dev);
2330 * If set_platform_dma_ops is not present a NULL domain can
2331 * happen only for first probe, in which case we leave
2332 * group->domain as NULL and let release clean everything up.
2335 WARN_ON(__iommu_device_set_domain(
2336 group, gdev->dev, group->domain,
2337 IOMMU_SET_DOMAIN_MUST_SUCCEED));
2338 else if (ops->set_platform_dma_ops)
2339 ops->set_platform_dma_ops(gdev->dev);
2340 if (gdev == last_gdev)
2346 void iommu_detach_group(struct iommu_domain *domain, struct iommu_group *group)
2348 mutex_lock(&group->mutex);
2349 __iommu_group_set_core_domain(group);
2350 mutex_unlock(&group->mutex);
2352 EXPORT_SYMBOL_GPL(iommu_detach_group);
2354 phys_addr_t iommu_iova_to_phys(struct iommu_domain *domain, dma_addr_t iova)
2356 if (domain->type == IOMMU_DOMAIN_IDENTITY)
2359 if (domain->type == IOMMU_DOMAIN_BLOCKED)
2362 return domain->ops->iova_to_phys(domain, iova);
2364 EXPORT_SYMBOL_GPL(iommu_iova_to_phys);
2366 static size_t iommu_pgsize(struct iommu_domain *domain, unsigned long iova,
2367 phys_addr_t paddr, size_t size, size_t *count)
2369 unsigned int pgsize_idx, pgsize_idx_next;
2370 unsigned long pgsizes;
2371 size_t offset, pgsize, pgsize_next;
2372 unsigned long addr_merge = paddr | iova;
2374 /* Page sizes supported by the hardware and small enough for @size */
2375 pgsizes = domain->pgsize_bitmap & GENMASK(__fls(size), 0);
2377 /* Constrain the page sizes further based on the maximum alignment */
2378 if (likely(addr_merge))
2379 pgsizes &= GENMASK(__ffs(addr_merge), 0);
2381 /* Make sure we have at least one suitable page size */
2384 /* Pick the biggest page size remaining */
2385 pgsize_idx = __fls(pgsizes);
2386 pgsize = BIT(pgsize_idx);
2390 /* Find the next biggest support page size, if it exists */
2391 pgsizes = domain->pgsize_bitmap & ~GENMASK(pgsize_idx, 0);
2395 pgsize_idx_next = __ffs(pgsizes);
2396 pgsize_next = BIT(pgsize_idx_next);
2399 * There's no point trying a bigger page size unless the virtual
2400 * and physical addresses are similarly offset within the larger page.
2402 if ((iova ^ paddr) & (pgsize_next - 1))
2405 /* Calculate the offset to the next page size alignment boundary */
2406 offset = pgsize_next - (addr_merge & (pgsize_next - 1));
2409 * If size is big enough to accommodate the larger page, reduce
2410 * the number of smaller pages.
2412 if (offset + pgsize_next <= size)
2416 *count = size >> pgsize_idx;
2420 static int __iommu_map_pages(struct iommu_domain *domain, unsigned long iova,
2421 phys_addr_t paddr, size_t size, int prot,
2422 gfp_t gfp, size_t *mapped)
2424 const struct iommu_domain_ops *ops = domain->ops;
2425 size_t pgsize, count;
2428 pgsize = iommu_pgsize(domain, iova, paddr, size, &count);
2430 pr_debug("mapping: iova 0x%lx pa %pa pgsize 0x%zx count %zu\n",
2431 iova, &paddr, pgsize, count);
2433 if (ops->map_pages) {
2434 ret = ops->map_pages(domain, iova, paddr, pgsize, count, prot,
2437 ret = ops->map(domain, iova, paddr, pgsize, prot, gfp);
2438 *mapped = ret ? 0 : pgsize;
2444 static int __iommu_map(struct iommu_domain *domain, unsigned long iova,
2445 phys_addr_t paddr, size_t size, int prot, gfp_t gfp)
2447 const struct iommu_domain_ops *ops = domain->ops;
2448 unsigned long orig_iova = iova;
2449 unsigned int min_pagesz;
2450 size_t orig_size = size;
2451 phys_addr_t orig_paddr = paddr;
2454 if (unlikely(!(ops->map || ops->map_pages) ||
2455 domain->pgsize_bitmap == 0UL))
2458 if (unlikely(!(domain->type & __IOMMU_DOMAIN_PAGING)))
2461 /* find out the minimum page size supported */
2462 min_pagesz = 1 << __ffs(domain->pgsize_bitmap);
2465 * both the virtual address and the physical one, as well as
2466 * the size of the mapping, must be aligned (at least) to the
2467 * size of the smallest page supported by the hardware
2469 if (!IS_ALIGNED(iova | paddr | size, min_pagesz)) {
2470 pr_err("unaligned: iova 0x%lx pa %pa size 0x%zx min_pagesz 0x%x\n",
2471 iova, &paddr, size, min_pagesz);
2475 pr_debug("map: iova 0x%lx pa %pa size 0x%zx\n", iova, &paddr, size);
2480 ret = __iommu_map_pages(domain, iova, paddr, size, prot, gfp,
2483 * Some pages may have been mapped, even if an error occurred,
2484 * so we should account for those so they can be unmapped.
2495 /* unroll mapping in case something went wrong */
2497 iommu_unmap(domain, orig_iova, orig_size - size);
2499 trace_map(orig_iova, orig_paddr, orig_size);
2504 int iommu_map(struct iommu_domain *domain, unsigned long iova,
2505 phys_addr_t paddr, size_t size, int prot, gfp_t gfp)
2507 const struct iommu_domain_ops *ops = domain->ops;
2510 might_sleep_if(gfpflags_allow_blocking(gfp));
2512 /* Discourage passing strange GFP flags */
2513 if (WARN_ON_ONCE(gfp & (__GFP_COMP | __GFP_DMA | __GFP_DMA32 |
2517 ret = __iommu_map(domain, iova, paddr, size, prot, gfp);
2518 if (ret == 0 && ops->iotlb_sync_map)
2519 ops->iotlb_sync_map(domain, iova, size);
2523 EXPORT_SYMBOL_GPL(iommu_map);
2525 static size_t __iommu_unmap_pages(struct iommu_domain *domain,
2526 unsigned long iova, size_t size,
2527 struct iommu_iotlb_gather *iotlb_gather)
2529 const struct iommu_domain_ops *ops = domain->ops;
2530 size_t pgsize, count;
2532 pgsize = iommu_pgsize(domain, iova, iova, size, &count);
2533 return ops->unmap_pages ?
2534 ops->unmap_pages(domain, iova, pgsize, count, iotlb_gather) :
2535 ops->unmap(domain, iova, pgsize, iotlb_gather);
2538 static size_t __iommu_unmap(struct iommu_domain *domain,
2539 unsigned long iova, size_t size,
2540 struct iommu_iotlb_gather *iotlb_gather)
2542 const struct iommu_domain_ops *ops = domain->ops;
2543 size_t unmapped_page, unmapped = 0;
2544 unsigned long orig_iova = iova;
2545 unsigned int min_pagesz;
2547 if (unlikely(!(ops->unmap || ops->unmap_pages) ||
2548 domain->pgsize_bitmap == 0UL))
2551 if (unlikely(!(domain->type & __IOMMU_DOMAIN_PAGING)))
2554 /* find out the minimum page size supported */
2555 min_pagesz = 1 << __ffs(domain->pgsize_bitmap);
2558 * The virtual address, as well as the size of the mapping, must be
2559 * aligned (at least) to the size of the smallest page supported
2562 if (!IS_ALIGNED(iova | size, min_pagesz)) {
2563 pr_err("unaligned: iova 0x%lx size 0x%zx min_pagesz 0x%x\n",
2564 iova, size, min_pagesz);
2568 pr_debug("unmap this: iova 0x%lx size 0x%zx\n", iova, size);
2571 * Keep iterating until we either unmap 'size' bytes (or more)
2572 * or we hit an area that isn't mapped.
2574 while (unmapped < size) {
2575 unmapped_page = __iommu_unmap_pages(domain, iova,
2581 pr_debug("unmapped: iova 0x%lx size 0x%zx\n",
2582 iova, unmapped_page);
2584 iova += unmapped_page;
2585 unmapped += unmapped_page;
2588 trace_unmap(orig_iova, size, unmapped);
2592 size_t iommu_unmap(struct iommu_domain *domain,
2593 unsigned long iova, size_t size)
2595 struct iommu_iotlb_gather iotlb_gather;
2598 iommu_iotlb_gather_init(&iotlb_gather);
2599 ret = __iommu_unmap(domain, iova, size, &iotlb_gather);
2600 iommu_iotlb_sync(domain, &iotlb_gather);
2604 EXPORT_SYMBOL_GPL(iommu_unmap);
2606 size_t iommu_unmap_fast(struct iommu_domain *domain,
2607 unsigned long iova, size_t size,
2608 struct iommu_iotlb_gather *iotlb_gather)
2610 return __iommu_unmap(domain, iova, size, iotlb_gather);
2612 EXPORT_SYMBOL_GPL(iommu_unmap_fast);
2614 ssize_t iommu_map_sg(struct iommu_domain *domain, unsigned long iova,
2615 struct scatterlist *sg, unsigned int nents, int prot,
2618 const struct iommu_domain_ops *ops = domain->ops;
2619 size_t len = 0, mapped = 0;
2624 might_sleep_if(gfpflags_allow_blocking(gfp));
2626 /* Discourage passing strange GFP flags */
2627 if (WARN_ON_ONCE(gfp & (__GFP_COMP | __GFP_DMA | __GFP_DMA32 |
2631 while (i <= nents) {
2632 phys_addr_t s_phys = sg_phys(sg);
2634 if (len && s_phys != start + len) {
2635 ret = __iommu_map(domain, iova + mapped, start,
2645 if (sg_dma_is_bus_address(sg))
2660 if (ops->iotlb_sync_map)
2661 ops->iotlb_sync_map(domain, iova, mapped);
2665 /* undo mappings already done */
2666 iommu_unmap(domain, iova, mapped);
2670 EXPORT_SYMBOL_GPL(iommu_map_sg);
2673 * report_iommu_fault() - report about an IOMMU fault to the IOMMU framework
2674 * @domain: the iommu domain where the fault has happened
2675 * @dev: the device where the fault has happened
2676 * @iova: the faulting address
2677 * @flags: mmu fault flags (e.g. IOMMU_FAULT_READ/IOMMU_FAULT_WRITE/...)
2679 * This function should be called by the low-level IOMMU implementations
2680 * whenever IOMMU faults happen, to allow high-level users, that are
2681 * interested in such events, to know about them.
2683 * This event may be useful for several possible use cases:
2684 * - mere logging of the event
2685 * - dynamic TLB/PTE loading
2686 * - if restarting of the faulting device is required
2688 * Returns 0 on success and an appropriate error code otherwise (if dynamic
2689 * PTE/TLB loading will one day be supported, implementations will be able
2690 * to tell whether it succeeded or not according to this return value).
2692 * Specifically, -ENOSYS is returned if a fault handler isn't installed
2693 * (though fault handlers can also return -ENOSYS, in case they want to
2694 * elicit the default behavior of the IOMMU drivers).
2696 int report_iommu_fault(struct iommu_domain *domain, struct device *dev,
2697 unsigned long iova, int flags)
2702 * if upper layers showed interest and installed a fault handler,
2705 if (domain->handler)
2706 ret = domain->handler(domain, dev, iova, flags,
2707 domain->handler_token);
2709 trace_io_page_fault(dev, iova, flags);
2712 EXPORT_SYMBOL_GPL(report_iommu_fault);
2714 static int __init iommu_init(void)
2716 iommu_group_kset = kset_create_and_add("iommu_groups",
2718 BUG_ON(!iommu_group_kset);
2720 iommu_debugfs_setup();
2724 core_initcall(iommu_init);
2726 int iommu_enable_nesting(struct iommu_domain *domain)
2728 if (domain->type != IOMMU_DOMAIN_UNMANAGED)
2730 if (!domain->ops->enable_nesting)
2732 return domain->ops->enable_nesting(domain);
2734 EXPORT_SYMBOL_GPL(iommu_enable_nesting);
2736 int iommu_set_pgtable_quirks(struct iommu_domain *domain,
2737 unsigned long quirk)
2739 if (domain->type != IOMMU_DOMAIN_UNMANAGED)
2741 if (!domain->ops->set_pgtable_quirks)
2743 return domain->ops->set_pgtable_quirks(domain, quirk);
2745 EXPORT_SYMBOL_GPL(iommu_set_pgtable_quirks);
2748 * iommu_get_resv_regions - get reserved regions
2749 * @dev: device for which to get reserved regions
2750 * @list: reserved region list for device
2752 * This returns a list of reserved IOVA regions specific to this device.
2753 * A domain user should not map IOVA in these ranges.
2755 void iommu_get_resv_regions(struct device *dev, struct list_head *list)
2757 const struct iommu_ops *ops = dev_iommu_ops(dev);
2759 if (ops->get_resv_regions)
2760 ops->get_resv_regions(dev, list);
2762 EXPORT_SYMBOL_GPL(iommu_get_resv_regions);
2765 * iommu_put_resv_regions - release reserved regions
2766 * @dev: device for which to free reserved regions
2767 * @list: reserved region list for device
2769 * This releases a reserved region list acquired by iommu_get_resv_regions().
2771 void iommu_put_resv_regions(struct device *dev, struct list_head *list)
2773 struct iommu_resv_region *entry, *next;
2775 list_for_each_entry_safe(entry, next, list, list) {
2777 entry->free(dev, entry);
2782 EXPORT_SYMBOL(iommu_put_resv_regions);
2784 struct iommu_resv_region *iommu_alloc_resv_region(phys_addr_t start,
2785 size_t length, int prot,
2786 enum iommu_resv_type type,
2789 struct iommu_resv_region *region;
2791 region = kzalloc(sizeof(*region), gfp);
2795 INIT_LIST_HEAD(®ion->list);
2796 region->start = start;
2797 region->length = length;
2798 region->prot = prot;
2799 region->type = type;
2802 EXPORT_SYMBOL_GPL(iommu_alloc_resv_region);
2804 void iommu_set_default_passthrough(bool cmd_line)
2807 iommu_cmd_line |= IOMMU_CMD_LINE_DMA_API;
2808 iommu_def_domain_type = IOMMU_DOMAIN_IDENTITY;
2811 void iommu_set_default_translated(bool cmd_line)
2814 iommu_cmd_line |= IOMMU_CMD_LINE_DMA_API;
2815 iommu_def_domain_type = IOMMU_DOMAIN_DMA;
2818 bool iommu_default_passthrough(void)
2820 return iommu_def_domain_type == IOMMU_DOMAIN_IDENTITY;
2822 EXPORT_SYMBOL_GPL(iommu_default_passthrough);
2824 const struct iommu_ops *iommu_ops_from_fwnode(struct fwnode_handle *fwnode)
2826 const struct iommu_ops *ops = NULL;
2827 struct iommu_device *iommu;
2829 spin_lock(&iommu_device_lock);
2830 list_for_each_entry(iommu, &iommu_device_list, list)
2831 if (iommu->fwnode == fwnode) {
2835 spin_unlock(&iommu_device_lock);
2839 int iommu_fwspec_init(struct device *dev, struct fwnode_handle *iommu_fwnode,
2840 const struct iommu_ops *ops)
2842 struct iommu_fwspec *fwspec = dev_iommu_fwspec_get(dev);
2845 return ops == fwspec->ops ? 0 : -EINVAL;
2847 if (!dev_iommu_get(dev))
2850 /* Preallocate for the overwhelmingly common case of 1 ID */
2851 fwspec = kzalloc(struct_size(fwspec, ids, 1), GFP_KERNEL);
2855 of_node_get(to_of_node(iommu_fwnode));
2856 fwspec->iommu_fwnode = iommu_fwnode;
2858 dev_iommu_fwspec_set(dev, fwspec);
2861 EXPORT_SYMBOL_GPL(iommu_fwspec_init);
2863 void iommu_fwspec_free(struct device *dev)
2865 struct iommu_fwspec *fwspec = dev_iommu_fwspec_get(dev);
2868 fwnode_handle_put(fwspec->iommu_fwnode);
2870 dev_iommu_fwspec_set(dev, NULL);
2873 EXPORT_SYMBOL_GPL(iommu_fwspec_free);
2875 int iommu_fwspec_add_ids(struct device *dev, u32 *ids, int num_ids)
2877 struct iommu_fwspec *fwspec = dev_iommu_fwspec_get(dev);
2883 new_num = fwspec->num_ids + num_ids;
2885 fwspec = krealloc(fwspec, struct_size(fwspec, ids, new_num),
2890 dev_iommu_fwspec_set(dev, fwspec);
2893 for (i = 0; i < num_ids; i++)
2894 fwspec->ids[fwspec->num_ids + i] = ids[i];
2896 fwspec->num_ids = new_num;
2899 EXPORT_SYMBOL_GPL(iommu_fwspec_add_ids);
2902 * Per device IOMMU features.
2904 int iommu_dev_enable_feature(struct device *dev, enum iommu_dev_features feat)
2906 if (dev->iommu && dev->iommu->iommu_dev) {
2907 const struct iommu_ops *ops = dev->iommu->iommu_dev->ops;
2909 if (ops->dev_enable_feat)
2910 return ops->dev_enable_feat(dev, feat);
2915 EXPORT_SYMBOL_GPL(iommu_dev_enable_feature);
2918 * The device drivers should do the necessary cleanups before calling this.
2920 int iommu_dev_disable_feature(struct device *dev, enum iommu_dev_features feat)
2922 if (dev->iommu && dev->iommu->iommu_dev) {
2923 const struct iommu_ops *ops = dev->iommu->iommu_dev->ops;
2925 if (ops->dev_disable_feat)
2926 return ops->dev_disable_feat(dev, feat);
2931 EXPORT_SYMBOL_GPL(iommu_dev_disable_feature);
2934 * iommu_setup_default_domain - Set the default_domain for the group
2935 * @group: Group to change
2936 * @target_type: Domain type to set as the default_domain
2938 * Allocate a default domain and set it as the current domain on the group. If
2939 * the group already has a default domain it will be changed to the target_type.
2940 * When target_type is 0 the default domain is selected based on driver and
2941 * system preferences.
2943 static int iommu_setup_default_domain(struct iommu_group *group,
2946 struct iommu_domain *old_dom = group->default_domain;
2947 struct group_device *gdev;
2948 struct iommu_domain *dom;
2953 lockdep_assert_held(&group->mutex);
2955 req_type = iommu_get_default_domain_type(group, target_type);
2960 * There are still some drivers which don't support default domains, so
2961 * we ignore the failure and leave group->default_domain NULL.
2963 * We assume that the iommu driver starts up the device in
2964 * 'set_platform_dma_ops' mode if it does not support default domains.
2966 dom = iommu_group_alloc_default_domain(group, req_type);
2968 /* Once in default_domain mode we never leave */
2969 if (group->default_domain)
2971 group->default_domain = NULL;
2975 if (group->default_domain == dom)
2979 * IOMMU_RESV_DIRECT and IOMMU_RESV_DIRECT_RELAXABLE regions must be
2980 * mapped before their device is attached, in order to guarantee
2981 * continuity with any FW activity
2983 direct_failed = false;
2984 for_each_group_device(group, gdev) {
2985 if (iommu_create_device_direct_mappings(dom, gdev->dev)) {
2986 direct_failed = true;
2988 gdev->dev->iommu->iommu_dev->dev,
2989 "IOMMU driver was not able to establish FW requested direct mapping.");
2993 /* We must set default_domain early for __iommu_device_set_domain */
2994 group->default_domain = dom;
2995 if (!group->domain) {
2997 * Drivers are not allowed to fail the first domain attach.
2998 * The only way to recover from this is to fail attaching the
2999 * iommu driver and call ops->release_device. Put the domain
3000 * in group->default_domain so it is freed after.
3002 ret = __iommu_group_set_domain_internal(
3003 group, dom, IOMMU_SET_DOMAIN_MUST_SUCCEED);
3007 ret = __iommu_group_set_domain(group, dom);
3009 goto err_restore_def_domain;
3013 * Drivers are supposed to allow mappings to be installed in a domain
3014 * before device attachment, but some don't. Hack around this defect by
3015 * trying again after attaching. If this happens it means the device
3016 * will not continuously have the IOMMU_RESV_DIRECT map.
3018 if (direct_failed) {
3019 for_each_group_device(group, gdev) {
3020 ret = iommu_create_device_direct_mappings(dom, gdev->dev);
3022 goto err_restore_domain;
3028 iommu_domain_free(old_dom);
3033 __iommu_group_set_domain_internal(
3034 group, old_dom, IOMMU_SET_DOMAIN_MUST_SUCCEED);
3035 err_restore_def_domain:
3037 iommu_domain_free(dom);
3038 group->default_domain = old_dom;
3044 * Changing the default domain through sysfs requires the users to unbind the
3045 * drivers from the devices in the iommu group, except for a DMA -> DMA-FQ
3046 * transition. Return failure if this isn't met.
3048 * We need to consider the race between this and the device release path.
3049 * group->mutex is used here to guarantee that the device release path
3050 * will not be entered at the same time.
3052 static ssize_t iommu_group_store_type(struct iommu_group *group,
3053 const char *buf, size_t count)
3055 struct group_device *gdev;
3058 if (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO))
3061 if (WARN_ON(!group) || !group->default_domain)
3064 if (sysfs_streq(buf, "identity"))
3065 req_type = IOMMU_DOMAIN_IDENTITY;
3066 else if (sysfs_streq(buf, "DMA"))
3067 req_type = IOMMU_DOMAIN_DMA;
3068 else if (sysfs_streq(buf, "DMA-FQ"))
3069 req_type = IOMMU_DOMAIN_DMA_FQ;
3070 else if (sysfs_streq(buf, "auto"))
3075 mutex_lock(&group->mutex);
3076 /* We can bring up a flush queue without tearing down the domain. */
3077 if (req_type == IOMMU_DOMAIN_DMA_FQ &&
3078 group->default_domain->type == IOMMU_DOMAIN_DMA) {
3079 ret = iommu_dma_init_fq(group->default_domain);
3083 group->default_domain->type = IOMMU_DOMAIN_DMA_FQ;
3088 /* Otherwise, ensure that device exists and no driver is bound. */
3089 if (list_empty(&group->devices) || group->owner_cnt) {
3094 ret = iommu_setup_default_domain(group, req_type);
3099 * Release the mutex here because ops->probe_finalize() call-back of
3100 * some vendor IOMMU drivers calls arm_iommu_attach_device() which
3101 * in-turn might call back into IOMMU core code, where it tries to take
3102 * group->mutex, resulting in a deadlock.
3104 mutex_unlock(&group->mutex);
3106 /* Make sure dma_ops is appropriatley set */
3107 for_each_group_device(group, gdev)
3108 iommu_group_do_probe_finalize(gdev->dev);
3112 mutex_unlock(&group->mutex);
3113 return ret ?: count;
3116 static bool iommu_is_default_domain(struct iommu_group *group)
3118 if (group->domain == group->default_domain)
3122 * If the default domain was set to identity and it is still an identity
3123 * domain then we consider this a pass. This happens because of
3124 * amd_iommu_init_device() replacing the default idenytity domain with an
3125 * identity domain that has a different configuration for AMDGPU.
3127 if (group->default_domain &&
3128 group->default_domain->type == IOMMU_DOMAIN_IDENTITY &&
3129 group->domain && group->domain->type == IOMMU_DOMAIN_IDENTITY)
3135 * iommu_device_use_default_domain() - Device driver wants to handle device
3136 * DMA through the kernel DMA API.
3139 * The device driver about to bind @dev wants to do DMA through the kernel
3140 * DMA API. Return 0 if it is allowed, otherwise an error.
3142 int iommu_device_use_default_domain(struct device *dev)
3144 struct iommu_group *group = iommu_group_get(dev);
3150 mutex_lock(&group->mutex);
3151 if (group->owner_cnt) {
3152 if (group->owner || !iommu_is_default_domain(group) ||
3153 !xa_empty(&group->pasid_array)) {
3162 mutex_unlock(&group->mutex);
3163 iommu_group_put(group);
3169 * iommu_device_unuse_default_domain() - Device driver stops handling device
3170 * DMA through the kernel DMA API.
3173 * The device driver doesn't want to do DMA through kernel DMA API anymore.
3174 * It must be called after iommu_device_use_default_domain().
3176 void iommu_device_unuse_default_domain(struct device *dev)
3178 struct iommu_group *group = iommu_group_get(dev);
3183 mutex_lock(&group->mutex);
3184 if (!WARN_ON(!group->owner_cnt || !xa_empty(&group->pasid_array)))
3187 mutex_unlock(&group->mutex);
3188 iommu_group_put(group);
3191 static int __iommu_group_alloc_blocking_domain(struct iommu_group *group)
3193 struct group_device *dev =
3194 list_first_entry(&group->devices, struct group_device, list);
3196 if (group->blocking_domain)
3199 group->blocking_domain =
3200 __iommu_domain_alloc(dev->dev->bus, IOMMU_DOMAIN_BLOCKED);
3201 if (!group->blocking_domain) {
3203 * For drivers that do not yet understand IOMMU_DOMAIN_BLOCKED
3204 * create an empty domain instead.
3206 group->blocking_domain = __iommu_domain_alloc(
3207 dev->dev->bus, IOMMU_DOMAIN_UNMANAGED);
3208 if (!group->blocking_domain)
3214 static int __iommu_take_dma_ownership(struct iommu_group *group, void *owner)
3218 if ((group->domain && group->domain != group->default_domain) ||
3219 !xa_empty(&group->pasid_array))
3222 ret = __iommu_group_alloc_blocking_domain(group);
3225 ret = __iommu_group_set_domain(group, group->blocking_domain);
3229 group->owner = owner;
3235 * iommu_group_claim_dma_owner() - Set DMA ownership of a group
3236 * @group: The group.
3237 * @owner: Caller specified pointer. Used for exclusive ownership.
3239 * This is to support backward compatibility for vfio which manages the dma
3240 * ownership in iommu_group level. New invocations on this interface should be
3241 * prohibited. Only a single owner may exist for a group.
3243 int iommu_group_claim_dma_owner(struct iommu_group *group, void *owner)
3247 if (WARN_ON(!owner))
3250 mutex_lock(&group->mutex);
3251 if (group->owner_cnt) {
3256 ret = __iommu_take_dma_ownership(group, owner);
3258 mutex_unlock(&group->mutex);
3262 EXPORT_SYMBOL_GPL(iommu_group_claim_dma_owner);
3265 * iommu_device_claim_dma_owner() - Set DMA ownership of a device
3267 * @owner: Caller specified pointer. Used for exclusive ownership.
3269 * Claim the DMA ownership of a device. Multiple devices in the same group may
3270 * concurrently claim ownership if they present the same owner value. Returns 0
3271 * on success and error code on failure
3273 int iommu_device_claim_dma_owner(struct device *dev, void *owner)
3275 struct iommu_group *group;
3278 if (WARN_ON(!owner))
3281 group = iommu_group_get(dev);
3285 mutex_lock(&group->mutex);
3286 if (group->owner_cnt) {
3287 if (group->owner != owner) {
3295 ret = __iommu_take_dma_ownership(group, owner);
3297 mutex_unlock(&group->mutex);
3298 iommu_group_put(group);
3302 EXPORT_SYMBOL_GPL(iommu_device_claim_dma_owner);
3304 static void __iommu_release_dma_ownership(struct iommu_group *group)
3306 if (WARN_ON(!group->owner_cnt || !group->owner ||
3307 !xa_empty(&group->pasid_array)))
3310 group->owner_cnt = 0;
3311 group->owner = NULL;
3312 __iommu_group_set_domain_nofail(group, group->default_domain);
3316 * iommu_group_release_dma_owner() - Release DMA ownership of a group
3319 * Release the DMA ownership claimed by iommu_group_claim_dma_owner().
3321 void iommu_group_release_dma_owner(struct iommu_group *group)
3323 mutex_lock(&group->mutex);
3324 __iommu_release_dma_ownership(group);
3325 mutex_unlock(&group->mutex);
3327 EXPORT_SYMBOL_GPL(iommu_group_release_dma_owner);
3330 * iommu_device_release_dma_owner() - Release DMA ownership of a device
3333 * Release the DMA ownership claimed by iommu_device_claim_dma_owner().
3335 void iommu_device_release_dma_owner(struct device *dev)
3337 struct iommu_group *group = iommu_group_get(dev);
3339 mutex_lock(&group->mutex);
3340 if (group->owner_cnt > 1)
3343 __iommu_release_dma_ownership(group);
3344 mutex_unlock(&group->mutex);
3345 iommu_group_put(group);
3347 EXPORT_SYMBOL_GPL(iommu_device_release_dma_owner);
3350 * iommu_group_dma_owner_claimed() - Query group dma ownership status
3351 * @group: The group.
3353 * This provides status query on a given group. It is racy and only for
3354 * non-binding status reporting.
3356 bool iommu_group_dma_owner_claimed(struct iommu_group *group)
3360 mutex_lock(&group->mutex);
3361 user = group->owner_cnt;
3362 mutex_unlock(&group->mutex);
3366 EXPORT_SYMBOL_GPL(iommu_group_dma_owner_claimed);
3368 static int __iommu_set_group_pasid(struct iommu_domain *domain,
3369 struct iommu_group *group, ioasid_t pasid)
3371 struct group_device *device;
3374 for_each_group_device(group, device) {
3375 ret = domain->ops->set_dev_pasid(domain, device->dev, pasid);
3383 static void __iommu_remove_group_pasid(struct iommu_group *group,
3386 struct group_device *device;
3387 const struct iommu_ops *ops;
3389 for_each_group_device(group, device) {
3390 ops = dev_iommu_ops(device->dev);
3391 ops->remove_dev_pasid(device->dev, pasid);
3396 * iommu_attach_device_pasid() - Attach a domain to pasid of device
3397 * @domain: the iommu domain.
3398 * @dev: the attached device.
3399 * @pasid: the pasid of the device.
3401 * Return: 0 on success, or an error.
3403 int iommu_attach_device_pasid(struct iommu_domain *domain,
3404 struct device *dev, ioasid_t pasid)
3406 struct iommu_group *group;
3410 if (!domain->ops->set_dev_pasid)
3413 group = iommu_group_get(dev);
3417 mutex_lock(&group->mutex);
3418 curr = xa_cmpxchg(&group->pasid_array, pasid, NULL, domain, GFP_KERNEL);
3420 ret = xa_err(curr) ? : -EBUSY;
3424 ret = __iommu_set_group_pasid(domain, group, pasid);
3426 __iommu_remove_group_pasid(group, pasid);
3427 xa_erase(&group->pasid_array, pasid);
3430 mutex_unlock(&group->mutex);
3431 iommu_group_put(group);
3435 EXPORT_SYMBOL_GPL(iommu_attach_device_pasid);
3438 * iommu_detach_device_pasid() - Detach the domain from pasid of device
3439 * @domain: the iommu domain.
3440 * @dev: the attached device.
3441 * @pasid: the pasid of the device.
3443 * The @domain must have been attached to @pasid of the @dev with
3444 * iommu_attach_device_pasid().
3446 void iommu_detach_device_pasid(struct iommu_domain *domain, struct device *dev,
3449 struct iommu_group *group = iommu_group_get(dev);
3451 mutex_lock(&group->mutex);
3452 __iommu_remove_group_pasid(group, pasid);
3453 WARN_ON(xa_erase(&group->pasid_array, pasid) != domain);
3454 mutex_unlock(&group->mutex);
3456 iommu_group_put(group);
3458 EXPORT_SYMBOL_GPL(iommu_detach_device_pasid);
3461 * iommu_get_domain_for_dev_pasid() - Retrieve domain for @pasid of @dev
3462 * @dev: the queried device
3463 * @pasid: the pasid of the device
3464 * @type: matched domain type, 0 for any match
3466 * This is a variant of iommu_get_domain_for_dev(). It returns the existing
3467 * domain attached to pasid of a device. Callers must hold a lock around this
3468 * function, and both iommu_attach/detach_dev_pasid() whenever a domain of
3469 * type is being manipulated. This API does not internally resolve races with
3472 * Return: attached domain on success, NULL otherwise.
3474 struct iommu_domain *iommu_get_domain_for_dev_pasid(struct device *dev,
3478 struct iommu_domain *domain;
3479 struct iommu_group *group;
3481 group = iommu_group_get(dev);
3485 xa_lock(&group->pasid_array);
3486 domain = xa_load(&group->pasid_array, pasid);
3487 if (type && domain && domain->type != type)
3488 domain = ERR_PTR(-EBUSY);
3489 xa_unlock(&group->pasid_array);
3490 iommu_group_put(group);
3494 EXPORT_SYMBOL_GPL(iommu_get_domain_for_dev_pasid);
3496 struct iommu_domain *iommu_sva_domain_alloc(struct device *dev,
3497 struct mm_struct *mm)
3499 const struct iommu_ops *ops = dev_iommu_ops(dev);
3500 struct iommu_domain *domain;
3502 domain = ops->domain_alloc(IOMMU_DOMAIN_SVA);
3506 domain->type = IOMMU_DOMAIN_SVA;
3509 domain->iopf_handler = iommu_sva_handle_iopf;
3510 domain->fault_data = mm;
3515 ioasid_t iommu_alloc_global_pasid(struct device *dev)
3519 /* max_pasids == 0 means that the device does not support PASID */
3520 if (!dev->iommu->max_pasids)
3521 return IOMMU_PASID_INVALID;
3524 * max_pasids is set up by vendor driver based on number of PASID bits
3525 * supported but the IDA allocation is inclusive.
3527 ret = ida_alloc_range(&iommu_global_pasid_ida, IOMMU_FIRST_GLOBAL_PASID,
3528 dev->iommu->max_pasids - 1, GFP_KERNEL);
3529 return ret < 0 ? IOMMU_PASID_INVALID : ret;
3531 EXPORT_SYMBOL_GPL(iommu_alloc_global_pasid);
3533 void iommu_free_global_pasid(ioasid_t pasid)
3535 if (WARN_ON(pasid == IOMMU_PASID_INVALID))
3538 ida_free(&iommu_global_pasid_ida, pasid);
3540 EXPORT_SYMBOL_GPL(iommu_free_global_pasid);