iommu: Allocate a default domain for iommu groups
[cascardo/linux.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 <trace/events/iommu.h>
35
36 static struct kset *iommu_group_kset;
37 static struct ida iommu_group_ida;
38 static struct mutex iommu_group_mutex;
39
40 struct iommu_callback_data {
41         const struct iommu_ops *ops;
42 };
43
44 struct iommu_group {
45         struct kobject kobj;
46         struct kobject *devices_kobj;
47         struct list_head devices;
48         struct mutex mutex;
49         struct blocking_notifier_head notifier;
50         void *iommu_data;
51         void (*iommu_data_release)(void *iommu_data);
52         char *name;
53         int id;
54         struct iommu_domain *default_domain;
55 };
56
57 struct iommu_device {
58         struct list_head list;
59         struct device *dev;
60         char *name;
61 };
62
63 struct iommu_group_attribute {
64         struct attribute attr;
65         ssize_t (*show)(struct iommu_group *group, char *buf);
66         ssize_t (*store)(struct iommu_group *group,
67                          const char *buf, size_t count);
68 };
69
70 #define IOMMU_GROUP_ATTR(_name, _mode, _show, _store)           \
71 struct iommu_group_attribute iommu_group_attr_##_name =         \
72         __ATTR(_name, _mode, _show, _store)
73
74 #define to_iommu_group_attr(_attr)      \
75         container_of(_attr, struct iommu_group_attribute, attr)
76 #define to_iommu_group(_kobj)           \
77         container_of(_kobj, struct iommu_group, kobj)
78
79 static struct iommu_domain *__iommu_domain_alloc(struct bus_type *bus,
80                                                  unsigned type);
81
82 static ssize_t iommu_group_attr_show(struct kobject *kobj,
83                                      struct attribute *__attr, char *buf)
84 {
85         struct iommu_group_attribute *attr = to_iommu_group_attr(__attr);
86         struct iommu_group *group = to_iommu_group(kobj);
87         ssize_t ret = -EIO;
88
89         if (attr->show)
90                 ret = attr->show(group, buf);
91         return ret;
92 }
93
94 static ssize_t iommu_group_attr_store(struct kobject *kobj,
95                                       struct attribute *__attr,
96                                       const char *buf, size_t count)
97 {
98         struct iommu_group_attribute *attr = to_iommu_group_attr(__attr);
99         struct iommu_group *group = to_iommu_group(kobj);
100         ssize_t ret = -EIO;
101
102         if (attr->store)
103                 ret = attr->store(group, buf, count);
104         return ret;
105 }
106
107 static const struct sysfs_ops iommu_group_sysfs_ops = {
108         .show = iommu_group_attr_show,
109         .store = iommu_group_attr_store,
110 };
111
112 static int iommu_group_create_file(struct iommu_group *group,
113                                    struct iommu_group_attribute *attr)
114 {
115         return sysfs_create_file(&group->kobj, &attr->attr);
116 }
117
118 static void iommu_group_remove_file(struct iommu_group *group,
119                                     struct iommu_group_attribute *attr)
120 {
121         sysfs_remove_file(&group->kobj, &attr->attr);
122 }
123
124 static ssize_t iommu_group_show_name(struct iommu_group *group, char *buf)
125 {
126         return sprintf(buf, "%s\n", group->name);
127 }
128
129 static IOMMU_GROUP_ATTR(name, S_IRUGO, iommu_group_show_name, NULL);
130
131 static void iommu_group_release(struct kobject *kobj)
132 {
133         struct iommu_group *group = to_iommu_group(kobj);
134
135         pr_debug("Releasing group %d\n", group->id);
136
137         if (group->iommu_data_release)
138                 group->iommu_data_release(group->iommu_data);
139
140         mutex_lock(&iommu_group_mutex);
141         ida_remove(&iommu_group_ida, group->id);
142         mutex_unlock(&iommu_group_mutex);
143
144         if (group->default_domain)
145                 iommu_domain_free(group->default_domain);
146
147         kfree(group->name);
148         kfree(group);
149 }
150
151 static struct kobj_type iommu_group_ktype = {
152         .sysfs_ops = &iommu_group_sysfs_ops,
153         .release = iommu_group_release,
154 };
155
156 /**
157  * iommu_group_alloc - Allocate a new group
158  * @name: Optional name to associate with group, visible in sysfs
159  *
160  * This function is called by an iommu driver to allocate a new iommu
161  * group.  The iommu group represents the minimum granularity of the iommu.
162  * Upon successful return, the caller holds a reference to the supplied
163  * group in order to hold the group until devices are added.  Use
164  * iommu_group_put() to release this extra reference count, allowing the
165  * group to be automatically reclaimed once it has no devices or external
166  * references.
167  */
168 struct iommu_group *iommu_group_alloc(void)
169 {
170         struct iommu_group *group;
171         int ret;
172
173         group = kzalloc(sizeof(*group), GFP_KERNEL);
174         if (!group)
175                 return ERR_PTR(-ENOMEM);
176
177         group->kobj.kset = iommu_group_kset;
178         mutex_init(&group->mutex);
179         INIT_LIST_HEAD(&group->devices);
180         BLOCKING_INIT_NOTIFIER_HEAD(&group->notifier);
181
182         mutex_lock(&iommu_group_mutex);
183
184 again:
185         if (unlikely(0 == ida_pre_get(&iommu_group_ida, GFP_KERNEL))) {
186                 kfree(group);
187                 mutex_unlock(&iommu_group_mutex);
188                 return ERR_PTR(-ENOMEM);
189         }
190
191         if (-EAGAIN == ida_get_new(&iommu_group_ida, &group->id))
192                 goto again;
193
194         mutex_unlock(&iommu_group_mutex);
195
196         ret = kobject_init_and_add(&group->kobj, &iommu_group_ktype,
197                                    NULL, "%d", group->id);
198         if (ret) {
199                 mutex_lock(&iommu_group_mutex);
200                 ida_remove(&iommu_group_ida, group->id);
201                 mutex_unlock(&iommu_group_mutex);
202                 kfree(group);
203                 return ERR_PTR(ret);
204         }
205
206         group->devices_kobj = kobject_create_and_add("devices", &group->kobj);
207         if (!group->devices_kobj) {
208                 kobject_put(&group->kobj); /* triggers .release & free */
209                 return ERR_PTR(-ENOMEM);
210         }
211
212         /*
213          * The devices_kobj holds a reference on the group kobject, so
214          * as long as that exists so will the group.  We can therefore
215          * use the devices_kobj for reference counting.
216          */
217         kobject_put(&group->kobj);
218
219         pr_debug("Allocated group %d\n", group->id);
220
221         return group;
222 }
223 EXPORT_SYMBOL_GPL(iommu_group_alloc);
224
225 struct iommu_group *iommu_group_get_by_id(int id)
226 {
227         struct kobject *group_kobj;
228         struct iommu_group *group;
229         const char *name;
230
231         if (!iommu_group_kset)
232                 return NULL;
233
234         name = kasprintf(GFP_KERNEL, "%d", id);
235         if (!name)
236                 return NULL;
237
238         group_kobj = kset_find_obj(iommu_group_kset, name);
239         kfree(name);
240
241         if (!group_kobj)
242                 return NULL;
243
244         group = container_of(group_kobj, struct iommu_group, kobj);
245         BUG_ON(group->id != id);
246
247         kobject_get(group->devices_kobj);
248         kobject_put(&group->kobj);
249
250         return group;
251 }
252 EXPORT_SYMBOL_GPL(iommu_group_get_by_id);
253
254 /**
255  * iommu_group_get_iommudata - retrieve iommu_data registered for a group
256  * @group: the group
257  *
258  * iommu drivers can store data in the group for use when doing iommu
259  * operations.  This function provides a way to retrieve it.  Caller
260  * should hold a group reference.
261  */
262 void *iommu_group_get_iommudata(struct iommu_group *group)
263 {
264         return group->iommu_data;
265 }
266 EXPORT_SYMBOL_GPL(iommu_group_get_iommudata);
267
268 /**
269  * iommu_group_set_iommudata - set iommu_data for a group
270  * @group: the group
271  * @iommu_data: new data
272  * @release: release function for iommu_data
273  *
274  * iommu drivers can store data in the group for use when doing iommu
275  * operations.  This function provides a way to set the data after
276  * the group has been allocated.  Caller should hold a group reference.
277  */
278 void iommu_group_set_iommudata(struct iommu_group *group, void *iommu_data,
279                                void (*release)(void *iommu_data))
280 {
281         group->iommu_data = iommu_data;
282         group->iommu_data_release = release;
283 }
284 EXPORT_SYMBOL_GPL(iommu_group_set_iommudata);
285
286 /**
287  * iommu_group_set_name - set name for a group
288  * @group: the group
289  * @name: name
290  *
291  * Allow iommu driver to set a name for a group.  When set it will
292  * appear in a name attribute file under the group in sysfs.
293  */
294 int iommu_group_set_name(struct iommu_group *group, const char *name)
295 {
296         int ret;
297
298         if (group->name) {
299                 iommu_group_remove_file(group, &iommu_group_attr_name);
300                 kfree(group->name);
301                 group->name = NULL;
302                 if (!name)
303                         return 0;
304         }
305
306         group->name = kstrdup(name, GFP_KERNEL);
307         if (!group->name)
308                 return -ENOMEM;
309
310         ret = iommu_group_create_file(group, &iommu_group_attr_name);
311         if (ret) {
312                 kfree(group->name);
313                 group->name = NULL;
314                 return ret;
315         }
316
317         return 0;
318 }
319 EXPORT_SYMBOL_GPL(iommu_group_set_name);
320
321 /**
322  * iommu_group_add_device - add a device to an iommu group
323  * @group: the group into which to add the device (reference should be held)
324  * @dev: the device
325  *
326  * This function is called by an iommu driver to add a device into a
327  * group.  Adding a device increments the group reference count.
328  */
329 int iommu_group_add_device(struct iommu_group *group, struct device *dev)
330 {
331         int ret, i = 0;
332         struct iommu_device *device;
333
334         device = kzalloc(sizeof(*device), GFP_KERNEL);
335         if (!device)
336                 return -ENOMEM;
337
338         device->dev = dev;
339
340         ret = sysfs_create_link(&dev->kobj, &group->kobj, "iommu_group");
341         if (ret) {
342                 kfree(device);
343                 return ret;
344         }
345
346         device->name = kasprintf(GFP_KERNEL, "%s", kobject_name(&dev->kobj));
347 rename:
348         if (!device->name) {
349                 sysfs_remove_link(&dev->kobj, "iommu_group");
350                 kfree(device);
351                 return -ENOMEM;
352         }
353
354         ret = sysfs_create_link_nowarn(group->devices_kobj,
355                                        &dev->kobj, device->name);
356         if (ret) {
357                 kfree(device->name);
358                 if (ret == -EEXIST && i >= 0) {
359                         /*
360                          * Account for the slim chance of collision
361                          * and append an instance to the name.
362                          */
363                         device->name = kasprintf(GFP_KERNEL, "%s.%d",
364                                                  kobject_name(&dev->kobj), i++);
365                         goto rename;
366                 }
367
368                 sysfs_remove_link(&dev->kobj, "iommu_group");
369                 kfree(device);
370                 return ret;
371         }
372
373         kobject_get(group->devices_kobj);
374
375         dev->iommu_group = group;
376
377         mutex_lock(&group->mutex);
378         list_add_tail(&device->list, &group->devices);
379         mutex_unlock(&group->mutex);
380
381         /* Notify any listeners about change to group. */
382         blocking_notifier_call_chain(&group->notifier,
383                                      IOMMU_GROUP_NOTIFY_ADD_DEVICE, dev);
384
385         trace_add_device_to_group(group->id, dev);
386
387         pr_info("Adding device %s to group %d\n", dev_name(dev), group->id);
388
389         return 0;
390 }
391 EXPORT_SYMBOL_GPL(iommu_group_add_device);
392
393 /**
394  * iommu_group_remove_device - remove a device from it's current group
395  * @dev: device to be removed
396  *
397  * This function is called by an iommu driver to remove the device from
398  * it's current group.  This decrements the iommu group reference count.
399  */
400 void iommu_group_remove_device(struct device *dev)
401 {
402         struct iommu_group *group = dev->iommu_group;
403         struct iommu_device *tmp_device, *device = NULL;
404
405         pr_info("Removing device %s from group %d\n", dev_name(dev), group->id);
406
407         /* Pre-notify listeners that a device is being removed. */
408         blocking_notifier_call_chain(&group->notifier,
409                                      IOMMU_GROUP_NOTIFY_DEL_DEVICE, dev);
410
411         mutex_lock(&group->mutex);
412         list_for_each_entry(tmp_device, &group->devices, list) {
413                 if (tmp_device->dev == dev) {
414                         device = tmp_device;
415                         list_del(&device->list);
416                         break;
417                 }
418         }
419         mutex_unlock(&group->mutex);
420
421         if (!device)
422                 return;
423
424         sysfs_remove_link(group->devices_kobj, device->name);
425         sysfs_remove_link(&dev->kobj, "iommu_group");
426
427         trace_remove_device_from_group(group->id, dev);
428
429         kfree(device->name);
430         kfree(device);
431         dev->iommu_group = NULL;
432         kobject_put(group->devices_kobj);
433 }
434 EXPORT_SYMBOL_GPL(iommu_group_remove_device);
435
436 /**
437  * iommu_group_for_each_dev - iterate over each device in the group
438  * @group: the group
439  * @data: caller opaque data to be passed to callback function
440  * @fn: caller supplied callback function
441  *
442  * This function is called by group users to iterate over group devices.
443  * Callers should hold a reference count to the group during callback.
444  * The group->mutex is held across callbacks, which will block calls to
445  * iommu_group_add/remove_device.
446  */
447 int iommu_group_for_each_dev(struct iommu_group *group, void *data,
448                              int (*fn)(struct device *, void *))
449 {
450         struct iommu_device *device;
451         int ret = 0;
452
453         mutex_lock(&group->mutex);
454         list_for_each_entry(device, &group->devices, list) {
455                 ret = fn(device->dev, data);
456                 if (ret)
457                         break;
458         }
459         mutex_unlock(&group->mutex);
460         return ret;
461 }
462 EXPORT_SYMBOL_GPL(iommu_group_for_each_dev);
463
464 /**
465  * iommu_group_get - Return the group for a device and increment reference
466  * @dev: get the group that this device belongs to
467  *
468  * This function is called by iommu drivers and users to get the group
469  * for the specified device.  If found, the group is returned and the group
470  * reference in incremented, else NULL.
471  */
472 struct iommu_group *iommu_group_get(struct device *dev)
473 {
474         struct iommu_group *group = dev->iommu_group;
475
476         if (group)
477                 kobject_get(group->devices_kobj);
478
479         return group;
480 }
481 EXPORT_SYMBOL_GPL(iommu_group_get);
482
483 /**
484  * iommu_group_put - Decrement group reference
485  * @group: the group to use
486  *
487  * This function is called by iommu drivers and users to release the
488  * iommu group.  Once the reference count is zero, the group is released.
489  */
490 void iommu_group_put(struct iommu_group *group)
491 {
492         if (group)
493                 kobject_put(group->devices_kobj);
494 }
495 EXPORT_SYMBOL_GPL(iommu_group_put);
496
497 /**
498  * iommu_group_register_notifier - Register a notifier for group changes
499  * @group: the group to watch
500  * @nb: notifier block to signal
501  *
502  * This function allows iommu group users to track changes in a group.
503  * See include/linux/iommu.h for actions sent via this notifier.  Caller
504  * should hold a reference to the group throughout notifier registration.
505  */
506 int iommu_group_register_notifier(struct iommu_group *group,
507                                   struct notifier_block *nb)
508 {
509         return blocking_notifier_chain_register(&group->notifier, nb);
510 }
511 EXPORT_SYMBOL_GPL(iommu_group_register_notifier);
512
513 /**
514  * iommu_group_unregister_notifier - Unregister a notifier
515  * @group: the group to watch
516  * @nb: notifier block to signal
517  *
518  * Unregister a previously registered group notifier block.
519  */
520 int iommu_group_unregister_notifier(struct iommu_group *group,
521                                     struct notifier_block *nb)
522 {
523         return blocking_notifier_chain_unregister(&group->notifier, nb);
524 }
525 EXPORT_SYMBOL_GPL(iommu_group_unregister_notifier);
526
527 /**
528  * iommu_group_id - Return ID for a group
529  * @group: the group to ID
530  *
531  * Return the unique ID for the group matching the sysfs group number.
532  */
533 int iommu_group_id(struct iommu_group *group)
534 {
535         return group->id;
536 }
537 EXPORT_SYMBOL_GPL(iommu_group_id);
538
539 static struct iommu_group *get_pci_alias_group(struct pci_dev *pdev,
540                                                unsigned long *devfns);
541
542 /*
543  * To consider a PCI device isolated, we require ACS to support Source
544  * Validation, Request Redirection, Completer Redirection, and Upstream
545  * Forwarding.  This effectively means that devices cannot spoof their
546  * requester ID, requests and completions cannot be redirected, and all
547  * transactions are forwarded upstream, even as it passes through a
548  * bridge where the target device is downstream.
549  */
550 #define REQ_ACS_FLAGS   (PCI_ACS_SV | PCI_ACS_RR | PCI_ACS_CR | PCI_ACS_UF)
551
552 /*
553  * For multifunction devices which are not isolated from each other, find
554  * all the other non-isolated functions and look for existing groups.  For
555  * each function, we also need to look for aliases to or from other devices
556  * that may already have a group.
557  */
558 static struct iommu_group *get_pci_function_alias_group(struct pci_dev *pdev,
559                                                         unsigned long *devfns)
560 {
561         struct pci_dev *tmp = NULL;
562         struct iommu_group *group;
563
564         if (!pdev->multifunction || pci_acs_enabled(pdev, REQ_ACS_FLAGS))
565                 return NULL;
566
567         for_each_pci_dev(tmp) {
568                 if (tmp == pdev || tmp->bus != pdev->bus ||
569                     PCI_SLOT(tmp->devfn) != PCI_SLOT(pdev->devfn) ||
570                     pci_acs_enabled(tmp, REQ_ACS_FLAGS))
571                         continue;
572
573                 group = get_pci_alias_group(tmp, devfns);
574                 if (group) {
575                         pci_dev_put(tmp);
576                         return group;
577                 }
578         }
579
580         return NULL;
581 }
582
583 /*
584  * Look for aliases to or from the given device for exisiting groups.  The
585  * dma_alias_devfn only supports aliases on the same bus, therefore the search
586  * space is quite small (especially since we're really only looking at pcie
587  * device, and therefore only expect multiple slots on the root complex or
588  * downstream switch ports).  It's conceivable though that a pair of
589  * multifunction devices could have aliases between them that would cause a
590  * loop.  To prevent this, we use a bitmap to track where we've been.
591  */
592 static struct iommu_group *get_pci_alias_group(struct pci_dev *pdev,
593                                                unsigned long *devfns)
594 {
595         struct pci_dev *tmp = NULL;
596         struct iommu_group *group;
597
598         if (test_and_set_bit(pdev->devfn & 0xff, devfns))
599                 return NULL;
600
601         group = iommu_group_get(&pdev->dev);
602         if (group)
603                 return group;
604
605         for_each_pci_dev(tmp) {
606                 if (tmp == pdev || tmp->bus != pdev->bus)
607                         continue;
608
609                 /* We alias them or they alias us */
610                 if (((pdev->dev_flags & PCI_DEV_FLAGS_DMA_ALIAS_DEVFN) &&
611                      pdev->dma_alias_devfn == tmp->devfn) ||
612                     ((tmp->dev_flags & PCI_DEV_FLAGS_DMA_ALIAS_DEVFN) &&
613                      tmp->dma_alias_devfn == pdev->devfn)) {
614
615                         group = get_pci_alias_group(tmp, devfns);
616                         if (group) {
617                                 pci_dev_put(tmp);
618                                 return group;
619                         }
620
621                         group = get_pci_function_alias_group(tmp, devfns);
622                         if (group) {
623                                 pci_dev_put(tmp);
624                                 return group;
625                         }
626                 }
627         }
628
629         return NULL;
630 }
631
632 struct group_for_pci_data {
633         struct pci_dev *pdev;
634         struct iommu_group *group;
635 };
636
637 /*
638  * DMA alias iterator callback, return the last seen device.  Stop and return
639  * the IOMMU group if we find one along the way.
640  */
641 static int get_pci_alias_or_group(struct pci_dev *pdev, u16 alias, void *opaque)
642 {
643         struct group_for_pci_data *data = opaque;
644
645         data->pdev = pdev;
646         data->group = iommu_group_get(&pdev->dev);
647
648         return data->group != NULL;
649 }
650
651 /*
652  * Use standard PCI bus topology, isolation features, and DMA alias quirks
653  * to find or create an IOMMU group for a device.
654  */
655 static struct iommu_group *iommu_group_get_for_pci_dev(struct pci_dev *pdev)
656 {
657         struct group_for_pci_data data;
658         struct pci_bus *bus;
659         struct iommu_group *group = NULL;
660         u64 devfns[4] = { 0 };
661
662         /*
663          * Find the upstream DMA alias for the device.  A device must not
664          * be aliased due to topology in order to have its own IOMMU group.
665          * If we find an alias along the way that already belongs to a
666          * group, use it.
667          */
668         if (pci_for_each_dma_alias(pdev, get_pci_alias_or_group, &data))
669                 return data.group;
670
671         pdev = data.pdev;
672
673         /*
674          * Continue upstream from the point of minimum IOMMU granularity
675          * due to aliases to the point where devices are protected from
676          * peer-to-peer DMA by PCI ACS.  Again, if we find an existing
677          * group, use it.
678          */
679         for (bus = pdev->bus; !pci_is_root_bus(bus); bus = bus->parent) {
680                 if (!bus->self)
681                         continue;
682
683                 if (pci_acs_path_enabled(bus->self, NULL, REQ_ACS_FLAGS))
684                         break;
685
686                 pdev = bus->self;
687
688                 group = iommu_group_get(&pdev->dev);
689                 if (group)
690                         return group;
691         }
692
693         /*
694          * Look for existing groups on device aliases.  If we alias another
695          * device or another device aliases us, use the same group.
696          */
697         group = get_pci_alias_group(pdev, (unsigned long *)devfns);
698         if (group)
699                 return group;
700
701         /*
702          * Look for existing groups on non-isolated functions on the same
703          * slot and aliases of those funcions, if any.  No need to clear
704          * the search bitmap, the tested devfns are still valid.
705          */
706         group = get_pci_function_alias_group(pdev, (unsigned long *)devfns);
707         if (group)
708                 return group;
709
710         /* No shared group found, allocate new */
711         group = iommu_group_alloc();
712         if (group) {
713                 /*
714                  * Try to allocate a default domain - needs support from the
715                  * IOMMU driver.
716                  */
717                 group->default_domain = __iommu_domain_alloc(pdev->dev.bus,
718                                                              IOMMU_DOMAIN_DMA);
719         }
720
721         return group;
722 }
723
724 /**
725  * iommu_group_get_for_dev - Find or create the IOMMU group for a device
726  * @dev: target device
727  *
728  * This function is intended to be called by IOMMU drivers and extended to
729  * support common, bus-defined algorithms when determining or creating the
730  * IOMMU group for a device.  On success, the caller will hold a reference
731  * to the returned IOMMU group, which will already include the provided
732  * device.  The reference should be released with iommu_group_put().
733  */
734 struct iommu_group *iommu_group_get_for_dev(struct device *dev)
735 {
736         struct iommu_group *group;
737         int ret;
738
739         group = iommu_group_get(dev);
740         if (group)
741                 return group;
742
743         if (!dev_is_pci(dev))
744                 return ERR_PTR(-EINVAL);
745
746         group = iommu_group_get_for_pci_dev(to_pci_dev(dev));
747
748         if (IS_ERR(group))
749                 return group;
750
751         ret = iommu_group_add_device(group, dev);
752         if (ret) {
753                 iommu_group_put(group);
754                 return ERR_PTR(ret);
755         }
756
757         return group;
758 }
759
760 static int add_iommu_group(struct device *dev, void *data)
761 {
762         struct iommu_callback_data *cb = data;
763         const struct iommu_ops *ops = cb->ops;
764
765         if (!ops->add_device)
766                 return 0;
767
768         WARN_ON(dev->iommu_group);
769
770         return ops->add_device(dev);
771 }
772
773 static int remove_iommu_group(struct device *dev, void *data)
774 {
775         struct iommu_callback_data *cb = data;
776         const struct iommu_ops *ops = cb->ops;
777
778         if (ops->remove_device && dev->iommu_group)
779                 ops->remove_device(dev);
780
781         return 0;
782 }
783
784 static int iommu_bus_notifier(struct notifier_block *nb,
785                               unsigned long action, void *data)
786 {
787         struct device *dev = data;
788         const struct iommu_ops *ops = dev->bus->iommu_ops;
789         struct iommu_group *group;
790         unsigned long group_action = 0;
791
792         /*
793          * ADD/DEL call into iommu driver ops if provided, which may
794          * result in ADD/DEL notifiers to group->notifier
795          */
796         if (action == BUS_NOTIFY_ADD_DEVICE) {
797                 if (ops->add_device)
798                         return ops->add_device(dev);
799         } else if (action == BUS_NOTIFY_REMOVED_DEVICE) {
800                 if (ops->remove_device && dev->iommu_group) {
801                         ops->remove_device(dev);
802                         return 0;
803                 }
804         }
805
806         /*
807          * Remaining BUS_NOTIFYs get filtered and republished to the
808          * group, if anyone is listening
809          */
810         group = iommu_group_get(dev);
811         if (!group)
812                 return 0;
813
814         switch (action) {
815         case BUS_NOTIFY_BIND_DRIVER:
816                 group_action = IOMMU_GROUP_NOTIFY_BIND_DRIVER;
817                 break;
818         case BUS_NOTIFY_BOUND_DRIVER:
819                 group_action = IOMMU_GROUP_NOTIFY_BOUND_DRIVER;
820                 break;
821         case BUS_NOTIFY_UNBIND_DRIVER:
822                 group_action = IOMMU_GROUP_NOTIFY_UNBIND_DRIVER;
823                 break;
824         case BUS_NOTIFY_UNBOUND_DRIVER:
825                 group_action = IOMMU_GROUP_NOTIFY_UNBOUND_DRIVER;
826                 break;
827         }
828
829         if (group_action)
830                 blocking_notifier_call_chain(&group->notifier,
831                                              group_action, dev);
832
833         iommu_group_put(group);
834         return 0;
835 }
836
837 static int iommu_bus_init(struct bus_type *bus, const struct iommu_ops *ops)
838 {
839         int err;
840         struct notifier_block *nb;
841         struct iommu_callback_data cb = {
842                 .ops = ops,
843         };
844
845         nb = kzalloc(sizeof(struct notifier_block), GFP_KERNEL);
846         if (!nb)
847                 return -ENOMEM;
848
849         nb->notifier_call = iommu_bus_notifier;
850
851         err = bus_register_notifier(bus, nb);
852         if (err)
853                 goto out_free;
854
855         err = bus_for_each_dev(bus, NULL, &cb, add_iommu_group);
856         if (err)
857                 goto out_err;
858
859
860         return 0;
861
862 out_err:
863         /* Clean up */
864         bus_for_each_dev(bus, NULL, &cb, remove_iommu_group);
865         bus_unregister_notifier(bus, nb);
866
867 out_free:
868         kfree(nb);
869
870         return err;
871 }
872
873 /**
874  * bus_set_iommu - set iommu-callbacks for the bus
875  * @bus: bus.
876  * @ops: the callbacks provided by the iommu-driver
877  *
878  * This function is called by an iommu driver to set the iommu methods
879  * used for a particular bus. Drivers for devices on that bus can use
880  * the iommu-api after these ops are registered.
881  * This special function is needed because IOMMUs are usually devices on
882  * the bus itself, so the iommu drivers are not initialized when the bus
883  * is set up. With this function the iommu-driver can set the iommu-ops
884  * afterwards.
885  */
886 int bus_set_iommu(struct bus_type *bus, const struct iommu_ops *ops)
887 {
888         int err;
889
890         if (bus->iommu_ops != NULL)
891                 return -EBUSY;
892
893         bus->iommu_ops = ops;
894
895         /* Do IOMMU specific setup for this bus-type */
896         err = iommu_bus_init(bus, ops);
897         if (err)
898                 bus->iommu_ops = NULL;
899
900         return err;
901 }
902 EXPORT_SYMBOL_GPL(bus_set_iommu);
903
904 bool iommu_present(struct bus_type *bus)
905 {
906         return bus->iommu_ops != NULL;
907 }
908 EXPORT_SYMBOL_GPL(iommu_present);
909
910 bool iommu_capable(struct bus_type *bus, enum iommu_cap cap)
911 {
912         if (!bus->iommu_ops || !bus->iommu_ops->capable)
913                 return false;
914
915         return bus->iommu_ops->capable(cap);
916 }
917 EXPORT_SYMBOL_GPL(iommu_capable);
918
919 /**
920  * iommu_set_fault_handler() - set a fault handler for an iommu domain
921  * @domain: iommu domain
922  * @handler: fault handler
923  * @token: user data, will be passed back to the fault handler
924  *
925  * This function should be used by IOMMU users which want to be notified
926  * whenever an IOMMU fault happens.
927  *
928  * The fault handler itself should return 0 on success, and an appropriate
929  * error code otherwise.
930  */
931 void iommu_set_fault_handler(struct iommu_domain *domain,
932                                         iommu_fault_handler_t handler,
933                                         void *token)
934 {
935         BUG_ON(!domain);
936
937         domain->handler = handler;
938         domain->handler_token = token;
939 }
940 EXPORT_SYMBOL_GPL(iommu_set_fault_handler);
941
942 static struct iommu_domain *__iommu_domain_alloc(struct bus_type *bus,
943                                                  unsigned type)
944 {
945         struct iommu_domain *domain;
946
947         if (bus == NULL || bus->iommu_ops == NULL)
948                 return NULL;
949
950         domain = bus->iommu_ops->domain_alloc(type);
951         if (!domain)
952                 return NULL;
953
954         domain->ops  = bus->iommu_ops;
955         domain->type = type;
956
957         return domain;
958 }
959
960 struct iommu_domain *iommu_domain_alloc(struct bus_type *bus)
961 {
962         return __iommu_domain_alloc(bus, IOMMU_DOMAIN_UNMANAGED);
963 }
964 EXPORT_SYMBOL_GPL(iommu_domain_alloc);
965
966 void iommu_domain_free(struct iommu_domain *domain)
967 {
968         domain->ops->domain_free(domain);
969 }
970 EXPORT_SYMBOL_GPL(iommu_domain_free);
971
972 int iommu_attach_device(struct iommu_domain *domain, struct device *dev)
973 {
974         int ret;
975         if (unlikely(domain->ops->attach_dev == NULL))
976                 return -ENODEV;
977
978         ret = domain->ops->attach_dev(domain, dev);
979         if (!ret)
980                 trace_attach_device_to_domain(dev);
981         return ret;
982 }
983 EXPORT_SYMBOL_GPL(iommu_attach_device);
984
985 void iommu_detach_device(struct iommu_domain *domain, struct device *dev)
986 {
987         if (unlikely(domain->ops->detach_dev == NULL))
988                 return;
989
990         domain->ops->detach_dev(domain, dev);
991         trace_detach_device_from_domain(dev);
992 }
993 EXPORT_SYMBOL_GPL(iommu_detach_device);
994
995 /*
996  * IOMMU groups are really the natrual working unit of the IOMMU, but
997  * the IOMMU API works on domains and devices.  Bridge that gap by
998  * iterating over the devices in a group.  Ideally we'd have a single
999  * device which represents the requestor ID of the group, but we also
1000  * allow IOMMU drivers to create policy defined minimum sets, where
1001  * the physical hardware may be able to distiguish members, but we
1002  * wish to group them at a higher level (ex. untrusted multi-function
1003  * PCI devices).  Thus we attach each device.
1004  */
1005 static int iommu_group_do_attach_device(struct device *dev, void *data)
1006 {
1007         struct iommu_domain *domain = data;
1008
1009         return iommu_attach_device(domain, dev);
1010 }
1011
1012 int iommu_attach_group(struct iommu_domain *domain, struct iommu_group *group)
1013 {
1014         return iommu_group_for_each_dev(group, domain,
1015                                         iommu_group_do_attach_device);
1016 }
1017 EXPORT_SYMBOL_GPL(iommu_attach_group);
1018
1019 static int iommu_group_do_detach_device(struct device *dev, void *data)
1020 {
1021         struct iommu_domain *domain = data;
1022
1023         iommu_detach_device(domain, dev);
1024
1025         return 0;
1026 }
1027
1028 void iommu_detach_group(struct iommu_domain *domain, struct iommu_group *group)
1029 {
1030         iommu_group_for_each_dev(group, domain, iommu_group_do_detach_device);
1031 }
1032 EXPORT_SYMBOL_GPL(iommu_detach_group);
1033
1034 phys_addr_t iommu_iova_to_phys(struct iommu_domain *domain, dma_addr_t iova)
1035 {
1036         if (unlikely(domain->ops->iova_to_phys == NULL))
1037                 return 0;
1038
1039         return domain->ops->iova_to_phys(domain, iova);
1040 }
1041 EXPORT_SYMBOL_GPL(iommu_iova_to_phys);
1042
1043 static size_t iommu_pgsize(struct iommu_domain *domain,
1044                            unsigned long addr_merge, size_t size)
1045 {
1046         unsigned int pgsize_idx;
1047         size_t pgsize;
1048
1049         /* Max page size that still fits into 'size' */
1050         pgsize_idx = __fls(size);
1051
1052         /* need to consider alignment requirements ? */
1053         if (likely(addr_merge)) {
1054                 /* Max page size allowed by address */
1055                 unsigned int align_pgsize_idx = __ffs(addr_merge);
1056                 pgsize_idx = min(pgsize_idx, align_pgsize_idx);
1057         }
1058
1059         /* build a mask of acceptable page sizes */
1060         pgsize = (1UL << (pgsize_idx + 1)) - 1;
1061
1062         /* throw away page sizes not supported by the hardware */
1063         pgsize &= domain->ops->pgsize_bitmap;
1064
1065         /* make sure we're still sane */
1066         BUG_ON(!pgsize);
1067
1068         /* pick the biggest page */
1069         pgsize_idx = __fls(pgsize);
1070         pgsize = 1UL << pgsize_idx;
1071
1072         return pgsize;
1073 }
1074
1075 int iommu_map(struct iommu_domain *domain, unsigned long iova,
1076               phys_addr_t paddr, size_t size, int prot)
1077 {
1078         unsigned long orig_iova = iova;
1079         unsigned int min_pagesz;
1080         size_t orig_size = size;
1081         int ret = 0;
1082
1083         if (unlikely(domain->ops->map == NULL ||
1084                      domain->ops->pgsize_bitmap == 0UL))
1085                 return -ENODEV;
1086
1087         if (unlikely(!(domain->type & __IOMMU_DOMAIN_PAGING)))
1088                 return -EINVAL;
1089
1090         /* find out the minimum page size supported */
1091         min_pagesz = 1 << __ffs(domain->ops->pgsize_bitmap);
1092
1093         /*
1094          * both the virtual address and the physical one, as well as
1095          * the size of the mapping, must be aligned (at least) to the
1096          * size of the smallest page supported by the hardware
1097          */
1098         if (!IS_ALIGNED(iova | paddr | size, min_pagesz)) {
1099                 pr_err("unaligned: iova 0x%lx pa %pa size 0x%zx min_pagesz 0x%x\n",
1100                        iova, &paddr, size, min_pagesz);
1101                 return -EINVAL;
1102         }
1103
1104         pr_debug("map: iova 0x%lx pa %pa size 0x%zx\n", iova, &paddr, size);
1105
1106         while (size) {
1107                 size_t pgsize = iommu_pgsize(domain, iova | paddr, size);
1108
1109                 pr_debug("mapping: iova 0x%lx pa %pa pgsize 0x%zx\n",
1110                          iova, &paddr, pgsize);
1111
1112                 ret = domain->ops->map(domain, iova, paddr, pgsize, prot);
1113                 if (ret)
1114                         break;
1115
1116                 iova += pgsize;
1117                 paddr += pgsize;
1118                 size -= pgsize;
1119         }
1120
1121         /* unroll mapping in case something went wrong */
1122         if (ret)
1123                 iommu_unmap(domain, orig_iova, orig_size - size);
1124         else
1125                 trace_map(orig_iova, paddr, orig_size);
1126
1127         return ret;
1128 }
1129 EXPORT_SYMBOL_GPL(iommu_map);
1130
1131 size_t iommu_unmap(struct iommu_domain *domain, unsigned long iova, size_t size)
1132 {
1133         size_t unmapped_page, unmapped = 0;
1134         unsigned int min_pagesz;
1135         unsigned long orig_iova = iova;
1136
1137         if (unlikely(domain->ops->unmap == NULL ||
1138                      domain->ops->pgsize_bitmap == 0UL))
1139                 return -ENODEV;
1140
1141         if (unlikely(!(domain->type & __IOMMU_DOMAIN_PAGING)))
1142                 return -EINVAL;
1143
1144         /* find out the minimum page size supported */
1145         min_pagesz = 1 << __ffs(domain->ops->pgsize_bitmap);
1146
1147         /*
1148          * The virtual address, as well as the size of the mapping, must be
1149          * aligned (at least) to the size of the smallest page supported
1150          * by the hardware
1151          */
1152         if (!IS_ALIGNED(iova | size, min_pagesz)) {
1153                 pr_err("unaligned: iova 0x%lx size 0x%zx min_pagesz 0x%x\n",
1154                        iova, size, min_pagesz);
1155                 return -EINVAL;
1156         }
1157
1158         pr_debug("unmap this: iova 0x%lx size 0x%zx\n", iova, size);
1159
1160         /*
1161          * Keep iterating until we either unmap 'size' bytes (or more)
1162          * or we hit an area that isn't mapped.
1163          */
1164         while (unmapped < size) {
1165                 size_t pgsize = iommu_pgsize(domain, iova, size - unmapped);
1166
1167                 unmapped_page = domain->ops->unmap(domain, iova, pgsize);
1168                 if (!unmapped_page)
1169                         break;
1170
1171                 pr_debug("unmapped: iova 0x%lx size 0x%zx\n",
1172                          iova, unmapped_page);
1173
1174                 iova += unmapped_page;
1175                 unmapped += unmapped_page;
1176         }
1177
1178         trace_unmap(orig_iova, size, unmapped);
1179         return unmapped;
1180 }
1181 EXPORT_SYMBOL_GPL(iommu_unmap);
1182
1183 size_t default_iommu_map_sg(struct iommu_domain *domain, unsigned long iova,
1184                          struct scatterlist *sg, unsigned int nents, int prot)
1185 {
1186         struct scatterlist *s;
1187         size_t mapped = 0;
1188         unsigned int i, min_pagesz;
1189         int ret;
1190
1191         if (unlikely(domain->ops->pgsize_bitmap == 0UL))
1192                 return 0;
1193
1194         min_pagesz = 1 << __ffs(domain->ops->pgsize_bitmap);
1195
1196         for_each_sg(sg, s, nents, i) {
1197                 phys_addr_t phys = page_to_phys(sg_page(s)) + s->offset;
1198
1199                 /*
1200                  * We are mapping on IOMMU page boundaries, so offset within
1201                  * the page must be 0. However, the IOMMU may support pages
1202                  * smaller than PAGE_SIZE, so s->offset may still represent
1203                  * an offset of that boundary within the CPU page.
1204                  */
1205                 if (!IS_ALIGNED(s->offset, min_pagesz))
1206                         goto out_err;
1207
1208                 ret = iommu_map(domain, iova + mapped, phys, s->length, prot);
1209                 if (ret)
1210                         goto out_err;
1211
1212                 mapped += s->length;
1213         }
1214
1215         return mapped;
1216
1217 out_err:
1218         /* undo mappings already done */
1219         iommu_unmap(domain, iova, mapped);
1220
1221         return 0;
1222
1223 }
1224 EXPORT_SYMBOL_GPL(default_iommu_map_sg);
1225
1226 int iommu_domain_window_enable(struct iommu_domain *domain, u32 wnd_nr,
1227                                phys_addr_t paddr, u64 size, int prot)
1228 {
1229         if (unlikely(domain->ops->domain_window_enable == NULL))
1230                 return -ENODEV;
1231
1232         return domain->ops->domain_window_enable(domain, wnd_nr, paddr, size,
1233                                                  prot);
1234 }
1235 EXPORT_SYMBOL_GPL(iommu_domain_window_enable);
1236
1237 void iommu_domain_window_disable(struct iommu_domain *domain, u32 wnd_nr)
1238 {
1239         if (unlikely(domain->ops->domain_window_disable == NULL))
1240                 return;
1241
1242         return domain->ops->domain_window_disable(domain, wnd_nr);
1243 }
1244 EXPORT_SYMBOL_GPL(iommu_domain_window_disable);
1245
1246 static int __init iommu_init(void)
1247 {
1248         iommu_group_kset = kset_create_and_add("iommu_groups",
1249                                                NULL, kernel_kobj);
1250         ida_init(&iommu_group_ida);
1251         mutex_init(&iommu_group_mutex);
1252
1253         BUG_ON(!iommu_group_kset);
1254
1255         return 0;
1256 }
1257 arch_initcall(iommu_init);
1258
1259 int iommu_domain_get_attr(struct iommu_domain *domain,
1260                           enum iommu_attr attr, void *data)
1261 {
1262         struct iommu_domain_geometry *geometry;
1263         bool *paging;
1264         int ret = 0;
1265         u32 *count;
1266
1267         switch (attr) {
1268         case DOMAIN_ATTR_GEOMETRY:
1269                 geometry  = data;
1270                 *geometry = domain->geometry;
1271
1272                 break;
1273         case DOMAIN_ATTR_PAGING:
1274                 paging  = data;
1275                 *paging = (domain->ops->pgsize_bitmap != 0UL);
1276                 break;
1277         case DOMAIN_ATTR_WINDOWS:
1278                 count = data;
1279
1280                 if (domain->ops->domain_get_windows != NULL)
1281                         *count = domain->ops->domain_get_windows(domain);
1282                 else
1283                         ret = -ENODEV;
1284
1285                 break;
1286         default:
1287                 if (!domain->ops->domain_get_attr)
1288                         return -EINVAL;
1289
1290                 ret = domain->ops->domain_get_attr(domain, attr, data);
1291         }
1292
1293         return ret;
1294 }
1295 EXPORT_SYMBOL_GPL(iommu_domain_get_attr);
1296
1297 int iommu_domain_set_attr(struct iommu_domain *domain,
1298                           enum iommu_attr attr, void *data)
1299 {
1300         int ret = 0;
1301         u32 *count;
1302
1303         switch (attr) {
1304         case DOMAIN_ATTR_WINDOWS:
1305                 count = data;
1306
1307                 if (domain->ops->domain_set_windows != NULL)
1308                         ret = domain->ops->domain_set_windows(domain, *count);
1309                 else
1310                         ret = -ENODEV;
1311
1312                 break;
1313         default:
1314                 if (domain->ops->domain_set_attr == NULL)
1315                         return -EINVAL;
1316
1317                 ret = domain->ops->domain_set_attr(domain, attr, data);
1318         }
1319
1320         return ret;
1321 }
1322 EXPORT_SYMBOL_GPL(iommu_domain_set_attr);