xref: /linux/drivers/iommu/iommu.c (revision 6c65fb318e8bbf21e939e651028b955324f1d873)
1 /*
2  * Copyright (C) 2007-2008 Advanced Micro Devices, Inc.
3  * Author: Joerg Roedel <jroedel@suse.de>
4  *
5  * This program is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License version 2 as published
7  * by the Free Software Foundation.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
17  */
18 
19 #define pr_fmt(fmt)    "iommu: " fmt
20 
21 #include <linux/device.h>
22 #include <linux/kernel.h>
23 #include <linux/bug.h>
24 #include <linux/types.h>
25 #include <linux/module.h>
26 #include <linux/slab.h>
27 #include <linux/errno.h>
28 #include <linux/iommu.h>
29 #include <linux/idr.h>
30 #include <linux/notifier.h>
31 #include <linux/err.h>
32 #include <linux/pci.h>
33 #include <linux/bitops.h>
34 #include <linux/property.h>
35 #include <trace/events/iommu.h>
36 
37 static struct kset *iommu_group_kset;
38 static DEFINE_IDA(iommu_group_ida);
39 
40 struct iommu_callback_data {
41 	const struct iommu_ops *ops;
42 };
43 
44 struct iommu_group {
45 	struct kobject kobj;
46 	struct kobject *devices_kobj;
47 	struct list_head devices;
48 	struct mutex mutex;
49 	struct blocking_notifier_head notifier;
50 	void *iommu_data;
51 	void (*iommu_data_release)(void *iommu_data);
52 	char *name;
53 	int id;
54 	struct iommu_domain *default_domain;
55 	struct iommu_domain *domain;
56 };
57 
58 struct iommu_device {
59 	struct list_head list;
60 	struct device *dev;
61 	char *name;
62 };
63 
64 struct iommu_group_attribute {
65 	struct attribute attr;
66 	ssize_t (*show)(struct iommu_group *group, char *buf);
67 	ssize_t (*store)(struct iommu_group *group,
68 			 const char *buf, size_t count);
69 };
70 
71 #define IOMMU_GROUP_ATTR(_name, _mode, _show, _store)		\
72 struct iommu_group_attribute iommu_group_attr_##_name =		\
73 	__ATTR(_name, _mode, _show, _store)
74 
75 #define to_iommu_group_attr(_attr)	\
76 	container_of(_attr, struct iommu_group_attribute, attr)
77 #define to_iommu_group(_kobj)		\
78 	container_of(_kobj, struct iommu_group, kobj)
79 
80 static struct iommu_domain *__iommu_domain_alloc(struct bus_type *bus,
81 						 unsigned type);
82 static int __iommu_attach_device(struct iommu_domain *domain,
83 				 struct device *dev);
84 static int __iommu_attach_group(struct iommu_domain *domain,
85 				struct iommu_group *group);
86 static void __iommu_detach_group(struct iommu_domain *domain,
87 				 struct iommu_group *group);
88 
89 static ssize_t iommu_group_attr_show(struct kobject *kobj,
90 				     struct attribute *__attr, char *buf)
91 {
92 	struct iommu_group_attribute *attr = to_iommu_group_attr(__attr);
93 	struct iommu_group *group = to_iommu_group(kobj);
94 	ssize_t ret = -EIO;
95 
96 	if (attr->show)
97 		ret = attr->show(group, buf);
98 	return ret;
99 }
100 
101 static ssize_t iommu_group_attr_store(struct kobject *kobj,
102 				      struct attribute *__attr,
103 				      const char *buf, size_t count)
104 {
105 	struct iommu_group_attribute *attr = to_iommu_group_attr(__attr);
106 	struct iommu_group *group = to_iommu_group(kobj);
107 	ssize_t ret = -EIO;
108 
109 	if (attr->store)
110 		ret = attr->store(group, buf, count);
111 	return ret;
112 }
113 
114 static const struct sysfs_ops iommu_group_sysfs_ops = {
115 	.show = iommu_group_attr_show,
116 	.store = iommu_group_attr_store,
117 };
118 
119 static int iommu_group_create_file(struct iommu_group *group,
120 				   struct iommu_group_attribute *attr)
121 {
122 	return sysfs_create_file(&group->kobj, &attr->attr);
123 }
124 
125 static void iommu_group_remove_file(struct iommu_group *group,
126 				    struct iommu_group_attribute *attr)
127 {
128 	sysfs_remove_file(&group->kobj, &attr->attr);
129 }
130 
131 static ssize_t iommu_group_show_name(struct iommu_group *group, char *buf)
132 {
133 	return sprintf(buf, "%s\n", group->name);
134 }
135 
136 /**
137  * iommu_insert_resv_region - Insert a new region in the
138  * list of reserved regions.
139  * @new: new region to insert
140  * @regions: list of regions
141  *
142  * The new element is sorted by address with respect to the other
143  * regions of the same type. In case it overlaps with another
144  * region of the same type, regions are merged. In case it
145  * overlaps with another region of different type, regions are
146  * not merged.
147  */
148 static int iommu_insert_resv_region(struct iommu_resv_region *new,
149 				    struct list_head *regions)
150 {
151 	struct iommu_resv_region *region;
152 	phys_addr_t start = new->start;
153 	phys_addr_t end = new->start + new->length - 1;
154 	struct list_head *pos = regions->next;
155 
156 	while (pos != regions) {
157 		struct iommu_resv_region *entry =
158 			list_entry(pos, struct iommu_resv_region, list);
159 		phys_addr_t a = entry->start;
160 		phys_addr_t b = entry->start + entry->length - 1;
161 		int type = entry->type;
162 
163 		if (end < a) {
164 			goto insert;
165 		} else if (start > b) {
166 			pos = pos->next;
167 		} else if ((start >= a) && (end <= b)) {
168 			if (new->type == type)
169 				goto done;
170 			else
171 				pos = pos->next;
172 		} else {
173 			if (new->type == type) {
174 				phys_addr_t new_start = min(a, start);
175 				phys_addr_t new_end = max(b, end);
176 
177 				list_del(&entry->list);
178 				entry->start = new_start;
179 				entry->length = new_end - new_start + 1;
180 				iommu_insert_resv_region(entry, regions);
181 			} else {
182 				pos = pos->next;
183 			}
184 		}
185 	}
186 insert:
187 	region = iommu_alloc_resv_region(new->start, new->length,
188 					 new->prot, new->type);
189 	if (!region)
190 		return -ENOMEM;
191 
192 	list_add_tail(&region->list, pos);
193 done:
194 	return 0;
195 }
196 
197 static int
198 iommu_insert_device_resv_regions(struct list_head *dev_resv_regions,
199 				 struct list_head *group_resv_regions)
200 {
201 	struct iommu_resv_region *entry;
202 	int ret;
203 
204 	list_for_each_entry(entry, dev_resv_regions, list) {
205 		ret = iommu_insert_resv_region(entry, group_resv_regions);
206 		if (ret)
207 			break;
208 	}
209 	return ret;
210 }
211 
212 int iommu_get_group_resv_regions(struct iommu_group *group,
213 				 struct list_head *head)
214 {
215 	struct iommu_device *device;
216 	int ret = 0;
217 
218 	mutex_lock(&group->mutex);
219 	list_for_each_entry(device, &group->devices, list) {
220 		struct list_head dev_resv_regions;
221 
222 		INIT_LIST_HEAD(&dev_resv_regions);
223 		iommu_get_resv_regions(device->dev, &dev_resv_regions);
224 		ret = iommu_insert_device_resv_regions(&dev_resv_regions, head);
225 		iommu_put_resv_regions(device->dev, &dev_resv_regions);
226 		if (ret)
227 			break;
228 	}
229 	mutex_unlock(&group->mutex);
230 	return ret;
231 }
232 EXPORT_SYMBOL_GPL(iommu_get_group_resv_regions);
233 
234 static IOMMU_GROUP_ATTR(name, S_IRUGO, iommu_group_show_name, NULL);
235 
236 static void iommu_group_release(struct kobject *kobj)
237 {
238 	struct iommu_group *group = to_iommu_group(kobj);
239 
240 	pr_debug("Releasing group %d\n", group->id);
241 
242 	if (group->iommu_data_release)
243 		group->iommu_data_release(group->iommu_data);
244 
245 	ida_simple_remove(&iommu_group_ida, group->id);
246 
247 	if (group->default_domain)
248 		iommu_domain_free(group->default_domain);
249 
250 	kfree(group->name);
251 	kfree(group);
252 }
253 
254 static struct kobj_type iommu_group_ktype = {
255 	.sysfs_ops = &iommu_group_sysfs_ops,
256 	.release = iommu_group_release,
257 };
258 
259 /**
260  * iommu_group_alloc - Allocate a new group
261  * @name: Optional name to associate with group, visible in sysfs
262  *
263  * This function is called by an iommu driver to allocate a new iommu
264  * group.  The iommu group represents the minimum granularity of the iommu.
265  * Upon successful return, the caller holds a reference to the supplied
266  * group in order to hold the group until devices are added.  Use
267  * iommu_group_put() to release this extra reference count, allowing the
268  * group to be automatically reclaimed once it has no devices or external
269  * references.
270  */
271 struct iommu_group *iommu_group_alloc(void)
272 {
273 	struct iommu_group *group;
274 	int ret;
275 
276 	group = kzalloc(sizeof(*group), GFP_KERNEL);
277 	if (!group)
278 		return ERR_PTR(-ENOMEM);
279 
280 	group->kobj.kset = iommu_group_kset;
281 	mutex_init(&group->mutex);
282 	INIT_LIST_HEAD(&group->devices);
283 	BLOCKING_INIT_NOTIFIER_HEAD(&group->notifier);
284 
285 	ret = ida_simple_get(&iommu_group_ida, 0, 0, GFP_KERNEL);
286 	if (ret < 0) {
287 		kfree(group);
288 		return ERR_PTR(ret);
289 	}
290 	group->id = ret;
291 
292 	ret = kobject_init_and_add(&group->kobj, &iommu_group_ktype,
293 				   NULL, "%d", group->id);
294 	if (ret) {
295 		ida_simple_remove(&iommu_group_ida, group->id);
296 		kfree(group);
297 		return ERR_PTR(ret);
298 	}
299 
300 	group->devices_kobj = kobject_create_and_add("devices", &group->kobj);
301 	if (!group->devices_kobj) {
302 		kobject_put(&group->kobj); /* triggers .release & free */
303 		return ERR_PTR(-ENOMEM);
304 	}
305 
306 	/*
307 	 * The devices_kobj holds a reference on the group kobject, so
308 	 * as long as that exists so will the group.  We can therefore
309 	 * use the devices_kobj for reference counting.
310 	 */
311 	kobject_put(&group->kobj);
312 
313 	pr_debug("Allocated group %d\n", group->id);
314 
315 	return group;
316 }
317 EXPORT_SYMBOL_GPL(iommu_group_alloc);
318 
319 struct iommu_group *iommu_group_get_by_id(int id)
320 {
321 	struct kobject *group_kobj;
322 	struct iommu_group *group;
323 	const char *name;
324 
325 	if (!iommu_group_kset)
326 		return NULL;
327 
328 	name = kasprintf(GFP_KERNEL, "%d", id);
329 	if (!name)
330 		return NULL;
331 
332 	group_kobj = kset_find_obj(iommu_group_kset, name);
333 	kfree(name);
334 
335 	if (!group_kobj)
336 		return NULL;
337 
338 	group = container_of(group_kobj, struct iommu_group, kobj);
339 	BUG_ON(group->id != id);
340 
341 	kobject_get(group->devices_kobj);
342 	kobject_put(&group->kobj);
343 
344 	return group;
345 }
346 EXPORT_SYMBOL_GPL(iommu_group_get_by_id);
347 
348 /**
349  * iommu_group_get_iommudata - retrieve iommu_data registered for a group
350  * @group: the group
351  *
352  * iommu drivers can store data in the group for use when doing iommu
353  * operations.  This function provides a way to retrieve it.  Caller
354  * should hold a group reference.
355  */
356 void *iommu_group_get_iommudata(struct iommu_group *group)
357 {
358 	return group->iommu_data;
359 }
360 EXPORT_SYMBOL_GPL(iommu_group_get_iommudata);
361 
362 /**
363  * iommu_group_set_iommudata - set iommu_data for a group
364  * @group: the group
365  * @iommu_data: new data
366  * @release: release function for iommu_data
367  *
368  * iommu drivers can store data in the group for use when doing iommu
369  * operations.  This function provides a way to set the data after
370  * the group has been allocated.  Caller should hold a group reference.
371  */
372 void iommu_group_set_iommudata(struct iommu_group *group, void *iommu_data,
373 			       void (*release)(void *iommu_data))
374 {
375 	group->iommu_data = iommu_data;
376 	group->iommu_data_release = release;
377 }
378 EXPORT_SYMBOL_GPL(iommu_group_set_iommudata);
379 
380 /**
381  * iommu_group_set_name - set name for a group
382  * @group: the group
383  * @name: name
384  *
385  * Allow iommu driver to set a name for a group.  When set it will
386  * appear in a name attribute file under the group in sysfs.
387  */
388 int iommu_group_set_name(struct iommu_group *group, const char *name)
389 {
390 	int ret;
391 
392 	if (group->name) {
393 		iommu_group_remove_file(group, &iommu_group_attr_name);
394 		kfree(group->name);
395 		group->name = NULL;
396 		if (!name)
397 			return 0;
398 	}
399 
400 	group->name = kstrdup(name, GFP_KERNEL);
401 	if (!group->name)
402 		return -ENOMEM;
403 
404 	ret = iommu_group_create_file(group, &iommu_group_attr_name);
405 	if (ret) {
406 		kfree(group->name);
407 		group->name = NULL;
408 		return ret;
409 	}
410 
411 	return 0;
412 }
413 EXPORT_SYMBOL_GPL(iommu_group_set_name);
414 
415 static int iommu_group_create_direct_mappings(struct iommu_group *group,
416 					      struct device *dev)
417 {
418 	struct iommu_domain *domain = group->default_domain;
419 	struct iommu_resv_region *entry;
420 	struct list_head mappings;
421 	unsigned long pg_size;
422 	int ret = 0;
423 
424 	if (!domain || domain->type != IOMMU_DOMAIN_DMA)
425 		return 0;
426 
427 	BUG_ON(!domain->pgsize_bitmap);
428 
429 	pg_size = 1UL << __ffs(domain->pgsize_bitmap);
430 	INIT_LIST_HEAD(&mappings);
431 
432 	iommu_get_resv_regions(dev, &mappings);
433 
434 	/* We need to consider overlapping regions for different devices */
435 	list_for_each_entry(entry, &mappings, list) {
436 		dma_addr_t start, end, addr;
437 
438 		if (domain->ops->apply_resv_region)
439 			domain->ops->apply_resv_region(dev, domain, entry);
440 
441 		start = ALIGN(entry->start, pg_size);
442 		end   = ALIGN(entry->start + entry->length, pg_size);
443 
444 		if (entry->type != IOMMU_RESV_DIRECT)
445 			continue;
446 
447 		for (addr = start; addr < end; addr += pg_size) {
448 			phys_addr_t phys_addr;
449 
450 			phys_addr = iommu_iova_to_phys(domain, addr);
451 			if (phys_addr)
452 				continue;
453 
454 			ret = iommu_map(domain, addr, addr, pg_size, entry->prot);
455 			if (ret)
456 				goto out;
457 		}
458 
459 	}
460 
461 out:
462 	iommu_put_resv_regions(dev, &mappings);
463 
464 	return ret;
465 }
466 
467 /**
468  * iommu_group_add_device - add a device to an iommu group
469  * @group: the group into which to add the device (reference should be held)
470  * @dev: the device
471  *
472  * This function is called by an iommu driver to add a device into a
473  * group.  Adding a device increments the group reference count.
474  */
475 int iommu_group_add_device(struct iommu_group *group, struct device *dev)
476 {
477 	int ret, i = 0;
478 	struct iommu_device *device;
479 
480 	device = kzalloc(sizeof(*device), GFP_KERNEL);
481 	if (!device)
482 		return -ENOMEM;
483 
484 	device->dev = dev;
485 
486 	ret = sysfs_create_link(&dev->kobj, &group->kobj, "iommu_group");
487 	if (ret) {
488 		kfree(device);
489 		return ret;
490 	}
491 
492 	device->name = kasprintf(GFP_KERNEL, "%s", kobject_name(&dev->kobj));
493 rename:
494 	if (!device->name) {
495 		sysfs_remove_link(&dev->kobj, "iommu_group");
496 		kfree(device);
497 		return -ENOMEM;
498 	}
499 
500 	ret = sysfs_create_link_nowarn(group->devices_kobj,
501 				       &dev->kobj, device->name);
502 	if (ret) {
503 		kfree(device->name);
504 		if (ret == -EEXIST && i >= 0) {
505 			/*
506 			 * Account for the slim chance of collision
507 			 * and append an instance to the name.
508 			 */
509 			device->name = kasprintf(GFP_KERNEL, "%s.%d",
510 						 kobject_name(&dev->kobj), i++);
511 			goto rename;
512 		}
513 
514 		sysfs_remove_link(&dev->kobj, "iommu_group");
515 		kfree(device);
516 		return ret;
517 	}
518 
519 	kobject_get(group->devices_kobj);
520 
521 	dev->iommu_group = group;
522 
523 	iommu_group_create_direct_mappings(group, dev);
524 
525 	mutex_lock(&group->mutex);
526 	list_add_tail(&device->list, &group->devices);
527 	if (group->domain)
528 		__iommu_attach_device(group->domain, dev);
529 	mutex_unlock(&group->mutex);
530 
531 	/* Notify any listeners about change to group. */
532 	blocking_notifier_call_chain(&group->notifier,
533 				     IOMMU_GROUP_NOTIFY_ADD_DEVICE, dev);
534 
535 	trace_add_device_to_group(group->id, dev);
536 
537 	pr_info("Adding device %s to group %d\n", dev_name(dev), group->id);
538 
539 	return 0;
540 }
541 EXPORT_SYMBOL_GPL(iommu_group_add_device);
542 
543 /**
544  * iommu_group_remove_device - remove a device from it's current group
545  * @dev: device to be removed
546  *
547  * This function is called by an iommu driver to remove the device from
548  * it's current group.  This decrements the iommu group reference count.
549  */
550 void iommu_group_remove_device(struct device *dev)
551 {
552 	struct iommu_group *group = dev->iommu_group;
553 	struct iommu_device *tmp_device, *device = NULL;
554 
555 	pr_info("Removing device %s from group %d\n", dev_name(dev), group->id);
556 
557 	/* Pre-notify listeners that a device is being removed. */
558 	blocking_notifier_call_chain(&group->notifier,
559 				     IOMMU_GROUP_NOTIFY_DEL_DEVICE, dev);
560 
561 	mutex_lock(&group->mutex);
562 	list_for_each_entry(tmp_device, &group->devices, list) {
563 		if (tmp_device->dev == dev) {
564 			device = tmp_device;
565 			list_del(&device->list);
566 			break;
567 		}
568 	}
569 	mutex_unlock(&group->mutex);
570 
571 	if (!device)
572 		return;
573 
574 	sysfs_remove_link(group->devices_kobj, device->name);
575 	sysfs_remove_link(&dev->kobj, "iommu_group");
576 
577 	trace_remove_device_from_group(group->id, dev);
578 
579 	kfree(device->name);
580 	kfree(device);
581 	dev->iommu_group = NULL;
582 	kobject_put(group->devices_kobj);
583 }
584 EXPORT_SYMBOL_GPL(iommu_group_remove_device);
585 
586 static int iommu_group_device_count(struct iommu_group *group)
587 {
588 	struct iommu_device *entry;
589 	int ret = 0;
590 
591 	list_for_each_entry(entry, &group->devices, list)
592 		ret++;
593 
594 	return ret;
595 }
596 
597 /**
598  * iommu_group_for_each_dev - iterate over each device in the group
599  * @group: the group
600  * @data: caller opaque data to be passed to callback function
601  * @fn: caller supplied callback function
602  *
603  * This function is called by group users to iterate over group devices.
604  * Callers should hold a reference count to the group during callback.
605  * The group->mutex is held across callbacks, which will block calls to
606  * iommu_group_add/remove_device.
607  */
608 static int __iommu_group_for_each_dev(struct iommu_group *group, void *data,
609 				      int (*fn)(struct device *, void *))
610 {
611 	struct iommu_device *device;
612 	int ret = 0;
613 
614 	list_for_each_entry(device, &group->devices, list) {
615 		ret = fn(device->dev, data);
616 		if (ret)
617 			break;
618 	}
619 	return ret;
620 }
621 
622 
623 int iommu_group_for_each_dev(struct iommu_group *group, void *data,
624 			     int (*fn)(struct device *, void *))
625 {
626 	int ret;
627 
628 	mutex_lock(&group->mutex);
629 	ret = __iommu_group_for_each_dev(group, data, fn);
630 	mutex_unlock(&group->mutex);
631 
632 	return ret;
633 }
634 EXPORT_SYMBOL_GPL(iommu_group_for_each_dev);
635 
636 /**
637  * iommu_group_get - Return the group for a device and increment reference
638  * @dev: get the group that this device belongs to
639  *
640  * This function is called by iommu drivers and users to get the group
641  * for the specified device.  If found, the group is returned and the group
642  * reference in incremented, else NULL.
643  */
644 struct iommu_group *iommu_group_get(struct device *dev)
645 {
646 	struct iommu_group *group = dev->iommu_group;
647 
648 	if (group)
649 		kobject_get(group->devices_kobj);
650 
651 	return group;
652 }
653 EXPORT_SYMBOL_GPL(iommu_group_get);
654 
655 /**
656  * iommu_group_ref_get - Increment reference on a group
657  * @group: the group to use, must not be NULL
658  *
659  * This function is called by iommu drivers to take additional references on an
660  * existing group.  Returns the given group for convenience.
661  */
662 struct iommu_group *iommu_group_ref_get(struct iommu_group *group)
663 {
664 	kobject_get(group->devices_kobj);
665 	return group;
666 }
667 
668 /**
669  * iommu_group_put - Decrement group reference
670  * @group: the group to use
671  *
672  * This function is called by iommu drivers and users to release the
673  * iommu group.  Once the reference count is zero, the group is released.
674  */
675 void iommu_group_put(struct iommu_group *group)
676 {
677 	if (group)
678 		kobject_put(group->devices_kobj);
679 }
680 EXPORT_SYMBOL_GPL(iommu_group_put);
681 
682 /**
683  * iommu_group_register_notifier - Register a notifier for group changes
684  * @group: the group to watch
685  * @nb: notifier block to signal
686  *
687  * This function allows iommu group users to track changes in a group.
688  * See include/linux/iommu.h for actions sent via this notifier.  Caller
689  * should hold a reference to the group throughout notifier registration.
690  */
691 int iommu_group_register_notifier(struct iommu_group *group,
692 				  struct notifier_block *nb)
693 {
694 	return blocking_notifier_chain_register(&group->notifier, nb);
695 }
696 EXPORT_SYMBOL_GPL(iommu_group_register_notifier);
697 
698 /**
699  * iommu_group_unregister_notifier - Unregister a notifier
700  * @group: the group to watch
701  * @nb: notifier block to signal
702  *
703  * Unregister a previously registered group notifier block.
704  */
705 int iommu_group_unregister_notifier(struct iommu_group *group,
706 				    struct notifier_block *nb)
707 {
708 	return blocking_notifier_chain_unregister(&group->notifier, nb);
709 }
710 EXPORT_SYMBOL_GPL(iommu_group_unregister_notifier);
711 
712 /**
713  * iommu_group_id - Return ID for a group
714  * @group: the group to ID
715  *
716  * Return the unique ID for the group matching the sysfs group number.
717  */
718 int iommu_group_id(struct iommu_group *group)
719 {
720 	return group->id;
721 }
722 EXPORT_SYMBOL_GPL(iommu_group_id);
723 
724 static struct iommu_group *get_pci_alias_group(struct pci_dev *pdev,
725 					       unsigned long *devfns);
726 
727 /*
728  * To consider a PCI device isolated, we require ACS to support Source
729  * Validation, Request Redirection, Completer Redirection, and Upstream
730  * Forwarding.  This effectively means that devices cannot spoof their
731  * requester ID, requests and completions cannot be redirected, and all
732  * transactions are forwarded upstream, even as it passes through a
733  * bridge where the target device is downstream.
734  */
735 #define REQ_ACS_FLAGS   (PCI_ACS_SV | PCI_ACS_RR | PCI_ACS_CR | PCI_ACS_UF)
736 
737 /*
738  * For multifunction devices which are not isolated from each other, find
739  * all the other non-isolated functions and look for existing groups.  For
740  * each function, we also need to look for aliases to or from other devices
741  * that may already have a group.
742  */
743 static struct iommu_group *get_pci_function_alias_group(struct pci_dev *pdev,
744 							unsigned long *devfns)
745 {
746 	struct pci_dev *tmp = NULL;
747 	struct iommu_group *group;
748 
749 	if (!pdev->multifunction || pci_acs_enabled(pdev, REQ_ACS_FLAGS))
750 		return NULL;
751 
752 	for_each_pci_dev(tmp) {
753 		if (tmp == pdev || tmp->bus != pdev->bus ||
754 		    PCI_SLOT(tmp->devfn) != PCI_SLOT(pdev->devfn) ||
755 		    pci_acs_enabled(tmp, REQ_ACS_FLAGS))
756 			continue;
757 
758 		group = get_pci_alias_group(tmp, devfns);
759 		if (group) {
760 			pci_dev_put(tmp);
761 			return group;
762 		}
763 	}
764 
765 	return NULL;
766 }
767 
768 /*
769  * Look for aliases to or from the given device for existing groups. DMA
770  * aliases are only supported on the same bus, therefore the search
771  * space is quite small (especially since we're really only looking at pcie
772  * device, and therefore only expect multiple slots on the root complex or
773  * downstream switch ports).  It's conceivable though that a pair of
774  * multifunction devices could have aliases between them that would cause a
775  * loop.  To prevent this, we use a bitmap to track where we've been.
776  */
777 static struct iommu_group *get_pci_alias_group(struct pci_dev *pdev,
778 					       unsigned long *devfns)
779 {
780 	struct pci_dev *tmp = NULL;
781 	struct iommu_group *group;
782 
783 	if (test_and_set_bit(pdev->devfn & 0xff, devfns))
784 		return NULL;
785 
786 	group = iommu_group_get(&pdev->dev);
787 	if (group)
788 		return group;
789 
790 	for_each_pci_dev(tmp) {
791 		if (tmp == pdev || tmp->bus != pdev->bus)
792 			continue;
793 
794 		/* We alias them or they alias us */
795 		if (pci_devs_are_dma_aliases(pdev, tmp)) {
796 			group = get_pci_alias_group(tmp, devfns);
797 			if (group) {
798 				pci_dev_put(tmp);
799 				return group;
800 			}
801 
802 			group = get_pci_function_alias_group(tmp, devfns);
803 			if (group) {
804 				pci_dev_put(tmp);
805 				return group;
806 			}
807 		}
808 	}
809 
810 	return NULL;
811 }
812 
813 struct group_for_pci_data {
814 	struct pci_dev *pdev;
815 	struct iommu_group *group;
816 };
817 
818 /*
819  * DMA alias iterator callback, return the last seen device.  Stop and return
820  * the IOMMU group if we find one along the way.
821  */
822 static int get_pci_alias_or_group(struct pci_dev *pdev, u16 alias, void *opaque)
823 {
824 	struct group_for_pci_data *data = opaque;
825 
826 	data->pdev = pdev;
827 	data->group = iommu_group_get(&pdev->dev);
828 
829 	return data->group != NULL;
830 }
831 
832 /*
833  * Generic device_group call-back function. It just allocates one
834  * iommu-group per device.
835  */
836 struct iommu_group *generic_device_group(struct device *dev)
837 {
838 	struct iommu_group *group;
839 
840 	group = iommu_group_alloc();
841 	if (IS_ERR(group))
842 		return NULL;
843 
844 	return group;
845 }
846 
847 /*
848  * Use standard PCI bus topology, isolation features, and DMA alias quirks
849  * to find or create an IOMMU group for a device.
850  */
851 struct iommu_group *pci_device_group(struct device *dev)
852 {
853 	struct pci_dev *pdev = to_pci_dev(dev);
854 	struct group_for_pci_data data;
855 	struct pci_bus *bus;
856 	struct iommu_group *group = NULL;
857 	u64 devfns[4] = { 0 };
858 
859 	if (WARN_ON(!dev_is_pci(dev)))
860 		return ERR_PTR(-EINVAL);
861 
862 	/*
863 	 * Find the upstream DMA alias for the device.  A device must not
864 	 * be aliased due to topology in order to have its own IOMMU group.
865 	 * If we find an alias along the way that already belongs to a
866 	 * group, use it.
867 	 */
868 	if (pci_for_each_dma_alias(pdev, get_pci_alias_or_group, &data))
869 		return data.group;
870 
871 	pdev = data.pdev;
872 
873 	/*
874 	 * Continue upstream from the point of minimum IOMMU granularity
875 	 * due to aliases to the point where devices are protected from
876 	 * peer-to-peer DMA by PCI ACS.  Again, if we find an existing
877 	 * group, use it.
878 	 */
879 	for (bus = pdev->bus; !pci_is_root_bus(bus); bus = bus->parent) {
880 		if (!bus->self)
881 			continue;
882 
883 		if (pci_acs_path_enabled(bus->self, NULL, REQ_ACS_FLAGS))
884 			break;
885 
886 		pdev = bus->self;
887 
888 		group = iommu_group_get(&pdev->dev);
889 		if (group)
890 			return group;
891 	}
892 
893 	/*
894 	 * Look for existing groups on device aliases.  If we alias another
895 	 * device or another device aliases us, use the same group.
896 	 */
897 	group = get_pci_alias_group(pdev, (unsigned long *)devfns);
898 	if (group)
899 		return group;
900 
901 	/*
902 	 * Look for existing groups on non-isolated functions on the same
903 	 * slot and aliases of those funcions, if any.  No need to clear
904 	 * the search bitmap, the tested devfns are still valid.
905 	 */
906 	group = get_pci_function_alias_group(pdev, (unsigned long *)devfns);
907 	if (group)
908 		return group;
909 
910 	/* No shared group found, allocate new */
911 	group = iommu_group_alloc();
912 	if (IS_ERR(group))
913 		return NULL;
914 
915 	return group;
916 }
917 
918 /**
919  * iommu_group_get_for_dev - Find or create the IOMMU group for a device
920  * @dev: target device
921  *
922  * This function is intended to be called by IOMMU drivers and extended to
923  * support common, bus-defined algorithms when determining or creating the
924  * IOMMU group for a device.  On success, the caller will hold a reference
925  * to the returned IOMMU group, which will already include the provided
926  * device.  The reference should be released with iommu_group_put().
927  */
928 struct iommu_group *iommu_group_get_for_dev(struct device *dev)
929 {
930 	const struct iommu_ops *ops = dev->bus->iommu_ops;
931 	struct iommu_group *group;
932 	int ret;
933 
934 	group = iommu_group_get(dev);
935 	if (group)
936 		return group;
937 
938 	group = ERR_PTR(-EINVAL);
939 
940 	if (ops && ops->device_group)
941 		group = ops->device_group(dev);
942 
943 	if (IS_ERR(group))
944 		return group;
945 
946 	/*
947 	 * Try to allocate a default domain - needs support from the
948 	 * IOMMU driver.
949 	 */
950 	if (!group->default_domain) {
951 		group->default_domain = __iommu_domain_alloc(dev->bus,
952 							     IOMMU_DOMAIN_DMA);
953 		if (!group->domain)
954 			group->domain = group->default_domain;
955 	}
956 
957 	ret = iommu_group_add_device(group, dev);
958 	if (ret) {
959 		iommu_group_put(group);
960 		return ERR_PTR(ret);
961 	}
962 
963 	return group;
964 }
965 
966 struct iommu_domain *iommu_group_default_domain(struct iommu_group *group)
967 {
968 	return group->default_domain;
969 }
970 
971 static int add_iommu_group(struct device *dev, void *data)
972 {
973 	struct iommu_callback_data *cb = data;
974 	const struct iommu_ops *ops = cb->ops;
975 	int ret;
976 
977 	if (!ops->add_device)
978 		return 0;
979 
980 	WARN_ON(dev->iommu_group);
981 
982 	ret = ops->add_device(dev);
983 
984 	/*
985 	 * We ignore -ENODEV errors for now, as they just mean that the
986 	 * device is not translated by an IOMMU. We still care about
987 	 * other errors and fail to initialize when they happen.
988 	 */
989 	if (ret == -ENODEV)
990 		ret = 0;
991 
992 	return ret;
993 }
994 
995 static int remove_iommu_group(struct device *dev, void *data)
996 {
997 	struct iommu_callback_data *cb = data;
998 	const struct iommu_ops *ops = cb->ops;
999 
1000 	if (ops->remove_device && dev->iommu_group)
1001 		ops->remove_device(dev);
1002 
1003 	return 0;
1004 }
1005 
1006 static int iommu_bus_notifier(struct notifier_block *nb,
1007 			      unsigned long action, void *data)
1008 {
1009 	struct device *dev = data;
1010 	const struct iommu_ops *ops = dev->bus->iommu_ops;
1011 	struct iommu_group *group;
1012 	unsigned long group_action = 0;
1013 
1014 	/*
1015 	 * ADD/DEL call into iommu driver ops if provided, which may
1016 	 * result in ADD/DEL notifiers to group->notifier
1017 	 */
1018 	if (action == BUS_NOTIFY_ADD_DEVICE) {
1019 		if (ops->add_device)
1020 			return ops->add_device(dev);
1021 	} else if (action == BUS_NOTIFY_REMOVED_DEVICE) {
1022 		if (ops->remove_device && dev->iommu_group) {
1023 			ops->remove_device(dev);
1024 			return 0;
1025 		}
1026 	}
1027 
1028 	/*
1029 	 * Remaining BUS_NOTIFYs get filtered and republished to the
1030 	 * group, if anyone is listening
1031 	 */
1032 	group = iommu_group_get(dev);
1033 	if (!group)
1034 		return 0;
1035 
1036 	switch (action) {
1037 	case BUS_NOTIFY_BIND_DRIVER:
1038 		group_action = IOMMU_GROUP_NOTIFY_BIND_DRIVER;
1039 		break;
1040 	case BUS_NOTIFY_BOUND_DRIVER:
1041 		group_action = IOMMU_GROUP_NOTIFY_BOUND_DRIVER;
1042 		break;
1043 	case BUS_NOTIFY_UNBIND_DRIVER:
1044 		group_action = IOMMU_GROUP_NOTIFY_UNBIND_DRIVER;
1045 		break;
1046 	case BUS_NOTIFY_UNBOUND_DRIVER:
1047 		group_action = IOMMU_GROUP_NOTIFY_UNBOUND_DRIVER;
1048 		break;
1049 	}
1050 
1051 	if (group_action)
1052 		blocking_notifier_call_chain(&group->notifier,
1053 					     group_action, dev);
1054 
1055 	iommu_group_put(group);
1056 	return 0;
1057 }
1058 
1059 static int iommu_bus_init(struct bus_type *bus, const struct iommu_ops *ops)
1060 {
1061 	int err;
1062 	struct notifier_block *nb;
1063 	struct iommu_callback_data cb = {
1064 		.ops = ops,
1065 	};
1066 
1067 	nb = kzalloc(sizeof(struct notifier_block), GFP_KERNEL);
1068 	if (!nb)
1069 		return -ENOMEM;
1070 
1071 	nb->notifier_call = iommu_bus_notifier;
1072 
1073 	err = bus_register_notifier(bus, nb);
1074 	if (err)
1075 		goto out_free;
1076 
1077 	err = bus_for_each_dev(bus, NULL, &cb, add_iommu_group);
1078 	if (err)
1079 		goto out_err;
1080 
1081 
1082 	return 0;
1083 
1084 out_err:
1085 	/* Clean up */
1086 	bus_for_each_dev(bus, NULL, &cb, remove_iommu_group);
1087 	bus_unregister_notifier(bus, nb);
1088 
1089 out_free:
1090 	kfree(nb);
1091 
1092 	return err;
1093 }
1094 
1095 /**
1096  * bus_set_iommu - set iommu-callbacks for the bus
1097  * @bus: bus.
1098  * @ops: the callbacks provided by the iommu-driver
1099  *
1100  * This function is called by an iommu driver to set the iommu methods
1101  * used for a particular bus. Drivers for devices on that bus can use
1102  * the iommu-api after these ops are registered.
1103  * This special function is needed because IOMMUs are usually devices on
1104  * the bus itself, so the iommu drivers are not initialized when the bus
1105  * is set up. With this function the iommu-driver can set the iommu-ops
1106  * afterwards.
1107  */
1108 int bus_set_iommu(struct bus_type *bus, const struct iommu_ops *ops)
1109 {
1110 	int err;
1111 
1112 	if (bus->iommu_ops != NULL)
1113 		return -EBUSY;
1114 
1115 	bus->iommu_ops = ops;
1116 
1117 	/* Do IOMMU specific setup for this bus-type */
1118 	err = iommu_bus_init(bus, ops);
1119 	if (err)
1120 		bus->iommu_ops = NULL;
1121 
1122 	return err;
1123 }
1124 EXPORT_SYMBOL_GPL(bus_set_iommu);
1125 
1126 bool iommu_present(struct bus_type *bus)
1127 {
1128 	return bus->iommu_ops != NULL;
1129 }
1130 EXPORT_SYMBOL_GPL(iommu_present);
1131 
1132 bool iommu_capable(struct bus_type *bus, enum iommu_cap cap)
1133 {
1134 	if (!bus->iommu_ops || !bus->iommu_ops->capable)
1135 		return false;
1136 
1137 	return bus->iommu_ops->capable(cap);
1138 }
1139 EXPORT_SYMBOL_GPL(iommu_capable);
1140 
1141 /**
1142  * iommu_set_fault_handler() - set a fault handler for an iommu domain
1143  * @domain: iommu domain
1144  * @handler: fault handler
1145  * @token: user data, will be passed back to the fault handler
1146  *
1147  * This function should be used by IOMMU users which want to be notified
1148  * whenever an IOMMU fault happens.
1149  *
1150  * The fault handler itself should return 0 on success, and an appropriate
1151  * error code otherwise.
1152  */
1153 void iommu_set_fault_handler(struct iommu_domain *domain,
1154 					iommu_fault_handler_t handler,
1155 					void *token)
1156 {
1157 	BUG_ON(!domain);
1158 
1159 	domain->handler = handler;
1160 	domain->handler_token = token;
1161 }
1162 EXPORT_SYMBOL_GPL(iommu_set_fault_handler);
1163 
1164 static struct iommu_domain *__iommu_domain_alloc(struct bus_type *bus,
1165 						 unsigned type)
1166 {
1167 	struct iommu_domain *domain;
1168 
1169 	if (bus == NULL || bus->iommu_ops == NULL)
1170 		return NULL;
1171 
1172 	domain = bus->iommu_ops->domain_alloc(type);
1173 	if (!domain)
1174 		return NULL;
1175 
1176 	domain->ops  = bus->iommu_ops;
1177 	domain->type = type;
1178 	/* Assume all sizes by default; the driver may override this later */
1179 	domain->pgsize_bitmap  = bus->iommu_ops->pgsize_bitmap;
1180 
1181 	return domain;
1182 }
1183 
1184 struct iommu_domain *iommu_domain_alloc(struct bus_type *bus)
1185 {
1186 	return __iommu_domain_alloc(bus, IOMMU_DOMAIN_UNMANAGED);
1187 }
1188 EXPORT_SYMBOL_GPL(iommu_domain_alloc);
1189 
1190 void iommu_domain_free(struct iommu_domain *domain)
1191 {
1192 	domain->ops->domain_free(domain);
1193 }
1194 EXPORT_SYMBOL_GPL(iommu_domain_free);
1195 
1196 static int __iommu_attach_device(struct iommu_domain *domain,
1197 				 struct device *dev)
1198 {
1199 	int ret;
1200 	if (unlikely(domain->ops->attach_dev == NULL))
1201 		return -ENODEV;
1202 
1203 	ret = domain->ops->attach_dev(domain, dev);
1204 	if (!ret)
1205 		trace_attach_device_to_domain(dev);
1206 	return ret;
1207 }
1208 
1209 int iommu_attach_device(struct iommu_domain *domain, struct device *dev)
1210 {
1211 	struct iommu_group *group;
1212 	int ret;
1213 
1214 	group = iommu_group_get(dev);
1215 	/* FIXME: Remove this when groups a mandatory for iommu drivers */
1216 	if (group == NULL)
1217 		return __iommu_attach_device(domain, dev);
1218 
1219 	/*
1220 	 * We have a group - lock it to make sure the device-count doesn't
1221 	 * change while we are attaching
1222 	 */
1223 	mutex_lock(&group->mutex);
1224 	ret = -EINVAL;
1225 	if (iommu_group_device_count(group) != 1)
1226 		goto out_unlock;
1227 
1228 	ret = __iommu_attach_group(domain, group);
1229 
1230 out_unlock:
1231 	mutex_unlock(&group->mutex);
1232 	iommu_group_put(group);
1233 
1234 	return ret;
1235 }
1236 EXPORT_SYMBOL_GPL(iommu_attach_device);
1237 
1238 static void __iommu_detach_device(struct iommu_domain *domain,
1239 				  struct device *dev)
1240 {
1241 	if (unlikely(domain->ops->detach_dev == NULL))
1242 		return;
1243 
1244 	domain->ops->detach_dev(domain, dev);
1245 	trace_detach_device_from_domain(dev);
1246 }
1247 
1248 void iommu_detach_device(struct iommu_domain *domain, struct device *dev)
1249 {
1250 	struct iommu_group *group;
1251 
1252 	group = iommu_group_get(dev);
1253 	/* FIXME: Remove this when groups a mandatory for iommu drivers */
1254 	if (group == NULL)
1255 		return __iommu_detach_device(domain, dev);
1256 
1257 	mutex_lock(&group->mutex);
1258 	if (iommu_group_device_count(group) != 1) {
1259 		WARN_ON(1);
1260 		goto out_unlock;
1261 	}
1262 
1263 	__iommu_detach_group(domain, group);
1264 
1265 out_unlock:
1266 	mutex_unlock(&group->mutex);
1267 	iommu_group_put(group);
1268 }
1269 EXPORT_SYMBOL_GPL(iommu_detach_device);
1270 
1271 struct iommu_domain *iommu_get_domain_for_dev(struct device *dev)
1272 {
1273 	struct iommu_domain *domain;
1274 	struct iommu_group *group;
1275 
1276 	group = iommu_group_get(dev);
1277 	/* FIXME: Remove this when groups a mandatory for iommu drivers */
1278 	if (group == NULL)
1279 		return NULL;
1280 
1281 	domain = group->domain;
1282 
1283 	iommu_group_put(group);
1284 
1285 	return domain;
1286 }
1287 EXPORT_SYMBOL_GPL(iommu_get_domain_for_dev);
1288 
1289 /*
1290  * IOMMU groups are really the natrual working unit of the IOMMU, but
1291  * the IOMMU API works on domains and devices.  Bridge that gap by
1292  * iterating over the devices in a group.  Ideally we'd have a single
1293  * device which represents the requestor ID of the group, but we also
1294  * allow IOMMU drivers to create policy defined minimum sets, where
1295  * the physical hardware may be able to distiguish members, but we
1296  * wish to group them at a higher level (ex. untrusted multi-function
1297  * PCI devices).  Thus we attach each device.
1298  */
1299 static int iommu_group_do_attach_device(struct device *dev, void *data)
1300 {
1301 	struct iommu_domain *domain = data;
1302 
1303 	return __iommu_attach_device(domain, dev);
1304 }
1305 
1306 static int __iommu_attach_group(struct iommu_domain *domain,
1307 				struct iommu_group *group)
1308 {
1309 	int ret;
1310 
1311 	if (group->default_domain && group->domain != group->default_domain)
1312 		return -EBUSY;
1313 
1314 	ret = __iommu_group_for_each_dev(group, domain,
1315 					 iommu_group_do_attach_device);
1316 	if (ret == 0)
1317 		group->domain = domain;
1318 
1319 	return ret;
1320 }
1321 
1322 int iommu_attach_group(struct iommu_domain *domain, struct iommu_group *group)
1323 {
1324 	int ret;
1325 
1326 	mutex_lock(&group->mutex);
1327 	ret = __iommu_attach_group(domain, group);
1328 	mutex_unlock(&group->mutex);
1329 
1330 	return ret;
1331 }
1332 EXPORT_SYMBOL_GPL(iommu_attach_group);
1333 
1334 static int iommu_group_do_detach_device(struct device *dev, void *data)
1335 {
1336 	struct iommu_domain *domain = data;
1337 
1338 	__iommu_detach_device(domain, dev);
1339 
1340 	return 0;
1341 }
1342 
1343 static void __iommu_detach_group(struct iommu_domain *domain,
1344 				 struct iommu_group *group)
1345 {
1346 	int ret;
1347 
1348 	if (!group->default_domain) {
1349 		__iommu_group_for_each_dev(group, domain,
1350 					   iommu_group_do_detach_device);
1351 		group->domain = NULL;
1352 		return;
1353 	}
1354 
1355 	if (group->domain == group->default_domain)
1356 		return;
1357 
1358 	/* Detach by re-attaching to the default domain */
1359 	ret = __iommu_group_for_each_dev(group, group->default_domain,
1360 					 iommu_group_do_attach_device);
1361 	if (ret != 0)
1362 		WARN_ON(1);
1363 	else
1364 		group->domain = group->default_domain;
1365 }
1366 
1367 void iommu_detach_group(struct iommu_domain *domain, struct iommu_group *group)
1368 {
1369 	mutex_lock(&group->mutex);
1370 	__iommu_detach_group(domain, group);
1371 	mutex_unlock(&group->mutex);
1372 }
1373 EXPORT_SYMBOL_GPL(iommu_detach_group);
1374 
1375 phys_addr_t iommu_iova_to_phys(struct iommu_domain *domain, dma_addr_t iova)
1376 {
1377 	if (unlikely(domain->ops->iova_to_phys == NULL))
1378 		return 0;
1379 
1380 	return domain->ops->iova_to_phys(domain, iova);
1381 }
1382 EXPORT_SYMBOL_GPL(iommu_iova_to_phys);
1383 
1384 static size_t iommu_pgsize(struct iommu_domain *domain,
1385 			   unsigned long addr_merge, size_t size)
1386 {
1387 	unsigned int pgsize_idx;
1388 	size_t pgsize;
1389 
1390 	/* Max page size that still fits into 'size' */
1391 	pgsize_idx = __fls(size);
1392 
1393 	/* need to consider alignment requirements ? */
1394 	if (likely(addr_merge)) {
1395 		/* Max page size allowed by address */
1396 		unsigned int align_pgsize_idx = __ffs(addr_merge);
1397 		pgsize_idx = min(pgsize_idx, align_pgsize_idx);
1398 	}
1399 
1400 	/* build a mask of acceptable page sizes */
1401 	pgsize = (1UL << (pgsize_idx + 1)) - 1;
1402 
1403 	/* throw away page sizes not supported by the hardware */
1404 	pgsize &= domain->pgsize_bitmap;
1405 
1406 	/* make sure we're still sane */
1407 	BUG_ON(!pgsize);
1408 
1409 	/* pick the biggest page */
1410 	pgsize_idx = __fls(pgsize);
1411 	pgsize = 1UL << pgsize_idx;
1412 
1413 	return pgsize;
1414 }
1415 
1416 int iommu_map(struct iommu_domain *domain, unsigned long iova,
1417 	      phys_addr_t paddr, size_t size, int prot)
1418 {
1419 	unsigned long orig_iova = iova;
1420 	unsigned int min_pagesz;
1421 	size_t orig_size = size;
1422 	phys_addr_t orig_paddr = paddr;
1423 	int ret = 0;
1424 
1425 	if (unlikely(domain->ops->map == NULL ||
1426 		     domain->pgsize_bitmap == 0UL))
1427 		return -ENODEV;
1428 
1429 	if (unlikely(!(domain->type & __IOMMU_DOMAIN_PAGING)))
1430 		return -EINVAL;
1431 
1432 	/* find out the minimum page size supported */
1433 	min_pagesz = 1 << __ffs(domain->pgsize_bitmap);
1434 
1435 	/*
1436 	 * both the virtual address and the physical one, as well as
1437 	 * the size of the mapping, must be aligned (at least) to the
1438 	 * size of the smallest page supported by the hardware
1439 	 */
1440 	if (!IS_ALIGNED(iova | paddr | size, min_pagesz)) {
1441 		pr_err("unaligned: iova 0x%lx pa %pa size 0x%zx min_pagesz 0x%x\n",
1442 		       iova, &paddr, size, min_pagesz);
1443 		return -EINVAL;
1444 	}
1445 
1446 	pr_debug("map: iova 0x%lx pa %pa size 0x%zx\n", iova, &paddr, size);
1447 
1448 	while (size) {
1449 		size_t pgsize = iommu_pgsize(domain, iova | paddr, size);
1450 
1451 		pr_debug("mapping: iova 0x%lx pa %pa pgsize 0x%zx\n",
1452 			 iova, &paddr, pgsize);
1453 
1454 		ret = domain->ops->map(domain, iova, paddr, pgsize, prot);
1455 		if (ret)
1456 			break;
1457 
1458 		iova += pgsize;
1459 		paddr += pgsize;
1460 		size -= pgsize;
1461 	}
1462 
1463 	/* unroll mapping in case something went wrong */
1464 	if (ret)
1465 		iommu_unmap(domain, orig_iova, orig_size - size);
1466 	else
1467 		trace_map(orig_iova, orig_paddr, orig_size);
1468 
1469 	return ret;
1470 }
1471 EXPORT_SYMBOL_GPL(iommu_map);
1472 
1473 size_t iommu_unmap(struct iommu_domain *domain, unsigned long iova, size_t size)
1474 {
1475 	size_t unmapped_page, unmapped = 0;
1476 	unsigned int min_pagesz;
1477 	unsigned long orig_iova = iova;
1478 
1479 	if (unlikely(domain->ops->unmap == NULL ||
1480 		     domain->pgsize_bitmap == 0UL))
1481 		return -ENODEV;
1482 
1483 	if (unlikely(!(domain->type & __IOMMU_DOMAIN_PAGING)))
1484 		return -EINVAL;
1485 
1486 	/* find out the minimum page size supported */
1487 	min_pagesz = 1 << __ffs(domain->pgsize_bitmap);
1488 
1489 	/*
1490 	 * The virtual address, as well as the size of the mapping, must be
1491 	 * aligned (at least) to the size of the smallest page supported
1492 	 * by the hardware
1493 	 */
1494 	if (!IS_ALIGNED(iova | size, min_pagesz)) {
1495 		pr_err("unaligned: iova 0x%lx size 0x%zx min_pagesz 0x%x\n",
1496 		       iova, size, min_pagesz);
1497 		return -EINVAL;
1498 	}
1499 
1500 	pr_debug("unmap this: iova 0x%lx size 0x%zx\n", iova, size);
1501 
1502 	/*
1503 	 * Keep iterating until we either unmap 'size' bytes (or more)
1504 	 * or we hit an area that isn't mapped.
1505 	 */
1506 	while (unmapped < size) {
1507 		size_t pgsize = iommu_pgsize(domain, iova, size - unmapped);
1508 
1509 		unmapped_page = domain->ops->unmap(domain, iova, pgsize);
1510 		if (!unmapped_page)
1511 			break;
1512 
1513 		pr_debug("unmapped: iova 0x%lx size 0x%zx\n",
1514 			 iova, unmapped_page);
1515 
1516 		iova += unmapped_page;
1517 		unmapped += unmapped_page;
1518 	}
1519 
1520 	trace_unmap(orig_iova, size, unmapped);
1521 	return unmapped;
1522 }
1523 EXPORT_SYMBOL_GPL(iommu_unmap);
1524 
1525 size_t default_iommu_map_sg(struct iommu_domain *domain, unsigned long iova,
1526 			 struct scatterlist *sg, unsigned int nents, int prot)
1527 {
1528 	struct scatterlist *s;
1529 	size_t mapped = 0;
1530 	unsigned int i, min_pagesz;
1531 	int ret;
1532 
1533 	if (unlikely(domain->pgsize_bitmap == 0UL))
1534 		return 0;
1535 
1536 	min_pagesz = 1 << __ffs(domain->pgsize_bitmap);
1537 
1538 	for_each_sg(sg, s, nents, i) {
1539 		phys_addr_t phys = page_to_phys(sg_page(s)) + s->offset;
1540 
1541 		/*
1542 		 * We are mapping on IOMMU page boundaries, so offset within
1543 		 * the page must be 0. However, the IOMMU may support pages
1544 		 * smaller than PAGE_SIZE, so s->offset may still represent
1545 		 * an offset of that boundary within the CPU page.
1546 		 */
1547 		if (!IS_ALIGNED(s->offset, min_pagesz))
1548 			goto out_err;
1549 
1550 		ret = iommu_map(domain, iova + mapped, phys, s->length, prot);
1551 		if (ret)
1552 			goto out_err;
1553 
1554 		mapped += s->length;
1555 	}
1556 
1557 	return mapped;
1558 
1559 out_err:
1560 	/* undo mappings already done */
1561 	iommu_unmap(domain, iova, mapped);
1562 
1563 	return 0;
1564 
1565 }
1566 EXPORT_SYMBOL_GPL(default_iommu_map_sg);
1567 
1568 int iommu_domain_window_enable(struct iommu_domain *domain, u32 wnd_nr,
1569 			       phys_addr_t paddr, u64 size, int prot)
1570 {
1571 	if (unlikely(domain->ops->domain_window_enable == NULL))
1572 		return -ENODEV;
1573 
1574 	return domain->ops->domain_window_enable(domain, wnd_nr, paddr, size,
1575 						 prot);
1576 }
1577 EXPORT_SYMBOL_GPL(iommu_domain_window_enable);
1578 
1579 void iommu_domain_window_disable(struct iommu_domain *domain, u32 wnd_nr)
1580 {
1581 	if (unlikely(domain->ops->domain_window_disable == NULL))
1582 		return;
1583 
1584 	return domain->ops->domain_window_disable(domain, wnd_nr);
1585 }
1586 EXPORT_SYMBOL_GPL(iommu_domain_window_disable);
1587 
1588 static int __init iommu_init(void)
1589 {
1590 	iommu_group_kset = kset_create_and_add("iommu_groups",
1591 					       NULL, kernel_kobj);
1592 	BUG_ON(!iommu_group_kset);
1593 
1594 	return 0;
1595 }
1596 core_initcall(iommu_init);
1597 
1598 int iommu_domain_get_attr(struct iommu_domain *domain,
1599 			  enum iommu_attr attr, void *data)
1600 {
1601 	struct iommu_domain_geometry *geometry;
1602 	bool *paging;
1603 	int ret = 0;
1604 	u32 *count;
1605 
1606 	switch (attr) {
1607 	case DOMAIN_ATTR_GEOMETRY:
1608 		geometry  = data;
1609 		*geometry = domain->geometry;
1610 
1611 		break;
1612 	case DOMAIN_ATTR_PAGING:
1613 		paging  = data;
1614 		*paging = (domain->pgsize_bitmap != 0UL);
1615 		break;
1616 	case DOMAIN_ATTR_WINDOWS:
1617 		count = data;
1618 
1619 		if (domain->ops->domain_get_windows != NULL)
1620 			*count = domain->ops->domain_get_windows(domain);
1621 		else
1622 			ret = -ENODEV;
1623 
1624 		break;
1625 	default:
1626 		if (!domain->ops->domain_get_attr)
1627 			return -EINVAL;
1628 
1629 		ret = domain->ops->domain_get_attr(domain, attr, data);
1630 	}
1631 
1632 	return ret;
1633 }
1634 EXPORT_SYMBOL_GPL(iommu_domain_get_attr);
1635 
1636 int iommu_domain_set_attr(struct iommu_domain *domain,
1637 			  enum iommu_attr attr, void *data)
1638 {
1639 	int ret = 0;
1640 	u32 *count;
1641 
1642 	switch (attr) {
1643 	case DOMAIN_ATTR_WINDOWS:
1644 		count = data;
1645 
1646 		if (domain->ops->domain_set_windows != NULL)
1647 			ret = domain->ops->domain_set_windows(domain, *count);
1648 		else
1649 			ret = -ENODEV;
1650 
1651 		break;
1652 	default:
1653 		if (domain->ops->domain_set_attr == NULL)
1654 			return -EINVAL;
1655 
1656 		ret = domain->ops->domain_set_attr(domain, attr, data);
1657 	}
1658 
1659 	return ret;
1660 }
1661 EXPORT_SYMBOL_GPL(iommu_domain_set_attr);
1662 
1663 void iommu_get_resv_regions(struct device *dev, struct list_head *list)
1664 {
1665 	const struct iommu_ops *ops = dev->bus->iommu_ops;
1666 
1667 	if (ops && ops->get_resv_regions)
1668 		ops->get_resv_regions(dev, list);
1669 }
1670 
1671 void iommu_put_resv_regions(struct device *dev, struct list_head *list)
1672 {
1673 	const struct iommu_ops *ops = dev->bus->iommu_ops;
1674 
1675 	if (ops && ops->put_resv_regions)
1676 		ops->put_resv_regions(dev, list);
1677 }
1678 
1679 struct iommu_resv_region *iommu_alloc_resv_region(phys_addr_t start,
1680 						  size_t length,
1681 						  int prot, int type)
1682 {
1683 	struct iommu_resv_region *region;
1684 
1685 	region = kzalloc(sizeof(*region), GFP_KERNEL);
1686 	if (!region)
1687 		return NULL;
1688 
1689 	INIT_LIST_HEAD(&region->list);
1690 	region->start = start;
1691 	region->length = length;
1692 	region->prot = prot;
1693 	region->type = type;
1694 	return region;
1695 }
1696 
1697 /* Request that a device is direct mapped by the IOMMU */
1698 int iommu_request_dm_for_dev(struct device *dev)
1699 {
1700 	struct iommu_domain *dm_domain;
1701 	struct iommu_group *group;
1702 	int ret;
1703 
1704 	/* Device must already be in a group before calling this function */
1705 	group = iommu_group_get_for_dev(dev);
1706 	if (IS_ERR(group))
1707 		return PTR_ERR(group);
1708 
1709 	mutex_lock(&group->mutex);
1710 
1711 	/* Check if the default domain is already direct mapped */
1712 	ret = 0;
1713 	if (group->default_domain &&
1714 	    group->default_domain->type == IOMMU_DOMAIN_IDENTITY)
1715 		goto out;
1716 
1717 	/* Don't change mappings of existing devices */
1718 	ret = -EBUSY;
1719 	if (iommu_group_device_count(group) != 1)
1720 		goto out;
1721 
1722 	/* Allocate a direct mapped domain */
1723 	ret = -ENOMEM;
1724 	dm_domain = __iommu_domain_alloc(dev->bus, IOMMU_DOMAIN_IDENTITY);
1725 	if (!dm_domain)
1726 		goto out;
1727 
1728 	/* Attach the device to the domain */
1729 	ret = __iommu_attach_group(dm_domain, group);
1730 	if (ret) {
1731 		iommu_domain_free(dm_domain);
1732 		goto out;
1733 	}
1734 
1735 	/* Make the direct mapped domain the default for this group */
1736 	if (group->default_domain)
1737 		iommu_domain_free(group->default_domain);
1738 	group->default_domain = dm_domain;
1739 
1740 	pr_info("Using direct mapping for device %s\n", dev_name(dev));
1741 
1742 	ret = 0;
1743 out:
1744 	mutex_unlock(&group->mutex);
1745 	iommu_group_put(group);
1746 
1747 	return ret;
1748 }
1749 
1750 struct iommu_instance {
1751 	struct list_head list;
1752 	struct fwnode_handle *fwnode;
1753 	const struct iommu_ops *ops;
1754 };
1755 static LIST_HEAD(iommu_instance_list);
1756 static DEFINE_SPINLOCK(iommu_instance_lock);
1757 
1758 void iommu_register_instance(struct fwnode_handle *fwnode,
1759 			     const struct iommu_ops *ops)
1760 {
1761 	struct iommu_instance *iommu = kzalloc(sizeof(*iommu), GFP_KERNEL);
1762 
1763 	if (WARN_ON(!iommu))
1764 		return;
1765 
1766 	of_node_get(to_of_node(fwnode));
1767 	INIT_LIST_HEAD(&iommu->list);
1768 	iommu->fwnode = fwnode;
1769 	iommu->ops = ops;
1770 	spin_lock(&iommu_instance_lock);
1771 	list_add_tail(&iommu->list, &iommu_instance_list);
1772 	spin_unlock(&iommu_instance_lock);
1773 }
1774 
1775 const struct iommu_ops *iommu_get_instance(struct fwnode_handle *fwnode)
1776 {
1777 	struct iommu_instance *instance;
1778 	const struct iommu_ops *ops = NULL;
1779 
1780 	spin_lock(&iommu_instance_lock);
1781 	list_for_each_entry(instance, &iommu_instance_list, list)
1782 		if (instance->fwnode == fwnode) {
1783 			ops = instance->ops;
1784 			break;
1785 		}
1786 	spin_unlock(&iommu_instance_lock);
1787 	return ops;
1788 }
1789 
1790 int iommu_fwspec_init(struct device *dev, struct fwnode_handle *iommu_fwnode,
1791 		      const struct iommu_ops *ops)
1792 {
1793 	struct iommu_fwspec *fwspec = dev->iommu_fwspec;
1794 
1795 	if (fwspec)
1796 		return ops == fwspec->ops ? 0 : -EINVAL;
1797 
1798 	fwspec = kzalloc(sizeof(*fwspec), GFP_KERNEL);
1799 	if (!fwspec)
1800 		return -ENOMEM;
1801 
1802 	of_node_get(to_of_node(iommu_fwnode));
1803 	fwspec->iommu_fwnode = iommu_fwnode;
1804 	fwspec->ops = ops;
1805 	dev->iommu_fwspec = fwspec;
1806 	return 0;
1807 }
1808 EXPORT_SYMBOL_GPL(iommu_fwspec_init);
1809 
1810 void iommu_fwspec_free(struct device *dev)
1811 {
1812 	struct iommu_fwspec *fwspec = dev->iommu_fwspec;
1813 
1814 	if (fwspec) {
1815 		fwnode_handle_put(fwspec->iommu_fwnode);
1816 		kfree(fwspec);
1817 		dev->iommu_fwspec = NULL;
1818 	}
1819 }
1820 EXPORT_SYMBOL_GPL(iommu_fwspec_free);
1821 
1822 int iommu_fwspec_add_ids(struct device *dev, u32 *ids, int num_ids)
1823 {
1824 	struct iommu_fwspec *fwspec = dev->iommu_fwspec;
1825 	size_t size;
1826 	int i;
1827 
1828 	if (!fwspec)
1829 		return -EINVAL;
1830 
1831 	size = offsetof(struct iommu_fwspec, ids[fwspec->num_ids + num_ids]);
1832 	if (size > sizeof(*fwspec)) {
1833 		fwspec = krealloc(dev->iommu_fwspec, size, GFP_KERNEL);
1834 		if (!fwspec)
1835 			return -ENOMEM;
1836 	}
1837 
1838 	for (i = 0; i < num_ids; i++)
1839 		fwspec->ids[fwspec->num_ids + i] = ids[i];
1840 
1841 	fwspec->num_ids += num_ids;
1842 	dev->iommu_fwspec = fwspec;
1843 	return 0;
1844 }
1845 EXPORT_SYMBOL_GPL(iommu_fwspec_add_ids);
1846