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