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