Back to home page

OSCL-LXR

 
 

    


0001 // SPDX-License-Identifier: GPL-2.0-only
0002 /*
0003  * Copyright (C) 2007-2008 Advanced Micro Devices, Inc.
0004  * Author: Joerg Roedel <jroedel@suse.de>
0005  */
0006 
0007 #define pr_fmt(fmt)    "iommu: " fmt
0008 
0009 #include <linux/device.h>
0010 #include <linux/dma-iommu.h>
0011 #include <linux/kernel.h>
0012 #include <linux/bits.h>
0013 #include <linux/bug.h>
0014 #include <linux/types.h>
0015 #include <linux/init.h>
0016 #include <linux/export.h>
0017 #include <linux/slab.h>
0018 #include <linux/errno.h>
0019 #include <linux/iommu.h>
0020 #include <linux/idr.h>
0021 #include <linux/err.h>
0022 #include <linux/pci.h>
0023 #include <linux/bitops.h>
0024 #include <linux/property.h>
0025 #include <linux/fsl/mc.h>
0026 #include <linux/module.h>
0027 #include <linux/cc_platform.h>
0028 #include <trace/events/iommu.h>
0029 
0030 static struct kset *iommu_group_kset;
0031 static DEFINE_IDA(iommu_group_ida);
0032 
0033 static unsigned int iommu_def_domain_type __read_mostly;
0034 static bool iommu_dma_strict __read_mostly = IS_ENABLED(CONFIG_IOMMU_DEFAULT_DMA_STRICT);
0035 static u32 iommu_cmd_line __read_mostly;
0036 
0037 struct iommu_group {
0038     struct kobject kobj;
0039     struct kobject *devices_kobj;
0040     struct list_head devices;
0041     struct mutex mutex;
0042     void *iommu_data;
0043     void (*iommu_data_release)(void *iommu_data);
0044     char *name;
0045     int id;
0046     struct iommu_domain *default_domain;
0047     struct iommu_domain *blocking_domain;
0048     struct iommu_domain *domain;
0049     struct list_head entry;
0050     unsigned int owner_cnt;
0051     void *owner;
0052 };
0053 
0054 struct group_device {
0055     struct list_head list;
0056     struct device *dev;
0057     char *name;
0058 };
0059 
0060 struct iommu_group_attribute {
0061     struct attribute attr;
0062     ssize_t (*show)(struct iommu_group *group, char *buf);
0063     ssize_t (*store)(struct iommu_group *group,
0064              const char *buf, size_t count);
0065 };
0066 
0067 static const char * const iommu_group_resv_type_string[] = {
0068     [IOMMU_RESV_DIRECT]         = "direct",
0069     [IOMMU_RESV_DIRECT_RELAXABLE]       = "direct-relaxable",
0070     [IOMMU_RESV_RESERVED]           = "reserved",
0071     [IOMMU_RESV_MSI]            = "msi",
0072     [IOMMU_RESV_SW_MSI]         = "msi",
0073 };
0074 
0075 #define IOMMU_CMD_LINE_DMA_API      BIT(0)
0076 #define IOMMU_CMD_LINE_STRICT       BIT(1)
0077 
0078 static int iommu_alloc_default_domain(struct iommu_group *group,
0079                       struct device *dev);
0080 static struct iommu_domain *__iommu_domain_alloc(struct bus_type *bus,
0081                          unsigned type);
0082 static int __iommu_attach_device(struct iommu_domain *domain,
0083                  struct device *dev);
0084 static int __iommu_attach_group(struct iommu_domain *domain,
0085                 struct iommu_group *group);
0086 static int __iommu_group_set_domain(struct iommu_group *group,
0087                     struct iommu_domain *new_domain);
0088 static int iommu_create_device_direct_mappings(struct iommu_group *group,
0089                            struct device *dev);
0090 static struct iommu_group *iommu_group_get_for_dev(struct device *dev);
0091 static ssize_t iommu_group_store_type(struct iommu_group *group,
0092                       const char *buf, size_t count);
0093 
0094 #define IOMMU_GROUP_ATTR(_name, _mode, _show, _store)       \
0095 struct iommu_group_attribute iommu_group_attr_##_name =     \
0096     __ATTR(_name, _mode, _show, _store)
0097 
0098 #define to_iommu_group_attr(_attr)  \
0099     container_of(_attr, struct iommu_group_attribute, attr)
0100 #define to_iommu_group(_kobj)       \
0101     container_of(_kobj, struct iommu_group, kobj)
0102 
0103 static LIST_HEAD(iommu_device_list);
0104 static DEFINE_SPINLOCK(iommu_device_lock);
0105 
0106 /*
0107  * Use a function instead of an array here because the domain-type is a
0108  * bit-field, so an array would waste memory.
0109  */
0110 static const char *iommu_domain_type_str(unsigned int t)
0111 {
0112     switch (t) {
0113     case IOMMU_DOMAIN_BLOCKED:
0114         return "Blocked";
0115     case IOMMU_DOMAIN_IDENTITY:
0116         return "Passthrough";
0117     case IOMMU_DOMAIN_UNMANAGED:
0118         return "Unmanaged";
0119     case IOMMU_DOMAIN_DMA:
0120     case IOMMU_DOMAIN_DMA_FQ:
0121         return "Translated";
0122     default:
0123         return "Unknown";
0124     }
0125 }
0126 
0127 static int __init iommu_subsys_init(void)
0128 {
0129     if (!(iommu_cmd_line & IOMMU_CMD_LINE_DMA_API)) {
0130         if (IS_ENABLED(CONFIG_IOMMU_DEFAULT_PASSTHROUGH))
0131             iommu_set_default_passthrough(false);
0132         else
0133             iommu_set_default_translated(false);
0134 
0135         if (iommu_default_passthrough() && cc_platform_has(CC_ATTR_MEM_ENCRYPT)) {
0136             pr_info("Memory encryption detected - Disabling default IOMMU Passthrough\n");
0137             iommu_set_default_translated(false);
0138         }
0139     }
0140 
0141     if (!iommu_default_passthrough() && !iommu_dma_strict)
0142         iommu_def_domain_type = IOMMU_DOMAIN_DMA_FQ;
0143 
0144     pr_info("Default domain type: %s %s\n",
0145         iommu_domain_type_str(iommu_def_domain_type),
0146         (iommu_cmd_line & IOMMU_CMD_LINE_DMA_API) ?
0147             "(set via kernel command line)" : "");
0148 
0149     if (!iommu_default_passthrough())
0150         pr_info("DMA domain TLB invalidation policy: %s mode %s\n",
0151             iommu_dma_strict ? "strict" : "lazy",
0152             (iommu_cmd_line & IOMMU_CMD_LINE_STRICT) ?
0153                 "(set via kernel command line)" : "");
0154 
0155     return 0;
0156 }
0157 subsys_initcall(iommu_subsys_init);
0158 
0159 /**
0160  * iommu_device_register() - Register an IOMMU hardware instance
0161  * @iommu: IOMMU handle for the instance
0162  * @ops:   IOMMU ops to associate with the instance
0163  * @hwdev: (optional) actual instance device, used for fwnode lookup
0164  *
0165  * Return: 0 on success, or an error.
0166  */
0167 int iommu_device_register(struct iommu_device *iommu,
0168               const struct iommu_ops *ops, struct device *hwdev)
0169 {
0170     /* We need to be able to take module references appropriately */
0171     if (WARN_ON(is_module_address((unsigned long)ops) && !ops->owner))
0172         return -EINVAL;
0173 
0174     iommu->ops = ops;
0175     if (hwdev)
0176         iommu->fwnode = hwdev->fwnode;
0177 
0178     spin_lock(&iommu_device_lock);
0179     list_add_tail(&iommu->list, &iommu_device_list);
0180     spin_unlock(&iommu_device_lock);
0181     return 0;
0182 }
0183 EXPORT_SYMBOL_GPL(iommu_device_register);
0184 
0185 void iommu_device_unregister(struct iommu_device *iommu)
0186 {
0187     spin_lock(&iommu_device_lock);
0188     list_del(&iommu->list);
0189     spin_unlock(&iommu_device_lock);
0190 }
0191 EXPORT_SYMBOL_GPL(iommu_device_unregister);
0192 
0193 static struct dev_iommu *dev_iommu_get(struct device *dev)
0194 {
0195     struct dev_iommu *param = dev->iommu;
0196 
0197     if (param)
0198         return param;
0199 
0200     param = kzalloc(sizeof(*param), GFP_KERNEL);
0201     if (!param)
0202         return NULL;
0203 
0204     mutex_init(&param->lock);
0205     dev->iommu = param;
0206     return param;
0207 }
0208 
0209 static void dev_iommu_free(struct device *dev)
0210 {
0211     struct dev_iommu *param = dev->iommu;
0212 
0213     dev->iommu = NULL;
0214     if (param->fwspec) {
0215         fwnode_handle_put(param->fwspec->iommu_fwnode);
0216         kfree(param->fwspec);
0217     }
0218     kfree(param);
0219 }
0220 
0221 static int __iommu_probe_device(struct device *dev, struct list_head *group_list)
0222 {
0223     const struct iommu_ops *ops = dev->bus->iommu_ops;
0224     struct iommu_device *iommu_dev;
0225     struct iommu_group *group;
0226     int ret;
0227 
0228     if (!ops)
0229         return -ENODEV;
0230 
0231     if (!dev_iommu_get(dev))
0232         return -ENOMEM;
0233 
0234     if (!try_module_get(ops->owner)) {
0235         ret = -EINVAL;
0236         goto err_free;
0237     }
0238 
0239     iommu_dev = ops->probe_device(dev);
0240     if (IS_ERR(iommu_dev)) {
0241         ret = PTR_ERR(iommu_dev);
0242         goto out_module_put;
0243     }
0244 
0245     dev->iommu->iommu_dev = iommu_dev;
0246 
0247     group = iommu_group_get_for_dev(dev);
0248     if (IS_ERR(group)) {
0249         ret = PTR_ERR(group);
0250         goto out_release;
0251     }
0252     iommu_group_put(group);
0253 
0254     if (group_list && !group->default_domain && list_empty(&group->entry))
0255         list_add_tail(&group->entry, group_list);
0256 
0257     iommu_device_link(iommu_dev, dev);
0258 
0259     return 0;
0260 
0261 out_release:
0262     if (ops->release_device)
0263         ops->release_device(dev);
0264 
0265 out_module_put:
0266     module_put(ops->owner);
0267 
0268 err_free:
0269     dev_iommu_free(dev);
0270 
0271     return ret;
0272 }
0273 
0274 int iommu_probe_device(struct device *dev)
0275 {
0276     const struct iommu_ops *ops;
0277     struct iommu_group *group;
0278     int ret;
0279 
0280     ret = __iommu_probe_device(dev, NULL);
0281     if (ret)
0282         goto err_out;
0283 
0284     group = iommu_group_get(dev);
0285     if (!group) {
0286         ret = -ENODEV;
0287         goto err_release;
0288     }
0289 
0290     /*
0291      * Try to allocate a default domain - needs support from the
0292      * IOMMU driver. There are still some drivers which don't
0293      * support default domains, so the return value is not yet
0294      * checked.
0295      */
0296     mutex_lock(&group->mutex);
0297     iommu_alloc_default_domain(group, dev);
0298 
0299     /*
0300      * If device joined an existing group which has been claimed, don't
0301      * attach the default domain.
0302      */
0303     if (group->default_domain && !group->owner) {
0304         ret = __iommu_attach_device(group->default_domain, dev);
0305         if (ret) {
0306             mutex_unlock(&group->mutex);
0307             iommu_group_put(group);
0308             goto err_release;
0309         }
0310     }
0311 
0312     iommu_create_device_direct_mappings(group, dev);
0313 
0314     mutex_unlock(&group->mutex);
0315     iommu_group_put(group);
0316 
0317     ops = dev_iommu_ops(dev);
0318     if (ops->probe_finalize)
0319         ops->probe_finalize(dev);
0320 
0321     return 0;
0322 
0323 err_release:
0324     iommu_release_device(dev);
0325 
0326 err_out:
0327     return ret;
0328 
0329 }
0330 
0331 void iommu_release_device(struct device *dev)
0332 {
0333     const struct iommu_ops *ops;
0334 
0335     if (!dev->iommu)
0336         return;
0337 
0338     iommu_device_unlink(dev->iommu->iommu_dev, dev);
0339 
0340     ops = dev_iommu_ops(dev);
0341     if (ops->release_device)
0342         ops->release_device(dev);
0343 
0344     iommu_group_remove_device(dev);
0345     module_put(ops->owner);
0346     dev_iommu_free(dev);
0347 }
0348 
0349 static int __init iommu_set_def_domain_type(char *str)
0350 {
0351     bool pt;
0352     int ret;
0353 
0354     ret = kstrtobool(str, &pt);
0355     if (ret)
0356         return ret;
0357 
0358     if (pt)
0359         iommu_set_default_passthrough(true);
0360     else
0361         iommu_set_default_translated(true);
0362 
0363     return 0;
0364 }
0365 early_param("iommu.passthrough", iommu_set_def_domain_type);
0366 
0367 static int __init iommu_dma_setup(char *str)
0368 {
0369     int ret = kstrtobool(str, &iommu_dma_strict);
0370 
0371     if (!ret)
0372         iommu_cmd_line |= IOMMU_CMD_LINE_STRICT;
0373     return ret;
0374 }
0375 early_param("iommu.strict", iommu_dma_setup);
0376 
0377 void iommu_set_dma_strict(void)
0378 {
0379     iommu_dma_strict = true;
0380     if (iommu_def_domain_type == IOMMU_DOMAIN_DMA_FQ)
0381         iommu_def_domain_type = IOMMU_DOMAIN_DMA;
0382 }
0383 
0384 static ssize_t iommu_group_attr_show(struct kobject *kobj,
0385                      struct attribute *__attr, char *buf)
0386 {
0387     struct iommu_group_attribute *attr = to_iommu_group_attr(__attr);
0388     struct iommu_group *group = to_iommu_group(kobj);
0389     ssize_t ret = -EIO;
0390 
0391     if (attr->show)
0392         ret = attr->show(group, buf);
0393     return ret;
0394 }
0395 
0396 static ssize_t iommu_group_attr_store(struct kobject *kobj,
0397                       struct attribute *__attr,
0398                       const char *buf, size_t count)
0399 {
0400     struct iommu_group_attribute *attr = to_iommu_group_attr(__attr);
0401     struct iommu_group *group = to_iommu_group(kobj);
0402     ssize_t ret = -EIO;
0403 
0404     if (attr->store)
0405         ret = attr->store(group, buf, count);
0406     return ret;
0407 }
0408 
0409 static const struct sysfs_ops iommu_group_sysfs_ops = {
0410     .show = iommu_group_attr_show,
0411     .store = iommu_group_attr_store,
0412 };
0413 
0414 static int iommu_group_create_file(struct iommu_group *group,
0415                    struct iommu_group_attribute *attr)
0416 {
0417     return sysfs_create_file(&group->kobj, &attr->attr);
0418 }
0419 
0420 static void iommu_group_remove_file(struct iommu_group *group,
0421                     struct iommu_group_attribute *attr)
0422 {
0423     sysfs_remove_file(&group->kobj, &attr->attr);
0424 }
0425 
0426 static ssize_t iommu_group_show_name(struct iommu_group *group, char *buf)
0427 {
0428     return sprintf(buf, "%s\n", group->name);
0429 }
0430 
0431 /**
0432  * iommu_insert_resv_region - Insert a new region in the
0433  * list of reserved regions.
0434  * @new: new region to insert
0435  * @regions: list of regions
0436  *
0437  * Elements are sorted by start address and overlapping segments
0438  * of the same type are merged.
0439  */
0440 static int iommu_insert_resv_region(struct iommu_resv_region *new,
0441                     struct list_head *regions)
0442 {
0443     struct iommu_resv_region *iter, *tmp, *nr, *top;
0444     LIST_HEAD(stack);
0445 
0446     nr = iommu_alloc_resv_region(new->start, new->length,
0447                      new->prot, new->type);
0448     if (!nr)
0449         return -ENOMEM;
0450 
0451     /* First add the new element based on start address sorting */
0452     list_for_each_entry(iter, regions, list) {
0453         if (nr->start < iter->start ||
0454             (nr->start == iter->start && nr->type <= iter->type))
0455             break;
0456     }
0457     list_add_tail(&nr->list, &iter->list);
0458 
0459     /* Merge overlapping segments of type nr->type in @regions, if any */
0460     list_for_each_entry_safe(iter, tmp, regions, list) {
0461         phys_addr_t top_end, iter_end = iter->start + iter->length - 1;
0462 
0463         /* no merge needed on elements of different types than @new */
0464         if (iter->type != new->type) {
0465             list_move_tail(&iter->list, &stack);
0466             continue;
0467         }
0468 
0469         /* look for the last stack element of same type as @iter */
0470         list_for_each_entry_reverse(top, &stack, list)
0471             if (top->type == iter->type)
0472                 goto check_overlap;
0473 
0474         list_move_tail(&iter->list, &stack);
0475         continue;
0476 
0477 check_overlap:
0478         top_end = top->start + top->length - 1;
0479 
0480         if (iter->start > top_end + 1) {
0481             list_move_tail(&iter->list, &stack);
0482         } else {
0483             top->length = max(top_end, iter_end) - top->start + 1;
0484             list_del(&iter->list);
0485             kfree(iter);
0486         }
0487     }
0488     list_splice(&stack, regions);
0489     return 0;
0490 }
0491 
0492 static int
0493 iommu_insert_device_resv_regions(struct list_head *dev_resv_regions,
0494                  struct list_head *group_resv_regions)
0495 {
0496     struct iommu_resv_region *entry;
0497     int ret = 0;
0498 
0499     list_for_each_entry(entry, dev_resv_regions, list) {
0500         ret = iommu_insert_resv_region(entry, group_resv_regions);
0501         if (ret)
0502             break;
0503     }
0504     return ret;
0505 }
0506 
0507 int iommu_get_group_resv_regions(struct iommu_group *group,
0508                  struct list_head *head)
0509 {
0510     struct group_device *device;
0511     int ret = 0;
0512 
0513     mutex_lock(&group->mutex);
0514     list_for_each_entry(device, &group->devices, list) {
0515         struct list_head dev_resv_regions;
0516 
0517         /*
0518          * Non-API groups still expose reserved_regions in sysfs,
0519          * so filter out calls that get here that way.
0520          */
0521         if (!device->dev->iommu)
0522             break;
0523 
0524         INIT_LIST_HEAD(&dev_resv_regions);
0525         iommu_get_resv_regions(device->dev, &dev_resv_regions);
0526         ret = iommu_insert_device_resv_regions(&dev_resv_regions, head);
0527         iommu_put_resv_regions(device->dev, &dev_resv_regions);
0528         if (ret)
0529             break;
0530     }
0531     mutex_unlock(&group->mutex);
0532     return ret;
0533 }
0534 EXPORT_SYMBOL_GPL(iommu_get_group_resv_regions);
0535 
0536 static ssize_t iommu_group_show_resv_regions(struct iommu_group *group,
0537                          char *buf)
0538 {
0539     struct iommu_resv_region *region, *next;
0540     struct list_head group_resv_regions;
0541     char *str = buf;
0542 
0543     INIT_LIST_HEAD(&group_resv_regions);
0544     iommu_get_group_resv_regions(group, &group_resv_regions);
0545 
0546     list_for_each_entry_safe(region, next, &group_resv_regions, list) {
0547         str += sprintf(str, "0x%016llx 0x%016llx %s\n",
0548                    (long long int)region->start,
0549                    (long long int)(region->start +
0550                         region->length - 1),
0551                    iommu_group_resv_type_string[region->type]);
0552         kfree(region);
0553     }
0554 
0555     return (str - buf);
0556 }
0557 
0558 static ssize_t iommu_group_show_type(struct iommu_group *group,
0559                      char *buf)
0560 {
0561     char *type = "unknown\n";
0562 
0563     mutex_lock(&group->mutex);
0564     if (group->default_domain) {
0565         switch (group->default_domain->type) {
0566         case IOMMU_DOMAIN_BLOCKED:
0567             type = "blocked\n";
0568             break;
0569         case IOMMU_DOMAIN_IDENTITY:
0570             type = "identity\n";
0571             break;
0572         case IOMMU_DOMAIN_UNMANAGED:
0573             type = "unmanaged\n";
0574             break;
0575         case IOMMU_DOMAIN_DMA:
0576             type = "DMA\n";
0577             break;
0578         case IOMMU_DOMAIN_DMA_FQ:
0579             type = "DMA-FQ\n";
0580             break;
0581         }
0582     }
0583     mutex_unlock(&group->mutex);
0584     strcpy(buf, type);
0585 
0586     return strlen(type);
0587 }
0588 
0589 static IOMMU_GROUP_ATTR(name, S_IRUGO, iommu_group_show_name, NULL);
0590 
0591 static IOMMU_GROUP_ATTR(reserved_regions, 0444,
0592             iommu_group_show_resv_regions, NULL);
0593 
0594 static IOMMU_GROUP_ATTR(type, 0644, iommu_group_show_type,
0595             iommu_group_store_type);
0596 
0597 static void iommu_group_release(struct kobject *kobj)
0598 {
0599     struct iommu_group *group = to_iommu_group(kobj);
0600 
0601     pr_debug("Releasing group %d\n", group->id);
0602 
0603     if (group->iommu_data_release)
0604         group->iommu_data_release(group->iommu_data);
0605 
0606     ida_free(&iommu_group_ida, group->id);
0607 
0608     if (group->default_domain)
0609         iommu_domain_free(group->default_domain);
0610     if (group->blocking_domain)
0611         iommu_domain_free(group->blocking_domain);
0612 
0613     kfree(group->name);
0614     kfree(group);
0615 }
0616 
0617 static struct kobj_type iommu_group_ktype = {
0618     .sysfs_ops = &iommu_group_sysfs_ops,
0619     .release = iommu_group_release,
0620 };
0621 
0622 /**
0623  * iommu_group_alloc - Allocate a new group
0624  *
0625  * This function is called by an iommu driver to allocate a new iommu
0626  * group.  The iommu group represents the minimum granularity of the iommu.
0627  * Upon successful return, the caller holds a reference to the supplied
0628  * group in order to hold the group until devices are added.  Use
0629  * iommu_group_put() to release this extra reference count, allowing the
0630  * group to be automatically reclaimed once it has no devices or external
0631  * references.
0632  */
0633 struct iommu_group *iommu_group_alloc(void)
0634 {
0635     struct iommu_group *group;
0636     int ret;
0637 
0638     group = kzalloc(sizeof(*group), GFP_KERNEL);
0639     if (!group)
0640         return ERR_PTR(-ENOMEM);
0641 
0642     group->kobj.kset = iommu_group_kset;
0643     mutex_init(&group->mutex);
0644     INIT_LIST_HEAD(&group->devices);
0645     INIT_LIST_HEAD(&group->entry);
0646 
0647     ret = ida_alloc(&iommu_group_ida, GFP_KERNEL);
0648     if (ret < 0) {
0649         kfree(group);
0650         return ERR_PTR(ret);
0651     }
0652     group->id = ret;
0653 
0654     ret = kobject_init_and_add(&group->kobj, &iommu_group_ktype,
0655                    NULL, "%d", group->id);
0656     if (ret) {
0657         ida_free(&iommu_group_ida, group->id);
0658         kobject_put(&group->kobj);
0659         return ERR_PTR(ret);
0660     }
0661 
0662     group->devices_kobj = kobject_create_and_add("devices", &group->kobj);
0663     if (!group->devices_kobj) {
0664         kobject_put(&group->kobj); /* triggers .release & free */
0665         return ERR_PTR(-ENOMEM);
0666     }
0667 
0668     /*
0669      * The devices_kobj holds a reference on the group kobject, so
0670      * as long as that exists so will the group.  We can therefore
0671      * use the devices_kobj for reference counting.
0672      */
0673     kobject_put(&group->kobj);
0674 
0675     ret = iommu_group_create_file(group,
0676                       &iommu_group_attr_reserved_regions);
0677     if (ret)
0678         return ERR_PTR(ret);
0679 
0680     ret = iommu_group_create_file(group, &iommu_group_attr_type);
0681     if (ret)
0682         return ERR_PTR(ret);
0683 
0684     pr_debug("Allocated group %d\n", group->id);
0685 
0686     return group;
0687 }
0688 EXPORT_SYMBOL_GPL(iommu_group_alloc);
0689 
0690 struct iommu_group *iommu_group_get_by_id(int id)
0691 {
0692     struct kobject *group_kobj;
0693     struct iommu_group *group;
0694     const char *name;
0695 
0696     if (!iommu_group_kset)
0697         return NULL;
0698 
0699     name = kasprintf(GFP_KERNEL, "%d", id);
0700     if (!name)
0701         return NULL;
0702 
0703     group_kobj = kset_find_obj(iommu_group_kset, name);
0704     kfree(name);
0705 
0706     if (!group_kobj)
0707         return NULL;
0708 
0709     group = container_of(group_kobj, struct iommu_group, kobj);
0710     BUG_ON(group->id != id);
0711 
0712     kobject_get(group->devices_kobj);
0713     kobject_put(&group->kobj);
0714 
0715     return group;
0716 }
0717 EXPORT_SYMBOL_GPL(iommu_group_get_by_id);
0718 
0719 /**
0720  * iommu_group_get_iommudata - retrieve iommu_data registered for a group
0721  * @group: the group
0722  *
0723  * iommu drivers can store data in the group for use when doing iommu
0724  * operations.  This function provides a way to retrieve it.  Caller
0725  * should hold a group reference.
0726  */
0727 void *iommu_group_get_iommudata(struct iommu_group *group)
0728 {
0729     return group->iommu_data;
0730 }
0731 EXPORT_SYMBOL_GPL(iommu_group_get_iommudata);
0732 
0733 /**
0734  * iommu_group_set_iommudata - set iommu_data for a group
0735  * @group: the group
0736  * @iommu_data: new data
0737  * @release: release function for iommu_data
0738  *
0739  * iommu drivers can store data in the group for use when doing iommu
0740  * operations.  This function provides a way to set the data after
0741  * the group has been allocated.  Caller should hold a group reference.
0742  */
0743 void iommu_group_set_iommudata(struct iommu_group *group, void *iommu_data,
0744                    void (*release)(void *iommu_data))
0745 {
0746     group->iommu_data = iommu_data;
0747     group->iommu_data_release = release;
0748 }
0749 EXPORT_SYMBOL_GPL(iommu_group_set_iommudata);
0750 
0751 /**
0752  * iommu_group_set_name - set name for a group
0753  * @group: the group
0754  * @name: name
0755  *
0756  * Allow iommu driver to set a name for a group.  When set it will
0757  * appear in a name attribute file under the group in sysfs.
0758  */
0759 int iommu_group_set_name(struct iommu_group *group, const char *name)
0760 {
0761     int ret;
0762 
0763     if (group->name) {
0764         iommu_group_remove_file(group, &iommu_group_attr_name);
0765         kfree(group->name);
0766         group->name = NULL;
0767         if (!name)
0768             return 0;
0769     }
0770 
0771     group->name = kstrdup(name, GFP_KERNEL);
0772     if (!group->name)
0773         return -ENOMEM;
0774 
0775     ret = iommu_group_create_file(group, &iommu_group_attr_name);
0776     if (ret) {
0777         kfree(group->name);
0778         group->name = NULL;
0779         return ret;
0780     }
0781 
0782     return 0;
0783 }
0784 EXPORT_SYMBOL_GPL(iommu_group_set_name);
0785 
0786 static int iommu_create_device_direct_mappings(struct iommu_group *group,
0787                            struct device *dev)
0788 {
0789     struct iommu_domain *domain = group->default_domain;
0790     struct iommu_resv_region *entry;
0791     struct list_head mappings;
0792     unsigned long pg_size;
0793     int ret = 0;
0794 
0795     if (!domain || !iommu_is_dma_domain(domain))
0796         return 0;
0797 
0798     BUG_ON(!domain->pgsize_bitmap);
0799 
0800     pg_size = 1UL << __ffs(domain->pgsize_bitmap);
0801     INIT_LIST_HEAD(&mappings);
0802 
0803     iommu_get_resv_regions(dev, &mappings);
0804 
0805     /* We need to consider overlapping regions for different devices */
0806     list_for_each_entry(entry, &mappings, list) {
0807         dma_addr_t start, end, addr;
0808         size_t map_size = 0;
0809 
0810         start = ALIGN(entry->start, pg_size);
0811         end   = ALIGN(entry->start + entry->length, pg_size);
0812 
0813         if (entry->type != IOMMU_RESV_DIRECT &&
0814             entry->type != IOMMU_RESV_DIRECT_RELAXABLE)
0815             continue;
0816 
0817         for (addr = start; addr <= end; addr += pg_size) {
0818             phys_addr_t phys_addr;
0819 
0820             if (addr == end)
0821                 goto map_end;
0822 
0823             phys_addr = iommu_iova_to_phys(domain, addr);
0824             if (!phys_addr) {
0825                 map_size += pg_size;
0826                 continue;
0827             }
0828 
0829 map_end:
0830             if (map_size) {
0831                 ret = iommu_map(domain, addr - map_size,
0832                         addr - map_size, map_size,
0833                         entry->prot);
0834                 if (ret)
0835                     goto out;
0836                 map_size = 0;
0837             }
0838         }
0839 
0840     }
0841 
0842     iommu_flush_iotlb_all(domain);
0843 
0844 out:
0845     iommu_put_resv_regions(dev, &mappings);
0846 
0847     return ret;
0848 }
0849 
0850 static bool iommu_is_attach_deferred(struct device *dev)
0851 {
0852     const struct iommu_ops *ops = dev_iommu_ops(dev);
0853 
0854     if (ops->is_attach_deferred)
0855         return ops->is_attach_deferred(dev);
0856 
0857     return false;
0858 }
0859 
0860 /**
0861  * iommu_group_add_device - add a device to an iommu group
0862  * @group: the group into which to add the device (reference should be held)
0863  * @dev: the device
0864  *
0865  * This function is called by an iommu driver to add a device into a
0866  * group.  Adding a device increments the group reference count.
0867  */
0868 int iommu_group_add_device(struct iommu_group *group, struct device *dev)
0869 {
0870     int ret, i = 0;
0871     struct group_device *device;
0872 
0873     device = kzalloc(sizeof(*device), GFP_KERNEL);
0874     if (!device)
0875         return -ENOMEM;
0876 
0877     device->dev = dev;
0878 
0879     ret = sysfs_create_link(&dev->kobj, &group->kobj, "iommu_group");
0880     if (ret)
0881         goto err_free_device;
0882 
0883     device->name = kasprintf(GFP_KERNEL, "%s", kobject_name(&dev->kobj));
0884 rename:
0885     if (!device->name) {
0886         ret = -ENOMEM;
0887         goto err_remove_link;
0888     }
0889 
0890     ret = sysfs_create_link_nowarn(group->devices_kobj,
0891                        &dev->kobj, device->name);
0892     if (ret) {
0893         if (ret == -EEXIST && i >= 0) {
0894             /*
0895              * Account for the slim chance of collision
0896              * and append an instance to the name.
0897              */
0898             kfree(device->name);
0899             device->name = kasprintf(GFP_KERNEL, "%s.%d",
0900                          kobject_name(&dev->kobj), i++);
0901             goto rename;
0902         }
0903         goto err_free_name;
0904     }
0905 
0906     kobject_get(group->devices_kobj);
0907 
0908     dev->iommu_group = group;
0909 
0910     mutex_lock(&group->mutex);
0911     list_add_tail(&device->list, &group->devices);
0912     if (group->domain  && !iommu_is_attach_deferred(dev))
0913         ret = __iommu_attach_device(group->domain, dev);
0914     mutex_unlock(&group->mutex);
0915     if (ret)
0916         goto err_put_group;
0917 
0918     trace_add_device_to_group(group->id, dev);
0919 
0920     dev_info(dev, "Adding to iommu group %d\n", group->id);
0921 
0922     return 0;
0923 
0924 err_put_group:
0925     mutex_lock(&group->mutex);
0926     list_del(&device->list);
0927     mutex_unlock(&group->mutex);
0928     dev->iommu_group = NULL;
0929     kobject_put(group->devices_kobj);
0930     sysfs_remove_link(group->devices_kobj, device->name);
0931 err_free_name:
0932     kfree(device->name);
0933 err_remove_link:
0934     sysfs_remove_link(&dev->kobj, "iommu_group");
0935 err_free_device:
0936     kfree(device);
0937     dev_err(dev, "Failed to add to iommu group %d: %d\n", group->id, ret);
0938     return ret;
0939 }
0940 EXPORT_SYMBOL_GPL(iommu_group_add_device);
0941 
0942 /**
0943  * iommu_group_remove_device - remove a device from it's current group
0944  * @dev: device to be removed
0945  *
0946  * This function is called by an iommu driver to remove the device from
0947  * it's current group.  This decrements the iommu group reference count.
0948  */
0949 void iommu_group_remove_device(struct device *dev)
0950 {
0951     struct iommu_group *group = dev->iommu_group;
0952     struct group_device *tmp_device, *device = NULL;
0953 
0954     if (!group)
0955         return;
0956 
0957     dev_info(dev, "Removing from iommu group %d\n", group->id);
0958 
0959     mutex_lock(&group->mutex);
0960     list_for_each_entry(tmp_device, &group->devices, list) {
0961         if (tmp_device->dev == dev) {
0962             device = tmp_device;
0963             list_del(&device->list);
0964             break;
0965         }
0966     }
0967     mutex_unlock(&group->mutex);
0968 
0969     if (!device)
0970         return;
0971 
0972     sysfs_remove_link(group->devices_kobj, device->name);
0973     sysfs_remove_link(&dev->kobj, "iommu_group");
0974 
0975     trace_remove_device_from_group(group->id, dev);
0976 
0977     kfree(device->name);
0978     kfree(device);
0979     dev->iommu_group = NULL;
0980     kobject_put(group->devices_kobj);
0981 }
0982 EXPORT_SYMBOL_GPL(iommu_group_remove_device);
0983 
0984 static int iommu_group_device_count(struct iommu_group *group)
0985 {
0986     struct group_device *entry;
0987     int ret = 0;
0988 
0989     list_for_each_entry(entry, &group->devices, list)
0990         ret++;
0991 
0992     return ret;
0993 }
0994 
0995 static int __iommu_group_for_each_dev(struct iommu_group *group, void *data,
0996                       int (*fn)(struct device *, void *))
0997 {
0998     struct group_device *device;
0999     int ret = 0;
1000 
1001     list_for_each_entry(device, &group->devices, list) {
1002         ret = fn(device->dev, data);
1003         if (ret)
1004             break;
1005     }
1006     return ret;
1007 }
1008 
1009 /**
1010  * iommu_group_for_each_dev - iterate over each device in the group
1011  * @group: the group
1012  * @data: caller opaque data to be passed to callback function
1013  * @fn: caller supplied callback function
1014  *
1015  * This function is called by group users to iterate over group devices.
1016  * Callers should hold a reference count to the group during callback.
1017  * The group->mutex is held across callbacks, which will block calls to
1018  * iommu_group_add/remove_device.
1019  */
1020 int iommu_group_for_each_dev(struct iommu_group *group, void *data,
1021                  int (*fn)(struct device *, void *))
1022 {
1023     int ret;
1024 
1025     mutex_lock(&group->mutex);
1026     ret = __iommu_group_for_each_dev(group, data, fn);
1027     mutex_unlock(&group->mutex);
1028 
1029     return ret;
1030 }
1031 EXPORT_SYMBOL_GPL(iommu_group_for_each_dev);
1032 
1033 /**
1034  * iommu_group_get - Return the group for a device and increment reference
1035  * @dev: get the group that this device belongs to
1036  *
1037  * This function is called by iommu drivers and users to get the group
1038  * for the specified device.  If found, the group is returned and the group
1039  * reference in incremented, else NULL.
1040  */
1041 struct iommu_group *iommu_group_get(struct device *dev)
1042 {
1043     struct iommu_group *group = dev->iommu_group;
1044 
1045     if (group)
1046         kobject_get(group->devices_kobj);
1047 
1048     return group;
1049 }
1050 EXPORT_SYMBOL_GPL(iommu_group_get);
1051 
1052 /**
1053  * iommu_group_ref_get - Increment reference on a group
1054  * @group: the group to use, must not be NULL
1055  *
1056  * This function is called by iommu drivers to take additional references on an
1057  * existing group.  Returns the given group for convenience.
1058  */
1059 struct iommu_group *iommu_group_ref_get(struct iommu_group *group)
1060 {
1061     kobject_get(group->devices_kobj);
1062     return group;
1063 }
1064 EXPORT_SYMBOL_GPL(iommu_group_ref_get);
1065 
1066 /**
1067  * iommu_group_put - Decrement group reference
1068  * @group: the group to use
1069  *
1070  * This function is called by iommu drivers and users to release the
1071  * iommu group.  Once the reference count is zero, the group is released.
1072  */
1073 void iommu_group_put(struct iommu_group *group)
1074 {
1075     if (group)
1076         kobject_put(group->devices_kobj);
1077 }
1078 EXPORT_SYMBOL_GPL(iommu_group_put);
1079 
1080 /**
1081  * iommu_register_device_fault_handler() - Register a device fault handler
1082  * @dev: the device
1083  * @handler: the fault handler
1084  * @data: private data passed as argument to the handler
1085  *
1086  * When an IOMMU fault event is received, this handler gets called with the
1087  * fault event and data as argument. The handler should return 0 on success. If
1088  * the fault is recoverable (IOMMU_FAULT_PAGE_REQ), the consumer should also
1089  * complete the fault by calling iommu_page_response() with one of the following
1090  * response code:
1091  * - IOMMU_PAGE_RESP_SUCCESS: retry the translation
1092  * - IOMMU_PAGE_RESP_INVALID: terminate the fault
1093  * - IOMMU_PAGE_RESP_FAILURE: terminate the fault and stop reporting
1094  *   page faults if possible.
1095  *
1096  * Return 0 if the fault handler was installed successfully, or an error.
1097  */
1098 int iommu_register_device_fault_handler(struct device *dev,
1099                     iommu_dev_fault_handler_t handler,
1100                     void *data)
1101 {
1102     struct dev_iommu *param = dev->iommu;
1103     int ret = 0;
1104 
1105     if (!param)
1106         return -EINVAL;
1107 
1108     mutex_lock(&param->lock);
1109     /* Only allow one fault handler registered for each device */
1110     if (param->fault_param) {
1111         ret = -EBUSY;
1112         goto done_unlock;
1113     }
1114 
1115     get_device(dev);
1116     param->fault_param = kzalloc(sizeof(*param->fault_param), GFP_KERNEL);
1117     if (!param->fault_param) {
1118         put_device(dev);
1119         ret = -ENOMEM;
1120         goto done_unlock;
1121     }
1122     param->fault_param->handler = handler;
1123     param->fault_param->data = data;
1124     mutex_init(&param->fault_param->lock);
1125     INIT_LIST_HEAD(&param->fault_param->faults);
1126 
1127 done_unlock:
1128     mutex_unlock(&param->lock);
1129 
1130     return ret;
1131 }
1132 EXPORT_SYMBOL_GPL(iommu_register_device_fault_handler);
1133 
1134 /**
1135  * iommu_unregister_device_fault_handler() - Unregister the device fault handler
1136  * @dev: the device
1137  *
1138  * Remove the device fault handler installed with
1139  * iommu_register_device_fault_handler().
1140  *
1141  * Return 0 on success, or an error.
1142  */
1143 int iommu_unregister_device_fault_handler(struct device *dev)
1144 {
1145     struct dev_iommu *param = dev->iommu;
1146     int ret = 0;
1147 
1148     if (!param)
1149         return -EINVAL;
1150 
1151     mutex_lock(&param->lock);
1152 
1153     if (!param->fault_param)
1154         goto unlock;
1155 
1156     /* we cannot unregister handler if there are pending faults */
1157     if (!list_empty(&param->fault_param->faults)) {
1158         ret = -EBUSY;
1159         goto unlock;
1160     }
1161 
1162     kfree(param->fault_param);
1163     param->fault_param = NULL;
1164     put_device(dev);
1165 unlock:
1166     mutex_unlock(&param->lock);
1167 
1168     return ret;
1169 }
1170 EXPORT_SYMBOL_GPL(iommu_unregister_device_fault_handler);
1171 
1172 /**
1173  * iommu_report_device_fault() - Report fault event to device driver
1174  * @dev: the device
1175  * @evt: fault event data
1176  *
1177  * Called by IOMMU drivers when a fault is detected, typically in a threaded IRQ
1178  * handler. When this function fails and the fault is recoverable, it is the
1179  * caller's responsibility to complete the fault.
1180  *
1181  * Return 0 on success, or an error.
1182  */
1183 int iommu_report_device_fault(struct device *dev, struct iommu_fault_event *evt)
1184 {
1185     struct dev_iommu *param = dev->iommu;
1186     struct iommu_fault_event *evt_pending = NULL;
1187     struct iommu_fault_param *fparam;
1188     int ret = 0;
1189 
1190     if (!param || !evt)
1191         return -EINVAL;
1192 
1193     /* we only report device fault if there is a handler registered */
1194     mutex_lock(&param->lock);
1195     fparam = param->fault_param;
1196     if (!fparam || !fparam->handler) {
1197         ret = -EINVAL;
1198         goto done_unlock;
1199     }
1200 
1201     if (evt->fault.type == IOMMU_FAULT_PAGE_REQ &&
1202         (evt->fault.prm.flags & IOMMU_FAULT_PAGE_REQUEST_LAST_PAGE)) {
1203         evt_pending = kmemdup(evt, sizeof(struct iommu_fault_event),
1204                       GFP_KERNEL);
1205         if (!evt_pending) {
1206             ret = -ENOMEM;
1207             goto done_unlock;
1208         }
1209         mutex_lock(&fparam->lock);
1210         list_add_tail(&evt_pending->list, &fparam->faults);
1211         mutex_unlock(&fparam->lock);
1212     }
1213 
1214     ret = fparam->handler(&evt->fault, fparam->data);
1215     if (ret && evt_pending) {
1216         mutex_lock(&fparam->lock);
1217         list_del(&evt_pending->list);
1218         mutex_unlock(&fparam->lock);
1219         kfree(evt_pending);
1220     }
1221 done_unlock:
1222     mutex_unlock(&param->lock);
1223     return ret;
1224 }
1225 EXPORT_SYMBOL_GPL(iommu_report_device_fault);
1226 
1227 int iommu_page_response(struct device *dev,
1228             struct iommu_page_response *msg)
1229 {
1230     bool needs_pasid;
1231     int ret = -EINVAL;
1232     struct iommu_fault_event *evt;
1233     struct iommu_fault_page_request *prm;
1234     struct dev_iommu *param = dev->iommu;
1235     const struct iommu_ops *ops = dev_iommu_ops(dev);
1236     bool has_pasid = msg->flags & IOMMU_PAGE_RESP_PASID_VALID;
1237 
1238     if (!ops->page_response)
1239         return -ENODEV;
1240 
1241     if (!param || !param->fault_param)
1242         return -EINVAL;
1243 
1244     if (msg->version != IOMMU_PAGE_RESP_VERSION_1 ||
1245         msg->flags & ~IOMMU_PAGE_RESP_PASID_VALID)
1246         return -EINVAL;
1247 
1248     /* Only send response if there is a fault report pending */
1249     mutex_lock(&param->fault_param->lock);
1250     if (list_empty(&param->fault_param->faults)) {
1251         dev_warn_ratelimited(dev, "no pending PRQ, drop response\n");
1252         goto done_unlock;
1253     }
1254     /*
1255      * Check if we have a matching page request pending to respond,
1256      * otherwise return -EINVAL
1257      */
1258     list_for_each_entry(evt, &param->fault_param->faults, list) {
1259         prm = &evt->fault.prm;
1260         if (prm->grpid != msg->grpid)
1261             continue;
1262 
1263         /*
1264          * If the PASID is required, the corresponding request is
1265          * matched using the group ID, the PASID valid bit and the PASID
1266          * value. Otherwise only the group ID matches request and
1267          * response.
1268          */
1269         needs_pasid = prm->flags & IOMMU_FAULT_PAGE_RESPONSE_NEEDS_PASID;
1270         if (needs_pasid && (!has_pasid || msg->pasid != prm->pasid))
1271             continue;
1272 
1273         if (!needs_pasid && has_pasid) {
1274             /* No big deal, just clear it. */
1275             msg->flags &= ~IOMMU_PAGE_RESP_PASID_VALID;
1276             msg->pasid = 0;
1277         }
1278 
1279         ret = ops->page_response(dev, evt, msg);
1280         list_del(&evt->list);
1281         kfree(evt);
1282         break;
1283     }
1284 
1285 done_unlock:
1286     mutex_unlock(&param->fault_param->lock);
1287     return ret;
1288 }
1289 EXPORT_SYMBOL_GPL(iommu_page_response);
1290 
1291 /**
1292  * iommu_group_id - Return ID for a group
1293  * @group: the group to ID
1294  *
1295  * Return the unique ID for the group matching the sysfs group number.
1296  */
1297 int iommu_group_id(struct iommu_group *group)
1298 {
1299     return group->id;
1300 }
1301 EXPORT_SYMBOL_GPL(iommu_group_id);
1302 
1303 static struct iommu_group *get_pci_alias_group(struct pci_dev *pdev,
1304                            unsigned long *devfns);
1305 
1306 /*
1307  * To consider a PCI device isolated, we require ACS to support Source
1308  * Validation, Request Redirection, Completer Redirection, and Upstream
1309  * Forwarding.  This effectively means that devices cannot spoof their
1310  * requester ID, requests and completions cannot be redirected, and all
1311  * transactions are forwarded upstream, even as it passes through a
1312  * bridge where the target device is downstream.
1313  */
1314 #define REQ_ACS_FLAGS   (PCI_ACS_SV | PCI_ACS_RR | PCI_ACS_CR | PCI_ACS_UF)
1315 
1316 /*
1317  * For multifunction devices which are not isolated from each other, find
1318  * all the other non-isolated functions and look for existing groups.  For
1319  * each function, we also need to look for aliases to or from other devices
1320  * that may already have a group.
1321  */
1322 static struct iommu_group *get_pci_function_alias_group(struct pci_dev *pdev,
1323                             unsigned long *devfns)
1324 {
1325     struct pci_dev *tmp = NULL;
1326     struct iommu_group *group;
1327 
1328     if (!pdev->multifunction || pci_acs_enabled(pdev, REQ_ACS_FLAGS))
1329         return NULL;
1330 
1331     for_each_pci_dev(tmp) {
1332         if (tmp == pdev || tmp->bus != pdev->bus ||
1333             PCI_SLOT(tmp->devfn) != PCI_SLOT(pdev->devfn) ||
1334             pci_acs_enabled(tmp, REQ_ACS_FLAGS))
1335             continue;
1336 
1337         group = get_pci_alias_group(tmp, devfns);
1338         if (group) {
1339             pci_dev_put(tmp);
1340             return group;
1341         }
1342     }
1343 
1344     return NULL;
1345 }
1346 
1347 /*
1348  * Look for aliases to or from the given device for existing groups. DMA
1349  * aliases are only supported on the same bus, therefore the search
1350  * space is quite small (especially since we're really only looking at pcie
1351  * device, and therefore only expect multiple slots on the root complex or
1352  * downstream switch ports).  It's conceivable though that a pair of
1353  * multifunction devices could have aliases between them that would cause a
1354  * loop.  To prevent this, we use a bitmap to track where we've been.
1355  */
1356 static struct iommu_group *get_pci_alias_group(struct pci_dev *pdev,
1357                            unsigned long *devfns)
1358 {
1359     struct pci_dev *tmp = NULL;
1360     struct iommu_group *group;
1361 
1362     if (test_and_set_bit(pdev->devfn & 0xff, devfns))
1363         return NULL;
1364 
1365     group = iommu_group_get(&pdev->dev);
1366     if (group)
1367         return group;
1368 
1369     for_each_pci_dev(tmp) {
1370         if (tmp == pdev || tmp->bus != pdev->bus)
1371             continue;
1372 
1373         /* We alias them or they alias us */
1374         if (pci_devs_are_dma_aliases(pdev, tmp)) {
1375             group = get_pci_alias_group(tmp, devfns);
1376             if (group) {
1377                 pci_dev_put(tmp);
1378                 return group;
1379             }
1380 
1381             group = get_pci_function_alias_group(tmp, devfns);
1382             if (group) {
1383                 pci_dev_put(tmp);
1384                 return group;
1385             }
1386         }
1387     }
1388 
1389     return NULL;
1390 }
1391 
1392 struct group_for_pci_data {
1393     struct pci_dev *pdev;
1394     struct iommu_group *group;
1395 };
1396 
1397 /*
1398  * DMA alias iterator callback, return the last seen device.  Stop and return
1399  * the IOMMU group if we find one along the way.
1400  */
1401 static int get_pci_alias_or_group(struct pci_dev *pdev, u16 alias, void *opaque)
1402 {
1403     struct group_for_pci_data *data = opaque;
1404 
1405     data->pdev = pdev;
1406     data->group = iommu_group_get(&pdev->dev);
1407 
1408     return data->group != NULL;
1409 }
1410 
1411 /*
1412  * Generic device_group call-back function. It just allocates one
1413  * iommu-group per device.
1414  */
1415 struct iommu_group *generic_device_group(struct device *dev)
1416 {
1417     return iommu_group_alloc();
1418 }
1419 EXPORT_SYMBOL_GPL(generic_device_group);
1420 
1421 /*
1422  * Use standard PCI bus topology, isolation features, and DMA alias quirks
1423  * to find or create an IOMMU group for a device.
1424  */
1425 struct iommu_group *pci_device_group(struct device *dev)
1426 {
1427     struct pci_dev *pdev = to_pci_dev(dev);
1428     struct group_for_pci_data data;
1429     struct pci_bus *bus;
1430     struct iommu_group *group = NULL;
1431     u64 devfns[4] = { 0 };
1432 
1433     if (WARN_ON(!dev_is_pci(dev)))
1434         return ERR_PTR(-EINVAL);
1435 
1436     /*
1437      * Find the upstream DMA alias for the device.  A device must not
1438      * be aliased due to topology in order to have its own IOMMU group.
1439      * If we find an alias along the way that already belongs to a
1440      * group, use it.
1441      */
1442     if (pci_for_each_dma_alias(pdev, get_pci_alias_or_group, &data))
1443         return data.group;
1444 
1445     pdev = data.pdev;
1446 
1447     /*
1448      * Continue upstream from the point of minimum IOMMU granularity
1449      * due to aliases to the point where devices are protected from
1450      * peer-to-peer DMA by PCI ACS.  Again, if we find an existing
1451      * group, use it.
1452      */
1453     for (bus = pdev->bus; !pci_is_root_bus(bus); bus = bus->parent) {
1454         if (!bus->self)
1455             continue;
1456 
1457         if (pci_acs_path_enabled(bus->self, NULL, REQ_ACS_FLAGS))
1458             break;
1459 
1460         pdev = bus->self;
1461 
1462         group = iommu_group_get(&pdev->dev);
1463         if (group)
1464             return group;
1465     }
1466 
1467     /*
1468      * Look for existing groups on device aliases.  If we alias another
1469      * device or another device aliases us, use the same group.
1470      */
1471     group = get_pci_alias_group(pdev, (unsigned long *)devfns);
1472     if (group)
1473         return group;
1474 
1475     /*
1476      * Look for existing groups on non-isolated functions on the same
1477      * slot and aliases of those funcions, if any.  No need to clear
1478      * the search bitmap, the tested devfns are still valid.
1479      */
1480     group = get_pci_function_alias_group(pdev, (unsigned long *)devfns);
1481     if (group)
1482         return group;
1483 
1484     /* No shared group found, allocate new */
1485     return iommu_group_alloc();
1486 }
1487 EXPORT_SYMBOL_GPL(pci_device_group);
1488 
1489 /* Get the IOMMU group for device on fsl-mc bus */
1490 struct iommu_group *fsl_mc_device_group(struct device *dev)
1491 {
1492     struct device *cont_dev = fsl_mc_cont_dev(dev);
1493     struct iommu_group *group;
1494 
1495     group = iommu_group_get(cont_dev);
1496     if (!group)
1497         group = iommu_group_alloc();
1498     return group;
1499 }
1500 EXPORT_SYMBOL_GPL(fsl_mc_device_group);
1501 
1502 static int iommu_get_def_domain_type(struct device *dev)
1503 {
1504     const struct iommu_ops *ops = dev_iommu_ops(dev);
1505 
1506     if (dev_is_pci(dev) && to_pci_dev(dev)->untrusted)
1507         return IOMMU_DOMAIN_DMA;
1508 
1509     if (ops->def_domain_type)
1510         return ops->def_domain_type(dev);
1511 
1512     return 0;
1513 }
1514 
1515 static int iommu_group_alloc_default_domain(struct bus_type *bus,
1516                         struct iommu_group *group,
1517                         unsigned int type)
1518 {
1519     struct iommu_domain *dom;
1520 
1521     dom = __iommu_domain_alloc(bus, type);
1522     if (!dom && type != IOMMU_DOMAIN_DMA) {
1523         dom = __iommu_domain_alloc(bus, IOMMU_DOMAIN_DMA);
1524         if (dom)
1525             pr_warn("Failed to allocate default IOMMU domain of type %u for group %s - Falling back to IOMMU_DOMAIN_DMA",
1526                 type, group->name);
1527     }
1528 
1529     if (!dom)
1530         return -ENOMEM;
1531 
1532     group->default_domain = dom;
1533     if (!group->domain)
1534         group->domain = dom;
1535     return 0;
1536 }
1537 
1538 static int iommu_alloc_default_domain(struct iommu_group *group,
1539                       struct device *dev)
1540 {
1541     unsigned int type;
1542 
1543     if (group->default_domain)
1544         return 0;
1545 
1546     type = iommu_get_def_domain_type(dev) ? : iommu_def_domain_type;
1547 
1548     return iommu_group_alloc_default_domain(dev->bus, group, type);
1549 }
1550 
1551 /**
1552  * iommu_group_get_for_dev - Find or create the IOMMU group for a device
1553  * @dev: target device
1554  *
1555  * This function is intended to be called by IOMMU drivers and extended to
1556  * support common, bus-defined algorithms when determining or creating the
1557  * IOMMU group for a device.  On success, the caller will hold a reference
1558  * to the returned IOMMU group, which will already include the provided
1559  * device.  The reference should be released with iommu_group_put().
1560  */
1561 static struct iommu_group *iommu_group_get_for_dev(struct device *dev)
1562 {
1563     const struct iommu_ops *ops = dev_iommu_ops(dev);
1564     struct iommu_group *group;
1565     int ret;
1566 
1567     group = iommu_group_get(dev);
1568     if (group)
1569         return group;
1570 
1571     group = ops->device_group(dev);
1572     if (WARN_ON_ONCE(group == NULL))
1573         return ERR_PTR(-EINVAL);
1574 
1575     if (IS_ERR(group))
1576         return group;
1577 
1578     ret = iommu_group_add_device(group, dev);
1579     if (ret)
1580         goto out_put_group;
1581 
1582     return group;
1583 
1584 out_put_group:
1585     iommu_group_put(group);
1586 
1587     return ERR_PTR(ret);
1588 }
1589 
1590 struct iommu_domain *iommu_group_default_domain(struct iommu_group *group)
1591 {
1592     return group->default_domain;
1593 }
1594 
1595 static int probe_iommu_group(struct device *dev, void *data)
1596 {
1597     struct list_head *group_list = data;
1598     struct iommu_group *group;
1599     int ret;
1600 
1601     /* Device is probed already if in a group */
1602     group = iommu_group_get(dev);
1603     if (group) {
1604         iommu_group_put(group);
1605         return 0;
1606     }
1607 
1608     ret = __iommu_probe_device(dev, group_list);
1609     if (ret == -ENODEV)
1610         ret = 0;
1611 
1612     return ret;
1613 }
1614 
1615 static int remove_iommu_group(struct device *dev, void *data)
1616 {
1617     iommu_release_device(dev);
1618 
1619     return 0;
1620 }
1621 
1622 static int iommu_bus_notifier(struct notifier_block *nb,
1623                   unsigned long action, void *data)
1624 {
1625     struct device *dev = data;
1626 
1627     if (action == BUS_NOTIFY_ADD_DEVICE) {
1628         int ret;
1629 
1630         ret = iommu_probe_device(dev);
1631         return (ret) ? NOTIFY_DONE : NOTIFY_OK;
1632     } else if (action == BUS_NOTIFY_REMOVED_DEVICE) {
1633         iommu_release_device(dev);
1634         return NOTIFY_OK;
1635     }
1636 
1637     return 0;
1638 }
1639 
1640 struct __group_domain_type {
1641     struct device *dev;
1642     unsigned int type;
1643 };
1644 
1645 static int probe_get_default_domain_type(struct device *dev, void *data)
1646 {
1647     struct __group_domain_type *gtype = data;
1648     unsigned int type = iommu_get_def_domain_type(dev);
1649 
1650     if (type) {
1651         if (gtype->type && gtype->type != type) {
1652             dev_warn(dev, "Device needs domain type %s, but device %s in the same iommu group requires type %s - using default\n",
1653                  iommu_domain_type_str(type),
1654                  dev_name(gtype->dev),
1655                  iommu_domain_type_str(gtype->type));
1656             gtype->type = 0;
1657         }
1658 
1659         if (!gtype->dev) {
1660             gtype->dev  = dev;
1661             gtype->type = type;
1662         }
1663     }
1664 
1665     return 0;
1666 }
1667 
1668 static void probe_alloc_default_domain(struct bus_type *bus,
1669                        struct iommu_group *group)
1670 {
1671     struct __group_domain_type gtype;
1672 
1673     memset(&gtype, 0, sizeof(gtype));
1674 
1675     /* Ask for default domain requirements of all devices in the group */
1676     __iommu_group_for_each_dev(group, &gtype,
1677                    probe_get_default_domain_type);
1678 
1679     if (!gtype.type)
1680         gtype.type = iommu_def_domain_type;
1681 
1682     iommu_group_alloc_default_domain(bus, group, gtype.type);
1683 
1684 }
1685 
1686 static int iommu_group_do_dma_attach(struct device *dev, void *data)
1687 {
1688     struct iommu_domain *domain = data;
1689     int ret = 0;
1690 
1691     if (!iommu_is_attach_deferred(dev))
1692         ret = __iommu_attach_device(domain, dev);
1693 
1694     return ret;
1695 }
1696 
1697 static int __iommu_group_dma_attach(struct iommu_group *group)
1698 {
1699     return __iommu_group_for_each_dev(group, group->default_domain,
1700                       iommu_group_do_dma_attach);
1701 }
1702 
1703 static int iommu_group_do_probe_finalize(struct device *dev, void *data)
1704 {
1705     const struct iommu_ops *ops = dev_iommu_ops(dev);
1706 
1707     if (ops->probe_finalize)
1708         ops->probe_finalize(dev);
1709 
1710     return 0;
1711 }
1712 
1713 static void __iommu_group_dma_finalize(struct iommu_group *group)
1714 {
1715     __iommu_group_for_each_dev(group, group->default_domain,
1716                    iommu_group_do_probe_finalize);
1717 }
1718 
1719 static int iommu_do_create_direct_mappings(struct device *dev, void *data)
1720 {
1721     struct iommu_group *group = data;
1722 
1723     iommu_create_device_direct_mappings(group, dev);
1724 
1725     return 0;
1726 }
1727 
1728 static int iommu_group_create_direct_mappings(struct iommu_group *group)
1729 {
1730     return __iommu_group_for_each_dev(group, group,
1731                       iommu_do_create_direct_mappings);
1732 }
1733 
1734 int bus_iommu_probe(struct bus_type *bus)
1735 {
1736     struct iommu_group *group, *next;
1737     LIST_HEAD(group_list);
1738     int ret;
1739 
1740     /*
1741      * This code-path does not allocate the default domain when
1742      * creating the iommu group, so do it after the groups are
1743      * created.
1744      */
1745     ret = bus_for_each_dev(bus, NULL, &group_list, probe_iommu_group);
1746     if (ret)
1747         return ret;
1748 
1749     list_for_each_entry_safe(group, next, &group_list, entry) {
1750         /* Remove item from the list */
1751         list_del_init(&group->entry);
1752 
1753         mutex_lock(&group->mutex);
1754 
1755         /* Try to allocate default domain */
1756         probe_alloc_default_domain(bus, group);
1757 
1758         if (!group->default_domain) {
1759             mutex_unlock(&group->mutex);
1760             continue;
1761         }
1762 
1763         iommu_group_create_direct_mappings(group);
1764 
1765         ret = __iommu_group_dma_attach(group);
1766 
1767         mutex_unlock(&group->mutex);
1768 
1769         if (ret)
1770             break;
1771 
1772         __iommu_group_dma_finalize(group);
1773     }
1774 
1775     return ret;
1776 }
1777 
1778 static int iommu_bus_init(struct bus_type *bus, const struct iommu_ops *ops)
1779 {
1780     struct notifier_block *nb;
1781     int err;
1782 
1783     nb = kzalloc(sizeof(struct notifier_block), GFP_KERNEL);
1784     if (!nb)
1785         return -ENOMEM;
1786 
1787     nb->notifier_call = iommu_bus_notifier;
1788 
1789     err = bus_register_notifier(bus, nb);
1790     if (err)
1791         goto out_free;
1792 
1793     err = bus_iommu_probe(bus);
1794     if (err)
1795         goto out_err;
1796 
1797 
1798     return 0;
1799 
1800 out_err:
1801     /* Clean up */
1802     bus_for_each_dev(bus, NULL, NULL, remove_iommu_group);
1803     bus_unregister_notifier(bus, nb);
1804 
1805 out_free:
1806     kfree(nb);
1807 
1808     return err;
1809 }
1810 
1811 /**
1812  * bus_set_iommu - set iommu-callbacks for the bus
1813  * @bus: bus.
1814  * @ops: the callbacks provided by the iommu-driver
1815  *
1816  * This function is called by an iommu driver to set the iommu methods
1817  * used for a particular bus. Drivers for devices on that bus can use
1818  * the iommu-api after these ops are registered.
1819  * This special function is needed because IOMMUs are usually devices on
1820  * the bus itself, so the iommu drivers are not initialized when the bus
1821  * is set up. With this function the iommu-driver can set the iommu-ops
1822  * afterwards.
1823  */
1824 int bus_set_iommu(struct bus_type *bus, const struct iommu_ops *ops)
1825 {
1826     int err;
1827 
1828     if (ops == NULL) {
1829         bus->iommu_ops = NULL;
1830         return 0;
1831     }
1832 
1833     if (bus->iommu_ops != NULL)
1834         return -EBUSY;
1835 
1836     bus->iommu_ops = ops;
1837 
1838     /* Do IOMMU specific setup for this bus-type */
1839     err = iommu_bus_init(bus, ops);
1840     if (err)
1841         bus->iommu_ops = NULL;
1842 
1843     return err;
1844 }
1845 EXPORT_SYMBOL_GPL(bus_set_iommu);
1846 
1847 bool iommu_present(struct bus_type *bus)
1848 {
1849     return bus->iommu_ops != NULL;
1850 }
1851 EXPORT_SYMBOL_GPL(iommu_present);
1852 
1853 /**
1854  * device_iommu_capable() - check for a general IOMMU capability
1855  * @dev: device to which the capability would be relevant, if available
1856  * @cap: IOMMU capability
1857  *
1858  * Return: true if an IOMMU is present and supports the given capability
1859  * for the given device, otherwise false.
1860  */
1861 bool device_iommu_capable(struct device *dev, enum iommu_cap cap)
1862 {
1863     const struct iommu_ops *ops;
1864 
1865     if (!dev->iommu || !dev->iommu->iommu_dev)
1866         return false;
1867 
1868     ops = dev_iommu_ops(dev);
1869     if (!ops->capable)
1870         return false;
1871 
1872     return ops->capable(cap);
1873 }
1874 EXPORT_SYMBOL_GPL(device_iommu_capable);
1875 
1876 bool iommu_capable(struct bus_type *bus, enum iommu_cap cap)
1877 {
1878     if (!bus->iommu_ops || !bus->iommu_ops->capable)
1879         return false;
1880 
1881     return bus->iommu_ops->capable(cap);
1882 }
1883 EXPORT_SYMBOL_GPL(iommu_capable);
1884 
1885 /**
1886  * iommu_set_fault_handler() - set a fault handler for an iommu domain
1887  * @domain: iommu domain
1888  * @handler: fault handler
1889  * @token: user data, will be passed back to the fault handler
1890  *
1891  * This function should be used by IOMMU users which want to be notified
1892  * whenever an IOMMU fault happens.
1893  *
1894  * The fault handler itself should return 0 on success, and an appropriate
1895  * error code otherwise.
1896  */
1897 void iommu_set_fault_handler(struct iommu_domain *domain,
1898                     iommu_fault_handler_t handler,
1899                     void *token)
1900 {
1901     BUG_ON(!domain);
1902 
1903     domain->handler = handler;
1904     domain->handler_token = token;
1905 }
1906 EXPORT_SYMBOL_GPL(iommu_set_fault_handler);
1907 
1908 static struct iommu_domain *__iommu_domain_alloc(struct bus_type *bus,
1909                          unsigned type)
1910 {
1911     struct iommu_domain *domain;
1912 
1913     if (bus == NULL || bus->iommu_ops == NULL)
1914         return NULL;
1915 
1916     domain = bus->iommu_ops->domain_alloc(type);
1917     if (!domain)
1918         return NULL;
1919 
1920     domain->type = type;
1921     /* Assume all sizes by default; the driver may override this later */
1922     domain->pgsize_bitmap = bus->iommu_ops->pgsize_bitmap;
1923     if (!domain->ops)
1924         domain->ops = bus->iommu_ops->default_domain_ops;
1925 
1926     if (iommu_is_dma_domain(domain) && iommu_get_dma_cookie(domain)) {
1927         iommu_domain_free(domain);
1928         domain = NULL;
1929     }
1930     return domain;
1931 }
1932 
1933 struct iommu_domain *iommu_domain_alloc(struct bus_type *bus)
1934 {
1935     return __iommu_domain_alloc(bus, IOMMU_DOMAIN_UNMANAGED);
1936 }
1937 EXPORT_SYMBOL_GPL(iommu_domain_alloc);
1938 
1939 void iommu_domain_free(struct iommu_domain *domain)
1940 {
1941     iommu_put_dma_cookie(domain);
1942     domain->ops->free(domain);
1943 }
1944 EXPORT_SYMBOL_GPL(iommu_domain_free);
1945 
1946 /*
1947  * Put the group's domain back to the appropriate core-owned domain - either the
1948  * standard kernel-mode DMA configuration or an all-DMA-blocked domain.
1949  */
1950 static void __iommu_group_set_core_domain(struct iommu_group *group)
1951 {
1952     struct iommu_domain *new_domain;
1953     int ret;
1954 
1955     if (group->owner)
1956         new_domain = group->blocking_domain;
1957     else
1958         new_domain = group->default_domain;
1959 
1960     ret = __iommu_group_set_domain(group, new_domain);
1961     WARN(ret, "iommu driver failed to attach the default/blocking domain");
1962 }
1963 
1964 static int __iommu_attach_device(struct iommu_domain *domain,
1965                  struct device *dev)
1966 {
1967     int ret;
1968 
1969     if (unlikely(domain->ops->attach_dev == NULL))
1970         return -ENODEV;
1971 
1972     ret = domain->ops->attach_dev(domain, dev);
1973     if (!ret)
1974         trace_attach_device_to_domain(dev);
1975     return ret;
1976 }
1977 
1978 int iommu_attach_device(struct iommu_domain *domain, struct device *dev)
1979 {
1980     struct iommu_group *group;
1981     int ret;
1982 
1983     group = iommu_group_get(dev);
1984     if (!group)
1985         return -ENODEV;
1986 
1987     /*
1988      * Lock the group to make sure the device-count doesn't
1989      * change while we are attaching
1990      */
1991     mutex_lock(&group->mutex);
1992     ret = -EINVAL;
1993     if (iommu_group_device_count(group) != 1)
1994         goto out_unlock;
1995 
1996     ret = __iommu_attach_group(domain, group);
1997 
1998 out_unlock:
1999     mutex_unlock(&group->mutex);
2000     iommu_group_put(group);
2001 
2002     return ret;
2003 }
2004 EXPORT_SYMBOL_GPL(iommu_attach_device);
2005 
2006 int iommu_deferred_attach(struct device *dev, struct iommu_domain *domain)
2007 {
2008     if (iommu_is_attach_deferred(dev))
2009         return __iommu_attach_device(domain, dev);
2010 
2011     return 0;
2012 }
2013 
2014 static void __iommu_detach_device(struct iommu_domain *domain,
2015                   struct device *dev)
2016 {
2017     if (iommu_is_attach_deferred(dev))
2018         return;
2019 
2020     domain->ops->detach_dev(domain, dev);
2021     trace_detach_device_from_domain(dev);
2022 }
2023 
2024 void iommu_detach_device(struct iommu_domain *domain, struct device *dev)
2025 {
2026     struct iommu_group *group;
2027 
2028     group = iommu_group_get(dev);
2029     if (!group)
2030         return;
2031 
2032     mutex_lock(&group->mutex);
2033     if (WARN_ON(domain != group->domain) ||
2034         WARN_ON(iommu_group_device_count(group) != 1))
2035         goto out_unlock;
2036     __iommu_group_set_core_domain(group);
2037 
2038 out_unlock:
2039     mutex_unlock(&group->mutex);
2040     iommu_group_put(group);
2041 }
2042 EXPORT_SYMBOL_GPL(iommu_detach_device);
2043 
2044 struct iommu_domain *iommu_get_domain_for_dev(struct device *dev)
2045 {
2046     struct iommu_domain *domain;
2047     struct iommu_group *group;
2048 
2049     group = iommu_group_get(dev);
2050     if (!group)
2051         return NULL;
2052 
2053     domain = group->domain;
2054 
2055     iommu_group_put(group);
2056 
2057     return domain;
2058 }
2059 EXPORT_SYMBOL_GPL(iommu_get_domain_for_dev);
2060 
2061 /*
2062  * For IOMMU_DOMAIN_DMA implementations which already provide their own
2063  * guarantees that the group and its default domain are valid and correct.
2064  */
2065 struct iommu_domain *iommu_get_dma_domain(struct device *dev)
2066 {
2067     return dev->iommu_group->default_domain;
2068 }
2069 
2070 /*
2071  * IOMMU groups are really the natural working unit of the IOMMU, but
2072  * the IOMMU API works on domains and devices.  Bridge that gap by
2073  * iterating over the devices in a group.  Ideally we'd have a single
2074  * device which represents the requestor ID of the group, but we also
2075  * allow IOMMU drivers to create policy defined minimum sets, where
2076  * the physical hardware may be able to distiguish members, but we
2077  * wish to group them at a higher level (ex. untrusted multi-function
2078  * PCI devices).  Thus we attach each device.
2079  */
2080 static int iommu_group_do_attach_device(struct device *dev, void *data)
2081 {
2082     struct iommu_domain *domain = data;
2083 
2084     return __iommu_attach_device(domain, dev);
2085 }
2086 
2087 static int __iommu_attach_group(struct iommu_domain *domain,
2088                 struct iommu_group *group)
2089 {
2090     int ret;
2091 
2092     if (group->domain && group->domain != group->default_domain &&
2093         group->domain != group->blocking_domain)
2094         return -EBUSY;
2095 
2096     ret = __iommu_group_for_each_dev(group, domain,
2097                      iommu_group_do_attach_device);
2098     if (ret == 0)
2099         group->domain = domain;
2100 
2101     return ret;
2102 }
2103 
2104 int iommu_attach_group(struct iommu_domain *domain, struct iommu_group *group)
2105 {
2106     int ret;
2107 
2108     mutex_lock(&group->mutex);
2109     ret = __iommu_attach_group(domain, group);
2110     mutex_unlock(&group->mutex);
2111 
2112     return ret;
2113 }
2114 EXPORT_SYMBOL_GPL(iommu_attach_group);
2115 
2116 static int iommu_group_do_detach_device(struct device *dev, void *data)
2117 {
2118     struct iommu_domain *domain = data;
2119 
2120     __iommu_detach_device(domain, dev);
2121 
2122     return 0;
2123 }
2124 
2125 static int __iommu_group_set_domain(struct iommu_group *group,
2126                     struct iommu_domain *new_domain)
2127 {
2128     int ret;
2129 
2130     if (group->domain == new_domain)
2131         return 0;
2132 
2133     /*
2134      * New drivers should support default domains and so the detach_dev() op
2135      * will never be called. Otherwise the NULL domain represents some
2136      * platform specific behavior.
2137      */
2138     if (!new_domain) {
2139         if (WARN_ON(!group->domain->ops->detach_dev))
2140             return -EINVAL;
2141         __iommu_group_for_each_dev(group, group->domain,
2142                        iommu_group_do_detach_device);
2143         group->domain = NULL;
2144         return 0;
2145     }
2146 
2147     /*
2148      * Changing the domain is done by calling attach_dev() on the new
2149      * domain. This switch does not have to be atomic and DMA can be
2150      * discarded during the transition. DMA must only be able to access
2151      * either new_domain or group->domain, never something else.
2152      *
2153      * Note that this is called in error unwind paths, attaching to a
2154      * domain that has already been attached cannot fail.
2155      */
2156     ret = __iommu_group_for_each_dev(group, new_domain,
2157                      iommu_group_do_attach_device);
2158     if (ret)
2159         return ret;
2160     group->domain = new_domain;
2161     return 0;
2162 }
2163 
2164 void iommu_detach_group(struct iommu_domain *domain, struct iommu_group *group)
2165 {
2166     mutex_lock(&group->mutex);
2167     __iommu_group_set_core_domain(group);
2168     mutex_unlock(&group->mutex);
2169 }
2170 EXPORT_SYMBOL_GPL(iommu_detach_group);
2171 
2172 phys_addr_t iommu_iova_to_phys(struct iommu_domain *domain, dma_addr_t iova)
2173 {
2174     if (domain->type == IOMMU_DOMAIN_IDENTITY)
2175         return iova;
2176 
2177     if (domain->type == IOMMU_DOMAIN_BLOCKED)
2178         return 0;
2179 
2180     return domain->ops->iova_to_phys(domain, iova);
2181 }
2182 EXPORT_SYMBOL_GPL(iommu_iova_to_phys);
2183 
2184 static size_t iommu_pgsize(struct iommu_domain *domain, unsigned long iova,
2185                phys_addr_t paddr, size_t size, size_t *count)
2186 {
2187     unsigned int pgsize_idx, pgsize_idx_next;
2188     unsigned long pgsizes;
2189     size_t offset, pgsize, pgsize_next;
2190     unsigned long addr_merge = paddr | iova;
2191 
2192     /* Page sizes supported by the hardware and small enough for @size */
2193     pgsizes = domain->pgsize_bitmap & GENMASK(__fls(size), 0);
2194 
2195     /* Constrain the page sizes further based on the maximum alignment */
2196     if (likely(addr_merge))
2197         pgsizes &= GENMASK(__ffs(addr_merge), 0);
2198 
2199     /* Make sure we have at least one suitable page size */
2200     BUG_ON(!pgsizes);
2201 
2202     /* Pick the biggest page size remaining */
2203     pgsize_idx = __fls(pgsizes);
2204     pgsize = BIT(pgsize_idx);
2205     if (!count)
2206         return pgsize;
2207 
2208     /* Find the next biggest support page size, if it exists */
2209     pgsizes = domain->pgsize_bitmap & ~GENMASK(pgsize_idx, 0);
2210     if (!pgsizes)
2211         goto out_set_count;
2212 
2213     pgsize_idx_next = __ffs(pgsizes);
2214     pgsize_next = BIT(pgsize_idx_next);
2215 
2216     /*
2217      * There's no point trying a bigger page size unless the virtual
2218      * and physical addresses are similarly offset within the larger page.
2219      */
2220     if ((iova ^ paddr) & (pgsize_next - 1))
2221         goto out_set_count;
2222 
2223     /* Calculate the offset to the next page size alignment boundary */
2224     offset = pgsize_next - (addr_merge & (pgsize_next - 1));
2225 
2226     /*
2227      * If size is big enough to accommodate the larger page, reduce
2228      * the number of smaller pages.
2229      */
2230     if (offset + pgsize_next <= size)
2231         size = offset;
2232 
2233 out_set_count:
2234     *count = size >> pgsize_idx;
2235     return pgsize;
2236 }
2237 
2238 static int __iommu_map_pages(struct iommu_domain *domain, unsigned long iova,
2239                  phys_addr_t paddr, size_t size, int prot,
2240                  gfp_t gfp, size_t *mapped)
2241 {
2242     const struct iommu_domain_ops *ops = domain->ops;
2243     size_t pgsize, count;
2244     int ret;
2245 
2246     pgsize = iommu_pgsize(domain, iova, paddr, size, &count);
2247 
2248     pr_debug("mapping: iova 0x%lx pa %pa pgsize 0x%zx count %zu\n",
2249          iova, &paddr, pgsize, count);
2250 
2251     if (ops->map_pages) {
2252         ret = ops->map_pages(domain, iova, paddr, pgsize, count, prot,
2253                      gfp, mapped);
2254     } else {
2255         ret = ops->map(domain, iova, paddr, pgsize, prot, gfp);
2256         *mapped = ret ? 0 : pgsize;
2257     }
2258 
2259     return ret;
2260 }
2261 
2262 static int __iommu_map(struct iommu_domain *domain, unsigned long iova,
2263                phys_addr_t paddr, size_t size, int prot, gfp_t gfp)
2264 {
2265     const struct iommu_domain_ops *ops = domain->ops;
2266     unsigned long orig_iova = iova;
2267     unsigned int min_pagesz;
2268     size_t orig_size = size;
2269     phys_addr_t orig_paddr = paddr;
2270     int ret = 0;
2271 
2272     if (unlikely(!(ops->map || ops->map_pages) ||
2273              domain->pgsize_bitmap == 0UL))
2274         return -ENODEV;
2275 
2276     if (unlikely(!(domain->type & __IOMMU_DOMAIN_PAGING)))
2277         return -EINVAL;
2278 
2279     /* find out the minimum page size supported */
2280     min_pagesz = 1 << __ffs(domain->pgsize_bitmap);
2281 
2282     /*
2283      * both the virtual address and the physical one, as well as
2284      * the size of the mapping, must be aligned (at least) to the
2285      * size of the smallest page supported by the hardware
2286      */
2287     if (!IS_ALIGNED(iova | paddr | size, min_pagesz)) {
2288         pr_err("unaligned: iova 0x%lx pa %pa size 0x%zx min_pagesz 0x%x\n",
2289                iova, &paddr, size, min_pagesz);
2290         return -EINVAL;
2291     }
2292 
2293     pr_debug("map: iova 0x%lx pa %pa size 0x%zx\n", iova, &paddr, size);
2294 
2295     while (size) {
2296         size_t mapped = 0;
2297 
2298         ret = __iommu_map_pages(domain, iova, paddr, size, prot, gfp,
2299                     &mapped);
2300         /*
2301          * Some pages may have been mapped, even if an error occurred,
2302          * so we should account for those so they can be unmapped.
2303          */
2304         size -= mapped;
2305 
2306         if (ret)
2307             break;
2308 
2309         iova += mapped;
2310         paddr += mapped;
2311     }
2312 
2313     /* unroll mapping in case something went wrong */
2314     if (ret)
2315         iommu_unmap(domain, orig_iova, orig_size - size);
2316     else
2317         trace_map(orig_iova, orig_paddr, orig_size);
2318 
2319     return ret;
2320 }
2321 
2322 static int _iommu_map(struct iommu_domain *domain, unsigned long iova,
2323               phys_addr_t paddr, size_t size, int prot, gfp_t gfp)
2324 {
2325     const struct iommu_domain_ops *ops = domain->ops;
2326     int ret;
2327 
2328     ret = __iommu_map(domain, iova, paddr, size, prot, gfp);
2329     if (ret == 0 && ops->iotlb_sync_map)
2330         ops->iotlb_sync_map(domain, iova, size);
2331 
2332     return ret;
2333 }
2334 
2335 int iommu_map(struct iommu_domain *domain, unsigned long iova,
2336           phys_addr_t paddr, size_t size, int prot)
2337 {
2338     might_sleep();
2339     return _iommu_map(domain, iova, paddr, size, prot, GFP_KERNEL);
2340 }
2341 EXPORT_SYMBOL_GPL(iommu_map);
2342 
2343 int iommu_map_atomic(struct iommu_domain *domain, unsigned long iova,
2344           phys_addr_t paddr, size_t size, int prot)
2345 {
2346     return _iommu_map(domain, iova, paddr, size, prot, GFP_ATOMIC);
2347 }
2348 EXPORT_SYMBOL_GPL(iommu_map_atomic);
2349 
2350 static size_t __iommu_unmap_pages(struct iommu_domain *domain,
2351                   unsigned long iova, size_t size,
2352                   struct iommu_iotlb_gather *iotlb_gather)
2353 {
2354     const struct iommu_domain_ops *ops = domain->ops;
2355     size_t pgsize, count;
2356 
2357     pgsize = iommu_pgsize(domain, iova, iova, size, &count);
2358     return ops->unmap_pages ?
2359            ops->unmap_pages(domain, iova, pgsize, count, iotlb_gather) :
2360            ops->unmap(domain, iova, pgsize, iotlb_gather);
2361 }
2362 
2363 static size_t __iommu_unmap(struct iommu_domain *domain,
2364                 unsigned long iova, size_t size,
2365                 struct iommu_iotlb_gather *iotlb_gather)
2366 {
2367     const struct iommu_domain_ops *ops = domain->ops;
2368     size_t unmapped_page, unmapped = 0;
2369     unsigned long orig_iova = iova;
2370     unsigned int min_pagesz;
2371 
2372     if (unlikely(!(ops->unmap || ops->unmap_pages) ||
2373              domain->pgsize_bitmap == 0UL))
2374         return 0;
2375 
2376     if (unlikely(!(domain->type & __IOMMU_DOMAIN_PAGING)))
2377         return 0;
2378 
2379     /* find out the minimum page size supported */
2380     min_pagesz = 1 << __ffs(domain->pgsize_bitmap);
2381 
2382     /*
2383      * The virtual address, as well as the size of the mapping, must be
2384      * aligned (at least) to the size of the smallest page supported
2385      * by the hardware
2386      */
2387     if (!IS_ALIGNED(iova | size, min_pagesz)) {
2388         pr_err("unaligned: iova 0x%lx size 0x%zx min_pagesz 0x%x\n",
2389                iova, size, min_pagesz);
2390         return 0;
2391     }
2392 
2393     pr_debug("unmap this: iova 0x%lx size 0x%zx\n", iova, size);
2394 
2395     /*
2396      * Keep iterating until we either unmap 'size' bytes (or more)
2397      * or we hit an area that isn't mapped.
2398      */
2399     while (unmapped < size) {
2400         unmapped_page = __iommu_unmap_pages(domain, iova,
2401                             size - unmapped,
2402                             iotlb_gather);
2403         if (!unmapped_page)
2404             break;
2405 
2406         pr_debug("unmapped: iova 0x%lx size 0x%zx\n",
2407              iova, unmapped_page);
2408 
2409         iova += unmapped_page;
2410         unmapped += unmapped_page;
2411     }
2412 
2413     trace_unmap(orig_iova, size, unmapped);
2414     return unmapped;
2415 }
2416 
2417 size_t iommu_unmap(struct iommu_domain *domain,
2418            unsigned long iova, size_t size)
2419 {
2420     struct iommu_iotlb_gather iotlb_gather;
2421     size_t ret;
2422 
2423     iommu_iotlb_gather_init(&iotlb_gather);
2424     ret = __iommu_unmap(domain, iova, size, &iotlb_gather);
2425     iommu_iotlb_sync(domain, &iotlb_gather);
2426 
2427     return ret;
2428 }
2429 EXPORT_SYMBOL_GPL(iommu_unmap);
2430 
2431 size_t iommu_unmap_fast(struct iommu_domain *domain,
2432             unsigned long iova, size_t size,
2433             struct iommu_iotlb_gather *iotlb_gather)
2434 {
2435     return __iommu_unmap(domain, iova, size, iotlb_gather);
2436 }
2437 EXPORT_SYMBOL_GPL(iommu_unmap_fast);
2438 
2439 static ssize_t __iommu_map_sg(struct iommu_domain *domain, unsigned long iova,
2440         struct scatterlist *sg, unsigned int nents, int prot,
2441         gfp_t gfp)
2442 {
2443     const struct iommu_domain_ops *ops = domain->ops;
2444     size_t len = 0, mapped = 0;
2445     phys_addr_t start;
2446     unsigned int i = 0;
2447     int ret;
2448 
2449     while (i <= nents) {
2450         phys_addr_t s_phys = sg_phys(sg);
2451 
2452         if (len && s_phys != start + len) {
2453             ret = __iommu_map(domain, iova + mapped, start,
2454                     len, prot, gfp);
2455 
2456             if (ret)
2457                 goto out_err;
2458 
2459             mapped += len;
2460             len = 0;
2461         }
2462 
2463         if (sg_is_dma_bus_address(sg))
2464             goto next;
2465 
2466         if (len) {
2467             len += sg->length;
2468         } else {
2469             len = sg->length;
2470             start = s_phys;
2471         }
2472 
2473 next:
2474         if (++i < nents)
2475             sg = sg_next(sg);
2476     }
2477 
2478     if (ops->iotlb_sync_map)
2479         ops->iotlb_sync_map(domain, iova, mapped);
2480     return mapped;
2481 
2482 out_err:
2483     /* undo mappings already done */
2484     iommu_unmap(domain, iova, mapped);
2485 
2486     return ret;
2487 }
2488 
2489 ssize_t iommu_map_sg(struct iommu_domain *domain, unsigned long iova,
2490              struct scatterlist *sg, unsigned int nents, int prot)
2491 {
2492     might_sleep();
2493     return __iommu_map_sg(domain, iova, sg, nents, prot, GFP_KERNEL);
2494 }
2495 EXPORT_SYMBOL_GPL(iommu_map_sg);
2496 
2497 ssize_t iommu_map_sg_atomic(struct iommu_domain *domain, unsigned long iova,
2498             struct scatterlist *sg, unsigned int nents, int prot)
2499 {
2500     return __iommu_map_sg(domain, iova, sg, nents, prot, GFP_ATOMIC);
2501 }
2502 
2503 /**
2504  * report_iommu_fault() - report about an IOMMU fault to the IOMMU framework
2505  * @domain: the iommu domain where the fault has happened
2506  * @dev: the device where the fault has happened
2507  * @iova: the faulting address
2508  * @flags: mmu fault flags (e.g. IOMMU_FAULT_READ/IOMMU_FAULT_WRITE/...)
2509  *
2510  * This function should be called by the low-level IOMMU implementations
2511  * whenever IOMMU faults happen, to allow high-level users, that are
2512  * interested in such events, to know about them.
2513  *
2514  * This event may be useful for several possible use cases:
2515  * - mere logging of the event
2516  * - dynamic TLB/PTE loading
2517  * - if restarting of the faulting device is required
2518  *
2519  * Returns 0 on success and an appropriate error code otherwise (if dynamic
2520  * PTE/TLB loading will one day be supported, implementations will be able
2521  * to tell whether it succeeded or not according to this return value).
2522  *
2523  * Specifically, -ENOSYS is returned if a fault handler isn't installed
2524  * (though fault handlers can also return -ENOSYS, in case they want to
2525  * elicit the default behavior of the IOMMU drivers).
2526  */
2527 int report_iommu_fault(struct iommu_domain *domain, struct device *dev,
2528                unsigned long iova, int flags)
2529 {
2530     int ret = -ENOSYS;
2531 
2532     /*
2533      * if upper layers showed interest and installed a fault handler,
2534      * invoke it.
2535      */
2536     if (domain->handler)
2537         ret = domain->handler(domain, dev, iova, flags,
2538                         domain->handler_token);
2539 
2540     trace_io_page_fault(dev, iova, flags);
2541     return ret;
2542 }
2543 EXPORT_SYMBOL_GPL(report_iommu_fault);
2544 
2545 static int __init iommu_init(void)
2546 {
2547     iommu_group_kset = kset_create_and_add("iommu_groups",
2548                            NULL, kernel_kobj);
2549     BUG_ON(!iommu_group_kset);
2550 
2551     iommu_debugfs_setup();
2552 
2553     return 0;
2554 }
2555 core_initcall(iommu_init);
2556 
2557 int iommu_enable_nesting(struct iommu_domain *domain)
2558 {
2559     if (domain->type != IOMMU_DOMAIN_UNMANAGED)
2560         return -EINVAL;
2561     if (!domain->ops->enable_nesting)
2562         return -EINVAL;
2563     return domain->ops->enable_nesting(domain);
2564 }
2565 EXPORT_SYMBOL_GPL(iommu_enable_nesting);
2566 
2567 int iommu_set_pgtable_quirks(struct iommu_domain *domain,
2568         unsigned long quirk)
2569 {
2570     if (domain->type != IOMMU_DOMAIN_UNMANAGED)
2571         return -EINVAL;
2572     if (!domain->ops->set_pgtable_quirks)
2573         return -EINVAL;
2574     return domain->ops->set_pgtable_quirks(domain, quirk);
2575 }
2576 EXPORT_SYMBOL_GPL(iommu_set_pgtable_quirks);
2577 
2578 void iommu_get_resv_regions(struct device *dev, struct list_head *list)
2579 {
2580     const struct iommu_ops *ops = dev_iommu_ops(dev);
2581 
2582     if (ops->get_resv_regions)
2583         ops->get_resv_regions(dev, list);
2584 }
2585 
2586 /**
2587  * iommu_put_resv_regions - release resered regions
2588  * @dev: device for which to free reserved regions
2589  * @list: reserved region list for device
2590  *
2591  * This releases a reserved region list acquired by iommu_get_resv_regions().
2592  */
2593 void iommu_put_resv_regions(struct device *dev, struct list_head *list)
2594 {
2595     struct iommu_resv_region *entry, *next;
2596 
2597     list_for_each_entry_safe(entry, next, list, list) {
2598         if (entry->free)
2599             entry->free(dev, entry);
2600         else
2601             kfree(entry);
2602     }
2603 }
2604 EXPORT_SYMBOL(iommu_put_resv_regions);
2605 
2606 struct iommu_resv_region *iommu_alloc_resv_region(phys_addr_t start,
2607                           size_t length, int prot,
2608                           enum iommu_resv_type type)
2609 {
2610     struct iommu_resv_region *region;
2611 
2612     region = kzalloc(sizeof(*region), GFP_KERNEL);
2613     if (!region)
2614         return NULL;
2615 
2616     INIT_LIST_HEAD(&region->list);
2617     region->start = start;
2618     region->length = length;
2619     region->prot = prot;
2620     region->type = type;
2621     return region;
2622 }
2623 EXPORT_SYMBOL_GPL(iommu_alloc_resv_region);
2624 
2625 void iommu_set_default_passthrough(bool cmd_line)
2626 {
2627     if (cmd_line)
2628         iommu_cmd_line |= IOMMU_CMD_LINE_DMA_API;
2629     iommu_def_domain_type = IOMMU_DOMAIN_IDENTITY;
2630 }
2631 
2632 void iommu_set_default_translated(bool cmd_line)
2633 {
2634     if (cmd_line)
2635         iommu_cmd_line |= IOMMU_CMD_LINE_DMA_API;
2636     iommu_def_domain_type = IOMMU_DOMAIN_DMA;
2637 }
2638 
2639 bool iommu_default_passthrough(void)
2640 {
2641     return iommu_def_domain_type == IOMMU_DOMAIN_IDENTITY;
2642 }
2643 EXPORT_SYMBOL_GPL(iommu_default_passthrough);
2644 
2645 const struct iommu_ops *iommu_ops_from_fwnode(struct fwnode_handle *fwnode)
2646 {
2647     const struct iommu_ops *ops = NULL;
2648     struct iommu_device *iommu;
2649 
2650     spin_lock(&iommu_device_lock);
2651     list_for_each_entry(iommu, &iommu_device_list, list)
2652         if (iommu->fwnode == fwnode) {
2653             ops = iommu->ops;
2654             break;
2655         }
2656     spin_unlock(&iommu_device_lock);
2657     return ops;
2658 }
2659 
2660 int iommu_fwspec_init(struct device *dev, struct fwnode_handle *iommu_fwnode,
2661               const struct iommu_ops *ops)
2662 {
2663     struct iommu_fwspec *fwspec = dev_iommu_fwspec_get(dev);
2664 
2665     if (fwspec)
2666         return ops == fwspec->ops ? 0 : -EINVAL;
2667 
2668     if (!dev_iommu_get(dev))
2669         return -ENOMEM;
2670 
2671     /* Preallocate for the overwhelmingly common case of 1 ID */
2672     fwspec = kzalloc(struct_size(fwspec, ids, 1), GFP_KERNEL);
2673     if (!fwspec)
2674         return -ENOMEM;
2675 
2676     of_node_get(to_of_node(iommu_fwnode));
2677     fwspec->iommu_fwnode = iommu_fwnode;
2678     fwspec->ops = ops;
2679     dev_iommu_fwspec_set(dev, fwspec);
2680     return 0;
2681 }
2682 EXPORT_SYMBOL_GPL(iommu_fwspec_init);
2683 
2684 void iommu_fwspec_free(struct device *dev)
2685 {
2686     struct iommu_fwspec *fwspec = dev_iommu_fwspec_get(dev);
2687 
2688     if (fwspec) {
2689         fwnode_handle_put(fwspec->iommu_fwnode);
2690         kfree(fwspec);
2691         dev_iommu_fwspec_set(dev, NULL);
2692     }
2693 }
2694 EXPORT_SYMBOL_GPL(iommu_fwspec_free);
2695 
2696 int iommu_fwspec_add_ids(struct device *dev, u32 *ids, int num_ids)
2697 {
2698     struct iommu_fwspec *fwspec = dev_iommu_fwspec_get(dev);
2699     int i, new_num;
2700 
2701     if (!fwspec)
2702         return -EINVAL;
2703 
2704     new_num = fwspec->num_ids + num_ids;
2705     if (new_num > 1) {
2706         fwspec = krealloc(fwspec, struct_size(fwspec, ids, new_num),
2707                   GFP_KERNEL);
2708         if (!fwspec)
2709             return -ENOMEM;
2710 
2711         dev_iommu_fwspec_set(dev, fwspec);
2712     }
2713 
2714     for (i = 0; i < num_ids; i++)
2715         fwspec->ids[fwspec->num_ids + i] = ids[i];
2716 
2717     fwspec->num_ids = new_num;
2718     return 0;
2719 }
2720 EXPORT_SYMBOL_GPL(iommu_fwspec_add_ids);
2721 
2722 /*
2723  * Per device IOMMU features.
2724  */
2725 int iommu_dev_enable_feature(struct device *dev, enum iommu_dev_features feat)
2726 {
2727     if (dev->iommu && dev->iommu->iommu_dev) {
2728         const struct iommu_ops *ops = dev->iommu->iommu_dev->ops;
2729 
2730         if (ops->dev_enable_feat)
2731             return ops->dev_enable_feat(dev, feat);
2732     }
2733 
2734     return -ENODEV;
2735 }
2736 EXPORT_SYMBOL_GPL(iommu_dev_enable_feature);
2737 
2738 /*
2739  * The device drivers should do the necessary cleanups before calling this.
2740  */
2741 int iommu_dev_disable_feature(struct device *dev, enum iommu_dev_features feat)
2742 {
2743     if (dev->iommu && dev->iommu->iommu_dev) {
2744         const struct iommu_ops *ops = dev->iommu->iommu_dev->ops;
2745 
2746         if (ops->dev_disable_feat)
2747             return ops->dev_disable_feat(dev, feat);
2748     }
2749 
2750     return -EBUSY;
2751 }
2752 EXPORT_SYMBOL_GPL(iommu_dev_disable_feature);
2753 
2754 /**
2755  * iommu_sva_bind_device() - Bind a process address space to a device
2756  * @dev: the device
2757  * @mm: the mm to bind, caller must hold a reference to it
2758  * @drvdata: opaque data pointer to pass to bind callback
2759  *
2760  * Create a bond between device and address space, allowing the device to access
2761  * the mm using the returned PASID. If a bond already exists between @device and
2762  * @mm, it is returned and an additional reference is taken. Caller must call
2763  * iommu_sva_unbind_device() to release each reference.
2764  *
2765  * iommu_dev_enable_feature(dev, IOMMU_DEV_FEAT_SVA) must be called first, to
2766  * initialize the required SVA features.
2767  *
2768  * On error, returns an ERR_PTR value.
2769  */
2770 struct iommu_sva *
2771 iommu_sva_bind_device(struct device *dev, struct mm_struct *mm, void *drvdata)
2772 {
2773     struct iommu_group *group;
2774     struct iommu_sva *handle = ERR_PTR(-EINVAL);
2775     const struct iommu_ops *ops = dev_iommu_ops(dev);
2776 
2777     if (!ops->sva_bind)
2778         return ERR_PTR(-ENODEV);
2779 
2780     group = iommu_group_get(dev);
2781     if (!group)
2782         return ERR_PTR(-ENODEV);
2783 
2784     /* Ensure device count and domain don't change while we're binding */
2785     mutex_lock(&group->mutex);
2786 
2787     /*
2788      * To keep things simple, SVA currently doesn't support IOMMU groups
2789      * with more than one device. Existing SVA-capable systems are not
2790      * affected by the problems that required IOMMU groups (lack of ACS
2791      * isolation, device ID aliasing and other hardware issues).
2792      */
2793     if (iommu_group_device_count(group) != 1)
2794         goto out_unlock;
2795 
2796     handle = ops->sva_bind(dev, mm, drvdata);
2797 
2798 out_unlock:
2799     mutex_unlock(&group->mutex);
2800     iommu_group_put(group);
2801 
2802     return handle;
2803 }
2804 EXPORT_SYMBOL_GPL(iommu_sva_bind_device);
2805 
2806 /**
2807  * iommu_sva_unbind_device() - Remove a bond created with iommu_sva_bind_device
2808  * @handle: the handle returned by iommu_sva_bind_device()
2809  *
2810  * Put reference to a bond between device and address space. The device should
2811  * not be issuing any more transaction for this PASID. All outstanding page
2812  * requests for this PASID must have been flushed to the IOMMU.
2813  */
2814 void iommu_sva_unbind_device(struct iommu_sva *handle)
2815 {
2816     struct iommu_group *group;
2817     struct device *dev = handle->dev;
2818     const struct iommu_ops *ops = dev_iommu_ops(dev);
2819 
2820     if (!ops->sva_unbind)
2821         return;
2822 
2823     group = iommu_group_get(dev);
2824     if (!group)
2825         return;
2826 
2827     mutex_lock(&group->mutex);
2828     ops->sva_unbind(handle);
2829     mutex_unlock(&group->mutex);
2830 
2831     iommu_group_put(group);
2832 }
2833 EXPORT_SYMBOL_GPL(iommu_sva_unbind_device);
2834 
2835 u32 iommu_sva_get_pasid(struct iommu_sva *handle)
2836 {
2837     const struct iommu_ops *ops = dev_iommu_ops(handle->dev);
2838 
2839     if (!ops->sva_get_pasid)
2840         return IOMMU_PASID_INVALID;
2841 
2842     return ops->sva_get_pasid(handle);
2843 }
2844 EXPORT_SYMBOL_GPL(iommu_sva_get_pasid);
2845 
2846 /*
2847  * Changes the default domain of an iommu group that has *only* one device
2848  *
2849  * @group: The group for which the default domain should be changed
2850  * @prev_dev: The device in the group (this is used to make sure that the device
2851  *   hasn't changed after the caller has called this function)
2852  * @type: The type of the new default domain that gets associated with the group
2853  *
2854  * Returns 0 on success and error code on failure
2855  *
2856  * Note:
2857  * 1. Presently, this function is called only when user requests to change the
2858  *    group's default domain type through /sys/kernel/iommu_groups/<grp_id>/type
2859  *    Please take a closer look if intended to use for other purposes.
2860  */
2861 static int iommu_change_dev_def_domain(struct iommu_group *group,
2862                        struct device *prev_dev, int type)
2863 {
2864     struct iommu_domain *prev_dom;
2865     struct group_device *grp_dev;
2866     int ret, dev_def_dom;
2867     struct device *dev;
2868 
2869     mutex_lock(&group->mutex);
2870 
2871     if (group->default_domain != group->domain) {
2872         dev_err_ratelimited(prev_dev, "Group not assigned to default domain\n");
2873         ret = -EBUSY;
2874         goto out;
2875     }
2876 
2877     /*
2878      * iommu group wasn't locked while acquiring device lock in
2879      * iommu_group_store_type(). So, make sure that the device count hasn't
2880      * changed while acquiring device lock.
2881      *
2882      * Changing default domain of an iommu group with two or more devices
2883      * isn't supported because there could be a potential deadlock. Consider
2884      * the following scenario. T1 is trying to acquire device locks of all
2885      * the devices in the group and before it could acquire all of them,
2886      * there could be another thread T2 (from different sub-system and use
2887      * case) that has already acquired some of the device locks and might be
2888      * waiting for T1 to release other device locks.
2889      */
2890     if (iommu_group_device_count(group) != 1) {
2891         dev_err_ratelimited(prev_dev, "Cannot change default domain: Group has more than one device\n");
2892         ret = -EINVAL;
2893         goto out;
2894     }
2895 
2896     /* Since group has only one device */
2897     grp_dev = list_first_entry(&group->devices, struct group_device, list);
2898     dev = grp_dev->dev;
2899 
2900     if (prev_dev != dev) {
2901         dev_err_ratelimited(prev_dev, "Cannot change default domain: Device has been changed\n");
2902         ret = -EBUSY;
2903         goto out;
2904     }
2905 
2906     prev_dom = group->default_domain;
2907     if (!prev_dom) {
2908         ret = -EINVAL;
2909         goto out;
2910     }
2911 
2912     dev_def_dom = iommu_get_def_domain_type(dev);
2913     if (!type) {
2914         /*
2915          * If the user hasn't requested any specific type of domain and
2916          * if the device supports both the domains, then default to the
2917          * domain the device was booted with
2918          */
2919         type = dev_def_dom ? : iommu_def_domain_type;
2920     } else if (dev_def_dom && type != dev_def_dom) {
2921         dev_err_ratelimited(prev_dev, "Device cannot be in %s domain\n",
2922                     iommu_domain_type_str(type));
2923         ret = -EINVAL;
2924         goto out;
2925     }
2926 
2927     /*
2928      * Switch to a new domain only if the requested domain type is different
2929      * from the existing default domain type
2930      */
2931     if (prev_dom->type == type) {
2932         ret = 0;
2933         goto out;
2934     }
2935 
2936     /* We can bring up a flush queue without tearing down the domain */
2937     if (type == IOMMU_DOMAIN_DMA_FQ && prev_dom->type == IOMMU_DOMAIN_DMA) {
2938         ret = iommu_dma_init_fq(prev_dom);
2939         if (!ret)
2940             prev_dom->type = IOMMU_DOMAIN_DMA_FQ;
2941         goto out;
2942     }
2943 
2944     /* Sets group->default_domain to the newly allocated domain */
2945     ret = iommu_group_alloc_default_domain(dev->bus, group, type);
2946     if (ret)
2947         goto out;
2948 
2949     ret = iommu_create_device_direct_mappings(group, dev);
2950     if (ret)
2951         goto free_new_domain;
2952 
2953     ret = __iommu_attach_device(group->default_domain, dev);
2954     if (ret)
2955         goto free_new_domain;
2956 
2957     group->domain = group->default_domain;
2958 
2959     /*
2960      * Release the mutex here because ops->probe_finalize() call-back of
2961      * some vendor IOMMU drivers calls arm_iommu_attach_device() which
2962      * in-turn might call back into IOMMU core code, where it tries to take
2963      * group->mutex, resulting in a deadlock.
2964      */
2965     mutex_unlock(&group->mutex);
2966 
2967     /* Make sure dma_ops is appropriatley set */
2968     iommu_group_do_probe_finalize(dev, group->default_domain);
2969     iommu_domain_free(prev_dom);
2970     return 0;
2971 
2972 free_new_domain:
2973     iommu_domain_free(group->default_domain);
2974     group->default_domain = prev_dom;
2975     group->domain = prev_dom;
2976 
2977 out:
2978     mutex_unlock(&group->mutex);
2979 
2980     return ret;
2981 }
2982 
2983 /*
2984  * Changing the default domain through sysfs requires the users to unbind the
2985  * drivers from the devices in the iommu group, except for a DMA -> DMA-FQ
2986  * transition. Return failure if this isn't met.
2987  *
2988  * We need to consider the race between this and the device release path.
2989  * device_lock(dev) is used here to guarantee that the device release path
2990  * will not be entered at the same time.
2991  */
2992 static ssize_t iommu_group_store_type(struct iommu_group *group,
2993                       const char *buf, size_t count)
2994 {
2995     struct group_device *grp_dev;
2996     struct device *dev;
2997     int ret, req_type;
2998 
2999     if (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO))
3000         return -EACCES;
3001 
3002     if (WARN_ON(!group) || !group->default_domain)
3003         return -EINVAL;
3004 
3005     if (sysfs_streq(buf, "identity"))
3006         req_type = IOMMU_DOMAIN_IDENTITY;
3007     else if (sysfs_streq(buf, "DMA"))
3008         req_type = IOMMU_DOMAIN_DMA;
3009     else if (sysfs_streq(buf, "DMA-FQ"))
3010         req_type = IOMMU_DOMAIN_DMA_FQ;
3011     else if (sysfs_streq(buf, "auto"))
3012         req_type = 0;
3013     else
3014         return -EINVAL;
3015 
3016     /*
3017      * Lock/Unlock the group mutex here before device lock to
3018      * 1. Make sure that the iommu group has only one device (this is a
3019      *    prerequisite for step 2)
3020      * 2. Get struct *dev which is needed to lock device
3021      */
3022     mutex_lock(&group->mutex);
3023     if (iommu_group_device_count(group) != 1) {
3024         mutex_unlock(&group->mutex);
3025         pr_err_ratelimited("Cannot change default domain: Group has more than one device\n");
3026         return -EINVAL;
3027     }
3028 
3029     /* Since group has only one device */
3030     grp_dev = list_first_entry(&group->devices, struct group_device, list);
3031     dev = grp_dev->dev;
3032     get_device(dev);
3033 
3034     /*
3035      * Don't hold the group mutex because taking group mutex first and then
3036      * the device lock could potentially cause a deadlock as below. Assume
3037      * two threads T1 and T2. T1 is trying to change default domain of an
3038      * iommu group and T2 is trying to hot unplug a device or release [1] VF
3039      * of a PCIe device which is in the same iommu group. T1 takes group
3040      * mutex and before it could take device lock assume T2 has taken device
3041      * lock and is yet to take group mutex. Now, both the threads will be
3042      * waiting for the other thread to release lock. Below, lock order was
3043      * suggested.
3044      * device_lock(dev);
3045      *  mutex_lock(&group->mutex);
3046      *      iommu_change_dev_def_domain();
3047      *  mutex_unlock(&group->mutex);
3048      * device_unlock(dev);
3049      *
3050      * [1] Typical device release path
3051      * device_lock() from device/driver core code
3052      *  -> bus_notifier()
3053      *   -> iommu_bus_notifier()
3054      *    -> iommu_release_device()
3055      *     -> ops->release_device() vendor driver calls back iommu core code
3056      *      -> mutex_lock() from iommu core code
3057      */
3058     mutex_unlock(&group->mutex);
3059 
3060     /* Check if the device in the group still has a driver bound to it */
3061     device_lock(dev);
3062     if (device_is_bound(dev) && !(req_type == IOMMU_DOMAIN_DMA_FQ &&
3063         group->default_domain->type == IOMMU_DOMAIN_DMA)) {
3064         pr_err_ratelimited("Device is still bound to driver\n");
3065         ret = -EBUSY;
3066         goto out;
3067     }
3068 
3069     ret = iommu_change_dev_def_domain(group, dev, req_type);
3070     ret = ret ?: count;
3071 
3072 out:
3073     device_unlock(dev);
3074     put_device(dev);
3075 
3076     return ret;
3077 }
3078 
3079 static bool iommu_is_default_domain(struct iommu_group *group)
3080 {
3081     if (group->domain == group->default_domain)
3082         return true;
3083 
3084     /*
3085      * If the default domain was set to identity and it is still an identity
3086      * domain then we consider this a pass. This happens because of
3087      * amd_iommu_init_device() replacing the default idenytity domain with an
3088      * identity domain that has a different configuration for AMDGPU.
3089      */
3090     if (group->default_domain &&
3091         group->default_domain->type == IOMMU_DOMAIN_IDENTITY &&
3092         group->domain && group->domain->type == IOMMU_DOMAIN_IDENTITY)
3093         return true;
3094     return false;
3095 }
3096 
3097 /**
3098  * iommu_device_use_default_domain() - Device driver wants to handle device
3099  *                                     DMA through the kernel DMA API.
3100  * @dev: The device.
3101  *
3102  * The device driver about to bind @dev wants to do DMA through the kernel
3103  * DMA API. Return 0 if it is allowed, otherwise an error.
3104  */
3105 int iommu_device_use_default_domain(struct device *dev)
3106 {
3107     struct iommu_group *group = iommu_group_get(dev);
3108     int ret = 0;
3109 
3110     if (!group)
3111         return 0;
3112 
3113     mutex_lock(&group->mutex);
3114     if (group->owner_cnt) {
3115         if (group->owner || !iommu_is_default_domain(group)) {
3116             ret = -EBUSY;
3117             goto unlock_out;
3118         }
3119     }
3120 
3121     group->owner_cnt++;
3122 
3123 unlock_out:
3124     mutex_unlock(&group->mutex);
3125     iommu_group_put(group);
3126 
3127     return ret;
3128 }
3129 
3130 /**
3131  * iommu_device_unuse_default_domain() - Device driver stops handling device
3132  *                                       DMA through the kernel DMA API.
3133  * @dev: The device.
3134  *
3135  * The device driver doesn't want to do DMA through kernel DMA API anymore.
3136  * It must be called after iommu_device_use_default_domain().
3137  */
3138 void iommu_device_unuse_default_domain(struct device *dev)
3139 {
3140     struct iommu_group *group = iommu_group_get(dev);
3141 
3142     if (!group)
3143         return;
3144 
3145     mutex_lock(&group->mutex);
3146     if (!WARN_ON(!group->owner_cnt))
3147         group->owner_cnt--;
3148 
3149     mutex_unlock(&group->mutex);
3150     iommu_group_put(group);
3151 }
3152 
3153 static int __iommu_group_alloc_blocking_domain(struct iommu_group *group)
3154 {
3155     struct group_device *dev =
3156         list_first_entry(&group->devices, struct group_device, list);
3157 
3158     if (group->blocking_domain)
3159         return 0;
3160 
3161     group->blocking_domain =
3162         __iommu_domain_alloc(dev->dev->bus, IOMMU_DOMAIN_BLOCKED);
3163     if (!group->blocking_domain) {
3164         /*
3165          * For drivers that do not yet understand IOMMU_DOMAIN_BLOCKED
3166          * create an empty domain instead.
3167          */
3168         group->blocking_domain = __iommu_domain_alloc(
3169             dev->dev->bus, IOMMU_DOMAIN_UNMANAGED);
3170         if (!group->blocking_domain)
3171             return -EINVAL;
3172     }
3173     return 0;
3174 }
3175 
3176 /**
3177  * iommu_group_claim_dma_owner() - Set DMA ownership of a group
3178  * @group: The group.
3179  * @owner: Caller specified pointer. Used for exclusive ownership.
3180  *
3181  * This is to support backward compatibility for vfio which manages
3182  * the dma ownership in iommu_group level. New invocations on this
3183  * interface should be prohibited.
3184  */
3185 int iommu_group_claim_dma_owner(struct iommu_group *group, void *owner)
3186 {
3187     int ret = 0;
3188 
3189     mutex_lock(&group->mutex);
3190     if (group->owner_cnt) {
3191         ret = -EPERM;
3192         goto unlock_out;
3193     } else {
3194         if (group->domain && group->domain != group->default_domain) {
3195             ret = -EBUSY;
3196             goto unlock_out;
3197         }
3198 
3199         ret = __iommu_group_alloc_blocking_domain(group);
3200         if (ret)
3201             goto unlock_out;
3202 
3203         ret = __iommu_group_set_domain(group, group->blocking_domain);
3204         if (ret)
3205             goto unlock_out;
3206         group->owner = owner;
3207     }
3208 
3209     group->owner_cnt++;
3210 unlock_out:
3211     mutex_unlock(&group->mutex);
3212 
3213     return ret;
3214 }
3215 EXPORT_SYMBOL_GPL(iommu_group_claim_dma_owner);
3216 
3217 /**
3218  * iommu_group_release_dma_owner() - Release DMA ownership of a group
3219  * @group: The group.
3220  *
3221  * Release the DMA ownership claimed by iommu_group_claim_dma_owner().
3222  */
3223 void iommu_group_release_dma_owner(struct iommu_group *group)
3224 {
3225     int ret;
3226 
3227     mutex_lock(&group->mutex);
3228     if (WARN_ON(!group->owner_cnt || !group->owner))
3229         goto unlock_out;
3230 
3231     group->owner_cnt = 0;
3232     group->owner = NULL;
3233     ret = __iommu_group_set_domain(group, group->default_domain);
3234     WARN(ret, "iommu driver failed to attach the default domain");
3235 
3236 unlock_out:
3237     mutex_unlock(&group->mutex);
3238 }
3239 EXPORT_SYMBOL_GPL(iommu_group_release_dma_owner);
3240 
3241 /**
3242  * iommu_group_dma_owner_claimed() - Query group dma ownership status
3243  * @group: The group.
3244  *
3245  * This provides status query on a given group. It is racy and only for
3246  * non-binding status reporting.
3247  */
3248 bool iommu_group_dma_owner_claimed(struct iommu_group *group)
3249 {
3250     unsigned int user;
3251 
3252     mutex_lock(&group->mutex);
3253     user = group->owner_cnt;
3254     mutex_unlock(&group->mutex);
3255 
3256     return user;
3257 }
3258 EXPORT_SYMBOL_GPL(iommu_group_dma_owner_claimed);