For valid ptes, cpu_v7_set_pte_ext() derives the hardware read-only bit PTE_AP2 from L_PTE_DIRTY and L_PTE_RDONLY. pte_wrprotect() and pte_mkclean() only change those software bits and leave PTE_AP2 as it is. Starting from a dirty, writable pte, the software value therefore has PTE_AP2 clear while the installed entry has it set. KSM hits this since commit c33c794828f2 ("mm: ptep_get() conversion"), which made write_protect_page() return the software value instead of reading the installed entry back. replace_page() then finds the stored entry different and gives up. After a failed zero-page merge, KSM can fall back to a regular merge in the same pass, so zero-filled pages end up as ordinary KSM pages instead of mapping the zero page. Mask PTE_AP2 like PTE_EXT_NG for present ptes. L_PTE_DIRTY and L_PTE_RDONLY are still compared, so changes to the dirty and write-permission state remain visible. Fixes: ded947798469 ("ARM: 8109/1: mm: Modify pte_write and pmd_write logic for LPAE") Signed-off-by: Karl Mehltretter --- Assisted by an LLM. Tested on v7.4-rc3, multi_v7_defconfig with ARM_LPAE and KSM, as a 32-bit guest in QEMU (TCG, cortex-a15) and under KVM on a Raspberry Pi 400 (Cortex-A72). 1024 zero-filled pages merged with use_zero_pages=1, and test_unmerge_zero_pages from tools/testing/selftests/mm/ksm_functional_tests: ksm_zero_pages test_unmerge_zero_pages v7.4-rc3 0 fails with this patch 1024 passes Unpatched v6.12 shows the same failure. If this is better handled in KSM, reading the entry back after set_pte_at() in write_protect_page(), as before c33c794828f2, also fixes it. arch/arm/include/asm/pgtable-3level.h | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/arch/arm/include/asm/pgtable-3level.h b/arch/arm/include/asm/pgtable-3level.h index 7b71a3d414b..4a187d7be1d 100644 --- a/arch/arm/include/asm/pgtable-3level.h +++ b/arch/arm/include/asm/pgtable-3level.h @@ -161,11 +161,15 @@ static inline pmd_t *pud_pgtable(pud_t pud) * * To correct this behaviour, we mask off PTE_EXT_NG for any pte that is * present before running the comparison. + * + * Likewise, cpu_v7_set_pte_ext() sets PTE_AP2 in a valid stored entry when + * the pte is clean or read-only. PTE_AP2 is derived from L_PTE_DIRTY and + * L_PTE_RDONLY, which are still compared, so mask it off as well. */ #define __HAVE_ARCH_PTE_SAME -#define pte_same(pte_a,pte_b) ((pte_present(pte_a) ? pte_val(pte_a) & ~PTE_EXT_NG \ +#define pte_same(pte_a, pte_b) ((pte_present(pte_a) ? pte_val(pte_a) & ~(PTE_EXT_NG | PTE_AP2) \ : pte_val(pte_a)) \ - == (pte_present(pte_b) ? pte_val(pte_b) & ~PTE_EXT_NG \ + == (pte_present(pte_b) ? pte_val(pte_b) & ~(PTE_EXT_NG | PTE_AP2) \ : pte_val(pte_b))) #define set_pte_ext(ptep,pte,ext) cpu_set_pte_ext(ptep,__pte(pte_val(pte)|(ext))) base-commit: aebb7274476403040d582c61478df8f4a7bf9cd3 -- 2.39.5 (Apple Git-154)