iommu: Fix integer truncation
[linux-2.6-microblaze.git] / drivers / iommu / iommu.c
1 /*
2  * Copyright (C) 2007-2008 Advanced Micro Devices, Inc.
3  * Author: Joerg Roedel <jroedel@suse.de>
4  *
5  * This program is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License version 2 as published
7  * by the Free Software Foundation.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
17  */
18
19 #define pr_fmt(fmt)    "iommu: " fmt
20
21 #include <linux/device.h>
22 #include <linux/kernel.h>
23 #include <linux/bug.h>
24 #include <linux/types.h>
25 #include <linux/init.h>
26 #include <linux/export.h>
27 #include <linux/slab.h>
28 #include <linux/errno.h>
29 #include <linux/iommu.h>
30 #include <linux/idr.h>
31 #include <linux/notifier.h>
32 #include <linux/err.h>
33 #include <linux/pci.h>
34 #include <linux/bitops.h>
35 #include <linux/property.h>
36 #include <linux/fsl/mc.h>
37 #include <trace/events/iommu.h>
38
39 static struct kset *iommu_group_kset;
40 static DEFINE_IDA(iommu_group_ida);
41 #ifdef CONFIG_IOMMU_DEFAULT_PASSTHROUGH
42 static unsigned int iommu_def_domain_type = IOMMU_DOMAIN_IDENTITY;
43 #else
44 static unsigned int iommu_def_domain_type = IOMMU_DOMAIN_DMA;
45 #endif
46 static bool iommu_dma_strict __read_mostly = true;
47
48 struct iommu_group {
49         struct kobject kobj;
50         struct kobject *devices_kobj;
51         struct list_head devices;
52         struct mutex mutex;
53         struct blocking_notifier_head notifier;
54         void *iommu_data;
55         void (*iommu_data_release)(void *iommu_data);
56         char *name;
57         int id;
58         struct iommu_domain *default_domain;
59         struct iommu_domain *domain;
60 };
61
62 struct group_device {
63         struct list_head list;
64         struct device *dev;
65         char *name;
66 };
67
68 struct iommu_group_attribute {
69         struct attribute attr;
70         ssize_t (*show)(struct iommu_group *group, char *buf);
71         ssize_t (*store)(struct iommu_group *group,
72                          const char *buf, size_t count);
73 };
74
75 static const char * const iommu_group_resv_type_string[] = {
76         [IOMMU_RESV_DIRECT]     = "direct",
77         [IOMMU_RESV_RESERVED]   = "reserved",
78         [IOMMU_RESV_MSI]        = "msi",
79         [IOMMU_RESV_SW_MSI]     = "msi",
80 };
81
82 #define IOMMU_GROUP_ATTR(_name, _mode, _show, _store)           \
83 struct iommu_group_attribute iommu_group_attr_##_name =         \
84         __ATTR(_name, _mode, _show, _store)
85
86 #define to_iommu_group_attr(_attr)      \
87         container_of(_attr, struct iommu_group_attribute, attr)
88 #define to_iommu_group(_kobj)           \
89         container_of(_kobj, struct iommu_group, kobj)
90
91 static LIST_HEAD(iommu_device_list);
92 static DEFINE_SPINLOCK(iommu_device_lock);
93
94 int iommu_device_register(struct iommu_device *iommu)
95 {
96         spin_lock(&iommu_device_lock);
97         list_add_tail(&iommu->list, &iommu_device_list);
98         spin_unlock(&iommu_device_lock);
99
100         return 0;
101 }
102
103 void iommu_device_unregister(struct iommu_device *iommu)
104 {
105         spin_lock(&iommu_device_lock);
106         list_del(&iommu->list);
107         spin_unlock(&iommu_device_lock);
108 }
109
110 static struct iommu_param *iommu_get_dev_param(struct device *dev)
111 {
112         struct iommu_param *param = dev->iommu_param;
113
114         if (param)
115                 return param;
116
117         param = kzalloc(sizeof(*param), GFP_KERNEL);
118         if (!param)
119                 return NULL;
120
121         mutex_init(&param->lock);
122         dev->iommu_param = param;
123         return param;
124 }
125
126 static void iommu_free_dev_param(struct device *dev)
127 {
128         kfree(dev->iommu_param);
129         dev->iommu_param = NULL;
130 }
131
132 int iommu_probe_device(struct device *dev)
133 {
134         const struct iommu_ops *ops = dev->bus->iommu_ops;
135         int ret;
136
137         WARN_ON(dev->iommu_group);
138         if (!ops)
139                 return -EINVAL;
140
141         if (!iommu_get_dev_param(dev))
142                 return -ENOMEM;
143
144         ret = ops->add_device(dev);
145         if (ret)
146                 iommu_free_dev_param(dev);
147
148         return ret;
149 }
150
151 void iommu_release_device(struct device *dev)
152 {
153         const struct iommu_ops *ops = dev->bus->iommu_ops;
154
155         if (dev->iommu_group)
156                 ops->remove_device(dev);
157
158         iommu_free_dev_param(dev);
159 }
160
161 static struct iommu_domain *__iommu_domain_alloc(struct bus_type *bus,
162                                                  unsigned type);
163 static int __iommu_attach_device(struct iommu_domain *domain,
164                                  struct device *dev);
165 static int __iommu_attach_group(struct iommu_domain *domain,
166                                 struct iommu_group *group);
167 static void __iommu_detach_group(struct iommu_domain *domain,
168                                  struct iommu_group *group);
169
170 static int __init iommu_set_def_domain_type(char *str)
171 {
172         bool pt;
173         int ret;
174
175         ret = kstrtobool(str, &pt);
176         if (ret)
177                 return ret;
178
179         iommu_def_domain_type = pt ? IOMMU_DOMAIN_IDENTITY : IOMMU_DOMAIN_DMA;
180         return 0;
181 }
182 early_param("iommu.passthrough", iommu_set_def_domain_type);
183
184 static int __init iommu_dma_setup(char *str)
185 {
186         return kstrtobool(str, &iommu_dma_strict);
187 }
188 early_param("iommu.strict", iommu_dma_setup);
189
190 static ssize_t iommu_group_attr_show(struct kobject *kobj,
191                                      struct attribute *__attr, char *buf)
192 {
193         struct iommu_group_attribute *attr = to_iommu_group_attr(__attr);
194         struct iommu_group *group = to_iommu_group(kobj);
195         ssize_t ret = -EIO;
196
197         if (attr->show)
198                 ret = attr->show(group, buf);
199         return ret;
200 }
201
202 static ssize_t iommu_group_attr_store(struct kobject *kobj,
203                                       struct attribute *__attr,
204                                       const char *buf, size_t count)
205 {
206         struct iommu_group_attribute *attr = to_iommu_group_attr(__attr);
207         struct iommu_group *group = to_iommu_group(kobj);
208         ssize_t ret = -EIO;
209
210         if (attr->store)
211                 ret = attr->store(group, buf, count);
212         return ret;
213 }
214
215 static const struct sysfs_ops iommu_group_sysfs_ops = {
216         .show = iommu_group_attr_show,
217         .store = iommu_group_attr_store,
218 };
219
220 static int iommu_group_create_file(struct iommu_group *group,
221                                    struct iommu_group_attribute *attr)
222 {
223         return sysfs_create_file(&group->kobj, &attr->attr);
224 }
225
226 static void iommu_group_remove_file(struct iommu_group *group,
227                                     struct iommu_group_attribute *attr)
228 {
229         sysfs_remove_file(&group->kobj, &attr->attr);
230 }
231
232 static ssize_t iommu_group_show_name(struct iommu_group *group, char *buf)
233 {
234         return sprintf(buf, "%s\n", group->name);
235 }
236
237 /**
238  * iommu_insert_resv_region - Insert a new region in the
239  * list of reserved regions.
240  * @new: new region to insert
241  * @regions: list of regions
242  *
243  * The new element is sorted by address with respect to the other
244  * regions of the same type. In case it overlaps with another
245  * region of the same type, regions are merged. In case it
246  * overlaps with another region of different type, regions are
247  * not merged.
248  */
249 static int iommu_insert_resv_region(struct iommu_resv_region *new,
250                                     struct list_head *regions)
251 {
252         struct iommu_resv_region *region;
253         phys_addr_t start = new->start;
254         phys_addr_t end = new->start + new->length - 1;
255         struct list_head *pos = regions->next;
256
257         while (pos != regions) {
258                 struct iommu_resv_region *entry =
259                         list_entry(pos, struct iommu_resv_region, list);
260                 phys_addr_t a = entry->start;
261                 phys_addr_t b = entry->start + entry->length - 1;
262                 int type = entry->type;
263
264                 if (end < a) {
265                         goto insert;
266                 } else if (start > b) {
267                         pos = pos->next;
268                 } else if ((start >= a) && (end <= b)) {
269                         if (new->type == type)
270                                 goto done;
271                         else
272                                 pos = pos->next;
273                 } else {
274                         if (new->type == type) {
275                                 phys_addr_t new_start = min(a, start);
276                                 phys_addr_t new_end = max(b, end);
277
278                                 list_del(&entry->list);
279                                 entry->start = new_start;
280                                 entry->length = new_end - new_start + 1;
281                                 iommu_insert_resv_region(entry, regions);
282                         } else {
283                                 pos = pos->next;
284                         }
285                 }
286         }
287 insert:
288         region = iommu_alloc_resv_region(new->start, new->length,
289                                          new->prot, new->type);
290         if (!region)
291                 return -ENOMEM;
292
293         list_add_tail(&region->list, pos);
294 done:
295         return 0;
296 }
297
298 static int
299 iommu_insert_device_resv_regions(struct list_head *dev_resv_regions,
300                                  struct list_head *group_resv_regions)
301 {
302         struct iommu_resv_region *entry;
303         int ret = 0;
304
305         list_for_each_entry(entry, dev_resv_regions, list) {
306                 ret = iommu_insert_resv_region(entry, group_resv_regions);
307                 if (ret)
308                         break;
309         }
310         return ret;
311 }
312
313 int iommu_get_group_resv_regions(struct iommu_group *group,
314                                  struct list_head *head)
315 {
316         struct group_device *device;
317         int ret = 0;
318
319         mutex_lock(&group->mutex);
320         list_for_each_entry(device, &group->devices, list) {
321                 struct list_head dev_resv_regions;
322
323                 INIT_LIST_HEAD(&dev_resv_regions);
324                 iommu_get_resv_regions(device->dev, &dev_resv_regions);
325                 ret = iommu_insert_device_resv_regions(&dev_resv_regions, head);
326                 iommu_put_resv_regions(device->dev, &dev_resv_regions);
327                 if (ret)
328                         break;
329         }
330         mutex_unlock(&group->mutex);
331         return ret;
332 }
333 EXPORT_SYMBOL_GPL(iommu_get_group_resv_regions);
334
335 static ssize_t iommu_group_show_resv_regions(struct iommu_group *group,
336                                              char *buf)
337 {
338         struct iommu_resv_region *region, *next;
339         struct list_head group_resv_regions;
340         char *str = buf;
341
342         INIT_LIST_HEAD(&group_resv_regions);
343         iommu_get_group_resv_regions(group, &group_resv_regions);
344
345         list_for_each_entry_safe(region, next, &group_resv_regions, list) {
346                 str += sprintf(str, "0x%016llx 0x%016llx %s\n",
347                                (long long int)region->start,
348                                (long long int)(region->start +
349                                                 region->length - 1),
350                                iommu_group_resv_type_string[region->type]);
351                 kfree(region);
352         }
353
354         return (str - buf);
355 }
356
357 static ssize_t iommu_group_show_type(struct iommu_group *group,
358                                      char *buf)
359 {
360         char *type = "unknown\n";
361
362         if (group->default_domain) {
363                 switch (group->default_domain->type) {
364                 case IOMMU_DOMAIN_BLOCKED:
365                         type = "blocked\n";
366                         break;
367                 case IOMMU_DOMAIN_IDENTITY:
368                         type = "identity\n";
369                         break;
370                 case IOMMU_DOMAIN_UNMANAGED:
371                         type = "unmanaged\n";
372                         break;
373                 case IOMMU_DOMAIN_DMA:
374                         type = "DMA";
375                         break;
376                 }
377         }
378         strcpy(buf, type);
379
380         return strlen(type);
381 }
382
383 static IOMMU_GROUP_ATTR(name, S_IRUGO, iommu_group_show_name, NULL);
384
385 static IOMMU_GROUP_ATTR(reserved_regions, 0444,
386                         iommu_group_show_resv_regions, NULL);
387
388 static IOMMU_GROUP_ATTR(type, 0444, iommu_group_show_type, NULL);
389
390 static void iommu_group_release(struct kobject *kobj)
391 {
392         struct iommu_group *group = to_iommu_group(kobj);
393
394         pr_debug("Releasing group %d\n", group->id);
395
396         if (group->iommu_data_release)
397                 group->iommu_data_release(group->iommu_data);
398
399         ida_simple_remove(&iommu_group_ida, group->id);
400
401         if (group->default_domain)
402                 iommu_domain_free(group->default_domain);
403
404         kfree(group->name);
405         kfree(group);
406 }
407
408 static struct kobj_type iommu_group_ktype = {
409         .sysfs_ops = &iommu_group_sysfs_ops,
410         .release = iommu_group_release,
411 };
412
413 /**
414  * iommu_group_alloc - Allocate a new group
415  *
416  * This function is called by an iommu driver to allocate a new iommu
417  * group.  The iommu group represents the minimum granularity of the iommu.
418  * Upon successful return, the caller holds a reference to the supplied
419  * group in order to hold the group until devices are added.  Use
420  * iommu_group_put() to release this extra reference count, allowing the
421  * group to be automatically reclaimed once it has no devices or external
422  * references.
423  */
424 struct iommu_group *iommu_group_alloc(void)
425 {
426         struct iommu_group *group;
427         int ret;
428
429         group = kzalloc(sizeof(*group), GFP_KERNEL);
430         if (!group)
431                 return ERR_PTR(-ENOMEM);
432
433         group->kobj.kset = iommu_group_kset;
434         mutex_init(&group->mutex);
435         INIT_LIST_HEAD(&group->devices);
436         BLOCKING_INIT_NOTIFIER_HEAD(&group->notifier);
437
438         ret = ida_simple_get(&iommu_group_ida, 0, 0, GFP_KERNEL);
439         if (ret < 0) {
440                 kfree(group);
441                 return ERR_PTR(ret);
442         }
443         group->id = ret;
444
445         ret = kobject_init_and_add(&group->kobj, &iommu_group_ktype,
446                                    NULL, "%d", group->id);
447         if (ret) {
448                 ida_simple_remove(&iommu_group_ida, group->id);
449                 kfree(group);
450                 return ERR_PTR(ret);
451         }
452
453         group->devices_kobj = kobject_create_and_add("devices", &group->kobj);
454         if (!group->devices_kobj) {
455                 kobject_put(&group->kobj); /* triggers .release & free */
456                 return ERR_PTR(-ENOMEM);
457         }
458
459         /*
460          * The devices_kobj holds a reference on the group kobject, so
461          * as long as that exists so will the group.  We can therefore
462          * use the devices_kobj for reference counting.
463          */
464         kobject_put(&group->kobj);
465
466         ret = iommu_group_create_file(group,
467                                       &iommu_group_attr_reserved_regions);
468         if (ret)
469                 return ERR_PTR(ret);
470
471         ret = iommu_group_create_file(group, &iommu_group_attr_type);
472         if (ret)
473                 return ERR_PTR(ret);
474
475         pr_debug("Allocated group %d\n", group->id);
476
477         return group;
478 }
479 EXPORT_SYMBOL_GPL(iommu_group_alloc);
480
481 struct iommu_group *iommu_group_get_by_id(int id)
482 {
483         struct kobject *group_kobj;
484         struct iommu_group *group;
485         const char *name;
486
487         if (!iommu_group_kset)
488                 return NULL;
489
490         name = kasprintf(GFP_KERNEL, "%d", id);
491         if (!name)
492                 return NULL;
493
494         group_kobj = kset_find_obj(iommu_group_kset, name);
495         kfree(name);
496
497         if (!group_kobj)
498                 return NULL;
499
500         group = container_of(group_kobj, struct iommu_group, kobj);
501         BUG_ON(group->id != id);
502
503         kobject_get(group->devices_kobj);
504         kobject_put(&group->kobj);
505
506         return group;
507 }
508 EXPORT_SYMBOL_GPL(iommu_group_get_by_id);
509
510 /**
511  * iommu_group_get_iommudata - retrieve iommu_data registered for a group
512  * @group: the group
513  *
514  * iommu drivers can store data in the group for use when doing iommu
515  * operations.  This function provides a way to retrieve it.  Caller
516  * should hold a group reference.
517  */
518 void *iommu_group_get_iommudata(struct iommu_group *group)
519 {
520         return group->iommu_data;
521 }
522 EXPORT_SYMBOL_GPL(iommu_group_get_iommudata);
523
524 /**
525  * iommu_group_set_iommudata - set iommu_data for a group
526  * @group: the group
527  * @iommu_data: new data
528  * @release: release function for iommu_data
529  *
530  * iommu drivers can store data in the group for use when doing iommu
531  * operations.  This function provides a way to set the data after
532  * the group has been allocated.  Caller should hold a group reference.
533  */
534 void iommu_group_set_iommudata(struct iommu_group *group, void *iommu_data,
535                                void (*release)(void *iommu_data))
536 {
537         group->iommu_data = iommu_data;
538         group->iommu_data_release = release;
539 }
540 EXPORT_SYMBOL_GPL(iommu_group_set_iommudata);
541
542 /**
543  * iommu_group_set_name - set name for a group
544  * @group: the group
545  * @name: name
546  *
547  * Allow iommu driver to set a name for a group.  When set it will
548  * appear in a name attribute file under the group in sysfs.
549  */
550 int iommu_group_set_name(struct iommu_group *group, const char *name)
551 {
552         int ret;
553
554         if (group->name) {
555                 iommu_group_remove_file(group, &iommu_group_attr_name);
556                 kfree(group->name);
557                 group->name = NULL;
558                 if (!name)
559                         return 0;
560         }
561
562         group->name = kstrdup(name, GFP_KERNEL);
563         if (!group->name)
564                 return -ENOMEM;
565
566         ret = iommu_group_create_file(group, &iommu_group_attr_name);
567         if (ret) {
568                 kfree(group->name);
569                 group->name = NULL;
570                 return ret;
571         }
572
573         return 0;
574 }
575 EXPORT_SYMBOL_GPL(iommu_group_set_name);
576
577 static int iommu_group_create_direct_mappings(struct iommu_group *group,
578                                               struct device *dev)
579 {
580         struct iommu_domain *domain = group->default_domain;
581         struct iommu_resv_region *entry;
582         struct list_head mappings;
583         unsigned long pg_size;
584         int ret = 0;
585
586         if (!domain || domain->type != IOMMU_DOMAIN_DMA)
587                 return 0;
588
589         BUG_ON(!domain->pgsize_bitmap);
590
591         pg_size = 1UL << __ffs(domain->pgsize_bitmap);
592         INIT_LIST_HEAD(&mappings);
593
594         iommu_get_resv_regions(dev, &mappings);
595
596         /* We need to consider overlapping regions for different devices */
597         list_for_each_entry(entry, &mappings, list) {
598                 dma_addr_t start, end, addr;
599
600                 if (domain->ops->apply_resv_region)
601                         domain->ops->apply_resv_region(dev, domain, entry);
602
603                 start = ALIGN(entry->start, pg_size);
604                 end   = ALIGN(entry->start + entry->length, pg_size);
605
606                 if (entry->type != IOMMU_RESV_DIRECT)
607                         continue;
608
609                 for (addr = start; addr < end; addr += pg_size) {
610                         phys_addr_t phys_addr;
611
612                         phys_addr = iommu_iova_to_phys(domain, addr);
613                         if (phys_addr)
614                                 continue;
615
616                         ret = iommu_map(domain, addr, addr, pg_size, entry->prot);
617                         if (ret)
618                                 goto out;
619                 }
620
621         }
622
623         iommu_flush_tlb_all(domain);
624
625 out:
626         iommu_put_resv_regions(dev, &mappings);
627
628         return ret;
629 }
630
631 /**
632  * iommu_group_add_device - add a device to an iommu group
633  * @group: the group into which to add the device (reference should be held)
634  * @dev: the device
635  *
636  * This function is called by an iommu driver to add a device into a
637  * group.  Adding a device increments the group reference count.
638  */
639 int iommu_group_add_device(struct iommu_group *group, struct device *dev)
640 {
641         int ret, i = 0;
642         struct group_device *device;
643
644         device = kzalloc(sizeof(*device), GFP_KERNEL);
645         if (!device)
646                 return -ENOMEM;
647
648         device->dev = dev;
649
650         ret = sysfs_create_link(&dev->kobj, &group->kobj, "iommu_group");
651         if (ret)
652                 goto err_free_device;
653
654         device->name = kasprintf(GFP_KERNEL, "%s", kobject_name(&dev->kobj));
655 rename:
656         if (!device->name) {
657                 ret = -ENOMEM;
658                 goto err_remove_link;
659         }
660
661         ret = sysfs_create_link_nowarn(group->devices_kobj,
662                                        &dev->kobj, device->name);
663         if (ret) {
664                 if (ret == -EEXIST && i >= 0) {
665                         /*
666                          * Account for the slim chance of collision
667                          * and append an instance to the name.
668                          */
669                         kfree(device->name);
670                         device->name = kasprintf(GFP_KERNEL, "%s.%d",
671                                                  kobject_name(&dev->kobj), i++);
672                         goto rename;
673                 }
674                 goto err_free_name;
675         }
676
677         kobject_get(group->devices_kobj);
678
679         dev->iommu_group = group;
680
681         iommu_group_create_direct_mappings(group, dev);
682
683         mutex_lock(&group->mutex);
684         list_add_tail(&device->list, &group->devices);
685         if (group->domain)
686                 ret = __iommu_attach_device(group->domain, dev);
687         mutex_unlock(&group->mutex);
688         if (ret)
689                 goto err_put_group;
690
691         /* Notify any listeners about change to group. */
692         blocking_notifier_call_chain(&group->notifier,
693                                      IOMMU_GROUP_NOTIFY_ADD_DEVICE, dev);
694
695         trace_add_device_to_group(group->id, dev);
696
697         dev_info(dev, "Adding to iommu group %d\n", group->id);
698
699         return 0;
700
701 err_put_group:
702         mutex_lock(&group->mutex);
703         list_del(&device->list);
704         mutex_unlock(&group->mutex);
705         dev->iommu_group = NULL;
706         kobject_put(group->devices_kobj);
707 err_free_name:
708         kfree(device->name);
709 err_remove_link:
710         sysfs_remove_link(&dev->kobj, "iommu_group");
711 err_free_device:
712         kfree(device);
713         dev_err(dev, "Failed to add to iommu group %d: %d\n", group->id, ret);
714         return ret;
715 }
716 EXPORT_SYMBOL_GPL(iommu_group_add_device);
717
718 /**
719  * iommu_group_remove_device - remove a device from it's current group
720  * @dev: device to be removed
721  *
722  * This function is called by an iommu driver to remove the device from
723  * it's current group.  This decrements the iommu group reference count.
724  */
725 void iommu_group_remove_device(struct device *dev)
726 {
727         struct iommu_group *group = dev->iommu_group;
728         struct group_device *tmp_device, *device = NULL;
729
730         dev_info(dev, "Removing from iommu group %d\n", group->id);
731
732         /* Pre-notify listeners that a device is being removed. */
733         blocking_notifier_call_chain(&group->notifier,
734                                      IOMMU_GROUP_NOTIFY_DEL_DEVICE, dev);
735
736         mutex_lock(&group->mutex);
737         list_for_each_entry(tmp_device, &group->devices, list) {
738                 if (tmp_device->dev == dev) {
739                         device = tmp_device;
740                         list_del(&device->list);
741                         break;
742                 }
743         }
744         mutex_unlock(&group->mutex);
745
746         if (!device)
747                 return;
748
749         sysfs_remove_link(group->devices_kobj, device->name);
750         sysfs_remove_link(&dev->kobj, "iommu_group");
751
752         trace_remove_device_from_group(group->id, dev);
753
754         kfree(device->name);
755         kfree(device);
756         dev->iommu_group = NULL;
757         kobject_put(group->devices_kobj);
758 }
759 EXPORT_SYMBOL_GPL(iommu_group_remove_device);
760
761 static int iommu_group_device_count(struct iommu_group *group)
762 {
763         struct group_device *entry;
764         int ret = 0;
765
766         list_for_each_entry(entry, &group->devices, list)
767                 ret++;
768
769         return ret;
770 }
771
772 /**
773  * iommu_group_for_each_dev - iterate over each device in the group
774  * @group: the group
775  * @data: caller opaque data to be passed to callback function
776  * @fn: caller supplied callback function
777  *
778  * This function is called by group users to iterate over group devices.
779  * Callers should hold a reference count to the group during callback.
780  * The group->mutex is held across callbacks, which will block calls to
781  * iommu_group_add/remove_device.
782  */
783 static int __iommu_group_for_each_dev(struct iommu_group *group, void *data,
784                                       int (*fn)(struct device *, void *))
785 {
786         struct group_device *device;
787         int ret = 0;
788
789         list_for_each_entry(device, &group->devices, list) {
790                 ret = fn(device->dev, data);
791                 if (ret)
792                         break;
793         }
794         return ret;
795 }
796
797
798 int iommu_group_for_each_dev(struct iommu_group *group, void *data,
799                              int (*fn)(struct device *, void *))
800 {
801         int ret;
802
803         mutex_lock(&group->mutex);
804         ret = __iommu_group_for_each_dev(group, data, fn);
805         mutex_unlock(&group->mutex);
806
807         return ret;
808 }
809 EXPORT_SYMBOL_GPL(iommu_group_for_each_dev);
810
811 /**
812  * iommu_group_get - Return the group for a device and increment reference
813  * @dev: get the group that this device belongs to
814  *
815  * This function is called by iommu drivers and users to get the group
816  * for the specified device.  If found, the group is returned and the group
817  * reference in incremented, else NULL.
818  */
819 struct iommu_group *iommu_group_get(struct device *dev)
820 {
821         struct iommu_group *group = dev->iommu_group;
822
823         if (group)
824                 kobject_get(group->devices_kobj);
825
826         return group;
827 }
828 EXPORT_SYMBOL_GPL(iommu_group_get);
829
830 /**
831  * iommu_group_ref_get - Increment reference on a group
832  * @group: the group to use, must not be NULL
833  *
834  * This function is called by iommu drivers to take additional references on an
835  * existing group.  Returns the given group for convenience.
836  */
837 struct iommu_group *iommu_group_ref_get(struct iommu_group *group)
838 {
839         kobject_get(group->devices_kobj);
840         return group;
841 }
842
843 /**
844  * iommu_group_put - Decrement group reference
845  * @group: the group to use
846  *
847  * This function is called by iommu drivers and users to release the
848  * iommu group.  Once the reference count is zero, the group is released.
849  */
850 void iommu_group_put(struct iommu_group *group)
851 {
852         if (group)
853                 kobject_put(group->devices_kobj);
854 }
855 EXPORT_SYMBOL_GPL(iommu_group_put);
856
857 /**
858  * iommu_group_register_notifier - Register a notifier for group changes
859  * @group: the group to watch
860  * @nb: notifier block to signal
861  *
862  * This function allows iommu group users to track changes in a group.
863  * See include/linux/iommu.h for actions sent via this notifier.  Caller
864  * should hold a reference to the group throughout notifier registration.
865  */
866 int iommu_group_register_notifier(struct iommu_group *group,
867                                   struct notifier_block *nb)
868 {
869         return blocking_notifier_chain_register(&group->notifier, nb);
870 }
871 EXPORT_SYMBOL_GPL(iommu_group_register_notifier);
872
873 /**
874  * iommu_group_unregister_notifier - Unregister a notifier
875  * @group: the group to watch
876  * @nb: notifier block to signal
877  *
878  * Unregister a previously registered group notifier block.
879  */
880 int iommu_group_unregister_notifier(struct iommu_group *group,
881                                     struct notifier_block *nb)
882 {
883         return blocking_notifier_chain_unregister(&group->notifier, nb);
884 }
885 EXPORT_SYMBOL_GPL(iommu_group_unregister_notifier);
886
887 /**
888  * iommu_register_device_fault_handler() - Register a device fault handler
889  * @dev: the device
890  * @handler: the fault handler
891  * @data: private data passed as argument to the handler
892  *
893  * When an IOMMU fault event is received, this handler gets called with the
894  * fault event and data as argument. The handler should return 0 on success. If
895  * the fault is recoverable (IOMMU_FAULT_PAGE_REQ), the consumer should also
896  * complete the fault by calling iommu_page_response() with one of the following
897  * response code:
898  * - IOMMU_PAGE_RESP_SUCCESS: retry the translation
899  * - IOMMU_PAGE_RESP_INVALID: terminate the fault
900  * - IOMMU_PAGE_RESP_FAILURE: terminate the fault and stop reporting
901  *   page faults if possible.
902  *
903  * Return 0 if the fault handler was installed successfully, or an error.
904  */
905 int iommu_register_device_fault_handler(struct device *dev,
906                                         iommu_dev_fault_handler_t handler,
907                                         void *data)
908 {
909         struct iommu_param *param = dev->iommu_param;
910         int ret = 0;
911
912         if (!param)
913                 return -EINVAL;
914
915         mutex_lock(&param->lock);
916         /* Only allow one fault handler registered for each device */
917         if (param->fault_param) {
918                 ret = -EBUSY;
919                 goto done_unlock;
920         }
921
922         get_device(dev);
923         param->fault_param = kzalloc(sizeof(*param->fault_param), GFP_KERNEL);
924         if (!param->fault_param) {
925                 put_device(dev);
926                 ret = -ENOMEM;
927                 goto done_unlock;
928         }
929         param->fault_param->handler = handler;
930         param->fault_param->data = data;
931         mutex_init(&param->fault_param->lock);
932         INIT_LIST_HEAD(&param->fault_param->faults);
933
934 done_unlock:
935         mutex_unlock(&param->lock);
936
937         return ret;
938 }
939 EXPORT_SYMBOL_GPL(iommu_register_device_fault_handler);
940
941 /**
942  * iommu_unregister_device_fault_handler() - Unregister the device fault handler
943  * @dev: the device
944  *
945  * Remove the device fault handler installed with
946  * iommu_register_device_fault_handler().
947  *
948  * Return 0 on success, or an error.
949  */
950 int iommu_unregister_device_fault_handler(struct device *dev)
951 {
952         struct iommu_param *param = dev->iommu_param;
953         int ret = 0;
954
955         if (!param)
956                 return -EINVAL;
957
958         mutex_lock(&param->lock);
959
960         if (!param->fault_param)
961                 goto unlock;
962
963         /* we cannot unregister handler if there are pending faults */
964         if (!list_empty(&param->fault_param->faults)) {
965                 ret = -EBUSY;
966                 goto unlock;
967         }
968
969         kfree(param->fault_param);
970         param->fault_param = NULL;
971         put_device(dev);
972 unlock:
973         mutex_unlock(&param->lock);
974
975         return ret;
976 }
977 EXPORT_SYMBOL_GPL(iommu_unregister_device_fault_handler);
978
979 /**
980  * iommu_report_device_fault() - Report fault event to device driver
981  * @dev: the device
982  * @evt: fault event data
983  *
984  * Called by IOMMU drivers when a fault is detected, typically in a threaded IRQ
985  * handler. When this function fails and the fault is recoverable, it is the
986  * caller's responsibility to complete the fault.
987  *
988  * Return 0 on success, or an error.
989  */
990 int iommu_report_device_fault(struct device *dev, struct iommu_fault_event *evt)
991 {
992         struct iommu_param *param = dev->iommu_param;
993         struct iommu_fault_event *evt_pending = NULL;
994         struct iommu_fault_param *fparam;
995         int ret = 0;
996
997         if (!param || !evt)
998                 return -EINVAL;
999
1000         /* we only report device fault if there is a handler registered */
1001         mutex_lock(&param->lock);
1002         fparam = param->fault_param;
1003         if (!fparam || !fparam->handler) {
1004                 ret = -EINVAL;
1005                 goto done_unlock;
1006         }
1007
1008         if (evt->fault.type == IOMMU_FAULT_PAGE_REQ &&
1009             (evt->fault.prm.flags & IOMMU_FAULT_PAGE_REQUEST_LAST_PAGE)) {
1010                 evt_pending = kmemdup(evt, sizeof(struct iommu_fault_event),
1011                                       GFP_KERNEL);
1012                 if (!evt_pending) {
1013                         ret = -ENOMEM;
1014                         goto done_unlock;
1015                 }
1016                 mutex_lock(&fparam->lock);
1017                 list_add_tail(&evt_pending->list, &fparam->faults);
1018                 mutex_unlock(&fparam->lock);
1019         }
1020
1021         ret = fparam->handler(&evt->fault, fparam->data);
1022         if (ret && evt_pending) {
1023                 mutex_lock(&fparam->lock);
1024                 list_del(&evt_pending->list);
1025                 mutex_unlock(&fparam->lock);
1026                 kfree(evt_pending);
1027         }
1028 done_unlock:
1029         mutex_unlock(&param->lock);
1030         return ret;
1031 }
1032 EXPORT_SYMBOL_GPL(iommu_report_device_fault);
1033
1034 int iommu_page_response(struct device *dev,
1035                         struct iommu_page_response *msg)
1036 {
1037         bool pasid_valid;
1038         int ret = -EINVAL;
1039         struct iommu_fault_event *evt;
1040         struct iommu_fault_page_request *prm;
1041         struct iommu_param *param = dev->iommu_param;
1042         struct iommu_domain *domain = iommu_get_domain_for_dev(dev);
1043
1044         if (!domain || !domain->ops->page_response)
1045                 return -ENODEV;
1046
1047         if (!param || !param->fault_param)
1048                 return -EINVAL;
1049
1050         if (msg->version != IOMMU_PAGE_RESP_VERSION_1 ||
1051             msg->flags & ~IOMMU_PAGE_RESP_PASID_VALID)
1052                 return -EINVAL;
1053
1054         /* Only send response if there is a fault report pending */
1055         mutex_lock(&param->fault_param->lock);
1056         if (list_empty(&param->fault_param->faults)) {
1057                 dev_warn_ratelimited(dev, "no pending PRQ, drop response\n");
1058                 goto done_unlock;
1059         }
1060         /*
1061          * Check if we have a matching page request pending to respond,
1062          * otherwise return -EINVAL
1063          */
1064         list_for_each_entry(evt, &param->fault_param->faults, list) {
1065                 prm = &evt->fault.prm;
1066                 pasid_valid = prm->flags & IOMMU_FAULT_PAGE_REQUEST_PASID_VALID;
1067
1068                 if ((pasid_valid && prm->pasid != msg->pasid) ||
1069                     prm->grpid != msg->grpid)
1070                         continue;
1071
1072                 /* Sanitize the reply */
1073                 msg->flags = pasid_valid ? IOMMU_PAGE_RESP_PASID_VALID : 0;
1074
1075                 ret = domain->ops->page_response(dev, evt, msg);
1076                 list_del(&evt->list);
1077                 kfree(evt);
1078                 break;
1079         }
1080
1081 done_unlock:
1082         mutex_unlock(&param->fault_param->lock);
1083         return ret;
1084 }
1085 EXPORT_SYMBOL_GPL(iommu_page_response);
1086
1087 /**
1088  * iommu_group_id - Return ID for a group
1089  * @group: the group to ID
1090  *
1091  * Return the unique ID for the group matching the sysfs group number.
1092  */
1093 int iommu_group_id(struct iommu_group *group)
1094 {
1095         return group->id;
1096 }
1097 EXPORT_SYMBOL_GPL(iommu_group_id);
1098
1099 static struct iommu_group *get_pci_alias_group(struct pci_dev *pdev,
1100                                                unsigned long *devfns);
1101
1102 /*
1103  * To consider a PCI device isolated, we require ACS to support Source
1104  * Validation, Request Redirection, Completer Redirection, and Upstream
1105  * Forwarding.  This effectively means that devices cannot spoof their
1106  * requester ID, requests and completions cannot be redirected, and all
1107  * transactions are forwarded upstream, even as it passes through a
1108  * bridge where the target device is downstream.
1109  */
1110 #define REQ_ACS_FLAGS   (PCI_ACS_SV | PCI_ACS_RR | PCI_ACS_CR | PCI_ACS_UF)
1111
1112 /*
1113  * For multifunction devices which are not isolated from each other, find
1114  * all the other non-isolated functions and look for existing groups.  For
1115  * each function, we also need to look for aliases to or from other devices
1116  * that may already have a group.
1117  */
1118 static struct iommu_group *get_pci_function_alias_group(struct pci_dev *pdev,
1119                                                         unsigned long *devfns)
1120 {
1121         struct pci_dev *tmp = NULL;
1122         struct iommu_group *group;
1123
1124         if (!pdev->multifunction || pci_acs_enabled(pdev, REQ_ACS_FLAGS))
1125                 return NULL;
1126
1127         for_each_pci_dev(tmp) {
1128                 if (tmp == pdev || tmp->bus != pdev->bus ||
1129                     PCI_SLOT(tmp->devfn) != PCI_SLOT(pdev->devfn) ||
1130                     pci_acs_enabled(tmp, REQ_ACS_FLAGS))
1131                         continue;
1132
1133                 group = get_pci_alias_group(tmp, devfns);
1134                 if (group) {
1135                         pci_dev_put(tmp);
1136                         return group;
1137                 }
1138         }
1139
1140         return NULL;
1141 }
1142
1143 /*
1144  * Look for aliases to or from the given device for existing groups. DMA
1145  * aliases are only supported on the same bus, therefore the search
1146  * space is quite small (especially since we're really only looking at pcie
1147  * device, and therefore only expect multiple slots on the root complex or
1148  * downstream switch ports).  It's conceivable though that a pair of
1149  * multifunction devices could have aliases between them that would cause a
1150  * loop.  To prevent this, we use a bitmap to track where we've been.
1151  */
1152 static struct iommu_group *get_pci_alias_group(struct pci_dev *pdev,
1153                                                unsigned long *devfns)
1154 {
1155         struct pci_dev *tmp = NULL;
1156         struct iommu_group *group;
1157
1158         if (test_and_set_bit(pdev->devfn & 0xff, devfns))
1159                 return NULL;
1160
1161         group = iommu_group_get(&pdev->dev);
1162         if (group)
1163                 return group;
1164
1165         for_each_pci_dev(tmp) {
1166                 if (tmp == pdev || tmp->bus != pdev->bus)
1167                         continue;
1168
1169                 /* We alias them or they alias us */
1170                 if (pci_devs_are_dma_aliases(pdev, tmp)) {
1171                         group = get_pci_alias_group(tmp, devfns);
1172                         if (group) {
1173                                 pci_dev_put(tmp);
1174                                 return group;
1175                         }
1176
1177                         group = get_pci_function_alias_group(tmp, devfns);
1178                         if (group) {
1179                                 pci_dev_put(tmp);
1180                                 return group;
1181                         }
1182                 }
1183         }
1184
1185         return NULL;
1186 }
1187
1188 struct group_for_pci_data {
1189         struct pci_dev *pdev;
1190         struct iommu_group *group;
1191 };
1192
1193 /*
1194  * DMA alias iterator callback, return the last seen device.  Stop and return
1195  * the IOMMU group if we find one along the way.
1196  */
1197 static int get_pci_alias_or_group(struct pci_dev *pdev, u16 alias, void *opaque)
1198 {
1199         struct group_for_pci_data *data = opaque;
1200
1201         data->pdev = pdev;
1202         data->group = iommu_group_get(&pdev->dev);
1203
1204         return data->group != NULL;
1205 }
1206
1207 /*
1208  * Generic device_group call-back function. It just allocates one
1209  * iommu-group per device.
1210  */
1211 struct iommu_group *generic_device_group(struct device *dev)
1212 {
1213         return iommu_group_alloc();
1214 }
1215
1216 /*
1217  * Use standard PCI bus topology, isolation features, and DMA alias quirks
1218  * to find or create an IOMMU group for a device.
1219  */
1220 struct iommu_group *pci_device_group(struct device *dev)
1221 {
1222         struct pci_dev *pdev = to_pci_dev(dev);
1223         struct group_for_pci_data data;
1224         struct pci_bus *bus;
1225         struct iommu_group *group = NULL;
1226         u64 devfns[4] = { 0 };
1227
1228         if (WARN_ON(!dev_is_pci(dev)))
1229                 return ERR_PTR(-EINVAL);
1230
1231         /*
1232          * Find the upstream DMA alias for the device.  A device must not
1233          * be aliased due to topology in order to have its own IOMMU group.
1234          * If we find an alias along the way that already belongs to a
1235          * group, use it.
1236          */
1237         if (pci_for_each_dma_alias(pdev, get_pci_alias_or_group, &data))
1238                 return data.group;
1239
1240         pdev = data.pdev;
1241
1242         /*
1243          * Continue upstream from the point of minimum IOMMU granularity
1244          * due to aliases to the point where devices are protected from
1245          * peer-to-peer DMA by PCI ACS.  Again, if we find an existing
1246          * group, use it.
1247          */
1248         for (bus = pdev->bus; !pci_is_root_bus(bus); bus = bus->parent) {
1249                 if (!bus->self)
1250                         continue;
1251
1252                 if (pci_acs_path_enabled(bus->self, NULL, REQ_ACS_FLAGS))
1253                         break;
1254
1255                 pdev = bus->self;
1256
1257                 group = iommu_group_get(&pdev->dev);
1258                 if (group)
1259                         return group;
1260         }
1261
1262         /*
1263          * Look for existing groups on device aliases.  If we alias another
1264          * device or another device aliases us, use the same group.
1265          */
1266         group = get_pci_alias_group(pdev, (unsigned long *)devfns);
1267         if (group)
1268                 return group;
1269
1270         /*
1271          * Look for existing groups on non-isolated functions on the same
1272          * slot and aliases of those funcions, if any.  No need to clear
1273          * the search bitmap, the tested devfns are still valid.
1274          */
1275         group = get_pci_function_alias_group(pdev, (unsigned long *)devfns);
1276         if (group)
1277                 return group;
1278
1279         /* No shared group found, allocate new */
1280         return iommu_group_alloc();
1281 }
1282
1283 /* Get the IOMMU group for device on fsl-mc bus */
1284 struct iommu_group *fsl_mc_device_group(struct device *dev)
1285 {
1286         struct device *cont_dev = fsl_mc_cont_dev(dev);
1287         struct iommu_group *group;
1288
1289         group = iommu_group_get(cont_dev);
1290         if (!group)
1291                 group = iommu_group_alloc();
1292         return group;
1293 }
1294
1295 /**
1296  * iommu_group_get_for_dev - Find or create the IOMMU group for a device
1297  * @dev: target device
1298  *
1299  * This function is intended to be called by IOMMU drivers and extended to
1300  * support common, bus-defined algorithms when determining or creating the
1301  * IOMMU group for a device.  On success, the caller will hold a reference
1302  * to the returned IOMMU group, which will already include the provided
1303  * device.  The reference should be released with iommu_group_put().
1304  */
1305 struct iommu_group *iommu_group_get_for_dev(struct device *dev)
1306 {
1307         const struct iommu_ops *ops = dev->bus->iommu_ops;
1308         struct iommu_group *group;
1309         int ret;
1310
1311         group = iommu_group_get(dev);
1312         if (group)
1313                 return group;
1314
1315         if (!ops)
1316                 return ERR_PTR(-EINVAL);
1317
1318         group = ops->device_group(dev);
1319         if (WARN_ON_ONCE(group == NULL))
1320                 return ERR_PTR(-EINVAL);
1321
1322         if (IS_ERR(group))
1323                 return group;
1324
1325         /*
1326          * Try to allocate a default domain - needs support from the
1327          * IOMMU driver.
1328          */
1329         if (!group->default_domain) {
1330                 struct iommu_domain *dom;
1331
1332                 dom = __iommu_domain_alloc(dev->bus, iommu_def_domain_type);
1333                 if (!dom && iommu_def_domain_type != IOMMU_DOMAIN_DMA) {
1334                         dom = __iommu_domain_alloc(dev->bus, IOMMU_DOMAIN_DMA);
1335                         if (dom) {
1336                                 dev_warn(dev,
1337                                          "failed to allocate default IOMMU domain of type %u; falling back to IOMMU_DOMAIN_DMA",
1338                                          iommu_def_domain_type);
1339                         }
1340                 }
1341
1342                 group->default_domain = dom;
1343                 if (!group->domain)
1344                         group->domain = dom;
1345
1346                 if (dom && !iommu_dma_strict) {
1347                         int attr = 1;
1348                         iommu_domain_set_attr(dom,
1349                                               DOMAIN_ATTR_DMA_USE_FLUSH_QUEUE,
1350                                               &attr);
1351                 }
1352         }
1353
1354         ret = iommu_group_add_device(group, dev);
1355         if (ret) {
1356                 iommu_group_put(group);
1357                 return ERR_PTR(ret);
1358         }
1359
1360         return group;
1361 }
1362
1363 struct iommu_domain *iommu_group_default_domain(struct iommu_group *group)
1364 {
1365         return group->default_domain;
1366 }
1367
1368 static int add_iommu_group(struct device *dev, void *data)
1369 {
1370         int ret = iommu_probe_device(dev);
1371
1372         /*
1373          * We ignore -ENODEV errors for now, as they just mean that the
1374          * device is not translated by an IOMMU. We still care about
1375          * other errors and fail to initialize when they happen.
1376          */
1377         if (ret == -ENODEV)
1378                 ret = 0;
1379
1380         return ret;
1381 }
1382
1383 static int remove_iommu_group(struct device *dev, void *data)
1384 {
1385         iommu_release_device(dev);
1386
1387         return 0;
1388 }
1389
1390 static int iommu_bus_notifier(struct notifier_block *nb,
1391                               unsigned long action, void *data)
1392 {
1393         unsigned long group_action = 0;
1394         struct device *dev = data;
1395         struct iommu_group *group;
1396
1397         /*
1398          * ADD/DEL call into iommu driver ops if provided, which may
1399          * result in ADD/DEL notifiers to group->notifier
1400          */
1401         if (action == BUS_NOTIFY_ADD_DEVICE) {
1402                 int ret;
1403
1404                 ret = iommu_probe_device(dev);
1405                 return (ret) ? NOTIFY_DONE : NOTIFY_OK;
1406         } else if (action == BUS_NOTIFY_REMOVED_DEVICE) {
1407                 iommu_release_device(dev);
1408                 return NOTIFY_OK;
1409         }
1410
1411         /*
1412          * Remaining BUS_NOTIFYs get filtered and republished to the
1413          * group, if anyone is listening
1414          */
1415         group = iommu_group_get(dev);
1416         if (!group)
1417                 return 0;
1418
1419         switch (action) {
1420         case BUS_NOTIFY_BIND_DRIVER:
1421                 group_action = IOMMU_GROUP_NOTIFY_BIND_DRIVER;
1422                 break;
1423         case BUS_NOTIFY_BOUND_DRIVER:
1424                 group_action = IOMMU_GROUP_NOTIFY_BOUND_DRIVER;
1425                 break;
1426         case BUS_NOTIFY_UNBIND_DRIVER:
1427                 group_action = IOMMU_GROUP_NOTIFY_UNBIND_DRIVER;
1428                 break;
1429         case BUS_NOTIFY_UNBOUND_DRIVER:
1430                 group_action = IOMMU_GROUP_NOTIFY_UNBOUND_DRIVER;
1431                 break;
1432         }
1433
1434         if (group_action)
1435                 blocking_notifier_call_chain(&group->notifier,
1436                                              group_action, dev);
1437
1438         iommu_group_put(group);
1439         return 0;
1440 }
1441
1442 static int iommu_bus_init(struct bus_type *bus, const struct iommu_ops *ops)
1443 {
1444         int err;
1445         struct notifier_block *nb;
1446
1447         nb = kzalloc(sizeof(struct notifier_block), GFP_KERNEL);
1448         if (!nb)
1449                 return -ENOMEM;
1450
1451         nb->notifier_call = iommu_bus_notifier;
1452
1453         err = bus_register_notifier(bus, nb);
1454         if (err)
1455                 goto out_free;
1456
1457         err = bus_for_each_dev(bus, NULL, NULL, add_iommu_group);
1458         if (err)
1459                 goto out_err;
1460
1461
1462         return 0;
1463
1464 out_err:
1465         /* Clean up */
1466         bus_for_each_dev(bus, NULL, NULL, remove_iommu_group);
1467         bus_unregister_notifier(bus, nb);
1468
1469 out_free:
1470         kfree(nb);
1471
1472         return err;
1473 }
1474
1475 /**
1476  * bus_set_iommu - set iommu-callbacks for the bus
1477  * @bus: bus.
1478  * @ops: the callbacks provided by the iommu-driver
1479  *
1480  * This function is called by an iommu driver to set the iommu methods
1481  * used for a particular bus. Drivers for devices on that bus can use
1482  * the iommu-api after these ops are registered.
1483  * This special function is needed because IOMMUs are usually devices on
1484  * the bus itself, so the iommu drivers are not initialized when the bus
1485  * is set up. With this function the iommu-driver can set the iommu-ops
1486  * afterwards.
1487  */
1488 int bus_set_iommu(struct bus_type *bus, const struct iommu_ops *ops)
1489 {
1490         int err;
1491
1492         if (bus->iommu_ops != NULL)
1493                 return -EBUSY;
1494
1495         bus->iommu_ops = ops;
1496
1497         /* Do IOMMU specific setup for this bus-type */
1498         err = iommu_bus_init(bus, ops);
1499         if (err)
1500                 bus->iommu_ops = NULL;
1501
1502         return err;
1503 }
1504 EXPORT_SYMBOL_GPL(bus_set_iommu);
1505
1506 bool iommu_present(struct bus_type *bus)
1507 {
1508         return bus->iommu_ops != NULL;
1509 }
1510 EXPORT_SYMBOL_GPL(iommu_present);
1511
1512 bool iommu_capable(struct bus_type *bus, enum iommu_cap cap)
1513 {
1514         if (!bus->iommu_ops || !bus->iommu_ops->capable)
1515                 return false;
1516
1517         return bus->iommu_ops->capable(cap);
1518 }
1519 EXPORT_SYMBOL_GPL(iommu_capable);
1520
1521 /**
1522  * iommu_set_fault_handler() - set a fault handler for an iommu domain
1523  * @domain: iommu domain
1524  * @handler: fault handler
1525  * @token: user data, will be passed back to the fault handler
1526  *
1527  * This function should be used by IOMMU users which want to be notified
1528  * whenever an IOMMU fault happens.
1529  *
1530  * The fault handler itself should return 0 on success, and an appropriate
1531  * error code otherwise.
1532  */
1533 void iommu_set_fault_handler(struct iommu_domain *domain,
1534                                         iommu_fault_handler_t handler,
1535                                         void *token)
1536 {
1537         BUG_ON(!domain);
1538
1539         domain->handler = handler;
1540         domain->handler_token = token;
1541 }
1542 EXPORT_SYMBOL_GPL(iommu_set_fault_handler);
1543
1544 static struct iommu_domain *__iommu_domain_alloc(struct bus_type *bus,
1545                                                  unsigned type)
1546 {
1547         struct iommu_domain *domain;
1548
1549         if (bus == NULL || bus->iommu_ops == NULL)
1550                 return NULL;
1551
1552         domain = bus->iommu_ops->domain_alloc(type);
1553         if (!domain)
1554                 return NULL;
1555
1556         domain->ops  = bus->iommu_ops;
1557         domain->type = type;
1558         /* Assume all sizes by default; the driver may override this later */
1559         domain->pgsize_bitmap  = bus->iommu_ops->pgsize_bitmap;
1560
1561         return domain;
1562 }
1563
1564 struct iommu_domain *iommu_domain_alloc(struct bus_type *bus)
1565 {
1566         return __iommu_domain_alloc(bus, IOMMU_DOMAIN_UNMANAGED);
1567 }
1568 EXPORT_SYMBOL_GPL(iommu_domain_alloc);
1569
1570 void iommu_domain_free(struct iommu_domain *domain)
1571 {
1572         domain->ops->domain_free(domain);
1573 }
1574 EXPORT_SYMBOL_GPL(iommu_domain_free);
1575
1576 static int __iommu_attach_device(struct iommu_domain *domain,
1577                                  struct device *dev)
1578 {
1579         int ret;
1580         if ((domain->ops->is_attach_deferred != NULL) &&
1581             domain->ops->is_attach_deferred(domain, dev))
1582                 return 0;
1583
1584         if (unlikely(domain->ops->attach_dev == NULL))
1585                 return -ENODEV;
1586
1587         ret = domain->ops->attach_dev(domain, dev);
1588         if (!ret)
1589                 trace_attach_device_to_domain(dev);
1590         return ret;
1591 }
1592
1593 int iommu_attach_device(struct iommu_domain *domain, struct device *dev)
1594 {
1595         struct iommu_group *group;
1596         int ret;
1597
1598         group = iommu_group_get(dev);
1599         if (!group)
1600                 return -ENODEV;
1601
1602         /*
1603          * Lock the group to make sure the device-count doesn't
1604          * change while we are attaching
1605          */
1606         mutex_lock(&group->mutex);
1607         ret = -EINVAL;
1608         if (iommu_group_device_count(group) != 1)
1609                 goto out_unlock;
1610
1611         ret = __iommu_attach_group(domain, group);
1612
1613 out_unlock:
1614         mutex_unlock(&group->mutex);
1615         iommu_group_put(group);
1616
1617         return ret;
1618 }
1619 EXPORT_SYMBOL_GPL(iommu_attach_device);
1620
1621 static void __iommu_detach_device(struct iommu_domain *domain,
1622                                   struct device *dev)
1623 {
1624         if ((domain->ops->is_attach_deferred != NULL) &&
1625             domain->ops->is_attach_deferred(domain, dev))
1626                 return;
1627
1628         if (unlikely(domain->ops->detach_dev == NULL))
1629                 return;
1630
1631         domain->ops->detach_dev(domain, dev);
1632         trace_detach_device_from_domain(dev);
1633 }
1634
1635 void iommu_detach_device(struct iommu_domain *domain, struct device *dev)
1636 {
1637         struct iommu_group *group;
1638
1639         group = iommu_group_get(dev);
1640         if (!group)
1641                 return;
1642
1643         mutex_lock(&group->mutex);
1644         if (iommu_group_device_count(group) != 1) {
1645                 WARN_ON(1);
1646                 goto out_unlock;
1647         }
1648
1649         __iommu_detach_group(domain, group);
1650
1651 out_unlock:
1652         mutex_unlock(&group->mutex);
1653         iommu_group_put(group);
1654 }
1655 EXPORT_SYMBOL_GPL(iommu_detach_device);
1656
1657 struct iommu_domain *iommu_get_domain_for_dev(struct device *dev)
1658 {
1659         struct iommu_domain *domain;
1660         struct iommu_group *group;
1661
1662         group = iommu_group_get(dev);
1663         if (!group)
1664                 return NULL;
1665
1666         domain = group->domain;
1667
1668         iommu_group_put(group);
1669
1670         return domain;
1671 }
1672 EXPORT_SYMBOL_GPL(iommu_get_domain_for_dev);
1673
1674 /*
1675  * For IOMMU_DOMAIN_DMA implementations which already provide their own
1676  * guarantees that the group and its default domain are valid and correct.
1677  */
1678 struct iommu_domain *iommu_get_dma_domain(struct device *dev)
1679 {
1680         return dev->iommu_group->default_domain;
1681 }
1682
1683 /*
1684  * IOMMU groups are really the natural working unit of the IOMMU, but
1685  * the IOMMU API works on domains and devices.  Bridge that gap by
1686  * iterating over the devices in a group.  Ideally we'd have a single
1687  * device which represents the requestor ID of the group, but we also
1688  * allow IOMMU drivers to create policy defined minimum sets, where
1689  * the physical hardware may be able to distiguish members, but we
1690  * wish to group them at a higher level (ex. untrusted multi-function
1691  * PCI devices).  Thus we attach each device.
1692  */
1693 static int iommu_group_do_attach_device(struct device *dev, void *data)
1694 {
1695         struct iommu_domain *domain = data;
1696
1697         return __iommu_attach_device(domain, dev);
1698 }
1699
1700 static int __iommu_attach_group(struct iommu_domain *domain,
1701                                 struct iommu_group *group)
1702 {
1703         int ret;
1704
1705         if (group->default_domain && group->domain != group->default_domain)
1706                 return -EBUSY;
1707
1708         ret = __iommu_group_for_each_dev(group, domain,
1709                                          iommu_group_do_attach_device);
1710         if (ret == 0)
1711                 group->domain = domain;
1712
1713         return ret;
1714 }
1715
1716 int iommu_attach_group(struct iommu_domain *domain, struct iommu_group *group)
1717 {
1718         int ret;
1719
1720         mutex_lock(&group->mutex);
1721         ret = __iommu_attach_group(domain, group);
1722         mutex_unlock(&group->mutex);
1723
1724         return ret;
1725 }
1726 EXPORT_SYMBOL_GPL(iommu_attach_group);
1727
1728 static int iommu_group_do_detach_device(struct device *dev, void *data)
1729 {
1730         struct iommu_domain *domain = data;
1731
1732         __iommu_detach_device(domain, dev);
1733
1734         return 0;
1735 }
1736
1737 static void __iommu_detach_group(struct iommu_domain *domain,
1738                                  struct iommu_group *group)
1739 {
1740         int ret;
1741
1742         if (!group->default_domain) {
1743                 __iommu_group_for_each_dev(group, domain,
1744                                            iommu_group_do_detach_device);
1745                 group->domain = NULL;
1746                 return;
1747         }
1748
1749         if (group->domain == group->default_domain)
1750                 return;
1751
1752         /* Detach by re-attaching to the default domain */
1753         ret = __iommu_group_for_each_dev(group, group->default_domain,
1754                                          iommu_group_do_attach_device);
1755         if (ret != 0)
1756                 WARN_ON(1);
1757         else
1758                 group->domain = group->default_domain;
1759 }
1760
1761 void iommu_detach_group(struct iommu_domain *domain, struct iommu_group *group)
1762 {
1763         mutex_lock(&group->mutex);
1764         __iommu_detach_group(domain, group);
1765         mutex_unlock(&group->mutex);
1766 }
1767 EXPORT_SYMBOL_GPL(iommu_detach_group);
1768
1769 phys_addr_t iommu_iova_to_phys(struct iommu_domain *domain, dma_addr_t iova)
1770 {
1771         if (unlikely(domain->ops->iova_to_phys == NULL))
1772                 return 0;
1773
1774         return domain->ops->iova_to_phys(domain, iova);
1775 }
1776 EXPORT_SYMBOL_GPL(iommu_iova_to_phys);
1777
1778 static size_t iommu_pgsize(struct iommu_domain *domain,
1779                            unsigned long addr_merge, size_t size)
1780 {
1781         unsigned int pgsize_idx;
1782         size_t pgsize;
1783
1784         /* Max page size that still fits into 'size' */
1785         pgsize_idx = __fls(size);
1786
1787         /* need to consider alignment requirements ? */
1788         if (likely(addr_merge)) {
1789                 /* Max page size allowed by address */
1790                 unsigned int align_pgsize_idx = __ffs(addr_merge);
1791                 pgsize_idx = min(pgsize_idx, align_pgsize_idx);
1792         }
1793
1794         /* build a mask of acceptable page sizes */
1795         pgsize = (1UL << (pgsize_idx + 1)) - 1;
1796
1797         /* throw away page sizes not supported by the hardware */
1798         pgsize &= domain->pgsize_bitmap;
1799
1800         /* make sure we're still sane */
1801         BUG_ON(!pgsize);
1802
1803         /* pick the biggest page */
1804         pgsize_idx = __fls(pgsize);
1805         pgsize = 1UL << pgsize_idx;
1806
1807         return pgsize;
1808 }
1809
1810 int iommu_map(struct iommu_domain *domain, unsigned long iova,
1811               phys_addr_t paddr, size_t size, int prot)
1812 {
1813         const struct iommu_ops *ops = domain->ops;
1814         unsigned long orig_iova = iova;
1815         unsigned int min_pagesz;
1816         size_t orig_size = size;
1817         phys_addr_t orig_paddr = paddr;
1818         int ret = 0;
1819
1820         if (unlikely(ops->map == NULL ||
1821                      domain->pgsize_bitmap == 0UL))
1822                 return -ENODEV;
1823
1824         if (unlikely(!(domain->type & __IOMMU_DOMAIN_PAGING)))
1825                 return -EINVAL;
1826
1827         /* find out the minimum page size supported */
1828         min_pagesz = 1 << __ffs(domain->pgsize_bitmap);
1829
1830         /*
1831          * both the virtual address and the physical one, as well as
1832          * the size of the mapping, must be aligned (at least) to the
1833          * size of the smallest page supported by the hardware
1834          */
1835         if (!IS_ALIGNED(iova | paddr | size, min_pagesz)) {
1836                 pr_err("unaligned: iova 0x%lx pa %pa size 0x%zx min_pagesz 0x%x\n",
1837                        iova, &paddr, size, min_pagesz);
1838                 return -EINVAL;
1839         }
1840
1841         pr_debug("map: iova 0x%lx pa %pa size 0x%zx\n", iova, &paddr, size);
1842
1843         while (size) {
1844                 size_t pgsize = iommu_pgsize(domain, iova | paddr, size);
1845
1846                 pr_debug("mapping: iova 0x%lx pa %pa pgsize 0x%zx\n",
1847                          iova, &paddr, pgsize);
1848
1849                 ret = ops->map(domain, iova, paddr, pgsize, prot);
1850                 if (ret)
1851                         break;
1852
1853                 iova += pgsize;
1854                 paddr += pgsize;
1855                 size -= pgsize;
1856         }
1857
1858         if (ops->iotlb_sync_map)
1859                 ops->iotlb_sync_map(domain);
1860
1861         /* unroll mapping in case something went wrong */
1862         if (ret)
1863                 iommu_unmap(domain, orig_iova, orig_size - size);
1864         else
1865                 trace_map(orig_iova, orig_paddr, orig_size);
1866
1867         return ret;
1868 }
1869 EXPORT_SYMBOL_GPL(iommu_map);
1870
1871 static size_t __iommu_unmap(struct iommu_domain *domain,
1872                             unsigned long iova, size_t size,
1873                             bool sync)
1874 {
1875         const struct iommu_ops *ops = domain->ops;
1876         size_t unmapped_page, unmapped = 0;
1877         unsigned long orig_iova = iova;
1878         unsigned int min_pagesz;
1879
1880         if (unlikely(ops->unmap == NULL ||
1881                      domain->pgsize_bitmap == 0UL))
1882                 return 0;
1883
1884         if (unlikely(!(domain->type & __IOMMU_DOMAIN_PAGING)))
1885                 return 0;
1886
1887         /* find out the minimum page size supported */
1888         min_pagesz = 1 << __ffs(domain->pgsize_bitmap);
1889
1890         /*
1891          * The virtual address, as well as the size of the mapping, must be
1892          * aligned (at least) to the size of the smallest page supported
1893          * by the hardware
1894          */
1895         if (!IS_ALIGNED(iova | size, min_pagesz)) {
1896                 pr_err("unaligned: iova 0x%lx size 0x%zx min_pagesz 0x%x\n",
1897                        iova, size, min_pagesz);
1898                 return 0;
1899         }
1900
1901         pr_debug("unmap this: iova 0x%lx size 0x%zx\n", iova, size);
1902
1903         /*
1904          * Keep iterating until we either unmap 'size' bytes (or more)
1905          * or we hit an area that isn't mapped.
1906          */
1907         while (unmapped < size) {
1908                 size_t pgsize = iommu_pgsize(domain, iova, size - unmapped);
1909
1910                 unmapped_page = ops->unmap(domain, iova, pgsize);
1911                 if (!unmapped_page)
1912                         break;
1913
1914                 if (sync && ops->iotlb_range_add)
1915                         ops->iotlb_range_add(domain, iova, pgsize);
1916
1917                 pr_debug("unmapped: iova 0x%lx size 0x%zx\n",
1918                          iova, unmapped_page);
1919
1920                 iova += unmapped_page;
1921                 unmapped += unmapped_page;
1922         }
1923
1924         if (sync && ops->iotlb_sync)
1925                 ops->iotlb_sync(domain);
1926
1927         trace_unmap(orig_iova, size, unmapped);
1928         return unmapped;
1929 }
1930
1931 size_t iommu_unmap(struct iommu_domain *domain,
1932                    unsigned long iova, size_t size)
1933 {
1934         return __iommu_unmap(domain, iova, size, true);
1935 }
1936 EXPORT_SYMBOL_GPL(iommu_unmap);
1937
1938 size_t iommu_unmap_fast(struct iommu_domain *domain,
1939                         unsigned long iova, size_t size)
1940 {
1941         return __iommu_unmap(domain, iova, size, false);
1942 }
1943 EXPORT_SYMBOL_GPL(iommu_unmap_fast);
1944
1945 size_t iommu_map_sg(struct iommu_domain *domain, unsigned long iova,
1946                     struct scatterlist *sg, unsigned int nents, int prot)
1947 {
1948         size_t len = 0, mapped = 0;
1949         phys_addr_t start;
1950         unsigned int i = 0;
1951         int ret;
1952
1953         while (i <= nents) {
1954                 phys_addr_t s_phys = sg_phys(sg);
1955
1956                 if (len && s_phys != start + len) {
1957                         ret = iommu_map(domain, iova + mapped, start, len, prot);
1958                         if (ret)
1959                                 goto out_err;
1960
1961                         mapped += len;
1962                         len = 0;
1963                 }
1964
1965                 if (len) {
1966                         len += sg->length;
1967                 } else {
1968                         len = sg->length;
1969                         start = s_phys;
1970                 }
1971
1972                 if (++i < nents)
1973                         sg = sg_next(sg);
1974         }
1975
1976         return mapped;
1977
1978 out_err:
1979         /* undo mappings already done */
1980         iommu_unmap(domain, iova, mapped);
1981
1982         return 0;
1983
1984 }
1985 EXPORT_SYMBOL_GPL(iommu_map_sg);
1986
1987 int iommu_domain_window_enable(struct iommu_domain *domain, u32 wnd_nr,
1988                                phys_addr_t paddr, u64 size, int prot)
1989 {
1990         if (unlikely(domain->ops->domain_window_enable == NULL))
1991                 return -ENODEV;
1992
1993         return domain->ops->domain_window_enable(domain, wnd_nr, paddr, size,
1994                                                  prot);
1995 }
1996 EXPORT_SYMBOL_GPL(iommu_domain_window_enable);
1997
1998 void iommu_domain_window_disable(struct iommu_domain *domain, u32 wnd_nr)
1999 {
2000         if (unlikely(domain->ops->domain_window_disable == NULL))
2001                 return;
2002
2003         return domain->ops->domain_window_disable(domain, wnd_nr);
2004 }
2005 EXPORT_SYMBOL_GPL(iommu_domain_window_disable);
2006
2007 /**
2008  * report_iommu_fault() - report about an IOMMU fault to the IOMMU framework
2009  * @domain: the iommu domain where the fault has happened
2010  * @dev: the device where the fault has happened
2011  * @iova: the faulting address
2012  * @flags: mmu fault flags (e.g. IOMMU_FAULT_READ/IOMMU_FAULT_WRITE/...)
2013  *
2014  * This function should be called by the low-level IOMMU implementations
2015  * whenever IOMMU faults happen, to allow high-level users, that are
2016  * interested in such events, to know about them.
2017  *
2018  * This event may be useful for several possible use cases:
2019  * - mere logging of the event
2020  * - dynamic TLB/PTE loading
2021  * - if restarting of the faulting device is required
2022  *
2023  * Returns 0 on success and an appropriate error code otherwise (if dynamic
2024  * PTE/TLB loading will one day be supported, implementations will be able
2025  * to tell whether it succeeded or not according to this return value).
2026  *
2027  * Specifically, -ENOSYS is returned if a fault handler isn't installed
2028  * (though fault handlers can also return -ENOSYS, in case they want to
2029  * elicit the default behavior of the IOMMU drivers).
2030  */
2031 int report_iommu_fault(struct iommu_domain *domain, struct device *dev,
2032                        unsigned long iova, int flags)
2033 {
2034         int ret = -ENOSYS;
2035
2036         /*
2037          * if upper layers showed interest and installed a fault handler,
2038          * invoke it.
2039          */
2040         if (domain->handler)
2041                 ret = domain->handler(domain, dev, iova, flags,
2042                                                 domain->handler_token);
2043
2044         trace_io_page_fault(dev, iova, flags);
2045         return ret;
2046 }
2047 EXPORT_SYMBOL_GPL(report_iommu_fault);
2048
2049 static int __init iommu_init(void)
2050 {
2051         iommu_group_kset = kset_create_and_add("iommu_groups",
2052                                                NULL, kernel_kobj);
2053         BUG_ON(!iommu_group_kset);
2054
2055         iommu_debugfs_setup();
2056
2057         return 0;
2058 }
2059 core_initcall(iommu_init);
2060
2061 int iommu_domain_get_attr(struct iommu_domain *domain,
2062                           enum iommu_attr attr, void *data)
2063 {
2064         struct iommu_domain_geometry *geometry;
2065         bool *paging;
2066         int ret = 0;
2067
2068         switch (attr) {
2069         case DOMAIN_ATTR_GEOMETRY:
2070                 geometry  = data;
2071                 *geometry = domain->geometry;
2072
2073                 break;
2074         case DOMAIN_ATTR_PAGING:
2075                 paging  = data;
2076                 *paging = (domain->pgsize_bitmap != 0UL);
2077                 break;
2078         default:
2079                 if (!domain->ops->domain_get_attr)
2080                         return -EINVAL;
2081
2082                 ret = domain->ops->domain_get_attr(domain, attr, data);
2083         }
2084
2085         return ret;
2086 }
2087 EXPORT_SYMBOL_GPL(iommu_domain_get_attr);
2088
2089 int iommu_domain_set_attr(struct iommu_domain *domain,
2090                           enum iommu_attr attr, void *data)
2091 {
2092         int ret = 0;
2093
2094         switch (attr) {
2095         default:
2096                 if (domain->ops->domain_set_attr == NULL)
2097                         return -EINVAL;
2098
2099                 ret = domain->ops->domain_set_attr(domain, attr, data);
2100         }
2101
2102         return ret;
2103 }
2104 EXPORT_SYMBOL_GPL(iommu_domain_set_attr);
2105
2106 void iommu_get_resv_regions(struct device *dev, struct list_head *list)
2107 {
2108         const struct iommu_ops *ops = dev->bus->iommu_ops;
2109
2110         if (ops && ops->get_resv_regions)
2111                 ops->get_resv_regions(dev, list);
2112 }
2113
2114 void iommu_put_resv_regions(struct device *dev, struct list_head *list)
2115 {
2116         const struct iommu_ops *ops = dev->bus->iommu_ops;
2117
2118         if (ops && ops->put_resv_regions)
2119                 ops->put_resv_regions(dev, list);
2120 }
2121
2122 struct iommu_resv_region *iommu_alloc_resv_region(phys_addr_t start,
2123                                                   size_t length, int prot,
2124                                                   enum iommu_resv_type type)
2125 {
2126         struct iommu_resv_region *region;
2127
2128         region = kzalloc(sizeof(*region), GFP_KERNEL);
2129         if (!region)
2130                 return NULL;
2131
2132         INIT_LIST_HEAD(&region->list);
2133         region->start = start;
2134         region->length = length;
2135         region->prot = prot;
2136         region->type = type;
2137         return region;
2138 }
2139
2140 /* Request that a device is direct mapped by the IOMMU */
2141 int iommu_request_dm_for_dev(struct device *dev)
2142 {
2143         struct iommu_domain *dm_domain;
2144         struct iommu_group *group;
2145         int ret;
2146
2147         /* Device must already be in a group before calling this function */
2148         group = iommu_group_get(dev);
2149         if (!group)
2150                 return -EINVAL;
2151
2152         mutex_lock(&group->mutex);
2153
2154         /* Check if the default domain is already direct mapped */
2155         ret = 0;
2156         if (group->default_domain &&
2157             group->default_domain->type == IOMMU_DOMAIN_IDENTITY)
2158                 goto out;
2159
2160         /* Don't change mappings of existing devices */
2161         ret = -EBUSY;
2162         if (iommu_group_device_count(group) != 1)
2163                 goto out;
2164
2165         /* Allocate a direct mapped domain */
2166         ret = -ENOMEM;
2167         dm_domain = __iommu_domain_alloc(dev->bus, IOMMU_DOMAIN_IDENTITY);
2168         if (!dm_domain)
2169                 goto out;
2170
2171         /* Attach the device to the domain */
2172         ret = __iommu_attach_group(dm_domain, group);
2173         if (ret) {
2174                 iommu_domain_free(dm_domain);
2175                 goto out;
2176         }
2177
2178         /* Make the direct mapped domain the default for this group */
2179         if (group->default_domain)
2180                 iommu_domain_free(group->default_domain);
2181         group->default_domain = dm_domain;
2182
2183         dev_info(dev, "Using iommu direct mapping\n");
2184
2185         ret = 0;
2186 out:
2187         mutex_unlock(&group->mutex);
2188         iommu_group_put(group);
2189
2190         return ret;
2191 }
2192
2193 const struct iommu_ops *iommu_ops_from_fwnode(struct fwnode_handle *fwnode)
2194 {
2195         const struct iommu_ops *ops = NULL;
2196         struct iommu_device *iommu;
2197
2198         spin_lock(&iommu_device_lock);
2199         list_for_each_entry(iommu, &iommu_device_list, list)
2200                 if (iommu->fwnode == fwnode) {
2201                         ops = iommu->ops;
2202                         break;
2203                 }
2204         spin_unlock(&iommu_device_lock);
2205         return ops;
2206 }
2207
2208 int iommu_fwspec_init(struct device *dev, struct fwnode_handle *iommu_fwnode,
2209                       const struct iommu_ops *ops)
2210 {
2211         struct iommu_fwspec *fwspec = dev_iommu_fwspec_get(dev);
2212
2213         if (fwspec)
2214                 return ops == fwspec->ops ? 0 : -EINVAL;
2215
2216         fwspec = kzalloc(sizeof(*fwspec), GFP_KERNEL);
2217         if (!fwspec)
2218                 return -ENOMEM;
2219
2220         of_node_get(to_of_node(iommu_fwnode));
2221         fwspec->iommu_fwnode = iommu_fwnode;
2222         fwspec->ops = ops;
2223         dev_iommu_fwspec_set(dev, fwspec);
2224         return 0;
2225 }
2226 EXPORT_SYMBOL_GPL(iommu_fwspec_init);
2227
2228 void iommu_fwspec_free(struct device *dev)
2229 {
2230         struct iommu_fwspec *fwspec = dev_iommu_fwspec_get(dev);
2231
2232         if (fwspec) {
2233                 fwnode_handle_put(fwspec->iommu_fwnode);
2234                 kfree(fwspec);
2235                 dev_iommu_fwspec_set(dev, NULL);
2236         }
2237 }
2238 EXPORT_SYMBOL_GPL(iommu_fwspec_free);
2239
2240 int iommu_fwspec_add_ids(struct device *dev, u32 *ids, int num_ids)
2241 {
2242         struct iommu_fwspec *fwspec = dev_iommu_fwspec_get(dev);
2243         size_t size;
2244         int i;
2245
2246         if (!fwspec)
2247                 return -EINVAL;
2248
2249         size = offsetof(struct iommu_fwspec, ids[fwspec->num_ids + num_ids]);
2250         if (size > sizeof(*fwspec)) {
2251                 fwspec = krealloc(fwspec, size, GFP_KERNEL);
2252                 if (!fwspec)
2253                         return -ENOMEM;
2254
2255                 dev_iommu_fwspec_set(dev, fwspec);
2256         }
2257
2258         for (i = 0; i < num_ids; i++)
2259                 fwspec->ids[fwspec->num_ids + i] = ids[i];
2260
2261         fwspec->num_ids += num_ids;
2262         return 0;
2263 }
2264 EXPORT_SYMBOL_GPL(iommu_fwspec_add_ids);
2265
2266 /*
2267  * Per device IOMMU features.
2268  */
2269 bool iommu_dev_has_feature(struct device *dev, enum iommu_dev_features feat)
2270 {
2271         const struct iommu_ops *ops = dev->bus->iommu_ops;
2272
2273         if (ops && ops->dev_has_feat)
2274                 return ops->dev_has_feat(dev, feat);
2275
2276         return false;
2277 }
2278 EXPORT_SYMBOL_GPL(iommu_dev_has_feature);
2279
2280 int iommu_dev_enable_feature(struct device *dev, enum iommu_dev_features feat)
2281 {
2282         const struct iommu_ops *ops = dev->bus->iommu_ops;
2283
2284         if (ops && ops->dev_enable_feat)
2285                 return ops->dev_enable_feat(dev, feat);
2286
2287         return -ENODEV;
2288 }
2289 EXPORT_SYMBOL_GPL(iommu_dev_enable_feature);
2290
2291 /*
2292  * The device drivers should do the necessary cleanups before calling this.
2293  * For example, before disabling the aux-domain feature, the device driver
2294  * should detach all aux-domains. Otherwise, this will return -EBUSY.
2295  */
2296 int iommu_dev_disable_feature(struct device *dev, enum iommu_dev_features feat)
2297 {
2298         const struct iommu_ops *ops = dev->bus->iommu_ops;
2299
2300         if (ops && ops->dev_disable_feat)
2301                 return ops->dev_disable_feat(dev, feat);
2302
2303         return -EBUSY;
2304 }
2305 EXPORT_SYMBOL_GPL(iommu_dev_disable_feature);
2306
2307 bool iommu_dev_feature_enabled(struct device *dev, enum iommu_dev_features feat)
2308 {
2309         const struct iommu_ops *ops = dev->bus->iommu_ops;
2310
2311         if (ops && ops->dev_feat_enabled)
2312                 return ops->dev_feat_enabled(dev, feat);
2313
2314         return false;
2315 }
2316 EXPORT_SYMBOL_GPL(iommu_dev_feature_enabled);
2317
2318 /*
2319  * Aux-domain specific attach/detach.
2320  *
2321  * Only works if iommu_dev_feature_enabled(dev, IOMMU_DEV_FEAT_AUX) returns
2322  * true. Also, as long as domains are attached to a device through this
2323  * interface, any tries to call iommu_attach_device() should fail
2324  * (iommu_detach_device() can't fail, so we fail when trying to re-attach).
2325  * This should make us safe against a device being attached to a guest as a
2326  * whole while there are still pasid users on it (aux and sva).
2327  */
2328 int iommu_aux_attach_device(struct iommu_domain *domain, struct device *dev)
2329 {
2330         int ret = -ENODEV;
2331
2332         if (domain->ops->aux_attach_dev)
2333                 ret = domain->ops->aux_attach_dev(domain, dev);
2334
2335         if (!ret)
2336                 trace_attach_device_to_domain(dev);
2337
2338         return ret;
2339 }
2340 EXPORT_SYMBOL_GPL(iommu_aux_attach_device);
2341
2342 void iommu_aux_detach_device(struct iommu_domain *domain, struct device *dev)
2343 {
2344         if (domain->ops->aux_detach_dev) {
2345                 domain->ops->aux_detach_dev(domain, dev);
2346                 trace_detach_device_from_domain(dev);
2347         }
2348 }
2349 EXPORT_SYMBOL_GPL(iommu_aux_detach_device);
2350
2351 int iommu_aux_get_pasid(struct iommu_domain *domain, struct device *dev)
2352 {
2353         int ret = -ENODEV;
2354
2355         if (domain->ops->aux_get_pasid)
2356                 ret = domain->ops->aux_get_pasid(domain, dev);
2357
2358         return ret;
2359 }
2360 EXPORT_SYMBOL_GPL(iommu_aux_get_pasid);
2361
2362 /**
2363  * iommu_sva_bind_device() - Bind a process address space to a device
2364  * @dev: the device
2365  * @mm: the mm to bind, caller must hold a reference to it
2366  *
2367  * Create a bond between device and address space, allowing the device to access
2368  * the mm using the returned PASID. If a bond already exists between @device and
2369  * @mm, it is returned and an additional reference is taken. Caller must call
2370  * iommu_sva_unbind_device() to release each reference.
2371  *
2372  * iommu_dev_enable_feature(dev, IOMMU_DEV_FEAT_SVA) must be called first, to
2373  * initialize the required SVA features.
2374  *
2375  * On error, returns an ERR_PTR value.
2376  */
2377 struct iommu_sva *
2378 iommu_sva_bind_device(struct device *dev, struct mm_struct *mm, void *drvdata)
2379 {
2380         struct iommu_group *group;
2381         struct iommu_sva *handle = ERR_PTR(-EINVAL);
2382         const struct iommu_ops *ops = dev->bus->iommu_ops;
2383
2384         if (!ops || !ops->sva_bind)
2385                 return ERR_PTR(-ENODEV);
2386
2387         group = iommu_group_get(dev);
2388         if (!group)
2389                 return ERR_PTR(-ENODEV);
2390
2391         /* Ensure device count and domain don't change while we're binding */
2392         mutex_lock(&group->mutex);
2393
2394         /*
2395          * To keep things simple, SVA currently doesn't support IOMMU groups
2396          * with more than one device. Existing SVA-capable systems are not
2397          * affected by the problems that required IOMMU groups (lack of ACS
2398          * isolation, device ID aliasing and other hardware issues).
2399          */
2400         if (iommu_group_device_count(group) != 1)
2401                 goto out_unlock;
2402
2403         handle = ops->sva_bind(dev, mm, drvdata);
2404
2405 out_unlock:
2406         mutex_unlock(&group->mutex);
2407         iommu_group_put(group);
2408
2409         return handle;
2410 }
2411 EXPORT_SYMBOL_GPL(iommu_sva_bind_device);
2412
2413 /**
2414  * iommu_sva_unbind_device() - Remove a bond created with iommu_sva_bind_device
2415  * @handle: the handle returned by iommu_sva_bind_device()
2416  *
2417  * Put reference to a bond between device and address space. The device should
2418  * not be issuing any more transaction for this PASID. All outstanding page
2419  * requests for this PASID must have been flushed to the IOMMU.
2420  *
2421  * Returns 0 on success, or an error value
2422  */
2423 void iommu_sva_unbind_device(struct iommu_sva *handle)
2424 {
2425         struct iommu_group *group;
2426         struct device *dev = handle->dev;
2427         const struct iommu_ops *ops = dev->bus->iommu_ops;
2428
2429         if (!ops || !ops->sva_unbind)
2430                 return;
2431
2432         group = iommu_group_get(dev);
2433         if (!group)
2434                 return;
2435
2436         mutex_lock(&group->mutex);
2437         ops->sva_unbind(handle);
2438         mutex_unlock(&group->mutex);
2439
2440         iommu_group_put(group);
2441 }
2442 EXPORT_SYMBOL_GPL(iommu_sva_unbind_device);
2443
2444 int iommu_sva_set_ops(struct iommu_sva *handle,
2445                       const struct iommu_sva_ops *sva_ops)
2446 {
2447         if (handle->ops && handle->ops != sva_ops)
2448                 return -EEXIST;
2449
2450         handle->ops = sva_ops;
2451         return 0;
2452 }
2453 EXPORT_SYMBOL_GPL(iommu_sva_set_ops);
2454
2455 int iommu_sva_get_pasid(struct iommu_sva *handle)
2456 {
2457         const struct iommu_ops *ops = handle->dev->bus->iommu_ops;
2458
2459         if (!ops || !ops->sva_get_pasid)
2460                 return IOMMU_PASID_INVALID;
2461
2462         return ops->sva_get_pasid(handle);
2463 }
2464 EXPORT_SYMBOL_GPL(iommu_sva_get_pasid);