xref: /openbmc/u-boot/drivers/mtd/spi/sf_mtd.c (revision 894c3ad2)
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * Copyright (C) 2012-2014 Daniel Schwierzeck, daniel.schwierzeck@gmail.com
4  */
5 
6 #include <common.h>
7 #include <malloc.h>
8 #include <linux/errno.h>
9 #include <linux/mtd/mtd.h>
10 #include <spi_flash.h>
11 
12 static struct mtd_info sf_mtd_info;
13 static char sf_mtd_name[8];
14 
15 static int spi_flash_mtd_erase(struct mtd_info *mtd, struct erase_info *instr)
16 {
17 	struct spi_flash *flash = mtd->priv;
18 	int err;
19 
20 	instr->state = MTD_ERASING;
21 
22 	err = spi_flash_erase(flash, instr->addr, instr->len);
23 	if (err) {
24 		instr->state = MTD_ERASE_FAILED;
25 		instr->fail_addr = MTD_FAIL_ADDR_UNKNOWN;
26 		return -EIO;
27 	}
28 
29 	instr->state = MTD_ERASE_DONE;
30 	mtd_erase_callback(instr);
31 
32 	return 0;
33 }
34 
35 static int spi_flash_mtd_read(struct mtd_info *mtd, loff_t from, size_t len,
36 	size_t *retlen, u_char *buf)
37 {
38 	struct spi_flash *flash = mtd->priv;
39 	int err;
40 
41 	err = spi_flash_read(flash, from, len, buf);
42 	if (!err)
43 		*retlen = len;
44 
45 	return err;
46 }
47 
48 static int spi_flash_mtd_write(struct mtd_info *mtd, loff_t to, size_t len,
49 	size_t *retlen, const u_char *buf)
50 {
51 	struct spi_flash *flash = mtd->priv;
52 	int err;
53 
54 	err = spi_flash_write(flash, to, len, buf);
55 	if (!err)
56 		*retlen = len;
57 
58 	return err;
59 }
60 
61 static void spi_flash_mtd_sync(struct mtd_info *mtd)
62 {
63 }
64 
65 static int spi_flash_mtd_number(void)
66 {
67 #ifdef CONFIG_SYS_MAX_FLASH_BANKS
68 	return CONFIG_SYS_MAX_FLASH_BANKS;
69 #else
70 	return 0;
71 #endif
72 }
73 
74 int spi_flash_mtd_register(struct spi_flash *flash)
75 {
76 	memset(&sf_mtd_info, 0, sizeof(sf_mtd_info));
77 	sprintf(sf_mtd_name, "nor%d", spi_flash_mtd_number());
78 
79 	sf_mtd_info.name = sf_mtd_name;
80 	sf_mtd_info.type = MTD_NORFLASH;
81 	sf_mtd_info.flags = MTD_CAP_NORFLASH;
82 	sf_mtd_info.writesize = 1;
83 	sf_mtd_info.writebufsize = flash->page_size;
84 
85 	sf_mtd_info._erase = spi_flash_mtd_erase;
86 	sf_mtd_info._read = spi_flash_mtd_read;
87 	sf_mtd_info._write = spi_flash_mtd_write;
88 	sf_mtd_info._sync = spi_flash_mtd_sync;
89 
90 	sf_mtd_info.size = flash->size;
91 	sf_mtd_info.priv = flash;
92 
93 	/* Only uniform flash devices for now */
94 	sf_mtd_info.numeraseregions = 0;
95 	sf_mtd_info.erasesize = flash->sector_size;
96 
97 	return add_mtd_device(&sf_mtd_info);
98 }
99 
100 void spi_flash_mtd_unregister(void)
101 {
102 	del_mtd_device(&sf_mtd_info);
103 }
104