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