iopt_map_file_pages() stores a reference to the file passed to IOMMU_IOAS_MAP_FILE in the iopt_pages of the new mapping: iopt_map_file_pages() iopt_alloc_file_pages() pages->file = get_file(file) iopt_release_pages() drops that reference only when the iopt_pages is destroyed, which for a file mapping happens while the iommufd file is being torn down. Nothing restricts which file can be passed, so userspace can map the iommufd file itself, or a vfio device fd bound to the same iommufd, both of which own an iommufd_ctx reference. The reference graph then contains a cycle and the file, the iopt_pages, the IOAS and the iommufd_ctx are all leaked; kmemleak reports it as "memory leak in path_openat" with the holder taken through iopt_map_file_pages(). Reverse the test instead of trying to enumerate the files that own an iommufd_ctx: accept only the files that memfd_pin_folios() is able to pin, which is exactly the set of files the mapping can be built from. file_is_memfd_compatible() reports that set, so the same test can run here before the reference is handed to iopt_pages. dma-bufs are unaffected: they are taken by the dma_buf_get() branch above and never reach the file branch, and iopt_pages holds the dma_buf there, not a struct file. Fixes: f4986a72d6e4 ("iommufd: Add IOMMU_IOAS_MAP_FILE") Reported-by: syzbot+7666ed2c3d42196bf7e3@syzkaller.appspotmail.com Closes: https://syzkaller.appspot.com/bug?extid=7666ed2c3d42196bf7e3 Signed-off-by: Jiahao Xu --- v2: - Call an exported mm helper instead of shmem_file(): shmem_file() became an out-of-line function in mm/shmem.c that is not exported, so calling it from iommufd.ko failed at modpost with "symbol 'shmem_file' undefined!". Reported by Jason Gunthorpe. - Use file_is_memfd_compatible(), renamed from memfd_pin_folios_supported() as suggested by David Hildenbrand. v1: https://lore.kernel.org/all/20261119104417.459962-1-xujiahao@cmss.chinamobile.com/ --- drivers/iommu/iommufd/io_pagetable.c | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/drivers/iommu/iommufd/io_pagetable.c b/drivers/iommu/iommufd/io_pagetable.c index 5ac736cf5..c9aad275f 100644 --- a/drivers/iommu/iommufd/io_pagetable.c +++ b/drivers/iommu/iommufd/io_pagetable.c @@ -515,6 +515,18 @@ int iopt_map_file_pages(struct iommufd_ctx *ictx, struct io_pagetable *iopt, if (!file) return -EBADF; + /* + * iopt_pages keeps a reference to the file until the mapping is + * destroyed, so only accept the files memfd_pin_folios() is able + * to pin. Any other fd, in particular one that itself owns an + * iommufd_ctx (iommufd, vfio, ...), would put the file into a + * reference cycle with this iommufd and never be released. + */ + if (!file_is_memfd_compatible(file)) { + fput(file); + return -EINVAL; + } + pages = iopt_alloc_file_pages(file, start_byte, start, length, iommu_prot & IOMMU_WRITE); fput(file); -- 2.43.0