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