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