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