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