xref: /openbmc/linux/drivers/iommu/iommu.c (revision 77423a62)
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/dma-iommu.h>
11 #include <linux/kernel.h>
12 #include <linux/bits.h>
13 #include <linux/bug.h>
14 #include <linux/types.h>
15 #include <linux/init.h>
16 #include <linux/export.h>
17 #include <linux/slab.h>
18 #include <linux/errno.h>
19 #include <linux/iommu.h>
20 #include <linux/idr.h>
21 #include <linux/err.h>
22 #include <linux/pci.h>
23 #include <linux/bitops.h>
24 #include <linux/property.h>
25 #include <linux/fsl/mc.h>
26 #include <linux/module.h>
27 #include <linux/cc_platform.h>
28 #include <trace/events/iommu.h>
29 
30 static struct kset *iommu_group_kset;
31 static DEFINE_IDA(iommu_group_ida);
32 
33 static unsigned int iommu_def_domain_type __read_mostly;
34 static bool iommu_dma_strict __read_mostly = IS_ENABLED(CONFIG_IOMMU_DEFAULT_DMA_STRICT);
35 static u32 iommu_cmd_line __read_mostly;
36 
37 struct iommu_group {
38 	struct kobject kobj;
39 	struct kobject *devices_kobj;
40 	struct list_head devices;
41 	struct mutex mutex;
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 *blocking_domain;
48 	struct iommu_domain *domain;
49 	struct list_head entry;
50 	unsigned int owner_cnt;
51 	void *owner;
52 };
53 
54 struct group_device {
55 	struct list_head list;
56 	struct device *dev;
57 	char *name;
58 };
59 
60 struct iommu_group_attribute {
61 	struct attribute attr;
62 	ssize_t (*show)(struct iommu_group *group, char *buf);
63 	ssize_t (*store)(struct iommu_group *group,
64 			 const char *buf, size_t count);
65 };
66 
67 static const char * const iommu_group_resv_type_string[] = {
68 	[IOMMU_RESV_DIRECT]			= "direct",
69 	[IOMMU_RESV_DIRECT_RELAXABLE]		= "direct-relaxable",
70 	[IOMMU_RESV_RESERVED]			= "reserved",
71 	[IOMMU_RESV_MSI]			= "msi",
72 	[IOMMU_RESV_SW_MSI]			= "msi",
73 };
74 
75 #define IOMMU_CMD_LINE_DMA_API		BIT(0)
76 #define IOMMU_CMD_LINE_STRICT		BIT(1)
77 
78 static int iommu_alloc_default_domain(struct iommu_group *group,
79 				      struct device *dev);
80 static struct iommu_domain *__iommu_domain_alloc(struct bus_type *bus,
81 						 unsigned type);
82 static int __iommu_attach_device(struct iommu_domain *domain,
83 				 struct device *dev);
84 static int __iommu_attach_group(struct iommu_domain *domain,
85 				struct iommu_group *group);
86 static int __iommu_group_set_domain(struct iommu_group *group,
87 				    struct iommu_domain *new_domain);
88 static int iommu_create_device_direct_mappings(struct iommu_group *group,
89 					       struct device *dev);
90 static struct iommu_group *iommu_group_get_for_dev(struct device *dev);
91 static ssize_t iommu_group_store_type(struct iommu_group *group,
92 				      const char *buf, size_t count);
93 
94 #define IOMMU_GROUP_ATTR(_name, _mode, _show, _store)		\
95 struct iommu_group_attribute iommu_group_attr_##_name =		\
96 	__ATTR(_name, _mode, _show, _store)
97 
98 #define to_iommu_group_attr(_attr)	\
99 	container_of(_attr, struct iommu_group_attribute, attr)
100 #define to_iommu_group(_kobj)		\
101 	container_of(_kobj, struct iommu_group, kobj)
102 
103 static LIST_HEAD(iommu_device_list);
104 static DEFINE_SPINLOCK(iommu_device_lock);
105 
106 /*
107  * Use a function instead of an array here because the domain-type is a
108  * bit-field, so an array would waste memory.
109  */
110 static const char *iommu_domain_type_str(unsigned int t)
111 {
112 	switch (t) {
113 	case IOMMU_DOMAIN_BLOCKED:
114 		return "Blocked";
115 	case IOMMU_DOMAIN_IDENTITY:
116 		return "Passthrough";
117 	case IOMMU_DOMAIN_UNMANAGED:
118 		return "Unmanaged";
119 	case IOMMU_DOMAIN_DMA:
120 	case IOMMU_DOMAIN_DMA_FQ:
121 		return "Translated";
122 	default:
123 		return "Unknown";
124 	}
125 }
126 
127 static int __init iommu_subsys_init(void)
128 {
129 	if (!(iommu_cmd_line & IOMMU_CMD_LINE_DMA_API)) {
130 		if (IS_ENABLED(CONFIG_IOMMU_DEFAULT_PASSTHROUGH))
131 			iommu_set_default_passthrough(false);
132 		else
133 			iommu_set_default_translated(false);
134 
135 		if (iommu_default_passthrough() && cc_platform_has(CC_ATTR_MEM_ENCRYPT)) {
136 			pr_info("Memory encryption detected - Disabling default IOMMU Passthrough\n");
137 			iommu_set_default_translated(false);
138 		}
139 	}
140 
141 	if (!iommu_default_passthrough() && !iommu_dma_strict)
142 		iommu_def_domain_type = IOMMU_DOMAIN_DMA_FQ;
143 
144 	pr_info("Default domain type: %s %s\n",
145 		iommu_domain_type_str(iommu_def_domain_type),
146 		(iommu_cmd_line & IOMMU_CMD_LINE_DMA_API) ?
147 			"(set via kernel command line)" : "");
148 
149 	if (!iommu_default_passthrough())
150 		pr_info("DMA domain TLB invalidation policy: %s mode %s\n",
151 			iommu_dma_strict ? "strict" : "lazy",
152 			(iommu_cmd_line & IOMMU_CMD_LINE_STRICT) ?
153 				"(set via kernel command line)" : "");
154 
155 	return 0;
156 }
157 subsys_initcall(iommu_subsys_init);
158 
159 /**
160  * iommu_device_register() - Register an IOMMU hardware instance
161  * @iommu: IOMMU handle for the instance
162  * @ops:   IOMMU ops to associate with the instance
163  * @hwdev: (optional) actual instance device, used for fwnode lookup
164  *
165  * Return: 0 on success, or an error.
166  */
167 int iommu_device_register(struct iommu_device *iommu,
168 			  const struct iommu_ops *ops, struct device *hwdev)
169 {
170 	/* We need to be able to take module references appropriately */
171 	if (WARN_ON(is_module_address((unsigned long)ops) && !ops->owner))
172 		return -EINVAL;
173 
174 	iommu->ops = ops;
175 	if (hwdev)
176 		iommu->fwnode = hwdev->fwnode;
177 
178 	spin_lock(&iommu_device_lock);
179 	list_add_tail(&iommu->list, &iommu_device_list);
180 	spin_unlock(&iommu_device_lock);
181 	return 0;
182 }
183 EXPORT_SYMBOL_GPL(iommu_device_register);
184 
185 void iommu_device_unregister(struct iommu_device *iommu)
186 {
187 	spin_lock(&iommu_device_lock);
188 	list_del(&iommu->list);
189 	spin_unlock(&iommu_device_lock);
190 }
191 EXPORT_SYMBOL_GPL(iommu_device_unregister);
192 
193 static struct dev_iommu *dev_iommu_get(struct device *dev)
194 {
195 	struct dev_iommu *param = dev->iommu;
196 
197 	if (param)
198 		return param;
199 
200 	param = kzalloc(sizeof(*param), GFP_KERNEL);
201 	if (!param)
202 		return NULL;
203 
204 	mutex_init(&param->lock);
205 	dev->iommu = param;
206 	return param;
207 }
208 
209 static void dev_iommu_free(struct device *dev)
210 {
211 	struct dev_iommu *param = dev->iommu;
212 
213 	dev->iommu = NULL;
214 	if (param->fwspec) {
215 		fwnode_handle_put(param->fwspec->iommu_fwnode);
216 		kfree(param->fwspec);
217 	}
218 	kfree(param);
219 }
220 
221 static int __iommu_probe_device(struct device *dev, struct list_head *group_list)
222 {
223 	const struct iommu_ops *ops = dev->bus->iommu_ops;
224 	struct iommu_device *iommu_dev;
225 	struct iommu_group *group;
226 	int ret;
227 
228 	if (!ops)
229 		return -ENODEV;
230 
231 	if (!dev_iommu_get(dev))
232 		return -ENOMEM;
233 
234 	if (!try_module_get(ops->owner)) {
235 		ret = -EINVAL;
236 		goto err_free;
237 	}
238 
239 	iommu_dev = ops->probe_device(dev);
240 	if (IS_ERR(iommu_dev)) {
241 		ret = PTR_ERR(iommu_dev);
242 		goto out_module_put;
243 	}
244 
245 	dev->iommu->iommu_dev = iommu_dev;
246 
247 	group = iommu_group_get_for_dev(dev);
248 	if (IS_ERR(group)) {
249 		ret = PTR_ERR(group);
250 		goto out_release;
251 	}
252 	iommu_group_put(group);
253 
254 	if (group_list && !group->default_domain && list_empty(&group->entry))
255 		list_add_tail(&group->entry, group_list);
256 
257 	iommu_device_link(iommu_dev, dev);
258 
259 	return 0;
260 
261 out_release:
262 	if (ops->release_device)
263 		ops->release_device(dev);
264 
265 out_module_put:
266 	module_put(ops->owner);
267 
268 err_free:
269 	dev_iommu_free(dev);
270 
271 	return ret;
272 }
273 
274 int iommu_probe_device(struct device *dev)
275 {
276 	const struct iommu_ops *ops;
277 	struct iommu_group *group;
278 	int ret;
279 
280 	ret = __iommu_probe_device(dev, NULL);
281 	if (ret)
282 		goto err_out;
283 
284 	group = iommu_group_get(dev);
285 	if (!group) {
286 		ret = -ENODEV;
287 		goto err_release;
288 	}
289 
290 	/*
291 	 * Try to allocate a default domain - needs support from the
292 	 * IOMMU driver. There are still some drivers which don't
293 	 * support default domains, so the return value is not yet
294 	 * checked.
295 	 */
296 	mutex_lock(&group->mutex);
297 	iommu_alloc_default_domain(group, dev);
298 
299 	/*
300 	 * If device joined an existing group which has been claimed, don't
301 	 * attach the default domain.
302 	 */
303 	if (group->default_domain && !group->owner) {
304 		ret = __iommu_attach_device(group->default_domain, dev);
305 		if (ret) {
306 			mutex_unlock(&group->mutex);
307 			iommu_group_put(group);
308 			goto err_release;
309 		}
310 	}
311 
312 	iommu_create_device_direct_mappings(group, dev);
313 
314 	mutex_unlock(&group->mutex);
315 	iommu_group_put(group);
316 
317 	ops = dev_iommu_ops(dev);
318 	if (ops->probe_finalize)
319 		ops->probe_finalize(dev);
320 
321 	return 0;
322 
323 err_release:
324 	iommu_release_device(dev);
325 
326 err_out:
327 	return ret;
328 
329 }
330 
331 void iommu_release_device(struct device *dev)
332 {
333 	const struct iommu_ops *ops;
334 
335 	if (!dev->iommu)
336 		return;
337 
338 	iommu_device_unlink(dev->iommu->iommu_dev, dev);
339 
340 	ops = dev_iommu_ops(dev);
341 	if (ops->release_device)
342 		ops->release_device(dev);
343 
344 	iommu_group_remove_device(dev);
345 	module_put(ops->owner);
346 	dev_iommu_free(dev);
347 }
348 
349 static int __init iommu_set_def_domain_type(char *str)
350 {
351 	bool pt;
352 	int ret;
353 
354 	ret = kstrtobool(str, &pt);
355 	if (ret)
356 		return ret;
357 
358 	if (pt)
359 		iommu_set_default_passthrough(true);
360 	else
361 		iommu_set_default_translated(true);
362 
363 	return 0;
364 }
365 early_param("iommu.passthrough", iommu_set_def_domain_type);
366 
367 static int __init iommu_dma_setup(char *str)
368 {
369 	int ret = kstrtobool(str, &iommu_dma_strict);
370 
371 	if (!ret)
372 		iommu_cmd_line |= IOMMU_CMD_LINE_STRICT;
373 	return ret;
374 }
375 early_param("iommu.strict", iommu_dma_setup);
376 
377 void iommu_set_dma_strict(void)
378 {
379 	iommu_dma_strict = true;
380 	if (iommu_def_domain_type == IOMMU_DOMAIN_DMA_FQ)
381 		iommu_def_domain_type = IOMMU_DOMAIN_DMA;
382 }
383 
384 static ssize_t iommu_group_attr_show(struct kobject *kobj,
385 				     struct attribute *__attr, char *buf)
386 {
387 	struct iommu_group_attribute *attr = to_iommu_group_attr(__attr);
388 	struct iommu_group *group = to_iommu_group(kobj);
389 	ssize_t ret = -EIO;
390 
391 	if (attr->show)
392 		ret = attr->show(group, buf);
393 	return ret;
394 }
395 
396 static ssize_t iommu_group_attr_store(struct kobject *kobj,
397 				      struct attribute *__attr,
398 				      const char *buf, size_t count)
399 {
400 	struct iommu_group_attribute *attr = to_iommu_group_attr(__attr);
401 	struct iommu_group *group = to_iommu_group(kobj);
402 	ssize_t ret = -EIO;
403 
404 	if (attr->store)
405 		ret = attr->store(group, buf, count);
406 	return ret;
407 }
408 
409 static const struct sysfs_ops iommu_group_sysfs_ops = {
410 	.show = iommu_group_attr_show,
411 	.store = iommu_group_attr_store,
412 };
413 
414 static int iommu_group_create_file(struct iommu_group *group,
415 				   struct iommu_group_attribute *attr)
416 {
417 	return sysfs_create_file(&group->kobj, &attr->attr);
418 }
419 
420 static void iommu_group_remove_file(struct iommu_group *group,
421 				    struct iommu_group_attribute *attr)
422 {
423 	sysfs_remove_file(&group->kobj, &attr->attr);
424 }
425 
426 static ssize_t iommu_group_show_name(struct iommu_group *group, char *buf)
427 {
428 	return sprintf(buf, "%s\n", group->name);
429 }
430 
431 /**
432  * iommu_insert_resv_region - Insert a new region in the
433  * list of reserved regions.
434  * @new: new region to insert
435  * @regions: list of regions
436  *
437  * Elements are sorted by start address and overlapping segments
438  * of the same type are merged.
439  */
440 static int iommu_insert_resv_region(struct iommu_resv_region *new,
441 				    struct list_head *regions)
442 {
443 	struct iommu_resv_region *iter, *tmp, *nr, *top;
444 	LIST_HEAD(stack);
445 
446 	nr = iommu_alloc_resv_region(new->start, new->length,
447 				     new->prot, new->type);
448 	if (!nr)
449 		return -ENOMEM;
450 
451 	/* First add the new element based on start address sorting */
452 	list_for_each_entry(iter, regions, list) {
453 		if (nr->start < iter->start ||
454 		    (nr->start == iter->start && nr->type <= iter->type))
455 			break;
456 	}
457 	list_add_tail(&nr->list, &iter->list);
458 
459 	/* Merge overlapping segments of type nr->type in @regions, if any */
460 	list_for_each_entry_safe(iter, tmp, regions, list) {
461 		phys_addr_t top_end, iter_end = iter->start + iter->length - 1;
462 
463 		/* no merge needed on elements of different types than @new */
464 		if (iter->type != new->type) {
465 			list_move_tail(&iter->list, &stack);
466 			continue;
467 		}
468 
469 		/* look for the last stack element of same type as @iter */
470 		list_for_each_entry_reverse(top, &stack, list)
471 			if (top->type == iter->type)
472 				goto check_overlap;
473 
474 		list_move_tail(&iter->list, &stack);
475 		continue;
476 
477 check_overlap:
478 		top_end = top->start + top->length - 1;
479 
480 		if (iter->start > top_end + 1) {
481 			list_move_tail(&iter->list, &stack);
482 		} else {
483 			top->length = max(top_end, iter_end) - top->start + 1;
484 			list_del(&iter->list);
485 			kfree(iter);
486 		}
487 	}
488 	list_splice(&stack, regions);
489 	return 0;
490 }
491 
492 static int
493 iommu_insert_device_resv_regions(struct list_head *dev_resv_regions,
494 				 struct list_head *group_resv_regions)
495 {
496 	struct iommu_resv_region *entry;
497 	int ret = 0;
498 
499 	list_for_each_entry(entry, dev_resv_regions, list) {
500 		ret = iommu_insert_resv_region(entry, group_resv_regions);
501 		if (ret)
502 			break;
503 	}
504 	return ret;
505 }
506 
507 int iommu_get_group_resv_regions(struct iommu_group *group,
508 				 struct list_head *head)
509 {
510 	struct group_device *device;
511 	int ret = 0;
512 
513 	mutex_lock(&group->mutex);
514 	list_for_each_entry(device, &group->devices, list) {
515 		struct list_head dev_resv_regions;
516 
517 		/*
518 		 * Non-API groups still expose reserved_regions in sysfs,
519 		 * so filter out calls that get here that way.
520 		 */
521 		if (!device->dev->iommu)
522 			break;
523 
524 		INIT_LIST_HEAD(&dev_resv_regions);
525 		iommu_get_resv_regions(device->dev, &dev_resv_regions);
526 		ret = iommu_insert_device_resv_regions(&dev_resv_regions, head);
527 		iommu_put_resv_regions(device->dev, &dev_resv_regions);
528 		if (ret)
529 			break;
530 	}
531 	mutex_unlock(&group->mutex);
532 	return ret;
533 }
534 EXPORT_SYMBOL_GPL(iommu_get_group_resv_regions);
535 
536 static ssize_t iommu_group_show_resv_regions(struct iommu_group *group,
537 					     char *buf)
538 {
539 	struct iommu_resv_region *region, *next;
540 	struct list_head group_resv_regions;
541 	char *str = buf;
542 
543 	INIT_LIST_HEAD(&group_resv_regions);
544 	iommu_get_group_resv_regions(group, &group_resv_regions);
545 
546 	list_for_each_entry_safe(region, next, &group_resv_regions, list) {
547 		str += sprintf(str, "0x%016llx 0x%016llx %s\n",
548 			       (long long int)region->start,
549 			       (long long int)(region->start +
550 						region->length - 1),
551 			       iommu_group_resv_type_string[region->type]);
552 		kfree(region);
553 	}
554 
555 	return (str - buf);
556 }
557 
558 static ssize_t iommu_group_show_type(struct iommu_group *group,
559 				     char *buf)
560 {
561 	char *type = "unknown\n";
562 
563 	mutex_lock(&group->mutex);
564 	if (group->default_domain) {
565 		switch (group->default_domain->type) {
566 		case IOMMU_DOMAIN_BLOCKED:
567 			type = "blocked\n";
568 			break;
569 		case IOMMU_DOMAIN_IDENTITY:
570 			type = "identity\n";
571 			break;
572 		case IOMMU_DOMAIN_UNMANAGED:
573 			type = "unmanaged\n";
574 			break;
575 		case IOMMU_DOMAIN_DMA:
576 			type = "DMA\n";
577 			break;
578 		case IOMMU_DOMAIN_DMA_FQ:
579 			type = "DMA-FQ\n";
580 			break;
581 		}
582 	}
583 	mutex_unlock(&group->mutex);
584 	strcpy(buf, type);
585 
586 	return strlen(type);
587 }
588 
589 static IOMMU_GROUP_ATTR(name, S_IRUGO, iommu_group_show_name, NULL);
590 
591 static IOMMU_GROUP_ATTR(reserved_regions, 0444,
592 			iommu_group_show_resv_regions, NULL);
593 
594 static IOMMU_GROUP_ATTR(type, 0644, iommu_group_show_type,
595 			iommu_group_store_type);
596 
597 static void iommu_group_release(struct kobject *kobj)
598 {
599 	struct iommu_group *group = to_iommu_group(kobj);
600 
601 	pr_debug("Releasing group %d\n", group->id);
602 
603 	if (group->iommu_data_release)
604 		group->iommu_data_release(group->iommu_data);
605 
606 	ida_free(&iommu_group_ida, group->id);
607 
608 	if (group->default_domain)
609 		iommu_domain_free(group->default_domain);
610 	if (group->blocking_domain)
611 		iommu_domain_free(group->blocking_domain);
612 
613 	kfree(group->name);
614 	kfree(group);
615 }
616 
617 static struct kobj_type iommu_group_ktype = {
618 	.sysfs_ops = &iommu_group_sysfs_ops,
619 	.release = iommu_group_release,
620 };
621 
622 /**
623  * iommu_group_alloc - Allocate a new group
624  *
625  * This function is called by an iommu driver to allocate a new iommu
626  * group.  The iommu group represents the minimum granularity of the iommu.
627  * Upon successful return, the caller holds a reference to the supplied
628  * group in order to hold the group until devices are added.  Use
629  * iommu_group_put() to release this extra reference count, allowing the
630  * group to be automatically reclaimed once it has no devices or external
631  * references.
632  */
633 struct iommu_group *iommu_group_alloc(void)
634 {
635 	struct iommu_group *group;
636 	int ret;
637 
638 	group = kzalloc(sizeof(*group), GFP_KERNEL);
639 	if (!group)
640 		return ERR_PTR(-ENOMEM);
641 
642 	group->kobj.kset = iommu_group_kset;
643 	mutex_init(&group->mutex);
644 	INIT_LIST_HEAD(&group->devices);
645 	INIT_LIST_HEAD(&group->entry);
646 
647 	ret = ida_alloc(&iommu_group_ida, GFP_KERNEL);
648 	if (ret < 0) {
649 		kfree(group);
650 		return ERR_PTR(ret);
651 	}
652 	group->id = ret;
653 
654 	ret = kobject_init_and_add(&group->kobj, &iommu_group_ktype,
655 				   NULL, "%d", group->id);
656 	if (ret) {
657 		ida_free(&iommu_group_ida, group->id);
658 		kobject_put(&group->kobj);
659 		return ERR_PTR(ret);
660 	}
661 
662 	group->devices_kobj = kobject_create_and_add("devices", &group->kobj);
663 	if (!group->devices_kobj) {
664 		kobject_put(&group->kobj); /* triggers .release & free */
665 		return ERR_PTR(-ENOMEM);
666 	}
667 
668 	/*
669 	 * The devices_kobj holds a reference on the group kobject, so
670 	 * as long as that exists so will the group.  We can therefore
671 	 * use the devices_kobj for reference counting.
672 	 */
673 	kobject_put(&group->kobj);
674 
675 	ret = iommu_group_create_file(group,
676 				      &iommu_group_attr_reserved_regions);
677 	if (ret)
678 		return ERR_PTR(ret);
679 
680 	ret = iommu_group_create_file(group, &iommu_group_attr_type);
681 	if (ret)
682 		return ERR_PTR(ret);
683 
684 	pr_debug("Allocated group %d\n", group->id);
685 
686 	return group;
687 }
688 EXPORT_SYMBOL_GPL(iommu_group_alloc);
689 
690 struct iommu_group *iommu_group_get_by_id(int id)
691 {
692 	struct kobject *group_kobj;
693 	struct iommu_group *group;
694 	const char *name;
695 
696 	if (!iommu_group_kset)
697 		return NULL;
698 
699 	name = kasprintf(GFP_KERNEL, "%d", id);
700 	if (!name)
701 		return NULL;
702 
703 	group_kobj = kset_find_obj(iommu_group_kset, name);
704 	kfree(name);
705 
706 	if (!group_kobj)
707 		return NULL;
708 
709 	group = container_of(group_kobj, struct iommu_group, kobj);
710 	BUG_ON(group->id != id);
711 
712 	kobject_get(group->devices_kobj);
713 	kobject_put(&group->kobj);
714 
715 	return group;
716 }
717 EXPORT_SYMBOL_GPL(iommu_group_get_by_id);
718 
719 /**
720  * iommu_group_get_iommudata - retrieve iommu_data registered for a group
721  * @group: the group
722  *
723  * iommu drivers can store data in the group for use when doing iommu
724  * operations.  This function provides a way to retrieve it.  Caller
725  * should hold a group reference.
726  */
727 void *iommu_group_get_iommudata(struct iommu_group *group)
728 {
729 	return group->iommu_data;
730 }
731 EXPORT_SYMBOL_GPL(iommu_group_get_iommudata);
732 
733 /**
734  * iommu_group_set_iommudata - set iommu_data for a group
735  * @group: the group
736  * @iommu_data: new data
737  * @release: release function for iommu_data
738  *
739  * iommu drivers can store data in the group for use when doing iommu
740  * operations.  This function provides a way to set the data after
741  * the group has been allocated.  Caller should hold a group reference.
742  */
743 void iommu_group_set_iommudata(struct iommu_group *group, void *iommu_data,
744 			       void (*release)(void *iommu_data))
745 {
746 	group->iommu_data = iommu_data;
747 	group->iommu_data_release = release;
748 }
749 EXPORT_SYMBOL_GPL(iommu_group_set_iommudata);
750 
751 /**
752  * iommu_group_set_name - set name for a group
753  * @group: the group
754  * @name: name
755  *
756  * Allow iommu driver to set a name for a group.  When set it will
757  * appear in a name attribute file under the group in sysfs.
758  */
759 int iommu_group_set_name(struct iommu_group *group, const char *name)
760 {
761 	int ret;
762 
763 	if (group->name) {
764 		iommu_group_remove_file(group, &iommu_group_attr_name);
765 		kfree(group->name);
766 		group->name = NULL;
767 		if (!name)
768 			return 0;
769 	}
770 
771 	group->name = kstrdup(name, GFP_KERNEL);
772 	if (!group->name)
773 		return -ENOMEM;
774 
775 	ret = iommu_group_create_file(group, &iommu_group_attr_name);
776 	if (ret) {
777 		kfree(group->name);
778 		group->name = NULL;
779 		return ret;
780 	}
781 
782 	return 0;
783 }
784 EXPORT_SYMBOL_GPL(iommu_group_set_name);
785 
786 static int iommu_create_device_direct_mappings(struct iommu_group *group,
787 					       struct device *dev)
788 {
789 	struct iommu_domain *domain = group->default_domain;
790 	struct iommu_resv_region *entry;
791 	struct list_head mappings;
792 	unsigned long pg_size;
793 	int ret = 0;
794 
795 	if (!domain || !iommu_is_dma_domain(domain))
796 		return 0;
797 
798 	BUG_ON(!domain->pgsize_bitmap);
799 
800 	pg_size = 1UL << __ffs(domain->pgsize_bitmap);
801 	INIT_LIST_HEAD(&mappings);
802 
803 	iommu_get_resv_regions(dev, &mappings);
804 
805 	/* We need to consider overlapping regions for different devices */
806 	list_for_each_entry(entry, &mappings, list) {
807 		dma_addr_t start, end, addr;
808 		size_t map_size = 0;
809 
810 		start = ALIGN(entry->start, pg_size);
811 		end   = ALIGN(entry->start + entry->length, pg_size);
812 
813 		if (entry->type != IOMMU_RESV_DIRECT &&
814 		    entry->type != IOMMU_RESV_DIRECT_RELAXABLE)
815 			continue;
816 
817 		for (addr = start; addr <= end; addr += pg_size) {
818 			phys_addr_t phys_addr;
819 
820 			if (addr == end)
821 				goto map_end;
822 
823 			phys_addr = iommu_iova_to_phys(domain, addr);
824 			if (!phys_addr) {
825 				map_size += pg_size;
826 				continue;
827 			}
828 
829 map_end:
830 			if (map_size) {
831 				ret = iommu_map(domain, addr - map_size,
832 						addr - map_size, map_size,
833 						entry->prot);
834 				if (ret)
835 					goto out;
836 				map_size = 0;
837 			}
838 		}
839 
840 	}
841 
842 	iommu_flush_iotlb_all(domain);
843 
844 out:
845 	iommu_put_resv_regions(dev, &mappings);
846 
847 	return ret;
848 }
849 
850 static bool iommu_is_attach_deferred(struct device *dev)
851 {
852 	const struct iommu_ops *ops = dev_iommu_ops(dev);
853 
854 	if (ops->is_attach_deferred)
855 		return ops->is_attach_deferred(dev);
856 
857 	return false;
858 }
859 
860 /**
861  * iommu_group_add_device - add a device to an iommu group
862  * @group: the group into which to add the device (reference should be held)
863  * @dev: the device
864  *
865  * This function is called by an iommu driver to add a device into a
866  * group.  Adding a device increments the group reference count.
867  */
868 int iommu_group_add_device(struct iommu_group *group, struct device *dev)
869 {
870 	int ret, i = 0;
871 	struct group_device *device;
872 
873 	device = kzalloc(sizeof(*device), GFP_KERNEL);
874 	if (!device)
875 		return -ENOMEM;
876 
877 	device->dev = dev;
878 
879 	ret = sysfs_create_link(&dev->kobj, &group->kobj, "iommu_group");
880 	if (ret)
881 		goto err_free_device;
882 
883 	device->name = kasprintf(GFP_KERNEL, "%s", kobject_name(&dev->kobj));
884 rename:
885 	if (!device->name) {
886 		ret = -ENOMEM;
887 		goto err_remove_link;
888 	}
889 
890 	ret = sysfs_create_link_nowarn(group->devices_kobj,
891 				       &dev->kobj, device->name);
892 	if (ret) {
893 		if (ret == -EEXIST && i >= 0) {
894 			/*
895 			 * Account for the slim chance of collision
896 			 * and append an instance to the name.
897 			 */
898 			kfree(device->name);
899 			device->name = kasprintf(GFP_KERNEL, "%s.%d",
900 						 kobject_name(&dev->kobj), i++);
901 			goto rename;
902 		}
903 		goto err_free_name;
904 	}
905 
906 	kobject_get(group->devices_kobj);
907 
908 	dev->iommu_group = group;
909 
910 	mutex_lock(&group->mutex);
911 	list_add_tail(&device->list, &group->devices);
912 	if (group->domain  && !iommu_is_attach_deferred(dev))
913 		ret = __iommu_attach_device(group->domain, dev);
914 	mutex_unlock(&group->mutex);
915 	if (ret)
916 		goto err_put_group;
917 
918 	trace_add_device_to_group(group->id, dev);
919 
920 	dev_info(dev, "Adding to iommu group %d\n", group->id);
921 
922 	return 0;
923 
924 err_put_group:
925 	mutex_lock(&group->mutex);
926 	list_del(&device->list);
927 	mutex_unlock(&group->mutex);
928 	dev->iommu_group = NULL;
929 	kobject_put(group->devices_kobj);
930 	sysfs_remove_link(group->devices_kobj, device->name);
931 err_free_name:
932 	kfree(device->name);
933 err_remove_link:
934 	sysfs_remove_link(&dev->kobj, "iommu_group");
935 err_free_device:
936 	kfree(device);
937 	dev_err(dev, "Failed to add to iommu group %d: %d\n", group->id, ret);
938 	return ret;
939 }
940 EXPORT_SYMBOL_GPL(iommu_group_add_device);
941 
942 /**
943  * iommu_group_remove_device - remove a device from it's current group
944  * @dev: device to be removed
945  *
946  * This function is called by an iommu driver to remove the device from
947  * it's current group.  This decrements the iommu group reference count.
948  */
949 void iommu_group_remove_device(struct device *dev)
950 {
951 	struct iommu_group *group = dev->iommu_group;
952 	struct group_device *tmp_device, *device = NULL;
953 
954 	if (!group)
955 		return;
956 
957 	dev_info(dev, "Removing from iommu group %d\n", group->id);
958 
959 	mutex_lock(&group->mutex);
960 	list_for_each_entry(tmp_device, &group->devices, list) {
961 		if (tmp_device->dev == dev) {
962 			device = tmp_device;
963 			list_del(&device->list);
964 			break;
965 		}
966 	}
967 	mutex_unlock(&group->mutex);
968 
969 	if (!device)
970 		return;
971 
972 	sysfs_remove_link(group->devices_kobj, device->name);
973 	sysfs_remove_link(&dev->kobj, "iommu_group");
974 
975 	trace_remove_device_from_group(group->id, dev);
976 
977 	kfree(device->name);
978 	kfree(device);
979 	dev->iommu_group = NULL;
980 	kobject_put(group->devices_kobj);
981 }
982 EXPORT_SYMBOL_GPL(iommu_group_remove_device);
983 
984 static int iommu_group_device_count(struct iommu_group *group)
985 {
986 	struct group_device *entry;
987 	int ret = 0;
988 
989 	list_for_each_entry(entry, &group->devices, list)
990 		ret++;
991 
992 	return ret;
993 }
994 
995 static int __iommu_group_for_each_dev(struct iommu_group *group, void *data,
996 				      int (*fn)(struct device *, void *))
997 {
998 	struct group_device *device;
999 	int ret = 0;
1000 
1001 	list_for_each_entry(device, &group->devices, list) {
1002 		ret = fn(device->dev, data);
1003 		if (ret)
1004 			break;
1005 	}
1006 	return ret;
1007 }
1008 
1009 /**
1010  * iommu_group_for_each_dev - iterate over each device in the group
1011  * @group: the group
1012  * @data: caller opaque data to be passed to callback function
1013  * @fn: caller supplied callback function
1014  *
1015  * This function is called by group users to iterate over group devices.
1016  * Callers should hold a reference count to the group during callback.
1017  * The group->mutex is held across callbacks, which will block calls to
1018  * iommu_group_add/remove_device.
1019  */
1020 int iommu_group_for_each_dev(struct iommu_group *group, void *data,
1021 			     int (*fn)(struct device *, void *))
1022 {
1023 	int ret;
1024 
1025 	mutex_lock(&group->mutex);
1026 	ret = __iommu_group_for_each_dev(group, data, fn);
1027 	mutex_unlock(&group->mutex);
1028 
1029 	return ret;
1030 }
1031 EXPORT_SYMBOL_GPL(iommu_group_for_each_dev);
1032 
1033 /**
1034  * iommu_group_get - Return the group for a device and increment reference
1035  * @dev: get the group that this device belongs to
1036  *
1037  * This function is called by iommu drivers and users to get the group
1038  * for the specified device.  If found, the group is returned and the group
1039  * reference in incremented, else NULL.
1040  */
1041 struct iommu_group *iommu_group_get(struct device *dev)
1042 {
1043 	struct iommu_group *group = dev->iommu_group;
1044 
1045 	if (group)
1046 		kobject_get(group->devices_kobj);
1047 
1048 	return group;
1049 }
1050 EXPORT_SYMBOL_GPL(iommu_group_get);
1051 
1052 /**
1053  * iommu_group_ref_get - Increment reference on a group
1054  * @group: the group to use, must not be NULL
1055  *
1056  * This function is called by iommu drivers to take additional references on an
1057  * existing group.  Returns the given group for convenience.
1058  */
1059 struct iommu_group *iommu_group_ref_get(struct iommu_group *group)
1060 {
1061 	kobject_get(group->devices_kobj);
1062 	return group;
1063 }
1064 EXPORT_SYMBOL_GPL(iommu_group_ref_get);
1065 
1066 /**
1067  * iommu_group_put - Decrement group reference
1068  * @group: the group to use
1069  *
1070  * This function is called by iommu drivers and users to release the
1071  * iommu group.  Once the reference count is zero, the group is released.
1072  */
1073 void iommu_group_put(struct iommu_group *group)
1074 {
1075 	if (group)
1076 		kobject_put(group->devices_kobj);
1077 }
1078 EXPORT_SYMBOL_GPL(iommu_group_put);
1079 
1080 /**
1081  * iommu_register_device_fault_handler() - Register a device fault handler
1082  * @dev: the device
1083  * @handler: the fault handler
1084  * @data: private data passed as argument to the handler
1085  *
1086  * When an IOMMU fault event is received, this handler gets called with the
1087  * fault event and data as argument. The handler should return 0 on success. If
1088  * the fault is recoverable (IOMMU_FAULT_PAGE_REQ), the consumer should also
1089  * complete the fault by calling iommu_page_response() with one of the following
1090  * response code:
1091  * - IOMMU_PAGE_RESP_SUCCESS: retry the translation
1092  * - IOMMU_PAGE_RESP_INVALID: terminate the fault
1093  * - IOMMU_PAGE_RESP_FAILURE: terminate the fault and stop reporting
1094  *   page faults if possible.
1095  *
1096  * Return 0 if the fault handler was installed successfully, or an error.
1097  */
1098 int iommu_register_device_fault_handler(struct device *dev,
1099 					iommu_dev_fault_handler_t handler,
1100 					void *data)
1101 {
1102 	struct dev_iommu *param = dev->iommu;
1103 	int ret = 0;
1104 
1105 	if (!param)
1106 		return -EINVAL;
1107 
1108 	mutex_lock(&param->lock);
1109 	/* Only allow one fault handler registered for each device */
1110 	if (param->fault_param) {
1111 		ret = -EBUSY;
1112 		goto done_unlock;
1113 	}
1114 
1115 	get_device(dev);
1116 	param->fault_param = kzalloc(sizeof(*param->fault_param), GFP_KERNEL);
1117 	if (!param->fault_param) {
1118 		put_device(dev);
1119 		ret = -ENOMEM;
1120 		goto done_unlock;
1121 	}
1122 	param->fault_param->handler = handler;
1123 	param->fault_param->data = data;
1124 	mutex_init(&param->fault_param->lock);
1125 	INIT_LIST_HEAD(&param->fault_param->faults);
1126 
1127 done_unlock:
1128 	mutex_unlock(&param->lock);
1129 
1130 	return ret;
1131 }
1132 EXPORT_SYMBOL_GPL(iommu_register_device_fault_handler);
1133 
1134 /**
1135  * iommu_unregister_device_fault_handler() - Unregister the device fault handler
1136  * @dev: the device
1137  *
1138  * Remove the device fault handler installed with
1139  * iommu_register_device_fault_handler().
1140  *
1141  * Return 0 on success, or an error.
1142  */
1143 int iommu_unregister_device_fault_handler(struct device *dev)
1144 {
1145 	struct dev_iommu *param = dev->iommu;
1146 	int ret = 0;
1147 
1148 	if (!param)
1149 		return -EINVAL;
1150 
1151 	mutex_lock(&param->lock);
1152 
1153 	if (!param->fault_param)
1154 		goto unlock;
1155 
1156 	/* we cannot unregister handler if there are pending faults */
1157 	if (!list_empty(&param->fault_param->faults)) {
1158 		ret = -EBUSY;
1159 		goto unlock;
1160 	}
1161 
1162 	kfree(param->fault_param);
1163 	param->fault_param = NULL;
1164 	put_device(dev);
1165 unlock:
1166 	mutex_unlock(&param->lock);
1167 
1168 	return ret;
1169 }
1170 EXPORT_SYMBOL_GPL(iommu_unregister_device_fault_handler);
1171 
1172 /**
1173  * iommu_report_device_fault() - Report fault event to device driver
1174  * @dev: the device
1175  * @evt: fault event data
1176  *
1177  * Called by IOMMU drivers when a fault is detected, typically in a threaded IRQ
1178  * handler. When this function fails and the fault is recoverable, it is the
1179  * caller's responsibility to complete the fault.
1180  *
1181  * Return 0 on success, or an error.
1182  */
1183 int iommu_report_device_fault(struct device *dev, struct iommu_fault_event *evt)
1184 {
1185 	struct dev_iommu *param = dev->iommu;
1186 	struct iommu_fault_event *evt_pending = NULL;
1187 	struct iommu_fault_param *fparam;
1188 	int ret = 0;
1189 
1190 	if (!param || !evt)
1191 		return -EINVAL;
1192 
1193 	/* we only report device fault if there is a handler registered */
1194 	mutex_lock(&param->lock);
1195 	fparam = param->fault_param;
1196 	if (!fparam || !fparam->handler) {
1197 		ret = -EINVAL;
1198 		goto done_unlock;
1199 	}
1200 
1201 	if (evt->fault.type == IOMMU_FAULT_PAGE_REQ &&
1202 	    (evt->fault.prm.flags & IOMMU_FAULT_PAGE_REQUEST_LAST_PAGE)) {
1203 		evt_pending = kmemdup(evt, sizeof(struct iommu_fault_event),
1204 				      GFP_KERNEL);
1205 		if (!evt_pending) {
1206 			ret = -ENOMEM;
1207 			goto done_unlock;
1208 		}
1209 		mutex_lock(&fparam->lock);
1210 		list_add_tail(&evt_pending->list, &fparam->faults);
1211 		mutex_unlock(&fparam->lock);
1212 	}
1213 
1214 	ret = fparam->handler(&evt->fault, fparam->data);
1215 	if (ret && evt_pending) {
1216 		mutex_lock(&fparam->lock);
1217 		list_del(&evt_pending->list);
1218 		mutex_unlock(&fparam->lock);
1219 		kfree(evt_pending);
1220 	}
1221 done_unlock:
1222 	mutex_unlock(&param->lock);
1223 	return ret;
1224 }
1225 EXPORT_SYMBOL_GPL(iommu_report_device_fault);
1226 
1227 int iommu_page_response(struct device *dev,
1228 			struct iommu_page_response *msg)
1229 {
1230 	bool needs_pasid;
1231 	int ret = -EINVAL;
1232 	struct iommu_fault_event *evt;
1233 	struct iommu_fault_page_request *prm;
1234 	struct dev_iommu *param = dev->iommu;
1235 	const struct iommu_ops *ops = dev_iommu_ops(dev);
1236 	bool has_pasid = msg->flags & IOMMU_PAGE_RESP_PASID_VALID;
1237 
1238 	if (!ops->page_response)
1239 		return -ENODEV;
1240 
1241 	if (!param || !param->fault_param)
1242 		return -EINVAL;
1243 
1244 	if (msg->version != IOMMU_PAGE_RESP_VERSION_1 ||
1245 	    msg->flags & ~IOMMU_PAGE_RESP_PASID_VALID)
1246 		return -EINVAL;
1247 
1248 	/* Only send response if there is a fault report pending */
1249 	mutex_lock(&param->fault_param->lock);
1250 	if (list_empty(&param->fault_param->faults)) {
1251 		dev_warn_ratelimited(dev, "no pending PRQ, drop response\n");
1252 		goto done_unlock;
1253 	}
1254 	/*
1255 	 * Check if we have a matching page request pending to respond,
1256 	 * otherwise return -EINVAL
1257 	 */
1258 	list_for_each_entry(evt, &param->fault_param->faults, list) {
1259 		prm = &evt->fault.prm;
1260 		if (prm->grpid != msg->grpid)
1261 			continue;
1262 
1263 		/*
1264 		 * If the PASID is required, the corresponding request is
1265 		 * matched using the group ID, the PASID valid bit and the PASID
1266 		 * value. Otherwise only the group ID matches request and
1267 		 * response.
1268 		 */
1269 		needs_pasid = prm->flags & IOMMU_FAULT_PAGE_RESPONSE_NEEDS_PASID;
1270 		if (needs_pasid && (!has_pasid || msg->pasid != prm->pasid))
1271 			continue;
1272 
1273 		if (!needs_pasid && has_pasid) {
1274 			/* No big deal, just clear it. */
1275 			msg->flags &= ~IOMMU_PAGE_RESP_PASID_VALID;
1276 			msg->pasid = 0;
1277 		}
1278 
1279 		ret = ops->page_response(dev, evt, msg);
1280 		list_del(&evt->list);
1281 		kfree(evt);
1282 		break;
1283 	}
1284 
1285 done_unlock:
1286 	mutex_unlock(&param->fault_param->lock);
1287 	return ret;
1288 }
1289 EXPORT_SYMBOL_GPL(iommu_page_response);
1290 
1291 /**
1292  * iommu_group_id - Return ID for a group
1293  * @group: the group to ID
1294  *
1295  * Return the unique ID for the group matching the sysfs group number.
1296  */
1297 int iommu_group_id(struct iommu_group *group)
1298 {
1299 	return group->id;
1300 }
1301 EXPORT_SYMBOL_GPL(iommu_group_id);
1302 
1303 static struct iommu_group *get_pci_alias_group(struct pci_dev *pdev,
1304 					       unsigned long *devfns);
1305 
1306 /*
1307  * To consider a PCI device isolated, we require ACS to support Source
1308  * Validation, Request Redirection, Completer Redirection, and Upstream
1309  * Forwarding.  This effectively means that devices cannot spoof their
1310  * requester ID, requests and completions cannot be redirected, and all
1311  * transactions are forwarded upstream, even as it passes through a
1312  * bridge where the target device is downstream.
1313  */
1314 #define REQ_ACS_FLAGS   (PCI_ACS_SV | PCI_ACS_RR | PCI_ACS_CR | PCI_ACS_UF)
1315 
1316 /*
1317  * For multifunction devices which are not isolated from each other, find
1318  * all the other non-isolated functions and look for existing groups.  For
1319  * each function, we also need to look for aliases to or from other devices
1320  * that may already have a group.
1321  */
1322 static struct iommu_group *get_pci_function_alias_group(struct pci_dev *pdev,
1323 							unsigned long *devfns)
1324 {
1325 	struct pci_dev *tmp = NULL;
1326 	struct iommu_group *group;
1327 
1328 	if (!pdev->multifunction || pci_acs_enabled(pdev, REQ_ACS_FLAGS))
1329 		return NULL;
1330 
1331 	for_each_pci_dev(tmp) {
1332 		if (tmp == pdev || tmp->bus != pdev->bus ||
1333 		    PCI_SLOT(tmp->devfn) != PCI_SLOT(pdev->devfn) ||
1334 		    pci_acs_enabled(tmp, REQ_ACS_FLAGS))
1335 			continue;
1336 
1337 		group = get_pci_alias_group(tmp, devfns);
1338 		if (group) {
1339 			pci_dev_put(tmp);
1340 			return group;
1341 		}
1342 	}
1343 
1344 	return NULL;
1345 }
1346 
1347 /*
1348  * Look for aliases to or from the given device for existing groups. DMA
1349  * aliases are only supported on the same bus, therefore the search
1350  * space is quite small (especially since we're really only looking at pcie
1351  * device, and therefore only expect multiple slots on the root complex or
1352  * downstream switch ports).  It's conceivable though that a pair of
1353  * multifunction devices could have aliases between them that would cause a
1354  * loop.  To prevent this, we use a bitmap to track where we've been.
1355  */
1356 static struct iommu_group *get_pci_alias_group(struct pci_dev *pdev,
1357 					       unsigned long *devfns)
1358 {
1359 	struct pci_dev *tmp = NULL;
1360 	struct iommu_group *group;
1361 
1362 	if (test_and_set_bit(pdev->devfn & 0xff, devfns))
1363 		return NULL;
1364 
1365 	group = iommu_group_get(&pdev->dev);
1366 	if (group)
1367 		return group;
1368 
1369 	for_each_pci_dev(tmp) {
1370 		if (tmp == pdev || tmp->bus != pdev->bus)
1371 			continue;
1372 
1373 		/* We alias them or they alias us */
1374 		if (pci_devs_are_dma_aliases(pdev, tmp)) {
1375 			group = get_pci_alias_group(tmp, devfns);
1376 			if (group) {
1377 				pci_dev_put(tmp);
1378 				return group;
1379 			}
1380 
1381 			group = get_pci_function_alias_group(tmp, devfns);
1382 			if (group) {
1383 				pci_dev_put(tmp);
1384 				return group;
1385 			}
1386 		}
1387 	}
1388 
1389 	return NULL;
1390 }
1391 
1392 struct group_for_pci_data {
1393 	struct pci_dev *pdev;
1394 	struct iommu_group *group;
1395 };
1396 
1397 /*
1398  * DMA alias iterator callback, return the last seen device.  Stop and return
1399  * the IOMMU group if we find one along the way.
1400  */
1401 static int get_pci_alias_or_group(struct pci_dev *pdev, u16 alias, void *opaque)
1402 {
1403 	struct group_for_pci_data *data = opaque;
1404 
1405 	data->pdev = pdev;
1406 	data->group = iommu_group_get(&pdev->dev);
1407 
1408 	return data->group != NULL;
1409 }
1410 
1411 /*
1412  * Generic device_group call-back function. It just allocates one
1413  * iommu-group per device.
1414  */
1415 struct iommu_group *generic_device_group(struct device *dev)
1416 {
1417 	return iommu_group_alloc();
1418 }
1419 EXPORT_SYMBOL_GPL(generic_device_group);
1420 
1421 /*
1422  * Use standard PCI bus topology, isolation features, and DMA alias quirks
1423  * to find or create an IOMMU group for a device.
1424  */
1425 struct iommu_group *pci_device_group(struct device *dev)
1426 {
1427 	struct pci_dev *pdev = to_pci_dev(dev);
1428 	struct group_for_pci_data data;
1429 	struct pci_bus *bus;
1430 	struct iommu_group *group = NULL;
1431 	u64 devfns[4] = { 0 };
1432 
1433 	if (WARN_ON(!dev_is_pci(dev)))
1434 		return ERR_PTR(-EINVAL);
1435 
1436 	/*
1437 	 * Find the upstream DMA alias for the device.  A device must not
1438 	 * be aliased due to topology in order to have its own IOMMU group.
1439 	 * If we find an alias along the way that already belongs to a
1440 	 * group, use it.
1441 	 */
1442 	if (pci_for_each_dma_alias(pdev, get_pci_alias_or_group, &data))
1443 		return data.group;
1444 
1445 	pdev = data.pdev;
1446 
1447 	/*
1448 	 * Continue upstream from the point of minimum IOMMU granularity
1449 	 * due to aliases to the point where devices are protected from
1450 	 * peer-to-peer DMA by PCI ACS.  Again, if we find an existing
1451 	 * group, use it.
1452 	 */
1453 	for (bus = pdev->bus; !pci_is_root_bus(bus); bus = bus->parent) {
1454 		if (!bus->self)
1455 			continue;
1456 
1457 		if (pci_acs_path_enabled(bus->self, NULL, REQ_ACS_FLAGS))
1458 			break;
1459 
1460 		pdev = bus->self;
1461 
1462 		group = iommu_group_get(&pdev->dev);
1463 		if (group)
1464 			return group;
1465 	}
1466 
1467 	/*
1468 	 * Look for existing groups on device aliases.  If we alias another
1469 	 * device or another device aliases us, use the same group.
1470 	 */
1471 	group = get_pci_alias_group(pdev, (unsigned long *)devfns);
1472 	if (group)
1473 		return group;
1474 
1475 	/*
1476 	 * Look for existing groups on non-isolated functions on the same
1477 	 * slot and aliases of those funcions, if any.  No need to clear
1478 	 * the search bitmap, the tested devfns are still valid.
1479 	 */
1480 	group = get_pci_function_alias_group(pdev, (unsigned long *)devfns);
1481 	if (group)
1482 		return group;
1483 
1484 	/* No shared group found, allocate new */
1485 	return iommu_group_alloc();
1486 }
1487 EXPORT_SYMBOL_GPL(pci_device_group);
1488 
1489 /* Get the IOMMU group for device on fsl-mc bus */
1490 struct iommu_group *fsl_mc_device_group(struct device *dev)
1491 {
1492 	struct device *cont_dev = fsl_mc_cont_dev(dev);
1493 	struct iommu_group *group;
1494 
1495 	group = iommu_group_get(cont_dev);
1496 	if (!group)
1497 		group = iommu_group_alloc();
1498 	return group;
1499 }
1500 EXPORT_SYMBOL_GPL(fsl_mc_device_group);
1501 
1502 static int iommu_get_def_domain_type(struct device *dev)
1503 {
1504 	const struct iommu_ops *ops = dev_iommu_ops(dev);
1505 
1506 	if (dev_is_pci(dev) && to_pci_dev(dev)->untrusted)
1507 		return IOMMU_DOMAIN_DMA;
1508 
1509 	if (ops->def_domain_type)
1510 		return ops->def_domain_type(dev);
1511 
1512 	return 0;
1513 }
1514 
1515 static int iommu_group_alloc_default_domain(struct bus_type *bus,
1516 					    struct iommu_group *group,
1517 					    unsigned int type)
1518 {
1519 	struct iommu_domain *dom;
1520 
1521 	dom = __iommu_domain_alloc(bus, type);
1522 	if (!dom && type != IOMMU_DOMAIN_DMA) {
1523 		dom = __iommu_domain_alloc(bus, IOMMU_DOMAIN_DMA);
1524 		if (dom)
1525 			pr_warn("Failed to allocate default IOMMU domain of type %u for group %s - Falling back to IOMMU_DOMAIN_DMA",
1526 				type, group->name);
1527 	}
1528 
1529 	if (!dom)
1530 		return -ENOMEM;
1531 
1532 	group->default_domain = dom;
1533 	if (!group->domain)
1534 		group->domain = dom;
1535 	return 0;
1536 }
1537 
1538 static int iommu_alloc_default_domain(struct iommu_group *group,
1539 				      struct device *dev)
1540 {
1541 	unsigned int type;
1542 
1543 	if (group->default_domain)
1544 		return 0;
1545 
1546 	type = iommu_get_def_domain_type(dev) ? : iommu_def_domain_type;
1547 
1548 	return iommu_group_alloc_default_domain(dev->bus, group, type);
1549 }
1550 
1551 /**
1552  * iommu_group_get_for_dev - Find or create the IOMMU group for a device
1553  * @dev: target device
1554  *
1555  * This function is intended to be called by IOMMU drivers and extended to
1556  * support common, bus-defined algorithms when determining or creating the
1557  * IOMMU group for a device.  On success, the caller will hold a reference
1558  * to the returned IOMMU group, which will already include the provided
1559  * device.  The reference should be released with iommu_group_put().
1560  */
1561 static struct iommu_group *iommu_group_get_for_dev(struct device *dev)
1562 {
1563 	const struct iommu_ops *ops = dev_iommu_ops(dev);
1564 	struct iommu_group *group;
1565 	int ret;
1566 
1567 	group = iommu_group_get(dev);
1568 	if (group)
1569 		return group;
1570 
1571 	group = ops->device_group(dev);
1572 	if (WARN_ON_ONCE(group == NULL))
1573 		return ERR_PTR(-EINVAL);
1574 
1575 	if (IS_ERR(group))
1576 		return group;
1577 
1578 	ret = iommu_group_add_device(group, dev);
1579 	if (ret)
1580 		goto out_put_group;
1581 
1582 	return group;
1583 
1584 out_put_group:
1585 	iommu_group_put(group);
1586 
1587 	return ERR_PTR(ret);
1588 }
1589 
1590 struct iommu_domain *iommu_group_default_domain(struct iommu_group *group)
1591 {
1592 	return group->default_domain;
1593 }
1594 
1595 static int probe_iommu_group(struct device *dev, void *data)
1596 {
1597 	struct list_head *group_list = data;
1598 	struct iommu_group *group;
1599 	int ret;
1600 
1601 	/* Device is probed already if in a group */
1602 	group = iommu_group_get(dev);
1603 	if (group) {
1604 		iommu_group_put(group);
1605 		return 0;
1606 	}
1607 
1608 	ret = __iommu_probe_device(dev, group_list);
1609 	if (ret == -ENODEV)
1610 		ret = 0;
1611 
1612 	return ret;
1613 }
1614 
1615 static int remove_iommu_group(struct device *dev, void *data)
1616 {
1617 	iommu_release_device(dev);
1618 
1619 	return 0;
1620 }
1621 
1622 static int iommu_bus_notifier(struct notifier_block *nb,
1623 			      unsigned long action, void *data)
1624 {
1625 	struct device *dev = data;
1626 
1627 	if (action == BUS_NOTIFY_ADD_DEVICE) {
1628 		int ret;
1629 
1630 		ret = iommu_probe_device(dev);
1631 		return (ret) ? NOTIFY_DONE : NOTIFY_OK;
1632 	} else if (action == BUS_NOTIFY_REMOVED_DEVICE) {
1633 		iommu_release_device(dev);
1634 		return NOTIFY_OK;
1635 	}
1636 
1637 	return 0;
1638 }
1639 
1640 struct __group_domain_type {
1641 	struct device *dev;
1642 	unsigned int type;
1643 };
1644 
1645 static int probe_get_default_domain_type(struct device *dev, void *data)
1646 {
1647 	struct __group_domain_type *gtype = data;
1648 	unsigned int type = iommu_get_def_domain_type(dev);
1649 
1650 	if (type) {
1651 		if (gtype->type && gtype->type != type) {
1652 			dev_warn(dev, "Device needs domain type %s, but device %s in the same iommu group requires type %s - using default\n",
1653 				 iommu_domain_type_str(type),
1654 				 dev_name(gtype->dev),
1655 				 iommu_domain_type_str(gtype->type));
1656 			gtype->type = 0;
1657 		}
1658 
1659 		if (!gtype->dev) {
1660 			gtype->dev  = dev;
1661 			gtype->type = type;
1662 		}
1663 	}
1664 
1665 	return 0;
1666 }
1667 
1668 static void probe_alloc_default_domain(struct bus_type *bus,
1669 				       struct iommu_group *group)
1670 {
1671 	struct __group_domain_type gtype;
1672 
1673 	memset(&gtype, 0, sizeof(gtype));
1674 
1675 	/* Ask for default domain requirements of all devices in the group */
1676 	__iommu_group_for_each_dev(group, &gtype,
1677 				   probe_get_default_domain_type);
1678 
1679 	if (!gtype.type)
1680 		gtype.type = iommu_def_domain_type;
1681 
1682 	iommu_group_alloc_default_domain(bus, group, gtype.type);
1683 
1684 }
1685 
1686 static int iommu_group_do_dma_attach(struct device *dev, void *data)
1687 {
1688 	struct iommu_domain *domain = data;
1689 	int ret = 0;
1690 
1691 	if (!iommu_is_attach_deferred(dev))
1692 		ret = __iommu_attach_device(domain, dev);
1693 
1694 	return ret;
1695 }
1696 
1697 static int __iommu_group_dma_attach(struct iommu_group *group)
1698 {
1699 	return __iommu_group_for_each_dev(group, group->default_domain,
1700 					  iommu_group_do_dma_attach);
1701 }
1702 
1703 static int iommu_group_do_probe_finalize(struct device *dev, void *data)
1704 {
1705 	const struct iommu_ops *ops = dev_iommu_ops(dev);
1706 
1707 	if (ops->probe_finalize)
1708 		ops->probe_finalize(dev);
1709 
1710 	return 0;
1711 }
1712 
1713 static void __iommu_group_dma_finalize(struct iommu_group *group)
1714 {
1715 	__iommu_group_for_each_dev(group, group->default_domain,
1716 				   iommu_group_do_probe_finalize);
1717 }
1718 
1719 static int iommu_do_create_direct_mappings(struct device *dev, void *data)
1720 {
1721 	struct iommu_group *group = data;
1722 
1723 	iommu_create_device_direct_mappings(group, dev);
1724 
1725 	return 0;
1726 }
1727 
1728 static int iommu_group_create_direct_mappings(struct iommu_group *group)
1729 {
1730 	return __iommu_group_for_each_dev(group, group,
1731 					  iommu_do_create_direct_mappings);
1732 }
1733 
1734 int bus_iommu_probe(struct bus_type *bus)
1735 {
1736 	struct iommu_group *group, *next;
1737 	LIST_HEAD(group_list);
1738 	int ret;
1739 
1740 	/*
1741 	 * This code-path does not allocate the default domain when
1742 	 * creating the iommu group, so do it after the groups are
1743 	 * created.
1744 	 */
1745 	ret = bus_for_each_dev(bus, NULL, &group_list, probe_iommu_group);
1746 	if (ret)
1747 		return ret;
1748 
1749 	list_for_each_entry_safe(group, next, &group_list, entry) {
1750 		/* Remove item from the list */
1751 		list_del_init(&group->entry);
1752 
1753 		mutex_lock(&group->mutex);
1754 
1755 		/* Try to allocate default domain */
1756 		probe_alloc_default_domain(bus, group);
1757 
1758 		if (!group->default_domain) {
1759 			mutex_unlock(&group->mutex);
1760 			continue;
1761 		}
1762 
1763 		iommu_group_create_direct_mappings(group);
1764 
1765 		ret = __iommu_group_dma_attach(group);
1766 
1767 		mutex_unlock(&group->mutex);
1768 
1769 		if (ret)
1770 			break;
1771 
1772 		__iommu_group_dma_finalize(group);
1773 	}
1774 
1775 	return ret;
1776 }
1777 
1778 static int iommu_bus_init(struct bus_type *bus, const struct iommu_ops *ops)
1779 {
1780 	struct notifier_block *nb;
1781 	int err;
1782 
1783 	nb = kzalloc(sizeof(struct notifier_block), GFP_KERNEL);
1784 	if (!nb)
1785 		return -ENOMEM;
1786 
1787 	nb->notifier_call = iommu_bus_notifier;
1788 
1789 	err = bus_register_notifier(bus, nb);
1790 	if (err)
1791 		goto out_free;
1792 
1793 	err = bus_iommu_probe(bus);
1794 	if (err)
1795 		goto out_err;
1796 
1797 
1798 	return 0;
1799 
1800 out_err:
1801 	/* Clean up */
1802 	bus_for_each_dev(bus, NULL, NULL, remove_iommu_group);
1803 	bus_unregister_notifier(bus, nb);
1804 
1805 out_free:
1806 	kfree(nb);
1807 
1808 	return err;
1809 }
1810 
1811 /**
1812  * bus_set_iommu - set iommu-callbacks for the bus
1813  * @bus: bus.
1814  * @ops: the callbacks provided by the iommu-driver
1815  *
1816  * This function is called by an iommu driver to set the iommu methods
1817  * used for a particular bus. Drivers for devices on that bus can use
1818  * the iommu-api after these ops are registered.
1819  * This special function is needed because IOMMUs are usually devices on
1820  * the bus itself, so the iommu drivers are not initialized when the bus
1821  * is set up. With this function the iommu-driver can set the iommu-ops
1822  * afterwards.
1823  */
1824 int bus_set_iommu(struct bus_type *bus, const struct iommu_ops *ops)
1825 {
1826 	int err;
1827 
1828 	if (ops == NULL) {
1829 		bus->iommu_ops = NULL;
1830 		return 0;
1831 	}
1832 
1833 	if (bus->iommu_ops != NULL)
1834 		return -EBUSY;
1835 
1836 	bus->iommu_ops = ops;
1837 
1838 	/* Do IOMMU specific setup for this bus-type */
1839 	err = iommu_bus_init(bus, ops);
1840 	if (err)
1841 		bus->iommu_ops = NULL;
1842 
1843 	return err;
1844 }
1845 EXPORT_SYMBOL_GPL(bus_set_iommu);
1846 
1847 bool iommu_present(struct bus_type *bus)
1848 {
1849 	return bus->iommu_ops != NULL;
1850 }
1851 EXPORT_SYMBOL_GPL(iommu_present);
1852 
1853 /**
1854  * device_iommu_capable() - check for a general IOMMU capability
1855  * @dev: device to which the capability would be relevant, if available
1856  * @cap: IOMMU capability
1857  *
1858  * Return: true if an IOMMU is present and supports the given capability
1859  * for the given device, otherwise false.
1860  */
1861 bool device_iommu_capable(struct device *dev, enum iommu_cap cap)
1862 {
1863 	const struct iommu_ops *ops;
1864 
1865 	if (!dev->iommu || !dev->iommu->iommu_dev)
1866 		return false;
1867 
1868 	ops = dev_iommu_ops(dev);
1869 	if (!ops->capable)
1870 		return false;
1871 
1872 	return ops->capable(cap);
1873 }
1874 EXPORT_SYMBOL_GPL(device_iommu_capable);
1875 
1876 bool iommu_capable(struct bus_type *bus, enum iommu_cap cap)
1877 {
1878 	if (!bus->iommu_ops || !bus->iommu_ops->capable)
1879 		return false;
1880 
1881 	return bus->iommu_ops->capable(cap);
1882 }
1883 EXPORT_SYMBOL_GPL(iommu_capable);
1884 
1885 /**
1886  * iommu_set_fault_handler() - set a fault handler for an iommu domain
1887  * @domain: iommu domain
1888  * @handler: fault handler
1889  * @token: user data, will be passed back to the fault handler
1890  *
1891  * This function should be used by IOMMU users which want to be notified
1892  * whenever an IOMMU fault happens.
1893  *
1894  * The fault handler itself should return 0 on success, and an appropriate
1895  * error code otherwise.
1896  */
1897 void iommu_set_fault_handler(struct iommu_domain *domain,
1898 					iommu_fault_handler_t handler,
1899 					void *token)
1900 {
1901 	BUG_ON(!domain);
1902 
1903 	domain->handler = handler;
1904 	domain->handler_token = token;
1905 }
1906 EXPORT_SYMBOL_GPL(iommu_set_fault_handler);
1907 
1908 static struct iommu_domain *__iommu_domain_alloc(struct bus_type *bus,
1909 						 unsigned type)
1910 {
1911 	struct iommu_domain *domain;
1912 
1913 	if (bus == NULL || bus->iommu_ops == NULL)
1914 		return NULL;
1915 
1916 	domain = bus->iommu_ops->domain_alloc(type);
1917 	if (!domain)
1918 		return NULL;
1919 
1920 	domain->type = type;
1921 	/* Assume all sizes by default; the driver may override this later */
1922 	domain->pgsize_bitmap = bus->iommu_ops->pgsize_bitmap;
1923 	if (!domain->ops)
1924 		domain->ops = bus->iommu_ops->default_domain_ops;
1925 
1926 	if (iommu_is_dma_domain(domain) && iommu_get_dma_cookie(domain)) {
1927 		iommu_domain_free(domain);
1928 		domain = NULL;
1929 	}
1930 	return domain;
1931 }
1932 
1933 struct iommu_domain *iommu_domain_alloc(struct bus_type *bus)
1934 {
1935 	return __iommu_domain_alloc(bus, IOMMU_DOMAIN_UNMANAGED);
1936 }
1937 EXPORT_SYMBOL_GPL(iommu_domain_alloc);
1938 
1939 void iommu_domain_free(struct iommu_domain *domain)
1940 {
1941 	iommu_put_dma_cookie(domain);
1942 	domain->ops->free(domain);
1943 }
1944 EXPORT_SYMBOL_GPL(iommu_domain_free);
1945 
1946 /*
1947  * Put the group's domain back to the appropriate core-owned domain - either the
1948  * standard kernel-mode DMA configuration or an all-DMA-blocked domain.
1949  */
1950 static void __iommu_group_set_core_domain(struct iommu_group *group)
1951 {
1952 	struct iommu_domain *new_domain;
1953 	int ret;
1954 
1955 	if (group->owner)
1956 		new_domain = group->blocking_domain;
1957 	else
1958 		new_domain = group->default_domain;
1959 
1960 	ret = __iommu_group_set_domain(group, new_domain);
1961 	WARN(ret, "iommu driver failed to attach the default/blocking domain");
1962 }
1963 
1964 static int __iommu_attach_device(struct iommu_domain *domain,
1965 				 struct device *dev)
1966 {
1967 	int ret;
1968 
1969 	if (unlikely(domain->ops->attach_dev == NULL))
1970 		return -ENODEV;
1971 
1972 	ret = domain->ops->attach_dev(domain, dev);
1973 	if (!ret)
1974 		trace_attach_device_to_domain(dev);
1975 	return ret;
1976 }
1977 
1978 int iommu_attach_device(struct iommu_domain *domain, struct device *dev)
1979 {
1980 	struct iommu_group *group;
1981 	int ret;
1982 
1983 	group = iommu_group_get(dev);
1984 	if (!group)
1985 		return -ENODEV;
1986 
1987 	/*
1988 	 * Lock the group to make sure the device-count doesn't
1989 	 * change while we are attaching
1990 	 */
1991 	mutex_lock(&group->mutex);
1992 	ret = -EINVAL;
1993 	if (iommu_group_device_count(group) != 1)
1994 		goto out_unlock;
1995 
1996 	ret = __iommu_attach_group(domain, group);
1997 
1998 out_unlock:
1999 	mutex_unlock(&group->mutex);
2000 	iommu_group_put(group);
2001 
2002 	return ret;
2003 }
2004 EXPORT_SYMBOL_GPL(iommu_attach_device);
2005 
2006 int iommu_deferred_attach(struct device *dev, struct iommu_domain *domain)
2007 {
2008 	if (iommu_is_attach_deferred(dev))
2009 		return __iommu_attach_device(domain, dev);
2010 
2011 	return 0;
2012 }
2013 
2014 static void __iommu_detach_device(struct iommu_domain *domain,
2015 				  struct device *dev)
2016 {
2017 	if (iommu_is_attach_deferred(dev))
2018 		return;
2019 
2020 	domain->ops->detach_dev(domain, dev);
2021 	trace_detach_device_from_domain(dev);
2022 }
2023 
2024 void iommu_detach_device(struct iommu_domain *domain, struct device *dev)
2025 {
2026 	struct iommu_group *group;
2027 
2028 	group = iommu_group_get(dev);
2029 	if (!group)
2030 		return;
2031 
2032 	mutex_lock(&group->mutex);
2033 	if (WARN_ON(domain != group->domain) ||
2034 	    WARN_ON(iommu_group_device_count(group) != 1))
2035 		goto out_unlock;
2036 	__iommu_group_set_core_domain(group);
2037 
2038 out_unlock:
2039 	mutex_unlock(&group->mutex);
2040 	iommu_group_put(group);
2041 }
2042 EXPORT_SYMBOL_GPL(iommu_detach_device);
2043 
2044 struct iommu_domain *iommu_get_domain_for_dev(struct device *dev)
2045 {
2046 	struct iommu_domain *domain;
2047 	struct iommu_group *group;
2048 
2049 	group = iommu_group_get(dev);
2050 	if (!group)
2051 		return NULL;
2052 
2053 	domain = group->domain;
2054 
2055 	iommu_group_put(group);
2056 
2057 	return domain;
2058 }
2059 EXPORT_SYMBOL_GPL(iommu_get_domain_for_dev);
2060 
2061 /*
2062  * For IOMMU_DOMAIN_DMA implementations which already provide their own
2063  * guarantees that the group and its default domain are valid and correct.
2064  */
2065 struct iommu_domain *iommu_get_dma_domain(struct device *dev)
2066 {
2067 	return dev->iommu_group->default_domain;
2068 }
2069 
2070 /*
2071  * IOMMU groups are really the natural working unit of the IOMMU, but
2072  * the IOMMU API works on domains and devices.  Bridge that gap by
2073  * iterating over the devices in a group.  Ideally we'd have a single
2074  * device which represents the requestor ID of the group, but we also
2075  * allow IOMMU drivers to create policy defined minimum sets, where
2076  * the physical hardware may be able to distiguish members, but we
2077  * wish to group them at a higher level (ex. untrusted multi-function
2078  * PCI devices).  Thus we attach each device.
2079  */
2080 static int iommu_group_do_attach_device(struct device *dev, void *data)
2081 {
2082 	struct iommu_domain *domain = data;
2083 
2084 	return __iommu_attach_device(domain, dev);
2085 }
2086 
2087 static int __iommu_attach_group(struct iommu_domain *domain,
2088 				struct iommu_group *group)
2089 {
2090 	int ret;
2091 
2092 	if (group->domain && group->domain != group->default_domain &&
2093 	    group->domain != group->blocking_domain)
2094 		return -EBUSY;
2095 
2096 	ret = __iommu_group_for_each_dev(group, domain,
2097 					 iommu_group_do_attach_device);
2098 	if (ret == 0)
2099 		group->domain = domain;
2100 
2101 	return ret;
2102 }
2103 
2104 int iommu_attach_group(struct iommu_domain *domain, struct iommu_group *group)
2105 {
2106 	int ret;
2107 
2108 	mutex_lock(&group->mutex);
2109 	ret = __iommu_attach_group(domain, group);
2110 	mutex_unlock(&group->mutex);
2111 
2112 	return ret;
2113 }
2114 EXPORT_SYMBOL_GPL(iommu_attach_group);
2115 
2116 static int iommu_group_do_detach_device(struct device *dev, void *data)
2117 {
2118 	struct iommu_domain *domain = data;
2119 
2120 	__iommu_detach_device(domain, dev);
2121 
2122 	return 0;
2123 }
2124 
2125 static int __iommu_group_set_domain(struct iommu_group *group,
2126 				    struct iommu_domain *new_domain)
2127 {
2128 	int ret;
2129 
2130 	if (group->domain == new_domain)
2131 		return 0;
2132 
2133 	/*
2134 	 * New drivers should support default domains and so the detach_dev() op
2135 	 * will never be called. Otherwise the NULL domain represents some
2136 	 * platform specific behavior.
2137 	 */
2138 	if (!new_domain) {
2139 		if (WARN_ON(!group->domain->ops->detach_dev))
2140 			return -EINVAL;
2141 		__iommu_group_for_each_dev(group, group->domain,
2142 					   iommu_group_do_detach_device);
2143 		group->domain = NULL;
2144 		return 0;
2145 	}
2146 
2147 	/*
2148 	 * Changing the domain is done by calling attach_dev() on the new
2149 	 * domain. This switch does not have to be atomic and DMA can be
2150 	 * discarded during the transition. DMA must only be able to access
2151 	 * either new_domain or group->domain, never something else.
2152 	 *
2153 	 * Note that this is called in error unwind paths, attaching to a
2154 	 * domain that has already been attached cannot fail.
2155 	 */
2156 	ret = __iommu_group_for_each_dev(group, new_domain,
2157 					 iommu_group_do_attach_device);
2158 	if (ret)
2159 		return ret;
2160 	group->domain = new_domain;
2161 	return 0;
2162 }
2163 
2164 void iommu_detach_group(struct iommu_domain *domain, struct iommu_group *group)
2165 {
2166 	mutex_lock(&group->mutex);
2167 	__iommu_group_set_core_domain(group);
2168 	mutex_unlock(&group->mutex);
2169 }
2170 EXPORT_SYMBOL_GPL(iommu_detach_group);
2171 
2172 phys_addr_t iommu_iova_to_phys(struct iommu_domain *domain, dma_addr_t iova)
2173 {
2174 	if (domain->type == IOMMU_DOMAIN_IDENTITY)
2175 		return iova;
2176 
2177 	if (domain->type == IOMMU_DOMAIN_BLOCKED)
2178 		return 0;
2179 
2180 	return domain->ops->iova_to_phys(domain, iova);
2181 }
2182 EXPORT_SYMBOL_GPL(iommu_iova_to_phys);
2183 
2184 static size_t iommu_pgsize(struct iommu_domain *domain, unsigned long iova,
2185 			   phys_addr_t paddr, size_t size, size_t *count)
2186 {
2187 	unsigned int pgsize_idx, pgsize_idx_next;
2188 	unsigned long pgsizes;
2189 	size_t offset, pgsize, pgsize_next;
2190 	unsigned long addr_merge = paddr | iova;
2191 
2192 	/* Page sizes supported by the hardware and small enough for @size */
2193 	pgsizes = domain->pgsize_bitmap & GENMASK(__fls(size), 0);
2194 
2195 	/* Constrain the page sizes further based on the maximum alignment */
2196 	if (likely(addr_merge))
2197 		pgsizes &= GENMASK(__ffs(addr_merge), 0);
2198 
2199 	/* Make sure we have at least one suitable page size */
2200 	BUG_ON(!pgsizes);
2201 
2202 	/* Pick the biggest page size remaining */
2203 	pgsize_idx = __fls(pgsizes);
2204 	pgsize = BIT(pgsize_idx);
2205 	if (!count)
2206 		return pgsize;
2207 
2208 	/* Find the next biggest support page size, if it exists */
2209 	pgsizes = domain->pgsize_bitmap & ~GENMASK(pgsize_idx, 0);
2210 	if (!pgsizes)
2211 		goto out_set_count;
2212 
2213 	pgsize_idx_next = __ffs(pgsizes);
2214 	pgsize_next = BIT(pgsize_idx_next);
2215 
2216 	/*
2217 	 * There's no point trying a bigger page size unless the virtual
2218 	 * and physical addresses are similarly offset within the larger page.
2219 	 */
2220 	if ((iova ^ paddr) & (pgsize_next - 1))
2221 		goto out_set_count;
2222 
2223 	/* Calculate the offset to the next page size alignment boundary */
2224 	offset = pgsize_next - (addr_merge & (pgsize_next - 1));
2225 
2226 	/*
2227 	 * If size is big enough to accommodate the larger page, reduce
2228 	 * the number of smaller pages.
2229 	 */
2230 	if (offset + pgsize_next <= size)
2231 		size = offset;
2232 
2233 out_set_count:
2234 	*count = size >> pgsize_idx;
2235 	return pgsize;
2236 }
2237 
2238 static int __iommu_map_pages(struct iommu_domain *domain, unsigned long iova,
2239 			     phys_addr_t paddr, size_t size, int prot,
2240 			     gfp_t gfp, size_t *mapped)
2241 {
2242 	const struct iommu_domain_ops *ops = domain->ops;
2243 	size_t pgsize, count;
2244 	int ret;
2245 
2246 	pgsize = iommu_pgsize(domain, iova, paddr, size, &count);
2247 
2248 	pr_debug("mapping: iova 0x%lx pa %pa pgsize 0x%zx count %zu\n",
2249 		 iova, &paddr, pgsize, count);
2250 
2251 	if (ops->map_pages) {
2252 		ret = ops->map_pages(domain, iova, paddr, pgsize, count, prot,
2253 				     gfp, mapped);
2254 	} else {
2255 		ret = ops->map(domain, iova, paddr, pgsize, prot, gfp);
2256 		*mapped = ret ? 0 : pgsize;
2257 	}
2258 
2259 	return ret;
2260 }
2261 
2262 static int __iommu_map(struct iommu_domain *domain, unsigned long iova,
2263 		       phys_addr_t paddr, size_t size, int prot, gfp_t gfp)
2264 {
2265 	const struct iommu_domain_ops *ops = domain->ops;
2266 	unsigned long orig_iova = iova;
2267 	unsigned int min_pagesz;
2268 	size_t orig_size = size;
2269 	phys_addr_t orig_paddr = paddr;
2270 	int ret = 0;
2271 
2272 	if (unlikely(!(ops->map || ops->map_pages) ||
2273 		     domain->pgsize_bitmap == 0UL))
2274 		return -ENODEV;
2275 
2276 	if (unlikely(!(domain->type & __IOMMU_DOMAIN_PAGING)))
2277 		return -EINVAL;
2278 
2279 	/* find out the minimum page size supported */
2280 	min_pagesz = 1 << __ffs(domain->pgsize_bitmap);
2281 
2282 	/*
2283 	 * both the virtual address and the physical one, as well as
2284 	 * the size of the mapping, must be aligned (at least) to the
2285 	 * size of the smallest page supported by the hardware
2286 	 */
2287 	if (!IS_ALIGNED(iova | paddr | size, min_pagesz)) {
2288 		pr_err("unaligned: iova 0x%lx pa %pa size 0x%zx min_pagesz 0x%x\n",
2289 		       iova, &paddr, size, min_pagesz);
2290 		return -EINVAL;
2291 	}
2292 
2293 	pr_debug("map: iova 0x%lx pa %pa size 0x%zx\n", iova, &paddr, size);
2294 
2295 	while (size) {
2296 		size_t mapped = 0;
2297 
2298 		ret = __iommu_map_pages(domain, iova, paddr, size, prot, gfp,
2299 					&mapped);
2300 		/*
2301 		 * Some pages may have been mapped, even if an error occurred,
2302 		 * so we should account for those so they can be unmapped.
2303 		 */
2304 		size -= mapped;
2305 
2306 		if (ret)
2307 			break;
2308 
2309 		iova += mapped;
2310 		paddr += mapped;
2311 	}
2312 
2313 	/* unroll mapping in case something went wrong */
2314 	if (ret)
2315 		iommu_unmap(domain, orig_iova, orig_size - size);
2316 	else
2317 		trace_map(orig_iova, orig_paddr, orig_size);
2318 
2319 	return ret;
2320 }
2321 
2322 static int _iommu_map(struct iommu_domain *domain, unsigned long iova,
2323 		      phys_addr_t paddr, size_t size, int prot, gfp_t gfp)
2324 {
2325 	const struct iommu_domain_ops *ops = domain->ops;
2326 	int ret;
2327 
2328 	ret = __iommu_map(domain, iova, paddr, size, prot, gfp);
2329 	if (ret == 0 && ops->iotlb_sync_map)
2330 		ops->iotlb_sync_map(domain, iova, size);
2331 
2332 	return ret;
2333 }
2334 
2335 int iommu_map(struct iommu_domain *domain, unsigned long iova,
2336 	      phys_addr_t paddr, size_t size, int prot)
2337 {
2338 	might_sleep();
2339 	return _iommu_map(domain, iova, paddr, size, prot, GFP_KERNEL);
2340 }
2341 EXPORT_SYMBOL_GPL(iommu_map);
2342 
2343 int iommu_map_atomic(struct iommu_domain *domain, unsigned long iova,
2344 	      phys_addr_t paddr, size_t size, int prot)
2345 {
2346 	return _iommu_map(domain, iova, paddr, size, prot, GFP_ATOMIC);
2347 }
2348 EXPORT_SYMBOL_GPL(iommu_map_atomic);
2349 
2350 static size_t __iommu_unmap_pages(struct iommu_domain *domain,
2351 				  unsigned long iova, size_t size,
2352 				  struct iommu_iotlb_gather *iotlb_gather)
2353 {
2354 	const struct iommu_domain_ops *ops = domain->ops;
2355 	size_t pgsize, count;
2356 
2357 	pgsize = iommu_pgsize(domain, iova, iova, size, &count);
2358 	return ops->unmap_pages ?
2359 	       ops->unmap_pages(domain, iova, pgsize, count, iotlb_gather) :
2360 	       ops->unmap(domain, iova, pgsize, iotlb_gather);
2361 }
2362 
2363 static size_t __iommu_unmap(struct iommu_domain *domain,
2364 			    unsigned long iova, size_t size,
2365 			    struct iommu_iotlb_gather *iotlb_gather)
2366 {
2367 	const struct iommu_domain_ops *ops = domain->ops;
2368 	size_t unmapped_page, unmapped = 0;
2369 	unsigned long orig_iova = iova;
2370 	unsigned int min_pagesz;
2371 
2372 	if (unlikely(!(ops->unmap || ops->unmap_pages) ||
2373 		     domain->pgsize_bitmap == 0UL))
2374 		return 0;
2375 
2376 	if (unlikely(!(domain->type & __IOMMU_DOMAIN_PAGING)))
2377 		return 0;
2378 
2379 	/* find out the minimum page size supported */
2380 	min_pagesz = 1 << __ffs(domain->pgsize_bitmap);
2381 
2382 	/*
2383 	 * The virtual address, as well as the size of the mapping, must be
2384 	 * aligned (at least) to the size of the smallest page supported
2385 	 * by the hardware
2386 	 */
2387 	if (!IS_ALIGNED(iova | size, min_pagesz)) {
2388 		pr_err("unaligned: iova 0x%lx size 0x%zx min_pagesz 0x%x\n",
2389 		       iova, size, min_pagesz);
2390 		return 0;
2391 	}
2392 
2393 	pr_debug("unmap this: iova 0x%lx size 0x%zx\n", iova, size);
2394 
2395 	/*
2396 	 * Keep iterating until we either unmap 'size' bytes (or more)
2397 	 * or we hit an area that isn't mapped.
2398 	 */
2399 	while (unmapped < size) {
2400 		unmapped_page = __iommu_unmap_pages(domain, iova,
2401 						    size - unmapped,
2402 						    iotlb_gather);
2403 		if (!unmapped_page)
2404 			break;
2405 
2406 		pr_debug("unmapped: iova 0x%lx size 0x%zx\n",
2407 			 iova, unmapped_page);
2408 
2409 		iova += unmapped_page;
2410 		unmapped += unmapped_page;
2411 	}
2412 
2413 	trace_unmap(orig_iova, size, unmapped);
2414 	return unmapped;
2415 }
2416 
2417 size_t iommu_unmap(struct iommu_domain *domain,
2418 		   unsigned long iova, size_t size)
2419 {
2420 	struct iommu_iotlb_gather iotlb_gather;
2421 	size_t ret;
2422 
2423 	iommu_iotlb_gather_init(&iotlb_gather);
2424 	ret = __iommu_unmap(domain, iova, size, &iotlb_gather);
2425 	iommu_iotlb_sync(domain, &iotlb_gather);
2426 
2427 	return ret;
2428 }
2429 EXPORT_SYMBOL_GPL(iommu_unmap);
2430 
2431 size_t iommu_unmap_fast(struct iommu_domain *domain,
2432 			unsigned long iova, size_t size,
2433 			struct iommu_iotlb_gather *iotlb_gather)
2434 {
2435 	return __iommu_unmap(domain, iova, size, iotlb_gather);
2436 }
2437 EXPORT_SYMBOL_GPL(iommu_unmap_fast);
2438 
2439 static ssize_t __iommu_map_sg(struct iommu_domain *domain, unsigned long iova,
2440 		struct scatterlist *sg, unsigned int nents, int prot,
2441 		gfp_t gfp)
2442 {
2443 	const struct iommu_domain_ops *ops = domain->ops;
2444 	size_t len = 0, mapped = 0;
2445 	phys_addr_t start;
2446 	unsigned int i = 0;
2447 	int ret;
2448 
2449 	while (i <= nents) {
2450 		phys_addr_t s_phys = sg_phys(sg);
2451 
2452 		if (len && s_phys != start + len) {
2453 			ret = __iommu_map(domain, iova + mapped, start,
2454 					len, prot, gfp);
2455 
2456 			if (ret)
2457 				goto out_err;
2458 
2459 			mapped += len;
2460 			len = 0;
2461 		}
2462 
2463 		if (sg_is_dma_bus_address(sg))
2464 			goto next;
2465 
2466 		if (len) {
2467 			len += sg->length;
2468 		} else {
2469 			len = sg->length;
2470 			start = s_phys;
2471 		}
2472 
2473 next:
2474 		if (++i < nents)
2475 			sg = sg_next(sg);
2476 	}
2477 
2478 	if (ops->iotlb_sync_map)
2479 		ops->iotlb_sync_map(domain, iova, mapped);
2480 	return mapped;
2481 
2482 out_err:
2483 	/* undo mappings already done */
2484 	iommu_unmap(domain, iova, mapped);
2485 
2486 	return ret;
2487 }
2488 
2489 ssize_t iommu_map_sg(struct iommu_domain *domain, unsigned long iova,
2490 		     struct scatterlist *sg, unsigned int nents, int prot)
2491 {
2492 	might_sleep();
2493 	return __iommu_map_sg(domain, iova, sg, nents, prot, GFP_KERNEL);
2494 }
2495 EXPORT_SYMBOL_GPL(iommu_map_sg);
2496 
2497 ssize_t iommu_map_sg_atomic(struct iommu_domain *domain, unsigned long iova,
2498 		    struct scatterlist *sg, unsigned int nents, int prot)
2499 {
2500 	return __iommu_map_sg(domain, iova, sg, nents, prot, GFP_ATOMIC);
2501 }
2502 
2503 /**
2504  * report_iommu_fault() - report about an IOMMU fault to the IOMMU framework
2505  * @domain: the iommu domain where the fault has happened
2506  * @dev: the device where the fault has happened
2507  * @iova: the faulting address
2508  * @flags: mmu fault flags (e.g. IOMMU_FAULT_READ/IOMMU_FAULT_WRITE/...)
2509  *
2510  * This function should be called by the low-level IOMMU implementations
2511  * whenever IOMMU faults happen, to allow high-level users, that are
2512  * interested in such events, to know about them.
2513  *
2514  * This event may be useful for several possible use cases:
2515  * - mere logging of the event
2516  * - dynamic TLB/PTE loading
2517  * - if restarting of the faulting device is required
2518  *
2519  * Returns 0 on success and an appropriate error code otherwise (if dynamic
2520  * PTE/TLB loading will one day be supported, implementations will be able
2521  * to tell whether it succeeded or not according to this return value).
2522  *
2523  * Specifically, -ENOSYS is returned if a fault handler isn't installed
2524  * (though fault handlers can also return -ENOSYS, in case they want to
2525  * elicit the default behavior of the IOMMU drivers).
2526  */
2527 int report_iommu_fault(struct iommu_domain *domain, struct device *dev,
2528 		       unsigned long iova, int flags)
2529 {
2530 	int ret = -ENOSYS;
2531 
2532 	/*
2533 	 * if upper layers showed interest and installed a fault handler,
2534 	 * invoke it.
2535 	 */
2536 	if (domain->handler)
2537 		ret = domain->handler(domain, dev, iova, flags,
2538 						domain->handler_token);
2539 
2540 	trace_io_page_fault(dev, iova, flags);
2541 	return ret;
2542 }
2543 EXPORT_SYMBOL_GPL(report_iommu_fault);
2544 
2545 static int __init iommu_init(void)
2546 {
2547 	iommu_group_kset = kset_create_and_add("iommu_groups",
2548 					       NULL, kernel_kobj);
2549 	BUG_ON(!iommu_group_kset);
2550 
2551 	iommu_debugfs_setup();
2552 
2553 	return 0;
2554 }
2555 core_initcall(iommu_init);
2556 
2557 int iommu_enable_nesting(struct iommu_domain *domain)
2558 {
2559 	if (domain->type != IOMMU_DOMAIN_UNMANAGED)
2560 		return -EINVAL;
2561 	if (!domain->ops->enable_nesting)
2562 		return -EINVAL;
2563 	return domain->ops->enable_nesting(domain);
2564 }
2565 EXPORT_SYMBOL_GPL(iommu_enable_nesting);
2566 
2567 int iommu_set_pgtable_quirks(struct iommu_domain *domain,
2568 		unsigned long quirk)
2569 {
2570 	if (domain->type != IOMMU_DOMAIN_UNMANAGED)
2571 		return -EINVAL;
2572 	if (!domain->ops->set_pgtable_quirks)
2573 		return -EINVAL;
2574 	return domain->ops->set_pgtable_quirks(domain, quirk);
2575 }
2576 EXPORT_SYMBOL_GPL(iommu_set_pgtable_quirks);
2577 
2578 void iommu_get_resv_regions(struct device *dev, struct list_head *list)
2579 {
2580 	const struct iommu_ops *ops = dev_iommu_ops(dev);
2581 
2582 	if (ops->get_resv_regions)
2583 		ops->get_resv_regions(dev, list);
2584 }
2585 
2586 /**
2587  * iommu_put_resv_regions - release resered regions
2588  * @dev: device for which to free reserved regions
2589  * @list: reserved region list for device
2590  *
2591  * This releases a reserved region list acquired by iommu_get_resv_regions().
2592  */
2593 void iommu_put_resv_regions(struct device *dev, struct list_head *list)
2594 {
2595 	struct iommu_resv_region *entry, *next;
2596 
2597 	list_for_each_entry_safe(entry, next, list, list) {
2598 		if (entry->free)
2599 			entry->free(dev, entry);
2600 		else
2601 			kfree(entry);
2602 	}
2603 }
2604 EXPORT_SYMBOL(iommu_put_resv_regions);
2605 
2606 struct iommu_resv_region *iommu_alloc_resv_region(phys_addr_t start,
2607 						  size_t length, int prot,
2608 						  enum iommu_resv_type type)
2609 {
2610 	struct iommu_resv_region *region;
2611 
2612 	region = kzalloc(sizeof(*region), GFP_KERNEL);
2613 	if (!region)
2614 		return NULL;
2615 
2616 	INIT_LIST_HEAD(&region->list);
2617 	region->start = start;
2618 	region->length = length;
2619 	region->prot = prot;
2620 	region->type = type;
2621 	return region;
2622 }
2623 EXPORT_SYMBOL_GPL(iommu_alloc_resv_region);
2624 
2625 void iommu_set_default_passthrough(bool cmd_line)
2626 {
2627 	if (cmd_line)
2628 		iommu_cmd_line |= IOMMU_CMD_LINE_DMA_API;
2629 	iommu_def_domain_type = IOMMU_DOMAIN_IDENTITY;
2630 }
2631 
2632 void iommu_set_default_translated(bool cmd_line)
2633 {
2634 	if (cmd_line)
2635 		iommu_cmd_line |= IOMMU_CMD_LINE_DMA_API;
2636 	iommu_def_domain_type = IOMMU_DOMAIN_DMA;
2637 }
2638 
2639 bool iommu_default_passthrough(void)
2640 {
2641 	return iommu_def_domain_type == IOMMU_DOMAIN_IDENTITY;
2642 }
2643 EXPORT_SYMBOL_GPL(iommu_default_passthrough);
2644 
2645 const struct iommu_ops *iommu_ops_from_fwnode(struct fwnode_handle *fwnode)
2646 {
2647 	const struct iommu_ops *ops = NULL;
2648 	struct iommu_device *iommu;
2649 
2650 	spin_lock(&iommu_device_lock);
2651 	list_for_each_entry(iommu, &iommu_device_list, list)
2652 		if (iommu->fwnode == fwnode) {
2653 			ops = iommu->ops;
2654 			break;
2655 		}
2656 	spin_unlock(&iommu_device_lock);
2657 	return ops;
2658 }
2659 
2660 int iommu_fwspec_init(struct device *dev, struct fwnode_handle *iommu_fwnode,
2661 		      const struct iommu_ops *ops)
2662 {
2663 	struct iommu_fwspec *fwspec = dev_iommu_fwspec_get(dev);
2664 
2665 	if (fwspec)
2666 		return ops == fwspec->ops ? 0 : -EINVAL;
2667 
2668 	if (!dev_iommu_get(dev))
2669 		return -ENOMEM;
2670 
2671 	/* Preallocate for the overwhelmingly common case of 1 ID */
2672 	fwspec = kzalloc(struct_size(fwspec, ids, 1), GFP_KERNEL);
2673 	if (!fwspec)
2674 		return -ENOMEM;
2675 
2676 	of_node_get(to_of_node(iommu_fwnode));
2677 	fwspec->iommu_fwnode = iommu_fwnode;
2678 	fwspec->ops = ops;
2679 	dev_iommu_fwspec_set(dev, fwspec);
2680 	return 0;
2681 }
2682 EXPORT_SYMBOL_GPL(iommu_fwspec_init);
2683 
2684 void iommu_fwspec_free(struct device *dev)
2685 {
2686 	struct iommu_fwspec *fwspec = dev_iommu_fwspec_get(dev);
2687 
2688 	if (fwspec) {
2689 		fwnode_handle_put(fwspec->iommu_fwnode);
2690 		kfree(fwspec);
2691 		dev_iommu_fwspec_set(dev, NULL);
2692 	}
2693 }
2694 EXPORT_SYMBOL_GPL(iommu_fwspec_free);
2695 
2696 int iommu_fwspec_add_ids(struct device *dev, u32 *ids, int num_ids)
2697 {
2698 	struct iommu_fwspec *fwspec = dev_iommu_fwspec_get(dev);
2699 	int i, new_num;
2700 
2701 	if (!fwspec)
2702 		return -EINVAL;
2703 
2704 	new_num = fwspec->num_ids + num_ids;
2705 	if (new_num > 1) {
2706 		fwspec = krealloc(fwspec, struct_size(fwspec, ids, new_num),
2707 				  GFP_KERNEL);
2708 		if (!fwspec)
2709 			return -ENOMEM;
2710 
2711 		dev_iommu_fwspec_set(dev, fwspec);
2712 	}
2713 
2714 	for (i = 0; i < num_ids; i++)
2715 		fwspec->ids[fwspec->num_ids + i] = ids[i];
2716 
2717 	fwspec->num_ids = new_num;
2718 	return 0;
2719 }
2720 EXPORT_SYMBOL_GPL(iommu_fwspec_add_ids);
2721 
2722 /*
2723  * Per device IOMMU features.
2724  */
2725 int iommu_dev_enable_feature(struct device *dev, enum iommu_dev_features feat)
2726 {
2727 	if (dev->iommu && dev->iommu->iommu_dev) {
2728 		const struct iommu_ops *ops = dev->iommu->iommu_dev->ops;
2729 
2730 		if (ops->dev_enable_feat)
2731 			return ops->dev_enable_feat(dev, feat);
2732 	}
2733 
2734 	return -ENODEV;
2735 }
2736 EXPORT_SYMBOL_GPL(iommu_dev_enable_feature);
2737 
2738 /*
2739  * The device drivers should do the necessary cleanups before calling this.
2740  */
2741 int iommu_dev_disable_feature(struct device *dev, enum iommu_dev_features feat)
2742 {
2743 	if (dev->iommu && dev->iommu->iommu_dev) {
2744 		const struct iommu_ops *ops = dev->iommu->iommu_dev->ops;
2745 
2746 		if (ops->dev_disable_feat)
2747 			return ops->dev_disable_feat(dev, feat);
2748 	}
2749 
2750 	return -EBUSY;
2751 }
2752 EXPORT_SYMBOL_GPL(iommu_dev_disable_feature);
2753 
2754 /**
2755  * iommu_sva_bind_device() - Bind a process address space to a device
2756  * @dev: the device
2757  * @mm: the mm to bind, caller must hold a reference to it
2758  * @drvdata: opaque data pointer to pass to bind callback
2759  *
2760  * Create a bond between device and address space, allowing the device to access
2761  * the mm using the returned PASID. If a bond already exists between @device and
2762  * @mm, it is returned and an additional reference is taken. Caller must call
2763  * iommu_sva_unbind_device() to release each reference.
2764  *
2765  * iommu_dev_enable_feature(dev, IOMMU_DEV_FEAT_SVA) must be called first, to
2766  * initialize the required SVA features.
2767  *
2768  * On error, returns an ERR_PTR value.
2769  */
2770 struct iommu_sva *
2771 iommu_sva_bind_device(struct device *dev, struct mm_struct *mm, void *drvdata)
2772 {
2773 	struct iommu_group *group;
2774 	struct iommu_sva *handle = ERR_PTR(-EINVAL);
2775 	const struct iommu_ops *ops = dev_iommu_ops(dev);
2776 
2777 	if (!ops->sva_bind)
2778 		return ERR_PTR(-ENODEV);
2779 
2780 	group = iommu_group_get(dev);
2781 	if (!group)
2782 		return ERR_PTR(-ENODEV);
2783 
2784 	/* Ensure device count and domain don't change while we're binding */
2785 	mutex_lock(&group->mutex);
2786 
2787 	/*
2788 	 * To keep things simple, SVA currently doesn't support IOMMU groups
2789 	 * with more than one device. Existing SVA-capable systems are not
2790 	 * affected by the problems that required IOMMU groups (lack of ACS
2791 	 * isolation, device ID aliasing and other hardware issues).
2792 	 */
2793 	if (iommu_group_device_count(group) != 1)
2794 		goto out_unlock;
2795 
2796 	handle = ops->sva_bind(dev, mm, drvdata);
2797 
2798 out_unlock:
2799 	mutex_unlock(&group->mutex);
2800 	iommu_group_put(group);
2801 
2802 	return handle;
2803 }
2804 EXPORT_SYMBOL_GPL(iommu_sva_bind_device);
2805 
2806 /**
2807  * iommu_sva_unbind_device() - Remove a bond created with iommu_sva_bind_device
2808  * @handle: the handle returned by iommu_sva_bind_device()
2809  *
2810  * Put reference to a bond between device and address space. The device should
2811  * not be issuing any more transaction for this PASID. All outstanding page
2812  * requests for this PASID must have been flushed to the IOMMU.
2813  */
2814 void iommu_sva_unbind_device(struct iommu_sva *handle)
2815 {
2816 	struct iommu_group *group;
2817 	struct device *dev = handle->dev;
2818 	const struct iommu_ops *ops = dev_iommu_ops(dev);
2819 
2820 	if (!ops->sva_unbind)
2821 		return;
2822 
2823 	group = iommu_group_get(dev);
2824 	if (!group)
2825 		return;
2826 
2827 	mutex_lock(&group->mutex);
2828 	ops->sva_unbind(handle);
2829 	mutex_unlock(&group->mutex);
2830 
2831 	iommu_group_put(group);
2832 }
2833 EXPORT_SYMBOL_GPL(iommu_sva_unbind_device);
2834 
2835 u32 iommu_sva_get_pasid(struct iommu_sva *handle)
2836 {
2837 	const struct iommu_ops *ops = dev_iommu_ops(handle->dev);
2838 
2839 	if (!ops->sva_get_pasid)
2840 		return IOMMU_PASID_INVALID;
2841 
2842 	return ops->sva_get_pasid(handle);
2843 }
2844 EXPORT_SYMBOL_GPL(iommu_sva_get_pasid);
2845 
2846 /*
2847  * Changes the default domain of an iommu group that has *only* one device
2848  *
2849  * @group: The group for which the default domain should be changed
2850  * @prev_dev: The device in the group (this is used to make sure that the device
2851  *	 hasn't changed after the caller has called this function)
2852  * @type: The type of the new default domain that gets associated with the group
2853  *
2854  * Returns 0 on success and error code on failure
2855  *
2856  * Note:
2857  * 1. Presently, this function is called only when user requests to change the
2858  *    group's default domain type through /sys/kernel/iommu_groups/<grp_id>/type
2859  *    Please take a closer look if intended to use for other purposes.
2860  */
2861 static int iommu_change_dev_def_domain(struct iommu_group *group,
2862 				       struct device *prev_dev, int type)
2863 {
2864 	struct iommu_domain *prev_dom;
2865 	struct group_device *grp_dev;
2866 	int ret, dev_def_dom;
2867 	struct device *dev;
2868 
2869 	mutex_lock(&group->mutex);
2870 
2871 	if (group->default_domain != group->domain) {
2872 		dev_err_ratelimited(prev_dev, "Group not assigned to default domain\n");
2873 		ret = -EBUSY;
2874 		goto out;
2875 	}
2876 
2877 	/*
2878 	 * iommu group wasn't locked while acquiring device lock in
2879 	 * iommu_group_store_type(). So, make sure that the device count hasn't
2880 	 * changed while acquiring device lock.
2881 	 *
2882 	 * Changing default domain of an iommu group with two or more devices
2883 	 * isn't supported because there could be a potential deadlock. Consider
2884 	 * the following scenario. T1 is trying to acquire device locks of all
2885 	 * the devices in the group and before it could acquire all of them,
2886 	 * there could be another thread T2 (from different sub-system and use
2887 	 * case) that has already acquired some of the device locks and might be
2888 	 * waiting for T1 to release other device locks.
2889 	 */
2890 	if (iommu_group_device_count(group) != 1) {
2891 		dev_err_ratelimited(prev_dev, "Cannot change default domain: Group has more than one device\n");
2892 		ret = -EINVAL;
2893 		goto out;
2894 	}
2895 
2896 	/* Since group has only one device */
2897 	grp_dev = list_first_entry(&group->devices, struct group_device, list);
2898 	dev = grp_dev->dev;
2899 
2900 	if (prev_dev != dev) {
2901 		dev_err_ratelimited(prev_dev, "Cannot change default domain: Device has been changed\n");
2902 		ret = -EBUSY;
2903 		goto out;
2904 	}
2905 
2906 	prev_dom = group->default_domain;
2907 	if (!prev_dom) {
2908 		ret = -EINVAL;
2909 		goto out;
2910 	}
2911 
2912 	dev_def_dom = iommu_get_def_domain_type(dev);
2913 	if (!type) {
2914 		/*
2915 		 * If the user hasn't requested any specific type of domain and
2916 		 * if the device supports both the domains, then default to the
2917 		 * domain the device was booted with
2918 		 */
2919 		type = dev_def_dom ? : iommu_def_domain_type;
2920 	} else if (dev_def_dom && type != dev_def_dom) {
2921 		dev_err_ratelimited(prev_dev, "Device cannot be in %s domain\n",
2922 				    iommu_domain_type_str(type));
2923 		ret = -EINVAL;
2924 		goto out;
2925 	}
2926 
2927 	/*
2928 	 * Switch to a new domain only if the requested domain type is different
2929 	 * from the existing default domain type
2930 	 */
2931 	if (prev_dom->type == type) {
2932 		ret = 0;
2933 		goto out;
2934 	}
2935 
2936 	/* We can bring up a flush queue without tearing down the domain */
2937 	if (type == IOMMU_DOMAIN_DMA_FQ && prev_dom->type == IOMMU_DOMAIN_DMA) {
2938 		ret = iommu_dma_init_fq(prev_dom);
2939 		if (!ret)
2940 			prev_dom->type = IOMMU_DOMAIN_DMA_FQ;
2941 		goto out;
2942 	}
2943 
2944 	/* Sets group->default_domain to the newly allocated domain */
2945 	ret = iommu_group_alloc_default_domain(dev->bus, group, type);
2946 	if (ret)
2947 		goto out;
2948 
2949 	ret = iommu_create_device_direct_mappings(group, dev);
2950 	if (ret)
2951 		goto free_new_domain;
2952 
2953 	ret = __iommu_attach_device(group->default_domain, dev);
2954 	if (ret)
2955 		goto free_new_domain;
2956 
2957 	group->domain = group->default_domain;
2958 
2959 	/*
2960 	 * Release the mutex here because ops->probe_finalize() call-back of
2961 	 * some vendor IOMMU drivers calls arm_iommu_attach_device() which
2962 	 * in-turn might call back into IOMMU core code, where it tries to take
2963 	 * group->mutex, resulting in a deadlock.
2964 	 */
2965 	mutex_unlock(&group->mutex);
2966 
2967 	/* Make sure dma_ops is appropriatley set */
2968 	iommu_group_do_probe_finalize(dev, group->default_domain);
2969 	iommu_domain_free(prev_dom);
2970 	return 0;
2971 
2972 free_new_domain:
2973 	iommu_domain_free(group->default_domain);
2974 	group->default_domain = prev_dom;
2975 	group->domain = prev_dom;
2976 
2977 out:
2978 	mutex_unlock(&group->mutex);
2979 
2980 	return ret;
2981 }
2982 
2983 /*
2984  * Changing the default domain through sysfs requires the users to unbind the
2985  * drivers from the devices in the iommu group, except for a DMA -> DMA-FQ
2986  * transition. Return failure if this isn't met.
2987  *
2988  * We need to consider the race between this and the device release path.
2989  * device_lock(dev) is used here to guarantee that the device release path
2990  * will not be entered at the same time.
2991  */
2992 static ssize_t iommu_group_store_type(struct iommu_group *group,
2993 				      const char *buf, size_t count)
2994 {
2995 	struct group_device *grp_dev;
2996 	struct device *dev;
2997 	int ret, req_type;
2998 
2999 	if (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO))
3000 		return -EACCES;
3001 
3002 	if (WARN_ON(!group) || !group->default_domain)
3003 		return -EINVAL;
3004 
3005 	if (sysfs_streq(buf, "identity"))
3006 		req_type = IOMMU_DOMAIN_IDENTITY;
3007 	else if (sysfs_streq(buf, "DMA"))
3008 		req_type = IOMMU_DOMAIN_DMA;
3009 	else if (sysfs_streq(buf, "DMA-FQ"))
3010 		req_type = IOMMU_DOMAIN_DMA_FQ;
3011 	else if (sysfs_streq(buf, "auto"))
3012 		req_type = 0;
3013 	else
3014 		return -EINVAL;
3015 
3016 	/*
3017 	 * Lock/Unlock the group mutex here before device lock to
3018 	 * 1. Make sure that the iommu group has only one device (this is a
3019 	 *    prerequisite for step 2)
3020 	 * 2. Get struct *dev which is needed to lock device
3021 	 */
3022 	mutex_lock(&group->mutex);
3023 	if (iommu_group_device_count(group) != 1) {
3024 		mutex_unlock(&group->mutex);
3025 		pr_err_ratelimited("Cannot change default domain: Group has more than one device\n");
3026 		return -EINVAL;
3027 	}
3028 
3029 	/* Since group has only one device */
3030 	grp_dev = list_first_entry(&group->devices, struct group_device, list);
3031 	dev = grp_dev->dev;
3032 	get_device(dev);
3033 
3034 	/*
3035 	 * Don't hold the group mutex because taking group mutex first and then
3036 	 * the device lock could potentially cause a deadlock as below. Assume
3037 	 * two threads T1 and T2. T1 is trying to change default domain of an
3038 	 * iommu group and T2 is trying to hot unplug a device or release [1] VF
3039 	 * of a PCIe device which is in the same iommu group. T1 takes group
3040 	 * mutex and before it could take device lock assume T2 has taken device
3041 	 * lock and is yet to take group mutex. Now, both the threads will be
3042 	 * waiting for the other thread to release lock. Below, lock order was
3043 	 * suggested.
3044 	 * device_lock(dev);
3045 	 *	mutex_lock(&group->mutex);
3046 	 *		iommu_change_dev_def_domain();
3047 	 *	mutex_unlock(&group->mutex);
3048 	 * device_unlock(dev);
3049 	 *
3050 	 * [1] Typical device release path
3051 	 * device_lock() from device/driver core code
3052 	 *  -> bus_notifier()
3053 	 *   -> iommu_bus_notifier()
3054 	 *    -> iommu_release_device()
3055 	 *     -> ops->release_device() vendor driver calls back iommu core code
3056 	 *      -> mutex_lock() from iommu core code
3057 	 */
3058 	mutex_unlock(&group->mutex);
3059 
3060 	/* Check if the device in the group still has a driver bound to it */
3061 	device_lock(dev);
3062 	if (device_is_bound(dev) && !(req_type == IOMMU_DOMAIN_DMA_FQ &&
3063 	    group->default_domain->type == IOMMU_DOMAIN_DMA)) {
3064 		pr_err_ratelimited("Device is still bound to driver\n");
3065 		ret = -EBUSY;
3066 		goto out;
3067 	}
3068 
3069 	ret = iommu_change_dev_def_domain(group, dev, req_type);
3070 	ret = ret ?: count;
3071 
3072 out:
3073 	device_unlock(dev);
3074 	put_device(dev);
3075 
3076 	return ret;
3077 }
3078 
3079 /**
3080  * iommu_device_use_default_domain() - Device driver wants to handle device
3081  *                                     DMA through the kernel DMA API.
3082  * @dev: The device.
3083  *
3084  * The device driver about to bind @dev wants to do DMA through the kernel
3085  * DMA API. Return 0 if it is allowed, otherwise an error.
3086  */
3087 int iommu_device_use_default_domain(struct device *dev)
3088 {
3089 	struct iommu_group *group = iommu_group_get(dev);
3090 	int ret = 0;
3091 
3092 	if (!group)
3093 		return 0;
3094 
3095 	mutex_lock(&group->mutex);
3096 	if (group->owner_cnt) {
3097 		if (group->domain != group->default_domain ||
3098 		    group->owner) {
3099 			ret = -EBUSY;
3100 			goto unlock_out;
3101 		}
3102 	}
3103 
3104 	group->owner_cnt++;
3105 
3106 unlock_out:
3107 	mutex_unlock(&group->mutex);
3108 	iommu_group_put(group);
3109 
3110 	return ret;
3111 }
3112 
3113 /**
3114  * iommu_device_unuse_default_domain() - Device driver stops handling device
3115  *                                       DMA through the kernel DMA API.
3116  * @dev: The device.
3117  *
3118  * The device driver doesn't want to do DMA through kernel DMA API anymore.
3119  * It must be called after iommu_device_use_default_domain().
3120  */
3121 void iommu_device_unuse_default_domain(struct device *dev)
3122 {
3123 	struct iommu_group *group = iommu_group_get(dev);
3124 
3125 	if (!group)
3126 		return;
3127 
3128 	mutex_lock(&group->mutex);
3129 	if (!WARN_ON(!group->owner_cnt))
3130 		group->owner_cnt--;
3131 
3132 	mutex_unlock(&group->mutex);
3133 	iommu_group_put(group);
3134 }
3135 
3136 static int __iommu_group_alloc_blocking_domain(struct iommu_group *group)
3137 {
3138 	struct group_device *dev =
3139 		list_first_entry(&group->devices, struct group_device, list);
3140 
3141 	if (group->blocking_domain)
3142 		return 0;
3143 
3144 	group->blocking_domain =
3145 		__iommu_domain_alloc(dev->dev->bus, IOMMU_DOMAIN_BLOCKED);
3146 	if (!group->blocking_domain) {
3147 		/*
3148 		 * For drivers that do not yet understand IOMMU_DOMAIN_BLOCKED
3149 		 * create an empty domain instead.
3150 		 */
3151 		group->blocking_domain = __iommu_domain_alloc(
3152 			dev->dev->bus, IOMMU_DOMAIN_UNMANAGED);
3153 		if (!group->blocking_domain)
3154 			return -EINVAL;
3155 	}
3156 	return 0;
3157 }
3158 
3159 /**
3160  * iommu_group_claim_dma_owner() - Set DMA ownership of a group
3161  * @group: The group.
3162  * @owner: Caller specified pointer. Used for exclusive ownership.
3163  *
3164  * This is to support backward compatibility for vfio which manages
3165  * the dma ownership in iommu_group level. New invocations on this
3166  * interface should be prohibited.
3167  */
3168 int iommu_group_claim_dma_owner(struct iommu_group *group, void *owner)
3169 {
3170 	int ret = 0;
3171 
3172 	mutex_lock(&group->mutex);
3173 	if (group->owner_cnt) {
3174 		ret = -EPERM;
3175 		goto unlock_out;
3176 	} else {
3177 		if (group->domain && group->domain != group->default_domain) {
3178 			ret = -EBUSY;
3179 			goto unlock_out;
3180 		}
3181 
3182 		ret = __iommu_group_alloc_blocking_domain(group);
3183 		if (ret)
3184 			goto unlock_out;
3185 
3186 		ret = __iommu_group_set_domain(group, group->blocking_domain);
3187 		if (ret)
3188 			goto unlock_out;
3189 		group->owner = owner;
3190 	}
3191 
3192 	group->owner_cnt++;
3193 unlock_out:
3194 	mutex_unlock(&group->mutex);
3195 
3196 	return ret;
3197 }
3198 EXPORT_SYMBOL_GPL(iommu_group_claim_dma_owner);
3199 
3200 /**
3201  * iommu_group_release_dma_owner() - Release DMA ownership of a group
3202  * @group: The group.
3203  *
3204  * Release the DMA ownership claimed by iommu_group_claim_dma_owner().
3205  */
3206 void iommu_group_release_dma_owner(struct iommu_group *group)
3207 {
3208 	int ret;
3209 
3210 	mutex_lock(&group->mutex);
3211 	if (WARN_ON(!group->owner_cnt || !group->owner))
3212 		goto unlock_out;
3213 
3214 	group->owner_cnt = 0;
3215 	group->owner = NULL;
3216 	ret = __iommu_group_set_domain(group, group->default_domain);
3217 	WARN(ret, "iommu driver failed to attach the default domain");
3218 
3219 unlock_out:
3220 	mutex_unlock(&group->mutex);
3221 }
3222 EXPORT_SYMBOL_GPL(iommu_group_release_dma_owner);
3223 
3224 /**
3225  * iommu_group_dma_owner_claimed() - Query group dma ownership status
3226  * @group: The group.
3227  *
3228  * This provides status query on a given group. It is racy and only for
3229  * non-binding status reporting.
3230  */
3231 bool iommu_group_dma_owner_claimed(struct iommu_group *group)
3232 {
3233 	unsigned int user;
3234 
3235 	mutex_lock(&group->mutex);
3236 	user = group->owner_cnt;
3237 	mutex_unlock(&group->mutex);
3238 
3239 	return user;
3240 }
3241 EXPORT_SYMBOL_GPL(iommu_group_dma_owner_claimed);
3242