xref: /linux/tools/testing/selftests/vfio/lib/include/libvfio/iommu.h (revision b61104e7a6349bd2c2b3e2fb3260d87f15eda8f4)
1 /* SPDX-License-Identifier: GPL-2.0-only */
2 #ifndef SELFTESTS_VFIO_LIB_INCLUDE_LIBVFIO_IOMMU_H
3 #define SELFTESTS_VFIO_LIB_INCLUDE_LIBVFIO_IOMMU_H
4 
5 #include <linux/list.h>
6 #include <linux/types.h>
7 
8 #include <libvfio/assert.h>
9 
10 typedef u64 iova_t;
11 
12 struct iommu_mode {
13 	const char *name;
14 	const char *container_path;
15 	unsigned long iommu_type;
16 };
17 
18 extern const char *default_iommu_mode;
19 
20 struct dma_region {
21 	struct list_head link;
22 	void *vaddr;
23 	iova_t iova;
24 	u64 size;
25 };
26 
27 struct iommu {
28 	const struct iommu_mode *mode;
29 	int container_fd;
30 	int iommufd;
31 	u32 ioas_id;
32 	struct list_head dma_regions;
33 };
34 
35 struct iommu *iommu_init(const char *iommu_mode);
36 void iommu_cleanup(struct iommu *iommu);
37 
38 int __iommu_map(struct iommu *iommu, struct dma_region *region);
39 
40 static inline void iommu_map(struct iommu *iommu, struct dma_region *region)
41 {
42 	VFIO_ASSERT_EQ(__iommu_map(iommu, region), 0);
43 }
44 
45 int __iommu_unmap(struct iommu *iommu, struct dma_region *region, u64 *unmapped);
46 
47 static inline void iommu_unmap(struct iommu *iommu, struct dma_region *region)
48 {
49 	VFIO_ASSERT_EQ(__iommu_unmap(iommu, region, NULL), 0);
50 }
51 
52 int __iommu_unmap_all(struct iommu *iommu, u64 *unmapped);
53 
54 static inline void iommu_unmap_all(struct iommu *iommu)
55 {
56 	VFIO_ASSERT_EQ(__iommu_unmap_all(iommu, NULL), 0);
57 }
58 
59 int __iommu_hva2iova(struct iommu *iommu, void *vaddr, iova_t *iova);
60 iova_t iommu_hva2iova(struct iommu *iommu, void *vaddr);
61 
62 struct iommu_iova_range *iommu_iova_ranges(struct iommu *iommu, u32 *nranges);
63 
64 /*
65  * Generator for VFIO selftests fixture variants that replicate across all
66  * possible IOMMU modes. Tests must define FIXTURE_VARIANT_ADD_IOMMU_MODE()
67  * which should then use FIXTURE_VARIANT_ADD() to create the variant.
68  */
69 #define FIXTURE_VARIANT_ADD_ALL_IOMMU_MODES(...) \
70 FIXTURE_VARIANT_ADD_IOMMU_MODE(vfio_type1_iommu, ##__VA_ARGS__); \
71 FIXTURE_VARIANT_ADD_IOMMU_MODE(vfio_type1v2_iommu, ##__VA_ARGS__); \
72 FIXTURE_VARIANT_ADD_IOMMU_MODE(iommufd_compat_type1, ##__VA_ARGS__); \
73 FIXTURE_VARIANT_ADD_IOMMU_MODE(iommufd_compat_type1v2, ##__VA_ARGS__); \
74 FIXTURE_VARIANT_ADD_IOMMU_MODE(iommufd, ##__VA_ARGS__)
75 
76 #endif /* SELFTESTS_VFIO_LIB_INCLUDE_LIBVFIO_IOMMU_H */
77