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