OSDN Git Service

Merge tag 'vfio-v6.6-rc1' of https://github.com/awilliam/linux-vfio
[tomoyo/tomoyo-test1.git] / drivers / iommu / iommufd / device.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (c) 2021-2022, NVIDIA CORPORATION & AFFILIATES
3  */
4 #include <linux/iommufd.h>
5 #include <linux/slab.h>
6 #include <linux/iommu.h>
7
8 #include "io_pagetable.h"
9 #include "iommufd_private.h"
10
11 static bool allow_unsafe_interrupts;
12 module_param(allow_unsafe_interrupts, bool, S_IRUGO | S_IWUSR);
13 MODULE_PARM_DESC(
14         allow_unsafe_interrupts,
15         "Allow IOMMUFD to bind to devices even if the platform cannot isolate "
16         "the MSI interrupt window. Enabling this is a security weakness.");
17
18 void iommufd_device_destroy(struct iommufd_object *obj)
19 {
20         struct iommufd_device *idev =
21                 container_of(obj, struct iommufd_device, obj);
22
23         iommu_device_release_dma_owner(idev->dev);
24         iommu_group_put(idev->group);
25         if (!iommufd_selftest_is_mock_dev(idev->dev))
26                 iommufd_ctx_put(idev->ictx);
27 }
28
29 /**
30  * iommufd_device_bind - Bind a physical device to an iommu fd
31  * @ictx: iommufd file descriptor
32  * @dev: Pointer to a physical device struct
33  * @id: Output ID number to return to userspace for this device
34  *
35  * A successful bind establishes an ownership over the device and returns
36  * struct iommufd_device pointer, otherwise returns error pointer.
37  *
38  * A driver using this API must set driver_managed_dma and must not touch
39  * the device until this routine succeeds and establishes ownership.
40  *
41  * Binding a PCI device places the entire RID under iommufd control.
42  *
43  * The caller must undo this with iommufd_device_unbind()
44  */
45 struct iommufd_device *iommufd_device_bind(struct iommufd_ctx *ictx,
46                                            struct device *dev, u32 *id)
47 {
48         struct iommufd_device *idev;
49         struct iommu_group *group;
50         int rc;
51
52         /*
53          * iommufd always sets IOMMU_CACHE because we offer no way for userspace
54          * to restore cache coherency.
55          */
56         if (!device_iommu_capable(dev, IOMMU_CAP_CACHE_COHERENCY))
57                 return ERR_PTR(-EINVAL);
58
59         group = iommu_group_get(dev);
60         if (!group)
61                 return ERR_PTR(-ENODEV);
62
63         rc = iommu_device_claim_dma_owner(dev, ictx);
64         if (rc)
65                 goto out_group_put;
66
67         idev = iommufd_object_alloc(ictx, idev, IOMMUFD_OBJ_DEVICE);
68         if (IS_ERR(idev)) {
69                 rc = PTR_ERR(idev);
70                 goto out_release_owner;
71         }
72         idev->ictx = ictx;
73         if (!iommufd_selftest_is_mock_dev(dev))
74                 iommufd_ctx_get(ictx);
75         idev->dev = dev;
76         idev->enforce_cache_coherency =
77                 device_iommu_capable(dev, IOMMU_CAP_ENFORCE_CACHE_COHERENCY);
78         /* The calling driver is a user until iommufd_device_unbind() */
79         refcount_inc(&idev->obj.users);
80         /* group refcount moves into iommufd_device */
81         idev->group = group;
82
83         /*
84          * If the caller fails after this success it must call
85          * iommufd_unbind_device() which is safe since we hold this refcount.
86          * This also means the device is a leaf in the graph and no other object
87          * can take a reference on it.
88          */
89         iommufd_object_finalize(ictx, &idev->obj);
90         *id = idev->obj.id;
91         return idev;
92
93 out_release_owner:
94         iommu_device_release_dma_owner(dev);
95 out_group_put:
96         iommu_group_put(group);
97         return ERR_PTR(rc);
98 }
99 EXPORT_SYMBOL_NS_GPL(iommufd_device_bind, IOMMUFD);
100
101 /**
102  * iommufd_ctx_has_group - True if any device within the group is bound
103  *                         to the ictx
104  * @ictx: iommufd file descriptor
105  * @group: Pointer to a physical iommu_group struct
106  *
107  * True if any device within the group has been bound to this ictx, ex. via
108  * iommufd_device_bind(), therefore implying ictx ownership of the group.
109  */
110 bool iommufd_ctx_has_group(struct iommufd_ctx *ictx, struct iommu_group *group)
111 {
112         struct iommufd_object *obj;
113         unsigned long index;
114
115         if (!ictx || !group)
116                 return false;
117
118         xa_lock(&ictx->objects);
119         xa_for_each(&ictx->objects, index, obj) {
120                 if (obj->type == IOMMUFD_OBJ_DEVICE &&
121                     container_of(obj, struct iommufd_device, obj)->group == group) {
122                         xa_unlock(&ictx->objects);
123                         return true;
124                 }
125         }
126         xa_unlock(&ictx->objects);
127         return false;
128 }
129 EXPORT_SYMBOL_NS_GPL(iommufd_ctx_has_group, IOMMUFD);
130
131 /**
132  * iommufd_device_unbind - Undo iommufd_device_bind()
133  * @idev: Device returned by iommufd_device_bind()
134  *
135  * Release the device from iommufd control. The DMA ownership will return back
136  * to unowned with DMA controlled by the DMA API. This invalidates the
137  * iommufd_device pointer, other APIs that consume it must not be called
138  * concurrently.
139  */
140 void iommufd_device_unbind(struct iommufd_device *idev)
141 {
142         iommufd_object_destroy_user(idev->ictx, &idev->obj);
143 }
144 EXPORT_SYMBOL_NS_GPL(iommufd_device_unbind, IOMMUFD);
145
146 struct iommufd_ctx *iommufd_device_to_ictx(struct iommufd_device *idev)
147 {
148         return idev->ictx;
149 }
150 EXPORT_SYMBOL_NS_GPL(iommufd_device_to_ictx, IOMMUFD);
151
152 u32 iommufd_device_to_id(struct iommufd_device *idev)
153 {
154         return idev->obj.id;
155 }
156 EXPORT_SYMBOL_NS_GPL(iommufd_device_to_id, IOMMUFD);
157
158 static int iommufd_device_setup_msi(struct iommufd_device *idev,
159                                     struct iommufd_hw_pagetable *hwpt,
160                                     phys_addr_t sw_msi_start)
161 {
162         int rc;
163
164         /*
165          * If the IOMMU driver gives a IOMMU_RESV_SW_MSI then it is asking us to
166          * call iommu_get_msi_cookie() on its behalf. This is necessary to setup
167          * the MSI window so iommu_dma_prepare_msi() can install pages into our
168          * domain after request_irq(). If it is not done interrupts will not
169          * work on this domain.
170          *
171          * FIXME: This is conceptually broken for iommufd since we want to allow
172          * userspace to change the domains, eg switch from an identity IOAS to a
173          * DMA IOAS. There is currently no way to create a MSI window that
174          * matches what the IRQ layer actually expects in a newly created
175          * domain.
176          */
177         if (sw_msi_start != PHYS_ADDR_MAX && !hwpt->msi_cookie) {
178                 rc = iommu_get_msi_cookie(hwpt->domain, sw_msi_start);
179                 if (rc)
180                         return rc;
181
182                 /*
183                  * iommu_get_msi_cookie() can only be called once per domain,
184                  * it returns -EBUSY on later calls.
185                  */
186                 hwpt->msi_cookie = true;
187         }
188
189         /*
190          * For historical compat with VFIO the insecure interrupt path is
191          * allowed if the module parameter is set. Insecure means that a MemWr
192          * operation from the device (eg a simple DMA) cannot trigger an
193          * interrupt outside this iommufd context.
194          */
195         if (!iommufd_selftest_is_mock_dev(idev->dev) &&
196             !iommu_group_has_isolated_msi(idev->group)) {
197                 if (!allow_unsafe_interrupts)
198                         return -EPERM;
199
200                 dev_warn(
201                         idev->dev,
202                         "MSI interrupts are not secure, they cannot be isolated by the platform. "
203                         "Check that platform features like interrupt remapping are enabled. "
204                         "Use the \"allow_unsafe_interrupts\" module parameter to override\n");
205         }
206         return 0;
207 }
208
209 static bool iommufd_hw_pagetable_has_group(struct iommufd_hw_pagetable *hwpt,
210                                            struct iommu_group *group)
211 {
212         struct iommufd_device *cur_dev;
213
214         lockdep_assert_held(&hwpt->devices_lock);
215
216         list_for_each_entry(cur_dev, &hwpt->devices, devices_item)
217                 if (cur_dev->group == group)
218                         return true;
219         return false;
220 }
221
222 int iommufd_hw_pagetable_attach(struct iommufd_hw_pagetable *hwpt,
223                                 struct iommufd_device *idev)
224 {
225         phys_addr_t sw_msi_start = PHYS_ADDR_MAX;
226         int rc;
227
228         lockdep_assert_held(&hwpt->devices_lock);
229
230         if (WARN_ON(idev->hwpt))
231                 return -EINVAL;
232
233         /*
234          * Try to upgrade the domain we have, it is an iommu driver bug to
235          * report IOMMU_CAP_ENFORCE_CACHE_COHERENCY but fail
236          * enforce_cache_coherency when there are no devices attached to the
237          * domain.
238          */
239         if (idev->enforce_cache_coherency && !hwpt->enforce_cache_coherency) {
240                 if (hwpt->domain->ops->enforce_cache_coherency)
241                         hwpt->enforce_cache_coherency =
242                                 hwpt->domain->ops->enforce_cache_coherency(
243                                         hwpt->domain);
244                 if (!hwpt->enforce_cache_coherency) {
245                         WARN_ON(list_empty(&hwpt->devices));
246                         return -EINVAL;
247                 }
248         }
249
250         rc = iopt_table_enforce_group_resv_regions(&hwpt->ioas->iopt, idev->dev,
251                                                    idev->group, &sw_msi_start);
252         if (rc)
253                 return rc;
254
255         rc = iommufd_device_setup_msi(idev, hwpt, sw_msi_start);
256         if (rc)
257                 goto err_unresv;
258
259         /*
260          * FIXME: Hack around missing a device-centric iommu api, only attach to
261          * the group once for the first device that is in the group.
262          */
263         if (!iommufd_hw_pagetable_has_group(hwpt, idev->group)) {
264                 rc = iommu_attach_group(hwpt->domain, idev->group);
265                 if (rc)
266                         goto err_unresv;
267         }
268         return 0;
269 err_unresv:
270         iopt_remove_reserved_iova(&hwpt->ioas->iopt, idev->dev);
271         return rc;
272 }
273
274 void iommufd_hw_pagetable_detach(struct iommufd_hw_pagetable *hwpt,
275                                  struct iommufd_device *idev)
276 {
277         if (!iommufd_hw_pagetable_has_group(hwpt, idev->group))
278                 iommu_detach_group(hwpt->domain, idev->group);
279         iopt_remove_reserved_iova(&hwpt->ioas->iopt, idev->dev);
280 }
281
282 static int iommufd_device_do_attach(struct iommufd_device *idev,
283                                     struct iommufd_hw_pagetable *hwpt)
284 {
285         int rc;
286
287         mutex_lock(&hwpt->devices_lock);
288         rc = iommufd_hw_pagetable_attach(hwpt, idev);
289         if (rc)
290                 goto out_unlock;
291
292         idev->hwpt = hwpt;
293         refcount_inc(&hwpt->obj.users);
294         list_add(&idev->devices_item, &hwpt->devices);
295 out_unlock:
296         mutex_unlock(&hwpt->devices_lock);
297         return rc;
298 }
299
300 /*
301  * When automatically managing the domains we search for a compatible domain in
302  * the iopt and if one is found use it, otherwise create a new domain.
303  * Automatic domain selection will never pick a manually created domain.
304  */
305 static int iommufd_device_auto_get_domain(struct iommufd_device *idev,
306                                           struct iommufd_ioas *ioas)
307 {
308         struct iommufd_hw_pagetable *hwpt;
309         int rc;
310
311         /*
312          * There is no differentiation when domains are allocated, so any domain
313          * that is willing to attach to the device is interchangeable with any
314          * other.
315          */
316         mutex_lock(&ioas->mutex);
317         list_for_each_entry(hwpt, &ioas->hwpt_list, hwpt_item) {
318                 if (!hwpt->auto_domain)
319                         continue;
320
321                 if (!iommufd_lock_obj(&hwpt->obj))
322                         continue;
323                 rc = iommufd_device_do_attach(idev, hwpt);
324                 iommufd_put_object(&hwpt->obj);
325
326                 /*
327                  * -EINVAL means the domain is incompatible with the device.
328                  * Other error codes should propagate to userspace as failure.
329                  * Success means the domain is attached.
330                  */
331                 if (rc == -EINVAL)
332                         continue;
333                 goto out_unlock;
334         }
335
336         hwpt = iommufd_hw_pagetable_alloc(idev->ictx, ioas, idev, true);
337         if (IS_ERR(hwpt)) {
338                 rc = PTR_ERR(hwpt);
339                 goto out_unlock;
340         }
341         hwpt->auto_domain = true;
342
343         mutex_unlock(&ioas->mutex);
344         iommufd_object_finalize(idev->ictx, &hwpt->obj);
345         return 0;
346 out_unlock:
347         mutex_unlock(&ioas->mutex);
348         return rc;
349 }
350
351 /**
352  * iommufd_device_attach - Connect a device from an iommu_domain
353  * @idev: device to attach
354  * @pt_id: Input a IOMMUFD_OBJ_IOAS, or IOMMUFD_OBJ_HW_PAGETABLE
355  *         Output the IOMMUFD_OBJ_HW_PAGETABLE ID
356  *
357  * This connects the device to an iommu_domain, either automatically or manually
358  * selected. Once this completes the device could do DMA.
359  *
360  * The caller should return the resulting pt_id back to userspace.
361  * This function is undone by calling iommufd_device_detach().
362  */
363 int iommufd_device_attach(struct iommufd_device *idev, u32 *pt_id)
364 {
365         struct iommufd_object *pt_obj;
366         int rc;
367
368         pt_obj = iommufd_get_object(idev->ictx, *pt_id, IOMMUFD_OBJ_ANY);
369         if (IS_ERR(pt_obj))
370                 return PTR_ERR(pt_obj);
371
372         switch (pt_obj->type) {
373         case IOMMUFD_OBJ_HW_PAGETABLE: {
374                 struct iommufd_hw_pagetable *hwpt =
375                         container_of(pt_obj, struct iommufd_hw_pagetable, obj);
376
377                 rc = iommufd_device_do_attach(idev, hwpt);
378                 if (rc)
379                         goto out_put_pt_obj;
380                 break;
381         }
382         case IOMMUFD_OBJ_IOAS: {
383                 struct iommufd_ioas *ioas =
384                         container_of(pt_obj, struct iommufd_ioas, obj);
385
386                 rc = iommufd_device_auto_get_domain(idev, ioas);
387                 if (rc)
388                         goto out_put_pt_obj;
389                 break;
390         }
391         default:
392                 rc = -EINVAL;
393                 goto out_put_pt_obj;
394         }
395
396         refcount_inc(&idev->obj.users);
397         *pt_id = idev->hwpt->obj.id;
398         rc = 0;
399
400 out_put_pt_obj:
401         iommufd_put_object(pt_obj);
402         return rc;
403 }
404 EXPORT_SYMBOL_NS_GPL(iommufd_device_attach, IOMMUFD);
405
406 /**
407  * iommufd_device_detach - Disconnect a device to an iommu_domain
408  * @idev: device to detach
409  *
410  * Undo iommufd_device_attach(). This disconnects the idev from the previously
411  * attached pt_id. The device returns back to a blocked DMA translation.
412  */
413 void iommufd_device_detach(struct iommufd_device *idev)
414 {
415         struct iommufd_hw_pagetable *hwpt = idev->hwpt;
416
417         mutex_lock(&hwpt->devices_lock);
418         list_del(&idev->devices_item);
419         idev->hwpt = NULL;
420         iommufd_hw_pagetable_detach(hwpt, idev);
421         mutex_unlock(&hwpt->devices_lock);
422
423         if (hwpt->auto_domain)
424                 iommufd_object_deref_user(idev->ictx, &hwpt->obj);
425         else
426                 refcount_dec(&hwpt->obj.users);
427
428         refcount_dec(&idev->obj.users);
429 }
430 EXPORT_SYMBOL_NS_GPL(iommufd_device_detach, IOMMUFD);
431
432 void iommufd_access_destroy_object(struct iommufd_object *obj)
433 {
434         struct iommufd_access *access =
435                 container_of(obj, struct iommufd_access, obj);
436
437         if (access->ioas) {
438                 iopt_remove_access(&access->ioas->iopt, access);
439                 refcount_dec(&access->ioas->obj.users);
440                 access->ioas = NULL;
441         }
442         iommufd_ctx_put(access->ictx);
443 }
444
445 /**
446  * iommufd_access_create - Create an iommufd_access
447  * @ictx: iommufd file descriptor
448  * @ops: Driver's ops to associate with the access
449  * @data: Opaque data to pass into ops functions
450  * @id: Output ID number to return to userspace for this access
451  *
452  * An iommufd_access allows a driver to read/write to the IOAS without using
453  * DMA. The underlying CPU memory can be accessed using the
454  * iommufd_access_pin_pages() or iommufd_access_rw() functions.
455  *
456  * The provided ops are required to use iommufd_access_pin_pages().
457  */
458 struct iommufd_access *
459 iommufd_access_create(struct iommufd_ctx *ictx,
460                       const struct iommufd_access_ops *ops, void *data, u32 *id)
461 {
462         struct iommufd_access *access;
463
464         /*
465          * There is no uAPI for the access object, but to keep things symmetric
466          * use the object infrastructure anyhow.
467          */
468         access = iommufd_object_alloc(ictx, access, IOMMUFD_OBJ_ACCESS);
469         if (IS_ERR(access))
470                 return access;
471
472         access->data = data;
473         access->ops = ops;
474
475         if (ops->needs_pin_pages)
476                 access->iova_alignment = PAGE_SIZE;
477         else
478                 access->iova_alignment = 1;
479
480         /* The calling driver is a user until iommufd_access_destroy() */
481         refcount_inc(&access->obj.users);
482         access->ictx = ictx;
483         iommufd_ctx_get(ictx);
484         iommufd_object_finalize(ictx, &access->obj);
485         *id = access->obj.id;
486         mutex_init(&access->ioas_lock);
487         return access;
488 }
489 EXPORT_SYMBOL_NS_GPL(iommufd_access_create, IOMMUFD);
490
491 /**
492  * iommufd_access_destroy - Destroy an iommufd_access
493  * @access: The access to destroy
494  *
495  * The caller must stop using the access before destroying it.
496  */
497 void iommufd_access_destroy(struct iommufd_access *access)
498 {
499         iommufd_object_destroy_user(access->ictx, &access->obj);
500 }
501 EXPORT_SYMBOL_NS_GPL(iommufd_access_destroy, IOMMUFD);
502
503 void iommufd_access_detach(struct iommufd_access *access)
504 {
505         struct iommufd_ioas *cur_ioas = access->ioas;
506
507         mutex_lock(&access->ioas_lock);
508         if (WARN_ON(!access->ioas))
509                 goto out;
510         /*
511          * Set ioas to NULL to block any further iommufd_access_pin_pages().
512          * iommufd_access_unpin_pages() can continue using access->ioas_unpin.
513          */
514         access->ioas = NULL;
515
516         if (access->ops->unmap) {
517                 mutex_unlock(&access->ioas_lock);
518                 access->ops->unmap(access->data, 0, ULONG_MAX);
519                 mutex_lock(&access->ioas_lock);
520         }
521         iopt_remove_access(&cur_ioas->iopt, access);
522         refcount_dec(&cur_ioas->obj.users);
523 out:
524         access->ioas_unpin = NULL;
525         mutex_unlock(&access->ioas_lock);
526 }
527 EXPORT_SYMBOL_NS_GPL(iommufd_access_detach, IOMMUFD);
528
529 int iommufd_access_attach(struct iommufd_access *access, u32 ioas_id)
530 {
531         struct iommufd_ioas *new_ioas;
532         int rc = 0;
533
534         mutex_lock(&access->ioas_lock);
535         if (WARN_ON(access->ioas || access->ioas_unpin)) {
536                 mutex_unlock(&access->ioas_lock);
537                 return -EINVAL;
538         }
539
540         new_ioas = iommufd_get_ioas(access->ictx, ioas_id);
541         if (IS_ERR(new_ioas)) {
542                 mutex_unlock(&access->ioas_lock);
543                 return PTR_ERR(new_ioas);
544         }
545
546         rc = iopt_add_access(&new_ioas->iopt, access);
547         if (rc) {
548                 mutex_unlock(&access->ioas_lock);
549                 iommufd_put_object(&new_ioas->obj);
550                 return rc;
551         }
552         iommufd_ref_to_users(&new_ioas->obj);
553
554         access->ioas = new_ioas;
555         access->ioas_unpin = new_ioas;
556         mutex_unlock(&access->ioas_lock);
557         return 0;
558 }
559 EXPORT_SYMBOL_NS_GPL(iommufd_access_attach, IOMMUFD);
560
561 /**
562  * iommufd_access_notify_unmap - Notify users of an iopt to stop using it
563  * @iopt: iopt to work on
564  * @iova: Starting iova in the iopt
565  * @length: Number of bytes
566  *
567  * After this function returns there should be no users attached to the pages
568  * linked to this iopt that intersect with iova,length. Anyone that has attached
569  * a user through iopt_access_pages() needs to detach it through
570  * iommufd_access_unpin_pages() before this function returns.
571  *
572  * iommufd_access_destroy() will wait for any outstanding unmap callback to
573  * complete. Once iommufd_access_destroy() no unmap ops are running or will
574  * run in the future. Due to this a driver must not create locking that prevents
575  * unmap to complete while iommufd_access_destroy() is running.
576  */
577 void iommufd_access_notify_unmap(struct io_pagetable *iopt, unsigned long iova,
578                                  unsigned long length)
579 {
580         struct iommufd_ioas *ioas =
581                 container_of(iopt, struct iommufd_ioas, iopt);
582         struct iommufd_access *access;
583         unsigned long index;
584
585         xa_lock(&ioas->iopt.access_list);
586         xa_for_each(&ioas->iopt.access_list, index, access) {
587                 if (!iommufd_lock_obj(&access->obj))
588                         continue;
589                 xa_unlock(&ioas->iopt.access_list);
590
591                 access->ops->unmap(access->data, iova, length);
592
593                 iommufd_put_object(&access->obj);
594                 xa_lock(&ioas->iopt.access_list);
595         }
596         xa_unlock(&ioas->iopt.access_list);
597 }
598
599 /**
600  * iommufd_access_unpin_pages() - Undo iommufd_access_pin_pages
601  * @access: IOAS access to act on
602  * @iova: Starting IOVA
603  * @length: Number of bytes to access
604  *
605  * Return the struct page's. The caller must stop accessing them before calling
606  * this. The iova/length must exactly match the one provided to access_pages.
607  */
608 void iommufd_access_unpin_pages(struct iommufd_access *access,
609                                 unsigned long iova, unsigned long length)
610 {
611         struct iopt_area_contig_iter iter;
612         struct io_pagetable *iopt;
613         unsigned long last_iova;
614         struct iopt_area *area;
615
616         if (WARN_ON(!length) ||
617             WARN_ON(check_add_overflow(iova, length - 1, &last_iova)))
618                 return;
619
620         mutex_lock(&access->ioas_lock);
621         /*
622          * The driver must be doing something wrong if it calls this before an
623          * iommufd_access_attach() or after an iommufd_access_detach().
624          */
625         if (WARN_ON(!access->ioas_unpin)) {
626                 mutex_unlock(&access->ioas_lock);
627                 return;
628         }
629         iopt = &access->ioas_unpin->iopt;
630
631         down_read(&iopt->iova_rwsem);
632         iopt_for_each_contig_area(&iter, area, iopt, iova, last_iova)
633                 iopt_area_remove_access(
634                         area, iopt_area_iova_to_index(area, iter.cur_iova),
635                         iopt_area_iova_to_index(
636                                 area,
637                                 min(last_iova, iopt_area_last_iova(area))));
638         WARN_ON(!iopt_area_contig_done(&iter));
639         up_read(&iopt->iova_rwsem);
640         mutex_unlock(&access->ioas_lock);
641 }
642 EXPORT_SYMBOL_NS_GPL(iommufd_access_unpin_pages, IOMMUFD);
643
644 static bool iopt_area_contig_is_aligned(struct iopt_area_contig_iter *iter)
645 {
646         if (iopt_area_start_byte(iter->area, iter->cur_iova) % PAGE_SIZE)
647                 return false;
648
649         if (!iopt_area_contig_done(iter) &&
650             (iopt_area_start_byte(iter->area, iopt_area_last_iova(iter->area)) %
651              PAGE_SIZE) != (PAGE_SIZE - 1))
652                 return false;
653         return true;
654 }
655
656 static bool check_area_prot(struct iopt_area *area, unsigned int flags)
657 {
658         if (flags & IOMMUFD_ACCESS_RW_WRITE)
659                 return area->iommu_prot & IOMMU_WRITE;
660         return area->iommu_prot & IOMMU_READ;
661 }
662
663 /**
664  * iommufd_access_pin_pages() - Return a list of pages under the iova
665  * @access: IOAS access to act on
666  * @iova: Starting IOVA
667  * @length: Number of bytes to access
668  * @out_pages: Output page list
669  * @flags: IOPMMUFD_ACCESS_RW_* flags
670  *
671  * Reads @length bytes starting at iova and returns the struct page * pointers.
672  * These can be kmap'd by the caller for CPU access.
673  *
674  * The caller must perform iommufd_access_unpin_pages() when done to balance
675  * this.
676  *
677  * This API always requires a page aligned iova. This happens naturally if the
678  * ioas alignment is >= PAGE_SIZE and the iova is PAGE_SIZE aligned. However
679  * smaller alignments have corner cases where this API can fail on otherwise
680  * aligned iova.
681  */
682 int iommufd_access_pin_pages(struct iommufd_access *access, unsigned long iova,
683                              unsigned long length, struct page **out_pages,
684                              unsigned int flags)
685 {
686         struct iopt_area_contig_iter iter;
687         struct io_pagetable *iopt;
688         unsigned long last_iova;
689         struct iopt_area *area;
690         int rc;
691
692         /* Driver's ops don't support pin_pages */
693         if (IS_ENABLED(CONFIG_IOMMUFD_TEST) &&
694             WARN_ON(access->iova_alignment != PAGE_SIZE || !access->ops->unmap))
695                 return -EINVAL;
696
697         if (!length)
698                 return -EINVAL;
699         if (check_add_overflow(iova, length - 1, &last_iova))
700                 return -EOVERFLOW;
701
702         mutex_lock(&access->ioas_lock);
703         if (!access->ioas) {
704                 mutex_unlock(&access->ioas_lock);
705                 return -ENOENT;
706         }
707         iopt = &access->ioas->iopt;
708
709         down_read(&iopt->iova_rwsem);
710         iopt_for_each_contig_area(&iter, area, iopt, iova, last_iova) {
711                 unsigned long last = min(last_iova, iopt_area_last_iova(area));
712                 unsigned long last_index = iopt_area_iova_to_index(area, last);
713                 unsigned long index =
714                         iopt_area_iova_to_index(area, iter.cur_iova);
715
716                 if (area->prevent_access ||
717                     !iopt_area_contig_is_aligned(&iter)) {
718                         rc = -EINVAL;
719                         goto err_remove;
720                 }
721
722                 if (!check_area_prot(area, flags)) {
723                         rc = -EPERM;
724                         goto err_remove;
725                 }
726
727                 rc = iopt_area_add_access(area, index, last_index, out_pages,
728                                           flags);
729                 if (rc)
730                         goto err_remove;
731                 out_pages += last_index - index + 1;
732         }
733         if (!iopt_area_contig_done(&iter)) {
734                 rc = -ENOENT;
735                 goto err_remove;
736         }
737
738         up_read(&iopt->iova_rwsem);
739         mutex_unlock(&access->ioas_lock);
740         return 0;
741
742 err_remove:
743         if (iova < iter.cur_iova) {
744                 last_iova = iter.cur_iova - 1;
745                 iopt_for_each_contig_area(&iter, area, iopt, iova, last_iova)
746                         iopt_area_remove_access(
747                                 area,
748                                 iopt_area_iova_to_index(area, iter.cur_iova),
749                                 iopt_area_iova_to_index(
750                                         area, min(last_iova,
751                                                   iopt_area_last_iova(area))));
752         }
753         up_read(&iopt->iova_rwsem);
754         mutex_unlock(&access->ioas_lock);
755         return rc;
756 }
757 EXPORT_SYMBOL_NS_GPL(iommufd_access_pin_pages, IOMMUFD);
758
759 /**
760  * iommufd_access_rw - Read or write data under the iova
761  * @access: IOAS access to act on
762  * @iova: Starting IOVA
763  * @data: Kernel buffer to copy to/from
764  * @length: Number of bytes to access
765  * @flags: IOMMUFD_ACCESS_RW_* flags
766  *
767  * Copy kernel to/from data into the range given by IOVA/length. If flags
768  * indicates IOMMUFD_ACCESS_RW_KTHREAD then a large copy can be optimized
769  * by changing it into copy_to/from_user().
770  */
771 int iommufd_access_rw(struct iommufd_access *access, unsigned long iova,
772                       void *data, size_t length, unsigned int flags)
773 {
774         struct iopt_area_contig_iter iter;
775         struct io_pagetable *iopt;
776         struct iopt_area *area;
777         unsigned long last_iova;
778         int rc;
779
780         if (!length)
781                 return -EINVAL;
782         if (check_add_overflow(iova, length - 1, &last_iova))
783                 return -EOVERFLOW;
784
785         mutex_lock(&access->ioas_lock);
786         if (!access->ioas) {
787                 mutex_unlock(&access->ioas_lock);
788                 return -ENOENT;
789         }
790         iopt = &access->ioas->iopt;
791
792         down_read(&iopt->iova_rwsem);
793         iopt_for_each_contig_area(&iter, area, iopt, iova, last_iova) {
794                 unsigned long last = min(last_iova, iopt_area_last_iova(area));
795                 unsigned long bytes = (last - iter.cur_iova) + 1;
796
797                 if (area->prevent_access) {
798                         rc = -EINVAL;
799                         goto err_out;
800                 }
801
802                 if (!check_area_prot(area, flags)) {
803                         rc = -EPERM;
804                         goto err_out;
805                 }
806
807                 rc = iopt_pages_rw_access(
808                         area->pages, iopt_area_start_byte(area, iter.cur_iova),
809                         data, bytes, flags);
810                 if (rc)
811                         goto err_out;
812                 data += bytes;
813         }
814         if (!iopt_area_contig_done(&iter))
815                 rc = -ENOENT;
816 err_out:
817         up_read(&iopt->iova_rwsem);
818         mutex_unlock(&access->ioas_lock);
819         return rc;
820 }
821 EXPORT_SYMBOL_NS_GPL(iommufd_access_rw, IOMMUFD);