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