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