xref: /openbmc/linux/drivers/iommu/iommufd/device.c (revision a35762dd14adb952442e487d8dad4bb50b614b2b)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (c) 2021-2022, NVIDIA CORPORATION & AFFILIATES
3  */
4 #include <linux/iommufd.h>
5 #include <linux/slab.h>
6 #include <linux/iommu.h>
7 #include "../iommu-priv.h"
8 
9 #include "io_pagetable.h"
10 #include "iommufd_private.h"
11 
12 static bool allow_unsafe_interrupts;
13 module_param(allow_unsafe_interrupts, bool, S_IRUGO | S_IWUSR);
14 MODULE_PARM_DESC(
15 	allow_unsafe_interrupts,
16 	"Allow IOMMUFD to bind to devices even if the platform cannot isolate "
17 	"the MSI interrupt window. Enabling this is a security weakness.");
18 
19 static void iommufd_group_release(struct kref *kref)
20 {
21 	struct iommufd_group *igroup =
22 		container_of(kref, struct iommufd_group, ref);
23 
24 	WARN_ON(igroup->hwpt || !list_empty(&igroup->device_list));
25 
26 	xa_cmpxchg(&igroup->ictx->groups, iommu_group_id(igroup->group), igroup,
27 		   NULL, GFP_KERNEL);
28 	iommu_group_put(igroup->group);
29 	mutex_destroy(&igroup->lock);
30 	kfree(igroup);
31 }
32 
33 static void iommufd_put_group(struct iommufd_group *group)
34 {
35 	kref_put(&group->ref, iommufd_group_release);
36 }
37 
38 static bool iommufd_group_try_get(struct iommufd_group *igroup,
39 				  struct iommu_group *group)
40 {
41 	if (!igroup)
42 		return false;
43 	/*
44 	 * group ID's cannot be re-used until the group is put back which does
45 	 * not happen if we could get an igroup pointer under the xa_lock.
46 	 */
47 	if (WARN_ON(igroup->group != group))
48 		return false;
49 	return kref_get_unless_zero(&igroup->ref);
50 }
51 
52 /*
53  * iommufd needs to store some more data for each iommu_group, we keep a
54  * parallel xarray indexed by iommu_group id to hold this instead of putting it
55  * in the core structure. To keep things simple the iommufd_group memory is
56  * unique within the iommufd_ctx. This makes it easy to check there are no
57  * memory leaks.
58  */
59 static struct iommufd_group *iommufd_get_group(struct iommufd_ctx *ictx,
60 					       struct device *dev)
61 {
62 	struct iommufd_group *new_igroup;
63 	struct iommufd_group *cur_igroup;
64 	struct iommufd_group *igroup;
65 	struct iommu_group *group;
66 	unsigned int id;
67 
68 	group = iommu_group_get(dev);
69 	if (!group)
70 		return ERR_PTR(-ENODEV);
71 
72 	id = iommu_group_id(group);
73 
74 	xa_lock(&ictx->groups);
75 	igroup = xa_load(&ictx->groups, id);
76 	if (iommufd_group_try_get(igroup, group)) {
77 		xa_unlock(&ictx->groups);
78 		iommu_group_put(group);
79 		return igroup;
80 	}
81 	xa_unlock(&ictx->groups);
82 
83 	new_igroup = kzalloc(sizeof(*new_igroup), GFP_KERNEL);
84 	if (!new_igroup) {
85 		iommu_group_put(group);
86 		return ERR_PTR(-ENOMEM);
87 	}
88 
89 	kref_init(&new_igroup->ref);
90 	mutex_init(&new_igroup->lock);
91 	INIT_LIST_HEAD(&new_igroup->device_list);
92 	new_igroup->sw_msi_start = PHYS_ADDR_MAX;
93 	/* group reference moves into new_igroup */
94 	new_igroup->group = group;
95 
96 	/*
97 	 * The ictx is not additionally refcounted here becase all objects using
98 	 * an igroup must put it before their destroy completes.
99 	 */
100 	new_igroup->ictx = ictx;
101 
102 	/*
103 	 * We dropped the lock so igroup is invalid. NULL is a safe and likely
104 	 * value to assume for the xa_cmpxchg algorithm.
105 	 */
106 	cur_igroup = NULL;
107 	xa_lock(&ictx->groups);
108 	while (true) {
109 		igroup = __xa_cmpxchg(&ictx->groups, id, cur_igroup, new_igroup,
110 				      GFP_KERNEL);
111 		if (xa_is_err(igroup)) {
112 			xa_unlock(&ictx->groups);
113 			iommufd_put_group(new_igroup);
114 			return ERR_PTR(xa_err(igroup));
115 		}
116 
117 		/* new_group was successfully installed */
118 		if (cur_igroup == igroup) {
119 			xa_unlock(&ictx->groups);
120 			return new_igroup;
121 		}
122 
123 		/* Check again if the current group is any good */
124 		if (iommufd_group_try_get(igroup, group)) {
125 			xa_unlock(&ictx->groups);
126 			iommufd_put_group(new_igroup);
127 			return igroup;
128 		}
129 		cur_igroup = igroup;
130 	}
131 }
132 
133 void iommufd_device_destroy(struct iommufd_object *obj)
134 {
135 	struct iommufd_device *idev =
136 		container_of(obj, struct iommufd_device, obj);
137 
138 	iommu_device_release_dma_owner(idev->dev);
139 	iommufd_put_group(idev->igroup);
140 	if (!iommufd_selftest_is_mock_dev(idev->dev))
141 		iommufd_ctx_put(idev->ictx);
142 }
143 
144 /**
145  * iommufd_device_bind - Bind a physical device to an iommu fd
146  * @ictx: iommufd file descriptor
147  * @dev: Pointer to a physical device struct
148  * @id: Output ID number to return to userspace for this device
149  *
150  * A successful bind establishes an ownership over the device and returns
151  * struct iommufd_device pointer, otherwise returns error pointer.
152  *
153  * A driver using this API must set driver_managed_dma and must not touch
154  * the device until this routine succeeds and establishes ownership.
155  *
156  * Binding a PCI device places the entire RID under iommufd control.
157  *
158  * The caller must undo this with iommufd_device_unbind()
159  */
160 struct iommufd_device *iommufd_device_bind(struct iommufd_ctx *ictx,
161 					   struct device *dev, u32 *id)
162 {
163 	struct iommufd_device *idev;
164 	struct iommufd_group *igroup;
165 	int rc;
166 
167 	/*
168 	 * iommufd always sets IOMMU_CACHE because we offer no way for userspace
169 	 * to restore cache coherency.
170 	 */
171 	if (!device_iommu_capable(dev, IOMMU_CAP_CACHE_COHERENCY))
172 		return ERR_PTR(-EINVAL);
173 
174 	igroup = iommufd_get_group(ictx, dev);
175 	if (IS_ERR(igroup))
176 		return ERR_CAST(igroup);
177 
178 	/*
179 	 * For historical compat with VFIO the insecure interrupt path is
180 	 * allowed if the module parameter is set. Secure/Isolated means that a
181 	 * MemWr operation from the device (eg a simple DMA) cannot trigger an
182 	 * interrupt outside this iommufd context.
183 	 */
184 	if (!iommufd_selftest_is_mock_dev(dev) &&
185 	    !iommu_group_has_isolated_msi(igroup->group)) {
186 		if (!allow_unsafe_interrupts) {
187 			rc = -EPERM;
188 			goto out_group_put;
189 		}
190 
191 		dev_warn(
192 			dev,
193 			"MSI interrupts are not secure, they cannot be isolated by the platform. "
194 			"Check that platform features like interrupt remapping are enabled. "
195 			"Use the \"allow_unsafe_interrupts\" module parameter to override\n");
196 	}
197 
198 	rc = iommu_device_claim_dma_owner(dev, ictx);
199 	if (rc)
200 		goto out_group_put;
201 
202 	idev = iommufd_object_alloc(ictx, idev, IOMMUFD_OBJ_DEVICE);
203 	if (IS_ERR(idev)) {
204 		rc = PTR_ERR(idev);
205 		goto out_release_owner;
206 	}
207 	idev->ictx = ictx;
208 	if (!iommufd_selftest_is_mock_dev(dev))
209 		iommufd_ctx_get(ictx);
210 	idev->dev = dev;
211 	idev->enforce_cache_coherency =
212 		device_iommu_capable(dev, IOMMU_CAP_ENFORCE_CACHE_COHERENCY);
213 	/* The calling driver is a user until iommufd_device_unbind() */
214 	refcount_inc(&idev->obj.users);
215 	/* igroup refcount moves into iommufd_device */
216 	idev->igroup = igroup;
217 
218 	/*
219 	 * If the caller fails after this success it must call
220 	 * iommufd_unbind_device() which is safe since we hold this refcount.
221 	 * This also means the device is a leaf in the graph and no other object
222 	 * can take a reference on it.
223 	 */
224 	iommufd_object_finalize(ictx, &idev->obj);
225 	*id = idev->obj.id;
226 	return idev;
227 
228 out_release_owner:
229 	iommu_device_release_dma_owner(dev);
230 out_group_put:
231 	iommufd_put_group(igroup);
232 	return ERR_PTR(rc);
233 }
234 EXPORT_SYMBOL_NS_GPL(iommufd_device_bind, IOMMUFD);
235 
236 /**
237  * iommufd_ctx_has_group - True if any device within the group is bound
238  *                         to the ictx
239  * @ictx: iommufd file descriptor
240  * @group: Pointer to a physical iommu_group struct
241  *
242  * True if any device within the group has been bound to this ictx, ex. via
243  * iommufd_device_bind(), therefore implying ictx ownership of the group.
244  */
245 bool iommufd_ctx_has_group(struct iommufd_ctx *ictx, struct iommu_group *group)
246 {
247 	struct iommufd_object *obj;
248 	unsigned long index;
249 
250 	if (!ictx || !group)
251 		return false;
252 
253 	xa_lock(&ictx->objects);
254 	xa_for_each(&ictx->objects, index, obj) {
255 		if (obj->type == IOMMUFD_OBJ_DEVICE &&
256 		    container_of(obj, struct iommufd_device, obj)
257 				    ->igroup->group == group) {
258 			xa_unlock(&ictx->objects);
259 			return true;
260 		}
261 	}
262 	xa_unlock(&ictx->objects);
263 	return false;
264 }
265 EXPORT_SYMBOL_NS_GPL(iommufd_ctx_has_group, IOMMUFD);
266 
267 /**
268  * iommufd_device_unbind - Undo iommufd_device_bind()
269  * @idev: Device returned by iommufd_device_bind()
270  *
271  * Release the device from iommufd control. The DMA ownership will return back
272  * to unowned with DMA controlled by the DMA API. This invalidates the
273  * iommufd_device pointer, other APIs that consume it must not be called
274  * concurrently.
275  */
276 void iommufd_device_unbind(struct iommufd_device *idev)
277 {
278 	iommufd_object_destroy_user(idev->ictx, &idev->obj);
279 }
280 EXPORT_SYMBOL_NS_GPL(iommufd_device_unbind, IOMMUFD);
281 
282 struct iommufd_ctx *iommufd_device_to_ictx(struct iommufd_device *idev)
283 {
284 	return idev->ictx;
285 }
286 EXPORT_SYMBOL_NS_GPL(iommufd_device_to_ictx, IOMMUFD);
287 
288 u32 iommufd_device_to_id(struct iommufd_device *idev)
289 {
290 	return idev->obj.id;
291 }
292 EXPORT_SYMBOL_NS_GPL(iommufd_device_to_id, IOMMUFD);
293 
294 static int iommufd_group_setup_msi(struct iommufd_group *igroup,
295 				   struct iommufd_hw_pagetable *hwpt)
296 {
297 	phys_addr_t sw_msi_start = igroup->sw_msi_start;
298 	int rc;
299 
300 	/*
301 	 * If the IOMMU driver gives a IOMMU_RESV_SW_MSI then it is asking us to
302 	 * call iommu_get_msi_cookie() on its behalf. This is necessary to setup
303 	 * the MSI window so iommu_dma_prepare_msi() can install pages into our
304 	 * domain after request_irq(). If it is not done interrupts will not
305 	 * work on this domain.
306 	 *
307 	 * FIXME: This is conceptually broken for iommufd since we want to allow
308 	 * userspace to change the domains, eg switch from an identity IOAS to a
309 	 * DMA IOAS. There is currently no way to create a MSI window that
310 	 * matches what the IRQ layer actually expects in a newly created
311 	 * domain.
312 	 */
313 	if (sw_msi_start != PHYS_ADDR_MAX && !hwpt->msi_cookie) {
314 		rc = iommu_get_msi_cookie(hwpt->domain, sw_msi_start);
315 		if (rc)
316 			return rc;
317 
318 		/*
319 		 * iommu_get_msi_cookie() can only be called once per domain,
320 		 * it returns -EBUSY on later calls.
321 		 */
322 		hwpt->msi_cookie = true;
323 	}
324 	return 0;
325 }
326 
327 int iommufd_hw_pagetable_attach(struct iommufd_hw_pagetable *hwpt,
328 				struct iommufd_device *idev)
329 {
330 	int rc;
331 
332 	mutex_lock(&idev->igroup->lock);
333 
334 	if (idev->igroup->hwpt != NULL && idev->igroup->hwpt != hwpt) {
335 		rc = -EINVAL;
336 		goto err_unlock;
337 	}
338 
339 	/* Try to upgrade the domain we have */
340 	if (idev->enforce_cache_coherency) {
341 		rc = iommufd_hw_pagetable_enforce_cc(hwpt);
342 		if (rc)
343 			goto err_unlock;
344 	}
345 
346 	rc = iopt_table_enforce_dev_resv_regions(&hwpt->ioas->iopt, idev->dev,
347 						 &idev->igroup->sw_msi_start);
348 	if (rc)
349 		goto err_unlock;
350 
351 	/*
352 	 * Only attach to the group once for the first device that is in the
353 	 * group. All the other devices will follow this attachment. The user
354 	 * should attach every device individually to the hwpt as the per-device
355 	 * reserved regions are only updated during individual device
356 	 * attachment.
357 	 */
358 	if (list_empty(&idev->igroup->device_list)) {
359 		rc = iommufd_group_setup_msi(idev->igroup, hwpt);
360 		if (rc)
361 			goto err_unresv;
362 
363 		rc = iommu_attach_group(hwpt->domain, idev->igroup->group);
364 		if (rc)
365 			goto err_unresv;
366 		idev->igroup->hwpt = hwpt;
367 	}
368 	refcount_inc(&hwpt->obj.users);
369 	list_add_tail(&idev->group_item, &idev->igroup->device_list);
370 	mutex_unlock(&idev->igroup->lock);
371 	return 0;
372 err_unresv:
373 	iopt_remove_reserved_iova(&hwpt->ioas->iopt, idev->dev);
374 err_unlock:
375 	mutex_unlock(&idev->igroup->lock);
376 	return rc;
377 }
378 
379 struct iommufd_hw_pagetable *
380 iommufd_hw_pagetable_detach(struct iommufd_device *idev)
381 {
382 	struct iommufd_hw_pagetable *hwpt = idev->igroup->hwpt;
383 
384 	mutex_lock(&idev->igroup->lock);
385 	list_del(&idev->group_item);
386 	if (list_empty(&idev->igroup->device_list)) {
387 		iommu_detach_group(hwpt->domain, idev->igroup->group);
388 		idev->igroup->hwpt = NULL;
389 	}
390 	iopt_remove_reserved_iova(&hwpt->ioas->iopt, idev->dev);
391 	mutex_unlock(&idev->igroup->lock);
392 
393 	/* Caller must destroy hwpt */
394 	return hwpt;
395 }
396 
397 static struct iommufd_hw_pagetable *
398 iommufd_device_do_attach(struct iommufd_device *idev,
399 			 struct iommufd_hw_pagetable *hwpt)
400 {
401 	int rc;
402 
403 	rc = iommufd_hw_pagetable_attach(hwpt, idev);
404 	if (rc)
405 		return ERR_PTR(rc);
406 	return NULL;
407 }
408 
409 static struct iommufd_hw_pagetable *
410 iommufd_device_do_replace(struct iommufd_device *idev,
411 			  struct iommufd_hw_pagetable *hwpt)
412 {
413 	struct iommufd_group *igroup = idev->igroup;
414 	struct iommufd_hw_pagetable *old_hwpt;
415 	unsigned int num_devices = 0;
416 	struct iommufd_device *cur;
417 	int rc;
418 
419 	mutex_lock(&idev->igroup->lock);
420 
421 	if (igroup->hwpt == NULL) {
422 		rc = -EINVAL;
423 		goto err_unlock;
424 	}
425 
426 	if (hwpt == igroup->hwpt) {
427 		mutex_unlock(&idev->igroup->lock);
428 		return NULL;
429 	}
430 
431 	/* Try to upgrade the domain we have */
432 	list_for_each_entry(cur, &igroup->device_list, group_item) {
433 		num_devices++;
434 		if (cur->enforce_cache_coherency) {
435 			rc = iommufd_hw_pagetable_enforce_cc(hwpt);
436 			if (rc)
437 				goto err_unlock;
438 		}
439 	}
440 
441 	old_hwpt = igroup->hwpt;
442 	if (hwpt->ioas != old_hwpt->ioas) {
443 		list_for_each_entry(cur, &igroup->device_list, group_item) {
444 			rc = iopt_table_enforce_dev_resv_regions(
445 				&hwpt->ioas->iopt, cur->dev, NULL);
446 			if (rc)
447 				goto err_unresv;
448 		}
449 	}
450 
451 	rc = iommufd_group_setup_msi(idev->igroup, hwpt);
452 	if (rc)
453 		goto err_unresv;
454 
455 	rc = iommu_group_replace_domain(igroup->group, hwpt->domain);
456 	if (rc)
457 		goto err_unresv;
458 
459 	if (hwpt->ioas != old_hwpt->ioas) {
460 		list_for_each_entry(cur, &igroup->device_list, group_item)
461 			iopt_remove_reserved_iova(&old_hwpt->ioas->iopt,
462 						  cur->dev);
463 	}
464 
465 	igroup->hwpt = hwpt;
466 
467 	/*
468 	 * Move the refcounts held by the device_list to the new hwpt. Retain a
469 	 * refcount for this thread as the caller will free it.
470 	 */
471 	refcount_add(num_devices, &hwpt->obj.users);
472 	if (num_devices > 1)
473 		WARN_ON(refcount_sub_and_test(num_devices - 1,
474 					      &old_hwpt->obj.users));
475 	mutex_unlock(&idev->igroup->lock);
476 
477 	/* Caller must destroy old_hwpt */
478 	return old_hwpt;
479 err_unresv:
480 	list_for_each_entry(cur, &igroup->device_list, group_item)
481 		iopt_remove_reserved_iova(&hwpt->ioas->iopt, cur->dev);
482 err_unlock:
483 	mutex_unlock(&idev->igroup->lock);
484 	return ERR_PTR(rc);
485 }
486 
487 typedef struct iommufd_hw_pagetable *(*attach_fn)(
488 	struct iommufd_device *idev, struct iommufd_hw_pagetable *hwpt);
489 
490 /*
491  * When automatically managing the domains we search for a compatible domain in
492  * the iopt and if one is found use it, otherwise create a new domain.
493  * Automatic domain selection will never pick a manually created domain.
494  */
495 static struct iommufd_hw_pagetable *
496 iommufd_device_auto_get_domain(struct iommufd_device *idev,
497 			       struct iommufd_ioas *ioas, u32 *pt_id,
498 			       attach_fn do_attach)
499 {
500 	/*
501 	 * iommufd_hw_pagetable_attach() is called by
502 	 * iommufd_hw_pagetable_alloc() in immediate attachment mode, same as
503 	 * iommufd_device_do_attach(). So if we are in this mode then we prefer
504 	 * to use the immediate_attach path as it supports drivers that can't
505 	 * directly allocate a domain.
506 	 */
507 	bool immediate_attach = do_attach == iommufd_device_do_attach;
508 	struct iommufd_hw_pagetable *destroy_hwpt;
509 	struct iommufd_hw_pagetable *hwpt;
510 
511 	/*
512 	 * There is no differentiation when domains are allocated, so any domain
513 	 * that is willing to attach to the device is interchangeable with any
514 	 * other.
515 	 */
516 	mutex_lock(&ioas->mutex);
517 	list_for_each_entry(hwpt, &ioas->hwpt_list, hwpt_item) {
518 		if (!hwpt->auto_domain)
519 			continue;
520 
521 		if (!iommufd_lock_obj(&hwpt->obj))
522 			continue;
523 		destroy_hwpt = (*do_attach)(idev, hwpt);
524 		if (IS_ERR(destroy_hwpt)) {
525 			iommufd_put_object(&hwpt->obj);
526 			/*
527 			 * -EINVAL means the domain is incompatible with the
528 			 * device. Other error codes should propagate to
529 			 * userspace as failure. Success means the domain is
530 			 * attached.
531 			 */
532 			if (PTR_ERR(destroy_hwpt) == -EINVAL)
533 				continue;
534 			goto out_unlock;
535 		}
536 		*pt_id = hwpt->obj.id;
537 		iommufd_put_object(&hwpt->obj);
538 		goto out_unlock;
539 	}
540 
541 	hwpt = iommufd_hw_pagetable_alloc(idev->ictx, ioas, idev,
542 					  immediate_attach);
543 	if (IS_ERR(hwpt)) {
544 		destroy_hwpt = ERR_CAST(hwpt);
545 		goto out_unlock;
546 	}
547 
548 	if (!immediate_attach) {
549 		destroy_hwpt = (*do_attach)(idev, hwpt);
550 		if (IS_ERR(destroy_hwpt))
551 			goto out_abort;
552 	} else {
553 		destroy_hwpt = NULL;
554 	}
555 
556 	hwpt->auto_domain = true;
557 	*pt_id = hwpt->obj.id;
558 
559 	iommufd_object_finalize(idev->ictx, &hwpt->obj);
560 	mutex_unlock(&ioas->mutex);
561 	return destroy_hwpt;
562 
563 out_abort:
564 	iommufd_object_abort_and_destroy(idev->ictx, &hwpt->obj);
565 out_unlock:
566 	mutex_unlock(&ioas->mutex);
567 	return destroy_hwpt;
568 }
569 
570 static int iommufd_device_change_pt(struct iommufd_device *idev, u32 *pt_id,
571 				    attach_fn do_attach)
572 {
573 	struct iommufd_hw_pagetable *destroy_hwpt;
574 	struct iommufd_object *pt_obj;
575 
576 	pt_obj = iommufd_get_object(idev->ictx, *pt_id, IOMMUFD_OBJ_ANY);
577 	if (IS_ERR(pt_obj))
578 		return PTR_ERR(pt_obj);
579 
580 	switch (pt_obj->type) {
581 	case IOMMUFD_OBJ_HW_PAGETABLE: {
582 		struct iommufd_hw_pagetable *hwpt =
583 			container_of(pt_obj, struct iommufd_hw_pagetable, obj);
584 
585 		destroy_hwpt = (*do_attach)(idev, hwpt);
586 		if (IS_ERR(destroy_hwpt))
587 			goto out_put_pt_obj;
588 		break;
589 	}
590 	case IOMMUFD_OBJ_IOAS: {
591 		struct iommufd_ioas *ioas =
592 			container_of(pt_obj, struct iommufd_ioas, obj);
593 
594 		destroy_hwpt = iommufd_device_auto_get_domain(idev, ioas, pt_id,
595 							      do_attach);
596 		if (IS_ERR(destroy_hwpt))
597 			goto out_put_pt_obj;
598 		break;
599 	}
600 	default:
601 		destroy_hwpt = ERR_PTR(-EINVAL);
602 		goto out_put_pt_obj;
603 	}
604 	iommufd_put_object(pt_obj);
605 
606 	/* This destruction has to be after we unlock everything */
607 	if (destroy_hwpt)
608 		iommufd_hw_pagetable_put(idev->ictx, destroy_hwpt);
609 	return 0;
610 
611 out_put_pt_obj:
612 	iommufd_put_object(pt_obj);
613 	return PTR_ERR(destroy_hwpt);
614 }
615 
616 /**
617  * iommufd_device_attach - Connect a device to an iommu_domain
618  * @idev: device to attach
619  * @pt_id: Input a IOMMUFD_OBJ_IOAS, or IOMMUFD_OBJ_HW_PAGETABLE
620  *         Output the IOMMUFD_OBJ_HW_PAGETABLE ID
621  *
622  * This connects the device to an iommu_domain, either automatically or manually
623  * selected. Once this completes the device could do DMA.
624  *
625  * The caller should return the resulting pt_id back to userspace.
626  * This function is undone by calling iommufd_device_detach().
627  */
628 int iommufd_device_attach(struct iommufd_device *idev, u32 *pt_id)
629 {
630 	int rc;
631 
632 	rc = iommufd_device_change_pt(idev, pt_id, &iommufd_device_do_attach);
633 	if (rc)
634 		return rc;
635 
636 	/*
637 	 * Pairs with iommufd_device_detach() - catches caller bugs attempting
638 	 * to destroy a device with an attachment.
639 	 */
640 	refcount_inc(&idev->obj.users);
641 	return 0;
642 }
643 EXPORT_SYMBOL_NS_GPL(iommufd_device_attach, IOMMUFD);
644 
645 /**
646  * iommufd_device_replace - Change the device's iommu_domain
647  * @idev: device to change
648  * @pt_id: Input a IOMMUFD_OBJ_IOAS, or IOMMUFD_OBJ_HW_PAGETABLE
649  *         Output the IOMMUFD_OBJ_HW_PAGETABLE ID
650  *
651  * This is the same as::
652  *
653  *   iommufd_device_detach();
654  *   iommufd_device_attach();
655  *
656  * If it fails then no change is made to the attachment. The iommu driver may
657  * implement this so there is no disruption in translation. This can only be
658  * called if iommufd_device_attach() has already succeeded.
659  */
660 int iommufd_device_replace(struct iommufd_device *idev, u32 *pt_id)
661 {
662 	return iommufd_device_change_pt(idev, pt_id,
663 					&iommufd_device_do_replace);
664 }
665 EXPORT_SYMBOL_NS_GPL(iommufd_device_replace, IOMMUFD);
666 
667 /**
668  * iommufd_device_detach - Disconnect a device to an iommu_domain
669  * @idev: device to detach
670  *
671  * Undo iommufd_device_attach(). This disconnects the idev from the previously
672  * attached pt_id. The device returns back to a blocked DMA translation.
673  */
674 void iommufd_device_detach(struct iommufd_device *idev)
675 {
676 	struct iommufd_hw_pagetable *hwpt;
677 
678 	hwpt = iommufd_hw_pagetable_detach(idev);
679 	iommufd_hw_pagetable_put(idev->ictx, hwpt);
680 	refcount_dec(&idev->obj.users);
681 }
682 EXPORT_SYMBOL_NS_GPL(iommufd_device_detach, IOMMUFD);
683 
684 /*
685  * On success, it will refcount_inc() at a valid new_ioas and refcount_dec() at
686  * a valid cur_ioas (access->ioas). A caller passing in a valid new_ioas should
687  * call iommufd_put_object() if it does an iommufd_get_object() for a new_ioas.
688  */
689 static int iommufd_access_change_ioas(struct iommufd_access *access,
690 				      struct iommufd_ioas *new_ioas)
691 {
692 	u32 iopt_access_list_id = access->iopt_access_list_id;
693 	struct iommufd_ioas *cur_ioas = access->ioas;
694 	int rc;
695 
696 	lockdep_assert_held(&access->ioas_lock);
697 
698 	/* We are racing with a concurrent detach, bail */
699 	if (cur_ioas != access->ioas_unpin)
700 		return -EBUSY;
701 
702 	if (cur_ioas == new_ioas)
703 		return 0;
704 
705 	/*
706 	 * Set ioas to NULL to block any further iommufd_access_pin_pages().
707 	 * iommufd_access_unpin_pages() can continue using access->ioas_unpin.
708 	 */
709 	access->ioas = NULL;
710 
711 	if (new_ioas) {
712 		rc = iopt_add_access(&new_ioas->iopt, access);
713 		if (rc) {
714 			access->ioas = cur_ioas;
715 			return rc;
716 		}
717 		refcount_inc(&new_ioas->obj.users);
718 	}
719 
720 	if (cur_ioas) {
721 		if (access->ops->unmap) {
722 			mutex_unlock(&access->ioas_lock);
723 			access->ops->unmap(access->data, 0, ULONG_MAX);
724 			mutex_lock(&access->ioas_lock);
725 		}
726 		iopt_remove_access(&cur_ioas->iopt, access, iopt_access_list_id);
727 		refcount_dec(&cur_ioas->obj.users);
728 	}
729 
730 	access->ioas = new_ioas;
731 	access->ioas_unpin = new_ioas;
732 
733 	return 0;
734 }
735 
736 static int iommufd_access_change_ioas_id(struct iommufd_access *access, u32 id)
737 {
738 	struct iommufd_ioas *ioas = iommufd_get_ioas(access->ictx, id);
739 	int rc;
740 
741 	if (IS_ERR(ioas))
742 		return PTR_ERR(ioas);
743 	rc = iommufd_access_change_ioas(access, ioas);
744 	iommufd_put_object(&ioas->obj);
745 	return rc;
746 }
747 
748 void iommufd_access_destroy_object(struct iommufd_object *obj)
749 {
750 	struct iommufd_access *access =
751 		container_of(obj, struct iommufd_access, obj);
752 
753 	mutex_lock(&access->ioas_lock);
754 	if (access->ioas)
755 		WARN_ON(iommufd_access_change_ioas(access, NULL));
756 	mutex_unlock(&access->ioas_lock);
757 	iommufd_ctx_put(access->ictx);
758 }
759 
760 /**
761  * iommufd_access_create - Create an iommufd_access
762  * @ictx: iommufd file descriptor
763  * @ops: Driver's ops to associate with the access
764  * @data: Opaque data to pass into ops functions
765  * @id: Output ID number to return to userspace for this access
766  *
767  * An iommufd_access allows a driver to read/write to the IOAS without using
768  * DMA. The underlying CPU memory can be accessed using the
769  * iommufd_access_pin_pages() or iommufd_access_rw() functions.
770  *
771  * The provided ops are required to use iommufd_access_pin_pages().
772  */
773 struct iommufd_access *
774 iommufd_access_create(struct iommufd_ctx *ictx,
775 		      const struct iommufd_access_ops *ops, void *data, u32 *id)
776 {
777 	struct iommufd_access *access;
778 
779 	/*
780 	 * There is no uAPI for the access object, but to keep things symmetric
781 	 * use the object infrastructure anyhow.
782 	 */
783 	access = iommufd_object_alloc(ictx, access, IOMMUFD_OBJ_ACCESS);
784 	if (IS_ERR(access))
785 		return access;
786 
787 	access->data = data;
788 	access->ops = ops;
789 
790 	if (ops->needs_pin_pages)
791 		access->iova_alignment = PAGE_SIZE;
792 	else
793 		access->iova_alignment = 1;
794 
795 	/* The calling driver is a user until iommufd_access_destroy() */
796 	refcount_inc(&access->obj.users);
797 	access->ictx = ictx;
798 	iommufd_ctx_get(ictx);
799 	iommufd_object_finalize(ictx, &access->obj);
800 	*id = access->obj.id;
801 	mutex_init(&access->ioas_lock);
802 	return access;
803 }
804 EXPORT_SYMBOL_NS_GPL(iommufd_access_create, IOMMUFD);
805 
806 /**
807  * iommufd_access_destroy - Destroy an iommufd_access
808  * @access: The access to destroy
809  *
810  * The caller must stop using the access before destroying it.
811  */
812 void iommufd_access_destroy(struct iommufd_access *access)
813 {
814 	iommufd_object_destroy_user(access->ictx, &access->obj);
815 }
816 EXPORT_SYMBOL_NS_GPL(iommufd_access_destroy, IOMMUFD);
817 
818 void iommufd_access_detach(struct iommufd_access *access)
819 {
820 	mutex_lock(&access->ioas_lock);
821 	if (WARN_ON(!access->ioas)) {
822 		mutex_unlock(&access->ioas_lock);
823 		return;
824 	}
825 	WARN_ON(iommufd_access_change_ioas(access, NULL));
826 	mutex_unlock(&access->ioas_lock);
827 }
828 EXPORT_SYMBOL_NS_GPL(iommufd_access_detach, IOMMUFD);
829 
830 int iommufd_access_attach(struct iommufd_access *access, u32 ioas_id)
831 {
832 	int rc;
833 
834 	mutex_lock(&access->ioas_lock);
835 	if (WARN_ON(access->ioas)) {
836 		mutex_unlock(&access->ioas_lock);
837 		return -EINVAL;
838 	}
839 
840 	rc = iommufd_access_change_ioas_id(access, ioas_id);
841 	mutex_unlock(&access->ioas_lock);
842 	return rc;
843 }
844 EXPORT_SYMBOL_NS_GPL(iommufd_access_attach, IOMMUFD);
845 
846 int iommufd_access_replace(struct iommufd_access *access, u32 ioas_id)
847 {
848 	int rc;
849 
850 	mutex_lock(&access->ioas_lock);
851 	if (!access->ioas) {
852 		mutex_unlock(&access->ioas_lock);
853 		return -ENOENT;
854 	}
855 	rc = iommufd_access_change_ioas_id(access, ioas_id);
856 	mutex_unlock(&access->ioas_lock);
857 	return rc;
858 }
859 EXPORT_SYMBOL_NS_GPL(iommufd_access_replace, IOMMUFD);
860 
861 /**
862  * iommufd_access_notify_unmap - Notify users of an iopt to stop using it
863  * @iopt: iopt to work on
864  * @iova: Starting iova in the iopt
865  * @length: Number of bytes
866  *
867  * After this function returns there should be no users attached to the pages
868  * linked to this iopt that intersect with iova,length. Anyone that has attached
869  * a user through iopt_access_pages() needs to detach it through
870  * iommufd_access_unpin_pages() before this function returns.
871  *
872  * iommufd_access_destroy() will wait for any outstanding unmap callback to
873  * complete. Once iommufd_access_destroy() no unmap ops are running or will
874  * run in the future. Due to this a driver must not create locking that prevents
875  * unmap to complete while iommufd_access_destroy() is running.
876  */
877 void iommufd_access_notify_unmap(struct io_pagetable *iopt, unsigned long iova,
878 				 unsigned long length)
879 {
880 	struct iommufd_ioas *ioas =
881 		container_of(iopt, struct iommufd_ioas, iopt);
882 	struct iommufd_access *access;
883 	unsigned long index;
884 
885 	xa_lock(&ioas->iopt.access_list);
886 	xa_for_each(&ioas->iopt.access_list, index, access) {
887 		if (!iommufd_lock_obj(&access->obj))
888 			continue;
889 		xa_unlock(&ioas->iopt.access_list);
890 
891 		access->ops->unmap(access->data, iova, length);
892 
893 		iommufd_put_object(&access->obj);
894 		xa_lock(&ioas->iopt.access_list);
895 	}
896 	xa_unlock(&ioas->iopt.access_list);
897 }
898 
899 /**
900  * iommufd_access_unpin_pages() - Undo iommufd_access_pin_pages
901  * @access: IOAS access to act on
902  * @iova: Starting IOVA
903  * @length: Number of bytes to access
904  *
905  * Return the struct page's. The caller must stop accessing them before calling
906  * this. The iova/length must exactly match the one provided to access_pages.
907  */
908 void iommufd_access_unpin_pages(struct iommufd_access *access,
909 				unsigned long iova, unsigned long length)
910 {
911 	struct iopt_area_contig_iter iter;
912 	struct io_pagetable *iopt;
913 	unsigned long last_iova;
914 	struct iopt_area *area;
915 
916 	if (WARN_ON(!length) ||
917 	    WARN_ON(check_add_overflow(iova, length - 1, &last_iova)))
918 		return;
919 
920 	mutex_lock(&access->ioas_lock);
921 	/*
922 	 * The driver must be doing something wrong if it calls this before an
923 	 * iommufd_access_attach() or after an iommufd_access_detach().
924 	 */
925 	if (WARN_ON(!access->ioas_unpin)) {
926 		mutex_unlock(&access->ioas_lock);
927 		return;
928 	}
929 	iopt = &access->ioas_unpin->iopt;
930 
931 	down_read(&iopt->iova_rwsem);
932 	iopt_for_each_contig_area(&iter, area, iopt, iova, last_iova)
933 		iopt_area_remove_access(
934 			area, iopt_area_iova_to_index(area, iter.cur_iova),
935 			iopt_area_iova_to_index(
936 				area,
937 				min(last_iova, iopt_area_last_iova(area))));
938 	WARN_ON(!iopt_area_contig_done(&iter));
939 	up_read(&iopt->iova_rwsem);
940 	mutex_unlock(&access->ioas_lock);
941 }
942 EXPORT_SYMBOL_NS_GPL(iommufd_access_unpin_pages, IOMMUFD);
943 
944 static bool iopt_area_contig_is_aligned(struct iopt_area_contig_iter *iter)
945 {
946 	if (iopt_area_start_byte(iter->area, iter->cur_iova) % PAGE_SIZE)
947 		return false;
948 
949 	if (!iopt_area_contig_done(iter) &&
950 	    (iopt_area_start_byte(iter->area, iopt_area_last_iova(iter->area)) %
951 	     PAGE_SIZE) != (PAGE_SIZE - 1))
952 		return false;
953 	return true;
954 }
955 
956 static bool check_area_prot(struct iopt_area *area, unsigned int flags)
957 {
958 	if (flags & IOMMUFD_ACCESS_RW_WRITE)
959 		return area->iommu_prot & IOMMU_WRITE;
960 	return area->iommu_prot & IOMMU_READ;
961 }
962 
963 /**
964  * iommufd_access_pin_pages() - Return a list of pages under the iova
965  * @access: IOAS access to act on
966  * @iova: Starting IOVA
967  * @length: Number of bytes to access
968  * @out_pages: Output page list
969  * @flags: IOPMMUFD_ACCESS_RW_* flags
970  *
971  * Reads @length bytes starting at iova and returns the struct page * pointers.
972  * These can be kmap'd by the caller for CPU access.
973  *
974  * The caller must perform iommufd_access_unpin_pages() when done to balance
975  * this.
976  *
977  * This API always requires a page aligned iova. This happens naturally if the
978  * ioas alignment is >= PAGE_SIZE and the iova is PAGE_SIZE aligned. However
979  * smaller alignments have corner cases where this API can fail on otherwise
980  * aligned iova.
981  */
982 int iommufd_access_pin_pages(struct iommufd_access *access, unsigned long iova,
983 			     unsigned long length, struct page **out_pages,
984 			     unsigned int flags)
985 {
986 	struct iopt_area_contig_iter iter;
987 	struct io_pagetable *iopt;
988 	unsigned long last_iova;
989 	struct iopt_area *area;
990 	int rc;
991 
992 	/* Driver's ops don't support pin_pages */
993 	if (IS_ENABLED(CONFIG_IOMMUFD_TEST) &&
994 	    WARN_ON(access->iova_alignment != PAGE_SIZE || !access->ops->unmap))
995 		return -EINVAL;
996 
997 	if (!length)
998 		return -EINVAL;
999 	if (check_add_overflow(iova, length - 1, &last_iova))
1000 		return -EOVERFLOW;
1001 
1002 	mutex_lock(&access->ioas_lock);
1003 	if (!access->ioas) {
1004 		mutex_unlock(&access->ioas_lock);
1005 		return -ENOENT;
1006 	}
1007 	iopt = &access->ioas->iopt;
1008 
1009 	down_read(&iopt->iova_rwsem);
1010 	iopt_for_each_contig_area(&iter, area, iopt, iova, last_iova) {
1011 		unsigned long last = min(last_iova, iopt_area_last_iova(area));
1012 		unsigned long last_index = iopt_area_iova_to_index(area, last);
1013 		unsigned long index =
1014 			iopt_area_iova_to_index(area, iter.cur_iova);
1015 
1016 		if (area->prevent_access ||
1017 		    !iopt_area_contig_is_aligned(&iter)) {
1018 			rc = -EINVAL;
1019 			goto err_remove;
1020 		}
1021 
1022 		if (!check_area_prot(area, flags)) {
1023 			rc = -EPERM;
1024 			goto err_remove;
1025 		}
1026 
1027 		rc = iopt_area_add_access(area, index, last_index, out_pages,
1028 					  flags);
1029 		if (rc)
1030 			goto err_remove;
1031 		out_pages += last_index - index + 1;
1032 	}
1033 	if (!iopt_area_contig_done(&iter)) {
1034 		rc = -ENOENT;
1035 		goto err_remove;
1036 	}
1037 
1038 	up_read(&iopt->iova_rwsem);
1039 	mutex_unlock(&access->ioas_lock);
1040 	return 0;
1041 
1042 err_remove:
1043 	if (iova < iter.cur_iova) {
1044 		last_iova = iter.cur_iova - 1;
1045 		iopt_for_each_contig_area(&iter, area, iopt, iova, last_iova)
1046 			iopt_area_remove_access(
1047 				area,
1048 				iopt_area_iova_to_index(area, iter.cur_iova),
1049 				iopt_area_iova_to_index(
1050 					area, min(last_iova,
1051 						  iopt_area_last_iova(area))));
1052 	}
1053 	up_read(&iopt->iova_rwsem);
1054 	mutex_unlock(&access->ioas_lock);
1055 	return rc;
1056 }
1057 EXPORT_SYMBOL_NS_GPL(iommufd_access_pin_pages, IOMMUFD);
1058 
1059 /**
1060  * iommufd_access_rw - Read or write data under the iova
1061  * @access: IOAS access to act on
1062  * @iova: Starting IOVA
1063  * @data: Kernel buffer to copy to/from
1064  * @length: Number of bytes to access
1065  * @flags: IOMMUFD_ACCESS_RW_* flags
1066  *
1067  * Copy kernel to/from data into the range given by IOVA/length. If flags
1068  * indicates IOMMUFD_ACCESS_RW_KTHREAD then a large copy can be optimized
1069  * by changing it into copy_to/from_user().
1070  */
1071 int iommufd_access_rw(struct iommufd_access *access, unsigned long iova,
1072 		      void *data, size_t length, unsigned int flags)
1073 {
1074 	struct iopt_area_contig_iter iter;
1075 	struct io_pagetable *iopt;
1076 	struct iopt_area *area;
1077 	unsigned long last_iova;
1078 	int rc;
1079 
1080 	if (!length)
1081 		return -EINVAL;
1082 	if (check_add_overflow(iova, length - 1, &last_iova))
1083 		return -EOVERFLOW;
1084 
1085 	mutex_lock(&access->ioas_lock);
1086 	if (!access->ioas) {
1087 		mutex_unlock(&access->ioas_lock);
1088 		return -ENOENT;
1089 	}
1090 	iopt = &access->ioas->iopt;
1091 
1092 	down_read(&iopt->iova_rwsem);
1093 	iopt_for_each_contig_area(&iter, area, iopt, iova, last_iova) {
1094 		unsigned long last = min(last_iova, iopt_area_last_iova(area));
1095 		unsigned long bytes = (last - iter.cur_iova) + 1;
1096 
1097 		if (area->prevent_access) {
1098 			rc = -EINVAL;
1099 			goto err_out;
1100 		}
1101 
1102 		if (!check_area_prot(area, flags)) {
1103 			rc = -EPERM;
1104 			goto err_out;
1105 		}
1106 
1107 		rc = iopt_pages_rw_access(
1108 			area->pages, iopt_area_start_byte(area, iter.cur_iova),
1109 			data, bytes, flags);
1110 		if (rc)
1111 			goto err_out;
1112 		data += bytes;
1113 	}
1114 	if (!iopt_area_contig_done(&iter))
1115 		rc = -ENOENT;
1116 err_out:
1117 	up_read(&iopt->iova_rwsem);
1118 	mutex_unlock(&access->ioas_lock);
1119 	return rc;
1120 }
1121 EXPORT_SYMBOL_NS_GPL(iommufd_access_rw, IOMMUFD);
1122