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