mtd: spi-nor: Mask out fast read if not requested in DT
[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 #ifdef CONFIG_SPI_FLASH_SPANSION
319 static int spansion_read_any_reg(struct spi_nor *nor, u32 addr, u8 dummy,
320                                  u8 *val)
321 {
322         struct spi_mem_op op =
323                         SPI_MEM_OP(SPI_MEM_OP_CMD(SPINOR_OP_RDAR, 1),
324                                    SPI_MEM_OP_ADDR(nor->addr_width, addr, 1),
325                                    SPI_MEM_OP_DUMMY(dummy / 8, 1),
326                                    SPI_MEM_OP_DATA_IN(1, NULL, 1));
327
328         return spi_nor_read_write_reg(nor, &op, val);
329 }
330
331 static int spansion_write_any_reg(struct spi_nor *nor, u32 addr, u8 val)
332 {
333         struct spi_mem_op op =
334                         SPI_MEM_OP(SPI_MEM_OP_CMD(SPINOR_OP_WRAR, 1),
335                                    SPI_MEM_OP_ADDR(nor->addr_width, addr, 1),
336                                    SPI_MEM_OP_NO_DUMMY,
337                                    SPI_MEM_OP_DATA_OUT(1, NULL, 1));
338
339         return spi_nor_read_write_reg(nor, &op, &val);
340 }
341 #endif
342
343 static ssize_t spi_nor_read_data(struct spi_nor *nor, loff_t from, size_t len,
344                                  u_char *buf)
345 {
346         struct spi_mem_op op =
347                         SPI_MEM_OP(SPI_MEM_OP_CMD(nor->read_opcode, 0),
348                                    SPI_MEM_OP_ADDR(nor->addr_width, from, 0),
349                                    SPI_MEM_OP_DUMMY(nor->read_dummy, 0),
350                                    SPI_MEM_OP_DATA_IN(len, buf, 0));
351         size_t remaining = len;
352         int ret;
353
354         spi_nor_setup_op(nor, &op, nor->read_proto);
355
356         /* convert the dummy cycles to the number of bytes */
357         op.dummy.nbytes = (nor->read_dummy * op.dummy.buswidth) / 8;
358         if (spi_nor_protocol_is_dtr(nor->read_proto))
359                 op.dummy.nbytes *= 2;
360
361         while (remaining) {
362                 op.data.nbytes = remaining < UINT_MAX ? remaining : UINT_MAX;
363                 ret = spi_mem_adjust_op_size(nor->spi, &op);
364                 if (ret)
365                         return ret;
366
367                 ret = spi_mem_exec_op(nor->spi, &op);
368                 if (ret)
369                         return ret;
370
371                 op.addr.val += op.data.nbytes;
372                 remaining -= op.data.nbytes;
373                 op.data.buf.in += op.data.nbytes;
374         }
375
376         return len;
377 }
378
379 static ssize_t spi_nor_write_data(struct spi_nor *nor, loff_t to, size_t len,
380                                   const u_char *buf)
381 {
382         struct spi_mem_op op =
383                         SPI_MEM_OP(SPI_MEM_OP_CMD(nor->program_opcode, 0),
384                                    SPI_MEM_OP_ADDR(nor->addr_width, to, 0),
385                                    SPI_MEM_OP_NO_DUMMY,
386                                    SPI_MEM_OP_DATA_OUT(len, buf, 0));
387         int ret;
388
389         if (nor->program_opcode == SPINOR_OP_AAI_WP && nor->sst_write_second)
390                 op.addr.nbytes = 0;
391
392         spi_nor_setup_op(nor, &op, nor->write_proto);
393
394         ret = spi_mem_adjust_op_size(nor->spi, &op);
395         if (ret)
396                 return ret;
397         op.data.nbytes = len < op.data.nbytes ? len : op.data.nbytes;
398
399         ret = spi_mem_exec_op(nor->spi, &op);
400         if (ret)
401                 return ret;
402
403         return op.data.nbytes;
404 }
405
406 /*
407  * Read the status register, returning its value in the location
408  * Return the status register value.
409  * Returns negative if error occurred.
410  */
411 static int read_sr(struct spi_nor *nor)
412 {
413         struct spi_mem_op op;
414         int ret;
415         u8 val[2];
416         u8 addr_nbytes, dummy;
417
418         if (nor->reg_proto == SNOR_PROTO_8_8_8_DTR) {
419                 addr_nbytes = nor->rdsr_addr_nbytes;
420                 dummy = nor->rdsr_dummy;
421         } else {
422                 addr_nbytes = 0;
423                 dummy = 0;
424         }
425
426         op = (struct spi_mem_op)SPI_MEM_OP(SPI_MEM_OP_CMD(SPINOR_OP_RDSR, 0),
427                                            SPI_MEM_OP_ADDR(addr_nbytes, 0, 0),
428                                            SPI_MEM_OP_DUMMY(dummy, 0),
429                                            SPI_MEM_OP_DATA_IN(1, NULL, 0));
430
431         spi_nor_setup_op(nor, &op, nor->reg_proto);
432
433         /*
434          * We don't want to read only one byte in DTR mode. So, read 2 and then
435          * discard the second byte.
436          */
437         if (spi_nor_protocol_is_dtr(nor->reg_proto))
438                 op.data.nbytes = 2;
439
440         ret = spi_nor_read_write_reg(nor, &op, val);
441         if (ret < 0) {
442                 pr_debug("error %d reading SR\n", (int)ret);
443                 return ret;
444         }
445
446         return *val;
447 }
448
449 /*
450  * Read the flag status register, returning its value in the location
451  * Return the status register value.
452  * Returns negative if error occurred.
453  */
454 static int read_fsr(struct spi_nor *nor)
455 {
456         struct spi_mem_op op;
457         int ret;
458         u8 val[2];
459         u8 addr_nbytes, dummy;
460
461         if (nor->reg_proto == SNOR_PROTO_8_8_8_DTR) {
462                 addr_nbytes = nor->rdsr_addr_nbytes;
463                 dummy = nor->rdsr_dummy;
464         } else {
465                 addr_nbytes = 0;
466                 dummy = 0;
467         }
468
469         op = (struct spi_mem_op)SPI_MEM_OP(SPI_MEM_OP_CMD(SPINOR_OP_RDFSR, 0),
470                                            SPI_MEM_OP_ADDR(addr_nbytes, 0, 0),
471                                            SPI_MEM_OP_DUMMY(dummy, 0),
472                                            SPI_MEM_OP_DATA_IN(1, NULL, 0));
473
474         spi_nor_setup_op(nor, &op, nor->reg_proto);
475
476         /*
477          * We don't want to read only one byte in DTR mode. So, read 2 and then
478          * discard the second byte.
479          */
480         if (spi_nor_protocol_is_dtr(nor->reg_proto))
481                 op.data.nbytes = 2;
482
483         ret = spi_nor_read_write_reg(nor, &op, val);
484         if (ret < 0) {
485                 pr_debug("error %d reading FSR\n", ret);
486                 return ret;
487         }
488
489         return *val;
490 }
491
492 /*
493  * Read configuration register, returning its value in the
494  * location. Return the configuration register value.
495  * Returns negative if error occurred.
496  */
497 #if defined(CONFIG_SPI_FLASH_SPANSION) || defined(CONFIG_SPI_FLASH_WINBOND)
498 static int read_cr(struct spi_nor *nor)
499 {
500         int ret;
501         u8 val;
502
503         ret = nor->read_reg(nor, SPINOR_OP_RDCR, &val, 1);
504         if (ret < 0) {
505                 dev_dbg(nor->dev, "error %d reading CR\n", ret);
506                 return ret;
507         }
508
509         return val;
510 }
511 #endif
512
513 /*
514  * Write status register 1 byte
515  * Returns negative if error occurred.
516  */
517 static int write_sr(struct spi_nor *nor, u8 val)
518 {
519         nor->cmd_buf[0] = val;
520         return nor->write_reg(nor, SPINOR_OP_WRSR, nor->cmd_buf, 1);
521 }
522
523 /*
524  * Set write enable latch with Write Enable command.
525  * Returns negative if error occurred.
526  */
527 static int write_enable(struct spi_nor *nor)
528 {
529         return nor->write_reg(nor, SPINOR_OP_WREN, NULL, 0);
530 }
531
532 /*
533  * Send write disable instruction to the chip.
534  */
535 static int write_disable(struct spi_nor *nor)
536 {
537         return nor->write_reg(nor, SPINOR_OP_WRDI, NULL, 0);
538 }
539
540 static struct spi_nor *mtd_to_spi_nor(struct mtd_info *mtd)
541 {
542         return mtd->priv;
543 }
544
545 #ifndef CONFIG_SPI_FLASH_BAR
546 static u8 spi_nor_convert_opcode(u8 opcode, const u8 table[][2], size_t size)
547 {
548         size_t i;
549
550         for (i = 0; i < size; i++)
551                 if (table[i][0] == opcode)
552                         return table[i][1];
553
554         /* No conversion found, keep input op code. */
555         return opcode;
556 }
557
558 static u8 spi_nor_convert_3to4_read(u8 opcode)
559 {
560         static const u8 spi_nor_3to4_read[][2] = {
561                 { SPINOR_OP_READ,       SPINOR_OP_READ_4B },
562                 { SPINOR_OP_READ_FAST,  SPINOR_OP_READ_FAST_4B },
563                 { SPINOR_OP_READ_1_1_2, SPINOR_OP_READ_1_1_2_4B },
564                 { SPINOR_OP_READ_1_2_2, SPINOR_OP_READ_1_2_2_4B },
565                 { SPINOR_OP_READ_1_1_4, SPINOR_OP_READ_1_1_4_4B },
566                 { SPINOR_OP_READ_1_4_4, SPINOR_OP_READ_1_4_4_4B },
567                 { SPINOR_OP_READ_1_1_8, SPINOR_OP_READ_1_1_8_4B },
568                 { SPINOR_OP_READ_1_8_8, SPINOR_OP_READ_1_8_8_4B },
569
570                 { SPINOR_OP_READ_1_1_1_DTR,     SPINOR_OP_READ_1_1_1_DTR_4B },
571                 { SPINOR_OP_READ_1_2_2_DTR,     SPINOR_OP_READ_1_2_2_DTR_4B },
572                 { SPINOR_OP_READ_1_4_4_DTR,     SPINOR_OP_READ_1_4_4_DTR_4B },
573         };
574
575         return spi_nor_convert_opcode(opcode, spi_nor_3to4_read,
576                                       ARRAY_SIZE(spi_nor_3to4_read));
577 }
578
579 static u8 spi_nor_convert_3to4_program(u8 opcode)
580 {
581         static const u8 spi_nor_3to4_program[][2] = {
582                 { SPINOR_OP_PP,         SPINOR_OP_PP_4B },
583                 { SPINOR_OP_PP_1_1_4,   SPINOR_OP_PP_1_1_4_4B },
584                 { SPINOR_OP_PP_1_4_4,   SPINOR_OP_PP_1_4_4_4B },
585                 { SPINOR_OP_PP_1_1_8,   SPINOR_OP_PP_1_1_8_4B },
586                 { SPINOR_OP_PP_1_8_8,   SPINOR_OP_PP_1_8_8_4B },
587         };
588
589         return spi_nor_convert_opcode(opcode, spi_nor_3to4_program,
590                                       ARRAY_SIZE(spi_nor_3to4_program));
591 }
592
593 static u8 spi_nor_convert_3to4_erase(u8 opcode)
594 {
595         static const u8 spi_nor_3to4_erase[][2] = {
596                 { SPINOR_OP_BE_4K,      SPINOR_OP_BE_4K_4B },
597                 { SPINOR_OP_BE_32K,     SPINOR_OP_BE_32K_4B },
598                 { SPINOR_OP_SE,         SPINOR_OP_SE_4B },
599         };
600
601         return spi_nor_convert_opcode(opcode, spi_nor_3to4_erase,
602                                       ARRAY_SIZE(spi_nor_3to4_erase));
603 }
604
605 static void spi_nor_set_4byte_opcodes(struct spi_nor *nor,
606                                       const struct flash_info *info)
607 {
608         /* Do some manufacturer fixups first */
609         switch (JEDEC_MFR(info)) {
610         case SNOR_MFR_SPANSION:
611                 /* No small sector erase for 4-byte command set */
612                 nor->erase_opcode = SPINOR_OP_SE;
613                 nor->mtd.erasesize = info->sector_size;
614                 break;
615
616         default:
617                 break;
618         }
619
620         nor->read_opcode = spi_nor_convert_3to4_read(nor->read_opcode);
621         nor->program_opcode = spi_nor_convert_3to4_program(nor->program_opcode);
622         nor->erase_opcode = spi_nor_convert_3to4_erase(nor->erase_opcode);
623 }
624 #endif /* !CONFIG_SPI_FLASH_BAR */
625
626 /* Enable/disable 4-byte addressing mode. */
627 static int set_4byte(struct spi_nor *nor, const struct flash_info *info,
628                      int enable)
629 {
630         int status;
631         bool need_wren = false;
632         u8 cmd;
633
634         switch (JEDEC_MFR(info)) {
635         case SNOR_MFR_ST:
636         case SNOR_MFR_MICRON:
637                 /* Some Micron need WREN command; all will accept it */
638                 need_wren = true;
639         case SNOR_MFR_ISSI:
640         case SNOR_MFR_MACRONIX:
641         case SNOR_MFR_WINBOND:
642                 if (need_wren)
643                         write_enable(nor);
644
645                 cmd = enable ? SPINOR_OP_EN4B : SPINOR_OP_EX4B;
646                 status = nor->write_reg(nor, cmd, NULL, 0);
647                 if (need_wren)
648                         write_disable(nor);
649
650                 if (!status && !enable &&
651                     JEDEC_MFR(info) == SNOR_MFR_WINBOND) {
652                         /*
653                          * On Winbond W25Q256FV, leaving 4byte mode causes
654                          * the Extended Address Register to be set to 1, so all
655                          * 3-byte-address reads come from the second 16M.
656                          * We must clear the register to enable normal behavior.
657                          */
658                         write_enable(nor);
659                         nor->cmd_buf[0] = 0;
660                         nor->write_reg(nor, SPINOR_OP_WREAR, nor->cmd_buf, 1);
661                         write_disable(nor);
662                 }
663
664                 return status;
665         case SNOR_MFR_CYPRESS:
666                 cmd = enable ? SPINOR_OP_EN4B : SPINOR_OP_EX4B_CYPRESS;
667                 return nor->write_reg(nor, cmd, NULL, 0);
668         default:
669                 /* Spansion style */
670                 nor->cmd_buf[0] = enable << 7;
671                 return nor->write_reg(nor, SPINOR_OP_BRWR, nor->cmd_buf, 1);
672         }
673 }
674
675 #ifdef CONFIG_SPI_FLASH_SPANSION
676 /*
677  * Read status register 1 by using Read Any Register command to support multi
678  * die package parts.
679  */
680 static int spansion_sr_ready(struct spi_nor *nor, u32 addr_base, u8 dummy)
681 {
682         u32 reg_addr = addr_base + SPINOR_REG_ADDR_STR1V;
683         u8 sr;
684         int ret;
685
686         ret = spansion_read_any_reg(nor, reg_addr, dummy, &sr);
687         if (ret < 0)
688                 return ret;
689
690         if (sr & (SR_E_ERR | SR_P_ERR)) {
691                 if (sr & SR_E_ERR)
692                         dev_dbg(nor->dev, "Erase Error occurred\n");
693                 else
694                         dev_dbg(nor->dev, "Programming Error occurred\n");
695
696                 nor->write_reg(nor, SPINOR_OP_CLSR, NULL, 0);
697                 return -EIO;
698         }
699
700         return !(sr & SR_WIP);
701 }
702 #endif
703
704 static int spi_nor_sr_ready(struct spi_nor *nor)
705 {
706         int sr = read_sr(nor);
707
708         if (sr < 0)
709                 return sr;
710
711         if (nor->flags & SNOR_F_USE_CLSR && sr & (SR_E_ERR | SR_P_ERR)) {
712                 if (sr & SR_E_ERR)
713                         dev_dbg(nor->dev, "Erase Error occurred\n");
714                 else
715                         dev_dbg(nor->dev, "Programming Error occurred\n");
716
717                 nor->write_reg(nor, SPINOR_OP_CLSR, NULL, 0);
718                 return -EIO;
719         }
720
721         return !(sr & SR_WIP);
722 }
723
724 static int spi_nor_fsr_ready(struct spi_nor *nor)
725 {
726         int fsr = read_fsr(nor);
727
728         if (fsr < 0)
729                 return fsr;
730
731         if (fsr & (FSR_E_ERR | FSR_P_ERR)) {
732                 if (fsr & FSR_E_ERR)
733                         dev_err(nor->dev, "Erase operation failed.\n");
734                 else
735                         dev_err(nor->dev, "Program operation failed.\n");
736
737                 if (fsr & FSR_PT_ERR)
738                         dev_err(nor->dev,
739                                 "Attempted to modify a protected sector.\n");
740
741                 nor->write_reg(nor, SPINOR_OP_CLFSR, NULL, 0);
742                 return -EIO;
743         }
744
745         return fsr & FSR_READY;
746 }
747
748 static int spi_nor_default_ready(struct spi_nor *nor)
749 {
750         int sr, fsr;
751
752         sr = spi_nor_sr_ready(nor);
753         if (sr < 0)
754                 return sr;
755         fsr = nor->flags & SNOR_F_USE_FSR ? spi_nor_fsr_ready(nor) : 1;
756         if (fsr < 0)
757                 return fsr;
758         return sr && fsr;
759 }
760
761 static int spi_nor_ready(struct spi_nor *nor)
762 {
763         if (nor->ready)
764                 return nor->ready(nor);
765
766         return spi_nor_default_ready(nor);
767 }
768
769 /*
770  * Service routine to read status register until ready, or timeout occurs.
771  * Returns non-zero if error.
772  */
773 static int spi_nor_wait_till_ready_with_timeout(struct spi_nor *nor,
774                                                 unsigned long timeout)
775 {
776         unsigned long timebase;
777         int ret;
778
779         timebase = get_timer(0);
780
781         while (get_timer(timebase) < timeout) {
782                 ret = spi_nor_ready(nor);
783                 if (ret < 0)
784                         return ret;
785                 if (ret)
786                         return 0;
787         }
788
789         dev_err(nor->dev, "flash operation timed out\n");
790
791         return -ETIMEDOUT;
792 }
793
794 static int spi_nor_wait_till_ready(struct spi_nor *nor)
795 {
796         return spi_nor_wait_till_ready_with_timeout(nor,
797                                                     DEFAULT_READY_WAIT_JIFFIES);
798 }
799
800 #ifdef CONFIG_SPI_FLASH_BAR
801 /*
802  * This "clean_bar" is necessary in a situation when one was accessing
803  * spi flash memory > 16 MiB by using Bank Address Register's BA24 bit.
804  *
805  * After it the BA24 bit shall be cleared to allow access to correct
806  * memory region after SW reset (by calling "reset" command).
807  *
808  * Otherwise, the BA24 bit may be left set and then after reset, the
809  * ROM would read/write/erase SPL from 16 MiB * bank_sel address.
810  */
811 static int clean_bar(struct spi_nor *nor)
812 {
813         u8 cmd, bank_sel = 0;
814
815         if (nor->bank_curr == 0)
816                 return 0;
817         cmd = nor->bank_write_cmd;
818         nor->bank_curr = 0;
819         write_enable(nor);
820
821         return nor->write_reg(nor, cmd, &bank_sel, 1);
822 }
823
824 static int write_bar(struct spi_nor *nor, u32 offset)
825 {
826         u8 cmd, bank_sel;
827         int ret;
828
829         bank_sel = offset / SZ_16M;
830         if (bank_sel == nor->bank_curr)
831                 goto bar_end;
832
833         cmd = nor->bank_write_cmd;
834         write_enable(nor);
835         ret = nor->write_reg(nor, cmd, &bank_sel, 1);
836         if (ret < 0) {
837                 debug("SF: fail to write bank register\n");
838                 return ret;
839         }
840
841 bar_end:
842         nor->bank_curr = bank_sel;
843         return nor->bank_curr;
844 }
845
846 static int read_bar(struct spi_nor *nor, const struct flash_info *info)
847 {
848         u8 curr_bank = 0;
849         int ret;
850
851         switch (JEDEC_MFR(info)) {
852         case SNOR_MFR_SPANSION:
853                 nor->bank_read_cmd = SPINOR_OP_BRRD;
854                 nor->bank_write_cmd = SPINOR_OP_BRWR;
855                 break;
856         default:
857                 nor->bank_read_cmd = SPINOR_OP_RDEAR;
858                 nor->bank_write_cmd = SPINOR_OP_WREAR;
859         }
860
861         ret = nor->read_reg(nor, nor->bank_read_cmd,
862                                     &curr_bank, 1);
863         if (ret) {
864                 debug("SF: fail to read bank addr register\n");
865                 return ret;
866         }
867         nor->bank_curr = curr_bank;
868
869         return 0;
870 }
871 #endif
872
873 /*
874  * Initiate the erasure of a single sector. Returns the number of bytes erased
875  * on success, a negative error code on error.
876  */
877 static int spi_nor_erase_sector(struct spi_nor *nor, u32 addr)
878 {
879         struct spi_mem_op op =
880                 SPI_MEM_OP(SPI_MEM_OP_CMD(nor->erase_opcode, 0),
881                            SPI_MEM_OP_ADDR(nor->addr_width, addr, 0),
882                            SPI_MEM_OP_NO_DUMMY,
883                            SPI_MEM_OP_NO_DATA);
884         int ret;
885
886         spi_nor_setup_op(nor, &op, nor->write_proto);
887
888         if (nor->erase)
889                 return nor->erase(nor, addr);
890
891         /*
892          * Default implementation, if driver doesn't have a specialized HW
893          * control
894          */
895         ret = spi_mem_exec_op(nor->spi, &op);
896         if (ret)
897                 return ret;
898
899         return nor->mtd.erasesize;
900 }
901
902 /*
903  * Erase an address range on the nor chip.  The address range may extend
904  * one or more erase sectors.  Return an error is there is a problem erasing.
905  */
906 static int spi_nor_erase(struct mtd_info *mtd, struct erase_info *instr)
907 {
908         struct spi_nor *nor = mtd_to_spi_nor(mtd);
909         u32 addr, len, rem;
910         int ret;
911
912         dev_dbg(nor->dev, "at 0x%llx, len %lld\n", (long long)instr->addr,
913                 (long long)instr->len);
914
915         if (!instr->len)
916                 return 0;
917
918         div_u64_rem(instr->len, mtd->erasesize, &rem);
919         if (rem)
920                 return -EINVAL;
921
922         addr = instr->addr;
923         len = instr->len;
924
925         while (len) {
926                 WATCHDOG_RESET();
927 #ifdef CONFIG_SPI_FLASH_BAR
928                 ret = write_bar(nor, addr);
929                 if (ret < 0)
930                         return ret;
931 #endif
932                 write_enable(nor);
933
934                 ret = spi_nor_erase_sector(nor, addr);
935                 if (ret < 0)
936                         goto erase_err;
937
938                 addr += ret;
939                 len -= ret;
940
941                 ret = spi_nor_wait_till_ready(nor);
942                 if (ret)
943                         goto erase_err;
944         }
945
946 erase_err:
947 #ifdef CONFIG_SPI_FLASH_BAR
948         ret = clean_bar(nor);
949 #endif
950         write_disable(nor);
951
952         return ret;
953 }
954
955 #ifdef CONFIG_SPI_FLASH_SPANSION
956 /**
957  * spansion_erase_non_uniform() - erase non-uniform sectors for Spansion/Cypress
958  *                                chips
959  * @nor:        pointer to a 'struct spi_nor'
960  * @addr:       address of the sector to erase
961  * @opcode_4k:  opcode for 4K sector erase
962  * @ovlsz_top:  size of overlaid portion at the top address
963  * @ovlsz_btm:  size of overlaid portion at the bottom address
964  *
965  * Erase an address range on the nor chip that can contain 4KB sectors overlaid
966  * on top and/or bottom. The appropriate erase opcode and size are chosen by
967  * address to erase and size of overlaid portion.
968  *
969  * Return: number of bytes erased on success, -errno otherwise.
970  */
971 static int spansion_erase_non_uniform(struct spi_nor *nor, u32 addr,
972                                       u8 opcode_4k, u32 ovlsz_top,
973                                       u32 ovlsz_btm)
974 {
975         struct spi_mem_op op =
976                 SPI_MEM_OP(SPI_MEM_OP_CMD(nor->erase_opcode, 0),
977                            SPI_MEM_OP_ADDR(nor->addr_width, addr, 0),
978                            SPI_MEM_OP_NO_DUMMY,
979                            SPI_MEM_OP_NO_DATA);
980         struct mtd_info *mtd = &nor->mtd;
981         u32 erasesize;
982         int ret;
983
984         /* 4KB sectors */
985         if (op.addr.val < ovlsz_btm ||
986             op.addr.val >= mtd->size - ovlsz_top) {
987                 op.cmd.opcode = opcode_4k;
988                 erasesize = SZ_4K;
989
990         /* Non-overlaid portion in the normal sector at the bottom */
991         } else if (op.addr.val == ovlsz_btm) {
992                 op.cmd.opcode = nor->erase_opcode;
993                 erasesize = mtd->erasesize - ovlsz_btm;
994
995         /* Non-overlaid portion in the normal sector at the top */
996         } else if (op.addr.val == mtd->size - mtd->erasesize) {
997                 op.cmd.opcode = nor->erase_opcode;
998                 erasesize = mtd->erasesize - ovlsz_top;
999
1000         /* Normal sectors */
1001         } else {
1002                 op.cmd.opcode = nor->erase_opcode;
1003                 erasesize = mtd->erasesize;
1004         }
1005
1006         spi_nor_setup_op(nor, &op, nor->write_proto);
1007
1008         ret = spi_mem_exec_op(nor->spi, &op);
1009         if (ret)
1010                 return ret;
1011
1012         return erasesize;
1013 }
1014 #endif
1015
1016 #if defined(CONFIG_SPI_FLASH_STMICRO) || defined(CONFIG_SPI_FLASH_SST)
1017 /* Write status register and ensure bits in mask match written values */
1018 static int write_sr_and_check(struct spi_nor *nor, u8 status_new, u8 mask)
1019 {
1020         int ret;
1021
1022         write_enable(nor);
1023         ret = write_sr(nor, status_new);
1024         if (ret)
1025                 return ret;
1026
1027         ret = spi_nor_wait_till_ready(nor);
1028         if (ret)
1029                 return ret;
1030
1031         ret = read_sr(nor);
1032         if (ret < 0)
1033                 return ret;
1034
1035         return ((ret & mask) != (status_new & mask)) ? -EIO : 0;
1036 }
1037
1038 static void stm_get_locked_range(struct spi_nor *nor, u8 sr, loff_t *ofs,
1039                                  uint64_t *len)
1040 {
1041         struct mtd_info *mtd = &nor->mtd;
1042         u8 mask = SR_BP2 | SR_BP1 | SR_BP0;
1043         int shift = ffs(mask) - 1;
1044         int pow;
1045
1046         if (!(sr & mask)) {
1047                 /* No protection */
1048                 *ofs = 0;
1049                 *len = 0;
1050         } else {
1051                 pow = ((sr & mask) ^ mask) >> shift;
1052                 *len = mtd->size >> pow;
1053                 if (nor->flags & SNOR_F_HAS_SR_TB && sr & SR_TB)
1054                         *ofs = 0;
1055                 else
1056                         *ofs = mtd->size - *len;
1057         }
1058 }
1059
1060 /*
1061  * Return 1 if the entire region is locked (if @locked is true) or unlocked (if
1062  * @locked is false); 0 otherwise
1063  */
1064 static int stm_check_lock_status_sr(struct spi_nor *nor, loff_t ofs, u64 len,
1065                                     u8 sr, bool locked)
1066 {
1067         loff_t lock_offs;
1068         uint64_t lock_len;
1069
1070         if (!len)
1071                 return 1;
1072
1073         stm_get_locked_range(nor, sr, &lock_offs, &lock_len);
1074
1075         if (locked)
1076                 /* Requested range is a sub-range of locked range */
1077                 return (ofs + len <= lock_offs + lock_len) && (ofs >= lock_offs);
1078         else
1079                 /* Requested range does not overlap with locked range */
1080                 return (ofs >= lock_offs + lock_len) || (ofs + len <= lock_offs);
1081 }
1082
1083 static int stm_is_locked_sr(struct spi_nor *nor, loff_t ofs, uint64_t len,
1084                             u8 sr)
1085 {
1086         return stm_check_lock_status_sr(nor, ofs, len, sr, true);
1087 }
1088
1089 static int stm_is_unlocked_sr(struct spi_nor *nor, loff_t ofs, uint64_t len,
1090                               u8 sr)
1091 {
1092         return stm_check_lock_status_sr(nor, ofs, len, sr, false);
1093 }
1094
1095 /*
1096  * Lock a region of the flash. Compatible with ST Micro and similar flash.
1097  * Supports the block protection bits BP{0,1,2} in the status register
1098  * (SR). Does not support these features found in newer SR bitfields:
1099  *   - SEC: sector/block protect - only handle SEC=0 (block protect)
1100  *   - CMP: complement protect - only support CMP=0 (range is not complemented)
1101  *
1102  * Support for the following is provided conditionally for some flash:
1103  *   - TB: top/bottom protect
1104  *
1105  * Sample table portion for 8MB flash (Winbond w25q64fw):
1106  *
1107  *   SEC  |  TB   |  BP2  |  BP1  |  BP0  |  Prot Length  | Protected Portion
1108  *  --------------------------------------------------------------------------
1109  *    X   |   X   |   0   |   0   |   0   |  NONE         | NONE
1110  *    0   |   0   |   0   |   0   |   1   |  128 KB       | Upper 1/64
1111  *    0   |   0   |   0   |   1   |   0   |  256 KB       | Upper 1/32
1112  *    0   |   0   |   0   |   1   |   1   |  512 KB       | Upper 1/16
1113  *    0   |   0   |   1   |   0   |   0   |  1 MB         | Upper 1/8
1114  *    0   |   0   |   1   |   0   |   1   |  2 MB         | Upper 1/4
1115  *    0   |   0   |   1   |   1   |   0   |  4 MB         | Upper 1/2
1116  *    X   |   X   |   1   |   1   |   1   |  8 MB         | ALL
1117  *  ------|-------|-------|-------|-------|---------------|-------------------
1118  *    0   |   1   |   0   |   0   |   1   |  128 KB       | Lower 1/64
1119  *    0   |   1   |   0   |   1   |   0   |  256 KB       | Lower 1/32
1120  *    0   |   1   |   0   |   1   |   1   |  512 KB       | Lower 1/16
1121  *    0   |   1   |   1   |   0   |   0   |  1 MB         | Lower 1/8
1122  *    0   |   1   |   1   |   0   |   1   |  2 MB         | Lower 1/4
1123  *    0   |   1   |   1   |   1   |   0   |  4 MB         | Lower 1/2
1124  *
1125  * Returns negative on errors, 0 on success.
1126  */
1127 static int stm_lock(struct spi_nor *nor, loff_t ofs, uint64_t len)
1128 {
1129         struct mtd_info *mtd = &nor->mtd;
1130         int status_old, status_new;
1131         u8 mask = SR_BP2 | SR_BP1 | SR_BP0;
1132         u8 shift = ffs(mask) - 1, pow, val;
1133         loff_t lock_len;
1134         bool can_be_top = true, can_be_bottom = nor->flags & SNOR_F_HAS_SR_TB;
1135         bool use_top;
1136
1137         status_old = read_sr(nor);
1138         if (status_old < 0)
1139                 return status_old;
1140
1141         /* If nothing in our range is unlocked, we don't need to do anything */
1142         if (stm_is_locked_sr(nor, ofs, len, status_old))
1143                 return 0;
1144
1145         /* If anything below us is unlocked, we can't use 'bottom' protection */
1146         if (!stm_is_locked_sr(nor, 0, ofs, status_old))
1147                 can_be_bottom = false;
1148
1149         /* If anything above us is unlocked, we can't use 'top' protection */
1150         if (!stm_is_locked_sr(nor, ofs + len, mtd->size - (ofs + len),
1151                               status_old))
1152                 can_be_top = false;
1153
1154         if (!can_be_bottom && !can_be_top)
1155                 return -EINVAL;
1156
1157         /* Prefer top, if both are valid */
1158         use_top = can_be_top;
1159
1160         /* lock_len: length of region that should end up locked */
1161         if (use_top)
1162                 lock_len = mtd->size - ofs;
1163         else
1164                 lock_len = ofs + len;
1165
1166         /*
1167          * Need smallest pow such that:
1168          *
1169          *   1 / (2^pow) <= (len / size)
1170          *
1171          * so (assuming power-of-2 size) we do:
1172          *
1173          *   pow = ceil(log2(size / len)) = log2(size) - floor(log2(len))
1174          */
1175         pow = ilog2(mtd->size) - ilog2(lock_len);
1176         val = mask - (pow << shift);
1177         if (val & ~mask)
1178                 return -EINVAL;
1179         /* Don't "lock" with no region! */
1180         if (!(val & mask))
1181                 return -EINVAL;
1182
1183         status_new = (status_old & ~mask & ~SR_TB) | val;
1184
1185         /* Disallow further writes if WP pin is asserted */
1186         status_new |= SR_SRWD;
1187
1188         if (!use_top)
1189                 status_new |= SR_TB;
1190
1191         /* Don't bother if they're the same */
1192         if (status_new == status_old)
1193                 return 0;
1194
1195         /* Only modify protection if it will not unlock other areas */
1196         if ((status_new & mask) < (status_old & mask))
1197                 return -EINVAL;
1198
1199         return write_sr_and_check(nor, status_new, mask);
1200 }
1201
1202 /*
1203  * Unlock a region of the flash. See stm_lock() for more info
1204  *
1205  * Returns negative on errors, 0 on success.
1206  */
1207 static int stm_unlock(struct spi_nor *nor, loff_t ofs, uint64_t len)
1208 {
1209         struct mtd_info *mtd = &nor->mtd;
1210         int status_old, status_new;
1211         u8 mask = SR_BP2 | SR_BP1 | SR_BP0;
1212         u8 shift = ffs(mask) - 1, pow, val;
1213         loff_t lock_len;
1214         bool can_be_top = true, can_be_bottom = nor->flags & SNOR_F_HAS_SR_TB;
1215         bool use_top;
1216
1217         status_old = read_sr(nor);
1218         if (status_old < 0)
1219                 return status_old;
1220
1221         /* If nothing in our range is locked, we don't need to do anything */
1222         if (stm_is_unlocked_sr(nor, ofs, len, status_old))
1223                 return 0;
1224
1225         /* If anything below us is locked, we can't use 'top' protection */
1226         if (!stm_is_unlocked_sr(nor, 0, ofs, status_old))
1227                 can_be_top = false;
1228
1229         /* If anything above us is locked, we can't use 'bottom' protection */
1230         if (!stm_is_unlocked_sr(nor, ofs + len, mtd->size - (ofs + len),
1231                                 status_old))
1232                 can_be_bottom = false;
1233
1234         if (!can_be_bottom && !can_be_top)
1235                 return -EINVAL;
1236
1237         /* Prefer top, if both are valid */
1238         use_top = can_be_top;
1239
1240         /* lock_len: length of region that should remain locked */
1241         if (use_top)
1242                 lock_len = mtd->size - (ofs + len);
1243         else
1244                 lock_len = ofs;
1245
1246         /*
1247          * Need largest pow such that:
1248          *
1249          *   1 / (2^pow) >= (len / size)
1250          *
1251          * so (assuming power-of-2 size) we do:
1252          *
1253          *   pow = floor(log2(size / len)) = log2(size) - ceil(log2(len))
1254          */
1255         pow = ilog2(mtd->size) - order_base_2(lock_len);
1256         if (lock_len == 0) {
1257                 val = 0; /* fully unlocked */
1258         } else {
1259                 val = mask - (pow << shift);
1260                 /* Some power-of-two sizes are not supported */
1261                 if (val & ~mask)
1262                         return -EINVAL;
1263         }
1264
1265         status_new = (status_old & ~mask & ~SR_TB) | val;
1266
1267         /* Don't protect status register if we're fully unlocked */
1268         if (lock_len == 0)
1269                 status_new &= ~SR_SRWD;
1270
1271         if (!use_top)
1272                 status_new |= SR_TB;
1273
1274         /* Don't bother if they're the same */
1275         if (status_new == status_old)
1276                 return 0;
1277
1278         /* Only modify protection if it will not lock other areas */
1279         if ((status_new & mask) > (status_old & mask))
1280                 return -EINVAL;
1281
1282         return write_sr_and_check(nor, status_new, mask);
1283 }
1284
1285 /*
1286  * Check if a region of the flash is (completely) locked. See stm_lock() for
1287  * more info.
1288  *
1289  * Returns 1 if entire region is locked, 0 if any portion is unlocked, and
1290  * negative on errors.
1291  */
1292 static int stm_is_locked(struct spi_nor *nor, loff_t ofs, uint64_t len)
1293 {
1294         int status;
1295
1296         status = read_sr(nor);
1297         if (status < 0)
1298                 return status;
1299
1300         return stm_is_locked_sr(nor, ofs, len, status);
1301 }
1302 #endif /* CONFIG_SPI_FLASH_STMICRO */
1303
1304 static const struct flash_info *spi_nor_read_id(struct spi_nor *nor)
1305 {
1306         int                     tmp;
1307         u8                      id[SPI_NOR_MAX_ID_LEN];
1308         const struct flash_info *info;
1309
1310         tmp = nor->read_reg(nor, SPINOR_OP_RDID, id, SPI_NOR_MAX_ID_LEN);
1311         if (tmp < 0) {
1312                 dev_dbg(nor->dev, "error %d reading JEDEC ID\n", tmp);
1313                 return ERR_PTR(tmp);
1314         }
1315
1316         info = spi_nor_ids;
1317         for (; info->name; info++) {
1318                 if (info->id_len) {
1319                         if (!memcmp(info->id, id, info->id_len))
1320                                 return info;
1321                 }
1322         }
1323
1324         dev_err(nor->dev, "unrecognized JEDEC id bytes: %02x, %02x, %02x\n",
1325                 id[0], id[1], id[2]);
1326         return ERR_PTR(-ENODEV);
1327 }
1328
1329 static int spi_nor_read(struct mtd_info *mtd, loff_t from, size_t len,
1330                         size_t *retlen, u_char *buf)
1331 {
1332         struct spi_nor *nor = mtd_to_spi_nor(mtd);
1333         int ret;
1334
1335         dev_dbg(nor->dev, "from 0x%08x, len %zd\n", (u32)from, len);
1336
1337         while (len) {
1338                 loff_t addr = from;
1339                 size_t read_len = len;
1340
1341 #ifdef CONFIG_SPI_FLASH_BAR
1342                 u32 remain_len;
1343
1344                 ret = write_bar(nor, addr);
1345                 if (ret < 0)
1346                         return log_ret(ret);
1347                 remain_len = (SZ_16M * (nor->bank_curr + 1)) - addr;
1348
1349                 if (len < remain_len)
1350                         read_len = len;
1351                 else
1352                         read_len = remain_len;
1353 #endif
1354
1355                 ret = nor->read(nor, addr, read_len, buf);
1356                 if (ret == 0) {
1357                         /* We shouldn't see 0-length reads */
1358                         ret = -EIO;
1359                         goto read_err;
1360                 }
1361                 if (ret < 0)
1362                         goto read_err;
1363
1364                 *retlen += ret;
1365                 buf += ret;
1366                 from += ret;
1367                 len -= ret;
1368         }
1369         ret = 0;
1370
1371 read_err:
1372 #ifdef CONFIG_SPI_FLASH_BAR
1373         ret = clean_bar(nor);
1374 #endif
1375         return ret;
1376 }
1377
1378 #ifdef CONFIG_SPI_FLASH_SST
1379 /*
1380  * sst26 flash series has its own block protection implementation:
1381  * 4x   - 8  KByte blocks - read & write protection bits - upper addresses
1382  * 1x   - 32 KByte blocks - write protection bits
1383  * rest - 64 KByte blocks - write protection bits
1384  * 1x   - 32 KByte blocks - write protection bits
1385  * 4x   - 8  KByte blocks - read & write protection bits - lower addresses
1386  *
1387  * We'll support only per 64k lock/unlock so lower and upper 64 KByte region
1388  * will be treated as single block.
1389  */
1390 #define SST26_BPR_8K_NUM                4
1391 #define SST26_MAX_BPR_REG_LEN           (18 + 1)
1392 #define SST26_BOUND_REG_SIZE            ((32 + SST26_BPR_8K_NUM * 8) * SZ_1K)
1393
1394 enum lock_ctl {
1395         SST26_CTL_LOCK,
1396         SST26_CTL_UNLOCK,
1397         SST26_CTL_CHECK
1398 };
1399
1400 static bool sst26_process_bpr(u32 bpr_size, u8 *cmd, u32 bit, enum lock_ctl ctl)
1401 {
1402         switch (ctl) {
1403         case SST26_CTL_LOCK:
1404                 cmd[bpr_size - (bit / 8) - 1] |= BIT(bit % 8);
1405                 break;
1406         case SST26_CTL_UNLOCK:
1407                 cmd[bpr_size - (bit / 8) - 1] &= ~BIT(bit % 8);
1408                 break;
1409         case SST26_CTL_CHECK:
1410                 return !!(cmd[bpr_size - (bit / 8) - 1] & BIT(bit % 8));
1411         }
1412
1413         return false;
1414 }
1415
1416 /*
1417  * Lock, unlock or check lock status of the flash region of the flash (depending
1418  * on the lock_ctl value)
1419  */
1420 static int sst26_lock_ctl(struct spi_nor *nor, loff_t ofs, uint64_t len, enum lock_ctl ctl)
1421 {
1422         struct mtd_info *mtd = &nor->mtd;
1423         u32 i, bpr_ptr, rptr_64k, lptr_64k, bpr_size;
1424         bool lower_64k = false, upper_64k = false;
1425         u8 bpr_buff[SST26_MAX_BPR_REG_LEN] = {};
1426         int ret;
1427
1428         /* Check length and offset for 64k alignment */
1429         if ((ofs & (SZ_64K - 1)) || (len & (SZ_64K - 1))) {
1430                 dev_err(nor->dev, "length or offset is not 64KiB allighned\n");
1431                 return -EINVAL;
1432         }
1433
1434         if (ofs + len > mtd->size) {
1435                 dev_err(nor->dev, "range is more than device size: %#llx + %#llx > %#llx\n",
1436                         ofs, len, mtd->size);
1437                 return -EINVAL;
1438         }
1439
1440         /* SST26 family has only 16 Mbit, 32 Mbit and 64 Mbit IC */
1441         if (mtd->size != SZ_2M &&
1442             mtd->size != SZ_4M &&
1443             mtd->size != SZ_8M)
1444                 return -EINVAL;
1445
1446         bpr_size = 2 + (mtd->size / SZ_64K / 8);
1447
1448         ret = nor->read_reg(nor, SPINOR_OP_READ_BPR, bpr_buff, bpr_size);
1449         if (ret < 0) {
1450                 dev_err(nor->dev, "fail to read block-protection register\n");
1451                 return ret;
1452         }
1453
1454         rptr_64k = min_t(u32, ofs + len, mtd->size - SST26_BOUND_REG_SIZE);
1455         lptr_64k = max_t(u32, ofs, SST26_BOUND_REG_SIZE);
1456
1457         upper_64k = ((ofs + len) > (mtd->size - SST26_BOUND_REG_SIZE));
1458         lower_64k = (ofs < SST26_BOUND_REG_SIZE);
1459
1460         /* Lower bits in block-protection register are about 64k region */
1461         bpr_ptr = lptr_64k / SZ_64K - 1;
1462
1463         /* Process 64K blocks region */
1464         while (lptr_64k < rptr_64k) {
1465                 if (sst26_process_bpr(bpr_size, bpr_buff, bpr_ptr, ctl))
1466                         return EACCES;
1467
1468                 bpr_ptr++;
1469                 lptr_64k += SZ_64K;
1470         }
1471
1472         /* 32K and 8K region bits in BPR are after 64k region bits */
1473         bpr_ptr = (mtd->size - 2 * SST26_BOUND_REG_SIZE) / SZ_64K;
1474
1475         /* Process lower 32K block region */
1476         if (lower_64k)
1477                 if (sst26_process_bpr(bpr_size, bpr_buff, bpr_ptr, ctl))
1478                         return EACCES;
1479
1480         bpr_ptr++;
1481
1482         /* Process upper 32K block region */
1483         if (upper_64k)
1484                 if (sst26_process_bpr(bpr_size, bpr_buff, bpr_ptr, ctl))
1485                         return EACCES;
1486
1487         bpr_ptr++;
1488
1489         /* Process lower 8K block regions */
1490         for (i = 0; i < SST26_BPR_8K_NUM; i++) {
1491                 if (lower_64k)
1492                         if (sst26_process_bpr(bpr_size, bpr_buff, bpr_ptr, ctl))
1493                                 return EACCES;
1494
1495                 /* In 8K area BPR has both read and write protection bits */
1496                 bpr_ptr += 2;
1497         }
1498
1499         /* Process upper 8K block regions */
1500         for (i = 0; i < SST26_BPR_8K_NUM; i++) {
1501                 if (upper_64k)
1502                         if (sst26_process_bpr(bpr_size, bpr_buff, bpr_ptr, ctl))
1503                                 return EACCES;
1504
1505                 /* In 8K area BPR has both read and write protection bits */
1506                 bpr_ptr += 2;
1507         }
1508
1509         /* If we check region status we don't need to write BPR back */
1510         if (ctl == SST26_CTL_CHECK)
1511                 return 0;
1512
1513         ret = nor->write_reg(nor, SPINOR_OP_WRITE_BPR, bpr_buff, bpr_size);
1514         if (ret < 0) {
1515                 dev_err(nor->dev, "fail to write block-protection register\n");
1516                 return ret;
1517         }
1518
1519         return 0;
1520 }
1521
1522 static int sst26_unlock(struct spi_nor *nor, loff_t ofs, uint64_t len)
1523 {
1524         return sst26_lock_ctl(nor, ofs, len, SST26_CTL_UNLOCK);
1525 }
1526
1527 static int sst26_lock(struct spi_nor *nor, loff_t ofs, uint64_t len)
1528 {
1529         return sst26_lock_ctl(nor, ofs, len, SST26_CTL_LOCK);
1530 }
1531
1532 /*
1533  * Returns EACCES (positive value) if region is locked, 0 if region is unlocked,
1534  * and negative on errors.
1535  */
1536 static int sst26_is_locked(struct spi_nor *nor, loff_t ofs, uint64_t len)
1537 {
1538         /*
1539          * is_locked function is used for check before reading or erasing flash
1540          * region, so offset and length might be not 64k allighned, so adjust
1541          * them to be 64k allighned as sst26_lock_ctl works only with 64k
1542          * allighned regions.
1543          */
1544         ofs -= ofs & (SZ_64K - 1);
1545         len = len & (SZ_64K - 1) ? (len & ~(SZ_64K - 1)) + SZ_64K : len;
1546
1547         return sst26_lock_ctl(nor, ofs, len, SST26_CTL_CHECK);
1548 }
1549
1550 static int sst_write_byteprogram(struct spi_nor *nor, loff_t to, size_t len,
1551                                  size_t *retlen, const u_char *buf)
1552 {
1553         size_t actual;
1554         int ret = 0;
1555
1556         for (actual = 0; actual < len; actual++) {
1557                 nor->program_opcode = SPINOR_OP_BP;
1558
1559                 write_enable(nor);
1560                 /* write one byte. */
1561                 ret = nor->write(nor, to, 1, buf + actual);
1562                 if (ret < 0)
1563                         goto sst_write_err;
1564                 ret = spi_nor_wait_till_ready(nor);
1565                 if (ret)
1566                         goto sst_write_err;
1567                 to++;
1568         }
1569
1570 sst_write_err:
1571         write_disable(nor);
1572         return ret;
1573 }
1574
1575 static int sst_write(struct mtd_info *mtd, loff_t to, size_t len,
1576                      size_t *retlen, const u_char *buf)
1577 {
1578         struct spi_nor *nor = mtd_to_spi_nor(mtd);
1579         struct spi_slave *spi = nor->spi;
1580         size_t actual;
1581         int ret;
1582
1583         dev_dbg(nor->dev, "to 0x%08x, len %zd\n", (u32)to, len);
1584         if (spi->mode & SPI_TX_BYTE)
1585                 return sst_write_byteprogram(nor, to, len, retlen, buf);
1586
1587         write_enable(nor);
1588
1589         nor->sst_write_second = false;
1590
1591         actual = to % 2;
1592         /* Start write from odd address. */
1593         if (actual) {
1594                 nor->program_opcode = SPINOR_OP_BP;
1595
1596                 /* write one byte. */
1597                 ret = nor->write(nor, to, 1, buf);
1598                 if (ret < 0)
1599                         goto sst_write_err;
1600                 ret = spi_nor_wait_till_ready(nor);
1601                 if (ret)
1602                         goto sst_write_err;
1603         }
1604         to += actual;
1605
1606         /* Write out most of the data here. */
1607         for (; actual < len - 1; actual += 2) {
1608                 nor->program_opcode = SPINOR_OP_AAI_WP;
1609
1610                 /* write two bytes. */
1611                 ret = nor->write(nor, to, 2, buf + actual);
1612                 if (ret < 0)
1613                         goto sst_write_err;
1614                 ret = spi_nor_wait_till_ready(nor);
1615                 if (ret)
1616                         goto sst_write_err;
1617                 to += 2;
1618                 nor->sst_write_second = true;
1619         }
1620         nor->sst_write_second = false;
1621
1622         write_disable(nor);
1623         ret = spi_nor_wait_till_ready(nor);
1624         if (ret)
1625                 goto sst_write_err;
1626
1627         /* Write out trailing byte if it exists. */
1628         if (actual != len) {
1629                 write_enable(nor);
1630
1631                 nor->program_opcode = SPINOR_OP_BP;
1632                 ret = nor->write(nor, to, 1, buf + actual);
1633                 if (ret < 0)
1634                         goto sst_write_err;
1635                 ret = spi_nor_wait_till_ready(nor);
1636                 if (ret)
1637                         goto sst_write_err;
1638                 write_disable(nor);
1639                 actual += 1;
1640         }
1641 sst_write_err:
1642         *retlen += actual;
1643         return ret;
1644 }
1645 #endif
1646 /*
1647  * Write an address range to the nor chip.  Data must be written in
1648  * FLASH_PAGESIZE chunks.  The address range may be any size provided
1649  * it is within the physical boundaries.
1650  */
1651 static int spi_nor_write(struct mtd_info *mtd, loff_t to, size_t len,
1652         size_t *retlen, const u_char *buf)
1653 {
1654         struct spi_nor *nor = mtd_to_spi_nor(mtd);
1655         size_t page_offset, page_remain, i;
1656         ssize_t ret;
1657
1658 #ifdef CONFIG_SPI_FLASH_SST
1659         /* sst nor chips use AAI word program */
1660         if (nor->info->flags & SST_WRITE)
1661                 return sst_write(mtd, to, len, retlen, buf);
1662 #endif
1663
1664         dev_dbg(nor->dev, "to 0x%08x, len %zd\n", (u32)to, len);
1665
1666         if (!len)
1667                 return 0;
1668
1669         for (i = 0; i < len; ) {
1670                 ssize_t written;
1671                 loff_t addr = to + i;
1672                 WATCHDOG_RESET();
1673
1674                 /*
1675                  * If page_size is a power of two, the offset can be quickly
1676                  * calculated with an AND operation. On the other cases we
1677                  * need to do a modulus operation (more expensive).
1678                  */
1679                 if (is_power_of_2(nor->page_size)) {
1680                         page_offset = addr & (nor->page_size - 1);
1681                 } else {
1682                         u64 aux = addr;
1683
1684                         page_offset = do_div(aux, nor->page_size);
1685                 }
1686                 /* the size of data remaining on the first page */
1687                 page_remain = min_t(size_t,
1688                                     nor->page_size - page_offset, len - i);
1689
1690 #ifdef CONFIG_SPI_FLASH_BAR
1691                 ret = write_bar(nor, addr);
1692                 if (ret < 0)
1693                         return ret;
1694 #endif
1695                 write_enable(nor);
1696                 ret = nor->write(nor, addr, page_remain, buf + i);
1697                 if (ret < 0)
1698                         goto write_err;
1699                 written = ret;
1700
1701                 ret = spi_nor_wait_till_ready(nor);
1702                 if (ret)
1703                         goto write_err;
1704                 *retlen += written;
1705                 i += written;
1706         }
1707
1708 write_err:
1709 #ifdef CONFIG_SPI_FLASH_BAR
1710         ret = clean_bar(nor);
1711 #endif
1712         return ret;
1713 }
1714
1715 #if defined(CONFIG_SPI_FLASH_MACRONIX) || defined(CONFIG_SPI_FLASH_ISSI)
1716 /**
1717  * macronix_quad_enable() - set QE bit in Status Register.
1718  * @nor:        pointer to a 'struct spi_nor'
1719  *
1720  * Set the Quad Enable (QE) bit in the Status Register.
1721  *
1722  * bit 6 of the Status Register is the QE bit for Macronix like QSPI memories.
1723  *
1724  * Return: 0 on success, -errno otherwise.
1725  */
1726 static int macronix_quad_enable(struct spi_nor *nor)
1727 {
1728         int ret, val;
1729
1730         val = read_sr(nor);
1731         if (val < 0)
1732                 return val;
1733         if (val & SR_QUAD_EN_MX)
1734                 return 0;
1735
1736         write_enable(nor);
1737
1738         write_sr(nor, val | SR_QUAD_EN_MX);
1739
1740         ret = spi_nor_wait_till_ready(nor);
1741         if (ret)
1742                 return ret;
1743
1744         ret = read_sr(nor);
1745         if (!(ret > 0 && (ret & SR_QUAD_EN_MX))) {
1746                 dev_err(nor->dev, "Macronix Quad bit not set\n");
1747                 return -EINVAL;
1748         }
1749
1750         return 0;
1751 }
1752 #endif
1753
1754 #ifdef CONFIG_SPI_FLASH_SPANSION
1755 /**
1756  * spansion_quad_enable_volatile() - enable Quad I/O mode in volatile register.
1757  * @nor:        pointer to a 'struct spi_nor'
1758  * @addr_base:  base address of register (can be >0 in multi-die parts)
1759  * @dummy:      number of dummy cycles for register read
1760  *
1761  * It is recommended to update volatile registers in the field application due
1762  * to a risk of the non-volatile registers corruption by power interrupt. This
1763  * function sets Quad Enable bit in CFR1 volatile.
1764  *
1765  * Return: 0 on success, -errno otherwise.
1766  */
1767 static int spansion_quad_enable_volatile(struct spi_nor *nor, u32 addr_base,
1768                                          u8 dummy)
1769 {
1770         u32 addr = addr_base + SPINOR_REG_ADDR_CFR1V;
1771
1772         u8 cr;
1773         int ret;
1774
1775         /* Check current Quad Enable bit value. */
1776         ret = spansion_read_any_reg(nor, addr, dummy, &cr);
1777         if (ret < 0) {
1778                 dev_dbg(nor->dev,
1779                         "error while reading configuration register\n");
1780                 return -EINVAL;
1781         }
1782
1783         if (cr & CR_QUAD_EN_SPAN)
1784                 return 0;
1785
1786         cr |= CR_QUAD_EN_SPAN;
1787
1788         write_enable(nor);
1789
1790         ret = spansion_write_any_reg(nor, addr, cr);
1791
1792         if (ret < 0) {
1793                 dev_dbg(nor->dev,
1794                         "error while writing configuration register\n");
1795                 return -EINVAL;
1796         }
1797
1798         /* Read back and check it. */
1799         ret = spansion_read_any_reg(nor, addr, dummy, &cr);
1800         if (ret || !(cr & CR_QUAD_EN_SPAN)) {
1801                 dev_dbg(nor->dev, "Spansion Quad bit not set\n");
1802                 return -EINVAL;
1803         }
1804
1805         return 0;
1806 }
1807 #endif
1808
1809 #if defined(CONFIG_SPI_FLASH_SPANSION) || defined(CONFIG_SPI_FLASH_WINBOND)
1810 /*
1811  * Write status Register and configuration register with 2 bytes
1812  * The first byte will be written to the status register, while the
1813  * second byte will be written to the configuration register.
1814  * Return negative if error occurred.
1815  */
1816 static int write_sr_cr(struct spi_nor *nor, u8 *sr_cr)
1817 {
1818         int ret;
1819
1820         write_enable(nor);
1821
1822         ret = nor->write_reg(nor, SPINOR_OP_WRSR, sr_cr, 2);
1823         if (ret < 0) {
1824                 dev_dbg(nor->dev,
1825                         "error while writing configuration register\n");
1826                 return -EINVAL;
1827         }
1828
1829         ret = spi_nor_wait_till_ready(nor);
1830         if (ret) {
1831                 dev_dbg(nor->dev,
1832                         "timeout while writing configuration register\n");
1833                 return ret;
1834         }
1835
1836         return 0;
1837 }
1838
1839 /**
1840  * spansion_read_cr_quad_enable() - set QE bit in Configuration Register.
1841  * @nor:        pointer to a 'struct spi_nor'
1842  *
1843  * Set the Quad Enable (QE) bit in the Configuration Register.
1844  * This function should be used with QSPI memories supporting the Read
1845  * Configuration Register (35h) instruction.
1846  *
1847  * bit 1 of the Configuration Register is the QE bit for Spansion like QSPI
1848  * memories.
1849  *
1850  * Return: 0 on success, -errno otherwise.
1851  */
1852 static int spansion_read_cr_quad_enable(struct spi_nor *nor)
1853 {
1854         u8 sr_cr[2];
1855         int ret;
1856
1857         /* Check current Quad Enable bit value. */
1858         ret = read_cr(nor);
1859         if (ret < 0) {
1860                 dev_dbg(nor->dev,
1861                         "error while reading configuration register\n");
1862                 return -EINVAL;
1863         }
1864
1865         if (ret & CR_QUAD_EN_SPAN)
1866                 return 0;
1867
1868         sr_cr[1] = ret | CR_QUAD_EN_SPAN;
1869
1870         /* Keep the current value of the Status Register. */
1871         ret = read_sr(nor);
1872         if (ret < 0) {
1873                 dev_dbg(nor->dev, "error while reading status register\n");
1874                 return -EINVAL;
1875         }
1876         sr_cr[0] = ret;
1877
1878         ret = write_sr_cr(nor, sr_cr);
1879         if (ret)
1880                 return ret;
1881
1882         /* Read back and check it. */
1883         ret = read_cr(nor);
1884         if (!(ret > 0 && (ret & CR_QUAD_EN_SPAN))) {
1885                 dev_dbg(nor->dev, "Spansion Quad bit not set\n");
1886                 return -EINVAL;
1887         }
1888
1889         return 0;
1890 }
1891
1892 #if CONFIG_IS_ENABLED(SPI_FLASH_SFDP_SUPPORT)
1893 /**
1894  * spansion_no_read_cr_quad_enable() - set QE bit in Configuration Register.
1895  * @nor:        pointer to a 'struct spi_nor'
1896  *
1897  * Set the Quad Enable (QE) bit in the Configuration Register.
1898  * This function should be used with QSPI memories not supporting the Read
1899  * Configuration Register (35h) instruction.
1900  *
1901  * bit 1 of the Configuration Register is the QE bit for Spansion like QSPI
1902  * memories.
1903  *
1904  * Return: 0 on success, -errno otherwise.
1905  */
1906 static int spansion_no_read_cr_quad_enable(struct spi_nor *nor)
1907 {
1908         u8 sr_cr[2];
1909         int ret;
1910
1911         /* Keep the current value of the Status Register. */
1912         ret = read_sr(nor);
1913         if (ret < 0) {
1914                 dev_dbg(nor->dev, "error while reading status register\n");
1915                 return -EINVAL;
1916         }
1917         sr_cr[0] = ret;
1918         sr_cr[1] = CR_QUAD_EN_SPAN;
1919
1920         return write_sr_cr(nor, sr_cr);
1921 }
1922
1923 #endif /* CONFIG_SPI_FLASH_SFDP_SUPPORT */
1924 #endif /* CONFIG_SPI_FLASH_SPANSION */
1925
1926 static void
1927 spi_nor_set_read_settings(struct spi_nor_read_command *read,
1928                           u8 num_mode_clocks,
1929                           u8 num_wait_states,
1930                           u8 opcode,
1931                           enum spi_nor_protocol proto)
1932 {
1933         read->num_mode_clocks = num_mode_clocks;
1934         read->num_wait_states = num_wait_states;
1935         read->opcode = opcode;
1936         read->proto = proto;
1937 }
1938
1939 static void
1940 spi_nor_set_pp_settings(struct spi_nor_pp_command *pp,
1941                         u8 opcode,
1942                         enum spi_nor_protocol proto)
1943 {
1944         pp->opcode = opcode;
1945         pp->proto = proto;
1946 }
1947
1948 #if CONFIG_IS_ENABLED(SPI_FLASH_SFDP_SUPPORT)
1949 /*
1950  * Serial Flash Discoverable Parameters (SFDP) parsing.
1951  */
1952
1953 /**
1954  * spi_nor_read_sfdp() - read Serial Flash Discoverable Parameters.
1955  * @nor:        pointer to a 'struct spi_nor'
1956  * @addr:       offset in the SFDP area to start reading data from
1957  * @len:        number of bytes to read
1958  * @buf:        buffer where the SFDP data are copied into (dma-safe memory)
1959  *
1960  * Whatever the actual numbers of bytes for address and dummy cycles are
1961  * for (Fast) Read commands, the Read SFDP (5Ah) instruction is always
1962  * followed by a 3-byte address and 8 dummy clock cycles.
1963  *
1964  * Return: 0 on success, -errno otherwise.
1965  */
1966 static int spi_nor_read_sfdp(struct spi_nor *nor, u32 addr,
1967                              size_t len, void *buf)
1968 {
1969         u8 addr_width, read_opcode, read_dummy;
1970         int ret;
1971
1972         read_opcode = nor->read_opcode;
1973         addr_width = nor->addr_width;
1974         read_dummy = nor->read_dummy;
1975
1976         nor->read_opcode = SPINOR_OP_RDSFDP;
1977         nor->addr_width = 3;
1978         nor->read_dummy = 8;
1979
1980         while (len) {
1981                 ret = nor->read(nor, addr, len, (u8 *)buf);
1982                 if (!ret || ret > len) {
1983                         ret = -EIO;
1984                         goto read_err;
1985                 }
1986                 if (ret < 0)
1987                         goto read_err;
1988
1989                 buf += ret;
1990                 addr += ret;
1991                 len -= ret;
1992         }
1993         ret = 0;
1994
1995 read_err:
1996         nor->read_opcode = read_opcode;
1997         nor->addr_width = addr_width;
1998         nor->read_dummy = read_dummy;
1999
2000         return ret;
2001 }
2002
2003 /* Fast Read settings. */
2004
2005 static void
2006 spi_nor_set_read_settings_from_bfpt(struct spi_nor_read_command *read,
2007                                     u16 half,
2008                                     enum spi_nor_protocol proto)
2009 {
2010         read->num_mode_clocks = (half >> 5) & 0x07;
2011         read->num_wait_states = (half >> 0) & 0x1f;
2012         read->opcode = (half >> 8) & 0xff;
2013         read->proto = proto;
2014 }
2015
2016 struct sfdp_bfpt_read {
2017         /* The Fast Read x-y-z hardware capability in params->hwcaps.mask. */
2018         u32                     hwcaps;
2019
2020         /*
2021          * The <supported_bit> bit in <supported_dword> BFPT DWORD tells us
2022          * whether the Fast Read x-y-z command is supported.
2023          */
2024         u32                     supported_dword;
2025         u32                     supported_bit;
2026
2027         /*
2028          * The half-word at offset <setting_shift> in <setting_dword> BFPT DWORD
2029          * encodes the op code, the number of mode clocks and the number of wait
2030          * states to be used by Fast Read x-y-z command.
2031          */
2032         u32                     settings_dword;
2033         u32                     settings_shift;
2034
2035         /* The SPI protocol for this Fast Read x-y-z command. */
2036         enum spi_nor_protocol   proto;
2037 };
2038
2039 static const struct sfdp_bfpt_read sfdp_bfpt_reads[] = {
2040         /* Fast Read 1-1-2 */
2041         {
2042                 SNOR_HWCAPS_READ_1_1_2,
2043                 BFPT_DWORD(1), BIT(16), /* Supported bit */
2044                 BFPT_DWORD(4), 0,       /* Settings */
2045                 SNOR_PROTO_1_1_2,
2046         },
2047
2048         /* Fast Read 1-2-2 */
2049         {
2050                 SNOR_HWCAPS_READ_1_2_2,
2051                 BFPT_DWORD(1), BIT(20), /* Supported bit */
2052                 BFPT_DWORD(4), 16,      /* Settings */
2053                 SNOR_PROTO_1_2_2,
2054         },
2055
2056         /* Fast Read 2-2-2 */
2057         {
2058                 SNOR_HWCAPS_READ_2_2_2,
2059                 BFPT_DWORD(5),  BIT(0), /* Supported bit */
2060                 BFPT_DWORD(6), 16,      /* Settings */
2061                 SNOR_PROTO_2_2_2,
2062         },
2063
2064         /* Fast Read 1-1-4 */
2065         {
2066                 SNOR_HWCAPS_READ_1_1_4,
2067                 BFPT_DWORD(1), BIT(22), /* Supported bit */
2068                 BFPT_DWORD(3), 16,      /* Settings */
2069                 SNOR_PROTO_1_1_4,
2070         },
2071
2072         /* Fast Read 1-4-4 */
2073         {
2074                 SNOR_HWCAPS_READ_1_4_4,
2075                 BFPT_DWORD(1), BIT(21), /* Supported bit */
2076                 BFPT_DWORD(3), 0,       /* Settings */
2077                 SNOR_PROTO_1_4_4,
2078         },
2079
2080         /* Fast Read 4-4-4 */
2081         {
2082                 SNOR_HWCAPS_READ_4_4_4,
2083                 BFPT_DWORD(5), BIT(4),  /* Supported bit */
2084                 BFPT_DWORD(7), 16,      /* Settings */
2085                 SNOR_PROTO_4_4_4,
2086         },
2087 };
2088
2089 struct sfdp_bfpt_erase {
2090         /*
2091          * The half-word at offset <shift> in DWORD <dwoard> encodes the
2092          * op code and erase sector size to be used by Sector Erase commands.
2093          */
2094         u32                     dword;
2095         u32                     shift;
2096 };
2097
2098 static const struct sfdp_bfpt_erase sfdp_bfpt_erases[] = {
2099         /* Erase Type 1 in DWORD8 bits[15:0] */
2100         {BFPT_DWORD(8), 0},
2101
2102         /* Erase Type 2 in DWORD8 bits[31:16] */
2103         {BFPT_DWORD(8), 16},
2104
2105         /* Erase Type 3 in DWORD9 bits[15:0] */
2106         {BFPT_DWORD(9), 0},
2107
2108         /* Erase Type 4 in DWORD9 bits[31:16] */
2109         {BFPT_DWORD(9), 16},
2110 };
2111
2112 static int spi_nor_hwcaps_read2cmd(u32 hwcaps);
2113
2114 static int
2115 spi_nor_post_bfpt_fixups(struct spi_nor *nor,
2116                          const struct sfdp_parameter_header *bfpt_header,
2117                          const struct sfdp_bfpt *bfpt,
2118                          struct spi_nor_flash_parameter *params)
2119 {
2120         if (nor->fixups && nor->fixups->post_bfpt)
2121                 return nor->fixups->post_bfpt(nor, bfpt_header, bfpt, params);
2122
2123         return 0;
2124 }
2125
2126 /**
2127  * spi_nor_parse_bfpt() - read and parse the Basic Flash Parameter Table.
2128  * @nor:                pointer to a 'struct spi_nor'
2129  * @bfpt_header:        pointer to the 'struct sfdp_parameter_header' describing
2130  *                      the Basic Flash Parameter Table length and version
2131  * @params:             pointer to the 'struct spi_nor_flash_parameter' to be
2132  *                      filled
2133  *
2134  * The Basic Flash Parameter Table is the main and only mandatory table as
2135  * defined by the SFDP (JESD216) specification.
2136  * It provides us with the total size (memory density) of the data array and
2137  * the number of address bytes for Fast Read, Page Program and Sector Erase
2138  * commands.
2139  * For Fast READ commands, it also gives the number of mode clock cycles and
2140  * wait states (regrouped in the number of dummy clock cycles) for each
2141  * supported instruction op code.
2142  * For Page Program, the page size is now available since JESD216 rev A, however
2143  * the supported instruction op codes are still not provided.
2144  * For Sector Erase commands, this table stores the supported instruction op
2145  * codes and the associated sector sizes.
2146  * Finally, the Quad Enable Requirements (QER) are also available since JESD216
2147  * rev A. The QER bits encode the manufacturer dependent procedure to be
2148  * executed to set the Quad Enable (QE) bit in some internal register of the
2149  * Quad SPI memory. Indeed the QE bit, when it exists, must be set before
2150  * sending any Quad SPI command to the memory. Actually, setting the QE bit
2151  * tells the memory to reassign its WP# and HOLD#/RESET# pins to functions IO2
2152  * and IO3 hence enabling 4 (Quad) I/O lines.
2153  *
2154  * Return: 0 on success, -errno otherwise.
2155  */
2156 static int spi_nor_parse_bfpt(struct spi_nor *nor,
2157                               const struct sfdp_parameter_header *bfpt_header,
2158                               struct spi_nor_flash_parameter *params)
2159 {
2160         struct mtd_info *mtd = &nor->mtd;
2161         struct sfdp_bfpt bfpt;
2162         size_t len;
2163         int i, cmd, err;
2164         u32 addr;
2165         u16 half;
2166
2167         /* JESD216 Basic Flash Parameter Table length is at least 9 DWORDs. */
2168         if (bfpt_header->length < BFPT_DWORD_MAX_JESD216)
2169                 return -EINVAL;
2170
2171         /* Read the Basic Flash Parameter Table. */
2172         len = min_t(size_t, sizeof(bfpt),
2173                     bfpt_header->length * sizeof(u32));
2174         addr = SFDP_PARAM_HEADER_PTP(bfpt_header);
2175         memset(&bfpt, 0, sizeof(bfpt));
2176         err = spi_nor_read_sfdp(nor,  addr, len, &bfpt);
2177         if (err < 0)
2178                 return err;
2179
2180         /* Fix endianness of the BFPT DWORDs. */
2181         for (i = 0; i < BFPT_DWORD_MAX; i++)
2182                 bfpt.dwords[i] = le32_to_cpu(bfpt.dwords[i]);
2183
2184         /* Number of address bytes. */
2185         switch (bfpt.dwords[BFPT_DWORD(1)] & BFPT_DWORD1_ADDRESS_BYTES_MASK) {
2186         case BFPT_DWORD1_ADDRESS_BYTES_3_ONLY:
2187                 nor->addr_width = 3;
2188                 break;
2189
2190         case BFPT_DWORD1_ADDRESS_BYTES_4_ONLY:
2191                 nor->addr_width = 4;
2192                 break;
2193
2194         default:
2195                 break;
2196         }
2197
2198         /* Flash Memory Density (in bits). */
2199         params->size = bfpt.dwords[BFPT_DWORD(2)];
2200         if (params->size & BIT(31)) {
2201                 params->size &= ~BIT(31);
2202
2203                 /*
2204                  * Prevent overflows on params->size. Anyway, a NOR of 2^64
2205                  * bits is unlikely to exist so this error probably means
2206                  * the BFPT we are reading is corrupted/wrong.
2207                  */
2208                 if (params->size > 63)
2209                         return -EINVAL;
2210
2211                 params->size = 1ULL << params->size;
2212         } else {
2213                 params->size++;
2214         }
2215         params->size >>= 3; /* Convert to bytes. */
2216
2217         /* Fast Read settings. */
2218         for (i = 0; i < ARRAY_SIZE(sfdp_bfpt_reads); i++) {
2219                 const struct sfdp_bfpt_read *rd = &sfdp_bfpt_reads[i];
2220                 struct spi_nor_read_command *read;
2221
2222                 if (!(bfpt.dwords[rd->supported_dword] & rd->supported_bit)) {
2223                         params->hwcaps.mask &= ~rd->hwcaps;
2224                         continue;
2225                 }
2226
2227                 params->hwcaps.mask |= rd->hwcaps;
2228                 cmd = spi_nor_hwcaps_read2cmd(rd->hwcaps);
2229                 read = &params->reads[cmd];
2230                 half = bfpt.dwords[rd->settings_dword] >> rd->settings_shift;
2231                 spi_nor_set_read_settings_from_bfpt(read, half, rd->proto);
2232         }
2233
2234         /* Sector Erase settings. */
2235         for (i = 0; i < ARRAY_SIZE(sfdp_bfpt_erases); i++) {
2236                 const struct sfdp_bfpt_erase *er = &sfdp_bfpt_erases[i];
2237                 u32 erasesize;
2238                 u8 opcode;
2239
2240                 half = bfpt.dwords[er->dword] >> er->shift;
2241                 erasesize = half & 0xff;
2242
2243                 /* erasesize == 0 means this Erase Type is not supported. */
2244                 if (!erasesize)
2245                         continue;
2246
2247                 erasesize = 1U << erasesize;
2248                 opcode = (half >> 8) & 0xff;
2249 #ifdef CONFIG_SPI_FLASH_USE_4K_SECTORS
2250                 if (erasesize == SZ_4K) {
2251                         nor->erase_opcode = opcode;
2252                         mtd->erasesize = erasesize;
2253                         break;
2254                 }
2255 #endif
2256                 if (!mtd->erasesize || mtd->erasesize < erasesize) {
2257                         nor->erase_opcode = opcode;
2258                         mtd->erasesize = erasesize;
2259                 }
2260         }
2261
2262         /* Stop here if not JESD216 rev A or later. */
2263         if (bfpt_header->length == BFPT_DWORD_MAX_JESD216)
2264                 return spi_nor_post_bfpt_fixups(nor, bfpt_header, &bfpt,
2265                                                 params);
2266
2267         /* Page size: this field specifies 'N' so the page size = 2^N bytes. */
2268         params->page_size = bfpt.dwords[BFPT_DWORD(11)];
2269         params->page_size &= BFPT_DWORD11_PAGE_SIZE_MASK;
2270         params->page_size >>= BFPT_DWORD11_PAGE_SIZE_SHIFT;
2271         params->page_size = 1U << params->page_size;
2272
2273         /* Quad Enable Requirements. */
2274         switch (bfpt.dwords[BFPT_DWORD(15)] & BFPT_DWORD15_QER_MASK) {
2275         case BFPT_DWORD15_QER_NONE:
2276                 params->quad_enable = NULL;
2277                 break;
2278 #if defined(CONFIG_SPI_FLASH_SPANSION) || defined(CONFIG_SPI_FLASH_WINBOND)
2279         case BFPT_DWORD15_QER_SR2_BIT1_BUGGY:
2280         case BFPT_DWORD15_QER_SR2_BIT1_NO_RD:
2281                 params->quad_enable = spansion_no_read_cr_quad_enable;
2282                 break;
2283 #endif
2284 #if defined(CONFIG_SPI_FLASH_MACRONIX) || defined(CONFIG_SPI_FLASH_ISSI)
2285         case BFPT_DWORD15_QER_SR1_BIT6:
2286                 params->quad_enable = macronix_quad_enable;
2287                 break;
2288 #endif
2289 #if defined(CONFIG_SPI_FLASH_SPANSION) || defined(CONFIG_SPI_FLASH_WINBOND)
2290         case BFPT_DWORD15_QER_SR2_BIT1:
2291                 params->quad_enable = spansion_read_cr_quad_enable;
2292                 break;
2293 #endif
2294         default:
2295                 dev_dbg(nor->dev, "BFPT QER reserved value used\n");
2296                 break;
2297         }
2298
2299         /* Soft Reset support. */
2300         if (bfpt.dwords[BFPT_DWORD(16)] & BFPT_DWORD16_SOFT_RST)
2301                 nor->flags |= SNOR_F_SOFT_RESET;
2302
2303         /* Stop here if JESD216 rev B. */
2304         if (bfpt_header->length == BFPT_DWORD_MAX_JESD216B)
2305                 return spi_nor_post_bfpt_fixups(nor, bfpt_header, &bfpt,
2306                                                 params);
2307
2308         /* 8D-8D-8D command extension. */
2309         switch (bfpt.dwords[BFPT_DWORD(18)] & BFPT_DWORD18_CMD_EXT_MASK) {
2310         case BFPT_DWORD18_CMD_EXT_REP:
2311                 nor->cmd_ext_type = SPI_NOR_EXT_REPEAT;
2312                 break;
2313
2314         case BFPT_DWORD18_CMD_EXT_INV:
2315                 nor->cmd_ext_type = SPI_NOR_EXT_INVERT;
2316                 break;
2317
2318         case BFPT_DWORD18_CMD_EXT_RES:
2319                 return -EINVAL;
2320
2321         case BFPT_DWORD18_CMD_EXT_16B:
2322                 dev_err(nor->dev, "16-bit opcodes not supported\n");
2323                 return -ENOTSUPP;
2324         }
2325
2326         return spi_nor_post_bfpt_fixups(nor, bfpt_header, &bfpt, params);
2327 }
2328
2329 /**
2330  * spi_nor_parse_microchip_sfdp() - parse the Microchip manufacturer specific
2331  * SFDP table.
2332  * @nor:                pointer to a 'struct spi_nor'.
2333  * @param_header:       pointer to the SFDP parameter header.
2334  *
2335  * Return: 0 on success, -errno otherwise.
2336  */
2337 static int
2338 spi_nor_parse_microchip_sfdp(struct spi_nor *nor,
2339                              const struct sfdp_parameter_header *param_header)
2340 {
2341         size_t size;
2342         u32 addr;
2343         int ret;
2344
2345         size = param_header->length * sizeof(u32);
2346         addr = SFDP_PARAM_HEADER_PTP(param_header);
2347
2348         nor->manufacturer_sfdp = devm_kmalloc(nor->dev, size, GFP_KERNEL);
2349         if (!nor->manufacturer_sfdp)
2350                 return -ENOMEM;
2351
2352         ret = spi_nor_read_sfdp(nor, addr, size, nor->manufacturer_sfdp);
2353
2354         return ret;
2355 }
2356
2357 /**
2358  * spi_nor_parse_profile1() - parse the xSPI Profile 1.0 table
2359  * @nor:                pointer to a 'struct spi_nor'
2360  * @profile1_header:    pointer to the 'struct sfdp_parameter_header' describing
2361  *                      the 4-Byte Address Instruction Table length and version.
2362  * @params:             pointer to the 'struct spi_nor_flash_parameter' to be.
2363  *
2364  * Return: 0 on success, -errno otherwise.
2365  */
2366 static int spi_nor_parse_profile1(struct spi_nor *nor,
2367                                   const struct sfdp_parameter_header *profile1_header,
2368                                   struct spi_nor_flash_parameter *params)
2369 {
2370         u32 *table, opcode, addr;
2371         size_t len;
2372         int ret, i;
2373         u8 dummy;
2374
2375         len = profile1_header->length * sizeof(*table);
2376         table = kmalloc(len, GFP_KERNEL);
2377         if (!table)
2378                 return -ENOMEM;
2379
2380         addr = SFDP_PARAM_HEADER_PTP(profile1_header);
2381         ret = spi_nor_read_sfdp(nor, addr, len, table);
2382         if (ret)
2383                 goto out;
2384
2385         /* Fix endianness of the table DWORDs. */
2386         for (i = 0; i < profile1_header->length; i++)
2387                 table[i] = le32_to_cpu(table[i]);
2388
2389         /* Get 8D-8D-8D fast read opcode and dummy cycles. */
2390         opcode = FIELD_GET(PROFILE1_DWORD1_RD_FAST_CMD, table[0]);
2391
2392         /*
2393          * We don't know what speed the controller is running at. Find the
2394          * dummy cycles for the fastest frequency the flash can run at to be
2395          * sure we are never short of dummy cycles. A value of 0 means the
2396          * frequency is not supported.
2397          *
2398          * Default to PROFILE1_DUMMY_DEFAULT if we don't find anything, and let
2399          * flashes set the correct value if needed in their fixup hooks.
2400          */
2401         dummy = FIELD_GET(PROFILE1_DWORD4_DUMMY_200MHZ, table[3]);
2402         if (!dummy)
2403                 dummy = FIELD_GET(PROFILE1_DWORD5_DUMMY_166MHZ, table[4]);
2404         if (!dummy)
2405                 dummy = FIELD_GET(PROFILE1_DWORD5_DUMMY_133MHZ, table[4]);
2406         if (!dummy)
2407                 dummy = FIELD_GET(PROFILE1_DWORD5_DUMMY_100MHZ, table[4]);
2408         if (!dummy)
2409                 dummy = PROFILE1_DUMMY_DEFAULT;
2410
2411         /* Round up to an even value to avoid tripping controllers up. */
2412         dummy = ROUND_UP_TO(dummy, 2);
2413
2414         /* Update the fast read settings. */
2415         spi_nor_set_read_settings(&params->reads[SNOR_CMD_READ_8_8_8_DTR],
2416                                   0, dummy, opcode,
2417                                   SNOR_PROTO_8_8_8_DTR);
2418
2419         /*
2420          * Set the Read Status Register dummy cycles and dummy address bytes.
2421          */
2422         if (table[0] & PROFILE1_DWORD1_RDSR_DUMMY)
2423                 params->rdsr_dummy = 8;
2424         else
2425                 params->rdsr_dummy = 4;
2426
2427         if (table[0] & PROFILE1_DWORD1_RDSR_ADDR_BYTES)
2428                 params->rdsr_addr_nbytes = 4;
2429         else
2430                 params->rdsr_addr_nbytes = 0;
2431
2432 out:
2433         kfree(table);
2434         return ret;
2435 }
2436
2437 /**
2438  * spi_nor_parse_sfdp() - parse the Serial Flash Discoverable Parameters.
2439  * @nor:                pointer to a 'struct spi_nor'
2440  * @params:             pointer to the 'struct spi_nor_flash_parameter' to be
2441  *                      filled
2442  *
2443  * The Serial Flash Discoverable Parameters are described by the JEDEC JESD216
2444  * specification. This is a standard which tends to supported by almost all
2445  * (Q)SPI memory manufacturers. Those hard-coded tables allow us to learn at
2446  * runtime the main parameters needed to perform basic SPI flash operations such
2447  * as Fast Read, Page Program or Sector Erase commands.
2448  *
2449  * Return: 0 on success, -errno otherwise.
2450  */
2451 static int spi_nor_parse_sfdp(struct spi_nor *nor,
2452                               struct spi_nor_flash_parameter *params)
2453 {
2454         const struct sfdp_parameter_header *param_header, *bfpt_header;
2455         struct sfdp_parameter_header *param_headers = NULL;
2456         struct sfdp_header header;
2457         size_t psize;
2458         int i, err;
2459
2460         /* Get the SFDP header. */
2461         err = spi_nor_read_sfdp(nor, 0, sizeof(header), &header);
2462         if (err < 0)
2463                 return err;
2464
2465         /* Check the SFDP header version. */
2466         if (le32_to_cpu(header.signature) != SFDP_SIGNATURE ||
2467             header.major != SFDP_JESD216_MAJOR)
2468                 return -EINVAL;
2469
2470         /*
2471          * Verify that the first and only mandatory parameter header is a
2472          * Basic Flash Parameter Table header as specified in JESD216.
2473          */
2474         bfpt_header = &header.bfpt_header;
2475         if (SFDP_PARAM_HEADER_ID(bfpt_header) != SFDP_BFPT_ID ||
2476             bfpt_header->major != SFDP_JESD216_MAJOR)
2477                 return -EINVAL;
2478
2479         /*
2480          * Allocate memory then read all parameter headers with a single
2481          * Read SFDP command. These parameter headers will actually be parsed
2482          * twice: a first time to get the latest revision of the basic flash
2483          * parameter table, then a second time to handle the supported optional
2484          * tables.
2485          * Hence we read the parameter headers once for all to reduce the
2486          * processing time. Also we use kmalloc() instead of devm_kmalloc()
2487          * because we don't need to keep these parameter headers: the allocated
2488          * memory is always released with kfree() before exiting this function.
2489          */
2490         if (header.nph) {
2491                 psize = header.nph * sizeof(*param_headers);
2492
2493                 param_headers = kmalloc(psize, GFP_KERNEL);
2494                 if (!param_headers)
2495                         return -ENOMEM;
2496
2497                 err = spi_nor_read_sfdp(nor, sizeof(header),
2498                                         psize, param_headers);
2499                 if (err < 0) {
2500                         dev_err(nor->dev,
2501                                 "failed to read SFDP parameter headers\n");
2502                         goto exit;
2503                 }
2504         }
2505
2506         /*
2507          * Check other parameter headers to get the latest revision of
2508          * the basic flash parameter table.
2509          */
2510         for (i = 0; i < header.nph; i++) {
2511                 param_header = &param_headers[i];
2512
2513                 if (SFDP_PARAM_HEADER_ID(param_header) == SFDP_BFPT_ID &&
2514                     param_header->major == SFDP_JESD216_MAJOR &&
2515                     (param_header->minor > bfpt_header->minor ||
2516                      (param_header->minor == bfpt_header->minor &&
2517                       param_header->length > bfpt_header->length)))
2518                         bfpt_header = param_header;
2519         }
2520
2521         err = spi_nor_parse_bfpt(nor, bfpt_header, params);
2522         if (err)
2523                 goto exit;
2524
2525         /* Parse other parameter headers. */
2526         for (i = 0; i < header.nph; i++) {
2527                 param_header = &param_headers[i];
2528
2529                 switch (SFDP_PARAM_HEADER_ID(param_header)) {
2530                 case SFDP_SECTOR_MAP_ID:
2531                         dev_info(nor->dev,
2532                                  "non-uniform erase sector maps are not supported yet.\n");
2533                         break;
2534
2535                 case SFDP_SST_ID:
2536                         err = spi_nor_parse_microchip_sfdp(nor, param_header);
2537                         break;
2538
2539                 case SFDP_PROFILE1_ID:
2540                         err = spi_nor_parse_profile1(nor, param_header, params);
2541                         break;
2542
2543                 default:
2544                         break;
2545                 }
2546
2547                 if (err) {
2548                         dev_warn(nor->dev,
2549                                  "Failed to parse optional parameter table: %04x\n",
2550                                  SFDP_PARAM_HEADER_ID(param_header));
2551                         /*
2552                          * Let's not drop all information we extracted so far
2553                          * if optional table parsers fail. In case of failing,
2554                          * each optional parser is responsible to roll back to
2555                          * the previously known spi_nor data.
2556                          */
2557                         err = 0;
2558                 }
2559         }
2560
2561 exit:
2562         kfree(param_headers);
2563         return err;
2564 }
2565 #else
2566 static int spi_nor_parse_sfdp(struct spi_nor *nor,
2567                               struct spi_nor_flash_parameter *params)
2568 {
2569         return -EINVAL;
2570 }
2571 #endif /* SPI_FLASH_SFDP_SUPPORT */
2572
2573 /**
2574  * spi_nor_post_sfdp_fixups() - Updates the flash's parameters and settings
2575  * after SFDP has been parsed (is also called for SPI NORs that do not
2576  * support RDSFDP).
2577  * @nor:        pointer to a 'struct spi_nor'
2578  *
2579  * Typically used to tweak various parameters that could not be extracted by
2580  * other means (i.e. when information provided by the SFDP/flash_info tables
2581  * are incomplete or wrong).
2582  */
2583 static void spi_nor_post_sfdp_fixups(struct spi_nor *nor,
2584                                      struct spi_nor_flash_parameter *params)
2585 {
2586         if (nor->fixups && nor->fixups->post_sfdp)
2587                 nor->fixups->post_sfdp(nor, params);
2588 }
2589
2590 static void spi_nor_default_init_fixups(struct spi_nor *nor)
2591 {
2592         if (nor->fixups && nor->fixups->default_init)
2593                 nor->fixups->default_init(nor);
2594 }
2595
2596 static int spi_nor_init_params(struct spi_nor *nor,
2597                                const struct flash_info *info,
2598                                struct spi_nor_flash_parameter *params)
2599 {
2600         /* Set legacy flash parameters as default. */
2601         memset(params, 0, sizeof(*params));
2602
2603         /* Set SPI NOR sizes. */
2604         params->size = info->sector_size * info->n_sectors;
2605         params->page_size = info->page_size;
2606
2607         if (!(info->flags & SPI_NOR_NO_FR)) {
2608                 /* Default to Fast Read for DT and non-DT platform devices. */
2609                 params->hwcaps.mask |= SNOR_HWCAPS_READ_FAST;
2610
2611                 /* Mask out Fast Read if not requested at DT instantiation. */
2612 #if CONFIG_IS_ENABLED(DM_SPI)
2613                 if (!ofnode_read_bool(dev_ofnode(nor->spi->dev),
2614                                       "m25p,fast-read"))
2615                         params->hwcaps.mask &= ~SNOR_HWCAPS_READ_FAST;
2616 #endif
2617         }
2618
2619         /* (Fast) Read settings. */
2620         params->hwcaps.mask |= SNOR_HWCAPS_READ;
2621         spi_nor_set_read_settings(&params->reads[SNOR_CMD_READ],
2622                                   0, 0, SPINOR_OP_READ,
2623                                   SNOR_PROTO_1_1_1);
2624
2625         if (params->hwcaps.mask & SNOR_HWCAPS_READ_FAST)
2626                 spi_nor_set_read_settings(&params->reads[SNOR_CMD_READ_FAST],
2627                                           0, 8, SPINOR_OP_READ_FAST,
2628                                           SNOR_PROTO_1_1_1);
2629
2630         if (info->flags & SPI_NOR_DUAL_READ) {
2631                 params->hwcaps.mask |= SNOR_HWCAPS_READ_1_1_2;
2632                 spi_nor_set_read_settings(&params->reads[SNOR_CMD_READ_1_1_2],
2633                                           0, 8, SPINOR_OP_READ_1_1_2,
2634                                           SNOR_PROTO_1_1_2);
2635         }
2636
2637         if (info->flags & SPI_NOR_QUAD_READ) {
2638                 params->hwcaps.mask |= SNOR_HWCAPS_READ_1_1_4;
2639                 spi_nor_set_read_settings(&params->reads[SNOR_CMD_READ_1_1_4],
2640                                           0, 8, SPINOR_OP_READ_1_1_4,
2641                                           SNOR_PROTO_1_1_4);
2642         }
2643
2644         if (info->flags & SPI_NOR_OCTAL_READ) {
2645                 params->hwcaps.mask |= SNOR_HWCAPS_READ_1_1_8;
2646                 spi_nor_set_read_settings(&params->reads[SNOR_CMD_READ_1_1_8],
2647                                           0, 8, SPINOR_OP_READ_1_1_8,
2648                                           SNOR_PROTO_1_1_8);
2649         }
2650
2651         if (info->flags & SPI_NOR_OCTAL_DTR_READ) {
2652                 params->hwcaps.mask |= SNOR_HWCAPS_READ_8_8_8_DTR;
2653                 spi_nor_set_read_settings(&params->reads[SNOR_CMD_READ_8_8_8_DTR],
2654                                           0, 20, SPINOR_OP_READ_FAST,
2655                                           SNOR_PROTO_8_8_8_DTR);
2656         }
2657
2658         /* Page Program settings. */
2659         params->hwcaps.mask |= SNOR_HWCAPS_PP;
2660         spi_nor_set_pp_settings(&params->page_programs[SNOR_CMD_PP],
2661                                 SPINOR_OP_PP, SNOR_PROTO_1_1_1);
2662
2663         /*
2664          * Since xSPI Page Program opcode is backward compatible with
2665          * Legacy SPI, use Legacy SPI opcode there as well.
2666          */
2667         spi_nor_set_pp_settings(&params->page_programs[SNOR_CMD_PP_8_8_8_DTR],
2668                                 SPINOR_OP_PP, SNOR_PROTO_8_8_8_DTR);
2669
2670         if (info->flags & SPI_NOR_QUAD_READ) {
2671                 params->hwcaps.mask |= SNOR_HWCAPS_PP_1_1_4;
2672                 spi_nor_set_pp_settings(&params->page_programs[SNOR_CMD_PP_1_1_4],
2673                                         SPINOR_OP_PP_1_1_4, SNOR_PROTO_1_1_4);
2674         }
2675
2676         /* Select the procedure to set the Quad Enable bit. */
2677         if (params->hwcaps.mask & (SNOR_HWCAPS_READ_QUAD |
2678                                    SNOR_HWCAPS_PP_QUAD)) {
2679                 switch (JEDEC_MFR(info)) {
2680 #if defined(CONFIG_SPI_FLASH_MACRONIX) || defined(CONFIG_SPI_FLASH_ISSI)
2681                 case SNOR_MFR_MACRONIX:
2682                 case SNOR_MFR_ISSI:
2683                         params->quad_enable = macronix_quad_enable;
2684                         break;
2685 #endif
2686                 case SNOR_MFR_ST:
2687                 case SNOR_MFR_MICRON:
2688                         break;
2689
2690                 default:
2691 #if defined(CONFIG_SPI_FLASH_SPANSION) || defined(CONFIG_SPI_FLASH_WINBOND)
2692                         /* Kept only for backward compatibility purpose. */
2693                         params->quad_enable = spansion_read_cr_quad_enable;
2694 #endif
2695                         break;
2696                 }
2697         }
2698
2699         spi_nor_default_init_fixups(nor);
2700
2701         /* Override the parameters with data read from SFDP tables. */
2702         nor->addr_width = 0;
2703         nor->mtd.erasesize = 0;
2704         if ((info->flags & (SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ |
2705              SPI_NOR_OCTAL_DTR_READ)) &&
2706             !(info->flags & SPI_NOR_SKIP_SFDP)) {
2707                 struct spi_nor_flash_parameter sfdp_params;
2708
2709                 memcpy(&sfdp_params, params, sizeof(sfdp_params));
2710                 if (spi_nor_parse_sfdp(nor, &sfdp_params)) {
2711                         nor->addr_width = 0;
2712                         nor->mtd.erasesize = 0;
2713                 } else {
2714                         memcpy(params, &sfdp_params, sizeof(*params));
2715                 }
2716         }
2717
2718         spi_nor_post_sfdp_fixups(nor, params);
2719
2720         return 0;
2721 }
2722
2723 static int spi_nor_hwcaps2cmd(u32 hwcaps, const int table[][2], size_t size)
2724 {
2725         size_t i;
2726
2727         for (i = 0; i < size; i++)
2728                 if (table[i][0] == (int)hwcaps)
2729                         return table[i][1];
2730
2731         return -EINVAL;
2732 }
2733
2734 static int spi_nor_hwcaps_read2cmd(u32 hwcaps)
2735 {
2736         static const int hwcaps_read2cmd[][2] = {
2737                 { SNOR_HWCAPS_READ,             SNOR_CMD_READ },
2738                 { SNOR_HWCAPS_READ_FAST,        SNOR_CMD_READ_FAST },
2739                 { SNOR_HWCAPS_READ_1_1_1_DTR,   SNOR_CMD_READ_1_1_1_DTR },
2740                 { SNOR_HWCAPS_READ_1_1_2,       SNOR_CMD_READ_1_1_2 },
2741                 { SNOR_HWCAPS_READ_1_2_2,       SNOR_CMD_READ_1_2_2 },
2742                 { SNOR_HWCAPS_READ_2_2_2,       SNOR_CMD_READ_2_2_2 },
2743                 { SNOR_HWCAPS_READ_1_2_2_DTR,   SNOR_CMD_READ_1_2_2_DTR },
2744                 { SNOR_HWCAPS_READ_1_1_4,       SNOR_CMD_READ_1_1_4 },
2745                 { SNOR_HWCAPS_READ_1_4_4,       SNOR_CMD_READ_1_4_4 },
2746                 { SNOR_HWCAPS_READ_4_4_4,       SNOR_CMD_READ_4_4_4 },
2747                 { SNOR_HWCAPS_READ_1_4_4_DTR,   SNOR_CMD_READ_1_4_4_DTR },
2748                 { SNOR_HWCAPS_READ_1_1_8,       SNOR_CMD_READ_1_1_8 },
2749                 { SNOR_HWCAPS_READ_1_8_8,       SNOR_CMD_READ_1_8_8 },
2750                 { SNOR_HWCAPS_READ_8_8_8,       SNOR_CMD_READ_8_8_8 },
2751                 { SNOR_HWCAPS_READ_1_8_8_DTR,   SNOR_CMD_READ_1_8_8_DTR },
2752                 { SNOR_HWCAPS_READ_8_8_8_DTR,   SNOR_CMD_READ_8_8_8_DTR },
2753         };
2754
2755         return spi_nor_hwcaps2cmd(hwcaps, hwcaps_read2cmd,
2756                                   ARRAY_SIZE(hwcaps_read2cmd));
2757 }
2758
2759 static int spi_nor_hwcaps_pp2cmd(u32 hwcaps)
2760 {
2761         static const int hwcaps_pp2cmd[][2] = {
2762                 { SNOR_HWCAPS_PP,               SNOR_CMD_PP },
2763                 { SNOR_HWCAPS_PP_1_1_4,         SNOR_CMD_PP_1_1_4 },
2764                 { SNOR_HWCAPS_PP_1_4_4,         SNOR_CMD_PP_1_4_4 },
2765                 { SNOR_HWCAPS_PP_4_4_4,         SNOR_CMD_PP_4_4_4 },
2766                 { SNOR_HWCAPS_PP_1_1_8,         SNOR_CMD_PP_1_1_8 },
2767                 { SNOR_HWCAPS_PP_1_8_8,         SNOR_CMD_PP_1_8_8 },
2768                 { SNOR_HWCAPS_PP_8_8_8,         SNOR_CMD_PP_8_8_8 },
2769                 { SNOR_HWCAPS_PP_8_8_8_DTR,     SNOR_CMD_PP_8_8_8_DTR },
2770         };
2771
2772         return spi_nor_hwcaps2cmd(hwcaps, hwcaps_pp2cmd,
2773                                   ARRAY_SIZE(hwcaps_pp2cmd));
2774 }
2775
2776 #ifdef CONFIG_SPI_FLASH_SMART_HWCAPS
2777 /**
2778  * spi_nor_check_op - check if the operation is supported by controller
2779  * @nor:        pointer to a 'struct spi_nor'
2780  * @op:         pointer to op template to be checked
2781  *
2782  * Returns 0 if operation is supported, -ENOTSUPP otherwise.
2783  */
2784 static int spi_nor_check_op(struct spi_nor *nor,
2785                             struct spi_mem_op *op)
2786 {
2787         /*
2788          * First test with 4 address bytes. The opcode itself might be a 3B
2789          * addressing opcode but we don't care, because SPI controller
2790          * implementation should not check the opcode, but just the sequence.
2791          */
2792         op->addr.nbytes = 4;
2793         if (!spi_mem_supports_op(nor->spi, op)) {
2794                 if (nor->mtd.size > SZ_16M)
2795                         return -ENOTSUPP;
2796
2797                 /* If flash size <= 16MB, 3 address bytes are sufficient */
2798                 op->addr.nbytes = 3;
2799                 if (!spi_mem_supports_op(nor->spi, op))
2800                         return -ENOTSUPP;
2801         }
2802
2803         return 0;
2804 }
2805
2806 /**
2807  * spi_nor_check_readop - check if the read op is supported by controller
2808  * @nor:         pointer to a 'struct spi_nor'
2809  * @read:        pointer to op template to be checked
2810  *
2811  * Returns 0 if operation is supported, -ENOTSUPP otherwise.
2812  */
2813 static int spi_nor_check_readop(struct spi_nor *nor,
2814                                 const struct spi_nor_read_command *read)
2815 {
2816         struct spi_mem_op op = SPI_MEM_OP(SPI_MEM_OP_CMD(read->opcode, 0),
2817                                           SPI_MEM_OP_ADDR(3, 0, 0),
2818                                           SPI_MEM_OP_DUMMY(1, 0),
2819                                           SPI_MEM_OP_DATA_IN(2, NULL, 0));
2820
2821         spi_nor_setup_op(nor, &op, read->proto);
2822
2823         op.dummy.nbytes = (read->num_mode_clocks + read->num_wait_states) *
2824                           op.dummy.buswidth / 8;
2825         if (spi_nor_protocol_is_dtr(nor->read_proto))
2826                 op.dummy.nbytes *= 2;
2827
2828         return spi_nor_check_op(nor, &op);
2829 }
2830
2831 /**
2832  * spi_nor_check_pp - check if the page program op is supported by controller
2833  * @nor:         pointer to a 'struct spi_nor'
2834  * @pp:          pointer to op template to be checked
2835  *
2836  * Returns 0 if operation is supported, -ENOTSUPP otherwise.
2837  */
2838 static int spi_nor_check_pp(struct spi_nor *nor,
2839                             const struct spi_nor_pp_command *pp)
2840 {
2841         struct spi_mem_op op = SPI_MEM_OP(SPI_MEM_OP_CMD(pp->opcode, 0),
2842                                           SPI_MEM_OP_ADDR(3, 0, 0),
2843                                           SPI_MEM_OP_NO_DUMMY,
2844                                           SPI_MEM_OP_DATA_OUT(2, NULL, 0));
2845
2846         spi_nor_setup_op(nor, &op, pp->proto);
2847
2848         return spi_nor_check_op(nor, &op);
2849 }
2850
2851 /**
2852  * spi_nor_adjust_hwcaps - Find optimal Read/Write protocol based on SPI
2853  *                         controller capabilities
2854  * @nor:        pointer to a 'struct spi_nor'
2855  * @params:     pointer to the 'struct spi_nor_flash_parameter'
2856  *              representing SPI NOR flash capabilities
2857  * @hwcaps:     pointer to resulting capabilities after adjusting
2858  *              according to controller and flash's capability
2859  *
2860  * Discard caps based on what the SPI controller actually supports (using
2861  * spi_mem_supports_op()).
2862  */
2863 static void
2864 spi_nor_adjust_hwcaps(struct spi_nor *nor,
2865                       const struct spi_nor_flash_parameter *params,
2866                       u32 *hwcaps)
2867 {
2868         unsigned int cap;
2869
2870         /*
2871          * Start by assuming the controller supports every capability.
2872          * We will mask them after checking what's really supported
2873          * using spi_mem_supports_op().
2874          */
2875         *hwcaps = SNOR_HWCAPS_ALL & params->hwcaps.mask;
2876
2877         /* X-X-X modes are not supported yet, mask them all. */
2878         *hwcaps &= ~SNOR_HWCAPS_X_X_X;
2879
2880         /*
2881          * If the reset line is broken, we do not want to enter a stateful
2882          * mode.
2883          */
2884         if (nor->flags & SNOR_F_BROKEN_RESET)
2885                 *hwcaps &= ~(SNOR_HWCAPS_X_X_X | SNOR_HWCAPS_X_X_X_DTR);
2886
2887         for (cap = 0; cap < sizeof(*hwcaps) * BITS_PER_BYTE; cap++) {
2888                 int rdidx, ppidx;
2889
2890                 if (!(*hwcaps & BIT(cap)))
2891                         continue;
2892
2893                 rdidx = spi_nor_hwcaps_read2cmd(BIT(cap));
2894                 if (rdidx >= 0 &&
2895                     spi_nor_check_readop(nor, &params->reads[rdidx]))
2896                         *hwcaps &= ~BIT(cap);
2897
2898                 ppidx = spi_nor_hwcaps_pp2cmd(BIT(cap));
2899                 if (ppidx < 0)
2900                         continue;
2901
2902                 if (spi_nor_check_pp(nor, &params->page_programs[ppidx]))
2903                         *hwcaps &= ~BIT(cap);
2904         }
2905 }
2906 #else
2907 /**
2908  * spi_nor_adjust_hwcaps - Find optimal Read/Write protocol based on SPI
2909  *                         controller capabilities
2910  * @nor:        pointer to a 'struct spi_nor'
2911  * @params:     pointer to the 'struct spi_nor_flash_parameter'
2912  *              representing SPI NOR flash capabilities
2913  * @hwcaps:     pointer to resulting capabilities after adjusting
2914  *              according to controller and flash's capability
2915  *
2916  * Select caps based on what the SPI controller and SPI flash both support.
2917  */
2918 static void
2919 spi_nor_adjust_hwcaps(struct spi_nor *nor,
2920                       const struct spi_nor_flash_parameter *params,
2921                       u32 *hwcaps)
2922 {
2923         struct spi_slave *spi = nor->spi;
2924         u32 ignored_mask = (SNOR_HWCAPS_READ_2_2_2 |
2925                             SNOR_HWCAPS_READ_4_4_4 |
2926                             SNOR_HWCAPS_READ_8_8_8 |
2927                             SNOR_HWCAPS_PP_4_4_4   |
2928                             SNOR_HWCAPS_PP_8_8_8);
2929         u32 spi_hwcaps = (SNOR_HWCAPS_READ | SNOR_HWCAPS_READ_FAST |
2930                           SNOR_HWCAPS_PP);
2931
2932         /* Get the hardware capabilities the SPI controller supports. */
2933         if (spi->mode & SPI_RX_OCTAL) {
2934                 spi_hwcaps |= SNOR_HWCAPS_READ_1_1_8;
2935
2936                 if (spi->mode & SPI_TX_OCTAL)
2937                         spi_hwcaps |= (SNOR_HWCAPS_READ_1_8_8 |
2938                                         SNOR_HWCAPS_PP_1_1_8 |
2939                                         SNOR_HWCAPS_PP_1_8_8);
2940         } else if (spi->mode & SPI_RX_QUAD) {
2941                 spi_hwcaps |= SNOR_HWCAPS_READ_1_1_4;
2942
2943                 if (spi->mode & SPI_TX_QUAD)
2944                         spi_hwcaps |= (SNOR_HWCAPS_READ_1_4_4 |
2945                                         SNOR_HWCAPS_PP_1_1_4 |
2946                                         SNOR_HWCAPS_PP_1_4_4);
2947         } else if (spi->mode & SPI_RX_DUAL) {
2948                 spi_hwcaps |= SNOR_HWCAPS_READ_1_1_2;
2949
2950                 if (spi->mode & SPI_TX_DUAL)
2951                         spi_hwcaps |= SNOR_HWCAPS_READ_1_2_2;
2952         }
2953
2954         /*
2955          * Keep only the hardware capabilities supported by both the SPI
2956          * controller and the SPI flash memory.
2957          */
2958         *hwcaps = spi_hwcaps & params->hwcaps.mask;
2959         if (*hwcaps & ignored_mask) {
2960                 dev_dbg(nor->dev,
2961                         "SPI n-n-n protocols are not supported yet.\n");
2962                 *hwcaps &= ~ignored_mask;
2963         }
2964 }
2965 #endif /* CONFIG_SPI_FLASH_SMART_HWCAPS */
2966
2967 static int spi_nor_select_read(struct spi_nor *nor,
2968                                const struct spi_nor_flash_parameter *params,
2969                                u32 shared_hwcaps)
2970 {
2971         int cmd, best_match = fls(shared_hwcaps & SNOR_HWCAPS_READ_MASK) - 1;
2972         const struct spi_nor_read_command *read;
2973
2974         if (best_match < 0)
2975                 return -EINVAL;
2976
2977         cmd = spi_nor_hwcaps_read2cmd(BIT(best_match));
2978         if (cmd < 0)
2979                 return -EINVAL;
2980
2981         read = &params->reads[cmd];
2982         nor->read_opcode = read->opcode;
2983         nor->read_proto = read->proto;
2984
2985         /*
2986          * In the spi-nor framework, we don't need to make the difference
2987          * between mode clock cycles and wait state clock cycles.
2988          * Indeed, the value of the mode clock cycles is used by a QSPI
2989          * flash memory to know whether it should enter or leave its 0-4-4
2990          * (Continuous Read / XIP) mode.
2991          * eXecution In Place is out of the scope of the mtd sub-system.
2992          * Hence we choose to merge both mode and wait state clock cycles
2993          * into the so called dummy clock cycles.
2994          */
2995         nor->read_dummy = read->num_mode_clocks + read->num_wait_states;
2996         return 0;
2997 }
2998
2999 static int spi_nor_select_pp(struct spi_nor *nor,
3000                              const struct spi_nor_flash_parameter *params,
3001                              u32 shared_hwcaps)
3002 {
3003         int cmd, best_match = fls(shared_hwcaps & SNOR_HWCAPS_PP_MASK) - 1;
3004         const struct spi_nor_pp_command *pp;
3005
3006         if (best_match < 0)
3007                 return -EINVAL;
3008
3009         cmd = spi_nor_hwcaps_pp2cmd(BIT(best_match));
3010         if (cmd < 0)
3011                 return -EINVAL;
3012
3013         pp = &params->page_programs[cmd];
3014         nor->program_opcode = pp->opcode;
3015         nor->write_proto = pp->proto;
3016         return 0;
3017 }
3018
3019 static int spi_nor_select_erase(struct spi_nor *nor,
3020                                 const struct flash_info *info)
3021 {
3022         struct mtd_info *mtd = &nor->mtd;
3023
3024         /* Do nothing if already configured from SFDP. */
3025         if (mtd->erasesize)
3026                 return 0;
3027
3028 #ifdef CONFIG_SPI_FLASH_USE_4K_SECTORS
3029         /* prefer "small sector" erase if possible */
3030         if (info->flags & SECT_4K) {
3031                 nor->erase_opcode = SPINOR_OP_BE_4K;
3032                 mtd->erasesize = 4096;
3033         } else if (info->flags & SECT_4K_PMC) {
3034                 nor->erase_opcode = SPINOR_OP_BE_4K_PMC;
3035                 mtd->erasesize = 4096;
3036         } else
3037 #endif
3038         {
3039                 nor->erase_opcode = SPINOR_OP_SE;
3040                 mtd->erasesize = info->sector_size;
3041         }
3042         return 0;
3043 }
3044
3045 static int spi_nor_default_setup(struct spi_nor *nor,
3046                                  const struct flash_info *info,
3047                                  const struct spi_nor_flash_parameter *params)
3048 {
3049         u32 shared_mask;
3050         bool enable_quad_io;
3051         int err;
3052
3053         spi_nor_adjust_hwcaps(nor, params, &shared_mask);
3054
3055         /* Select the (Fast) Read command. */
3056         err = spi_nor_select_read(nor, params, shared_mask);
3057         if (err) {
3058                 dev_dbg(nor->dev,
3059                         "can't select read settings supported by both the SPI controller and memory.\n");
3060                 return err;
3061         }
3062
3063         /* Select the Page Program command. */
3064         err = spi_nor_select_pp(nor, params, shared_mask);
3065         if (err) {
3066                 dev_dbg(nor->dev,
3067                         "can't select write settings supported by both the SPI controller and memory.\n");
3068                 return err;
3069         }
3070
3071         /* Select the Sector Erase command. */
3072         err = spi_nor_select_erase(nor, info);
3073         if (err) {
3074                 dev_dbg(nor->dev,
3075                         "can't select erase settings supported by both the SPI controller and memory.\n");
3076                 return err;
3077         }
3078
3079         /* Enable Quad I/O if needed. */
3080         enable_quad_io = (spi_nor_get_protocol_width(nor->read_proto) == 4 ||
3081                           spi_nor_get_protocol_width(nor->write_proto) == 4);
3082         if (enable_quad_io && params->quad_enable)
3083                 nor->quad_enable = params->quad_enable;
3084         else
3085                 nor->quad_enable = NULL;
3086
3087         return 0;
3088 }
3089
3090 static int spi_nor_setup(struct spi_nor *nor, const struct flash_info *info,
3091                          const struct spi_nor_flash_parameter *params)
3092 {
3093         if (!nor->setup)
3094                 return 0;
3095
3096         return nor->setup(nor, info, params);
3097 }
3098
3099 #ifdef CONFIG_SPI_FLASH_SPANSION
3100 static int s25hx_t_mdp_ready(struct spi_nor *nor)
3101 {
3102         u32 addr;
3103         int ret;
3104
3105         for (addr = 0; addr < nor->mtd.size; addr += SZ_128M) {
3106                 ret = spansion_sr_ready(nor, addr, 0);
3107                 if (!ret)
3108                         return ret;
3109         }
3110
3111         return 1;
3112 }
3113
3114 static int s25hx_t_quad_enable(struct spi_nor *nor)
3115 {
3116         u32 addr;
3117         int ret;
3118
3119         for (addr = 0; addr < nor->mtd.size; addr += SZ_128M) {
3120                 ret = spansion_quad_enable_volatile(nor, addr, 0);
3121                 if (ret)
3122                         return ret;
3123         }
3124
3125         return 0;
3126 }
3127
3128 static int s25hx_t_erase_non_uniform(struct spi_nor *nor, loff_t addr)
3129 {
3130         /* Support 32 x 4KB sectors at bottom */
3131         return spansion_erase_non_uniform(nor, addr, SPINOR_OP_BE_4K_4B, 0,
3132                                           SZ_128K);
3133 }
3134
3135 static int s25hx_t_setup(struct spi_nor *nor, const struct flash_info *info,
3136                          const struct spi_nor_flash_parameter *params)
3137 {
3138         int ret;
3139         u8 cfr3v;
3140
3141 #ifdef CONFIG_SPI_FLASH_BAR
3142         return -ENOTSUPP; /* Bank Address Register is not supported */
3143 #endif
3144         /*
3145          * Read CFR3V to check if uniform sector is selected. If not, assign an
3146          * erase hook that supports non-uniform erase.
3147          */
3148         ret = spansion_read_any_reg(nor, SPINOR_REG_ADDR_CFR3V, 0, &cfr3v);
3149         if (ret)
3150                 return ret;
3151         if (!(cfr3v & CFR3V_UNHYSA))
3152                 nor->erase = s25hx_t_erase_non_uniform;
3153
3154         /*
3155          * For the multi-die package parts, the ready() hook is needed to check
3156          * all dies' status via read any register.
3157          */
3158         if (nor->mtd.size > SZ_128M)
3159                 nor->ready = s25hx_t_mdp_ready;
3160
3161         return spi_nor_default_setup(nor, info, params);
3162 }
3163
3164 static void s25hx_t_default_init(struct spi_nor *nor)
3165 {
3166         nor->setup = s25hx_t_setup;
3167 }
3168
3169 static int s25hx_t_post_bfpt_fixup(struct spi_nor *nor,
3170                                    const struct sfdp_parameter_header *header,
3171                                    const struct sfdp_bfpt *bfpt,
3172                                    struct spi_nor_flash_parameter *params)
3173 {
3174         int ret;
3175         u32 addr;
3176         u8 cfr3v;
3177
3178         /* erase size in case it is set to 4K from BFPT */
3179         nor->erase_opcode = SPINOR_OP_SE_4B;
3180         nor->mtd.erasesize = nor->info->sector_size;
3181
3182         ret = set_4byte(nor, nor->info, 1);
3183         if (ret)
3184                 return ret;
3185         nor->addr_width = 4;
3186
3187         /*
3188          * The page_size is set to 512B from BFPT, but it actually depends on
3189          * the configuration register. Look up the CFR3V and determine the
3190          * page_size. For multi-die package parts, use 512B only when the all
3191          * dies are configured to 512B buffer.
3192          */
3193         for (addr = 0; addr < params->size; addr += SZ_128M) {
3194                 ret = spansion_read_any_reg(nor, addr + SPINOR_REG_ADDR_CFR3V,
3195                                             0, &cfr3v);
3196                 if (ret)
3197                         return ret;
3198
3199                 if (!(cfr3v & CFR3V_PGMBUF)) {
3200                         params->page_size = 256;
3201                         return 0;
3202                 }
3203         }
3204         params->page_size = 512;
3205
3206         return 0;
3207 }
3208
3209 static void s25hx_t_post_sfdp_fixup(struct spi_nor *nor,
3210                                     struct spi_nor_flash_parameter *params)
3211 {
3212         /* READ_FAST_4B (0Ch) requires mode cycles*/
3213         params->reads[SNOR_CMD_READ_FAST].num_mode_clocks = 8;
3214         /* PP_1_1_4 is not supported */
3215         params->hwcaps.mask &= ~SNOR_HWCAPS_PP_1_1_4;
3216         /* Use volatile register to enable quad */
3217         params->quad_enable = s25hx_t_quad_enable;
3218 }
3219
3220 static struct spi_nor_fixups s25hx_t_fixups = {
3221         .default_init = s25hx_t_default_init,
3222         .post_bfpt = s25hx_t_post_bfpt_fixup,
3223         .post_sfdp = s25hx_t_post_sfdp_fixup,
3224 };
3225 #endif
3226
3227 #ifdef CONFIG_SPI_FLASH_S28HS512T
3228 /**
3229  * spi_nor_cypress_octal_dtr_enable() - Enable octal DTR on Cypress flashes.
3230  * @nor:                pointer to a 'struct spi_nor'
3231  *
3232  * This also sets the memory access latency cycles to 24 to allow the flash to
3233  * run at up to 200MHz.
3234  *
3235  * Return: 0 on success, -errno otherwise.
3236  */
3237 static int spi_nor_cypress_octal_dtr_enable(struct spi_nor *nor)
3238 {
3239         struct spi_mem_op op;
3240         u8 buf;
3241         u8 addr_width = 3;
3242         int ret;
3243
3244         /* Use 24 dummy cycles for memory array reads. */
3245         ret = write_enable(nor);
3246         if (ret)
3247                 return ret;
3248
3249         buf = SPINOR_REG_CYPRESS_CFR2V_MEMLAT_11_24;
3250         op = (struct spi_mem_op)SPI_MEM_OP(SPI_MEM_OP_CMD(SPINOR_OP_WR_ANY_REG, 1),
3251                         SPI_MEM_OP_ADDR(addr_width, SPINOR_REG_CYPRESS_CFR2V, 1),
3252                         SPI_MEM_OP_NO_DUMMY,
3253                         SPI_MEM_OP_DATA_OUT(1, &buf, 1));
3254         ret = spi_mem_exec_op(nor->spi, &op);
3255         if (ret) {
3256                 dev_warn(nor->dev,
3257                          "failed to set default memory latency value: %d\n",
3258                          ret);
3259                 return ret;
3260         }
3261         ret = spi_nor_wait_till_ready(nor);
3262         if (ret)
3263                 return ret;
3264
3265         nor->read_dummy = 24;
3266
3267         /* Set the octal and DTR enable bits. */
3268         ret = write_enable(nor);
3269         if (ret)
3270                 return ret;
3271
3272         buf = SPINOR_REG_CYPRESS_CFR5V_OCT_DTR_EN;
3273         op = (struct spi_mem_op)SPI_MEM_OP(SPI_MEM_OP_CMD(SPINOR_OP_WR_ANY_REG, 1),
3274                         SPI_MEM_OP_ADDR(addr_width, SPINOR_REG_CYPRESS_CFR5V, 1),
3275                         SPI_MEM_OP_NO_DUMMY,
3276                         SPI_MEM_OP_DATA_OUT(1, &buf, 1));
3277         ret = spi_mem_exec_op(nor->spi, &op);
3278         if (ret) {
3279                 dev_warn(nor->dev, "Failed to enable octal DTR mode\n");
3280                 return ret;
3281         }
3282
3283         return 0;
3284 }
3285
3286 static int s28hs512t_erase_non_uniform(struct spi_nor *nor, loff_t addr)
3287 {
3288         /* Factory default configuration: 32 x 4 KiB sectors at bottom. */
3289         return spansion_erase_non_uniform(nor, addr, SPINOR_OP_S28_SE_4K,
3290                                           0, SZ_128K);
3291 }
3292
3293 static int s28hs512t_setup(struct spi_nor *nor, const struct flash_info *info,
3294                            const struct spi_nor_flash_parameter *params)
3295 {
3296         struct spi_mem_op op;
3297         u8 buf;
3298         u8 addr_width = 3;
3299         int ret;
3300
3301         ret = spi_nor_wait_till_ready(nor);
3302         if (ret)
3303                 return ret;
3304
3305         /*
3306          * Check CFR3V to check if non-uniform sector mode is selected. If it
3307          * is, set the erase hook to the non-uniform erase procedure.
3308          */
3309         op = (struct spi_mem_op)
3310                 SPI_MEM_OP(SPI_MEM_OP_CMD(SPINOR_OP_RD_ANY_REG, 1),
3311                            SPI_MEM_OP_ADDR(addr_width,
3312                                            SPINOR_REG_CYPRESS_CFR3V, 1),
3313                            SPI_MEM_OP_NO_DUMMY,
3314                            SPI_MEM_OP_DATA_IN(1, &buf, 1));
3315
3316         ret = spi_mem_exec_op(nor->spi, &op);
3317         if (ret)
3318                 return ret;
3319
3320         if (!(buf & SPINOR_REG_CYPRESS_CFR3V_UNISECT))
3321                 nor->erase = s28hs512t_erase_non_uniform;
3322
3323         return spi_nor_default_setup(nor, info, params);
3324 }
3325
3326 static void s28hs512t_default_init(struct spi_nor *nor)
3327 {
3328         nor->octal_dtr_enable = spi_nor_cypress_octal_dtr_enable;
3329         nor->setup = s28hs512t_setup;
3330 }
3331
3332 static void s28hs512t_post_sfdp_fixup(struct spi_nor *nor,
3333                                       struct spi_nor_flash_parameter *params)
3334 {
3335         /*
3336          * On older versions of the flash the xSPI Profile 1.0 table has the
3337          * 8D-8D-8D Fast Read opcode as 0x00. But it actually should be 0xEE.
3338          */
3339         if (params->reads[SNOR_CMD_READ_8_8_8_DTR].opcode == 0)
3340                 params->reads[SNOR_CMD_READ_8_8_8_DTR].opcode =
3341                         SPINOR_OP_CYPRESS_RD_FAST;
3342
3343         params->hwcaps.mask |= SNOR_HWCAPS_PP_8_8_8_DTR;
3344
3345         /* This flash is also missing the 4-byte Page Program opcode bit. */
3346         spi_nor_set_pp_settings(&params->page_programs[SNOR_CMD_PP],
3347                                 SPINOR_OP_PP_4B, SNOR_PROTO_1_1_1);
3348         /*
3349          * Since xSPI Page Program opcode is backward compatible with
3350          * Legacy SPI, use Legacy SPI opcode there as well.
3351          */
3352         spi_nor_set_pp_settings(&params->page_programs[SNOR_CMD_PP_8_8_8_DTR],
3353                                 SPINOR_OP_PP_4B, SNOR_PROTO_8_8_8_DTR);
3354
3355         /*
3356          * The xSPI Profile 1.0 table advertises the number of additional
3357          * address bytes needed for Read Status Register command as 0 but the
3358          * actual value for that is 4.
3359          */
3360         params->rdsr_addr_nbytes = 4;
3361 }
3362
3363 static int s28hs512t_post_bfpt_fixup(struct spi_nor *nor,
3364                                      const struct sfdp_parameter_header *bfpt_header,
3365                                      const struct sfdp_bfpt *bfpt,
3366                                      struct spi_nor_flash_parameter *params)
3367 {
3368         struct spi_mem_op op;
3369         u8 buf;
3370         u8 addr_width = 3;
3371         int ret;
3372
3373         /*
3374          * The BFPT table advertises a 512B page size but the page size is
3375          * actually configurable (with the default being 256B). Read from
3376          * CFR3V[4] and set the correct size.
3377          */
3378         op = (struct spi_mem_op)
3379                 SPI_MEM_OP(SPI_MEM_OP_CMD(SPINOR_OP_RD_ANY_REG, 1),
3380                            SPI_MEM_OP_ADDR(addr_width, SPINOR_REG_CYPRESS_CFR3V, 1),
3381                            SPI_MEM_OP_NO_DUMMY,
3382                            SPI_MEM_OP_DATA_IN(1, &buf, 1));
3383         ret = spi_mem_exec_op(nor->spi, &op);
3384         if (ret)
3385                 return ret;
3386
3387         if (buf & SPINOR_REG_CYPRESS_CFR3V_PGSZ)
3388                 params->page_size = 512;
3389         else
3390                 params->page_size = 256;
3391
3392         /*
3393          * The BFPT advertises that it supports 4k erases, and the datasheet
3394          * says the same. But 4k erases did not work when testing. So, use 256k
3395          * erases for now.
3396          */
3397         nor->erase_opcode = SPINOR_OP_SE_4B;
3398         nor->mtd.erasesize = 0x40000;
3399
3400         return 0;
3401 }
3402
3403 static struct spi_nor_fixups s28hs512t_fixups = {
3404         .default_init = s28hs512t_default_init,
3405         .post_sfdp = s28hs512t_post_sfdp_fixup,
3406         .post_bfpt = s28hs512t_post_bfpt_fixup,
3407 };
3408 #endif /* CONFIG_SPI_FLASH_S28HS512T */
3409
3410 #ifdef CONFIG_SPI_FLASH_MT35XU
3411 static int spi_nor_micron_octal_dtr_enable(struct spi_nor *nor)
3412 {
3413         struct spi_mem_op op;
3414         u8 buf;
3415         u8 addr_width = 3;
3416         int ret;
3417
3418         /* Set dummy cycles for Fast Read to the default of 20. */
3419         ret = write_enable(nor);
3420         if (ret)
3421                 return ret;
3422
3423         buf = 20;
3424         op = (struct spi_mem_op)
3425                 SPI_MEM_OP(SPI_MEM_OP_CMD(SPINOR_OP_MT_WR_ANY_REG, 1),
3426                            SPI_MEM_OP_ADDR(addr_width, SPINOR_REG_MT_CFR1V, 1),
3427                            SPI_MEM_OP_NO_DUMMY,
3428                            SPI_MEM_OP_DATA_OUT(1, &buf, 1));
3429         ret = spi_mem_exec_op(nor->spi, &op);
3430         if (ret)
3431                 return ret;
3432
3433         ret = spi_nor_wait_till_ready(nor);
3434         if (ret)
3435                 return ret;
3436
3437         nor->read_dummy = 20;
3438
3439         ret = write_enable(nor);
3440         if (ret)
3441                 return ret;
3442
3443         buf = SPINOR_MT_OCT_DTR;
3444         op = (struct spi_mem_op)
3445                 SPI_MEM_OP(SPI_MEM_OP_CMD(SPINOR_OP_MT_WR_ANY_REG, 1),
3446                            SPI_MEM_OP_ADDR(addr_width, SPINOR_REG_MT_CFR0V, 1),
3447                            SPI_MEM_OP_NO_DUMMY,
3448                            SPI_MEM_OP_DATA_OUT(1, &buf, 1));
3449         ret = spi_mem_exec_op(nor->spi, &op);
3450         if (ret) {
3451                 dev_err(nor->dev, "Failed to enable octal DTR mode\n");
3452                 return ret;
3453         }
3454
3455         return 0;
3456 }
3457
3458 static void mt35xu512aba_default_init(struct spi_nor *nor)
3459 {
3460         nor->octal_dtr_enable = spi_nor_micron_octal_dtr_enable;
3461 }
3462
3463 static void mt35xu512aba_post_sfdp_fixup(struct spi_nor *nor,
3464                                          struct spi_nor_flash_parameter *params)
3465 {
3466         /* Set the Fast Read settings. */
3467         params->hwcaps.mask |= SNOR_HWCAPS_READ_8_8_8_DTR;
3468         spi_nor_set_read_settings(&params->reads[SNOR_CMD_READ_8_8_8_DTR],
3469                                   0, 20, SPINOR_OP_MT_DTR_RD,
3470                                   SNOR_PROTO_8_8_8_DTR);
3471
3472         params->hwcaps.mask |= SNOR_HWCAPS_PP_8_8_8_DTR;
3473
3474         nor->cmd_ext_type = SPI_NOR_EXT_REPEAT;
3475         params->rdsr_dummy = 8;
3476         params->rdsr_addr_nbytes = 0;
3477
3478         /*
3479          * The BFPT quad enable field is set to a reserved value so the quad
3480          * enable function is ignored by spi_nor_parse_bfpt(). Make sure we
3481          * disable it.
3482          */
3483         params->quad_enable = NULL;
3484 }
3485
3486 static struct spi_nor_fixups mt35xu512aba_fixups = {
3487         .default_init = mt35xu512aba_default_init,
3488         .post_sfdp = mt35xu512aba_post_sfdp_fixup,
3489 };
3490 #endif /* CONFIG_SPI_FLASH_MT35XU */
3491
3492 /** spi_nor_octal_dtr_enable() - enable Octal DTR I/O if needed
3493  * @nor:                 pointer to a 'struct spi_nor'
3494  *
3495  * Return: 0 on success, -errno otherwise.
3496  */
3497 static int spi_nor_octal_dtr_enable(struct spi_nor *nor)
3498 {
3499         int ret;
3500
3501         if (!nor->octal_dtr_enable)
3502                 return 0;
3503
3504         if (!(nor->read_proto == SNOR_PROTO_8_8_8_DTR &&
3505               nor->write_proto == SNOR_PROTO_8_8_8_DTR))
3506                 return 0;
3507
3508         ret = nor->octal_dtr_enable(nor);
3509         if (ret)
3510                 return ret;
3511
3512         nor->reg_proto = SNOR_PROTO_8_8_8_DTR;
3513
3514         return 0;
3515 }
3516
3517 static int spi_nor_init(struct spi_nor *nor)
3518 {
3519         int err;
3520
3521         err = spi_nor_octal_dtr_enable(nor);
3522         if (err) {
3523                 dev_dbg(nor->dev, "Octal DTR mode not supported\n");
3524                 return err;
3525         }
3526
3527         /*
3528          * Atmel, SST, Intel/Numonyx, and others serial NOR tend to power up
3529          * with the software protection bits set
3530          */
3531         if (IS_ENABLED(CONFIG_SPI_FLASH_UNLOCK_ALL) &&
3532             (JEDEC_MFR(nor->info) == SNOR_MFR_ATMEL ||
3533              JEDEC_MFR(nor->info) == SNOR_MFR_INTEL ||
3534              JEDEC_MFR(nor->info) == SNOR_MFR_SST ||
3535              nor->info->flags & SPI_NOR_HAS_LOCK)) {
3536                 write_enable(nor);
3537                 write_sr(nor, 0);
3538                 spi_nor_wait_till_ready(nor);
3539         }
3540
3541         if (nor->quad_enable) {
3542                 err = nor->quad_enable(nor);
3543                 if (err) {
3544                         dev_dbg(nor->dev, "quad mode not supported\n");
3545                         return err;
3546                 }
3547         }
3548
3549         if (nor->addr_width == 4 &&
3550             !(nor->info->flags & SPI_NOR_OCTAL_DTR_READ) &&
3551             (JEDEC_MFR(nor->info) != SNOR_MFR_SPANSION) &&
3552             !(nor->info->flags & SPI_NOR_4B_OPCODES)) {
3553                 /*
3554                  * If the RESET# pin isn't hooked up properly, or the system
3555                  * otherwise doesn't perform a reset command in the boot
3556                  * sequence, it's impossible to 100% protect against unexpected
3557                  * reboots (e.g., crashes). Warn the user (or hopefully, system
3558                  * designer) that this is bad.
3559                  */
3560                 if (nor->flags & SNOR_F_BROKEN_RESET)
3561                         debug("enabling reset hack; may not recover from unexpected reboots\n");
3562                 set_4byte(nor, nor->info, 1);
3563         }
3564
3565         return 0;
3566 }
3567
3568 #ifdef CONFIG_SPI_FLASH_SOFT_RESET
3569 /**
3570  * spi_nor_soft_reset() - perform the JEDEC Software Reset sequence
3571  * @nor:        the spi_nor structure
3572  *
3573  * This function can be used to switch from Octal DTR mode to legacy mode on a
3574  * flash that supports it. The soft reset is executed in Octal DTR mode.
3575  *
3576  * Return: 0 for success, -errno for failure.
3577  */
3578 static int spi_nor_soft_reset(struct spi_nor *nor)
3579 {
3580         struct spi_mem_op op;
3581         int ret;
3582         enum spi_nor_cmd_ext ext;
3583
3584         ext = nor->cmd_ext_type;
3585         nor->cmd_ext_type = SPI_NOR_EXT_REPEAT;
3586
3587         op = (struct spi_mem_op)SPI_MEM_OP(SPI_MEM_OP_CMD(SPINOR_OP_SRSTEN, 0),
3588                         SPI_MEM_OP_NO_DUMMY,
3589                         SPI_MEM_OP_NO_ADDR,
3590                         SPI_MEM_OP_NO_DATA);
3591         spi_nor_setup_op(nor, &op, SNOR_PROTO_8_8_8_DTR);
3592         ret = spi_mem_exec_op(nor->spi, &op);
3593         if (ret) {
3594                 dev_warn(nor->dev, "Software reset enable failed: %d\n", ret);
3595                 goto out;
3596         }
3597
3598         op = (struct spi_mem_op)SPI_MEM_OP(SPI_MEM_OP_CMD(SPINOR_OP_SRST, 0),
3599                         SPI_MEM_OP_NO_DUMMY,
3600                         SPI_MEM_OP_NO_ADDR,
3601                         SPI_MEM_OP_NO_DATA);
3602         spi_nor_setup_op(nor, &op, SNOR_PROTO_8_8_8_DTR);
3603         ret = spi_mem_exec_op(nor->spi, &op);
3604         if (ret) {
3605                 dev_warn(nor->dev, "Software reset failed: %d\n", ret);
3606                 goto out;
3607         }
3608
3609         /*
3610          * Software Reset is not instant, and the delay varies from flash to
3611          * flash. Looking at a few flashes, most range somewhere below 100
3612          * microseconds. So, wait for 200ms just to be sure.
3613          */
3614         udelay(SPI_NOR_SRST_SLEEP_LEN);
3615
3616 out:
3617         nor->cmd_ext_type = ext;
3618         return ret;
3619 }
3620 #endif /* CONFIG_SPI_FLASH_SOFT_RESET */
3621
3622 int spi_nor_remove(struct spi_nor *nor)
3623 {
3624 #ifdef CONFIG_SPI_FLASH_SOFT_RESET
3625         if (nor->info->flags & SPI_NOR_OCTAL_DTR_READ &&
3626             nor->flags & SNOR_F_SOFT_RESET)
3627                 return spi_nor_soft_reset(nor);
3628 #endif
3629
3630         return 0;
3631 }
3632
3633 void spi_nor_set_fixups(struct spi_nor *nor)
3634 {
3635 #ifdef CONFIG_SPI_FLASH_SPANSION
3636         if (JEDEC_MFR(nor->info) == SNOR_MFR_CYPRESS) {
3637                 switch (nor->info->id[1]) {
3638                 case 0x2a: /* S25HL (QSPI, 3.3V) */
3639                 case 0x2b: /* S25HS (QSPI, 1.8V) */
3640                         nor->fixups = &s25hx_t_fixups;
3641                         break;
3642
3643                 default:
3644                         break;
3645                 }
3646         }
3647 #endif
3648
3649 #ifdef CONFIG_SPI_FLASH_S28HS512T
3650         if (!strcmp(nor->info->name, "s28hs512t"))
3651                 nor->fixups = &s28hs512t_fixups;
3652 #endif
3653
3654 #ifdef CONFIG_SPI_FLASH_MT35XU
3655         if (!strcmp(nor->info->name, "mt35xu512aba"))
3656                 nor->fixups = &mt35xu512aba_fixups;
3657 #endif
3658 }
3659
3660 int spi_nor_scan(struct spi_nor *nor)
3661 {
3662         struct spi_nor_flash_parameter params;
3663         const struct flash_info *info = NULL;
3664         struct mtd_info *mtd = &nor->mtd;
3665         struct spi_slave *spi = nor->spi;
3666         int ret;
3667
3668         /* Reset SPI protocol for all commands. */
3669         nor->reg_proto = SNOR_PROTO_1_1_1;
3670         nor->read_proto = SNOR_PROTO_1_1_1;
3671         nor->write_proto = SNOR_PROTO_1_1_1;
3672         nor->read = spi_nor_read_data;
3673         nor->write = spi_nor_write_data;
3674         nor->read_reg = spi_nor_read_reg;
3675         nor->write_reg = spi_nor_write_reg;
3676
3677         nor->setup = spi_nor_default_setup;
3678
3679 #ifdef CONFIG_SPI_FLASH_SOFT_RESET_ON_BOOT
3680         /*
3681          * When the flash is handed to us in a stateful mode like 8D-8D-8D, it
3682          * is difficult to detect the mode the flash is in. One option is to
3683          * read SFDP in all modes and see which one gives the correct "SFDP"
3684          * signature, but not all flashes support SFDP in 8D-8D-8D mode.
3685          *
3686          * Further, even if you detect the mode of the flash via SFDP, you
3687          * still have the problem of actually reading the ID. The Read ID
3688          * command is not standardized across flash vendors. Flashes can have
3689          * different dummy cycles needed for reading the ID. Some flashes even
3690          * expect a 4-byte dummy address with the Read ID command. All this
3691          * information cannot be obtained from the SFDP table.
3692          *
3693          * So, perform a Software Reset sequence before reading the ID and
3694          * initializing the flash. A Soft Reset will bring back the flash in
3695          * its default protocol mode assuming no non-volatile configuration was
3696          * set. This will let us detect the flash even if ROM hands it to us in
3697          * Octal DTR mode.
3698          *
3699          * To accommodate cases where there is more than one flash on a board,
3700          * and only one of them needs a soft reset, failure to reset is not
3701          * made fatal, and we still try to read ID if possible.
3702          */
3703         spi_nor_soft_reset(nor);
3704 #endif /* CONFIG_SPI_FLASH_SOFT_RESET_ON_BOOT */
3705
3706         info = spi_nor_read_id(nor);
3707         if (IS_ERR_OR_NULL(info))
3708                 return -ENOENT;
3709         nor->info = info;
3710
3711         spi_nor_set_fixups(nor);
3712
3713         /* Parse the Serial Flash Discoverable Parameters table. */
3714         ret = spi_nor_init_params(nor, info, &params);
3715         if (ret)
3716                 return ret;
3717
3718         if (!mtd->name)
3719                 mtd->name = info->name;
3720         mtd->dev = nor->dev;
3721         mtd->priv = nor;
3722         mtd->type = MTD_NORFLASH;
3723         mtd->writesize = 1;
3724         mtd->flags = MTD_CAP_NORFLASH;
3725         mtd->size = params.size;
3726         mtd->_erase = spi_nor_erase;
3727         mtd->_read = spi_nor_read;
3728         mtd->_write = spi_nor_write;
3729
3730 #if defined(CONFIG_SPI_FLASH_STMICRO) || defined(CONFIG_SPI_FLASH_SST)
3731         /* NOR protection support for STmicro/Micron chips and similar */
3732         if (JEDEC_MFR(info) == SNOR_MFR_ST ||
3733             JEDEC_MFR(info) == SNOR_MFR_MICRON ||
3734             JEDEC_MFR(info) == SNOR_MFR_SST ||
3735                         info->flags & SPI_NOR_HAS_LOCK) {
3736                 nor->flash_lock = stm_lock;
3737                 nor->flash_unlock = stm_unlock;
3738                 nor->flash_is_locked = stm_is_locked;
3739         }
3740 #endif
3741
3742 #ifdef CONFIG_SPI_FLASH_SST
3743         /*
3744          * sst26 series block protection implementation differs from other
3745          * series.
3746          */
3747         if (info->flags & SPI_NOR_HAS_SST26LOCK) {
3748                 nor->flash_lock = sst26_lock;
3749                 nor->flash_unlock = sst26_unlock;
3750                 nor->flash_is_locked = sst26_is_locked;
3751         }
3752 #endif
3753
3754         if (info->flags & USE_FSR)
3755                 nor->flags |= SNOR_F_USE_FSR;
3756         if (info->flags & SPI_NOR_HAS_TB)
3757                 nor->flags |= SNOR_F_HAS_SR_TB;
3758         if (info->flags & NO_CHIP_ERASE)
3759                 nor->flags |= SNOR_F_NO_OP_CHIP_ERASE;
3760         if (info->flags & USE_CLSR)
3761                 nor->flags |= SNOR_F_USE_CLSR;
3762
3763         if (info->flags & SPI_NOR_NO_ERASE)
3764                 mtd->flags |= MTD_NO_ERASE;
3765
3766         nor->page_size = params.page_size;
3767         mtd->writebufsize = nor->page_size;
3768
3769         /* Some devices cannot do fast-read, no matter what DT tells us */
3770         if ((info->flags & SPI_NOR_NO_FR) || (spi->mode & SPI_RX_SLOW))
3771                 params.hwcaps.mask &= ~SNOR_HWCAPS_READ_FAST;
3772
3773         /*
3774          * Configure the SPI memory:
3775          * - select op codes for (Fast) Read, Page Program and Sector Erase.
3776          * - set the number of dummy cycles (mode cycles + wait states).
3777          * - set the SPI protocols for register and memory accesses.
3778          * - set the Quad Enable bit if needed (required by SPI x-y-4 protos).
3779          */
3780         ret = spi_nor_setup(nor, info, &params);
3781         if (ret)
3782                 return ret;
3783
3784         if (spi_nor_protocol_is_dtr(nor->read_proto)) {
3785                  /* Always use 4-byte addresses in DTR mode. */
3786                 nor->addr_width = 4;
3787         } else if (nor->addr_width) {
3788                 /* already configured from SFDP */
3789         } else if (info->addr_width) {
3790                 nor->addr_width = info->addr_width;
3791         } else {
3792                 nor->addr_width = 3;
3793         }
3794
3795         if (nor->addr_width == 3 && mtd->size > SZ_16M) {
3796 #ifndef CONFIG_SPI_FLASH_BAR
3797                 /* enable 4-byte addressing if the device exceeds 16MiB */
3798                 nor->addr_width = 4;
3799                 if (JEDEC_MFR(info) == SNOR_MFR_SPANSION ||
3800                     info->flags & SPI_NOR_4B_OPCODES)
3801                         spi_nor_set_4byte_opcodes(nor, info);
3802 #else
3803         /* Configure the BAR - discover bank cmds and read current bank */
3804         nor->addr_width = 3;
3805         ret = read_bar(nor, info);
3806         if (ret < 0)
3807                 return ret;
3808 #endif
3809         }
3810
3811         if (nor->addr_width > SPI_NOR_MAX_ADDR_WIDTH) {
3812                 dev_dbg(nor->dev, "address width is too large: %u\n",
3813                         nor->addr_width);
3814                 return -EINVAL;
3815         }
3816
3817         /* Send all the required SPI flash commands to initialize device */
3818         ret = spi_nor_init(nor);
3819         if (ret)
3820                 return ret;
3821
3822         nor->rdsr_dummy = params.rdsr_dummy;
3823         nor->rdsr_addr_nbytes = params.rdsr_addr_nbytes;
3824         nor->name = mtd->name;
3825         nor->size = mtd->size;
3826         nor->erase_size = mtd->erasesize;
3827         nor->sector_size = mtd->erasesize;
3828
3829 #ifndef CONFIG_SPL_BUILD
3830         printf("SF: Detected %s with page size ", nor->name);
3831         print_size(nor->page_size, ", erase size ");
3832         print_size(nor->erase_size, ", total ");
3833         print_size(nor->size, "");
3834         puts("\n");
3835 #endif
3836
3837         return 0;
3838 }
3839
3840 /* U-Boot specific functions, need to extend MTD to support these */
3841 int spi_flash_cmd_get_sw_write_prot(struct spi_nor *nor)
3842 {
3843         int sr = read_sr(nor);
3844
3845         if (sr < 0)
3846                 return sr;
3847
3848         return (sr >> 2) & 7;
3849 }