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