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