xref: /linux/drivers/iommu/iommufd/device.c (revision b4ada0618eed0fbd1b1630f73deb048c592b06a1)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (c) 2021-2022, NVIDIA CORPORATION & AFFILIATES
3  */
4 #include <linux/iommu.h>
5 #include <linux/iommufd.h>
6 #include <linux/pci-ats.h>
7 #include <linux/slab.h>
8 #include <uapi/linux/iommufd.h>
9 
10 #include "../iommu-priv.h"
11 #include "io_pagetable.h"
12 #include "iommufd_private.h"
13 
14 static bool allow_unsafe_interrupts;
15 module_param(allow_unsafe_interrupts, bool, S_IRUGO | S_IWUSR);
16 MODULE_PARM_DESC(
17 	allow_unsafe_interrupts,
18 	"Allow IOMMUFD to bind to devices even if the platform cannot isolate "
19 	"the MSI interrupt window. Enabling this is a security weakness.");
20 
21 struct iommufd_attach {
22 	struct iommufd_hw_pagetable *hwpt;
23 	struct xarray device_array;
24 };
25 
26 static void iommufd_group_release(struct kref *kref)
27 {
28 	struct iommufd_group *igroup =
29 		container_of(kref, struct iommufd_group, ref);
30 
31 	WARN_ON(!xa_empty(&igroup->pasid_attach));
32 
33 	xa_cmpxchg(&igroup->ictx->groups, iommu_group_id(igroup->group), igroup,
34 		   NULL, GFP_KERNEL);
35 	iommu_group_put(igroup->group);
36 	mutex_destroy(&igroup->lock);
37 	kfree(igroup);
38 }
39 
40 static void iommufd_put_group(struct iommufd_group *group)
41 {
42 	kref_put(&group->ref, iommufd_group_release);
43 }
44 
45 static bool iommufd_group_try_get(struct iommufd_group *igroup,
46 				  struct iommu_group *group)
47 {
48 	if (!igroup)
49 		return false;
50 	/*
51 	 * group ID's cannot be re-used until the group is put back which does
52 	 * not happen if we could get an igroup pointer under the xa_lock.
53 	 */
54 	if (WARN_ON(igroup->group != group))
55 		return false;
56 	return kref_get_unless_zero(&igroup->ref);
57 }
58 
59 /*
60  * iommufd needs to store some more data for each iommu_group, we keep a
61  * parallel xarray indexed by iommu_group id to hold this instead of putting it
62  * in the core structure. To keep things simple the iommufd_group memory is
63  * unique within the iommufd_ctx. This makes it easy to check there are no
64  * memory leaks.
65  */
66 static struct iommufd_group *iommufd_get_group(struct iommufd_ctx *ictx,
67 					       struct device *dev)
68 {
69 	struct iommufd_group *new_igroup;
70 	struct iommufd_group *cur_igroup;
71 	struct iommufd_group *igroup;
72 	struct iommu_group *group;
73 	unsigned int id;
74 
75 	group = iommu_group_get(dev);
76 	if (!group)
77 		return ERR_PTR(-ENODEV);
78 
79 	id = iommu_group_id(group);
80 
81 	xa_lock(&ictx->groups);
82 	igroup = xa_load(&ictx->groups, id);
83 	if (iommufd_group_try_get(igroup, group)) {
84 		xa_unlock(&ictx->groups);
85 		iommu_group_put(group);
86 		return igroup;
87 	}
88 	xa_unlock(&ictx->groups);
89 
90 	new_igroup = kzalloc(sizeof(*new_igroup), GFP_KERNEL);
91 	if (!new_igroup) {
92 		iommu_group_put(group);
93 		return ERR_PTR(-ENOMEM);
94 	}
95 
96 	kref_init(&new_igroup->ref);
97 	mutex_init(&new_igroup->lock);
98 	xa_init(&new_igroup->pasid_attach);
99 	new_igroup->sw_msi_start = PHYS_ADDR_MAX;
100 	/* group reference moves into new_igroup */
101 	new_igroup->group = group;
102 
103 	/*
104 	 * The ictx is not additionally refcounted here becase all objects using
105 	 * an igroup must put it before their destroy completes.
106 	 */
107 	new_igroup->ictx = ictx;
108 
109 	/*
110 	 * We dropped the lock so igroup is invalid. NULL is a safe and likely
111 	 * value to assume for the xa_cmpxchg algorithm.
112 	 */
113 	cur_igroup = NULL;
114 	xa_lock(&ictx->groups);
115 	while (true) {
116 		igroup = __xa_cmpxchg(&ictx->groups, id, cur_igroup, new_igroup,
117 				      GFP_KERNEL);
118 		if (xa_is_err(igroup)) {
119 			xa_unlock(&ictx->groups);
120 			iommufd_put_group(new_igroup);
121 			return ERR_PTR(xa_err(igroup));
122 		}
123 
124 		/* new_group was successfully installed */
125 		if (cur_igroup == igroup) {
126 			xa_unlock(&ictx->groups);
127 			return new_igroup;
128 		}
129 
130 		/* Check again if the current group is any good */
131 		if (iommufd_group_try_get(igroup, group)) {
132 			xa_unlock(&ictx->groups);
133 			iommufd_put_group(new_igroup);
134 			return igroup;
135 		}
136 		cur_igroup = igroup;
137 	}
138 }
139 
140 static void iommufd_device_remove_vdev(struct iommufd_device *idev)
141 {
142 	struct iommufd_vdevice *vdev;
143 
144 	mutex_lock(&idev->igroup->lock);
145 	/* prevent new references from vdev */
146 	idev->destroying = true;
147 	/* vdev has been completely destroyed by userspace */
148 	if (!idev->vdev)
149 		goto out_unlock;
150 
151 	vdev = iommufd_get_vdevice(idev->ictx, idev->vdev->obj.id);
152 	/*
153 	 * An ongoing vdev destroy ioctl has removed the vdev from the object
154 	 * xarray, but has not finished iommufd_vdevice_destroy() yet as it
155 	 * needs the same mutex. We exit the locking then wait on wait_cnt
156 	 * reference for the vdev destruction.
157 	 */
158 	if (IS_ERR(vdev))
159 		goto out_unlock;
160 
161 	/* Should never happen */
162 	if (WARN_ON(vdev != idev->vdev)) {
163 		iommufd_put_object(idev->ictx, &vdev->obj);
164 		goto out_unlock;
165 	}
166 
167 	/*
168 	 * vdev is still alive. Hold a users refcount to prevent racing with
169 	 * userspace destruction, then use iommufd_object_tombstone_user() to
170 	 * destroy it and leave a tombstone.
171 	 */
172 	refcount_inc(&vdev->obj.users);
173 	iommufd_put_object(idev->ictx, &vdev->obj);
174 	mutex_unlock(&idev->igroup->lock);
175 	iommufd_object_tombstone_user(idev->ictx, &vdev->obj);
176 	return;
177 
178 out_unlock:
179 	mutex_unlock(&idev->igroup->lock);
180 }
181 
182 void iommufd_device_pre_destroy(struct iommufd_object *obj)
183 {
184 	struct iommufd_device *idev =
185 		container_of(obj, struct iommufd_device, obj);
186 
187 	/* Release the wait_cnt reference on this */
188 	iommufd_device_remove_vdev(idev);
189 }
190 
191 void iommufd_device_destroy(struct iommufd_object *obj)
192 {
193 	struct iommufd_device *idev =
194 		container_of(obj, struct iommufd_device, obj);
195 
196 	iommu_device_release_dma_owner(idev->dev);
197 	iommufd_put_group(idev->igroup);
198 	if (!iommufd_selftest_is_mock_dev(idev->dev))
199 		iommufd_ctx_put(idev->ictx);
200 }
201 
202 /**
203  * iommufd_device_bind - Bind a physical device to an iommu fd
204  * @ictx: iommufd file descriptor
205  * @dev: Pointer to a physical device struct
206  * @id: Output ID number to return to userspace for this device
207  *
208  * A successful bind establishes an ownership over the device and returns
209  * struct iommufd_device pointer, otherwise returns error pointer.
210  *
211  * A driver using this API must set driver_managed_dma and must not touch
212  * the device until this routine succeeds and establishes ownership.
213  *
214  * Binding a PCI device places the entire RID under iommufd control.
215  *
216  * The caller must undo this with iommufd_device_unbind()
217  */
218 struct iommufd_device *iommufd_device_bind(struct iommufd_ctx *ictx,
219 					   struct device *dev, u32 *id)
220 {
221 	struct iommufd_device *idev;
222 	struct iommufd_group *igroup;
223 	int rc;
224 
225 	/*
226 	 * iommufd always sets IOMMU_CACHE because we offer no way for userspace
227 	 * to restore cache coherency.
228 	 */
229 	if (!device_iommu_capable(dev, IOMMU_CAP_CACHE_COHERENCY))
230 		return ERR_PTR(-EINVAL);
231 
232 	igroup = iommufd_get_group(ictx, dev);
233 	if (IS_ERR(igroup))
234 		return ERR_CAST(igroup);
235 
236 	/*
237 	 * For historical compat with VFIO the insecure interrupt path is
238 	 * allowed if the module parameter is set. Secure/Isolated means that a
239 	 * MemWr operation from the device (eg a simple DMA) cannot trigger an
240 	 * interrupt outside this iommufd context.
241 	 */
242 	if (!iommufd_selftest_is_mock_dev(dev) &&
243 	    !iommu_group_has_isolated_msi(igroup->group)) {
244 		if (!allow_unsafe_interrupts) {
245 			rc = -EPERM;
246 			goto out_group_put;
247 		}
248 
249 		dev_warn(
250 			dev,
251 			"MSI interrupts are not secure, they cannot be isolated by the platform. "
252 			"Check that platform features like interrupt remapping are enabled. "
253 			"Use the \"allow_unsafe_interrupts\" module parameter to override\n");
254 	}
255 
256 	rc = iommu_device_claim_dma_owner(dev, ictx);
257 	if (rc)
258 		goto out_group_put;
259 
260 	idev = iommufd_object_alloc(ictx, idev, IOMMUFD_OBJ_DEVICE);
261 	if (IS_ERR(idev)) {
262 		rc = PTR_ERR(idev);
263 		goto out_release_owner;
264 	}
265 	idev->ictx = ictx;
266 	if (!iommufd_selftest_is_mock_dev(dev))
267 		iommufd_ctx_get(ictx);
268 	idev->dev = dev;
269 	idev->enforce_cache_coherency =
270 		device_iommu_capable(dev, IOMMU_CAP_ENFORCE_CACHE_COHERENCY);
271 	/* The calling driver is a user until iommufd_device_unbind() */
272 	refcount_inc(&idev->obj.users);
273 	/* igroup refcount moves into iommufd_device */
274 	idev->igroup = igroup;
275 
276 	/*
277 	 * If the caller fails after this success it must call
278 	 * iommufd_unbind_device() which is safe since we hold this refcount.
279 	 * This also means the device is a leaf in the graph and no other object
280 	 * can take a reference on it.
281 	 */
282 	iommufd_object_finalize(ictx, &idev->obj);
283 	*id = idev->obj.id;
284 	return idev;
285 
286 out_release_owner:
287 	iommu_device_release_dma_owner(dev);
288 out_group_put:
289 	iommufd_put_group(igroup);
290 	return ERR_PTR(rc);
291 }
292 EXPORT_SYMBOL_NS_GPL(iommufd_device_bind, "IOMMUFD");
293 
294 /**
295  * iommufd_ctx_has_group - True if any device within the group is bound
296  *                         to the ictx
297  * @ictx: iommufd file descriptor
298  * @group: Pointer to a physical iommu_group struct
299  *
300  * True if any device within the group has been bound to this ictx, ex. via
301  * iommufd_device_bind(), therefore implying ictx ownership of the group.
302  */
303 bool iommufd_ctx_has_group(struct iommufd_ctx *ictx, struct iommu_group *group)
304 {
305 	struct iommufd_object *obj;
306 	unsigned long index;
307 
308 	if (!ictx || !group)
309 		return false;
310 
311 	xa_lock(&ictx->objects);
312 	xa_for_each(&ictx->objects, index, obj) {
313 		if (obj->type == IOMMUFD_OBJ_DEVICE &&
314 		    container_of(obj, struct iommufd_device, obj)
315 				    ->igroup->group == group) {
316 			xa_unlock(&ictx->objects);
317 			return true;
318 		}
319 	}
320 	xa_unlock(&ictx->objects);
321 	return false;
322 }
323 EXPORT_SYMBOL_NS_GPL(iommufd_ctx_has_group, "IOMMUFD");
324 
325 /**
326  * iommufd_device_unbind - Undo iommufd_device_bind()
327  * @idev: Device returned by iommufd_device_bind()
328  *
329  * Release the device from iommufd control. The DMA ownership will return back
330  * to unowned with DMA controlled by the DMA API. This invalidates the
331  * iommufd_device pointer, other APIs that consume it must not be called
332  * concurrently.
333  */
334 void iommufd_device_unbind(struct iommufd_device *idev)
335 {
336 	iommufd_object_destroy_user(idev->ictx, &idev->obj);
337 }
338 EXPORT_SYMBOL_NS_GPL(iommufd_device_unbind, "IOMMUFD");
339 
340 struct iommufd_ctx *iommufd_device_to_ictx(struct iommufd_device *idev)
341 {
342 	return idev->ictx;
343 }
344 EXPORT_SYMBOL_NS_GPL(iommufd_device_to_ictx, "IOMMUFD");
345 
346 u32 iommufd_device_to_id(struct iommufd_device *idev)
347 {
348 	return idev->obj.id;
349 }
350 EXPORT_SYMBOL_NS_GPL(iommufd_device_to_id, "IOMMUFD");
351 
352 static unsigned int iommufd_group_device_num(struct iommufd_group *igroup,
353 					     ioasid_t pasid)
354 {
355 	struct iommufd_attach *attach;
356 	struct iommufd_device *idev;
357 	unsigned int count = 0;
358 	unsigned long index;
359 
360 	lockdep_assert_held(&igroup->lock);
361 
362 	attach = xa_load(&igroup->pasid_attach, pasid);
363 	if (attach)
364 		xa_for_each(&attach->device_array, index, idev)
365 			count++;
366 	return count;
367 }
368 
369 #ifdef CONFIG_IRQ_MSI_IOMMU
370 static int iommufd_group_setup_msi(struct iommufd_group *igroup,
371 				   struct iommufd_hwpt_paging *hwpt_paging)
372 {
373 	struct iommufd_ctx *ictx = igroup->ictx;
374 	struct iommufd_sw_msi_map *cur;
375 
376 	if (igroup->sw_msi_start == PHYS_ADDR_MAX)
377 		return 0;
378 
379 	/*
380 	 * Install all the MSI pages the device has been using into the domain
381 	 */
382 	guard(mutex)(&ictx->sw_msi_lock);
383 	list_for_each_entry(cur, &ictx->sw_msi_list, sw_msi_item) {
384 		int rc;
385 
386 		if (cur->sw_msi_start != igroup->sw_msi_start ||
387 		    !test_bit(cur->id, igroup->required_sw_msi.bitmap))
388 			continue;
389 
390 		rc = iommufd_sw_msi_install(ictx, hwpt_paging, cur);
391 		if (rc)
392 			return rc;
393 	}
394 	return 0;
395 }
396 #else
397 static inline int
398 iommufd_group_setup_msi(struct iommufd_group *igroup,
399 			struct iommufd_hwpt_paging *hwpt_paging)
400 {
401 	return 0;
402 }
403 #endif
404 
405 static bool
406 iommufd_group_first_attach(struct iommufd_group *igroup, ioasid_t pasid)
407 {
408 	lockdep_assert_held(&igroup->lock);
409 	return !xa_load(&igroup->pasid_attach, pasid);
410 }
411 
412 static int
413 iommufd_device_attach_reserved_iova(struct iommufd_device *idev,
414 				    struct iommufd_hwpt_paging *hwpt_paging)
415 {
416 	struct iommufd_group *igroup = idev->igroup;
417 	int rc;
418 
419 	lockdep_assert_held(&igroup->lock);
420 
421 	rc = iopt_table_enforce_dev_resv_regions(&hwpt_paging->ioas->iopt,
422 						 idev->dev,
423 						 &igroup->sw_msi_start);
424 	if (rc)
425 		return rc;
426 
427 	if (iommufd_group_first_attach(igroup, IOMMU_NO_PASID)) {
428 		rc = iommufd_group_setup_msi(igroup, hwpt_paging);
429 		if (rc) {
430 			iopt_remove_reserved_iova(&hwpt_paging->ioas->iopt,
431 						  idev->dev);
432 			return rc;
433 		}
434 	}
435 	return 0;
436 }
437 
438 /* The device attach/detach/replace helpers for attach_handle */
439 
440 static bool iommufd_device_is_attached(struct iommufd_device *idev,
441 				       ioasid_t pasid)
442 {
443 	struct iommufd_attach *attach;
444 
445 	attach = xa_load(&idev->igroup->pasid_attach, pasid);
446 	return xa_load(&attach->device_array, idev->obj.id);
447 }
448 
449 static int iommufd_hwpt_pasid_compat(struct iommufd_hw_pagetable *hwpt,
450 				     struct iommufd_device *idev,
451 				     ioasid_t pasid)
452 {
453 	struct iommufd_group *igroup = idev->igroup;
454 
455 	lockdep_assert_held(&igroup->lock);
456 
457 	if (pasid == IOMMU_NO_PASID) {
458 		unsigned long start = IOMMU_NO_PASID;
459 
460 		if (!hwpt->pasid_compat &&
461 		    xa_find_after(&igroup->pasid_attach,
462 				  &start, UINT_MAX, XA_PRESENT))
463 			return -EINVAL;
464 	} else {
465 		struct iommufd_attach *attach;
466 
467 		if (!hwpt->pasid_compat)
468 			return -EINVAL;
469 
470 		attach = xa_load(&igroup->pasid_attach, IOMMU_NO_PASID);
471 		if (attach && attach->hwpt && !attach->hwpt->pasid_compat)
472 			return -EINVAL;
473 	}
474 
475 	return 0;
476 }
477 
478 static bool iommufd_hwpt_compatible_device(struct iommufd_hw_pagetable *hwpt,
479 					   struct iommufd_device *idev)
480 {
481 	struct pci_dev *pdev;
482 
483 	if (!hwpt->fault || !dev_is_pci(idev->dev))
484 		return true;
485 
486 	/*
487 	 * Once we turn on PCI/PRI support for VF, the response failure code
488 	 * should not be forwarded to the hardware due to PRI being a shared
489 	 * resource between PF and VFs. There is no coordination for this
490 	 * shared capability. This waits for a vPRI reset to recover.
491 	 */
492 	pdev = to_pci_dev(idev->dev);
493 
494 	return (!pdev->is_virtfn || !pci_pri_supported(pdev));
495 }
496 
497 static int iommufd_hwpt_attach_device(struct iommufd_hw_pagetable *hwpt,
498 				      struct iommufd_device *idev,
499 				      ioasid_t pasid)
500 {
501 	struct iommufd_attach_handle *handle;
502 	int rc;
503 
504 	if (!iommufd_hwpt_compatible_device(hwpt, idev))
505 		return -EINVAL;
506 
507 	rc = iommufd_hwpt_pasid_compat(hwpt, idev, pasid);
508 	if (rc)
509 		return rc;
510 
511 	handle = kzalloc(sizeof(*handle), GFP_KERNEL);
512 	if (!handle)
513 		return -ENOMEM;
514 
515 	handle->idev = idev;
516 	if (pasid == IOMMU_NO_PASID)
517 		rc = iommu_attach_group_handle(hwpt->domain, idev->igroup->group,
518 					       &handle->handle);
519 	else
520 		rc = iommu_attach_device_pasid(hwpt->domain, idev->dev, pasid,
521 					       &handle->handle);
522 	if (rc)
523 		goto out_free_handle;
524 
525 	return 0;
526 
527 out_free_handle:
528 	kfree(handle);
529 	return rc;
530 }
531 
532 static struct iommufd_attach_handle *
533 iommufd_device_get_attach_handle(struct iommufd_device *idev, ioasid_t pasid)
534 {
535 	struct iommu_attach_handle *handle;
536 
537 	lockdep_assert_held(&idev->igroup->lock);
538 
539 	handle = iommu_attach_handle_get(idev->igroup->group, pasid, 0);
540 	if (IS_ERR(handle))
541 		return NULL;
542 	return to_iommufd_handle(handle);
543 }
544 
545 static void iommufd_hwpt_detach_device(struct iommufd_hw_pagetable *hwpt,
546 				       struct iommufd_device *idev,
547 				       ioasid_t pasid)
548 {
549 	struct iommufd_attach_handle *handle;
550 
551 	handle = iommufd_device_get_attach_handle(idev, pasid);
552 	if (pasid == IOMMU_NO_PASID)
553 		iommu_detach_group_handle(hwpt->domain, idev->igroup->group);
554 	else
555 		iommu_detach_device_pasid(hwpt->domain, idev->dev, pasid);
556 
557 	iommufd_auto_response_faults(hwpt, handle);
558 	kfree(handle);
559 }
560 
561 static int iommufd_hwpt_replace_device(struct iommufd_device *idev,
562 				       ioasid_t pasid,
563 				       struct iommufd_hw_pagetable *hwpt,
564 				       struct iommufd_hw_pagetable *old)
565 {
566 	struct iommufd_attach_handle *handle, *old_handle;
567 	int rc;
568 
569 	if (!iommufd_hwpt_compatible_device(hwpt, idev))
570 		return -EINVAL;
571 
572 	rc = iommufd_hwpt_pasid_compat(hwpt, idev, pasid);
573 	if (rc)
574 		return rc;
575 
576 	old_handle = iommufd_device_get_attach_handle(idev, pasid);
577 
578 	handle = kzalloc(sizeof(*handle), GFP_KERNEL);
579 	if (!handle)
580 		return -ENOMEM;
581 
582 	handle->idev = idev;
583 	if (pasid == IOMMU_NO_PASID)
584 		rc = iommu_replace_group_handle(idev->igroup->group,
585 						hwpt->domain, &handle->handle);
586 	else
587 		rc = iommu_replace_device_pasid(hwpt->domain, idev->dev,
588 						pasid, &handle->handle);
589 	if (rc)
590 		goto out_free_handle;
591 
592 	iommufd_auto_response_faults(hwpt, old_handle);
593 	kfree(old_handle);
594 
595 	return 0;
596 
597 out_free_handle:
598 	kfree(handle);
599 	return rc;
600 }
601 
602 int iommufd_hw_pagetable_attach(struct iommufd_hw_pagetable *hwpt,
603 				struct iommufd_device *idev, ioasid_t pasid)
604 {
605 	struct iommufd_hwpt_paging *hwpt_paging = find_hwpt_paging(hwpt);
606 	bool attach_resv = hwpt_paging && pasid == IOMMU_NO_PASID;
607 	struct iommufd_group *igroup = idev->igroup;
608 	struct iommufd_hw_pagetable *old_hwpt;
609 	struct iommufd_attach *attach;
610 	int rc;
611 
612 	mutex_lock(&igroup->lock);
613 
614 	attach = xa_cmpxchg(&igroup->pasid_attach, pasid, NULL,
615 			    XA_ZERO_ENTRY, GFP_KERNEL);
616 	if (xa_is_err(attach)) {
617 		rc = xa_err(attach);
618 		goto err_unlock;
619 	}
620 
621 	if (!attach) {
622 		attach = kzalloc(sizeof(*attach), GFP_KERNEL);
623 		if (!attach) {
624 			rc = -ENOMEM;
625 			goto err_release_pasid;
626 		}
627 		xa_init(&attach->device_array);
628 	}
629 
630 	old_hwpt = attach->hwpt;
631 
632 	rc = xa_insert(&attach->device_array, idev->obj.id, XA_ZERO_ENTRY,
633 		       GFP_KERNEL);
634 	if (rc) {
635 		WARN_ON(rc == -EBUSY && !old_hwpt);
636 		goto err_free_attach;
637 	}
638 
639 	if (old_hwpt && old_hwpt != hwpt) {
640 		rc = -EINVAL;
641 		goto err_release_devid;
642 	}
643 
644 	if (attach_resv) {
645 		rc = iommufd_device_attach_reserved_iova(idev, hwpt_paging);
646 		if (rc)
647 			goto err_release_devid;
648 	}
649 
650 	/*
651 	 * Only attach to the group once for the first device that is in the
652 	 * group. All the other devices will follow this attachment. The user
653 	 * should attach every device individually to the hwpt as the per-device
654 	 * reserved regions are only updated during individual device
655 	 * attachment.
656 	 */
657 	if (iommufd_group_first_attach(igroup, pasid)) {
658 		rc = iommufd_hwpt_attach_device(hwpt, idev, pasid);
659 		if (rc)
660 			goto err_unresv;
661 		attach->hwpt = hwpt;
662 		WARN_ON(xa_is_err(xa_store(&igroup->pasid_attach, pasid, attach,
663 					   GFP_KERNEL)));
664 	}
665 	refcount_inc(&hwpt->obj.users);
666 	WARN_ON(xa_is_err(xa_store(&attach->device_array, idev->obj.id,
667 				   idev, GFP_KERNEL)));
668 	mutex_unlock(&igroup->lock);
669 	return 0;
670 err_unresv:
671 	if (attach_resv)
672 		iopt_remove_reserved_iova(&hwpt_paging->ioas->iopt, idev->dev);
673 err_release_devid:
674 	xa_release(&attach->device_array, idev->obj.id);
675 err_free_attach:
676 	if (iommufd_group_first_attach(igroup, pasid))
677 		kfree(attach);
678 err_release_pasid:
679 	if (iommufd_group_first_attach(igroup, pasid))
680 		xa_release(&igroup->pasid_attach, pasid);
681 err_unlock:
682 	mutex_unlock(&igroup->lock);
683 	return rc;
684 }
685 
686 struct iommufd_hw_pagetable *
687 iommufd_hw_pagetable_detach(struct iommufd_device *idev, ioasid_t pasid)
688 {
689 	struct iommufd_group *igroup = idev->igroup;
690 	struct iommufd_hwpt_paging *hwpt_paging;
691 	struct iommufd_hw_pagetable *hwpt;
692 	struct iommufd_attach *attach;
693 
694 	mutex_lock(&igroup->lock);
695 	attach = xa_load(&igroup->pasid_attach, pasid);
696 	if (!attach) {
697 		mutex_unlock(&igroup->lock);
698 		return NULL;
699 	}
700 
701 	hwpt = attach->hwpt;
702 	hwpt_paging = find_hwpt_paging(hwpt);
703 
704 	xa_erase(&attach->device_array, idev->obj.id);
705 	if (xa_empty(&attach->device_array)) {
706 		iommufd_hwpt_detach_device(hwpt, idev, pasid);
707 		xa_erase(&igroup->pasid_attach, pasid);
708 		kfree(attach);
709 	}
710 	if (hwpt_paging && pasid == IOMMU_NO_PASID)
711 		iopt_remove_reserved_iova(&hwpt_paging->ioas->iopt, idev->dev);
712 	mutex_unlock(&igroup->lock);
713 
714 	/* Caller must destroy hwpt */
715 	return hwpt;
716 }
717 
718 static struct iommufd_hw_pagetable *
719 iommufd_device_do_attach(struct iommufd_device *idev, ioasid_t pasid,
720 			 struct iommufd_hw_pagetable *hwpt)
721 {
722 	int rc;
723 
724 	rc = iommufd_hw_pagetable_attach(hwpt, idev, pasid);
725 	if (rc)
726 		return ERR_PTR(rc);
727 	return NULL;
728 }
729 
730 static void
731 iommufd_group_remove_reserved_iova(struct iommufd_group *igroup,
732 				   struct iommufd_hwpt_paging *hwpt_paging)
733 {
734 	struct iommufd_attach *attach;
735 	struct iommufd_device *cur;
736 	unsigned long index;
737 
738 	lockdep_assert_held(&igroup->lock);
739 
740 	attach = xa_load(&igroup->pasid_attach, IOMMU_NO_PASID);
741 	xa_for_each(&attach->device_array, index, cur)
742 		iopt_remove_reserved_iova(&hwpt_paging->ioas->iopt, cur->dev);
743 }
744 
745 static int
746 iommufd_group_do_replace_reserved_iova(struct iommufd_group *igroup,
747 				       struct iommufd_hwpt_paging *hwpt_paging)
748 {
749 	struct iommufd_hwpt_paging *old_hwpt_paging;
750 	struct iommufd_attach *attach;
751 	struct iommufd_device *cur;
752 	unsigned long index;
753 	int rc;
754 
755 	lockdep_assert_held(&igroup->lock);
756 
757 	attach = xa_load(&igroup->pasid_attach, IOMMU_NO_PASID);
758 	old_hwpt_paging = find_hwpt_paging(attach->hwpt);
759 	if (!old_hwpt_paging || hwpt_paging->ioas != old_hwpt_paging->ioas) {
760 		xa_for_each(&attach->device_array, index, cur) {
761 			rc = iopt_table_enforce_dev_resv_regions(
762 				&hwpt_paging->ioas->iopt, cur->dev, NULL);
763 			if (rc)
764 				goto err_unresv;
765 		}
766 	}
767 
768 	rc = iommufd_group_setup_msi(igroup, hwpt_paging);
769 	if (rc)
770 		goto err_unresv;
771 	return 0;
772 
773 err_unresv:
774 	iommufd_group_remove_reserved_iova(igroup, hwpt_paging);
775 	return rc;
776 }
777 
778 static struct iommufd_hw_pagetable *
779 iommufd_device_do_replace(struct iommufd_device *idev, ioasid_t pasid,
780 			  struct iommufd_hw_pagetable *hwpt)
781 {
782 	struct iommufd_hwpt_paging *hwpt_paging = find_hwpt_paging(hwpt);
783 	bool attach_resv = hwpt_paging && pasid == IOMMU_NO_PASID;
784 	struct iommufd_hwpt_paging *old_hwpt_paging;
785 	struct iommufd_group *igroup = idev->igroup;
786 	struct iommufd_hw_pagetable *old_hwpt;
787 	struct iommufd_attach *attach;
788 	unsigned int num_devices;
789 	int rc;
790 
791 	mutex_lock(&igroup->lock);
792 
793 	attach = xa_load(&igroup->pasid_attach, pasid);
794 	if (!attach) {
795 		rc = -EINVAL;
796 		goto err_unlock;
797 	}
798 
799 	old_hwpt = attach->hwpt;
800 
801 	WARN_ON(!old_hwpt || xa_empty(&attach->device_array));
802 
803 	if (!iommufd_device_is_attached(idev, pasid)) {
804 		rc = -EINVAL;
805 		goto err_unlock;
806 	}
807 
808 	if (hwpt == old_hwpt) {
809 		mutex_unlock(&igroup->lock);
810 		return NULL;
811 	}
812 
813 	if (attach_resv) {
814 		rc = iommufd_group_do_replace_reserved_iova(igroup, hwpt_paging);
815 		if (rc)
816 			goto err_unlock;
817 	}
818 
819 	rc = iommufd_hwpt_replace_device(idev, pasid, hwpt, old_hwpt);
820 	if (rc)
821 		goto err_unresv;
822 
823 	old_hwpt_paging = find_hwpt_paging(old_hwpt);
824 	if (old_hwpt_paging && pasid == IOMMU_NO_PASID &&
825 	    (!hwpt_paging || hwpt_paging->ioas != old_hwpt_paging->ioas))
826 		iommufd_group_remove_reserved_iova(igroup, old_hwpt_paging);
827 
828 	attach->hwpt = hwpt;
829 
830 	num_devices = iommufd_group_device_num(igroup, pasid);
831 	/*
832 	 * Move the refcounts held by the device_array to the new hwpt. Retain a
833 	 * refcount for this thread as the caller will free it.
834 	 */
835 	refcount_add(num_devices, &hwpt->obj.users);
836 	if (num_devices > 1)
837 		WARN_ON(refcount_sub_and_test(num_devices - 1,
838 					      &old_hwpt->obj.users));
839 	mutex_unlock(&igroup->lock);
840 
841 	/* Caller must destroy old_hwpt */
842 	return old_hwpt;
843 err_unresv:
844 	if (attach_resv)
845 		iommufd_group_remove_reserved_iova(igroup, hwpt_paging);
846 err_unlock:
847 	mutex_unlock(&igroup->lock);
848 	return ERR_PTR(rc);
849 }
850 
851 typedef struct iommufd_hw_pagetable *(*attach_fn)(
852 	struct iommufd_device *idev, ioasid_t pasid,
853 	struct iommufd_hw_pagetable *hwpt);
854 
855 /*
856  * When automatically managing the domains we search for a compatible domain in
857  * the iopt and if one is found use it, otherwise create a new domain.
858  * Automatic domain selection will never pick a manually created domain.
859  */
860 static struct iommufd_hw_pagetable *
861 iommufd_device_auto_get_domain(struct iommufd_device *idev, ioasid_t pasid,
862 			       struct iommufd_ioas *ioas, u32 *pt_id,
863 			       attach_fn do_attach)
864 {
865 	/*
866 	 * iommufd_hw_pagetable_attach() is called by
867 	 * iommufd_hw_pagetable_alloc() in immediate attachment mode, same as
868 	 * iommufd_device_do_attach(). So if we are in this mode then we prefer
869 	 * to use the immediate_attach path as it supports drivers that can't
870 	 * directly allocate a domain.
871 	 */
872 	bool immediate_attach = do_attach == iommufd_device_do_attach;
873 	struct iommufd_hw_pagetable *destroy_hwpt;
874 	struct iommufd_hwpt_paging *hwpt_paging;
875 	struct iommufd_hw_pagetable *hwpt;
876 
877 	/*
878 	 * There is no differentiation when domains are allocated, so any domain
879 	 * that is willing to attach to the device is interchangeable with any
880 	 * other.
881 	 */
882 	mutex_lock(&ioas->mutex);
883 	list_for_each_entry(hwpt_paging, &ioas->hwpt_list, hwpt_item) {
884 		if (!hwpt_paging->auto_domain)
885 			continue;
886 
887 		hwpt = &hwpt_paging->common;
888 		if (!iommufd_lock_obj(&hwpt->obj))
889 			continue;
890 		destroy_hwpt = (*do_attach)(idev, pasid, hwpt);
891 		if (IS_ERR(destroy_hwpt)) {
892 			iommufd_put_object(idev->ictx, &hwpt->obj);
893 			/*
894 			 * -EINVAL means the domain is incompatible with the
895 			 * device. Other error codes should propagate to
896 			 * userspace as failure. Success means the domain is
897 			 * attached.
898 			 */
899 			if (PTR_ERR(destroy_hwpt) == -EINVAL)
900 				continue;
901 			goto out_unlock;
902 		}
903 		*pt_id = hwpt->obj.id;
904 		iommufd_put_object(idev->ictx, &hwpt->obj);
905 		goto out_unlock;
906 	}
907 
908 	hwpt_paging = iommufd_hwpt_paging_alloc(idev->ictx, ioas, idev, pasid,
909 						0, immediate_attach, NULL);
910 	if (IS_ERR(hwpt_paging)) {
911 		destroy_hwpt = ERR_CAST(hwpt_paging);
912 		goto out_unlock;
913 	}
914 	hwpt = &hwpt_paging->common;
915 
916 	if (!immediate_attach) {
917 		destroy_hwpt = (*do_attach)(idev, pasid, hwpt);
918 		if (IS_ERR(destroy_hwpt))
919 			goto out_abort;
920 	} else {
921 		destroy_hwpt = NULL;
922 	}
923 
924 	hwpt_paging->auto_domain = true;
925 	*pt_id = hwpt->obj.id;
926 
927 	iommufd_object_finalize(idev->ictx, &hwpt->obj);
928 	mutex_unlock(&ioas->mutex);
929 	return destroy_hwpt;
930 
931 out_abort:
932 	iommufd_object_abort_and_destroy(idev->ictx, &hwpt->obj);
933 out_unlock:
934 	mutex_unlock(&ioas->mutex);
935 	return destroy_hwpt;
936 }
937 
938 static int iommufd_device_change_pt(struct iommufd_device *idev,
939 				    ioasid_t pasid,
940 				    u32 *pt_id, attach_fn do_attach)
941 {
942 	struct iommufd_hw_pagetable *destroy_hwpt;
943 	struct iommufd_object *pt_obj;
944 
945 	pt_obj = iommufd_get_object(idev->ictx, *pt_id, IOMMUFD_OBJ_ANY);
946 	if (IS_ERR(pt_obj))
947 		return PTR_ERR(pt_obj);
948 
949 	switch (pt_obj->type) {
950 	case IOMMUFD_OBJ_HWPT_NESTED:
951 	case IOMMUFD_OBJ_HWPT_PAGING: {
952 		struct iommufd_hw_pagetable *hwpt =
953 			container_of(pt_obj, struct iommufd_hw_pagetable, obj);
954 
955 		destroy_hwpt = (*do_attach)(idev, pasid, hwpt);
956 		if (IS_ERR(destroy_hwpt))
957 			goto out_put_pt_obj;
958 		break;
959 	}
960 	case IOMMUFD_OBJ_IOAS: {
961 		struct iommufd_ioas *ioas =
962 			container_of(pt_obj, struct iommufd_ioas, obj);
963 
964 		destroy_hwpt = iommufd_device_auto_get_domain(idev, pasid, ioas,
965 							      pt_id, do_attach);
966 		if (IS_ERR(destroy_hwpt))
967 			goto out_put_pt_obj;
968 		break;
969 	}
970 	default:
971 		destroy_hwpt = ERR_PTR(-EINVAL);
972 		goto out_put_pt_obj;
973 	}
974 	iommufd_put_object(idev->ictx, pt_obj);
975 
976 	/* This destruction has to be after we unlock everything */
977 	if (destroy_hwpt)
978 		iommufd_hw_pagetable_put(idev->ictx, destroy_hwpt);
979 	return 0;
980 
981 out_put_pt_obj:
982 	iommufd_put_object(idev->ictx, pt_obj);
983 	return PTR_ERR(destroy_hwpt);
984 }
985 
986 /**
987  * iommufd_device_attach - Connect a device/pasid to an iommu_domain
988  * @idev: device to attach
989  * @pasid: pasid to attach
990  * @pt_id: Input a IOMMUFD_OBJ_IOAS, or IOMMUFD_OBJ_HWPT_PAGING
991  *         Output the IOMMUFD_OBJ_HWPT_PAGING ID
992  *
993  * This connects the device/pasid to an iommu_domain, either automatically
994  * or manually selected. Once this completes the device could do DMA with
995  * @pasid. @pasid is IOMMU_NO_PASID if this attach is for no pasid usage.
996  *
997  * The caller should return the resulting pt_id back to userspace.
998  * This function is undone by calling iommufd_device_detach().
999  */
1000 int iommufd_device_attach(struct iommufd_device *idev, ioasid_t pasid,
1001 			  u32 *pt_id)
1002 {
1003 	int rc;
1004 
1005 	rc = iommufd_device_change_pt(idev, pasid, pt_id,
1006 				      &iommufd_device_do_attach);
1007 	if (rc)
1008 		return rc;
1009 
1010 	/*
1011 	 * Pairs with iommufd_device_detach() - catches caller bugs attempting
1012 	 * to destroy a device with an attachment.
1013 	 */
1014 	refcount_inc(&idev->obj.users);
1015 	return 0;
1016 }
1017 EXPORT_SYMBOL_NS_GPL(iommufd_device_attach, "IOMMUFD");
1018 
1019 /**
1020  * iommufd_device_replace - Change the device/pasid's iommu_domain
1021  * @idev: device to change
1022  * @pasid: pasid to change
1023  * @pt_id: Input a IOMMUFD_OBJ_IOAS, or IOMMUFD_OBJ_HWPT_PAGING
1024  *         Output the IOMMUFD_OBJ_HWPT_PAGING ID
1025  *
1026  * This is the same as::
1027  *
1028  *   iommufd_device_detach();
1029  *   iommufd_device_attach();
1030  *
1031  * If it fails then no change is made to the attachment. The iommu driver may
1032  * implement this so there is no disruption in translation. This can only be
1033  * called if iommufd_device_attach() has already succeeded. @pasid is
1034  * IOMMU_NO_PASID for no pasid usage.
1035  */
1036 int iommufd_device_replace(struct iommufd_device *idev, ioasid_t pasid,
1037 			   u32 *pt_id)
1038 {
1039 	return iommufd_device_change_pt(idev, pasid, pt_id,
1040 					&iommufd_device_do_replace);
1041 }
1042 EXPORT_SYMBOL_NS_GPL(iommufd_device_replace, "IOMMUFD");
1043 
1044 /**
1045  * iommufd_device_detach - Disconnect a device/device to an iommu_domain
1046  * @idev: device to detach
1047  * @pasid: pasid to detach
1048  *
1049  * Undo iommufd_device_attach(). This disconnects the idev from the previously
1050  * attached pt_id. The device returns back to a blocked DMA translation.
1051  * @pasid is IOMMU_NO_PASID for no pasid usage.
1052  */
1053 void iommufd_device_detach(struct iommufd_device *idev, ioasid_t pasid)
1054 {
1055 	struct iommufd_hw_pagetable *hwpt;
1056 
1057 	hwpt = iommufd_hw_pagetable_detach(idev, pasid);
1058 	if (!hwpt)
1059 		return;
1060 	iommufd_hw_pagetable_put(idev->ictx, hwpt);
1061 	refcount_dec(&idev->obj.users);
1062 }
1063 EXPORT_SYMBOL_NS_GPL(iommufd_device_detach, "IOMMUFD");
1064 
1065 /*
1066  * On success, it will refcount_inc() at a valid new_ioas and refcount_dec() at
1067  * a valid cur_ioas (access->ioas). A caller passing in a valid new_ioas should
1068  * call iommufd_put_object() if it does an iommufd_get_object() for a new_ioas.
1069  */
1070 static int iommufd_access_change_ioas(struct iommufd_access *access,
1071 				      struct iommufd_ioas *new_ioas)
1072 {
1073 	u32 iopt_access_list_id = access->iopt_access_list_id;
1074 	struct iommufd_ioas *cur_ioas = access->ioas;
1075 	int rc;
1076 
1077 	lockdep_assert_held(&access->ioas_lock);
1078 
1079 	/* We are racing with a concurrent detach, bail */
1080 	if (cur_ioas != access->ioas_unpin)
1081 		return -EBUSY;
1082 
1083 	if (cur_ioas == new_ioas)
1084 		return 0;
1085 
1086 	/*
1087 	 * Set ioas to NULL to block any further iommufd_access_pin_pages().
1088 	 * iommufd_access_unpin_pages() can continue using access->ioas_unpin.
1089 	 */
1090 	access->ioas = NULL;
1091 
1092 	if (new_ioas) {
1093 		rc = iopt_add_access(&new_ioas->iopt, access);
1094 		if (rc) {
1095 			access->ioas = cur_ioas;
1096 			return rc;
1097 		}
1098 		refcount_inc(&new_ioas->obj.users);
1099 	}
1100 
1101 	if (cur_ioas) {
1102 		if (!iommufd_access_is_internal(access) && access->ops->unmap) {
1103 			mutex_unlock(&access->ioas_lock);
1104 			access->ops->unmap(access->data, 0, ULONG_MAX);
1105 			mutex_lock(&access->ioas_lock);
1106 		}
1107 		iopt_remove_access(&cur_ioas->iopt, access, iopt_access_list_id);
1108 		refcount_dec(&cur_ioas->obj.users);
1109 	}
1110 
1111 	access->ioas = new_ioas;
1112 	access->ioas_unpin = new_ioas;
1113 
1114 	return 0;
1115 }
1116 
1117 static int iommufd_access_change_ioas_id(struct iommufd_access *access, u32 id)
1118 {
1119 	struct iommufd_ioas *ioas = iommufd_get_ioas(access->ictx, id);
1120 	int rc;
1121 
1122 	if (IS_ERR(ioas))
1123 		return PTR_ERR(ioas);
1124 	rc = iommufd_access_change_ioas(access, ioas);
1125 	iommufd_put_object(access->ictx, &ioas->obj);
1126 	return rc;
1127 }
1128 
1129 void iommufd_access_destroy_object(struct iommufd_object *obj)
1130 {
1131 	struct iommufd_access *access =
1132 		container_of(obj, struct iommufd_access, obj);
1133 
1134 	mutex_lock(&access->ioas_lock);
1135 	if (access->ioas)
1136 		WARN_ON(iommufd_access_change_ioas(access, NULL));
1137 	mutex_unlock(&access->ioas_lock);
1138 	if (!iommufd_access_is_internal(access))
1139 		iommufd_ctx_put(access->ictx);
1140 }
1141 
1142 static struct iommufd_access *__iommufd_access_create(struct iommufd_ctx *ictx)
1143 {
1144 	struct iommufd_access *access;
1145 
1146 	/*
1147 	 * There is no uAPI for the access object, but to keep things symmetric
1148 	 * use the object infrastructure anyhow.
1149 	 */
1150 	access = iommufd_object_alloc(ictx, access, IOMMUFD_OBJ_ACCESS);
1151 	if (IS_ERR(access))
1152 		return access;
1153 
1154 	/* The calling driver is a user until iommufd_access_destroy() */
1155 	refcount_inc(&access->obj.users);
1156 	mutex_init(&access->ioas_lock);
1157 	return access;
1158 }
1159 
1160 struct iommufd_access *iommufd_access_create_internal(struct iommufd_ctx *ictx)
1161 {
1162 	struct iommufd_access *access;
1163 
1164 	access = __iommufd_access_create(ictx);
1165 	if (IS_ERR(access))
1166 		return access;
1167 	access->iova_alignment = PAGE_SIZE;
1168 
1169 	iommufd_object_finalize(ictx, &access->obj);
1170 	return access;
1171 }
1172 
1173 /**
1174  * iommufd_access_create - Create an iommufd_access
1175  * @ictx: iommufd file descriptor
1176  * @ops: Driver's ops to associate with the access
1177  * @data: Opaque data to pass into ops functions
1178  * @id: Output ID number to return to userspace for this access
1179  *
1180  * An iommufd_access allows a driver to read/write to the IOAS without using
1181  * DMA. The underlying CPU memory can be accessed using the
1182  * iommufd_access_pin_pages() or iommufd_access_rw() functions.
1183  *
1184  * The provided ops are required to use iommufd_access_pin_pages().
1185  */
1186 struct iommufd_access *
1187 iommufd_access_create(struct iommufd_ctx *ictx,
1188 		      const struct iommufd_access_ops *ops, void *data, u32 *id)
1189 {
1190 	struct iommufd_access *access;
1191 
1192 	access = __iommufd_access_create(ictx);
1193 	if (IS_ERR(access))
1194 		return access;
1195 
1196 	access->data = data;
1197 	access->ops = ops;
1198 
1199 	if (ops->needs_pin_pages)
1200 		access->iova_alignment = PAGE_SIZE;
1201 	else
1202 		access->iova_alignment = 1;
1203 
1204 	access->ictx = ictx;
1205 	iommufd_ctx_get(ictx);
1206 	iommufd_object_finalize(ictx, &access->obj);
1207 	*id = access->obj.id;
1208 	return access;
1209 }
1210 EXPORT_SYMBOL_NS_GPL(iommufd_access_create, "IOMMUFD");
1211 
1212 /**
1213  * iommufd_access_destroy - Destroy an iommufd_access
1214  * @access: The access to destroy
1215  *
1216  * The caller must stop using the access before destroying it.
1217  */
1218 void iommufd_access_destroy(struct iommufd_access *access)
1219 {
1220 	iommufd_object_destroy_user(access->ictx, &access->obj);
1221 }
1222 EXPORT_SYMBOL_NS_GPL(iommufd_access_destroy, "IOMMUFD");
1223 
1224 void iommufd_access_detach(struct iommufd_access *access)
1225 {
1226 	mutex_lock(&access->ioas_lock);
1227 	if (WARN_ON(!access->ioas)) {
1228 		mutex_unlock(&access->ioas_lock);
1229 		return;
1230 	}
1231 	WARN_ON(iommufd_access_change_ioas(access, NULL));
1232 	mutex_unlock(&access->ioas_lock);
1233 }
1234 EXPORT_SYMBOL_NS_GPL(iommufd_access_detach, "IOMMUFD");
1235 
1236 int iommufd_access_attach(struct iommufd_access *access, u32 ioas_id)
1237 {
1238 	int rc;
1239 
1240 	mutex_lock(&access->ioas_lock);
1241 	if (WARN_ON(access->ioas)) {
1242 		mutex_unlock(&access->ioas_lock);
1243 		return -EINVAL;
1244 	}
1245 
1246 	rc = iommufd_access_change_ioas_id(access, ioas_id);
1247 	mutex_unlock(&access->ioas_lock);
1248 	return rc;
1249 }
1250 EXPORT_SYMBOL_NS_GPL(iommufd_access_attach, "IOMMUFD");
1251 
1252 int iommufd_access_attach_internal(struct iommufd_access *access,
1253 				   struct iommufd_ioas *ioas)
1254 {
1255 	int rc;
1256 
1257 	mutex_lock(&access->ioas_lock);
1258 	if (WARN_ON(access->ioas)) {
1259 		mutex_unlock(&access->ioas_lock);
1260 		return -EINVAL;
1261 	}
1262 
1263 	rc = iommufd_access_change_ioas(access, ioas);
1264 	mutex_unlock(&access->ioas_lock);
1265 	return rc;
1266 }
1267 
1268 int iommufd_access_replace(struct iommufd_access *access, u32 ioas_id)
1269 {
1270 	int rc;
1271 
1272 	mutex_lock(&access->ioas_lock);
1273 	if (!access->ioas) {
1274 		mutex_unlock(&access->ioas_lock);
1275 		return -ENOENT;
1276 	}
1277 	rc = iommufd_access_change_ioas_id(access, ioas_id);
1278 	mutex_unlock(&access->ioas_lock);
1279 	return rc;
1280 }
1281 EXPORT_SYMBOL_NS_GPL(iommufd_access_replace, "IOMMUFD");
1282 
1283 /**
1284  * iommufd_access_notify_unmap - Notify users of an iopt to stop using it
1285  * @iopt: iopt to work on
1286  * @iova: Starting iova in the iopt
1287  * @length: Number of bytes
1288  *
1289  * After this function returns there should be no users attached to the pages
1290  * linked to this iopt that intersect with iova,length. Anyone that has attached
1291  * a user through iopt_access_pages() needs to detach it through
1292  * iommufd_access_unpin_pages() before this function returns.
1293  *
1294  * iommufd_access_destroy() will wait for any outstanding unmap callback to
1295  * complete. Once iommufd_access_destroy() no unmap ops are running or will
1296  * run in the future. Due to this a driver must not create locking that prevents
1297  * unmap to complete while iommufd_access_destroy() is running.
1298  */
1299 void iommufd_access_notify_unmap(struct io_pagetable *iopt, unsigned long iova,
1300 				 unsigned long length)
1301 {
1302 	struct iommufd_ioas *ioas =
1303 		container_of(iopt, struct iommufd_ioas, iopt);
1304 	struct iommufd_access *access;
1305 	unsigned long index;
1306 
1307 	xa_lock(&ioas->iopt.access_list);
1308 	xa_for_each(&ioas->iopt.access_list, index, access) {
1309 		if (!iommufd_lock_obj(&access->obj) ||
1310 		    iommufd_access_is_internal(access))
1311 			continue;
1312 		xa_unlock(&ioas->iopt.access_list);
1313 
1314 		access->ops->unmap(access->data, iova, length);
1315 
1316 		iommufd_put_object(access->ictx, &access->obj);
1317 		xa_lock(&ioas->iopt.access_list);
1318 	}
1319 	xa_unlock(&ioas->iopt.access_list);
1320 }
1321 
1322 /**
1323  * iommufd_access_unpin_pages() - Undo iommufd_access_pin_pages
1324  * @access: IOAS access to act on
1325  * @iova: Starting IOVA
1326  * @length: Number of bytes to access
1327  *
1328  * Return the struct page's. The caller must stop accessing them before calling
1329  * this. The iova/length must exactly match the one provided to access_pages.
1330  */
1331 void iommufd_access_unpin_pages(struct iommufd_access *access,
1332 				unsigned long iova, unsigned long length)
1333 {
1334 	bool internal = iommufd_access_is_internal(access);
1335 	struct iopt_area_contig_iter iter;
1336 	struct io_pagetable *iopt;
1337 	unsigned long last_iova;
1338 	struct iopt_area *area;
1339 
1340 	if (WARN_ON(!length) ||
1341 	    WARN_ON(check_add_overflow(iova, length - 1, &last_iova)))
1342 		return;
1343 
1344 	mutex_lock(&access->ioas_lock);
1345 	/*
1346 	 * The driver must be doing something wrong if it calls this before an
1347 	 * iommufd_access_attach() or after an iommufd_access_detach().
1348 	 */
1349 	if (WARN_ON(!access->ioas_unpin)) {
1350 		mutex_unlock(&access->ioas_lock);
1351 		return;
1352 	}
1353 	iopt = &access->ioas_unpin->iopt;
1354 
1355 	down_read(&iopt->iova_rwsem);
1356 	iopt_for_each_contig_area(&iter, area, iopt, iova, last_iova)
1357 		iopt_area_remove_access(
1358 			area, iopt_area_iova_to_index(area, iter.cur_iova),
1359 			iopt_area_iova_to_index(
1360 				area,
1361 				min(last_iova, iopt_area_last_iova(area))),
1362 			internal);
1363 	WARN_ON(!iopt_area_contig_done(&iter));
1364 	up_read(&iopt->iova_rwsem);
1365 	mutex_unlock(&access->ioas_lock);
1366 }
1367 EXPORT_SYMBOL_NS_GPL(iommufd_access_unpin_pages, "IOMMUFD");
1368 
1369 static bool iopt_area_contig_is_aligned(struct iopt_area_contig_iter *iter)
1370 {
1371 	if (iopt_area_start_byte(iter->area, iter->cur_iova) % PAGE_SIZE)
1372 		return false;
1373 
1374 	if (!iopt_area_contig_done(iter) &&
1375 	    (iopt_area_start_byte(iter->area, iopt_area_last_iova(iter->area)) %
1376 	     PAGE_SIZE) != (PAGE_SIZE - 1))
1377 		return false;
1378 	return true;
1379 }
1380 
1381 static bool check_area_prot(struct iopt_area *area, unsigned int flags)
1382 {
1383 	if (flags & IOMMUFD_ACCESS_RW_WRITE)
1384 		return area->iommu_prot & IOMMU_WRITE;
1385 	return area->iommu_prot & IOMMU_READ;
1386 }
1387 
1388 /**
1389  * iommufd_access_pin_pages() - Return a list of pages under the iova
1390  * @access: IOAS access to act on
1391  * @iova: Starting IOVA
1392  * @length: Number of bytes to access
1393  * @out_pages: Output page list
1394  * @flags: IOPMMUFD_ACCESS_RW_* flags
1395  *
1396  * Reads @length bytes starting at iova and returns the struct page * pointers.
1397  * These can be kmap'd by the caller for CPU access.
1398  *
1399  * The caller must perform iommufd_access_unpin_pages() when done to balance
1400  * this.
1401  *
1402  * This API always requires a page aligned iova. This happens naturally if the
1403  * ioas alignment is >= PAGE_SIZE and the iova is PAGE_SIZE aligned. However
1404  * smaller alignments have corner cases where this API can fail on otherwise
1405  * aligned iova.
1406  */
1407 int iommufd_access_pin_pages(struct iommufd_access *access, unsigned long iova,
1408 			     unsigned long length, struct page **out_pages,
1409 			     unsigned int flags)
1410 {
1411 	bool internal = iommufd_access_is_internal(access);
1412 	struct iopt_area_contig_iter iter;
1413 	struct io_pagetable *iopt;
1414 	unsigned long last_iova;
1415 	struct iopt_area *area;
1416 	int rc;
1417 
1418 	/* Driver's ops don't support pin_pages */
1419 	if (IS_ENABLED(CONFIG_IOMMUFD_TEST) &&
1420 	    WARN_ON(access->iova_alignment != PAGE_SIZE ||
1421 		    (!internal && !access->ops->unmap)))
1422 		return -EINVAL;
1423 
1424 	if (!length)
1425 		return -EINVAL;
1426 	if (check_add_overflow(iova, length - 1, &last_iova))
1427 		return -EOVERFLOW;
1428 
1429 	mutex_lock(&access->ioas_lock);
1430 	if (!access->ioas) {
1431 		mutex_unlock(&access->ioas_lock);
1432 		return -ENOENT;
1433 	}
1434 	iopt = &access->ioas->iopt;
1435 
1436 	down_read(&iopt->iova_rwsem);
1437 	iopt_for_each_contig_area(&iter, area, iopt, iova, last_iova) {
1438 		unsigned long last = min(last_iova, iopt_area_last_iova(area));
1439 		unsigned long last_index = iopt_area_iova_to_index(area, last);
1440 		unsigned long index =
1441 			iopt_area_iova_to_index(area, iter.cur_iova);
1442 
1443 		if (area->prevent_access ||
1444 		    !iopt_area_contig_is_aligned(&iter)) {
1445 			rc = -EINVAL;
1446 			goto err_remove;
1447 		}
1448 
1449 		if (!check_area_prot(area, flags)) {
1450 			rc = -EPERM;
1451 			goto err_remove;
1452 		}
1453 
1454 		rc = iopt_area_add_access(area, index, last_index, out_pages,
1455 					  flags, internal);
1456 		if (rc)
1457 			goto err_remove;
1458 		out_pages += last_index - index + 1;
1459 	}
1460 	if (!iopt_area_contig_done(&iter)) {
1461 		rc = -ENOENT;
1462 		goto err_remove;
1463 	}
1464 
1465 	up_read(&iopt->iova_rwsem);
1466 	mutex_unlock(&access->ioas_lock);
1467 	return 0;
1468 
1469 err_remove:
1470 	if (iova < iter.cur_iova) {
1471 		last_iova = iter.cur_iova - 1;
1472 		iopt_for_each_contig_area(&iter, area, iopt, iova, last_iova)
1473 			iopt_area_remove_access(
1474 				area,
1475 				iopt_area_iova_to_index(area, iter.cur_iova),
1476 				iopt_area_iova_to_index(
1477 					area, min(last_iova,
1478 						  iopt_area_last_iova(area))),
1479 				internal);
1480 	}
1481 	up_read(&iopt->iova_rwsem);
1482 	mutex_unlock(&access->ioas_lock);
1483 	return rc;
1484 }
1485 EXPORT_SYMBOL_NS_GPL(iommufd_access_pin_pages, "IOMMUFD");
1486 
1487 /**
1488  * iommufd_access_rw - Read or write data under the iova
1489  * @access: IOAS access to act on
1490  * @iova: Starting IOVA
1491  * @data: Kernel buffer to copy to/from
1492  * @length: Number of bytes to access
1493  * @flags: IOMMUFD_ACCESS_RW_* flags
1494  *
1495  * Copy kernel to/from data into the range given by IOVA/length. If flags
1496  * indicates IOMMUFD_ACCESS_RW_KTHREAD then a large copy can be optimized
1497  * by changing it into copy_to/from_user().
1498  */
1499 int iommufd_access_rw(struct iommufd_access *access, unsigned long iova,
1500 		      void *data, size_t length, unsigned int flags)
1501 {
1502 	struct iopt_area_contig_iter iter;
1503 	struct io_pagetable *iopt;
1504 	struct iopt_area *area;
1505 	unsigned long last_iova;
1506 	int rc = -EINVAL;
1507 
1508 	if (!length)
1509 		return -EINVAL;
1510 	if (check_add_overflow(iova, length - 1, &last_iova))
1511 		return -EOVERFLOW;
1512 
1513 	mutex_lock(&access->ioas_lock);
1514 	if (!access->ioas) {
1515 		mutex_unlock(&access->ioas_lock);
1516 		return -ENOENT;
1517 	}
1518 	iopt = &access->ioas->iopt;
1519 
1520 	down_read(&iopt->iova_rwsem);
1521 	iopt_for_each_contig_area(&iter, area, iopt, iova, last_iova) {
1522 		unsigned long last = min(last_iova, iopt_area_last_iova(area));
1523 		unsigned long bytes = (last - iter.cur_iova) + 1;
1524 
1525 		if (area->prevent_access) {
1526 			rc = -EINVAL;
1527 			goto err_out;
1528 		}
1529 
1530 		if (!check_area_prot(area, flags)) {
1531 			rc = -EPERM;
1532 			goto err_out;
1533 		}
1534 
1535 		rc = iopt_pages_rw_access(
1536 			area->pages, iopt_area_start_byte(area, iter.cur_iova),
1537 			data, bytes, flags);
1538 		if (rc)
1539 			goto err_out;
1540 		data += bytes;
1541 	}
1542 	if (!iopt_area_contig_done(&iter))
1543 		rc = -ENOENT;
1544 err_out:
1545 	up_read(&iopt->iova_rwsem);
1546 	mutex_unlock(&access->ioas_lock);
1547 	return rc;
1548 }
1549 EXPORT_SYMBOL_NS_GPL(iommufd_access_rw, "IOMMUFD");
1550 
1551 int iommufd_get_hw_info(struct iommufd_ucmd *ucmd)
1552 {
1553 	const u32 SUPPORTED_FLAGS = IOMMU_HW_INFO_FLAG_INPUT_TYPE;
1554 	struct iommu_hw_info *cmd = ucmd->cmd;
1555 	void __user *user_ptr = u64_to_user_ptr(cmd->data_uptr);
1556 	const struct iommu_ops *ops;
1557 	struct iommufd_device *idev;
1558 	unsigned int data_len;
1559 	unsigned int copy_len;
1560 	void *data;
1561 	int rc;
1562 
1563 	if (cmd->flags & ~SUPPORTED_FLAGS)
1564 		return -EOPNOTSUPP;
1565 	if (cmd->__reserved[0] || cmd->__reserved[1] || cmd->__reserved[2])
1566 		return -EOPNOTSUPP;
1567 
1568 	/* Clear the type field since drivers don't support a random input */
1569 	if (!(cmd->flags & IOMMU_HW_INFO_FLAG_INPUT_TYPE))
1570 		cmd->in_data_type = IOMMU_HW_INFO_TYPE_DEFAULT;
1571 
1572 	idev = iommufd_get_device(ucmd, cmd->dev_id);
1573 	if (IS_ERR(idev))
1574 		return PTR_ERR(idev);
1575 
1576 	ops = dev_iommu_ops(idev->dev);
1577 	if (ops->hw_info) {
1578 		data = ops->hw_info(idev->dev, &data_len, &cmd->out_data_type);
1579 		if (IS_ERR(data)) {
1580 			rc = PTR_ERR(data);
1581 			goto out_put;
1582 		}
1583 
1584 		/*
1585 		 * drivers that have hw_info callback should have a unique
1586 		 * iommu_hw_info_type.
1587 		 */
1588 		if (WARN_ON_ONCE(cmd->out_data_type ==
1589 				 IOMMU_HW_INFO_TYPE_NONE)) {
1590 			rc = -EOPNOTSUPP;
1591 			goto out_free;
1592 		}
1593 	} else {
1594 		cmd->out_data_type = IOMMU_HW_INFO_TYPE_NONE;
1595 		data_len = 0;
1596 		data = NULL;
1597 	}
1598 
1599 	copy_len = min(cmd->data_len, data_len);
1600 	if (copy_to_user(user_ptr, data, copy_len)) {
1601 		rc = -EFAULT;
1602 		goto out_free;
1603 	}
1604 
1605 	/*
1606 	 * Zero the trailing bytes if the user buffer is bigger than the
1607 	 * data size kernel actually has.
1608 	 */
1609 	if (copy_len < cmd->data_len) {
1610 		if (clear_user(user_ptr + copy_len, cmd->data_len - copy_len)) {
1611 			rc = -EFAULT;
1612 			goto out_free;
1613 		}
1614 	}
1615 
1616 	/*
1617 	 * We return the length the kernel supports so userspace may know what
1618 	 * the kernel capability is. It could be larger than the input buffer.
1619 	 */
1620 	cmd->data_len = data_len;
1621 
1622 	cmd->out_capabilities = 0;
1623 	if (device_iommu_capable(idev->dev, IOMMU_CAP_DIRTY_TRACKING))
1624 		cmd->out_capabilities |= IOMMU_HW_CAP_DIRTY_TRACKING;
1625 
1626 	cmd->out_max_pasid_log2 = 0;
1627 	/*
1628 	 * Currently, all iommu drivers enable PASID in the probe_device()
1629 	 * op if iommu and device supports it. So the max_pasids stored in
1630 	 * dev->iommu indicates both PASID support and enable status. A
1631 	 * non-zero dev->iommu->max_pasids means PASID is supported and
1632 	 * enabled. The iommufd only reports PASID capability to userspace
1633 	 * if it's enabled.
1634 	 */
1635 	if (idev->dev->iommu->max_pasids) {
1636 		cmd->out_max_pasid_log2 = ilog2(idev->dev->iommu->max_pasids);
1637 
1638 		if (dev_is_pci(idev->dev)) {
1639 			struct pci_dev *pdev = to_pci_dev(idev->dev);
1640 			int ctrl;
1641 
1642 			ctrl = pci_pasid_status(pdev);
1643 
1644 			WARN_ON_ONCE(ctrl < 0 ||
1645 				     !(ctrl & PCI_PASID_CTRL_ENABLE));
1646 
1647 			if (ctrl & PCI_PASID_CTRL_EXEC)
1648 				cmd->out_capabilities |=
1649 						IOMMU_HW_CAP_PCI_PASID_EXEC;
1650 			if (ctrl & PCI_PASID_CTRL_PRIV)
1651 				cmd->out_capabilities |=
1652 						IOMMU_HW_CAP_PCI_PASID_PRIV;
1653 		}
1654 	}
1655 
1656 	rc = iommufd_ucmd_respond(ucmd, sizeof(*cmd));
1657 out_free:
1658 	kfree(data);
1659 out_put:
1660 	iommufd_put_object(ucmd->ictx, &idev->obj);
1661 	return rc;
1662 }
1663