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