[PATCH 05/10] nvmem: core: Serialise writes when toggling the write-protect GPIO

From: Lee Jones

Date: Thu Dec 03 2026 - 03:26:45 EST


nvmem_access_chunk() deasserts nvmem->wp_gpio, calls ops->reg_write(),
and re-asserts nvmem->wp_gpio while callers hold only the shared SRCU
read lock. Concurrent writers can therefore overlap, allowing one
writer to re-assert write protection while another writer is still
executing ops->reg_write().

Add a per-device wp_lock mutex to struct nvmem_device and hold it
across the WP GPIO deassert, ops->reg_write(), and WP GPIO re-assert
sequence whenever nvmem->wp_gpio is present.

Fixes: 2a127da461a9 ("nvmem: add support for the write-protect pin")
Closes: https://sashiko.dev/#/bug/linux-d7d845df-786a-40cf-b43c-f4ce2e295c82
Cc: stable@xxxxxxxxxxxxxxx
Signed-off-by: Lee Jones <lee@xxxxxxxxxx>
---

Cc: Bartosz Golaszewski <bartosz.golaszewski@xxxxxxxxxxxxxxxx>
Cc: Greg Kroah-Hartman <gregkh@xxxxxxxxxxxxxxxxxxx>
Cc: Khouloud Touil <ktouil@xxxxxxxxxxxx>
Cc: Linus Walleij <linusw@xxxxxxxxxx>
Cc: Maxime Ripard <mripard@xxxxxxxxxx>
Cc: Srinivas Kandagatla <srini@xxxxxxxxxx>

drivers/nvmem/core.c | 7 +++++++
drivers/nvmem/internals.h | 2 ++
2 files changed, 9 insertions(+)

diff --git a/drivers/nvmem/core.c b/drivers/nvmem/core.c
index e7c687cb6ce6..2ba1ab037907 100644
--- a/drivers/nvmem/core.c
+++ b/drivers/nvmem/core.c
@@ -70,6 +70,11 @@ static int nvmem_access_chunk(struct nvmem_device *nvmem,
if (!ops->reg_write)
return -EOPNOTSUPP;

+ if (!nvmem->wp_gpio)
+ return ops->reg_write(nvmem->priv, offset, val, bytes);
+
+ guard(mutex)(&nvmem->wp_lock);
+
ret = gpiod_set_value_cansleep(nvmem->wp_gpio, 0);
if (ret)
return ret;
@@ -574,6 +579,7 @@ static void nvmem_release(struct device *dev)
nvmem_device_remove_all_cells(nvmem);
ida_free(&nvmem_ida, nvmem->id);
of_node_put(nvmem->dev.of_node);
+ mutex_destroy(&nvmem->wp_lock);
cleanup_srcu_struct(&nvmem->srcu);
kfree(nvmem);
}
@@ -983,6 +989,7 @@ struct nvmem_device *nvmem_register(const struct nvmem_config *config)
return ERR_PTR(rval);
}

+ mutex_init(&nvmem->wp_lock);
rcu_assign_pointer(nvmem->ops, ops);

device_initialize(&nvmem->dev);
diff --git a/drivers/nvmem/internals.h b/drivers/nvmem/internals.h
index bc7a99f5aefb..3d59ac799170 100644
--- a/drivers/nvmem/internals.h
+++ b/drivers/nvmem/internals.h
@@ -4,6 +4,7 @@
#define _LINUX_NVMEM_INTERNALS_H

#include <linux/device.h>
+#include <linux/mutex.h>
#include <linux/nvmem-consumer.h>
#include <linux/nvmem-provider.h>
#include <linux/srcu.h>
@@ -34,6 +35,7 @@ struct nvmem_device {
const struct nvmem_keepout *keepout;
unsigned int nkeepout;
struct gpio_desc *wp_gpio;
+ struct mutex wp_lock; /* serialises WP GPIO writes */
struct nvmem_layout *layout;
struct nvmem_operations __rcu *ops;
void *priv;
--
2.56.1.911.g883d8bcb20-goog