Re: [PATCH 1/2] mm: introduce mmap_lock_speculation_{start|end}
From: Jann Horn
Date: Tue Sep 10 2024 - 11:32:18 EST
On Tue, Sep 10, 2024 at 4:09 AM Suren Baghdasaryan <surenb@xxxxxxxxxx> wrote:
> On Mon, Sep 9, 2024 at 5:35 AM Jann Horn <jannh@xxxxxxxxxx> wrote:
> > On Fri, Sep 6, 2024 at 7:12 AM Andrii Nakryiko <andrii@xxxxxxxxxx> wrote:
> > > static inline void mmap_write_lock(struct mm_struct *mm)
> > > {
> > > __mmap_lock_trace_start_locking(mm, true);
> > > down_write(&mm->mmap_lock);
> > > + inc_mm_lock_seq(mm);
> > > __mmap_lock_trace_acquire_returned(mm, true, true);
> > > }
> >
> > Similarly, inc_mm_lock_seq(), which does a store-release, can only
> > provide "release lock" semantics, not "take lock" semantics, because
> > the CPU can reorder it with later stores; for example, this code:
> >
> > inc_mm_lock_seq()
> > [locked stuff goes here]
> > inc_mm_lock_seq()
> >
> > can be reordered into this:
> >
> > [locked stuff goes here]
> > inc_mm_lock_seq()
> > inc_mm_lock_seq()
> >
> > so the lock is broken.
>
> Ugh, yes. We do need smp_wmb() AFTER the inc_mm_lock_seq(). Whenever
> we use inc_mm_lock_seq() for "take lock" semantics, it's preceded by a
> down_write(&mm->mmap_lock) with implied ACQUIRE ordering. So I thought
> we can use it but I realize now that this reordering is still
> possible:
> CPU1 CPU2
> mmap_write_lock()
> down_write(&mm->mmap_lock);
> vma->vm_file = ...;
>
> mmap_lock_speculation_start() // seq = mm->mm_lock_seq
> <speculate>
> mmap_lock_speculation_end() // return (mm->mm_lock_seq == seq)
>
> inc_mm_lock_seq(mm);
> mmap_write_unlock() // inc_mm_lock_seq(mm)
>
> Is that what you were describing?
Yeah, that's the scenario I was thinking of (though I did not spend
the time to look at the surroundings to see if there are other implied
barriers that happen to stop this).