Re: [PATCH 1/2] mm/ksm: Reset KSM counters in mm_struct during fork

From: David Hildenbrand
Date: Tue Aug 26 2025 - 10:22:19 EST


On 26.08.25 15:47, Giorgi Tchankvetadze wrote:
What if we only allocate KSM stats when a process actually uses KSM?

struct ksm_mm_stats {
atomic_long_t merging_pages;
atomic_long_t rmap_items;
atomic_long_t zero_pages;
};
struct ksm_mm_stats *mm->ksm_stats; // NULL until first enter

static inline struct ksm_mm_stats *mm_get_ksm_stats(struct mm_struct *mm)
{
if (likely(mm->ksm_stats))
return mm->ksm_stats;
return ksm_alloc_stats_if_needed(mm); // Slow path
}

The fork'ed child uses KSM. It just doesn't have any stable rmap entries.

We have to copy the zero_pages counter such that ksm_might_unmap_zero_page() will do the right thing.

But you're comment made me realize that there is likely another bug:

When copying zero_pages during fork(), we have to increment &ksm_zero_pages as well. Otherwise we will get an underflow later.

@Donet, can you look into that as well?

--
Cheers

David / dhildenb