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 static struct kset *iommu_group_kset;
40 static DEFINE_IDA(iommu_group_ida);
41 static DEFINE_IDA(iommu_global_pasid_ida);
43 static unsigned int iommu_def_domain_type __read_mostly;
44 static bool iommu_dma_strict __read_mostly = IS_ENABLED(CONFIG_IOMMU_DEFAULT_DMA_STRICT);
45 static u32 iommu_cmd_line __read_mostly;
49 struct kobject *devices_kobj;
50 struct list_head devices;
51 struct xarray pasid_array;
54 void (*iommu_data_release)(void *iommu_data);
57 struct iommu_domain *default_domain;
58 struct iommu_domain *blocking_domain;
59 struct iommu_domain *domain;
60 struct list_head entry;
61 unsigned int owner_cnt;
66 struct list_head list;
71 /* Iterate over each struct group_device in a struct iommu_group */
72 #define for_each_group_device(group, pos) \
73 list_for_each_entry(pos, &(group)->devices, list)
75 struct iommu_group_attribute {
76 struct attribute attr;
77 ssize_t (*show)(struct iommu_group *group, char *buf);
78 ssize_t (*store)(struct iommu_group *group,
79 const char *buf, size_t count);
82 static const char * const iommu_group_resv_type_string[] = {
83 [IOMMU_RESV_DIRECT] = "direct",
84 [IOMMU_RESV_DIRECT_RELAXABLE] = "direct-relaxable",
85 [IOMMU_RESV_RESERVED] = "reserved",
86 [IOMMU_RESV_MSI] = "msi",
87 [IOMMU_RESV_SW_MSI] = "msi",
90 #define IOMMU_CMD_LINE_DMA_API BIT(0)
91 #define IOMMU_CMD_LINE_STRICT BIT(1)
93 static int iommu_bus_notifier(struct notifier_block *nb,
94 unsigned long action, void *data);
95 static void iommu_release_device(struct device *dev);
96 static struct iommu_domain *
97 __iommu_group_domain_alloc(struct iommu_group *group, unsigned int type);
98 static int __iommu_attach_device(struct iommu_domain *domain,
100 static int __iommu_attach_group(struct iommu_domain *domain,
101 struct iommu_group *group);
104 IOMMU_SET_DOMAIN_MUST_SUCCEED = 1 << 0,
107 static int __iommu_device_set_domain(struct iommu_group *group,
109 struct iommu_domain *new_domain,
111 static int __iommu_group_set_domain_internal(struct iommu_group *group,
112 struct iommu_domain *new_domain,
114 static int __iommu_group_set_domain(struct iommu_group *group,
115 struct iommu_domain *new_domain)
117 return __iommu_group_set_domain_internal(group, new_domain, 0);
119 static void __iommu_group_set_domain_nofail(struct iommu_group *group,
120 struct iommu_domain *new_domain)
122 WARN_ON(__iommu_group_set_domain_internal(
123 group, new_domain, IOMMU_SET_DOMAIN_MUST_SUCCEED));
126 static int iommu_setup_default_domain(struct iommu_group *group,
128 static int iommu_create_device_direct_mappings(struct iommu_domain *domain,
130 static ssize_t iommu_group_store_type(struct iommu_group *group,
131 const char *buf, size_t count);
132 static struct group_device *iommu_group_alloc_device(struct iommu_group *group,
134 static void __iommu_group_free_device(struct iommu_group *group,
135 struct group_device *grp_dev);
137 #define IOMMU_GROUP_ATTR(_name, _mode, _show, _store) \
138 struct iommu_group_attribute iommu_group_attr_##_name = \
139 __ATTR(_name, _mode, _show, _store)
141 #define to_iommu_group_attr(_attr) \
142 container_of(_attr, struct iommu_group_attribute, attr)
143 #define to_iommu_group(_kobj) \
144 container_of(_kobj, struct iommu_group, kobj)
146 static LIST_HEAD(iommu_device_list);
147 static DEFINE_SPINLOCK(iommu_device_lock);
149 static const struct bus_type * const iommu_buses[] = {
154 #ifdef CONFIG_ARM_AMBA
157 #ifdef CONFIG_FSL_MC_BUS
160 #ifdef CONFIG_TEGRA_HOST1X_CONTEXT_BUS
161 &host1x_context_device_bus_type,
163 #ifdef CONFIG_CDX_BUS
169 * Use a function instead of an array here because the domain-type is a
170 * bit-field, so an array would waste memory.
172 static const char *iommu_domain_type_str(unsigned int t)
175 case IOMMU_DOMAIN_BLOCKED:
177 case IOMMU_DOMAIN_IDENTITY:
178 return "Passthrough";
179 case IOMMU_DOMAIN_UNMANAGED:
181 case IOMMU_DOMAIN_DMA:
182 case IOMMU_DOMAIN_DMA_FQ:
184 case IOMMU_DOMAIN_PLATFORM:
191 static int __init iommu_subsys_init(void)
193 struct notifier_block *nb;
195 if (!(iommu_cmd_line & IOMMU_CMD_LINE_DMA_API)) {
196 if (IS_ENABLED(CONFIG_IOMMU_DEFAULT_PASSTHROUGH))
197 iommu_set_default_passthrough(false);
199 iommu_set_default_translated(false);
201 if (iommu_default_passthrough() && cc_platform_has(CC_ATTR_MEM_ENCRYPT)) {
202 pr_info("Memory encryption detected - Disabling default IOMMU Passthrough\n");
203 iommu_set_default_translated(false);
207 if (!iommu_default_passthrough() && !iommu_dma_strict)
208 iommu_def_domain_type = IOMMU_DOMAIN_DMA_FQ;
210 pr_info("Default domain type: %s%s\n",
211 iommu_domain_type_str(iommu_def_domain_type),
212 (iommu_cmd_line & IOMMU_CMD_LINE_DMA_API) ?
213 " (set via kernel command line)" : "");
215 if (!iommu_default_passthrough())
216 pr_info("DMA domain TLB invalidation policy: %s mode%s\n",
217 iommu_dma_strict ? "strict" : "lazy",
218 (iommu_cmd_line & IOMMU_CMD_LINE_STRICT) ?
219 " (set via kernel command line)" : "");
221 nb = kcalloc(ARRAY_SIZE(iommu_buses), sizeof(*nb), GFP_KERNEL);
225 for (int i = 0; i < ARRAY_SIZE(iommu_buses); i++) {
226 nb[i].notifier_call = iommu_bus_notifier;
227 bus_register_notifier(iommu_buses[i], &nb[i]);
232 subsys_initcall(iommu_subsys_init);
234 static int remove_iommu_group(struct device *dev, void *data)
236 if (dev->iommu && dev->iommu->iommu_dev == data)
237 iommu_release_device(dev);
243 * iommu_device_register() - Register an IOMMU hardware instance
244 * @iommu: IOMMU handle for the instance
245 * @ops: IOMMU ops to associate with the instance
246 * @hwdev: (optional) actual instance device, used for fwnode lookup
248 * Return: 0 on success, or an error.
250 int iommu_device_register(struct iommu_device *iommu,
251 const struct iommu_ops *ops, struct device *hwdev)
255 /* We need to be able to take module references appropriately */
256 if (WARN_ON(is_module_address((unsigned long)ops) && !ops->owner))
261 iommu->fwnode = dev_fwnode(hwdev);
263 spin_lock(&iommu_device_lock);
264 list_add_tail(&iommu->list, &iommu_device_list);
265 spin_unlock(&iommu_device_lock);
267 for (int i = 0; i < ARRAY_SIZE(iommu_buses) && !err; i++)
268 err = bus_iommu_probe(iommu_buses[i]);
270 iommu_device_unregister(iommu);
273 EXPORT_SYMBOL_GPL(iommu_device_register);
275 void iommu_device_unregister(struct iommu_device *iommu)
277 for (int i = 0; i < ARRAY_SIZE(iommu_buses); i++)
278 bus_for_each_dev(iommu_buses[i], NULL, iommu, remove_iommu_group);
280 spin_lock(&iommu_device_lock);
281 list_del(&iommu->list);
282 spin_unlock(&iommu_device_lock);
284 /* Pairs with the alloc in generic_single_device_group() */
285 iommu_group_put(iommu->singleton_group);
286 iommu->singleton_group = NULL;
288 EXPORT_SYMBOL_GPL(iommu_device_unregister);
290 #if IS_ENABLED(CONFIG_IOMMUFD_TEST)
291 void iommu_device_unregister_bus(struct iommu_device *iommu,
292 const struct bus_type *bus,
293 struct notifier_block *nb)
295 bus_unregister_notifier(bus, nb);
296 iommu_device_unregister(iommu);
298 EXPORT_SYMBOL_GPL(iommu_device_unregister_bus);
301 * Register an iommu driver against a single bus. This is only used by iommufd
302 * selftest to create a mock iommu driver. The caller must provide
303 * some memory to hold a notifier_block.
305 int iommu_device_register_bus(struct iommu_device *iommu,
306 const struct iommu_ops *ops,
307 const struct bus_type *bus,
308 struct notifier_block *nb)
313 nb->notifier_call = iommu_bus_notifier;
314 err = bus_register_notifier(bus, nb);
318 spin_lock(&iommu_device_lock);
319 list_add_tail(&iommu->list, &iommu_device_list);
320 spin_unlock(&iommu_device_lock);
322 err = bus_iommu_probe(bus);
324 iommu_device_unregister_bus(iommu, bus, nb);
329 EXPORT_SYMBOL_GPL(iommu_device_register_bus);
332 static struct dev_iommu *dev_iommu_get(struct device *dev)
334 struct dev_iommu *param = dev->iommu;
336 lockdep_assert_held(&iommu_probe_device_lock);
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);
363 * Internal equivalent of device_iommu_mapped() for when we care that a device
364 * actually has API ops, and don't want false positives from VFIO-only groups.
366 static bool dev_has_iommu(struct device *dev)
368 return dev->iommu && dev->iommu->iommu_dev;
371 static u32 dev_iommu_get_max_pasids(struct device *dev)
373 u32 max_pasids = 0, bits = 0;
376 if (dev_is_pci(dev)) {
377 ret = pci_max_pasids(to_pci_dev(dev));
381 ret = device_property_read_u32(dev, "pasid-num-bits", &bits);
383 max_pasids = 1UL << bits;
386 return min_t(u32, max_pasids, dev->iommu->iommu_dev->max_pasids);
389 void dev_iommu_priv_set(struct device *dev, void *priv)
391 /* FSL_PAMU does something weird */
392 if (!IS_ENABLED(CONFIG_FSL_PAMU))
393 lockdep_assert_held(&iommu_probe_device_lock);
394 dev->iommu->priv = priv;
396 EXPORT_SYMBOL_GPL(dev_iommu_priv_set);
399 * Init the dev->iommu and dev->iommu_group in the struct device and get the
402 static int iommu_init_device(struct device *dev, const struct iommu_ops *ops)
404 struct iommu_device *iommu_dev;
405 struct iommu_group *group;
408 if (!dev_iommu_get(dev))
411 if (!try_module_get(ops->owner)) {
416 iommu_dev = ops->probe_device(dev);
417 if (IS_ERR(iommu_dev)) {
418 ret = PTR_ERR(iommu_dev);
421 dev->iommu->iommu_dev = iommu_dev;
423 ret = iommu_device_link(iommu_dev, dev);
427 group = ops->device_group(dev);
428 if (WARN_ON_ONCE(group == NULL))
429 group = ERR_PTR(-EINVAL);
431 ret = PTR_ERR(group);
434 dev->iommu_group = group;
436 dev->iommu->max_pasids = dev_iommu_get_max_pasids(dev);
437 if (ops->is_attach_deferred)
438 dev->iommu->attach_deferred = ops->is_attach_deferred(dev);
442 iommu_device_unlink(iommu_dev, dev);
444 if (ops->release_device)
445 ops->release_device(dev);
447 module_put(ops->owner);
449 dev->iommu->iommu_dev = NULL;
454 static void iommu_deinit_device(struct device *dev)
456 struct iommu_group *group = dev->iommu_group;
457 const struct iommu_ops *ops = dev_iommu_ops(dev);
459 lockdep_assert_held(&group->mutex);
461 iommu_device_unlink(dev->iommu->iommu_dev, dev);
464 * release_device() must stop using any attached domain on the device.
465 * If there are still other devices in the group, they are not affected
468 * If the iommu driver provides release_domain, the core code ensures
469 * that domain is attached prior to calling release_device. Drivers can
470 * use this to enforce a translation on the idle iommu. Typically, the
471 * global static blocked_domain is a good choice.
473 * Otherwise, the iommu driver must set the device to either an identity
474 * or a blocking translation in release_device() and stop using any
475 * domain pointer, as it is going to be freed.
477 * Regardless, if a delayed attach never occurred, then the release
478 * should still avoid touching any hardware configuration either.
480 if (!dev->iommu->attach_deferred && ops->release_domain)
481 ops->release_domain->ops->attach_dev(ops->release_domain, dev);
483 if (ops->release_device)
484 ops->release_device(dev);
487 * If this is the last driver to use the group then we must free the
488 * domains before we do the module_put().
490 if (list_empty(&group->devices)) {
491 if (group->default_domain) {
492 iommu_domain_free(group->default_domain);
493 group->default_domain = NULL;
495 if (group->blocking_domain) {
496 iommu_domain_free(group->blocking_domain);
497 group->blocking_domain = NULL;
499 group->domain = NULL;
502 /* Caller must put iommu_group */
503 dev->iommu_group = NULL;
504 module_put(ops->owner);
508 DEFINE_MUTEX(iommu_probe_device_lock);
510 static int __iommu_probe_device(struct device *dev, struct list_head *group_list)
512 const struct iommu_ops *ops;
513 struct iommu_fwspec *fwspec;
514 struct iommu_group *group;
515 struct group_device *gdev;
519 * For FDT-based systems and ACPI IORT/VIOT, drivers register IOMMU
520 * instances with non-NULL fwnodes, and client devices should have been
521 * identified with a fwspec by this point. Otherwise, we can currently
522 * assume that only one of Intel, AMD, s390, PAMU or legacy SMMUv2 can
523 * be present, and that any of their registered instances has suitable
524 * ops for probing, and thus cheekily co-opt the same mechanism.
526 fwspec = dev_iommu_fwspec_get(dev);
527 if (fwspec && fwspec->ops)
530 ops = iommu_ops_from_fwnode(NULL);
535 * Serialise to avoid races between IOMMU drivers registering in
536 * parallel and/or the "replay" calls from ACPI/OF code via client
537 * driver probe. Once the latter have been cleaned up we should
538 * probably be able to use device_lock() here to minimise the scope,
539 * but for now enforcing a simple global ordering is fine.
541 lockdep_assert_held(&iommu_probe_device_lock);
543 /* Device is probed already if in a group */
544 if (dev->iommu_group)
547 ret = iommu_init_device(dev, ops);
551 group = dev->iommu_group;
552 gdev = iommu_group_alloc_device(group, dev);
553 mutex_lock(&group->mutex);
560 * The gdev must be in the list before calling
561 * iommu_setup_default_domain()
563 list_add_tail(&gdev->list, &group->devices);
564 WARN_ON(group->default_domain && !group->domain);
565 if (group->default_domain)
566 iommu_create_device_direct_mappings(group->default_domain, dev);
568 ret = __iommu_device_set_domain(group, dev, group->domain, 0);
570 goto err_remove_gdev;
571 } else if (!group->default_domain && !group_list) {
572 ret = iommu_setup_default_domain(group, 0);
574 goto err_remove_gdev;
575 } else if (!group->default_domain) {
577 * With a group_list argument we defer the default_domain setup
578 * to the caller by providing a de-duplicated list of groups
579 * that need further setup.
581 if (list_empty(&group->entry))
582 list_add_tail(&group->entry, group_list);
584 mutex_unlock(&group->mutex);
587 iommu_dma_set_pci_32bit_workaround(dev);
592 list_del(&gdev->list);
593 __iommu_group_free_device(group, gdev);
595 iommu_deinit_device(dev);
596 mutex_unlock(&group->mutex);
597 iommu_group_put(group);
602 int iommu_probe_device(struct device *dev)
604 const struct iommu_ops *ops;
607 mutex_lock(&iommu_probe_device_lock);
608 ret = __iommu_probe_device(dev, NULL);
609 mutex_unlock(&iommu_probe_device_lock);
613 ops = dev_iommu_ops(dev);
614 if (ops->probe_finalize)
615 ops->probe_finalize(dev);
620 static void __iommu_group_free_device(struct iommu_group *group,
621 struct group_device *grp_dev)
623 struct device *dev = grp_dev->dev;
625 sysfs_remove_link(group->devices_kobj, grp_dev->name);
626 sysfs_remove_link(&dev->kobj, "iommu_group");
628 trace_remove_device_from_group(group->id, dev);
631 * If the group has become empty then ownership must have been
632 * released, and the current domain must be set back to NULL or
633 * the default domain.
635 if (list_empty(&group->devices))
636 WARN_ON(group->owner_cnt ||
637 group->domain != group->default_domain);
639 kfree(grp_dev->name);
643 /* Remove the iommu_group from the struct device. */
644 static void __iommu_group_remove_device(struct device *dev)
646 struct iommu_group *group = dev->iommu_group;
647 struct group_device *device;
649 mutex_lock(&group->mutex);
650 for_each_group_device(group, device) {
651 if (device->dev != dev)
654 list_del(&device->list);
655 __iommu_group_free_device(group, device);
656 if (dev_has_iommu(dev))
657 iommu_deinit_device(dev);
659 dev->iommu_group = NULL;
662 mutex_unlock(&group->mutex);
665 * Pairs with the get in iommu_init_device() or
666 * iommu_group_add_device()
668 iommu_group_put(group);
671 static void iommu_release_device(struct device *dev)
673 struct iommu_group *group = dev->iommu_group;
676 __iommu_group_remove_device(dev);
678 /* Free any fwspec if no iommu_driver was ever attached */
683 static int __init iommu_set_def_domain_type(char *str)
688 ret = kstrtobool(str, &pt);
693 iommu_set_default_passthrough(true);
695 iommu_set_default_translated(true);
699 early_param("iommu.passthrough", iommu_set_def_domain_type);
701 static int __init iommu_dma_setup(char *str)
703 int ret = kstrtobool(str, &iommu_dma_strict);
706 iommu_cmd_line |= IOMMU_CMD_LINE_STRICT;
709 early_param("iommu.strict", iommu_dma_setup);
711 void iommu_set_dma_strict(void)
713 iommu_dma_strict = true;
714 if (iommu_def_domain_type == IOMMU_DOMAIN_DMA_FQ)
715 iommu_def_domain_type = IOMMU_DOMAIN_DMA;
718 static ssize_t iommu_group_attr_show(struct kobject *kobj,
719 struct attribute *__attr, char *buf)
721 struct iommu_group_attribute *attr = to_iommu_group_attr(__attr);
722 struct iommu_group *group = to_iommu_group(kobj);
726 ret = attr->show(group, buf);
730 static ssize_t iommu_group_attr_store(struct kobject *kobj,
731 struct attribute *__attr,
732 const char *buf, size_t count)
734 struct iommu_group_attribute *attr = to_iommu_group_attr(__attr);
735 struct iommu_group *group = to_iommu_group(kobj);
739 ret = attr->store(group, buf, count);
743 static const struct sysfs_ops iommu_group_sysfs_ops = {
744 .show = iommu_group_attr_show,
745 .store = iommu_group_attr_store,
748 static int iommu_group_create_file(struct iommu_group *group,
749 struct iommu_group_attribute *attr)
751 return sysfs_create_file(&group->kobj, &attr->attr);
754 static void iommu_group_remove_file(struct iommu_group *group,
755 struct iommu_group_attribute *attr)
757 sysfs_remove_file(&group->kobj, &attr->attr);
760 static ssize_t iommu_group_show_name(struct iommu_group *group, char *buf)
762 return sysfs_emit(buf, "%s\n", group->name);
766 * iommu_insert_resv_region - Insert a new region in the
767 * list of reserved regions.
768 * @new: new region to insert
769 * @regions: list of regions
771 * Elements are sorted by start address and overlapping segments
772 * of the same type are merged.
774 static int iommu_insert_resv_region(struct iommu_resv_region *new,
775 struct list_head *regions)
777 struct iommu_resv_region *iter, *tmp, *nr, *top;
780 nr = iommu_alloc_resv_region(new->start, new->length,
781 new->prot, new->type, GFP_KERNEL);
785 /* First add the new element based on start address sorting */
786 list_for_each_entry(iter, regions, list) {
787 if (nr->start < iter->start ||
788 (nr->start == iter->start && nr->type <= iter->type))
791 list_add_tail(&nr->list, &iter->list);
793 /* Merge overlapping segments of type nr->type in @regions, if any */
794 list_for_each_entry_safe(iter, tmp, regions, list) {
795 phys_addr_t top_end, iter_end = iter->start + iter->length - 1;
797 /* no merge needed on elements of different types than @new */
798 if (iter->type != new->type) {
799 list_move_tail(&iter->list, &stack);
803 /* look for the last stack element of same type as @iter */
804 list_for_each_entry_reverse(top, &stack, list)
805 if (top->type == iter->type)
808 list_move_tail(&iter->list, &stack);
812 top_end = top->start + top->length - 1;
814 if (iter->start > top_end + 1) {
815 list_move_tail(&iter->list, &stack);
817 top->length = max(top_end, iter_end) - top->start + 1;
818 list_del(&iter->list);
822 list_splice(&stack, regions);
827 iommu_insert_device_resv_regions(struct list_head *dev_resv_regions,
828 struct list_head *group_resv_regions)
830 struct iommu_resv_region *entry;
833 list_for_each_entry(entry, dev_resv_regions, list) {
834 ret = iommu_insert_resv_region(entry, group_resv_regions);
841 int iommu_get_group_resv_regions(struct iommu_group *group,
842 struct list_head *head)
844 struct group_device *device;
847 mutex_lock(&group->mutex);
848 for_each_group_device(group, device) {
849 struct list_head dev_resv_regions;
852 * Non-API groups still expose reserved_regions in sysfs,
853 * so filter out calls that get here that way.
855 if (!dev_has_iommu(device->dev))
858 INIT_LIST_HEAD(&dev_resv_regions);
859 iommu_get_resv_regions(device->dev, &dev_resv_regions);
860 ret = iommu_insert_device_resv_regions(&dev_resv_regions, head);
861 iommu_put_resv_regions(device->dev, &dev_resv_regions);
865 mutex_unlock(&group->mutex);
868 EXPORT_SYMBOL_GPL(iommu_get_group_resv_regions);
870 static ssize_t iommu_group_show_resv_regions(struct iommu_group *group,
873 struct iommu_resv_region *region, *next;
874 struct list_head group_resv_regions;
877 INIT_LIST_HEAD(&group_resv_regions);
878 iommu_get_group_resv_regions(group, &group_resv_regions);
880 list_for_each_entry_safe(region, next, &group_resv_regions, list) {
881 offset += sysfs_emit_at(buf, offset, "0x%016llx 0x%016llx %s\n",
882 (long long)region->start,
883 (long long)(region->start +
885 iommu_group_resv_type_string[region->type]);
892 static ssize_t iommu_group_show_type(struct iommu_group *group,
895 char *type = "unknown";
897 mutex_lock(&group->mutex);
898 if (group->default_domain) {
899 switch (group->default_domain->type) {
900 case IOMMU_DOMAIN_BLOCKED:
903 case IOMMU_DOMAIN_IDENTITY:
906 case IOMMU_DOMAIN_UNMANAGED:
909 case IOMMU_DOMAIN_DMA:
912 case IOMMU_DOMAIN_DMA_FQ:
917 mutex_unlock(&group->mutex);
919 return sysfs_emit(buf, "%s\n", type);
922 static IOMMU_GROUP_ATTR(name, S_IRUGO, iommu_group_show_name, NULL);
924 static IOMMU_GROUP_ATTR(reserved_regions, 0444,
925 iommu_group_show_resv_regions, NULL);
927 static IOMMU_GROUP_ATTR(type, 0644, iommu_group_show_type,
928 iommu_group_store_type);
930 static void iommu_group_release(struct kobject *kobj)
932 struct iommu_group *group = to_iommu_group(kobj);
934 pr_debug("Releasing group %d\n", group->id);
936 if (group->iommu_data_release)
937 group->iommu_data_release(group->iommu_data);
939 ida_free(&iommu_group_ida, group->id);
941 /* Domains are free'd by iommu_deinit_device() */
942 WARN_ON(group->default_domain);
943 WARN_ON(group->blocking_domain);
949 static const struct kobj_type iommu_group_ktype = {
950 .sysfs_ops = &iommu_group_sysfs_ops,
951 .release = iommu_group_release,
955 * iommu_group_alloc - Allocate a new group
957 * This function is called by an iommu driver to allocate a new iommu
958 * group. The iommu group represents the minimum granularity of the iommu.
959 * Upon successful return, the caller holds a reference to the supplied
960 * group in order to hold the group until devices are added. Use
961 * iommu_group_put() to release this extra reference count, allowing the
962 * group to be automatically reclaimed once it has no devices or external
965 struct iommu_group *iommu_group_alloc(void)
967 struct iommu_group *group;
970 group = kzalloc(sizeof(*group), GFP_KERNEL);
972 return ERR_PTR(-ENOMEM);
974 group->kobj.kset = iommu_group_kset;
975 mutex_init(&group->mutex);
976 INIT_LIST_HEAD(&group->devices);
977 INIT_LIST_HEAD(&group->entry);
978 xa_init(&group->pasid_array);
980 ret = ida_alloc(&iommu_group_ida, GFP_KERNEL);
987 ret = kobject_init_and_add(&group->kobj, &iommu_group_ktype,
988 NULL, "%d", group->id);
990 kobject_put(&group->kobj);
994 group->devices_kobj = kobject_create_and_add("devices", &group->kobj);
995 if (!group->devices_kobj) {
996 kobject_put(&group->kobj); /* triggers .release & free */
997 return ERR_PTR(-ENOMEM);
1001 * The devices_kobj holds a reference on the group kobject, so
1002 * as long as that exists so will the group. We can therefore
1003 * use the devices_kobj for reference counting.
1005 kobject_put(&group->kobj);
1007 ret = iommu_group_create_file(group,
1008 &iommu_group_attr_reserved_regions);
1010 kobject_put(group->devices_kobj);
1011 return ERR_PTR(ret);
1014 ret = iommu_group_create_file(group, &iommu_group_attr_type);
1016 kobject_put(group->devices_kobj);
1017 return ERR_PTR(ret);
1020 pr_debug("Allocated group %d\n", group->id);
1024 EXPORT_SYMBOL_GPL(iommu_group_alloc);
1027 * iommu_group_get_iommudata - retrieve iommu_data registered for a group
1030 * iommu drivers can store data in the group for use when doing iommu
1031 * operations. This function provides a way to retrieve it. Caller
1032 * should hold a group reference.
1034 void *iommu_group_get_iommudata(struct iommu_group *group)
1036 return group->iommu_data;
1038 EXPORT_SYMBOL_GPL(iommu_group_get_iommudata);
1041 * iommu_group_set_iommudata - set iommu_data for a group
1043 * @iommu_data: new data
1044 * @release: release function for iommu_data
1046 * iommu drivers can store data in the group for use when doing iommu
1047 * operations. This function provides a way to set the data after
1048 * the group has been allocated. Caller should hold a group reference.
1050 void iommu_group_set_iommudata(struct iommu_group *group, void *iommu_data,
1051 void (*release)(void *iommu_data))
1053 group->iommu_data = iommu_data;
1054 group->iommu_data_release = release;
1056 EXPORT_SYMBOL_GPL(iommu_group_set_iommudata);
1059 * iommu_group_set_name - set name for a group
1063 * Allow iommu driver to set a name for a group. When set it will
1064 * appear in a name attribute file under the group in sysfs.
1066 int iommu_group_set_name(struct iommu_group *group, const char *name)
1071 iommu_group_remove_file(group, &iommu_group_attr_name);
1078 group->name = kstrdup(name, GFP_KERNEL);
1082 ret = iommu_group_create_file(group, &iommu_group_attr_name);
1091 EXPORT_SYMBOL_GPL(iommu_group_set_name);
1093 static int iommu_create_device_direct_mappings(struct iommu_domain *domain,
1096 struct iommu_resv_region *entry;
1097 struct list_head mappings;
1098 unsigned long pg_size;
1101 pg_size = domain->pgsize_bitmap ? 1UL << __ffs(domain->pgsize_bitmap) : 0;
1102 INIT_LIST_HEAD(&mappings);
1104 if (WARN_ON_ONCE(iommu_is_dma_domain(domain) && !pg_size))
1107 iommu_get_resv_regions(dev, &mappings);
1109 /* We need to consider overlapping regions for different devices */
1110 list_for_each_entry(entry, &mappings, list) {
1111 dma_addr_t start, end, addr;
1112 size_t map_size = 0;
1114 if (entry->type == IOMMU_RESV_DIRECT)
1115 dev->iommu->require_direct = 1;
1117 if ((entry->type != IOMMU_RESV_DIRECT &&
1118 entry->type != IOMMU_RESV_DIRECT_RELAXABLE) ||
1119 !iommu_is_dma_domain(domain))
1122 start = ALIGN(entry->start, pg_size);
1123 end = ALIGN(entry->start + entry->length, pg_size);
1125 for (addr = start; addr <= end; addr += pg_size) {
1126 phys_addr_t phys_addr;
1131 phys_addr = iommu_iova_to_phys(domain, addr);
1133 map_size += pg_size;
1139 ret = iommu_map(domain, addr - map_size,
1140 addr - map_size, map_size,
1141 entry->prot, GFP_KERNEL);
1150 if (!list_empty(&mappings) && iommu_is_dma_domain(domain))
1151 iommu_flush_iotlb_all(domain);
1154 iommu_put_resv_regions(dev, &mappings);
1159 /* This is undone by __iommu_group_free_device() */
1160 static struct group_device *iommu_group_alloc_device(struct iommu_group *group,
1164 struct group_device *device;
1166 device = kzalloc(sizeof(*device), GFP_KERNEL);
1168 return ERR_PTR(-ENOMEM);
1172 ret = sysfs_create_link(&dev->kobj, &group->kobj, "iommu_group");
1174 goto err_free_device;
1176 device->name = kasprintf(GFP_KERNEL, "%s", kobject_name(&dev->kobj));
1178 if (!device->name) {
1180 goto err_remove_link;
1183 ret = sysfs_create_link_nowarn(group->devices_kobj,
1184 &dev->kobj, device->name);
1186 if (ret == -EEXIST && i >= 0) {
1188 * Account for the slim chance of collision
1189 * and append an instance to the name.
1191 kfree(device->name);
1192 device->name = kasprintf(GFP_KERNEL, "%s.%d",
1193 kobject_name(&dev->kobj), i++);
1199 trace_add_device_to_group(group->id, dev);
1201 dev_info(dev, "Adding to iommu group %d\n", group->id);
1206 kfree(device->name);
1208 sysfs_remove_link(&dev->kobj, "iommu_group");
1211 dev_err(dev, "Failed to add to iommu group %d: %d\n", group->id, ret);
1212 return ERR_PTR(ret);
1216 * iommu_group_add_device - add a device to an iommu group
1217 * @group: the group into which to add the device (reference should be held)
1220 * This function is called by an iommu driver to add a device into a
1221 * group. Adding a device increments the group reference count.
1223 int iommu_group_add_device(struct iommu_group *group, struct device *dev)
1225 struct group_device *gdev;
1227 gdev = iommu_group_alloc_device(group, dev);
1229 return PTR_ERR(gdev);
1231 iommu_group_ref_get(group);
1232 dev->iommu_group = group;
1234 mutex_lock(&group->mutex);
1235 list_add_tail(&gdev->list, &group->devices);
1236 mutex_unlock(&group->mutex);
1239 EXPORT_SYMBOL_GPL(iommu_group_add_device);
1242 * iommu_group_remove_device - remove a device from it's current group
1243 * @dev: device to be removed
1245 * This function is called by an iommu driver to remove the device from
1246 * it's current group. This decrements the iommu group reference count.
1248 void iommu_group_remove_device(struct device *dev)
1250 struct iommu_group *group = dev->iommu_group;
1255 dev_info(dev, "Removing from iommu group %d\n", group->id);
1257 __iommu_group_remove_device(dev);
1259 EXPORT_SYMBOL_GPL(iommu_group_remove_device);
1261 #if IS_ENABLED(CONFIG_LOCKDEP) && IS_ENABLED(CONFIG_IOMMU_API)
1263 * iommu_group_mutex_assert - Check device group mutex lock
1264 * @dev: the device that has group param set
1266 * This function is called by an iommu driver to check whether it holds
1267 * group mutex lock for the given device or not.
1269 * Note that this function must be called after device group param is set.
1271 void iommu_group_mutex_assert(struct device *dev)
1273 struct iommu_group *group = dev->iommu_group;
1275 lockdep_assert_held(&group->mutex);
1277 EXPORT_SYMBOL_GPL(iommu_group_mutex_assert);
1280 static struct device *iommu_group_first_dev(struct iommu_group *group)
1282 lockdep_assert_held(&group->mutex);
1283 return list_first_entry(&group->devices, struct group_device, list)->dev;
1287 * iommu_group_for_each_dev - iterate over each device in the group
1289 * @data: caller opaque data to be passed to callback function
1290 * @fn: caller supplied callback function
1292 * This function is called by group users to iterate over group devices.
1293 * Callers should hold a reference count to the group during callback.
1294 * The group->mutex is held across callbacks, which will block calls to
1295 * iommu_group_add/remove_device.
1297 int iommu_group_for_each_dev(struct iommu_group *group, void *data,
1298 int (*fn)(struct device *, void *))
1300 struct group_device *device;
1303 mutex_lock(&group->mutex);
1304 for_each_group_device(group, device) {
1305 ret = fn(device->dev, data);
1309 mutex_unlock(&group->mutex);
1313 EXPORT_SYMBOL_GPL(iommu_group_for_each_dev);
1316 * iommu_group_get - Return the group for a device and increment reference
1317 * @dev: get the group that this device belongs to
1319 * This function is called by iommu drivers and users to get the group
1320 * for the specified device. If found, the group is returned and the group
1321 * reference in incremented, else NULL.
1323 struct iommu_group *iommu_group_get(struct device *dev)
1325 struct iommu_group *group = dev->iommu_group;
1328 kobject_get(group->devices_kobj);
1332 EXPORT_SYMBOL_GPL(iommu_group_get);
1335 * iommu_group_ref_get - Increment reference on a group
1336 * @group: the group to use, must not be NULL
1338 * This function is called by iommu drivers to take additional references on an
1339 * existing group. Returns the given group for convenience.
1341 struct iommu_group *iommu_group_ref_get(struct iommu_group *group)
1343 kobject_get(group->devices_kobj);
1346 EXPORT_SYMBOL_GPL(iommu_group_ref_get);
1349 * iommu_group_put - Decrement group reference
1350 * @group: the group to use
1352 * This function is called by iommu drivers and users to release the
1353 * iommu group. Once the reference count is zero, the group is released.
1355 void iommu_group_put(struct iommu_group *group)
1358 kobject_put(group->devices_kobj);
1360 EXPORT_SYMBOL_GPL(iommu_group_put);
1363 * iommu_group_id - Return ID for a group
1364 * @group: the group to ID
1366 * Return the unique ID for the group matching the sysfs group number.
1368 int iommu_group_id(struct iommu_group *group)
1372 EXPORT_SYMBOL_GPL(iommu_group_id);
1374 static struct iommu_group *get_pci_alias_group(struct pci_dev *pdev,
1375 unsigned long *devfns);
1378 * To consider a PCI device isolated, we require ACS to support Source
1379 * Validation, Request Redirection, Completer Redirection, and Upstream
1380 * Forwarding. This effectively means that devices cannot spoof their
1381 * requester ID, requests and completions cannot be redirected, and all
1382 * transactions are forwarded upstream, even as it passes through a
1383 * bridge where the target device is downstream.
1385 #define REQ_ACS_FLAGS (PCI_ACS_SV | PCI_ACS_RR | PCI_ACS_CR | PCI_ACS_UF)
1388 * For multifunction devices which are not isolated from each other, find
1389 * all the other non-isolated functions and look for existing groups. For
1390 * each function, we also need to look for aliases to or from other devices
1391 * that may already have a group.
1393 static struct iommu_group *get_pci_function_alias_group(struct pci_dev *pdev,
1394 unsigned long *devfns)
1396 struct pci_dev *tmp = NULL;
1397 struct iommu_group *group;
1399 if (!pdev->multifunction || pci_acs_enabled(pdev, REQ_ACS_FLAGS))
1402 for_each_pci_dev(tmp) {
1403 if (tmp == pdev || tmp->bus != pdev->bus ||
1404 PCI_SLOT(tmp->devfn) != PCI_SLOT(pdev->devfn) ||
1405 pci_acs_enabled(tmp, REQ_ACS_FLAGS))
1408 group = get_pci_alias_group(tmp, devfns);
1419 * Look for aliases to or from the given device for existing groups. DMA
1420 * aliases are only supported on the same bus, therefore the search
1421 * space is quite small (especially since we're really only looking at pcie
1422 * device, and therefore only expect multiple slots on the root complex or
1423 * downstream switch ports). It's conceivable though that a pair of
1424 * multifunction devices could have aliases between them that would cause a
1425 * loop. To prevent this, we use a bitmap to track where we've been.
1427 static struct iommu_group *get_pci_alias_group(struct pci_dev *pdev,
1428 unsigned long *devfns)
1430 struct pci_dev *tmp = NULL;
1431 struct iommu_group *group;
1433 if (test_and_set_bit(pdev->devfn & 0xff, devfns))
1436 group = iommu_group_get(&pdev->dev);
1440 for_each_pci_dev(tmp) {
1441 if (tmp == pdev || tmp->bus != pdev->bus)
1444 /* We alias them or they alias us */
1445 if (pci_devs_are_dma_aliases(pdev, tmp)) {
1446 group = get_pci_alias_group(tmp, devfns);
1452 group = get_pci_function_alias_group(tmp, devfns);
1463 struct group_for_pci_data {
1464 struct pci_dev *pdev;
1465 struct iommu_group *group;
1469 * DMA alias iterator callback, return the last seen device. Stop and return
1470 * the IOMMU group if we find one along the way.
1472 static int get_pci_alias_or_group(struct pci_dev *pdev, u16 alias, void *opaque)
1474 struct group_for_pci_data *data = opaque;
1477 data->group = iommu_group_get(&pdev->dev);
1479 return data->group != NULL;
1483 * Generic device_group call-back function. It just allocates one
1484 * iommu-group per device.
1486 struct iommu_group *generic_device_group(struct device *dev)
1488 return iommu_group_alloc();
1490 EXPORT_SYMBOL_GPL(generic_device_group);
1493 * Generic device_group call-back function. It just allocates one
1494 * iommu-group per iommu driver instance shared by every device
1495 * probed by that iommu driver.
1497 struct iommu_group *generic_single_device_group(struct device *dev)
1499 struct iommu_device *iommu = dev->iommu->iommu_dev;
1501 if (!iommu->singleton_group) {
1502 struct iommu_group *group;
1504 group = iommu_group_alloc();
1507 iommu->singleton_group = group;
1509 return iommu_group_ref_get(iommu->singleton_group);
1511 EXPORT_SYMBOL_GPL(generic_single_device_group);
1514 * Use standard PCI bus topology, isolation features, and DMA alias quirks
1515 * to find or create an IOMMU group for a device.
1517 struct iommu_group *pci_device_group(struct device *dev)
1519 struct pci_dev *pdev = to_pci_dev(dev);
1520 struct group_for_pci_data data;
1521 struct pci_bus *bus;
1522 struct iommu_group *group = NULL;
1523 u64 devfns[4] = { 0 };
1525 if (WARN_ON(!dev_is_pci(dev)))
1526 return ERR_PTR(-EINVAL);
1529 * Find the upstream DMA alias for the device. A device must not
1530 * be aliased due to topology in order to have its own IOMMU group.
1531 * If we find an alias along the way that already belongs to a
1534 if (pci_for_each_dma_alias(pdev, get_pci_alias_or_group, &data))
1540 * Continue upstream from the point of minimum IOMMU granularity
1541 * due to aliases to the point where devices are protected from
1542 * peer-to-peer DMA by PCI ACS. Again, if we find an existing
1545 for (bus = pdev->bus; !pci_is_root_bus(bus); bus = bus->parent) {
1549 if (pci_acs_path_enabled(bus->self, NULL, REQ_ACS_FLAGS))
1554 group = iommu_group_get(&pdev->dev);
1560 * Look for existing groups on device aliases. If we alias another
1561 * device or another device aliases us, use the same group.
1563 group = get_pci_alias_group(pdev, (unsigned long *)devfns);
1568 * Look for existing groups on non-isolated functions on the same
1569 * slot and aliases of those funcions, if any. No need to clear
1570 * the search bitmap, the tested devfns are still valid.
1572 group = get_pci_function_alias_group(pdev, (unsigned long *)devfns);
1576 /* No shared group found, allocate new */
1577 return iommu_group_alloc();
1579 EXPORT_SYMBOL_GPL(pci_device_group);
1581 /* Get the IOMMU group for device on fsl-mc bus */
1582 struct iommu_group *fsl_mc_device_group(struct device *dev)
1584 struct device *cont_dev = fsl_mc_cont_dev(dev);
1585 struct iommu_group *group;
1587 group = iommu_group_get(cont_dev);
1589 group = iommu_group_alloc();
1592 EXPORT_SYMBOL_GPL(fsl_mc_device_group);
1594 static struct iommu_domain *
1595 __iommu_group_alloc_default_domain(struct iommu_group *group, int req_type)
1597 if (group->default_domain && group->default_domain->type == req_type)
1598 return group->default_domain;
1599 return __iommu_group_domain_alloc(group, req_type);
1603 * req_type of 0 means "auto" which means to select a domain based on
1604 * iommu_def_domain_type or what the driver actually supports.
1606 static struct iommu_domain *
1607 iommu_group_alloc_default_domain(struct iommu_group *group, int req_type)
1609 const struct iommu_ops *ops = dev_iommu_ops(iommu_group_first_dev(group));
1610 struct iommu_domain *dom;
1612 lockdep_assert_held(&group->mutex);
1615 * Allow legacy drivers to specify the domain that will be the default
1616 * domain. This should always be either an IDENTITY/BLOCKED/PLATFORM
1617 * domain. Do not use in new drivers.
1619 if (ops->default_domain) {
1620 if (req_type != ops->default_domain->type)
1621 return ERR_PTR(-EINVAL);
1622 return ops->default_domain;
1626 return __iommu_group_alloc_default_domain(group, req_type);
1628 /* The driver gave no guidance on what type to use, try the default */
1629 dom = __iommu_group_alloc_default_domain(group, iommu_def_domain_type);
1633 /* Otherwise IDENTITY and DMA_FQ defaults will try DMA */
1634 if (iommu_def_domain_type == IOMMU_DOMAIN_DMA)
1635 return ERR_PTR(-EINVAL);
1636 dom = __iommu_group_alloc_default_domain(group, IOMMU_DOMAIN_DMA);
1640 pr_warn("Failed to allocate default IOMMU domain of type %u for group %s - Falling back to IOMMU_DOMAIN_DMA",
1641 iommu_def_domain_type, group->name);
1645 struct iommu_domain *iommu_group_default_domain(struct iommu_group *group)
1647 return group->default_domain;
1650 static int probe_iommu_group(struct device *dev, void *data)
1652 struct list_head *group_list = data;
1655 mutex_lock(&iommu_probe_device_lock);
1656 ret = __iommu_probe_device(dev, group_list);
1657 mutex_unlock(&iommu_probe_device_lock);
1664 static int iommu_bus_notifier(struct notifier_block *nb,
1665 unsigned long action, void *data)
1667 struct device *dev = data;
1669 if (action == BUS_NOTIFY_ADD_DEVICE) {
1672 ret = iommu_probe_device(dev);
1673 return (ret) ? NOTIFY_DONE : NOTIFY_OK;
1674 } else if (action == BUS_NOTIFY_REMOVED_DEVICE) {
1675 iommu_release_device(dev);
1683 * Combine the driver's chosen def_domain_type across all the devices in a
1684 * group. Drivers must give a consistent result.
1686 static int iommu_get_def_domain_type(struct iommu_group *group,
1687 struct device *dev, int cur_type)
1689 const struct iommu_ops *ops = dev_iommu_ops(dev);
1692 if (ops->default_domain) {
1694 * Drivers that declare a global static default_domain will
1695 * always choose that.
1697 type = ops->default_domain->type;
1699 if (ops->def_domain_type)
1700 type = ops->def_domain_type(dev);
1704 if (!type || cur_type == type)
1709 dev_err_ratelimited(
1711 "IOMMU driver error, requesting conflicting def_domain_type, %s and %s, for devices in group %u.\n",
1712 iommu_domain_type_str(cur_type), iommu_domain_type_str(type),
1716 * Try to recover, drivers are allowed to force IDENITY or DMA, IDENTITY
1719 if (type == IOMMU_DOMAIN_IDENTITY)
1725 * A target_type of 0 will select the best domain type. 0 can be returned in
1726 * this case meaning the global default should be used.
1728 static int iommu_get_default_domain_type(struct iommu_group *group,
1731 struct device *untrusted = NULL;
1732 struct group_device *gdev;
1733 int driver_type = 0;
1735 lockdep_assert_held(&group->mutex);
1738 * ARM32 drivers supporting CONFIG_ARM_DMA_USE_IOMMU can declare an
1739 * identity_domain and it will automatically become their default
1740 * domain. Later on ARM_DMA_USE_IOMMU will install its UNMANAGED domain.
1741 * Override the selection to IDENTITY.
1743 if (IS_ENABLED(CONFIG_ARM_DMA_USE_IOMMU)) {
1744 static_assert(!(IS_ENABLED(CONFIG_ARM_DMA_USE_IOMMU) &&
1745 IS_ENABLED(CONFIG_IOMMU_DMA)));
1746 driver_type = IOMMU_DOMAIN_IDENTITY;
1749 for_each_group_device(group, gdev) {
1750 driver_type = iommu_get_def_domain_type(group, gdev->dev,
1753 if (dev_is_pci(gdev->dev) && to_pci_dev(gdev->dev)->untrusted) {
1755 * No ARM32 using systems will set untrusted, it cannot
1758 if (WARN_ON(IS_ENABLED(CONFIG_ARM_DMA_USE_IOMMU)))
1760 untrusted = gdev->dev;
1765 * If the common dma ops are not selected in kconfig then we cannot use
1766 * IOMMU_DOMAIN_DMA at all. Force IDENTITY if nothing else has been
1769 if (!IS_ENABLED(CONFIG_IOMMU_DMA)) {
1770 if (WARN_ON(driver_type == IOMMU_DOMAIN_DMA))
1773 driver_type = IOMMU_DOMAIN_IDENTITY;
1777 if (driver_type && driver_type != IOMMU_DOMAIN_DMA) {
1778 dev_err_ratelimited(
1780 "Device is not trusted, but driver is overriding group %u to %s, refusing to probe.\n",
1781 group->id, iommu_domain_type_str(driver_type));
1784 driver_type = IOMMU_DOMAIN_DMA;
1788 if (driver_type && target_type != driver_type)
1795 static void iommu_group_do_probe_finalize(struct device *dev)
1797 const struct iommu_ops *ops = dev_iommu_ops(dev);
1799 if (ops->probe_finalize)
1800 ops->probe_finalize(dev);
1803 int bus_iommu_probe(const struct bus_type *bus)
1805 struct iommu_group *group, *next;
1806 LIST_HEAD(group_list);
1809 ret = bus_for_each_dev(bus, NULL, &group_list, probe_iommu_group);
1813 list_for_each_entry_safe(group, next, &group_list, entry) {
1814 struct group_device *gdev;
1816 mutex_lock(&group->mutex);
1818 /* Remove item from the list */
1819 list_del_init(&group->entry);
1822 * We go to the trouble of deferred default domain creation so
1823 * that the cross-group default domain type and the setup of the
1824 * IOMMU_RESV_DIRECT will work correctly in non-hotpug scenarios.
1826 ret = iommu_setup_default_domain(group, 0);
1828 mutex_unlock(&group->mutex);
1831 mutex_unlock(&group->mutex);
1834 * FIXME: Mis-locked because the ops->probe_finalize() call-back
1835 * of some IOMMU drivers calls arm_iommu_attach_device() which
1836 * in-turn might call back into IOMMU core code, where it tries
1837 * to take group->mutex, resulting in a deadlock.
1839 for_each_group_device(group, gdev)
1840 iommu_group_do_probe_finalize(gdev->dev);
1847 * iommu_present() - make platform-specific assumptions about an IOMMU
1848 * @bus: bus to check
1850 * Do not use this function. You want device_iommu_mapped() instead.
1852 * Return: true if some IOMMU is present and aware of devices on the given bus;
1853 * in general it may not be the only IOMMU, and it may not have anything to do
1854 * with whatever device you are ultimately interested in.
1856 bool iommu_present(const struct bus_type *bus)
1860 for (int i = 0; i < ARRAY_SIZE(iommu_buses); i++) {
1861 if (iommu_buses[i] == bus) {
1862 spin_lock(&iommu_device_lock);
1863 ret = !list_empty(&iommu_device_list);
1864 spin_unlock(&iommu_device_lock);
1869 EXPORT_SYMBOL_GPL(iommu_present);
1872 * device_iommu_capable() - check for a general IOMMU capability
1873 * @dev: device to which the capability would be relevant, if available
1874 * @cap: IOMMU capability
1876 * Return: true if an IOMMU is present and supports the given capability
1877 * for the given device, otherwise false.
1879 bool device_iommu_capable(struct device *dev, enum iommu_cap cap)
1881 const struct iommu_ops *ops;
1883 if (!dev_has_iommu(dev))
1886 ops = dev_iommu_ops(dev);
1890 return ops->capable(dev, cap);
1892 EXPORT_SYMBOL_GPL(device_iommu_capable);
1895 * iommu_group_has_isolated_msi() - Compute msi_device_has_isolated_msi()
1897 * @group: Group to query
1899 * IOMMU groups should not have differing values of
1900 * msi_device_has_isolated_msi() for devices in a group. However nothing
1901 * directly prevents this, so ensure mistakes don't result in isolation failures
1902 * by checking that all the devices are the same.
1904 bool iommu_group_has_isolated_msi(struct iommu_group *group)
1906 struct group_device *group_dev;
1909 mutex_lock(&group->mutex);
1910 for_each_group_device(group, group_dev)
1911 ret &= msi_device_has_isolated_msi(group_dev->dev);
1912 mutex_unlock(&group->mutex);
1915 EXPORT_SYMBOL_GPL(iommu_group_has_isolated_msi);
1918 * iommu_set_fault_handler() - set a fault handler for an iommu domain
1919 * @domain: iommu domain
1920 * @handler: fault handler
1921 * @token: user data, will be passed back to the fault handler
1923 * This function should be used by IOMMU users which want to be notified
1924 * whenever an IOMMU fault happens.
1926 * The fault handler itself should return 0 on success, and an appropriate
1927 * error code otherwise.
1929 void iommu_set_fault_handler(struct iommu_domain *domain,
1930 iommu_fault_handler_t handler,
1935 domain->handler = handler;
1936 domain->handler_token = token;
1938 EXPORT_SYMBOL_GPL(iommu_set_fault_handler);
1940 static struct iommu_domain *__iommu_domain_alloc(const struct iommu_ops *ops,
1944 struct iommu_domain *domain;
1945 unsigned int alloc_type = type & IOMMU_DOMAIN_ALLOC_FLAGS;
1947 if (alloc_type == IOMMU_DOMAIN_IDENTITY && ops->identity_domain)
1948 return ops->identity_domain;
1949 else if (alloc_type == IOMMU_DOMAIN_BLOCKED && ops->blocked_domain)
1950 return ops->blocked_domain;
1951 else if (type & __IOMMU_DOMAIN_PAGING && ops->domain_alloc_paging)
1952 domain = ops->domain_alloc_paging(dev);
1953 else if (ops->domain_alloc)
1954 domain = ops->domain_alloc(alloc_type);
1956 return ERR_PTR(-EOPNOTSUPP);
1959 * Many domain_alloc ops now return ERR_PTR, make things easier for the
1960 * driver by accepting ERR_PTR from all domain_alloc ops instead of
1966 return ERR_PTR(-ENOMEM);
1968 domain->type = type;
1969 domain->owner = ops;
1971 * If not already set, assume all sizes by default; the driver
1972 * may override this later
1974 if (!domain->pgsize_bitmap)
1975 domain->pgsize_bitmap = ops->pgsize_bitmap;
1978 domain->ops = ops->default_domain_ops;
1980 if (iommu_is_dma_domain(domain)) {
1983 rc = iommu_get_dma_cookie(domain);
1985 iommu_domain_free(domain);
1992 static struct iommu_domain *
1993 __iommu_group_domain_alloc(struct iommu_group *group, unsigned int type)
1995 struct device *dev = iommu_group_first_dev(group);
1997 return __iommu_domain_alloc(dev_iommu_ops(dev), dev, type);
2000 static int __iommu_domain_alloc_dev(struct device *dev, void *data)
2002 const struct iommu_ops **ops = data;
2004 if (!dev_has_iommu(dev))
2007 if (WARN_ONCE(*ops && *ops != dev_iommu_ops(dev),
2008 "Multiple IOMMU drivers present for bus %s, which the public IOMMU API can't fully support yet. You will still need to disable one or more for this to work, sorry!\n",
2012 *ops = dev_iommu_ops(dev);
2016 struct iommu_domain *iommu_domain_alloc(const struct bus_type *bus)
2018 const struct iommu_ops *ops = NULL;
2019 int err = bus_for_each_dev(bus, NULL, &ops, __iommu_domain_alloc_dev);
2020 struct iommu_domain *domain;
2025 domain = __iommu_domain_alloc(ops, NULL, IOMMU_DOMAIN_UNMANAGED);
2030 EXPORT_SYMBOL_GPL(iommu_domain_alloc);
2032 void iommu_domain_free(struct iommu_domain *domain)
2034 if (domain->type == IOMMU_DOMAIN_SVA)
2036 iommu_put_dma_cookie(domain);
2037 if (domain->ops->free)
2038 domain->ops->free(domain);
2040 EXPORT_SYMBOL_GPL(iommu_domain_free);
2043 * Put the group's domain back to the appropriate core-owned domain - either the
2044 * standard kernel-mode DMA configuration or an all-DMA-blocked domain.
2046 static void __iommu_group_set_core_domain(struct iommu_group *group)
2048 struct iommu_domain *new_domain;
2051 new_domain = group->blocking_domain;
2053 new_domain = group->default_domain;
2055 __iommu_group_set_domain_nofail(group, new_domain);
2058 static int __iommu_attach_device(struct iommu_domain *domain,
2063 if (unlikely(domain->ops->attach_dev == NULL))
2066 ret = domain->ops->attach_dev(domain, dev);
2069 dev->iommu->attach_deferred = 0;
2070 trace_attach_device_to_domain(dev);
2075 * iommu_attach_device - Attach an IOMMU domain to a device
2076 * @domain: IOMMU domain to attach
2077 * @dev: Device that will be attached
2079 * Returns 0 on success and error code on failure
2081 * Note that EINVAL can be treated as a soft failure, indicating
2082 * that certain configuration of the domain is incompatible with
2083 * the device. In this case attaching a different domain to the
2084 * device may succeed.
2086 int iommu_attach_device(struct iommu_domain *domain, struct device *dev)
2088 /* Caller must be a probed driver on dev */
2089 struct iommu_group *group = dev->iommu_group;
2096 * Lock the group to make sure the device-count doesn't
2097 * change while we are attaching
2099 mutex_lock(&group->mutex);
2101 if (list_count_nodes(&group->devices) != 1)
2104 ret = __iommu_attach_group(domain, group);
2107 mutex_unlock(&group->mutex);
2110 EXPORT_SYMBOL_GPL(iommu_attach_device);
2112 int iommu_deferred_attach(struct device *dev, struct iommu_domain *domain)
2114 if (dev->iommu && dev->iommu->attach_deferred)
2115 return __iommu_attach_device(domain, dev);
2120 void iommu_detach_device(struct iommu_domain *domain, struct device *dev)
2122 /* Caller must be a probed driver on dev */
2123 struct iommu_group *group = dev->iommu_group;
2128 mutex_lock(&group->mutex);
2129 if (WARN_ON(domain != group->domain) ||
2130 WARN_ON(list_count_nodes(&group->devices) != 1))
2132 __iommu_group_set_core_domain(group);
2135 mutex_unlock(&group->mutex);
2137 EXPORT_SYMBOL_GPL(iommu_detach_device);
2139 struct iommu_domain *iommu_get_domain_for_dev(struct device *dev)
2141 /* Caller must be a probed driver on dev */
2142 struct iommu_group *group = dev->iommu_group;
2147 return group->domain;
2149 EXPORT_SYMBOL_GPL(iommu_get_domain_for_dev);
2152 * For IOMMU_DOMAIN_DMA implementations which already provide their own
2153 * guarantees that the group and its default domain are valid and correct.
2155 struct iommu_domain *iommu_get_dma_domain(struct device *dev)
2157 return dev->iommu_group->default_domain;
2160 static int __iommu_attach_group(struct iommu_domain *domain,
2161 struct iommu_group *group)
2165 if (group->domain && group->domain != group->default_domain &&
2166 group->domain != group->blocking_domain)
2169 dev = iommu_group_first_dev(group);
2170 if (!dev_has_iommu(dev) || dev_iommu_ops(dev) != domain->owner)
2173 return __iommu_group_set_domain(group, domain);
2177 * iommu_attach_group - Attach an IOMMU domain to an IOMMU group
2178 * @domain: IOMMU domain to attach
2179 * @group: IOMMU group that will be attached
2181 * Returns 0 on success and error code on failure
2183 * Note that EINVAL can be treated as a soft failure, indicating
2184 * that certain configuration of the domain is incompatible with
2185 * the group. In this case attaching a different domain to the
2186 * group may succeed.
2188 int iommu_attach_group(struct iommu_domain *domain, struct iommu_group *group)
2192 mutex_lock(&group->mutex);
2193 ret = __iommu_attach_group(domain, group);
2194 mutex_unlock(&group->mutex);
2198 EXPORT_SYMBOL_GPL(iommu_attach_group);
2201 * iommu_group_replace_domain - replace the domain that a group is attached to
2202 * @new_domain: new IOMMU domain to replace with
2203 * @group: IOMMU group that will be attached to the new domain
2205 * This API allows the group to switch domains without being forced to go to
2206 * the blocking domain in-between.
2208 * If the currently attached domain is a core domain (e.g. a default_domain),
2209 * it will act just like the iommu_attach_group().
2211 int iommu_group_replace_domain(struct iommu_group *group,
2212 struct iommu_domain *new_domain)
2219 mutex_lock(&group->mutex);
2220 ret = __iommu_group_set_domain(group, new_domain);
2221 mutex_unlock(&group->mutex);
2224 EXPORT_SYMBOL_NS_GPL(iommu_group_replace_domain, IOMMUFD_INTERNAL);
2226 static int __iommu_device_set_domain(struct iommu_group *group,
2228 struct iommu_domain *new_domain,
2234 * If the device requires IOMMU_RESV_DIRECT then we cannot allow
2235 * the blocking domain to be attached as it does not contain the
2236 * required 1:1 mapping. This test effectively excludes the device
2237 * being used with iommu_group_claim_dma_owner() which will block
2238 * vfio and iommufd as well.
2240 if (dev->iommu->require_direct &&
2241 (new_domain->type == IOMMU_DOMAIN_BLOCKED ||
2242 new_domain == group->blocking_domain)) {
2244 "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");
2248 if (dev->iommu->attach_deferred) {
2249 if (new_domain == group->default_domain)
2251 dev->iommu->attach_deferred = 0;
2254 ret = __iommu_attach_device(new_domain, dev);
2257 * If we have a blocking domain then try to attach that in hopes
2258 * of avoiding a UAF. Modern drivers should implement blocking
2259 * domains as global statics that cannot fail.
2261 if ((flags & IOMMU_SET_DOMAIN_MUST_SUCCEED) &&
2262 group->blocking_domain &&
2263 group->blocking_domain != new_domain)
2264 __iommu_attach_device(group->blocking_domain, dev);
2271 * If 0 is returned the group's domain is new_domain. If an error is returned
2272 * then the group's domain will be set back to the existing domain unless
2273 * IOMMU_SET_DOMAIN_MUST_SUCCEED, otherwise an error is returned and the group's
2274 * domains is left inconsistent. This is a driver bug to fail attach with a
2275 * previously good domain. We try to avoid a kernel UAF because of this.
2277 * IOMMU groups are really the natural working unit of the IOMMU, but the IOMMU
2278 * API works on domains and devices. Bridge that gap by iterating over the
2279 * devices in a group. Ideally we'd have a single device which represents the
2280 * requestor ID of the group, but we also allow IOMMU drivers to create policy
2281 * defined minimum sets, where the physical hardware may be able to distiguish
2282 * members, but we wish to group them at a higher level (ex. untrusted
2283 * multi-function PCI devices). Thus we attach each device.
2285 static int __iommu_group_set_domain_internal(struct iommu_group *group,
2286 struct iommu_domain *new_domain,
2289 struct group_device *last_gdev;
2290 struct group_device *gdev;
2294 lockdep_assert_held(&group->mutex);
2296 if (group->domain == new_domain)
2299 if (WARN_ON(!new_domain))
2303 * Changing the domain is done by calling attach_dev() on the new
2304 * domain. This switch does not have to be atomic and DMA can be
2305 * discarded during the transition. DMA must only be able to access
2306 * either new_domain or group->domain, never something else.
2309 for_each_group_device(group, gdev) {
2310 ret = __iommu_device_set_domain(group, gdev->dev, new_domain,
2315 * Keep trying the other devices in the group. If a
2316 * driver fails attach to an otherwise good domain, and
2317 * does not support blocking domains, it should at least
2318 * drop its reference on the current domain so we don't
2321 if (flags & IOMMU_SET_DOMAIN_MUST_SUCCEED)
2326 group->domain = new_domain;
2331 * This is called in error unwind paths. A well behaved driver should
2332 * always allow us to attach to a domain that was already attached.
2335 for_each_group_device(group, gdev) {
2337 * A NULL domain can happen only for first probe, in which case
2338 * we leave group->domain as NULL and let release clean
2342 WARN_ON(__iommu_device_set_domain(
2343 group, gdev->dev, group->domain,
2344 IOMMU_SET_DOMAIN_MUST_SUCCEED));
2345 if (gdev == last_gdev)
2351 void iommu_detach_group(struct iommu_domain *domain, struct iommu_group *group)
2353 mutex_lock(&group->mutex);
2354 __iommu_group_set_core_domain(group);
2355 mutex_unlock(&group->mutex);
2357 EXPORT_SYMBOL_GPL(iommu_detach_group);
2359 phys_addr_t iommu_iova_to_phys(struct iommu_domain *domain, dma_addr_t iova)
2361 if (domain->type == IOMMU_DOMAIN_IDENTITY)
2364 if (domain->type == IOMMU_DOMAIN_BLOCKED)
2367 return domain->ops->iova_to_phys(domain, iova);
2369 EXPORT_SYMBOL_GPL(iommu_iova_to_phys);
2371 static size_t iommu_pgsize(struct iommu_domain *domain, unsigned long iova,
2372 phys_addr_t paddr, size_t size, size_t *count)
2374 unsigned int pgsize_idx, pgsize_idx_next;
2375 unsigned long pgsizes;
2376 size_t offset, pgsize, pgsize_next;
2377 unsigned long addr_merge = paddr | iova;
2379 /* Page sizes supported by the hardware and small enough for @size */
2380 pgsizes = domain->pgsize_bitmap & GENMASK(__fls(size), 0);
2382 /* Constrain the page sizes further based on the maximum alignment */
2383 if (likely(addr_merge))
2384 pgsizes &= GENMASK(__ffs(addr_merge), 0);
2386 /* Make sure we have at least one suitable page size */
2389 /* Pick the biggest page size remaining */
2390 pgsize_idx = __fls(pgsizes);
2391 pgsize = BIT(pgsize_idx);
2395 /* Find the next biggest support page size, if it exists */
2396 pgsizes = domain->pgsize_bitmap & ~GENMASK(pgsize_idx, 0);
2400 pgsize_idx_next = __ffs(pgsizes);
2401 pgsize_next = BIT(pgsize_idx_next);
2404 * There's no point trying a bigger page size unless the virtual
2405 * and physical addresses are similarly offset within the larger page.
2407 if ((iova ^ paddr) & (pgsize_next - 1))
2410 /* Calculate the offset to the next page size alignment boundary */
2411 offset = pgsize_next - (addr_merge & (pgsize_next - 1));
2414 * If size is big enough to accommodate the larger page, reduce
2415 * the number of smaller pages.
2417 if (offset + pgsize_next <= size)
2421 *count = size >> pgsize_idx;
2425 static int __iommu_map(struct iommu_domain *domain, unsigned long iova,
2426 phys_addr_t paddr, size_t size, int prot, gfp_t gfp)
2428 const struct iommu_domain_ops *ops = domain->ops;
2429 unsigned long orig_iova = iova;
2430 unsigned int min_pagesz;
2431 size_t orig_size = size;
2432 phys_addr_t orig_paddr = paddr;
2435 if (unlikely(!(domain->type & __IOMMU_DOMAIN_PAGING)))
2438 if (WARN_ON(!ops->map_pages || domain->pgsize_bitmap == 0UL))
2441 /* find out the minimum page size supported */
2442 min_pagesz = 1 << __ffs(domain->pgsize_bitmap);
2445 * both the virtual address and the physical one, as well as
2446 * the size of the mapping, must be aligned (at least) to the
2447 * size of the smallest page supported by the hardware
2449 if (!IS_ALIGNED(iova | paddr | size, min_pagesz)) {
2450 pr_err("unaligned: iova 0x%lx pa %pa size 0x%zx min_pagesz 0x%x\n",
2451 iova, &paddr, size, min_pagesz);
2455 pr_debug("map: iova 0x%lx pa %pa size 0x%zx\n", iova, &paddr, size);
2458 size_t pgsize, count, mapped = 0;
2460 pgsize = iommu_pgsize(domain, iova, paddr, size, &count);
2462 pr_debug("mapping: iova 0x%lx pa %pa pgsize 0x%zx count %zu\n",
2463 iova, &paddr, pgsize, count);
2464 ret = ops->map_pages(domain, iova, paddr, pgsize, count, prot,
2467 * Some pages may have been mapped, even if an error occurred,
2468 * so we should account for those so they can be unmapped.
2479 /* unroll mapping in case something went wrong */
2481 iommu_unmap(domain, orig_iova, orig_size - size);
2483 trace_map(orig_iova, orig_paddr, orig_size);
2488 int iommu_map(struct iommu_domain *domain, unsigned long iova,
2489 phys_addr_t paddr, size_t size, int prot, gfp_t gfp)
2491 const struct iommu_domain_ops *ops = domain->ops;
2494 might_sleep_if(gfpflags_allow_blocking(gfp));
2496 /* Discourage passing strange GFP flags */
2497 if (WARN_ON_ONCE(gfp & (__GFP_COMP | __GFP_DMA | __GFP_DMA32 |
2501 ret = __iommu_map(domain, iova, paddr, size, prot, gfp);
2502 if (ret == 0 && ops->iotlb_sync_map) {
2503 ret = ops->iotlb_sync_map(domain, iova, size);
2511 /* undo mappings already done */
2512 iommu_unmap(domain, iova, size);
2516 EXPORT_SYMBOL_GPL(iommu_map);
2518 static size_t __iommu_unmap(struct iommu_domain *domain,
2519 unsigned long iova, size_t size,
2520 struct iommu_iotlb_gather *iotlb_gather)
2522 const struct iommu_domain_ops *ops = domain->ops;
2523 size_t unmapped_page, unmapped = 0;
2524 unsigned long orig_iova = iova;
2525 unsigned int min_pagesz;
2527 if (unlikely(!(domain->type & __IOMMU_DOMAIN_PAGING)))
2530 if (WARN_ON(!ops->unmap_pages || domain->pgsize_bitmap == 0UL))
2533 /* find out the minimum page size supported */
2534 min_pagesz = 1 << __ffs(domain->pgsize_bitmap);
2537 * The virtual address, as well as the size of the mapping, must be
2538 * aligned (at least) to the size of the smallest page supported
2541 if (!IS_ALIGNED(iova | size, min_pagesz)) {
2542 pr_err("unaligned: iova 0x%lx size 0x%zx min_pagesz 0x%x\n",
2543 iova, size, min_pagesz);
2547 pr_debug("unmap this: iova 0x%lx size 0x%zx\n", iova, size);
2550 * Keep iterating until we either unmap 'size' bytes (or more)
2551 * or we hit an area that isn't mapped.
2553 while (unmapped < size) {
2554 size_t pgsize, count;
2556 pgsize = iommu_pgsize(domain, iova, iova, size - unmapped, &count);
2557 unmapped_page = ops->unmap_pages(domain, iova, pgsize, count, iotlb_gather);
2561 pr_debug("unmapped: iova 0x%lx size 0x%zx\n",
2562 iova, unmapped_page);
2564 iova += unmapped_page;
2565 unmapped += unmapped_page;
2568 trace_unmap(orig_iova, size, unmapped);
2572 size_t iommu_unmap(struct iommu_domain *domain,
2573 unsigned long iova, size_t size)
2575 struct iommu_iotlb_gather iotlb_gather;
2578 iommu_iotlb_gather_init(&iotlb_gather);
2579 ret = __iommu_unmap(domain, iova, size, &iotlb_gather);
2580 iommu_iotlb_sync(domain, &iotlb_gather);
2584 EXPORT_SYMBOL_GPL(iommu_unmap);
2586 size_t iommu_unmap_fast(struct iommu_domain *domain,
2587 unsigned long iova, size_t size,
2588 struct iommu_iotlb_gather *iotlb_gather)
2590 return __iommu_unmap(domain, iova, size, iotlb_gather);
2592 EXPORT_SYMBOL_GPL(iommu_unmap_fast);
2594 ssize_t iommu_map_sg(struct iommu_domain *domain, unsigned long iova,
2595 struct scatterlist *sg, unsigned int nents, int prot,
2598 const struct iommu_domain_ops *ops = domain->ops;
2599 size_t len = 0, mapped = 0;
2604 might_sleep_if(gfpflags_allow_blocking(gfp));
2606 /* Discourage passing strange GFP flags */
2607 if (WARN_ON_ONCE(gfp & (__GFP_COMP | __GFP_DMA | __GFP_DMA32 |
2611 while (i <= nents) {
2612 phys_addr_t s_phys = sg_phys(sg);
2614 if (len && s_phys != start + len) {
2615 ret = __iommu_map(domain, iova + mapped, start,
2625 if (sg_dma_is_bus_address(sg))
2640 if (ops->iotlb_sync_map) {
2641 ret = ops->iotlb_sync_map(domain, iova, mapped);
2648 /* undo mappings already done */
2649 iommu_unmap(domain, iova, mapped);
2653 EXPORT_SYMBOL_GPL(iommu_map_sg);
2656 * report_iommu_fault() - report about an IOMMU fault to the IOMMU framework
2657 * @domain: the iommu domain where the fault has happened
2658 * @dev: the device where the fault has happened
2659 * @iova: the faulting address
2660 * @flags: mmu fault flags (e.g. IOMMU_FAULT_READ/IOMMU_FAULT_WRITE/...)
2662 * This function should be called by the low-level IOMMU implementations
2663 * whenever IOMMU faults happen, to allow high-level users, that are
2664 * interested in such events, to know about them.
2666 * This event may be useful for several possible use cases:
2667 * - mere logging of the event
2668 * - dynamic TLB/PTE loading
2669 * - if restarting of the faulting device is required
2671 * Returns 0 on success and an appropriate error code otherwise (if dynamic
2672 * PTE/TLB loading will one day be supported, implementations will be able
2673 * to tell whether it succeeded or not according to this return value).
2675 * Specifically, -ENOSYS is returned if a fault handler isn't installed
2676 * (though fault handlers can also return -ENOSYS, in case they want to
2677 * elicit the default behavior of the IOMMU drivers).
2679 int report_iommu_fault(struct iommu_domain *domain, struct device *dev,
2680 unsigned long iova, int flags)
2685 * if upper layers showed interest and installed a fault handler,
2688 if (domain->handler)
2689 ret = domain->handler(domain, dev, iova, flags,
2690 domain->handler_token);
2692 trace_io_page_fault(dev, iova, flags);
2695 EXPORT_SYMBOL_GPL(report_iommu_fault);
2697 static int __init iommu_init(void)
2699 iommu_group_kset = kset_create_and_add("iommu_groups",
2701 BUG_ON(!iommu_group_kset);
2703 iommu_debugfs_setup();
2707 core_initcall(iommu_init);
2709 int iommu_enable_nesting(struct iommu_domain *domain)
2711 if (domain->type != IOMMU_DOMAIN_UNMANAGED)
2713 if (!domain->ops->enable_nesting)
2715 return domain->ops->enable_nesting(domain);
2717 EXPORT_SYMBOL_GPL(iommu_enable_nesting);
2719 int iommu_set_pgtable_quirks(struct iommu_domain *domain,
2720 unsigned long quirk)
2722 if (domain->type != IOMMU_DOMAIN_UNMANAGED)
2724 if (!domain->ops->set_pgtable_quirks)
2726 return domain->ops->set_pgtable_quirks(domain, quirk);
2728 EXPORT_SYMBOL_GPL(iommu_set_pgtable_quirks);
2731 * iommu_get_resv_regions - get reserved regions
2732 * @dev: device for which to get reserved regions
2733 * @list: reserved region list for device
2735 * This returns a list of reserved IOVA regions specific to this device.
2736 * A domain user should not map IOVA in these ranges.
2738 void iommu_get_resv_regions(struct device *dev, struct list_head *list)
2740 const struct iommu_ops *ops = dev_iommu_ops(dev);
2742 if (ops->get_resv_regions)
2743 ops->get_resv_regions(dev, list);
2745 EXPORT_SYMBOL_GPL(iommu_get_resv_regions);
2748 * iommu_put_resv_regions - release reserved regions
2749 * @dev: device for which to free reserved regions
2750 * @list: reserved region list for device
2752 * This releases a reserved region list acquired by iommu_get_resv_regions().
2754 void iommu_put_resv_regions(struct device *dev, struct list_head *list)
2756 struct iommu_resv_region *entry, *next;
2758 list_for_each_entry_safe(entry, next, list, list) {
2760 entry->free(dev, entry);
2765 EXPORT_SYMBOL(iommu_put_resv_regions);
2767 struct iommu_resv_region *iommu_alloc_resv_region(phys_addr_t start,
2768 size_t length, int prot,
2769 enum iommu_resv_type type,
2772 struct iommu_resv_region *region;
2774 region = kzalloc(sizeof(*region), gfp);
2778 INIT_LIST_HEAD(®ion->list);
2779 region->start = start;
2780 region->length = length;
2781 region->prot = prot;
2782 region->type = type;
2785 EXPORT_SYMBOL_GPL(iommu_alloc_resv_region);
2787 void iommu_set_default_passthrough(bool cmd_line)
2790 iommu_cmd_line |= IOMMU_CMD_LINE_DMA_API;
2791 iommu_def_domain_type = IOMMU_DOMAIN_IDENTITY;
2794 void iommu_set_default_translated(bool cmd_line)
2797 iommu_cmd_line |= IOMMU_CMD_LINE_DMA_API;
2798 iommu_def_domain_type = IOMMU_DOMAIN_DMA;
2801 bool iommu_default_passthrough(void)
2803 return iommu_def_domain_type == IOMMU_DOMAIN_IDENTITY;
2805 EXPORT_SYMBOL_GPL(iommu_default_passthrough);
2807 const struct iommu_ops *iommu_ops_from_fwnode(const struct fwnode_handle *fwnode)
2809 const struct iommu_ops *ops = NULL;
2810 struct iommu_device *iommu;
2812 spin_lock(&iommu_device_lock);
2813 list_for_each_entry(iommu, &iommu_device_list, list)
2814 if (iommu->fwnode == fwnode) {
2818 spin_unlock(&iommu_device_lock);
2822 int iommu_fwspec_init(struct device *dev, struct fwnode_handle *iommu_fwnode,
2823 const struct iommu_ops *ops)
2825 struct iommu_fwspec *fwspec = dev_iommu_fwspec_get(dev);
2828 return ops == fwspec->ops ? 0 : -EINVAL;
2830 if (!dev_iommu_get(dev))
2833 /* Preallocate for the overwhelmingly common case of 1 ID */
2834 fwspec = kzalloc(struct_size(fwspec, ids, 1), GFP_KERNEL);
2838 of_node_get(to_of_node(iommu_fwnode));
2839 fwspec->iommu_fwnode = iommu_fwnode;
2841 dev_iommu_fwspec_set(dev, fwspec);
2844 EXPORT_SYMBOL_GPL(iommu_fwspec_init);
2846 void iommu_fwspec_free(struct device *dev)
2848 struct iommu_fwspec *fwspec = dev_iommu_fwspec_get(dev);
2851 fwnode_handle_put(fwspec->iommu_fwnode);
2853 dev_iommu_fwspec_set(dev, NULL);
2856 EXPORT_SYMBOL_GPL(iommu_fwspec_free);
2858 int iommu_fwspec_add_ids(struct device *dev, const u32 *ids, int num_ids)
2860 struct iommu_fwspec *fwspec = dev_iommu_fwspec_get(dev);
2866 new_num = fwspec->num_ids + num_ids;
2868 fwspec = krealloc(fwspec, struct_size(fwspec, ids, new_num),
2873 dev_iommu_fwspec_set(dev, fwspec);
2876 for (i = 0; i < num_ids; i++)
2877 fwspec->ids[fwspec->num_ids + i] = ids[i];
2879 fwspec->num_ids = new_num;
2882 EXPORT_SYMBOL_GPL(iommu_fwspec_add_ids);
2885 * Per device IOMMU features.
2887 int iommu_dev_enable_feature(struct device *dev, enum iommu_dev_features feat)
2889 if (dev_has_iommu(dev)) {
2890 const struct iommu_ops *ops = dev_iommu_ops(dev);
2892 if (ops->dev_enable_feat)
2893 return ops->dev_enable_feat(dev, feat);
2898 EXPORT_SYMBOL_GPL(iommu_dev_enable_feature);
2901 * The device drivers should do the necessary cleanups before calling this.
2903 int iommu_dev_disable_feature(struct device *dev, enum iommu_dev_features feat)
2905 if (dev_has_iommu(dev)) {
2906 const struct iommu_ops *ops = dev_iommu_ops(dev);
2908 if (ops->dev_disable_feat)
2909 return ops->dev_disable_feat(dev, feat);
2914 EXPORT_SYMBOL_GPL(iommu_dev_disable_feature);
2917 * iommu_setup_default_domain - Set the default_domain for the group
2918 * @group: Group to change
2919 * @target_type: Domain type to set as the default_domain
2921 * Allocate a default domain and set it as the current domain on the group. If
2922 * the group already has a default domain it will be changed to the target_type.
2923 * When target_type is 0 the default domain is selected based on driver and
2924 * system preferences.
2926 static int iommu_setup_default_domain(struct iommu_group *group,
2929 struct iommu_domain *old_dom = group->default_domain;
2930 struct group_device *gdev;
2931 struct iommu_domain *dom;
2936 lockdep_assert_held(&group->mutex);
2938 req_type = iommu_get_default_domain_type(group, target_type);
2942 dom = iommu_group_alloc_default_domain(group, req_type);
2944 return PTR_ERR(dom);
2946 if (group->default_domain == dom)
2950 * IOMMU_RESV_DIRECT and IOMMU_RESV_DIRECT_RELAXABLE regions must be
2951 * mapped before their device is attached, in order to guarantee
2952 * continuity with any FW activity
2954 direct_failed = false;
2955 for_each_group_device(group, gdev) {
2956 if (iommu_create_device_direct_mappings(dom, gdev->dev)) {
2957 direct_failed = true;
2959 gdev->dev->iommu->iommu_dev->dev,
2960 "IOMMU driver was not able to establish FW requested direct mapping.");
2964 /* We must set default_domain early for __iommu_device_set_domain */
2965 group->default_domain = dom;
2966 if (!group->domain) {
2968 * Drivers are not allowed to fail the first domain attach.
2969 * The only way to recover from this is to fail attaching the
2970 * iommu driver and call ops->release_device. Put the domain
2971 * in group->default_domain so it is freed after.
2973 ret = __iommu_group_set_domain_internal(
2974 group, dom, IOMMU_SET_DOMAIN_MUST_SUCCEED);
2978 ret = __iommu_group_set_domain(group, dom);
2980 goto err_restore_def_domain;
2984 * Drivers are supposed to allow mappings to be installed in a domain
2985 * before device attachment, but some don't. Hack around this defect by
2986 * trying again after attaching. If this happens it means the device
2987 * will not continuously have the IOMMU_RESV_DIRECT map.
2989 if (direct_failed) {
2990 for_each_group_device(group, gdev) {
2991 ret = iommu_create_device_direct_mappings(dom, gdev->dev);
2993 goto err_restore_domain;
2999 iommu_domain_free(old_dom);
3004 __iommu_group_set_domain_internal(
3005 group, old_dom, IOMMU_SET_DOMAIN_MUST_SUCCEED);
3006 err_restore_def_domain:
3008 iommu_domain_free(dom);
3009 group->default_domain = old_dom;
3015 * Changing the default domain through sysfs requires the users to unbind the
3016 * drivers from the devices in the iommu group, except for a DMA -> DMA-FQ
3017 * transition. Return failure if this isn't met.
3019 * We need to consider the race between this and the device release path.
3020 * group->mutex is used here to guarantee that the device release path
3021 * will not be entered at the same time.
3023 static ssize_t iommu_group_store_type(struct iommu_group *group,
3024 const char *buf, size_t count)
3026 struct group_device *gdev;
3029 if (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO))
3032 if (WARN_ON(!group) || !group->default_domain)
3035 if (sysfs_streq(buf, "identity"))
3036 req_type = IOMMU_DOMAIN_IDENTITY;
3037 else if (sysfs_streq(buf, "DMA"))
3038 req_type = IOMMU_DOMAIN_DMA;
3039 else if (sysfs_streq(buf, "DMA-FQ"))
3040 req_type = IOMMU_DOMAIN_DMA_FQ;
3041 else if (sysfs_streq(buf, "auto"))
3046 mutex_lock(&group->mutex);
3047 /* We can bring up a flush queue without tearing down the domain. */
3048 if (req_type == IOMMU_DOMAIN_DMA_FQ &&
3049 group->default_domain->type == IOMMU_DOMAIN_DMA) {
3050 ret = iommu_dma_init_fq(group->default_domain);
3054 group->default_domain->type = IOMMU_DOMAIN_DMA_FQ;
3059 /* Otherwise, ensure that device exists and no driver is bound. */
3060 if (list_empty(&group->devices) || group->owner_cnt) {
3065 ret = iommu_setup_default_domain(group, req_type);
3070 * Release the mutex here because ops->probe_finalize() call-back of
3071 * some vendor IOMMU drivers calls arm_iommu_attach_device() which
3072 * in-turn might call back into IOMMU core code, where it tries to take
3073 * group->mutex, resulting in a deadlock.
3075 mutex_unlock(&group->mutex);
3077 /* Make sure dma_ops is appropriatley set */
3078 for_each_group_device(group, gdev)
3079 iommu_group_do_probe_finalize(gdev->dev);
3083 mutex_unlock(&group->mutex);
3084 return ret ?: count;
3088 * iommu_device_use_default_domain() - Device driver wants to handle device
3089 * DMA through the kernel DMA API.
3092 * The device driver about to bind @dev wants to do DMA through the kernel
3093 * DMA API. Return 0 if it is allowed, otherwise an error.
3095 int iommu_device_use_default_domain(struct device *dev)
3097 /* Caller is the driver core during the pre-probe path */
3098 struct iommu_group *group = dev->iommu_group;
3104 mutex_lock(&group->mutex);
3105 if (group->owner_cnt) {
3106 if (group->domain != group->default_domain || group->owner ||
3107 !xa_empty(&group->pasid_array)) {
3116 mutex_unlock(&group->mutex);
3121 * iommu_device_unuse_default_domain() - Device driver stops handling device
3122 * DMA through the kernel DMA API.
3125 * The device driver doesn't want to do DMA through kernel DMA API anymore.
3126 * It must be called after iommu_device_use_default_domain().
3128 void iommu_device_unuse_default_domain(struct device *dev)
3130 /* Caller is the driver core during the post-probe path */
3131 struct iommu_group *group = dev->iommu_group;
3136 mutex_lock(&group->mutex);
3137 if (!WARN_ON(!group->owner_cnt || !xa_empty(&group->pasid_array)))
3140 mutex_unlock(&group->mutex);
3143 static int __iommu_group_alloc_blocking_domain(struct iommu_group *group)
3145 struct iommu_domain *domain;
3147 if (group->blocking_domain)
3150 domain = __iommu_group_domain_alloc(group, IOMMU_DOMAIN_BLOCKED);
3151 if (IS_ERR(domain)) {
3153 * For drivers that do not yet understand IOMMU_DOMAIN_BLOCKED
3154 * create an empty domain instead.
3156 domain = __iommu_group_domain_alloc(group,
3157 IOMMU_DOMAIN_UNMANAGED);
3159 return PTR_ERR(domain);
3161 group->blocking_domain = domain;
3165 static int __iommu_take_dma_ownership(struct iommu_group *group, void *owner)
3169 if ((group->domain && group->domain != group->default_domain) ||
3170 !xa_empty(&group->pasid_array))
3173 ret = __iommu_group_alloc_blocking_domain(group);
3176 ret = __iommu_group_set_domain(group, group->blocking_domain);
3180 group->owner = owner;
3186 * iommu_group_claim_dma_owner() - Set DMA ownership of a group
3187 * @group: The group.
3188 * @owner: Caller specified pointer. Used for exclusive ownership.
3190 * This is to support backward compatibility for vfio which manages the dma
3191 * ownership in iommu_group level. New invocations on this interface should be
3192 * prohibited. Only a single owner may exist for a group.
3194 int iommu_group_claim_dma_owner(struct iommu_group *group, void *owner)
3198 if (WARN_ON(!owner))
3201 mutex_lock(&group->mutex);
3202 if (group->owner_cnt) {
3207 ret = __iommu_take_dma_ownership(group, owner);
3209 mutex_unlock(&group->mutex);
3213 EXPORT_SYMBOL_GPL(iommu_group_claim_dma_owner);
3216 * iommu_device_claim_dma_owner() - Set DMA ownership of a device
3218 * @owner: Caller specified pointer. Used for exclusive ownership.
3220 * Claim the DMA ownership of a device. Multiple devices in the same group may
3221 * concurrently claim ownership if they present the same owner value. Returns 0
3222 * on success and error code on failure
3224 int iommu_device_claim_dma_owner(struct device *dev, void *owner)
3226 /* Caller must be a probed driver on dev */
3227 struct iommu_group *group = dev->iommu_group;
3230 if (WARN_ON(!owner))
3236 mutex_lock(&group->mutex);
3237 if (group->owner_cnt) {
3238 if (group->owner != owner) {
3246 ret = __iommu_take_dma_ownership(group, owner);
3248 mutex_unlock(&group->mutex);
3251 EXPORT_SYMBOL_GPL(iommu_device_claim_dma_owner);
3253 static void __iommu_release_dma_ownership(struct iommu_group *group)
3255 if (WARN_ON(!group->owner_cnt || !group->owner ||
3256 !xa_empty(&group->pasid_array)))
3259 group->owner_cnt = 0;
3260 group->owner = NULL;
3261 __iommu_group_set_domain_nofail(group, group->default_domain);
3265 * iommu_group_release_dma_owner() - Release DMA ownership of a group
3268 * Release the DMA ownership claimed by iommu_group_claim_dma_owner().
3270 void iommu_group_release_dma_owner(struct iommu_group *group)
3272 mutex_lock(&group->mutex);
3273 __iommu_release_dma_ownership(group);
3274 mutex_unlock(&group->mutex);
3276 EXPORT_SYMBOL_GPL(iommu_group_release_dma_owner);
3279 * iommu_device_release_dma_owner() - Release DMA ownership of a device
3282 * Release the DMA ownership claimed by iommu_device_claim_dma_owner().
3284 void iommu_device_release_dma_owner(struct device *dev)
3286 /* Caller must be a probed driver on dev */
3287 struct iommu_group *group = dev->iommu_group;
3289 mutex_lock(&group->mutex);
3290 if (group->owner_cnt > 1)
3293 __iommu_release_dma_ownership(group);
3294 mutex_unlock(&group->mutex);
3296 EXPORT_SYMBOL_GPL(iommu_device_release_dma_owner);
3299 * iommu_group_dma_owner_claimed() - Query group dma ownership status
3300 * @group: The group.
3302 * This provides status query on a given group. It is racy and only for
3303 * non-binding status reporting.
3305 bool iommu_group_dma_owner_claimed(struct iommu_group *group)
3309 mutex_lock(&group->mutex);
3310 user = group->owner_cnt;
3311 mutex_unlock(&group->mutex);
3315 EXPORT_SYMBOL_GPL(iommu_group_dma_owner_claimed);
3317 static int __iommu_set_group_pasid(struct iommu_domain *domain,
3318 struct iommu_group *group, ioasid_t pasid)
3320 struct group_device *device;
3323 for_each_group_device(group, device) {
3324 ret = domain->ops->set_dev_pasid(domain, device->dev, pasid);
3332 static void __iommu_remove_group_pasid(struct iommu_group *group,
3335 struct group_device *device;
3336 const struct iommu_ops *ops;
3338 for_each_group_device(group, device) {
3339 ops = dev_iommu_ops(device->dev);
3340 ops->remove_dev_pasid(device->dev, pasid);
3345 * iommu_attach_device_pasid() - Attach a domain to pasid of device
3346 * @domain: the iommu domain.
3347 * @dev: the attached device.
3348 * @pasid: the pasid of the device.
3350 * Return: 0 on success, or an error.
3352 int iommu_attach_device_pasid(struct iommu_domain *domain,
3353 struct device *dev, ioasid_t pasid)
3355 /* Caller must be a probed driver on dev */
3356 struct iommu_group *group = dev->iommu_group;
3360 if (!domain->ops->set_dev_pasid)
3366 if (!dev_has_iommu(dev) || dev_iommu_ops(dev) != domain->owner)
3369 mutex_lock(&group->mutex);
3370 curr = xa_cmpxchg(&group->pasid_array, pasid, NULL, domain, GFP_KERNEL);
3372 ret = xa_err(curr) ? : -EBUSY;
3376 ret = __iommu_set_group_pasid(domain, group, pasid);
3378 __iommu_remove_group_pasid(group, pasid);
3379 xa_erase(&group->pasid_array, pasid);
3382 mutex_unlock(&group->mutex);
3385 EXPORT_SYMBOL_GPL(iommu_attach_device_pasid);
3388 * iommu_detach_device_pasid() - Detach the domain from pasid of device
3389 * @domain: the iommu domain.
3390 * @dev: the attached device.
3391 * @pasid: the pasid of the device.
3393 * The @domain must have been attached to @pasid of the @dev with
3394 * iommu_attach_device_pasid().
3396 void iommu_detach_device_pasid(struct iommu_domain *domain, struct device *dev,
3399 /* Caller must be a probed driver on dev */
3400 struct iommu_group *group = dev->iommu_group;
3402 mutex_lock(&group->mutex);
3403 __iommu_remove_group_pasid(group, pasid);
3404 WARN_ON(xa_erase(&group->pasid_array, pasid) != domain);
3405 mutex_unlock(&group->mutex);
3407 EXPORT_SYMBOL_GPL(iommu_detach_device_pasid);
3410 * iommu_get_domain_for_dev_pasid() - Retrieve domain for @pasid of @dev
3411 * @dev: the queried device
3412 * @pasid: the pasid of the device
3413 * @type: matched domain type, 0 for any match
3415 * This is a variant of iommu_get_domain_for_dev(). It returns the existing
3416 * domain attached to pasid of a device. Callers must hold a lock around this
3417 * function, and both iommu_attach/detach_dev_pasid() whenever a domain of
3418 * type is being manipulated. This API does not internally resolve races with
3421 * Return: attached domain on success, NULL otherwise.
3423 struct iommu_domain *iommu_get_domain_for_dev_pasid(struct device *dev,
3427 /* Caller must be a probed driver on dev */
3428 struct iommu_group *group = dev->iommu_group;
3429 struct iommu_domain *domain;
3434 xa_lock(&group->pasid_array);
3435 domain = xa_load(&group->pasid_array, pasid);
3436 if (type && domain && domain->type != type)
3437 domain = ERR_PTR(-EBUSY);
3438 xa_unlock(&group->pasid_array);
3442 EXPORT_SYMBOL_GPL(iommu_get_domain_for_dev_pasid);
3444 ioasid_t iommu_alloc_global_pasid(struct device *dev)
3448 /* max_pasids == 0 means that the device does not support PASID */
3449 if (!dev->iommu->max_pasids)
3450 return IOMMU_PASID_INVALID;
3453 * max_pasids is set up by vendor driver based on number of PASID bits
3454 * supported but the IDA allocation is inclusive.
3456 ret = ida_alloc_range(&iommu_global_pasid_ida, IOMMU_FIRST_GLOBAL_PASID,
3457 dev->iommu->max_pasids - 1, GFP_KERNEL);
3458 return ret < 0 ? IOMMU_PASID_INVALID : ret;
3460 EXPORT_SYMBOL_GPL(iommu_alloc_global_pasid);
3462 void iommu_free_global_pasid(ioasid_t pasid)
3464 if (WARN_ON(pasid == IOMMU_PASID_INVALID))
3467 ida_free(&iommu_global_pasid_ida, pasid);
3469 EXPORT_SYMBOL_GPL(iommu_free_global_pasid);