1 // SPDX-License-Identifier: GPL-2.0-only
3 * Copyright (C) 2007-2008 Advanced Micro Devices, Inc.
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"
38 #include "iommu-sva.h"
40 static struct kset *iommu_group_kset;
41 static DEFINE_IDA(iommu_group_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 *__iommu_domain_alloc(const struct bus_type *bus,
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 struct iommu_group *iommu_group_get_for_dev(struct device *dev);
131 static ssize_t iommu_group_store_type(struct iommu_group *group,
132 const char *buf, size_t count);
134 #define IOMMU_GROUP_ATTR(_name, _mode, _show, _store) \
135 struct iommu_group_attribute iommu_group_attr_##_name = \
136 __ATTR(_name, _mode, _show, _store)
138 #define to_iommu_group_attr(_attr) \
139 container_of(_attr, struct iommu_group_attribute, attr)
140 #define to_iommu_group(_kobj) \
141 container_of(_kobj, struct iommu_group, kobj)
143 static LIST_HEAD(iommu_device_list);
144 static DEFINE_SPINLOCK(iommu_device_lock);
146 static struct bus_type * const iommu_buses[] = {
151 #ifdef CONFIG_ARM_AMBA
154 #ifdef CONFIG_FSL_MC_BUS
157 #ifdef CONFIG_TEGRA_HOST1X_CONTEXT_BUS
158 &host1x_context_device_bus_type,
160 #ifdef CONFIG_CDX_BUS
166 * Use a function instead of an array here because the domain-type is a
167 * bit-field, so an array would waste memory.
169 static const char *iommu_domain_type_str(unsigned int t)
172 case IOMMU_DOMAIN_BLOCKED:
174 case IOMMU_DOMAIN_IDENTITY:
175 return "Passthrough";
176 case IOMMU_DOMAIN_UNMANAGED:
178 case IOMMU_DOMAIN_DMA:
179 case IOMMU_DOMAIN_DMA_FQ:
186 static int __init iommu_subsys_init(void)
188 struct notifier_block *nb;
190 if (!(iommu_cmd_line & IOMMU_CMD_LINE_DMA_API)) {
191 if (IS_ENABLED(CONFIG_IOMMU_DEFAULT_PASSTHROUGH))
192 iommu_set_default_passthrough(false);
194 iommu_set_default_translated(false);
196 if (iommu_default_passthrough() && cc_platform_has(CC_ATTR_MEM_ENCRYPT)) {
197 pr_info("Memory encryption detected - Disabling default IOMMU Passthrough\n");
198 iommu_set_default_translated(false);
202 if (!iommu_default_passthrough() && !iommu_dma_strict)
203 iommu_def_domain_type = IOMMU_DOMAIN_DMA_FQ;
205 pr_info("Default domain type: %s%s\n",
206 iommu_domain_type_str(iommu_def_domain_type),
207 (iommu_cmd_line & IOMMU_CMD_LINE_DMA_API) ?
208 " (set via kernel command line)" : "");
210 if (!iommu_default_passthrough())
211 pr_info("DMA domain TLB invalidation policy: %s mode%s\n",
212 iommu_dma_strict ? "strict" : "lazy",
213 (iommu_cmd_line & IOMMU_CMD_LINE_STRICT) ?
214 " (set via kernel command line)" : "");
216 nb = kcalloc(ARRAY_SIZE(iommu_buses), sizeof(*nb), GFP_KERNEL);
220 for (int i = 0; i < ARRAY_SIZE(iommu_buses); i++) {
221 nb[i].notifier_call = iommu_bus_notifier;
222 bus_register_notifier(iommu_buses[i], &nb[i]);
227 subsys_initcall(iommu_subsys_init);
229 static int remove_iommu_group(struct device *dev, void *data)
231 if (dev->iommu && dev->iommu->iommu_dev == data)
232 iommu_release_device(dev);
238 * iommu_device_register() - Register an IOMMU hardware instance
239 * @iommu: IOMMU handle for the instance
240 * @ops: IOMMU ops to associate with the instance
241 * @hwdev: (optional) actual instance device, used for fwnode lookup
243 * Return: 0 on success, or an error.
245 int iommu_device_register(struct iommu_device *iommu,
246 const struct iommu_ops *ops, struct device *hwdev)
250 /* We need to be able to take module references appropriately */
251 if (WARN_ON(is_module_address((unsigned long)ops) && !ops->owner))
254 * Temporarily enforce global restriction to a single driver. This was
255 * already the de-facto behaviour, since any possible combination of
256 * existing drivers would compete for at least the PCI or platform bus.
258 if (iommu_buses[0]->iommu_ops && iommu_buses[0]->iommu_ops != ops)
263 iommu->fwnode = dev_fwnode(hwdev);
265 spin_lock(&iommu_device_lock);
266 list_add_tail(&iommu->list, &iommu_device_list);
267 spin_unlock(&iommu_device_lock);
269 for (int i = 0; i < ARRAY_SIZE(iommu_buses) && !err; i++) {
270 iommu_buses[i]->iommu_ops = ops;
271 err = bus_iommu_probe(iommu_buses[i]);
274 iommu_device_unregister(iommu);
277 EXPORT_SYMBOL_GPL(iommu_device_register);
279 void iommu_device_unregister(struct iommu_device *iommu)
281 for (int i = 0; i < ARRAY_SIZE(iommu_buses); i++)
282 bus_for_each_dev(iommu_buses[i], NULL, iommu, remove_iommu_group);
284 spin_lock(&iommu_device_lock);
285 list_del(&iommu->list);
286 spin_unlock(&iommu_device_lock);
288 EXPORT_SYMBOL_GPL(iommu_device_unregister);
290 static struct dev_iommu *dev_iommu_get(struct device *dev)
292 struct dev_iommu *param = dev->iommu;
297 param = kzalloc(sizeof(*param), GFP_KERNEL);
301 mutex_init(¶m->lock);
306 static void dev_iommu_free(struct device *dev)
308 struct dev_iommu *param = dev->iommu;
312 fwnode_handle_put(param->fwspec->iommu_fwnode);
313 kfree(param->fwspec);
318 static u32 dev_iommu_get_max_pasids(struct device *dev)
320 u32 max_pasids = 0, bits = 0;
323 if (dev_is_pci(dev)) {
324 ret = pci_max_pasids(to_pci_dev(dev));
328 ret = device_property_read_u32(dev, "pasid-num-bits", &bits);
330 max_pasids = 1UL << bits;
333 return min_t(u32, max_pasids, dev->iommu->iommu_dev->max_pasids);
336 static int __iommu_probe_device(struct device *dev, struct list_head *group_list)
338 const struct iommu_ops *ops = dev->bus->iommu_ops;
339 struct iommu_device *iommu_dev;
340 struct iommu_group *group;
341 static DEFINE_MUTEX(iommu_probe_device_lock);
347 * Serialise to avoid races between IOMMU drivers registering in
348 * parallel and/or the "replay" calls from ACPI/OF code via client
349 * driver probe. Once the latter have been cleaned up we should
350 * probably be able to use device_lock() here to minimise the scope,
351 * but for now enforcing a simple global ordering is fine.
353 mutex_lock(&iommu_probe_device_lock);
354 if (!dev_iommu_get(dev)) {
359 if (!try_module_get(ops->owner)) {
364 iommu_dev = ops->probe_device(dev);
365 if (IS_ERR(iommu_dev)) {
366 ret = PTR_ERR(iommu_dev);
370 dev->iommu->iommu_dev = iommu_dev;
371 dev->iommu->max_pasids = dev_iommu_get_max_pasids(dev);
372 if (ops->is_attach_deferred)
373 dev->iommu->attach_deferred = ops->is_attach_deferred(dev);
375 group = iommu_group_get_for_dev(dev);
377 ret = PTR_ERR(group);
381 mutex_lock(&group->mutex);
382 if (group_list && !group->default_domain && list_empty(&group->entry))
383 list_add_tail(&group->entry, group_list);
384 mutex_unlock(&group->mutex);
385 iommu_group_put(group);
387 mutex_unlock(&iommu_probe_device_lock);
388 iommu_device_link(iommu_dev, dev);
393 if (ops->release_device)
394 ops->release_device(dev);
397 module_put(ops->owner);
403 mutex_unlock(&iommu_probe_device_lock);
408 int iommu_probe_device(struct device *dev)
410 const struct iommu_ops *ops;
411 struct iommu_group *group;
414 ret = __iommu_probe_device(dev, NULL);
418 group = iommu_group_get(dev);
424 mutex_lock(&group->mutex);
426 if (group->default_domain)
427 iommu_create_device_direct_mappings(group->default_domain, dev);
430 ret = __iommu_device_set_domain(group, dev, group->domain, 0);
433 } else if (!group->default_domain) {
434 ret = iommu_setup_default_domain(group, 0);
439 mutex_unlock(&group->mutex);
440 iommu_group_put(group);
442 ops = dev_iommu_ops(dev);
443 if (ops->probe_finalize)
444 ops->probe_finalize(dev);
449 mutex_unlock(&group->mutex);
450 iommu_group_put(group);
452 iommu_release_device(dev);
460 * Remove a device from a group's device list and return the group device
463 static struct group_device *
464 __iommu_group_remove_device(struct iommu_group *group, struct device *dev)
466 struct group_device *device;
468 lockdep_assert_held(&group->mutex);
469 for_each_group_device(group, device) {
470 if (device->dev == dev) {
471 list_del(&device->list);
480 * Release a device from its group and decrements the iommu group reference
483 static void __iommu_group_release_device(struct iommu_group *group,
484 struct group_device *grp_dev)
486 struct device *dev = grp_dev->dev;
488 sysfs_remove_link(group->devices_kobj, grp_dev->name);
489 sysfs_remove_link(&dev->kobj, "iommu_group");
491 trace_remove_device_from_group(group->id, dev);
493 kfree(grp_dev->name);
495 dev->iommu_group = NULL;
496 kobject_put(group->devices_kobj);
499 static void iommu_release_device(struct device *dev)
501 struct iommu_group *group = dev->iommu_group;
502 struct group_device *device;
503 const struct iommu_ops *ops;
505 if (!dev->iommu || !group)
508 iommu_device_unlink(dev->iommu->iommu_dev, dev);
510 mutex_lock(&group->mutex);
511 device = __iommu_group_remove_device(group, dev);
514 * If the group has become empty then ownership must have been released,
515 * and the current domain must be set back to NULL or the default
518 if (list_empty(&group->devices))
519 WARN_ON(group->owner_cnt ||
520 group->domain != group->default_domain);
523 * release_device() must stop using any attached domain on the device.
524 * If there are still other devices in the group they are not effected
527 * The IOMMU driver must set the device to either an identity or
528 * blocking translation and stop using any domain pointer, as it is
531 ops = dev_iommu_ops(dev);
532 if (ops->release_device)
533 ops->release_device(dev);
534 mutex_unlock(&group->mutex);
537 __iommu_group_release_device(group, device);
539 module_put(ops->owner);
543 static int __init iommu_set_def_domain_type(char *str)
548 ret = kstrtobool(str, &pt);
553 iommu_set_default_passthrough(true);
555 iommu_set_default_translated(true);
559 early_param("iommu.passthrough", iommu_set_def_domain_type);
561 static int __init iommu_dma_setup(char *str)
563 int ret = kstrtobool(str, &iommu_dma_strict);
566 iommu_cmd_line |= IOMMU_CMD_LINE_STRICT;
569 early_param("iommu.strict", iommu_dma_setup);
571 void iommu_set_dma_strict(void)
573 iommu_dma_strict = true;
574 if (iommu_def_domain_type == IOMMU_DOMAIN_DMA_FQ)
575 iommu_def_domain_type = IOMMU_DOMAIN_DMA;
578 static ssize_t iommu_group_attr_show(struct kobject *kobj,
579 struct attribute *__attr, char *buf)
581 struct iommu_group_attribute *attr = to_iommu_group_attr(__attr);
582 struct iommu_group *group = to_iommu_group(kobj);
586 ret = attr->show(group, buf);
590 static ssize_t iommu_group_attr_store(struct kobject *kobj,
591 struct attribute *__attr,
592 const char *buf, size_t count)
594 struct iommu_group_attribute *attr = to_iommu_group_attr(__attr);
595 struct iommu_group *group = to_iommu_group(kobj);
599 ret = attr->store(group, buf, count);
603 static const struct sysfs_ops iommu_group_sysfs_ops = {
604 .show = iommu_group_attr_show,
605 .store = iommu_group_attr_store,
608 static int iommu_group_create_file(struct iommu_group *group,
609 struct iommu_group_attribute *attr)
611 return sysfs_create_file(&group->kobj, &attr->attr);
614 static void iommu_group_remove_file(struct iommu_group *group,
615 struct iommu_group_attribute *attr)
617 sysfs_remove_file(&group->kobj, &attr->attr);
620 static ssize_t iommu_group_show_name(struct iommu_group *group, char *buf)
622 return sysfs_emit(buf, "%s\n", group->name);
626 * iommu_insert_resv_region - Insert a new region in the
627 * list of reserved regions.
628 * @new: new region to insert
629 * @regions: list of regions
631 * Elements are sorted by start address and overlapping segments
632 * of the same type are merged.
634 static int iommu_insert_resv_region(struct iommu_resv_region *new,
635 struct list_head *regions)
637 struct iommu_resv_region *iter, *tmp, *nr, *top;
640 nr = iommu_alloc_resv_region(new->start, new->length,
641 new->prot, new->type, GFP_KERNEL);
645 /* First add the new element based on start address sorting */
646 list_for_each_entry(iter, regions, list) {
647 if (nr->start < iter->start ||
648 (nr->start == iter->start && nr->type <= iter->type))
651 list_add_tail(&nr->list, &iter->list);
653 /* Merge overlapping segments of type nr->type in @regions, if any */
654 list_for_each_entry_safe(iter, tmp, regions, list) {
655 phys_addr_t top_end, iter_end = iter->start + iter->length - 1;
657 /* no merge needed on elements of different types than @new */
658 if (iter->type != new->type) {
659 list_move_tail(&iter->list, &stack);
663 /* look for the last stack element of same type as @iter */
664 list_for_each_entry_reverse(top, &stack, list)
665 if (top->type == iter->type)
668 list_move_tail(&iter->list, &stack);
672 top_end = top->start + top->length - 1;
674 if (iter->start > top_end + 1) {
675 list_move_tail(&iter->list, &stack);
677 top->length = max(top_end, iter_end) - top->start + 1;
678 list_del(&iter->list);
682 list_splice(&stack, regions);
687 iommu_insert_device_resv_regions(struct list_head *dev_resv_regions,
688 struct list_head *group_resv_regions)
690 struct iommu_resv_region *entry;
693 list_for_each_entry(entry, dev_resv_regions, list) {
694 ret = iommu_insert_resv_region(entry, group_resv_regions);
701 int iommu_get_group_resv_regions(struct iommu_group *group,
702 struct list_head *head)
704 struct group_device *device;
707 mutex_lock(&group->mutex);
708 for_each_group_device(group, device) {
709 struct list_head dev_resv_regions;
712 * Non-API groups still expose reserved_regions in sysfs,
713 * so filter out calls that get here that way.
715 if (!device->dev->iommu)
718 INIT_LIST_HEAD(&dev_resv_regions);
719 iommu_get_resv_regions(device->dev, &dev_resv_regions);
720 ret = iommu_insert_device_resv_regions(&dev_resv_regions, head);
721 iommu_put_resv_regions(device->dev, &dev_resv_regions);
725 mutex_unlock(&group->mutex);
728 EXPORT_SYMBOL_GPL(iommu_get_group_resv_regions);
730 static ssize_t iommu_group_show_resv_regions(struct iommu_group *group,
733 struct iommu_resv_region *region, *next;
734 struct list_head group_resv_regions;
737 INIT_LIST_HEAD(&group_resv_regions);
738 iommu_get_group_resv_regions(group, &group_resv_regions);
740 list_for_each_entry_safe(region, next, &group_resv_regions, list) {
741 offset += sysfs_emit_at(buf, offset, "0x%016llx 0x%016llx %s\n",
742 (long long)region->start,
743 (long long)(region->start +
745 iommu_group_resv_type_string[region->type]);
752 static ssize_t iommu_group_show_type(struct iommu_group *group,
755 char *type = "unknown";
757 mutex_lock(&group->mutex);
758 if (group->default_domain) {
759 switch (group->default_domain->type) {
760 case IOMMU_DOMAIN_BLOCKED:
763 case IOMMU_DOMAIN_IDENTITY:
766 case IOMMU_DOMAIN_UNMANAGED:
769 case IOMMU_DOMAIN_DMA:
772 case IOMMU_DOMAIN_DMA_FQ:
777 mutex_unlock(&group->mutex);
779 return sysfs_emit(buf, "%s\n", type);
782 static IOMMU_GROUP_ATTR(name, S_IRUGO, iommu_group_show_name, NULL);
784 static IOMMU_GROUP_ATTR(reserved_regions, 0444,
785 iommu_group_show_resv_regions, NULL);
787 static IOMMU_GROUP_ATTR(type, 0644, iommu_group_show_type,
788 iommu_group_store_type);
790 static void iommu_group_release(struct kobject *kobj)
792 struct iommu_group *group = to_iommu_group(kobj);
794 pr_debug("Releasing group %d\n", group->id);
796 if (group->iommu_data_release)
797 group->iommu_data_release(group->iommu_data);
799 ida_free(&iommu_group_ida, group->id);
801 if (group->default_domain)
802 iommu_domain_free(group->default_domain);
803 if (group->blocking_domain)
804 iommu_domain_free(group->blocking_domain);
810 static const struct kobj_type iommu_group_ktype = {
811 .sysfs_ops = &iommu_group_sysfs_ops,
812 .release = iommu_group_release,
816 * iommu_group_alloc - Allocate a new group
818 * This function is called by an iommu driver to allocate a new iommu
819 * group. The iommu group represents the minimum granularity of the iommu.
820 * Upon successful return, the caller holds a reference to the supplied
821 * group in order to hold the group until devices are added. Use
822 * iommu_group_put() to release this extra reference count, allowing the
823 * group to be automatically reclaimed once it has no devices or external
826 struct iommu_group *iommu_group_alloc(void)
828 struct iommu_group *group;
831 group = kzalloc(sizeof(*group), GFP_KERNEL);
833 return ERR_PTR(-ENOMEM);
835 group->kobj.kset = iommu_group_kset;
836 mutex_init(&group->mutex);
837 INIT_LIST_HEAD(&group->devices);
838 INIT_LIST_HEAD(&group->entry);
839 xa_init(&group->pasid_array);
841 ret = ida_alloc(&iommu_group_ida, GFP_KERNEL);
848 ret = kobject_init_and_add(&group->kobj, &iommu_group_ktype,
849 NULL, "%d", group->id);
851 kobject_put(&group->kobj);
855 group->devices_kobj = kobject_create_and_add("devices", &group->kobj);
856 if (!group->devices_kobj) {
857 kobject_put(&group->kobj); /* triggers .release & free */
858 return ERR_PTR(-ENOMEM);
862 * The devices_kobj holds a reference on the group kobject, so
863 * as long as that exists so will the group. We can therefore
864 * use the devices_kobj for reference counting.
866 kobject_put(&group->kobj);
868 ret = iommu_group_create_file(group,
869 &iommu_group_attr_reserved_regions);
871 kobject_put(group->devices_kobj);
875 ret = iommu_group_create_file(group, &iommu_group_attr_type);
877 kobject_put(group->devices_kobj);
881 pr_debug("Allocated group %d\n", group->id);
885 EXPORT_SYMBOL_GPL(iommu_group_alloc);
888 * iommu_group_get_iommudata - retrieve iommu_data registered for a group
891 * iommu drivers can store data in the group for use when doing iommu
892 * operations. This function provides a way to retrieve it. Caller
893 * should hold a group reference.
895 void *iommu_group_get_iommudata(struct iommu_group *group)
897 return group->iommu_data;
899 EXPORT_SYMBOL_GPL(iommu_group_get_iommudata);
902 * iommu_group_set_iommudata - set iommu_data for a group
904 * @iommu_data: new data
905 * @release: release function for iommu_data
907 * iommu drivers can store data in the group for use when doing iommu
908 * operations. This function provides a way to set the data after
909 * the group has been allocated. Caller should hold a group reference.
911 void iommu_group_set_iommudata(struct iommu_group *group, void *iommu_data,
912 void (*release)(void *iommu_data))
914 group->iommu_data = iommu_data;
915 group->iommu_data_release = release;
917 EXPORT_SYMBOL_GPL(iommu_group_set_iommudata);
920 * iommu_group_set_name - set name for a group
924 * Allow iommu driver to set a name for a group. When set it will
925 * appear in a name attribute file under the group in sysfs.
927 int iommu_group_set_name(struct iommu_group *group, const char *name)
932 iommu_group_remove_file(group, &iommu_group_attr_name);
939 group->name = kstrdup(name, GFP_KERNEL);
943 ret = iommu_group_create_file(group, &iommu_group_attr_name);
952 EXPORT_SYMBOL_GPL(iommu_group_set_name);
954 static int iommu_create_device_direct_mappings(struct iommu_domain *domain,
957 struct iommu_resv_region *entry;
958 struct list_head mappings;
959 unsigned long pg_size;
962 if (!iommu_is_dma_domain(domain))
965 BUG_ON(!domain->pgsize_bitmap);
967 pg_size = 1UL << __ffs(domain->pgsize_bitmap);
968 INIT_LIST_HEAD(&mappings);
970 iommu_get_resv_regions(dev, &mappings);
972 /* We need to consider overlapping regions for different devices */
973 list_for_each_entry(entry, &mappings, list) {
974 dma_addr_t start, end, addr;
977 start = ALIGN(entry->start, pg_size);
978 end = ALIGN(entry->start + entry->length, pg_size);
980 if (entry->type != IOMMU_RESV_DIRECT &&
981 entry->type != IOMMU_RESV_DIRECT_RELAXABLE)
984 for (addr = start; addr <= end; addr += pg_size) {
985 phys_addr_t phys_addr;
990 phys_addr = iommu_iova_to_phys(domain, addr);
998 ret = iommu_map(domain, addr - map_size,
999 addr - map_size, map_size,
1000 entry->prot, GFP_KERNEL);
1009 iommu_flush_iotlb_all(domain);
1012 iommu_put_resv_regions(dev, &mappings);
1018 * iommu_group_add_device - add a device to an iommu group
1019 * @group: the group into which to add the device (reference should be held)
1022 * This function is called by an iommu driver to add a device into a
1023 * group. Adding a device increments the group reference count.
1025 int iommu_group_add_device(struct iommu_group *group, struct device *dev)
1028 struct group_device *device;
1030 device = kzalloc(sizeof(*device), GFP_KERNEL);
1036 ret = sysfs_create_link(&dev->kobj, &group->kobj, "iommu_group");
1038 goto err_free_device;
1040 device->name = kasprintf(GFP_KERNEL, "%s", kobject_name(&dev->kobj));
1042 if (!device->name) {
1044 goto err_remove_link;
1047 ret = sysfs_create_link_nowarn(group->devices_kobj,
1048 &dev->kobj, device->name);
1050 if (ret == -EEXIST && i >= 0) {
1052 * Account for the slim chance of collision
1053 * and append an instance to the name.
1055 kfree(device->name);
1056 device->name = kasprintf(GFP_KERNEL, "%s.%d",
1057 kobject_name(&dev->kobj), i++);
1063 kobject_get(group->devices_kobj);
1065 dev->iommu_group = group;
1067 mutex_lock(&group->mutex);
1068 list_add_tail(&device->list, &group->devices);
1069 mutex_unlock(&group->mutex);
1070 trace_add_device_to_group(group->id, dev);
1072 dev_info(dev, "Adding to iommu group %d\n", group->id);
1077 kfree(device->name);
1079 sysfs_remove_link(&dev->kobj, "iommu_group");
1082 dev_err(dev, "Failed to add to iommu group %d: %d\n", group->id, ret);
1085 EXPORT_SYMBOL_GPL(iommu_group_add_device);
1088 * iommu_group_remove_device - remove a device from it's current group
1089 * @dev: device to be removed
1091 * This function is called by an iommu driver to remove the device from
1092 * it's current group. This decrements the iommu group reference count.
1094 void iommu_group_remove_device(struct device *dev)
1096 struct iommu_group *group = dev->iommu_group;
1097 struct group_device *device;
1102 dev_info(dev, "Removing from iommu group %d\n", group->id);
1104 mutex_lock(&group->mutex);
1105 device = __iommu_group_remove_device(group, dev);
1106 mutex_unlock(&group->mutex);
1109 __iommu_group_release_device(group, device);
1111 EXPORT_SYMBOL_GPL(iommu_group_remove_device);
1114 * iommu_group_for_each_dev - iterate over each device in the group
1116 * @data: caller opaque data to be passed to callback function
1117 * @fn: caller supplied callback function
1119 * This function is called by group users to iterate over group devices.
1120 * Callers should hold a reference count to the group during callback.
1121 * The group->mutex is held across callbacks, which will block calls to
1122 * iommu_group_add/remove_device.
1124 int iommu_group_for_each_dev(struct iommu_group *group, void *data,
1125 int (*fn)(struct device *, void *))
1127 struct group_device *device;
1130 mutex_lock(&group->mutex);
1131 for_each_group_device(group, device) {
1132 ret = fn(device->dev, data);
1136 mutex_unlock(&group->mutex);
1140 EXPORT_SYMBOL_GPL(iommu_group_for_each_dev);
1143 * iommu_group_get - Return the group for a device and increment reference
1144 * @dev: get the group that this device belongs to
1146 * This function is called by iommu drivers and users to get the group
1147 * for the specified device. If found, the group is returned and the group
1148 * reference in incremented, else NULL.
1150 struct iommu_group *iommu_group_get(struct device *dev)
1152 struct iommu_group *group = dev->iommu_group;
1155 kobject_get(group->devices_kobj);
1159 EXPORT_SYMBOL_GPL(iommu_group_get);
1162 * iommu_group_ref_get - Increment reference on a group
1163 * @group: the group to use, must not be NULL
1165 * This function is called by iommu drivers to take additional references on an
1166 * existing group. Returns the given group for convenience.
1168 struct iommu_group *iommu_group_ref_get(struct iommu_group *group)
1170 kobject_get(group->devices_kobj);
1173 EXPORT_SYMBOL_GPL(iommu_group_ref_get);
1176 * iommu_group_put - Decrement group reference
1177 * @group: the group to use
1179 * This function is called by iommu drivers and users to release the
1180 * iommu group. Once the reference count is zero, the group is released.
1182 void iommu_group_put(struct iommu_group *group)
1185 kobject_put(group->devices_kobj);
1187 EXPORT_SYMBOL_GPL(iommu_group_put);
1190 * iommu_register_device_fault_handler() - Register a device fault handler
1192 * @handler: the fault handler
1193 * @data: private data passed as argument to the handler
1195 * When an IOMMU fault event is received, this handler gets called with the
1196 * fault event and data as argument. The handler should return 0 on success. If
1197 * the fault is recoverable (IOMMU_FAULT_PAGE_REQ), the consumer should also
1198 * complete the fault by calling iommu_page_response() with one of the following
1200 * - IOMMU_PAGE_RESP_SUCCESS: retry the translation
1201 * - IOMMU_PAGE_RESP_INVALID: terminate the fault
1202 * - IOMMU_PAGE_RESP_FAILURE: terminate the fault and stop reporting
1203 * page faults if possible.
1205 * Return 0 if the fault handler was installed successfully, or an error.
1207 int iommu_register_device_fault_handler(struct device *dev,
1208 iommu_dev_fault_handler_t handler,
1211 struct dev_iommu *param = dev->iommu;
1217 mutex_lock(¶m->lock);
1218 /* Only allow one fault handler registered for each device */
1219 if (param->fault_param) {
1225 param->fault_param = kzalloc(sizeof(*param->fault_param), GFP_KERNEL);
1226 if (!param->fault_param) {
1231 param->fault_param->handler = handler;
1232 param->fault_param->data = data;
1233 mutex_init(¶m->fault_param->lock);
1234 INIT_LIST_HEAD(¶m->fault_param->faults);
1237 mutex_unlock(¶m->lock);
1241 EXPORT_SYMBOL_GPL(iommu_register_device_fault_handler);
1244 * iommu_unregister_device_fault_handler() - Unregister the device fault handler
1247 * Remove the device fault handler installed with
1248 * iommu_register_device_fault_handler().
1250 * Return 0 on success, or an error.
1252 int iommu_unregister_device_fault_handler(struct device *dev)
1254 struct dev_iommu *param = dev->iommu;
1260 mutex_lock(¶m->lock);
1262 if (!param->fault_param)
1265 /* we cannot unregister handler if there are pending faults */
1266 if (!list_empty(¶m->fault_param->faults)) {
1271 kfree(param->fault_param);
1272 param->fault_param = NULL;
1275 mutex_unlock(¶m->lock);
1279 EXPORT_SYMBOL_GPL(iommu_unregister_device_fault_handler);
1282 * iommu_report_device_fault() - Report fault event to device driver
1284 * @evt: fault event data
1286 * Called by IOMMU drivers when a fault is detected, typically in a threaded IRQ
1287 * handler. When this function fails and the fault is recoverable, it is the
1288 * caller's responsibility to complete the fault.
1290 * Return 0 on success, or an error.
1292 int iommu_report_device_fault(struct device *dev, struct iommu_fault_event *evt)
1294 struct dev_iommu *param = dev->iommu;
1295 struct iommu_fault_event *evt_pending = NULL;
1296 struct iommu_fault_param *fparam;
1302 /* we only report device fault if there is a handler registered */
1303 mutex_lock(¶m->lock);
1304 fparam = param->fault_param;
1305 if (!fparam || !fparam->handler) {
1310 if (evt->fault.type == IOMMU_FAULT_PAGE_REQ &&
1311 (evt->fault.prm.flags & IOMMU_FAULT_PAGE_REQUEST_LAST_PAGE)) {
1312 evt_pending = kmemdup(evt, sizeof(struct iommu_fault_event),
1318 mutex_lock(&fparam->lock);
1319 list_add_tail(&evt_pending->list, &fparam->faults);
1320 mutex_unlock(&fparam->lock);
1323 ret = fparam->handler(&evt->fault, fparam->data);
1324 if (ret && evt_pending) {
1325 mutex_lock(&fparam->lock);
1326 list_del(&evt_pending->list);
1327 mutex_unlock(&fparam->lock);
1331 mutex_unlock(¶m->lock);
1334 EXPORT_SYMBOL_GPL(iommu_report_device_fault);
1336 int iommu_page_response(struct device *dev,
1337 struct iommu_page_response *msg)
1341 struct iommu_fault_event *evt;
1342 struct iommu_fault_page_request *prm;
1343 struct dev_iommu *param = dev->iommu;
1344 const struct iommu_ops *ops = dev_iommu_ops(dev);
1345 bool has_pasid = msg->flags & IOMMU_PAGE_RESP_PASID_VALID;
1347 if (!ops->page_response)
1350 if (!param || !param->fault_param)
1353 if (msg->version != IOMMU_PAGE_RESP_VERSION_1 ||
1354 msg->flags & ~IOMMU_PAGE_RESP_PASID_VALID)
1357 /* Only send response if there is a fault report pending */
1358 mutex_lock(¶m->fault_param->lock);
1359 if (list_empty(¶m->fault_param->faults)) {
1360 dev_warn_ratelimited(dev, "no pending PRQ, drop response\n");
1364 * Check if we have a matching page request pending to respond,
1365 * otherwise return -EINVAL
1367 list_for_each_entry(evt, ¶m->fault_param->faults, list) {
1368 prm = &evt->fault.prm;
1369 if (prm->grpid != msg->grpid)
1373 * If the PASID is required, the corresponding request is
1374 * matched using the group ID, the PASID valid bit and the PASID
1375 * value. Otherwise only the group ID matches request and
1378 needs_pasid = prm->flags & IOMMU_FAULT_PAGE_RESPONSE_NEEDS_PASID;
1379 if (needs_pasid && (!has_pasid || msg->pasid != prm->pasid))
1382 if (!needs_pasid && has_pasid) {
1383 /* No big deal, just clear it. */
1384 msg->flags &= ~IOMMU_PAGE_RESP_PASID_VALID;
1388 ret = ops->page_response(dev, evt, msg);
1389 list_del(&evt->list);
1395 mutex_unlock(¶m->fault_param->lock);
1398 EXPORT_SYMBOL_GPL(iommu_page_response);
1401 * iommu_group_id - Return ID for a group
1402 * @group: the group to ID
1404 * Return the unique ID for the group matching the sysfs group number.
1406 int iommu_group_id(struct iommu_group *group)
1410 EXPORT_SYMBOL_GPL(iommu_group_id);
1412 static struct iommu_group *get_pci_alias_group(struct pci_dev *pdev,
1413 unsigned long *devfns);
1416 * To consider a PCI device isolated, we require ACS to support Source
1417 * Validation, Request Redirection, Completer Redirection, and Upstream
1418 * Forwarding. This effectively means that devices cannot spoof their
1419 * requester ID, requests and completions cannot be redirected, and all
1420 * transactions are forwarded upstream, even as it passes through a
1421 * bridge where the target device is downstream.
1423 #define REQ_ACS_FLAGS (PCI_ACS_SV | PCI_ACS_RR | PCI_ACS_CR | PCI_ACS_UF)
1426 * For multifunction devices which are not isolated from each other, find
1427 * all the other non-isolated functions and look for existing groups. For
1428 * each function, we also need to look for aliases to or from other devices
1429 * that may already have a group.
1431 static struct iommu_group *get_pci_function_alias_group(struct pci_dev *pdev,
1432 unsigned long *devfns)
1434 struct pci_dev *tmp = NULL;
1435 struct iommu_group *group;
1437 if (!pdev->multifunction || pci_acs_enabled(pdev, REQ_ACS_FLAGS))
1440 for_each_pci_dev(tmp) {
1441 if (tmp == pdev || tmp->bus != pdev->bus ||
1442 PCI_SLOT(tmp->devfn) != PCI_SLOT(pdev->devfn) ||
1443 pci_acs_enabled(tmp, REQ_ACS_FLAGS))
1446 group = get_pci_alias_group(tmp, devfns);
1457 * Look for aliases to or from the given device for existing groups. DMA
1458 * aliases are only supported on the same bus, therefore the search
1459 * space is quite small (especially since we're really only looking at pcie
1460 * device, and therefore only expect multiple slots on the root complex or
1461 * downstream switch ports). It's conceivable though that a pair of
1462 * multifunction devices could have aliases between them that would cause a
1463 * loop. To prevent this, we use a bitmap to track where we've been.
1465 static struct iommu_group *get_pci_alias_group(struct pci_dev *pdev,
1466 unsigned long *devfns)
1468 struct pci_dev *tmp = NULL;
1469 struct iommu_group *group;
1471 if (test_and_set_bit(pdev->devfn & 0xff, devfns))
1474 group = iommu_group_get(&pdev->dev);
1478 for_each_pci_dev(tmp) {
1479 if (tmp == pdev || tmp->bus != pdev->bus)
1482 /* We alias them or they alias us */
1483 if (pci_devs_are_dma_aliases(pdev, tmp)) {
1484 group = get_pci_alias_group(tmp, devfns);
1490 group = get_pci_function_alias_group(tmp, devfns);
1501 struct group_for_pci_data {
1502 struct pci_dev *pdev;
1503 struct iommu_group *group;
1507 * DMA alias iterator callback, return the last seen device. Stop and return
1508 * the IOMMU group if we find one along the way.
1510 static int get_pci_alias_or_group(struct pci_dev *pdev, u16 alias, void *opaque)
1512 struct group_for_pci_data *data = opaque;
1515 data->group = iommu_group_get(&pdev->dev);
1517 return data->group != NULL;
1521 * Generic device_group call-back function. It just allocates one
1522 * iommu-group per device.
1524 struct iommu_group *generic_device_group(struct device *dev)
1526 return iommu_group_alloc();
1528 EXPORT_SYMBOL_GPL(generic_device_group);
1531 * Use standard PCI bus topology, isolation features, and DMA alias quirks
1532 * to find or create an IOMMU group for a device.
1534 struct iommu_group *pci_device_group(struct device *dev)
1536 struct pci_dev *pdev = to_pci_dev(dev);
1537 struct group_for_pci_data data;
1538 struct pci_bus *bus;
1539 struct iommu_group *group = NULL;
1540 u64 devfns[4] = { 0 };
1542 if (WARN_ON(!dev_is_pci(dev)))
1543 return ERR_PTR(-EINVAL);
1546 * Find the upstream DMA alias for the device. A device must not
1547 * be aliased due to topology in order to have its own IOMMU group.
1548 * If we find an alias along the way that already belongs to a
1551 if (pci_for_each_dma_alias(pdev, get_pci_alias_or_group, &data))
1557 * Continue upstream from the point of minimum IOMMU granularity
1558 * due to aliases to the point where devices are protected from
1559 * peer-to-peer DMA by PCI ACS. Again, if we find an existing
1562 for (bus = pdev->bus; !pci_is_root_bus(bus); bus = bus->parent) {
1566 if (pci_acs_path_enabled(bus->self, NULL, REQ_ACS_FLAGS))
1571 group = iommu_group_get(&pdev->dev);
1577 * Look for existing groups on device aliases. If we alias another
1578 * device or another device aliases us, use the same group.
1580 group = get_pci_alias_group(pdev, (unsigned long *)devfns);
1585 * Look for existing groups on non-isolated functions on the same
1586 * slot and aliases of those funcions, if any. No need to clear
1587 * the search bitmap, the tested devfns are still valid.
1589 group = get_pci_function_alias_group(pdev, (unsigned long *)devfns);
1593 /* No shared group found, allocate new */
1594 return iommu_group_alloc();
1596 EXPORT_SYMBOL_GPL(pci_device_group);
1598 /* Get the IOMMU group for device on fsl-mc bus */
1599 struct iommu_group *fsl_mc_device_group(struct device *dev)
1601 struct device *cont_dev = fsl_mc_cont_dev(dev);
1602 struct iommu_group *group;
1604 group = iommu_group_get(cont_dev);
1606 group = iommu_group_alloc();
1609 EXPORT_SYMBOL_GPL(fsl_mc_device_group);
1611 static int iommu_get_def_domain_type(struct device *dev)
1613 const struct iommu_ops *ops = dev_iommu_ops(dev);
1615 if (dev_is_pci(dev) && to_pci_dev(dev)->untrusted)
1616 return IOMMU_DOMAIN_DMA;
1618 if (ops->def_domain_type)
1619 return ops->def_domain_type(dev);
1624 static struct iommu_domain *
1625 __iommu_group_alloc_default_domain(const struct bus_type *bus,
1626 struct iommu_group *group, int req_type)
1628 if (group->default_domain && group->default_domain->type == req_type)
1629 return group->default_domain;
1630 return __iommu_domain_alloc(bus, req_type);
1634 * req_type of 0 means "auto" which means to select a domain based on
1635 * iommu_def_domain_type or what the driver actually supports.
1637 static struct iommu_domain *
1638 iommu_group_alloc_default_domain(struct iommu_group *group, int req_type)
1640 const struct bus_type *bus =
1641 list_first_entry(&group->devices, struct group_device, list)
1643 struct iommu_domain *dom;
1645 lockdep_assert_held(&group->mutex);
1648 return __iommu_group_alloc_default_domain(bus, group, req_type);
1650 /* The driver gave no guidance on what type to use, try the default */
1651 dom = __iommu_group_alloc_default_domain(bus, group, iommu_def_domain_type);
1655 /* Otherwise IDENTITY and DMA_FQ defaults will try DMA */
1656 if (iommu_def_domain_type == IOMMU_DOMAIN_DMA)
1658 dom = __iommu_group_alloc_default_domain(bus, group, IOMMU_DOMAIN_DMA);
1662 pr_warn("Failed to allocate default IOMMU domain of type %u for group %s - Falling back to IOMMU_DOMAIN_DMA",
1663 iommu_def_domain_type, group->name);
1668 * iommu_group_get_for_dev - Find or create the IOMMU group for a device
1669 * @dev: target device
1671 * This function is intended to be called by IOMMU drivers and extended to
1672 * support common, bus-defined algorithms when determining or creating the
1673 * IOMMU group for a device. On success, the caller will hold a reference
1674 * to the returned IOMMU group, which will already include the provided
1675 * device. The reference should be released with iommu_group_put().
1677 static struct iommu_group *iommu_group_get_for_dev(struct device *dev)
1679 const struct iommu_ops *ops = dev_iommu_ops(dev);
1680 struct iommu_group *group;
1683 group = iommu_group_get(dev);
1687 group = ops->device_group(dev);
1688 if (WARN_ON_ONCE(group == NULL))
1689 return ERR_PTR(-EINVAL);
1694 ret = iommu_group_add_device(group, dev);
1701 iommu_group_put(group);
1703 return ERR_PTR(ret);
1706 struct iommu_domain *iommu_group_default_domain(struct iommu_group *group)
1708 return group->default_domain;
1711 static int probe_iommu_group(struct device *dev, void *data)
1713 struct list_head *group_list = data;
1714 struct iommu_group *group;
1717 /* Device is probed already if in a group */
1718 group = iommu_group_get(dev);
1720 iommu_group_put(group);
1724 ret = __iommu_probe_device(dev, group_list);
1731 static int iommu_bus_notifier(struct notifier_block *nb,
1732 unsigned long action, void *data)
1734 struct device *dev = data;
1736 if (action == BUS_NOTIFY_ADD_DEVICE) {
1739 ret = iommu_probe_device(dev);
1740 return (ret) ? NOTIFY_DONE : NOTIFY_OK;
1741 } else if (action == BUS_NOTIFY_REMOVED_DEVICE) {
1742 iommu_release_device(dev);
1749 /* A target_type of 0 will select the best domain type and cannot fail */
1750 static int iommu_get_default_domain_type(struct iommu_group *group,
1753 int best_type = target_type;
1754 struct group_device *gdev;
1755 struct device *last_dev;
1757 lockdep_assert_held(&group->mutex);
1759 for_each_group_device(group, gdev) {
1760 unsigned int type = iommu_get_def_domain_type(gdev->dev);
1762 if (best_type && type && best_type != type) {
1764 dev_err_ratelimited(
1766 "Device cannot be in %s domain\n",
1767 iommu_domain_type_str(target_type));
1773 "Device needs domain type %s, but device %s in the same iommu group requires type %s - using default\n",
1774 iommu_domain_type_str(type), dev_name(last_dev),
1775 iommu_domain_type_str(best_type));
1780 last_dev = gdev->dev;
1785 static void iommu_group_do_probe_finalize(struct device *dev)
1787 const struct iommu_ops *ops = dev_iommu_ops(dev);
1789 if (ops->probe_finalize)
1790 ops->probe_finalize(dev);
1793 int bus_iommu_probe(const struct bus_type *bus)
1795 struct iommu_group *group, *next;
1796 LIST_HEAD(group_list);
1800 * This code-path does not allocate the default domain when
1801 * creating the iommu group, so do it after the groups are
1804 ret = bus_for_each_dev(bus, NULL, &group_list, probe_iommu_group);
1808 list_for_each_entry_safe(group, next, &group_list, entry) {
1809 struct group_device *gdev;
1811 mutex_lock(&group->mutex);
1813 /* Remove item from the list */
1814 list_del_init(&group->entry);
1816 ret = iommu_setup_default_domain(group, 0);
1818 mutex_unlock(&group->mutex);
1821 mutex_unlock(&group->mutex);
1824 * FIXME: Mis-locked because the ops->probe_finalize() call-back
1825 * of some IOMMU drivers calls arm_iommu_attach_device() which
1826 * in-turn might call back into IOMMU core code, where it tries
1827 * to take group->mutex, resulting in a deadlock.
1829 for_each_group_device(group, gdev)
1830 iommu_group_do_probe_finalize(gdev->dev);
1836 bool iommu_present(const struct bus_type *bus)
1838 return bus->iommu_ops != NULL;
1840 EXPORT_SYMBOL_GPL(iommu_present);
1843 * device_iommu_capable() - check for a general IOMMU capability
1844 * @dev: device to which the capability would be relevant, if available
1845 * @cap: IOMMU capability
1847 * Return: true if an IOMMU is present and supports the given capability
1848 * for the given device, otherwise false.
1850 bool device_iommu_capable(struct device *dev, enum iommu_cap cap)
1852 const struct iommu_ops *ops;
1854 if (!dev->iommu || !dev->iommu->iommu_dev)
1857 ops = dev_iommu_ops(dev);
1861 return ops->capable(dev, cap);
1863 EXPORT_SYMBOL_GPL(device_iommu_capable);
1866 * iommu_group_has_isolated_msi() - Compute msi_device_has_isolated_msi()
1868 * @group: Group to query
1870 * IOMMU groups should not have differing values of
1871 * msi_device_has_isolated_msi() for devices in a group. However nothing
1872 * directly prevents this, so ensure mistakes don't result in isolation failures
1873 * by checking that all the devices are the same.
1875 bool iommu_group_has_isolated_msi(struct iommu_group *group)
1877 struct group_device *group_dev;
1880 mutex_lock(&group->mutex);
1881 for_each_group_device(group, group_dev)
1882 ret &= msi_device_has_isolated_msi(group_dev->dev);
1883 mutex_unlock(&group->mutex);
1886 EXPORT_SYMBOL_GPL(iommu_group_has_isolated_msi);
1889 * iommu_set_fault_handler() - set a fault handler for an iommu domain
1890 * @domain: iommu domain
1891 * @handler: fault handler
1892 * @token: user data, will be passed back to the fault handler
1894 * This function should be used by IOMMU users which want to be notified
1895 * whenever an IOMMU fault happens.
1897 * The fault handler itself should return 0 on success, and an appropriate
1898 * error code otherwise.
1900 void iommu_set_fault_handler(struct iommu_domain *domain,
1901 iommu_fault_handler_t handler,
1906 domain->handler = handler;
1907 domain->handler_token = token;
1909 EXPORT_SYMBOL_GPL(iommu_set_fault_handler);
1911 static struct iommu_domain *__iommu_domain_alloc(const struct bus_type *bus,
1914 struct iommu_domain *domain;
1915 unsigned int alloc_type = type & IOMMU_DOMAIN_ALLOC_FLAGS;
1917 if (bus == NULL || bus->iommu_ops == NULL)
1920 domain = bus->iommu_ops->domain_alloc(alloc_type);
1924 domain->type = type;
1926 * If not already set, assume all sizes by default; the driver
1927 * may override this later
1929 if (!domain->pgsize_bitmap)
1930 domain->pgsize_bitmap = bus->iommu_ops->pgsize_bitmap;
1933 domain->ops = bus->iommu_ops->default_domain_ops;
1935 if (iommu_is_dma_domain(domain) && iommu_get_dma_cookie(domain)) {
1936 iommu_domain_free(domain);
1942 struct iommu_domain *iommu_domain_alloc(const struct bus_type *bus)
1944 return __iommu_domain_alloc(bus, IOMMU_DOMAIN_UNMANAGED);
1946 EXPORT_SYMBOL_GPL(iommu_domain_alloc);
1948 void iommu_domain_free(struct iommu_domain *domain)
1950 if (domain->type == IOMMU_DOMAIN_SVA)
1952 iommu_put_dma_cookie(domain);
1953 domain->ops->free(domain);
1955 EXPORT_SYMBOL_GPL(iommu_domain_free);
1958 * Put the group's domain back to the appropriate core-owned domain - either the
1959 * standard kernel-mode DMA configuration or an all-DMA-blocked domain.
1961 static void __iommu_group_set_core_domain(struct iommu_group *group)
1963 struct iommu_domain *new_domain;
1966 new_domain = group->blocking_domain;
1968 new_domain = group->default_domain;
1970 __iommu_group_set_domain_nofail(group, new_domain);
1973 static int __iommu_attach_device(struct iommu_domain *domain,
1978 if (unlikely(domain->ops->attach_dev == NULL))
1981 ret = domain->ops->attach_dev(domain, dev);
1984 dev->iommu->attach_deferred = 0;
1985 trace_attach_device_to_domain(dev);
1990 * iommu_attach_device - Attach an IOMMU domain to a device
1991 * @domain: IOMMU domain to attach
1992 * @dev: Device that will be attached
1994 * Returns 0 on success and error code on failure
1996 * Note that EINVAL can be treated as a soft failure, indicating
1997 * that certain configuration of the domain is incompatible with
1998 * the device. In this case attaching a different domain to the
1999 * device may succeed.
2001 int iommu_attach_device(struct iommu_domain *domain, struct device *dev)
2003 struct iommu_group *group;
2006 group = iommu_group_get(dev);
2011 * Lock the group to make sure the device-count doesn't
2012 * change while we are attaching
2014 mutex_lock(&group->mutex);
2016 if (list_count_nodes(&group->devices) != 1)
2019 ret = __iommu_attach_group(domain, group);
2022 mutex_unlock(&group->mutex);
2023 iommu_group_put(group);
2027 EXPORT_SYMBOL_GPL(iommu_attach_device);
2029 int iommu_deferred_attach(struct device *dev, struct iommu_domain *domain)
2031 if (dev->iommu && dev->iommu->attach_deferred)
2032 return __iommu_attach_device(domain, dev);
2037 void iommu_detach_device(struct iommu_domain *domain, struct device *dev)
2039 struct iommu_group *group;
2041 group = iommu_group_get(dev);
2045 mutex_lock(&group->mutex);
2046 if (WARN_ON(domain != group->domain) ||
2047 WARN_ON(list_count_nodes(&group->devices) != 1))
2049 __iommu_group_set_core_domain(group);
2052 mutex_unlock(&group->mutex);
2053 iommu_group_put(group);
2055 EXPORT_SYMBOL_GPL(iommu_detach_device);
2057 struct iommu_domain *iommu_get_domain_for_dev(struct device *dev)
2059 struct iommu_domain *domain;
2060 struct iommu_group *group;
2062 group = iommu_group_get(dev);
2066 domain = group->domain;
2068 iommu_group_put(group);
2072 EXPORT_SYMBOL_GPL(iommu_get_domain_for_dev);
2075 * For IOMMU_DOMAIN_DMA implementations which already provide their own
2076 * guarantees that the group and its default domain are valid and correct.
2078 struct iommu_domain *iommu_get_dma_domain(struct device *dev)
2080 return dev->iommu_group->default_domain;
2083 static int __iommu_attach_group(struct iommu_domain *domain,
2084 struct iommu_group *group)
2086 if (group->domain && group->domain != group->default_domain &&
2087 group->domain != group->blocking_domain)
2090 return __iommu_group_set_domain(group, domain);
2094 * iommu_attach_group - Attach an IOMMU domain to an IOMMU group
2095 * @domain: IOMMU domain to attach
2096 * @group: IOMMU group that will be attached
2098 * Returns 0 on success and error code on failure
2100 * Note that EINVAL can be treated as a soft failure, indicating
2101 * that certain configuration of the domain is incompatible with
2102 * the group. In this case attaching a different domain to the
2103 * group may succeed.
2105 int iommu_attach_group(struct iommu_domain *domain, struct iommu_group *group)
2109 mutex_lock(&group->mutex);
2110 ret = __iommu_attach_group(domain, group);
2111 mutex_unlock(&group->mutex);
2115 EXPORT_SYMBOL_GPL(iommu_attach_group);
2117 static int __iommu_device_set_domain(struct iommu_group *group,
2119 struct iommu_domain *new_domain,
2124 if (dev->iommu->attach_deferred) {
2125 if (new_domain == group->default_domain)
2127 dev->iommu->attach_deferred = 0;
2130 ret = __iommu_attach_device(new_domain, dev);
2133 * If we have a blocking domain then try to attach that in hopes
2134 * of avoiding a UAF. Modern drivers should implement blocking
2135 * domains as global statics that cannot fail.
2137 if ((flags & IOMMU_SET_DOMAIN_MUST_SUCCEED) &&
2138 group->blocking_domain &&
2139 group->blocking_domain != new_domain)
2140 __iommu_attach_device(group->blocking_domain, dev);
2147 * If 0 is returned the group's domain is new_domain. If an error is returned
2148 * then the group's domain will be set back to the existing domain unless
2149 * IOMMU_SET_DOMAIN_MUST_SUCCEED, otherwise an error is returned and the group's
2150 * domains is left inconsistent. This is a driver bug to fail attach with a
2151 * previously good domain. We try to avoid a kernel UAF because of this.
2153 * IOMMU groups are really the natural working unit of the IOMMU, but the IOMMU
2154 * API works on domains and devices. Bridge that gap by iterating over the
2155 * devices in a group. Ideally we'd have a single device which represents the
2156 * requestor ID of the group, but we also allow IOMMU drivers to create policy
2157 * defined minimum sets, where the physical hardware may be able to distiguish
2158 * members, but we wish to group them at a higher level (ex. untrusted
2159 * multi-function PCI devices). Thus we attach each device.
2161 static int __iommu_group_set_domain_internal(struct iommu_group *group,
2162 struct iommu_domain *new_domain,
2165 struct group_device *last_gdev;
2166 struct group_device *gdev;
2170 lockdep_assert_held(&group->mutex);
2172 if (group->domain == new_domain)
2176 * New drivers should support default domains, so set_platform_dma()
2177 * op will never be called. Otherwise the NULL domain represents some
2178 * platform specific behavior.
2181 for_each_group_device(group, gdev) {
2182 const struct iommu_ops *ops = dev_iommu_ops(gdev->dev);
2184 if (!WARN_ON(!ops->set_platform_dma_ops))
2185 ops->set_platform_dma_ops(gdev->dev);
2187 group->domain = NULL;
2192 * Changing the domain is done by calling attach_dev() on the new
2193 * domain. This switch does not have to be atomic and DMA can be
2194 * discarded during the transition. DMA must only be able to access
2195 * either new_domain or group->domain, never something else.
2198 for_each_group_device(group, gdev) {
2199 ret = __iommu_device_set_domain(group, gdev->dev, new_domain,
2204 * Keep trying the other devices in the group. If a
2205 * driver fails attach to an otherwise good domain, and
2206 * does not support blocking domains, it should at least
2207 * drop its reference on the current domain so we don't
2210 if (flags & IOMMU_SET_DOMAIN_MUST_SUCCEED)
2215 group->domain = new_domain;
2220 * This is called in error unwind paths. A well behaved driver should
2221 * always allow us to attach to a domain that was already attached.
2224 for_each_group_device(group, gdev) {
2225 const struct iommu_ops *ops = dev_iommu_ops(gdev->dev);
2228 * If set_platform_dma_ops is not present a NULL domain can
2229 * happen only for first probe, in which case we leave
2230 * group->domain as NULL and let release clean everything up.
2233 WARN_ON(__iommu_device_set_domain(
2234 group, gdev->dev, group->domain,
2235 IOMMU_SET_DOMAIN_MUST_SUCCEED));
2236 else if (ops->set_platform_dma_ops)
2237 ops->set_platform_dma_ops(gdev->dev);
2238 if (gdev == last_gdev)
2244 void iommu_detach_group(struct iommu_domain *domain, struct iommu_group *group)
2246 mutex_lock(&group->mutex);
2247 __iommu_group_set_core_domain(group);
2248 mutex_unlock(&group->mutex);
2250 EXPORT_SYMBOL_GPL(iommu_detach_group);
2252 phys_addr_t iommu_iova_to_phys(struct iommu_domain *domain, dma_addr_t iova)
2254 if (domain->type == IOMMU_DOMAIN_IDENTITY)
2257 if (domain->type == IOMMU_DOMAIN_BLOCKED)
2260 return domain->ops->iova_to_phys(domain, iova);
2262 EXPORT_SYMBOL_GPL(iommu_iova_to_phys);
2264 static size_t iommu_pgsize(struct iommu_domain *domain, unsigned long iova,
2265 phys_addr_t paddr, size_t size, size_t *count)
2267 unsigned int pgsize_idx, pgsize_idx_next;
2268 unsigned long pgsizes;
2269 size_t offset, pgsize, pgsize_next;
2270 unsigned long addr_merge = paddr | iova;
2272 /* Page sizes supported by the hardware and small enough for @size */
2273 pgsizes = domain->pgsize_bitmap & GENMASK(__fls(size), 0);
2275 /* Constrain the page sizes further based on the maximum alignment */
2276 if (likely(addr_merge))
2277 pgsizes &= GENMASK(__ffs(addr_merge), 0);
2279 /* Make sure we have at least one suitable page size */
2282 /* Pick the biggest page size remaining */
2283 pgsize_idx = __fls(pgsizes);
2284 pgsize = BIT(pgsize_idx);
2288 /* Find the next biggest support page size, if it exists */
2289 pgsizes = domain->pgsize_bitmap & ~GENMASK(pgsize_idx, 0);
2293 pgsize_idx_next = __ffs(pgsizes);
2294 pgsize_next = BIT(pgsize_idx_next);
2297 * There's no point trying a bigger page size unless the virtual
2298 * and physical addresses are similarly offset within the larger page.
2300 if ((iova ^ paddr) & (pgsize_next - 1))
2303 /* Calculate the offset to the next page size alignment boundary */
2304 offset = pgsize_next - (addr_merge & (pgsize_next - 1));
2307 * If size is big enough to accommodate the larger page, reduce
2308 * the number of smaller pages.
2310 if (offset + pgsize_next <= size)
2314 *count = size >> pgsize_idx;
2318 static int __iommu_map_pages(struct iommu_domain *domain, unsigned long iova,
2319 phys_addr_t paddr, size_t size, int prot,
2320 gfp_t gfp, size_t *mapped)
2322 const struct iommu_domain_ops *ops = domain->ops;
2323 size_t pgsize, count;
2326 pgsize = iommu_pgsize(domain, iova, paddr, size, &count);
2328 pr_debug("mapping: iova 0x%lx pa %pa pgsize 0x%zx count %zu\n",
2329 iova, &paddr, pgsize, count);
2331 if (ops->map_pages) {
2332 ret = ops->map_pages(domain, iova, paddr, pgsize, count, prot,
2335 ret = ops->map(domain, iova, paddr, pgsize, prot, gfp);
2336 *mapped = ret ? 0 : pgsize;
2342 static int __iommu_map(struct iommu_domain *domain, unsigned long iova,
2343 phys_addr_t paddr, size_t size, int prot, gfp_t gfp)
2345 const struct iommu_domain_ops *ops = domain->ops;
2346 unsigned long orig_iova = iova;
2347 unsigned int min_pagesz;
2348 size_t orig_size = size;
2349 phys_addr_t orig_paddr = paddr;
2352 if (unlikely(!(ops->map || ops->map_pages) ||
2353 domain->pgsize_bitmap == 0UL))
2356 if (unlikely(!(domain->type & __IOMMU_DOMAIN_PAGING)))
2359 /* find out the minimum page size supported */
2360 min_pagesz = 1 << __ffs(domain->pgsize_bitmap);
2363 * both the virtual address and the physical one, as well as
2364 * the size of the mapping, must be aligned (at least) to the
2365 * size of the smallest page supported by the hardware
2367 if (!IS_ALIGNED(iova | paddr | size, min_pagesz)) {
2368 pr_err("unaligned: iova 0x%lx pa %pa size 0x%zx min_pagesz 0x%x\n",
2369 iova, &paddr, size, min_pagesz);
2373 pr_debug("map: iova 0x%lx pa %pa size 0x%zx\n", iova, &paddr, size);
2378 ret = __iommu_map_pages(domain, iova, paddr, size, prot, gfp,
2381 * Some pages may have been mapped, even if an error occurred,
2382 * so we should account for those so they can be unmapped.
2393 /* unroll mapping in case something went wrong */
2395 iommu_unmap(domain, orig_iova, orig_size - size);
2397 trace_map(orig_iova, orig_paddr, orig_size);
2402 int iommu_map(struct iommu_domain *domain, unsigned long iova,
2403 phys_addr_t paddr, size_t size, int prot, gfp_t gfp)
2405 const struct iommu_domain_ops *ops = domain->ops;
2408 might_sleep_if(gfpflags_allow_blocking(gfp));
2410 /* Discourage passing strange GFP flags */
2411 if (WARN_ON_ONCE(gfp & (__GFP_COMP | __GFP_DMA | __GFP_DMA32 |
2415 ret = __iommu_map(domain, iova, paddr, size, prot, gfp);
2416 if (ret == 0 && ops->iotlb_sync_map)
2417 ops->iotlb_sync_map(domain, iova, size);
2421 EXPORT_SYMBOL_GPL(iommu_map);
2423 static size_t __iommu_unmap_pages(struct iommu_domain *domain,
2424 unsigned long iova, size_t size,
2425 struct iommu_iotlb_gather *iotlb_gather)
2427 const struct iommu_domain_ops *ops = domain->ops;
2428 size_t pgsize, count;
2430 pgsize = iommu_pgsize(domain, iova, iova, size, &count);
2431 return ops->unmap_pages ?
2432 ops->unmap_pages(domain, iova, pgsize, count, iotlb_gather) :
2433 ops->unmap(domain, iova, pgsize, iotlb_gather);
2436 static size_t __iommu_unmap(struct iommu_domain *domain,
2437 unsigned long iova, size_t size,
2438 struct iommu_iotlb_gather *iotlb_gather)
2440 const struct iommu_domain_ops *ops = domain->ops;
2441 size_t unmapped_page, unmapped = 0;
2442 unsigned long orig_iova = iova;
2443 unsigned int min_pagesz;
2445 if (unlikely(!(ops->unmap || ops->unmap_pages) ||
2446 domain->pgsize_bitmap == 0UL))
2449 if (unlikely(!(domain->type & __IOMMU_DOMAIN_PAGING)))
2452 /* find out the minimum page size supported */
2453 min_pagesz = 1 << __ffs(domain->pgsize_bitmap);
2456 * The virtual address, as well as the size of the mapping, must be
2457 * aligned (at least) to the size of the smallest page supported
2460 if (!IS_ALIGNED(iova | size, min_pagesz)) {
2461 pr_err("unaligned: iova 0x%lx size 0x%zx min_pagesz 0x%x\n",
2462 iova, size, min_pagesz);
2466 pr_debug("unmap this: iova 0x%lx size 0x%zx\n", iova, size);
2469 * Keep iterating until we either unmap 'size' bytes (or more)
2470 * or we hit an area that isn't mapped.
2472 while (unmapped < size) {
2473 unmapped_page = __iommu_unmap_pages(domain, iova,
2479 pr_debug("unmapped: iova 0x%lx size 0x%zx\n",
2480 iova, unmapped_page);
2482 iova += unmapped_page;
2483 unmapped += unmapped_page;
2486 trace_unmap(orig_iova, size, unmapped);
2490 size_t iommu_unmap(struct iommu_domain *domain,
2491 unsigned long iova, size_t size)
2493 struct iommu_iotlb_gather iotlb_gather;
2496 iommu_iotlb_gather_init(&iotlb_gather);
2497 ret = __iommu_unmap(domain, iova, size, &iotlb_gather);
2498 iommu_iotlb_sync(domain, &iotlb_gather);
2502 EXPORT_SYMBOL_GPL(iommu_unmap);
2504 size_t iommu_unmap_fast(struct iommu_domain *domain,
2505 unsigned long iova, size_t size,
2506 struct iommu_iotlb_gather *iotlb_gather)
2508 return __iommu_unmap(domain, iova, size, iotlb_gather);
2510 EXPORT_SYMBOL_GPL(iommu_unmap_fast);
2512 ssize_t iommu_map_sg(struct iommu_domain *domain, unsigned long iova,
2513 struct scatterlist *sg, unsigned int nents, int prot,
2516 const struct iommu_domain_ops *ops = domain->ops;
2517 size_t len = 0, mapped = 0;
2522 might_sleep_if(gfpflags_allow_blocking(gfp));
2524 /* Discourage passing strange GFP flags */
2525 if (WARN_ON_ONCE(gfp & (__GFP_COMP | __GFP_DMA | __GFP_DMA32 |
2529 while (i <= nents) {
2530 phys_addr_t s_phys = sg_phys(sg);
2532 if (len && s_phys != start + len) {
2533 ret = __iommu_map(domain, iova + mapped, start,
2543 if (sg_dma_is_bus_address(sg))
2558 if (ops->iotlb_sync_map)
2559 ops->iotlb_sync_map(domain, iova, mapped);
2563 /* undo mappings already done */
2564 iommu_unmap(domain, iova, mapped);
2568 EXPORT_SYMBOL_GPL(iommu_map_sg);
2571 * report_iommu_fault() - report about an IOMMU fault to the IOMMU framework
2572 * @domain: the iommu domain where the fault has happened
2573 * @dev: the device where the fault has happened
2574 * @iova: the faulting address
2575 * @flags: mmu fault flags (e.g. IOMMU_FAULT_READ/IOMMU_FAULT_WRITE/...)
2577 * This function should be called by the low-level IOMMU implementations
2578 * whenever IOMMU faults happen, to allow high-level users, that are
2579 * interested in such events, to know about them.
2581 * This event may be useful for several possible use cases:
2582 * - mere logging of the event
2583 * - dynamic TLB/PTE loading
2584 * - if restarting of the faulting device is required
2586 * Returns 0 on success and an appropriate error code otherwise (if dynamic
2587 * PTE/TLB loading will one day be supported, implementations will be able
2588 * to tell whether it succeeded or not according to this return value).
2590 * Specifically, -ENOSYS is returned if a fault handler isn't installed
2591 * (though fault handlers can also return -ENOSYS, in case they want to
2592 * elicit the default behavior of the IOMMU drivers).
2594 int report_iommu_fault(struct iommu_domain *domain, struct device *dev,
2595 unsigned long iova, int flags)
2600 * if upper layers showed interest and installed a fault handler,
2603 if (domain->handler)
2604 ret = domain->handler(domain, dev, iova, flags,
2605 domain->handler_token);
2607 trace_io_page_fault(dev, iova, flags);
2610 EXPORT_SYMBOL_GPL(report_iommu_fault);
2612 static int __init iommu_init(void)
2614 iommu_group_kset = kset_create_and_add("iommu_groups",
2616 BUG_ON(!iommu_group_kset);
2618 iommu_debugfs_setup();
2622 core_initcall(iommu_init);
2624 int iommu_enable_nesting(struct iommu_domain *domain)
2626 if (domain->type != IOMMU_DOMAIN_UNMANAGED)
2628 if (!domain->ops->enable_nesting)
2630 return domain->ops->enable_nesting(domain);
2632 EXPORT_SYMBOL_GPL(iommu_enable_nesting);
2634 int iommu_set_pgtable_quirks(struct iommu_domain *domain,
2635 unsigned long quirk)
2637 if (domain->type != IOMMU_DOMAIN_UNMANAGED)
2639 if (!domain->ops->set_pgtable_quirks)
2641 return domain->ops->set_pgtable_quirks(domain, quirk);
2643 EXPORT_SYMBOL_GPL(iommu_set_pgtable_quirks);
2645 void iommu_get_resv_regions(struct device *dev, struct list_head *list)
2647 const struct iommu_ops *ops = dev_iommu_ops(dev);
2649 if (ops->get_resv_regions)
2650 ops->get_resv_regions(dev, list);
2654 * iommu_put_resv_regions - release resered regions
2655 * @dev: device for which to free reserved regions
2656 * @list: reserved region list for device
2658 * This releases a reserved region list acquired by iommu_get_resv_regions().
2660 void iommu_put_resv_regions(struct device *dev, struct list_head *list)
2662 struct iommu_resv_region *entry, *next;
2664 list_for_each_entry_safe(entry, next, list, list) {
2666 entry->free(dev, entry);
2671 EXPORT_SYMBOL(iommu_put_resv_regions);
2673 struct iommu_resv_region *iommu_alloc_resv_region(phys_addr_t start,
2674 size_t length, int prot,
2675 enum iommu_resv_type type,
2678 struct iommu_resv_region *region;
2680 region = kzalloc(sizeof(*region), gfp);
2684 INIT_LIST_HEAD(®ion->list);
2685 region->start = start;
2686 region->length = length;
2687 region->prot = prot;
2688 region->type = type;
2691 EXPORT_SYMBOL_GPL(iommu_alloc_resv_region);
2693 void iommu_set_default_passthrough(bool cmd_line)
2696 iommu_cmd_line |= IOMMU_CMD_LINE_DMA_API;
2697 iommu_def_domain_type = IOMMU_DOMAIN_IDENTITY;
2700 void iommu_set_default_translated(bool cmd_line)
2703 iommu_cmd_line |= IOMMU_CMD_LINE_DMA_API;
2704 iommu_def_domain_type = IOMMU_DOMAIN_DMA;
2707 bool iommu_default_passthrough(void)
2709 return iommu_def_domain_type == IOMMU_DOMAIN_IDENTITY;
2711 EXPORT_SYMBOL_GPL(iommu_default_passthrough);
2713 const struct iommu_ops *iommu_ops_from_fwnode(struct fwnode_handle *fwnode)
2715 const struct iommu_ops *ops = NULL;
2716 struct iommu_device *iommu;
2718 spin_lock(&iommu_device_lock);
2719 list_for_each_entry(iommu, &iommu_device_list, list)
2720 if (iommu->fwnode == fwnode) {
2724 spin_unlock(&iommu_device_lock);
2728 int iommu_fwspec_init(struct device *dev, struct fwnode_handle *iommu_fwnode,
2729 const struct iommu_ops *ops)
2731 struct iommu_fwspec *fwspec = dev_iommu_fwspec_get(dev);
2734 return ops == fwspec->ops ? 0 : -EINVAL;
2736 if (!dev_iommu_get(dev))
2739 /* Preallocate for the overwhelmingly common case of 1 ID */
2740 fwspec = kzalloc(struct_size(fwspec, ids, 1), GFP_KERNEL);
2744 of_node_get(to_of_node(iommu_fwnode));
2745 fwspec->iommu_fwnode = iommu_fwnode;
2747 dev_iommu_fwspec_set(dev, fwspec);
2750 EXPORT_SYMBOL_GPL(iommu_fwspec_init);
2752 void iommu_fwspec_free(struct device *dev)
2754 struct iommu_fwspec *fwspec = dev_iommu_fwspec_get(dev);
2757 fwnode_handle_put(fwspec->iommu_fwnode);
2759 dev_iommu_fwspec_set(dev, NULL);
2762 EXPORT_SYMBOL_GPL(iommu_fwspec_free);
2764 int iommu_fwspec_add_ids(struct device *dev, u32 *ids, int num_ids)
2766 struct iommu_fwspec *fwspec = dev_iommu_fwspec_get(dev);
2772 new_num = fwspec->num_ids + num_ids;
2774 fwspec = krealloc(fwspec, struct_size(fwspec, ids, new_num),
2779 dev_iommu_fwspec_set(dev, fwspec);
2782 for (i = 0; i < num_ids; i++)
2783 fwspec->ids[fwspec->num_ids + i] = ids[i];
2785 fwspec->num_ids = new_num;
2788 EXPORT_SYMBOL_GPL(iommu_fwspec_add_ids);
2791 * Per device IOMMU features.
2793 int iommu_dev_enable_feature(struct device *dev, enum iommu_dev_features feat)
2795 if (dev->iommu && dev->iommu->iommu_dev) {
2796 const struct iommu_ops *ops = dev->iommu->iommu_dev->ops;
2798 if (ops->dev_enable_feat)
2799 return ops->dev_enable_feat(dev, feat);
2804 EXPORT_SYMBOL_GPL(iommu_dev_enable_feature);
2807 * The device drivers should do the necessary cleanups before calling this.
2809 int iommu_dev_disable_feature(struct device *dev, enum iommu_dev_features feat)
2811 if (dev->iommu && dev->iommu->iommu_dev) {
2812 const struct iommu_ops *ops = dev->iommu->iommu_dev->ops;
2814 if (ops->dev_disable_feat)
2815 return ops->dev_disable_feat(dev, feat);
2820 EXPORT_SYMBOL_GPL(iommu_dev_disable_feature);
2823 * iommu_setup_default_domain - Set the default_domain for the group
2824 * @group: Group to change
2825 * @target_type: Domain type to set as the default_domain
2827 * Allocate a default domain and set it as the current domain on the group. If
2828 * the group already has a default domain it will be changed to the target_type.
2829 * When target_type is 0 the default domain is selected based on driver and
2830 * system preferences.
2832 static int iommu_setup_default_domain(struct iommu_group *group,
2835 struct iommu_domain *old_dom = group->default_domain;
2836 struct group_device *gdev;
2837 struct iommu_domain *dom;
2842 lockdep_assert_held(&group->mutex);
2844 req_type = iommu_get_default_domain_type(group, target_type);
2849 * There are still some drivers which don't support default domains, so
2850 * we ignore the failure and leave group->default_domain NULL.
2852 * We assume that the iommu driver starts up the device in
2853 * 'set_platform_dma_ops' mode if it does not support default domains.
2855 dom = iommu_group_alloc_default_domain(group, req_type);
2857 /* Once in default_domain mode we never leave */
2858 if (group->default_domain)
2860 group->default_domain = NULL;
2864 if (group->default_domain == dom)
2868 * IOMMU_RESV_DIRECT and IOMMU_RESV_DIRECT_RELAXABLE regions must be
2869 * mapped before their device is attached, in order to guarantee
2870 * continuity with any FW activity
2872 direct_failed = false;
2873 for_each_group_device(group, gdev) {
2874 if (iommu_create_device_direct_mappings(dom, gdev->dev)) {
2875 direct_failed = true;
2877 gdev->dev->iommu->iommu_dev->dev,
2878 "IOMMU driver was not able to establish FW requested direct mapping.");
2882 /* We must set default_domain early for __iommu_device_set_domain */
2883 group->default_domain = dom;
2884 if (!group->domain) {
2886 * Drivers are not allowed to fail the first domain attach.
2887 * The only way to recover from this is to fail attaching the
2888 * iommu driver and call ops->release_device. Put the domain
2889 * in group->default_domain so it is freed after.
2891 ret = __iommu_group_set_domain_internal(
2892 group, dom, IOMMU_SET_DOMAIN_MUST_SUCCEED);
2896 ret = __iommu_group_set_domain(group, dom);
2898 goto err_restore_def_domain;
2902 * Drivers are supposed to allow mappings to be installed in a domain
2903 * before device attachment, but some don't. Hack around this defect by
2904 * trying again after attaching. If this happens it means the device
2905 * will not continuously have the IOMMU_RESV_DIRECT map.
2907 if (direct_failed) {
2908 for_each_group_device(group, gdev) {
2909 ret = iommu_create_device_direct_mappings(dom, gdev->dev);
2911 goto err_restore_domain;
2917 iommu_domain_free(old_dom);
2922 __iommu_group_set_domain_internal(
2923 group, old_dom, IOMMU_SET_DOMAIN_MUST_SUCCEED);
2924 err_restore_def_domain:
2926 iommu_domain_free(dom);
2927 group->default_domain = old_dom;
2933 * Changing the default domain through sysfs requires the users to unbind the
2934 * drivers from the devices in the iommu group, except for a DMA -> DMA-FQ
2935 * transition. Return failure if this isn't met.
2937 * We need to consider the race between this and the device release path.
2938 * group->mutex is used here to guarantee that the device release path
2939 * will not be entered at the same time.
2941 static ssize_t iommu_group_store_type(struct iommu_group *group,
2942 const char *buf, size_t count)
2944 struct group_device *gdev;
2947 if (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO))
2950 if (WARN_ON(!group) || !group->default_domain)
2953 if (sysfs_streq(buf, "identity"))
2954 req_type = IOMMU_DOMAIN_IDENTITY;
2955 else if (sysfs_streq(buf, "DMA"))
2956 req_type = IOMMU_DOMAIN_DMA;
2957 else if (sysfs_streq(buf, "DMA-FQ"))
2958 req_type = IOMMU_DOMAIN_DMA_FQ;
2959 else if (sysfs_streq(buf, "auto"))
2964 mutex_lock(&group->mutex);
2965 /* We can bring up a flush queue without tearing down the domain. */
2966 if (req_type == IOMMU_DOMAIN_DMA_FQ &&
2967 group->default_domain->type == IOMMU_DOMAIN_DMA) {
2968 ret = iommu_dma_init_fq(group->default_domain);
2972 group->default_domain->type = IOMMU_DOMAIN_DMA_FQ;
2977 /* Otherwise, ensure that device exists and no driver is bound. */
2978 if (list_empty(&group->devices) || group->owner_cnt) {
2983 ret = iommu_setup_default_domain(group, req_type);
2988 * Release the mutex here because ops->probe_finalize() call-back of
2989 * some vendor IOMMU drivers calls arm_iommu_attach_device() which
2990 * in-turn might call back into IOMMU core code, where it tries to take
2991 * group->mutex, resulting in a deadlock.
2993 mutex_unlock(&group->mutex);
2995 /* Make sure dma_ops is appropriatley set */
2996 for_each_group_device(group, gdev)
2997 iommu_group_do_probe_finalize(gdev->dev);
3001 mutex_unlock(&group->mutex);
3002 return ret ?: count;
3005 static bool iommu_is_default_domain(struct iommu_group *group)
3007 if (group->domain == group->default_domain)
3011 * If the default domain was set to identity and it is still an identity
3012 * domain then we consider this a pass. This happens because of
3013 * amd_iommu_init_device() replacing the default idenytity domain with an
3014 * identity domain that has a different configuration for AMDGPU.
3016 if (group->default_domain &&
3017 group->default_domain->type == IOMMU_DOMAIN_IDENTITY &&
3018 group->domain && group->domain->type == IOMMU_DOMAIN_IDENTITY)
3024 * iommu_device_use_default_domain() - Device driver wants to handle device
3025 * DMA through the kernel DMA API.
3028 * The device driver about to bind @dev wants to do DMA through the kernel
3029 * DMA API. Return 0 if it is allowed, otherwise an error.
3031 int iommu_device_use_default_domain(struct device *dev)
3033 struct iommu_group *group = iommu_group_get(dev);
3039 mutex_lock(&group->mutex);
3040 if (group->owner_cnt) {
3041 if (group->owner || !iommu_is_default_domain(group) ||
3042 !xa_empty(&group->pasid_array)) {
3051 mutex_unlock(&group->mutex);
3052 iommu_group_put(group);
3058 * iommu_device_unuse_default_domain() - Device driver stops handling device
3059 * DMA through the kernel DMA API.
3062 * The device driver doesn't want to do DMA through kernel DMA API anymore.
3063 * It must be called after iommu_device_use_default_domain().
3065 void iommu_device_unuse_default_domain(struct device *dev)
3067 struct iommu_group *group = iommu_group_get(dev);
3072 mutex_lock(&group->mutex);
3073 if (!WARN_ON(!group->owner_cnt || !xa_empty(&group->pasid_array)))
3076 mutex_unlock(&group->mutex);
3077 iommu_group_put(group);
3080 static int __iommu_group_alloc_blocking_domain(struct iommu_group *group)
3082 struct group_device *dev =
3083 list_first_entry(&group->devices, struct group_device, list);
3085 if (group->blocking_domain)
3088 group->blocking_domain =
3089 __iommu_domain_alloc(dev->dev->bus, IOMMU_DOMAIN_BLOCKED);
3090 if (!group->blocking_domain) {
3092 * For drivers that do not yet understand IOMMU_DOMAIN_BLOCKED
3093 * create an empty domain instead.
3095 group->blocking_domain = __iommu_domain_alloc(
3096 dev->dev->bus, IOMMU_DOMAIN_UNMANAGED);
3097 if (!group->blocking_domain)
3103 static int __iommu_take_dma_ownership(struct iommu_group *group, void *owner)
3107 if ((group->domain && group->domain != group->default_domain) ||
3108 !xa_empty(&group->pasid_array))
3111 ret = __iommu_group_alloc_blocking_domain(group);
3114 ret = __iommu_group_set_domain(group, group->blocking_domain);
3118 group->owner = owner;
3124 * iommu_group_claim_dma_owner() - Set DMA ownership of a group
3125 * @group: The group.
3126 * @owner: Caller specified pointer. Used for exclusive ownership.
3128 * This is to support backward compatibility for vfio which manages the dma
3129 * ownership in iommu_group level. New invocations on this interface should be
3130 * prohibited. Only a single owner may exist for a group.
3132 int iommu_group_claim_dma_owner(struct iommu_group *group, void *owner)
3136 if (WARN_ON(!owner))
3139 mutex_lock(&group->mutex);
3140 if (group->owner_cnt) {
3145 ret = __iommu_take_dma_ownership(group, owner);
3147 mutex_unlock(&group->mutex);
3151 EXPORT_SYMBOL_GPL(iommu_group_claim_dma_owner);
3154 * iommu_device_claim_dma_owner() - Set DMA ownership of a device
3156 * @owner: Caller specified pointer. Used for exclusive ownership.
3158 * Claim the DMA ownership of a device. Multiple devices in the same group may
3159 * concurrently claim ownership if they present the same owner value. Returns 0
3160 * on success and error code on failure
3162 int iommu_device_claim_dma_owner(struct device *dev, void *owner)
3164 struct iommu_group *group;
3167 if (WARN_ON(!owner))
3170 group = iommu_group_get(dev);
3174 mutex_lock(&group->mutex);
3175 if (group->owner_cnt) {
3176 if (group->owner != owner) {
3184 ret = __iommu_take_dma_ownership(group, owner);
3186 mutex_unlock(&group->mutex);
3187 iommu_group_put(group);
3191 EXPORT_SYMBOL_GPL(iommu_device_claim_dma_owner);
3193 static void __iommu_release_dma_ownership(struct iommu_group *group)
3195 if (WARN_ON(!group->owner_cnt || !group->owner ||
3196 !xa_empty(&group->pasid_array)))
3199 group->owner_cnt = 0;
3200 group->owner = NULL;
3201 __iommu_group_set_domain_nofail(group, group->default_domain);
3205 * iommu_group_release_dma_owner() - Release DMA ownership of a group
3208 * Release the DMA ownership claimed by iommu_group_claim_dma_owner().
3210 void iommu_group_release_dma_owner(struct iommu_group *group)
3212 mutex_lock(&group->mutex);
3213 __iommu_release_dma_ownership(group);
3214 mutex_unlock(&group->mutex);
3216 EXPORT_SYMBOL_GPL(iommu_group_release_dma_owner);
3219 * iommu_device_release_dma_owner() - Release DMA ownership of a device
3220 * @group: The device.
3222 * Release the DMA ownership claimed by iommu_device_claim_dma_owner().
3224 void iommu_device_release_dma_owner(struct device *dev)
3226 struct iommu_group *group = iommu_group_get(dev);
3228 mutex_lock(&group->mutex);
3229 if (group->owner_cnt > 1)
3232 __iommu_release_dma_ownership(group);
3233 mutex_unlock(&group->mutex);
3234 iommu_group_put(group);
3236 EXPORT_SYMBOL_GPL(iommu_device_release_dma_owner);
3239 * iommu_group_dma_owner_claimed() - Query group dma ownership status
3240 * @group: The group.
3242 * This provides status query on a given group. It is racy and only for
3243 * non-binding status reporting.
3245 bool iommu_group_dma_owner_claimed(struct iommu_group *group)
3249 mutex_lock(&group->mutex);
3250 user = group->owner_cnt;
3251 mutex_unlock(&group->mutex);
3255 EXPORT_SYMBOL_GPL(iommu_group_dma_owner_claimed);
3257 static int __iommu_set_group_pasid(struct iommu_domain *domain,
3258 struct iommu_group *group, ioasid_t pasid)
3260 struct group_device *device;
3263 for_each_group_device(group, device) {
3264 ret = domain->ops->set_dev_pasid(domain, device->dev, pasid);
3272 static void __iommu_remove_group_pasid(struct iommu_group *group,
3275 struct group_device *device;
3276 const struct iommu_ops *ops;
3278 for_each_group_device(group, device) {
3279 ops = dev_iommu_ops(device->dev);
3280 ops->remove_dev_pasid(device->dev, pasid);
3285 * iommu_attach_device_pasid() - Attach a domain to pasid of device
3286 * @domain: the iommu domain.
3287 * @dev: the attached device.
3288 * @pasid: the pasid of the device.
3290 * Return: 0 on success, or an error.
3292 int iommu_attach_device_pasid(struct iommu_domain *domain,
3293 struct device *dev, ioasid_t pasid)
3295 struct iommu_group *group;
3299 if (!domain->ops->set_dev_pasid)
3302 group = iommu_group_get(dev);
3306 mutex_lock(&group->mutex);
3307 curr = xa_cmpxchg(&group->pasid_array, pasid, NULL, domain, GFP_KERNEL);
3309 ret = xa_err(curr) ? : -EBUSY;
3313 ret = __iommu_set_group_pasid(domain, group, pasid);
3315 __iommu_remove_group_pasid(group, pasid);
3316 xa_erase(&group->pasid_array, pasid);
3319 mutex_unlock(&group->mutex);
3320 iommu_group_put(group);
3324 EXPORT_SYMBOL_GPL(iommu_attach_device_pasid);
3327 * iommu_detach_device_pasid() - Detach the domain from pasid of device
3328 * @domain: the iommu domain.
3329 * @dev: the attached device.
3330 * @pasid: the pasid of the device.
3332 * The @domain must have been attached to @pasid of the @dev with
3333 * iommu_attach_device_pasid().
3335 void iommu_detach_device_pasid(struct iommu_domain *domain, struct device *dev,
3338 struct iommu_group *group = iommu_group_get(dev);
3340 mutex_lock(&group->mutex);
3341 __iommu_remove_group_pasid(group, pasid);
3342 WARN_ON(xa_erase(&group->pasid_array, pasid) != domain);
3343 mutex_unlock(&group->mutex);
3345 iommu_group_put(group);
3347 EXPORT_SYMBOL_GPL(iommu_detach_device_pasid);
3350 * iommu_get_domain_for_dev_pasid() - Retrieve domain for @pasid of @dev
3351 * @dev: the queried device
3352 * @pasid: the pasid of the device
3353 * @type: matched domain type, 0 for any match
3355 * This is a variant of iommu_get_domain_for_dev(). It returns the existing
3356 * domain attached to pasid of a device. Callers must hold a lock around this
3357 * function, and both iommu_attach/detach_dev_pasid() whenever a domain of
3358 * type is being manipulated. This API does not internally resolve races with
3361 * Return: attached domain on success, NULL otherwise.
3363 struct iommu_domain *iommu_get_domain_for_dev_pasid(struct device *dev,
3367 struct iommu_domain *domain;
3368 struct iommu_group *group;
3370 group = iommu_group_get(dev);
3374 xa_lock(&group->pasid_array);
3375 domain = xa_load(&group->pasid_array, pasid);
3376 if (type && domain && domain->type != type)
3377 domain = ERR_PTR(-EBUSY);
3378 xa_unlock(&group->pasid_array);
3379 iommu_group_put(group);
3383 EXPORT_SYMBOL_GPL(iommu_get_domain_for_dev_pasid);
3385 struct iommu_domain *iommu_sva_domain_alloc(struct device *dev,
3386 struct mm_struct *mm)
3388 const struct iommu_ops *ops = dev_iommu_ops(dev);
3389 struct iommu_domain *domain;
3391 domain = ops->domain_alloc(IOMMU_DOMAIN_SVA);
3395 domain->type = IOMMU_DOMAIN_SVA;
3398 domain->iopf_handler = iommu_sva_handle_iopf;
3399 domain->fault_data = mm;