Re: [PATCH] nvmem: keep write protection disabled while writers are active
From: James Hilliard
Date: Thu Nov 19 2026 - 12:14:27 EST
On Thu, Nov 19, 2026 at 6:25 AM Bartosz Golaszewski <brgl@xxxxxxxxxx> wrote:
>
> On Tue, Nov 17, 2026 at 03:09:08PM -0700, James Hilliard wrote:
> > The core deasserts the WP GPIO before calling the provider and asserts
> > it again on return. Two concurrent writes can both deassert WP before
> > the first one finishes. That writer then protects the device while the
> > other is still writing or waiting for the provider lock.
> >
> > Count active writers per device under a mutex. Only the first writer
> > deasserts WP and only the last one restores it, including on provider
> > errors. Keep the mutex outside the provider callback so providers that
> > forward writes to another NVMEM device can still nest.
> >
> > Fixes: 2a127da461a9 ("nvmem: add support for the write-protect pin")
> > Cc: stable@xxxxxxxxxxxxxxx
> > Link: https://lore.kernel.org/r/sashiko-outbox-219526@xxxxxxxxxx/
> > Signed-off-by: James Hilliard <james.hilliard1@xxxxxxxxx>
> > ---
>
> This adds a mutex where there was previously none in nvmem core.
> Synchronization was left to the underlying providers.
>
> Can we not use atomic ops and avoid the mutex? I'm talking about
> something like:
There's a race on the first write as well. The first writer can
increment the count from 0 to 1 and be preempted before it deasserts
WP. A second writer then sees a nonzero count, skips the GPIO call
and enters the provider's write callback while WP is still asserted.
>
> if (atomic_fetch_inc(nvmem->wp_cnt) == 0)
> gpiod_set_value_cansleep(nvmem->wp_gpio, 0);
>
> if (atomic_dec_return(nvmem->wp_cnt) == 0)
> gpiod_set_value_cansleep(nvmem->wp_gpio, 1);
>
> The only problem here is when we put the last reference, start setting
> the value to 1 to enable WP, while another writer bumps it back up and
> we drive WP pin back low. But then we expect the GPIO chip driver to
> handle synchronization in this case.
The GPIO driver can serialize both calls and still execute them in
the wrong order. If the last writer drops the count to zero and is
preempted, a new writer can deassert WP and start writing. The old
writer can then resume and assert WP in the middle of that write.
The mutex keeps the count change and the GPIO transition together.
It's released before calling the provider, so it doesn't serialize
the writes themselves.
>
> Bart