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