1 // SPDX-License-Identifier: GPL-2.0+
3 * (C) Copyright 2019 Collabora
4 * (C) Copyright 2019 GE
10 #include <spi_flash.h>
12 static const u8 bootcount_magic = 0xbc;
14 struct bootcount_spi_flash_priv {
15 struct udevice *spi_flash;
19 static int bootcount_spi_flash_update(struct udevice *dev, u32 offset, u32 len, const void *buf)
21 struct spi_flash *flash = dev_get_uclass_priv(dev);
22 u32 sector_size = flash->sector_size;
23 u32 sector_offset = offset % sector_size;
24 u32 sector = offset - sector_offset;
27 /* code only supports updating a single sector */
28 if (sector_offset + len > sector_size)
31 u8 *buffer = malloc(sector_size);
35 err = spi_flash_read_dm(dev, sector, sector_size, buffer);
39 memcpy(buffer + sector_offset, buf, len);
41 err = spi_flash_erase_dm(dev, sector, sector_size);
45 err = spi_flash_write_dm(dev, sector, sector_size, buffer);
54 static int bootcount_spi_flash_set(struct udevice *dev, const u32 a)
56 struct bootcount_spi_flash_priv *priv = dev_get_priv(dev);
57 const u16 val = bootcount_magic << 8 | (a & 0xff);
59 if (bootcount_spi_flash_update(priv->spi_flash, priv->offset, 2, &val) < 0) {
60 debug("%s: write failed\n", __func__);
67 static int bootcount_spi_flash_get(struct udevice *dev, u32 *a)
69 struct bootcount_spi_flash_priv *priv = dev_get_priv(dev);
72 if (spi_flash_read_dm(priv->spi_flash, priv->offset, 2, &val) < 0) {
73 debug("%s: read failed\n", __func__);
77 if (val >> 8 == bootcount_magic) {
82 debug("%s: bootcount magic does not match on %04x\n", __func__, val);
86 static int bootcount_spi_flash_probe(struct udevice *dev)
88 struct ofnode_phandle_args phandle_args;
89 struct bootcount_spi_flash_priv *priv = dev_get_priv(dev);
90 struct udevice *spi_flash;
92 if (dev_read_phandle_with_args(dev, "spi-flash", NULL, 0, 0, &phandle_args)) {
93 debug("%s: spi-flash backing device not specified\n", dev->name);
97 if (uclass_get_device_by_ofnode(UCLASS_SPI_FLASH, phandle_args.node, &spi_flash)) {
98 debug("%s: could not get backing device\n", dev->name);
102 priv->spi_flash = spi_flash;
103 priv->offset = dev_read_u32_default(dev, "offset", 0);
108 static const struct bootcount_ops bootcount_spi_flash_ops = {
109 .get = bootcount_spi_flash_get,
110 .set = bootcount_spi_flash_set,
113 static const struct udevice_id bootcount_spi_flash_ids[] = {
114 { .compatible = "u-boot,bootcount-spi-flash" },
118 U_BOOT_DRIVER(bootcount_spi_flash) = {
119 .name = "bootcount-spi-flash",
120 .id = UCLASS_BOOTCOUNT,
121 .priv_auto = sizeof(struct bootcount_spi_flash_priv),
122 .probe = bootcount_spi_flash_probe,
123 .of_match = bootcount_spi_flash_ids,
124 .ops = &bootcount_spi_flash_ops,