iommu: Retire bus ops
[linux-2.6-microblaze.git] / drivers / iommu / iommu.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright (C) 2007-2008 Advanced Micro Devices, Inc.
4  * Author: Joerg Roedel <jroedel@suse.de>
5  */
6
7 #define pr_fmt(fmt)    "iommu: " fmt
8
9 #include <linux/amba/bus.h>
10 #include <linux/device.h>
11 #include <linux/kernel.h>
12 #include <linux/bits.h>
13 #include <linux/bug.h>
14 #include <linux/types.h>
15 #include <linux/init.h>
16 #include <linux/export.h>
17 #include <linux/slab.h>
18 #include <linux/errno.h>
19 #include <linux/host1x_context_bus.h>
20 #include <linux/iommu.h>
21 #include <linux/idr.h>
22 #include <linux/err.h>
23 #include <linux/pci.h>
24 #include <linux/pci-ats.h>
25 #include <linux/bitops.h>
26 #include <linux/platform_device.h>
27 #include <linux/property.h>
28 #include <linux/fsl/mc.h>
29 #include <linux/module.h>
30 #include <linux/cc_platform.h>
31 #include <linux/cdx/cdx_bus.h>
32 #include <trace/events/iommu.h>
33 #include <linux/sched/mm.h>
34 #include <linux/msi.h>
35
36 #include "dma-iommu.h"
37 #include "iommu-priv.h"
38
39 #include "iommu-sva.h"
40
41 static struct kset *iommu_group_kset;
42 static DEFINE_IDA(iommu_group_ida);
43 static DEFINE_IDA(iommu_global_pasid_ida);
44
45 static unsigned int iommu_def_domain_type __read_mostly;
46 static bool iommu_dma_strict __read_mostly = IS_ENABLED(CONFIG_IOMMU_DEFAULT_DMA_STRICT);
47 static u32 iommu_cmd_line __read_mostly;
48
49 struct iommu_group {
50         struct kobject kobj;
51         struct kobject *devices_kobj;
52         struct list_head devices;
53         struct xarray pasid_array;
54         struct mutex mutex;
55         void *iommu_data;
56         void (*iommu_data_release)(void *iommu_data);
57         char *name;
58         int id;
59         struct iommu_domain *default_domain;
60         struct iommu_domain *blocking_domain;
61         struct iommu_domain *domain;
62         struct list_head entry;
63         unsigned int owner_cnt;
64         void *owner;
65 };
66
67 struct group_device {
68         struct list_head list;
69         struct device *dev;
70         char *name;
71 };
72
73 /* Iterate over each struct group_device in a struct iommu_group */
74 #define for_each_group_device(group, pos) \
75         list_for_each_entry(pos, &(group)->devices, list)
76
77 struct iommu_group_attribute {
78         struct attribute attr;
79         ssize_t (*show)(struct iommu_group *group, char *buf);
80         ssize_t (*store)(struct iommu_group *group,
81                          const char *buf, size_t count);
82 };
83
84 static const char * const iommu_group_resv_type_string[] = {
85         [IOMMU_RESV_DIRECT]                     = "direct",
86         [IOMMU_RESV_DIRECT_RELAXABLE]           = "direct-relaxable",
87         [IOMMU_RESV_RESERVED]                   = "reserved",
88         [IOMMU_RESV_MSI]                        = "msi",
89         [IOMMU_RESV_SW_MSI]                     = "msi",
90 };
91
92 #define IOMMU_CMD_LINE_DMA_API          BIT(0)
93 #define IOMMU_CMD_LINE_STRICT           BIT(1)
94
95 static int iommu_bus_notifier(struct notifier_block *nb,
96                               unsigned long action, void *data);
97 static void iommu_release_device(struct device *dev);
98 static struct iommu_domain *
99 __iommu_group_domain_alloc(struct iommu_group *group, unsigned int type);
100 static int __iommu_attach_device(struct iommu_domain *domain,
101                                  struct device *dev);
102 static int __iommu_attach_group(struct iommu_domain *domain,
103                                 struct iommu_group *group);
104
105 enum {
106         IOMMU_SET_DOMAIN_MUST_SUCCEED = 1 << 0,
107 };
108
109 static int __iommu_device_set_domain(struct iommu_group *group,
110                                      struct device *dev,
111                                      struct iommu_domain *new_domain,
112                                      unsigned int flags);
113 static int __iommu_group_set_domain_internal(struct iommu_group *group,
114                                              struct iommu_domain *new_domain,
115                                              unsigned int flags);
116 static int __iommu_group_set_domain(struct iommu_group *group,
117                                     struct iommu_domain *new_domain)
118 {
119         return __iommu_group_set_domain_internal(group, new_domain, 0);
120 }
121 static void __iommu_group_set_domain_nofail(struct iommu_group *group,
122                                             struct iommu_domain *new_domain)
123 {
124         WARN_ON(__iommu_group_set_domain_internal(
125                 group, new_domain, IOMMU_SET_DOMAIN_MUST_SUCCEED));
126 }
127
128 static int iommu_setup_default_domain(struct iommu_group *group,
129                                       int target_type);
130 static int iommu_create_device_direct_mappings(struct iommu_domain *domain,
131                                                struct device *dev);
132 static ssize_t iommu_group_store_type(struct iommu_group *group,
133                                       const char *buf, size_t count);
134 static struct group_device *iommu_group_alloc_device(struct iommu_group *group,
135                                                      struct device *dev);
136 static void __iommu_group_free_device(struct iommu_group *group,
137                                       struct group_device *grp_dev);
138
139 #define IOMMU_GROUP_ATTR(_name, _mode, _show, _store)           \
140 struct iommu_group_attribute iommu_group_attr_##_name =         \
141         __ATTR(_name, _mode, _show, _store)
142
143 #define to_iommu_group_attr(_attr)      \
144         container_of(_attr, struct iommu_group_attribute, attr)
145 #define to_iommu_group(_kobj)           \
146         container_of(_kobj, struct iommu_group, kobj)
147
148 static LIST_HEAD(iommu_device_list);
149 static DEFINE_SPINLOCK(iommu_device_lock);
150
151 static const struct bus_type * const iommu_buses[] = {
152         &platform_bus_type,
153 #ifdef CONFIG_PCI
154         &pci_bus_type,
155 #endif
156 #ifdef CONFIG_ARM_AMBA
157         &amba_bustype,
158 #endif
159 #ifdef CONFIG_FSL_MC_BUS
160         &fsl_mc_bus_type,
161 #endif
162 #ifdef CONFIG_TEGRA_HOST1X_CONTEXT_BUS
163         &host1x_context_device_bus_type,
164 #endif
165 #ifdef CONFIG_CDX_BUS
166         &cdx_bus_type,
167 #endif
168 };
169
170 /*
171  * Use a function instead of an array here because the domain-type is a
172  * bit-field, so an array would waste memory.
173  */
174 static const char *iommu_domain_type_str(unsigned int t)
175 {
176         switch (t) {
177         case IOMMU_DOMAIN_BLOCKED:
178                 return "Blocked";
179         case IOMMU_DOMAIN_IDENTITY:
180                 return "Passthrough";
181         case IOMMU_DOMAIN_UNMANAGED:
182                 return "Unmanaged";
183         case IOMMU_DOMAIN_DMA:
184         case IOMMU_DOMAIN_DMA_FQ:
185                 return "Translated";
186         case IOMMU_DOMAIN_PLATFORM:
187                 return "Platform";
188         default:
189                 return "Unknown";
190         }
191 }
192
193 static int __init iommu_subsys_init(void)
194 {
195         struct notifier_block *nb;
196
197         if (!(iommu_cmd_line & IOMMU_CMD_LINE_DMA_API)) {
198                 if (IS_ENABLED(CONFIG_IOMMU_DEFAULT_PASSTHROUGH))
199                         iommu_set_default_passthrough(false);
200                 else
201                         iommu_set_default_translated(false);
202
203                 if (iommu_default_passthrough() && cc_platform_has(CC_ATTR_MEM_ENCRYPT)) {
204                         pr_info("Memory encryption detected - Disabling default IOMMU Passthrough\n");
205                         iommu_set_default_translated(false);
206                 }
207         }
208
209         if (!iommu_default_passthrough() && !iommu_dma_strict)
210                 iommu_def_domain_type = IOMMU_DOMAIN_DMA_FQ;
211
212         pr_info("Default domain type: %s%s\n",
213                 iommu_domain_type_str(iommu_def_domain_type),
214                 (iommu_cmd_line & IOMMU_CMD_LINE_DMA_API) ?
215                         " (set via kernel command line)" : "");
216
217         if (!iommu_default_passthrough())
218                 pr_info("DMA domain TLB invalidation policy: %s mode%s\n",
219                         iommu_dma_strict ? "strict" : "lazy",
220                         (iommu_cmd_line & IOMMU_CMD_LINE_STRICT) ?
221                                 " (set via kernel command line)" : "");
222
223         nb = kcalloc(ARRAY_SIZE(iommu_buses), sizeof(*nb), GFP_KERNEL);
224         if (!nb)
225                 return -ENOMEM;
226
227         for (int i = 0; i < ARRAY_SIZE(iommu_buses); i++) {
228                 nb[i].notifier_call = iommu_bus_notifier;
229                 bus_register_notifier(iommu_buses[i], &nb[i]);
230         }
231
232         return 0;
233 }
234 subsys_initcall(iommu_subsys_init);
235
236 static int remove_iommu_group(struct device *dev, void *data)
237 {
238         if (dev->iommu && dev->iommu->iommu_dev == data)
239                 iommu_release_device(dev);
240
241         return 0;
242 }
243
244 /**
245  * iommu_device_register() - Register an IOMMU hardware instance
246  * @iommu: IOMMU handle for the instance
247  * @ops:   IOMMU ops to associate with the instance
248  * @hwdev: (optional) actual instance device, used for fwnode lookup
249  *
250  * Return: 0 on success, or an error.
251  */
252 int iommu_device_register(struct iommu_device *iommu,
253                           const struct iommu_ops *ops, struct device *hwdev)
254 {
255         int err = 0;
256
257         /* We need to be able to take module references appropriately */
258         if (WARN_ON(is_module_address((unsigned long)ops) && !ops->owner))
259                 return -EINVAL;
260
261         iommu->ops = ops;
262         if (hwdev)
263                 iommu->fwnode = dev_fwnode(hwdev);
264
265         spin_lock(&iommu_device_lock);
266         list_add_tail(&iommu->list, &iommu_device_list);
267         spin_unlock(&iommu_device_lock);
268
269         for (int i = 0; i < ARRAY_SIZE(iommu_buses) && !err; i++)
270                 err = bus_iommu_probe(iommu_buses[i]);
271         if (err)
272                 iommu_device_unregister(iommu);
273         return err;
274 }
275 EXPORT_SYMBOL_GPL(iommu_device_register);
276
277 void iommu_device_unregister(struct iommu_device *iommu)
278 {
279         for (int i = 0; i < ARRAY_SIZE(iommu_buses); i++)
280                 bus_for_each_dev(iommu_buses[i], NULL, iommu, remove_iommu_group);
281
282         spin_lock(&iommu_device_lock);
283         list_del(&iommu->list);
284         spin_unlock(&iommu_device_lock);
285
286         /* Pairs with the alloc in generic_single_device_group() */
287         iommu_group_put(iommu->singleton_group);
288         iommu->singleton_group = NULL;
289 }
290 EXPORT_SYMBOL_GPL(iommu_device_unregister);
291
292 #if IS_ENABLED(CONFIG_IOMMUFD_TEST)
293 void iommu_device_unregister_bus(struct iommu_device *iommu,
294                                  struct bus_type *bus,
295                                  struct notifier_block *nb)
296 {
297         bus_unregister_notifier(bus, nb);
298         iommu_device_unregister(iommu);
299 }
300 EXPORT_SYMBOL_GPL(iommu_device_unregister_bus);
301
302 /*
303  * Register an iommu driver against a single bus. This is only used by iommufd
304  * selftest to create a mock iommu driver. The caller must provide
305  * some memory to hold a notifier_block.
306  */
307 int iommu_device_register_bus(struct iommu_device *iommu,
308                               const struct iommu_ops *ops, struct bus_type *bus,
309                               struct notifier_block *nb)
310 {
311         int err;
312
313         iommu->ops = ops;
314         nb->notifier_call = iommu_bus_notifier;
315         err = bus_register_notifier(bus, nb);
316         if (err)
317                 return err;
318
319         spin_lock(&iommu_device_lock);
320         list_add_tail(&iommu->list, &iommu_device_list);
321         spin_unlock(&iommu_device_lock);
322
323         err = bus_iommu_probe(bus);
324         if (err) {
325                 iommu_device_unregister_bus(iommu, bus, nb);
326                 return err;
327         }
328         return 0;
329 }
330 EXPORT_SYMBOL_GPL(iommu_device_register_bus);
331 #endif
332
333 static struct dev_iommu *dev_iommu_get(struct device *dev)
334 {
335         struct dev_iommu *param = dev->iommu;
336
337         if (param)
338                 return param;
339
340         param = kzalloc(sizeof(*param), GFP_KERNEL);
341         if (!param)
342                 return NULL;
343
344         mutex_init(&param->lock);
345         dev->iommu = param;
346         return param;
347 }
348
349 static void dev_iommu_free(struct device *dev)
350 {
351         struct dev_iommu *param = dev->iommu;
352
353         dev->iommu = NULL;
354         if (param->fwspec) {
355                 fwnode_handle_put(param->fwspec->iommu_fwnode);
356                 kfree(param->fwspec);
357         }
358         kfree(param);
359 }
360
361 /*
362  * Internal equivalent of device_iommu_mapped() for when we care that a device
363  * actually has API ops, and don't want false positives from VFIO-only groups.
364  */
365 static bool dev_has_iommu(struct device *dev)
366 {
367         return dev->iommu && dev->iommu->iommu_dev;
368 }
369
370 static u32 dev_iommu_get_max_pasids(struct device *dev)
371 {
372         u32 max_pasids = 0, bits = 0;
373         int ret;
374
375         if (dev_is_pci(dev)) {
376                 ret = pci_max_pasids(to_pci_dev(dev));
377                 if (ret > 0)
378                         max_pasids = ret;
379         } else {
380                 ret = device_property_read_u32(dev, "pasid-num-bits", &bits);
381                 if (!ret)
382                         max_pasids = 1UL << bits;
383         }
384
385         return min_t(u32, max_pasids, dev->iommu->iommu_dev->max_pasids);
386 }
387
388 /*
389  * Init the dev->iommu and dev->iommu_group in the struct device and get the
390  * driver probed
391  */
392 static int iommu_init_device(struct device *dev, const struct iommu_ops *ops)
393 {
394         struct iommu_device *iommu_dev;
395         struct iommu_group *group;
396         int ret;
397
398         if (!dev_iommu_get(dev))
399                 return -ENOMEM;
400
401         if (!try_module_get(ops->owner)) {
402                 ret = -EINVAL;
403                 goto err_free;
404         }
405
406         iommu_dev = ops->probe_device(dev);
407         if (IS_ERR(iommu_dev)) {
408                 ret = PTR_ERR(iommu_dev);
409                 goto err_module_put;
410         }
411         dev->iommu->iommu_dev = iommu_dev;
412
413         ret = iommu_device_link(iommu_dev, dev);
414         if (ret)
415                 goto err_release;
416
417         group = ops->device_group(dev);
418         if (WARN_ON_ONCE(group == NULL))
419                 group = ERR_PTR(-EINVAL);
420         if (IS_ERR(group)) {
421                 ret = PTR_ERR(group);
422                 goto err_unlink;
423         }
424         dev->iommu_group = group;
425
426         dev->iommu->max_pasids = dev_iommu_get_max_pasids(dev);
427         if (ops->is_attach_deferred)
428                 dev->iommu->attach_deferred = ops->is_attach_deferred(dev);
429         return 0;
430
431 err_unlink:
432         iommu_device_unlink(iommu_dev, dev);
433 err_release:
434         if (ops->release_device)
435                 ops->release_device(dev);
436 err_module_put:
437         module_put(ops->owner);
438 err_free:
439         dev->iommu->iommu_dev = NULL;
440         dev_iommu_free(dev);
441         return ret;
442 }
443
444 static void iommu_deinit_device(struct device *dev)
445 {
446         struct iommu_group *group = dev->iommu_group;
447         const struct iommu_ops *ops = dev_iommu_ops(dev);
448
449         lockdep_assert_held(&group->mutex);
450
451         iommu_device_unlink(dev->iommu->iommu_dev, dev);
452
453         /*
454          * release_device() must stop using any attached domain on the device.
455          * If there are still other devices in the group they are not effected
456          * by this callback.
457          *
458          * The IOMMU driver must set the device to either an identity or
459          * blocking translation and stop using any domain pointer, as it is
460          * going to be freed.
461          */
462         if (ops->release_device)
463                 ops->release_device(dev);
464
465         /*
466          * If this is the last driver to use the group then we must free the
467          * domains before we do the module_put().
468          */
469         if (list_empty(&group->devices)) {
470                 if (group->default_domain) {
471                         iommu_domain_free(group->default_domain);
472                         group->default_domain = NULL;
473                 }
474                 if (group->blocking_domain) {
475                         iommu_domain_free(group->blocking_domain);
476                         group->blocking_domain = NULL;
477                 }
478                 group->domain = NULL;
479         }
480
481         /* Caller must put iommu_group */
482         dev->iommu_group = NULL;
483         module_put(ops->owner);
484         dev_iommu_free(dev);
485 }
486
487 static int __iommu_probe_device(struct device *dev, struct list_head *group_list)
488 {
489         const struct iommu_ops *ops;
490         struct iommu_fwspec *fwspec;
491         struct iommu_group *group;
492         static DEFINE_MUTEX(iommu_probe_device_lock);
493         struct group_device *gdev;
494         int ret;
495
496         /*
497          * For FDT-based systems and ACPI IORT/VIOT, drivers register IOMMU
498          * instances with non-NULL fwnodes, and client devices should have been
499          * identified with a fwspec by this point. Otherwise, we can currently
500          * assume that only one of Intel, AMD, s390, PAMU or legacy SMMUv2 can
501          * be present, and that any of their registered instances has suitable
502          * ops for probing, and thus cheekily co-opt the same mechanism.
503          */
504         fwspec = dev_iommu_fwspec_get(dev);
505         if (fwspec && fwspec->ops)
506                 ops = fwspec->ops;
507         else
508                 ops = iommu_ops_from_fwnode(NULL);
509
510         if (!ops)
511                 return -ENODEV;
512         /*
513          * Serialise to avoid races between IOMMU drivers registering in
514          * parallel and/or the "replay" calls from ACPI/OF code via client
515          * driver probe. Once the latter have been cleaned up we should
516          * probably be able to use device_lock() here to minimise the scope,
517          * but for now enforcing a simple global ordering is fine.
518          */
519         mutex_lock(&iommu_probe_device_lock);
520
521         /* Device is probed already if in a group */
522         if (dev->iommu_group) {
523                 ret = 0;
524                 goto out_unlock;
525         }
526
527         ret = iommu_init_device(dev, ops);
528         if (ret)
529                 goto out_unlock;
530
531         group = dev->iommu_group;
532         gdev = iommu_group_alloc_device(group, dev);
533         mutex_lock(&group->mutex);
534         if (IS_ERR(gdev)) {
535                 ret = PTR_ERR(gdev);
536                 goto err_put_group;
537         }
538
539         /*
540          * The gdev must be in the list before calling
541          * iommu_setup_default_domain()
542          */
543         list_add_tail(&gdev->list, &group->devices);
544         WARN_ON(group->default_domain && !group->domain);
545         if (group->default_domain)
546                 iommu_create_device_direct_mappings(group->default_domain, dev);
547         if (group->domain) {
548                 ret = __iommu_device_set_domain(group, dev, group->domain, 0);
549                 if (ret)
550                         goto err_remove_gdev;
551         } else if (!group->default_domain && !group_list) {
552                 ret = iommu_setup_default_domain(group, 0);
553                 if (ret)
554                         goto err_remove_gdev;
555         } else if (!group->default_domain) {
556                 /*
557                  * With a group_list argument we defer the default_domain setup
558                  * to the caller by providing a de-duplicated list of groups
559                  * that need further setup.
560                  */
561                 if (list_empty(&group->entry))
562                         list_add_tail(&group->entry, group_list);
563         }
564         mutex_unlock(&group->mutex);
565         mutex_unlock(&iommu_probe_device_lock);
566
567         if (dev_is_pci(dev))
568                 iommu_dma_set_pci_32bit_workaround(dev);
569
570         return 0;
571
572 err_remove_gdev:
573         list_del(&gdev->list);
574         __iommu_group_free_device(group, gdev);
575 err_put_group:
576         iommu_deinit_device(dev);
577         mutex_unlock(&group->mutex);
578         iommu_group_put(group);
579 out_unlock:
580         mutex_unlock(&iommu_probe_device_lock);
581
582         return ret;
583 }
584
585 int iommu_probe_device(struct device *dev)
586 {
587         const struct iommu_ops *ops;
588         int ret;
589
590         ret = __iommu_probe_device(dev, NULL);
591         if (ret)
592                 return ret;
593
594         ops = dev_iommu_ops(dev);
595         if (ops->probe_finalize)
596                 ops->probe_finalize(dev);
597
598         return 0;
599 }
600
601 static void __iommu_group_free_device(struct iommu_group *group,
602                                       struct group_device *grp_dev)
603 {
604         struct device *dev = grp_dev->dev;
605
606         sysfs_remove_link(group->devices_kobj, grp_dev->name);
607         sysfs_remove_link(&dev->kobj, "iommu_group");
608
609         trace_remove_device_from_group(group->id, dev);
610
611         /*
612          * If the group has become empty then ownership must have been
613          * released, and the current domain must be set back to NULL or
614          * the default domain.
615          */
616         if (list_empty(&group->devices))
617                 WARN_ON(group->owner_cnt ||
618                         group->domain != group->default_domain);
619
620         kfree(grp_dev->name);
621         kfree(grp_dev);
622 }
623
624 /* Remove the iommu_group from the struct device. */
625 static void __iommu_group_remove_device(struct device *dev)
626 {
627         struct iommu_group *group = dev->iommu_group;
628         struct group_device *device;
629
630         mutex_lock(&group->mutex);
631         for_each_group_device(group, device) {
632                 if (device->dev != dev)
633                         continue;
634
635                 list_del(&device->list);
636                 __iommu_group_free_device(group, device);
637                 if (dev_has_iommu(dev))
638                         iommu_deinit_device(dev);
639                 else
640                         dev->iommu_group = NULL;
641                 break;
642         }
643         mutex_unlock(&group->mutex);
644
645         /*
646          * Pairs with the get in iommu_init_device() or
647          * iommu_group_add_device()
648          */
649         iommu_group_put(group);
650 }
651
652 static void iommu_release_device(struct device *dev)
653 {
654         struct iommu_group *group = dev->iommu_group;
655
656         if (group)
657                 __iommu_group_remove_device(dev);
658
659         /* Free any fwspec if no iommu_driver was ever attached */
660         if (dev->iommu)
661                 dev_iommu_free(dev);
662 }
663
664 static int __init iommu_set_def_domain_type(char *str)
665 {
666         bool pt;
667         int ret;
668
669         ret = kstrtobool(str, &pt);
670         if (ret)
671                 return ret;
672
673         if (pt)
674                 iommu_set_default_passthrough(true);
675         else
676                 iommu_set_default_translated(true);
677
678         return 0;
679 }
680 early_param("iommu.passthrough", iommu_set_def_domain_type);
681
682 static int __init iommu_dma_setup(char *str)
683 {
684         int ret = kstrtobool(str, &iommu_dma_strict);
685
686         if (!ret)
687                 iommu_cmd_line |= IOMMU_CMD_LINE_STRICT;
688         return ret;
689 }
690 early_param("iommu.strict", iommu_dma_setup);
691
692 void iommu_set_dma_strict(void)
693 {
694         iommu_dma_strict = true;
695         if (iommu_def_domain_type == IOMMU_DOMAIN_DMA_FQ)
696                 iommu_def_domain_type = IOMMU_DOMAIN_DMA;
697 }
698
699 static ssize_t iommu_group_attr_show(struct kobject *kobj,
700                                      struct attribute *__attr, char *buf)
701 {
702         struct iommu_group_attribute *attr = to_iommu_group_attr(__attr);
703         struct iommu_group *group = to_iommu_group(kobj);
704         ssize_t ret = -EIO;
705
706         if (attr->show)
707                 ret = attr->show(group, buf);
708         return ret;
709 }
710
711 static ssize_t iommu_group_attr_store(struct kobject *kobj,
712                                       struct attribute *__attr,
713                                       const char *buf, size_t count)
714 {
715         struct iommu_group_attribute *attr = to_iommu_group_attr(__attr);
716         struct iommu_group *group = to_iommu_group(kobj);
717         ssize_t ret = -EIO;
718
719         if (attr->store)
720                 ret = attr->store(group, buf, count);
721         return ret;
722 }
723
724 static const struct sysfs_ops iommu_group_sysfs_ops = {
725         .show = iommu_group_attr_show,
726         .store = iommu_group_attr_store,
727 };
728
729 static int iommu_group_create_file(struct iommu_group *group,
730                                    struct iommu_group_attribute *attr)
731 {
732         return sysfs_create_file(&group->kobj, &attr->attr);
733 }
734
735 static void iommu_group_remove_file(struct iommu_group *group,
736                                     struct iommu_group_attribute *attr)
737 {
738         sysfs_remove_file(&group->kobj, &attr->attr);
739 }
740
741 static ssize_t iommu_group_show_name(struct iommu_group *group, char *buf)
742 {
743         return sysfs_emit(buf, "%s\n", group->name);
744 }
745
746 /**
747  * iommu_insert_resv_region - Insert a new region in the
748  * list of reserved regions.
749  * @new: new region to insert
750  * @regions: list of regions
751  *
752  * Elements are sorted by start address and overlapping segments
753  * of the same type are merged.
754  */
755 static int iommu_insert_resv_region(struct iommu_resv_region *new,
756                                     struct list_head *regions)
757 {
758         struct iommu_resv_region *iter, *tmp, *nr, *top;
759         LIST_HEAD(stack);
760
761         nr = iommu_alloc_resv_region(new->start, new->length,
762                                      new->prot, new->type, GFP_KERNEL);
763         if (!nr)
764                 return -ENOMEM;
765
766         /* First add the new element based on start address sorting */
767         list_for_each_entry(iter, regions, list) {
768                 if (nr->start < iter->start ||
769                     (nr->start == iter->start && nr->type <= iter->type))
770                         break;
771         }
772         list_add_tail(&nr->list, &iter->list);
773
774         /* Merge overlapping segments of type nr->type in @regions, if any */
775         list_for_each_entry_safe(iter, tmp, regions, list) {
776                 phys_addr_t top_end, iter_end = iter->start + iter->length - 1;
777
778                 /* no merge needed on elements of different types than @new */
779                 if (iter->type != new->type) {
780                         list_move_tail(&iter->list, &stack);
781                         continue;
782                 }
783
784                 /* look for the last stack element of same type as @iter */
785                 list_for_each_entry_reverse(top, &stack, list)
786                         if (top->type == iter->type)
787                                 goto check_overlap;
788
789                 list_move_tail(&iter->list, &stack);
790                 continue;
791
792 check_overlap:
793                 top_end = top->start + top->length - 1;
794
795                 if (iter->start > top_end + 1) {
796                         list_move_tail(&iter->list, &stack);
797                 } else {
798                         top->length = max(top_end, iter_end) - top->start + 1;
799                         list_del(&iter->list);
800                         kfree(iter);
801                 }
802         }
803         list_splice(&stack, regions);
804         return 0;
805 }
806
807 static int
808 iommu_insert_device_resv_regions(struct list_head *dev_resv_regions,
809                                  struct list_head *group_resv_regions)
810 {
811         struct iommu_resv_region *entry;
812         int ret = 0;
813
814         list_for_each_entry(entry, dev_resv_regions, list) {
815                 ret = iommu_insert_resv_region(entry, group_resv_regions);
816                 if (ret)
817                         break;
818         }
819         return ret;
820 }
821
822 int iommu_get_group_resv_regions(struct iommu_group *group,
823                                  struct list_head *head)
824 {
825         struct group_device *device;
826         int ret = 0;
827
828         mutex_lock(&group->mutex);
829         for_each_group_device(group, device) {
830                 struct list_head dev_resv_regions;
831
832                 /*
833                  * Non-API groups still expose reserved_regions in sysfs,
834                  * so filter out calls that get here that way.
835                  */
836                 if (!dev_has_iommu(device->dev))
837                         break;
838
839                 INIT_LIST_HEAD(&dev_resv_regions);
840                 iommu_get_resv_regions(device->dev, &dev_resv_regions);
841                 ret = iommu_insert_device_resv_regions(&dev_resv_regions, head);
842                 iommu_put_resv_regions(device->dev, &dev_resv_regions);
843                 if (ret)
844                         break;
845         }
846         mutex_unlock(&group->mutex);
847         return ret;
848 }
849 EXPORT_SYMBOL_GPL(iommu_get_group_resv_regions);
850
851 static ssize_t iommu_group_show_resv_regions(struct iommu_group *group,
852                                              char *buf)
853 {
854         struct iommu_resv_region *region, *next;
855         struct list_head group_resv_regions;
856         int offset = 0;
857
858         INIT_LIST_HEAD(&group_resv_regions);
859         iommu_get_group_resv_regions(group, &group_resv_regions);
860
861         list_for_each_entry_safe(region, next, &group_resv_regions, list) {
862                 offset += sysfs_emit_at(buf, offset, "0x%016llx 0x%016llx %s\n",
863                                         (long long)region->start,
864                                         (long long)(region->start +
865                                                     region->length - 1),
866                                         iommu_group_resv_type_string[region->type]);
867                 kfree(region);
868         }
869
870         return offset;
871 }
872
873 static ssize_t iommu_group_show_type(struct iommu_group *group,
874                                      char *buf)
875 {
876         char *type = "unknown";
877
878         mutex_lock(&group->mutex);
879         if (group->default_domain) {
880                 switch (group->default_domain->type) {
881                 case IOMMU_DOMAIN_BLOCKED:
882                         type = "blocked";
883                         break;
884                 case IOMMU_DOMAIN_IDENTITY:
885                         type = "identity";
886                         break;
887                 case IOMMU_DOMAIN_UNMANAGED:
888                         type = "unmanaged";
889                         break;
890                 case IOMMU_DOMAIN_DMA:
891                         type = "DMA";
892                         break;
893                 case IOMMU_DOMAIN_DMA_FQ:
894                         type = "DMA-FQ";
895                         break;
896                 }
897         }
898         mutex_unlock(&group->mutex);
899
900         return sysfs_emit(buf, "%s\n", type);
901 }
902
903 static IOMMU_GROUP_ATTR(name, S_IRUGO, iommu_group_show_name, NULL);
904
905 static IOMMU_GROUP_ATTR(reserved_regions, 0444,
906                         iommu_group_show_resv_regions, NULL);
907
908 static IOMMU_GROUP_ATTR(type, 0644, iommu_group_show_type,
909                         iommu_group_store_type);
910
911 static void iommu_group_release(struct kobject *kobj)
912 {
913         struct iommu_group *group = to_iommu_group(kobj);
914
915         pr_debug("Releasing group %d\n", group->id);
916
917         if (group->iommu_data_release)
918                 group->iommu_data_release(group->iommu_data);
919
920         ida_free(&iommu_group_ida, group->id);
921
922         /* Domains are free'd by iommu_deinit_device() */
923         WARN_ON(group->default_domain);
924         WARN_ON(group->blocking_domain);
925
926         kfree(group->name);
927         kfree(group);
928 }
929
930 static const struct kobj_type iommu_group_ktype = {
931         .sysfs_ops = &iommu_group_sysfs_ops,
932         .release = iommu_group_release,
933 };
934
935 /**
936  * iommu_group_alloc - Allocate a new group
937  *
938  * This function is called by an iommu driver to allocate a new iommu
939  * group.  The iommu group represents the minimum granularity of the iommu.
940  * Upon successful return, the caller holds a reference to the supplied
941  * group in order to hold the group until devices are added.  Use
942  * iommu_group_put() to release this extra reference count, allowing the
943  * group to be automatically reclaimed once it has no devices or external
944  * references.
945  */
946 struct iommu_group *iommu_group_alloc(void)
947 {
948         struct iommu_group *group;
949         int ret;
950
951         group = kzalloc(sizeof(*group), GFP_KERNEL);
952         if (!group)
953                 return ERR_PTR(-ENOMEM);
954
955         group->kobj.kset = iommu_group_kset;
956         mutex_init(&group->mutex);
957         INIT_LIST_HEAD(&group->devices);
958         INIT_LIST_HEAD(&group->entry);
959         xa_init(&group->pasid_array);
960
961         ret = ida_alloc(&iommu_group_ida, GFP_KERNEL);
962         if (ret < 0) {
963                 kfree(group);
964                 return ERR_PTR(ret);
965         }
966         group->id = ret;
967
968         ret = kobject_init_and_add(&group->kobj, &iommu_group_ktype,
969                                    NULL, "%d", group->id);
970         if (ret) {
971                 kobject_put(&group->kobj);
972                 return ERR_PTR(ret);
973         }
974
975         group->devices_kobj = kobject_create_and_add("devices", &group->kobj);
976         if (!group->devices_kobj) {
977                 kobject_put(&group->kobj); /* triggers .release & free */
978                 return ERR_PTR(-ENOMEM);
979         }
980
981         /*
982          * The devices_kobj holds a reference on the group kobject, so
983          * as long as that exists so will the group.  We can therefore
984          * use the devices_kobj for reference counting.
985          */
986         kobject_put(&group->kobj);
987
988         ret = iommu_group_create_file(group,
989                                       &iommu_group_attr_reserved_regions);
990         if (ret) {
991                 kobject_put(group->devices_kobj);
992                 return ERR_PTR(ret);
993         }
994
995         ret = iommu_group_create_file(group, &iommu_group_attr_type);
996         if (ret) {
997                 kobject_put(group->devices_kobj);
998                 return ERR_PTR(ret);
999         }
1000
1001         pr_debug("Allocated group %d\n", group->id);
1002
1003         return group;
1004 }
1005 EXPORT_SYMBOL_GPL(iommu_group_alloc);
1006
1007 /**
1008  * iommu_group_get_iommudata - retrieve iommu_data registered for a group
1009  * @group: the group
1010  *
1011  * iommu drivers can store data in the group for use when doing iommu
1012  * operations.  This function provides a way to retrieve it.  Caller
1013  * should hold a group reference.
1014  */
1015 void *iommu_group_get_iommudata(struct iommu_group *group)
1016 {
1017         return group->iommu_data;
1018 }
1019 EXPORT_SYMBOL_GPL(iommu_group_get_iommudata);
1020
1021 /**
1022  * iommu_group_set_iommudata - set iommu_data for a group
1023  * @group: the group
1024  * @iommu_data: new data
1025  * @release: release function for iommu_data
1026  *
1027  * iommu drivers can store data in the group for use when doing iommu
1028  * operations.  This function provides a way to set the data after
1029  * the group has been allocated.  Caller should hold a group reference.
1030  */
1031 void iommu_group_set_iommudata(struct iommu_group *group, void *iommu_data,
1032                                void (*release)(void *iommu_data))
1033 {
1034         group->iommu_data = iommu_data;
1035         group->iommu_data_release = release;
1036 }
1037 EXPORT_SYMBOL_GPL(iommu_group_set_iommudata);
1038
1039 /**
1040  * iommu_group_set_name - set name for a group
1041  * @group: the group
1042  * @name: name
1043  *
1044  * Allow iommu driver to set a name for a group.  When set it will
1045  * appear in a name attribute file under the group in sysfs.
1046  */
1047 int iommu_group_set_name(struct iommu_group *group, const char *name)
1048 {
1049         int ret;
1050
1051         if (group->name) {
1052                 iommu_group_remove_file(group, &iommu_group_attr_name);
1053                 kfree(group->name);
1054                 group->name = NULL;
1055                 if (!name)
1056                         return 0;
1057         }
1058
1059         group->name = kstrdup(name, GFP_KERNEL);
1060         if (!group->name)
1061                 return -ENOMEM;
1062
1063         ret = iommu_group_create_file(group, &iommu_group_attr_name);
1064         if (ret) {
1065                 kfree(group->name);
1066                 group->name = NULL;
1067                 return ret;
1068         }
1069
1070         return 0;
1071 }
1072 EXPORT_SYMBOL_GPL(iommu_group_set_name);
1073
1074 static int iommu_create_device_direct_mappings(struct iommu_domain *domain,
1075                                                struct device *dev)
1076 {
1077         struct iommu_resv_region *entry;
1078         struct list_head mappings;
1079         unsigned long pg_size;
1080         int ret = 0;
1081
1082         pg_size = domain->pgsize_bitmap ? 1UL << __ffs(domain->pgsize_bitmap) : 0;
1083         INIT_LIST_HEAD(&mappings);
1084
1085         if (WARN_ON_ONCE(iommu_is_dma_domain(domain) && !pg_size))
1086                 return -EINVAL;
1087
1088         iommu_get_resv_regions(dev, &mappings);
1089
1090         /* We need to consider overlapping regions for different devices */
1091         list_for_each_entry(entry, &mappings, list) {
1092                 dma_addr_t start, end, addr;
1093                 size_t map_size = 0;
1094
1095                 if (entry->type == IOMMU_RESV_DIRECT)
1096                         dev->iommu->require_direct = 1;
1097
1098                 if ((entry->type != IOMMU_RESV_DIRECT &&
1099                      entry->type != IOMMU_RESV_DIRECT_RELAXABLE) ||
1100                     !iommu_is_dma_domain(domain))
1101                         continue;
1102
1103                 start = ALIGN(entry->start, pg_size);
1104                 end   = ALIGN(entry->start + entry->length, pg_size);
1105
1106                 for (addr = start; addr <= end; addr += pg_size) {
1107                         phys_addr_t phys_addr;
1108
1109                         if (addr == end)
1110                                 goto map_end;
1111
1112                         phys_addr = iommu_iova_to_phys(domain, addr);
1113                         if (!phys_addr) {
1114                                 map_size += pg_size;
1115                                 continue;
1116                         }
1117
1118 map_end:
1119                         if (map_size) {
1120                                 ret = iommu_map(domain, addr - map_size,
1121                                                 addr - map_size, map_size,
1122                                                 entry->prot, GFP_KERNEL);
1123                                 if (ret)
1124                                         goto out;
1125                                 map_size = 0;
1126                         }
1127                 }
1128
1129         }
1130
1131         if (!list_empty(&mappings) && iommu_is_dma_domain(domain))
1132                 iommu_flush_iotlb_all(domain);
1133
1134 out:
1135         iommu_put_resv_regions(dev, &mappings);
1136
1137         return ret;
1138 }
1139
1140 /* This is undone by __iommu_group_free_device() */
1141 static struct group_device *iommu_group_alloc_device(struct iommu_group *group,
1142                                                      struct device *dev)
1143 {
1144         int ret, i = 0;
1145         struct group_device *device;
1146
1147         device = kzalloc(sizeof(*device), GFP_KERNEL);
1148         if (!device)
1149                 return ERR_PTR(-ENOMEM);
1150
1151         device->dev = dev;
1152
1153         ret = sysfs_create_link(&dev->kobj, &group->kobj, "iommu_group");
1154         if (ret)
1155                 goto err_free_device;
1156
1157         device->name = kasprintf(GFP_KERNEL, "%s", kobject_name(&dev->kobj));
1158 rename:
1159         if (!device->name) {
1160                 ret = -ENOMEM;
1161                 goto err_remove_link;
1162         }
1163
1164         ret = sysfs_create_link_nowarn(group->devices_kobj,
1165                                        &dev->kobj, device->name);
1166         if (ret) {
1167                 if (ret == -EEXIST && i >= 0) {
1168                         /*
1169                          * Account for the slim chance of collision
1170                          * and append an instance to the name.
1171                          */
1172                         kfree(device->name);
1173                         device->name = kasprintf(GFP_KERNEL, "%s.%d",
1174                                                  kobject_name(&dev->kobj), i++);
1175                         goto rename;
1176                 }
1177                 goto err_free_name;
1178         }
1179
1180         trace_add_device_to_group(group->id, dev);
1181
1182         dev_info(dev, "Adding to iommu group %d\n", group->id);
1183
1184         return device;
1185
1186 err_free_name:
1187         kfree(device->name);
1188 err_remove_link:
1189         sysfs_remove_link(&dev->kobj, "iommu_group");
1190 err_free_device:
1191         kfree(device);
1192         dev_err(dev, "Failed to add to iommu group %d: %d\n", group->id, ret);
1193         return ERR_PTR(ret);
1194 }
1195
1196 /**
1197  * iommu_group_add_device - add a device to an iommu group
1198  * @group: the group into which to add the device (reference should be held)
1199  * @dev: the device
1200  *
1201  * This function is called by an iommu driver to add a device into a
1202  * group.  Adding a device increments the group reference count.
1203  */
1204 int iommu_group_add_device(struct iommu_group *group, struct device *dev)
1205 {
1206         struct group_device *gdev;
1207
1208         gdev = iommu_group_alloc_device(group, dev);
1209         if (IS_ERR(gdev))
1210                 return PTR_ERR(gdev);
1211
1212         iommu_group_ref_get(group);
1213         dev->iommu_group = group;
1214
1215         mutex_lock(&group->mutex);
1216         list_add_tail(&gdev->list, &group->devices);
1217         mutex_unlock(&group->mutex);
1218         return 0;
1219 }
1220 EXPORT_SYMBOL_GPL(iommu_group_add_device);
1221
1222 /**
1223  * iommu_group_remove_device - remove a device from it's current group
1224  * @dev: device to be removed
1225  *
1226  * This function is called by an iommu driver to remove the device from
1227  * it's current group.  This decrements the iommu group reference count.
1228  */
1229 void iommu_group_remove_device(struct device *dev)
1230 {
1231         struct iommu_group *group = dev->iommu_group;
1232
1233         if (!group)
1234                 return;
1235
1236         dev_info(dev, "Removing from iommu group %d\n", group->id);
1237
1238         __iommu_group_remove_device(dev);
1239 }
1240 EXPORT_SYMBOL_GPL(iommu_group_remove_device);
1241
1242 static struct device *iommu_group_first_dev(struct iommu_group *group)
1243 {
1244         lockdep_assert_held(&group->mutex);
1245         return list_first_entry(&group->devices, struct group_device, list)->dev;
1246 }
1247
1248 /**
1249  * iommu_group_for_each_dev - iterate over each device in the group
1250  * @group: the group
1251  * @data: caller opaque data to be passed to callback function
1252  * @fn: caller supplied callback function
1253  *
1254  * This function is called by group users to iterate over group devices.
1255  * Callers should hold a reference count to the group during callback.
1256  * The group->mutex is held across callbacks, which will block calls to
1257  * iommu_group_add/remove_device.
1258  */
1259 int iommu_group_for_each_dev(struct iommu_group *group, void *data,
1260                              int (*fn)(struct device *, void *))
1261 {
1262         struct group_device *device;
1263         int ret = 0;
1264
1265         mutex_lock(&group->mutex);
1266         for_each_group_device(group, device) {
1267                 ret = fn(device->dev, data);
1268                 if (ret)
1269                         break;
1270         }
1271         mutex_unlock(&group->mutex);
1272
1273         return ret;
1274 }
1275 EXPORT_SYMBOL_GPL(iommu_group_for_each_dev);
1276
1277 /**
1278  * iommu_group_get - Return the group for a device and increment reference
1279  * @dev: get the group that this device belongs to
1280  *
1281  * This function is called by iommu drivers and users to get the group
1282  * for the specified device.  If found, the group is returned and the group
1283  * reference in incremented, else NULL.
1284  */
1285 struct iommu_group *iommu_group_get(struct device *dev)
1286 {
1287         struct iommu_group *group = dev->iommu_group;
1288
1289         if (group)
1290                 kobject_get(group->devices_kobj);
1291
1292         return group;
1293 }
1294 EXPORT_SYMBOL_GPL(iommu_group_get);
1295
1296 /**
1297  * iommu_group_ref_get - Increment reference on a group
1298  * @group: the group to use, must not be NULL
1299  *
1300  * This function is called by iommu drivers to take additional references on an
1301  * existing group.  Returns the given group for convenience.
1302  */
1303 struct iommu_group *iommu_group_ref_get(struct iommu_group *group)
1304 {
1305         kobject_get(group->devices_kobj);
1306         return group;
1307 }
1308 EXPORT_SYMBOL_GPL(iommu_group_ref_get);
1309
1310 /**
1311  * iommu_group_put - Decrement group reference
1312  * @group: the group to use
1313  *
1314  * This function is called by iommu drivers and users to release the
1315  * iommu group.  Once the reference count is zero, the group is released.
1316  */
1317 void iommu_group_put(struct iommu_group *group)
1318 {
1319         if (group)
1320                 kobject_put(group->devices_kobj);
1321 }
1322 EXPORT_SYMBOL_GPL(iommu_group_put);
1323
1324 /**
1325  * iommu_register_device_fault_handler() - Register a device fault handler
1326  * @dev: the device
1327  * @handler: the fault handler
1328  * @data: private data passed as argument to the handler
1329  *
1330  * When an IOMMU fault event is received, this handler gets called with the
1331  * fault event and data as argument. The handler should return 0 on success. If
1332  * the fault is recoverable (IOMMU_FAULT_PAGE_REQ), the consumer should also
1333  * complete the fault by calling iommu_page_response() with one of the following
1334  * response code:
1335  * - IOMMU_PAGE_RESP_SUCCESS: retry the translation
1336  * - IOMMU_PAGE_RESP_INVALID: terminate the fault
1337  * - IOMMU_PAGE_RESP_FAILURE: terminate the fault and stop reporting
1338  *   page faults if possible.
1339  *
1340  * Return 0 if the fault handler was installed successfully, or an error.
1341  */
1342 int iommu_register_device_fault_handler(struct device *dev,
1343                                         iommu_dev_fault_handler_t handler,
1344                                         void *data)
1345 {
1346         struct dev_iommu *param = dev->iommu;
1347         int ret = 0;
1348
1349         if (!param)
1350                 return -EINVAL;
1351
1352         mutex_lock(&param->lock);
1353         /* Only allow one fault handler registered for each device */
1354         if (param->fault_param) {
1355                 ret = -EBUSY;
1356                 goto done_unlock;
1357         }
1358
1359         get_device(dev);
1360         param->fault_param = kzalloc(sizeof(*param->fault_param), GFP_KERNEL);
1361         if (!param->fault_param) {
1362                 put_device(dev);
1363                 ret = -ENOMEM;
1364                 goto done_unlock;
1365         }
1366         param->fault_param->handler = handler;
1367         param->fault_param->data = data;
1368         mutex_init(&param->fault_param->lock);
1369         INIT_LIST_HEAD(&param->fault_param->faults);
1370
1371 done_unlock:
1372         mutex_unlock(&param->lock);
1373
1374         return ret;
1375 }
1376 EXPORT_SYMBOL_GPL(iommu_register_device_fault_handler);
1377
1378 /**
1379  * iommu_unregister_device_fault_handler() - Unregister the device fault handler
1380  * @dev: the device
1381  *
1382  * Remove the device fault handler installed with
1383  * iommu_register_device_fault_handler().
1384  *
1385  * Return 0 on success, or an error.
1386  */
1387 int iommu_unregister_device_fault_handler(struct device *dev)
1388 {
1389         struct dev_iommu *param = dev->iommu;
1390         int ret = 0;
1391
1392         if (!param)
1393                 return -EINVAL;
1394
1395         mutex_lock(&param->lock);
1396
1397         if (!param->fault_param)
1398                 goto unlock;
1399
1400         /* we cannot unregister handler if there are pending faults */
1401         if (!list_empty(&param->fault_param->faults)) {
1402                 ret = -EBUSY;
1403                 goto unlock;
1404         }
1405
1406         kfree(param->fault_param);
1407         param->fault_param = NULL;
1408         put_device(dev);
1409 unlock:
1410         mutex_unlock(&param->lock);
1411
1412         return ret;
1413 }
1414 EXPORT_SYMBOL_GPL(iommu_unregister_device_fault_handler);
1415
1416 /**
1417  * iommu_report_device_fault() - Report fault event to device driver
1418  * @dev: the device
1419  * @evt: fault event data
1420  *
1421  * Called by IOMMU drivers when a fault is detected, typically in a threaded IRQ
1422  * handler. When this function fails and the fault is recoverable, it is the
1423  * caller's responsibility to complete the fault.
1424  *
1425  * Return 0 on success, or an error.
1426  */
1427 int iommu_report_device_fault(struct device *dev, struct iommu_fault_event *evt)
1428 {
1429         struct dev_iommu *param = dev->iommu;
1430         struct iommu_fault_event *evt_pending = NULL;
1431         struct iommu_fault_param *fparam;
1432         int ret = 0;
1433
1434         if (!param || !evt)
1435                 return -EINVAL;
1436
1437         /* we only report device fault if there is a handler registered */
1438         mutex_lock(&param->lock);
1439         fparam = param->fault_param;
1440         if (!fparam || !fparam->handler) {
1441                 ret = -EINVAL;
1442                 goto done_unlock;
1443         }
1444
1445         if (evt->fault.type == IOMMU_FAULT_PAGE_REQ &&
1446             (evt->fault.prm.flags & IOMMU_FAULT_PAGE_REQUEST_LAST_PAGE)) {
1447                 evt_pending = kmemdup(evt, sizeof(struct iommu_fault_event),
1448                                       GFP_KERNEL);
1449                 if (!evt_pending) {
1450                         ret = -ENOMEM;
1451                         goto done_unlock;
1452                 }
1453                 mutex_lock(&fparam->lock);
1454                 list_add_tail(&evt_pending->list, &fparam->faults);
1455                 mutex_unlock(&fparam->lock);
1456         }
1457
1458         ret = fparam->handler(&evt->fault, fparam->data);
1459         if (ret && evt_pending) {
1460                 mutex_lock(&fparam->lock);
1461                 list_del(&evt_pending->list);
1462                 mutex_unlock(&fparam->lock);
1463                 kfree(evt_pending);
1464         }
1465 done_unlock:
1466         mutex_unlock(&param->lock);
1467         return ret;
1468 }
1469 EXPORT_SYMBOL_GPL(iommu_report_device_fault);
1470
1471 int iommu_page_response(struct device *dev,
1472                         struct iommu_page_response *msg)
1473 {
1474         bool needs_pasid;
1475         int ret = -EINVAL;
1476         struct iommu_fault_event *evt;
1477         struct iommu_fault_page_request *prm;
1478         struct dev_iommu *param = dev->iommu;
1479         const struct iommu_ops *ops = dev_iommu_ops(dev);
1480         bool has_pasid = msg->flags & IOMMU_PAGE_RESP_PASID_VALID;
1481
1482         if (!ops->page_response)
1483                 return -ENODEV;
1484
1485         if (!param || !param->fault_param)
1486                 return -EINVAL;
1487
1488         if (msg->version != IOMMU_PAGE_RESP_VERSION_1 ||
1489             msg->flags & ~IOMMU_PAGE_RESP_PASID_VALID)
1490                 return -EINVAL;
1491
1492         /* Only send response if there is a fault report pending */
1493         mutex_lock(&param->fault_param->lock);
1494         if (list_empty(&param->fault_param->faults)) {
1495                 dev_warn_ratelimited(dev, "no pending PRQ, drop response\n");
1496                 goto done_unlock;
1497         }
1498         /*
1499          * Check if we have a matching page request pending to respond,
1500          * otherwise return -EINVAL
1501          */
1502         list_for_each_entry(evt, &param->fault_param->faults, list) {
1503                 prm = &evt->fault.prm;
1504                 if (prm->grpid != msg->grpid)
1505                         continue;
1506
1507                 /*
1508                  * If the PASID is required, the corresponding request is
1509                  * matched using the group ID, the PASID valid bit and the PASID
1510                  * value. Otherwise only the group ID matches request and
1511                  * response.
1512                  */
1513                 needs_pasid = prm->flags & IOMMU_FAULT_PAGE_RESPONSE_NEEDS_PASID;
1514                 if (needs_pasid && (!has_pasid || msg->pasid != prm->pasid))
1515                         continue;
1516
1517                 if (!needs_pasid && has_pasid) {
1518                         /* No big deal, just clear it. */
1519                         msg->flags &= ~IOMMU_PAGE_RESP_PASID_VALID;
1520                         msg->pasid = 0;
1521                 }
1522
1523                 ret = ops->page_response(dev, evt, msg);
1524                 list_del(&evt->list);
1525                 kfree(evt);
1526                 break;
1527         }
1528
1529 done_unlock:
1530         mutex_unlock(&param->fault_param->lock);
1531         return ret;
1532 }
1533 EXPORT_SYMBOL_GPL(iommu_page_response);
1534
1535 /**
1536  * iommu_group_id - Return ID for a group
1537  * @group: the group to ID
1538  *
1539  * Return the unique ID for the group matching the sysfs group number.
1540  */
1541 int iommu_group_id(struct iommu_group *group)
1542 {
1543         return group->id;
1544 }
1545 EXPORT_SYMBOL_GPL(iommu_group_id);
1546
1547 static struct iommu_group *get_pci_alias_group(struct pci_dev *pdev,
1548                                                unsigned long *devfns);
1549
1550 /*
1551  * To consider a PCI device isolated, we require ACS to support Source
1552  * Validation, Request Redirection, Completer Redirection, and Upstream
1553  * Forwarding.  This effectively means that devices cannot spoof their
1554  * requester ID, requests and completions cannot be redirected, and all
1555  * transactions are forwarded upstream, even as it passes through a
1556  * bridge where the target device is downstream.
1557  */
1558 #define REQ_ACS_FLAGS   (PCI_ACS_SV | PCI_ACS_RR | PCI_ACS_CR | PCI_ACS_UF)
1559
1560 /*
1561  * For multifunction devices which are not isolated from each other, find
1562  * all the other non-isolated functions and look for existing groups.  For
1563  * each function, we also need to look for aliases to or from other devices
1564  * that may already have a group.
1565  */
1566 static struct iommu_group *get_pci_function_alias_group(struct pci_dev *pdev,
1567                                                         unsigned long *devfns)
1568 {
1569         struct pci_dev *tmp = NULL;
1570         struct iommu_group *group;
1571
1572         if (!pdev->multifunction || pci_acs_enabled(pdev, REQ_ACS_FLAGS))
1573                 return NULL;
1574
1575         for_each_pci_dev(tmp) {
1576                 if (tmp == pdev || tmp->bus != pdev->bus ||
1577                     PCI_SLOT(tmp->devfn) != PCI_SLOT(pdev->devfn) ||
1578                     pci_acs_enabled(tmp, REQ_ACS_FLAGS))
1579                         continue;
1580
1581                 group = get_pci_alias_group(tmp, devfns);
1582                 if (group) {
1583                         pci_dev_put(tmp);
1584                         return group;
1585                 }
1586         }
1587
1588         return NULL;
1589 }
1590
1591 /*
1592  * Look for aliases to or from the given device for existing groups. DMA
1593  * aliases are only supported on the same bus, therefore the search
1594  * space is quite small (especially since we're really only looking at pcie
1595  * device, and therefore only expect multiple slots on the root complex or
1596  * downstream switch ports).  It's conceivable though that a pair of
1597  * multifunction devices could have aliases between them that would cause a
1598  * loop.  To prevent this, we use a bitmap to track where we've been.
1599  */
1600 static struct iommu_group *get_pci_alias_group(struct pci_dev *pdev,
1601                                                unsigned long *devfns)
1602 {
1603         struct pci_dev *tmp = NULL;
1604         struct iommu_group *group;
1605
1606         if (test_and_set_bit(pdev->devfn & 0xff, devfns))
1607                 return NULL;
1608
1609         group = iommu_group_get(&pdev->dev);
1610         if (group)
1611                 return group;
1612
1613         for_each_pci_dev(tmp) {
1614                 if (tmp == pdev || tmp->bus != pdev->bus)
1615                         continue;
1616
1617                 /* We alias them or they alias us */
1618                 if (pci_devs_are_dma_aliases(pdev, tmp)) {
1619                         group = get_pci_alias_group(tmp, devfns);
1620                         if (group) {
1621                                 pci_dev_put(tmp);
1622                                 return group;
1623                         }
1624
1625                         group = get_pci_function_alias_group(tmp, devfns);
1626                         if (group) {
1627                                 pci_dev_put(tmp);
1628                                 return group;
1629                         }
1630                 }
1631         }
1632
1633         return NULL;
1634 }
1635
1636 struct group_for_pci_data {
1637         struct pci_dev *pdev;
1638         struct iommu_group *group;
1639 };
1640
1641 /*
1642  * DMA alias iterator callback, return the last seen device.  Stop and return
1643  * the IOMMU group if we find one along the way.
1644  */
1645 static int get_pci_alias_or_group(struct pci_dev *pdev, u16 alias, void *opaque)
1646 {
1647         struct group_for_pci_data *data = opaque;
1648
1649         data->pdev = pdev;
1650         data->group = iommu_group_get(&pdev->dev);
1651
1652         return data->group != NULL;
1653 }
1654
1655 /*
1656  * Generic device_group call-back function. It just allocates one
1657  * iommu-group per device.
1658  */
1659 struct iommu_group *generic_device_group(struct device *dev)
1660 {
1661         return iommu_group_alloc();
1662 }
1663 EXPORT_SYMBOL_GPL(generic_device_group);
1664
1665 /*
1666  * Generic device_group call-back function. It just allocates one
1667  * iommu-group per iommu driver instance shared by every device
1668  * probed by that iommu driver.
1669  */
1670 struct iommu_group *generic_single_device_group(struct device *dev)
1671 {
1672         struct iommu_device *iommu = dev->iommu->iommu_dev;
1673
1674         if (!iommu->singleton_group) {
1675                 struct iommu_group *group;
1676
1677                 group = iommu_group_alloc();
1678                 if (IS_ERR(group))
1679                         return group;
1680                 iommu->singleton_group = group;
1681         }
1682         return iommu_group_ref_get(iommu->singleton_group);
1683 }
1684 EXPORT_SYMBOL_GPL(generic_single_device_group);
1685
1686 /*
1687  * Use standard PCI bus topology, isolation features, and DMA alias quirks
1688  * to find or create an IOMMU group for a device.
1689  */
1690 struct iommu_group *pci_device_group(struct device *dev)
1691 {
1692         struct pci_dev *pdev = to_pci_dev(dev);
1693         struct group_for_pci_data data;
1694         struct pci_bus *bus;
1695         struct iommu_group *group = NULL;
1696         u64 devfns[4] = { 0 };
1697
1698         if (WARN_ON(!dev_is_pci(dev)))
1699                 return ERR_PTR(-EINVAL);
1700
1701         /*
1702          * Find the upstream DMA alias for the device.  A device must not
1703          * be aliased due to topology in order to have its own IOMMU group.
1704          * If we find an alias along the way that already belongs to a
1705          * group, use it.
1706          */
1707         if (pci_for_each_dma_alias(pdev, get_pci_alias_or_group, &data))
1708                 return data.group;
1709
1710         pdev = data.pdev;
1711
1712         /*
1713          * Continue upstream from the point of minimum IOMMU granularity
1714          * due to aliases to the point where devices are protected from
1715          * peer-to-peer DMA by PCI ACS.  Again, if we find an existing
1716          * group, use it.
1717          */
1718         for (bus = pdev->bus; !pci_is_root_bus(bus); bus = bus->parent) {
1719                 if (!bus->self)
1720                         continue;
1721
1722                 if (pci_acs_path_enabled(bus->self, NULL, REQ_ACS_FLAGS))
1723                         break;
1724
1725                 pdev = bus->self;
1726
1727                 group = iommu_group_get(&pdev->dev);
1728                 if (group)
1729                         return group;
1730         }
1731
1732         /*
1733          * Look for existing groups on device aliases.  If we alias another
1734          * device or another device aliases us, use the same group.
1735          */
1736         group = get_pci_alias_group(pdev, (unsigned long *)devfns);
1737         if (group)
1738                 return group;
1739
1740         /*
1741          * Look for existing groups on non-isolated functions on the same
1742          * slot and aliases of those funcions, if any.  No need to clear
1743          * the search bitmap, the tested devfns are still valid.
1744          */
1745         group = get_pci_function_alias_group(pdev, (unsigned long *)devfns);
1746         if (group)
1747                 return group;
1748
1749         /* No shared group found, allocate new */
1750         return iommu_group_alloc();
1751 }
1752 EXPORT_SYMBOL_GPL(pci_device_group);
1753
1754 /* Get the IOMMU group for device on fsl-mc bus */
1755 struct iommu_group *fsl_mc_device_group(struct device *dev)
1756 {
1757         struct device *cont_dev = fsl_mc_cont_dev(dev);
1758         struct iommu_group *group;
1759
1760         group = iommu_group_get(cont_dev);
1761         if (!group)
1762                 group = iommu_group_alloc();
1763         return group;
1764 }
1765 EXPORT_SYMBOL_GPL(fsl_mc_device_group);
1766
1767 static struct iommu_domain *
1768 __iommu_group_alloc_default_domain(struct iommu_group *group, int req_type)
1769 {
1770         if (group->default_domain && group->default_domain->type == req_type)
1771                 return group->default_domain;
1772         return __iommu_group_domain_alloc(group, req_type);
1773 }
1774
1775 /*
1776  * req_type of 0 means "auto" which means to select a domain based on
1777  * iommu_def_domain_type or what the driver actually supports.
1778  */
1779 static struct iommu_domain *
1780 iommu_group_alloc_default_domain(struct iommu_group *group, int req_type)
1781 {
1782         const struct iommu_ops *ops = dev_iommu_ops(iommu_group_first_dev(group));
1783         struct iommu_domain *dom;
1784
1785         lockdep_assert_held(&group->mutex);
1786
1787         /*
1788          * Allow legacy drivers to specify the domain that will be the default
1789          * domain. This should always be either an IDENTITY/BLOCKED/PLATFORM
1790          * domain. Do not use in new drivers.
1791          */
1792         if (ops->default_domain) {
1793                 if (req_type)
1794                         return NULL;
1795                 return ops->default_domain;
1796         }
1797
1798         if (req_type)
1799                 return __iommu_group_alloc_default_domain(group, req_type);
1800
1801         /* The driver gave no guidance on what type to use, try the default */
1802         dom = __iommu_group_alloc_default_domain(group, iommu_def_domain_type);
1803         if (dom)
1804                 return dom;
1805
1806         /* Otherwise IDENTITY and DMA_FQ defaults will try DMA */
1807         if (iommu_def_domain_type == IOMMU_DOMAIN_DMA)
1808                 return NULL;
1809         dom = __iommu_group_alloc_default_domain(group, IOMMU_DOMAIN_DMA);
1810         if (!dom)
1811                 return NULL;
1812
1813         pr_warn("Failed to allocate default IOMMU domain of type %u for group %s - Falling back to IOMMU_DOMAIN_DMA",
1814                 iommu_def_domain_type, group->name);
1815         return dom;
1816 }
1817
1818 struct iommu_domain *iommu_group_default_domain(struct iommu_group *group)
1819 {
1820         return group->default_domain;
1821 }
1822
1823 static int probe_iommu_group(struct device *dev, void *data)
1824 {
1825         struct list_head *group_list = data;
1826         int ret;
1827
1828         ret = __iommu_probe_device(dev, group_list);
1829         if (ret == -ENODEV)
1830                 ret = 0;
1831
1832         return ret;
1833 }
1834
1835 static int iommu_bus_notifier(struct notifier_block *nb,
1836                               unsigned long action, void *data)
1837 {
1838         struct device *dev = data;
1839
1840         if (action == BUS_NOTIFY_ADD_DEVICE) {
1841                 int ret;
1842
1843                 ret = iommu_probe_device(dev);
1844                 return (ret) ? NOTIFY_DONE : NOTIFY_OK;
1845         } else if (action == BUS_NOTIFY_REMOVED_DEVICE) {
1846                 iommu_release_device(dev);
1847                 return NOTIFY_OK;
1848         }
1849
1850         return 0;
1851 }
1852
1853 /*
1854  * Combine the driver's chosen def_domain_type across all the devices in a
1855  * group. Drivers must give a consistent result.
1856  */
1857 static int iommu_get_def_domain_type(struct iommu_group *group,
1858                                      struct device *dev, int cur_type)
1859 {
1860         const struct iommu_ops *ops = dev_iommu_ops(dev);
1861         int type;
1862
1863         if (!ops->def_domain_type)
1864                 return cur_type;
1865
1866         type = ops->def_domain_type(dev);
1867         if (!type || cur_type == type)
1868                 return cur_type;
1869         if (!cur_type)
1870                 return type;
1871
1872         dev_err_ratelimited(
1873                 dev,
1874                 "IOMMU driver error, requesting conflicting def_domain_type, %s and %s, for devices in group %u.\n",
1875                 iommu_domain_type_str(cur_type), iommu_domain_type_str(type),
1876                 group->id);
1877
1878         /*
1879          * Try to recover, drivers are allowed to force IDENITY or DMA, IDENTITY
1880          * takes precedence.
1881          */
1882         if (type == IOMMU_DOMAIN_IDENTITY)
1883                 return type;
1884         return cur_type;
1885 }
1886
1887 /*
1888  * A target_type of 0 will select the best domain type. 0 can be returned in
1889  * this case meaning the global default should be used.
1890  */
1891 static int iommu_get_default_domain_type(struct iommu_group *group,
1892                                          int target_type)
1893 {
1894         struct device *untrusted = NULL;
1895         struct group_device *gdev;
1896         int driver_type = 0;
1897
1898         lockdep_assert_held(&group->mutex);
1899
1900         /*
1901          * ARM32 drivers supporting CONFIG_ARM_DMA_USE_IOMMU can declare an
1902          * identity_domain and it will automatically become their default
1903          * domain. Later on ARM_DMA_USE_IOMMU will install its UNMANAGED domain.
1904          * Override the selection to IDENTITY.
1905          */
1906         if (IS_ENABLED(CONFIG_ARM_DMA_USE_IOMMU)) {
1907                 static_assert(!(IS_ENABLED(CONFIG_ARM_DMA_USE_IOMMU) &&
1908                                 IS_ENABLED(CONFIG_IOMMU_DMA)));
1909                 driver_type = IOMMU_DOMAIN_IDENTITY;
1910         }
1911
1912         for_each_group_device(group, gdev) {
1913                 driver_type = iommu_get_def_domain_type(group, gdev->dev,
1914                                                         driver_type);
1915
1916                 if (dev_is_pci(gdev->dev) && to_pci_dev(gdev->dev)->untrusted) {
1917                         /*
1918                          * No ARM32 using systems will set untrusted, it cannot
1919                          * work.
1920                          */
1921                         if (WARN_ON(IS_ENABLED(CONFIG_ARM_DMA_USE_IOMMU)))
1922                                 return -1;
1923                         untrusted = gdev->dev;
1924                 }
1925         }
1926
1927         /*
1928          * If the common dma ops are not selected in kconfig then we cannot use
1929          * IOMMU_DOMAIN_DMA at all. Force IDENTITY if nothing else has been
1930          * selected.
1931          */
1932         if (!IS_ENABLED(CONFIG_IOMMU_DMA)) {
1933                 if (WARN_ON(driver_type == IOMMU_DOMAIN_DMA))
1934                         return -1;
1935                 if (!driver_type)
1936                         driver_type = IOMMU_DOMAIN_IDENTITY;
1937         }
1938
1939         if (untrusted) {
1940                 if (driver_type && driver_type != IOMMU_DOMAIN_DMA) {
1941                         dev_err_ratelimited(
1942                                 untrusted,
1943                                 "Device is not trusted, but driver is overriding group %u to %s, refusing to probe.\n",
1944                                 group->id, iommu_domain_type_str(driver_type));
1945                         return -1;
1946                 }
1947                 driver_type = IOMMU_DOMAIN_DMA;
1948         }
1949
1950         if (target_type) {
1951                 if (driver_type && target_type != driver_type)
1952                         return -1;
1953                 return target_type;
1954         }
1955         return driver_type;
1956 }
1957
1958 static void iommu_group_do_probe_finalize(struct device *dev)
1959 {
1960         const struct iommu_ops *ops = dev_iommu_ops(dev);
1961
1962         if (ops->probe_finalize)
1963                 ops->probe_finalize(dev);
1964 }
1965
1966 int bus_iommu_probe(const struct bus_type *bus)
1967 {
1968         struct iommu_group *group, *next;
1969         LIST_HEAD(group_list);
1970         int ret;
1971
1972         ret = bus_for_each_dev(bus, NULL, &group_list, probe_iommu_group);
1973         if (ret)
1974                 return ret;
1975
1976         list_for_each_entry_safe(group, next, &group_list, entry) {
1977                 struct group_device *gdev;
1978
1979                 mutex_lock(&group->mutex);
1980
1981                 /* Remove item from the list */
1982                 list_del_init(&group->entry);
1983
1984                 /*
1985                  * We go to the trouble of deferred default domain creation so
1986                  * that the cross-group default domain type and the setup of the
1987                  * IOMMU_RESV_DIRECT will work correctly in non-hotpug scenarios.
1988                  */
1989                 ret = iommu_setup_default_domain(group, 0);
1990                 if (ret) {
1991                         mutex_unlock(&group->mutex);
1992                         return ret;
1993                 }
1994                 mutex_unlock(&group->mutex);
1995
1996                 /*
1997                  * FIXME: Mis-locked because the ops->probe_finalize() call-back
1998                  * of some IOMMU drivers calls arm_iommu_attach_device() which
1999                  * in-turn might call back into IOMMU core code, where it tries
2000                  * to take group->mutex, resulting in a deadlock.
2001                  */
2002                 for_each_group_device(group, gdev)
2003                         iommu_group_do_probe_finalize(gdev->dev);
2004         }
2005
2006         return 0;
2007 }
2008
2009 /**
2010  * iommu_present() - make platform-specific assumptions about an IOMMU
2011  * @bus: bus to check
2012  *
2013  * Do not use this function. You want device_iommu_mapped() instead.
2014  *
2015  * Return: true if some IOMMU is present and aware of devices on the given bus;
2016  * in general it may not be the only IOMMU, and it may not have anything to do
2017  * with whatever device you are ultimately interested in.
2018  */
2019 bool iommu_present(const struct bus_type *bus)
2020 {
2021         bool ret = false;
2022
2023         for (int i = 0; i < ARRAY_SIZE(iommu_buses); i++) {
2024                 if (iommu_buses[i] == bus) {
2025                         spin_lock(&iommu_device_lock);
2026                         ret = !list_empty(&iommu_device_list);
2027                         spin_unlock(&iommu_device_lock);
2028                 }
2029         }
2030         return ret;
2031 }
2032 EXPORT_SYMBOL_GPL(iommu_present);
2033
2034 /**
2035  * device_iommu_capable() - check for a general IOMMU capability
2036  * @dev: device to which the capability would be relevant, if available
2037  * @cap: IOMMU capability
2038  *
2039  * Return: true if an IOMMU is present and supports the given capability
2040  * for the given device, otherwise false.
2041  */
2042 bool device_iommu_capable(struct device *dev, enum iommu_cap cap)
2043 {
2044         const struct iommu_ops *ops;
2045
2046         if (!dev_has_iommu(dev))
2047                 return false;
2048
2049         ops = dev_iommu_ops(dev);
2050         if (!ops->capable)
2051                 return false;
2052
2053         return ops->capable(dev, cap);
2054 }
2055 EXPORT_SYMBOL_GPL(device_iommu_capable);
2056
2057 /**
2058  * iommu_group_has_isolated_msi() - Compute msi_device_has_isolated_msi()
2059  *       for a group
2060  * @group: Group to query
2061  *
2062  * IOMMU groups should not have differing values of
2063  * msi_device_has_isolated_msi() for devices in a group. However nothing
2064  * directly prevents this, so ensure mistakes don't result in isolation failures
2065  * by checking that all the devices are the same.
2066  */
2067 bool iommu_group_has_isolated_msi(struct iommu_group *group)
2068 {
2069         struct group_device *group_dev;
2070         bool ret = true;
2071
2072         mutex_lock(&group->mutex);
2073         for_each_group_device(group, group_dev)
2074                 ret &= msi_device_has_isolated_msi(group_dev->dev);
2075         mutex_unlock(&group->mutex);
2076         return ret;
2077 }
2078 EXPORT_SYMBOL_GPL(iommu_group_has_isolated_msi);
2079
2080 /**
2081  * iommu_set_fault_handler() - set a fault handler for an iommu domain
2082  * @domain: iommu domain
2083  * @handler: fault handler
2084  * @token: user data, will be passed back to the fault handler
2085  *
2086  * This function should be used by IOMMU users which want to be notified
2087  * whenever an IOMMU fault happens.
2088  *
2089  * The fault handler itself should return 0 on success, and an appropriate
2090  * error code otherwise.
2091  */
2092 void iommu_set_fault_handler(struct iommu_domain *domain,
2093                                         iommu_fault_handler_t handler,
2094                                         void *token)
2095 {
2096         BUG_ON(!domain);
2097
2098         domain->handler = handler;
2099         domain->handler_token = token;
2100 }
2101 EXPORT_SYMBOL_GPL(iommu_set_fault_handler);
2102
2103 static struct iommu_domain *__iommu_domain_alloc(const struct iommu_ops *ops,
2104                                                  struct device *dev,
2105                                                  unsigned int type)
2106 {
2107         struct iommu_domain *domain;
2108         unsigned int alloc_type = type & IOMMU_DOMAIN_ALLOC_FLAGS;
2109
2110         if (alloc_type == IOMMU_DOMAIN_IDENTITY && ops->identity_domain)
2111                 return ops->identity_domain;
2112         else if (alloc_type == IOMMU_DOMAIN_BLOCKED && ops->blocked_domain)
2113                 return ops->blocked_domain;
2114         else if (type & __IOMMU_DOMAIN_PAGING && ops->domain_alloc_paging)
2115                 domain = ops->domain_alloc_paging(dev);
2116         else if (ops->domain_alloc)
2117                 domain = ops->domain_alloc(alloc_type);
2118         else
2119                 return NULL;
2120
2121         if (!domain)
2122                 return NULL;
2123
2124         domain->type = type;
2125         domain->owner = ops;
2126         /*
2127          * If not already set, assume all sizes by default; the driver
2128          * may override this later
2129          */
2130         if (!domain->pgsize_bitmap)
2131                 domain->pgsize_bitmap = ops->pgsize_bitmap;
2132
2133         if (!domain->ops)
2134                 domain->ops = ops->default_domain_ops;
2135
2136         if (iommu_is_dma_domain(domain) && iommu_get_dma_cookie(domain)) {
2137                 iommu_domain_free(domain);
2138                 domain = NULL;
2139         }
2140         return domain;
2141 }
2142
2143 static struct iommu_domain *
2144 __iommu_group_domain_alloc(struct iommu_group *group, unsigned int type)
2145 {
2146         struct device *dev = iommu_group_first_dev(group);
2147
2148         return __iommu_domain_alloc(dev_iommu_ops(dev), dev, type);
2149 }
2150
2151 static int __iommu_domain_alloc_dev(struct device *dev, void *data)
2152 {
2153         const struct iommu_ops **ops = data;
2154
2155         if (!dev_has_iommu(dev))
2156                 return 0;
2157
2158         if (WARN_ONCE(*ops && *ops != dev_iommu_ops(dev),
2159                       "Multiple IOMMU drivers present for bus %s, which the public IOMMU API can't fully support yet. You will still need to disable one or more for this to work, sorry!\n",
2160                       dev_bus_name(dev)))
2161                 return -EBUSY;
2162
2163         *ops = dev_iommu_ops(dev);
2164         return 0;
2165 }
2166
2167 struct iommu_domain *iommu_domain_alloc(const struct bus_type *bus)
2168 {
2169         const struct iommu_ops *ops = NULL;
2170         int err = bus_for_each_dev(bus, NULL, &ops, __iommu_domain_alloc_dev);
2171
2172         if (err || !ops)
2173                 return NULL;
2174
2175         return __iommu_domain_alloc(ops, NULL, IOMMU_DOMAIN_UNMANAGED);
2176 }
2177 EXPORT_SYMBOL_GPL(iommu_domain_alloc);
2178
2179 void iommu_domain_free(struct iommu_domain *domain)
2180 {
2181         if (domain->type == IOMMU_DOMAIN_SVA)
2182                 mmdrop(domain->mm);
2183         iommu_put_dma_cookie(domain);
2184         if (domain->ops->free)
2185                 domain->ops->free(domain);
2186 }
2187 EXPORT_SYMBOL_GPL(iommu_domain_free);
2188
2189 /*
2190  * Put the group's domain back to the appropriate core-owned domain - either the
2191  * standard kernel-mode DMA configuration or an all-DMA-blocked domain.
2192  */
2193 static void __iommu_group_set_core_domain(struct iommu_group *group)
2194 {
2195         struct iommu_domain *new_domain;
2196
2197         if (group->owner)
2198                 new_domain = group->blocking_domain;
2199         else
2200                 new_domain = group->default_domain;
2201
2202         __iommu_group_set_domain_nofail(group, new_domain);
2203 }
2204
2205 static int __iommu_attach_device(struct iommu_domain *domain,
2206                                  struct device *dev)
2207 {
2208         int ret;
2209
2210         if (unlikely(domain->ops->attach_dev == NULL))
2211                 return -ENODEV;
2212
2213         ret = domain->ops->attach_dev(domain, dev);
2214         if (ret)
2215                 return ret;
2216         dev->iommu->attach_deferred = 0;
2217         trace_attach_device_to_domain(dev);
2218         return 0;
2219 }
2220
2221 /**
2222  * iommu_attach_device - Attach an IOMMU domain to a device
2223  * @domain: IOMMU domain to attach
2224  * @dev: Device that will be attached
2225  *
2226  * Returns 0 on success and error code on failure
2227  *
2228  * Note that EINVAL can be treated as a soft failure, indicating
2229  * that certain configuration of the domain is incompatible with
2230  * the device. In this case attaching a different domain to the
2231  * device may succeed.
2232  */
2233 int iommu_attach_device(struct iommu_domain *domain, struct device *dev)
2234 {
2235         /* Caller must be a probed driver on dev */
2236         struct iommu_group *group = dev->iommu_group;
2237         int ret;
2238
2239         if (!group)
2240                 return -ENODEV;
2241
2242         /*
2243          * Lock the group to make sure the device-count doesn't
2244          * change while we are attaching
2245          */
2246         mutex_lock(&group->mutex);
2247         ret = -EINVAL;
2248         if (list_count_nodes(&group->devices) != 1)
2249                 goto out_unlock;
2250
2251         ret = __iommu_attach_group(domain, group);
2252
2253 out_unlock:
2254         mutex_unlock(&group->mutex);
2255         return ret;
2256 }
2257 EXPORT_SYMBOL_GPL(iommu_attach_device);
2258
2259 int iommu_deferred_attach(struct device *dev, struct iommu_domain *domain)
2260 {
2261         if (dev->iommu && dev->iommu->attach_deferred)
2262                 return __iommu_attach_device(domain, dev);
2263
2264         return 0;
2265 }
2266
2267 void iommu_detach_device(struct iommu_domain *domain, struct device *dev)
2268 {
2269         /* Caller must be a probed driver on dev */
2270         struct iommu_group *group = dev->iommu_group;
2271
2272         if (!group)
2273                 return;
2274
2275         mutex_lock(&group->mutex);
2276         if (WARN_ON(domain != group->domain) ||
2277             WARN_ON(list_count_nodes(&group->devices) != 1))
2278                 goto out_unlock;
2279         __iommu_group_set_core_domain(group);
2280
2281 out_unlock:
2282         mutex_unlock(&group->mutex);
2283 }
2284 EXPORT_SYMBOL_GPL(iommu_detach_device);
2285
2286 struct iommu_domain *iommu_get_domain_for_dev(struct device *dev)
2287 {
2288         /* Caller must be a probed driver on dev */
2289         struct iommu_group *group = dev->iommu_group;
2290
2291         if (!group)
2292                 return NULL;
2293
2294         return group->domain;
2295 }
2296 EXPORT_SYMBOL_GPL(iommu_get_domain_for_dev);
2297
2298 /*
2299  * For IOMMU_DOMAIN_DMA implementations which already provide their own
2300  * guarantees that the group and its default domain are valid and correct.
2301  */
2302 struct iommu_domain *iommu_get_dma_domain(struct device *dev)
2303 {
2304         return dev->iommu_group->default_domain;
2305 }
2306
2307 static int __iommu_attach_group(struct iommu_domain *domain,
2308                                 struct iommu_group *group)
2309 {
2310         struct device *dev;
2311
2312         if (group->domain && group->domain != group->default_domain &&
2313             group->domain != group->blocking_domain)
2314                 return -EBUSY;
2315
2316         dev = iommu_group_first_dev(group);
2317         if (!dev_has_iommu(dev) || dev_iommu_ops(dev) != domain->owner)
2318                 return -EINVAL;
2319
2320         return __iommu_group_set_domain(group, domain);
2321 }
2322
2323 /**
2324  * iommu_attach_group - Attach an IOMMU domain to an IOMMU group
2325  * @domain: IOMMU domain to attach
2326  * @group: IOMMU group that will be attached
2327  *
2328  * Returns 0 on success and error code on failure
2329  *
2330  * Note that EINVAL can be treated as a soft failure, indicating
2331  * that certain configuration of the domain is incompatible with
2332  * the group. In this case attaching a different domain to the
2333  * group may succeed.
2334  */
2335 int iommu_attach_group(struct iommu_domain *domain, struct iommu_group *group)
2336 {
2337         int ret;
2338
2339         mutex_lock(&group->mutex);
2340         ret = __iommu_attach_group(domain, group);
2341         mutex_unlock(&group->mutex);
2342
2343         return ret;
2344 }
2345 EXPORT_SYMBOL_GPL(iommu_attach_group);
2346
2347 /**
2348  * iommu_group_replace_domain - replace the domain that a group is attached to
2349  * @new_domain: new IOMMU domain to replace with
2350  * @group: IOMMU group that will be attached to the new domain
2351  *
2352  * This API allows the group to switch domains without being forced to go to
2353  * the blocking domain in-between.
2354  *
2355  * If the currently attached domain is a core domain (e.g. a default_domain),
2356  * it will act just like the iommu_attach_group().
2357  */
2358 int iommu_group_replace_domain(struct iommu_group *group,
2359                                struct iommu_domain *new_domain)
2360 {
2361         int ret;
2362
2363         if (!new_domain)
2364                 return -EINVAL;
2365
2366         mutex_lock(&group->mutex);
2367         ret = __iommu_group_set_domain(group, new_domain);
2368         mutex_unlock(&group->mutex);
2369         return ret;
2370 }
2371 EXPORT_SYMBOL_NS_GPL(iommu_group_replace_domain, IOMMUFD_INTERNAL);
2372
2373 static int __iommu_device_set_domain(struct iommu_group *group,
2374                                      struct device *dev,
2375                                      struct iommu_domain *new_domain,
2376                                      unsigned int flags)
2377 {
2378         int ret;
2379
2380         /*
2381          * If the device requires IOMMU_RESV_DIRECT then we cannot allow
2382          * the blocking domain to be attached as it does not contain the
2383          * required 1:1 mapping. This test effectively excludes the device
2384          * being used with iommu_group_claim_dma_owner() which will block
2385          * vfio and iommufd as well.
2386          */
2387         if (dev->iommu->require_direct &&
2388             (new_domain->type == IOMMU_DOMAIN_BLOCKED ||
2389              new_domain == group->blocking_domain)) {
2390                 dev_warn(dev,
2391                          "Firmware has requested this device have a 1:1 IOMMU mapping, rejecting configuring the device without a 1:1 mapping. Contact your platform vendor.\n");
2392                 return -EINVAL;
2393         }
2394
2395         if (dev->iommu->attach_deferred) {
2396                 if (new_domain == group->default_domain)
2397                         return 0;
2398                 dev->iommu->attach_deferred = 0;
2399         }
2400
2401         ret = __iommu_attach_device(new_domain, dev);
2402         if (ret) {
2403                 /*
2404                  * If we have a blocking domain then try to attach that in hopes
2405                  * of avoiding a UAF. Modern drivers should implement blocking
2406                  * domains as global statics that cannot fail.
2407                  */
2408                 if ((flags & IOMMU_SET_DOMAIN_MUST_SUCCEED) &&
2409                     group->blocking_domain &&
2410                     group->blocking_domain != new_domain)
2411                         __iommu_attach_device(group->blocking_domain, dev);
2412                 return ret;
2413         }
2414         return 0;
2415 }
2416
2417 /*
2418  * If 0 is returned the group's domain is new_domain. If an error is returned
2419  * then the group's domain will be set back to the existing domain unless
2420  * IOMMU_SET_DOMAIN_MUST_SUCCEED, otherwise an error is returned and the group's
2421  * domains is left inconsistent. This is a driver bug to fail attach with a
2422  * previously good domain. We try to avoid a kernel UAF because of this.
2423  *
2424  * IOMMU groups are really the natural working unit of the IOMMU, but the IOMMU
2425  * API works on domains and devices.  Bridge that gap by iterating over the
2426  * devices in a group.  Ideally we'd have a single device which represents the
2427  * requestor ID of the group, but we also allow IOMMU drivers to create policy
2428  * defined minimum sets, where the physical hardware may be able to distiguish
2429  * members, but we wish to group them at a higher level (ex. untrusted
2430  * multi-function PCI devices).  Thus we attach each device.
2431  */
2432 static int __iommu_group_set_domain_internal(struct iommu_group *group,
2433                                              struct iommu_domain *new_domain,
2434                                              unsigned int flags)
2435 {
2436         struct group_device *last_gdev;
2437         struct group_device *gdev;
2438         int result;
2439         int ret;
2440
2441         lockdep_assert_held(&group->mutex);
2442
2443         if (group->domain == new_domain)
2444                 return 0;
2445
2446         if (WARN_ON(!new_domain))
2447                 return -EINVAL;
2448
2449         /*
2450          * Changing the domain is done by calling attach_dev() on the new
2451          * domain. This switch does not have to be atomic and DMA can be
2452          * discarded during the transition. DMA must only be able to access
2453          * either new_domain or group->domain, never something else.
2454          */
2455         result = 0;
2456         for_each_group_device(group, gdev) {
2457                 ret = __iommu_device_set_domain(group, gdev->dev, new_domain,
2458                                                 flags);
2459                 if (ret) {
2460                         result = ret;
2461                         /*
2462                          * Keep trying the other devices in the group. If a
2463                          * driver fails attach to an otherwise good domain, and
2464                          * does not support blocking domains, it should at least
2465                          * drop its reference on the current domain so we don't
2466                          * UAF.
2467                          */
2468                         if (flags & IOMMU_SET_DOMAIN_MUST_SUCCEED)
2469                                 continue;
2470                         goto err_revert;
2471                 }
2472         }
2473         group->domain = new_domain;
2474         return result;
2475
2476 err_revert:
2477         /*
2478          * This is called in error unwind paths. A well behaved driver should
2479          * always allow us to attach to a domain that was already attached.
2480          */
2481         last_gdev = gdev;
2482         for_each_group_device(group, gdev) {
2483                 /*
2484                  * A NULL domain can happen only for first probe, in which case
2485                  * we leave group->domain as NULL and let release clean
2486                  * everything up.
2487                  */
2488                 if (group->domain)
2489                         WARN_ON(__iommu_device_set_domain(
2490                                 group, gdev->dev, group->domain,
2491                                 IOMMU_SET_DOMAIN_MUST_SUCCEED));
2492                 if (gdev == last_gdev)
2493                         break;
2494         }
2495         return ret;
2496 }
2497
2498 void iommu_detach_group(struct iommu_domain *domain, struct iommu_group *group)
2499 {
2500         mutex_lock(&group->mutex);
2501         __iommu_group_set_core_domain(group);
2502         mutex_unlock(&group->mutex);
2503 }
2504 EXPORT_SYMBOL_GPL(iommu_detach_group);
2505
2506 phys_addr_t iommu_iova_to_phys(struct iommu_domain *domain, dma_addr_t iova)
2507 {
2508         if (domain->type == IOMMU_DOMAIN_IDENTITY)
2509                 return iova;
2510
2511         if (domain->type == IOMMU_DOMAIN_BLOCKED)
2512                 return 0;
2513
2514         return domain->ops->iova_to_phys(domain, iova);
2515 }
2516 EXPORT_SYMBOL_GPL(iommu_iova_to_phys);
2517
2518 static size_t iommu_pgsize(struct iommu_domain *domain, unsigned long iova,
2519                            phys_addr_t paddr, size_t size, size_t *count)
2520 {
2521         unsigned int pgsize_idx, pgsize_idx_next;
2522         unsigned long pgsizes;
2523         size_t offset, pgsize, pgsize_next;
2524         unsigned long addr_merge = paddr | iova;
2525
2526         /* Page sizes supported by the hardware and small enough for @size */
2527         pgsizes = domain->pgsize_bitmap & GENMASK(__fls(size), 0);
2528
2529         /* Constrain the page sizes further based on the maximum alignment */
2530         if (likely(addr_merge))
2531                 pgsizes &= GENMASK(__ffs(addr_merge), 0);
2532
2533         /* Make sure we have at least one suitable page size */
2534         BUG_ON(!pgsizes);
2535
2536         /* Pick the biggest page size remaining */
2537         pgsize_idx = __fls(pgsizes);
2538         pgsize = BIT(pgsize_idx);
2539         if (!count)
2540                 return pgsize;
2541
2542         /* Find the next biggest support page size, if it exists */
2543         pgsizes = domain->pgsize_bitmap & ~GENMASK(pgsize_idx, 0);
2544         if (!pgsizes)
2545                 goto out_set_count;
2546
2547         pgsize_idx_next = __ffs(pgsizes);
2548         pgsize_next = BIT(pgsize_idx_next);
2549
2550         /*
2551          * There's no point trying a bigger page size unless the virtual
2552          * and physical addresses are similarly offset within the larger page.
2553          */
2554         if ((iova ^ paddr) & (pgsize_next - 1))
2555                 goto out_set_count;
2556
2557         /* Calculate the offset to the next page size alignment boundary */
2558         offset = pgsize_next - (addr_merge & (pgsize_next - 1));
2559
2560         /*
2561          * If size is big enough to accommodate the larger page, reduce
2562          * the number of smaller pages.
2563          */
2564         if (offset + pgsize_next <= size)
2565                 size = offset;
2566
2567 out_set_count:
2568         *count = size >> pgsize_idx;
2569         return pgsize;
2570 }
2571
2572 static int __iommu_map(struct iommu_domain *domain, unsigned long iova,
2573                        phys_addr_t paddr, size_t size, int prot, gfp_t gfp)
2574 {
2575         const struct iommu_domain_ops *ops = domain->ops;
2576         unsigned long orig_iova = iova;
2577         unsigned int min_pagesz;
2578         size_t orig_size = size;
2579         phys_addr_t orig_paddr = paddr;
2580         int ret = 0;
2581
2582         if (unlikely(!(domain->type & __IOMMU_DOMAIN_PAGING)))
2583                 return -EINVAL;
2584
2585         if (WARN_ON(!ops->map_pages || domain->pgsize_bitmap == 0UL))
2586                 return -ENODEV;
2587
2588         /* find out the minimum page size supported */
2589         min_pagesz = 1 << __ffs(domain->pgsize_bitmap);
2590
2591         /*
2592          * both the virtual address and the physical one, as well as
2593          * the size of the mapping, must be aligned (at least) to the
2594          * size of the smallest page supported by the hardware
2595          */
2596         if (!IS_ALIGNED(iova | paddr | size, min_pagesz)) {
2597                 pr_err("unaligned: iova 0x%lx pa %pa size 0x%zx min_pagesz 0x%x\n",
2598                        iova, &paddr, size, min_pagesz);
2599                 return -EINVAL;
2600         }
2601
2602         pr_debug("map: iova 0x%lx pa %pa size 0x%zx\n", iova, &paddr, size);
2603
2604         while (size) {
2605                 size_t pgsize, count, mapped = 0;
2606
2607                 pgsize = iommu_pgsize(domain, iova, paddr, size, &count);
2608
2609                 pr_debug("mapping: iova 0x%lx pa %pa pgsize 0x%zx count %zu\n",
2610                          iova, &paddr, pgsize, count);
2611                 ret = ops->map_pages(domain, iova, paddr, pgsize, count, prot,
2612                                      gfp, &mapped);
2613                 /*
2614                  * Some pages may have been mapped, even if an error occurred,
2615                  * so we should account for those so they can be unmapped.
2616                  */
2617                 size -= mapped;
2618
2619                 if (ret)
2620                         break;
2621
2622                 iova += mapped;
2623                 paddr += mapped;
2624         }
2625
2626         /* unroll mapping in case something went wrong */
2627         if (ret)
2628                 iommu_unmap(domain, orig_iova, orig_size - size);
2629         else
2630                 trace_map(orig_iova, orig_paddr, orig_size);
2631
2632         return ret;
2633 }
2634
2635 int iommu_map(struct iommu_domain *domain, unsigned long iova,
2636               phys_addr_t paddr, size_t size, int prot, gfp_t gfp)
2637 {
2638         const struct iommu_domain_ops *ops = domain->ops;
2639         int ret;
2640
2641         might_sleep_if(gfpflags_allow_blocking(gfp));
2642
2643         /* Discourage passing strange GFP flags */
2644         if (WARN_ON_ONCE(gfp & (__GFP_COMP | __GFP_DMA | __GFP_DMA32 |
2645                                 __GFP_HIGHMEM)))
2646                 return -EINVAL;
2647
2648         ret = __iommu_map(domain, iova, paddr, size, prot, gfp);
2649         if (ret == 0 && ops->iotlb_sync_map) {
2650                 ret = ops->iotlb_sync_map(domain, iova, size);
2651                 if (ret)
2652                         goto out_err;
2653         }
2654
2655         return ret;
2656
2657 out_err:
2658         /* undo mappings already done */
2659         iommu_unmap(domain, iova, size);
2660
2661         return ret;
2662 }
2663 EXPORT_SYMBOL_GPL(iommu_map);
2664
2665 static size_t __iommu_unmap(struct iommu_domain *domain,
2666                             unsigned long iova, size_t size,
2667                             struct iommu_iotlb_gather *iotlb_gather)
2668 {
2669         const struct iommu_domain_ops *ops = domain->ops;
2670         size_t unmapped_page, unmapped = 0;
2671         unsigned long orig_iova = iova;
2672         unsigned int min_pagesz;
2673
2674         if (unlikely(!(domain->type & __IOMMU_DOMAIN_PAGING)))
2675                 return 0;
2676
2677         if (WARN_ON(!ops->unmap_pages || domain->pgsize_bitmap == 0UL))
2678                 return 0;
2679
2680         /* find out the minimum page size supported */
2681         min_pagesz = 1 << __ffs(domain->pgsize_bitmap);
2682
2683         /*
2684          * The virtual address, as well as the size of the mapping, must be
2685          * aligned (at least) to the size of the smallest page supported
2686          * by the hardware
2687          */
2688         if (!IS_ALIGNED(iova | size, min_pagesz)) {
2689                 pr_err("unaligned: iova 0x%lx size 0x%zx min_pagesz 0x%x\n",
2690                        iova, size, min_pagesz);
2691                 return 0;
2692         }
2693
2694         pr_debug("unmap this: iova 0x%lx size 0x%zx\n", iova, size);
2695
2696         /*
2697          * Keep iterating until we either unmap 'size' bytes (or more)
2698          * or we hit an area that isn't mapped.
2699          */
2700         while (unmapped < size) {
2701                 size_t pgsize, count;
2702
2703                 pgsize = iommu_pgsize(domain, iova, iova, size - unmapped, &count);
2704                 unmapped_page = ops->unmap_pages(domain, iova, pgsize, count, iotlb_gather);
2705                 if (!unmapped_page)
2706                         break;
2707
2708                 pr_debug("unmapped: iova 0x%lx size 0x%zx\n",
2709                          iova, unmapped_page);
2710
2711                 iova += unmapped_page;
2712                 unmapped += unmapped_page;
2713         }
2714
2715         trace_unmap(orig_iova, size, unmapped);
2716         return unmapped;
2717 }
2718
2719 size_t iommu_unmap(struct iommu_domain *domain,
2720                    unsigned long iova, size_t size)
2721 {
2722         struct iommu_iotlb_gather iotlb_gather;
2723         size_t ret;
2724
2725         iommu_iotlb_gather_init(&iotlb_gather);
2726         ret = __iommu_unmap(domain, iova, size, &iotlb_gather);
2727         iommu_iotlb_sync(domain, &iotlb_gather);
2728
2729         return ret;
2730 }
2731 EXPORT_SYMBOL_GPL(iommu_unmap);
2732
2733 size_t iommu_unmap_fast(struct iommu_domain *domain,
2734                         unsigned long iova, size_t size,
2735                         struct iommu_iotlb_gather *iotlb_gather)
2736 {
2737         return __iommu_unmap(domain, iova, size, iotlb_gather);
2738 }
2739 EXPORT_SYMBOL_GPL(iommu_unmap_fast);
2740
2741 ssize_t iommu_map_sg(struct iommu_domain *domain, unsigned long iova,
2742                      struct scatterlist *sg, unsigned int nents, int prot,
2743                      gfp_t gfp)
2744 {
2745         const struct iommu_domain_ops *ops = domain->ops;
2746         size_t len = 0, mapped = 0;
2747         phys_addr_t start;
2748         unsigned int i = 0;
2749         int ret;
2750
2751         might_sleep_if(gfpflags_allow_blocking(gfp));
2752
2753         /* Discourage passing strange GFP flags */
2754         if (WARN_ON_ONCE(gfp & (__GFP_COMP | __GFP_DMA | __GFP_DMA32 |
2755                                 __GFP_HIGHMEM)))
2756                 return -EINVAL;
2757
2758         while (i <= nents) {
2759                 phys_addr_t s_phys = sg_phys(sg);
2760
2761                 if (len && s_phys != start + len) {
2762                         ret = __iommu_map(domain, iova + mapped, start,
2763                                         len, prot, gfp);
2764
2765                         if (ret)
2766                                 goto out_err;
2767
2768                         mapped += len;
2769                         len = 0;
2770                 }
2771
2772                 if (sg_dma_is_bus_address(sg))
2773                         goto next;
2774
2775                 if (len) {
2776                         len += sg->length;
2777                 } else {
2778                         len = sg->length;
2779                         start = s_phys;
2780                 }
2781
2782 next:
2783                 if (++i < nents)
2784                         sg = sg_next(sg);
2785         }
2786
2787         if (ops->iotlb_sync_map) {
2788                 ret = ops->iotlb_sync_map(domain, iova, mapped);
2789                 if (ret)
2790                         goto out_err;
2791         }
2792         return mapped;
2793
2794 out_err:
2795         /* undo mappings already done */
2796         iommu_unmap(domain, iova, mapped);
2797
2798         return ret;
2799 }
2800 EXPORT_SYMBOL_GPL(iommu_map_sg);
2801
2802 /**
2803  * report_iommu_fault() - report about an IOMMU fault to the IOMMU framework
2804  * @domain: the iommu domain where the fault has happened
2805  * @dev: the device where the fault has happened
2806  * @iova: the faulting address
2807  * @flags: mmu fault flags (e.g. IOMMU_FAULT_READ/IOMMU_FAULT_WRITE/...)
2808  *
2809  * This function should be called by the low-level IOMMU implementations
2810  * whenever IOMMU faults happen, to allow high-level users, that are
2811  * interested in such events, to know about them.
2812  *
2813  * This event may be useful for several possible use cases:
2814  * - mere logging of the event
2815  * - dynamic TLB/PTE loading
2816  * - if restarting of the faulting device is required
2817  *
2818  * Returns 0 on success and an appropriate error code otherwise (if dynamic
2819  * PTE/TLB loading will one day be supported, implementations will be able
2820  * to tell whether it succeeded or not according to this return value).
2821  *
2822  * Specifically, -ENOSYS is returned if a fault handler isn't installed
2823  * (though fault handlers can also return -ENOSYS, in case they want to
2824  * elicit the default behavior of the IOMMU drivers).
2825  */
2826 int report_iommu_fault(struct iommu_domain *domain, struct device *dev,
2827                        unsigned long iova, int flags)
2828 {
2829         int ret = -ENOSYS;
2830
2831         /*
2832          * if upper layers showed interest and installed a fault handler,
2833          * invoke it.
2834          */
2835         if (domain->handler)
2836                 ret = domain->handler(domain, dev, iova, flags,
2837                                                 domain->handler_token);
2838
2839         trace_io_page_fault(dev, iova, flags);
2840         return ret;
2841 }
2842 EXPORT_SYMBOL_GPL(report_iommu_fault);
2843
2844 static int __init iommu_init(void)
2845 {
2846         iommu_group_kset = kset_create_and_add("iommu_groups",
2847                                                NULL, kernel_kobj);
2848         BUG_ON(!iommu_group_kset);
2849
2850         iommu_debugfs_setup();
2851
2852         return 0;
2853 }
2854 core_initcall(iommu_init);
2855
2856 int iommu_enable_nesting(struct iommu_domain *domain)
2857 {
2858         if (domain->type != IOMMU_DOMAIN_UNMANAGED)
2859                 return -EINVAL;
2860         if (!domain->ops->enable_nesting)
2861                 return -EINVAL;
2862         return domain->ops->enable_nesting(domain);
2863 }
2864 EXPORT_SYMBOL_GPL(iommu_enable_nesting);
2865
2866 int iommu_set_pgtable_quirks(struct iommu_domain *domain,
2867                 unsigned long quirk)
2868 {
2869         if (domain->type != IOMMU_DOMAIN_UNMANAGED)
2870                 return -EINVAL;
2871         if (!domain->ops->set_pgtable_quirks)
2872                 return -EINVAL;
2873         return domain->ops->set_pgtable_quirks(domain, quirk);
2874 }
2875 EXPORT_SYMBOL_GPL(iommu_set_pgtable_quirks);
2876
2877 /**
2878  * iommu_get_resv_regions - get reserved regions
2879  * @dev: device for which to get reserved regions
2880  * @list: reserved region list for device
2881  *
2882  * This returns a list of reserved IOVA regions specific to this device.
2883  * A domain user should not map IOVA in these ranges.
2884  */
2885 void iommu_get_resv_regions(struct device *dev, struct list_head *list)
2886 {
2887         const struct iommu_ops *ops = dev_iommu_ops(dev);
2888
2889         if (ops->get_resv_regions)
2890                 ops->get_resv_regions(dev, list);
2891 }
2892 EXPORT_SYMBOL_GPL(iommu_get_resv_regions);
2893
2894 /**
2895  * iommu_put_resv_regions - release reserved regions
2896  * @dev: device for which to free reserved regions
2897  * @list: reserved region list for device
2898  *
2899  * This releases a reserved region list acquired by iommu_get_resv_regions().
2900  */
2901 void iommu_put_resv_regions(struct device *dev, struct list_head *list)
2902 {
2903         struct iommu_resv_region *entry, *next;
2904
2905         list_for_each_entry_safe(entry, next, list, list) {
2906                 if (entry->free)
2907                         entry->free(dev, entry);
2908                 else
2909                         kfree(entry);
2910         }
2911 }
2912 EXPORT_SYMBOL(iommu_put_resv_regions);
2913
2914 struct iommu_resv_region *iommu_alloc_resv_region(phys_addr_t start,
2915                                                   size_t length, int prot,
2916                                                   enum iommu_resv_type type,
2917                                                   gfp_t gfp)
2918 {
2919         struct iommu_resv_region *region;
2920
2921         region = kzalloc(sizeof(*region), gfp);
2922         if (!region)
2923                 return NULL;
2924
2925         INIT_LIST_HEAD(&region->list);
2926         region->start = start;
2927         region->length = length;
2928         region->prot = prot;
2929         region->type = type;
2930         return region;
2931 }
2932 EXPORT_SYMBOL_GPL(iommu_alloc_resv_region);
2933
2934 void iommu_set_default_passthrough(bool cmd_line)
2935 {
2936         if (cmd_line)
2937                 iommu_cmd_line |= IOMMU_CMD_LINE_DMA_API;
2938         iommu_def_domain_type = IOMMU_DOMAIN_IDENTITY;
2939 }
2940
2941 void iommu_set_default_translated(bool cmd_line)
2942 {
2943         if (cmd_line)
2944                 iommu_cmd_line |= IOMMU_CMD_LINE_DMA_API;
2945         iommu_def_domain_type = IOMMU_DOMAIN_DMA;
2946 }
2947
2948 bool iommu_default_passthrough(void)
2949 {
2950         return iommu_def_domain_type == IOMMU_DOMAIN_IDENTITY;
2951 }
2952 EXPORT_SYMBOL_GPL(iommu_default_passthrough);
2953
2954 const struct iommu_ops *iommu_ops_from_fwnode(struct fwnode_handle *fwnode)
2955 {
2956         const struct iommu_ops *ops = NULL;
2957         struct iommu_device *iommu;
2958
2959         spin_lock(&iommu_device_lock);
2960         list_for_each_entry(iommu, &iommu_device_list, list)
2961                 if (iommu->fwnode == fwnode) {
2962                         ops = iommu->ops;
2963                         break;
2964                 }
2965         spin_unlock(&iommu_device_lock);
2966         return ops;
2967 }
2968
2969 int iommu_fwspec_init(struct device *dev, struct fwnode_handle *iommu_fwnode,
2970                       const struct iommu_ops *ops)
2971 {
2972         struct iommu_fwspec *fwspec = dev_iommu_fwspec_get(dev);
2973
2974         if (fwspec)
2975                 return ops == fwspec->ops ? 0 : -EINVAL;
2976
2977         if (!dev_iommu_get(dev))
2978                 return -ENOMEM;
2979
2980         /* Preallocate for the overwhelmingly common case of 1 ID */
2981         fwspec = kzalloc(struct_size(fwspec, ids, 1), GFP_KERNEL);
2982         if (!fwspec)
2983                 return -ENOMEM;
2984
2985         of_node_get(to_of_node(iommu_fwnode));
2986         fwspec->iommu_fwnode = iommu_fwnode;
2987         fwspec->ops = ops;
2988         dev_iommu_fwspec_set(dev, fwspec);
2989         return 0;
2990 }
2991 EXPORT_SYMBOL_GPL(iommu_fwspec_init);
2992
2993 void iommu_fwspec_free(struct device *dev)
2994 {
2995         struct iommu_fwspec *fwspec = dev_iommu_fwspec_get(dev);
2996
2997         if (fwspec) {
2998                 fwnode_handle_put(fwspec->iommu_fwnode);
2999                 kfree(fwspec);
3000                 dev_iommu_fwspec_set(dev, NULL);
3001         }
3002 }
3003 EXPORT_SYMBOL_GPL(iommu_fwspec_free);
3004
3005 int iommu_fwspec_add_ids(struct device *dev, u32 *ids, int num_ids)
3006 {
3007         struct iommu_fwspec *fwspec = dev_iommu_fwspec_get(dev);
3008         int i, new_num;
3009
3010         if (!fwspec)
3011                 return -EINVAL;
3012
3013         new_num = fwspec->num_ids + num_ids;
3014         if (new_num > 1) {
3015                 fwspec = krealloc(fwspec, struct_size(fwspec, ids, new_num),
3016                                   GFP_KERNEL);
3017                 if (!fwspec)
3018                         return -ENOMEM;
3019
3020                 dev_iommu_fwspec_set(dev, fwspec);
3021         }
3022
3023         for (i = 0; i < num_ids; i++)
3024                 fwspec->ids[fwspec->num_ids + i] = ids[i];
3025
3026         fwspec->num_ids = new_num;
3027         return 0;
3028 }
3029 EXPORT_SYMBOL_GPL(iommu_fwspec_add_ids);
3030
3031 /*
3032  * Per device IOMMU features.
3033  */
3034 int iommu_dev_enable_feature(struct device *dev, enum iommu_dev_features feat)
3035 {
3036         if (dev_has_iommu(dev)) {
3037                 const struct iommu_ops *ops = dev_iommu_ops(dev);
3038
3039                 if (ops->dev_enable_feat)
3040                         return ops->dev_enable_feat(dev, feat);
3041         }
3042
3043         return -ENODEV;
3044 }
3045 EXPORT_SYMBOL_GPL(iommu_dev_enable_feature);
3046
3047 /*
3048  * The device drivers should do the necessary cleanups before calling this.
3049  */
3050 int iommu_dev_disable_feature(struct device *dev, enum iommu_dev_features feat)
3051 {
3052         if (dev_has_iommu(dev)) {
3053                 const struct iommu_ops *ops = dev_iommu_ops(dev);
3054
3055                 if (ops->dev_disable_feat)
3056                         return ops->dev_disable_feat(dev, feat);
3057         }
3058
3059         return -EBUSY;
3060 }
3061 EXPORT_SYMBOL_GPL(iommu_dev_disable_feature);
3062
3063 /**
3064  * iommu_setup_default_domain - Set the default_domain for the group
3065  * @group: Group to change
3066  * @target_type: Domain type to set as the default_domain
3067  *
3068  * Allocate a default domain and set it as the current domain on the group. If
3069  * the group already has a default domain it will be changed to the target_type.
3070  * When target_type is 0 the default domain is selected based on driver and
3071  * system preferences.
3072  */
3073 static int iommu_setup_default_domain(struct iommu_group *group,
3074                                       int target_type)
3075 {
3076         struct iommu_domain *old_dom = group->default_domain;
3077         struct group_device *gdev;
3078         struct iommu_domain *dom;
3079         bool direct_failed;
3080         int req_type;
3081         int ret;
3082
3083         lockdep_assert_held(&group->mutex);
3084
3085         req_type = iommu_get_default_domain_type(group, target_type);
3086         if (req_type < 0)
3087                 return -EINVAL;
3088
3089         dom = iommu_group_alloc_default_domain(group, req_type);
3090         if (!dom)
3091                 return -ENODEV;
3092
3093         if (group->default_domain == dom)
3094                 return 0;
3095
3096         /*
3097          * IOMMU_RESV_DIRECT and IOMMU_RESV_DIRECT_RELAXABLE regions must be
3098          * mapped before their device is attached, in order to guarantee
3099          * continuity with any FW activity
3100          */
3101         direct_failed = false;
3102         for_each_group_device(group, gdev) {
3103                 if (iommu_create_device_direct_mappings(dom, gdev->dev)) {
3104                         direct_failed = true;
3105                         dev_warn_once(
3106                                 gdev->dev->iommu->iommu_dev->dev,
3107                                 "IOMMU driver was not able to establish FW requested direct mapping.");
3108                 }
3109         }
3110
3111         /* We must set default_domain early for __iommu_device_set_domain */
3112         group->default_domain = dom;
3113         if (!group->domain) {
3114                 /*
3115                  * Drivers are not allowed to fail the first domain attach.
3116                  * The only way to recover from this is to fail attaching the
3117                  * iommu driver and call ops->release_device. Put the domain
3118                  * in group->default_domain so it is freed after.
3119                  */
3120                 ret = __iommu_group_set_domain_internal(
3121                         group, dom, IOMMU_SET_DOMAIN_MUST_SUCCEED);
3122                 if (WARN_ON(ret))
3123                         goto out_free_old;
3124         } else {
3125                 ret = __iommu_group_set_domain(group, dom);
3126                 if (ret)
3127                         goto err_restore_def_domain;
3128         }
3129
3130         /*
3131          * Drivers are supposed to allow mappings to be installed in a domain
3132          * before device attachment, but some don't. Hack around this defect by
3133          * trying again after attaching. If this happens it means the device
3134          * will not continuously have the IOMMU_RESV_DIRECT map.
3135          */
3136         if (direct_failed) {
3137                 for_each_group_device(group, gdev) {
3138                         ret = iommu_create_device_direct_mappings(dom, gdev->dev);
3139                         if (ret)
3140                                 goto err_restore_domain;
3141                 }
3142         }
3143
3144 out_free_old:
3145         if (old_dom)
3146                 iommu_domain_free(old_dom);
3147         return ret;
3148
3149 err_restore_domain:
3150         if (old_dom)
3151                 __iommu_group_set_domain_internal(
3152                         group, old_dom, IOMMU_SET_DOMAIN_MUST_SUCCEED);
3153 err_restore_def_domain:
3154         if (old_dom) {
3155                 iommu_domain_free(dom);
3156                 group->default_domain = old_dom;
3157         }
3158         return ret;
3159 }
3160
3161 /*
3162  * Changing the default domain through sysfs requires the users to unbind the
3163  * drivers from the devices in the iommu group, except for a DMA -> DMA-FQ
3164  * transition. Return failure if this isn't met.
3165  *
3166  * We need to consider the race between this and the device release path.
3167  * group->mutex is used here to guarantee that the device release path
3168  * will not be entered at the same time.
3169  */
3170 static ssize_t iommu_group_store_type(struct iommu_group *group,
3171                                       const char *buf, size_t count)
3172 {
3173         struct group_device *gdev;
3174         int ret, req_type;
3175
3176         if (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO))
3177                 return -EACCES;
3178
3179         if (WARN_ON(!group) || !group->default_domain)
3180                 return -EINVAL;
3181
3182         if (sysfs_streq(buf, "identity"))
3183                 req_type = IOMMU_DOMAIN_IDENTITY;
3184         else if (sysfs_streq(buf, "DMA"))
3185                 req_type = IOMMU_DOMAIN_DMA;
3186         else if (sysfs_streq(buf, "DMA-FQ"))
3187                 req_type = IOMMU_DOMAIN_DMA_FQ;
3188         else if (sysfs_streq(buf, "auto"))
3189                 req_type = 0;
3190         else
3191                 return -EINVAL;
3192
3193         mutex_lock(&group->mutex);
3194         /* We can bring up a flush queue without tearing down the domain. */
3195         if (req_type == IOMMU_DOMAIN_DMA_FQ &&
3196             group->default_domain->type == IOMMU_DOMAIN_DMA) {
3197                 ret = iommu_dma_init_fq(group->default_domain);
3198                 if (ret)
3199                         goto out_unlock;
3200
3201                 group->default_domain->type = IOMMU_DOMAIN_DMA_FQ;
3202                 ret = count;
3203                 goto out_unlock;
3204         }
3205
3206         /* Otherwise, ensure that device exists and no driver is bound. */
3207         if (list_empty(&group->devices) || group->owner_cnt) {
3208                 ret = -EPERM;
3209                 goto out_unlock;
3210         }
3211
3212         ret = iommu_setup_default_domain(group, req_type);
3213         if (ret)
3214                 goto out_unlock;
3215
3216         /*
3217          * Release the mutex here because ops->probe_finalize() call-back of
3218          * some vendor IOMMU drivers calls arm_iommu_attach_device() which
3219          * in-turn might call back into IOMMU core code, where it tries to take
3220          * group->mutex, resulting in a deadlock.
3221          */
3222         mutex_unlock(&group->mutex);
3223
3224         /* Make sure dma_ops is appropriatley set */
3225         for_each_group_device(group, gdev)
3226                 iommu_group_do_probe_finalize(gdev->dev);
3227         return count;
3228
3229 out_unlock:
3230         mutex_unlock(&group->mutex);
3231         return ret ?: count;
3232 }
3233
3234 /**
3235  * iommu_device_use_default_domain() - Device driver wants to handle device
3236  *                                     DMA through the kernel DMA API.
3237  * @dev: The device.
3238  *
3239  * The device driver about to bind @dev wants to do DMA through the kernel
3240  * DMA API. Return 0 if it is allowed, otherwise an error.
3241  */
3242 int iommu_device_use_default_domain(struct device *dev)
3243 {
3244         /* Caller is the driver core during the pre-probe path */
3245         struct iommu_group *group = dev->iommu_group;
3246         int ret = 0;
3247
3248         if (!group)
3249                 return 0;
3250
3251         mutex_lock(&group->mutex);
3252         if (group->owner_cnt) {
3253                 if (group->domain != group->default_domain || group->owner ||
3254                     !xa_empty(&group->pasid_array)) {
3255                         ret = -EBUSY;
3256                         goto unlock_out;
3257                 }
3258         }
3259
3260         group->owner_cnt++;
3261
3262 unlock_out:
3263         mutex_unlock(&group->mutex);
3264         return ret;
3265 }
3266
3267 /**
3268  * iommu_device_unuse_default_domain() - Device driver stops handling device
3269  *                                       DMA through the kernel DMA API.
3270  * @dev: The device.
3271  *
3272  * The device driver doesn't want to do DMA through kernel DMA API anymore.
3273  * It must be called after iommu_device_use_default_domain().
3274  */
3275 void iommu_device_unuse_default_domain(struct device *dev)
3276 {
3277         /* Caller is the driver core during the post-probe path */
3278         struct iommu_group *group = dev->iommu_group;
3279
3280         if (!group)
3281                 return;
3282
3283         mutex_lock(&group->mutex);
3284         if (!WARN_ON(!group->owner_cnt || !xa_empty(&group->pasid_array)))
3285                 group->owner_cnt--;
3286
3287         mutex_unlock(&group->mutex);
3288 }
3289
3290 static int __iommu_group_alloc_blocking_domain(struct iommu_group *group)
3291 {
3292         if (group->blocking_domain)
3293                 return 0;
3294
3295         group->blocking_domain =
3296                 __iommu_group_domain_alloc(group, IOMMU_DOMAIN_BLOCKED);
3297         if (!group->blocking_domain) {
3298                 /*
3299                  * For drivers that do not yet understand IOMMU_DOMAIN_BLOCKED
3300                  * create an empty domain instead.
3301                  */
3302                 group->blocking_domain = __iommu_group_domain_alloc(
3303                         group, IOMMU_DOMAIN_UNMANAGED);
3304                 if (!group->blocking_domain)
3305                         return -EINVAL;
3306         }
3307         return 0;
3308 }
3309
3310 static int __iommu_take_dma_ownership(struct iommu_group *group, void *owner)
3311 {
3312         int ret;
3313
3314         if ((group->domain && group->domain != group->default_domain) ||
3315             !xa_empty(&group->pasid_array))
3316                 return -EBUSY;
3317
3318         ret = __iommu_group_alloc_blocking_domain(group);
3319         if (ret)
3320                 return ret;
3321         ret = __iommu_group_set_domain(group, group->blocking_domain);
3322         if (ret)
3323                 return ret;
3324
3325         group->owner = owner;
3326         group->owner_cnt++;
3327         return 0;
3328 }
3329
3330 /**
3331  * iommu_group_claim_dma_owner() - Set DMA ownership of a group
3332  * @group: The group.
3333  * @owner: Caller specified pointer. Used for exclusive ownership.
3334  *
3335  * This is to support backward compatibility for vfio which manages the dma
3336  * ownership in iommu_group level. New invocations on this interface should be
3337  * prohibited. Only a single owner may exist for a group.
3338  */
3339 int iommu_group_claim_dma_owner(struct iommu_group *group, void *owner)
3340 {
3341         int ret = 0;
3342
3343         if (WARN_ON(!owner))
3344                 return -EINVAL;
3345
3346         mutex_lock(&group->mutex);
3347         if (group->owner_cnt) {
3348                 ret = -EPERM;
3349                 goto unlock_out;
3350         }
3351
3352         ret = __iommu_take_dma_ownership(group, owner);
3353 unlock_out:
3354         mutex_unlock(&group->mutex);
3355
3356         return ret;
3357 }
3358 EXPORT_SYMBOL_GPL(iommu_group_claim_dma_owner);
3359
3360 /**
3361  * iommu_device_claim_dma_owner() - Set DMA ownership of a device
3362  * @dev: The device.
3363  * @owner: Caller specified pointer. Used for exclusive ownership.
3364  *
3365  * Claim the DMA ownership of a device. Multiple devices in the same group may
3366  * concurrently claim ownership if they present the same owner value. Returns 0
3367  * on success and error code on failure
3368  */
3369 int iommu_device_claim_dma_owner(struct device *dev, void *owner)
3370 {
3371         /* Caller must be a probed driver on dev */
3372         struct iommu_group *group = dev->iommu_group;
3373         int ret = 0;
3374
3375         if (WARN_ON(!owner))
3376                 return -EINVAL;
3377
3378         if (!group)
3379                 return -ENODEV;
3380
3381         mutex_lock(&group->mutex);
3382         if (group->owner_cnt) {
3383                 if (group->owner != owner) {
3384                         ret = -EPERM;
3385                         goto unlock_out;
3386                 }
3387                 group->owner_cnt++;
3388                 goto unlock_out;
3389         }
3390
3391         ret = __iommu_take_dma_ownership(group, owner);
3392 unlock_out:
3393         mutex_unlock(&group->mutex);
3394         return ret;
3395 }
3396 EXPORT_SYMBOL_GPL(iommu_device_claim_dma_owner);
3397
3398 static void __iommu_release_dma_ownership(struct iommu_group *group)
3399 {
3400         if (WARN_ON(!group->owner_cnt || !group->owner ||
3401                     !xa_empty(&group->pasid_array)))
3402                 return;
3403
3404         group->owner_cnt = 0;
3405         group->owner = NULL;
3406         __iommu_group_set_domain_nofail(group, group->default_domain);
3407 }
3408
3409 /**
3410  * iommu_group_release_dma_owner() - Release DMA ownership of a group
3411  * @group: The group
3412  *
3413  * Release the DMA ownership claimed by iommu_group_claim_dma_owner().
3414  */
3415 void iommu_group_release_dma_owner(struct iommu_group *group)
3416 {
3417         mutex_lock(&group->mutex);
3418         __iommu_release_dma_ownership(group);
3419         mutex_unlock(&group->mutex);
3420 }
3421 EXPORT_SYMBOL_GPL(iommu_group_release_dma_owner);
3422
3423 /**
3424  * iommu_device_release_dma_owner() - Release DMA ownership of a device
3425  * @dev: The device.
3426  *
3427  * Release the DMA ownership claimed by iommu_device_claim_dma_owner().
3428  */
3429 void iommu_device_release_dma_owner(struct device *dev)
3430 {
3431         /* Caller must be a probed driver on dev */
3432         struct iommu_group *group = dev->iommu_group;
3433
3434         mutex_lock(&group->mutex);
3435         if (group->owner_cnt > 1)
3436                 group->owner_cnt--;
3437         else
3438                 __iommu_release_dma_ownership(group);
3439         mutex_unlock(&group->mutex);
3440 }
3441 EXPORT_SYMBOL_GPL(iommu_device_release_dma_owner);
3442
3443 /**
3444  * iommu_group_dma_owner_claimed() - Query group dma ownership status
3445  * @group: The group.
3446  *
3447  * This provides status query on a given group. It is racy and only for
3448  * non-binding status reporting.
3449  */
3450 bool iommu_group_dma_owner_claimed(struct iommu_group *group)
3451 {
3452         unsigned int user;
3453
3454         mutex_lock(&group->mutex);
3455         user = group->owner_cnt;
3456         mutex_unlock(&group->mutex);
3457
3458         return user;
3459 }
3460 EXPORT_SYMBOL_GPL(iommu_group_dma_owner_claimed);
3461
3462 static int __iommu_set_group_pasid(struct iommu_domain *domain,
3463                                    struct iommu_group *group, ioasid_t pasid)
3464 {
3465         struct group_device *device;
3466         int ret = 0;
3467
3468         for_each_group_device(group, device) {
3469                 ret = domain->ops->set_dev_pasid(domain, device->dev, pasid);
3470                 if (ret)
3471                         break;
3472         }
3473
3474         return ret;
3475 }
3476
3477 static void __iommu_remove_group_pasid(struct iommu_group *group,
3478                                        ioasid_t pasid)
3479 {
3480         struct group_device *device;
3481         const struct iommu_ops *ops;
3482
3483         for_each_group_device(group, device) {
3484                 ops = dev_iommu_ops(device->dev);
3485                 ops->remove_dev_pasid(device->dev, pasid);
3486         }
3487 }
3488
3489 /*
3490  * iommu_attach_device_pasid() - Attach a domain to pasid of device
3491  * @domain: the iommu domain.
3492  * @dev: the attached device.
3493  * @pasid: the pasid of the device.
3494  *
3495  * Return: 0 on success, or an error.
3496  */
3497 int iommu_attach_device_pasid(struct iommu_domain *domain,
3498                               struct device *dev, ioasid_t pasid)
3499 {
3500         /* Caller must be a probed driver on dev */
3501         struct iommu_group *group = dev->iommu_group;
3502         void *curr;
3503         int ret;
3504
3505         if (!domain->ops->set_dev_pasid)
3506                 return -EOPNOTSUPP;
3507
3508         if (!group)
3509                 return -ENODEV;
3510
3511         if (!dev_has_iommu(dev) || dev_iommu_ops(dev) != domain->owner)
3512                 return -EINVAL;
3513
3514         mutex_lock(&group->mutex);
3515         curr = xa_cmpxchg(&group->pasid_array, pasid, NULL, domain, GFP_KERNEL);
3516         if (curr) {
3517                 ret = xa_err(curr) ? : -EBUSY;
3518                 goto out_unlock;
3519         }
3520
3521         ret = __iommu_set_group_pasid(domain, group, pasid);
3522         if (ret) {
3523                 __iommu_remove_group_pasid(group, pasid);
3524                 xa_erase(&group->pasid_array, pasid);
3525         }
3526 out_unlock:
3527         mutex_unlock(&group->mutex);
3528         return ret;
3529 }
3530 EXPORT_SYMBOL_GPL(iommu_attach_device_pasid);
3531
3532 /*
3533  * iommu_detach_device_pasid() - Detach the domain from pasid of device
3534  * @domain: the iommu domain.
3535  * @dev: the attached device.
3536  * @pasid: the pasid of the device.
3537  *
3538  * The @domain must have been attached to @pasid of the @dev with
3539  * iommu_attach_device_pasid().
3540  */
3541 void iommu_detach_device_pasid(struct iommu_domain *domain, struct device *dev,
3542                                ioasid_t pasid)
3543 {
3544         /* Caller must be a probed driver on dev */
3545         struct iommu_group *group = dev->iommu_group;
3546
3547         mutex_lock(&group->mutex);
3548         __iommu_remove_group_pasid(group, pasid);
3549         WARN_ON(xa_erase(&group->pasid_array, pasid) != domain);
3550         mutex_unlock(&group->mutex);
3551 }
3552 EXPORT_SYMBOL_GPL(iommu_detach_device_pasid);
3553
3554 /*
3555  * iommu_get_domain_for_dev_pasid() - Retrieve domain for @pasid of @dev
3556  * @dev: the queried device
3557  * @pasid: the pasid of the device
3558  * @type: matched domain type, 0 for any match
3559  *
3560  * This is a variant of iommu_get_domain_for_dev(). It returns the existing
3561  * domain attached to pasid of a device. Callers must hold a lock around this
3562  * function, and both iommu_attach/detach_dev_pasid() whenever a domain of
3563  * type is being manipulated. This API does not internally resolve races with
3564  * attach/detach.
3565  *
3566  * Return: attached domain on success, NULL otherwise.
3567  */
3568 struct iommu_domain *iommu_get_domain_for_dev_pasid(struct device *dev,
3569                                                     ioasid_t pasid,
3570                                                     unsigned int type)
3571 {
3572         /* Caller must be a probed driver on dev */
3573         struct iommu_group *group = dev->iommu_group;
3574         struct iommu_domain *domain;
3575
3576         if (!group)
3577                 return NULL;
3578
3579         xa_lock(&group->pasid_array);
3580         domain = xa_load(&group->pasid_array, pasid);
3581         if (type && domain && domain->type != type)
3582                 domain = ERR_PTR(-EBUSY);
3583         xa_unlock(&group->pasid_array);
3584
3585         return domain;
3586 }
3587 EXPORT_SYMBOL_GPL(iommu_get_domain_for_dev_pasid);
3588
3589 struct iommu_domain *iommu_sva_domain_alloc(struct device *dev,
3590                                             struct mm_struct *mm)
3591 {
3592         const struct iommu_ops *ops = dev_iommu_ops(dev);
3593         struct iommu_domain *domain;
3594
3595         domain = ops->domain_alloc(IOMMU_DOMAIN_SVA);
3596         if (!domain)
3597                 return NULL;
3598
3599         domain->type = IOMMU_DOMAIN_SVA;
3600         mmgrab(mm);
3601         domain->mm = mm;
3602         domain->iopf_handler = iommu_sva_handle_iopf;
3603         domain->fault_data = mm;
3604
3605         return domain;
3606 }
3607
3608 ioasid_t iommu_alloc_global_pasid(struct device *dev)
3609 {
3610         int ret;
3611
3612         /* max_pasids == 0 means that the device does not support PASID */
3613         if (!dev->iommu->max_pasids)
3614                 return IOMMU_PASID_INVALID;
3615
3616         /*
3617          * max_pasids is set up by vendor driver based on number of PASID bits
3618          * supported but the IDA allocation is inclusive.
3619          */
3620         ret = ida_alloc_range(&iommu_global_pasid_ida, IOMMU_FIRST_GLOBAL_PASID,
3621                               dev->iommu->max_pasids - 1, GFP_KERNEL);
3622         return ret < 0 ? IOMMU_PASID_INVALID : ret;
3623 }
3624 EXPORT_SYMBOL_GPL(iommu_alloc_global_pasid);
3625
3626 void iommu_free_global_pasid(ioasid_t pasid)
3627 {
3628         if (WARN_ON(pasid == IOMMU_PASID_INVALID))
3629                 return;
3630
3631         ida_free(&iommu_global_pasid_ida, pasid);
3632 }
3633 EXPORT_SYMBOL_GPL(iommu_free_global_pasid);