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