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