xref: /linux/drivers/iommu/iommufd/selftest.c (revision fbf5df34a4dbcd09d433dd4f0916bf9b2ddb16de)
1 // SPDX-License-Identifier: GPL-2.0
2 /* Copyright (c) 2021-2022, NVIDIA CORPORATION & AFFILIATES.
3  *
4  * Kernel side components to support tools/testing/selftests/iommu
5  */
6 #include <linux/anon_inodes.h>
7 #include <linux/debugfs.h>
8 #include <linux/dma-buf.h>
9 #include <linux/dma-resv.h>
10 #include <linux/fault-inject.h>
11 #include <linux/file.h>
12 #include <linux/iommu.h>
13 #include <linux/platform_device.h>
14 #include <linux/slab.h>
15 #include <linux/xarray.h>
16 #include <uapi/linux/iommufd.h>
17 #include <linux/generic_pt/iommu.h>
18 #include "../iommu-pages.h"
19 
20 #include "../iommu-priv.h"
21 #include "io_pagetable.h"
22 #include "iommufd_private.h"
23 #include "iommufd_test.h"
24 
25 static DECLARE_FAULT_ATTR(fail_iommufd);
26 static struct dentry *dbgfs_root;
27 static struct platform_device *selftest_iommu_dev;
28 static const struct iommu_ops mock_ops;
29 static struct iommu_domain_ops domain_nested_ops;
30 
31 size_t iommufd_test_memory_limit = 65536;
32 
33 struct mock_bus_type {
34 	struct bus_type bus;
35 	struct notifier_block nb;
36 };
37 
38 static struct mock_bus_type iommufd_mock_bus_type = {
39 	.bus = {
40 		.name = "iommufd_mock",
41 	},
42 };
43 
44 static DEFINE_IDA(mock_dev_ida);
45 
46 enum {
47 	MOCK_DIRTY_TRACK = 1,
48 };
49 
50 static int mock_dev_enable_iopf(struct device *dev, struct iommu_domain *domain);
51 static void mock_dev_disable_iopf(struct device *dev, struct iommu_domain *domain);
52 
53 /*
54  * Syzkaller has trouble randomizing the correct iova to use since it is linked
55  * to the map ioctl's output, and it has no ide about that. So, simplify things.
56  * In syzkaller mode the 64 bit IOVA is converted into an nth area and offset
57  * value. This has a much smaller randomization space and syzkaller can hit it.
58  */
59 static unsigned long __iommufd_test_syz_conv_iova(struct io_pagetable *iopt,
60 						  u64 *iova)
61 {
62 	struct syz_layout {
63 		__u32 nth_area;
64 		__u32 offset;
65 	};
66 	struct syz_layout *syz = (void *)iova;
67 	unsigned int nth = syz->nth_area;
68 	struct iopt_area *area;
69 
70 	down_read(&iopt->iova_rwsem);
71 	for (area = iopt_area_iter_first(iopt, 0, ULONG_MAX); area;
72 	     area = iopt_area_iter_next(area, 0, ULONG_MAX)) {
73 		if (nth == 0) {
74 			up_read(&iopt->iova_rwsem);
75 			return iopt_area_iova(area) + syz->offset;
76 		}
77 		nth--;
78 	}
79 	up_read(&iopt->iova_rwsem);
80 
81 	return 0;
82 }
83 
84 static unsigned long iommufd_test_syz_conv_iova(struct iommufd_access *access,
85 						u64 *iova)
86 {
87 	unsigned long ret;
88 
89 	mutex_lock(&access->ioas_lock);
90 	if (!access->ioas) {
91 		mutex_unlock(&access->ioas_lock);
92 		return 0;
93 	}
94 	ret = __iommufd_test_syz_conv_iova(&access->ioas->iopt, iova);
95 	mutex_unlock(&access->ioas_lock);
96 	return ret;
97 }
98 
99 void iommufd_test_syz_conv_iova_id(struct iommufd_ucmd *ucmd,
100 				   unsigned int ioas_id, u64 *iova, u32 *flags)
101 {
102 	struct iommufd_ioas *ioas;
103 
104 	if (!(*flags & MOCK_FLAGS_ACCESS_SYZ))
105 		return;
106 	*flags &= ~(u32)MOCK_FLAGS_ACCESS_SYZ;
107 
108 	ioas = iommufd_get_ioas(ucmd->ictx, ioas_id);
109 	if (IS_ERR(ioas))
110 		return;
111 	*iova = __iommufd_test_syz_conv_iova(&ioas->iopt, iova);
112 	iommufd_put_object(ucmd->ictx, &ioas->obj);
113 }
114 
115 struct mock_iommu_domain {
116 	union {
117 		struct iommu_domain domain;
118 		struct pt_iommu iommu;
119 		struct pt_iommu_amdv1 amdv1;
120 	};
121 	unsigned long flags;
122 };
123 PT_IOMMU_CHECK_DOMAIN(struct mock_iommu_domain, iommu, domain);
124 PT_IOMMU_CHECK_DOMAIN(struct mock_iommu_domain, amdv1.iommu, domain);
125 
126 static inline struct mock_iommu_domain *
127 to_mock_domain(struct iommu_domain *domain)
128 {
129 	return container_of(domain, struct mock_iommu_domain, domain);
130 }
131 
132 struct mock_iommu_domain_nested {
133 	struct iommu_domain domain;
134 	struct mock_viommu *mock_viommu;
135 	u32 iotlb[MOCK_NESTED_DOMAIN_IOTLB_NUM];
136 };
137 
138 static inline struct mock_iommu_domain_nested *
139 to_mock_nested(struct iommu_domain *domain)
140 {
141 	return container_of(domain, struct mock_iommu_domain_nested, domain);
142 }
143 
144 struct mock_viommu {
145 	struct iommufd_viommu core;
146 	struct mock_iommu_domain *s2_parent;
147 	struct mock_hw_queue *hw_queue[IOMMU_TEST_HW_QUEUE_MAX];
148 	struct mutex queue_mutex;
149 
150 	unsigned long mmap_offset;
151 	u32 *page; /* Mmap page to test u32 type of in_data */
152 };
153 
154 static inline struct mock_viommu *to_mock_viommu(struct iommufd_viommu *viommu)
155 {
156 	return container_of(viommu, struct mock_viommu, core);
157 }
158 
159 struct mock_hw_queue {
160 	struct iommufd_hw_queue core;
161 	struct mock_viommu *mock_viommu;
162 	struct mock_hw_queue *prev;
163 	u16 index;
164 };
165 
166 static inline struct mock_hw_queue *
167 to_mock_hw_queue(struct iommufd_hw_queue *hw_queue)
168 {
169 	return container_of(hw_queue, struct mock_hw_queue, core);
170 }
171 
172 enum selftest_obj_type {
173 	TYPE_IDEV,
174 };
175 
176 struct mock_dev {
177 	struct device dev;
178 	struct mock_viommu *viommu;
179 	struct rw_semaphore viommu_rwsem;
180 	unsigned long flags;
181 	unsigned long vdev_id;
182 	int id;
183 	u32 cache[MOCK_DEV_CACHE_NUM];
184 	atomic_t pasid_1024_fake_error;
185 	unsigned int iopf_refcount;
186 	struct iommu_domain *domain;
187 };
188 
189 static inline struct mock_dev *to_mock_dev(struct device *dev)
190 {
191 	return container_of(dev, struct mock_dev, dev);
192 }
193 
194 struct selftest_obj {
195 	struct iommufd_object obj;
196 	enum selftest_obj_type type;
197 
198 	union {
199 		struct {
200 			struct iommufd_device *idev;
201 			struct iommufd_ctx *ictx;
202 			struct mock_dev *mock_dev;
203 		} idev;
204 	};
205 };
206 
207 static inline struct selftest_obj *to_selftest_obj(struct iommufd_object *obj)
208 {
209 	return container_of(obj, struct selftest_obj, obj);
210 }
211 
212 static int mock_domain_nop_attach(struct iommu_domain *domain,
213 				  struct device *dev, struct iommu_domain *old)
214 {
215 	struct mock_dev *mdev = to_mock_dev(dev);
216 	struct mock_viommu *new_viommu = NULL;
217 	unsigned long vdev_id = 0;
218 	int rc;
219 
220 	if (domain->dirty_ops && (mdev->flags & MOCK_FLAGS_DEVICE_NO_DIRTY))
221 		return -EINVAL;
222 
223 	iommu_group_mutex_assert(dev);
224 	if (domain->type == IOMMU_DOMAIN_NESTED) {
225 		new_viommu = to_mock_nested(domain)->mock_viommu;
226 		if (new_viommu) {
227 			rc = iommufd_viommu_get_vdev_id(&new_viommu->core, dev,
228 							&vdev_id);
229 			if (rc)
230 				return rc;
231 		}
232 	}
233 	if (new_viommu != mdev->viommu) {
234 		down_write(&mdev->viommu_rwsem);
235 		mdev->viommu = new_viommu;
236 		mdev->vdev_id = vdev_id;
237 		up_write(&mdev->viommu_rwsem);
238 	}
239 
240 	rc = mock_dev_enable_iopf(dev, domain);
241 	if (rc)
242 		return rc;
243 
244 	mock_dev_disable_iopf(dev, mdev->domain);
245 	mdev->domain = domain;
246 
247 	return 0;
248 }
249 
250 static int mock_domain_set_dev_pasid_nop(struct iommu_domain *domain,
251 					 struct device *dev, ioasid_t pasid,
252 					 struct iommu_domain *old)
253 {
254 	struct mock_dev *mdev = to_mock_dev(dev);
255 	int rc;
256 
257 	/*
258 	 * Per the first attach with pasid 1024, set the
259 	 * mdev->pasid_1024_fake_error. Hence the second call of this op
260 	 * can fake an error to validate the error path of the core. This
261 	 * is helpful to test the case in which the iommu core needs to
262 	 * rollback to the old domain due to driver failure. e.g. replace.
263 	 * User should be careful about the third call of this op, it shall
264 	 * succeed since the mdev->pasid_1024_fake_error is cleared in the
265 	 * second call.
266 	 */
267 	if (pasid == 1024) {
268 		if (domain->type == IOMMU_DOMAIN_BLOCKED) {
269 			atomic_set(&mdev->pasid_1024_fake_error, 0);
270 		} else if (atomic_read(&mdev->pasid_1024_fake_error)) {
271 			/*
272 			 * Clear the flag, and fake an error to fail the
273 			 * replacement.
274 			 */
275 			atomic_set(&mdev->pasid_1024_fake_error, 0);
276 			return -ENOMEM;
277 		} else {
278 			/* Set the flag to fake an error in next call */
279 			atomic_set(&mdev->pasid_1024_fake_error, 1);
280 		}
281 	}
282 
283 	rc = mock_dev_enable_iopf(dev, domain);
284 	if (rc)
285 		return rc;
286 
287 	mock_dev_disable_iopf(dev, old);
288 
289 	return 0;
290 }
291 
292 static const struct iommu_domain_ops mock_blocking_ops = {
293 	.attach_dev = mock_domain_nop_attach,
294 	.set_dev_pasid = mock_domain_set_dev_pasid_nop
295 };
296 
297 static struct iommu_domain mock_blocking_domain = {
298 	.type = IOMMU_DOMAIN_BLOCKED,
299 	.ops = &mock_blocking_ops,
300 };
301 
302 static void *mock_domain_hw_info(struct device *dev, u32 *length,
303 				 enum iommu_hw_info_type *type)
304 {
305 	struct iommu_test_hw_info *info;
306 
307 	if (*type != IOMMU_HW_INFO_TYPE_DEFAULT &&
308 	    *type != IOMMU_HW_INFO_TYPE_SELFTEST)
309 		return ERR_PTR(-EOPNOTSUPP);
310 
311 	info = kzalloc_obj(*info);
312 	if (!info)
313 		return ERR_PTR(-ENOMEM);
314 
315 	info->test_reg = IOMMU_HW_INFO_SELFTEST_REGVAL;
316 	*length = sizeof(*info);
317 	*type = IOMMU_HW_INFO_TYPE_SELFTEST;
318 
319 	return info;
320 }
321 
322 static int mock_domain_set_dirty_tracking(struct iommu_domain *domain,
323 					  bool enable)
324 {
325 	struct mock_iommu_domain *mock = to_mock_domain(domain);
326 	unsigned long flags = mock->flags;
327 
328 	if (enable && !domain->dirty_ops)
329 		return -EINVAL;
330 
331 	/* No change? */
332 	if (!(enable ^ !!(flags & MOCK_DIRTY_TRACK)))
333 		return 0;
334 
335 	flags = (enable ? flags | MOCK_DIRTY_TRACK : flags & ~MOCK_DIRTY_TRACK);
336 
337 	mock->flags = flags;
338 	return 0;
339 }
340 
341 static struct mock_iommu_domain_nested *
342 __mock_domain_alloc_nested(const struct iommu_user_data *user_data)
343 {
344 	struct mock_iommu_domain_nested *mock_nested;
345 	struct iommu_hwpt_selftest user_cfg;
346 	int rc, i;
347 
348 	if (user_data->type != IOMMU_HWPT_DATA_SELFTEST)
349 		return ERR_PTR(-EOPNOTSUPP);
350 
351 	rc = iommu_copy_struct_from_user(&user_cfg, user_data,
352 					 IOMMU_HWPT_DATA_SELFTEST, iotlb);
353 	if (rc)
354 		return ERR_PTR(rc);
355 
356 	mock_nested = kzalloc_obj(*mock_nested);
357 	if (!mock_nested)
358 		return ERR_PTR(-ENOMEM);
359 	mock_nested->domain.ops = &domain_nested_ops;
360 	mock_nested->domain.type = IOMMU_DOMAIN_NESTED;
361 	for (i = 0; i < MOCK_NESTED_DOMAIN_IOTLB_NUM; i++)
362 		mock_nested->iotlb[i] = user_cfg.iotlb;
363 	return mock_nested;
364 }
365 
366 static struct iommu_domain *
367 mock_domain_alloc_nested(struct device *dev, struct iommu_domain *parent,
368 			 u32 flags, const struct iommu_user_data *user_data)
369 {
370 	struct mock_iommu_domain_nested *mock_nested;
371 	struct mock_iommu_domain *mock_parent;
372 
373 	if (flags & ~IOMMU_HWPT_ALLOC_PASID)
374 		return ERR_PTR(-EOPNOTSUPP);
375 	if (!parent || !(parent->type & __IOMMU_DOMAIN_PAGING))
376 		return ERR_PTR(-EINVAL);
377 
378 	mock_parent = to_mock_domain(parent);
379 	if (!mock_parent)
380 		return ERR_PTR(-EINVAL);
381 
382 	mock_nested = __mock_domain_alloc_nested(user_data);
383 	if (IS_ERR(mock_nested))
384 		return ERR_CAST(mock_nested);
385 	return &mock_nested->domain;
386 }
387 
388 static void mock_domain_free(struct iommu_domain *domain)
389 {
390 	struct mock_iommu_domain *mock = to_mock_domain(domain);
391 
392 	pt_iommu_deinit(&mock->iommu);
393 	kfree(mock);
394 }
395 
396 static void mock_iotlb_sync(struct iommu_domain *domain,
397 				struct iommu_iotlb_gather *gather)
398 {
399 	iommu_put_pages_list(&gather->freelist);
400 }
401 
402 static const struct iommu_domain_ops amdv1_mock_ops = {
403 	IOMMU_PT_DOMAIN_OPS(amdv1_mock),
404 	.free = mock_domain_free,
405 	.attach_dev = mock_domain_nop_attach,
406 	.set_dev_pasid = mock_domain_set_dev_pasid_nop,
407 	.iotlb_sync = &mock_iotlb_sync,
408 };
409 
410 static const struct iommu_domain_ops amdv1_mock_huge_ops = {
411 	IOMMU_PT_DOMAIN_OPS(amdv1_mock),
412 	.free = mock_domain_free,
413 	.attach_dev = mock_domain_nop_attach,
414 	.set_dev_pasid = mock_domain_set_dev_pasid_nop,
415 	.iotlb_sync = &mock_iotlb_sync,
416 };
417 #undef pt_iommu_amdv1_mock_map_pages
418 
419 static const struct iommu_dirty_ops amdv1_mock_dirty_ops = {
420 	IOMMU_PT_DIRTY_OPS(amdv1_mock),
421 	.set_dirty_tracking = mock_domain_set_dirty_tracking,
422 };
423 
424 static struct mock_iommu_domain *
425 mock_domain_alloc_pgtable(struct device *dev,
426 			  const struct iommu_hwpt_selftest *user_cfg, u32 flags)
427 {
428 	struct mock_iommu_domain *mock;
429 	int rc;
430 
431 	mock = kzalloc_obj(*mock);
432 	if (!mock)
433 		return ERR_PTR(-ENOMEM);
434 	mock->domain.type = IOMMU_DOMAIN_UNMANAGED;
435 
436 	mock->amdv1.iommu.nid = NUMA_NO_NODE;
437 
438 	switch (user_cfg->pagetable_type) {
439 	case MOCK_IOMMUPT_DEFAULT:
440 	case MOCK_IOMMUPT_HUGE: {
441 		struct pt_iommu_amdv1_cfg cfg = {};
442 
443 		/* The mock version has a 2k page size */
444 		cfg.common.hw_max_vasz_lg2 = 56;
445 		cfg.common.hw_max_oasz_lg2 = 51;
446 		cfg.starting_level = 2;
447 		if (user_cfg->pagetable_type == MOCK_IOMMUPT_HUGE)
448 			mock->domain.ops = &amdv1_mock_huge_ops;
449 		else
450 			mock->domain.ops = &amdv1_mock_ops;
451 		rc = pt_iommu_amdv1_mock_init(&mock->amdv1, &cfg, GFP_KERNEL);
452 		if (rc)
453 			goto err_free;
454 
455 		/*
456 		 * In huge mode userspace should only provide huge pages, we
457 		 * have to include PAGE_SIZE for the domain to be accepted by
458 		 * iommufd.
459 		 */
460 		if (user_cfg->pagetable_type == MOCK_IOMMUPT_HUGE)
461 			mock->domain.pgsize_bitmap = MOCK_HUGE_PAGE_SIZE |
462 						     PAGE_SIZE;
463 		if (flags & IOMMU_HWPT_ALLOC_DIRTY_TRACKING)
464 			mock->domain.dirty_ops = &amdv1_mock_dirty_ops;
465 		break;
466 	}
467 	default:
468 		rc = -EOPNOTSUPP;
469 		goto err_free;
470 	}
471 
472 	/*
473 	 * Override the real aperture to the MOCK aperture for test purposes.
474 	 */
475 	if (user_cfg->pagetable_type == MOCK_IOMMUPT_DEFAULT) {
476 		WARN_ON(mock->domain.geometry.aperture_start != 0);
477 		WARN_ON(mock->domain.geometry.aperture_end < MOCK_APERTURE_LAST);
478 
479 		mock->domain.geometry.aperture_start = MOCK_APERTURE_START;
480 		mock->domain.geometry.aperture_end = MOCK_APERTURE_LAST;
481 	}
482 
483 	return mock;
484 err_free:
485 	kfree(mock);
486 	return ERR_PTR(rc);
487 }
488 
489 static struct iommu_domain *
490 mock_domain_alloc_paging_flags(struct device *dev, u32 flags,
491 			       const struct iommu_user_data *user_data)
492 {
493 	bool has_dirty_flag = flags & IOMMU_HWPT_ALLOC_DIRTY_TRACKING;
494 	const u32 PAGING_FLAGS = IOMMU_HWPT_ALLOC_DIRTY_TRACKING |
495 				 IOMMU_HWPT_ALLOC_NEST_PARENT |
496 				 IOMMU_HWPT_ALLOC_PASID;
497 	struct mock_dev *mdev = to_mock_dev(dev);
498 	bool no_dirty_ops = mdev->flags & MOCK_FLAGS_DEVICE_NO_DIRTY;
499 	struct iommu_hwpt_selftest user_cfg = {};
500 	struct mock_iommu_domain *mock;
501 	int rc;
502 
503 	if ((flags & ~PAGING_FLAGS) || (has_dirty_flag && no_dirty_ops))
504 		return ERR_PTR(-EOPNOTSUPP);
505 
506 	if (user_data && (user_data->type != IOMMU_HWPT_DATA_SELFTEST &&
507 			  user_data->type != IOMMU_HWPT_DATA_NONE))
508 		return ERR_PTR(-EOPNOTSUPP);
509 
510 	if (user_data) {
511 		rc = iommu_copy_struct_from_user(
512 			&user_cfg, user_data, IOMMU_HWPT_DATA_SELFTEST, iotlb);
513 		if (rc)
514 			return ERR_PTR(rc);
515 	}
516 
517 	mock = mock_domain_alloc_pgtable(dev, &user_cfg, flags);
518 	if (IS_ERR(mock))
519 		return ERR_CAST(mock);
520 	return &mock->domain;
521 }
522 
523 static bool mock_domain_capable(struct device *dev, enum iommu_cap cap)
524 {
525 	struct mock_dev *mdev = to_mock_dev(dev);
526 
527 	switch (cap) {
528 	case IOMMU_CAP_CACHE_COHERENCY:
529 		return true;
530 	case IOMMU_CAP_DIRTY_TRACKING:
531 		return !(mdev->flags & MOCK_FLAGS_DEVICE_NO_DIRTY);
532 	default:
533 		break;
534 	}
535 
536 	return false;
537 }
538 
539 static struct iopf_queue *mock_iommu_iopf_queue;
540 
541 static struct mock_iommu_device {
542 	struct iommu_device iommu_dev;
543 	struct completion complete;
544 	refcount_t users;
545 } mock_iommu;
546 
547 static struct iommu_device *mock_probe_device(struct device *dev)
548 {
549 	if (dev->bus != &iommufd_mock_bus_type.bus)
550 		return ERR_PTR(-ENODEV);
551 	return &mock_iommu.iommu_dev;
552 }
553 
554 static void mock_domain_page_response(struct device *dev, struct iopf_fault *evt,
555 				      struct iommu_page_response *msg)
556 {
557 }
558 
559 static int mock_dev_enable_iopf(struct device *dev, struct iommu_domain *domain)
560 {
561 	struct mock_dev *mdev = to_mock_dev(dev);
562 	int ret;
563 
564 	if (!domain || !domain->iopf_handler)
565 		return 0;
566 
567 	if (!mock_iommu_iopf_queue)
568 		return -ENODEV;
569 
570 	if (mdev->iopf_refcount) {
571 		mdev->iopf_refcount++;
572 		return 0;
573 	}
574 
575 	ret = iopf_queue_add_device(mock_iommu_iopf_queue, dev);
576 	if (ret)
577 		return ret;
578 
579 	mdev->iopf_refcount = 1;
580 
581 	return 0;
582 }
583 
584 static void mock_dev_disable_iopf(struct device *dev, struct iommu_domain *domain)
585 {
586 	struct mock_dev *mdev = to_mock_dev(dev);
587 
588 	if (!domain || !domain->iopf_handler)
589 		return;
590 
591 	if (--mdev->iopf_refcount)
592 		return;
593 
594 	iopf_queue_remove_device(mock_iommu_iopf_queue, dev);
595 }
596 
597 static void mock_viommu_destroy(struct iommufd_viommu *viommu)
598 {
599 	struct mock_iommu_device *mock_iommu = container_of(
600 		viommu->iommu_dev, struct mock_iommu_device, iommu_dev);
601 	struct mock_viommu *mock_viommu = to_mock_viommu(viommu);
602 
603 	if (refcount_dec_and_test(&mock_iommu->users))
604 		complete(&mock_iommu->complete);
605 	if (mock_viommu->mmap_offset)
606 		iommufd_viommu_destroy_mmap(&mock_viommu->core,
607 					    mock_viommu->mmap_offset);
608 	free_pages((unsigned long)mock_viommu->page, 1);
609 	mutex_destroy(&mock_viommu->queue_mutex);
610 
611 	/* iommufd core frees mock_viommu and viommu */
612 }
613 
614 static struct iommu_domain *
615 mock_viommu_alloc_domain_nested(struct iommufd_viommu *viommu, u32 flags,
616 				const struct iommu_user_data *user_data)
617 {
618 	struct mock_viommu *mock_viommu = to_mock_viommu(viommu);
619 	struct mock_iommu_domain_nested *mock_nested;
620 
621 	if (flags & ~IOMMU_HWPT_ALLOC_PASID)
622 		return ERR_PTR(-EOPNOTSUPP);
623 
624 	mock_nested = __mock_domain_alloc_nested(user_data);
625 	if (IS_ERR(mock_nested))
626 		return ERR_CAST(mock_nested);
627 	mock_nested->mock_viommu = mock_viommu;
628 	return &mock_nested->domain;
629 }
630 
631 static int mock_viommu_cache_invalidate(struct iommufd_viommu *viommu,
632 					struct iommu_user_data_array *array)
633 {
634 	struct iommu_viommu_invalidate_selftest *cmds;
635 	struct iommu_viommu_invalidate_selftest *cur;
636 	struct iommu_viommu_invalidate_selftest *end;
637 	int rc;
638 
639 	/* A zero-length array is allowed to validate the array type */
640 	if (array->entry_num == 0 &&
641 	    array->type == IOMMU_VIOMMU_INVALIDATE_DATA_SELFTEST) {
642 		array->entry_num = 0;
643 		return 0;
644 	}
645 
646 	cmds = kzalloc_objs(*cmds, array->entry_num);
647 	if (!cmds)
648 		return -ENOMEM;
649 	cur = cmds;
650 	end = cmds + array->entry_num;
651 
652 	static_assert(sizeof(*cmds) == 3 * sizeof(u32));
653 	rc = iommu_copy_struct_from_full_user_array(
654 		cmds, sizeof(*cmds), array,
655 		IOMMU_VIOMMU_INVALIDATE_DATA_SELFTEST);
656 	if (rc)
657 		goto out;
658 
659 	while (cur != end) {
660 		struct mock_dev *mdev;
661 		struct device *dev;
662 		int i;
663 
664 		if (cur->flags & ~IOMMU_TEST_INVALIDATE_FLAG_ALL) {
665 			rc = -EOPNOTSUPP;
666 			goto out;
667 		}
668 
669 		if (cur->cache_id > MOCK_DEV_CACHE_ID_MAX) {
670 			rc = -EINVAL;
671 			goto out;
672 		}
673 
674 		xa_lock(&viommu->vdevs);
675 		dev = iommufd_viommu_find_dev(viommu,
676 					      (unsigned long)cur->vdev_id);
677 		if (!dev) {
678 			xa_unlock(&viommu->vdevs);
679 			rc = -EINVAL;
680 			goto out;
681 		}
682 		mdev = container_of(dev, struct mock_dev, dev);
683 
684 		if (cur->flags & IOMMU_TEST_INVALIDATE_FLAG_ALL) {
685 			/* Invalidate all cache entries and ignore cache_id */
686 			for (i = 0; i < MOCK_DEV_CACHE_NUM; i++)
687 				mdev->cache[i] = 0;
688 		} else {
689 			mdev->cache[cur->cache_id] = 0;
690 		}
691 		xa_unlock(&viommu->vdevs);
692 
693 		cur++;
694 	}
695 out:
696 	array->entry_num = cur - cmds;
697 	kfree(cmds);
698 	return rc;
699 }
700 
701 static size_t mock_viommu_get_hw_queue_size(struct iommufd_viommu *viommu,
702 					    enum iommu_hw_queue_type queue_type)
703 {
704 	if (queue_type != IOMMU_HW_QUEUE_TYPE_SELFTEST)
705 		return 0;
706 	return HW_QUEUE_STRUCT_SIZE(struct mock_hw_queue, core);
707 }
708 
709 static void mock_hw_queue_destroy(struct iommufd_hw_queue *hw_queue)
710 {
711 	struct mock_hw_queue *mock_hw_queue = to_mock_hw_queue(hw_queue);
712 	struct mock_viommu *mock_viommu = mock_hw_queue->mock_viommu;
713 
714 	mutex_lock(&mock_viommu->queue_mutex);
715 	mock_viommu->hw_queue[mock_hw_queue->index] = NULL;
716 	if (mock_hw_queue->prev)
717 		iommufd_hw_queue_undepend(mock_hw_queue, mock_hw_queue->prev,
718 					  core);
719 	mutex_unlock(&mock_viommu->queue_mutex);
720 }
721 
722 /* Test iommufd_hw_queue_depend/undepend() */
723 static int mock_hw_queue_init_phys(struct iommufd_hw_queue *hw_queue, u32 index,
724 				   phys_addr_t base_addr_pa)
725 {
726 	struct mock_viommu *mock_viommu = to_mock_viommu(hw_queue->viommu);
727 	struct mock_hw_queue *mock_hw_queue = to_mock_hw_queue(hw_queue);
728 	struct mock_hw_queue *prev = NULL;
729 	int rc = 0;
730 
731 	if (index >= IOMMU_TEST_HW_QUEUE_MAX)
732 		return -EINVAL;
733 
734 	mutex_lock(&mock_viommu->queue_mutex);
735 
736 	if (mock_viommu->hw_queue[index]) {
737 		rc = -EEXIST;
738 		goto unlock;
739 	}
740 
741 	if (index) {
742 		prev = mock_viommu->hw_queue[index - 1];
743 		if (!prev) {
744 			rc = -EIO;
745 			goto unlock;
746 		}
747 	}
748 
749 	/*
750 	 * Test to catch a kernel bug if the core converted the physical address
751 	 * incorrectly. Let mock_domain_iova_to_phys() WARN_ON if it fails.
752 	 */
753 	if (base_addr_pa != iommu_iova_to_phys(&mock_viommu->s2_parent->domain,
754 					       hw_queue->base_addr)) {
755 		rc = -EFAULT;
756 		goto unlock;
757 	}
758 
759 	if (prev) {
760 		rc = iommufd_hw_queue_depend(mock_hw_queue, prev, core);
761 		if (rc)
762 			goto unlock;
763 	}
764 
765 	mock_hw_queue->prev = prev;
766 	mock_hw_queue->mock_viommu = mock_viommu;
767 	mock_viommu->hw_queue[index] = mock_hw_queue;
768 
769 	hw_queue->destroy = &mock_hw_queue_destroy;
770 unlock:
771 	mutex_unlock(&mock_viommu->queue_mutex);
772 	return rc;
773 }
774 
775 static struct iommufd_viommu_ops mock_viommu_ops = {
776 	.destroy = mock_viommu_destroy,
777 	.alloc_domain_nested = mock_viommu_alloc_domain_nested,
778 	.cache_invalidate = mock_viommu_cache_invalidate,
779 	.get_hw_queue_size = mock_viommu_get_hw_queue_size,
780 	.hw_queue_init_phys = mock_hw_queue_init_phys,
781 };
782 
783 static size_t mock_get_viommu_size(struct device *dev,
784 				   enum iommu_viommu_type viommu_type)
785 {
786 	if (viommu_type != IOMMU_VIOMMU_TYPE_SELFTEST)
787 		return 0;
788 	return VIOMMU_STRUCT_SIZE(struct mock_viommu, core);
789 }
790 
791 static int mock_viommu_init(struct iommufd_viommu *viommu,
792 			    struct iommu_domain *parent_domain,
793 			    const struct iommu_user_data *user_data)
794 {
795 	struct mock_iommu_device *mock_iommu = container_of(
796 		viommu->iommu_dev, struct mock_iommu_device, iommu_dev);
797 	struct mock_viommu *mock_viommu = to_mock_viommu(viommu);
798 	struct iommu_viommu_selftest data;
799 	int rc;
800 
801 	if (user_data) {
802 		rc = iommu_copy_struct_from_user(
803 			&data, user_data, IOMMU_VIOMMU_TYPE_SELFTEST, out_data);
804 		if (rc)
805 			return rc;
806 
807 		/* Allocate two pages */
808 		mock_viommu->page =
809 			(u32 *)__get_free_pages(GFP_KERNEL | __GFP_ZERO, 1);
810 		if (!mock_viommu->page)
811 			return -ENOMEM;
812 
813 		rc = iommufd_viommu_alloc_mmap(&mock_viommu->core,
814 					       __pa(mock_viommu->page),
815 					       PAGE_SIZE * 2,
816 					       &mock_viommu->mmap_offset);
817 		if (rc)
818 			goto err_free_page;
819 
820 		/* For loopback tests on both the page and out_data */
821 		*mock_viommu->page = data.in_data;
822 		data.out_data = data.in_data;
823 		data.out_mmap_length = PAGE_SIZE * 2;
824 		data.out_mmap_offset = mock_viommu->mmap_offset;
825 		rc = iommu_copy_struct_to_user(
826 			user_data, &data, IOMMU_VIOMMU_TYPE_SELFTEST, out_data);
827 		if (rc)
828 			goto err_destroy_mmap;
829 	}
830 
831 	refcount_inc(&mock_iommu->users);
832 	mutex_init(&mock_viommu->queue_mutex);
833 	mock_viommu->s2_parent = to_mock_domain(parent_domain);
834 
835 	viommu->ops = &mock_viommu_ops;
836 	return 0;
837 
838 err_destroy_mmap:
839 	iommufd_viommu_destroy_mmap(&mock_viommu->core,
840 				    mock_viommu->mmap_offset);
841 err_free_page:
842 	free_pages((unsigned long)mock_viommu->page, 1);
843 	return rc;
844 }
845 
846 static const struct iommu_ops mock_ops = {
847 	/*
848 	 * IOMMU_DOMAIN_BLOCKED cannot be returned from def_domain_type()
849 	 * because it is zero.
850 	 */
851 	.default_domain = &mock_blocking_domain,
852 	.blocked_domain = &mock_blocking_domain,
853 	.owner = THIS_MODULE,
854 	.hw_info = mock_domain_hw_info,
855 	.domain_alloc_paging_flags = mock_domain_alloc_paging_flags,
856 	.domain_alloc_nested = mock_domain_alloc_nested,
857 	.capable = mock_domain_capable,
858 	.device_group = generic_device_group,
859 	.probe_device = mock_probe_device,
860 	.page_response = mock_domain_page_response,
861 	.user_pasid_table = true,
862 	.get_viommu_size = mock_get_viommu_size,
863 	.viommu_init = mock_viommu_init,
864 };
865 
866 static void mock_domain_free_nested(struct iommu_domain *domain)
867 {
868 	kfree(to_mock_nested(domain));
869 }
870 
871 static int
872 mock_domain_cache_invalidate_user(struct iommu_domain *domain,
873 				  struct iommu_user_data_array *array)
874 {
875 	struct mock_iommu_domain_nested *mock_nested = to_mock_nested(domain);
876 	struct iommu_hwpt_invalidate_selftest inv;
877 	u32 processed = 0;
878 	int i = 0, j;
879 	int rc = 0;
880 
881 	if (array->type != IOMMU_HWPT_INVALIDATE_DATA_SELFTEST) {
882 		rc = -EINVAL;
883 		goto out;
884 	}
885 
886 	for ( ; i < array->entry_num; i++) {
887 		rc = iommu_copy_struct_from_user_array(&inv, array,
888 						       IOMMU_HWPT_INVALIDATE_DATA_SELFTEST,
889 						       i, iotlb_id);
890 		if (rc)
891 			break;
892 
893 		if (inv.flags & ~IOMMU_TEST_INVALIDATE_FLAG_ALL) {
894 			rc = -EOPNOTSUPP;
895 			break;
896 		}
897 
898 		if (inv.iotlb_id > MOCK_NESTED_DOMAIN_IOTLB_ID_MAX) {
899 			rc = -EINVAL;
900 			break;
901 		}
902 
903 		if (inv.flags & IOMMU_TEST_INVALIDATE_FLAG_ALL) {
904 			/* Invalidate all mock iotlb entries and ignore iotlb_id */
905 			for (j = 0; j < MOCK_NESTED_DOMAIN_IOTLB_NUM; j++)
906 				mock_nested->iotlb[j] = 0;
907 		} else {
908 			mock_nested->iotlb[inv.iotlb_id] = 0;
909 		}
910 
911 		processed++;
912 	}
913 
914 out:
915 	array->entry_num = processed;
916 	return rc;
917 }
918 
919 static struct iommu_domain_ops domain_nested_ops = {
920 	.free = mock_domain_free_nested,
921 	.attach_dev = mock_domain_nop_attach,
922 	.cache_invalidate_user = mock_domain_cache_invalidate_user,
923 	.set_dev_pasid = mock_domain_set_dev_pasid_nop,
924 };
925 
926 static inline struct iommufd_hw_pagetable *
927 __get_md_pagetable(struct iommufd_ucmd *ucmd, u32 mockpt_id, u32 hwpt_type)
928 {
929 	struct iommufd_object *obj;
930 
931 	obj = iommufd_get_object(ucmd->ictx, mockpt_id, hwpt_type);
932 	if (IS_ERR(obj))
933 		return ERR_CAST(obj);
934 	return container_of(obj, struct iommufd_hw_pagetable, obj);
935 }
936 
937 static inline struct iommufd_hw_pagetable *
938 get_md_pagetable(struct iommufd_ucmd *ucmd, u32 mockpt_id,
939 		 struct mock_iommu_domain **mock)
940 {
941 	struct iommufd_hw_pagetable *hwpt;
942 
943 	hwpt = __get_md_pagetable(ucmd, mockpt_id, IOMMUFD_OBJ_HWPT_PAGING);
944 	if (IS_ERR(hwpt))
945 		return hwpt;
946 	if (hwpt->domain->type != IOMMU_DOMAIN_UNMANAGED ||
947 	    hwpt->domain->owner != &mock_ops) {
948 		iommufd_put_object(ucmd->ictx, &hwpt->obj);
949 		return ERR_PTR(-EINVAL);
950 	}
951 	*mock = to_mock_domain(hwpt->domain);
952 	return hwpt;
953 }
954 
955 static inline struct iommufd_hw_pagetable *
956 get_md_pagetable_nested(struct iommufd_ucmd *ucmd, u32 mockpt_id,
957 			struct mock_iommu_domain_nested **mock_nested)
958 {
959 	struct iommufd_hw_pagetable *hwpt;
960 
961 	hwpt = __get_md_pagetable(ucmd, mockpt_id, IOMMUFD_OBJ_HWPT_NESTED);
962 	if (IS_ERR(hwpt))
963 		return hwpt;
964 	if (hwpt->domain->type != IOMMU_DOMAIN_NESTED ||
965 	    hwpt->domain->ops != &domain_nested_ops) {
966 		iommufd_put_object(ucmd->ictx, &hwpt->obj);
967 		return ERR_PTR(-EINVAL);
968 	}
969 	*mock_nested = to_mock_nested(hwpt->domain);
970 	return hwpt;
971 }
972 
973 static void mock_dev_release(struct device *dev)
974 {
975 	struct mock_dev *mdev = to_mock_dev(dev);
976 
977 	ida_free(&mock_dev_ida, mdev->id);
978 	kfree(mdev);
979 }
980 
981 static struct mock_dev *mock_dev_create(unsigned long dev_flags)
982 {
983 	struct property_entry prop[] = {
984 		PROPERTY_ENTRY_U32("pasid-num-bits", 0),
985 		{},
986 	};
987 	const u32 valid_flags = MOCK_FLAGS_DEVICE_NO_DIRTY |
988 				MOCK_FLAGS_DEVICE_PASID;
989 	struct mock_dev *mdev;
990 	int rc, i;
991 
992 	if (dev_flags & ~valid_flags)
993 		return ERR_PTR(-EINVAL);
994 
995 	mdev = kzalloc_obj(*mdev);
996 	if (!mdev)
997 		return ERR_PTR(-ENOMEM);
998 
999 	init_rwsem(&mdev->viommu_rwsem);
1000 	device_initialize(&mdev->dev);
1001 	mdev->flags = dev_flags;
1002 	mdev->dev.release = mock_dev_release;
1003 	mdev->dev.bus = &iommufd_mock_bus_type.bus;
1004 	for (i = 0; i < MOCK_DEV_CACHE_NUM; i++)
1005 		mdev->cache[i] = IOMMU_TEST_DEV_CACHE_DEFAULT;
1006 
1007 	rc = ida_alloc(&mock_dev_ida, GFP_KERNEL);
1008 	if (rc < 0)
1009 		goto err_put;
1010 	mdev->id = rc;
1011 
1012 	rc = dev_set_name(&mdev->dev, "iommufd_mock%u", mdev->id);
1013 	if (rc)
1014 		goto err_put;
1015 
1016 	if (dev_flags & MOCK_FLAGS_DEVICE_PASID)
1017 		prop[0] = PROPERTY_ENTRY_U32("pasid-num-bits", MOCK_PASID_WIDTH);
1018 
1019 	rc = device_create_managed_software_node(&mdev->dev, prop, NULL);
1020 	if (rc) {
1021 		dev_err(&mdev->dev, "add pasid-num-bits property failed, rc: %d", rc);
1022 		goto err_put;
1023 	}
1024 
1025 	rc = iommu_mock_device_add(&mdev->dev, &mock_iommu.iommu_dev);
1026 	if (rc)
1027 		goto err_put;
1028 	return mdev;
1029 
1030 err_put:
1031 	put_device(&mdev->dev);
1032 	return ERR_PTR(rc);
1033 }
1034 
1035 static void mock_dev_destroy(struct mock_dev *mdev)
1036 {
1037 	device_unregister(&mdev->dev);
1038 }
1039 
1040 bool iommufd_selftest_is_mock_dev(struct device *dev)
1041 {
1042 	return dev->release == mock_dev_release;
1043 }
1044 
1045 /* Create an hw_pagetable with the mock domain so we can test the domain ops */
1046 static int iommufd_test_mock_domain(struct iommufd_ucmd *ucmd,
1047 				    struct iommu_test_cmd *cmd)
1048 {
1049 	struct iommufd_device *idev;
1050 	struct selftest_obj *sobj;
1051 	u32 pt_id = cmd->id;
1052 	u32 dev_flags = 0;
1053 	u32 idev_id;
1054 	int rc;
1055 
1056 	sobj = iommufd_object_alloc(ucmd->ictx, sobj, IOMMUFD_OBJ_SELFTEST);
1057 	if (IS_ERR(sobj))
1058 		return PTR_ERR(sobj);
1059 
1060 	sobj->idev.ictx = ucmd->ictx;
1061 	sobj->type = TYPE_IDEV;
1062 
1063 	if (cmd->op == IOMMU_TEST_OP_MOCK_DOMAIN_FLAGS)
1064 		dev_flags = cmd->mock_domain_flags.dev_flags;
1065 
1066 	sobj->idev.mock_dev = mock_dev_create(dev_flags);
1067 	if (IS_ERR(sobj->idev.mock_dev)) {
1068 		rc = PTR_ERR(sobj->idev.mock_dev);
1069 		goto out_sobj;
1070 	}
1071 
1072 	idev = iommufd_device_bind(ucmd->ictx, &sobj->idev.mock_dev->dev,
1073 				   &idev_id);
1074 	if (IS_ERR(idev)) {
1075 		rc = PTR_ERR(idev);
1076 		goto out_mdev;
1077 	}
1078 	sobj->idev.idev = idev;
1079 
1080 	rc = iommufd_device_attach(idev, IOMMU_NO_PASID, &pt_id);
1081 	if (rc)
1082 		goto out_unbind;
1083 
1084 	/* Userspace must destroy the device_id to destroy the object */
1085 	cmd->mock_domain.out_hwpt_id = pt_id;
1086 	cmd->mock_domain.out_stdev_id = sobj->obj.id;
1087 	cmd->mock_domain.out_idev_id = idev_id;
1088 	rc = iommufd_ucmd_respond(ucmd, sizeof(*cmd));
1089 	if (rc)
1090 		goto out_detach;
1091 	iommufd_object_finalize(ucmd->ictx, &sobj->obj);
1092 	return 0;
1093 
1094 out_detach:
1095 	iommufd_device_detach(idev, IOMMU_NO_PASID);
1096 out_unbind:
1097 	iommufd_device_unbind(idev);
1098 out_mdev:
1099 	mock_dev_destroy(sobj->idev.mock_dev);
1100 out_sobj:
1101 	iommufd_object_abort(ucmd->ictx, &sobj->obj);
1102 	return rc;
1103 }
1104 
1105 static struct selftest_obj *
1106 iommufd_test_get_selftest_obj(struct iommufd_ctx *ictx, u32 id)
1107 {
1108 	struct iommufd_object *dev_obj;
1109 	struct selftest_obj *sobj;
1110 
1111 	/*
1112 	 * Prefer to use the OBJ_SELFTEST because the destroy_rwsem will ensure
1113 	 * it doesn't race with detach, which is not allowed.
1114 	 */
1115 	dev_obj = iommufd_get_object(ictx, id, IOMMUFD_OBJ_SELFTEST);
1116 	if (IS_ERR(dev_obj))
1117 		return ERR_CAST(dev_obj);
1118 
1119 	sobj = to_selftest_obj(dev_obj);
1120 	if (sobj->type != TYPE_IDEV) {
1121 		iommufd_put_object(ictx, dev_obj);
1122 		return ERR_PTR(-EINVAL);
1123 	}
1124 	return sobj;
1125 }
1126 
1127 /* Replace the mock domain with a manually allocated hw_pagetable */
1128 static int iommufd_test_mock_domain_replace(struct iommufd_ucmd *ucmd,
1129 					    unsigned int device_id, u32 pt_id,
1130 					    struct iommu_test_cmd *cmd)
1131 {
1132 	struct selftest_obj *sobj;
1133 	int rc;
1134 
1135 	sobj = iommufd_test_get_selftest_obj(ucmd->ictx, device_id);
1136 	if (IS_ERR(sobj))
1137 		return PTR_ERR(sobj);
1138 
1139 	rc = iommufd_device_replace(sobj->idev.idev, IOMMU_NO_PASID, &pt_id);
1140 	if (rc)
1141 		goto out_sobj;
1142 
1143 	cmd->mock_domain_replace.pt_id = pt_id;
1144 	rc = iommufd_ucmd_respond(ucmd, sizeof(*cmd));
1145 
1146 out_sobj:
1147 	iommufd_put_object(ucmd->ictx, &sobj->obj);
1148 	return rc;
1149 }
1150 
1151 /* Add an additional reserved IOVA to the IOAS */
1152 static int iommufd_test_add_reserved(struct iommufd_ucmd *ucmd,
1153 				     unsigned int mockpt_id,
1154 				     unsigned long start, size_t length)
1155 {
1156 	unsigned long last;
1157 	struct iommufd_ioas *ioas;
1158 	int rc;
1159 
1160 	if (!length)
1161 		return -EINVAL;
1162 	if (check_add_overflow(start, length - 1, &last))
1163 		return -EOVERFLOW;
1164 
1165 	ioas = iommufd_get_ioas(ucmd->ictx, mockpt_id);
1166 	if (IS_ERR(ioas))
1167 		return PTR_ERR(ioas);
1168 	down_write(&ioas->iopt.iova_rwsem);
1169 	rc = iopt_reserve_iova(&ioas->iopt, start, last, NULL);
1170 	up_write(&ioas->iopt.iova_rwsem);
1171 	iommufd_put_object(ucmd->ictx, &ioas->obj);
1172 	return rc;
1173 }
1174 
1175 /* Check that every pfn under each iova matches the pfn under a user VA */
1176 static int iommufd_test_md_check_pa(struct iommufd_ucmd *ucmd,
1177 				    unsigned int mockpt_id, unsigned long iova,
1178 				    size_t length, void __user *uptr)
1179 {
1180 	struct iommufd_hw_pagetable *hwpt;
1181 	struct mock_iommu_domain *mock;
1182 	unsigned int page_size;
1183 	uintptr_t end;
1184 	int rc;
1185 
1186 	hwpt = get_md_pagetable(ucmd, mockpt_id, &mock);
1187 	if (IS_ERR(hwpt))
1188 		return PTR_ERR(hwpt);
1189 
1190 	page_size = 1 << __ffs(mock->domain.pgsize_bitmap);
1191 	if (iova % page_size || length % page_size ||
1192 	    (uintptr_t)uptr % page_size ||
1193 	    check_add_overflow((uintptr_t)uptr, (uintptr_t)length, &end)) {
1194 		rc = -EINVAL;
1195 		goto out_put;
1196 	}
1197 
1198 	for (; length; length -= page_size) {
1199 		struct page *pages[1];
1200 		phys_addr_t io_phys;
1201 		unsigned long pfn;
1202 		long npages;
1203 
1204 		npages = get_user_pages_fast((uintptr_t)uptr & PAGE_MASK, 1, 0,
1205 					     pages);
1206 		if (npages < 0) {
1207 			rc = npages;
1208 			goto out_put;
1209 		}
1210 		if (WARN_ON(npages != 1)) {
1211 			rc = -EFAULT;
1212 			goto out_put;
1213 		}
1214 		pfn = page_to_pfn(pages[0]);
1215 		put_page(pages[0]);
1216 
1217 		io_phys = mock->domain.ops->iova_to_phys(&mock->domain, iova);
1218 		if (io_phys !=
1219 		    pfn * PAGE_SIZE + ((uintptr_t)uptr % PAGE_SIZE)) {
1220 			rc = -EINVAL;
1221 			goto out_put;
1222 		}
1223 		iova += page_size;
1224 		uptr += page_size;
1225 	}
1226 	rc = 0;
1227 
1228 out_put:
1229 	iommufd_put_object(ucmd->ictx, &hwpt->obj);
1230 	return rc;
1231 }
1232 
1233 /* Check that the page ref count matches, to look for missing pin/unpins */
1234 static int iommufd_test_md_check_refs(struct iommufd_ucmd *ucmd,
1235 				      void __user *uptr, size_t length,
1236 				      unsigned int refs)
1237 {
1238 	uintptr_t end;
1239 
1240 	if (length % PAGE_SIZE || (uintptr_t)uptr % PAGE_SIZE ||
1241 	    check_add_overflow((uintptr_t)uptr, (uintptr_t)length, &end))
1242 		return -EINVAL;
1243 
1244 	for (; length; length -= PAGE_SIZE) {
1245 		struct page *pages[1];
1246 		long npages;
1247 
1248 		npages = get_user_pages_fast((uintptr_t)uptr, 1, 0, pages);
1249 		if (npages < 0)
1250 			return npages;
1251 		if (WARN_ON(npages != 1))
1252 			return -EFAULT;
1253 		if (!PageCompound(pages[0])) {
1254 			unsigned int count;
1255 
1256 			count = page_ref_count(pages[0]);
1257 			if (count / GUP_PIN_COUNTING_BIAS != refs) {
1258 				put_page(pages[0]);
1259 				return -EIO;
1260 			}
1261 		}
1262 		put_page(pages[0]);
1263 		uptr += PAGE_SIZE;
1264 	}
1265 	return 0;
1266 }
1267 
1268 static int iommufd_test_md_check_iotlb(struct iommufd_ucmd *ucmd, u32 mockpt_id,
1269 				       unsigned int iotlb_id, u32 iotlb)
1270 {
1271 	struct mock_iommu_domain_nested *mock_nested;
1272 	struct iommufd_hw_pagetable *hwpt;
1273 	int rc = 0;
1274 
1275 	hwpt = get_md_pagetable_nested(ucmd, mockpt_id, &mock_nested);
1276 	if (IS_ERR(hwpt))
1277 		return PTR_ERR(hwpt);
1278 
1279 	mock_nested = to_mock_nested(hwpt->domain);
1280 
1281 	if (iotlb_id > MOCK_NESTED_DOMAIN_IOTLB_ID_MAX ||
1282 	    mock_nested->iotlb[iotlb_id] != iotlb)
1283 		rc = -EINVAL;
1284 	iommufd_put_object(ucmd->ictx, &hwpt->obj);
1285 	return rc;
1286 }
1287 
1288 static int iommufd_test_dev_check_cache(struct iommufd_ucmd *ucmd, u32 idev_id,
1289 					unsigned int cache_id, u32 cache)
1290 {
1291 	struct iommufd_device *idev;
1292 	struct mock_dev *mdev;
1293 	int rc = 0;
1294 
1295 	idev = iommufd_get_device(ucmd, idev_id);
1296 	if (IS_ERR(idev))
1297 		return PTR_ERR(idev);
1298 	mdev = container_of(idev->dev, struct mock_dev, dev);
1299 
1300 	if (cache_id > MOCK_DEV_CACHE_ID_MAX || mdev->cache[cache_id] != cache)
1301 		rc = -EINVAL;
1302 	iommufd_put_object(ucmd->ictx, &idev->obj);
1303 	return rc;
1304 }
1305 
1306 struct selftest_access {
1307 	struct iommufd_access *access;
1308 	struct file *file;
1309 	struct mutex lock;
1310 	struct list_head items;
1311 	unsigned int next_id;
1312 	bool destroying;
1313 };
1314 
1315 struct selftest_access_item {
1316 	struct list_head items_elm;
1317 	unsigned long iova;
1318 	size_t length;
1319 	unsigned int id;
1320 };
1321 
1322 static const struct file_operations iommfd_test_staccess_fops;
1323 
1324 static struct selftest_access *iommufd_access_get(int fd)
1325 {
1326 	struct file *file;
1327 
1328 	file = fget(fd);
1329 	if (!file)
1330 		return ERR_PTR(-EBADFD);
1331 
1332 	if (file->f_op != &iommfd_test_staccess_fops) {
1333 		fput(file);
1334 		return ERR_PTR(-EBADFD);
1335 	}
1336 	return file->private_data;
1337 }
1338 
1339 static void iommufd_test_access_unmap(void *data, unsigned long iova,
1340 				      unsigned long length)
1341 {
1342 	unsigned long iova_last = iova + length - 1;
1343 	struct selftest_access *staccess = data;
1344 	struct selftest_access_item *item;
1345 	struct selftest_access_item *tmp;
1346 
1347 	mutex_lock(&staccess->lock);
1348 	list_for_each_entry_safe(item, tmp, &staccess->items, items_elm) {
1349 		if (iova > item->iova + item->length - 1 ||
1350 		    iova_last < item->iova)
1351 			continue;
1352 		list_del(&item->items_elm);
1353 		iommufd_access_unpin_pages(staccess->access, item->iova,
1354 					   item->length);
1355 		kfree(item);
1356 	}
1357 	mutex_unlock(&staccess->lock);
1358 }
1359 
1360 static int iommufd_test_access_item_destroy(struct iommufd_ucmd *ucmd,
1361 					    unsigned int access_id,
1362 					    unsigned int item_id)
1363 {
1364 	struct selftest_access_item *item;
1365 	struct selftest_access *staccess;
1366 
1367 	staccess = iommufd_access_get(access_id);
1368 	if (IS_ERR(staccess))
1369 		return PTR_ERR(staccess);
1370 
1371 	mutex_lock(&staccess->lock);
1372 	list_for_each_entry(item, &staccess->items, items_elm) {
1373 		if (item->id == item_id) {
1374 			list_del(&item->items_elm);
1375 			iommufd_access_unpin_pages(staccess->access, item->iova,
1376 						   item->length);
1377 			mutex_unlock(&staccess->lock);
1378 			kfree(item);
1379 			fput(staccess->file);
1380 			return 0;
1381 		}
1382 	}
1383 	mutex_unlock(&staccess->lock);
1384 	fput(staccess->file);
1385 	return -ENOENT;
1386 }
1387 
1388 static int iommufd_test_staccess_release(struct inode *inode,
1389 					 struct file *filep)
1390 {
1391 	struct selftest_access *staccess = filep->private_data;
1392 
1393 	if (staccess->access) {
1394 		iommufd_test_access_unmap(staccess, 0, ULONG_MAX);
1395 		iommufd_access_destroy(staccess->access);
1396 	}
1397 	mutex_destroy(&staccess->lock);
1398 	kfree(staccess);
1399 	return 0;
1400 }
1401 
1402 static const struct iommufd_access_ops selftest_access_ops_pin = {
1403 	.needs_pin_pages = 1,
1404 	.unmap = iommufd_test_access_unmap,
1405 };
1406 
1407 static const struct iommufd_access_ops selftest_access_ops = {
1408 	.unmap = iommufd_test_access_unmap,
1409 };
1410 
1411 static const struct file_operations iommfd_test_staccess_fops = {
1412 	.release = iommufd_test_staccess_release,
1413 };
1414 
1415 static struct selftest_access *iommufd_test_alloc_access(void)
1416 {
1417 	struct selftest_access *staccess;
1418 	struct file *filep;
1419 
1420 	staccess = kzalloc_obj(*staccess, GFP_KERNEL_ACCOUNT);
1421 	if (!staccess)
1422 		return ERR_PTR(-ENOMEM);
1423 	INIT_LIST_HEAD(&staccess->items);
1424 	mutex_init(&staccess->lock);
1425 
1426 	filep = anon_inode_getfile("[iommufd_test_staccess]",
1427 				   &iommfd_test_staccess_fops, staccess,
1428 				   O_RDWR);
1429 	if (IS_ERR(filep)) {
1430 		kfree(staccess);
1431 		return ERR_CAST(filep);
1432 	}
1433 	staccess->file = filep;
1434 	return staccess;
1435 }
1436 
1437 static int iommufd_test_create_access(struct iommufd_ucmd *ucmd,
1438 				      unsigned int ioas_id, unsigned int flags)
1439 {
1440 	struct iommu_test_cmd *cmd = ucmd->cmd;
1441 	struct selftest_access *staccess;
1442 	struct iommufd_access *access;
1443 	u32 id;
1444 	int fdno;
1445 	int rc;
1446 
1447 	if (flags & ~MOCK_FLAGS_ACCESS_CREATE_NEEDS_PIN_PAGES)
1448 		return -EOPNOTSUPP;
1449 
1450 	staccess = iommufd_test_alloc_access();
1451 	if (IS_ERR(staccess))
1452 		return PTR_ERR(staccess);
1453 
1454 	fdno = get_unused_fd_flags(O_CLOEXEC);
1455 	if (fdno < 0) {
1456 		rc = -ENOMEM;
1457 		goto out_free_staccess;
1458 	}
1459 
1460 	access = iommufd_access_create(
1461 		ucmd->ictx,
1462 		(flags & MOCK_FLAGS_ACCESS_CREATE_NEEDS_PIN_PAGES) ?
1463 			&selftest_access_ops_pin :
1464 			&selftest_access_ops,
1465 		staccess, &id);
1466 	if (IS_ERR(access)) {
1467 		rc = PTR_ERR(access);
1468 		goto out_put_fdno;
1469 	}
1470 	rc = iommufd_access_attach(access, ioas_id);
1471 	if (rc)
1472 		goto out_destroy;
1473 	cmd->create_access.out_access_fd = fdno;
1474 	rc = iommufd_ucmd_respond(ucmd, sizeof(*cmd));
1475 	if (rc)
1476 		goto out_destroy;
1477 
1478 	staccess->access = access;
1479 	fd_install(fdno, staccess->file);
1480 	return 0;
1481 
1482 out_destroy:
1483 	iommufd_access_destroy(access);
1484 out_put_fdno:
1485 	put_unused_fd(fdno);
1486 out_free_staccess:
1487 	fput(staccess->file);
1488 	return rc;
1489 }
1490 
1491 static int iommufd_test_access_replace_ioas(struct iommufd_ucmd *ucmd,
1492 					    unsigned int access_id,
1493 					    unsigned int ioas_id)
1494 {
1495 	struct selftest_access *staccess;
1496 	int rc;
1497 
1498 	staccess = iommufd_access_get(access_id);
1499 	if (IS_ERR(staccess))
1500 		return PTR_ERR(staccess);
1501 
1502 	rc = iommufd_access_replace(staccess->access, ioas_id);
1503 	fput(staccess->file);
1504 	return rc;
1505 }
1506 
1507 /* Check that the pages in a page array match the pages in the user VA */
1508 static int iommufd_test_check_pages(void __user *uptr, struct page **pages,
1509 				    size_t npages)
1510 {
1511 	for (; npages; npages--) {
1512 		struct page *tmp_pages[1];
1513 		long rc;
1514 
1515 		rc = get_user_pages_fast((uintptr_t)uptr, 1, 0, tmp_pages);
1516 		if (rc < 0)
1517 			return rc;
1518 		if (WARN_ON(rc != 1))
1519 			return -EFAULT;
1520 		put_page(tmp_pages[0]);
1521 		if (tmp_pages[0] != *pages)
1522 			return -EBADE;
1523 		pages++;
1524 		uptr += PAGE_SIZE;
1525 	}
1526 	return 0;
1527 }
1528 
1529 static int iommufd_test_access_pages(struct iommufd_ucmd *ucmd,
1530 				     unsigned int access_id, unsigned long iova,
1531 				     size_t length, void __user *uptr,
1532 				     u32 flags)
1533 {
1534 	struct iommu_test_cmd *cmd = ucmd->cmd;
1535 	struct selftest_access_item *item;
1536 	struct selftest_access *staccess;
1537 	struct page **pages;
1538 	size_t npages;
1539 	int rc;
1540 
1541 	/* Prevent syzkaller from triggering a WARN_ON in kvzalloc() */
1542 	if (length > 16 * 1024 * 1024)
1543 		return -ENOMEM;
1544 
1545 	if (flags & ~(MOCK_FLAGS_ACCESS_WRITE | MOCK_FLAGS_ACCESS_SYZ))
1546 		return -EOPNOTSUPP;
1547 
1548 	staccess = iommufd_access_get(access_id);
1549 	if (IS_ERR(staccess))
1550 		return PTR_ERR(staccess);
1551 
1552 	if (staccess->access->ops != &selftest_access_ops_pin) {
1553 		rc = -EOPNOTSUPP;
1554 		goto out_put;
1555 	}
1556 
1557 	if (flags & MOCK_FLAGS_ACCESS_SYZ)
1558 		iova = iommufd_test_syz_conv_iova(staccess->access,
1559 						  &cmd->access_pages.iova);
1560 
1561 	npages = (ALIGN(iova + length, PAGE_SIZE) -
1562 		  ALIGN_DOWN(iova, PAGE_SIZE)) /
1563 		 PAGE_SIZE;
1564 	pages = kvzalloc_objs(*pages, npages, GFP_KERNEL_ACCOUNT);
1565 	if (!pages) {
1566 		rc = -ENOMEM;
1567 		goto out_put;
1568 	}
1569 
1570 	/*
1571 	 * Drivers will need to think very carefully about this locking. The
1572 	 * core code can do multiple unmaps instantaneously after
1573 	 * iommufd_access_pin_pages() and *all* the unmaps must not return until
1574 	 * the range is unpinned. This simple implementation puts a global lock
1575 	 * around the pin, which may not suit drivers that want this to be a
1576 	 * performance path. drivers that get this wrong will trigger WARN_ON
1577 	 * races and cause EDEADLOCK failures to userspace.
1578 	 */
1579 	mutex_lock(&staccess->lock);
1580 	rc = iommufd_access_pin_pages(staccess->access, iova, length, pages,
1581 				      flags & MOCK_FLAGS_ACCESS_WRITE);
1582 	if (rc)
1583 		goto out_unlock;
1584 
1585 	/* For syzkaller allow uptr to be NULL to skip this check */
1586 	if (uptr) {
1587 		rc = iommufd_test_check_pages(
1588 			uptr - (iova - ALIGN_DOWN(iova, PAGE_SIZE)), pages,
1589 			npages);
1590 		if (rc)
1591 			goto out_unaccess;
1592 	}
1593 
1594 	item = kzalloc_obj(*item, GFP_KERNEL_ACCOUNT);
1595 	if (!item) {
1596 		rc = -ENOMEM;
1597 		goto out_unaccess;
1598 	}
1599 
1600 	item->iova = iova;
1601 	item->length = length;
1602 	item->id = staccess->next_id++;
1603 	list_add_tail(&item->items_elm, &staccess->items);
1604 
1605 	cmd->access_pages.out_access_pages_id = item->id;
1606 	rc = iommufd_ucmd_respond(ucmd, sizeof(*cmd));
1607 	if (rc)
1608 		goto out_free_item;
1609 	goto out_unlock;
1610 
1611 out_free_item:
1612 	list_del(&item->items_elm);
1613 	kfree(item);
1614 out_unaccess:
1615 	iommufd_access_unpin_pages(staccess->access, iova, length);
1616 out_unlock:
1617 	mutex_unlock(&staccess->lock);
1618 	kvfree(pages);
1619 out_put:
1620 	fput(staccess->file);
1621 	return rc;
1622 }
1623 
1624 static int iommufd_test_access_rw(struct iommufd_ucmd *ucmd,
1625 				  unsigned int access_id, unsigned long iova,
1626 				  size_t length, void __user *ubuf,
1627 				  unsigned int flags)
1628 {
1629 	struct iommu_test_cmd *cmd = ucmd->cmd;
1630 	struct selftest_access *staccess;
1631 	void *tmp;
1632 	int rc;
1633 
1634 	/* Prevent syzkaller from triggering a WARN_ON in kvzalloc() */
1635 	if (length > 16 * 1024 * 1024)
1636 		return -ENOMEM;
1637 
1638 	if (flags & ~(MOCK_ACCESS_RW_WRITE | MOCK_ACCESS_RW_SLOW_PATH |
1639 		      MOCK_FLAGS_ACCESS_SYZ))
1640 		return -EOPNOTSUPP;
1641 
1642 	staccess = iommufd_access_get(access_id);
1643 	if (IS_ERR(staccess))
1644 		return PTR_ERR(staccess);
1645 
1646 	tmp = kvzalloc(length, GFP_KERNEL_ACCOUNT);
1647 	if (!tmp) {
1648 		rc = -ENOMEM;
1649 		goto out_put;
1650 	}
1651 
1652 	if (flags & MOCK_ACCESS_RW_WRITE) {
1653 		if (copy_from_user(tmp, ubuf, length)) {
1654 			rc = -EFAULT;
1655 			goto out_free;
1656 		}
1657 	}
1658 
1659 	if (flags & MOCK_FLAGS_ACCESS_SYZ)
1660 		iova = iommufd_test_syz_conv_iova(staccess->access,
1661 						  &cmd->access_rw.iova);
1662 
1663 	rc = iommufd_access_rw(staccess->access, iova, tmp, length, flags);
1664 	if (rc)
1665 		goto out_free;
1666 	if (!(flags & MOCK_ACCESS_RW_WRITE)) {
1667 		if (copy_to_user(ubuf, tmp, length)) {
1668 			rc = -EFAULT;
1669 			goto out_free;
1670 		}
1671 	}
1672 
1673 out_free:
1674 	kvfree(tmp);
1675 out_put:
1676 	fput(staccess->file);
1677 	return rc;
1678 }
1679 static_assert((unsigned int)MOCK_ACCESS_RW_WRITE == IOMMUFD_ACCESS_RW_WRITE);
1680 static_assert((unsigned int)MOCK_ACCESS_RW_SLOW_PATH ==
1681 	      __IOMMUFD_ACCESS_RW_SLOW_PATH);
1682 
1683 static int iommufd_test_dirty(struct iommufd_ucmd *ucmd, unsigned int mockpt_id,
1684 			      unsigned long iova, size_t length,
1685 			      unsigned long page_size, void __user *uptr,
1686 			      u32 flags)
1687 {
1688 	unsigned long i, max;
1689 	struct iommu_test_cmd *cmd = ucmd->cmd;
1690 	struct iommufd_hw_pagetable *hwpt;
1691 	struct mock_iommu_domain *mock;
1692 	int rc, count = 0;
1693 	void *tmp;
1694 
1695 	if (!page_size || !length || iova % page_size || length % page_size ||
1696 	    !uptr)
1697 		return -EINVAL;
1698 
1699 	hwpt = get_md_pagetable(ucmd, mockpt_id, &mock);
1700 	if (IS_ERR(hwpt))
1701 		return PTR_ERR(hwpt);
1702 
1703 	if (!(mock->flags & MOCK_DIRTY_TRACK) || !mock->iommu.ops->set_dirty) {
1704 		rc = -EINVAL;
1705 		goto out_put;
1706 	}
1707 
1708 	max = length / page_size;
1709 	tmp = kvzalloc(DIV_ROUND_UP(max, BITS_PER_LONG) * sizeof(unsigned long),
1710 		       GFP_KERNEL_ACCOUNT);
1711 	if (!tmp) {
1712 		rc = -ENOMEM;
1713 		goto out_put;
1714 	}
1715 
1716 	if (copy_from_user(tmp, uptr, DIV_ROUND_UP(max, BITS_PER_BYTE))) {
1717 		rc = -EFAULT;
1718 		goto out_free;
1719 	}
1720 
1721 	for (i = 0; i < max; i++) {
1722 		if (!test_bit(i, (unsigned long *)tmp))
1723 			continue;
1724 		mock->iommu.ops->set_dirty(&mock->iommu, iova + i * page_size);
1725 		count++;
1726 	}
1727 
1728 	cmd->dirty.out_nr_dirty = count;
1729 	rc = iommufd_ucmd_respond(ucmd, sizeof(*cmd));
1730 out_free:
1731 	kvfree(tmp);
1732 out_put:
1733 	iommufd_put_object(ucmd->ictx, &hwpt->obj);
1734 	return rc;
1735 }
1736 
1737 static int iommufd_test_trigger_iopf(struct iommufd_ucmd *ucmd,
1738 				     struct iommu_test_cmd *cmd)
1739 {
1740 	struct iopf_fault event = {};
1741 	struct iommufd_device *idev;
1742 
1743 	idev = iommufd_get_device(ucmd, cmd->trigger_iopf.dev_id);
1744 	if (IS_ERR(idev))
1745 		return PTR_ERR(idev);
1746 
1747 	event.fault.prm.flags = IOMMU_FAULT_PAGE_REQUEST_LAST_PAGE;
1748 	if (cmd->trigger_iopf.pasid != IOMMU_NO_PASID)
1749 		event.fault.prm.flags |= IOMMU_FAULT_PAGE_REQUEST_PASID_VALID;
1750 	event.fault.type = IOMMU_FAULT_PAGE_REQ;
1751 	event.fault.prm.addr = cmd->trigger_iopf.addr;
1752 	event.fault.prm.pasid = cmd->trigger_iopf.pasid;
1753 	event.fault.prm.grpid = cmd->trigger_iopf.grpid;
1754 	event.fault.prm.perm = cmd->trigger_iopf.perm;
1755 
1756 	iommu_report_device_fault(idev->dev, &event);
1757 	iommufd_put_object(ucmd->ictx, &idev->obj);
1758 
1759 	return 0;
1760 }
1761 
1762 static int iommufd_test_trigger_vevent(struct iommufd_ucmd *ucmd,
1763 				       struct iommu_test_cmd *cmd)
1764 {
1765 	struct iommu_viommu_event_selftest test = {};
1766 	struct iommufd_device *idev;
1767 	struct mock_dev *mdev;
1768 	int rc = -ENOENT;
1769 
1770 	idev = iommufd_get_device(ucmd, cmd->trigger_vevent.dev_id);
1771 	if (IS_ERR(idev))
1772 		return PTR_ERR(idev);
1773 	mdev = to_mock_dev(idev->dev);
1774 
1775 	down_read(&mdev->viommu_rwsem);
1776 	if (!mdev->viommu || !mdev->vdev_id)
1777 		goto out_unlock;
1778 
1779 	test.virt_id = mdev->vdev_id;
1780 	rc = iommufd_viommu_report_event(&mdev->viommu->core,
1781 					 IOMMU_VEVENTQ_TYPE_SELFTEST, &test,
1782 					 sizeof(test));
1783 out_unlock:
1784 	up_read(&mdev->viommu_rwsem);
1785 	iommufd_put_object(ucmd->ictx, &idev->obj);
1786 
1787 	return rc;
1788 }
1789 
1790 static inline struct iommufd_hw_pagetable *
1791 iommufd_get_hwpt(struct iommufd_ucmd *ucmd, u32 id)
1792 {
1793 	struct iommufd_object *pt_obj;
1794 
1795 	pt_obj = iommufd_get_object(ucmd->ictx, id, IOMMUFD_OBJ_ANY);
1796 	if (IS_ERR(pt_obj))
1797 		return ERR_CAST(pt_obj);
1798 
1799 	if (pt_obj->type != IOMMUFD_OBJ_HWPT_NESTED &&
1800 	    pt_obj->type != IOMMUFD_OBJ_HWPT_PAGING) {
1801 		iommufd_put_object(ucmd->ictx, pt_obj);
1802 		return ERR_PTR(-EINVAL);
1803 	}
1804 
1805 	return container_of(pt_obj, struct iommufd_hw_pagetable, obj);
1806 }
1807 
1808 static int iommufd_test_pasid_check_hwpt(struct iommufd_ucmd *ucmd,
1809 					 struct iommu_test_cmd *cmd)
1810 {
1811 	u32 hwpt_id = cmd->pasid_check.hwpt_id;
1812 	struct iommu_domain *attached_domain;
1813 	struct iommu_attach_handle *handle;
1814 	struct iommufd_hw_pagetable *hwpt;
1815 	struct selftest_obj *sobj;
1816 	struct mock_dev *mdev;
1817 	int rc = 0;
1818 
1819 	sobj = iommufd_test_get_selftest_obj(ucmd->ictx, cmd->id);
1820 	if (IS_ERR(sobj))
1821 		return PTR_ERR(sobj);
1822 
1823 	mdev = sobj->idev.mock_dev;
1824 
1825 	handle = iommu_attach_handle_get(mdev->dev.iommu_group,
1826 					 cmd->pasid_check.pasid, 0);
1827 	if (IS_ERR(handle))
1828 		attached_domain = NULL;
1829 	else
1830 		attached_domain = handle->domain;
1831 
1832 	/* hwpt_id == 0 means to check if pasid is detached */
1833 	if (!hwpt_id) {
1834 		if (attached_domain)
1835 			rc = -EINVAL;
1836 		goto out_sobj;
1837 	}
1838 
1839 	hwpt = iommufd_get_hwpt(ucmd, hwpt_id);
1840 	if (IS_ERR(hwpt)) {
1841 		rc = PTR_ERR(hwpt);
1842 		goto out_sobj;
1843 	}
1844 
1845 	if (attached_domain != hwpt->domain)
1846 		rc = -EINVAL;
1847 
1848 	iommufd_put_object(ucmd->ictx, &hwpt->obj);
1849 out_sobj:
1850 	iommufd_put_object(ucmd->ictx, &sobj->obj);
1851 	return rc;
1852 }
1853 
1854 static int iommufd_test_pasid_attach(struct iommufd_ucmd *ucmd,
1855 				     struct iommu_test_cmd *cmd)
1856 {
1857 	struct selftest_obj *sobj;
1858 	int rc;
1859 
1860 	sobj = iommufd_test_get_selftest_obj(ucmd->ictx, cmd->id);
1861 	if (IS_ERR(sobj))
1862 		return PTR_ERR(sobj);
1863 
1864 	rc = iommufd_device_attach(sobj->idev.idev, cmd->pasid_attach.pasid,
1865 				   &cmd->pasid_attach.pt_id);
1866 	if (rc)
1867 		goto out_sobj;
1868 
1869 	rc = iommufd_ucmd_respond(ucmd, sizeof(*cmd));
1870 	if (rc)
1871 		iommufd_device_detach(sobj->idev.idev, cmd->pasid_attach.pasid);
1872 
1873 out_sobj:
1874 	iommufd_put_object(ucmd->ictx, &sobj->obj);
1875 	return rc;
1876 }
1877 
1878 static int iommufd_test_pasid_replace(struct iommufd_ucmd *ucmd,
1879 				      struct iommu_test_cmd *cmd)
1880 {
1881 	struct selftest_obj *sobj;
1882 	int rc;
1883 
1884 	sobj = iommufd_test_get_selftest_obj(ucmd->ictx, cmd->id);
1885 	if (IS_ERR(sobj))
1886 		return PTR_ERR(sobj);
1887 
1888 	rc = iommufd_device_replace(sobj->idev.idev, cmd->pasid_attach.pasid,
1889 				    &cmd->pasid_attach.pt_id);
1890 	if (rc)
1891 		goto out_sobj;
1892 
1893 	rc = iommufd_ucmd_respond(ucmd, sizeof(*cmd));
1894 
1895 out_sobj:
1896 	iommufd_put_object(ucmd->ictx, &sobj->obj);
1897 	return rc;
1898 }
1899 
1900 static int iommufd_test_pasid_detach(struct iommufd_ucmd *ucmd,
1901 				     struct iommu_test_cmd *cmd)
1902 {
1903 	struct selftest_obj *sobj;
1904 
1905 	sobj = iommufd_test_get_selftest_obj(ucmd->ictx, cmd->id);
1906 	if (IS_ERR(sobj))
1907 		return PTR_ERR(sobj);
1908 
1909 	iommufd_device_detach(sobj->idev.idev, cmd->pasid_detach.pasid);
1910 	iommufd_put_object(ucmd->ictx, &sobj->obj);
1911 	return 0;
1912 }
1913 
1914 void iommufd_selftest_destroy(struct iommufd_object *obj)
1915 {
1916 	struct selftest_obj *sobj = to_selftest_obj(obj);
1917 
1918 	switch (sobj->type) {
1919 	case TYPE_IDEV:
1920 		iommufd_device_detach(sobj->idev.idev, IOMMU_NO_PASID);
1921 		iommufd_device_unbind(sobj->idev.idev);
1922 		mock_dev_destroy(sobj->idev.mock_dev);
1923 		break;
1924 	}
1925 }
1926 
1927 struct iommufd_test_dma_buf {
1928 	void *memory;
1929 	size_t length;
1930 	bool revoked;
1931 };
1932 
1933 static int iommufd_test_dma_buf_attach(struct dma_buf *dmabuf,
1934 				       struct dma_buf_attachment *attachment)
1935 {
1936 	return 0;
1937 }
1938 
1939 static void iommufd_test_dma_buf_detach(struct dma_buf *dmabuf,
1940 					struct dma_buf_attachment *attachment)
1941 {
1942 }
1943 
1944 static struct sg_table *
1945 iommufd_test_dma_buf_map(struct dma_buf_attachment *attachment,
1946 			 enum dma_data_direction dir)
1947 {
1948 	return ERR_PTR(-EOPNOTSUPP);
1949 }
1950 
1951 static void iommufd_test_dma_buf_unmap(struct dma_buf_attachment *attachment,
1952 				       struct sg_table *sgt,
1953 				       enum dma_data_direction dir)
1954 {
1955 }
1956 
1957 static void iommufd_test_dma_buf_release(struct dma_buf *dmabuf)
1958 {
1959 	struct iommufd_test_dma_buf *priv = dmabuf->priv;
1960 
1961 	kfree(priv->memory);
1962 	kfree(priv);
1963 }
1964 
1965 static const struct dma_buf_ops iommufd_test_dmabuf_ops = {
1966 	.attach = iommufd_test_dma_buf_attach,
1967 	.detach = iommufd_test_dma_buf_detach,
1968 	.map_dma_buf = iommufd_test_dma_buf_map,
1969 	.release = iommufd_test_dma_buf_release,
1970 	.unmap_dma_buf = iommufd_test_dma_buf_unmap,
1971 };
1972 
1973 int iommufd_test_dma_buf_iommufd_map(struct dma_buf_attachment *attachment,
1974 				     struct phys_vec *phys)
1975 {
1976 	struct iommufd_test_dma_buf *priv = attachment->dmabuf->priv;
1977 
1978 	dma_resv_assert_held(attachment->dmabuf->resv);
1979 
1980 	if (attachment->dmabuf->ops != &iommufd_test_dmabuf_ops)
1981 		return -EOPNOTSUPP;
1982 
1983 	if (priv->revoked)
1984 		return -ENODEV;
1985 
1986 	phys->paddr = virt_to_phys(priv->memory);
1987 	phys->len = priv->length;
1988 	return 0;
1989 }
1990 
1991 static int iommufd_test_dmabuf_get(struct iommufd_ucmd *ucmd,
1992 				   unsigned int open_flags,
1993 				   size_t len)
1994 {
1995 	DEFINE_DMA_BUF_EXPORT_INFO(exp_info);
1996 	struct iommufd_test_dma_buf *priv;
1997 	struct dma_buf *dmabuf;
1998 	int rc;
1999 
2000 	len = ALIGN(len, PAGE_SIZE);
2001 	if (len == 0 || len > PAGE_SIZE * 512)
2002 		return -EINVAL;
2003 
2004 	priv = kzalloc_obj(*priv);
2005 	if (!priv)
2006 		return -ENOMEM;
2007 
2008 	priv->length = len;
2009 	priv->memory = kzalloc(len, GFP_KERNEL);
2010 	if (!priv->memory) {
2011 		rc = -ENOMEM;
2012 		goto err_free;
2013 	}
2014 
2015 	exp_info.ops = &iommufd_test_dmabuf_ops;
2016 	exp_info.size = len;
2017 	exp_info.flags = open_flags;
2018 	exp_info.priv = priv;
2019 
2020 	dmabuf = dma_buf_export(&exp_info);
2021 	if (IS_ERR(dmabuf)) {
2022 		rc = PTR_ERR(dmabuf);
2023 		goto err_free;
2024 	}
2025 
2026 	return dma_buf_fd(dmabuf, open_flags);
2027 
2028 err_free:
2029 	kfree(priv->memory);
2030 	kfree(priv);
2031 	return rc;
2032 }
2033 
2034 static int iommufd_test_dmabuf_revoke(struct iommufd_ucmd *ucmd, int fd,
2035 				      bool revoked)
2036 {
2037 	struct iommufd_test_dma_buf *priv;
2038 	struct dma_buf *dmabuf;
2039 	int rc = 0;
2040 
2041 	dmabuf = dma_buf_get(fd);
2042 	if (IS_ERR(dmabuf))
2043 		return PTR_ERR(dmabuf);
2044 
2045 	if (dmabuf->ops != &iommufd_test_dmabuf_ops) {
2046 		rc = -EOPNOTSUPP;
2047 		goto err_put;
2048 	}
2049 
2050 	priv = dmabuf->priv;
2051 	dma_resv_lock(dmabuf->resv, NULL);
2052 	priv->revoked = revoked;
2053 	dma_buf_invalidate_mappings(dmabuf);
2054 	dma_resv_unlock(dmabuf->resv);
2055 
2056 err_put:
2057 	dma_buf_put(dmabuf);
2058 	return rc;
2059 }
2060 
2061 int iommufd_test(struct iommufd_ucmd *ucmd)
2062 {
2063 	struct iommu_test_cmd *cmd = ucmd->cmd;
2064 
2065 	switch (cmd->op) {
2066 	case IOMMU_TEST_OP_ADD_RESERVED:
2067 		return iommufd_test_add_reserved(ucmd, cmd->id,
2068 						 cmd->add_reserved.start,
2069 						 cmd->add_reserved.length);
2070 	case IOMMU_TEST_OP_MOCK_DOMAIN:
2071 	case IOMMU_TEST_OP_MOCK_DOMAIN_FLAGS:
2072 		return iommufd_test_mock_domain(ucmd, cmd);
2073 	case IOMMU_TEST_OP_MOCK_DOMAIN_REPLACE:
2074 		return iommufd_test_mock_domain_replace(
2075 			ucmd, cmd->id, cmd->mock_domain_replace.pt_id, cmd);
2076 	case IOMMU_TEST_OP_MD_CHECK_MAP:
2077 		return iommufd_test_md_check_pa(
2078 			ucmd, cmd->id, cmd->check_map.iova,
2079 			cmd->check_map.length,
2080 			u64_to_user_ptr(cmd->check_map.uptr));
2081 	case IOMMU_TEST_OP_MD_CHECK_REFS:
2082 		return iommufd_test_md_check_refs(
2083 			ucmd, u64_to_user_ptr(cmd->check_refs.uptr),
2084 			cmd->check_refs.length, cmd->check_refs.refs);
2085 	case IOMMU_TEST_OP_MD_CHECK_IOTLB:
2086 		return iommufd_test_md_check_iotlb(ucmd, cmd->id,
2087 						   cmd->check_iotlb.id,
2088 						   cmd->check_iotlb.iotlb);
2089 	case IOMMU_TEST_OP_DEV_CHECK_CACHE:
2090 		return iommufd_test_dev_check_cache(ucmd, cmd->id,
2091 						    cmd->check_dev_cache.id,
2092 						    cmd->check_dev_cache.cache);
2093 	case IOMMU_TEST_OP_CREATE_ACCESS:
2094 		return iommufd_test_create_access(ucmd, cmd->id,
2095 						  cmd->create_access.flags);
2096 	case IOMMU_TEST_OP_ACCESS_REPLACE_IOAS:
2097 		return iommufd_test_access_replace_ioas(
2098 			ucmd, cmd->id, cmd->access_replace_ioas.ioas_id);
2099 	case IOMMU_TEST_OP_ACCESS_PAGES:
2100 		return iommufd_test_access_pages(
2101 			ucmd, cmd->id, cmd->access_pages.iova,
2102 			cmd->access_pages.length,
2103 			u64_to_user_ptr(cmd->access_pages.uptr),
2104 			cmd->access_pages.flags);
2105 	case IOMMU_TEST_OP_ACCESS_RW:
2106 		return iommufd_test_access_rw(
2107 			ucmd, cmd->id, cmd->access_rw.iova,
2108 			cmd->access_rw.length,
2109 			u64_to_user_ptr(cmd->access_rw.uptr),
2110 			cmd->access_rw.flags);
2111 	case IOMMU_TEST_OP_DESTROY_ACCESS_PAGES:
2112 		return iommufd_test_access_item_destroy(
2113 			ucmd, cmd->id, cmd->destroy_access_pages.access_pages_id);
2114 	case IOMMU_TEST_OP_SET_TEMP_MEMORY_LIMIT:
2115 		/* Protect _batch_init(), can not be less than elmsz */
2116 		if (cmd->memory_limit.limit <
2117 		    sizeof(unsigned long) + sizeof(u32))
2118 			return -EINVAL;
2119 		iommufd_test_memory_limit = cmd->memory_limit.limit;
2120 		return 0;
2121 	case IOMMU_TEST_OP_DIRTY:
2122 		return iommufd_test_dirty(ucmd, cmd->id, cmd->dirty.iova,
2123 					  cmd->dirty.length,
2124 					  cmd->dirty.page_size,
2125 					  u64_to_user_ptr(cmd->dirty.uptr),
2126 					  cmd->dirty.flags);
2127 	case IOMMU_TEST_OP_TRIGGER_IOPF:
2128 		return iommufd_test_trigger_iopf(ucmd, cmd);
2129 	case IOMMU_TEST_OP_TRIGGER_VEVENT:
2130 		return iommufd_test_trigger_vevent(ucmd, cmd);
2131 	case IOMMU_TEST_OP_PASID_ATTACH:
2132 		return iommufd_test_pasid_attach(ucmd, cmd);
2133 	case IOMMU_TEST_OP_PASID_REPLACE:
2134 		return iommufd_test_pasid_replace(ucmd, cmd);
2135 	case IOMMU_TEST_OP_PASID_DETACH:
2136 		return iommufd_test_pasid_detach(ucmd, cmd);
2137 	case IOMMU_TEST_OP_PASID_CHECK_HWPT:
2138 		return iommufd_test_pasid_check_hwpt(ucmd, cmd);
2139 	case IOMMU_TEST_OP_DMABUF_GET:
2140 		return iommufd_test_dmabuf_get(ucmd, cmd->dmabuf_get.open_flags,
2141 					       cmd->dmabuf_get.length);
2142 	case IOMMU_TEST_OP_DMABUF_REVOKE:
2143 		return iommufd_test_dmabuf_revoke(ucmd,
2144 						  cmd->dmabuf_revoke.dmabuf_fd,
2145 						  cmd->dmabuf_revoke.revoked);
2146 	default:
2147 		return -EOPNOTSUPP;
2148 	}
2149 }
2150 
2151 bool iommufd_should_fail(void)
2152 {
2153 	return should_fail(&fail_iommufd, 1);
2154 }
2155 
2156 int __init iommufd_test_init(void)
2157 {
2158 	struct platform_device_info pdevinfo = {
2159 		.name = "iommufd_selftest_iommu",
2160 	};
2161 	int rc;
2162 
2163 	dbgfs_root =
2164 		fault_create_debugfs_attr("fail_iommufd", NULL, &fail_iommufd);
2165 
2166 	selftest_iommu_dev = platform_device_register_full(&pdevinfo);
2167 	if (IS_ERR(selftest_iommu_dev)) {
2168 		rc = PTR_ERR(selftest_iommu_dev);
2169 		goto err_dbgfs;
2170 	}
2171 
2172 	rc = bus_register(&iommufd_mock_bus_type.bus);
2173 	if (rc)
2174 		goto err_platform;
2175 
2176 	rc = iommu_device_sysfs_add(&mock_iommu.iommu_dev,
2177 				    &selftest_iommu_dev->dev, NULL, "%s",
2178 				    dev_name(&selftest_iommu_dev->dev));
2179 	if (rc)
2180 		goto err_bus;
2181 
2182 	rc = iommu_device_register_bus(&mock_iommu.iommu_dev, &mock_ops,
2183 				       &iommufd_mock_bus_type.bus,
2184 				       &iommufd_mock_bus_type.nb);
2185 	if (rc)
2186 		goto err_sysfs;
2187 
2188 	refcount_set(&mock_iommu.users, 1);
2189 	init_completion(&mock_iommu.complete);
2190 
2191 	mock_iommu_iopf_queue = iopf_queue_alloc("mock-iopfq");
2192 	mock_iommu.iommu_dev.max_pasids = (1 << MOCK_PASID_WIDTH);
2193 
2194 	return 0;
2195 
2196 err_sysfs:
2197 	iommu_device_sysfs_remove(&mock_iommu.iommu_dev);
2198 err_bus:
2199 	bus_unregister(&iommufd_mock_bus_type.bus);
2200 err_platform:
2201 	platform_device_unregister(selftest_iommu_dev);
2202 err_dbgfs:
2203 	debugfs_remove_recursive(dbgfs_root);
2204 	return rc;
2205 }
2206 
2207 static void iommufd_test_wait_for_users(void)
2208 {
2209 	if (refcount_dec_and_test(&mock_iommu.users))
2210 		return;
2211 	/*
2212 	 * Time out waiting for iommu device user count to become 0.
2213 	 *
2214 	 * Note that this is just making an example here, since the selftest is
2215 	 * built into the iommufd module, i.e. it only unplugs the iommu device
2216 	 * when unloading the module. So, it is expected that this WARN_ON will
2217 	 * not trigger, as long as any iommufd FDs are open.
2218 	 */
2219 	WARN_ON(!wait_for_completion_timeout(&mock_iommu.complete,
2220 					     msecs_to_jiffies(10000)));
2221 }
2222 
2223 void iommufd_test_exit(void)
2224 {
2225 	if (mock_iommu_iopf_queue) {
2226 		iopf_queue_free(mock_iommu_iopf_queue);
2227 		mock_iommu_iopf_queue = NULL;
2228 	}
2229 
2230 	iommufd_test_wait_for_users();
2231 	iommu_device_sysfs_remove(&mock_iommu.iommu_dev);
2232 	iommu_device_unregister_bus(&mock_iommu.iommu_dev,
2233 				    &iommufd_mock_bus_type.bus,
2234 				    &iommufd_mock_bus_type.nb);
2235 	bus_unregister(&iommufd_mock_bus_type.bus);
2236 	platform_device_unregister(selftest_iommu_dev);
2237 	debugfs_remove_recursive(dbgfs_root);
2238 }
2239 
2240 MODULE_IMPORT_NS("GENERIC_PT_IOMMU");
2241