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