Skip to contentSkip to conversation

nvmem: fix cell write clobber of outside bits

PATCH New Michael Lotz 1 participant 1 message Feb 4 NVMEM framework

lore
Share & tools
lore
#0 lore raw

PATCH 1/1 nvmem: fix cell write clobber of outside bits

When a nvmem cell uses bits and does not end on a byte boundary, the missing upper bits are filled by reading the pre-existing value. These are masked and or-ed with the value in the write buffer, which comes from the user provided input buffer. However, when the input buffer has bits set outside the bit width of the cell, those were never cleared. That allowed a nvmem cell write to clobber the remaining upper bits of the last byte.

Example cell declaration:

    status@0 {
        reg = <0x0 0x1>;
        bits = <2 2>;
    };
Existing value:  0x10
Write value:     0xff
Expected result: 0x1c
Actual result:   0xfc

Fix this by first clearing the bits of the write buffer that are outside of the cell and only then or-ing the pre-existing value.

---
 drivers/nvmem/core.c | 6 ++++--
 1 file changed, 4 insertions(+), 2 deletions(-)
drivers/nvmem/core.c +4 -2
index 387c88c55259..25184f75b9ea 100644
@@ -1709,7 +1709,7 @@ static void *nvmem_cell_prepare_write_buffer(struct nvmem_cell_entry *cell,
 {
 	struct nvmem_device *nvmem = cell->nvmem;
 	int i, rc, nbits, bit_offset = cell->bit_offset;
-	u8 v, *p, *buf, *b, pbyte, pbits;
+	u8 v, *p, *buf, *b, pbyte, pbits, mask;
 
 	nbits = cell->nbits;
 	buf = kzalloc(cell->bytes, GFP_KERNEL);
@@ -1747,8 +1747,10 @@ static void *nvmem_cell_prepare_write_buffer(struct nvmem_cell_entry *cell,
 				    cell->offset + cell->bytes - 1, &v, 1);
 		if (rc)
 			goto err;
-		*p |= GENMASK(7, (nbits + bit_offset) % BITS_PER_BYTE) & v;
 
+		mask = GENMASK(7, (nbits + bit_offset) % BITS_PER_BYTE);
+		*p &= ~mask;
+		*p |= v & mask;
 	}
 
 	return buf;
Signature · 1 line
2.43.0