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