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