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