mtd: spi-nor-core: Add support for DTR protocol
[platform/kernel/u-boot.git] / drivers / mtd / spi / spi-nor-core.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Based on m25p80.c, by Mike Lavender (mike@steroidmicros.com), with
4  * influence from lart.c (Abraham Van Der Merwe) and mtd_dataflash.c
5  *
6  * Copyright (C) 2005, Intec Automation Inc.
7  * Copyright (C) 2014, Freescale Semiconductor, Inc.
8  *
9  * Synced from Linux v4.19
10  */
11
12 #include <common.h>
13 #include <log.h>
14 #include <watchdog.h>
15 #include <dm.h>
16 #include <dm/device_compat.h>
17 #include <dm/devres.h>
18 #include <linux/bitops.h>
19 #include <linux/err.h>
20 #include <linux/errno.h>
21 #include <linux/log2.h>
22 #include <linux/math64.h>
23 #include <linux/sizes.h>
24
25 #include <linux/mtd/mtd.h>
26 #include <linux/mtd/spi-nor.h>
27 #include <spi-mem.h>
28 #include <spi.h>
29
30 #include "sf_internal.h"
31
32 /* Define max times to check status register before we give up. */
33
34 /*
35  * For everything but full-chip erase; probably could be much smaller, but kept
36  * around for safety for now
37  */
38
39 #define HZ                                      CONFIG_SYS_HZ
40
41 #define DEFAULT_READY_WAIT_JIFFIES              (40UL * HZ)
42
43 struct sfdp_parameter_header {
44         u8              id_lsb;
45         u8              minor;
46         u8              major;
47         u8              length; /* in double words */
48         u8              parameter_table_pointer[3]; /* byte address */
49         u8              id_msb;
50 };
51
52 #define SFDP_PARAM_HEADER_ID(p) (((p)->id_msb << 8) | (p)->id_lsb)
53 #define SFDP_PARAM_HEADER_PTP(p) \
54         (((p)->parameter_table_pointer[2] << 16) | \
55          ((p)->parameter_table_pointer[1] <<  8) | \
56          ((p)->parameter_table_pointer[0] <<  0))
57
58 #define SFDP_BFPT_ID            0xff00  /* Basic Flash Parameter Table */
59 #define SFDP_SECTOR_MAP_ID      0xff81  /* Sector Map Table */
60 #define SFDP_SST_ID             0x01bf  /* Manufacturer specific Table */
61
62 #define SFDP_SIGNATURE          0x50444653U
63 #define SFDP_JESD216_MAJOR      1
64 #define SFDP_JESD216_MINOR      0
65 #define SFDP_JESD216A_MINOR     5
66 #define SFDP_JESD216B_MINOR     6
67
68 struct sfdp_header {
69         u32             signature; /* Ox50444653U <=> "SFDP" */
70         u8              minor;
71         u8              major;
72         u8              nph; /* 0-base number of parameter headers */
73         u8              unused;
74
75         /* Basic Flash Parameter Table. */
76         struct sfdp_parameter_header    bfpt_header;
77 };
78
79 /* Basic Flash Parameter Table */
80
81 /*
82  * JESD216 rev B defines a Basic Flash Parameter Table of 16 DWORDs.
83  * They are indexed from 1 but C arrays are indexed from 0.
84  */
85 #define BFPT_DWORD(i)           ((i) - 1)
86 #define BFPT_DWORD_MAX          16
87
88 /* The first version of JESB216 defined only 9 DWORDs. */
89 #define BFPT_DWORD_MAX_JESD216                  9
90
91 /* 1st DWORD. */
92 #define BFPT_DWORD1_FAST_READ_1_1_2             BIT(16)
93 #define BFPT_DWORD1_ADDRESS_BYTES_MASK          GENMASK(18, 17)
94 #define BFPT_DWORD1_ADDRESS_BYTES_3_ONLY        (0x0UL << 17)
95 #define BFPT_DWORD1_ADDRESS_BYTES_3_OR_4        (0x1UL << 17)
96 #define BFPT_DWORD1_ADDRESS_BYTES_4_ONLY        (0x2UL << 17)
97 #define BFPT_DWORD1_DTR                         BIT(19)
98 #define BFPT_DWORD1_FAST_READ_1_2_2             BIT(20)
99 #define BFPT_DWORD1_FAST_READ_1_4_4             BIT(21)
100 #define BFPT_DWORD1_FAST_READ_1_1_4             BIT(22)
101
102 /* 5th DWORD. */
103 #define BFPT_DWORD5_FAST_READ_2_2_2             BIT(0)
104 #define BFPT_DWORD5_FAST_READ_4_4_4             BIT(4)
105
106 /* 11th DWORD. */
107 #define BFPT_DWORD11_PAGE_SIZE_SHIFT            4
108 #define BFPT_DWORD11_PAGE_SIZE_MASK             GENMASK(7, 4)
109
110 /* 15th DWORD. */
111
112 /*
113  * (from JESD216 rev B)
114  * Quad Enable Requirements (QER):
115  * - 000b: Device does not have a QE bit. Device detects 1-1-4 and 1-4-4
116  *         reads based on instruction. DQ3/HOLD# functions are hold during
117  *         instruction phase.
118  * - 001b: QE is bit 1 of status register 2. It is set via Write Status with
119  *         two data bytes where bit 1 of the second byte is one.
120  *         [...]
121  *         Writing only one byte to the status register has the side-effect of
122  *         clearing status register 2, including the QE bit. The 100b code is
123  *         used if writing one byte to the status register does not modify
124  *         status register 2.
125  * - 010b: QE is bit 6 of status register 1. It is set via Write Status with
126  *         one data byte where bit 6 is one.
127  *         [...]
128  * - 011b: QE is bit 7 of status register 2. It is set via Write status
129  *         register 2 instruction 3Eh with one data byte where bit 7 is one.
130  *         [...]
131  *         The status register 2 is read using instruction 3Fh.
132  * - 100b: QE is bit 1 of status register 2. It is set via Write Status with
133  *         two data bytes where bit 1 of the second byte is one.
134  *         [...]
135  *         In contrast to the 001b code, writing one byte to the status
136  *         register does not modify status register 2.
137  * - 101b: QE is bit 1 of status register 2. Status register 1 is read using
138  *         Read Status instruction 05h. Status register2 is read using
139  *         instruction 35h. QE is set via Writ Status instruction 01h with
140  *         two data bytes where bit 1 of the second byte is one.
141  *         [...]
142  */
143 #define BFPT_DWORD15_QER_MASK                   GENMASK(22, 20)
144 #define BFPT_DWORD15_QER_NONE                   (0x0UL << 20) /* Micron */
145 #define BFPT_DWORD15_QER_SR2_BIT1_BUGGY         (0x1UL << 20)
146 #define BFPT_DWORD15_QER_SR1_BIT6               (0x2UL << 20) /* Macronix */
147 #define BFPT_DWORD15_QER_SR2_BIT7               (0x3UL << 20)
148 #define BFPT_DWORD15_QER_SR2_BIT1_NO_RD         (0x4UL << 20)
149 #define BFPT_DWORD15_QER_SR2_BIT1               (0x5UL << 20) /* Spansion */
150
151 struct sfdp_bfpt {
152         u32     dwords[BFPT_DWORD_MAX];
153 };
154
155 /**
156  * struct spi_nor_fixups - SPI NOR fixup hooks
157  * @default_init: called after default flash parameters init. Used to tweak
158  *                flash parameters when information provided by the flash_info
159  *                table is incomplete or wrong.
160  * @post_bfpt: called after the BFPT table has been parsed
161  * @post_sfdp: called after SFDP has been parsed (is also called for SPI NORs
162  *             that do not support RDSFDP). Typically used to tweak various
163  *             parameters that could not be extracted by other means (i.e.
164  *             when information provided by the SFDP/flash_info tables are
165  *             incomplete or wrong).
166  *
167  * Those hooks can be used to tweak the SPI NOR configuration when the SFDP
168  * table is broken or not available.
169  */
170 struct spi_nor_fixups {
171         void (*default_init)(struct spi_nor *nor);
172         int (*post_bfpt)(struct spi_nor *nor,
173                          const struct sfdp_parameter_header *bfpt_header,
174                          const struct sfdp_bfpt *bfpt,
175                          struct spi_nor_flash_parameter *params);
176         void (*post_sfdp)(struct spi_nor *nor,
177                           struct spi_nor_flash_parameter *params);
178 };
179
180 /**
181  * spi_nor_get_cmd_ext() - Get the command opcode extension based on the
182  *                         extension type.
183  * @nor:                pointer to a 'struct spi_nor'
184  * @op:                 pointer to the 'struct spi_mem_op' whose properties
185  *                      need to be initialized.
186  *
187  * Right now, only "repeat" and "invert" are supported.
188  *
189  * Return: The opcode extension.
190  */
191 static u8 spi_nor_get_cmd_ext(const struct spi_nor *nor,
192                               const struct spi_mem_op *op)
193 {
194         switch (nor->cmd_ext_type) {
195         case SPI_NOR_EXT_INVERT:
196                 return ~op->cmd.opcode;
197
198         case SPI_NOR_EXT_REPEAT:
199                 return op->cmd.opcode;
200
201         default:
202                 dev_dbg(nor->dev, "Unknown command extension type\n");
203                 return 0;
204         }
205 }
206
207 /**
208  * spi_nor_setup_op() - Set up common properties of a spi-mem op.
209  * @nor:                pointer to a 'struct spi_nor'
210  * @op:                 pointer to the 'struct spi_mem_op' whose properties
211  *                      need to be initialized.
212  * @proto:              the protocol from which the properties need to be set.
213  */
214 static void spi_nor_setup_op(const struct spi_nor *nor,
215                              struct spi_mem_op *op,
216                              const enum spi_nor_protocol proto)
217 {
218         u8 ext;
219
220         op->cmd.buswidth = spi_nor_get_protocol_inst_nbits(proto);
221
222         if (op->addr.nbytes)
223                 op->addr.buswidth = spi_nor_get_protocol_addr_nbits(proto);
224
225         if (op->dummy.nbytes)
226                 op->dummy.buswidth = spi_nor_get_protocol_addr_nbits(proto);
227
228         if (op->data.nbytes)
229                 op->data.buswidth = spi_nor_get_protocol_data_nbits(proto);
230
231         if (spi_nor_protocol_is_dtr(proto)) {
232                 /*
233                  * spi-mem supports mixed DTR modes, but right now we can only
234                  * have all phases either DTR or STR. IOW, spi-mem can have
235                  * something like 4S-4D-4D, but spi-nor can't. So, set all 4
236                  * phases to either DTR or STR.
237                  */
238                 op->cmd.dtr = op->addr.dtr = op->dummy.dtr =
239                         op->data.dtr = true;
240
241                 /* 2 bytes per clock cycle in DTR mode. */
242                 op->dummy.nbytes *= 2;
243
244                 ext = spi_nor_get_cmd_ext(nor, op);
245                 op->cmd.opcode = (op->cmd.opcode << 8) | ext;
246                 op->cmd.nbytes = 2;
247         }
248 }
249
250 static int spi_nor_read_write_reg(struct spi_nor *nor, struct spi_mem_op
251                 *op, void *buf)
252 {
253         if (op->data.dir == SPI_MEM_DATA_IN)
254                 op->data.buf.in = buf;
255         else
256                 op->data.buf.out = buf;
257         return spi_mem_exec_op(nor->spi, op);
258 }
259
260 static int spi_nor_read_reg(struct spi_nor *nor, u8 code, u8 *val, int len)
261 {
262         struct spi_mem_op op = SPI_MEM_OP(SPI_MEM_OP_CMD(code, 0),
263                                           SPI_MEM_OP_NO_ADDR,
264                                           SPI_MEM_OP_NO_DUMMY,
265                                           SPI_MEM_OP_DATA_IN(len, NULL, 0));
266         int ret;
267
268         spi_nor_setup_op(nor, &op, nor->reg_proto);
269
270         ret = spi_nor_read_write_reg(nor, &op, val);
271         if (ret < 0)
272                 dev_dbg(nor->dev, "error %d reading %x\n", ret, code);
273
274         return ret;
275 }
276
277 static int spi_nor_write_reg(struct spi_nor *nor, u8 opcode, u8 *buf, int len)
278 {
279         struct spi_mem_op op = SPI_MEM_OP(SPI_MEM_OP_CMD(opcode, 0),
280                                           SPI_MEM_OP_NO_ADDR,
281                                           SPI_MEM_OP_NO_DUMMY,
282                                           SPI_MEM_OP_DATA_OUT(len, NULL, 0));
283
284         spi_nor_setup_op(nor, &op, nor->reg_proto);
285
286         if (len == 0)
287                 op.data.dir = SPI_MEM_NO_DATA;
288
289         return spi_nor_read_write_reg(nor, &op, buf);
290 }
291
292 static ssize_t spi_nor_read_data(struct spi_nor *nor, loff_t from, size_t len,
293                                  u_char *buf)
294 {
295         struct spi_mem_op op =
296                         SPI_MEM_OP(SPI_MEM_OP_CMD(nor->read_opcode, 0),
297                                    SPI_MEM_OP_ADDR(nor->addr_width, from, 0),
298                                    SPI_MEM_OP_DUMMY(nor->read_dummy, 0),
299                                    SPI_MEM_OP_DATA_IN(len, buf, 0));
300         size_t remaining = len;
301         int ret;
302
303         spi_nor_setup_op(nor, &op, nor->read_proto);
304
305         /* convert the dummy cycles to the number of bytes */
306         op.dummy.nbytes = (nor->read_dummy * op.dummy.buswidth) / 8;
307         if (spi_nor_protocol_is_dtr(nor->read_proto))
308                 op.dummy.nbytes *= 2;
309
310         while (remaining) {
311                 op.data.nbytes = remaining < UINT_MAX ? remaining : UINT_MAX;
312                 ret = spi_mem_adjust_op_size(nor->spi, &op);
313                 if (ret)
314                         return ret;
315
316                 ret = spi_mem_exec_op(nor->spi, &op);
317                 if (ret)
318                         return ret;
319
320                 op.addr.val += op.data.nbytes;
321                 remaining -= op.data.nbytes;
322                 op.data.buf.in += op.data.nbytes;
323         }
324
325         return len;
326 }
327
328 static ssize_t spi_nor_write_data(struct spi_nor *nor, loff_t to, size_t len,
329                                   const u_char *buf)
330 {
331         struct spi_mem_op op =
332                         SPI_MEM_OP(SPI_MEM_OP_CMD(nor->program_opcode, 0),
333                                    SPI_MEM_OP_ADDR(nor->addr_width, to, 0),
334                                    SPI_MEM_OP_NO_DUMMY,
335                                    SPI_MEM_OP_DATA_OUT(len, buf, 0));
336         int ret;
337
338         if (nor->program_opcode == SPINOR_OP_AAI_WP && nor->sst_write_second)
339                 op.addr.nbytes = 0;
340
341         spi_nor_setup_op(nor, &op, nor->write_proto);
342
343         ret = spi_mem_adjust_op_size(nor->spi, &op);
344         if (ret)
345                 return ret;
346         op.data.nbytes = len < op.data.nbytes ? len : op.data.nbytes;
347
348         ret = spi_mem_exec_op(nor->spi, &op);
349         if (ret)
350                 return ret;
351
352         return op.data.nbytes;
353 }
354
355 /*
356  * Read the status register, returning its value in the location
357  * Return the status register value.
358  * Returns negative if error occurred.
359  */
360 static int read_sr(struct spi_nor *nor)
361 {
362         int ret;
363         u8 val;
364
365         ret = nor->read_reg(nor, SPINOR_OP_RDSR, &val, 1);
366         if (ret < 0) {
367                 pr_debug("error %d reading SR\n", (int)ret);
368                 return ret;
369         }
370
371         return val;
372 }
373
374 /*
375  * Read the flag status register, returning its value in the location
376  * Return the status register value.
377  * Returns negative if error occurred.
378  */
379 static int read_fsr(struct spi_nor *nor)
380 {
381         int ret;
382         u8 val;
383
384         ret = nor->read_reg(nor, SPINOR_OP_RDFSR, &val, 1);
385         if (ret < 0) {
386                 pr_debug("error %d reading FSR\n", ret);
387                 return ret;
388         }
389
390         return val;
391 }
392
393 /*
394  * Read configuration register, returning its value in the
395  * location. Return the configuration register value.
396  * Returns negative if error occurred.
397  */
398 #if defined(CONFIG_SPI_FLASH_SPANSION) || defined(CONFIG_SPI_FLASH_WINBOND)
399 static int read_cr(struct spi_nor *nor)
400 {
401         int ret;
402         u8 val;
403
404         ret = nor->read_reg(nor, SPINOR_OP_RDCR, &val, 1);
405         if (ret < 0) {
406                 dev_dbg(nor->dev, "error %d reading CR\n", ret);
407                 return ret;
408         }
409
410         return val;
411 }
412 #endif
413
414 /*
415  * Write status register 1 byte
416  * Returns negative if error occurred.
417  */
418 static int write_sr(struct spi_nor *nor, u8 val)
419 {
420         nor->cmd_buf[0] = val;
421         return nor->write_reg(nor, SPINOR_OP_WRSR, nor->cmd_buf, 1);
422 }
423
424 /*
425  * Set write enable latch with Write Enable command.
426  * Returns negative if error occurred.
427  */
428 static int write_enable(struct spi_nor *nor)
429 {
430         return nor->write_reg(nor, SPINOR_OP_WREN, NULL, 0);
431 }
432
433 /*
434  * Send write disable instruction to the chip.
435  */
436 static int write_disable(struct spi_nor *nor)
437 {
438         return nor->write_reg(nor, SPINOR_OP_WRDI, NULL, 0);
439 }
440
441 static struct spi_nor *mtd_to_spi_nor(struct mtd_info *mtd)
442 {
443         return mtd->priv;
444 }
445
446 #ifndef CONFIG_SPI_FLASH_BAR
447 static u8 spi_nor_convert_opcode(u8 opcode, const u8 table[][2], size_t size)
448 {
449         size_t i;
450
451         for (i = 0; i < size; i++)
452                 if (table[i][0] == opcode)
453                         return table[i][1];
454
455         /* No conversion found, keep input op code. */
456         return opcode;
457 }
458
459 static u8 spi_nor_convert_3to4_read(u8 opcode)
460 {
461         static const u8 spi_nor_3to4_read[][2] = {
462                 { SPINOR_OP_READ,       SPINOR_OP_READ_4B },
463                 { SPINOR_OP_READ_FAST,  SPINOR_OP_READ_FAST_4B },
464                 { SPINOR_OP_READ_1_1_2, SPINOR_OP_READ_1_1_2_4B },
465                 { SPINOR_OP_READ_1_2_2, SPINOR_OP_READ_1_2_2_4B },
466                 { SPINOR_OP_READ_1_1_4, SPINOR_OP_READ_1_1_4_4B },
467                 { SPINOR_OP_READ_1_4_4, SPINOR_OP_READ_1_4_4_4B },
468                 { SPINOR_OP_READ_1_1_8, SPINOR_OP_READ_1_1_8_4B },
469                 { SPINOR_OP_READ_1_8_8, SPINOR_OP_READ_1_8_8_4B },
470
471                 { SPINOR_OP_READ_1_1_1_DTR,     SPINOR_OP_READ_1_1_1_DTR_4B },
472                 { SPINOR_OP_READ_1_2_2_DTR,     SPINOR_OP_READ_1_2_2_DTR_4B },
473                 { SPINOR_OP_READ_1_4_4_DTR,     SPINOR_OP_READ_1_4_4_DTR_4B },
474         };
475
476         return spi_nor_convert_opcode(opcode, spi_nor_3to4_read,
477                                       ARRAY_SIZE(spi_nor_3to4_read));
478 }
479
480 static u8 spi_nor_convert_3to4_program(u8 opcode)
481 {
482         static const u8 spi_nor_3to4_program[][2] = {
483                 { SPINOR_OP_PP,         SPINOR_OP_PP_4B },
484                 { SPINOR_OP_PP_1_1_4,   SPINOR_OP_PP_1_1_4_4B },
485                 { SPINOR_OP_PP_1_4_4,   SPINOR_OP_PP_1_4_4_4B },
486                 { SPINOR_OP_PP_1_1_8,   SPINOR_OP_PP_1_1_8_4B },
487                 { SPINOR_OP_PP_1_8_8,   SPINOR_OP_PP_1_8_8_4B },
488         };
489
490         return spi_nor_convert_opcode(opcode, spi_nor_3to4_program,
491                                       ARRAY_SIZE(spi_nor_3to4_program));
492 }
493
494 static u8 spi_nor_convert_3to4_erase(u8 opcode)
495 {
496         static const u8 spi_nor_3to4_erase[][2] = {
497                 { SPINOR_OP_BE_4K,      SPINOR_OP_BE_4K_4B },
498                 { SPINOR_OP_BE_32K,     SPINOR_OP_BE_32K_4B },
499                 { SPINOR_OP_SE,         SPINOR_OP_SE_4B },
500         };
501
502         return spi_nor_convert_opcode(opcode, spi_nor_3to4_erase,
503                                       ARRAY_SIZE(spi_nor_3to4_erase));
504 }
505
506 static void spi_nor_set_4byte_opcodes(struct spi_nor *nor,
507                                       const struct flash_info *info)
508 {
509         /* Do some manufacturer fixups first */
510         switch (JEDEC_MFR(info)) {
511         case SNOR_MFR_SPANSION:
512                 /* No small sector erase for 4-byte command set */
513                 nor->erase_opcode = SPINOR_OP_SE;
514                 nor->mtd.erasesize = info->sector_size;
515                 break;
516
517         default:
518                 break;
519         }
520
521         nor->read_opcode = spi_nor_convert_3to4_read(nor->read_opcode);
522         nor->program_opcode = spi_nor_convert_3to4_program(nor->program_opcode);
523         nor->erase_opcode = spi_nor_convert_3to4_erase(nor->erase_opcode);
524 }
525 #endif /* !CONFIG_SPI_FLASH_BAR */
526
527 /* Enable/disable 4-byte addressing mode. */
528 static int set_4byte(struct spi_nor *nor, const struct flash_info *info,
529                      int enable)
530 {
531         int status;
532         bool need_wren = false;
533         u8 cmd;
534
535         switch (JEDEC_MFR(info)) {
536         case SNOR_MFR_ST:
537         case SNOR_MFR_MICRON:
538                 /* Some Micron need WREN command; all will accept it */
539                 need_wren = true;
540         case SNOR_MFR_ISSI:
541         case SNOR_MFR_MACRONIX:
542         case SNOR_MFR_WINBOND:
543                 if (need_wren)
544                         write_enable(nor);
545
546                 cmd = enable ? SPINOR_OP_EN4B : SPINOR_OP_EX4B;
547                 status = nor->write_reg(nor, cmd, NULL, 0);
548                 if (need_wren)
549                         write_disable(nor);
550
551                 if (!status && !enable &&
552                     JEDEC_MFR(info) == SNOR_MFR_WINBOND) {
553                         /*
554                          * On Winbond W25Q256FV, leaving 4byte mode causes
555                          * the Extended Address Register to be set to 1, so all
556                          * 3-byte-address reads come from the second 16M.
557                          * We must clear the register to enable normal behavior.
558                          */
559                         write_enable(nor);
560                         nor->cmd_buf[0] = 0;
561                         nor->write_reg(nor, SPINOR_OP_WREAR, nor->cmd_buf, 1);
562                         write_disable(nor);
563                 }
564
565                 return status;
566         default:
567                 /* Spansion style */
568                 nor->cmd_buf[0] = enable << 7;
569                 return nor->write_reg(nor, SPINOR_OP_BRWR, nor->cmd_buf, 1);
570         }
571 }
572
573 static int spi_nor_sr_ready(struct spi_nor *nor)
574 {
575         int sr = read_sr(nor);
576
577         if (sr < 0)
578                 return sr;
579
580         if (nor->flags & SNOR_F_USE_CLSR && sr & (SR_E_ERR | SR_P_ERR)) {
581                 if (sr & SR_E_ERR)
582                         dev_dbg(nor->dev, "Erase Error occurred\n");
583                 else
584                         dev_dbg(nor->dev, "Programming Error occurred\n");
585
586                 nor->write_reg(nor, SPINOR_OP_CLSR, NULL, 0);
587                 return -EIO;
588         }
589
590         return !(sr & SR_WIP);
591 }
592
593 static int spi_nor_fsr_ready(struct spi_nor *nor)
594 {
595         int fsr = read_fsr(nor);
596
597         if (fsr < 0)
598                 return fsr;
599
600         if (fsr & (FSR_E_ERR | FSR_P_ERR)) {
601                 if (fsr & FSR_E_ERR)
602                         dev_err(nor->dev, "Erase operation failed.\n");
603                 else
604                         dev_err(nor->dev, "Program operation failed.\n");
605
606                 if (fsr & FSR_PT_ERR)
607                         dev_err(nor->dev,
608                                 "Attempted to modify a protected sector.\n");
609
610                 nor->write_reg(nor, SPINOR_OP_CLFSR, NULL, 0);
611                 return -EIO;
612         }
613
614         return fsr & FSR_READY;
615 }
616
617 static int spi_nor_ready(struct spi_nor *nor)
618 {
619         int sr, fsr;
620
621         sr = spi_nor_sr_ready(nor);
622         if (sr < 0)
623                 return sr;
624         fsr = nor->flags & SNOR_F_USE_FSR ? spi_nor_fsr_ready(nor) : 1;
625         if (fsr < 0)
626                 return fsr;
627         return sr && fsr;
628 }
629
630 /*
631  * Service routine to read status register until ready, or timeout occurs.
632  * Returns non-zero if error.
633  */
634 static int spi_nor_wait_till_ready_with_timeout(struct spi_nor *nor,
635                                                 unsigned long timeout)
636 {
637         unsigned long timebase;
638         int ret;
639
640         timebase = get_timer(0);
641
642         while (get_timer(timebase) < timeout) {
643                 ret = spi_nor_ready(nor);
644                 if (ret < 0)
645                         return ret;
646                 if (ret)
647                         return 0;
648         }
649
650         dev_err(nor->dev, "flash operation timed out\n");
651
652         return -ETIMEDOUT;
653 }
654
655 static int spi_nor_wait_till_ready(struct spi_nor *nor)
656 {
657         return spi_nor_wait_till_ready_with_timeout(nor,
658                                                     DEFAULT_READY_WAIT_JIFFIES);
659 }
660
661 #ifdef CONFIG_SPI_FLASH_BAR
662 /*
663  * This "clean_bar" is necessary in a situation when one was accessing
664  * spi flash memory > 16 MiB by using Bank Address Register's BA24 bit.
665  *
666  * After it the BA24 bit shall be cleared to allow access to correct
667  * memory region after SW reset (by calling "reset" command).
668  *
669  * Otherwise, the BA24 bit may be left set and then after reset, the
670  * ROM would read/write/erase SPL from 16 MiB * bank_sel address.
671  */
672 static int clean_bar(struct spi_nor *nor)
673 {
674         u8 cmd, bank_sel = 0;
675
676         if (nor->bank_curr == 0)
677                 return 0;
678         cmd = nor->bank_write_cmd;
679         nor->bank_curr = 0;
680         write_enable(nor);
681
682         return nor->write_reg(nor, cmd, &bank_sel, 1);
683 }
684
685 static int write_bar(struct spi_nor *nor, u32 offset)
686 {
687         u8 cmd, bank_sel;
688         int ret;
689
690         bank_sel = offset / SZ_16M;
691         if (bank_sel == nor->bank_curr)
692                 goto bar_end;
693
694         cmd = nor->bank_write_cmd;
695         write_enable(nor);
696         ret = nor->write_reg(nor, cmd, &bank_sel, 1);
697         if (ret < 0) {
698                 debug("SF: fail to write bank register\n");
699                 return ret;
700         }
701
702 bar_end:
703         nor->bank_curr = bank_sel;
704         return nor->bank_curr;
705 }
706
707 static int read_bar(struct spi_nor *nor, const struct flash_info *info)
708 {
709         u8 curr_bank = 0;
710         int ret;
711
712         switch (JEDEC_MFR(info)) {
713         case SNOR_MFR_SPANSION:
714                 nor->bank_read_cmd = SPINOR_OP_BRRD;
715                 nor->bank_write_cmd = SPINOR_OP_BRWR;
716                 break;
717         default:
718                 nor->bank_read_cmd = SPINOR_OP_RDEAR;
719                 nor->bank_write_cmd = SPINOR_OP_WREAR;
720         }
721
722         ret = nor->read_reg(nor, nor->bank_read_cmd,
723                                     &curr_bank, 1);
724         if (ret) {
725                 debug("SF: fail to read bank addr register\n");
726                 return ret;
727         }
728         nor->bank_curr = curr_bank;
729
730         return 0;
731 }
732 #endif
733
734 /*
735  * Initiate the erasure of a single sector
736  */
737 static int spi_nor_erase_sector(struct spi_nor *nor, u32 addr)
738 {
739         struct spi_mem_op op =
740                 SPI_MEM_OP(SPI_MEM_OP_CMD(nor->erase_opcode, 0),
741                            SPI_MEM_OP_ADDR(nor->addr_width, addr, 0),
742                            SPI_MEM_OP_NO_DUMMY,
743                            SPI_MEM_OP_NO_DATA);
744
745         spi_nor_setup_op(nor, &op, nor->write_proto);
746
747         if (nor->erase)
748                 return nor->erase(nor, addr);
749
750         /*
751          * Default implementation, if driver doesn't have a specialized HW
752          * control
753          */
754         return spi_mem_exec_op(nor->spi, &op);
755 }
756
757 /*
758  * Erase an address range on the nor chip.  The address range may extend
759  * one or more erase sectors.  Return an error is there is a problem erasing.
760  */
761 static int spi_nor_erase(struct mtd_info *mtd, struct erase_info *instr)
762 {
763         struct spi_nor *nor = mtd_to_spi_nor(mtd);
764         u32 addr, len, rem;
765         int ret;
766
767         dev_dbg(nor->dev, "at 0x%llx, len %lld\n", (long long)instr->addr,
768                 (long long)instr->len);
769
770         if (!instr->len)
771                 return 0;
772
773         div_u64_rem(instr->len, mtd->erasesize, &rem);
774         if (rem)
775                 return -EINVAL;
776
777         addr = instr->addr;
778         len = instr->len;
779
780         while (len) {
781                 WATCHDOG_RESET();
782 #ifdef CONFIG_SPI_FLASH_BAR
783                 ret = write_bar(nor, addr);
784                 if (ret < 0)
785                         return ret;
786 #endif
787                 write_enable(nor);
788
789                 ret = spi_nor_erase_sector(nor, addr);
790                 if (ret)
791                         goto erase_err;
792
793                 addr += mtd->erasesize;
794                 len -= mtd->erasesize;
795
796                 ret = spi_nor_wait_till_ready(nor);
797                 if (ret)
798                         goto erase_err;
799         }
800
801 erase_err:
802 #ifdef CONFIG_SPI_FLASH_BAR
803         ret = clean_bar(nor);
804 #endif
805         write_disable(nor);
806
807         return ret;
808 }
809
810 #if defined(CONFIG_SPI_FLASH_STMICRO) || defined(CONFIG_SPI_FLASH_SST)
811 /* Write status register and ensure bits in mask match written values */
812 static int write_sr_and_check(struct spi_nor *nor, u8 status_new, u8 mask)
813 {
814         int ret;
815
816         write_enable(nor);
817         ret = write_sr(nor, status_new);
818         if (ret)
819                 return ret;
820
821         ret = spi_nor_wait_till_ready(nor);
822         if (ret)
823                 return ret;
824
825         ret = read_sr(nor);
826         if (ret < 0)
827                 return ret;
828
829         return ((ret & mask) != (status_new & mask)) ? -EIO : 0;
830 }
831
832 static void stm_get_locked_range(struct spi_nor *nor, u8 sr, loff_t *ofs,
833                                  uint64_t *len)
834 {
835         struct mtd_info *mtd = &nor->mtd;
836         u8 mask = SR_BP2 | SR_BP1 | SR_BP0;
837         int shift = ffs(mask) - 1;
838         int pow;
839
840         if (!(sr & mask)) {
841                 /* No protection */
842                 *ofs = 0;
843                 *len = 0;
844         } else {
845                 pow = ((sr & mask) ^ mask) >> shift;
846                 *len = mtd->size >> pow;
847                 if (nor->flags & SNOR_F_HAS_SR_TB && sr & SR_TB)
848                         *ofs = 0;
849                 else
850                         *ofs = mtd->size - *len;
851         }
852 }
853
854 /*
855  * Return 1 if the entire region is locked (if @locked is true) or unlocked (if
856  * @locked is false); 0 otherwise
857  */
858 static int stm_check_lock_status_sr(struct spi_nor *nor, loff_t ofs, u64 len,
859                                     u8 sr, bool locked)
860 {
861         loff_t lock_offs;
862         uint64_t lock_len;
863
864         if (!len)
865                 return 1;
866
867         stm_get_locked_range(nor, sr, &lock_offs, &lock_len);
868
869         if (locked)
870                 /* Requested range is a sub-range of locked range */
871                 return (ofs + len <= lock_offs + lock_len) && (ofs >= lock_offs);
872         else
873                 /* Requested range does not overlap with locked range */
874                 return (ofs >= lock_offs + lock_len) || (ofs + len <= lock_offs);
875 }
876
877 static int stm_is_locked_sr(struct spi_nor *nor, loff_t ofs, uint64_t len,
878                             u8 sr)
879 {
880         return stm_check_lock_status_sr(nor, ofs, len, sr, true);
881 }
882
883 static int stm_is_unlocked_sr(struct spi_nor *nor, loff_t ofs, uint64_t len,
884                               u8 sr)
885 {
886         return stm_check_lock_status_sr(nor, ofs, len, sr, false);
887 }
888
889 /*
890  * Lock a region of the flash. Compatible with ST Micro and similar flash.
891  * Supports the block protection bits BP{0,1,2} in the status register
892  * (SR). Does not support these features found in newer SR bitfields:
893  *   - SEC: sector/block protect - only handle SEC=0 (block protect)
894  *   - CMP: complement protect - only support CMP=0 (range is not complemented)
895  *
896  * Support for the following is provided conditionally for some flash:
897  *   - TB: top/bottom protect
898  *
899  * Sample table portion for 8MB flash (Winbond w25q64fw):
900  *
901  *   SEC  |  TB   |  BP2  |  BP1  |  BP0  |  Prot Length  | Protected Portion
902  *  --------------------------------------------------------------------------
903  *    X   |   X   |   0   |   0   |   0   |  NONE         | NONE
904  *    0   |   0   |   0   |   0   |   1   |  128 KB       | Upper 1/64
905  *    0   |   0   |   0   |   1   |   0   |  256 KB       | Upper 1/32
906  *    0   |   0   |   0   |   1   |   1   |  512 KB       | Upper 1/16
907  *    0   |   0   |   1   |   0   |   0   |  1 MB         | Upper 1/8
908  *    0   |   0   |   1   |   0   |   1   |  2 MB         | Upper 1/4
909  *    0   |   0   |   1   |   1   |   0   |  4 MB         | Upper 1/2
910  *    X   |   X   |   1   |   1   |   1   |  8 MB         | ALL
911  *  ------|-------|-------|-------|-------|---------------|-------------------
912  *    0   |   1   |   0   |   0   |   1   |  128 KB       | Lower 1/64
913  *    0   |   1   |   0   |   1   |   0   |  256 KB       | Lower 1/32
914  *    0   |   1   |   0   |   1   |   1   |  512 KB       | Lower 1/16
915  *    0   |   1   |   1   |   0   |   0   |  1 MB         | Lower 1/8
916  *    0   |   1   |   1   |   0   |   1   |  2 MB         | Lower 1/4
917  *    0   |   1   |   1   |   1   |   0   |  4 MB         | Lower 1/2
918  *
919  * Returns negative on errors, 0 on success.
920  */
921 static int stm_lock(struct spi_nor *nor, loff_t ofs, uint64_t len)
922 {
923         struct mtd_info *mtd = &nor->mtd;
924         int status_old, status_new;
925         u8 mask = SR_BP2 | SR_BP1 | SR_BP0;
926         u8 shift = ffs(mask) - 1, pow, val;
927         loff_t lock_len;
928         bool can_be_top = true, can_be_bottom = nor->flags & SNOR_F_HAS_SR_TB;
929         bool use_top;
930
931         status_old = read_sr(nor);
932         if (status_old < 0)
933                 return status_old;
934
935         /* If nothing in our range is unlocked, we don't need to do anything */
936         if (stm_is_locked_sr(nor, ofs, len, status_old))
937                 return 0;
938
939         /* If anything below us is unlocked, we can't use 'bottom' protection */
940         if (!stm_is_locked_sr(nor, 0, ofs, status_old))
941                 can_be_bottom = false;
942
943         /* If anything above us is unlocked, we can't use 'top' protection */
944         if (!stm_is_locked_sr(nor, ofs + len, mtd->size - (ofs + len),
945                               status_old))
946                 can_be_top = false;
947
948         if (!can_be_bottom && !can_be_top)
949                 return -EINVAL;
950
951         /* Prefer top, if both are valid */
952         use_top = can_be_top;
953
954         /* lock_len: length of region that should end up locked */
955         if (use_top)
956                 lock_len = mtd->size - ofs;
957         else
958                 lock_len = ofs + len;
959
960         /*
961          * Need smallest pow such that:
962          *
963          *   1 / (2^pow) <= (len / size)
964          *
965          * so (assuming power-of-2 size) we do:
966          *
967          *   pow = ceil(log2(size / len)) = log2(size) - floor(log2(len))
968          */
969         pow = ilog2(mtd->size) - ilog2(lock_len);
970         val = mask - (pow << shift);
971         if (val & ~mask)
972                 return -EINVAL;
973         /* Don't "lock" with no region! */
974         if (!(val & mask))
975                 return -EINVAL;
976
977         status_new = (status_old & ~mask & ~SR_TB) | val;
978
979         /* Disallow further writes if WP pin is asserted */
980         status_new |= SR_SRWD;
981
982         if (!use_top)
983                 status_new |= SR_TB;
984
985         /* Don't bother if they're the same */
986         if (status_new == status_old)
987                 return 0;
988
989         /* Only modify protection if it will not unlock other areas */
990         if ((status_new & mask) < (status_old & mask))
991                 return -EINVAL;
992
993         return write_sr_and_check(nor, status_new, mask);
994 }
995
996 /*
997  * Unlock a region of the flash. See stm_lock() for more info
998  *
999  * Returns negative on errors, 0 on success.
1000  */
1001 static int stm_unlock(struct spi_nor *nor, loff_t ofs, uint64_t len)
1002 {
1003         struct mtd_info *mtd = &nor->mtd;
1004         int status_old, status_new;
1005         u8 mask = SR_BP2 | SR_BP1 | SR_BP0;
1006         u8 shift = ffs(mask) - 1, pow, val;
1007         loff_t lock_len;
1008         bool can_be_top = true, can_be_bottom = nor->flags & SNOR_F_HAS_SR_TB;
1009         bool use_top;
1010
1011         status_old = read_sr(nor);
1012         if (status_old < 0)
1013                 return status_old;
1014
1015         /* If nothing in our range is locked, we don't need to do anything */
1016         if (stm_is_unlocked_sr(nor, ofs, len, status_old))
1017                 return 0;
1018
1019         /* If anything below us is locked, we can't use 'top' protection */
1020         if (!stm_is_unlocked_sr(nor, 0, ofs, status_old))
1021                 can_be_top = false;
1022
1023         /* If anything above us is locked, we can't use 'bottom' protection */
1024         if (!stm_is_unlocked_sr(nor, ofs + len, mtd->size - (ofs + len),
1025                                 status_old))
1026                 can_be_bottom = false;
1027
1028         if (!can_be_bottom && !can_be_top)
1029                 return -EINVAL;
1030
1031         /* Prefer top, if both are valid */
1032         use_top = can_be_top;
1033
1034         /* lock_len: length of region that should remain locked */
1035         if (use_top)
1036                 lock_len = mtd->size - (ofs + len);
1037         else
1038                 lock_len = ofs;
1039
1040         /*
1041          * Need largest pow such that:
1042          *
1043          *   1 / (2^pow) >= (len / size)
1044          *
1045          * so (assuming power-of-2 size) we do:
1046          *
1047          *   pow = floor(log2(size / len)) = log2(size) - ceil(log2(len))
1048          */
1049         pow = ilog2(mtd->size) - order_base_2(lock_len);
1050         if (lock_len == 0) {
1051                 val = 0; /* fully unlocked */
1052         } else {
1053                 val = mask - (pow << shift);
1054                 /* Some power-of-two sizes are not supported */
1055                 if (val & ~mask)
1056                         return -EINVAL;
1057         }
1058
1059         status_new = (status_old & ~mask & ~SR_TB) | val;
1060
1061         /* Don't protect status register if we're fully unlocked */
1062         if (lock_len == 0)
1063                 status_new &= ~SR_SRWD;
1064
1065         if (!use_top)
1066                 status_new |= SR_TB;
1067
1068         /* Don't bother if they're the same */
1069         if (status_new == status_old)
1070                 return 0;
1071
1072         /* Only modify protection if it will not lock other areas */
1073         if ((status_new & mask) > (status_old & mask))
1074                 return -EINVAL;
1075
1076         return write_sr_and_check(nor, status_new, mask);
1077 }
1078
1079 /*
1080  * Check if a region of the flash is (completely) locked. See stm_lock() for
1081  * more info.
1082  *
1083  * Returns 1 if entire region is locked, 0 if any portion is unlocked, and
1084  * negative on errors.
1085  */
1086 static int stm_is_locked(struct spi_nor *nor, loff_t ofs, uint64_t len)
1087 {
1088         int status;
1089
1090         status = read_sr(nor);
1091         if (status < 0)
1092                 return status;
1093
1094         return stm_is_locked_sr(nor, ofs, len, status);
1095 }
1096 #endif /* CONFIG_SPI_FLASH_STMICRO */
1097
1098 static const struct flash_info *spi_nor_read_id(struct spi_nor *nor)
1099 {
1100         int                     tmp;
1101         u8                      id[SPI_NOR_MAX_ID_LEN];
1102         const struct flash_info *info;
1103
1104         tmp = nor->read_reg(nor, SPINOR_OP_RDID, id, SPI_NOR_MAX_ID_LEN);
1105         if (tmp < 0) {
1106                 dev_dbg(nor->dev, "error %d reading JEDEC ID\n", tmp);
1107                 return ERR_PTR(tmp);
1108         }
1109
1110         info = spi_nor_ids;
1111         for (; info->name; info++) {
1112                 if (info->id_len) {
1113                         if (!memcmp(info->id, id, info->id_len))
1114                                 return info;
1115                 }
1116         }
1117
1118         dev_err(nor->dev, "unrecognized JEDEC id bytes: %02x, %02x, %02x\n",
1119                 id[0], id[1], id[2]);
1120         return ERR_PTR(-ENODEV);
1121 }
1122
1123 static int spi_nor_read(struct mtd_info *mtd, loff_t from, size_t len,
1124                         size_t *retlen, u_char *buf)
1125 {
1126         struct spi_nor *nor = mtd_to_spi_nor(mtd);
1127         int ret;
1128
1129         dev_dbg(nor->dev, "from 0x%08x, len %zd\n", (u32)from, len);
1130
1131         while (len) {
1132                 loff_t addr = from;
1133                 size_t read_len = len;
1134
1135 #ifdef CONFIG_SPI_FLASH_BAR
1136                 u32 remain_len;
1137
1138                 ret = write_bar(nor, addr);
1139                 if (ret < 0)
1140                         return log_ret(ret);
1141                 remain_len = (SZ_16M * (nor->bank_curr + 1)) - addr;
1142
1143                 if (len < remain_len)
1144                         read_len = len;
1145                 else
1146                         read_len = remain_len;
1147 #endif
1148
1149                 ret = nor->read(nor, addr, read_len, buf);
1150                 if (ret == 0) {
1151                         /* We shouldn't see 0-length reads */
1152                         ret = -EIO;
1153                         goto read_err;
1154                 }
1155                 if (ret < 0)
1156                         goto read_err;
1157
1158                 *retlen += ret;
1159                 buf += ret;
1160                 from += ret;
1161                 len -= ret;
1162         }
1163         ret = 0;
1164
1165 read_err:
1166 #ifdef CONFIG_SPI_FLASH_BAR
1167         ret = clean_bar(nor);
1168 #endif
1169         return ret;
1170 }
1171
1172 #ifdef CONFIG_SPI_FLASH_SST
1173 /*
1174  * sst26 flash series has its own block protection implementation:
1175  * 4x   - 8  KByte blocks - read & write protection bits - upper addresses
1176  * 1x   - 32 KByte blocks - write protection bits
1177  * rest - 64 KByte blocks - write protection bits
1178  * 1x   - 32 KByte blocks - write protection bits
1179  * 4x   - 8  KByte blocks - read & write protection bits - lower addresses
1180  *
1181  * We'll support only per 64k lock/unlock so lower and upper 64 KByte region
1182  * will be treated as single block.
1183  */
1184 #define SST26_BPR_8K_NUM                4
1185 #define SST26_MAX_BPR_REG_LEN           (18 + 1)
1186 #define SST26_BOUND_REG_SIZE            ((32 + SST26_BPR_8K_NUM * 8) * SZ_1K)
1187
1188 enum lock_ctl {
1189         SST26_CTL_LOCK,
1190         SST26_CTL_UNLOCK,
1191         SST26_CTL_CHECK
1192 };
1193
1194 static bool sst26_process_bpr(u32 bpr_size, u8 *cmd, u32 bit, enum lock_ctl ctl)
1195 {
1196         switch (ctl) {
1197         case SST26_CTL_LOCK:
1198                 cmd[bpr_size - (bit / 8) - 1] |= BIT(bit % 8);
1199                 break;
1200         case SST26_CTL_UNLOCK:
1201                 cmd[bpr_size - (bit / 8) - 1] &= ~BIT(bit % 8);
1202                 break;
1203         case SST26_CTL_CHECK:
1204                 return !!(cmd[bpr_size - (bit / 8) - 1] & BIT(bit % 8));
1205         }
1206
1207         return false;
1208 }
1209
1210 /*
1211  * Lock, unlock or check lock status of the flash region of the flash (depending
1212  * on the lock_ctl value)
1213  */
1214 static int sst26_lock_ctl(struct spi_nor *nor, loff_t ofs, uint64_t len, enum lock_ctl ctl)
1215 {
1216         struct mtd_info *mtd = &nor->mtd;
1217         u32 i, bpr_ptr, rptr_64k, lptr_64k, bpr_size;
1218         bool lower_64k = false, upper_64k = false;
1219         u8 bpr_buff[SST26_MAX_BPR_REG_LEN] = {};
1220         int ret;
1221
1222         /* Check length and offset for 64k alignment */
1223         if ((ofs & (SZ_64K - 1)) || (len & (SZ_64K - 1))) {
1224                 dev_err(nor->dev, "length or offset is not 64KiB allighned\n");
1225                 return -EINVAL;
1226         }
1227
1228         if (ofs + len > mtd->size) {
1229                 dev_err(nor->dev, "range is more than device size: %#llx + %#llx > %#llx\n",
1230                         ofs, len, mtd->size);
1231                 return -EINVAL;
1232         }
1233
1234         /* SST26 family has only 16 Mbit, 32 Mbit and 64 Mbit IC */
1235         if (mtd->size != SZ_2M &&
1236             mtd->size != SZ_4M &&
1237             mtd->size != SZ_8M)
1238                 return -EINVAL;
1239
1240         bpr_size = 2 + (mtd->size / SZ_64K / 8);
1241
1242         ret = nor->read_reg(nor, SPINOR_OP_READ_BPR, bpr_buff, bpr_size);
1243         if (ret < 0) {
1244                 dev_err(nor->dev, "fail to read block-protection register\n");
1245                 return ret;
1246         }
1247
1248         rptr_64k = min_t(u32, ofs + len, mtd->size - SST26_BOUND_REG_SIZE);
1249         lptr_64k = max_t(u32, ofs, SST26_BOUND_REG_SIZE);
1250
1251         upper_64k = ((ofs + len) > (mtd->size - SST26_BOUND_REG_SIZE));
1252         lower_64k = (ofs < SST26_BOUND_REG_SIZE);
1253
1254         /* Lower bits in block-protection register are about 64k region */
1255         bpr_ptr = lptr_64k / SZ_64K - 1;
1256
1257         /* Process 64K blocks region */
1258         while (lptr_64k < rptr_64k) {
1259                 if (sst26_process_bpr(bpr_size, bpr_buff, bpr_ptr, ctl))
1260                         return EACCES;
1261
1262                 bpr_ptr++;
1263                 lptr_64k += SZ_64K;
1264         }
1265
1266         /* 32K and 8K region bits in BPR are after 64k region bits */
1267         bpr_ptr = (mtd->size - 2 * SST26_BOUND_REG_SIZE) / SZ_64K;
1268
1269         /* Process lower 32K block region */
1270         if (lower_64k)
1271                 if (sst26_process_bpr(bpr_size, bpr_buff, bpr_ptr, ctl))
1272                         return EACCES;
1273
1274         bpr_ptr++;
1275
1276         /* Process upper 32K block region */
1277         if (upper_64k)
1278                 if (sst26_process_bpr(bpr_size, bpr_buff, bpr_ptr, ctl))
1279                         return EACCES;
1280
1281         bpr_ptr++;
1282
1283         /* Process lower 8K block regions */
1284         for (i = 0; i < SST26_BPR_8K_NUM; i++) {
1285                 if (lower_64k)
1286                         if (sst26_process_bpr(bpr_size, bpr_buff, bpr_ptr, ctl))
1287                                 return EACCES;
1288
1289                 /* In 8K area BPR has both read and write protection bits */
1290                 bpr_ptr += 2;
1291         }
1292
1293         /* Process upper 8K block regions */
1294         for (i = 0; i < SST26_BPR_8K_NUM; i++) {
1295                 if (upper_64k)
1296                         if (sst26_process_bpr(bpr_size, bpr_buff, bpr_ptr, ctl))
1297                                 return EACCES;
1298
1299                 /* In 8K area BPR has both read and write protection bits */
1300                 bpr_ptr += 2;
1301         }
1302
1303         /* If we check region status we don't need to write BPR back */
1304         if (ctl == SST26_CTL_CHECK)
1305                 return 0;
1306
1307         ret = nor->write_reg(nor, SPINOR_OP_WRITE_BPR, bpr_buff, bpr_size);
1308         if (ret < 0) {
1309                 dev_err(nor->dev, "fail to write block-protection register\n");
1310                 return ret;
1311         }
1312
1313         return 0;
1314 }
1315
1316 static int sst26_unlock(struct spi_nor *nor, loff_t ofs, uint64_t len)
1317 {
1318         return sst26_lock_ctl(nor, ofs, len, SST26_CTL_UNLOCK);
1319 }
1320
1321 static int sst26_lock(struct spi_nor *nor, loff_t ofs, uint64_t len)
1322 {
1323         return sst26_lock_ctl(nor, ofs, len, SST26_CTL_LOCK);
1324 }
1325
1326 /*
1327  * Returns EACCES (positive value) if region is locked, 0 if region is unlocked,
1328  * and negative on errors.
1329  */
1330 static int sst26_is_locked(struct spi_nor *nor, loff_t ofs, uint64_t len)
1331 {
1332         /*
1333          * is_locked function is used for check before reading or erasing flash
1334          * region, so offset and length might be not 64k allighned, so adjust
1335          * them to be 64k allighned as sst26_lock_ctl works only with 64k
1336          * allighned regions.
1337          */
1338         ofs -= ofs & (SZ_64K - 1);
1339         len = len & (SZ_64K - 1) ? (len & ~(SZ_64K - 1)) + SZ_64K : len;
1340
1341         return sst26_lock_ctl(nor, ofs, len, SST26_CTL_CHECK);
1342 }
1343
1344 static int sst_write_byteprogram(struct spi_nor *nor, loff_t to, size_t len,
1345                                  size_t *retlen, const u_char *buf)
1346 {
1347         size_t actual;
1348         int ret = 0;
1349
1350         for (actual = 0; actual < len; actual++) {
1351                 nor->program_opcode = SPINOR_OP_BP;
1352
1353                 write_enable(nor);
1354                 /* write one byte. */
1355                 ret = nor->write(nor, to, 1, buf + actual);
1356                 if (ret < 0)
1357                         goto sst_write_err;
1358                 ret = spi_nor_wait_till_ready(nor);
1359                 if (ret)
1360                         goto sst_write_err;
1361                 to++;
1362         }
1363
1364 sst_write_err:
1365         write_disable(nor);
1366         return ret;
1367 }
1368
1369 static int sst_write(struct mtd_info *mtd, loff_t to, size_t len,
1370                      size_t *retlen, const u_char *buf)
1371 {
1372         struct spi_nor *nor = mtd_to_spi_nor(mtd);
1373         struct spi_slave *spi = nor->spi;
1374         size_t actual;
1375         int ret;
1376
1377         dev_dbg(nor->dev, "to 0x%08x, len %zd\n", (u32)to, len);
1378         if (spi->mode & SPI_TX_BYTE)
1379                 return sst_write_byteprogram(nor, to, len, retlen, buf);
1380
1381         write_enable(nor);
1382
1383         nor->sst_write_second = false;
1384
1385         actual = to % 2;
1386         /* Start write from odd address. */
1387         if (actual) {
1388                 nor->program_opcode = SPINOR_OP_BP;
1389
1390                 /* write one byte. */
1391                 ret = nor->write(nor, to, 1, buf);
1392                 if (ret < 0)
1393                         goto sst_write_err;
1394                 ret = spi_nor_wait_till_ready(nor);
1395                 if (ret)
1396                         goto sst_write_err;
1397         }
1398         to += actual;
1399
1400         /* Write out most of the data here. */
1401         for (; actual < len - 1; actual += 2) {
1402                 nor->program_opcode = SPINOR_OP_AAI_WP;
1403
1404                 /* write two bytes. */
1405                 ret = nor->write(nor, to, 2, buf + actual);
1406                 if (ret < 0)
1407                         goto sst_write_err;
1408                 ret = spi_nor_wait_till_ready(nor);
1409                 if (ret)
1410                         goto sst_write_err;
1411                 to += 2;
1412                 nor->sst_write_second = true;
1413         }
1414         nor->sst_write_second = false;
1415
1416         write_disable(nor);
1417         ret = spi_nor_wait_till_ready(nor);
1418         if (ret)
1419                 goto sst_write_err;
1420
1421         /* Write out trailing byte if it exists. */
1422         if (actual != len) {
1423                 write_enable(nor);
1424
1425                 nor->program_opcode = SPINOR_OP_BP;
1426                 ret = nor->write(nor, to, 1, buf + actual);
1427                 if (ret < 0)
1428                         goto sst_write_err;
1429                 ret = spi_nor_wait_till_ready(nor);
1430                 if (ret)
1431                         goto sst_write_err;
1432                 write_disable(nor);
1433                 actual += 1;
1434         }
1435 sst_write_err:
1436         *retlen += actual;
1437         return ret;
1438 }
1439 #endif
1440 /*
1441  * Write an address range to the nor chip.  Data must be written in
1442  * FLASH_PAGESIZE chunks.  The address range may be any size provided
1443  * it is within the physical boundaries.
1444  */
1445 static int spi_nor_write(struct mtd_info *mtd, loff_t to, size_t len,
1446         size_t *retlen, const u_char *buf)
1447 {
1448         struct spi_nor *nor = mtd_to_spi_nor(mtd);
1449         size_t page_offset, page_remain, i;
1450         ssize_t ret;
1451
1452 #ifdef CONFIG_SPI_FLASH_SST
1453         /* sst nor chips use AAI word program */
1454         if (nor->info->flags & SST_WRITE)
1455                 return sst_write(mtd, to, len, retlen, buf);
1456 #endif
1457
1458         dev_dbg(nor->dev, "to 0x%08x, len %zd\n", (u32)to, len);
1459
1460         if (!len)
1461                 return 0;
1462
1463         for (i = 0; i < len; ) {
1464                 ssize_t written;
1465                 loff_t addr = to + i;
1466                 WATCHDOG_RESET();
1467
1468                 /*
1469                  * If page_size is a power of two, the offset can be quickly
1470                  * calculated with an AND operation. On the other cases we
1471                  * need to do a modulus operation (more expensive).
1472                  */
1473                 if (is_power_of_2(nor->page_size)) {
1474                         page_offset = addr & (nor->page_size - 1);
1475                 } else {
1476                         u64 aux = addr;
1477
1478                         page_offset = do_div(aux, nor->page_size);
1479                 }
1480                 /* the size of data remaining on the first page */
1481                 page_remain = min_t(size_t,
1482                                     nor->page_size - page_offset, len - i);
1483
1484 #ifdef CONFIG_SPI_FLASH_BAR
1485                 ret = write_bar(nor, addr);
1486                 if (ret < 0)
1487                         return ret;
1488 #endif
1489                 write_enable(nor);
1490                 ret = nor->write(nor, addr, page_remain, buf + i);
1491                 if (ret < 0)
1492                         goto write_err;
1493                 written = ret;
1494
1495                 ret = spi_nor_wait_till_ready(nor);
1496                 if (ret)
1497                         goto write_err;
1498                 *retlen += written;
1499                 i += written;
1500         }
1501
1502 write_err:
1503 #ifdef CONFIG_SPI_FLASH_BAR
1504         ret = clean_bar(nor);
1505 #endif
1506         return ret;
1507 }
1508
1509 #if defined(CONFIG_SPI_FLASH_MACRONIX) || defined(CONFIG_SPI_FLASH_ISSI)
1510 /**
1511  * macronix_quad_enable() - set QE bit in Status Register.
1512  * @nor:        pointer to a 'struct spi_nor'
1513  *
1514  * Set the Quad Enable (QE) bit in the Status Register.
1515  *
1516  * bit 6 of the Status Register is the QE bit for Macronix like QSPI memories.
1517  *
1518  * Return: 0 on success, -errno otherwise.
1519  */
1520 static int macronix_quad_enable(struct spi_nor *nor)
1521 {
1522         int ret, val;
1523
1524         val = read_sr(nor);
1525         if (val < 0)
1526                 return val;
1527         if (val & SR_QUAD_EN_MX)
1528                 return 0;
1529
1530         write_enable(nor);
1531
1532         write_sr(nor, val | SR_QUAD_EN_MX);
1533
1534         ret = spi_nor_wait_till_ready(nor);
1535         if (ret)
1536                 return ret;
1537
1538         ret = read_sr(nor);
1539         if (!(ret > 0 && (ret & SR_QUAD_EN_MX))) {
1540                 dev_err(nor->dev, "Macronix Quad bit not set\n");
1541                 return -EINVAL;
1542         }
1543
1544         return 0;
1545 }
1546 #endif
1547
1548 #if defined(CONFIG_SPI_FLASH_SPANSION) || defined(CONFIG_SPI_FLASH_WINBOND)
1549 /*
1550  * Write status Register and configuration register with 2 bytes
1551  * The first byte will be written to the status register, while the
1552  * second byte will be written to the configuration register.
1553  * Return negative if error occurred.
1554  */
1555 static int write_sr_cr(struct spi_nor *nor, u8 *sr_cr)
1556 {
1557         int ret;
1558
1559         write_enable(nor);
1560
1561         ret = nor->write_reg(nor, SPINOR_OP_WRSR, sr_cr, 2);
1562         if (ret < 0) {
1563                 dev_dbg(nor->dev,
1564                         "error while writing configuration register\n");
1565                 return -EINVAL;
1566         }
1567
1568         ret = spi_nor_wait_till_ready(nor);
1569         if (ret) {
1570                 dev_dbg(nor->dev,
1571                         "timeout while writing configuration register\n");
1572                 return ret;
1573         }
1574
1575         return 0;
1576 }
1577
1578 /**
1579  * spansion_read_cr_quad_enable() - set QE bit in Configuration Register.
1580  * @nor:        pointer to a 'struct spi_nor'
1581  *
1582  * Set the Quad Enable (QE) bit in the Configuration Register.
1583  * This function should be used with QSPI memories supporting the Read
1584  * Configuration Register (35h) instruction.
1585  *
1586  * bit 1 of the Configuration Register is the QE bit for Spansion like QSPI
1587  * memories.
1588  *
1589  * Return: 0 on success, -errno otherwise.
1590  */
1591 static int spansion_read_cr_quad_enable(struct spi_nor *nor)
1592 {
1593         u8 sr_cr[2];
1594         int ret;
1595
1596         /* Check current Quad Enable bit value. */
1597         ret = read_cr(nor);
1598         if (ret < 0) {
1599                 dev_dbg(nor->dev,
1600                         "error while reading configuration register\n");
1601                 return -EINVAL;
1602         }
1603
1604         if (ret & CR_QUAD_EN_SPAN)
1605                 return 0;
1606
1607         sr_cr[1] = ret | CR_QUAD_EN_SPAN;
1608
1609         /* Keep the current value of the Status Register. */
1610         ret = read_sr(nor);
1611         if (ret < 0) {
1612                 dev_dbg(nor->dev, "error while reading status register\n");
1613                 return -EINVAL;
1614         }
1615         sr_cr[0] = ret;
1616
1617         ret = write_sr_cr(nor, sr_cr);
1618         if (ret)
1619                 return ret;
1620
1621         /* Read back and check it. */
1622         ret = read_cr(nor);
1623         if (!(ret > 0 && (ret & CR_QUAD_EN_SPAN))) {
1624                 dev_dbg(nor->dev, "Spansion Quad bit not set\n");
1625                 return -EINVAL;
1626         }
1627
1628         return 0;
1629 }
1630
1631 #if CONFIG_IS_ENABLED(SPI_FLASH_SFDP_SUPPORT)
1632 /**
1633  * spansion_no_read_cr_quad_enable() - set QE bit in Configuration Register.
1634  * @nor:        pointer to a 'struct spi_nor'
1635  *
1636  * Set the Quad Enable (QE) bit in the Configuration Register.
1637  * This function should be used with QSPI memories not supporting the Read
1638  * Configuration Register (35h) instruction.
1639  *
1640  * bit 1 of the Configuration Register is the QE bit for Spansion like QSPI
1641  * memories.
1642  *
1643  * Return: 0 on success, -errno otherwise.
1644  */
1645 static int spansion_no_read_cr_quad_enable(struct spi_nor *nor)
1646 {
1647         u8 sr_cr[2];
1648         int ret;
1649
1650         /* Keep the current value of the Status Register. */
1651         ret = read_sr(nor);
1652         if (ret < 0) {
1653                 dev_dbg(nor->dev, "error while reading status register\n");
1654                 return -EINVAL;
1655         }
1656         sr_cr[0] = ret;
1657         sr_cr[1] = CR_QUAD_EN_SPAN;
1658
1659         return write_sr_cr(nor, sr_cr);
1660 }
1661
1662 #endif /* CONFIG_SPI_FLASH_SFDP_SUPPORT */
1663 #endif /* CONFIG_SPI_FLASH_SPANSION */
1664
1665 static void
1666 spi_nor_set_read_settings(struct spi_nor_read_command *read,
1667                           u8 num_mode_clocks,
1668                           u8 num_wait_states,
1669                           u8 opcode,
1670                           enum spi_nor_protocol proto)
1671 {
1672         read->num_mode_clocks = num_mode_clocks;
1673         read->num_wait_states = num_wait_states;
1674         read->opcode = opcode;
1675         read->proto = proto;
1676 }
1677
1678 static void
1679 spi_nor_set_pp_settings(struct spi_nor_pp_command *pp,
1680                         u8 opcode,
1681                         enum spi_nor_protocol proto)
1682 {
1683         pp->opcode = opcode;
1684         pp->proto = proto;
1685 }
1686
1687 #if CONFIG_IS_ENABLED(SPI_FLASH_SFDP_SUPPORT)
1688 /*
1689  * Serial Flash Discoverable Parameters (SFDP) parsing.
1690  */
1691
1692 /**
1693  * spi_nor_read_sfdp() - read Serial Flash Discoverable Parameters.
1694  * @nor:        pointer to a 'struct spi_nor'
1695  * @addr:       offset in the SFDP area to start reading data from
1696  * @len:        number of bytes to read
1697  * @buf:        buffer where the SFDP data are copied into (dma-safe memory)
1698  *
1699  * Whatever the actual numbers of bytes for address and dummy cycles are
1700  * for (Fast) Read commands, the Read SFDP (5Ah) instruction is always
1701  * followed by a 3-byte address and 8 dummy clock cycles.
1702  *
1703  * Return: 0 on success, -errno otherwise.
1704  */
1705 static int spi_nor_read_sfdp(struct spi_nor *nor, u32 addr,
1706                              size_t len, void *buf)
1707 {
1708         u8 addr_width, read_opcode, read_dummy;
1709         int ret;
1710
1711         read_opcode = nor->read_opcode;
1712         addr_width = nor->addr_width;
1713         read_dummy = nor->read_dummy;
1714
1715         nor->read_opcode = SPINOR_OP_RDSFDP;
1716         nor->addr_width = 3;
1717         nor->read_dummy = 8;
1718
1719         while (len) {
1720                 ret = nor->read(nor, addr, len, (u8 *)buf);
1721                 if (!ret || ret > len) {
1722                         ret = -EIO;
1723                         goto read_err;
1724                 }
1725                 if (ret < 0)
1726                         goto read_err;
1727
1728                 buf += ret;
1729                 addr += ret;
1730                 len -= ret;
1731         }
1732         ret = 0;
1733
1734 read_err:
1735         nor->read_opcode = read_opcode;
1736         nor->addr_width = addr_width;
1737         nor->read_dummy = read_dummy;
1738
1739         return ret;
1740 }
1741
1742 /* Fast Read settings. */
1743
1744 static void
1745 spi_nor_set_read_settings_from_bfpt(struct spi_nor_read_command *read,
1746                                     u16 half,
1747                                     enum spi_nor_protocol proto)
1748 {
1749         read->num_mode_clocks = (half >> 5) & 0x07;
1750         read->num_wait_states = (half >> 0) & 0x1f;
1751         read->opcode = (half >> 8) & 0xff;
1752         read->proto = proto;
1753 }
1754
1755 struct sfdp_bfpt_read {
1756         /* The Fast Read x-y-z hardware capability in params->hwcaps.mask. */
1757         u32                     hwcaps;
1758
1759         /*
1760          * The <supported_bit> bit in <supported_dword> BFPT DWORD tells us
1761          * whether the Fast Read x-y-z command is supported.
1762          */
1763         u32                     supported_dword;
1764         u32                     supported_bit;
1765
1766         /*
1767          * The half-word at offset <setting_shift> in <setting_dword> BFPT DWORD
1768          * encodes the op code, the number of mode clocks and the number of wait
1769          * states to be used by Fast Read x-y-z command.
1770          */
1771         u32                     settings_dword;
1772         u32                     settings_shift;
1773
1774         /* The SPI protocol for this Fast Read x-y-z command. */
1775         enum spi_nor_protocol   proto;
1776 };
1777
1778 static const struct sfdp_bfpt_read sfdp_bfpt_reads[] = {
1779         /* Fast Read 1-1-2 */
1780         {
1781                 SNOR_HWCAPS_READ_1_1_2,
1782                 BFPT_DWORD(1), BIT(16), /* Supported bit */
1783                 BFPT_DWORD(4), 0,       /* Settings */
1784                 SNOR_PROTO_1_1_2,
1785         },
1786
1787         /* Fast Read 1-2-2 */
1788         {
1789                 SNOR_HWCAPS_READ_1_2_2,
1790                 BFPT_DWORD(1), BIT(20), /* Supported bit */
1791                 BFPT_DWORD(4), 16,      /* Settings */
1792                 SNOR_PROTO_1_2_2,
1793         },
1794
1795         /* Fast Read 2-2-2 */
1796         {
1797                 SNOR_HWCAPS_READ_2_2_2,
1798                 BFPT_DWORD(5),  BIT(0), /* Supported bit */
1799                 BFPT_DWORD(6), 16,      /* Settings */
1800                 SNOR_PROTO_2_2_2,
1801         },
1802
1803         /* Fast Read 1-1-4 */
1804         {
1805                 SNOR_HWCAPS_READ_1_1_4,
1806                 BFPT_DWORD(1), BIT(22), /* Supported bit */
1807                 BFPT_DWORD(3), 16,      /* Settings */
1808                 SNOR_PROTO_1_1_4,
1809         },
1810
1811         /* Fast Read 1-4-4 */
1812         {
1813                 SNOR_HWCAPS_READ_1_4_4,
1814                 BFPT_DWORD(1), BIT(21), /* Supported bit */
1815                 BFPT_DWORD(3), 0,       /* Settings */
1816                 SNOR_PROTO_1_4_4,
1817         },
1818
1819         /* Fast Read 4-4-4 */
1820         {
1821                 SNOR_HWCAPS_READ_4_4_4,
1822                 BFPT_DWORD(5), BIT(4),  /* Supported bit */
1823                 BFPT_DWORD(7), 16,      /* Settings */
1824                 SNOR_PROTO_4_4_4,
1825         },
1826 };
1827
1828 struct sfdp_bfpt_erase {
1829         /*
1830          * The half-word at offset <shift> in DWORD <dwoard> encodes the
1831          * op code and erase sector size to be used by Sector Erase commands.
1832          */
1833         u32                     dword;
1834         u32                     shift;
1835 };
1836
1837 static const struct sfdp_bfpt_erase sfdp_bfpt_erases[] = {
1838         /* Erase Type 1 in DWORD8 bits[15:0] */
1839         {BFPT_DWORD(8), 0},
1840
1841         /* Erase Type 2 in DWORD8 bits[31:16] */
1842         {BFPT_DWORD(8), 16},
1843
1844         /* Erase Type 3 in DWORD9 bits[15:0] */
1845         {BFPT_DWORD(9), 0},
1846
1847         /* Erase Type 4 in DWORD9 bits[31:16] */
1848         {BFPT_DWORD(9), 16},
1849 };
1850
1851 static int spi_nor_hwcaps_read2cmd(u32 hwcaps);
1852
1853 static int
1854 spi_nor_post_bfpt_fixups(struct spi_nor *nor,
1855                          const struct sfdp_parameter_header *bfpt_header,
1856                          const struct sfdp_bfpt *bfpt,
1857                          struct spi_nor_flash_parameter *params)
1858 {
1859         if (nor->fixups && nor->fixups->post_bfpt)
1860                 return nor->fixups->post_bfpt(nor, bfpt_header, bfpt, params);
1861
1862         return 0;
1863 }
1864
1865 /**
1866  * spi_nor_parse_bfpt() - read and parse the Basic Flash Parameter Table.
1867  * @nor:                pointer to a 'struct spi_nor'
1868  * @bfpt_header:        pointer to the 'struct sfdp_parameter_header' describing
1869  *                      the Basic Flash Parameter Table length and version
1870  * @params:             pointer to the 'struct spi_nor_flash_parameter' to be
1871  *                      filled
1872  *
1873  * The Basic Flash Parameter Table is the main and only mandatory table as
1874  * defined by the SFDP (JESD216) specification.
1875  * It provides us with the total size (memory density) of the data array and
1876  * the number of address bytes for Fast Read, Page Program and Sector Erase
1877  * commands.
1878  * For Fast READ commands, it also gives the number of mode clock cycles and
1879  * wait states (regrouped in the number of dummy clock cycles) for each
1880  * supported instruction op code.
1881  * For Page Program, the page size is now available since JESD216 rev A, however
1882  * the supported instruction op codes are still not provided.
1883  * For Sector Erase commands, this table stores the supported instruction op
1884  * codes and the associated sector sizes.
1885  * Finally, the Quad Enable Requirements (QER) are also available since JESD216
1886  * rev A. The QER bits encode the manufacturer dependent procedure to be
1887  * executed to set the Quad Enable (QE) bit in some internal register of the
1888  * Quad SPI memory. Indeed the QE bit, when it exists, must be set before
1889  * sending any Quad SPI command to the memory. Actually, setting the QE bit
1890  * tells the memory to reassign its WP# and HOLD#/RESET# pins to functions IO2
1891  * and IO3 hence enabling 4 (Quad) I/O lines.
1892  *
1893  * Return: 0 on success, -errno otherwise.
1894  */
1895 static int spi_nor_parse_bfpt(struct spi_nor *nor,
1896                               const struct sfdp_parameter_header *bfpt_header,
1897                               struct spi_nor_flash_parameter *params)
1898 {
1899         struct mtd_info *mtd = &nor->mtd;
1900         struct sfdp_bfpt bfpt;
1901         size_t len;
1902         int i, cmd, err;
1903         u32 addr;
1904         u16 half;
1905
1906         /* JESD216 Basic Flash Parameter Table length is at least 9 DWORDs. */
1907         if (bfpt_header->length < BFPT_DWORD_MAX_JESD216)
1908                 return -EINVAL;
1909
1910         /* Read the Basic Flash Parameter Table. */
1911         len = min_t(size_t, sizeof(bfpt),
1912                     bfpt_header->length * sizeof(u32));
1913         addr = SFDP_PARAM_HEADER_PTP(bfpt_header);
1914         memset(&bfpt, 0, sizeof(bfpt));
1915         err = spi_nor_read_sfdp(nor,  addr, len, &bfpt);
1916         if (err < 0)
1917                 return err;
1918
1919         /* Fix endianness of the BFPT DWORDs. */
1920         for (i = 0; i < BFPT_DWORD_MAX; i++)
1921                 bfpt.dwords[i] = le32_to_cpu(bfpt.dwords[i]);
1922
1923         /* Number of address bytes. */
1924         switch (bfpt.dwords[BFPT_DWORD(1)] & BFPT_DWORD1_ADDRESS_BYTES_MASK) {
1925         case BFPT_DWORD1_ADDRESS_BYTES_3_ONLY:
1926                 nor->addr_width = 3;
1927                 break;
1928
1929         case BFPT_DWORD1_ADDRESS_BYTES_4_ONLY:
1930                 nor->addr_width = 4;
1931                 break;
1932
1933         default:
1934                 break;
1935         }
1936
1937         /* Flash Memory Density (in bits). */
1938         params->size = bfpt.dwords[BFPT_DWORD(2)];
1939         if (params->size & BIT(31)) {
1940                 params->size &= ~BIT(31);
1941
1942                 /*
1943                  * Prevent overflows on params->size. Anyway, a NOR of 2^64
1944                  * bits is unlikely to exist so this error probably means
1945                  * the BFPT we are reading is corrupted/wrong.
1946                  */
1947                 if (params->size > 63)
1948                         return -EINVAL;
1949
1950                 params->size = 1ULL << params->size;
1951         } else {
1952                 params->size++;
1953         }
1954         params->size >>= 3; /* Convert to bytes. */
1955
1956         /* Fast Read settings. */
1957         for (i = 0; i < ARRAY_SIZE(sfdp_bfpt_reads); i++) {
1958                 const struct sfdp_bfpt_read *rd = &sfdp_bfpt_reads[i];
1959                 struct spi_nor_read_command *read;
1960
1961                 if (!(bfpt.dwords[rd->supported_dword] & rd->supported_bit)) {
1962                         params->hwcaps.mask &= ~rd->hwcaps;
1963                         continue;
1964                 }
1965
1966                 params->hwcaps.mask |= rd->hwcaps;
1967                 cmd = spi_nor_hwcaps_read2cmd(rd->hwcaps);
1968                 read = &params->reads[cmd];
1969                 half = bfpt.dwords[rd->settings_dword] >> rd->settings_shift;
1970                 spi_nor_set_read_settings_from_bfpt(read, half, rd->proto);
1971         }
1972
1973         /* Sector Erase settings. */
1974         for (i = 0; i < ARRAY_SIZE(sfdp_bfpt_erases); i++) {
1975                 const struct sfdp_bfpt_erase *er = &sfdp_bfpt_erases[i];
1976                 u32 erasesize;
1977                 u8 opcode;
1978
1979                 half = bfpt.dwords[er->dword] >> er->shift;
1980                 erasesize = half & 0xff;
1981
1982                 /* erasesize == 0 means this Erase Type is not supported. */
1983                 if (!erasesize)
1984                         continue;
1985
1986                 erasesize = 1U << erasesize;
1987                 opcode = (half >> 8) & 0xff;
1988 #ifdef CONFIG_SPI_FLASH_USE_4K_SECTORS
1989                 if (erasesize == SZ_4K) {
1990                         nor->erase_opcode = opcode;
1991                         mtd->erasesize = erasesize;
1992                         break;
1993                 }
1994 #endif
1995                 if (!mtd->erasesize || mtd->erasesize < erasesize) {
1996                         nor->erase_opcode = opcode;
1997                         mtd->erasesize = erasesize;
1998                 }
1999         }
2000
2001         /* Stop here if not JESD216 rev A or later. */
2002         if (bfpt_header->length < BFPT_DWORD_MAX)
2003                 return spi_nor_post_bfpt_fixups(nor, bfpt_header, &bfpt,
2004                                                 params);
2005
2006         /* Page size: this field specifies 'N' so the page size = 2^N bytes. */
2007         params->page_size = bfpt.dwords[BFPT_DWORD(11)];
2008         params->page_size &= BFPT_DWORD11_PAGE_SIZE_MASK;
2009         params->page_size >>= BFPT_DWORD11_PAGE_SIZE_SHIFT;
2010         params->page_size = 1U << params->page_size;
2011
2012         /* Quad Enable Requirements. */
2013         switch (bfpt.dwords[BFPT_DWORD(15)] & BFPT_DWORD15_QER_MASK) {
2014         case BFPT_DWORD15_QER_NONE:
2015                 params->quad_enable = NULL;
2016                 break;
2017 #if defined(CONFIG_SPI_FLASH_SPANSION) || defined(CONFIG_SPI_FLASH_WINBOND)
2018         case BFPT_DWORD15_QER_SR2_BIT1_BUGGY:
2019         case BFPT_DWORD15_QER_SR2_BIT1_NO_RD:
2020                 params->quad_enable = spansion_no_read_cr_quad_enable;
2021                 break;
2022 #endif
2023 #if defined(CONFIG_SPI_FLASH_MACRONIX) || defined(CONFIG_SPI_FLASH_ISSI)
2024         case BFPT_DWORD15_QER_SR1_BIT6:
2025                 params->quad_enable = macronix_quad_enable;
2026                 break;
2027 #endif
2028 #if defined(CONFIG_SPI_FLASH_SPANSION) || defined(CONFIG_SPI_FLASH_WINBOND)
2029         case BFPT_DWORD15_QER_SR2_BIT1:
2030                 params->quad_enable = spansion_read_cr_quad_enable;
2031                 break;
2032 #endif
2033         default:
2034                 return -EINVAL;
2035         }
2036
2037         return spi_nor_post_bfpt_fixups(nor, bfpt_header, &bfpt, params);
2038 }
2039
2040 /**
2041  * spi_nor_parse_microchip_sfdp() - parse the Microchip manufacturer specific
2042  * SFDP table.
2043  * @nor:                pointer to a 'struct spi_nor'.
2044  * @param_header:       pointer to the SFDP parameter header.
2045  *
2046  * Return: 0 on success, -errno otherwise.
2047  */
2048 static int
2049 spi_nor_parse_microchip_sfdp(struct spi_nor *nor,
2050                              const struct sfdp_parameter_header *param_header)
2051 {
2052         size_t size;
2053         u32 addr;
2054         int ret;
2055
2056         size = param_header->length * sizeof(u32);
2057         addr = SFDP_PARAM_HEADER_PTP(param_header);
2058
2059         nor->manufacturer_sfdp = devm_kmalloc(nor->dev, size, GFP_KERNEL);
2060         if (!nor->manufacturer_sfdp)
2061                 return -ENOMEM;
2062
2063         ret = spi_nor_read_sfdp(nor, addr, size, nor->manufacturer_sfdp);
2064
2065         return ret;
2066 }
2067
2068 /**
2069  * spi_nor_parse_sfdp() - parse the Serial Flash Discoverable Parameters.
2070  * @nor:                pointer to a 'struct spi_nor'
2071  * @params:             pointer to the 'struct spi_nor_flash_parameter' to be
2072  *                      filled
2073  *
2074  * The Serial Flash Discoverable Parameters are described by the JEDEC JESD216
2075  * specification. This is a standard which tends to supported by almost all
2076  * (Q)SPI memory manufacturers. Those hard-coded tables allow us to learn at
2077  * runtime the main parameters needed to perform basic SPI flash operations such
2078  * as Fast Read, Page Program or Sector Erase commands.
2079  *
2080  * Return: 0 on success, -errno otherwise.
2081  */
2082 static int spi_nor_parse_sfdp(struct spi_nor *nor,
2083                               struct spi_nor_flash_parameter *params)
2084 {
2085         const struct sfdp_parameter_header *param_header, *bfpt_header;
2086         struct sfdp_parameter_header *param_headers = NULL;
2087         struct sfdp_header header;
2088         size_t psize;
2089         int i, err;
2090
2091         /* Get the SFDP header. */
2092         err = spi_nor_read_sfdp(nor, 0, sizeof(header), &header);
2093         if (err < 0)
2094                 return err;
2095
2096         /* Check the SFDP header version. */
2097         if (le32_to_cpu(header.signature) != SFDP_SIGNATURE ||
2098             header.major != SFDP_JESD216_MAJOR)
2099                 return -EINVAL;
2100
2101         /*
2102          * Verify that the first and only mandatory parameter header is a
2103          * Basic Flash Parameter Table header as specified in JESD216.
2104          */
2105         bfpt_header = &header.bfpt_header;
2106         if (SFDP_PARAM_HEADER_ID(bfpt_header) != SFDP_BFPT_ID ||
2107             bfpt_header->major != SFDP_JESD216_MAJOR)
2108                 return -EINVAL;
2109
2110         /*
2111          * Allocate memory then read all parameter headers with a single
2112          * Read SFDP command. These parameter headers will actually be parsed
2113          * twice: a first time to get the latest revision of the basic flash
2114          * parameter table, then a second time to handle the supported optional
2115          * tables.
2116          * Hence we read the parameter headers once for all to reduce the
2117          * processing time. Also we use kmalloc() instead of devm_kmalloc()
2118          * because we don't need to keep these parameter headers: the allocated
2119          * memory is always released with kfree() before exiting this function.
2120          */
2121         if (header.nph) {
2122                 psize = header.nph * sizeof(*param_headers);
2123
2124                 param_headers = kmalloc(psize, GFP_KERNEL);
2125                 if (!param_headers)
2126                         return -ENOMEM;
2127
2128                 err = spi_nor_read_sfdp(nor, sizeof(header),
2129                                         psize, param_headers);
2130                 if (err < 0) {
2131                         dev_err(nor->dev,
2132                                 "failed to read SFDP parameter headers\n");
2133                         goto exit;
2134                 }
2135         }
2136
2137         /*
2138          * Check other parameter headers to get the latest revision of
2139          * the basic flash parameter table.
2140          */
2141         for (i = 0; i < header.nph; i++) {
2142                 param_header = &param_headers[i];
2143
2144                 if (SFDP_PARAM_HEADER_ID(param_header) == SFDP_BFPT_ID &&
2145                     param_header->major == SFDP_JESD216_MAJOR &&
2146                     (param_header->minor > bfpt_header->minor ||
2147                      (param_header->minor == bfpt_header->minor &&
2148                       param_header->length > bfpt_header->length)))
2149                         bfpt_header = param_header;
2150         }
2151
2152         err = spi_nor_parse_bfpt(nor, bfpt_header, params);
2153         if (err)
2154                 goto exit;
2155
2156         /* Parse other parameter headers. */
2157         for (i = 0; i < header.nph; i++) {
2158                 param_header = &param_headers[i];
2159
2160                 switch (SFDP_PARAM_HEADER_ID(param_header)) {
2161                 case SFDP_SECTOR_MAP_ID:
2162                         dev_info(nor->dev,
2163                                  "non-uniform erase sector maps are not supported yet.\n");
2164                         break;
2165
2166                 case SFDP_SST_ID:
2167                         err = spi_nor_parse_microchip_sfdp(nor, param_header);
2168                         break;
2169
2170                 default:
2171                         break;
2172                 }
2173
2174                 if (err) {
2175                         dev_warn(nor->dev,
2176                                  "Failed to parse optional parameter table: %04x\n",
2177                                  SFDP_PARAM_HEADER_ID(param_header));
2178                         /*
2179                          * Let's not drop all information we extracted so far
2180                          * if optional table parsers fail. In case of failing,
2181                          * each optional parser is responsible to roll back to
2182                          * the previously known spi_nor data.
2183                          */
2184                         err = 0;
2185                 }
2186         }
2187
2188 exit:
2189         kfree(param_headers);
2190         return err;
2191 }
2192 #else
2193 static int spi_nor_parse_sfdp(struct spi_nor *nor,
2194                               struct spi_nor_flash_parameter *params)
2195 {
2196         return -EINVAL;
2197 }
2198 #endif /* SPI_FLASH_SFDP_SUPPORT */
2199
2200 /**
2201  * spi_nor_post_sfdp_fixups() - Updates the flash's parameters and settings
2202  * after SFDP has been parsed (is also called for SPI NORs that do not
2203  * support RDSFDP).
2204  * @nor:        pointer to a 'struct spi_nor'
2205  *
2206  * Typically used to tweak various parameters that could not be extracted by
2207  * other means (i.e. when information provided by the SFDP/flash_info tables
2208  * are incomplete or wrong).
2209  */
2210 static void spi_nor_post_sfdp_fixups(struct spi_nor *nor,
2211                                      struct spi_nor_flash_parameter *params)
2212 {
2213         if (nor->fixups && nor->fixups->post_sfdp)
2214                 nor->fixups->post_sfdp(nor, params);
2215 }
2216
2217 static void spi_nor_default_init_fixups(struct spi_nor *nor)
2218 {
2219         if (nor->fixups && nor->fixups->default_init)
2220                 nor->fixups->default_init(nor);
2221 }
2222
2223 static int spi_nor_init_params(struct spi_nor *nor,
2224                                const struct flash_info *info,
2225                                struct spi_nor_flash_parameter *params)
2226 {
2227         /* Set legacy flash parameters as default. */
2228         memset(params, 0, sizeof(*params));
2229
2230         /* Set SPI NOR sizes. */
2231         params->size = info->sector_size * info->n_sectors;
2232         params->page_size = info->page_size;
2233
2234         /* (Fast) Read settings. */
2235         params->hwcaps.mask |= SNOR_HWCAPS_READ;
2236         spi_nor_set_read_settings(&params->reads[SNOR_CMD_READ],
2237                                   0, 0, SPINOR_OP_READ,
2238                                   SNOR_PROTO_1_1_1);
2239
2240         if (!(info->flags & SPI_NOR_NO_FR)) {
2241                 params->hwcaps.mask |= SNOR_HWCAPS_READ_FAST;
2242                 spi_nor_set_read_settings(&params->reads[SNOR_CMD_READ_FAST],
2243                                           0, 8, SPINOR_OP_READ_FAST,
2244                                           SNOR_PROTO_1_1_1);
2245         }
2246
2247         if (info->flags & SPI_NOR_DUAL_READ) {
2248                 params->hwcaps.mask |= SNOR_HWCAPS_READ_1_1_2;
2249                 spi_nor_set_read_settings(&params->reads[SNOR_CMD_READ_1_1_2],
2250                                           0, 8, SPINOR_OP_READ_1_1_2,
2251                                           SNOR_PROTO_1_1_2);
2252         }
2253
2254         if (info->flags & SPI_NOR_QUAD_READ) {
2255                 params->hwcaps.mask |= SNOR_HWCAPS_READ_1_1_4;
2256                 spi_nor_set_read_settings(&params->reads[SNOR_CMD_READ_1_1_4],
2257                                           0, 8, SPINOR_OP_READ_1_1_4,
2258                                           SNOR_PROTO_1_1_4);
2259         }
2260
2261         if (info->flags & SPI_NOR_OCTAL_READ) {
2262                 params->hwcaps.mask |= SNOR_HWCAPS_READ_1_1_8;
2263                 spi_nor_set_read_settings(&params->reads[SNOR_CMD_READ_1_1_8],
2264                                           0, 8, SPINOR_OP_READ_1_1_8,
2265                                           SNOR_PROTO_1_1_8);
2266         }
2267
2268         if (info->flags & SPI_NOR_OCTAL_DTR_READ) {
2269                 params->hwcaps.mask |= SNOR_HWCAPS_READ_8_8_8_DTR;
2270                 spi_nor_set_read_settings(&params->reads[SNOR_CMD_READ_8_8_8_DTR],
2271                                           0, 20, SPINOR_OP_READ_FAST,
2272                                           SNOR_PROTO_8_8_8_DTR);
2273         }
2274
2275         /* Page Program settings. */
2276         params->hwcaps.mask |= SNOR_HWCAPS_PP;
2277         spi_nor_set_pp_settings(&params->page_programs[SNOR_CMD_PP],
2278                                 SPINOR_OP_PP, SNOR_PROTO_1_1_1);
2279
2280         /*
2281          * Since xSPI Page Program opcode is backward compatible with
2282          * Legacy SPI, use Legacy SPI opcode there as well.
2283          */
2284         spi_nor_set_pp_settings(&params->page_programs[SNOR_CMD_PP_8_8_8_DTR],
2285                                 SPINOR_OP_PP, SNOR_PROTO_8_8_8_DTR);
2286
2287         if (info->flags & SPI_NOR_QUAD_READ) {
2288                 params->hwcaps.mask |= SNOR_HWCAPS_PP_1_1_4;
2289                 spi_nor_set_pp_settings(&params->page_programs[SNOR_CMD_PP_1_1_4],
2290                                         SPINOR_OP_PP_1_1_4, SNOR_PROTO_1_1_4);
2291         }
2292
2293         /* Select the procedure to set the Quad Enable bit. */
2294         if (params->hwcaps.mask & (SNOR_HWCAPS_READ_QUAD |
2295                                    SNOR_HWCAPS_PP_QUAD)) {
2296                 switch (JEDEC_MFR(info)) {
2297 #if defined(CONFIG_SPI_FLASH_MACRONIX) || defined(CONFIG_SPI_FLASH_ISSI)
2298                 case SNOR_MFR_MACRONIX:
2299                 case SNOR_MFR_ISSI:
2300                         params->quad_enable = macronix_quad_enable;
2301                         break;
2302 #endif
2303                 case SNOR_MFR_ST:
2304                 case SNOR_MFR_MICRON:
2305                         break;
2306
2307                 default:
2308 #if defined(CONFIG_SPI_FLASH_SPANSION) || defined(CONFIG_SPI_FLASH_WINBOND)
2309                         /* Kept only for backward compatibility purpose. */
2310                         params->quad_enable = spansion_read_cr_quad_enable;
2311 #endif
2312                         break;
2313                 }
2314         }
2315
2316         spi_nor_default_init_fixups(nor);
2317
2318         /* Override the parameters with data read from SFDP tables. */
2319         nor->addr_width = 0;
2320         nor->mtd.erasesize = 0;
2321         if ((info->flags & (SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ |
2322              SPI_NOR_OCTAL_DTR_READ)) &&
2323             !(info->flags & SPI_NOR_SKIP_SFDP)) {
2324                 struct spi_nor_flash_parameter sfdp_params;
2325
2326                 memcpy(&sfdp_params, params, sizeof(sfdp_params));
2327                 if (spi_nor_parse_sfdp(nor, &sfdp_params)) {
2328                         nor->addr_width = 0;
2329                         nor->mtd.erasesize = 0;
2330                 } else {
2331                         memcpy(params, &sfdp_params, sizeof(*params));
2332                 }
2333         }
2334
2335         spi_nor_post_sfdp_fixups(nor, params);
2336
2337         return 0;
2338 }
2339
2340 static int spi_nor_hwcaps2cmd(u32 hwcaps, const int table[][2], size_t size)
2341 {
2342         size_t i;
2343
2344         for (i = 0; i < size; i++)
2345                 if (table[i][0] == (int)hwcaps)
2346                         return table[i][1];
2347
2348         return -EINVAL;
2349 }
2350
2351 static int spi_nor_hwcaps_read2cmd(u32 hwcaps)
2352 {
2353         static const int hwcaps_read2cmd[][2] = {
2354                 { SNOR_HWCAPS_READ,             SNOR_CMD_READ },
2355                 { SNOR_HWCAPS_READ_FAST,        SNOR_CMD_READ_FAST },
2356                 { SNOR_HWCAPS_READ_1_1_1_DTR,   SNOR_CMD_READ_1_1_1_DTR },
2357                 { SNOR_HWCAPS_READ_1_1_2,       SNOR_CMD_READ_1_1_2 },
2358                 { SNOR_HWCAPS_READ_1_2_2,       SNOR_CMD_READ_1_2_2 },
2359                 { SNOR_HWCAPS_READ_2_2_2,       SNOR_CMD_READ_2_2_2 },
2360                 { SNOR_HWCAPS_READ_1_2_2_DTR,   SNOR_CMD_READ_1_2_2_DTR },
2361                 { SNOR_HWCAPS_READ_1_1_4,       SNOR_CMD_READ_1_1_4 },
2362                 { SNOR_HWCAPS_READ_1_4_4,       SNOR_CMD_READ_1_4_4 },
2363                 { SNOR_HWCAPS_READ_4_4_4,       SNOR_CMD_READ_4_4_4 },
2364                 { SNOR_HWCAPS_READ_1_4_4_DTR,   SNOR_CMD_READ_1_4_4_DTR },
2365                 { SNOR_HWCAPS_READ_1_1_8,       SNOR_CMD_READ_1_1_8 },
2366                 { SNOR_HWCAPS_READ_1_8_8,       SNOR_CMD_READ_1_8_8 },
2367                 { SNOR_HWCAPS_READ_8_8_8,       SNOR_CMD_READ_8_8_8 },
2368                 { SNOR_HWCAPS_READ_1_8_8_DTR,   SNOR_CMD_READ_1_8_8_DTR },
2369                 { SNOR_HWCAPS_READ_8_8_8_DTR,   SNOR_CMD_READ_8_8_8_DTR },
2370         };
2371
2372         return spi_nor_hwcaps2cmd(hwcaps, hwcaps_read2cmd,
2373                                   ARRAY_SIZE(hwcaps_read2cmd));
2374 }
2375
2376 static int spi_nor_hwcaps_pp2cmd(u32 hwcaps)
2377 {
2378         static const int hwcaps_pp2cmd[][2] = {
2379                 { SNOR_HWCAPS_PP,               SNOR_CMD_PP },
2380                 { SNOR_HWCAPS_PP_1_1_4,         SNOR_CMD_PP_1_1_4 },
2381                 { SNOR_HWCAPS_PP_1_4_4,         SNOR_CMD_PP_1_4_4 },
2382                 { SNOR_HWCAPS_PP_4_4_4,         SNOR_CMD_PP_4_4_4 },
2383                 { SNOR_HWCAPS_PP_1_1_8,         SNOR_CMD_PP_1_1_8 },
2384                 { SNOR_HWCAPS_PP_1_8_8,         SNOR_CMD_PP_1_8_8 },
2385                 { SNOR_HWCAPS_PP_8_8_8,         SNOR_CMD_PP_8_8_8 },
2386                 { SNOR_HWCAPS_PP_8_8_8_DTR,     SNOR_CMD_PP_8_8_8_DTR },
2387         };
2388
2389         return spi_nor_hwcaps2cmd(hwcaps, hwcaps_pp2cmd,
2390                                   ARRAY_SIZE(hwcaps_pp2cmd));
2391 }
2392
2393 #ifdef CONFIG_SPI_FLASH_SMART_HWCAPS
2394 /**
2395  * spi_nor_check_op - check if the operation is supported by controller
2396  * @nor:        pointer to a 'struct spi_nor'
2397  * @op:         pointer to op template to be checked
2398  *
2399  * Returns 0 if operation is supported, -ENOTSUPP otherwise.
2400  */
2401 static int spi_nor_check_op(struct spi_nor *nor,
2402                             struct spi_mem_op *op)
2403 {
2404         /*
2405          * First test with 4 address bytes. The opcode itself might be a 3B
2406          * addressing opcode but we don't care, because SPI controller
2407          * implementation should not check the opcode, but just the sequence.
2408          */
2409         op->addr.nbytes = 4;
2410         if (!spi_mem_supports_op(nor->spi, op)) {
2411                 if (nor->mtd.size > SZ_16M)
2412                         return -ENOTSUPP;
2413
2414                 /* If flash size <= 16MB, 3 address bytes are sufficient */
2415                 op->addr.nbytes = 3;
2416                 if (!spi_mem_supports_op(nor->spi, op))
2417                         return -ENOTSUPP;
2418         }
2419
2420         return 0;
2421 }
2422
2423 /**
2424  * spi_nor_check_readop - check if the read op is supported by controller
2425  * @nor:         pointer to a 'struct spi_nor'
2426  * @read:        pointer to op template to be checked
2427  *
2428  * Returns 0 if operation is supported, -ENOTSUPP otherwise.
2429  */
2430 static int spi_nor_check_readop(struct spi_nor *nor,
2431                                 const struct spi_nor_read_command *read)
2432 {
2433         struct spi_mem_op op = SPI_MEM_OP(SPI_MEM_OP_CMD(read->opcode, 0),
2434                                           SPI_MEM_OP_ADDR(3, 0, 0),
2435                                           SPI_MEM_OP_DUMMY(1, 0),
2436                                           SPI_MEM_OP_DATA_IN(2, NULL, 0));
2437
2438         spi_nor_setup_op(nor, &op, read->proto);
2439
2440         op.dummy.nbytes = (read->num_mode_clocks + read->num_wait_states) *
2441                           op.dummy.buswidth / 8;
2442         if (spi_nor_protocol_is_dtr(nor->read_proto))
2443                 op.dummy.nbytes *= 2;
2444
2445         return spi_nor_check_op(nor, &op);
2446 }
2447
2448 /**
2449  * spi_nor_check_pp - check if the page program op is supported by controller
2450  * @nor:         pointer to a 'struct spi_nor'
2451  * @pp:          pointer to op template to be checked
2452  *
2453  * Returns 0 if operation is supported, -ENOTSUPP otherwise.
2454  */
2455 static int spi_nor_check_pp(struct spi_nor *nor,
2456                             const struct spi_nor_pp_command *pp)
2457 {
2458         struct spi_mem_op op = SPI_MEM_OP(SPI_MEM_OP_CMD(pp->opcode, 0),
2459                                           SPI_MEM_OP_ADDR(3, 0, 0),
2460                                           SPI_MEM_OP_NO_DUMMY,
2461                                           SPI_MEM_OP_DATA_OUT(2, NULL, 0));
2462
2463         spi_nor_setup_op(nor, &op, pp->proto);
2464
2465         return spi_nor_check_op(nor, &op);
2466 }
2467
2468 /**
2469  * spi_nor_adjust_hwcaps - Find optimal Read/Write protocol based on SPI
2470  *                         controller capabilities
2471  * @nor:        pointer to a 'struct spi_nor'
2472  * @params:     pointer to the 'struct spi_nor_flash_parameter'
2473  *              representing SPI NOR flash capabilities
2474  * @hwcaps:     pointer to resulting capabilities after adjusting
2475  *              according to controller and flash's capability
2476  *
2477  * Discard caps based on what the SPI controller actually supports (using
2478  * spi_mem_supports_op()).
2479  */
2480 static void
2481 spi_nor_adjust_hwcaps(struct spi_nor *nor,
2482                       const struct spi_nor_flash_parameter *params,
2483                       u32 *hwcaps)
2484 {
2485         unsigned int cap;
2486
2487         /*
2488          * Enable all caps by default. We will mask them after checking what's
2489          * really supported using spi_mem_supports_op().
2490          */
2491         *hwcaps = SNOR_HWCAPS_ALL;
2492
2493         /* X-X-X modes are not supported yet, mask them all. */
2494         *hwcaps &= ~SNOR_HWCAPS_X_X_X;
2495
2496         /*
2497          * If the reset line is broken, we do not want to enter a stateful
2498          * mode.
2499          */
2500         if (nor->flags & SNOR_F_BROKEN_RESET)
2501                 *hwcaps &= ~(SNOR_HWCAPS_X_X_X | SNOR_HWCAPS_X_X_X_DTR);
2502
2503         for (cap = 0; cap < sizeof(*hwcaps) * BITS_PER_BYTE; cap++) {
2504                 int rdidx, ppidx;
2505
2506                 if (!(*hwcaps & BIT(cap)))
2507                         continue;
2508
2509                 rdidx = spi_nor_hwcaps_read2cmd(BIT(cap));
2510                 if (rdidx >= 0 &&
2511                     spi_nor_check_readop(nor, &params->reads[rdidx]))
2512                         *hwcaps &= ~BIT(cap);
2513
2514                 ppidx = spi_nor_hwcaps_pp2cmd(BIT(cap));
2515                 if (ppidx < 0)
2516                         continue;
2517
2518                 if (spi_nor_check_pp(nor, &params->page_programs[ppidx]))
2519                         *hwcaps &= ~BIT(cap);
2520         }
2521 }
2522 #else
2523 /**
2524  * spi_nor_adjust_hwcaps - Find optimal Read/Write protocol based on SPI
2525  *                         controller capabilities
2526  * @nor:        pointer to a 'struct spi_nor'
2527  * @params:     pointer to the 'struct spi_nor_flash_parameter'
2528  *              representing SPI NOR flash capabilities
2529  * @hwcaps:     pointer to resulting capabilities after adjusting
2530  *              according to controller and flash's capability
2531  *
2532  * Select caps based on what the SPI controller and SPI flash both support.
2533  */
2534 static void
2535 spi_nor_adjust_hwcaps(struct spi_nor *nor,
2536                       const struct spi_nor_flash_parameter *params,
2537                       u32 *hwcaps)
2538 {
2539         struct spi_slave *spi = nor->spi;
2540         u32 ignored_mask = (SNOR_HWCAPS_READ_2_2_2 |
2541                             SNOR_HWCAPS_READ_4_4_4 |
2542                             SNOR_HWCAPS_READ_8_8_8 |
2543                             SNOR_HWCAPS_PP_4_4_4   |
2544                             SNOR_HWCAPS_PP_8_8_8);
2545         u32 spi_hwcaps = (SNOR_HWCAPS_READ | SNOR_HWCAPS_READ_FAST |
2546                           SNOR_HWCAPS_PP);
2547
2548         /* Get the hardware capabilities the SPI controller supports. */
2549         if (spi->mode & SPI_RX_OCTAL) {
2550                 spi_hwcaps |= SNOR_HWCAPS_READ_1_1_8;
2551
2552                 if (spi->mode & SPI_TX_OCTAL)
2553                         spi_hwcaps |= (SNOR_HWCAPS_READ_1_8_8 |
2554                                         SNOR_HWCAPS_PP_1_1_8 |
2555                                         SNOR_HWCAPS_PP_1_8_8);
2556         } else if (spi->mode & SPI_RX_QUAD) {
2557                 spi_hwcaps |= SNOR_HWCAPS_READ_1_1_4;
2558
2559                 if (spi->mode & SPI_TX_QUAD)
2560                         spi_hwcaps |= (SNOR_HWCAPS_READ_1_4_4 |
2561                                         SNOR_HWCAPS_PP_1_1_4 |
2562                                         SNOR_HWCAPS_PP_1_4_4);
2563         } else if (spi->mode & SPI_RX_DUAL) {
2564                 spi_hwcaps |= SNOR_HWCAPS_READ_1_1_2;
2565
2566                 if (spi->mode & SPI_TX_DUAL)
2567                         spi_hwcaps |= SNOR_HWCAPS_READ_1_2_2;
2568         }
2569
2570         /*
2571          * Keep only the hardware capabilities supported by both the SPI
2572          * controller and the SPI flash memory.
2573          */
2574         *hwcaps = spi_hwcaps & params->hwcaps.mask;
2575         if (*hwcaps & ignored_mask) {
2576                 dev_dbg(nor->dev,
2577                         "SPI n-n-n protocols are not supported yet.\n");
2578                 *hwcaps &= ~ignored_mask;
2579         }
2580 }
2581 #endif /* CONFIG_SPI_FLASH_SMART_HWCAPS */
2582
2583 static int spi_nor_select_read(struct spi_nor *nor,
2584                                const struct spi_nor_flash_parameter *params,
2585                                u32 shared_hwcaps)
2586 {
2587         int cmd, best_match = fls(shared_hwcaps & SNOR_HWCAPS_READ_MASK) - 1;
2588         const struct spi_nor_read_command *read;
2589
2590         if (best_match < 0)
2591                 return -EINVAL;
2592
2593         cmd = spi_nor_hwcaps_read2cmd(BIT(best_match));
2594         if (cmd < 0)
2595                 return -EINVAL;
2596
2597         read = &params->reads[cmd];
2598         nor->read_opcode = read->opcode;
2599         nor->read_proto = read->proto;
2600
2601         /*
2602          * In the spi-nor framework, we don't need to make the difference
2603          * between mode clock cycles and wait state clock cycles.
2604          * Indeed, the value of the mode clock cycles is used by a QSPI
2605          * flash memory to know whether it should enter or leave its 0-4-4
2606          * (Continuous Read / XIP) mode.
2607          * eXecution In Place is out of the scope of the mtd sub-system.
2608          * Hence we choose to merge both mode and wait state clock cycles
2609          * into the so called dummy clock cycles.
2610          */
2611         nor->read_dummy = read->num_mode_clocks + read->num_wait_states;
2612         return 0;
2613 }
2614
2615 static int spi_nor_select_pp(struct spi_nor *nor,
2616                              const struct spi_nor_flash_parameter *params,
2617                              u32 shared_hwcaps)
2618 {
2619         int cmd, best_match = fls(shared_hwcaps & SNOR_HWCAPS_PP_MASK) - 1;
2620         const struct spi_nor_pp_command *pp;
2621
2622         if (best_match < 0)
2623                 return -EINVAL;
2624
2625         cmd = spi_nor_hwcaps_pp2cmd(BIT(best_match));
2626         if (cmd < 0)
2627                 return -EINVAL;
2628
2629         pp = &params->page_programs[cmd];
2630         nor->program_opcode = pp->opcode;
2631         nor->write_proto = pp->proto;
2632         return 0;
2633 }
2634
2635 static int spi_nor_select_erase(struct spi_nor *nor,
2636                                 const struct flash_info *info)
2637 {
2638         struct mtd_info *mtd = &nor->mtd;
2639
2640         /* Do nothing if already configured from SFDP. */
2641         if (mtd->erasesize)
2642                 return 0;
2643
2644 #ifdef CONFIG_SPI_FLASH_USE_4K_SECTORS
2645         /* prefer "small sector" erase if possible */
2646         if (info->flags & SECT_4K) {
2647                 nor->erase_opcode = SPINOR_OP_BE_4K;
2648                 mtd->erasesize = 4096;
2649         } else if (info->flags & SECT_4K_PMC) {
2650                 nor->erase_opcode = SPINOR_OP_BE_4K_PMC;
2651                 mtd->erasesize = 4096;
2652         } else
2653 #endif
2654         {
2655                 nor->erase_opcode = SPINOR_OP_SE;
2656                 mtd->erasesize = info->sector_size;
2657         }
2658         return 0;
2659 }
2660
2661 static int spi_nor_default_setup(struct spi_nor *nor,
2662                                  const struct flash_info *info,
2663                                  const struct spi_nor_flash_parameter *params)
2664 {
2665         u32 shared_mask;
2666         bool enable_quad_io;
2667         int err;
2668
2669         spi_nor_adjust_hwcaps(nor, params, &shared_mask);
2670
2671         /* Select the (Fast) Read command. */
2672         err = spi_nor_select_read(nor, params, shared_mask);
2673         if (err) {
2674                 dev_dbg(nor->dev,
2675                         "can't select read settings supported by both the SPI controller and memory.\n");
2676                 return err;
2677         }
2678
2679         /* Select the Page Program command. */
2680         err = spi_nor_select_pp(nor, params, shared_mask);
2681         if (err) {
2682                 dev_dbg(nor->dev,
2683                         "can't select write settings supported by both the SPI controller and memory.\n");
2684                 return err;
2685         }
2686
2687         /* Select the Sector Erase command. */
2688         err = spi_nor_select_erase(nor, info);
2689         if (err) {
2690                 dev_dbg(nor->dev,
2691                         "can't select erase settings supported by both the SPI controller and memory.\n");
2692                 return err;
2693         }
2694
2695         /* Enable Quad I/O if needed. */
2696         enable_quad_io = (spi_nor_get_protocol_width(nor->read_proto) == 4 ||
2697                           spi_nor_get_protocol_width(nor->write_proto) == 4);
2698         if (enable_quad_io && params->quad_enable)
2699                 nor->quad_enable = params->quad_enable;
2700         else
2701                 nor->quad_enable = NULL;
2702
2703         return 0;
2704 }
2705
2706 static int spi_nor_setup(struct spi_nor *nor, const struct flash_info *info,
2707                          const struct spi_nor_flash_parameter *params)
2708 {
2709         if (!nor->setup)
2710                 return 0;
2711
2712         return nor->setup(nor, info, params);
2713 }
2714
2715 static int spi_nor_init(struct spi_nor *nor)
2716 {
2717         int err;
2718
2719         /*
2720          * Atmel, SST, Intel/Numonyx, and others serial NOR tend to power up
2721          * with the software protection bits set
2722          */
2723         if (IS_ENABLED(CONFIG_SPI_FLASH_UNLOCK_ALL) &&
2724             (JEDEC_MFR(nor->info) == SNOR_MFR_ATMEL ||
2725              JEDEC_MFR(nor->info) == SNOR_MFR_INTEL ||
2726              JEDEC_MFR(nor->info) == SNOR_MFR_SST ||
2727              nor->info->flags & SPI_NOR_HAS_LOCK)) {
2728                 write_enable(nor);
2729                 write_sr(nor, 0);
2730                 spi_nor_wait_till_ready(nor);
2731         }
2732
2733         if (nor->quad_enable) {
2734                 err = nor->quad_enable(nor);
2735                 if (err) {
2736                         dev_dbg(nor->dev, "quad mode not supported\n");
2737                         return err;
2738                 }
2739         }
2740
2741         if (nor->addr_width == 4 &&
2742             !(nor->info->flags & SPI_NOR_OCTAL_DTR_READ) &&
2743             (JEDEC_MFR(nor->info) != SNOR_MFR_SPANSION) &&
2744             !(nor->info->flags & SPI_NOR_4B_OPCODES)) {
2745                 /*
2746                  * If the RESET# pin isn't hooked up properly, or the system
2747                  * otherwise doesn't perform a reset command in the boot
2748                  * sequence, it's impossible to 100% protect against unexpected
2749                  * reboots (e.g., crashes). Warn the user (or hopefully, system
2750                  * designer) that this is bad.
2751                  */
2752                 if (nor->flags & SNOR_F_BROKEN_RESET)
2753                         debug("enabling reset hack; may not recover from unexpected reboots\n");
2754                 set_4byte(nor, nor->info, 1);
2755         }
2756
2757         return 0;
2758 }
2759
2760 void spi_nor_set_fixups(struct spi_nor *nor)
2761 {
2762 }
2763
2764 int spi_nor_scan(struct spi_nor *nor)
2765 {
2766         struct spi_nor_flash_parameter params;
2767         const struct flash_info *info = NULL;
2768         struct mtd_info *mtd = &nor->mtd;
2769         struct spi_slave *spi = nor->spi;
2770         int ret;
2771
2772         /* Reset SPI protocol for all commands. */
2773         nor->reg_proto = SNOR_PROTO_1_1_1;
2774         nor->read_proto = SNOR_PROTO_1_1_1;
2775         nor->write_proto = SNOR_PROTO_1_1_1;
2776         nor->read = spi_nor_read_data;
2777         nor->write = spi_nor_write_data;
2778         nor->read_reg = spi_nor_read_reg;
2779         nor->write_reg = spi_nor_write_reg;
2780
2781         nor->setup = spi_nor_default_setup;
2782
2783         info = spi_nor_read_id(nor);
2784         if (IS_ERR_OR_NULL(info))
2785                 return -ENOENT;
2786         nor->info = info;
2787
2788         spi_nor_set_fixups(nor);
2789
2790         /* Parse the Serial Flash Discoverable Parameters table. */
2791         ret = spi_nor_init_params(nor, info, &params);
2792         if (ret)
2793                 return ret;
2794
2795         if (!mtd->name)
2796                 mtd->name = info->name;
2797         mtd->dev = nor->dev;
2798         mtd->priv = nor;
2799         mtd->type = MTD_NORFLASH;
2800         mtd->writesize = 1;
2801         mtd->flags = MTD_CAP_NORFLASH;
2802         mtd->size = params.size;
2803         mtd->_erase = spi_nor_erase;
2804         mtd->_read = spi_nor_read;
2805         mtd->_write = spi_nor_write;
2806
2807 #if defined(CONFIG_SPI_FLASH_STMICRO) || defined(CONFIG_SPI_FLASH_SST)
2808         /* NOR protection support for STmicro/Micron chips and similar */
2809         if (JEDEC_MFR(info) == SNOR_MFR_ST ||
2810             JEDEC_MFR(info) == SNOR_MFR_MICRON ||
2811             JEDEC_MFR(info) == SNOR_MFR_SST ||
2812                         info->flags & SPI_NOR_HAS_LOCK) {
2813                 nor->flash_lock = stm_lock;
2814                 nor->flash_unlock = stm_unlock;
2815                 nor->flash_is_locked = stm_is_locked;
2816         }
2817 #endif
2818
2819 #ifdef CONFIG_SPI_FLASH_SST
2820         /*
2821          * sst26 series block protection implementation differs from other
2822          * series.
2823          */
2824         if (info->flags & SPI_NOR_HAS_SST26LOCK) {
2825                 nor->flash_lock = sst26_lock;
2826                 nor->flash_unlock = sst26_unlock;
2827                 nor->flash_is_locked = sst26_is_locked;
2828         }
2829 #endif
2830
2831         if (info->flags & USE_FSR)
2832                 nor->flags |= SNOR_F_USE_FSR;
2833         if (info->flags & SPI_NOR_HAS_TB)
2834                 nor->flags |= SNOR_F_HAS_SR_TB;
2835         if (info->flags & NO_CHIP_ERASE)
2836                 nor->flags |= SNOR_F_NO_OP_CHIP_ERASE;
2837         if (info->flags & USE_CLSR)
2838                 nor->flags |= SNOR_F_USE_CLSR;
2839
2840         if (info->flags & SPI_NOR_NO_ERASE)
2841                 mtd->flags |= MTD_NO_ERASE;
2842
2843         nor->page_size = params.page_size;
2844         mtd->writebufsize = nor->page_size;
2845
2846         /* Some devices cannot do fast-read, no matter what DT tells us */
2847         if ((info->flags & SPI_NOR_NO_FR) || (spi->mode & SPI_RX_SLOW))
2848                 params.hwcaps.mask &= ~SNOR_HWCAPS_READ_FAST;
2849
2850         /*
2851          * Configure the SPI memory:
2852          * - select op codes for (Fast) Read, Page Program and Sector Erase.
2853          * - set the number of dummy cycles (mode cycles + wait states).
2854          * - set the SPI protocols for register and memory accesses.
2855          * - set the Quad Enable bit if needed (required by SPI x-y-4 protos).
2856          */
2857         ret = spi_nor_setup(nor, info, &params);
2858         if (ret)
2859                 return ret;
2860
2861         if (spi_nor_protocol_is_dtr(nor->read_proto)) {
2862                  /* Always use 4-byte addresses in DTR mode. */
2863                 nor->addr_width = 4;
2864         } else if (nor->addr_width) {
2865                 /* already configured from SFDP */
2866         } else if (info->addr_width) {
2867                 nor->addr_width = info->addr_width;
2868         } else {
2869                 nor->addr_width = 3;
2870         }
2871
2872         if (nor->addr_width == 3 && mtd->size > SZ_16M) {
2873 #ifndef CONFIG_SPI_FLASH_BAR
2874                 /* enable 4-byte addressing if the device exceeds 16MiB */
2875                 nor->addr_width = 4;
2876                 if (JEDEC_MFR(info) == SNOR_MFR_SPANSION ||
2877                     info->flags & SPI_NOR_4B_OPCODES)
2878                         spi_nor_set_4byte_opcodes(nor, info);
2879 #else
2880         /* Configure the BAR - discover bank cmds and read current bank */
2881         nor->addr_width = 3;
2882         ret = read_bar(nor, info);
2883         if (ret < 0)
2884                 return ret;
2885 #endif
2886         }
2887
2888         if (nor->addr_width > SPI_NOR_MAX_ADDR_WIDTH) {
2889                 dev_dbg(nor->dev, "address width is too large: %u\n",
2890                         nor->addr_width);
2891                 return -EINVAL;
2892         }
2893
2894         /* Send all the required SPI flash commands to initialize device */
2895         ret = spi_nor_init(nor);
2896         if (ret)
2897                 return ret;
2898
2899         nor->name = mtd->name;
2900         nor->size = mtd->size;
2901         nor->erase_size = mtd->erasesize;
2902         nor->sector_size = mtd->erasesize;
2903
2904 #ifndef CONFIG_SPL_BUILD
2905         printf("SF: Detected %s with page size ", nor->name);
2906         print_size(nor->page_size, ", erase size ");
2907         print_size(nor->erase_size, ", total ");
2908         print_size(nor->size, "");
2909         puts("\n");
2910 #endif
2911
2912         return 0;
2913 }
2914
2915 /* U-Boot specific functions, need to extend MTD to support these */
2916 int spi_flash_cmd_get_sw_write_prot(struct spi_nor *nor)
2917 {
2918         int sr = read_sr(nor);
2919
2920         if (sr < 0)
2921                 return sr;
2922
2923         return (sr >> 2) & 7;
2924 }