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