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/device.h>
10 #include <linux/kernel.h>
11 #include <linux/bug.h>
12 #include <linux/types.h>
13 #include <linux/init.h>
14 #include <linux/export.h>
15 #include <linux/slab.h>
16 #include <linux/errno.h>
17 #include <linux/iommu.h>
18 #include <linux/idr.h>
19 #include <linux/notifier.h>
20 #include <linux/err.h>
21 #include <linux/pci.h>
22 #include <linux/bitops.h>
23 #include <linux/property.h>
24 #include <linux/fsl/mc.h>
25 #include <trace/events/iommu.h>
27 static struct kset *iommu_group_kset;
28 static DEFINE_IDA(iommu_group_ida);
30 static unsigned int iommu_def_domain_type __read_mostly;
31 static bool iommu_dma_strict __read_mostly = true;
32 static u32 iommu_cmd_line __read_mostly;
36 struct kobject *devices_kobj;
37 struct list_head devices;
39 struct blocking_notifier_head notifier;
41 void (*iommu_data_release)(void *iommu_data);
44 struct iommu_domain *default_domain;
45 struct iommu_domain *domain;
49 struct list_head list;
54 struct iommu_group_attribute {
55 struct attribute attr;
56 ssize_t (*show)(struct iommu_group *group, char *buf);
57 ssize_t (*store)(struct iommu_group *group,
58 const char *buf, size_t count);
61 static const char * const iommu_group_resv_type_string[] = {
62 [IOMMU_RESV_DIRECT] = "direct",
63 [IOMMU_RESV_DIRECT_RELAXABLE] = "direct-relaxable",
64 [IOMMU_RESV_RESERVED] = "reserved",
65 [IOMMU_RESV_MSI] = "msi",
66 [IOMMU_RESV_SW_MSI] = "msi",
69 #define IOMMU_CMD_LINE_DMA_API BIT(0)
71 static void iommu_set_cmd_line_dma_api(void)
73 iommu_cmd_line |= IOMMU_CMD_LINE_DMA_API;
76 static bool iommu_cmd_line_dma_api(void)
78 return !!(iommu_cmd_line & IOMMU_CMD_LINE_DMA_API);
81 #define IOMMU_GROUP_ATTR(_name, _mode, _show, _store) \
82 struct iommu_group_attribute iommu_group_attr_##_name = \
83 __ATTR(_name, _mode, _show, _store)
85 #define to_iommu_group_attr(_attr) \
86 container_of(_attr, struct iommu_group_attribute, attr)
87 #define to_iommu_group(_kobj) \
88 container_of(_kobj, struct iommu_group, kobj)
90 static LIST_HEAD(iommu_device_list);
91 static DEFINE_SPINLOCK(iommu_device_lock);
94 * Use a function instead of an array here because the domain-type is a
95 * bit-field, so an array would waste memory.
97 static const char *iommu_domain_type_str(unsigned int t)
100 case IOMMU_DOMAIN_BLOCKED:
102 case IOMMU_DOMAIN_IDENTITY:
103 return "Passthrough";
104 case IOMMU_DOMAIN_UNMANAGED:
106 case IOMMU_DOMAIN_DMA:
113 static int __init iommu_subsys_init(void)
115 bool cmd_line = iommu_cmd_line_dma_api();
118 if (IS_ENABLED(CONFIG_IOMMU_DEFAULT_PASSTHROUGH))
119 iommu_set_default_passthrough(false);
121 iommu_set_default_translated(false);
123 if (iommu_default_passthrough() && mem_encrypt_active()) {
124 pr_info("Memory encryption detected - Disabling default IOMMU Passthrough\n");
125 iommu_set_default_translated(false);
129 pr_info("Default domain type: %s %s\n",
130 iommu_domain_type_str(iommu_def_domain_type),
131 cmd_line ? "(set via kernel command line)" : "");
135 subsys_initcall(iommu_subsys_init);
137 int iommu_device_register(struct iommu_device *iommu)
139 spin_lock(&iommu_device_lock);
140 list_add_tail(&iommu->list, &iommu_device_list);
141 spin_unlock(&iommu_device_lock);
145 void iommu_device_unregister(struct iommu_device *iommu)
147 spin_lock(&iommu_device_lock);
148 list_del(&iommu->list);
149 spin_unlock(&iommu_device_lock);
152 static struct iommu_param *iommu_get_dev_param(struct device *dev)
154 struct iommu_param *param = dev->iommu_param;
159 param = kzalloc(sizeof(*param), GFP_KERNEL);
163 mutex_init(¶m->lock);
164 dev->iommu_param = param;
168 static void iommu_free_dev_param(struct device *dev)
170 kfree(dev->iommu_param);
171 dev->iommu_param = NULL;
174 int iommu_probe_device(struct device *dev)
176 const struct iommu_ops *ops = dev->bus->iommu_ops;
179 WARN_ON(dev->iommu_group);
183 if (!iommu_get_dev_param(dev))
186 ret = ops->add_device(dev);
188 iommu_free_dev_param(dev);
193 void iommu_release_device(struct device *dev)
195 const struct iommu_ops *ops = dev->bus->iommu_ops;
197 if (dev->iommu_group)
198 ops->remove_device(dev);
200 iommu_free_dev_param(dev);
203 static struct iommu_domain *__iommu_domain_alloc(struct bus_type *bus,
205 static int __iommu_attach_device(struct iommu_domain *domain,
207 static int __iommu_attach_group(struct iommu_domain *domain,
208 struct iommu_group *group);
209 static void __iommu_detach_group(struct iommu_domain *domain,
210 struct iommu_group *group);
212 static int __init iommu_set_def_domain_type(char *str)
217 ret = kstrtobool(str, &pt);
222 iommu_set_default_passthrough(true);
224 iommu_set_default_translated(true);
228 early_param("iommu.passthrough", iommu_set_def_domain_type);
230 static int __init iommu_dma_setup(char *str)
232 return kstrtobool(str, &iommu_dma_strict);
234 early_param("iommu.strict", iommu_dma_setup);
236 static ssize_t iommu_group_attr_show(struct kobject *kobj,
237 struct attribute *__attr, char *buf)
239 struct iommu_group_attribute *attr = to_iommu_group_attr(__attr);
240 struct iommu_group *group = to_iommu_group(kobj);
244 ret = attr->show(group, buf);
248 static ssize_t iommu_group_attr_store(struct kobject *kobj,
249 struct attribute *__attr,
250 const char *buf, size_t count)
252 struct iommu_group_attribute *attr = to_iommu_group_attr(__attr);
253 struct iommu_group *group = to_iommu_group(kobj);
257 ret = attr->store(group, buf, count);
261 static const struct sysfs_ops iommu_group_sysfs_ops = {
262 .show = iommu_group_attr_show,
263 .store = iommu_group_attr_store,
266 static int iommu_group_create_file(struct iommu_group *group,
267 struct iommu_group_attribute *attr)
269 return sysfs_create_file(&group->kobj, &attr->attr);
272 static void iommu_group_remove_file(struct iommu_group *group,
273 struct iommu_group_attribute *attr)
275 sysfs_remove_file(&group->kobj, &attr->attr);
278 static ssize_t iommu_group_show_name(struct iommu_group *group, char *buf)
280 return sprintf(buf, "%s\n", group->name);
284 * iommu_insert_resv_region - Insert a new region in the
285 * list of reserved regions.
286 * @new: new region to insert
287 * @regions: list of regions
289 * Elements are sorted by start address and overlapping segments
290 * of the same type are merged.
292 int iommu_insert_resv_region(struct iommu_resv_region *new,
293 struct list_head *regions)
295 struct iommu_resv_region *iter, *tmp, *nr, *top;
298 nr = iommu_alloc_resv_region(new->start, new->length,
299 new->prot, new->type);
303 /* First add the new element based on start address sorting */
304 list_for_each_entry(iter, regions, list) {
305 if (nr->start < iter->start ||
306 (nr->start == iter->start && nr->type <= iter->type))
309 list_add_tail(&nr->list, &iter->list);
311 /* Merge overlapping segments of type nr->type in @regions, if any */
312 list_for_each_entry_safe(iter, tmp, regions, list) {
313 phys_addr_t top_end, iter_end = iter->start + iter->length - 1;
315 /* no merge needed on elements of different types than @new */
316 if (iter->type != new->type) {
317 list_move_tail(&iter->list, &stack);
321 /* look for the last stack element of same type as @iter */
322 list_for_each_entry_reverse(top, &stack, list)
323 if (top->type == iter->type)
326 list_move_tail(&iter->list, &stack);
330 top_end = top->start + top->length - 1;
332 if (iter->start > top_end + 1) {
333 list_move_tail(&iter->list, &stack);
335 top->length = max(top_end, iter_end) - top->start + 1;
336 list_del(&iter->list);
340 list_splice(&stack, regions);
345 iommu_insert_device_resv_regions(struct list_head *dev_resv_regions,
346 struct list_head *group_resv_regions)
348 struct iommu_resv_region *entry;
351 list_for_each_entry(entry, dev_resv_regions, list) {
352 ret = iommu_insert_resv_region(entry, group_resv_regions);
359 int iommu_get_group_resv_regions(struct iommu_group *group,
360 struct list_head *head)
362 struct group_device *device;
365 mutex_lock(&group->mutex);
366 list_for_each_entry(device, &group->devices, list) {
367 struct list_head dev_resv_regions;
369 INIT_LIST_HEAD(&dev_resv_regions);
370 iommu_get_resv_regions(device->dev, &dev_resv_regions);
371 ret = iommu_insert_device_resv_regions(&dev_resv_regions, head);
372 iommu_put_resv_regions(device->dev, &dev_resv_regions);
376 mutex_unlock(&group->mutex);
379 EXPORT_SYMBOL_GPL(iommu_get_group_resv_regions);
381 static ssize_t iommu_group_show_resv_regions(struct iommu_group *group,
384 struct iommu_resv_region *region, *next;
385 struct list_head group_resv_regions;
388 INIT_LIST_HEAD(&group_resv_regions);
389 iommu_get_group_resv_regions(group, &group_resv_regions);
391 list_for_each_entry_safe(region, next, &group_resv_regions, list) {
392 str += sprintf(str, "0x%016llx 0x%016llx %s\n",
393 (long long int)region->start,
394 (long long int)(region->start +
396 iommu_group_resv_type_string[region->type]);
403 static ssize_t iommu_group_show_type(struct iommu_group *group,
406 char *type = "unknown\n";
408 if (group->default_domain) {
409 switch (group->default_domain->type) {
410 case IOMMU_DOMAIN_BLOCKED:
413 case IOMMU_DOMAIN_IDENTITY:
416 case IOMMU_DOMAIN_UNMANAGED:
417 type = "unmanaged\n";
419 case IOMMU_DOMAIN_DMA:
429 static IOMMU_GROUP_ATTR(name, S_IRUGO, iommu_group_show_name, NULL);
431 static IOMMU_GROUP_ATTR(reserved_regions, 0444,
432 iommu_group_show_resv_regions, NULL);
434 static IOMMU_GROUP_ATTR(type, 0444, iommu_group_show_type, NULL);
436 static void iommu_group_release(struct kobject *kobj)
438 struct iommu_group *group = to_iommu_group(kobj);
440 pr_debug("Releasing group %d\n", group->id);
442 if (group->iommu_data_release)
443 group->iommu_data_release(group->iommu_data);
445 ida_simple_remove(&iommu_group_ida, group->id);
447 if (group->default_domain)
448 iommu_domain_free(group->default_domain);
454 static struct kobj_type iommu_group_ktype = {
455 .sysfs_ops = &iommu_group_sysfs_ops,
456 .release = iommu_group_release,
460 * iommu_group_alloc - Allocate a new group
462 * This function is called by an iommu driver to allocate a new iommu
463 * group. The iommu group represents the minimum granularity of the iommu.
464 * Upon successful return, the caller holds a reference to the supplied
465 * group in order to hold the group until devices are added. Use
466 * iommu_group_put() to release this extra reference count, allowing the
467 * group to be automatically reclaimed once it has no devices or external
470 struct iommu_group *iommu_group_alloc(void)
472 struct iommu_group *group;
475 group = kzalloc(sizeof(*group), GFP_KERNEL);
477 return ERR_PTR(-ENOMEM);
479 group->kobj.kset = iommu_group_kset;
480 mutex_init(&group->mutex);
481 INIT_LIST_HEAD(&group->devices);
482 BLOCKING_INIT_NOTIFIER_HEAD(&group->notifier);
484 ret = ida_simple_get(&iommu_group_ida, 0, 0, GFP_KERNEL);
491 ret = kobject_init_and_add(&group->kobj, &iommu_group_ktype,
492 NULL, "%d", group->id);
494 ida_simple_remove(&iommu_group_ida, group->id);
495 kobject_put(&group->kobj);
499 group->devices_kobj = kobject_create_and_add("devices", &group->kobj);
500 if (!group->devices_kobj) {
501 kobject_put(&group->kobj); /* triggers .release & free */
502 return ERR_PTR(-ENOMEM);
506 * The devices_kobj holds a reference on the group kobject, so
507 * as long as that exists so will the group. We can therefore
508 * use the devices_kobj for reference counting.
510 kobject_put(&group->kobj);
512 ret = iommu_group_create_file(group,
513 &iommu_group_attr_reserved_regions);
517 ret = iommu_group_create_file(group, &iommu_group_attr_type);
521 pr_debug("Allocated group %d\n", group->id);
525 EXPORT_SYMBOL_GPL(iommu_group_alloc);
527 struct iommu_group *iommu_group_get_by_id(int id)
529 struct kobject *group_kobj;
530 struct iommu_group *group;
533 if (!iommu_group_kset)
536 name = kasprintf(GFP_KERNEL, "%d", id);
540 group_kobj = kset_find_obj(iommu_group_kset, name);
546 group = container_of(group_kobj, struct iommu_group, kobj);
547 BUG_ON(group->id != id);
549 kobject_get(group->devices_kobj);
550 kobject_put(&group->kobj);
554 EXPORT_SYMBOL_GPL(iommu_group_get_by_id);
557 * iommu_group_get_iommudata - retrieve iommu_data registered for a group
560 * iommu drivers can store data in the group for use when doing iommu
561 * operations. This function provides a way to retrieve it. Caller
562 * should hold a group reference.
564 void *iommu_group_get_iommudata(struct iommu_group *group)
566 return group->iommu_data;
568 EXPORT_SYMBOL_GPL(iommu_group_get_iommudata);
571 * iommu_group_set_iommudata - set iommu_data for a group
573 * @iommu_data: new data
574 * @release: release function for iommu_data
576 * iommu drivers can store data in the group for use when doing iommu
577 * operations. This function provides a way to set the data after
578 * the group has been allocated. Caller should hold a group reference.
580 void iommu_group_set_iommudata(struct iommu_group *group, void *iommu_data,
581 void (*release)(void *iommu_data))
583 group->iommu_data = iommu_data;
584 group->iommu_data_release = release;
586 EXPORT_SYMBOL_GPL(iommu_group_set_iommudata);
589 * iommu_group_set_name - set name for a group
593 * Allow iommu driver to set a name for a group. When set it will
594 * appear in a name attribute file under the group in sysfs.
596 int iommu_group_set_name(struct iommu_group *group, const char *name)
601 iommu_group_remove_file(group, &iommu_group_attr_name);
608 group->name = kstrdup(name, GFP_KERNEL);
612 ret = iommu_group_create_file(group, &iommu_group_attr_name);
621 EXPORT_SYMBOL_GPL(iommu_group_set_name);
623 static int iommu_group_create_direct_mappings(struct iommu_group *group,
626 struct iommu_domain *domain = group->default_domain;
627 struct iommu_resv_region *entry;
628 struct list_head mappings;
629 unsigned long pg_size;
632 if (!domain || domain->type != IOMMU_DOMAIN_DMA)
635 BUG_ON(!domain->pgsize_bitmap);
637 pg_size = 1UL << __ffs(domain->pgsize_bitmap);
638 INIT_LIST_HEAD(&mappings);
640 iommu_get_resv_regions(dev, &mappings);
642 /* We need to consider overlapping regions for different devices */
643 list_for_each_entry(entry, &mappings, list) {
644 dma_addr_t start, end, addr;
646 if (domain->ops->apply_resv_region)
647 domain->ops->apply_resv_region(dev, domain, entry);
649 start = ALIGN(entry->start, pg_size);
650 end = ALIGN(entry->start + entry->length, pg_size);
652 if (entry->type != IOMMU_RESV_DIRECT &&
653 entry->type != IOMMU_RESV_DIRECT_RELAXABLE)
656 for (addr = start; addr < end; addr += pg_size) {
657 phys_addr_t phys_addr;
659 phys_addr = iommu_iova_to_phys(domain, addr);
663 ret = iommu_map(domain, addr, addr, pg_size, entry->prot);
670 iommu_flush_tlb_all(domain);
673 iommu_put_resv_regions(dev, &mappings);
679 * iommu_group_add_device - add a device to an iommu group
680 * @group: the group into which to add the device (reference should be held)
683 * This function is called by an iommu driver to add a device into a
684 * group. Adding a device increments the group reference count.
686 int iommu_group_add_device(struct iommu_group *group, struct device *dev)
689 struct group_device *device;
691 device = kzalloc(sizeof(*device), GFP_KERNEL);
697 ret = sysfs_create_link(&dev->kobj, &group->kobj, "iommu_group");
699 goto err_free_device;
701 device->name = kasprintf(GFP_KERNEL, "%s", kobject_name(&dev->kobj));
705 goto err_remove_link;
708 ret = sysfs_create_link_nowarn(group->devices_kobj,
709 &dev->kobj, device->name);
711 if (ret == -EEXIST && i >= 0) {
713 * Account for the slim chance of collision
714 * and append an instance to the name.
717 device->name = kasprintf(GFP_KERNEL, "%s.%d",
718 kobject_name(&dev->kobj), i++);
724 kobject_get(group->devices_kobj);
726 dev->iommu_group = group;
728 iommu_group_create_direct_mappings(group, dev);
730 mutex_lock(&group->mutex);
731 list_add_tail(&device->list, &group->devices);
733 ret = __iommu_attach_device(group->domain, dev);
734 mutex_unlock(&group->mutex);
738 /* Notify any listeners about change to group. */
739 blocking_notifier_call_chain(&group->notifier,
740 IOMMU_GROUP_NOTIFY_ADD_DEVICE, dev);
742 trace_add_device_to_group(group->id, dev);
744 dev_info(dev, "Adding to iommu group %d\n", group->id);
749 mutex_lock(&group->mutex);
750 list_del(&device->list);
751 mutex_unlock(&group->mutex);
752 dev->iommu_group = NULL;
753 kobject_put(group->devices_kobj);
754 sysfs_remove_link(group->devices_kobj, device->name);
758 sysfs_remove_link(&dev->kobj, "iommu_group");
761 dev_err(dev, "Failed to add to iommu group %d: %d\n", group->id, ret);
764 EXPORT_SYMBOL_GPL(iommu_group_add_device);
767 * iommu_group_remove_device - remove a device from it's current group
768 * @dev: device to be removed
770 * This function is called by an iommu driver to remove the device from
771 * it's current group. This decrements the iommu group reference count.
773 void iommu_group_remove_device(struct device *dev)
775 struct iommu_group *group = dev->iommu_group;
776 struct group_device *tmp_device, *device = NULL;
781 dev_info(dev, "Removing from iommu group %d\n", group->id);
783 /* Pre-notify listeners that a device is being removed. */
784 blocking_notifier_call_chain(&group->notifier,
785 IOMMU_GROUP_NOTIFY_DEL_DEVICE, dev);
787 mutex_lock(&group->mutex);
788 list_for_each_entry(tmp_device, &group->devices, list) {
789 if (tmp_device->dev == dev) {
791 list_del(&device->list);
795 mutex_unlock(&group->mutex);
800 sysfs_remove_link(group->devices_kobj, device->name);
801 sysfs_remove_link(&dev->kobj, "iommu_group");
803 trace_remove_device_from_group(group->id, dev);
807 dev->iommu_group = NULL;
808 kobject_put(group->devices_kobj);
810 EXPORT_SYMBOL_GPL(iommu_group_remove_device);
812 static int iommu_group_device_count(struct iommu_group *group)
814 struct group_device *entry;
817 list_for_each_entry(entry, &group->devices, list)
824 * iommu_group_for_each_dev - iterate over each device in the group
826 * @data: caller opaque data to be passed to callback function
827 * @fn: caller supplied callback function
829 * This function is called by group users to iterate over group devices.
830 * Callers should hold a reference count to the group during callback.
831 * The group->mutex is held across callbacks, which will block calls to
832 * iommu_group_add/remove_device.
834 static int __iommu_group_for_each_dev(struct iommu_group *group, void *data,
835 int (*fn)(struct device *, void *))
837 struct group_device *device;
840 list_for_each_entry(device, &group->devices, list) {
841 ret = fn(device->dev, data);
849 int iommu_group_for_each_dev(struct iommu_group *group, void *data,
850 int (*fn)(struct device *, void *))
854 mutex_lock(&group->mutex);
855 ret = __iommu_group_for_each_dev(group, data, fn);
856 mutex_unlock(&group->mutex);
860 EXPORT_SYMBOL_GPL(iommu_group_for_each_dev);
863 * iommu_group_get - Return the group for a device and increment reference
864 * @dev: get the group that this device belongs to
866 * This function is called by iommu drivers and users to get the group
867 * for the specified device. If found, the group is returned and the group
868 * reference in incremented, else NULL.
870 struct iommu_group *iommu_group_get(struct device *dev)
872 struct iommu_group *group = dev->iommu_group;
875 kobject_get(group->devices_kobj);
879 EXPORT_SYMBOL_GPL(iommu_group_get);
882 * iommu_group_ref_get - Increment reference on a group
883 * @group: the group to use, must not be NULL
885 * This function is called by iommu drivers to take additional references on an
886 * existing group. Returns the given group for convenience.
888 struct iommu_group *iommu_group_ref_get(struct iommu_group *group)
890 kobject_get(group->devices_kobj);
895 * iommu_group_put - Decrement group reference
896 * @group: the group to use
898 * This function is called by iommu drivers and users to release the
899 * iommu group. Once the reference count is zero, the group is released.
901 void iommu_group_put(struct iommu_group *group)
904 kobject_put(group->devices_kobj);
906 EXPORT_SYMBOL_GPL(iommu_group_put);
909 * iommu_group_register_notifier - Register a notifier for group changes
910 * @group: the group to watch
911 * @nb: notifier block to signal
913 * This function allows iommu group users to track changes in a group.
914 * See include/linux/iommu.h for actions sent via this notifier. Caller
915 * should hold a reference to the group throughout notifier registration.
917 int iommu_group_register_notifier(struct iommu_group *group,
918 struct notifier_block *nb)
920 return blocking_notifier_chain_register(&group->notifier, nb);
922 EXPORT_SYMBOL_GPL(iommu_group_register_notifier);
925 * iommu_group_unregister_notifier - Unregister a notifier
926 * @group: the group to watch
927 * @nb: notifier block to signal
929 * Unregister a previously registered group notifier block.
931 int iommu_group_unregister_notifier(struct iommu_group *group,
932 struct notifier_block *nb)
934 return blocking_notifier_chain_unregister(&group->notifier, nb);
936 EXPORT_SYMBOL_GPL(iommu_group_unregister_notifier);
939 * iommu_register_device_fault_handler() - Register a device fault handler
941 * @handler: the fault handler
942 * @data: private data passed as argument to the handler
944 * When an IOMMU fault event is received, this handler gets called with the
945 * fault event and data as argument. The handler should return 0 on success. If
946 * the fault is recoverable (IOMMU_FAULT_PAGE_REQ), the consumer should also
947 * complete the fault by calling iommu_page_response() with one of the following
949 * - IOMMU_PAGE_RESP_SUCCESS: retry the translation
950 * - IOMMU_PAGE_RESP_INVALID: terminate the fault
951 * - IOMMU_PAGE_RESP_FAILURE: terminate the fault and stop reporting
952 * page faults if possible.
954 * Return 0 if the fault handler was installed successfully, or an error.
956 int iommu_register_device_fault_handler(struct device *dev,
957 iommu_dev_fault_handler_t handler,
960 struct iommu_param *param = dev->iommu_param;
966 mutex_lock(¶m->lock);
967 /* Only allow one fault handler registered for each device */
968 if (param->fault_param) {
974 param->fault_param = kzalloc(sizeof(*param->fault_param), GFP_KERNEL);
975 if (!param->fault_param) {
980 param->fault_param->handler = handler;
981 param->fault_param->data = data;
982 mutex_init(¶m->fault_param->lock);
983 INIT_LIST_HEAD(¶m->fault_param->faults);
986 mutex_unlock(¶m->lock);
990 EXPORT_SYMBOL_GPL(iommu_register_device_fault_handler);
993 * iommu_unregister_device_fault_handler() - Unregister the device fault handler
996 * Remove the device fault handler installed with
997 * iommu_register_device_fault_handler().
999 * Return 0 on success, or an error.
1001 int iommu_unregister_device_fault_handler(struct device *dev)
1003 struct iommu_param *param = dev->iommu_param;
1009 mutex_lock(¶m->lock);
1011 if (!param->fault_param)
1014 /* we cannot unregister handler if there are pending faults */
1015 if (!list_empty(¶m->fault_param->faults)) {
1020 kfree(param->fault_param);
1021 param->fault_param = NULL;
1024 mutex_unlock(¶m->lock);
1028 EXPORT_SYMBOL_GPL(iommu_unregister_device_fault_handler);
1031 * iommu_report_device_fault() - Report fault event to device driver
1033 * @evt: fault event data
1035 * Called by IOMMU drivers when a fault is detected, typically in a threaded IRQ
1036 * handler. When this function fails and the fault is recoverable, it is the
1037 * caller's responsibility to complete the fault.
1039 * Return 0 on success, or an error.
1041 int iommu_report_device_fault(struct device *dev, struct iommu_fault_event *evt)
1043 struct iommu_param *param = dev->iommu_param;
1044 struct iommu_fault_event *evt_pending = NULL;
1045 struct iommu_fault_param *fparam;
1051 /* we only report device fault if there is a handler registered */
1052 mutex_lock(¶m->lock);
1053 fparam = param->fault_param;
1054 if (!fparam || !fparam->handler) {
1059 if (evt->fault.type == IOMMU_FAULT_PAGE_REQ &&
1060 (evt->fault.prm.flags & IOMMU_FAULT_PAGE_REQUEST_LAST_PAGE)) {
1061 evt_pending = kmemdup(evt, sizeof(struct iommu_fault_event),
1067 mutex_lock(&fparam->lock);
1068 list_add_tail(&evt_pending->list, &fparam->faults);
1069 mutex_unlock(&fparam->lock);
1072 ret = fparam->handler(&evt->fault, fparam->data);
1073 if (ret && evt_pending) {
1074 mutex_lock(&fparam->lock);
1075 list_del(&evt_pending->list);
1076 mutex_unlock(&fparam->lock);
1080 mutex_unlock(¶m->lock);
1083 EXPORT_SYMBOL_GPL(iommu_report_device_fault);
1085 int iommu_page_response(struct device *dev,
1086 struct iommu_page_response *msg)
1090 struct iommu_fault_event *evt;
1091 struct iommu_fault_page_request *prm;
1092 struct iommu_param *param = dev->iommu_param;
1093 struct iommu_domain *domain = iommu_get_domain_for_dev(dev);
1095 if (!domain || !domain->ops->page_response)
1098 if (!param || !param->fault_param)
1101 if (msg->version != IOMMU_PAGE_RESP_VERSION_1 ||
1102 msg->flags & ~IOMMU_PAGE_RESP_PASID_VALID)
1105 /* Only send response if there is a fault report pending */
1106 mutex_lock(¶m->fault_param->lock);
1107 if (list_empty(¶m->fault_param->faults)) {
1108 dev_warn_ratelimited(dev, "no pending PRQ, drop response\n");
1112 * Check if we have a matching page request pending to respond,
1113 * otherwise return -EINVAL
1115 list_for_each_entry(evt, ¶m->fault_param->faults, list) {
1116 prm = &evt->fault.prm;
1117 pasid_valid = prm->flags & IOMMU_FAULT_PAGE_REQUEST_PASID_VALID;
1119 if ((pasid_valid && prm->pasid != msg->pasid) ||
1120 prm->grpid != msg->grpid)
1123 /* Sanitize the reply */
1124 msg->flags = pasid_valid ? IOMMU_PAGE_RESP_PASID_VALID : 0;
1126 ret = domain->ops->page_response(dev, evt, msg);
1127 list_del(&evt->list);
1133 mutex_unlock(¶m->fault_param->lock);
1136 EXPORT_SYMBOL_GPL(iommu_page_response);
1139 * iommu_group_id - Return ID for a group
1140 * @group: the group to ID
1142 * Return the unique ID for the group matching the sysfs group number.
1144 int iommu_group_id(struct iommu_group *group)
1148 EXPORT_SYMBOL_GPL(iommu_group_id);
1150 static struct iommu_group *get_pci_alias_group(struct pci_dev *pdev,
1151 unsigned long *devfns);
1154 * To consider a PCI device isolated, we require ACS to support Source
1155 * Validation, Request Redirection, Completer Redirection, and Upstream
1156 * Forwarding. This effectively means that devices cannot spoof their
1157 * requester ID, requests and completions cannot be redirected, and all
1158 * transactions are forwarded upstream, even as it passes through a
1159 * bridge where the target device is downstream.
1161 #define REQ_ACS_FLAGS (PCI_ACS_SV | PCI_ACS_RR | PCI_ACS_CR | PCI_ACS_UF)
1164 * For multifunction devices which are not isolated from each other, find
1165 * all the other non-isolated functions and look for existing groups. For
1166 * each function, we also need to look for aliases to or from other devices
1167 * that may already have a group.
1169 static struct iommu_group *get_pci_function_alias_group(struct pci_dev *pdev,
1170 unsigned long *devfns)
1172 struct pci_dev *tmp = NULL;
1173 struct iommu_group *group;
1175 if (!pdev->multifunction || pci_acs_enabled(pdev, REQ_ACS_FLAGS))
1178 for_each_pci_dev(tmp) {
1179 if (tmp == pdev || tmp->bus != pdev->bus ||
1180 PCI_SLOT(tmp->devfn) != PCI_SLOT(pdev->devfn) ||
1181 pci_acs_enabled(tmp, REQ_ACS_FLAGS))
1184 group = get_pci_alias_group(tmp, devfns);
1195 * Look for aliases to or from the given device for existing groups. DMA
1196 * aliases are only supported on the same bus, therefore the search
1197 * space is quite small (especially since we're really only looking at pcie
1198 * device, and therefore only expect multiple slots on the root complex or
1199 * downstream switch ports). It's conceivable though that a pair of
1200 * multifunction devices could have aliases between them that would cause a
1201 * loop. To prevent this, we use a bitmap to track where we've been.
1203 static struct iommu_group *get_pci_alias_group(struct pci_dev *pdev,
1204 unsigned long *devfns)
1206 struct pci_dev *tmp = NULL;
1207 struct iommu_group *group;
1209 if (test_and_set_bit(pdev->devfn & 0xff, devfns))
1212 group = iommu_group_get(&pdev->dev);
1216 for_each_pci_dev(tmp) {
1217 if (tmp == pdev || tmp->bus != pdev->bus)
1220 /* We alias them or they alias us */
1221 if (pci_devs_are_dma_aliases(pdev, tmp)) {
1222 group = get_pci_alias_group(tmp, devfns);
1228 group = get_pci_function_alias_group(tmp, devfns);
1239 struct group_for_pci_data {
1240 struct pci_dev *pdev;
1241 struct iommu_group *group;
1245 * DMA alias iterator callback, return the last seen device. Stop and return
1246 * the IOMMU group if we find one along the way.
1248 static int get_pci_alias_or_group(struct pci_dev *pdev, u16 alias, void *opaque)
1250 struct group_for_pci_data *data = opaque;
1253 data->group = iommu_group_get(&pdev->dev);
1255 return data->group != NULL;
1259 * Generic device_group call-back function. It just allocates one
1260 * iommu-group per device.
1262 struct iommu_group *generic_device_group(struct device *dev)
1264 return iommu_group_alloc();
1268 * Use standard PCI bus topology, isolation features, and DMA alias quirks
1269 * to find or create an IOMMU group for a device.
1271 struct iommu_group *pci_device_group(struct device *dev)
1273 struct pci_dev *pdev = to_pci_dev(dev);
1274 struct group_for_pci_data data;
1275 struct pci_bus *bus;
1276 struct iommu_group *group = NULL;
1277 u64 devfns[4] = { 0 };
1279 if (WARN_ON(!dev_is_pci(dev)))
1280 return ERR_PTR(-EINVAL);
1283 * Find the upstream DMA alias for the device. A device must not
1284 * be aliased due to topology in order to have its own IOMMU group.
1285 * If we find an alias along the way that already belongs to a
1288 if (pci_for_each_dma_alias(pdev, get_pci_alias_or_group, &data))
1294 * Continue upstream from the point of minimum IOMMU granularity
1295 * due to aliases to the point where devices are protected from
1296 * peer-to-peer DMA by PCI ACS. Again, if we find an existing
1299 for (bus = pdev->bus; !pci_is_root_bus(bus); bus = bus->parent) {
1303 if (pci_acs_path_enabled(bus->self, NULL, REQ_ACS_FLAGS))
1308 group = iommu_group_get(&pdev->dev);
1314 * Look for existing groups on device aliases. If we alias another
1315 * device or another device aliases us, use the same group.
1317 group = get_pci_alias_group(pdev, (unsigned long *)devfns);
1322 * Look for existing groups on non-isolated functions on the same
1323 * slot and aliases of those funcions, if any. No need to clear
1324 * the search bitmap, the tested devfns are still valid.
1326 group = get_pci_function_alias_group(pdev, (unsigned long *)devfns);
1330 /* No shared group found, allocate new */
1331 return iommu_group_alloc();
1334 /* Get the IOMMU group for device on fsl-mc bus */
1335 struct iommu_group *fsl_mc_device_group(struct device *dev)
1337 struct device *cont_dev = fsl_mc_cont_dev(dev);
1338 struct iommu_group *group;
1340 group = iommu_group_get(cont_dev);
1342 group = iommu_group_alloc();
1347 * iommu_group_get_for_dev - Find or create the IOMMU group for a device
1348 * @dev: target device
1350 * This function is intended to be called by IOMMU drivers and extended to
1351 * support common, bus-defined algorithms when determining or creating the
1352 * IOMMU group for a device. On success, the caller will hold a reference
1353 * to the returned IOMMU group, which will already include the provided
1354 * device. The reference should be released with iommu_group_put().
1356 struct iommu_group *iommu_group_get_for_dev(struct device *dev)
1358 const struct iommu_ops *ops = dev->bus->iommu_ops;
1359 struct iommu_group *group;
1362 group = iommu_group_get(dev);
1367 return ERR_PTR(-EINVAL);
1369 group = ops->device_group(dev);
1370 if (WARN_ON_ONCE(group == NULL))
1371 return ERR_PTR(-EINVAL);
1377 * Try to allocate a default domain - needs support from the
1380 if (!group->default_domain) {
1381 struct iommu_domain *dom;
1383 dom = __iommu_domain_alloc(dev->bus, iommu_def_domain_type);
1384 if (!dom && iommu_def_domain_type != IOMMU_DOMAIN_DMA) {
1385 dom = __iommu_domain_alloc(dev->bus, IOMMU_DOMAIN_DMA);
1388 "failed to allocate default IOMMU domain of type %u; falling back to IOMMU_DOMAIN_DMA",
1389 iommu_def_domain_type);
1393 group->default_domain = dom;
1395 group->domain = dom;
1397 if (dom && !iommu_dma_strict) {
1399 iommu_domain_set_attr(dom,
1400 DOMAIN_ATTR_DMA_USE_FLUSH_QUEUE,
1405 ret = iommu_group_add_device(group, dev);
1407 iommu_group_put(group);
1408 return ERR_PTR(ret);
1414 struct iommu_domain *iommu_group_default_domain(struct iommu_group *group)
1416 return group->default_domain;
1419 static int add_iommu_group(struct device *dev, void *data)
1421 int ret = iommu_probe_device(dev);
1424 * We ignore -ENODEV errors for now, as they just mean that the
1425 * device is not translated by an IOMMU. We still care about
1426 * other errors and fail to initialize when they happen.
1434 static int remove_iommu_group(struct device *dev, void *data)
1436 iommu_release_device(dev);
1441 static int iommu_bus_notifier(struct notifier_block *nb,
1442 unsigned long action, void *data)
1444 unsigned long group_action = 0;
1445 struct device *dev = data;
1446 struct iommu_group *group;
1449 * ADD/DEL call into iommu driver ops if provided, which may
1450 * result in ADD/DEL notifiers to group->notifier
1452 if (action == BUS_NOTIFY_ADD_DEVICE) {
1455 ret = iommu_probe_device(dev);
1456 return (ret) ? NOTIFY_DONE : NOTIFY_OK;
1457 } else if (action == BUS_NOTIFY_REMOVED_DEVICE) {
1458 iommu_release_device(dev);
1463 * Remaining BUS_NOTIFYs get filtered and republished to the
1464 * group, if anyone is listening
1466 group = iommu_group_get(dev);
1471 case BUS_NOTIFY_BIND_DRIVER:
1472 group_action = IOMMU_GROUP_NOTIFY_BIND_DRIVER;
1474 case BUS_NOTIFY_BOUND_DRIVER:
1475 group_action = IOMMU_GROUP_NOTIFY_BOUND_DRIVER;
1477 case BUS_NOTIFY_UNBIND_DRIVER:
1478 group_action = IOMMU_GROUP_NOTIFY_UNBIND_DRIVER;
1480 case BUS_NOTIFY_UNBOUND_DRIVER:
1481 group_action = IOMMU_GROUP_NOTIFY_UNBOUND_DRIVER;
1486 blocking_notifier_call_chain(&group->notifier,
1489 iommu_group_put(group);
1493 static int iommu_bus_init(struct bus_type *bus, const struct iommu_ops *ops)
1496 struct notifier_block *nb;
1498 nb = kzalloc(sizeof(struct notifier_block), GFP_KERNEL);
1502 nb->notifier_call = iommu_bus_notifier;
1504 err = bus_register_notifier(bus, nb);
1508 err = bus_for_each_dev(bus, NULL, NULL, add_iommu_group);
1517 bus_for_each_dev(bus, NULL, NULL, remove_iommu_group);
1518 bus_unregister_notifier(bus, nb);
1527 * bus_set_iommu - set iommu-callbacks for the bus
1529 * @ops: the callbacks provided by the iommu-driver
1531 * This function is called by an iommu driver to set the iommu methods
1532 * used for a particular bus. Drivers for devices on that bus can use
1533 * the iommu-api after these ops are registered.
1534 * This special function is needed because IOMMUs are usually devices on
1535 * the bus itself, so the iommu drivers are not initialized when the bus
1536 * is set up. With this function the iommu-driver can set the iommu-ops
1539 int bus_set_iommu(struct bus_type *bus, const struct iommu_ops *ops)
1543 if (bus->iommu_ops != NULL)
1546 bus->iommu_ops = ops;
1548 /* Do IOMMU specific setup for this bus-type */
1549 err = iommu_bus_init(bus, ops);
1551 bus->iommu_ops = NULL;
1555 EXPORT_SYMBOL_GPL(bus_set_iommu);
1557 bool iommu_present(struct bus_type *bus)
1559 return bus->iommu_ops != NULL;
1561 EXPORT_SYMBOL_GPL(iommu_present);
1563 bool iommu_capable(struct bus_type *bus, enum iommu_cap cap)
1565 if (!bus->iommu_ops || !bus->iommu_ops->capable)
1568 return bus->iommu_ops->capable(cap);
1570 EXPORT_SYMBOL_GPL(iommu_capable);
1573 * iommu_set_fault_handler() - set a fault handler for an iommu domain
1574 * @domain: iommu domain
1575 * @handler: fault handler
1576 * @token: user data, will be passed back to the fault handler
1578 * This function should be used by IOMMU users which want to be notified
1579 * whenever an IOMMU fault happens.
1581 * The fault handler itself should return 0 on success, and an appropriate
1582 * error code otherwise.
1584 void iommu_set_fault_handler(struct iommu_domain *domain,
1585 iommu_fault_handler_t handler,
1590 domain->handler = handler;
1591 domain->handler_token = token;
1593 EXPORT_SYMBOL_GPL(iommu_set_fault_handler);
1595 static struct iommu_domain *__iommu_domain_alloc(struct bus_type *bus,
1598 struct iommu_domain *domain;
1600 if (bus == NULL || bus->iommu_ops == NULL)
1603 domain = bus->iommu_ops->domain_alloc(type);
1607 domain->ops = bus->iommu_ops;
1608 domain->type = type;
1609 /* Assume all sizes by default; the driver may override this later */
1610 domain->pgsize_bitmap = bus->iommu_ops->pgsize_bitmap;
1615 struct iommu_domain *iommu_domain_alloc(struct bus_type *bus)
1617 return __iommu_domain_alloc(bus, IOMMU_DOMAIN_UNMANAGED);
1619 EXPORT_SYMBOL_GPL(iommu_domain_alloc);
1621 void iommu_domain_free(struct iommu_domain *domain)
1623 domain->ops->domain_free(domain);
1625 EXPORT_SYMBOL_GPL(iommu_domain_free);
1627 static int __iommu_attach_device(struct iommu_domain *domain,
1631 if ((domain->ops->is_attach_deferred != NULL) &&
1632 domain->ops->is_attach_deferred(domain, dev))
1635 if (unlikely(domain->ops->attach_dev == NULL))
1638 ret = domain->ops->attach_dev(domain, dev);
1640 trace_attach_device_to_domain(dev);
1644 int iommu_attach_device(struct iommu_domain *domain, struct device *dev)
1646 struct iommu_group *group;
1649 group = iommu_group_get(dev);
1654 * Lock the group to make sure the device-count doesn't
1655 * change while we are attaching
1657 mutex_lock(&group->mutex);
1659 if (iommu_group_device_count(group) != 1)
1662 ret = __iommu_attach_group(domain, group);
1665 mutex_unlock(&group->mutex);
1666 iommu_group_put(group);
1670 EXPORT_SYMBOL_GPL(iommu_attach_device);
1672 static void __iommu_detach_device(struct iommu_domain *domain,
1675 if ((domain->ops->is_attach_deferred != NULL) &&
1676 domain->ops->is_attach_deferred(domain, dev))
1679 if (unlikely(domain->ops->detach_dev == NULL))
1682 domain->ops->detach_dev(domain, dev);
1683 trace_detach_device_from_domain(dev);
1686 void iommu_detach_device(struct iommu_domain *domain, struct device *dev)
1688 struct iommu_group *group;
1690 group = iommu_group_get(dev);
1694 mutex_lock(&group->mutex);
1695 if (iommu_group_device_count(group) != 1) {
1700 __iommu_detach_group(domain, group);
1703 mutex_unlock(&group->mutex);
1704 iommu_group_put(group);
1706 EXPORT_SYMBOL_GPL(iommu_detach_device);
1708 struct iommu_domain *iommu_get_domain_for_dev(struct device *dev)
1710 struct iommu_domain *domain;
1711 struct iommu_group *group;
1713 group = iommu_group_get(dev);
1717 domain = group->domain;
1719 iommu_group_put(group);
1723 EXPORT_SYMBOL_GPL(iommu_get_domain_for_dev);
1726 * For IOMMU_DOMAIN_DMA implementations which already provide their own
1727 * guarantees that the group and its default domain are valid and correct.
1729 struct iommu_domain *iommu_get_dma_domain(struct device *dev)
1731 return dev->iommu_group->default_domain;
1735 * IOMMU groups are really the natural working unit of the IOMMU, but
1736 * the IOMMU API works on domains and devices. Bridge that gap by
1737 * iterating over the devices in a group. Ideally we'd have a single
1738 * device which represents the requestor ID of the group, but we also
1739 * allow IOMMU drivers to create policy defined minimum sets, where
1740 * the physical hardware may be able to distiguish members, but we
1741 * wish to group them at a higher level (ex. untrusted multi-function
1742 * PCI devices). Thus we attach each device.
1744 static int iommu_group_do_attach_device(struct device *dev, void *data)
1746 struct iommu_domain *domain = data;
1748 return __iommu_attach_device(domain, dev);
1751 static int __iommu_attach_group(struct iommu_domain *domain,
1752 struct iommu_group *group)
1756 if (group->default_domain && group->domain != group->default_domain)
1759 ret = __iommu_group_for_each_dev(group, domain,
1760 iommu_group_do_attach_device);
1762 group->domain = domain;
1767 int iommu_attach_group(struct iommu_domain *domain, struct iommu_group *group)
1771 mutex_lock(&group->mutex);
1772 ret = __iommu_attach_group(domain, group);
1773 mutex_unlock(&group->mutex);
1777 EXPORT_SYMBOL_GPL(iommu_attach_group);
1779 static int iommu_group_do_detach_device(struct device *dev, void *data)
1781 struct iommu_domain *domain = data;
1783 __iommu_detach_device(domain, dev);
1788 static void __iommu_detach_group(struct iommu_domain *domain,
1789 struct iommu_group *group)
1793 if (!group->default_domain) {
1794 __iommu_group_for_each_dev(group, domain,
1795 iommu_group_do_detach_device);
1796 group->domain = NULL;
1800 if (group->domain == group->default_domain)
1803 /* Detach by re-attaching to the default domain */
1804 ret = __iommu_group_for_each_dev(group, group->default_domain,
1805 iommu_group_do_attach_device);
1809 group->domain = group->default_domain;
1812 void iommu_detach_group(struct iommu_domain *domain, struct iommu_group *group)
1814 mutex_lock(&group->mutex);
1815 __iommu_detach_group(domain, group);
1816 mutex_unlock(&group->mutex);
1818 EXPORT_SYMBOL_GPL(iommu_detach_group);
1820 phys_addr_t iommu_iova_to_phys(struct iommu_domain *domain, dma_addr_t iova)
1822 if (unlikely(domain->ops->iova_to_phys == NULL))
1825 return domain->ops->iova_to_phys(domain, iova);
1827 EXPORT_SYMBOL_GPL(iommu_iova_to_phys);
1829 static size_t iommu_pgsize(struct iommu_domain *domain,
1830 unsigned long addr_merge, size_t size)
1832 unsigned int pgsize_idx;
1835 /* Max page size that still fits into 'size' */
1836 pgsize_idx = __fls(size);
1838 /* need to consider alignment requirements ? */
1839 if (likely(addr_merge)) {
1840 /* Max page size allowed by address */
1841 unsigned int align_pgsize_idx = __ffs(addr_merge);
1842 pgsize_idx = min(pgsize_idx, align_pgsize_idx);
1845 /* build a mask of acceptable page sizes */
1846 pgsize = (1UL << (pgsize_idx + 1)) - 1;
1848 /* throw away page sizes not supported by the hardware */
1849 pgsize &= domain->pgsize_bitmap;
1851 /* make sure we're still sane */
1854 /* pick the biggest page */
1855 pgsize_idx = __fls(pgsize);
1856 pgsize = 1UL << pgsize_idx;
1861 int __iommu_map(struct iommu_domain *domain, unsigned long iova,
1862 phys_addr_t paddr, size_t size, int prot, gfp_t gfp)
1864 const struct iommu_ops *ops = domain->ops;
1865 unsigned long orig_iova = iova;
1866 unsigned int min_pagesz;
1867 size_t orig_size = size;
1868 phys_addr_t orig_paddr = paddr;
1871 if (unlikely(ops->map == NULL ||
1872 domain->pgsize_bitmap == 0UL))
1875 if (unlikely(!(domain->type & __IOMMU_DOMAIN_PAGING)))
1878 /* find out the minimum page size supported */
1879 min_pagesz = 1 << __ffs(domain->pgsize_bitmap);
1882 * both the virtual address and the physical one, as well as
1883 * the size of the mapping, must be aligned (at least) to the
1884 * size of the smallest page supported by the hardware
1886 if (!IS_ALIGNED(iova | paddr | size, min_pagesz)) {
1887 pr_err("unaligned: iova 0x%lx pa %pa size 0x%zx min_pagesz 0x%x\n",
1888 iova, &paddr, size, min_pagesz);
1892 pr_debug("map: iova 0x%lx pa %pa size 0x%zx\n", iova, &paddr, size);
1895 size_t pgsize = iommu_pgsize(domain, iova | paddr, size);
1897 pr_debug("mapping: iova 0x%lx pa %pa pgsize 0x%zx\n",
1898 iova, &paddr, pgsize);
1899 ret = ops->map(domain, iova, paddr, pgsize, prot, gfp);
1909 if (ops->iotlb_sync_map)
1910 ops->iotlb_sync_map(domain);
1912 /* unroll mapping in case something went wrong */
1914 iommu_unmap(domain, orig_iova, orig_size - size);
1916 trace_map(orig_iova, orig_paddr, orig_size);
1921 int iommu_map(struct iommu_domain *domain, unsigned long iova,
1922 phys_addr_t paddr, size_t size, int prot)
1925 return __iommu_map(domain, iova, paddr, size, prot, GFP_KERNEL);
1927 EXPORT_SYMBOL_GPL(iommu_map);
1929 int iommu_map_atomic(struct iommu_domain *domain, unsigned long iova,
1930 phys_addr_t paddr, size_t size, int prot)
1932 return __iommu_map(domain, iova, paddr, size, prot, GFP_ATOMIC);
1934 EXPORT_SYMBOL_GPL(iommu_map_atomic);
1936 static size_t __iommu_unmap(struct iommu_domain *domain,
1937 unsigned long iova, size_t size,
1938 struct iommu_iotlb_gather *iotlb_gather)
1940 const struct iommu_ops *ops = domain->ops;
1941 size_t unmapped_page, unmapped = 0;
1942 unsigned long orig_iova = iova;
1943 unsigned int min_pagesz;
1945 if (unlikely(ops->unmap == NULL ||
1946 domain->pgsize_bitmap == 0UL))
1949 if (unlikely(!(domain->type & __IOMMU_DOMAIN_PAGING)))
1952 /* find out the minimum page size supported */
1953 min_pagesz = 1 << __ffs(domain->pgsize_bitmap);
1956 * The virtual address, as well as the size of the mapping, must be
1957 * aligned (at least) to the size of the smallest page supported
1960 if (!IS_ALIGNED(iova | size, min_pagesz)) {
1961 pr_err("unaligned: iova 0x%lx size 0x%zx min_pagesz 0x%x\n",
1962 iova, size, min_pagesz);
1966 pr_debug("unmap this: iova 0x%lx size 0x%zx\n", iova, size);
1969 * Keep iterating until we either unmap 'size' bytes (or more)
1970 * or we hit an area that isn't mapped.
1972 while (unmapped < size) {
1973 size_t pgsize = iommu_pgsize(domain, iova, size - unmapped);
1975 unmapped_page = ops->unmap(domain, iova, pgsize, iotlb_gather);
1979 pr_debug("unmapped: iova 0x%lx size 0x%zx\n",
1980 iova, unmapped_page);
1982 iova += unmapped_page;
1983 unmapped += unmapped_page;
1986 trace_unmap(orig_iova, size, unmapped);
1990 size_t iommu_unmap(struct iommu_domain *domain,
1991 unsigned long iova, size_t size)
1993 struct iommu_iotlb_gather iotlb_gather;
1996 iommu_iotlb_gather_init(&iotlb_gather);
1997 ret = __iommu_unmap(domain, iova, size, &iotlb_gather);
1998 iommu_tlb_sync(domain, &iotlb_gather);
2002 EXPORT_SYMBOL_GPL(iommu_unmap);
2004 size_t iommu_unmap_fast(struct iommu_domain *domain,
2005 unsigned long iova, size_t size,
2006 struct iommu_iotlb_gather *iotlb_gather)
2008 return __iommu_unmap(domain, iova, size, iotlb_gather);
2010 EXPORT_SYMBOL_GPL(iommu_unmap_fast);
2012 size_t __iommu_map_sg(struct iommu_domain *domain, unsigned long iova,
2013 struct scatterlist *sg, unsigned int nents, int prot,
2016 size_t len = 0, mapped = 0;
2021 while (i <= nents) {
2022 phys_addr_t s_phys = sg_phys(sg);
2024 if (len && s_phys != start + len) {
2025 ret = __iommu_map(domain, iova + mapped, start,
2049 /* undo mappings already done */
2050 iommu_unmap(domain, iova, mapped);
2056 size_t iommu_map_sg(struct iommu_domain *domain, unsigned long iova,
2057 struct scatterlist *sg, unsigned int nents, int prot)
2060 return __iommu_map_sg(domain, iova, sg, nents, prot, GFP_KERNEL);
2062 EXPORT_SYMBOL_GPL(iommu_map_sg);
2064 size_t iommu_map_sg_atomic(struct iommu_domain *domain, unsigned long iova,
2065 struct scatterlist *sg, unsigned int nents, int prot)
2067 return __iommu_map_sg(domain, iova, sg, nents, prot, GFP_ATOMIC);
2069 EXPORT_SYMBOL_GPL(iommu_map_sg_atomic);
2071 int iommu_domain_window_enable(struct iommu_domain *domain, u32 wnd_nr,
2072 phys_addr_t paddr, u64 size, int prot)
2074 if (unlikely(domain->ops->domain_window_enable == NULL))
2077 return domain->ops->domain_window_enable(domain, wnd_nr, paddr, size,
2080 EXPORT_SYMBOL_GPL(iommu_domain_window_enable);
2082 void iommu_domain_window_disable(struct iommu_domain *domain, u32 wnd_nr)
2084 if (unlikely(domain->ops->domain_window_disable == NULL))
2087 return domain->ops->domain_window_disable(domain, wnd_nr);
2089 EXPORT_SYMBOL_GPL(iommu_domain_window_disable);
2092 * report_iommu_fault() - report about an IOMMU fault to the IOMMU framework
2093 * @domain: the iommu domain where the fault has happened
2094 * @dev: the device where the fault has happened
2095 * @iova: the faulting address
2096 * @flags: mmu fault flags (e.g. IOMMU_FAULT_READ/IOMMU_FAULT_WRITE/...)
2098 * This function should be called by the low-level IOMMU implementations
2099 * whenever IOMMU faults happen, to allow high-level users, that are
2100 * interested in such events, to know about them.
2102 * This event may be useful for several possible use cases:
2103 * - mere logging of the event
2104 * - dynamic TLB/PTE loading
2105 * - if restarting of the faulting device is required
2107 * Returns 0 on success and an appropriate error code otherwise (if dynamic
2108 * PTE/TLB loading will one day be supported, implementations will be able
2109 * to tell whether it succeeded or not according to this return value).
2111 * Specifically, -ENOSYS is returned if a fault handler isn't installed
2112 * (though fault handlers can also return -ENOSYS, in case they want to
2113 * elicit the default behavior of the IOMMU drivers).
2115 int report_iommu_fault(struct iommu_domain *domain, struct device *dev,
2116 unsigned long iova, int flags)
2121 * if upper layers showed interest and installed a fault handler,
2124 if (domain->handler)
2125 ret = domain->handler(domain, dev, iova, flags,
2126 domain->handler_token);
2128 trace_io_page_fault(dev, iova, flags);
2131 EXPORT_SYMBOL_GPL(report_iommu_fault);
2133 static int __init iommu_init(void)
2135 iommu_group_kset = kset_create_and_add("iommu_groups",
2137 BUG_ON(!iommu_group_kset);
2139 iommu_debugfs_setup();
2143 core_initcall(iommu_init);
2145 int iommu_domain_get_attr(struct iommu_domain *domain,
2146 enum iommu_attr attr, void *data)
2148 struct iommu_domain_geometry *geometry;
2153 case DOMAIN_ATTR_GEOMETRY:
2155 *geometry = domain->geometry;
2158 case DOMAIN_ATTR_PAGING:
2160 *paging = (domain->pgsize_bitmap != 0UL);
2163 if (!domain->ops->domain_get_attr)
2166 ret = domain->ops->domain_get_attr(domain, attr, data);
2171 EXPORT_SYMBOL_GPL(iommu_domain_get_attr);
2173 int iommu_domain_set_attr(struct iommu_domain *domain,
2174 enum iommu_attr attr, void *data)
2180 if (domain->ops->domain_set_attr == NULL)
2183 ret = domain->ops->domain_set_attr(domain, attr, data);
2188 EXPORT_SYMBOL_GPL(iommu_domain_set_attr);
2190 void iommu_get_resv_regions(struct device *dev, struct list_head *list)
2192 const struct iommu_ops *ops = dev->bus->iommu_ops;
2194 if (ops && ops->get_resv_regions)
2195 ops->get_resv_regions(dev, list);
2198 void iommu_put_resv_regions(struct device *dev, struct list_head *list)
2200 const struct iommu_ops *ops = dev->bus->iommu_ops;
2202 if (ops && ops->put_resv_regions)
2203 ops->put_resv_regions(dev, list);
2206 struct iommu_resv_region *iommu_alloc_resv_region(phys_addr_t start,
2207 size_t length, int prot,
2208 enum iommu_resv_type type)
2210 struct iommu_resv_region *region;
2212 region = kzalloc(sizeof(*region), GFP_KERNEL);
2216 INIT_LIST_HEAD(®ion->list);
2217 region->start = start;
2218 region->length = length;
2219 region->prot = prot;
2220 region->type = type;
2225 request_default_domain_for_dev(struct device *dev, unsigned long type)
2227 struct iommu_domain *domain;
2228 struct iommu_group *group;
2231 /* Device must already be in a group before calling this function */
2232 group = iommu_group_get(dev);
2236 mutex_lock(&group->mutex);
2239 if (group->default_domain && group->default_domain->type == type)
2242 /* Don't change mappings of existing devices */
2244 if (iommu_group_device_count(group) != 1)
2248 domain = __iommu_domain_alloc(dev->bus, type);
2252 /* Attach the device to the domain */
2253 ret = __iommu_attach_group(domain, group);
2255 iommu_domain_free(domain);
2259 /* Make the domain the default for this group */
2260 if (group->default_domain)
2261 iommu_domain_free(group->default_domain);
2262 group->default_domain = domain;
2264 iommu_group_create_direct_mappings(group, dev);
2266 dev_info(dev, "Using iommu %s mapping\n",
2267 type == IOMMU_DOMAIN_DMA ? "dma" : "direct");
2271 mutex_unlock(&group->mutex);
2272 iommu_group_put(group);
2277 /* Request that a device is direct mapped by the IOMMU */
2278 int iommu_request_dm_for_dev(struct device *dev)
2280 return request_default_domain_for_dev(dev, IOMMU_DOMAIN_IDENTITY);
2283 /* Request that a device can't be direct mapped by the IOMMU */
2284 int iommu_request_dma_domain_for_dev(struct device *dev)
2286 return request_default_domain_for_dev(dev, IOMMU_DOMAIN_DMA);
2289 void iommu_set_default_passthrough(bool cmd_line)
2292 iommu_set_cmd_line_dma_api();
2294 iommu_def_domain_type = IOMMU_DOMAIN_IDENTITY;
2297 void iommu_set_default_translated(bool cmd_line)
2300 iommu_set_cmd_line_dma_api();
2302 iommu_def_domain_type = IOMMU_DOMAIN_DMA;
2305 bool iommu_default_passthrough(void)
2307 return iommu_def_domain_type == IOMMU_DOMAIN_IDENTITY;
2309 EXPORT_SYMBOL_GPL(iommu_default_passthrough);
2311 const struct iommu_ops *iommu_ops_from_fwnode(struct fwnode_handle *fwnode)
2313 const struct iommu_ops *ops = NULL;
2314 struct iommu_device *iommu;
2316 spin_lock(&iommu_device_lock);
2317 list_for_each_entry(iommu, &iommu_device_list, list)
2318 if (iommu->fwnode == fwnode) {
2322 spin_unlock(&iommu_device_lock);
2326 int iommu_fwspec_init(struct device *dev, struct fwnode_handle *iommu_fwnode,
2327 const struct iommu_ops *ops)
2329 struct iommu_fwspec *fwspec = dev_iommu_fwspec_get(dev);
2332 return ops == fwspec->ops ? 0 : -EINVAL;
2334 fwspec = kzalloc(sizeof(*fwspec), GFP_KERNEL);
2338 of_node_get(to_of_node(iommu_fwnode));
2339 fwspec->iommu_fwnode = iommu_fwnode;
2341 dev_iommu_fwspec_set(dev, fwspec);
2344 EXPORT_SYMBOL_GPL(iommu_fwspec_init);
2346 void iommu_fwspec_free(struct device *dev)
2348 struct iommu_fwspec *fwspec = dev_iommu_fwspec_get(dev);
2351 fwnode_handle_put(fwspec->iommu_fwnode);
2353 dev_iommu_fwspec_set(dev, NULL);
2356 EXPORT_SYMBOL_GPL(iommu_fwspec_free);
2358 int iommu_fwspec_add_ids(struct device *dev, u32 *ids, int num_ids)
2360 struct iommu_fwspec *fwspec = dev_iommu_fwspec_get(dev);
2367 size = offsetof(struct iommu_fwspec, ids[fwspec->num_ids + num_ids]);
2368 if (size > sizeof(*fwspec)) {
2369 fwspec = krealloc(fwspec, size, GFP_KERNEL);
2373 dev_iommu_fwspec_set(dev, fwspec);
2376 for (i = 0; i < num_ids; i++)
2377 fwspec->ids[fwspec->num_ids + i] = ids[i];
2379 fwspec->num_ids += num_ids;
2382 EXPORT_SYMBOL_GPL(iommu_fwspec_add_ids);
2385 * Per device IOMMU features.
2387 bool iommu_dev_has_feature(struct device *dev, enum iommu_dev_features feat)
2389 const struct iommu_ops *ops = dev->bus->iommu_ops;
2391 if (ops && ops->dev_has_feat)
2392 return ops->dev_has_feat(dev, feat);
2396 EXPORT_SYMBOL_GPL(iommu_dev_has_feature);
2398 int iommu_dev_enable_feature(struct device *dev, enum iommu_dev_features feat)
2400 const struct iommu_ops *ops = dev->bus->iommu_ops;
2402 if (ops && ops->dev_enable_feat)
2403 return ops->dev_enable_feat(dev, feat);
2407 EXPORT_SYMBOL_GPL(iommu_dev_enable_feature);
2410 * The device drivers should do the necessary cleanups before calling this.
2411 * For example, before disabling the aux-domain feature, the device driver
2412 * should detach all aux-domains. Otherwise, this will return -EBUSY.
2414 int iommu_dev_disable_feature(struct device *dev, enum iommu_dev_features feat)
2416 const struct iommu_ops *ops = dev->bus->iommu_ops;
2418 if (ops && ops->dev_disable_feat)
2419 return ops->dev_disable_feat(dev, feat);
2423 EXPORT_SYMBOL_GPL(iommu_dev_disable_feature);
2425 bool iommu_dev_feature_enabled(struct device *dev, enum iommu_dev_features feat)
2427 const struct iommu_ops *ops = dev->bus->iommu_ops;
2429 if (ops && ops->dev_feat_enabled)
2430 return ops->dev_feat_enabled(dev, feat);
2434 EXPORT_SYMBOL_GPL(iommu_dev_feature_enabled);
2437 * Aux-domain specific attach/detach.
2439 * Only works if iommu_dev_feature_enabled(dev, IOMMU_DEV_FEAT_AUX) returns
2440 * true. Also, as long as domains are attached to a device through this
2441 * interface, any tries to call iommu_attach_device() should fail
2442 * (iommu_detach_device() can't fail, so we fail when trying to re-attach).
2443 * This should make us safe against a device being attached to a guest as a
2444 * whole while there are still pasid users on it (aux and sva).
2446 int iommu_aux_attach_device(struct iommu_domain *domain, struct device *dev)
2450 if (domain->ops->aux_attach_dev)
2451 ret = domain->ops->aux_attach_dev(domain, dev);
2454 trace_attach_device_to_domain(dev);
2458 EXPORT_SYMBOL_GPL(iommu_aux_attach_device);
2460 void iommu_aux_detach_device(struct iommu_domain *domain, struct device *dev)
2462 if (domain->ops->aux_detach_dev) {
2463 domain->ops->aux_detach_dev(domain, dev);
2464 trace_detach_device_from_domain(dev);
2467 EXPORT_SYMBOL_GPL(iommu_aux_detach_device);
2469 int iommu_aux_get_pasid(struct iommu_domain *domain, struct device *dev)
2473 if (domain->ops->aux_get_pasid)
2474 ret = domain->ops->aux_get_pasid(domain, dev);
2478 EXPORT_SYMBOL_GPL(iommu_aux_get_pasid);
2481 * iommu_sva_bind_device() - Bind a process address space to a device
2483 * @mm: the mm to bind, caller must hold a reference to it
2485 * Create a bond between device and address space, allowing the device to access
2486 * the mm using the returned PASID. If a bond already exists between @device and
2487 * @mm, it is returned and an additional reference is taken. Caller must call
2488 * iommu_sva_unbind_device() to release each reference.
2490 * iommu_dev_enable_feature(dev, IOMMU_DEV_FEAT_SVA) must be called first, to
2491 * initialize the required SVA features.
2493 * On error, returns an ERR_PTR value.
2496 iommu_sva_bind_device(struct device *dev, struct mm_struct *mm, void *drvdata)
2498 struct iommu_group *group;
2499 struct iommu_sva *handle = ERR_PTR(-EINVAL);
2500 const struct iommu_ops *ops = dev->bus->iommu_ops;
2502 if (!ops || !ops->sva_bind)
2503 return ERR_PTR(-ENODEV);
2505 group = iommu_group_get(dev);
2507 return ERR_PTR(-ENODEV);
2509 /* Ensure device count and domain don't change while we're binding */
2510 mutex_lock(&group->mutex);
2513 * To keep things simple, SVA currently doesn't support IOMMU groups
2514 * with more than one device. Existing SVA-capable systems are not
2515 * affected by the problems that required IOMMU groups (lack of ACS
2516 * isolation, device ID aliasing and other hardware issues).
2518 if (iommu_group_device_count(group) != 1)
2521 handle = ops->sva_bind(dev, mm, drvdata);
2524 mutex_unlock(&group->mutex);
2525 iommu_group_put(group);
2529 EXPORT_SYMBOL_GPL(iommu_sva_bind_device);
2532 * iommu_sva_unbind_device() - Remove a bond created with iommu_sva_bind_device
2533 * @handle: the handle returned by iommu_sva_bind_device()
2535 * Put reference to a bond between device and address space. The device should
2536 * not be issuing any more transaction for this PASID. All outstanding page
2537 * requests for this PASID must have been flushed to the IOMMU.
2539 * Returns 0 on success, or an error value
2541 void iommu_sva_unbind_device(struct iommu_sva *handle)
2543 struct iommu_group *group;
2544 struct device *dev = handle->dev;
2545 const struct iommu_ops *ops = dev->bus->iommu_ops;
2547 if (!ops || !ops->sva_unbind)
2550 group = iommu_group_get(dev);
2554 mutex_lock(&group->mutex);
2555 ops->sva_unbind(handle);
2556 mutex_unlock(&group->mutex);
2558 iommu_group_put(group);
2560 EXPORT_SYMBOL_GPL(iommu_sva_unbind_device);
2562 int iommu_sva_set_ops(struct iommu_sva *handle,
2563 const struct iommu_sva_ops *sva_ops)
2565 if (handle->ops && handle->ops != sva_ops)
2568 handle->ops = sva_ops;
2571 EXPORT_SYMBOL_GPL(iommu_sva_set_ops);
2573 int iommu_sva_get_pasid(struct iommu_sva *handle)
2575 const struct iommu_ops *ops = handle->dev->bus->iommu_ops;
2577 if (!ops || !ops->sva_get_pasid)
2578 return IOMMU_PASID_INVALID;
2580 return ops->sva_get_pasid(handle);
2582 EXPORT_SYMBOL_GPL(iommu_sva_get_pasid);