mtd: spi-nor-core: Add non-uniform erase for Spansion/Cypress
[platform/kernel/u-boot.git] / drivers / mtd / spi / spi-nor-core.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Based on m25p80.c, by Mike Lavender (mike@steroidmicros.com), with
4  * influence from lart.c (Abraham Van Der Merwe) and mtd_dataflash.c
5  *
6  * Copyright (C) 2005, Intec Automation Inc.
7  * Copyright (C) 2014, Freescale Semiconductor, Inc.
8  *
9  * Synced from Linux v4.19
10  */
11
12 #include <common.h>
13 #include <log.h>
14 #include <watchdog.h>
15 #include <dm.h>
16 #include <dm/device_compat.h>
17 #include <dm/devres.h>
18 #include <linux/bitops.h>
19 #include <linux/err.h>
20 #include <linux/errno.h>
21 #include <linux/log2.h>
22 #include <linux/math64.h>
23 #include <linux/sizes.h>
24 #include <linux/bitfield.h>
25 #include <linux/delay.h>
26
27 #include <linux/mtd/mtd.h>
28 #include <linux/mtd/spi-nor.h>
29 #include <spi-mem.h>
30 #include <spi.h>
31
32 #include "sf_internal.h"
33
34 /* Define max times to check status register before we give up. */
35
36 /*
37  * For everything but full-chip erase; probably could be much smaller, but kept
38  * around for safety for now
39  */
40
41 #define HZ                                      CONFIG_SYS_HZ
42
43 #define DEFAULT_READY_WAIT_JIFFIES              (40UL * HZ)
44
45 #define ROUND_UP_TO(x, y)       (((x) + (y) - 1) / (y) * (y))
46
47 struct sfdp_parameter_header {
48         u8              id_lsb;
49         u8              minor;
50         u8              major;
51         u8              length; /* in double words */
52         u8              parameter_table_pointer[3]; /* byte address */
53         u8              id_msb;
54 };
55
56 #define SFDP_PARAM_HEADER_ID(p) (((p)->id_msb << 8) | (p)->id_lsb)
57 #define SFDP_PARAM_HEADER_PTP(p) \
58         (((p)->parameter_table_pointer[2] << 16) | \
59          ((p)->parameter_table_pointer[1] <<  8) | \
60          ((p)->parameter_table_pointer[0] <<  0))
61
62 #define SFDP_BFPT_ID            0xff00  /* Basic Flash Parameter Table */
63 #define SFDP_SECTOR_MAP_ID      0xff81  /* Sector Map Table */
64 #define SFDP_SST_ID             0x01bf  /* Manufacturer specific Table */
65 #define SFDP_PROFILE1_ID        0xff05  /* xSPI Profile 1.0 Table */
66
67 #define SFDP_SIGNATURE          0x50444653U
68 #define SFDP_JESD216_MAJOR      1
69 #define SFDP_JESD216_MINOR      0
70 #define SFDP_JESD216A_MINOR     5
71 #define SFDP_JESD216B_MINOR     6
72
73 struct sfdp_header {
74         u32             signature; /* Ox50444653U <=> "SFDP" */
75         u8              minor;
76         u8              major;
77         u8              nph; /* 0-base number of parameter headers */
78         u8              unused;
79
80         /* Basic Flash Parameter Table. */
81         struct sfdp_parameter_header    bfpt_header;
82 };
83
84 /* Basic Flash Parameter Table */
85
86 /*
87  * JESD216 rev D defines a Basic Flash Parameter Table of 20 DWORDs.
88  * They are indexed from 1 but C arrays are indexed from 0.
89  */
90 #define BFPT_DWORD(i)           ((i) - 1)
91 #define BFPT_DWORD_MAX          20
92
93 /* The first version of JESB216 defined only 9 DWORDs. */
94 #define BFPT_DWORD_MAX_JESD216                  9
95 #define BFPT_DWORD_MAX_JESD216B                 16
96
97 /* 1st DWORD. */
98 #define BFPT_DWORD1_FAST_READ_1_1_2             BIT(16)
99 #define BFPT_DWORD1_ADDRESS_BYTES_MASK          GENMASK(18, 17)
100 #define BFPT_DWORD1_ADDRESS_BYTES_3_ONLY        (0x0UL << 17)
101 #define BFPT_DWORD1_ADDRESS_BYTES_3_OR_4        (0x1UL << 17)
102 #define BFPT_DWORD1_ADDRESS_BYTES_4_ONLY        (0x2UL << 17)
103 #define BFPT_DWORD1_DTR                         BIT(19)
104 #define BFPT_DWORD1_FAST_READ_1_2_2             BIT(20)
105 #define BFPT_DWORD1_FAST_READ_1_4_4             BIT(21)
106 #define BFPT_DWORD1_FAST_READ_1_1_4             BIT(22)
107
108 /* 5th DWORD. */
109 #define BFPT_DWORD5_FAST_READ_2_2_2             BIT(0)
110 #define BFPT_DWORD5_FAST_READ_4_4_4             BIT(4)
111
112 /* 11th DWORD. */
113 #define BFPT_DWORD11_PAGE_SIZE_SHIFT            4
114 #define BFPT_DWORD11_PAGE_SIZE_MASK             GENMASK(7, 4)
115
116 /* 15th DWORD. */
117
118 /*
119  * (from JESD216 rev B)
120  * Quad Enable Requirements (QER):
121  * - 000b: Device does not have a QE bit. Device detects 1-1-4 and 1-4-4
122  *         reads based on instruction. DQ3/HOLD# functions are hold during
123  *         instruction phase.
124  * - 001b: QE is bit 1 of status register 2. It is set via Write Status with
125  *         two data bytes where bit 1 of the second byte is one.
126  *         [...]
127  *         Writing only one byte to the status register has the side-effect of
128  *         clearing status register 2, including the QE bit. The 100b code is
129  *         used if writing one byte to the status register does not modify
130  *         status register 2.
131  * - 010b: QE is bit 6 of status register 1. It is set via Write Status with
132  *         one data byte where bit 6 is one.
133  *         [...]
134  * - 011b: QE is bit 7 of status register 2. It is set via Write status
135  *         register 2 instruction 3Eh with one data byte where bit 7 is one.
136  *         [...]
137  *         The status register 2 is read using instruction 3Fh.
138  * - 100b: QE is bit 1 of status register 2. It is set via Write Status with
139  *         two data bytes where bit 1 of the second byte is one.
140  *         [...]
141  *         In contrast to the 001b code, writing one byte to the status
142  *         register does not modify status register 2.
143  * - 101b: QE is bit 1 of status register 2. Status register 1 is read using
144  *         Read Status instruction 05h. Status register2 is read using
145  *         instruction 35h. QE is set via Writ Status instruction 01h with
146  *         two data bytes where bit 1 of the second byte is one.
147  *         [...]
148  */
149 #define BFPT_DWORD15_QER_MASK                   GENMASK(22, 20)
150 #define BFPT_DWORD15_QER_NONE                   (0x0UL << 20) /* Micron */
151 #define BFPT_DWORD15_QER_SR2_BIT1_BUGGY         (0x1UL << 20)
152 #define BFPT_DWORD15_QER_SR1_BIT6               (0x2UL << 20) /* Macronix */
153 #define BFPT_DWORD15_QER_SR2_BIT7               (0x3UL << 20)
154 #define BFPT_DWORD15_QER_SR2_BIT1_NO_RD         (0x4UL << 20)
155 #define BFPT_DWORD15_QER_SR2_BIT1               (0x5UL << 20) /* Spansion */
156
157 #define BFPT_DWORD16_SOFT_RST                   BIT(12)
158
159 #define BFPT_DWORD18_CMD_EXT_MASK               GENMASK(30, 29)
160 #define BFPT_DWORD18_CMD_EXT_REP                (0x0UL << 29) /* Repeat */
161 #define BFPT_DWORD18_CMD_EXT_INV                (0x1UL << 29) /* Invert */
162 #define BFPT_DWORD18_CMD_EXT_RES                (0x2UL << 29) /* Reserved */
163 #define BFPT_DWORD18_CMD_EXT_16B                (0x3UL << 29) /* 16-bit opcode */
164
165 /* xSPI Profile 1.0 table (from JESD216D.01). */
166 #define PROFILE1_DWORD1_RD_FAST_CMD             GENMASK(15, 8)
167 #define PROFILE1_DWORD1_RDSR_DUMMY              BIT(28)
168 #define PROFILE1_DWORD1_RDSR_ADDR_BYTES         BIT(29)
169 #define PROFILE1_DWORD4_DUMMY_200MHZ            GENMASK(11, 7)
170 #define PROFILE1_DWORD5_DUMMY_166MHZ            GENMASK(31, 27)
171 #define PROFILE1_DWORD5_DUMMY_133MHZ            GENMASK(21, 17)
172 #define PROFILE1_DWORD5_DUMMY_100MHZ            GENMASK(11, 7)
173 #define PROFILE1_DUMMY_DEFAULT                  20
174
175 struct sfdp_bfpt {
176         u32     dwords[BFPT_DWORD_MAX];
177 };
178
179 /**
180  * struct spi_nor_fixups - SPI NOR fixup hooks
181  * @default_init: called after default flash parameters init. Used to tweak
182  *                flash parameters when information provided by the flash_info
183  *                table is incomplete or wrong.
184  * @post_bfpt: called after the BFPT table has been parsed
185  * @post_sfdp: called after SFDP has been parsed (is also called for SPI NORs
186  *             that do not support RDSFDP). Typically used to tweak various
187  *             parameters that could not be extracted by other means (i.e.
188  *             when information provided by the SFDP/flash_info tables are
189  *             incomplete or wrong).
190  *
191  * Those hooks can be used to tweak the SPI NOR configuration when the SFDP
192  * table is broken or not available.
193  */
194 struct spi_nor_fixups {
195         void (*default_init)(struct spi_nor *nor);
196         int (*post_bfpt)(struct spi_nor *nor,
197                          const struct sfdp_parameter_header *bfpt_header,
198                          const struct sfdp_bfpt *bfpt,
199                          struct spi_nor_flash_parameter *params);
200         void (*post_sfdp)(struct spi_nor *nor,
201                           struct spi_nor_flash_parameter *params);
202 };
203
204 #define SPI_NOR_SRST_SLEEP_LEN                  200
205
206 /**
207  * spi_nor_get_cmd_ext() - Get the command opcode extension based on the
208  *                         extension type.
209  * @nor:                pointer to a 'struct spi_nor'
210  * @op:                 pointer to the 'struct spi_mem_op' whose properties
211  *                      need to be initialized.
212  *
213  * Right now, only "repeat" and "invert" are supported.
214  *
215  * Return: The opcode extension.
216  */
217 static u8 spi_nor_get_cmd_ext(const struct spi_nor *nor,
218                               const struct spi_mem_op *op)
219 {
220         switch (nor->cmd_ext_type) {
221         case SPI_NOR_EXT_INVERT:
222                 return ~op->cmd.opcode;
223
224         case SPI_NOR_EXT_REPEAT:
225                 return op->cmd.opcode;
226
227         default:
228                 dev_dbg(nor->dev, "Unknown command extension type\n");
229                 return 0;
230         }
231 }
232
233 /**
234  * spi_nor_setup_op() - Set up common properties of a spi-mem op.
235  * @nor:                pointer to a 'struct spi_nor'
236  * @op:                 pointer to the 'struct spi_mem_op' whose properties
237  *                      need to be initialized.
238  * @proto:              the protocol from which the properties need to be set.
239  */
240 static void spi_nor_setup_op(const struct spi_nor *nor,
241                              struct spi_mem_op *op,
242                              const enum spi_nor_protocol proto)
243 {
244         u8 ext;
245
246         op->cmd.buswidth = spi_nor_get_protocol_inst_nbits(proto);
247
248         if (op->addr.nbytes)
249                 op->addr.buswidth = spi_nor_get_protocol_addr_nbits(proto);
250
251         if (op->dummy.nbytes)
252                 op->dummy.buswidth = spi_nor_get_protocol_addr_nbits(proto);
253
254         if (op->data.nbytes)
255                 op->data.buswidth = spi_nor_get_protocol_data_nbits(proto);
256
257         if (spi_nor_protocol_is_dtr(proto)) {
258                 /*
259                  * spi-mem supports mixed DTR modes, but right now we can only
260                  * have all phases either DTR or STR. IOW, spi-mem can have
261                  * something like 4S-4D-4D, but spi-nor can't. So, set all 4
262                  * phases to either DTR or STR.
263                  */
264                 op->cmd.dtr = op->addr.dtr = op->dummy.dtr =
265                         op->data.dtr = true;
266
267                 /* 2 bytes per clock cycle in DTR mode. */
268                 op->dummy.nbytes *= 2;
269
270                 ext = spi_nor_get_cmd_ext(nor, op);
271                 op->cmd.opcode = (op->cmd.opcode << 8) | ext;
272                 op->cmd.nbytes = 2;
273         }
274 }
275
276 static int spi_nor_read_write_reg(struct spi_nor *nor, struct spi_mem_op
277                 *op, void *buf)
278 {
279         if (op->data.dir == SPI_MEM_DATA_IN)
280                 op->data.buf.in = buf;
281         else
282                 op->data.buf.out = buf;
283         return spi_mem_exec_op(nor->spi, op);
284 }
285
286 static int spi_nor_read_reg(struct spi_nor *nor, u8 code, u8 *val, int len)
287 {
288         struct spi_mem_op op = SPI_MEM_OP(SPI_MEM_OP_CMD(code, 0),
289                                           SPI_MEM_OP_NO_ADDR,
290                                           SPI_MEM_OP_NO_DUMMY,
291                                           SPI_MEM_OP_DATA_IN(len, NULL, 0));
292         int ret;
293
294         spi_nor_setup_op(nor, &op, nor->reg_proto);
295
296         ret = spi_nor_read_write_reg(nor, &op, val);
297         if (ret < 0)
298                 dev_dbg(nor->dev, "error %d reading %x\n", ret, code);
299
300         return ret;
301 }
302
303 static int spi_nor_write_reg(struct spi_nor *nor, u8 opcode, u8 *buf, int len)
304 {
305         struct spi_mem_op op = SPI_MEM_OP(SPI_MEM_OP_CMD(opcode, 0),
306                                           SPI_MEM_OP_NO_ADDR,
307                                           SPI_MEM_OP_NO_DUMMY,
308                                           SPI_MEM_OP_DATA_OUT(len, NULL, 0));
309
310         spi_nor_setup_op(nor, &op, nor->reg_proto);
311
312         if (len == 0)
313                 op.data.dir = SPI_MEM_NO_DATA;
314
315         return spi_nor_read_write_reg(nor, &op, buf);
316 }
317
318 static ssize_t spi_nor_read_data(struct spi_nor *nor, loff_t from, size_t len,
319                                  u_char *buf)
320 {
321         struct spi_mem_op op =
322                         SPI_MEM_OP(SPI_MEM_OP_CMD(nor->read_opcode, 0),
323                                    SPI_MEM_OP_ADDR(nor->addr_width, from, 0),
324                                    SPI_MEM_OP_DUMMY(nor->read_dummy, 0),
325                                    SPI_MEM_OP_DATA_IN(len, buf, 0));
326         size_t remaining = len;
327         int ret;
328
329         spi_nor_setup_op(nor, &op, nor->read_proto);
330
331         /* convert the dummy cycles to the number of bytes */
332         op.dummy.nbytes = (nor->read_dummy * op.dummy.buswidth) / 8;
333         if (spi_nor_protocol_is_dtr(nor->read_proto))
334                 op.dummy.nbytes *= 2;
335
336         while (remaining) {
337                 op.data.nbytes = remaining < UINT_MAX ? remaining : UINT_MAX;
338                 ret = spi_mem_adjust_op_size(nor->spi, &op);
339                 if (ret)
340                         return ret;
341
342                 ret = spi_mem_exec_op(nor->spi, &op);
343                 if (ret)
344                         return ret;
345
346                 op.addr.val += op.data.nbytes;
347                 remaining -= op.data.nbytes;
348                 op.data.buf.in += op.data.nbytes;
349         }
350
351         return len;
352 }
353
354 static ssize_t spi_nor_write_data(struct spi_nor *nor, loff_t to, size_t len,
355                                   const u_char *buf)
356 {
357         struct spi_mem_op op =
358                         SPI_MEM_OP(SPI_MEM_OP_CMD(nor->program_opcode, 0),
359                                    SPI_MEM_OP_ADDR(nor->addr_width, to, 0),
360                                    SPI_MEM_OP_NO_DUMMY,
361                                    SPI_MEM_OP_DATA_OUT(len, buf, 0));
362         int ret;
363
364         if (nor->program_opcode == SPINOR_OP_AAI_WP && nor->sst_write_second)
365                 op.addr.nbytes = 0;
366
367         spi_nor_setup_op(nor, &op, nor->write_proto);
368
369         ret = spi_mem_adjust_op_size(nor->spi, &op);
370         if (ret)
371                 return ret;
372         op.data.nbytes = len < op.data.nbytes ? len : op.data.nbytes;
373
374         ret = spi_mem_exec_op(nor->spi, &op);
375         if (ret)
376                 return ret;
377
378         return op.data.nbytes;
379 }
380
381 /*
382  * Read the status register, returning its value in the location
383  * Return the status register value.
384  * Returns negative if error occurred.
385  */
386 static int read_sr(struct spi_nor *nor)
387 {
388         struct spi_mem_op op;
389         int ret;
390         u8 val[2];
391         u8 addr_nbytes, dummy;
392
393         if (nor->reg_proto == SNOR_PROTO_8_8_8_DTR) {
394                 addr_nbytes = nor->rdsr_addr_nbytes;
395                 dummy = nor->rdsr_dummy;
396         } else {
397                 addr_nbytes = 0;
398                 dummy = 0;
399         }
400
401         op = (struct spi_mem_op)SPI_MEM_OP(SPI_MEM_OP_CMD(SPINOR_OP_RDSR, 0),
402                                            SPI_MEM_OP_ADDR(addr_nbytes, 0, 0),
403                                            SPI_MEM_OP_DUMMY(dummy, 0),
404                                            SPI_MEM_OP_DATA_IN(1, NULL, 0));
405
406         spi_nor_setup_op(nor, &op, nor->reg_proto);
407
408         /*
409          * We don't want to read only one byte in DTR mode. So, read 2 and then
410          * discard the second byte.
411          */
412         if (spi_nor_protocol_is_dtr(nor->reg_proto))
413                 op.data.nbytes = 2;
414
415         ret = spi_nor_read_write_reg(nor, &op, val);
416         if (ret < 0) {
417                 pr_debug("error %d reading SR\n", (int)ret);
418                 return ret;
419         }
420
421         return *val;
422 }
423
424 /*
425  * Read the flag status register, returning its value in the location
426  * Return the status register value.
427  * Returns negative if error occurred.
428  */
429 static int read_fsr(struct spi_nor *nor)
430 {
431         struct spi_mem_op op;
432         int ret;
433         u8 val[2];
434         u8 addr_nbytes, dummy;
435
436         if (nor->reg_proto == SNOR_PROTO_8_8_8_DTR) {
437                 addr_nbytes = nor->rdsr_addr_nbytes;
438                 dummy = nor->rdsr_dummy;
439         } else {
440                 addr_nbytes = 0;
441                 dummy = 0;
442         }
443
444         op = (struct spi_mem_op)SPI_MEM_OP(SPI_MEM_OP_CMD(SPINOR_OP_RDFSR, 0),
445                                            SPI_MEM_OP_ADDR(addr_nbytes, 0, 0),
446                                            SPI_MEM_OP_DUMMY(dummy, 0),
447                                            SPI_MEM_OP_DATA_IN(1, NULL, 0));
448
449         spi_nor_setup_op(nor, &op, nor->reg_proto);
450
451         /*
452          * We don't want to read only one byte in DTR mode. So, read 2 and then
453          * discard the second byte.
454          */
455         if (spi_nor_protocol_is_dtr(nor->reg_proto))
456                 op.data.nbytes = 2;
457
458         ret = spi_nor_read_write_reg(nor, &op, val);
459         if (ret < 0) {
460                 pr_debug("error %d reading FSR\n", ret);
461                 return ret;
462         }
463
464         return *val;
465 }
466
467 /*
468  * Read configuration register, returning its value in the
469  * location. Return the configuration register value.
470  * Returns negative if error occurred.
471  */
472 #if defined(CONFIG_SPI_FLASH_SPANSION) || defined(CONFIG_SPI_FLASH_WINBOND)
473 static int read_cr(struct spi_nor *nor)
474 {
475         int ret;
476         u8 val;
477
478         ret = nor->read_reg(nor, SPINOR_OP_RDCR, &val, 1);
479         if (ret < 0) {
480                 dev_dbg(nor->dev, "error %d reading CR\n", ret);
481                 return ret;
482         }
483
484         return val;
485 }
486 #endif
487
488 /*
489  * Write status register 1 byte
490  * Returns negative if error occurred.
491  */
492 static int write_sr(struct spi_nor *nor, u8 val)
493 {
494         nor->cmd_buf[0] = val;
495         return nor->write_reg(nor, SPINOR_OP_WRSR, nor->cmd_buf, 1);
496 }
497
498 /*
499  * Set write enable latch with Write Enable command.
500  * Returns negative if error occurred.
501  */
502 static int write_enable(struct spi_nor *nor)
503 {
504         return nor->write_reg(nor, SPINOR_OP_WREN, NULL, 0);
505 }
506
507 /*
508  * Send write disable instruction to the chip.
509  */
510 static int write_disable(struct spi_nor *nor)
511 {
512         return nor->write_reg(nor, SPINOR_OP_WRDI, NULL, 0);
513 }
514
515 static struct spi_nor *mtd_to_spi_nor(struct mtd_info *mtd)
516 {
517         return mtd->priv;
518 }
519
520 #ifndef CONFIG_SPI_FLASH_BAR
521 static u8 spi_nor_convert_opcode(u8 opcode, const u8 table[][2], size_t size)
522 {
523         size_t i;
524
525         for (i = 0; i < size; i++)
526                 if (table[i][0] == opcode)
527                         return table[i][1];
528
529         /* No conversion found, keep input op code. */
530         return opcode;
531 }
532
533 static u8 spi_nor_convert_3to4_read(u8 opcode)
534 {
535         static const u8 spi_nor_3to4_read[][2] = {
536                 { SPINOR_OP_READ,       SPINOR_OP_READ_4B },
537                 { SPINOR_OP_READ_FAST,  SPINOR_OP_READ_FAST_4B },
538                 { SPINOR_OP_READ_1_1_2, SPINOR_OP_READ_1_1_2_4B },
539                 { SPINOR_OP_READ_1_2_2, SPINOR_OP_READ_1_2_2_4B },
540                 { SPINOR_OP_READ_1_1_4, SPINOR_OP_READ_1_1_4_4B },
541                 { SPINOR_OP_READ_1_4_4, SPINOR_OP_READ_1_4_4_4B },
542                 { SPINOR_OP_READ_1_1_8, SPINOR_OP_READ_1_1_8_4B },
543                 { SPINOR_OP_READ_1_8_8, SPINOR_OP_READ_1_8_8_4B },
544
545                 { SPINOR_OP_READ_1_1_1_DTR,     SPINOR_OP_READ_1_1_1_DTR_4B },
546                 { SPINOR_OP_READ_1_2_2_DTR,     SPINOR_OP_READ_1_2_2_DTR_4B },
547                 { SPINOR_OP_READ_1_4_4_DTR,     SPINOR_OP_READ_1_4_4_DTR_4B },
548         };
549
550         return spi_nor_convert_opcode(opcode, spi_nor_3to4_read,
551                                       ARRAY_SIZE(spi_nor_3to4_read));
552 }
553
554 static u8 spi_nor_convert_3to4_program(u8 opcode)
555 {
556         static const u8 spi_nor_3to4_program[][2] = {
557                 { SPINOR_OP_PP,         SPINOR_OP_PP_4B },
558                 { SPINOR_OP_PP_1_1_4,   SPINOR_OP_PP_1_1_4_4B },
559                 { SPINOR_OP_PP_1_4_4,   SPINOR_OP_PP_1_4_4_4B },
560                 { SPINOR_OP_PP_1_1_8,   SPINOR_OP_PP_1_1_8_4B },
561                 { SPINOR_OP_PP_1_8_8,   SPINOR_OP_PP_1_8_8_4B },
562         };
563
564         return spi_nor_convert_opcode(opcode, spi_nor_3to4_program,
565                                       ARRAY_SIZE(spi_nor_3to4_program));
566 }
567
568 static u8 spi_nor_convert_3to4_erase(u8 opcode)
569 {
570         static const u8 spi_nor_3to4_erase[][2] = {
571                 { SPINOR_OP_BE_4K,      SPINOR_OP_BE_4K_4B },
572                 { SPINOR_OP_BE_32K,     SPINOR_OP_BE_32K_4B },
573                 { SPINOR_OP_SE,         SPINOR_OP_SE_4B },
574         };
575
576         return spi_nor_convert_opcode(opcode, spi_nor_3to4_erase,
577                                       ARRAY_SIZE(spi_nor_3to4_erase));
578 }
579
580 static void spi_nor_set_4byte_opcodes(struct spi_nor *nor,
581                                       const struct flash_info *info)
582 {
583         /* Do some manufacturer fixups first */
584         switch (JEDEC_MFR(info)) {
585         case SNOR_MFR_SPANSION:
586                 /* No small sector erase for 4-byte command set */
587                 nor->erase_opcode = SPINOR_OP_SE;
588                 nor->mtd.erasesize = info->sector_size;
589                 break;
590
591         default:
592                 break;
593         }
594
595         nor->read_opcode = spi_nor_convert_3to4_read(nor->read_opcode);
596         nor->program_opcode = spi_nor_convert_3to4_program(nor->program_opcode);
597         nor->erase_opcode = spi_nor_convert_3to4_erase(nor->erase_opcode);
598 }
599 #endif /* !CONFIG_SPI_FLASH_BAR */
600
601 /* Enable/disable 4-byte addressing mode. */
602 static int set_4byte(struct spi_nor *nor, const struct flash_info *info,
603                      int enable)
604 {
605         int status;
606         bool need_wren = false;
607         u8 cmd;
608
609         switch (JEDEC_MFR(info)) {
610         case SNOR_MFR_ST:
611         case SNOR_MFR_MICRON:
612                 /* Some Micron need WREN command; all will accept it */
613                 need_wren = true;
614         case SNOR_MFR_ISSI:
615         case SNOR_MFR_MACRONIX:
616         case SNOR_MFR_WINBOND:
617                 if (need_wren)
618                         write_enable(nor);
619
620                 cmd = enable ? SPINOR_OP_EN4B : SPINOR_OP_EX4B;
621                 status = nor->write_reg(nor, cmd, NULL, 0);
622                 if (need_wren)
623                         write_disable(nor);
624
625                 if (!status && !enable &&
626                     JEDEC_MFR(info) == SNOR_MFR_WINBOND) {
627                         /*
628                          * On Winbond W25Q256FV, leaving 4byte mode causes
629                          * the Extended Address Register to be set to 1, so all
630                          * 3-byte-address reads come from the second 16M.
631                          * We must clear the register to enable normal behavior.
632                          */
633                         write_enable(nor);
634                         nor->cmd_buf[0] = 0;
635                         nor->write_reg(nor, SPINOR_OP_WREAR, nor->cmd_buf, 1);
636                         write_disable(nor);
637                 }
638
639                 return status;
640         default:
641                 /* Spansion style */
642                 nor->cmd_buf[0] = enable << 7;
643                 return nor->write_reg(nor, SPINOR_OP_BRWR, nor->cmd_buf, 1);
644         }
645 }
646
647 static int spi_nor_sr_ready(struct spi_nor *nor)
648 {
649         int sr = read_sr(nor);
650
651         if (sr < 0)
652                 return sr;
653
654         if (nor->flags & SNOR_F_USE_CLSR && sr & (SR_E_ERR | SR_P_ERR)) {
655                 if (sr & SR_E_ERR)
656                         dev_dbg(nor->dev, "Erase Error occurred\n");
657                 else
658                         dev_dbg(nor->dev, "Programming Error occurred\n");
659
660                 nor->write_reg(nor, SPINOR_OP_CLSR, NULL, 0);
661                 return -EIO;
662         }
663
664         return !(sr & SR_WIP);
665 }
666
667 static int spi_nor_fsr_ready(struct spi_nor *nor)
668 {
669         int fsr = read_fsr(nor);
670
671         if (fsr < 0)
672                 return fsr;
673
674         if (fsr & (FSR_E_ERR | FSR_P_ERR)) {
675                 if (fsr & FSR_E_ERR)
676                         dev_err(nor->dev, "Erase operation failed.\n");
677                 else
678                         dev_err(nor->dev, "Program operation failed.\n");
679
680                 if (fsr & FSR_PT_ERR)
681                         dev_err(nor->dev,
682                                 "Attempted to modify a protected sector.\n");
683
684                 nor->write_reg(nor, SPINOR_OP_CLFSR, NULL, 0);
685                 return -EIO;
686         }
687
688         return fsr & FSR_READY;
689 }
690
691 static int spi_nor_ready(struct spi_nor *nor)
692 {
693         int sr, fsr;
694
695         sr = spi_nor_sr_ready(nor);
696         if (sr < 0)
697                 return sr;
698         fsr = nor->flags & SNOR_F_USE_FSR ? spi_nor_fsr_ready(nor) : 1;
699         if (fsr < 0)
700                 return fsr;
701         return sr && fsr;
702 }
703
704 /*
705  * Service routine to read status register until ready, or timeout occurs.
706  * Returns non-zero if error.
707  */
708 static int spi_nor_wait_till_ready_with_timeout(struct spi_nor *nor,
709                                                 unsigned long timeout)
710 {
711         unsigned long timebase;
712         int ret;
713
714         timebase = get_timer(0);
715
716         while (get_timer(timebase) < timeout) {
717                 ret = spi_nor_ready(nor);
718                 if (ret < 0)
719                         return ret;
720                 if (ret)
721                         return 0;
722         }
723
724         dev_err(nor->dev, "flash operation timed out\n");
725
726         return -ETIMEDOUT;
727 }
728
729 static int spi_nor_wait_till_ready(struct spi_nor *nor)
730 {
731         return spi_nor_wait_till_ready_with_timeout(nor,
732                                                     DEFAULT_READY_WAIT_JIFFIES);
733 }
734
735 #ifdef CONFIG_SPI_FLASH_BAR
736 /*
737  * This "clean_bar" is necessary in a situation when one was accessing
738  * spi flash memory > 16 MiB by using Bank Address Register's BA24 bit.
739  *
740  * After it the BA24 bit shall be cleared to allow access to correct
741  * memory region after SW reset (by calling "reset" command).
742  *
743  * Otherwise, the BA24 bit may be left set and then after reset, the
744  * ROM would read/write/erase SPL from 16 MiB * bank_sel address.
745  */
746 static int clean_bar(struct spi_nor *nor)
747 {
748         u8 cmd, bank_sel = 0;
749
750         if (nor->bank_curr == 0)
751                 return 0;
752         cmd = nor->bank_write_cmd;
753         nor->bank_curr = 0;
754         write_enable(nor);
755
756         return nor->write_reg(nor, cmd, &bank_sel, 1);
757 }
758
759 static int write_bar(struct spi_nor *nor, u32 offset)
760 {
761         u8 cmd, bank_sel;
762         int ret;
763
764         bank_sel = offset / SZ_16M;
765         if (bank_sel == nor->bank_curr)
766                 goto bar_end;
767
768         cmd = nor->bank_write_cmd;
769         write_enable(nor);
770         ret = nor->write_reg(nor, cmd, &bank_sel, 1);
771         if (ret < 0) {
772                 debug("SF: fail to write bank register\n");
773                 return ret;
774         }
775
776 bar_end:
777         nor->bank_curr = bank_sel;
778         return nor->bank_curr;
779 }
780
781 static int read_bar(struct spi_nor *nor, const struct flash_info *info)
782 {
783         u8 curr_bank = 0;
784         int ret;
785
786         switch (JEDEC_MFR(info)) {
787         case SNOR_MFR_SPANSION:
788                 nor->bank_read_cmd = SPINOR_OP_BRRD;
789                 nor->bank_write_cmd = SPINOR_OP_BRWR;
790                 break;
791         default:
792                 nor->bank_read_cmd = SPINOR_OP_RDEAR;
793                 nor->bank_write_cmd = SPINOR_OP_WREAR;
794         }
795
796         ret = nor->read_reg(nor, nor->bank_read_cmd,
797                                     &curr_bank, 1);
798         if (ret) {
799                 debug("SF: fail to read bank addr register\n");
800                 return ret;
801         }
802         nor->bank_curr = curr_bank;
803
804         return 0;
805 }
806 #endif
807
808 /*
809  * Initiate the erasure of a single sector. Returns the number of bytes erased
810  * on success, a negative error code on error.
811  */
812 static int spi_nor_erase_sector(struct spi_nor *nor, u32 addr)
813 {
814         struct spi_mem_op op =
815                 SPI_MEM_OP(SPI_MEM_OP_CMD(nor->erase_opcode, 0),
816                            SPI_MEM_OP_ADDR(nor->addr_width, addr, 0),
817                            SPI_MEM_OP_NO_DUMMY,
818                            SPI_MEM_OP_NO_DATA);
819         int ret;
820
821         spi_nor_setup_op(nor, &op, nor->write_proto);
822
823         if (nor->erase)
824                 return nor->erase(nor, addr);
825
826         /*
827          * Default implementation, if driver doesn't have a specialized HW
828          * control
829          */
830         ret = spi_mem_exec_op(nor->spi, &op);
831         if (ret)
832                 return ret;
833
834         return nor->mtd.erasesize;
835 }
836
837 /*
838  * Erase an address range on the nor chip.  The address range may extend
839  * one or more erase sectors.  Return an error is there is a problem erasing.
840  */
841 static int spi_nor_erase(struct mtd_info *mtd, struct erase_info *instr)
842 {
843         struct spi_nor *nor = mtd_to_spi_nor(mtd);
844         u32 addr, len, rem;
845         int ret;
846
847         dev_dbg(nor->dev, "at 0x%llx, len %lld\n", (long long)instr->addr,
848                 (long long)instr->len);
849
850         if (!instr->len)
851                 return 0;
852
853         div_u64_rem(instr->len, mtd->erasesize, &rem);
854         if (rem)
855                 return -EINVAL;
856
857         addr = instr->addr;
858         len = instr->len;
859
860         while (len) {
861                 WATCHDOG_RESET();
862 #ifdef CONFIG_SPI_FLASH_BAR
863                 ret = write_bar(nor, addr);
864                 if (ret < 0)
865                         return ret;
866 #endif
867                 write_enable(nor);
868
869                 ret = spi_nor_erase_sector(nor, addr);
870                 if (ret < 0)
871                         goto erase_err;
872
873                 addr += ret;
874                 len -= ret;
875
876                 ret = spi_nor_wait_till_ready(nor);
877                 if (ret)
878                         goto erase_err;
879         }
880
881 erase_err:
882 #ifdef CONFIG_SPI_FLASH_BAR
883         ret = clean_bar(nor);
884 #endif
885         write_disable(nor);
886
887         return ret;
888 }
889
890 #ifdef CONFIG_SPI_FLASH_S28HS512T
891 /**
892  * spansion_erase_non_uniform() - erase non-uniform sectors for Spansion/Cypress
893  *                                chips
894  * @nor:        pointer to a 'struct spi_nor'
895  * @addr:       address of the sector to erase
896  * @opcode_4k:  opcode for 4K sector erase
897  * @ovlsz_top:  size of overlaid portion at the top address
898  * @ovlsz_btm:  size of overlaid portion at the bottom address
899  *
900  * Erase an address range on the nor chip that can contain 4KB sectors overlaid
901  * on top and/or bottom. The appropriate erase opcode and size are chosen by
902  * address to erase and size of overlaid portion.
903  *
904  * Return: number of bytes erased on success, -errno otherwise.
905  */
906 static int spansion_erase_non_uniform(struct spi_nor *nor, u32 addr,
907                                       u8 opcode_4k, u32 ovlsz_top,
908                                       u32 ovlsz_btm)
909 {
910         struct spi_mem_op op =
911                 SPI_MEM_OP(SPI_MEM_OP_CMD(nor->erase_opcode, 0),
912                            SPI_MEM_OP_ADDR(nor->addr_width, addr, 0),
913                            SPI_MEM_OP_NO_DUMMY,
914                            SPI_MEM_OP_NO_DATA);
915         struct mtd_info *mtd = &nor->mtd;
916         u32 erasesize;
917         int ret;
918
919         /* 4KB sectors */
920         if (op.addr.val < ovlsz_btm ||
921             op.addr.val >= mtd->size - ovlsz_top) {
922                 op.cmd.opcode = opcode_4k;
923                 erasesize = SZ_4K;
924
925         /* Non-overlaid portion in the normal sector at the bottom */
926         } else if (op.addr.val == ovlsz_btm) {
927                 op.cmd.opcode = nor->erase_opcode;
928                 erasesize = mtd->erasesize - ovlsz_btm;
929
930         /* Non-overlaid portion in the normal sector at the top */
931         } else if (op.addr.val == mtd->size - mtd->erasesize) {
932                 op.cmd.opcode = nor->erase_opcode;
933                 erasesize = mtd->erasesize - ovlsz_top;
934
935         /* Normal sectors */
936         } else {
937                 op.cmd.opcode = nor->erase_opcode;
938                 erasesize = mtd->erasesize;
939         }
940
941         spi_nor_setup_op(nor, &op, nor->write_proto);
942
943         ret = spi_mem_exec_op(nor->spi, &op);
944         if (ret)
945                 return ret;
946
947         return erasesize;
948 }
949 #endif
950
951 #if defined(CONFIG_SPI_FLASH_STMICRO) || defined(CONFIG_SPI_FLASH_SST)
952 /* Write status register and ensure bits in mask match written values */
953 static int write_sr_and_check(struct spi_nor *nor, u8 status_new, u8 mask)
954 {
955         int ret;
956
957         write_enable(nor);
958         ret = write_sr(nor, status_new);
959         if (ret)
960                 return ret;
961
962         ret = spi_nor_wait_till_ready(nor);
963         if (ret)
964                 return ret;
965
966         ret = read_sr(nor);
967         if (ret < 0)
968                 return ret;
969
970         return ((ret & mask) != (status_new & mask)) ? -EIO : 0;
971 }
972
973 static void stm_get_locked_range(struct spi_nor *nor, u8 sr, loff_t *ofs,
974                                  uint64_t *len)
975 {
976         struct mtd_info *mtd = &nor->mtd;
977         u8 mask = SR_BP2 | SR_BP1 | SR_BP0;
978         int shift = ffs(mask) - 1;
979         int pow;
980
981         if (!(sr & mask)) {
982                 /* No protection */
983                 *ofs = 0;
984                 *len = 0;
985         } else {
986                 pow = ((sr & mask) ^ mask) >> shift;
987                 *len = mtd->size >> pow;
988                 if (nor->flags & SNOR_F_HAS_SR_TB && sr & SR_TB)
989                         *ofs = 0;
990                 else
991                         *ofs = mtd->size - *len;
992         }
993 }
994
995 /*
996  * Return 1 if the entire region is locked (if @locked is true) or unlocked (if
997  * @locked is false); 0 otherwise
998  */
999 static int stm_check_lock_status_sr(struct spi_nor *nor, loff_t ofs, u64 len,
1000                                     u8 sr, bool locked)
1001 {
1002         loff_t lock_offs;
1003         uint64_t lock_len;
1004
1005         if (!len)
1006                 return 1;
1007
1008         stm_get_locked_range(nor, sr, &lock_offs, &lock_len);
1009
1010         if (locked)
1011                 /* Requested range is a sub-range of locked range */
1012                 return (ofs + len <= lock_offs + lock_len) && (ofs >= lock_offs);
1013         else
1014                 /* Requested range does not overlap with locked range */
1015                 return (ofs >= lock_offs + lock_len) || (ofs + len <= lock_offs);
1016 }
1017
1018 static int stm_is_locked_sr(struct spi_nor *nor, loff_t ofs, uint64_t len,
1019                             u8 sr)
1020 {
1021         return stm_check_lock_status_sr(nor, ofs, len, sr, true);
1022 }
1023
1024 static int stm_is_unlocked_sr(struct spi_nor *nor, loff_t ofs, uint64_t len,
1025                               u8 sr)
1026 {
1027         return stm_check_lock_status_sr(nor, ofs, len, sr, false);
1028 }
1029
1030 /*
1031  * Lock a region of the flash. Compatible with ST Micro and similar flash.
1032  * Supports the block protection bits BP{0,1,2} in the status register
1033  * (SR). Does not support these features found in newer SR bitfields:
1034  *   - SEC: sector/block protect - only handle SEC=0 (block protect)
1035  *   - CMP: complement protect - only support CMP=0 (range is not complemented)
1036  *
1037  * Support for the following is provided conditionally for some flash:
1038  *   - TB: top/bottom protect
1039  *
1040  * Sample table portion for 8MB flash (Winbond w25q64fw):
1041  *
1042  *   SEC  |  TB   |  BP2  |  BP1  |  BP0  |  Prot Length  | Protected Portion
1043  *  --------------------------------------------------------------------------
1044  *    X   |   X   |   0   |   0   |   0   |  NONE         | NONE
1045  *    0   |   0   |   0   |   0   |   1   |  128 KB       | Upper 1/64
1046  *    0   |   0   |   0   |   1   |   0   |  256 KB       | Upper 1/32
1047  *    0   |   0   |   0   |   1   |   1   |  512 KB       | Upper 1/16
1048  *    0   |   0   |   1   |   0   |   0   |  1 MB         | Upper 1/8
1049  *    0   |   0   |   1   |   0   |   1   |  2 MB         | Upper 1/4
1050  *    0   |   0   |   1   |   1   |   0   |  4 MB         | Upper 1/2
1051  *    X   |   X   |   1   |   1   |   1   |  8 MB         | ALL
1052  *  ------|-------|-------|-------|-------|---------------|-------------------
1053  *    0   |   1   |   0   |   0   |   1   |  128 KB       | Lower 1/64
1054  *    0   |   1   |   0   |   1   |   0   |  256 KB       | Lower 1/32
1055  *    0   |   1   |   0   |   1   |   1   |  512 KB       | Lower 1/16
1056  *    0   |   1   |   1   |   0   |   0   |  1 MB         | Lower 1/8
1057  *    0   |   1   |   1   |   0   |   1   |  2 MB         | Lower 1/4
1058  *    0   |   1   |   1   |   1   |   0   |  4 MB         | Lower 1/2
1059  *
1060  * Returns negative on errors, 0 on success.
1061  */
1062 static int stm_lock(struct spi_nor *nor, loff_t ofs, uint64_t len)
1063 {
1064         struct mtd_info *mtd = &nor->mtd;
1065         int status_old, status_new;
1066         u8 mask = SR_BP2 | SR_BP1 | SR_BP0;
1067         u8 shift = ffs(mask) - 1, pow, val;
1068         loff_t lock_len;
1069         bool can_be_top = true, can_be_bottom = nor->flags & SNOR_F_HAS_SR_TB;
1070         bool use_top;
1071
1072         status_old = read_sr(nor);
1073         if (status_old < 0)
1074                 return status_old;
1075
1076         /* If nothing in our range is unlocked, we don't need to do anything */
1077         if (stm_is_locked_sr(nor, ofs, len, status_old))
1078                 return 0;
1079
1080         /* If anything below us is unlocked, we can't use 'bottom' protection */
1081         if (!stm_is_locked_sr(nor, 0, ofs, status_old))
1082                 can_be_bottom = false;
1083
1084         /* If anything above us is unlocked, we can't use 'top' protection */
1085         if (!stm_is_locked_sr(nor, ofs + len, mtd->size - (ofs + len),
1086                               status_old))
1087                 can_be_top = false;
1088
1089         if (!can_be_bottom && !can_be_top)
1090                 return -EINVAL;
1091
1092         /* Prefer top, if both are valid */
1093         use_top = can_be_top;
1094
1095         /* lock_len: length of region that should end up locked */
1096         if (use_top)
1097                 lock_len = mtd->size - ofs;
1098         else
1099                 lock_len = ofs + len;
1100
1101         /*
1102          * Need smallest pow such that:
1103          *
1104          *   1 / (2^pow) <= (len / size)
1105          *
1106          * so (assuming power-of-2 size) we do:
1107          *
1108          *   pow = ceil(log2(size / len)) = log2(size) - floor(log2(len))
1109          */
1110         pow = ilog2(mtd->size) - ilog2(lock_len);
1111         val = mask - (pow << shift);
1112         if (val & ~mask)
1113                 return -EINVAL;
1114         /* Don't "lock" with no region! */
1115         if (!(val & mask))
1116                 return -EINVAL;
1117
1118         status_new = (status_old & ~mask & ~SR_TB) | val;
1119
1120         /* Disallow further writes if WP pin is asserted */
1121         status_new |= SR_SRWD;
1122
1123         if (!use_top)
1124                 status_new |= SR_TB;
1125
1126         /* Don't bother if they're the same */
1127         if (status_new == status_old)
1128                 return 0;
1129
1130         /* Only modify protection if it will not unlock other areas */
1131         if ((status_new & mask) < (status_old & mask))
1132                 return -EINVAL;
1133
1134         return write_sr_and_check(nor, status_new, mask);
1135 }
1136
1137 /*
1138  * Unlock a region of the flash. See stm_lock() for more info
1139  *
1140  * Returns negative on errors, 0 on success.
1141  */
1142 static int stm_unlock(struct spi_nor *nor, loff_t ofs, uint64_t len)
1143 {
1144         struct mtd_info *mtd = &nor->mtd;
1145         int status_old, status_new;
1146         u8 mask = SR_BP2 | SR_BP1 | SR_BP0;
1147         u8 shift = ffs(mask) - 1, pow, val;
1148         loff_t lock_len;
1149         bool can_be_top = true, can_be_bottom = nor->flags & SNOR_F_HAS_SR_TB;
1150         bool use_top;
1151
1152         status_old = read_sr(nor);
1153         if (status_old < 0)
1154                 return status_old;
1155
1156         /* If nothing in our range is locked, we don't need to do anything */
1157         if (stm_is_unlocked_sr(nor, ofs, len, status_old))
1158                 return 0;
1159
1160         /* If anything below us is locked, we can't use 'top' protection */
1161         if (!stm_is_unlocked_sr(nor, 0, ofs, status_old))
1162                 can_be_top = false;
1163
1164         /* If anything above us is locked, we can't use 'bottom' protection */
1165         if (!stm_is_unlocked_sr(nor, ofs + len, mtd->size - (ofs + len),
1166                                 status_old))
1167                 can_be_bottom = false;
1168
1169         if (!can_be_bottom && !can_be_top)
1170                 return -EINVAL;
1171
1172         /* Prefer top, if both are valid */
1173         use_top = can_be_top;
1174
1175         /* lock_len: length of region that should remain locked */
1176         if (use_top)
1177                 lock_len = mtd->size - (ofs + len);
1178         else
1179                 lock_len = ofs;
1180
1181         /*
1182          * Need largest pow such that:
1183          *
1184          *   1 / (2^pow) >= (len / size)
1185          *
1186          * so (assuming power-of-2 size) we do:
1187          *
1188          *   pow = floor(log2(size / len)) = log2(size) - ceil(log2(len))
1189          */
1190         pow = ilog2(mtd->size) - order_base_2(lock_len);
1191         if (lock_len == 0) {
1192                 val = 0; /* fully unlocked */
1193         } else {
1194                 val = mask - (pow << shift);
1195                 /* Some power-of-two sizes are not supported */
1196                 if (val & ~mask)
1197                         return -EINVAL;
1198         }
1199
1200         status_new = (status_old & ~mask & ~SR_TB) | val;
1201
1202         /* Don't protect status register if we're fully unlocked */
1203         if (lock_len == 0)
1204                 status_new &= ~SR_SRWD;
1205
1206         if (!use_top)
1207                 status_new |= SR_TB;
1208
1209         /* Don't bother if they're the same */
1210         if (status_new == status_old)
1211                 return 0;
1212
1213         /* Only modify protection if it will not lock other areas */
1214         if ((status_new & mask) > (status_old & mask))
1215                 return -EINVAL;
1216
1217         return write_sr_and_check(nor, status_new, mask);
1218 }
1219
1220 /*
1221  * Check if a region of the flash is (completely) locked. See stm_lock() for
1222  * more info.
1223  *
1224  * Returns 1 if entire region is locked, 0 if any portion is unlocked, and
1225  * negative on errors.
1226  */
1227 static int stm_is_locked(struct spi_nor *nor, loff_t ofs, uint64_t len)
1228 {
1229         int status;
1230
1231         status = read_sr(nor);
1232         if (status < 0)
1233                 return status;
1234
1235         return stm_is_locked_sr(nor, ofs, len, status);
1236 }
1237 #endif /* CONFIG_SPI_FLASH_STMICRO */
1238
1239 static const struct flash_info *spi_nor_read_id(struct spi_nor *nor)
1240 {
1241         int                     tmp;
1242         u8                      id[SPI_NOR_MAX_ID_LEN];
1243         const struct flash_info *info;
1244
1245         tmp = nor->read_reg(nor, SPINOR_OP_RDID, id, SPI_NOR_MAX_ID_LEN);
1246         if (tmp < 0) {
1247                 dev_dbg(nor->dev, "error %d reading JEDEC ID\n", tmp);
1248                 return ERR_PTR(tmp);
1249         }
1250
1251         info = spi_nor_ids;
1252         for (; info->name; info++) {
1253                 if (info->id_len) {
1254                         if (!memcmp(info->id, id, info->id_len))
1255                                 return info;
1256                 }
1257         }
1258
1259         dev_err(nor->dev, "unrecognized JEDEC id bytes: %02x, %02x, %02x\n",
1260                 id[0], id[1], id[2]);
1261         return ERR_PTR(-ENODEV);
1262 }
1263
1264 static int spi_nor_read(struct mtd_info *mtd, loff_t from, size_t len,
1265                         size_t *retlen, u_char *buf)
1266 {
1267         struct spi_nor *nor = mtd_to_spi_nor(mtd);
1268         int ret;
1269
1270         dev_dbg(nor->dev, "from 0x%08x, len %zd\n", (u32)from, len);
1271
1272         while (len) {
1273                 loff_t addr = from;
1274                 size_t read_len = len;
1275
1276 #ifdef CONFIG_SPI_FLASH_BAR
1277                 u32 remain_len;
1278
1279                 ret = write_bar(nor, addr);
1280                 if (ret < 0)
1281                         return log_ret(ret);
1282                 remain_len = (SZ_16M * (nor->bank_curr + 1)) - addr;
1283
1284                 if (len < remain_len)
1285                         read_len = len;
1286                 else
1287                         read_len = remain_len;
1288 #endif
1289
1290                 ret = nor->read(nor, addr, read_len, buf);
1291                 if (ret == 0) {
1292                         /* We shouldn't see 0-length reads */
1293                         ret = -EIO;
1294                         goto read_err;
1295                 }
1296                 if (ret < 0)
1297                         goto read_err;
1298
1299                 *retlen += ret;
1300                 buf += ret;
1301                 from += ret;
1302                 len -= ret;
1303         }
1304         ret = 0;
1305
1306 read_err:
1307 #ifdef CONFIG_SPI_FLASH_BAR
1308         ret = clean_bar(nor);
1309 #endif
1310         return ret;
1311 }
1312
1313 #ifdef CONFIG_SPI_FLASH_SST
1314 /*
1315  * sst26 flash series has its own block protection implementation:
1316  * 4x   - 8  KByte blocks - read & write protection bits - upper addresses
1317  * 1x   - 32 KByte blocks - write protection bits
1318  * rest - 64 KByte blocks - write protection bits
1319  * 1x   - 32 KByte blocks - write protection bits
1320  * 4x   - 8  KByte blocks - read & write protection bits - lower addresses
1321  *
1322  * We'll support only per 64k lock/unlock so lower and upper 64 KByte region
1323  * will be treated as single block.
1324  */
1325 #define SST26_BPR_8K_NUM                4
1326 #define SST26_MAX_BPR_REG_LEN           (18 + 1)
1327 #define SST26_BOUND_REG_SIZE            ((32 + SST26_BPR_8K_NUM * 8) * SZ_1K)
1328
1329 enum lock_ctl {
1330         SST26_CTL_LOCK,
1331         SST26_CTL_UNLOCK,
1332         SST26_CTL_CHECK
1333 };
1334
1335 static bool sst26_process_bpr(u32 bpr_size, u8 *cmd, u32 bit, enum lock_ctl ctl)
1336 {
1337         switch (ctl) {
1338         case SST26_CTL_LOCK:
1339                 cmd[bpr_size - (bit / 8) - 1] |= BIT(bit % 8);
1340                 break;
1341         case SST26_CTL_UNLOCK:
1342                 cmd[bpr_size - (bit / 8) - 1] &= ~BIT(bit % 8);
1343                 break;
1344         case SST26_CTL_CHECK:
1345                 return !!(cmd[bpr_size - (bit / 8) - 1] & BIT(bit % 8));
1346         }
1347
1348         return false;
1349 }
1350
1351 /*
1352  * Lock, unlock or check lock status of the flash region of the flash (depending
1353  * on the lock_ctl value)
1354  */
1355 static int sst26_lock_ctl(struct spi_nor *nor, loff_t ofs, uint64_t len, enum lock_ctl ctl)
1356 {
1357         struct mtd_info *mtd = &nor->mtd;
1358         u32 i, bpr_ptr, rptr_64k, lptr_64k, bpr_size;
1359         bool lower_64k = false, upper_64k = false;
1360         u8 bpr_buff[SST26_MAX_BPR_REG_LEN] = {};
1361         int ret;
1362
1363         /* Check length and offset for 64k alignment */
1364         if ((ofs & (SZ_64K - 1)) || (len & (SZ_64K - 1))) {
1365                 dev_err(nor->dev, "length or offset is not 64KiB allighned\n");
1366                 return -EINVAL;
1367         }
1368
1369         if (ofs + len > mtd->size) {
1370                 dev_err(nor->dev, "range is more than device size: %#llx + %#llx > %#llx\n",
1371                         ofs, len, mtd->size);
1372                 return -EINVAL;
1373         }
1374
1375         /* SST26 family has only 16 Mbit, 32 Mbit and 64 Mbit IC */
1376         if (mtd->size != SZ_2M &&
1377             mtd->size != SZ_4M &&
1378             mtd->size != SZ_8M)
1379                 return -EINVAL;
1380
1381         bpr_size = 2 + (mtd->size / SZ_64K / 8);
1382
1383         ret = nor->read_reg(nor, SPINOR_OP_READ_BPR, bpr_buff, bpr_size);
1384         if (ret < 0) {
1385                 dev_err(nor->dev, "fail to read block-protection register\n");
1386                 return ret;
1387         }
1388
1389         rptr_64k = min_t(u32, ofs + len, mtd->size - SST26_BOUND_REG_SIZE);
1390         lptr_64k = max_t(u32, ofs, SST26_BOUND_REG_SIZE);
1391
1392         upper_64k = ((ofs + len) > (mtd->size - SST26_BOUND_REG_SIZE));
1393         lower_64k = (ofs < SST26_BOUND_REG_SIZE);
1394
1395         /* Lower bits in block-protection register are about 64k region */
1396         bpr_ptr = lptr_64k / SZ_64K - 1;
1397
1398         /* Process 64K blocks region */
1399         while (lptr_64k < rptr_64k) {
1400                 if (sst26_process_bpr(bpr_size, bpr_buff, bpr_ptr, ctl))
1401                         return EACCES;
1402
1403                 bpr_ptr++;
1404                 lptr_64k += SZ_64K;
1405         }
1406
1407         /* 32K and 8K region bits in BPR are after 64k region bits */
1408         bpr_ptr = (mtd->size - 2 * SST26_BOUND_REG_SIZE) / SZ_64K;
1409
1410         /* Process lower 32K block region */
1411         if (lower_64k)
1412                 if (sst26_process_bpr(bpr_size, bpr_buff, bpr_ptr, ctl))
1413                         return EACCES;
1414
1415         bpr_ptr++;
1416
1417         /* Process upper 32K block region */
1418         if (upper_64k)
1419                 if (sst26_process_bpr(bpr_size, bpr_buff, bpr_ptr, ctl))
1420                         return EACCES;
1421
1422         bpr_ptr++;
1423
1424         /* Process lower 8K block regions */
1425         for (i = 0; i < SST26_BPR_8K_NUM; i++) {
1426                 if (lower_64k)
1427                         if (sst26_process_bpr(bpr_size, bpr_buff, bpr_ptr, ctl))
1428                                 return EACCES;
1429
1430                 /* In 8K area BPR has both read and write protection bits */
1431                 bpr_ptr += 2;
1432         }
1433
1434         /* Process upper 8K block regions */
1435         for (i = 0; i < SST26_BPR_8K_NUM; i++) {
1436                 if (upper_64k)
1437                         if (sst26_process_bpr(bpr_size, bpr_buff, bpr_ptr, ctl))
1438                                 return EACCES;
1439
1440                 /* In 8K area BPR has both read and write protection bits */
1441                 bpr_ptr += 2;
1442         }
1443
1444         /* If we check region status we don't need to write BPR back */
1445         if (ctl == SST26_CTL_CHECK)
1446                 return 0;
1447
1448         ret = nor->write_reg(nor, SPINOR_OP_WRITE_BPR, bpr_buff, bpr_size);
1449         if (ret < 0) {
1450                 dev_err(nor->dev, "fail to write block-protection register\n");
1451                 return ret;
1452         }
1453
1454         return 0;
1455 }
1456
1457 static int sst26_unlock(struct spi_nor *nor, loff_t ofs, uint64_t len)
1458 {
1459         return sst26_lock_ctl(nor, ofs, len, SST26_CTL_UNLOCK);
1460 }
1461
1462 static int sst26_lock(struct spi_nor *nor, loff_t ofs, uint64_t len)
1463 {
1464         return sst26_lock_ctl(nor, ofs, len, SST26_CTL_LOCK);
1465 }
1466
1467 /*
1468  * Returns EACCES (positive value) if region is locked, 0 if region is unlocked,
1469  * and negative on errors.
1470  */
1471 static int sst26_is_locked(struct spi_nor *nor, loff_t ofs, uint64_t len)
1472 {
1473         /*
1474          * is_locked function is used for check before reading or erasing flash
1475          * region, so offset and length might be not 64k allighned, so adjust
1476          * them to be 64k allighned as sst26_lock_ctl works only with 64k
1477          * allighned regions.
1478          */
1479         ofs -= ofs & (SZ_64K - 1);
1480         len = len & (SZ_64K - 1) ? (len & ~(SZ_64K - 1)) + SZ_64K : len;
1481
1482         return sst26_lock_ctl(nor, ofs, len, SST26_CTL_CHECK);
1483 }
1484
1485 static int sst_write_byteprogram(struct spi_nor *nor, loff_t to, size_t len,
1486                                  size_t *retlen, const u_char *buf)
1487 {
1488         size_t actual;
1489         int ret = 0;
1490
1491         for (actual = 0; actual < len; actual++) {
1492                 nor->program_opcode = SPINOR_OP_BP;
1493
1494                 write_enable(nor);
1495                 /* write one byte. */
1496                 ret = nor->write(nor, to, 1, buf + actual);
1497                 if (ret < 0)
1498                         goto sst_write_err;
1499                 ret = spi_nor_wait_till_ready(nor);
1500                 if (ret)
1501                         goto sst_write_err;
1502                 to++;
1503         }
1504
1505 sst_write_err:
1506         write_disable(nor);
1507         return ret;
1508 }
1509
1510 static int sst_write(struct mtd_info *mtd, loff_t to, size_t len,
1511                      size_t *retlen, const u_char *buf)
1512 {
1513         struct spi_nor *nor = mtd_to_spi_nor(mtd);
1514         struct spi_slave *spi = nor->spi;
1515         size_t actual;
1516         int ret;
1517
1518         dev_dbg(nor->dev, "to 0x%08x, len %zd\n", (u32)to, len);
1519         if (spi->mode & SPI_TX_BYTE)
1520                 return sst_write_byteprogram(nor, to, len, retlen, buf);
1521
1522         write_enable(nor);
1523
1524         nor->sst_write_second = false;
1525
1526         actual = to % 2;
1527         /* Start write from odd address. */
1528         if (actual) {
1529                 nor->program_opcode = SPINOR_OP_BP;
1530
1531                 /* write one byte. */
1532                 ret = nor->write(nor, to, 1, buf);
1533                 if (ret < 0)
1534                         goto sst_write_err;
1535                 ret = spi_nor_wait_till_ready(nor);
1536                 if (ret)
1537                         goto sst_write_err;
1538         }
1539         to += actual;
1540
1541         /* Write out most of the data here. */
1542         for (; actual < len - 1; actual += 2) {
1543                 nor->program_opcode = SPINOR_OP_AAI_WP;
1544
1545                 /* write two bytes. */
1546                 ret = nor->write(nor, to, 2, buf + actual);
1547                 if (ret < 0)
1548                         goto sst_write_err;
1549                 ret = spi_nor_wait_till_ready(nor);
1550                 if (ret)
1551                         goto sst_write_err;
1552                 to += 2;
1553                 nor->sst_write_second = true;
1554         }
1555         nor->sst_write_second = false;
1556
1557         write_disable(nor);
1558         ret = spi_nor_wait_till_ready(nor);
1559         if (ret)
1560                 goto sst_write_err;
1561
1562         /* Write out trailing byte if it exists. */
1563         if (actual != len) {
1564                 write_enable(nor);
1565
1566                 nor->program_opcode = SPINOR_OP_BP;
1567                 ret = nor->write(nor, to, 1, buf + actual);
1568                 if (ret < 0)
1569                         goto sst_write_err;
1570                 ret = spi_nor_wait_till_ready(nor);
1571                 if (ret)
1572                         goto sst_write_err;
1573                 write_disable(nor);
1574                 actual += 1;
1575         }
1576 sst_write_err:
1577         *retlen += actual;
1578         return ret;
1579 }
1580 #endif
1581 /*
1582  * Write an address range to the nor chip.  Data must be written in
1583  * FLASH_PAGESIZE chunks.  The address range may be any size provided
1584  * it is within the physical boundaries.
1585  */
1586 static int spi_nor_write(struct mtd_info *mtd, loff_t to, size_t len,
1587         size_t *retlen, const u_char *buf)
1588 {
1589         struct spi_nor *nor = mtd_to_spi_nor(mtd);
1590         size_t page_offset, page_remain, i;
1591         ssize_t ret;
1592
1593 #ifdef CONFIG_SPI_FLASH_SST
1594         /* sst nor chips use AAI word program */
1595         if (nor->info->flags & SST_WRITE)
1596                 return sst_write(mtd, to, len, retlen, buf);
1597 #endif
1598
1599         dev_dbg(nor->dev, "to 0x%08x, len %zd\n", (u32)to, len);
1600
1601         if (!len)
1602                 return 0;
1603
1604         for (i = 0; i < len; ) {
1605                 ssize_t written;
1606                 loff_t addr = to + i;
1607                 WATCHDOG_RESET();
1608
1609                 /*
1610                  * If page_size is a power of two, the offset can be quickly
1611                  * calculated with an AND operation. On the other cases we
1612                  * need to do a modulus operation (more expensive).
1613                  */
1614                 if (is_power_of_2(nor->page_size)) {
1615                         page_offset = addr & (nor->page_size - 1);
1616                 } else {
1617                         u64 aux = addr;
1618
1619                         page_offset = do_div(aux, nor->page_size);
1620                 }
1621                 /* the size of data remaining on the first page */
1622                 page_remain = min_t(size_t,
1623                                     nor->page_size - page_offset, len - i);
1624
1625 #ifdef CONFIG_SPI_FLASH_BAR
1626                 ret = write_bar(nor, addr);
1627                 if (ret < 0)
1628                         return ret;
1629 #endif
1630                 write_enable(nor);
1631                 ret = nor->write(nor, addr, page_remain, buf + i);
1632                 if (ret < 0)
1633                         goto write_err;
1634                 written = ret;
1635
1636                 ret = spi_nor_wait_till_ready(nor);
1637                 if (ret)
1638                         goto write_err;
1639                 *retlen += written;
1640                 i += written;
1641         }
1642
1643 write_err:
1644 #ifdef CONFIG_SPI_FLASH_BAR
1645         ret = clean_bar(nor);
1646 #endif
1647         return ret;
1648 }
1649
1650 #if defined(CONFIG_SPI_FLASH_MACRONIX) || defined(CONFIG_SPI_FLASH_ISSI)
1651 /**
1652  * macronix_quad_enable() - set QE bit in Status Register.
1653  * @nor:        pointer to a 'struct spi_nor'
1654  *
1655  * Set the Quad Enable (QE) bit in the Status Register.
1656  *
1657  * bit 6 of the Status Register is the QE bit for Macronix like QSPI memories.
1658  *
1659  * Return: 0 on success, -errno otherwise.
1660  */
1661 static int macronix_quad_enable(struct spi_nor *nor)
1662 {
1663         int ret, val;
1664
1665         val = read_sr(nor);
1666         if (val < 0)
1667                 return val;
1668         if (val & SR_QUAD_EN_MX)
1669                 return 0;
1670
1671         write_enable(nor);
1672
1673         write_sr(nor, val | SR_QUAD_EN_MX);
1674
1675         ret = spi_nor_wait_till_ready(nor);
1676         if (ret)
1677                 return ret;
1678
1679         ret = read_sr(nor);
1680         if (!(ret > 0 && (ret & SR_QUAD_EN_MX))) {
1681                 dev_err(nor->dev, "Macronix Quad bit not set\n");
1682                 return -EINVAL;
1683         }
1684
1685         return 0;
1686 }
1687 #endif
1688
1689 #if defined(CONFIG_SPI_FLASH_SPANSION) || defined(CONFIG_SPI_FLASH_WINBOND)
1690 /*
1691  * Write status Register and configuration register with 2 bytes
1692  * The first byte will be written to the status register, while the
1693  * second byte will be written to the configuration register.
1694  * Return negative if error occurred.
1695  */
1696 static int write_sr_cr(struct spi_nor *nor, u8 *sr_cr)
1697 {
1698         int ret;
1699
1700         write_enable(nor);
1701
1702         ret = nor->write_reg(nor, SPINOR_OP_WRSR, sr_cr, 2);
1703         if (ret < 0) {
1704                 dev_dbg(nor->dev,
1705                         "error while writing configuration register\n");
1706                 return -EINVAL;
1707         }
1708
1709         ret = spi_nor_wait_till_ready(nor);
1710         if (ret) {
1711                 dev_dbg(nor->dev,
1712                         "timeout while writing configuration register\n");
1713                 return ret;
1714         }
1715
1716         return 0;
1717 }
1718
1719 /**
1720  * spansion_read_cr_quad_enable() - set QE bit in Configuration Register.
1721  * @nor:        pointer to a 'struct spi_nor'
1722  *
1723  * Set the Quad Enable (QE) bit in the Configuration Register.
1724  * This function should be used with QSPI memories supporting the Read
1725  * Configuration Register (35h) instruction.
1726  *
1727  * bit 1 of the Configuration Register is the QE bit for Spansion like QSPI
1728  * memories.
1729  *
1730  * Return: 0 on success, -errno otherwise.
1731  */
1732 static int spansion_read_cr_quad_enable(struct spi_nor *nor)
1733 {
1734         u8 sr_cr[2];
1735         int ret;
1736
1737         /* Check current Quad Enable bit value. */
1738         ret = read_cr(nor);
1739         if (ret < 0) {
1740                 dev_dbg(nor->dev,
1741                         "error while reading configuration register\n");
1742                 return -EINVAL;
1743         }
1744
1745         if (ret & CR_QUAD_EN_SPAN)
1746                 return 0;
1747
1748         sr_cr[1] = ret | CR_QUAD_EN_SPAN;
1749
1750         /* Keep the current value of the Status Register. */
1751         ret = read_sr(nor);
1752         if (ret < 0) {
1753                 dev_dbg(nor->dev, "error while reading status register\n");
1754                 return -EINVAL;
1755         }
1756         sr_cr[0] = ret;
1757
1758         ret = write_sr_cr(nor, sr_cr);
1759         if (ret)
1760                 return ret;
1761
1762         /* Read back and check it. */
1763         ret = read_cr(nor);
1764         if (!(ret > 0 && (ret & CR_QUAD_EN_SPAN))) {
1765                 dev_dbg(nor->dev, "Spansion Quad bit not set\n");
1766                 return -EINVAL;
1767         }
1768
1769         return 0;
1770 }
1771
1772 #if CONFIG_IS_ENABLED(SPI_FLASH_SFDP_SUPPORT)
1773 /**
1774  * spansion_no_read_cr_quad_enable() - set QE bit in Configuration Register.
1775  * @nor:        pointer to a 'struct spi_nor'
1776  *
1777  * Set the Quad Enable (QE) bit in the Configuration Register.
1778  * This function should be used with QSPI memories not supporting the Read
1779  * Configuration Register (35h) instruction.
1780  *
1781  * bit 1 of the Configuration Register is the QE bit for Spansion like QSPI
1782  * memories.
1783  *
1784  * Return: 0 on success, -errno otherwise.
1785  */
1786 static int spansion_no_read_cr_quad_enable(struct spi_nor *nor)
1787 {
1788         u8 sr_cr[2];
1789         int ret;
1790
1791         /* Keep the current value of the Status Register. */
1792         ret = read_sr(nor);
1793         if (ret < 0) {
1794                 dev_dbg(nor->dev, "error while reading status register\n");
1795                 return -EINVAL;
1796         }
1797         sr_cr[0] = ret;
1798         sr_cr[1] = CR_QUAD_EN_SPAN;
1799
1800         return write_sr_cr(nor, sr_cr);
1801 }
1802
1803 #endif /* CONFIG_SPI_FLASH_SFDP_SUPPORT */
1804 #endif /* CONFIG_SPI_FLASH_SPANSION */
1805
1806 static void
1807 spi_nor_set_read_settings(struct spi_nor_read_command *read,
1808                           u8 num_mode_clocks,
1809                           u8 num_wait_states,
1810                           u8 opcode,
1811                           enum spi_nor_protocol proto)
1812 {
1813         read->num_mode_clocks = num_mode_clocks;
1814         read->num_wait_states = num_wait_states;
1815         read->opcode = opcode;
1816         read->proto = proto;
1817 }
1818
1819 static void
1820 spi_nor_set_pp_settings(struct spi_nor_pp_command *pp,
1821                         u8 opcode,
1822                         enum spi_nor_protocol proto)
1823 {
1824         pp->opcode = opcode;
1825         pp->proto = proto;
1826 }
1827
1828 #if CONFIG_IS_ENABLED(SPI_FLASH_SFDP_SUPPORT)
1829 /*
1830  * Serial Flash Discoverable Parameters (SFDP) parsing.
1831  */
1832
1833 /**
1834  * spi_nor_read_sfdp() - read Serial Flash Discoverable Parameters.
1835  * @nor:        pointer to a 'struct spi_nor'
1836  * @addr:       offset in the SFDP area to start reading data from
1837  * @len:        number of bytes to read
1838  * @buf:        buffer where the SFDP data are copied into (dma-safe memory)
1839  *
1840  * Whatever the actual numbers of bytes for address and dummy cycles are
1841  * for (Fast) Read commands, the Read SFDP (5Ah) instruction is always
1842  * followed by a 3-byte address and 8 dummy clock cycles.
1843  *
1844  * Return: 0 on success, -errno otherwise.
1845  */
1846 static int spi_nor_read_sfdp(struct spi_nor *nor, u32 addr,
1847                              size_t len, void *buf)
1848 {
1849         u8 addr_width, read_opcode, read_dummy;
1850         int ret;
1851
1852         read_opcode = nor->read_opcode;
1853         addr_width = nor->addr_width;
1854         read_dummy = nor->read_dummy;
1855
1856         nor->read_opcode = SPINOR_OP_RDSFDP;
1857         nor->addr_width = 3;
1858         nor->read_dummy = 8;
1859
1860         while (len) {
1861                 ret = nor->read(nor, addr, len, (u8 *)buf);
1862                 if (!ret || ret > len) {
1863                         ret = -EIO;
1864                         goto read_err;
1865                 }
1866                 if (ret < 0)
1867                         goto read_err;
1868
1869                 buf += ret;
1870                 addr += ret;
1871                 len -= ret;
1872         }
1873         ret = 0;
1874
1875 read_err:
1876         nor->read_opcode = read_opcode;
1877         nor->addr_width = addr_width;
1878         nor->read_dummy = read_dummy;
1879
1880         return ret;
1881 }
1882
1883 /* Fast Read settings. */
1884
1885 static void
1886 spi_nor_set_read_settings_from_bfpt(struct spi_nor_read_command *read,
1887                                     u16 half,
1888                                     enum spi_nor_protocol proto)
1889 {
1890         read->num_mode_clocks = (half >> 5) & 0x07;
1891         read->num_wait_states = (half >> 0) & 0x1f;
1892         read->opcode = (half >> 8) & 0xff;
1893         read->proto = proto;
1894 }
1895
1896 struct sfdp_bfpt_read {
1897         /* The Fast Read x-y-z hardware capability in params->hwcaps.mask. */
1898         u32                     hwcaps;
1899
1900         /*
1901          * The <supported_bit> bit in <supported_dword> BFPT DWORD tells us
1902          * whether the Fast Read x-y-z command is supported.
1903          */
1904         u32                     supported_dword;
1905         u32                     supported_bit;
1906
1907         /*
1908          * The half-word at offset <setting_shift> in <setting_dword> BFPT DWORD
1909          * encodes the op code, the number of mode clocks and the number of wait
1910          * states to be used by Fast Read x-y-z command.
1911          */
1912         u32                     settings_dword;
1913         u32                     settings_shift;
1914
1915         /* The SPI protocol for this Fast Read x-y-z command. */
1916         enum spi_nor_protocol   proto;
1917 };
1918
1919 static const struct sfdp_bfpt_read sfdp_bfpt_reads[] = {
1920         /* Fast Read 1-1-2 */
1921         {
1922                 SNOR_HWCAPS_READ_1_1_2,
1923                 BFPT_DWORD(1), BIT(16), /* Supported bit */
1924                 BFPT_DWORD(4), 0,       /* Settings */
1925                 SNOR_PROTO_1_1_2,
1926         },
1927
1928         /* Fast Read 1-2-2 */
1929         {
1930                 SNOR_HWCAPS_READ_1_2_2,
1931                 BFPT_DWORD(1), BIT(20), /* Supported bit */
1932                 BFPT_DWORD(4), 16,      /* Settings */
1933                 SNOR_PROTO_1_2_2,
1934         },
1935
1936         /* Fast Read 2-2-2 */
1937         {
1938                 SNOR_HWCAPS_READ_2_2_2,
1939                 BFPT_DWORD(5),  BIT(0), /* Supported bit */
1940                 BFPT_DWORD(6), 16,      /* Settings */
1941                 SNOR_PROTO_2_2_2,
1942         },
1943
1944         /* Fast Read 1-1-4 */
1945         {
1946                 SNOR_HWCAPS_READ_1_1_4,
1947                 BFPT_DWORD(1), BIT(22), /* Supported bit */
1948                 BFPT_DWORD(3), 16,      /* Settings */
1949                 SNOR_PROTO_1_1_4,
1950         },
1951
1952         /* Fast Read 1-4-4 */
1953         {
1954                 SNOR_HWCAPS_READ_1_4_4,
1955                 BFPT_DWORD(1), BIT(21), /* Supported bit */
1956                 BFPT_DWORD(3), 0,       /* Settings */
1957                 SNOR_PROTO_1_4_4,
1958         },
1959
1960         /* Fast Read 4-4-4 */
1961         {
1962                 SNOR_HWCAPS_READ_4_4_4,
1963                 BFPT_DWORD(5), BIT(4),  /* Supported bit */
1964                 BFPT_DWORD(7), 16,      /* Settings */
1965                 SNOR_PROTO_4_4_4,
1966         },
1967 };
1968
1969 struct sfdp_bfpt_erase {
1970         /*
1971          * The half-word at offset <shift> in DWORD <dwoard> encodes the
1972          * op code and erase sector size to be used by Sector Erase commands.
1973          */
1974         u32                     dword;
1975         u32                     shift;
1976 };
1977
1978 static const struct sfdp_bfpt_erase sfdp_bfpt_erases[] = {
1979         /* Erase Type 1 in DWORD8 bits[15:0] */
1980         {BFPT_DWORD(8), 0},
1981
1982         /* Erase Type 2 in DWORD8 bits[31:16] */
1983         {BFPT_DWORD(8), 16},
1984
1985         /* Erase Type 3 in DWORD9 bits[15:0] */
1986         {BFPT_DWORD(9), 0},
1987
1988         /* Erase Type 4 in DWORD9 bits[31:16] */
1989         {BFPT_DWORD(9), 16},
1990 };
1991
1992 static int spi_nor_hwcaps_read2cmd(u32 hwcaps);
1993
1994 static int
1995 spi_nor_post_bfpt_fixups(struct spi_nor *nor,
1996                          const struct sfdp_parameter_header *bfpt_header,
1997                          const struct sfdp_bfpt *bfpt,
1998                          struct spi_nor_flash_parameter *params)
1999 {
2000         if (nor->fixups && nor->fixups->post_bfpt)
2001                 return nor->fixups->post_bfpt(nor, bfpt_header, bfpt, params);
2002
2003         return 0;
2004 }
2005
2006 /**
2007  * spi_nor_parse_bfpt() - read and parse the Basic Flash Parameter Table.
2008  * @nor:                pointer to a 'struct spi_nor'
2009  * @bfpt_header:        pointer to the 'struct sfdp_parameter_header' describing
2010  *                      the Basic Flash Parameter Table length and version
2011  * @params:             pointer to the 'struct spi_nor_flash_parameter' to be
2012  *                      filled
2013  *
2014  * The Basic Flash Parameter Table is the main and only mandatory table as
2015  * defined by the SFDP (JESD216) specification.
2016  * It provides us with the total size (memory density) of the data array and
2017  * the number of address bytes for Fast Read, Page Program and Sector Erase
2018  * commands.
2019  * For Fast READ commands, it also gives the number of mode clock cycles and
2020  * wait states (regrouped in the number of dummy clock cycles) for each
2021  * supported instruction op code.
2022  * For Page Program, the page size is now available since JESD216 rev A, however
2023  * the supported instruction op codes are still not provided.
2024  * For Sector Erase commands, this table stores the supported instruction op
2025  * codes and the associated sector sizes.
2026  * Finally, the Quad Enable Requirements (QER) are also available since JESD216
2027  * rev A. The QER bits encode the manufacturer dependent procedure to be
2028  * executed to set the Quad Enable (QE) bit in some internal register of the
2029  * Quad SPI memory. Indeed the QE bit, when it exists, must be set before
2030  * sending any Quad SPI command to the memory. Actually, setting the QE bit
2031  * tells the memory to reassign its WP# and HOLD#/RESET# pins to functions IO2
2032  * and IO3 hence enabling 4 (Quad) I/O lines.
2033  *
2034  * Return: 0 on success, -errno otherwise.
2035  */
2036 static int spi_nor_parse_bfpt(struct spi_nor *nor,
2037                               const struct sfdp_parameter_header *bfpt_header,
2038                               struct spi_nor_flash_parameter *params)
2039 {
2040         struct mtd_info *mtd = &nor->mtd;
2041         struct sfdp_bfpt bfpt;
2042         size_t len;
2043         int i, cmd, err;
2044         u32 addr;
2045         u16 half;
2046
2047         /* JESD216 Basic Flash Parameter Table length is at least 9 DWORDs. */
2048         if (bfpt_header->length < BFPT_DWORD_MAX_JESD216)
2049                 return -EINVAL;
2050
2051         /* Read the Basic Flash Parameter Table. */
2052         len = min_t(size_t, sizeof(bfpt),
2053                     bfpt_header->length * sizeof(u32));
2054         addr = SFDP_PARAM_HEADER_PTP(bfpt_header);
2055         memset(&bfpt, 0, sizeof(bfpt));
2056         err = spi_nor_read_sfdp(nor,  addr, len, &bfpt);
2057         if (err < 0)
2058                 return err;
2059
2060         /* Fix endianness of the BFPT DWORDs. */
2061         for (i = 0; i < BFPT_DWORD_MAX; i++)
2062                 bfpt.dwords[i] = le32_to_cpu(bfpt.dwords[i]);
2063
2064         /* Number of address bytes. */
2065         switch (bfpt.dwords[BFPT_DWORD(1)] & BFPT_DWORD1_ADDRESS_BYTES_MASK) {
2066         case BFPT_DWORD1_ADDRESS_BYTES_3_ONLY:
2067                 nor->addr_width = 3;
2068                 break;
2069
2070         case BFPT_DWORD1_ADDRESS_BYTES_4_ONLY:
2071                 nor->addr_width = 4;
2072                 break;
2073
2074         default:
2075                 break;
2076         }
2077
2078         /* Flash Memory Density (in bits). */
2079         params->size = bfpt.dwords[BFPT_DWORD(2)];
2080         if (params->size & BIT(31)) {
2081                 params->size &= ~BIT(31);
2082
2083                 /*
2084                  * Prevent overflows on params->size. Anyway, a NOR of 2^64
2085                  * bits is unlikely to exist so this error probably means
2086                  * the BFPT we are reading is corrupted/wrong.
2087                  */
2088                 if (params->size > 63)
2089                         return -EINVAL;
2090
2091                 params->size = 1ULL << params->size;
2092         } else {
2093                 params->size++;
2094         }
2095         params->size >>= 3; /* Convert to bytes. */
2096
2097         /* Fast Read settings. */
2098         for (i = 0; i < ARRAY_SIZE(sfdp_bfpt_reads); i++) {
2099                 const struct sfdp_bfpt_read *rd = &sfdp_bfpt_reads[i];
2100                 struct spi_nor_read_command *read;
2101
2102                 if (!(bfpt.dwords[rd->supported_dword] & rd->supported_bit)) {
2103                         params->hwcaps.mask &= ~rd->hwcaps;
2104                         continue;
2105                 }
2106
2107                 params->hwcaps.mask |= rd->hwcaps;
2108                 cmd = spi_nor_hwcaps_read2cmd(rd->hwcaps);
2109                 read = &params->reads[cmd];
2110                 half = bfpt.dwords[rd->settings_dword] >> rd->settings_shift;
2111                 spi_nor_set_read_settings_from_bfpt(read, half, rd->proto);
2112         }
2113
2114         /* Sector Erase settings. */
2115         for (i = 0; i < ARRAY_SIZE(sfdp_bfpt_erases); i++) {
2116                 const struct sfdp_bfpt_erase *er = &sfdp_bfpt_erases[i];
2117                 u32 erasesize;
2118                 u8 opcode;
2119
2120                 half = bfpt.dwords[er->dword] >> er->shift;
2121                 erasesize = half & 0xff;
2122
2123                 /* erasesize == 0 means this Erase Type is not supported. */
2124                 if (!erasesize)
2125                         continue;
2126
2127                 erasesize = 1U << erasesize;
2128                 opcode = (half >> 8) & 0xff;
2129 #ifdef CONFIG_SPI_FLASH_USE_4K_SECTORS
2130                 if (erasesize == SZ_4K) {
2131                         nor->erase_opcode = opcode;
2132                         mtd->erasesize = erasesize;
2133                         break;
2134                 }
2135 #endif
2136                 if (!mtd->erasesize || mtd->erasesize < erasesize) {
2137                         nor->erase_opcode = opcode;
2138                         mtd->erasesize = erasesize;
2139                 }
2140         }
2141
2142         /* Stop here if not JESD216 rev A or later. */
2143         if (bfpt_header->length == BFPT_DWORD_MAX_JESD216)
2144                 return spi_nor_post_bfpt_fixups(nor, bfpt_header, &bfpt,
2145                                                 params);
2146
2147         /* Page size: this field specifies 'N' so the page size = 2^N bytes. */
2148         params->page_size = bfpt.dwords[BFPT_DWORD(11)];
2149         params->page_size &= BFPT_DWORD11_PAGE_SIZE_MASK;
2150         params->page_size >>= BFPT_DWORD11_PAGE_SIZE_SHIFT;
2151         params->page_size = 1U << params->page_size;
2152
2153         /* Quad Enable Requirements. */
2154         switch (bfpt.dwords[BFPT_DWORD(15)] & BFPT_DWORD15_QER_MASK) {
2155         case BFPT_DWORD15_QER_NONE:
2156                 params->quad_enable = NULL;
2157                 break;
2158 #if defined(CONFIG_SPI_FLASH_SPANSION) || defined(CONFIG_SPI_FLASH_WINBOND)
2159         case BFPT_DWORD15_QER_SR2_BIT1_BUGGY:
2160         case BFPT_DWORD15_QER_SR2_BIT1_NO_RD:
2161                 params->quad_enable = spansion_no_read_cr_quad_enable;
2162                 break;
2163 #endif
2164 #if defined(CONFIG_SPI_FLASH_MACRONIX) || defined(CONFIG_SPI_FLASH_ISSI)
2165         case BFPT_DWORD15_QER_SR1_BIT6:
2166                 params->quad_enable = macronix_quad_enable;
2167                 break;
2168 #endif
2169 #if defined(CONFIG_SPI_FLASH_SPANSION) || defined(CONFIG_SPI_FLASH_WINBOND)
2170         case BFPT_DWORD15_QER_SR2_BIT1:
2171                 params->quad_enable = spansion_read_cr_quad_enable;
2172                 break;
2173 #endif
2174         default:
2175                 dev_dbg(nor->dev, "BFPT QER reserved value used\n");
2176                 break;
2177         }
2178
2179         /* Soft Reset support. */
2180         if (bfpt.dwords[BFPT_DWORD(16)] & BFPT_DWORD16_SOFT_RST)
2181                 nor->flags |= SNOR_F_SOFT_RESET;
2182
2183         /* Stop here if JESD216 rev B. */
2184         if (bfpt_header->length == BFPT_DWORD_MAX_JESD216B)
2185                 return spi_nor_post_bfpt_fixups(nor, bfpt_header, &bfpt,
2186                                                 params);
2187
2188         /* 8D-8D-8D command extension. */
2189         switch (bfpt.dwords[BFPT_DWORD(18)] & BFPT_DWORD18_CMD_EXT_MASK) {
2190         case BFPT_DWORD18_CMD_EXT_REP:
2191                 nor->cmd_ext_type = SPI_NOR_EXT_REPEAT;
2192                 break;
2193
2194         case BFPT_DWORD18_CMD_EXT_INV:
2195                 nor->cmd_ext_type = SPI_NOR_EXT_INVERT;
2196                 break;
2197
2198         case BFPT_DWORD18_CMD_EXT_RES:
2199                 return -EINVAL;
2200
2201         case BFPT_DWORD18_CMD_EXT_16B:
2202                 dev_err(nor->dev, "16-bit opcodes not supported\n");
2203                 return -ENOTSUPP;
2204         }
2205
2206         return spi_nor_post_bfpt_fixups(nor, bfpt_header, &bfpt, params);
2207 }
2208
2209 /**
2210  * spi_nor_parse_microchip_sfdp() - parse the Microchip manufacturer specific
2211  * SFDP table.
2212  * @nor:                pointer to a 'struct spi_nor'.
2213  * @param_header:       pointer to the SFDP parameter header.
2214  *
2215  * Return: 0 on success, -errno otherwise.
2216  */
2217 static int
2218 spi_nor_parse_microchip_sfdp(struct spi_nor *nor,
2219                              const struct sfdp_parameter_header *param_header)
2220 {
2221         size_t size;
2222         u32 addr;
2223         int ret;
2224
2225         size = param_header->length * sizeof(u32);
2226         addr = SFDP_PARAM_HEADER_PTP(param_header);
2227
2228         nor->manufacturer_sfdp = devm_kmalloc(nor->dev, size, GFP_KERNEL);
2229         if (!nor->manufacturer_sfdp)
2230                 return -ENOMEM;
2231
2232         ret = spi_nor_read_sfdp(nor, addr, size, nor->manufacturer_sfdp);
2233
2234         return ret;
2235 }
2236
2237 /**
2238  * spi_nor_parse_profile1() - parse the xSPI Profile 1.0 table
2239  * @nor:                pointer to a 'struct spi_nor'
2240  * @profile1_header:    pointer to the 'struct sfdp_parameter_header' describing
2241  *                      the 4-Byte Address Instruction Table length and version.
2242  * @params:             pointer to the 'struct spi_nor_flash_parameter' to be.
2243  *
2244  * Return: 0 on success, -errno otherwise.
2245  */
2246 static int spi_nor_parse_profile1(struct spi_nor *nor,
2247                                   const struct sfdp_parameter_header *profile1_header,
2248                                   struct spi_nor_flash_parameter *params)
2249 {
2250         u32 *table, opcode, addr;
2251         size_t len;
2252         int ret, i;
2253         u8 dummy;
2254
2255         len = profile1_header->length * sizeof(*table);
2256         table = kmalloc(len, GFP_KERNEL);
2257         if (!table)
2258                 return -ENOMEM;
2259
2260         addr = SFDP_PARAM_HEADER_PTP(profile1_header);
2261         ret = spi_nor_read_sfdp(nor, addr, len, table);
2262         if (ret)
2263                 goto out;
2264
2265         /* Fix endianness of the table DWORDs. */
2266         for (i = 0; i < profile1_header->length; i++)
2267                 table[i] = le32_to_cpu(table[i]);
2268
2269         /* Get 8D-8D-8D fast read opcode and dummy cycles. */
2270         opcode = FIELD_GET(PROFILE1_DWORD1_RD_FAST_CMD, table[0]);
2271
2272         /*
2273          * We don't know what speed the controller is running at. Find the
2274          * dummy cycles for the fastest frequency the flash can run at to be
2275          * sure we are never short of dummy cycles. A value of 0 means the
2276          * frequency is not supported.
2277          *
2278          * Default to PROFILE1_DUMMY_DEFAULT if we don't find anything, and let
2279          * flashes set the correct value if needed in their fixup hooks.
2280          */
2281         dummy = FIELD_GET(PROFILE1_DWORD4_DUMMY_200MHZ, table[3]);
2282         if (!dummy)
2283                 dummy = FIELD_GET(PROFILE1_DWORD5_DUMMY_166MHZ, table[4]);
2284         if (!dummy)
2285                 dummy = FIELD_GET(PROFILE1_DWORD5_DUMMY_133MHZ, table[4]);
2286         if (!dummy)
2287                 dummy = FIELD_GET(PROFILE1_DWORD5_DUMMY_100MHZ, table[4]);
2288         if (!dummy)
2289                 dummy = PROFILE1_DUMMY_DEFAULT;
2290
2291         /* Round up to an even value to avoid tripping controllers up. */
2292         dummy = ROUND_UP_TO(dummy, 2);
2293
2294         /* Update the fast read settings. */
2295         spi_nor_set_read_settings(&params->reads[SNOR_CMD_READ_8_8_8_DTR],
2296                                   0, dummy, opcode,
2297                                   SNOR_PROTO_8_8_8_DTR);
2298
2299         /*
2300          * Set the Read Status Register dummy cycles and dummy address bytes.
2301          */
2302         if (table[0] & PROFILE1_DWORD1_RDSR_DUMMY)
2303                 params->rdsr_dummy = 8;
2304         else
2305                 params->rdsr_dummy = 4;
2306
2307         if (table[0] & PROFILE1_DWORD1_RDSR_ADDR_BYTES)
2308                 params->rdsr_addr_nbytes = 4;
2309         else
2310                 params->rdsr_addr_nbytes = 0;
2311
2312 out:
2313         kfree(table);
2314         return ret;
2315 }
2316
2317 /**
2318  * spi_nor_parse_sfdp() - parse the Serial Flash Discoverable Parameters.
2319  * @nor:                pointer to a 'struct spi_nor'
2320  * @params:             pointer to the 'struct spi_nor_flash_parameter' to be
2321  *                      filled
2322  *
2323  * The Serial Flash Discoverable Parameters are described by the JEDEC JESD216
2324  * specification. This is a standard which tends to supported by almost all
2325  * (Q)SPI memory manufacturers. Those hard-coded tables allow us to learn at
2326  * runtime the main parameters needed to perform basic SPI flash operations such
2327  * as Fast Read, Page Program or Sector Erase commands.
2328  *
2329  * Return: 0 on success, -errno otherwise.
2330  */
2331 static int spi_nor_parse_sfdp(struct spi_nor *nor,
2332                               struct spi_nor_flash_parameter *params)
2333 {
2334         const struct sfdp_parameter_header *param_header, *bfpt_header;
2335         struct sfdp_parameter_header *param_headers = NULL;
2336         struct sfdp_header header;
2337         size_t psize;
2338         int i, err;
2339
2340         /* Get the SFDP header. */
2341         err = spi_nor_read_sfdp(nor, 0, sizeof(header), &header);
2342         if (err < 0)
2343                 return err;
2344
2345         /* Check the SFDP header version. */
2346         if (le32_to_cpu(header.signature) != SFDP_SIGNATURE ||
2347             header.major != SFDP_JESD216_MAJOR)
2348                 return -EINVAL;
2349
2350         /*
2351          * Verify that the first and only mandatory parameter header is a
2352          * Basic Flash Parameter Table header as specified in JESD216.
2353          */
2354         bfpt_header = &header.bfpt_header;
2355         if (SFDP_PARAM_HEADER_ID(bfpt_header) != SFDP_BFPT_ID ||
2356             bfpt_header->major != SFDP_JESD216_MAJOR)
2357                 return -EINVAL;
2358
2359         /*
2360          * Allocate memory then read all parameter headers with a single
2361          * Read SFDP command. These parameter headers will actually be parsed
2362          * twice: a first time to get the latest revision of the basic flash
2363          * parameter table, then a second time to handle the supported optional
2364          * tables.
2365          * Hence we read the parameter headers once for all to reduce the
2366          * processing time. Also we use kmalloc() instead of devm_kmalloc()
2367          * because we don't need to keep these parameter headers: the allocated
2368          * memory is always released with kfree() before exiting this function.
2369          */
2370         if (header.nph) {
2371                 psize = header.nph * sizeof(*param_headers);
2372
2373                 param_headers = kmalloc(psize, GFP_KERNEL);
2374                 if (!param_headers)
2375                         return -ENOMEM;
2376
2377                 err = spi_nor_read_sfdp(nor, sizeof(header),
2378                                         psize, param_headers);
2379                 if (err < 0) {
2380                         dev_err(nor->dev,
2381                                 "failed to read SFDP parameter headers\n");
2382                         goto exit;
2383                 }
2384         }
2385
2386         /*
2387          * Check other parameter headers to get the latest revision of
2388          * the basic flash parameter table.
2389          */
2390         for (i = 0; i < header.nph; i++) {
2391                 param_header = &param_headers[i];
2392
2393                 if (SFDP_PARAM_HEADER_ID(param_header) == SFDP_BFPT_ID &&
2394                     param_header->major == SFDP_JESD216_MAJOR &&
2395                     (param_header->minor > bfpt_header->minor ||
2396                      (param_header->minor == bfpt_header->minor &&
2397                       param_header->length > bfpt_header->length)))
2398                         bfpt_header = param_header;
2399         }
2400
2401         err = spi_nor_parse_bfpt(nor, bfpt_header, params);
2402         if (err)
2403                 goto exit;
2404
2405         /* Parse other parameter headers. */
2406         for (i = 0; i < header.nph; i++) {
2407                 param_header = &param_headers[i];
2408
2409                 switch (SFDP_PARAM_HEADER_ID(param_header)) {
2410                 case SFDP_SECTOR_MAP_ID:
2411                         dev_info(nor->dev,
2412                                  "non-uniform erase sector maps are not supported yet.\n");
2413                         break;
2414
2415                 case SFDP_SST_ID:
2416                         err = spi_nor_parse_microchip_sfdp(nor, param_header);
2417                         break;
2418
2419                 case SFDP_PROFILE1_ID:
2420                         err = spi_nor_parse_profile1(nor, param_header, params);
2421                         break;
2422
2423                 default:
2424                         break;
2425                 }
2426
2427                 if (err) {
2428                         dev_warn(nor->dev,
2429                                  "Failed to parse optional parameter table: %04x\n",
2430                                  SFDP_PARAM_HEADER_ID(param_header));
2431                         /*
2432                          * Let's not drop all information we extracted so far
2433                          * if optional table parsers fail. In case of failing,
2434                          * each optional parser is responsible to roll back to
2435                          * the previously known spi_nor data.
2436                          */
2437                         err = 0;
2438                 }
2439         }
2440
2441 exit:
2442         kfree(param_headers);
2443         return err;
2444 }
2445 #else
2446 static int spi_nor_parse_sfdp(struct spi_nor *nor,
2447                               struct spi_nor_flash_parameter *params)
2448 {
2449         return -EINVAL;
2450 }
2451 #endif /* SPI_FLASH_SFDP_SUPPORT */
2452
2453 /**
2454  * spi_nor_post_sfdp_fixups() - Updates the flash's parameters and settings
2455  * after SFDP has been parsed (is also called for SPI NORs that do not
2456  * support RDSFDP).
2457  * @nor:        pointer to a 'struct spi_nor'
2458  *
2459  * Typically used to tweak various parameters that could not be extracted by
2460  * other means (i.e. when information provided by the SFDP/flash_info tables
2461  * are incomplete or wrong).
2462  */
2463 static void spi_nor_post_sfdp_fixups(struct spi_nor *nor,
2464                                      struct spi_nor_flash_parameter *params)
2465 {
2466         if (nor->fixups && nor->fixups->post_sfdp)
2467                 nor->fixups->post_sfdp(nor, params);
2468 }
2469
2470 static void spi_nor_default_init_fixups(struct spi_nor *nor)
2471 {
2472         if (nor->fixups && nor->fixups->default_init)
2473                 nor->fixups->default_init(nor);
2474 }
2475
2476 static int spi_nor_init_params(struct spi_nor *nor,
2477                                const struct flash_info *info,
2478                                struct spi_nor_flash_parameter *params)
2479 {
2480         /* Set legacy flash parameters as default. */
2481         memset(params, 0, sizeof(*params));
2482
2483         /* Set SPI NOR sizes. */
2484         params->size = info->sector_size * info->n_sectors;
2485         params->page_size = info->page_size;
2486
2487         /* (Fast) Read settings. */
2488         params->hwcaps.mask |= SNOR_HWCAPS_READ;
2489         spi_nor_set_read_settings(&params->reads[SNOR_CMD_READ],
2490                                   0, 0, SPINOR_OP_READ,
2491                                   SNOR_PROTO_1_1_1);
2492
2493         if (!(info->flags & SPI_NOR_NO_FR)) {
2494                 params->hwcaps.mask |= SNOR_HWCAPS_READ_FAST;
2495                 spi_nor_set_read_settings(&params->reads[SNOR_CMD_READ_FAST],
2496                                           0, 8, SPINOR_OP_READ_FAST,
2497                                           SNOR_PROTO_1_1_1);
2498         }
2499
2500         if (info->flags & SPI_NOR_DUAL_READ) {
2501                 params->hwcaps.mask |= SNOR_HWCAPS_READ_1_1_2;
2502                 spi_nor_set_read_settings(&params->reads[SNOR_CMD_READ_1_1_2],
2503                                           0, 8, SPINOR_OP_READ_1_1_2,
2504                                           SNOR_PROTO_1_1_2);
2505         }
2506
2507         if (info->flags & SPI_NOR_QUAD_READ) {
2508                 params->hwcaps.mask |= SNOR_HWCAPS_READ_1_1_4;
2509                 spi_nor_set_read_settings(&params->reads[SNOR_CMD_READ_1_1_4],
2510                                           0, 8, SPINOR_OP_READ_1_1_4,
2511                                           SNOR_PROTO_1_1_4);
2512         }
2513
2514         if (info->flags & SPI_NOR_OCTAL_READ) {
2515                 params->hwcaps.mask |= SNOR_HWCAPS_READ_1_1_8;
2516                 spi_nor_set_read_settings(&params->reads[SNOR_CMD_READ_1_1_8],
2517                                           0, 8, SPINOR_OP_READ_1_1_8,
2518                                           SNOR_PROTO_1_1_8);
2519         }
2520
2521         if (info->flags & SPI_NOR_OCTAL_DTR_READ) {
2522                 params->hwcaps.mask |= SNOR_HWCAPS_READ_8_8_8_DTR;
2523                 spi_nor_set_read_settings(&params->reads[SNOR_CMD_READ_8_8_8_DTR],
2524                                           0, 20, SPINOR_OP_READ_FAST,
2525                                           SNOR_PROTO_8_8_8_DTR);
2526         }
2527
2528         /* Page Program settings. */
2529         params->hwcaps.mask |= SNOR_HWCAPS_PP;
2530         spi_nor_set_pp_settings(&params->page_programs[SNOR_CMD_PP],
2531                                 SPINOR_OP_PP, SNOR_PROTO_1_1_1);
2532
2533         /*
2534          * Since xSPI Page Program opcode is backward compatible with
2535          * Legacy SPI, use Legacy SPI opcode there as well.
2536          */
2537         spi_nor_set_pp_settings(&params->page_programs[SNOR_CMD_PP_8_8_8_DTR],
2538                                 SPINOR_OP_PP, SNOR_PROTO_8_8_8_DTR);
2539
2540         if (info->flags & SPI_NOR_QUAD_READ) {
2541                 params->hwcaps.mask |= SNOR_HWCAPS_PP_1_1_4;
2542                 spi_nor_set_pp_settings(&params->page_programs[SNOR_CMD_PP_1_1_4],
2543                                         SPINOR_OP_PP_1_1_4, SNOR_PROTO_1_1_4);
2544         }
2545
2546         /* Select the procedure to set the Quad Enable bit. */
2547         if (params->hwcaps.mask & (SNOR_HWCAPS_READ_QUAD |
2548                                    SNOR_HWCAPS_PP_QUAD)) {
2549                 switch (JEDEC_MFR(info)) {
2550 #if defined(CONFIG_SPI_FLASH_MACRONIX) || defined(CONFIG_SPI_FLASH_ISSI)
2551                 case SNOR_MFR_MACRONIX:
2552                 case SNOR_MFR_ISSI:
2553                         params->quad_enable = macronix_quad_enable;
2554                         break;
2555 #endif
2556                 case SNOR_MFR_ST:
2557                 case SNOR_MFR_MICRON:
2558                         break;
2559
2560                 default:
2561 #if defined(CONFIG_SPI_FLASH_SPANSION) || defined(CONFIG_SPI_FLASH_WINBOND)
2562                         /* Kept only for backward compatibility purpose. */
2563                         params->quad_enable = spansion_read_cr_quad_enable;
2564 #endif
2565                         break;
2566                 }
2567         }
2568
2569         spi_nor_default_init_fixups(nor);
2570
2571         /* Override the parameters with data read from SFDP tables. */
2572         nor->addr_width = 0;
2573         nor->mtd.erasesize = 0;
2574         if ((info->flags & (SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ |
2575              SPI_NOR_OCTAL_DTR_READ)) &&
2576             !(info->flags & SPI_NOR_SKIP_SFDP)) {
2577                 struct spi_nor_flash_parameter sfdp_params;
2578
2579                 memcpy(&sfdp_params, params, sizeof(sfdp_params));
2580                 if (spi_nor_parse_sfdp(nor, &sfdp_params)) {
2581                         nor->addr_width = 0;
2582                         nor->mtd.erasesize = 0;
2583                 } else {
2584                         memcpy(params, &sfdp_params, sizeof(*params));
2585                 }
2586         }
2587
2588         spi_nor_post_sfdp_fixups(nor, params);
2589
2590         return 0;
2591 }
2592
2593 static int spi_nor_hwcaps2cmd(u32 hwcaps, const int table[][2], size_t size)
2594 {
2595         size_t i;
2596
2597         for (i = 0; i < size; i++)
2598                 if (table[i][0] == (int)hwcaps)
2599                         return table[i][1];
2600
2601         return -EINVAL;
2602 }
2603
2604 static int spi_nor_hwcaps_read2cmd(u32 hwcaps)
2605 {
2606         static const int hwcaps_read2cmd[][2] = {
2607                 { SNOR_HWCAPS_READ,             SNOR_CMD_READ },
2608                 { SNOR_HWCAPS_READ_FAST,        SNOR_CMD_READ_FAST },
2609                 { SNOR_HWCAPS_READ_1_1_1_DTR,   SNOR_CMD_READ_1_1_1_DTR },
2610                 { SNOR_HWCAPS_READ_1_1_2,       SNOR_CMD_READ_1_1_2 },
2611                 { SNOR_HWCAPS_READ_1_2_2,       SNOR_CMD_READ_1_2_2 },
2612                 { SNOR_HWCAPS_READ_2_2_2,       SNOR_CMD_READ_2_2_2 },
2613                 { SNOR_HWCAPS_READ_1_2_2_DTR,   SNOR_CMD_READ_1_2_2_DTR },
2614                 { SNOR_HWCAPS_READ_1_1_4,       SNOR_CMD_READ_1_1_4 },
2615                 { SNOR_HWCAPS_READ_1_4_4,       SNOR_CMD_READ_1_4_4 },
2616                 { SNOR_HWCAPS_READ_4_4_4,       SNOR_CMD_READ_4_4_4 },
2617                 { SNOR_HWCAPS_READ_1_4_4_DTR,   SNOR_CMD_READ_1_4_4_DTR },
2618                 { SNOR_HWCAPS_READ_1_1_8,       SNOR_CMD_READ_1_1_8 },
2619                 { SNOR_HWCAPS_READ_1_8_8,       SNOR_CMD_READ_1_8_8 },
2620                 { SNOR_HWCAPS_READ_8_8_8,       SNOR_CMD_READ_8_8_8 },
2621                 { SNOR_HWCAPS_READ_1_8_8_DTR,   SNOR_CMD_READ_1_8_8_DTR },
2622                 { SNOR_HWCAPS_READ_8_8_8_DTR,   SNOR_CMD_READ_8_8_8_DTR },
2623         };
2624
2625         return spi_nor_hwcaps2cmd(hwcaps, hwcaps_read2cmd,
2626                                   ARRAY_SIZE(hwcaps_read2cmd));
2627 }
2628
2629 static int spi_nor_hwcaps_pp2cmd(u32 hwcaps)
2630 {
2631         static const int hwcaps_pp2cmd[][2] = {
2632                 { SNOR_HWCAPS_PP,               SNOR_CMD_PP },
2633                 { SNOR_HWCAPS_PP_1_1_4,         SNOR_CMD_PP_1_1_4 },
2634                 { SNOR_HWCAPS_PP_1_4_4,         SNOR_CMD_PP_1_4_4 },
2635                 { SNOR_HWCAPS_PP_4_4_4,         SNOR_CMD_PP_4_4_4 },
2636                 { SNOR_HWCAPS_PP_1_1_8,         SNOR_CMD_PP_1_1_8 },
2637                 { SNOR_HWCAPS_PP_1_8_8,         SNOR_CMD_PP_1_8_8 },
2638                 { SNOR_HWCAPS_PP_8_8_8,         SNOR_CMD_PP_8_8_8 },
2639                 { SNOR_HWCAPS_PP_8_8_8_DTR,     SNOR_CMD_PP_8_8_8_DTR },
2640         };
2641
2642         return spi_nor_hwcaps2cmd(hwcaps, hwcaps_pp2cmd,
2643                                   ARRAY_SIZE(hwcaps_pp2cmd));
2644 }
2645
2646 #ifdef CONFIG_SPI_FLASH_SMART_HWCAPS
2647 /**
2648  * spi_nor_check_op - check if the operation is supported by controller
2649  * @nor:        pointer to a 'struct spi_nor'
2650  * @op:         pointer to op template to be checked
2651  *
2652  * Returns 0 if operation is supported, -ENOTSUPP otherwise.
2653  */
2654 static int spi_nor_check_op(struct spi_nor *nor,
2655                             struct spi_mem_op *op)
2656 {
2657         /*
2658          * First test with 4 address bytes. The opcode itself might be a 3B
2659          * addressing opcode but we don't care, because SPI controller
2660          * implementation should not check the opcode, but just the sequence.
2661          */
2662         op->addr.nbytes = 4;
2663         if (!spi_mem_supports_op(nor->spi, op)) {
2664                 if (nor->mtd.size > SZ_16M)
2665                         return -ENOTSUPP;
2666
2667                 /* If flash size <= 16MB, 3 address bytes are sufficient */
2668                 op->addr.nbytes = 3;
2669                 if (!spi_mem_supports_op(nor->spi, op))
2670                         return -ENOTSUPP;
2671         }
2672
2673         return 0;
2674 }
2675
2676 /**
2677  * spi_nor_check_readop - check if the read op is supported by controller
2678  * @nor:         pointer to a 'struct spi_nor'
2679  * @read:        pointer to op template to be checked
2680  *
2681  * Returns 0 if operation is supported, -ENOTSUPP otherwise.
2682  */
2683 static int spi_nor_check_readop(struct spi_nor *nor,
2684                                 const struct spi_nor_read_command *read)
2685 {
2686         struct spi_mem_op op = SPI_MEM_OP(SPI_MEM_OP_CMD(read->opcode, 0),
2687                                           SPI_MEM_OP_ADDR(3, 0, 0),
2688                                           SPI_MEM_OP_DUMMY(1, 0),
2689                                           SPI_MEM_OP_DATA_IN(2, NULL, 0));
2690
2691         spi_nor_setup_op(nor, &op, read->proto);
2692
2693         op.dummy.nbytes = (read->num_mode_clocks + read->num_wait_states) *
2694                           op.dummy.buswidth / 8;
2695         if (spi_nor_protocol_is_dtr(nor->read_proto))
2696                 op.dummy.nbytes *= 2;
2697
2698         return spi_nor_check_op(nor, &op);
2699 }
2700
2701 /**
2702  * spi_nor_check_pp - check if the page program op is supported by controller
2703  * @nor:         pointer to a 'struct spi_nor'
2704  * @pp:          pointer to op template to be checked
2705  *
2706  * Returns 0 if operation is supported, -ENOTSUPP otherwise.
2707  */
2708 static int spi_nor_check_pp(struct spi_nor *nor,
2709                             const struct spi_nor_pp_command *pp)
2710 {
2711         struct spi_mem_op op = SPI_MEM_OP(SPI_MEM_OP_CMD(pp->opcode, 0),
2712                                           SPI_MEM_OP_ADDR(3, 0, 0),
2713                                           SPI_MEM_OP_NO_DUMMY,
2714                                           SPI_MEM_OP_DATA_OUT(2, NULL, 0));
2715
2716         spi_nor_setup_op(nor, &op, pp->proto);
2717
2718         return spi_nor_check_op(nor, &op);
2719 }
2720
2721 /**
2722  * spi_nor_adjust_hwcaps - Find optimal Read/Write protocol based on SPI
2723  *                         controller capabilities
2724  * @nor:        pointer to a 'struct spi_nor'
2725  * @params:     pointer to the 'struct spi_nor_flash_parameter'
2726  *              representing SPI NOR flash capabilities
2727  * @hwcaps:     pointer to resulting capabilities after adjusting
2728  *              according to controller and flash's capability
2729  *
2730  * Discard caps based on what the SPI controller actually supports (using
2731  * spi_mem_supports_op()).
2732  */
2733 static void
2734 spi_nor_adjust_hwcaps(struct spi_nor *nor,
2735                       const struct spi_nor_flash_parameter *params,
2736                       u32 *hwcaps)
2737 {
2738         unsigned int cap;
2739
2740         /*
2741          * Enable all caps by default. We will mask them after checking what's
2742          * really supported using spi_mem_supports_op().
2743          */
2744         *hwcaps = SNOR_HWCAPS_ALL;
2745
2746         /* X-X-X modes are not supported yet, mask them all. */
2747         *hwcaps &= ~SNOR_HWCAPS_X_X_X;
2748
2749         /*
2750          * If the reset line is broken, we do not want to enter a stateful
2751          * mode.
2752          */
2753         if (nor->flags & SNOR_F_BROKEN_RESET)
2754                 *hwcaps &= ~(SNOR_HWCAPS_X_X_X | SNOR_HWCAPS_X_X_X_DTR);
2755
2756         for (cap = 0; cap < sizeof(*hwcaps) * BITS_PER_BYTE; cap++) {
2757                 int rdidx, ppidx;
2758
2759                 if (!(*hwcaps & BIT(cap)))
2760                         continue;
2761
2762                 rdidx = spi_nor_hwcaps_read2cmd(BIT(cap));
2763                 if (rdidx >= 0 &&
2764                     spi_nor_check_readop(nor, &params->reads[rdidx]))
2765                         *hwcaps &= ~BIT(cap);
2766
2767                 ppidx = spi_nor_hwcaps_pp2cmd(BIT(cap));
2768                 if (ppidx < 0)
2769                         continue;
2770
2771                 if (spi_nor_check_pp(nor, &params->page_programs[ppidx]))
2772                         *hwcaps &= ~BIT(cap);
2773         }
2774 }
2775 #else
2776 /**
2777  * spi_nor_adjust_hwcaps - Find optimal Read/Write protocol based on SPI
2778  *                         controller capabilities
2779  * @nor:        pointer to a 'struct spi_nor'
2780  * @params:     pointer to the 'struct spi_nor_flash_parameter'
2781  *              representing SPI NOR flash capabilities
2782  * @hwcaps:     pointer to resulting capabilities after adjusting
2783  *              according to controller and flash's capability
2784  *
2785  * Select caps based on what the SPI controller and SPI flash both support.
2786  */
2787 static void
2788 spi_nor_adjust_hwcaps(struct spi_nor *nor,
2789                       const struct spi_nor_flash_parameter *params,
2790                       u32 *hwcaps)
2791 {
2792         struct spi_slave *spi = nor->spi;
2793         u32 ignored_mask = (SNOR_HWCAPS_READ_2_2_2 |
2794                             SNOR_HWCAPS_READ_4_4_4 |
2795                             SNOR_HWCAPS_READ_8_8_8 |
2796                             SNOR_HWCAPS_PP_4_4_4   |
2797                             SNOR_HWCAPS_PP_8_8_8);
2798         u32 spi_hwcaps = (SNOR_HWCAPS_READ | SNOR_HWCAPS_READ_FAST |
2799                           SNOR_HWCAPS_PP);
2800
2801         /* Get the hardware capabilities the SPI controller supports. */
2802         if (spi->mode & SPI_RX_OCTAL) {
2803                 spi_hwcaps |= SNOR_HWCAPS_READ_1_1_8;
2804
2805                 if (spi->mode & SPI_TX_OCTAL)
2806                         spi_hwcaps |= (SNOR_HWCAPS_READ_1_8_8 |
2807                                         SNOR_HWCAPS_PP_1_1_8 |
2808                                         SNOR_HWCAPS_PP_1_8_8);
2809         } else if (spi->mode & SPI_RX_QUAD) {
2810                 spi_hwcaps |= SNOR_HWCAPS_READ_1_1_4;
2811
2812                 if (spi->mode & SPI_TX_QUAD)
2813                         spi_hwcaps |= (SNOR_HWCAPS_READ_1_4_4 |
2814                                         SNOR_HWCAPS_PP_1_1_4 |
2815                                         SNOR_HWCAPS_PP_1_4_4);
2816         } else if (spi->mode & SPI_RX_DUAL) {
2817                 spi_hwcaps |= SNOR_HWCAPS_READ_1_1_2;
2818
2819                 if (spi->mode & SPI_TX_DUAL)
2820                         spi_hwcaps |= SNOR_HWCAPS_READ_1_2_2;
2821         }
2822
2823         /*
2824          * Keep only the hardware capabilities supported by both the SPI
2825          * controller and the SPI flash memory.
2826          */
2827         *hwcaps = spi_hwcaps & params->hwcaps.mask;
2828         if (*hwcaps & ignored_mask) {
2829                 dev_dbg(nor->dev,
2830                         "SPI n-n-n protocols are not supported yet.\n");
2831                 *hwcaps &= ~ignored_mask;
2832         }
2833 }
2834 #endif /* CONFIG_SPI_FLASH_SMART_HWCAPS */
2835
2836 static int spi_nor_select_read(struct spi_nor *nor,
2837                                const struct spi_nor_flash_parameter *params,
2838                                u32 shared_hwcaps)
2839 {
2840         int cmd, best_match = fls(shared_hwcaps & SNOR_HWCAPS_READ_MASK) - 1;
2841         const struct spi_nor_read_command *read;
2842
2843         if (best_match < 0)
2844                 return -EINVAL;
2845
2846         cmd = spi_nor_hwcaps_read2cmd(BIT(best_match));
2847         if (cmd < 0)
2848                 return -EINVAL;
2849
2850         read = &params->reads[cmd];
2851         nor->read_opcode = read->opcode;
2852         nor->read_proto = read->proto;
2853
2854         /*
2855          * In the spi-nor framework, we don't need to make the difference
2856          * between mode clock cycles and wait state clock cycles.
2857          * Indeed, the value of the mode clock cycles is used by a QSPI
2858          * flash memory to know whether it should enter or leave its 0-4-4
2859          * (Continuous Read / XIP) mode.
2860          * eXecution In Place is out of the scope of the mtd sub-system.
2861          * Hence we choose to merge both mode and wait state clock cycles
2862          * into the so called dummy clock cycles.
2863          */
2864         nor->read_dummy = read->num_mode_clocks + read->num_wait_states;
2865         return 0;
2866 }
2867
2868 static int spi_nor_select_pp(struct spi_nor *nor,
2869                              const struct spi_nor_flash_parameter *params,
2870                              u32 shared_hwcaps)
2871 {
2872         int cmd, best_match = fls(shared_hwcaps & SNOR_HWCAPS_PP_MASK) - 1;
2873         const struct spi_nor_pp_command *pp;
2874
2875         if (best_match < 0)
2876                 return -EINVAL;
2877
2878         cmd = spi_nor_hwcaps_pp2cmd(BIT(best_match));
2879         if (cmd < 0)
2880                 return -EINVAL;
2881
2882         pp = &params->page_programs[cmd];
2883         nor->program_opcode = pp->opcode;
2884         nor->write_proto = pp->proto;
2885         return 0;
2886 }
2887
2888 static int spi_nor_select_erase(struct spi_nor *nor,
2889                                 const struct flash_info *info)
2890 {
2891         struct mtd_info *mtd = &nor->mtd;
2892
2893         /* Do nothing if already configured from SFDP. */
2894         if (mtd->erasesize)
2895                 return 0;
2896
2897 #ifdef CONFIG_SPI_FLASH_USE_4K_SECTORS
2898         /* prefer "small sector" erase if possible */
2899         if (info->flags & SECT_4K) {
2900                 nor->erase_opcode = SPINOR_OP_BE_4K;
2901                 mtd->erasesize = 4096;
2902         } else if (info->flags & SECT_4K_PMC) {
2903                 nor->erase_opcode = SPINOR_OP_BE_4K_PMC;
2904                 mtd->erasesize = 4096;
2905         } else
2906 #endif
2907         {
2908                 nor->erase_opcode = SPINOR_OP_SE;
2909                 mtd->erasesize = info->sector_size;
2910         }
2911         return 0;
2912 }
2913
2914 static int spi_nor_default_setup(struct spi_nor *nor,
2915                                  const struct flash_info *info,
2916                                  const struct spi_nor_flash_parameter *params)
2917 {
2918         u32 shared_mask;
2919         bool enable_quad_io;
2920         int err;
2921
2922         spi_nor_adjust_hwcaps(nor, params, &shared_mask);
2923
2924         /* Select the (Fast) Read command. */
2925         err = spi_nor_select_read(nor, params, shared_mask);
2926         if (err) {
2927                 dev_dbg(nor->dev,
2928                         "can't select read settings supported by both the SPI controller and memory.\n");
2929                 return err;
2930         }
2931
2932         /* Select the Page Program command. */
2933         err = spi_nor_select_pp(nor, params, shared_mask);
2934         if (err) {
2935                 dev_dbg(nor->dev,
2936                         "can't select write settings supported by both the SPI controller and memory.\n");
2937                 return err;
2938         }
2939
2940         /* Select the Sector Erase command. */
2941         err = spi_nor_select_erase(nor, info);
2942         if (err) {
2943                 dev_dbg(nor->dev,
2944                         "can't select erase settings supported by both the SPI controller and memory.\n");
2945                 return err;
2946         }
2947
2948         /* Enable Quad I/O if needed. */
2949         enable_quad_io = (spi_nor_get_protocol_width(nor->read_proto) == 4 ||
2950                           spi_nor_get_protocol_width(nor->write_proto) == 4);
2951         if (enable_quad_io && params->quad_enable)
2952                 nor->quad_enable = params->quad_enable;
2953         else
2954                 nor->quad_enable = NULL;
2955
2956         return 0;
2957 }
2958
2959 static int spi_nor_setup(struct spi_nor *nor, const struct flash_info *info,
2960                          const struct spi_nor_flash_parameter *params)
2961 {
2962         if (!nor->setup)
2963                 return 0;
2964
2965         return nor->setup(nor, info, params);
2966 }
2967
2968 /** spi_nor_octal_dtr_enable() - enable Octal DTR I/O if needed
2969  * @nor:                 pointer to a 'struct spi_nor'
2970  *
2971  * Return: 0 on success, -errno otherwise.
2972  */
2973 static int spi_nor_octal_dtr_enable(struct spi_nor *nor)
2974 {
2975         int ret;
2976
2977         if (!nor->octal_dtr_enable)
2978                 return 0;
2979
2980         if (!(nor->read_proto == SNOR_PROTO_8_8_8_DTR &&
2981               nor->write_proto == SNOR_PROTO_8_8_8_DTR))
2982                 return 0;
2983
2984         ret = nor->octal_dtr_enable(nor);
2985         if (ret)
2986                 return ret;
2987
2988         nor->reg_proto = SNOR_PROTO_8_8_8_DTR;
2989
2990         return 0;
2991 }
2992
2993 static int spi_nor_init(struct spi_nor *nor)
2994 {
2995         int err;
2996
2997         err = spi_nor_octal_dtr_enable(nor);
2998         if (err) {
2999                 dev_dbg(nor->dev, "Octal DTR mode not supported\n");
3000                 return err;
3001         }
3002
3003         /*
3004          * Atmel, SST, Intel/Numonyx, and others serial NOR tend to power up
3005          * with the software protection bits set
3006          */
3007         if (IS_ENABLED(CONFIG_SPI_FLASH_UNLOCK_ALL) &&
3008             (JEDEC_MFR(nor->info) == SNOR_MFR_ATMEL ||
3009              JEDEC_MFR(nor->info) == SNOR_MFR_INTEL ||
3010              JEDEC_MFR(nor->info) == SNOR_MFR_SST ||
3011              nor->info->flags & SPI_NOR_HAS_LOCK)) {
3012                 write_enable(nor);
3013                 write_sr(nor, 0);
3014                 spi_nor_wait_till_ready(nor);
3015         }
3016
3017         if (nor->quad_enable) {
3018                 err = nor->quad_enable(nor);
3019                 if (err) {
3020                         dev_dbg(nor->dev, "quad mode not supported\n");
3021                         return err;
3022                 }
3023         }
3024
3025         if (nor->addr_width == 4 &&
3026             !(nor->info->flags & SPI_NOR_OCTAL_DTR_READ) &&
3027             (JEDEC_MFR(nor->info) != SNOR_MFR_SPANSION) &&
3028             !(nor->info->flags & SPI_NOR_4B_OPCODES)) {
3029                 /*
3030                  * If the RESET# pin isn't hooked up properly, or the system
3031                  * otherwise doesn't perform a reset command in the boot
3032                  * sequence, it's impossible to 100% protect against unexpected
3033                  * reboots (e.g., crashes). Warn the user (or hopefully, system
3034                  * designer) that this is bad.
3035                  */
3036                 if (nor->flags & SNOR_F_BROKEN_RESET)
3037                         debug("enabling reset hack; may not recover from unexpected reboots\n");
3038                 set_4byte(nor, nor->info, 1);
3039         }
3040
3041         return 0;
3042 }
3043
3044 #ifdef CONFIG_SPI_FLASH_SOFT_RESET
3045 /**
3046  * spi_nor_soft_reset() - perform the JEDEC Software Reset sequence
3047  * @nor:        the spi_nor structure
3048  *
3049  * This function can be used to switch from Octal DTR mode to legacy mode on a
3050  * flash that supports it. The soft reset is executed in Octal DTR mode.
3051  *
3052  * Return: 0 for success, -errno for failure.
3053  */
3054 static int spi_nor_soft_reset(struct spi_nor *nor)
3055 {
3056         struct spi_mem_op op;
3057         int ret;
3058         enum spi_nor_cmd_ext ext;
3059
3060         ext = nor->cmd_ext_type;
3061         nor->cmd_ext_type = SPI_NOR_EXT_REPEAT;
3062
3063         op = (struct spi_mem_op)SPI_MEM_OP(SPI_MEM_OP_CMD(SPINOR_OP_SRSTEN, 0),
3064                         SPI_MEM_OP_NO_DUMMY,
3065                         SPI_MEM_OP_NO_ADDR,
3066                         SPI_MEM_OP_NO_DATA);
3067         spi_nor_setup_op(nor, &op, SNOR_PROTO_8_8_8_DTR);
3068         ret = spi_mem_exec_op(nor->spi, &op);
3069         if (ret) {
3070                 dev_warn(nor->dev, "Software reset enable failed: %d\n", ret);
3071                 goto out;
3072         }
3073
3074         op = (struct spi_mem_op)SPI_MEM_OP(SPI_MEM_OP_CMD(SPINOR_OP_SRST, 0),
3075                         SPI_MEM_OP_NO_DUMMY,
3076                         SPI_MEM_OP_NO_ADDR,
3077                         SPI_MEM_OP_NO_DATA);
3078         spi_nor_setup_op(nor, &op, SNOR_PROTO_8_8_8_DTR);
3079         ret = spi_mem_exec_op(nor->spi, &op);
3080         if (ret) {
3081                 dev_warn(nor->dev, "Software reset failed: %d\n", ret);
3082                 goto out;
3083         }
3084
3085         /*
3086          * Software Reset is not instant, and the delay varies from flash to
3087          * flash. Looking at a few flashes, most range somewhere below 100
3088          * microseconds. So, wait for 200ms just to be sure.
3089          */
3090         udelay(SPI_NOR_SRST_SLEEP_LEN);
3091
3092 out:
3093         nor->cmd_ext_type = ext;
3094         return ret;
3095 }
3096 #endif /* CONFIG_SPI_FLASH_SOFT_RESET */
3097
3098 int spi_nor_remove(struct spi_nor *nor)
3099 {
3100 #ifdef CONFIG_SPI_FLASH_SOFT_RESET
3101         if (nor->info->flags & SPI_NOR_OCTAL_DTR_READ &&
3102             nor->flags & SNOR_F_SOFT_RESET)
3103                 return spi_nor_soft_reset(nor);
3104 #endif
3105
3106         return 0;
3107 }
3108
3109 void spi_nor_set_fixups(struct spi_nor *nor)
3110 {
3111 }
3112
3113 int spi_nor_scan(struct spi_nor *nor)
3114 {
3115         struct spi_nor_flash_parameter params;
3116         const struct flash_info *info = NULL;
3117         struct mtd_info *mtd = &nor->mtd;
3118         struct spi_slave *spi = nor->spi;
3119         int ret;
3120
3121         /* Reset SPI protocol for all commands. */
3122         nor->reg_proto = SNOR_PROTO_1_1_1;
3123         nor->read_proto = SNOR_PROTO_1_1_1;
3124         nor->write_proto = SNOR_PROTO_1_1_1;
3125         nor->read = spi_nor_read_data;
3126         nor->write = spi_nor_write_data;
3127         nor->read_reg = spi_nor_read_reg;
3128         nor->write_reg = spi_nor_write_reg;
3129
3130         nor->setup = spi_nor_default_setup;
3131
3132 #ifdef CONFIG_SPI_FLASH_SOFT_RESET_ON_BOOT
3133         /*
3134          * When the flash is handed to us in a stateful mode like 8D-8D-8D, it
3135          * is difficult to detect the mode the flash is in. One option is to
3136          * read SFDP in all modes and see which one gives the correct "SFDP"
3137          * signature, but not all flashes support SFDP in 8D-8D-8D mode.
3138          *
3139          * Further, even if you detect the mode of the flash via SFDP, you
3140          * still have the problem of actually reading the ID. The Read ID
3141          * command is not standardized across flash vendors. Flashes can have
3142          * different dummy cycles needed for reading the ID. Some flashes even
3143          * expect a 4-byte dummy address with the Read ID command. All this
3144          * information cannot be obtained from the SFDP table.
3145          *
3146          * So, perform a Software Reset sequence before reading the ID and
3147          * initializing the flash. A Soft Reset will bring back the flash in
3148          * its default protocol mode assuming no non-volatile configuration was
3149          * set. This will let us detect the flash even if ROM hands it to us in
3150          * Octal DTR mode.
3151          *
3152          * To accommodate cases where there is more than one flash on a board,
3153          * and only one of them needs a soft reset, failure to reset is not
3154          * made fatal, and we still try to read ID if possible.
3155          */
3156         spi_nor_soft_reset(nor);
3157 #endif /* CONFIG_SPI_FLASH_SOFT_RESET_ON_BOOT */
3158
3159         info = spi_nor_read_id(nor);
3160         if (IS_ERR_OR_NULL(info))
3161                 return -ENOENT;
3162         nor->info = info;
3163
3164         spi_nor_set_fixups(nor);
3165
3166         /* Parse the Serial Flash Discoverable Parameters table. */
3167         ret = spi_nor_init_params(nor, info, &params);
3168         if (ret)
3169                 return ret;
3170
3171         if (!mtd->name)
3172                 mtd->name = info->name;
3173         mtd->dev = nor->dev;
3174         mtd->priv = nor;
3175         mtd->type = MTD_NORFLASH;
3176         mtd->writesize = 1;
3177         mtd->flags = MTD_CAP_NORFLASH;
3178         mtd->size = params.size;
3179         mtd->_erase = spi_nor_erase;
3180         mtd->_read = spi_nor_read;
3181         mtd->_write = spi_nor_write;
3182
3183 #if defined(CONFIG_SPI_FLASH_STMICRO) || defined(CONFIG_SPI_FLASH_SST)
3184         /* NOR protection support for STmicro/Micron chips and similar */
3185         if (JEDEC_MFR(info) == SNOR_MFR_ST ||
3186             JEDEC_MFR(info) == SNOR_MFR_MICRON ||
3187             JEDEC_MFR(info) == SNOR_MFR_SST ||
3188                         info->flags & SPI_NOR_HAS_LOCK) {
3189                 nor->flash_lock = stm_lock;
3190                 nor->flash_unlock = stm_unlock;
3191                 nor->flash_is_locked = stm_is_locked;
3192         }
3193 #endif
3194
3195 #ifdef CONFIG_SPI_FLASH_SST
3196         /*
3197          * sst26 series block protection implementation differs from other
3198          * series.
3199          */
3200         if (info->flags & SPI_NOR_HAS_SST26LOCK) {
3201                 nor->flash_lock = sst26_lock;
3202                 nor->flash_unlock = sst26_unlock;
3203                 nor->flash_is_locked = sst26_is_locked;
3204         }
3205 #endif
3206
3207         if (info->flags & USE_FSR)
3208                 nor->flags |= SNOR_F_USE_FSR;
3209         if (info->flags & SPI_NOR_HAS_TB)
3210                 nor->flags |= SNOR_F_HAS_SR_TB;
3211         if (info->flags & NO_CHIP_ERASE)
3212                 nor->flags |= SNOR_F_NO_OP_CHIP_ERASE;
3213         if (info->flags & USE_CLSR)
3214                 nor->flags |= SNOR_F_USE_CLSR;
3215
3216         if (info->flags & SPI_NOR_NO_ERASE)
3217                 mtd->flags |= MTD_NO_ERASE;
3218
3219         nor->page_size = params.page_size;
3220         mtd->writebufsize = nor->page_size;
3221
3222         /* Some devices cannot do fast-read, no matter what DT tells us */
3223         if ((info->flags & SPI_NOR_NO_FR) || (spi->mode & SPI_RX_SLOW))
3224                 params.hwcaps.mask &= ~SNOR_HWCAPS_READ_FAST;
3225
3226         /*
3227          * Configure the SPI memory:
3228          * - select op codes for (Fast) Read, Page Program and Sector Erase.
3229          * - set the number of dummy cycles (mode cycles + wait states).
3230          * - set the SPI protocols for register and memory accesses.
3231          * - set the Quad Enable bit if needed (required by SPI x-y-4 protos).
3232          */
3233         ret = spi_nor_setup(nor, info, &params);
3234         if (ret)
3235                 return ret;
3236
3237         if (spi_nor_protocol_is_dtr(nor->read_proto)) {
3238                  /* Always use 4-byte addresses in DTR mode. */
3239                 nor->addr_width = 4;
3240         } else if (nor->addr_width) {
3241                 /* already configured from SFDP */
3242         } else if (info->addr_width) {
3243                 nor->addr_width = info->addr_width;
3244         } else {
3245                 nor->addr_width = 3;
3246         }
3247
3248         if (nor->addr_width == 3 && mtd->size > SZ_16M) {
3249 #ifndef CONFIG_SPI_FLASH_BAR
3250                 /* enable 4-byte addressing if the device exceeds 16MiB */
3251                 nor->addr_width = 4;
3252                 if (JEDEC_MFR(info) == SNOR_MFR_SPANSION ||
3253                     info->flags & SPI_NOR_4B_OPCODES)
3254                         spi_nor_set_4byte_opcodes(nor, info);
3255 #else
3256         /* Configure the BAR - discover bank cmds and read current bank */
3257         nor->addr_width = 3;
3258         ret = read_bar(nor, info);
3259         if (ret < 0)
3260                 return ret;
3261 #endif
3262         }
3263
3264         if (nor->addr_width > SPI_NOR_MAX_ADDR_WIDTH) {
3265                 dev_dbg(nor->dev, "address width is too large: %u\n",
3266                         nor->addr_width);
3267                 return -EINVAL;
3268         }
3269
3270         /* Send all the required SPI flash commands to initialize device */
3271         ret = spi_nor_init(nor);
3272         if (ret)
3273                 return ret;
3274
3275         nor->rdsr_dummy = params.rdsr_dummy;
3276         nor->rdsr_addr_nbytes = params.rdsr_addr_nbytes;
3277         nor->name = mtd->name;
3278         nor->size = mtd->size;
3279         nor->erase_size = mtd->erasesize;
3280         nor->sector_size = mtd->erasesize;
3281
3282 #ifndef CONFIG_SPL_BUILD
3283         printf("SF: Detected %s with page size ", nor->name);
3284         print_size(nor->page_size, ", erase size ");
3285         print_size(nor->erase_size, ", total ");
3286         print_size(nor->size, "");
3287         puts("\n");
3288 #endif
3289
3290         return 0;
3291 }
3292
3293 /* U-Boot specific functions, need to extend MTD to support these */
3294 int spi_flash_cmd_get_sw_write_prot(struct spi_nor *nor)
3295 {
3296         int sr = read_sr(nor);
3297
3298         if (sr < 0)
3299                 return sr;
3300
3301         return (sr >> 2) & 7;
3302 }