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