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