When mprotect() of a shared hugetlb mapping races with a hugetlb fault in another process that can share the same PMD table, we can end up with page table entries that don't match the VMA flags, such as writable ones in a PROT_READ mapping or PROT_NONE ones in accessible VMAs. huge_pmd_share() takes i_mmap_rwsem and shares a PMD table if the flags of the two VMAs match, so while that lock is held the entries in a table have to match the flags of its VMA. However, mprotect_fixup() stores the new flags without i_mmap_rwsem, and only hugetlb_change_protection() takes it. A fault in between shares a table that still has the old entries, and the walk then unshares the table instead of changing them: process A process C VMA is RW, entries are RW VMA is R, PUD is empty ========================= ====================== mprotect_fixup() VMA flags = R huge_pmd_share() i_mmap_lock_read() flags match, take A's table i_mmap_unlock_read() hugetlb_change_protection() i_mmap_lock_write() huge_pmd_unshare() clear A's PUD, return 1 skip the entries VMA is R, entries are RW mprotect() changes both the flags and the entries while holding the mmap lock in write mode. Let's fix it by only sharing the page tables of another VMA if we can try-read-lock the mmap lock of its mm. If the trylock fails, we simply try the next VMA, or allocate our own page table. A trylock is fine, as we hold i_mmap_rwsem, which is usually taken under the mmap lock. We should use the VMA lock instead, but we'll do that separately. This has medium urgency, as it can result in endless page fault loops if mprotect() races with PMD table sharing and we end up with PROT_NONE entries in accessible VMAs. If the kernel accesses such memory, for example in copy_to_user(), the loop happens in the kernel and the task cannot be killed. Fixes: 39dde65c9940 ("[PATCH] shared page table for hugetlb page") Cc: Reported-by: Chris Mason Signed-off-by: David Hildenbrand (Arm) --- mm/hugetlb.c | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/mm/hugetlb.c b/mm/hugetlb.c index 2c13349863bd8..0b0f6e17b8b06 100644 --- a/mm/hugetlb.c +++ b/mm/hugetlb.c @@ -7264,15 +7264,23 @@ pte_t *huge_pmd_share(struct mm_struct *mm, struct vm_area_struct *vma, if (svma == vma) continue; + /* + * Stabilize the svma flags, as mprotect() changes flags + * before adjusting page tables. + */ + if (!mmap_read_trylock(svma->vm_mm)) + continue; + saddr = page_table_shareable(svma, vma, addr, idx); if (saddr) { spte = hugetlb_walk(svma, saddr, vma_mmu_pagesize(svma)); - if (spte) { + if (spte) ptdesc_pmd_pts_inc(virt_to_ptdesc(spte)); - break; - } } + mmap_read_unlock(svma->vm_mm); + if (spte) + break; } if (!spte) -- 2.56.1