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