1 // SPDX-License-Identifier: GPL-2.0+
3 * (C) Copyright 2019 Collabora
4 * (C) Copyright 2019 GE
11 static const u8 bootcount_magic = 0xbc;
13 struct bootcount_spi_flash_priv {
14 struct udevice *spi_flash;
18 static int bootcount_spi_flash_update(struct udevice *dev, u32 offset, u32 len, const void *buf)
20 struct spi_flash *flash = dev_get_uclass_priv(dev);
21 u32 sector_size = flash->sector_size;
22 u32 sector_offset = offset % sector_size;
23 u32 sector = offset - sector_offset;
26 /* code only supports updating a single sector */
27 if (sector_offset + len > sector_size)
30 u8 *buffer = malloc(sector_size);
34 err = spi_flash_read_dm(dev, sector, sector_size, buffer);
38 memcpy(buffer + sector_offset, buf, len);
40 err = spi_flash_erase_dm(dev, sector, sector_size);
44 err = spi_flash_write_dm(dev, sector, sector_size, buffer);
53 static int bootcount_spi_flash_set(struct udevice *dev, const u32 a)
55 struct bootcount_spi_flash_priv *priv = dev_get_priv(dev);
56 const u16 val = bootcount_magic << 8 | (a & 0xff);
58 if (bootcount_spi_flash_update(priv->spi_flash, priv->offset, 2, &val) < 0) {
59 debug("%s: write failed\n", __func__);
66 static int bootcount_spi_flash_get(struct udevice *dev, u32 *a)
68 struct bootcount_spi_flash_priv *priv = dev_get_priv(dev);
71 if (spi_flash_read_dm(priv->spi_flash, priv->offset, 2, &val) < 0) {
72 debug("%s: read failed\n", __func__);
76 if (val >> 8 == bootcount_magic) {
81 debug("%s: bootcount magic does not match on %04x\n", __func__, val);
85 static int bootcount_spi_flash_probe(struct udevice *dev)
87 struct ofnode_phandle_args phandle_args;
88 struct bootcount_spi_flash_priv *priv = dev_get_priv(dev);
89 struct udevice *spi_flash;
91 if (dev_read_phandle_with_args(dev, "spi-flash", NULL, 0, 0, &phandle_args)) {
92 debug("%s: spi-flash backing device not specified\n", dev->name);
96 if (uclass_get_device_by_ofnode(UCLASS_SPI_FLASH, phandle_args.node, &spi_flash)) {
97 debug("%s: could not get backing device\n", dev->name);
101 priv->spi_flash = spi_flash;
102 priv->offset = dev_read_u32_default(dev, "offset", 0);
107 static const struct bootcount_ops bootcount_spi_flash_ops = {
108 .get = bootcount_spi_flash_get,
109 .set = bootcount_spi_flash_set,
112 static const struct udevice_id bootcount_spi_flash_ids[] = {
113 { .compatible = "u-boot,bootcount-spi-flash" },
117 U_BOOT_DRIVER(bootcount_spi_flash) = {
118 .name = "bootcount-spi-flash",
119 .id = UCLASS_BOOTCOUNT,
120 .priv_auto = sizeof(struct bootcount_spi_flash_priv),
121 .probe = bootcount_spi_flash_probe,
122 .of_match = bootcount_spi_flash_ids,
123 .ops = &bootcount_spi_flash_ops,