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