A cell with a bits property is narrower than the bytes nvmem_cell_read() returns and nvmem_cell_write() doesn't mask the value written to it, so anything that doesn't fit spills into the neighbouring bits.
A consumer that computes the value it writes back, like a counter, thus needs to know the width of the cell. Let's add a helper that returns it. Assisted-by: Claude:opus-5.5 Signed-off-by: Ahmad Fatoum <[email protected]> --- drivers/nvmem/core.c | 16 ++++++++++++++++ include/linux/nvmem-consumer.h | 6 ++++++ 2 files changed, 22 insertions(+) diff --git a/drivers/nvmem/core.c b/drivers/nvmem/core.c index 79a36bb9b996..9fb7049c0116 100644 --- a/drivers/nvmem/core.c +++ b/drivers/nvmem/core.c @@ -928,6 +928,22 @@ void *nvmem_cell_read(struct nvmem_cell *cell, size_t *len) } EXPORT_SYMBOL_GPL(nvmem_cell_read); +/** + * nvmem_cell_nbits() - Get the width of a nvmem cell in bits + * + * @cell: nvmem cell to be queried. + * + * Return: the number of bits in the cell, which can be less than its size in + * bytes times 8 if the cell has a bits property. + */ +unsigned int nvmem_cell_nbits(struct nvmem_cell *cell) +{ + struct nvmem_cell_entry *entry = cell->entry; + + return entry->nbits ?: entry->bytes * BITS_PER_BYTE; +} +EXPORT_SYMBOL_GPL(nvmem_cell_nbits); + static inline const void *nvmem_cell_prepare_write_buffer(struct nvmem_cell_entry *cell, const u8 *_buf, int len) { diff --git a/include/linux/nvmem-consumer.h b/include/linux/nvmem-consumer.h index ff9b87442852..efce9bb0e593 100644 --- a/include/linux/nvmem-consumer.h +++ b/include/linux/nvmem-consumer.h @@ -28,6 +28,7 @@ extern struct class nvmem_class; struct nvmem_cell *nvmem_cell_get(struct device *dev, const char *name); void nvmem_cell_put(struct nvmem_cell *cell); void *nvmem_cell_read(struct nvmem_cell *cell, size_t *len); +unsigned int nvmem_cell_nbits(struct nvmem_cell *cell); void *nvmem_cell_get_and_read(struct device_node *np, const char *cell_name, size_t bytes); int nvmem_cell_read_variable_le_u32(struct device *dev, const char *cell_id, @@ -68,6 +69,11 @@ static inline char *nvmem_cell_read(struct nvmem_cell *cell, size_t *len) return ERR_PTR(-EOPNOTSUPP); } +static inline unsigned int nvmem_cell_nbits(struct nvmem_cell *cell) +{ + return 0; +} + static inline void *nvmem_cell_get_and_read(struct device_node *np, const char *cell_name, size_t bytes) -- 2.47.3
