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