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