1 // SPDX-License-Identifier: GPL-2.0+
3 * Copyright (C) 2012-2014 Daniel Schwierzeck, daniel.schwierzeck@gmail.com
8 #include <linux/errno.h>
9 #include <linux/mtd/mtd.h>
10 #include <spi_flash.h>
12 static struct mtd_info sf_mtd_info;
13 static bool sf_mtd_registered;
14 static char sf_mtd_name[8];
16 static int spi_flash_mtd_erase(struct mtd_info *mtd, struct erase_info *instr)
18 struct spi_flash *flash = mtd->priv;
24 instr->state = MTD_ERASING;
26 err = spi_flash_erase(flash, instr->addr, instr->len);
28 instr->state = MTD_ERASE_FAILED;
29 instr->fail_addr = MTD_FAIL_ADDR_UNKNOWN;
33 instr->state = MTD_ERASE_DONE;
34 mtd_erase_callback(instr);
39 static int spi_flash_mtd_read(struct mtd_info *mtd, loff_t from, size_t len,
40 size_t *retlen, u_char *buf)
42 struct spi_flash *flash = mtd->priv;
48 err = spi_flash_read(flash, from, len, buf);
55 static int spi_flash_mtd_write(struct mtd_info *mtd, loff_t to, size_t len,
56 size_t *retlen, const u_char *buf)
58 struct spi_flash *flash = mtd->priv;
64 err = spi_flash_write(flash, to, len, buf);
71 static void spi_flash_mtd_sync(struct mtd_info *mtd)
75 static int spi_flash_mtd_number(void)
77 #ifdef CONFIG_SYS_MAX_FLASH_BANKS
78 return CONFIG_SYS_MAX_FLASH_BANKS;
84 int spi_flash_mtd_register(struct spi_flash *flash)
88 if (sf_mtd_registered) {
89 ret = del_mtd_device(&sf_mtd_info);
93 sf_mtd_registered = false;
96 sf_mtd_registered = false;
97 memset(&sf_mtd_info, 0, sizeof(sf_mtd_info));
98 sprintf(sf_mtd_name, "nor%d", spi_flash_mtd_number());
100 sf_mtd_info.name = sf_mtd_name;
101 sf_mtd_info.type = MTD_NORFLASH;
102 sf_mtd_info.flags = MTD_CAP_NORFLASH;
103 sf_mtd_info.writesize = 1;
104 sf_mtd_info.writebufsize = flash->page_size;
106 sf_mtd_info._erase = spi_flash_mtd_erase;
107 sf_mtd_info._read = spi_flash_mtd_read;
108 sf_mtd_info._write = spi_flash_mtd_write;
109 sf_mtd_info._sync = spi_flash_mtd_sync;
111 sf_mtd_info.size = flash->size;
112 sf_mtd_info.priv = flash;
114 /* Only uniform flash devices for now */
115 sf_mtd_info.numeraseregions = 0;
116 sf_mtd_info.erasesize = flash->sector_size;
118 ret = add_mtd_device(&sf_mtd_info);
120 sf_mtd_registered = true;
125 void spi_flash_mtd_unregister(void)
129 if (!sf_mtd_registered)
132 ret = del_mtd_device(&sf_mtd_info);
134 sf_mtd_registered = false;
139 * Setting mtd->priv to NULL is the best we can do. Thanks to that,
140 * the MTD layer can still call mtd hooks without risking a
141 * use-after-free bug. Still, things should be fixed to prevent the
142 * spi_flash object from being destroyed when del_mtd_device() fails.
144 sf_mtd_info.priv = NULL;
145 printf("Failed to unregister MTD %s and the spi_flash object is going away: you're in deep trouble!",