memfd_alloc_folio() uses hugetlb_reserve_pages() to reserve the index of the folio it is about to allocate. If allocating the folio or adding it to the page cache fails, it undoes that reservation, but only if hugetlb_reserve_pages() reported that it actually performed the reservation. If the index was already reserved, for example through an mmap() of the same file, memfd_alloc_folio() must not undo that reservation. However, if hugetlb_reserve_pages() races with another reservation for the same index, region_add_limited() can reserve fewer pages than region_chg() counted. hugetlb_reserve_pages() will then hand back the surplus charges, but still report the number of pages that region_chg() counted. Consequently, after racing with hugetlbfs_file_mmap() reserving the same index, memfd_alloc_folio() will undo the reservation of the mmap() caller on error, and a later fault at that index can fail with SIGBUS. Reproduced by artificially delaying hugetlb_reserve_pages() after region_chg() during IOMMU_IOAS_MAP_FILE of a hugetlb memfd, while another process mmap()s the memfd, and failing the page cache insertion with fault injection. Once all unreserved huge pages are in use, the mmap() caller gets SIGBUS on fault. Let's fix it by only reporting the reservations that we actually added. Other callers are not affected, as they only care about error vs. success, not the actual number of reserved pages. This has low urgency, as it requires an allocation failure after racing with an mmap() of the same file. Fixes: 717cf9357325 ("mm/memfd: reserve hugetlb folios before allocation") Reported-by: Sashiko Cc: stable@vger.kernel.org Signed-off-by: David Hildenbrand (Arm) --- mm/hugetlb.c | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/mm/hugetlb.c b/mm/hugetlb.c index 025aae6d0b72e..68d90c7297921 100644 --- a/mm/hugetlb.c +++ b/mm/hugetlb.c @@ -6907,9 +6907,9 @@ long hugetlb_change_protection(struct vm_area_struct *vma, /* * Update the reservation map for the range [from, to]. * - * Returns the number of entries that would be added to the reservation map - * associated with the range [from, to]. This number is greater or equal to - * zero. -EINVAL or -ENOMEM is returned in case of any errors. + * Returns the number of huge pages that we reserved in the range [from, to], + * or a negative error code. On a later error, callers must only undo + * these reservations, not reservations that already existed in the range. */ long hugetlb_reserve_pages(struct inode *inode, @@ -7052,6 +7052,11 @@ long hugetlb_reserve_pages(struct inode *inode, rsv_adjust = hugepage_subpool_put_pages(spool, chg - add); hugetlb_acct_memory(h, -rsv_adjust); + /* + * Only report the reservations that we added, such that + * callers will not undo the racing reservations. + */ + chg = add; } else if (h_cg) { /* * The file_regions will hold their own reference to -- 2.56.1