mtd: spi: spi-nor-core: Add SFDP support
[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 <linux/err.h>
14 #include <linux/errno.h>
15 #include <linux/log2.h>
16 #include <linux/math64.h>
17 #include <linux/sizes.h>
18
19 #include <linux/mtd/mtd.h>
20 #include <linux/mtd/spi-nor.h>
21 #include <spi-mem.h>
22 #include <spi.h>
23
24 /* Define max times to check status register before we give up. */
25
26 /*
27  * For everything but full-chip erase; probably could be much smaller, but kept
28  * around for safety for now
29  */
30
31 #define HZ                                      CONFIG_SYS_HZ
32
33 #define DEFAULT_READY_WAIT_JIFFIES              (40UL * HZ)
34
35 #define SPI_NOR_MAX_ID_LEN      6
36 #define SPI_NOR_MAX_ADDR_WIDTH  4
37
38 struct flash_info {
39         char            *name;
40
41         /*
42          * This array stores the ID bytes.
43          * The first three bytes are the JEDIC ID.
44          * JEDEC ID zero means "no ID" (mostly older chips).
45          */
46         u8              id[SPI_NOR_MAX_ID_LEN];
47         u8              id_len;
48
49         /* The size listed here is what works with SPINOR_OP_SE, which isn't
50          * necessarily called a "sector" by the vendor.
51          */
52         unsigned int    sector_size;
53         u16             n_sectors;
54
55         u16             page_size;
56         u16             addr_width;
57
58         u16             flags;
59 #define SECT_4K                 BIT(0)  /* SPINOR_OP_BE_4K works uniformly */
60 #define SPI_NOR_NO_ERASE        BIT(1)  /* No erase command needed */
61 #define SST_WRITE               BIT(2)  /* use SST byte programming */
62 #define SPI_NOR_NO_FR           BIT(3)  /* Can't do fastread */
63 #define SECT_4K_PMC             BIT(4)  /* SPINOR_OP_BE_4K_PMC works uniformly */
64 #define SPI_NOR_DUAL_READ       BIT(5)  /* Flash supports Dual Read */
65 #define SPI_NOR_QUAD_READ       BIT(6)  /* Flash supports Quad Read */
66 #define USE_FSR                 BIT(7)  /* use flag status register */
67 #define SPI_NOR_HAS_LOCK        BIT(8)  /* Flash supports lock/unlock via SR */
68 #define SPI_NOR_HAS_TB          BIT(9)  /*
69                                          * Flash SR has Top/Bottom (TB) protect
70                                          * bit. Must be used with
71                                          * SPI_NOR_HAS_LOCK.
72                                          */
73 #define SPI_S3AN                BIT(10) /*
74                                          * Xilinx Spartan 3AN In-System Flash
75                                          * (MFR cannot be used for probing
76                                          * because it has the same value as
77                                          * ATMEL flashes)
78                                          */
79 #define SPI_NOR_4B_OPCODES      BIT(11) /*
80                                          * Use dedicated 4byte address op codes
81                                          * to support memory size above 128Mib.
82                                          */
83 #define NO_CHIP_ERASE           BIT(12) /* Chip does not support chip erase */
84 #define SPI_NOR_SKIP_SFDP       BIT(13) /* Skip parsing of SFDP tables */
85 #define USE_CLSR                BIT(14) /* use CLSR command */
86
87         int     (*quad_enable)(struct spi_nor *nor);
88 };
89
90 #define JEDEC_MFR(info) ((info)->id[0])
91
92 static int spi_nor_read_write_reg(struct spi_nor *nor, struct spi_mem_op
93                 *op, void *buf)
94 {
95         if (op->data.dir == SPI_MEM_DATA_IN)
96                 op->data.buf.in = buf;
97         else
98                 op->data.buf.out = buf;
99         return spi_mem_exec_op(nor->spi, op);
100 }
101
102 static int spi_nor_read_reg(struct spi_nor *nor, u8 code, u8 *val, int len)
103 {
104         struct spi_mem_op op = SPI_MEM_OP(SPI_MEM_OP_CMD(code, 1),
105                                           SPI_MEM_OP_NO_ADDR,
106                                           SPI_MEM_OP_NO_DUMMY,
107                                           SPI_MEM_OP_DATA_IN(len, NULL, 1));
108         int ret;
109
110         ret = spi_nor_read_write_reg(nor, &op, val);
111         if (ret < 0)
112                 dev_dbg(&flash->spimem->spi->dev, "error %d reading %x\n", ret,
113                         code);
114
115         return ret;
116 }
117
118 static int spi_nor_write_reg(struct spi_nor *nor, u8 opcode, u8 *buf, int len)
119 {
120         struct spi_mem_op op = SPI_MEM_OP(SPI_MEM_OP_CMD(opcode, 1),
121                                           SPI_MEM_OP_NO_ADDR,
122                                           SPI_MEM_OP_NO_DUMMY,
123                                           SPI_MEM_OP_DATA_OUT(len, NULL, 1));
124
125         return spi_nor_read_write_reg(nor, &op, buf);
126 }
127
128 static ssize_t spi_nor_read_data(struct spi_nor *nor, loff_t from, size_t len,
129                                  u_char *buf)
130 {
131         struct spi_mem_op op =
132                         SPI_MEM_OP(SPI_MEM_OP_CMD(nor->read_opcode, 1),
133                                    SPI_MEM_OP_ADDR(nor->addr_width, from, 1),
134                                    SPI_MEM_OP_DUMMY(nor->read_dummy, 1),
135                                    SPI_MEM_OP_DATA_IN(len, buf, 1));
136         size_t remaining = len;
137         int ret;
138
139         /* get transfer protocols. */
140         op.cmd.buswidth = spi_nor_get_protocol_inst_nbits(nor->read_proto);
141         op.addr.buswidth = spi_nor_get_protocol_addr_nbits(nor->read_proto);
142         op.dummy.buswidth = op.addr.buswidth;
143         op.data.buswidth = spi_nor_get_protocol_data_nbits(nor->read_proto);
144
145         /* convert the dummy cycles to the number of bytes */
146         op.dummy.nbytes = (nor->read_dummy * op.dummy.buswidth) / 8;
147
148         while (remaining) {
149                 op.data.nbytes = remaining < UINT_MAX ? remaining : UINT_MAX;
150                 ret = spi_mem_adjust_op_size(nor->spi, &op);
151                 if (ret)
152                         return ret;
153
154                 ret = spi_mem_exec_op(nor->spi, &op);
155                 if (ret)
156                         return ret;
157
158                 op.addr.val += op.data.nbytes;
159                 remaining -= op.data.nbytes;
160                 op.data.buf.in += op.data.nbytes;
161         }
162
163         return len;
164 }
165
166 static ssize_t spi_nor_write_data(struct spi_nor *nor, loff_t to, size_t len,
167                                   const u_char *buf)
168 {
169         struct spi_mem_op op =
170                         SPI_MEM_OP(SPI_MEM_OP_CMD(nor->program_opcode, 1),
171                                    SPI_MEM_OP_ADDR(nor->addr_width, to, 1),
172                                    SPI_MEM_OP_NO_DUMMY,
173                                    SPI_MEM_OP_DATA_OUT(len, buf, 1));
174         size_t remaining = len;
175         int ret;
176
177         /* get transfer protocols. */
178         op.cmd.buswidth = spi_nor_get_protocol_inst_nbits(nor->write_proto);
179         op.addr.buswidth = spi_nor_get_protocol_addr_nbits(nor->write_proto);
180         op.data.buswidth = spi_nor_get_protocol_data_nbits(nor->write_proto);
181
182         if (nor->program_opcode == SPINOR_OP_AAI_WP && nor->sst_write_second)
183                 op.addr.nbytes = 0;
184
185         while (remaining) {
186                 op.data.nbytes = remaining < UINT_MAX ? remaining : UINT_MAX;
187                 ret = spi_mem_adjust_op_size(nor->spi, &op);
188                 if (ret)
189                         return ret;
190
191                 ret = spi_mem_exec_op(nor->spi, &op);
192                 if (ret)
193                         return ret;
194
195                 op.addr.val += op.data.nbytes;
196                 remaining -= op.data.nbytes;
197                 op.data.buf.out += op.data.nbytes;
198         }
199
200         return len;
201 }
202
203 /*
204  * Read the status register, returning its value in the location
205  * Return the status register value.
206  * Returns negative if error occurred.
207  */
208 static int read_sr(struct spi_nor *nor)
209 {
210         int ret;
211         u8 val;
212
213         ret = nor->read_reg(nor, SPINOR_OP_RDSR, &val, 1);
214         if (ret < 0) {
215                 pr_debug("error %d reading SR\n", (int)ret);
216                 return ret;
217         }
218
219         return val;
220 }
221
222 /*
223  * Read the flag status register, returning its value in the location
224  * Return the status register value.
225  * Returns negative if error occurred.
226  */
227 static int read_fsr(struct spi_nor *nor)
228 {
229         int ret;
230         u8 val;
231
232         ret = nor->read_reg(nor, SPINOR_OP_RDFSR, &val, 1);
233         if (ret < 0) {
234                 pr_debug("error %d reading FSR\n", ret);
235                 return ret;
236         }
237
238         return val;
239 }
240
241 /*
242  * Read configuration register, returning its value in the
243  * location. Return the configuration register value.
244  * Returns negative if error occurred.
245  */
246 #if defined(CONFIG_SPI_FLASH_SPANSION) || defined(CONFIG_SPI_FLASH_WINBOND)
247 static int read_cr(struct spi_nor *nor)
248 {
249         int ret;
250         u8 val;
251
252         ret = nor->read_reg(nor, SPINOR_OP_RDCR, &val, 1);
253         if (ret < 0) {
254                 dev_dbg(nor->dev, "error %d reading CR\n", ret);
255                 return ret;
256         }
257
258         return val;
259 }
260 #endif
261
262 /*
263  * Write status register 1 byte
264  * Returns negative if error occurred.
265  */
266 static int write_sr(struct spi_nor *nor, u8 val)
267 {
268         nor->cmd_buf[0] = val;
269         return nor->write_reg(nor, SPINOR_OP_WRSR, nor->cmd_buf, 1);
270 }
271
272 /*
273  * Set write enable latch with Write Enable command.
274  * Returns negative if error occurred.
275  */
276 static int write_enable(struct spi_nor *nor)
277 {
278         return nor->write_reg(nor, SPINOR_OP_WREN, NULL, 0);
279 }
280
281 /*
282  * Send write disable instruction to the chip.
283  */
284 static int write_disable(struct spi_nor *nor)
285 {
286         return nor->write_reg(nor, SPINOR_OP_WRDI, NULL, 0);
287 }
288
289 static struct spi_nor *mtd_to_spi_nor(struct mtd_info *mtd)
290 {
291         return mtd->priv;
292 }
293
294 static u8 spi_nor_convert_opcode(u8 opcode, const u8 table[][2], size_t size)
295 {
296         size_t i;
297
298         for (i = 0; i < size; i++)
299                 if (table[i][0] == opcode)
300                         return table[i][1];
301
302         /* No conversion found, keep input op code. */
303         return opcode;
304 }
305
306 static u8 spi_nor_convert_3to4_read(u8 opcode)
307 {
308         static const u8 spi_nor_3to4_read[][2] = {
309                 { SPINOR_OP_READ,       SPINOR_OP_READ_4B },
310                 { SPINOR_OP_READ_FAST,  SPINOR_OP_READ_FAST_4B },
311                 { SPINOR_OP_READ_1_1_2, SPINOR_OP_READ_1_1_2_4B },
312                 { SPINOR_OP_READ_1_2_2, SPINOR_OP_READ_1_2_2_4B },
313                 { SPINOR_OP_READ_1_1_4, SPINOR_OP_READ_1_1_4_4B },
314                 { SPINOR_OP_READ_1_4_4, SPINOR_OP_READ_1_4_4_4B },
315
316                 { SPINOR_OP_READ_1_1_1_DTR,     SPINOR_OP_READ_1_1_1_DTR_4B },
317                 { SPINOR_OP_READ_1_2_2_DTR,     SPINOR_OP_READ_1_2_2_DTR_4B },
318                 { SPINOR_OP_READ_1_4_4_DTR,     SPINOR_OP_READ_1_4_4_DTR_4B },
319         };
320
321         return spi_nor_convert_opcode(opcode, spi_nor_3to4_read,
322                                       ARRAY_SIZE(spi_nor_3to4_read));
323 }
324
325 static u8 spi_nor_convert_3to4_program(u8 opcode)
326 {
327         static const u8 spi_nor_3to4_program[][2] = {
328                 { SPINOR_OP_PP,         SPINOR_OP_PP_4B },
329                 { SPINOR_OP_PP_1_1_4,   SPINOR_OP_PP_1_1_4_4B },
330                 { SPINOR_OP_PP_1_4_4,   SPINOR_OP_PP_1_4_4_4B },
331         };
332
333         return spi_nor_convert_opcode(opcode, spi_nor_3to4_program,
334                                       ARRAY_SIZE(spi_nor_3to4_program));
335 }
336
337 static u8 spi_nor_convert_3to4_erase(u8 opcode)
338 {
339         static const u8 spi_nor_3to4_erase[][2] = {
340                 { SPINOR_OP_BE_4K,      SPINOR_OP_BE_4K_4B },
341                 { SPINOR_OP_BE_32K,     SPINOR_OP_BE_32K_4B },
342                 { SPINOR_OP_SE,         SPINOR_OP_SE_4B },
343         };
344
345         return spi_nor_convert_opcode(opcode, spi_nor_3to4_erase,
346                                       ARRAY_SIZE(spi_nor_3to4_erase));
347 }
348
349 static void spi_nor_set_4byte_opcodes(struct spi_nor *nor,
350                                       const struct flash_info *info)
351 {
352         /* Do some manufacturer fixups first */
353         switch (JEDEC_MFR(info)) {
354         case SNOR_MFR_SPANSION:
355                 /* No small sector erase for 4-byte command set */
356                 nor->erase_opcode = SPINOR_OP_SE;
357                 nor->mtd.erasesize = info->sector_size;
358                 break;
359
360         default:
361                 break;
362         }
363
364         nor->read_opcode = spi_nor_convert_3to4_read(nor->read_opcode);
365         nor->program_opcode = spi_nor_convert_3to4_program(nor->program_opcode);
366         nor->erase_opcode = spi_nor_convert_3to4_erase(nor->erase_opcode);
367 }
368
369 /* Enable/disable 4-byte addressing mode. */
370 static int set_4byte(struct spi_nor *nor, const struct flash_info *info,
371                      int enable)
372 {
373         int status;
374         bool need_wren = false;
375         u8 cmd;
376
377         switch (JEDEC_MFR(info)) {
378         case SNOR_MFR_ST:
379         case SNOR_MFR_MICRON:
380                 /* Some Micron need WREN command; all will accept it */
381                 need_wren = true;
382         case SNOR_MFR_MACRONIX:
383         case SNOR_MFR_WINBOND:
384                 if (need_wren)
385                         write_enable(nor);
386
387                 cmd = enable ? SPINOR_OP_EN4B : SPINOR_OP_EX4B;
388                 status = nor->write_reg(nor, cmd, NULL, 0);
389                 if (need_wren)
390                         write_disable(nor);
391
392                 if (!status && !enable &&
393                     JEDEC_MFR(info) == SNOR_MFR_WINBOND) {
394                         /*
395                          * On Winbond W25Q256FV, leaving 4byte mode causes
396                          * the Extended Address Register to be set to 1, so all
397                          * 3-byte-address reads come from the second 16M.
398                          * We must clear the register to enable normal behavior.
399                          */
400                         write_enable(nor);
401                         nor->cmd_buf[0] = 0;
402                         nor->write_reg(nor, SPINOR_OP_WREAR, nor->cmd_buf, 1);
403                         write_disable(nor);
404                 }
405
406                 return status;
407         default:
408                 /* Spansion style */
409                 nor->cmd_buf[0] = enable << 7;
410                 return nor->write_reg(nor, SPINOR_OP_BRWR, nor->cmd_buf, 1);
411         }
412 }
413
414 static int spi_nor_sr_ready(struct spi_nor *nor)
415 {
416         int sr = read_sr(nor);
417
418         if (sr < 0)
419                 return sr;
420
421         if (nor->flags & SNOR_F_USE_CLSR && sr & (SR_E_ERR | SR_P_ERR)) {
422                 if (sr & SR_E_ERR)
423                         dev_dbg(nor->dev, "Erase Error occurred\n");
424                 else
425                         dev_dbg(nor->dev, "Programming Error occurred\n");
426
427                 nor->write_reg(nor, SPINOR_OP_CLSR, NULL, 0);
428                 return -EIO;
429         }
430
431         return !(sr & SR_WIP);
432 }
433
434 static int spi_nor_fsr_ready(struct spi_nor *nor)
435 {
436         int fsr = read_fsr(nor);
437
438         if (fsr < 0)
439                 return fsr;
440
441         if (fsr & (FSR_E_ERR | FSR_P_ERR)) {
442                 if (fsr & FSR_E_ERR)
443                         dev_dbg(nor->dev, "Erase operation failed.\n");
444                 else
445                         dev_dbg(nor->dev, "Program operation failed.\n");
446
447                 if (fsr & FSR_PT_ERR)
448                         dev_dbg(nor->dev,
449                                 "Attempted to modify a protected sector.\n");
450
451                 nor->write_reg(nor, SPINOR_OP_CLFSR, NULL, 0);
452                 return -EIO;
453         }
454
455         return fsr & FSR_READY;
456 }
457
458 static int spi_nor_ready(struct spi_nor *nor)
459 {
460         int sr, fsr;
461
462         sr = spi_nor_sr_ready(nor);
463         if (sr < 0)
464                 return sr;
465         fsr = nor->flags & SNOR_F_USE_FSR ? spi_nor_fsr_ready(nor) : 1;
466         if (fsr < 0)
467                 return fsr;
468         return sr && fsr;
469 }
470
471 /*
472  * Service routine to read status register until ready, or timeout occurs.
473  * Returns non-zero if error.
474  */
475 static int spi_nor_wait_till_ready_with_timeout(struct spi_nor *nor,
476                                                 unsigned long timeout)
477 {
478         unsigned long timebase;
479         int ret;
480
481         timebase = get_timer(0);
482
483         while (get_timer(timebase) < timeout) {
484                 ret = spi_nor_ready(nor);
485                 if (ret < 0)
486                         return ret;
487                 if (ret)
488                         return 0;
489         }
490
491         dev_err(nor->dev, "flash operation timed out\n");
492
493         return -ETIMEDOUT;
494 }
495
496 static int spi_nor_wait_till_ready(struct spi_nor *nor)
497 {
498         return spi_nor_wait_till_ready_with_timeout(nor,
499                                                     DEFAULT_READY_WAIT_JIFFIES);
500 }
501
502 /*
503  * Initiate the erasure of a single sector
504  */
505 static int spi_nor_erase_sector(struct spi_nor *nor, u32 addr)
506 {
507         u8 buf[SPI_NOR_MAX_ADDR_WIDTH];
508         int i;
509
510         if (nor->erase)
511                 return nor->erase(nor, addr);
512
513         /*
514          * Default implementation, if driver doesn't have a specialized HW
515          * control
516          */
517         for (i = nor->addr_width - 1; i >= 0; i--) {
518                 buf[i] = addr & 0xff;
519                 addr >>= 8;
520         }
521
522         return nor->write_reg(nor, nor->erase_opcode, buf, nor->addr_width);
523 }
524
525 /*
526  * Erase an address range on the nor chip.  The address range may extend
527  * one or more erase sectors.  Return an error is there is a problem erasing.
528  */
529 static int spi_nor_erase(struct mtd_info *mtd, struct erase_info *instr)
530 {
531         struct spi_nor *nor = mtd_to_spi_nor(mtd);
532         u32 addr, len, rem;
533         int ret;
534
535         dev_dbg(nor->dev, "at 0x%llx, len %lld\n", (long long)instr->addr,
536                 (long long)instr->len);
537
538         div_u64_rem(instr->len, mtd->erasesize, &rem);
539         if (rem)
540                 return -EINVAL;
541
542         addr = instr->addr;
543         len = instr->len;
544
545         while (len) {
546                 write_enable(nor);
547
548                 ret = spi_nor_erase_sector(nor, addr);
549                 if (ret)
550                         goto erase_err;
551
552                 addr += mtd->erasesize;
553                 len -= mtd->erasesize;
554
555                 ret = spi_nor_wait_till_ready(nor);
556                 if (ret)
557                         goto erase_err;
558         }
559
560         write_disable(nor);
561
562 erase_err:
563         return ret;
564 }
565
566 #if defined(CONFIG_SPI_FLASH_STMICRO) || defined(CONFIG_SPI_FLASH_SST)
567 /* Write status register and ensure bits in mask match written values */
568 static int write_sr_and_check(struct spi_nor *nor, u8 status_new, u8 mask)
569 {
570         int ret;
571
572         write_enable(nor);
573         ret = write_sr(nor, status_new);
574         if (ret)
575                 return ret;
576
577         ret = spi_nor_wait_till_ready(nor);
578         if (ret)
579                 return ret;
580
581         ret = read_sr(nor);
582         if (ret < 0)
583                 return ret;
584
585         return ((ret & mask) != (status_new & mask)) ? -EIO : 0;
586 }
587
588 static void stm_get_locked_range(struct spi_nor *nor, u8 sr, loff_t *ofs,
589                                  uint64_t *len)
590 {
591         struct mtd_info *mtd = &nor->mtd;
592         u8 mask = SR_BP2 | SR_BP1 | SR_BP0;
593         int shift = ffs(mask) - 1;
594         int pow;
595
596         if (!(sr & mask)) {
597                 /* No protection */
598                 *ofs = 0;
599                 *len = 0;
600         } else {
601                 pow = ((sr & mask) ^ mask) >> shift;
602                 *len = mtd->size >> pow;
603                 if (nor->flags & SNOR_F_HAS_SR_TB && sr & SR_TB)
604                         *ofs = 0;
605                 else
606                         *ofs = mtd->size - *len;
607         }
608 }
609
610 /*
611  * Return 1 if the entire region is locked (if @locked is true) or unlocked (if
612  * @locked is false); 0 otherwise
613  */
614 static int stm_check_lock_status_sr(struct spi_nor *nor, loff_t ofs, u64 len,
615                                     u8 sr, bool locked)
616 {
617         loff_t lock_offs;
618         uint64_t lock_len;
619
620         if (!len)
621                 return 1;
622
623         stm_get_locked_range(nor, sr, &lock_offs, &lock_len);
624
625         if (locked)
626                 /* Requested range is a sub-range of locked range */
627                 return (ofs + len <= lock_offs + lock_len) && (ofs >= lock_offs);
628         else
629                 /* Requested range does not overlap with locked range */
630                 return (ofs >= lock_offs + lock_len) || (ofs + len <= lock_offs);
631 }
632
633 static int stm_is_locked_sr(struct spi_nor *nor, loff_t ofs, uint64_t len,
634                             u8 sr)
635 {
636         return stm_check_lock_status_sr(nor, ofs, len, sr, true);
637 }
638
639 static int stm_is_unlocked_sr(struct spi_nor *nor, loff_t ofs, uint64_t len,
640                               u8 sr)
641 {
642         return stm_check_lock_status_sr(nor, ofs, len, sr, false);
643 }
644
645 /*
646  * Lock a region of the flash. Compatible with ST Micro and similar flash.
647  * Supports the block protection bits BP{0,1,2} in the status register
648  * (SR). Does not support these features found in newer SR bitfields:
649  *   - SEC: sector/block protect - only handle SEC=0 (block protect)
650  *   - CMP: complement protect - only support CMP=0 (range is not complemented)
651  *
652  * Support for the following is provided conditionally for some flash:
653  *   - TB: top/bottom protect
654  *
655  * Sample table portion for 8MB flash (Winbond w25q64fw):
656  *
657  *   SEC  |  TB   |  BP2  |  BP1  |  BP0  |  Prot Length  | Protected Portion
658  *  --------------------------------------------------------------------------
659  *    X   |   X   |   0   |   0   |   0   |  NONE         | NONE
660  *    0   |   0   |   0   |   0   |   1   |  128 KB       | Upper 1/64
661  *    0   |   0   |   0   |   1   |   0   |  256 KB       | Upper 1/32
662  *    0   |   0   |   0   |   1   |   1   |  512 KB       | Upper 1/16
663  *    0   |   0   |   1   |   0   |   0   |  1 MB         | Upper 1/8
664  *    0   |   0   |   1   |   0   |   1   |  2 MB         | Upper 1/4
665  *    0   |   0   |   1   |   1   |   0   |  4 MB         | Upper 1/2
666  *    X   |   X   |   1   |   1   |   1   |  8 MB         | ALL
667  *  ------|-------|-------|-------|-------|---------------|-------------------
668  *    0   |   1   |   0   |   0   |   1   |  128 KB       | Lower 1/64
669  *    0   |   1   |   0   |   1   |   0   |  256 KB       | Lower 1/32
670  *    0   |   1   |   0   |   1   |   1   |  512 KB       | Lower 1/16
671  *    0   |   1   |   1   |   0   |   0   |  1 MB         | Lower 1/8
672  *    0   |   1   |   1   |   0   |   1   |  2 MB         | Lower 1/4
673  *    0   |   1   |   1   |   1   |   0   |  4 MB         | Lower 1/2
674  *
675  * Returns negative on errors, 0 on success.
676  */
677 static int stm_lock(struct spi_nor *nor, loff_t ofs, uint64_t len)
678 {
679         struct mtd_info *mtd = &nor->mtd;
680         int status_old, status_new;
681         u8 mask = SR_BP2 | SR_BP1 | SR_BP0;
682         u8 shift = ffs(mask) - 1, pow, val;
683         loff_t lock_len;
684         bool can_be_top = true, can_be_bottom = nor->flags & SNOR_F_HAS_SR_TB;
685         bool use_top;
686
687         status_old = read_sr(nor);
688         if (status_old < 0)
689                 return status_old;
690
691         /* If nothing in our range is unlocked, we don't need to do anything */
692         if (stm_is_locked_sr(nor, ofs, len, status_old))
693                 return 0;
694
695         /* If anything below us is unlocked, we can't use 'bottom' protection */
696         if (!stm_is_locked_sr(nor, 0, ofs, status_old))
697                 can_be_bottom = false;
698
699         /* If anything above us is unlocked, we can't use 'top' protection */
700         if (!stm_is_locked_sr(nor, ofs + len, mtd->size - (ofs + len),
701                               status_old))
702                 can_be_top = false;
703
704         if (!can_be_bottom && !can_be_top)
705                 return -EINVAL;
706
707         /* Prefer top, if both are valid */
708         use_top = can_be_top;
709
710         /* lock_len: length of region that should end up locked */
711         if (use_top)
712                 lock_len = mtd->size - ofs;
713         else
714                 lock_len = ofs + len;
715
716         /*
717          * Need smallest pow such that:
718          *
719          *   1 / (2^pow) <= (len / size)
720          *
721          * so (assuming power-of-2 size) we do:
722          *
723          *   pow = ceil(log2(size / len)) = log2(size) - floor(log2(len))
724          */
725         pow = ilog2(mtd->size) - ilog2(lock_len);
726         val = mask - (pow << shift);
727         if (val & ~mask)
728                 return -EINVAL;
729         /* Don't "lock" with no region! */
730         if (!(val & mask))
731                 return -EINVAL;
732
733         status_new = (status_old & ~mask & ~SR_TB) | val;
734
735         /* Disallow further writes if WP pin is asserted */
736         status_new |= SR_SRWD;
737
738         if (!use_top)
739                 status_new |= SR_TB;
740
741         /* Don't bother if they're the same */
742         if (status_new == status_old)
743                 return 0;
744
745         /* Only modify protection if it will not unlock other areas */
746         if ((status_new & mask) < (status_old & mask))
747                 return -EINVAL;
748
749         return write_sr_and_check(nor, status_new, mask);
750 }
751
752 /*
753  * Unlock a region of the flash. See stm_lock() for more info
754  *
755  * Returns negative on errors, 0 on success.
756  */
757 static int stm_unlock(struct spi_nor *nor, loff_t ofs, uint64_t len)
758 {
759         struct mtd_info *mtd = &nor->mtd;
760         int status_old, status_new;
761         u8 mask = SR_BP2 | SR_BP1 | SR_BP0;
762         u8 shift = ffs(mask) - 1, pow, val;
763         loff_t lock_len;
764         bool can_be_top = true, can_be_bottom = nor->flags & SNOR_F_HAS_SR_TB;
765         bool use_top;
766
767         status_old = read_sr(nor);
768         if (status_old < 0)
769                 return status_old;
770
771         /* If nothing in our range is locked, we don't need to do anything */
772         if (stm_is_unlocked_sr(nor, ofs, len, status_old))
773                 return 0;
774
775         /* If anything below us is locked, we can't use 'top' protection */
776         if (!stm_is_unlocked_sr(nor, 0, ofs, status_old))
777                 can_be_top = false;
778
779         /* If anything above us is locked, we can't use 'bottom' protection */
780         if (!stm_is_unlocked_sr(nor, ofs + len, mtd->size - (ofs + len),
781                                 status_old))
782                 can_be_bottom = false;
783
784         if (!can_be_bottom && !can_be_top)
785                 return -EINVAL;
786
787         /* Prefer top, if both are valid */
788         use_top = can_be_top;
789
790         /* lock_len: length of region that should remain locked */
791         if (use_top)
792                 lock_len = mtd->size - (ofs + len);
793         else
794                 lock_len = ofs;
795
796         /*
797          * Need largest pow such that:
798          *
799          *   1 / (2^pow) >= (len / size)
800          *
801          * so (assuming power-of-2 size) we do:
802          *
803          *   pow = floor(log2(size / len)) = log2(size) - ceil(log2(len))
804          */
805         pow = ilog2(mtd->size) - order_base_2(lock_len);
806         if (lock_len == 0) {
807                 val = 0; /* fully unlocked */
808         } else {
809                 val = mask - (pow << shift);
810                 /* Some power-of-two sizes are not supported */
811                 if (val & ~mask)
812                         return -EINVAL;
813         }
814
815         status_new = (status_old & ~mask & ~SR_TB) | val;
816
817         /* Don't protect status register if we're fully unlocked */
818         if (lock_len == 0)
819                 status_new &= ~SR_SRWD;
820
821         if (!use_top)
822                 status_new |= SR_TB;
823
824         /* Don't bother if they're the same */
825         if (status_new == status_old)
826                 return 0;
827
828         /* Only modify protection if it will not lock other areas */
829         if ((status_new & mask) > (status_old & mask))
830                 return -EINVAL;
831
832         return write_sr_and_check(nor, status_new, mask);
833 }
834
835 /*
836  * Check if a region of the flash is (completely) locked. See stm_lock() for
837  * more info.
838  *
839  * Returns 1 if entire region is locked, 0 if any portion is unlocked, and
840  * negative on errors.
841  */
842 static int stm_is_locked(struct spi_nor *nor, loff_t ofs, uint64_t len)
843 {
844         int status;
845
846         status = read_sr(nor);
847         if (status < 0)
848                 return status;
849
850         return stm_is_locked_sr(nor, ofs, len, status);
851 }
852 #endif /* CONFIG_SPI_FLASH_STMICRO */
853
854 /* Used when the "_ext_id" is two bytes at most */
855 #define INFO(_jedec_id, _ext_id, _sector_size, _n_sectors, _flags)      \
856                 .id = {                                                 \
857                         ((_jedec_id) >> 16) & 0xff,                     \
858                         ((_jedec_id) >> 8) & 0xff,                      \
859                         (_jedec_id) & 0xff,                             \
860                         ((_ext_id) >> 8) & 0xff,                        \
861                         (_ext_id) & 0xff,                               \
862                         },                                              \
863                 .id_len = (!(_jedec_id) ? 0 : (3 + ((_ext_id) ? 2 : 0))),       \
864                 .sector_size = (_sector_size),                          \
865                 .n_sectors = (_n_sectors),                              \
866                 .page_size = 256,                                       \
867                 .flags = (_flags),
868
869 #define INFO6(_jedec_id, _ext_id, _sector_size, _n_sectors, _flags)     \
870                 .id = {                                                 \
871                         ((_jedec_id) >> 16) & 0xff,                     \
872                         ((_jedec_id) >> 8) & 0xff,                      \
873                         (_jedec_id) & 0xff,                             \
874                         ((_ext_id) >> 16) & 0xff,                       \
875                         ((_ext_id) >> 8) & 0xff,                        \
876                         (_ext_id) & 0xff,                               \
877                         },                                              \
878                 .id_len = 6,                                            \
879                 .sector_size = (_sector_size),                          \
880                 .n_sectors = (_n_sectors),                              \
881                 .page_size = 256,                                       \
882                 .flags = (_flags),
883
884 /* NOTE: double check command sets and memory organization when you add
885  * more nor chips.  This current list focusses on newer chips, which
886  * have been converging on command sets which including JEDEC ID.
887  *
888  * All newly added entries should describe *hardware* and should use SECT_4K
889  * (or SECT_4K_PMC) if hardware supports erasing 4 KiB sectors. For usage
890  * scenarios excluding small sectors there is config option that can be
891  * disabled: CONFIG_MTD_SPI_NOR_USE_4K_SECTORS.
892  * For historical (and compatibility) reasons (before we got above config) some
893  * old entries may be missing 4K flag.
894  */
895 const struct flash_info spi_nor_ids[] = {
896 #ifdef CONFIG_SPI_FLASH_ATMEL           /* ATMEL */
897         /* Atmel -- some are (confusingly) marketed as "DataFlash" */
898         { "at26df321",  INFO(0x1f4700, 0, 64 * 1024, 64, SECT_4K) },
899         { "at25df321a", INFO(0x1f4701, 0, 64 * 1024, 64, SECT_4K) },
900
901         { "at45db011d", INFO(0x1f2200, 0, 64 * 1024,   4, SECT_4K) },
902         { "at45db021d", INFO(0x1f2300, 0, 64 * 1024,   8, SECT_4K) },
903         { "at45db041d", INFO(0x1f2400, 0, 64 * 1024,   8, SECT_4K) },
904         { "at45db081d", INFO(0x1f2500, 0, 64 * 1024,  16, SECT_4K) },
905         { "at45db161d", INFO(0x1f2600, 0, 64 * 1024,  32, SECT_4K) },
906         { "at45db321d", INFO(0x1f2700, 0, 64 * 1024,  64, SECT_4K) },
907         { "at45db641d", INFO(0x1f2800, 0, 64 * 1024, 128, SECT_4K) },
908         { "at26df081a", INFO(0x1f4501, 0, 64 * 1024,  16, SECT_4K) },
909 #endif
910 #ifdef CONFIG_SPI_FLASH_EON             /* EON */
911         /* EON -- en25xxx */
912         { "en25q32b",   INFO(0x1c3016, 0, 64 * 1024,   64, 0) },
913         { "en25q64",    INFO(0x1c3017, 0, 64 * 1024,  128, SECT_4K) },
914         { "en25qh128",  INFO(0x1c7018, 0, 64 * 1024,  256, 0) },
915         { "en25s64",    INFO(0x1c3817, 0, 64 * 1024,  128, SECT_4K) },
916 #endif
917 #ifdef CONFIG_SPI_FLASH_GIGADEVICE      /* GIGADEVICE */
918         /* GigaDevice */
919         {
920                 "gd25q16", INFO(0xc84015, 0, 64 * 1024,  32,
921                         SECT_4K | SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ |
922                         SPI_NOR_HAS_LOCK | SPI_NOR_HAS_TB)
923         },
924         {
925                 "gd25q32", INFO(0xc84016, 0, 64 * 1024,  64,
926                         SECT_4K | SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ |
927                         SPI_NOR_HAS_LOCK | SPI_NOR_HAS_TB)
928         },
929         {
930                 "gd25lq32", INFO(0xc86016, 0, 64 * 1024, 64,
931                         SECT_4K | SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ |
932                         SPI_NOR_HAS_LOCK | SPI_NOR_HAS_TB)
933         },
934         {
935                 "gd25q64", INFO(0xc84017, 0, 64 * 1024, 128,
936                         SECT_4K | SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ |
937                         SPI_NOR_HAS_LOCK | SPI_NOR_HAS_TB)
938         },
939 #endif
940 #ifdef CONFIG_SPI_FLASH_ISSI            /* ISSI */
941         /* ISSI */
942         { "is25lq040b", INFO(0x9d4013, 0, 64 * 1024,   8,
943                         SECT_4K | SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ) },
944         { "is25lp032",  INFO(0x9d6016, 0, 64 * 1024,  64, 0) },
945         { "is25lp064",  INFO(0x9d6017, 0, 64 * 1024, 128, 0) },
946         { "is25lp128",  INFO(0x9d6018, 0, 64 * 1024, 256,
947                         SECT_4K | SPI_NOR_DUAL_READ) },
948         { "is25lp256",  INFO(0x9d6019, 0, 64 * 1024, 512,
949                         SECT_4K | SPI_NOR_DUAL_READ) },
950         { "is25wp032",  INFO(0x9d7016, 0, 64 * 1024,  64,
951                         SECT_4K | SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ) },
952         { "is25wp064",  INFO(0x9d7017, 0, 64 * 1024, 128,
953                         SECT_4K | SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ) },
954         { "is25wp128",  INFO(0x9d7018, 0, 64 * 1024, 256,
955                         SECT_4K | SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ) },
956 #endif
957 #ifdef CONFIG_SPI_FLASH_MACRONIX        /* MACRONIX */
958         /* Macronix */
959         { "mx25l2005a",  INFO(0xc22012, 0, 64 * 1024,   4, SECT_4K) },
960         { "mx25l4005a",  INFO(0xc22013, 0, 64 * 1024,   8, SECT_4K) },
961         { "mx25l8005",   INFO(0xc22014, 0, 64 * 1024,  16, 0) },
962         { "mx25l1606e",  INFO(0xc22015, 0, 64 * 1024,  32, SECT_4K) },
963         { "mx25l3205d",  INFO(0xc22016, 0, 64 * 1024,  64, SECT_4K) },
964         { "mx25l6405d",  INFO(0xc22017, 0, 64 * 1024, 128, SECT_4K) },
965         { "mx25u2033e",  INFO(0xc22532, 0, 64 * 1024,   4, SECT_4K) },
966         { "mx25u1635e",  INFO(0xc22535, 0, 64 * 1024,  32, SECT_4K) },
967         { "mx25u6435f",  INFO(0xc22537, 0, 64 * 1024, 128, SECT_4K) },
968         { "mx25l12805d", INFO(0xc22018, 0, 64 * 1024, 256, 0) },
969         { "mx25l12855e", INFO(0xc22618, 0, 64 * 1024, 256, 0) },
970         { "mx25l25635e", INFO(0xc22019, 0, 64 * 1024, 512, SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ) },
971         { "mx25u25635f", INFO(0xc22539, 0, 64 * 1024, 512, SECT_4K | SPI_NOR_4B_OPCODES) },
972         { "mx25l25655e", INFO(0xc22619, 0, 64 * 1024, 512, 0) },
973         { "mx66l51235l", INFO(0xc2201a, 0, 64 * 1024, 1024, SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ | SPI_NOR_4B_OPCODES) },
974         { "mx66u51235f", INFO(0xc2253a, 0, 64 * 1024, 1024, SECT_4K | SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ | SPI_NOR_4B_OPCODES) },
975         { "mx66l1g45g",  INFO(0xc2201b, 0, 64 * 1024, 2048, SECT_4K | SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ) },
976         { "mx25l1633e",  INFO(0xc22415, 0, 64 * 1024,   32, SPI_NOR_QUAD_READ | SPI_NOR_4B_OPCODES | SECT_4K) },
977 #endif
978
979 #ifdef CONFIG_SPI_FLASH_STMICRO         /* STMICRO */
980         /* Micron */
981         { "n25q016a",    INFO(0x20bb15, 0, 64 * 1024,   32, SECT_4K | SPI_NOR_QUAD_READ) },
982         { "n25q032",     INFO(0x20ba16, 0, 64 * 1024,   64, SPI_NOR_QUAD_READ) },
983         { "n25q032a",    INFO(0x20bb16, 0, 64 * 1024,   64, SPI_NOR_QUAD_READ) },
984         { "n25q064",     INFO(0x20ba17, 0, 64 * 1024,  128, SECT_4K | SPI_NOR_QUAD_READ) },
985         { "n25q064a",    INFO(0x20bb17, 0, 64 * 1024,  128, SECT_4K | SPI_NOR_QUAD_READ) },
986         { "n25q128a11",  INFO(0x20bb18, 0, 64 * 1024,  256, SECT_4K | SPI_NOR_QUAD_READ) },
987         { "n25q128a13",  INFO(0x20ba18, 0, 64 * 1024,  256, SECT_4K | SPI_NOR_QUAD_READ) },
988         { "n25q256a",    INFO(0x20ba19, 0, 64 * 1024,  512, SECT_4K | SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ) },
989         { "n25q256ax1",  INFO(0x20bb19, 0, 64 * 1024,  512, SECT_4K | SPI_NOR_QUAD_READ) },
990         { "n25q512a",    INFO(0x20bb20, 0, 64 * 1024, 1024, SECT_4K | USE_FSR | SPI_NOR_QUAD_READ) },
991         { "n25q512ax3",  INFO(0x20ba20, 0, 64 * 1024, 1024, SECT_4K | USE_FSR | SPI_NOR_QUAD_READ) },
992         { "n25q00",      INFO(0x20ba21, 0, 64 * 1024, 2048, SECT_4K | USE_FSR | SPI_NOR_QUAD_READ | NO_CHIP_ERASE) },
993         { "n25q00a",     INFO(0x20bb21, 0, 64 * 1024, 2048, SECT_4K | USE_FSR | SPI_NOR_QUAD_READ | NO_CHIP_ERASE) },
994         { "mt25qu02g",   INFO(0x20bb22, 0, 64 * 1024, 4096, SECT_4K | USE_FSR | SPI_NOR_QUAD_READ | NO_CHIP_ERASE) },
995 #endif
996 #ifdef CONFIG_SPI_FLASH_SPANSION        /* SPANSION */
997         /* Spansion/Cypress -- single (large) sector size only, at least
998          * for the chips listed here (without boot sectors).
999          */
1000         { "s25sl032p",  INFO(0x010215, 0x4d00,  64 * 1024,  64, SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ) },
1001         { "s25sl064p",  INFO(0x010216, 0x4d00,  64 * 1024, 128, SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ) },
1002         { "s25fl256s0", INFO(0x010219, 0x4d00, 256 * 1024, 128, USE_CLSR) },
1003         { "s25fl256s1", INFO(0x010219, 0x4d01,  64 * 1024, 512, SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ | USE_CLSR) },
1004         { "s25fl512s",  INFO6(0x010220, 0x4d0081, 256 * 1024, 256, SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ | USE_CLSR) },
1005         { "s25fl512s_256k",  INFO(0x010220, 0x4d00, 256 * 1024, 256, SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ | USE_CLSR) },
1006         { "s25fl512s_64k",  INFO(0x010220, 0x4d01, 64 * 1024, 1024, SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ | USE_CLSR) },
1007         { "s25fl512s_512k",  INFO(0x010220, 0x4f00, 256 * 1024, 256, SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ | USE_CLSR) },
1008         { "s25sl12800", INFO(0x012018, 0x0300, 256 * 1024,  64, 0) },
1009         { "s25sl12801", INFO(0x012018, 0x0301,  64 * 1024, 256, 0) },
1010         { "s25fl128s",  INFO6(0x012018, 0x4d0180, 64 * 1024, 256, SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ | USE_CLSR) },
1011         { "s25fl129p0", INFO(0x012018, 0x4d00, 256 * 1024,  64, SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ | USE_CLSR) },
1012         { "s25fl129p1", INFO(0x012018, 0x4d01,  64 * 1024, 256, SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ | USE_CLSR) },
1013         { "s25sl008a",  INFO(0x010213,      0,  64 * 1024,  16, 0) },
1014         { "s25sl016a",  INFO(0x010214,      0,  64 * 1024,  32, 0) },
1015         { "s25sl032a",  INFO(0x010215,      0,  64 * 1024,  64, 0) },
1016         { "s25sl064a",  INFO(0x010216,      0,  64 * 1024, 128, 0) },
1017         { "s25fl116k",  INFO(0x014015,      0,  64 * 1024,  32, SECT_4K | SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ) },
1018         { "s25fl164k",  INFO(0x014017,      0,  64 * 1024, 128, SECT_4K) },
1019         { "s25fl208k",  INFO(0x014014,      0,  64 * 1024,  16, SECT_4K | SPI_NOR_DUAL_READ) },
1020         { "s25fl128l",  INFO(0x016018,      0,  64 * 1024, 256, SECT_4K | SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ | SPI_NOR_4B_OPCODES) },
1021 #endif
1022 #ifdef CONFIG_SPI_FLASH_SST             /* SST */
1023         /* SST -- large erase sizes are "overlays", "sectors" are 4K */
1024         { "sst25vf040b", INFO(0xbf258d, 0, 64 * 1024,  8, SECT_4K | SST_WRITE) },
1025         { "sst25vf080b", INFO(0xbf258e, 0, 64 * 1024, 16, SECT_4K | SST_WRITE) },
1026         { "sst25vf016b", INFO(0xbf2541, 0, 64 * 1024, 32, SECT_4K | SST_WRITE) },
1027         { "sst25vf032b", INFO(0xbf254a, 0, 64 * 1024, 64, SECT_4K | SST_WRITE) },
1028         { "sst25vf064c", INFO(0xbf254b, 0, 64 * 1024, 128, SECT_4K) },
1029         { "sst25wf512",  INFO(0xbf2501, 0, 64 * 1024,  1, SECT_4K | SST_WRITE) },
1030         { "sst25wf010",  INFO(0xbf2502, 0, 64 * 1024,  2, SECT_4K | SST_WRITE) },
1031         { "sst25wf020",  INFO(0xbf2503, 0, 64 * 1024,  4, SECT_4K | SST_WRITE) },
1032         { "sst25wf020a", INFO(0x621612, 0, 64 * 1024,  4, SECT_4K) },
1033         { "sst25wf040b", INFO(0x621613, 0, 64 * 1024,  8, SECT_4K) },
1034         { "sst25wf040",  INFO(0xbf2504, 0, 64 * 1024,  8, SECT_4K | SST_WRITE) },
1035         { "sst25wf080",  INFO(0xbf2505, 0, 64 * 1024, 16, SECT_4K | SST_WRITE) },
1036         { "sst26vf064b", INFO(0xbf2643, 0, 64 * 1024, 128, SECT_4K | SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ) },
1037         { "sst26wf016",  INFO(0xbf2651, 0, 64 * 1024,  32, SECT_4K) },
1038         { "sst26wf032",  INFO(0xbf2622, 0, 64 * 1024,  64, SECT_4K) },
1039         { "sst26wf064",  INFO(0xbf2643, 0, 64 * 1024, 128, SECT_4K) },
1040 #endif
1041 #ifdef CONFIG_SPI_FLASH_STMICRO         /* STMICRO */
1042         /* ST Microelectronics -- newer production may have feature updates */
1043         { "m25p10",  INFO(0x202011,  0,  32 * 1024,   4, 0) },
1044         { "m25p20",  INFO(0x202012,  0,  64 * 1024,   4, 0) },
1045         { "m25p40",  INFO(0x202013,  0,  64 * 1024,   8, 0) },
1046         { "m25p80",  INFO(0x202014,  0,  64 * 1024,  16, 0) },
1047         { "m25p16",  INFO(0x202015,  0,  64 * 1024,  32, 0) },
1048         { "m25p32",  INFO(0x202016,  0,  64 * 1024,  64, 0) },
1049         { "m25p64",  INFO(0x202017,  0,  64 * 1024, 128, 0) },
1050         { "m25p128", INFO(0x202018,  0, 256 * 1024,  64, 0) },
1051         { "m25pe16", INFO(0x208015,  0, 64 * 1024, 32, SECT_4K) },
1052         { "m25px16",    INFO(0x207115,  0, 64 * 1024, 32, SECT_4K | SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ) },
1053         { "m25px64",    INFO(0x207117,  0, 64 * 1024, 128, 0) },
1054 #endif
1055 #ifdef CONFIG_SPI_FLASH_WINBOND         /* WINBOND */
1056         /* Winbond -- w25x "blocks" are 64K, "sectors" are 4KiB */
1057         { "w25x05", INFO(0xef3010, 0, 64 * 1024,  1,  SECT_4K) },
1058         { "w25x10", INFO(0xef3011, 0, 64 * 1024,  2,  SECT_4K) },
1059         { "w25x20", INFO(0xef3012, 0, 64 * 1024,  4,  SECT_4K) },
1060         { "w25x40", INFO(0xef3013, 0, 64 * 1024,  8,  SECT_4K) },
1061         { "w25x80", INFO(0xef3014, 0, 64 * 1024,  16, SECT_4K) },
1062         { "w25x16", INFO(0xef3015, 0, 64 * 1024,  32, SECT_4K) },
1063         {
1064                 "w25q16dw", INFO(0xef6015, 0, 64 * 1024,  32,
1065                         SECT_4K | SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ |
1066                         SPI_NOR_HAS_LOCK | SPI_NOR_HAS_TB)
1067         },
1068         { "w25x32", INFO(0xef3016, 0, 64 * 1024,  64, SECT_4K) },
1069         { "w25q20cl", INFO(0xef4012, 0, 64 * 1024,  4, SECT_4K) },
1070         { "w25q20bw", INFO(0xef5012, 0, 64 * 1024,  4, SECT_4K) },
1071         { "w25q20ew", INFO(0xef6012, 0, 64 * 1024,  4, SECT_4K) },
1072         { "w25q32", INFO(0xef4016, 0, 64 * 1024,  64, SECT_4K) },
1073         {
1074                 "w25q32dw", INFO(0xef6016, 0, 64 * 1024,  64,
1075                         SECT_4K | SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ |
1076                         SPI_NOR_HAS_LOCK | SPI_NOR_HAS_TB)
1077         },
1078         {
1079                 "w25q32jv", INFO(0xef7016, 0, 64 * 1024,  64,
1080                         SECT_4K | SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ |
1081                         SPI_NOR_HAS_LOCK | SPI_NOR_HAS_TB)
1082         },
1083         { "w25x64", INFO(0xef3017, 0, 64 * 1024, 128, SECT_4K) },
1084         { "w25q64", INFO(0xef4017, 0, 64 * 1024, 128, SECT_4K) },
1085         {
1086                 "w25q64dw", INFO(0xef6017, 0, 64 * 1024, 128,
1087                         SECT_4K | SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ |
1088                         SPI_NOR_HAS_LOCK | SPI_NOR_HAS_TB)
1089         },
1090         {
1091                 "w25q128fw", INFO(0xef6018, 0, 64 * 1024, 256,
1092                         SECT_4K | SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ |
1093                         SPI_NOR_HAS_LOCK | SPI_NOR_HAS_TB)
1094         },
1095         { "w25q80", INFO(0xef5014, 0, 64 * 1024,  16, SECT_4K) },
1096         { "w25q80bl", INFO(0xef4014, 0, 64 * 1024,  16, SECT_4K) },
1097         { "w25q128", INFO(0xef4018, 0, 64 * 1024, 256, SECT_4K) },
1098         { "w25q256", INFO(0xef4019, 0, 64 * 1024, 512, SECT_4K | SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ) },
1099         { "w25m512jv", INFO(0xef7119, 0, 64 * 1024, 1024,
1100                         SECT_4K | SPI_NOR_QUAD_READ | SPI_NOR_DUAL_READ) },
1101 #endif
1102 #ifdef CONFIG_SPI_FLASH_XMC
1103         /* XMC (Wuhan Xinxin Semiconductor Manufacturing Corp.) */
1104         { "XM25QH64A", INFO(0x207017, 0, 64 * 1024, 128, SECT_4K | SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ) },
1105         { "XM25QH128A", INFO(0x207018, 0, 64 * 1024, 256, SECT_4K | SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ) },
1106 #endif
1107         { },
1108 };
1109
1110 static const struct flash_info *spi_nor_read_id(struct spi_nor *nor)
1111 {
1112         int                     tmp;
1113         u8                      id[SPI_NOR_MAX_ID_LEN];
1114         const struct flash_info *info;
1115
1116         if (!ARRAY_SIZE(spi_nor_ids))
1117                 return ERR_PTR(-ENODEV);
1118
1119         tmp = nor->read_reg(nor, SPINOR_OP_RDID, id, SPI_NOR_MAX_ID_LEN);
1120         if (tmp < 0) {
1121                 dev_dbg(nor->dev, "error %d reading JEDEC ID\n", tmp);
1122                 return ERR_PTR(tmp);
1123         }
1124
1125         for (tmp = 0; tmp < ARRAY_SIZE(spi_nor_ids) - 1; tmp++) {
1126                 info = &spi_nor_ids[tmp];
1127                 if (info->id_len) {
1128                         if (!memcmp(info->id, id, info->id_len))
1129                                 return &spi_nor_ids[tmp];
1130                 }
1131         }
1132         dev_err(nor->dev, "unrecognized JEDEC id bytes: %02x, %02x, %02x\n",
1133                 id[0], id[1], id[2]);
1134         return ERR_PTR(-ENODEV);
1135 }
1136
1137 static int spi_nor_read(struct mtd_info *mtd, loff_t from, size_t len,
1138                         size_t *retlen, u_char *buf)
1139 {
1140         struct spi_nor *nor = mtd_to_spi_nor(mtd);
1141         int ret;
1142
1143         dev_dbg(nor->dev, "from 0x%08x, len %zd\n", (u32)from, len);
1144
1145         while (len) {
1146                 loff_t addr = from;
1147
1148                 ret = nor->read(nor, addr, len, buf);
1149                 if (ret == 0) {
1150                         /* We shouldn't see 0-length reads */
1151                         ret = -EIO;
1152                         goto read_err;
1153                 }
1154                 if (ret < 0)
1155                         goto read_err;
1156
1157                 *retlen += ret;
1158                 buf += ret;
1159                 from += ret;
1160                 len -= ret;
1161         }
1162         ret = 0;
1163
1164 read_err:
1165         return ret;
1166 }
1167
1168 #ifdef CONFIG_SPI_FLASH_SST
1169 static int sst_write(struct mtd_info *mtd, loff_t to, size_t len,
1170                      size_t *retlen, const u_char *buf)
1171 {
1172         struct spi_nor *nor = mtd_to_spi_nor(mtd);
1173         size_t actual;
1174         int ret;
1175
1176         dev_dbg(nor->dev, "to 0x%08x, len %zd\n", (u32)to, len);
1177
1178         write_enable(nor);
1179
1180         nor->sst_write_second = false;
1181
1182         actual = to % 2;
1183         /* Start write from odd address. */
1184         if (actual) {
1185                 nor->program_opcode = SPINOR_OP_BP;
1186
1187                 /* write one byte. */
1188                 ret = nor->write(nor, to, 1, buf);
1189                 if (ret < 0)
1190                         goto sst_write_err;
1191                 ret = spi_nor_wait_till_ready(nor);
1192                 if (ret)
1193                         goto sst_write_err;
1194         }
1195         to += actual;
1196
1197         /* Write out most of the data here. */
1198         for (; actual < len - 1; actual += 2) {
1199                 nor->program_opcode = SPINOR_OP_AAI_WP;
1200
1201                 /* write two bytes. */
1202                 ret = nor->write(nor, to, 2, buf + actual);
1203                 if (ret < 0)
1204                         goto sst_write_err;
1205                 ret = spi_nor_wait_till_ready(nor);
1206                 if (ret)
1207                         goto sst_write_err;
1208                 to += 2;
1209                 nor->sst_write_second = true;
1210         }
1211         nor->sst_write_second = false;
1212
1213         write_disable(nor);
1214         ret = spi_nor_wait_till_ready(nor);
1215         if (ret)
1216                 goto sst_write_err;
1217
1218         /* Write out trailing byte if it exists. */
1219         if (actual != len) {
1220                 write_enable(nor);
1221
1222                 nor->program_opcode = SPINOR_OP_BP;
1223                 ret = nor->write(nor, to, 1, buf + actual);
1224                 if (ret < 0)
1225                         goto sst_write_err;
1226                 ret = spi_nor_wait_till_ready(nor);
1227                 if (ret)
1228                         goto sst_write_err;
1229                 write_disable(nor);
1230                 actual += 1;
1231         }
1232 sst_write_err:
1233         *retlen += actual;
1234         return ret;
1235 }
1236 #endif
1237 /*
1238  * Write an address range to the nor chip.  Data must be written in
1239  * FLASH_PAGESIZE chunks.  The address range may be any size provided
1240  * it is within the physical boundaries.
1241  */
1242 static int spi_nor_write(struct mtd_info *mtd, loff_t to, size_t len,
1243         size_t *retlen, const u_char *buf)
1244 {
1245         struct spi_nor *nor = mtd_to_spi_nor(mtd);
1246         size_t page_offset, page_remain, i;
1247         ssize_t ret;
1248
1249         dev_dbg(nor->dev, "to 0x%08x, len %zd\n", (u32)to, len);
1250
1251         for (i = 0; i < len; ) {
1252                 ssize_t written;
1253                 loff_t addr = to + i;
1254
1255                 /*
1256                  * If page_size is a power of two, the offset can be quickly
1257                  * calculated with an AND operation. On the other cases we
1258                  * need to do a modulus operation (more expensive).
1259                  * Power of two numbers have only one bit set and we can use
1260                  * the instruction hweight32 to detect if we need to do a
1261                  * modulus (do_div()) or not.
1262                  */
1263                 if (hweight32(nor->page_size) == 1) {
1264                         page_offset = addr & (nor->page_size - 1);
1265                 } else {
1266                         u64 aux = addr;
1267
1268                         page_offset = do_div(aux, nor->page_size);
1269                 }
1270                 /* the size of data remaining on the first page */
1271                 page_remain = min_t(size_t,
1272                                     nor->page_size - page_offset, len - i);
1273
1274                 write_enable(nor);
1275                 ret = nor->write(nor, addr, page_remain, buf + i);
1276                 if (ret < 0)
1277                         goto write_err;
1278                 written = ret;
1279
1280                 ret = spi_nor_wait_till_ready(nor);
1281                 if (ret)
1282                         goto write_err;
1283                 *retlen += written;
1284                 i += written;
1285                 if (written != page_remain) {
1286                         ret = -EIO;
1287                         goto write_err;
1288                 }
1289         }
1290
1291 write_err:
1292         return ret;
1293 }
1294
1295 #ifdef CONFIG_SPI_FLASH_MACRONIX
1296 /**
1297  * macronix_quad_enable() - set QE bit in Status Register.
1298  * @nor:        pointer to a 'struct spi_nor'
1299  *
1300  * Set the Quad Enable (QE) bit in the Status Register.
1301  *
1302  * bit 6 of the Status Register is the QE bit for Macronix like QSPI memories.
1303  *
1304  * Return: 0 on success, -errno otherwise.
1305  */
1306 static int macronix_quad_enable(struct spi_nor *nor)
1307 {
1308         int ret, val;
1309
1310         val = read_sr(nor);
1311         if (val < 0)
1312                 return val;
1313         if (val & SR_QUAD_EN_MX)
1314                 return 0;
1315
1316         write_enable(nor);
1317
1318         write_sr(nor, val | SR_QUAD_EN_MX);
1319
1320         ret = spi_nor_wait_till_ready(nor);
1321         if (ret)
1322                 return ret;
1323
1324         ret = read_sr(nor);
1325         if (!(ret > 0 && (ret & SR_QUAD_EN_MX))) {
1326                 dev_err(nor->dev, "Macronix Quad bit not set\n");
1327                 return -EINVAL;
1328         }
1329
1330         return 0;
1331 }
1332 #endif
1333
1334 #if defined(CONFIG_SPI_FLASH_SPANSION) || defined(CONFIG_SPI_FLASH_WINBOND)
1335 /*
1336  * Write status Register and configuration register with 2 bytes
1337  * The first byte will be written to the status register, while the
1338  * second byte will be written to the configuration register.
1339  * Return negative if error occurred.
1340  */
1341 static int write_sr_cr(struct spi_nor *nor, u8 *sr_cr)
1342 {
1343         int ret;
1344
1345         write_enable(nor);
1346
1347         ret = nor->write_reg(nor, SPINOR_OP_WRSR, sr_cr, 2);
1348         if (ret < 0) {
1349                 dev_dbg(nor->dev,
1350                         "error while writing configuration register\n");
1351                 return -EINVAL;
1352         }
1353
1354         ret = spi_nor_wait_till_ready(nor);
1355         if (ret) {
1356                 dev_dbg(nor->dev,
1357                         "timeout while writing configuration register\n");
1358                 return ret;
1359         }
1360
1361         return 0;
1362 }
1363
1364 /**
1365  * spansion_read_cr_quad_enable() - set QE bit in Configuration Register.
1366  * @nor:        pointer to a 'struct spi_nor'
1367  *
1368  * Set the Quad Enable (QE) bit in the Configuration Register.
1369  * This function should be used with QSPI memories supporting the Read
1370  * Configuration Register (35h) instruction.
1371  *
1372  * bit 1 of the Configuration Register is the QE bit for Spansion like QSPI
1373  * memories.
1374  *
1375  * Return: 0 on success, -errno otherwise.
1376  */
1377 static int spansion_read_cr_quad_enable(struct spi_nor *nor)
1378 {
1379         u8 sr_cr[2];
1380         int ret;
1381
1382         /* Check current Quad Enable bit value. */
1383         ret = read_cr(nor);
1384         if (ret < 0) {
1385                 dev_dbg(dev, "error while reading configuration register\n");
1386                 return -EINVAL;
1387         }
1388
1389         if (ret & CR_QUAD_EN_SPAN)
1390                 return 0;
1391
1392         sr_cr[1] = ret | CR_QUAD_EN_SPAN;
1393
1394         /* Keep the current value of the Status Register. */
1395         ret = read_sr(nor);
1396         if (ret < 0) {
1397                 dev_dbg(dev, "error while reading status register\n");
1398                 return -EINVAL;
1399         }
1400         sr_cr[0] = ret;
1401
1402         ret = write_sr_cr(nor, sr_cr);
1403         if (ret)
1404                 return ret;
1405
1406         /* Read back and check it. */
1407         ret = read_cr(nor);
1408         if (!(ret > 0 && (ret & CR_QUAD_EN_SPAN))) {
1409                 dev_dbg(nor->dev, "Spansion Quad bit not set\n");
1410                 return -EINVAL;
1411         }
1412
1413         return 0;
1414 }
1415
1416 #if CONFIG_IS_ENABLED(SPI_FLASH_SFDP_SUPPORT)
1417 /**
1418  * spansion_no_read_cr_quad_enable() - set QE bit in Configuration Register.
1419  * @nor:        pointer to a 'struct spi_nor'
1420  *
1421  * Set the Quad Enable (QE) bit in the Configuration Register.
1422  * This function should be used with QSPI memories not supporting the Read
1423  * Configuration Register (35h) instruction.
1424  *
1425  * bit 1 of the Configuration Register is the QE bit for Spansion like QSPI
1426  * memories.
1427  *
1428  * Return: 0 on success, -errno otherwise.
1429  */
1430 static int spansion_no_read_cr_quad_enable(struct spi_nor *nor)
1431 {
1432         u8 sr_cr[2];
1433         int ret;
1434
1435         /* Keep the current value of the Status Register. */
1436         ret = read_sr(nor);
1437         if (ret < 0) {
1438                 dev_dbg(nor->dev, "error while reading status register\n");
1439                 return -EINVAL;
1440         }
1441         sr_cr[0] = ret;
1442         sr_cr[1] = CR_QUAD_EN_SPAN;
1443
1444         return write_sr_cr(nor, sr_cr);
1445 }
1446
1447 #endif /* CONFIG_SPI_FLASH_SFDP_SUPPORT */
1448 #endif /* CONFIG_SPI_FLASH_SPANSION */
1449
1450 struct spi_nor_read_command {
1451         u8                      num_mode_clocks;
1452         u8                      num_wait_states;
1453         u8                      opcode;
1454         enum spi_nor_protocol   proto;
1455 };
1456
1457 struct spi_nor_pp_command {
1458         u8                      opcode;
1459         enum spi_nor_protocol   proto;
1460 };
1461
1462 enum spi_nor_read_command_index {
1463         SNOR_CMD_READ,
1464         SNOR_CMD_READ_FAST,
1465         SNOR_CMD_READ_1_1_1_DTR,
1466
1467         /* Dual SPI */
1468         SNOR_CMD_READ_1_1_2,
1469         SNOR_CMD_READ_1_2_2,
1470         SNOR_CMD_READ_2_2_2,
1471         SNOR_CMD_READ_1_2_2_DTR,
1472
1473         /* Quad SPI */
1474         SNOR_CMD_READ_1_1_4,
1475         SNOR_CMD_READ_1_4_4,
1476         SNOR_CMD_READ_4_4_4,
1477         SNOR_CMD_READ_1_4_4_DTR,
1478
1479         /* Octo SPI */
1480         SNOR_CMD_READ_1_1_8,
1481         SNOR_CMD_READ_1_8_8,
1482         SNOR_CMD_READ_8_8_8,
1483         SNOR_CMD_READ_1_8_8_DTR,
1484
1485         SNOR_CMD_READ_MAX
1486 };
1487
1488 enum spi_nor_pp_command_index {
1489         SNOR_CMD_PP,
1490
1491         /* Quad SPI */
1492         SNOR_CMD_PP_1_1_4,
1493         SNOR_CMD_PP_1_4_4,
1494         SNOR_CMD_PP_4_4_4,
1495
1496         /* Octo SPI */
1497         SNOR_CMD_PP_1_1_8,
1498         SNOR_CMD_PP_1_8_8,
1499         SNOR_CMD_PP_8_8_8,
1500
1501         SNOR_CMD_PP_MAX
1502 };
1503
1504 struct spi_nor_flash_parameter {
1505         u64                             size;
1506         u32                             page_size;
1507
1508         struct spi_nor_hwcaps           hwcaps;
1509         struct spi_nor_read_command     reads[SNOR_CMD_READ_MAX];
1510         struct spi_nor_pp_command       page_programs[SNOR_CMD_PP_MAX];
1511
1512         int (*quad_enable)(struct spi_nor *nor);
1513 };
1514
1515 static void
1516 spi_nor_set_read_settings(struct spi_nor_read_command *read,
1517                           u8 num_mode_clocks,
1518                           u8 num_wait_states,
1519                           u8 opcode,
1520                           enum spi_nor_protocol proto)
1521 {
1522         read->num_mode_clocks = num_mode_clocks;
1523         read->num_wait_states = num_wait_states;
1524         read->opcode = opcode;
1525         read->proto = proto;
1526 }
1527
1528 static void
1529 spi_nor_set_pp_settings(struct spi_nor_pp_command *pp,
1530                         u8 opcode,
1531                         enum spi_nor_protocol proto)
1532 {
1533         pp->opcode = opcode;
1534         pp->proto = proto;
1535 }
1536
1537 #if CONFIG_IS_ENABLED(SPI_FLASH_SFDP_SUPPORT)
1538 /*
1539  * Serial Flash Discoverable Parameters (SFDP) parsing.
1540  */
1541
1542 /**
1543  * spi_nor_read_sfdp() - read Serial Flash Discoverable Parameters.
1544  * @nor:        pointer to a 'struct spi_nor'
1545  * @addr:       offset in the SFDP area to start reading data from
1546  * @len:        number of bytes to read
1547  * @buf:        buffer where the SFDP data are copied into (dma-safe memory)
1548  *
1549  * Whatever the actual numbers of bytes for address and dummy cycles are
1550  * for (Fast) Read commands, the Read SFDP (5Ah) instruction is always
1551  * followed by a 3-byte address and 8 dummy clock cycles.
1552  *
1553  * Return: 0 on success, -errno otherwise.
1554  */
1555 static int spi_nor_read_sfdp(struct spi_nor *nor, u32 addr,
1556                              size_t len, void *buf)
1557 {
1558         u8 addr_width, read_opcode, read_dummy;
1559         int ret;
1560
1561         read_opcode = nor->read_opcode;
1562         addr_width = nor->addr_width;
1563         read_dummy = nor->read_dummy;
1564
1565         nor->read_opcode = SPINOR_OP_RDSFDP;
1566         nor->addr_width = 3;
1567         nor->read_dummy = 8;
1568
1569         while (len) {
1570                 ret = nor->read(nor, addr, len, (u8 *)buf);
1571                 if (!ret || ret > len) {
1572                         ret = -EIO;
1573                         goto read_err;
1574                 }
1575                 if (ret < 0)
1576                         goto read_err;
1577
1578                 buf += ret;
1579                 addr += ret;
1580                 len -= ret;
1581         }
1582         ret = 0;
1583
1584 read_err:
1585         nor->read_opcode = read_opcode;
1586         nor->addr_width = addr_width;
1587         nor->read_dummy = read_dummy;
1588
1589         return ret;
1590 }
1591
1592 struct sfdp_parameter_header {
1593         u8              id_lsb;
1594         u8              minor;
1595         u8              major;
1596         u8              length; /* in double words */
1597         u8              parameter_table_pointer[3]; /* byte address */
1598         u8              id_msb;
1599 };
1600
1601 #define SFDP_PARAM_HEADER_ID(p) (((p)->id_msb << 8) | (p)->id_lsb)
1602 #define SFDP_PARAM_HEADER_PTP(p) \
1603         (((p)->parameter_table_pointer[2] << 16) | \
1604          ((p)->parameter_table_pointer[1] <<  8) | \
1605          ((p)->parameter_table_pointer[0] <<  0))
1606
1607 #define SFDP_BFPT_ID            0xff00  /* Basic Flash Parameter Table */
1608 #define SFDP_SECTOR_MAP_ID      0xff81  /* Sector Map Table */
1609
1610 #define SFDP_SIGNATURE          0x50444653U
1611 #define SFDP_JESD216_MAJOR      1
1612 #define SFDP_JESD216_MINOR      0
1613 #define SFDP_JESD216A_MINOR     5
1614 #define SFDP_JESD216B_MINOR     6
1615
1616 struct sfdp_header {
1617         u32             signature; /* Ox50444653U <=> "SFDP" */
1618         u8              minor;
1619         u8              major;
1620         u8              nph; /* 0-base number of parameter headers */
1621         u8              unused;
1622
1623         /* Basic Flash Parameter Table. */
1624         struct sfdp_parameter_header    bfpt_header;
1625 };
1626
1627 /* Basic Flash Parameter Table */
1628
1629 /*
1630  * JESD216 rev B defines a Basic Flash Parameter Table of 16 DWORDs.
1631  * They are indexed from 1 but C arrays are indexed from 0.
1632  */
1633 #define BFPT_DWORD(i)           ((i) - 1)
1634 #define BFPT_DWORD_MAX          16
1635
1636 /* The first version of JESB216 defined only 9 DWORDs. */
1637 #define BFPT_DWORD_MAX_JESD216                  9
1638
1639 /* 1st DWORD. */
1640 #define BFPT_DWORD1_FAST_READ_1_1_2             BIT(16)
1641 #define BFPT_DWORD1_ADDRESS_BYTES_MASK          GENMASK(18, 17)
1642 #define BFPT_DWORD1_ADDRESS_BYTES_3_ONLY        (0x0UL << 17)
1643 #define BFPT_DWORD1_ADDRESS_BYTES_3_OR_4        (0x1UL << 17)
1644 #define BFPT_DWORD1_ADDRESS_BYTES_4_ONLY        (0x2UL << 17)
1645 #define BFPT_DWORD1_DTR                         BIT(19)
1646 #define BFPT_DWORD1_FAST_READ_1_2_2             BIT(20)
1647 #define BFPT_DWORD1_FAST_READ_1_4_4             BIT(21)
1648 #define BFPT_DWORD1_FAST_READ_1_1_4             BIT(22)
1649
1650 /* 5th DWORD. */
1651 #define BFPT_DWORD5_FAST_READ_2_2_2             BIT(0)
1652 #define BFPT_DWORD5_FAST_READ_4_4_4             BIT(4)
1653
1654 /* 11th DWORD. */
1655 #define BFPT_DWORD11_PAGE_SIZE_SHIFT            4
1656 #define BFPT_DWORD11_PAGE_SIZE_MASK             GENMASK(7, 4)
1657
1658 /* 15th DWORD. */
1659
1660 /*
1661  * (from JESD216 rev B)
1662  * Quad Enable Requirements (QER):
1663  * - 000b: Device does not have a QE bit. Device detects 1-1-4 and 1-4-4
1664  *         reads based on instruction. DQ3/HOLD# functions are hold during
1665  *         instruction phase.
1666  * - 001b: QE is bit 1 of status register 2. It is set via Write Status with
1667  *         two data bytes where bit 1 of the second byte is one.
1668  *         [...]
1669  *         Writing only one byte to the status register has the side-effect of
1670  *         clearing status register 2, including the QE bit. The 100b code is
1671  *         used if writing one byte to the status register does not modify
1672  *         status register 2.
1673  * - 010b: QE is bit 6 of status register 1. It is set via Write Status with
1674  *         one data byte where bit 6 is one.
1675  *         [...]
1676  * - 011b: QE is bit 7 of status register 2. It is set via Write status
1677  *         register 2 instruction 3Eh with one data byte where bit 7 is one.
1678  *         [...]
1679  *         The status register 2 is read using instruction 3Fh.
1680  * - 100b: QE is bit 1 of status register 2. It is set via Write Status with
1681  *         two data bytes where bit 1 of the second byte is one.
1682  *         [...]
1683  *         In contrast to the 001b code, writing one byte to the status
1684  *         register does not modify status register 2.
1685  * - 101b: QE is bit 1 of status register 2. Status register 1 is read using
1686  *         Read Status instruction 05h. Status register2 is read using
1687  *         instruction 35h. QE is set via Writ Status instruction 01h with
1688  *         two data bytes where bit 1 of the second byte is one.
1689  *         [...]
1690  */
1691 #define BFPT_DWORD15_QER_MASK                   GENMASK(22, 20)
1692 #define BFPT_DWORD15_QER_NONE                   (0x0UL << 20) /* Micron */
1693 #define BFPT_DWORD15_QER_SR2_BIT1_BUGGY         (0x1UL << 20)
1694 #define BFPT_DWORD15_QER_SR1_BIT6               (0x2UL << 20) /* Macronix */
1695 #define BFPT_DWORD15_QER_SR2_BIT7               (0x3UL << 20)
1696 #define BFPT_DWORD15_QER_SR2_BIT1_NO_RD         (0x4UL << 20)
1697 #define BFPT_DWORD15_QER_SR2_BIT1               (0x5UL << 20) /* Spansion */
1698
1699 struct sfdp_bfpt {
1700         u32     dwords[BFPT_DWORD_MAX];
1701 };
1702
1703 /* Fast Read settings. */
1704
1705 static void
1706 spi_nor_set_read_settings_from_bfpt(struct spi_nor_read_command *read,
1707                                     u16 half,
1708                                     enum spi_nor_protocol proto)
1709 {
1710         read->num_mode_clocks = (half >> 5) & 0x07;
1711         read->num_wait_states = (half >> 0) & 0x1f;
1712         read->opcode = (half >> 8) & 0xff;
1713         read->proto = proto;
1714 }
1715
1716 struct sfdp_bfpt_read {
1717         /* The Fast Read x-y-z hardware capability in params->hwcaps.mask. */
1718         u32                     hwcaps;
1719
1720         /*
1721          * The <supported_bit> bit in <supported_dword> BFPT DWORD tells us
1722          * whether the Fast Read x-y-z command is supported.
1723          */
1724         u32                     supported_dword;
1725         u32                     supported_bit;
1726
1727         /*
1728          * The half-word at offset <setting_shift> in <setting_dword> BFPT DWORD
1729          * encodes the op code, the number of mode clocks and the number of wait
1730          * states to be used by Fast Read x-y-z command.
1731          */
1732         u32                     settings_dword;
1733         u32                     settings_shift;
1734
1735         /* The SPI protocol for this Fast Read x-y-z command. */
1736         enum spi_nor_protocol   proto;
1737 };
1738
1739 static const struct sfdp_bfpt_read sfdp_bfpt_reads[] = {
1740         /* Fast Read 1-1-2 */
1741         {
1742                 SNOR_HWCAPS_READ_1_1_2,
1743                 BFPT_DWORD(1), BIT(16), /* Supported bit */
1744                 BFPT_DWORD(4), 0,       /* Settings */
1745                 SNOR_PROTO_1_1_2,
1746         },
1747
1748         /* Fast Read 1-2-2 */
1749         {
1750                 SNOR_HWCAPS_READ_1_2_2,
1751                 BFPT_DWORD(1), BIT(20), /* Supported bit */
1752                 BFPT_DWORD(4), 16,      /* Settings */
1753                 SNOR_PROTO_1_2_2,
1754         },
1755
1756         /* Fast Read 2-2-2 */
1757         {
1758                 SNOR_HWCAPS_READ_2_2_2,
1759                 BFPT_DWORD(5),  BIT(0), /* Supported bit */
1760                 BFPT_DWORD(6), 16,      /* Settings */
1761                 SNOR_PROTO_2_2_2,
1762         },
1763
1764         /* Fast Read 1-1-4 */
1765         {
1766                 SNOR_HWCAPS_READ_1_1_4,
1767                 BFPT_DWORD(1), BIT(22), /* Supported bit */
1768                 BFPT_DWORD(3), 16,      /* Settings */
1769                 SNOR_PROTO_1_1_4,
1770         },
1771
1772         /* Fast Read 1-4-4 */
1773         {
1774                 SNOR_HWCAPS_READ_1_4_4,
1775                 BFPT_DWORD(1), BIT(21), /* Supported bit */
1776                 BFPT_DWORD(3), 0,       /* Settings */
1777                 SNOR_PROTO_1_4_4,
1778         },
1779
1780         /* Fast Read 4-4-4 */
1781         {
1782                 SNOR_HWCAPS_READ_4_4_4,
1783                 BFPT_DWORD(5), BIT(4),  /* Supported bit */
1784                 BFPT_DWORD(7), 16,      /* Settings */
1785                 SNOR_PROTO_4_4_4,
1786         },
1787 };
1788
1789 struct sfdp_bfpt_erase {
1790         /*
1791          * The half-word at offset <shift> in DWORD <dwoard> encodes the
1792          * op code and erase sector size to be used by Sector Erase commands.
1793          */
1794         u32                     dword;
1795         u32                     shift;
1796 };
1797
1798 static const struct sfdp_bfpt_erase sfdp_bfpt_erases[] = {
1799         /* Erase Type 1 in DWORD8 bits[15:0] */
1800         {BFPT_DWORD(8), 0},
1801
1802         /* Erase Type 2 in DWORD8 bits[31:16] */
1803         {BFPT_DWORD(8), 16},
1804
1805         /* Erase Type 3 in DWORD9 bits[15:0] */
1806         {BFPT_DWORD(9), 0},
1807
1808         /* Erase Type 4 in DWORD9 bits[31:16] */
1809         {BFPT_DWORD(9), 16},
1810 };
1811
1812 static int spi_nor_hwcaps_read2cmd(u32 hwcaps);
1813
1814 /**
1815  * spi_nor_parse_bfpt() - read and parse the Basic Flash Parameter Table.
1816  * @nor:                pointer to a 'struct spi_nor'
1817  * @bfpt_header:        pointer to the 'struct sfdp_parameter_header' describing
1818  *                      the Basic Flash Parameter Table length and version
1819  * @params:             pointer to the 'struct spi_nor_flash_parameter' to be
1820  *                      filled
1821  *
1822  * The Basic Flash Parameter Table is the main and only mandatory table as
1823  * defined by the SFDP (JESD216) specification.
1824  * It provides us with the total size (memory density) of the data array and
1825  * the number of address bytes for Fast Read, Page Program and Sector Erase
1826  * commands.
1827  * For Fast READ commands, it also gives the number of mode clock cycles and
1828  * wait states (regrouped in the number of dummy clock cycles) for each
1829  * supported instruction op code.
1830  * For Page Program, the page size is now available since JESD216 rev A, however
1831  * the supported instruction op codes are still not provided.
1832  * For Sector Erase commands, this table stores the supported instruction op
1833  * codes and the associated sector sizes.
1834  * Finally, the Quad Enable Requirements (QER) are also available since JESD216
1835  * rev A. The QER bits encode the manufacturer dependent procedure to be
1836  * executed to set the Quad Enable (QE) bit in some internal register of the
1837  * Quad SPI memory. Indeed the QE bit, when it exists, must be set before
1838  * sending any Quad SPI command to the memory. Actually, setting the QE bit
1839  * tells the memory to reassign its WP# and HOLD#/RESET# pins to functions IO2
1840  * and IO3 hence enabling 4 (Quad) I/O lines.
1841  *
1842  * Return: 0 on success, -errno otherwise.
1843  */
1844 static int spi_nor_parse_bfpt(struct spi_nor *nor,
1845                               const struct sfdp_parameter_header *bfpt_header,
1846                               struct spi_nor_flash_parameter *params)
1847 {
1848         struct mtd_info *mtd = &nor->mtd;
1849         struct sfdp_bfpt bfpt;
1850         size_t len;
1851         int i, cmd, err;
1852         u32 addr;
1853         u16 half;
1854
1855         /* JESD216 Basic Flash Parameter Table length is at least 9 DWORDs. */
1856         if (bfpt_header->length < BFPT_DWORD_MAX_JESD216)
1857                 return -EINVAL;
1858
1859         /* Read the Basic Flash Parameter Table. */
1860         len = min_t(size_t, sizeof(bfpt),
1861                     bfpt_header->length * sizeof(u32));
1862         addr = SFDP_PARAM_HEADER_PTP(bfpt_header);
1863         memset(&bfpt, 0, sizeof(bfpt));
1864         err = spi_nor_read_sfdp(nor,  addr, len, &bfpt);
1865         if (err < 0)
1866                 return err;
1867
1868         /* Fix endianness of the BFPT DWORDs. */
1869         for (i = 0; i < BFPT_DWORD_MAX; i++)
1870                 bfpt.dwords[i] = le32_to_cpu(bfpt.dwords[i]);
1871
1872         /* Number of address bytes. */
1873         switch (bfpt.dwords[BFPT_DWORD(1)] & BFPT_DWORD1_ADDRESS_BYTES_MASK) {
1874         case BFPT_DWORD1_ADDRESS_BYTES_3_ONLY:
1875                 nor->addr_width = 3;
1876                 break;
1877
1878         case BFPT_DWORD1_ADDRESS_BYTES_4_ONLY:
1879                 nor->addr_width = 4;
1880                 break;
1881
1882         default:
1883                 break;
1884         }
1885
1886         /* Flash Memory Density (in bits). */
1887         params->size = bfpt.dwords[BFPT_DWORD(2)];
1888         if (params->size & BIT(31)) {
1889                 params->size &= ~BIT(31);
1890
1891                 /*
1892                  * Prevent overflows on params->size. Anyway, a NOR of 2^64
1893                  * bits is unlikely to exist so this error probably means
1894                  * the BFPT we are reading is corrupted/wrong.
1895                  */
1896                 if (params->size > 63)
1897                         return -EINVAL;
1898
1899                 params->size = 1ULL << params->size;
1900         } else {
1901                 params->size++;
1902         }
1903         params->size >>= 3; /* Convert to bytes. */
1904
1905         /* Fast Read settings. */
1906         for (i = 0; i < ARRAY_SIZE(sfdp_bfpt_reads); i++) {
1907                 const struct sfdp_bfpt_read *rd = &sfdp_bfpt_reads[i];
1908                 struct spi_nor_read_command *read;
1909
1910                 if (!(bfpt.dwords[rd->supported_dword] & rd->supported_bit)) {
1911                         params->hwcaps.mask &= ~rd->hwcaps;
1912                         continue;
1913                 }
1914
1915                 params->hwcaps.mask |= rd->hwcaps;
1916                 cmd = spi_nor_hwcaps_read2cmd(rd->hwcaps);
1917                 read = &params->reads[cmd];
1918                 half = bfpt.dwords[rd->settings_dword] >> rd->settings_shift;
1919                 spi_nor_set_read_settings_from_bfpt(read, half, rd->proto);
1920         }
1921
1922         /* Sector Erase settings. */
1923         for (i = 0; i < ARRAY_SIZE(sfdp_bfpt_erases); i++) {
1924                 const struct sfdp_bfpt_erase *er = &sfdp_bfpt_erases[i];
1925                 u32 erasesize;
1926                 u8 opcode;
1927
1928                 half = bfpt.dwords[er->dword] >> er->shift;
1929                 erasesize = half & 0xff;
1930
1931                 /* erasesize == 0 means this Erase Type is not supported. */
1932                 if (!erasesize)
1933                         continue;
1934
1935                 erasesize = 1U << erasesize;
1936                 opcode = (half >> 8) & 0xff;
1937 #ifdef CONFIG_MTD_SPI_NOR_USE_4K_SECTORS
1938                 if (erasesize == SZ_4K) {
1939                         nor->erase_opcode = opcode;
1940                         mtd->erasesize = erasesize;
1941                         break;
1942                 }
1943 #endif
1944                 if (!mtd->erasesize || mtd->erasesize < erasesize) {
1945                         nor->erase_opcode = opcode;
1946                         mtd->erasesize = erasesize;
1947                 }
1948         }
1949
1950         /* Stop here if not JESD216 rev A or later. */
1951         if (bfpt_header->length < BFPT_DWORD_MAX)
1952                 return 0;
1953
1954         /* Page size: this field specifies 'N' so the page size = 2^N bytes. */
1955         params->page_size = bfpt.dwords[BFPT_DWORD(11)];
1956         params->page_size &= BFPT_DWORD11_PAGE_SIZE_MASK;
1957         params->page_size >>= BFPT_DWORD11_PAGE_SIZE_SHIFT;
1958         params->page_size = 1U << params->page_size;
1959
1960         /* Quad Enable Requirements. */
1961         switch (bfpt.dwords[BFPT_DWORD(15)] & BFPT_DWORD15_QER_MASK) {
1962         case BFPT_DWORD15_QER_NONE:
1963                 params->quad_enable = NULL;
1964                 break;
1965 #if defined(CONFIG_SPI_FLASH_SPANSION) || defined(CONFIG_SPI_FLASH_WINBOND)
1966         case BFPT_DWORD15_QER_SR2_BIT1_BUGGY:
1967         case BFPT_DWORD15_QER_SR2_BIT1_NO_RD:
1968                 params->quad_enable = spansion_no_read_cr_quad_enable;
1969                 break;
1970 #endif
1971 #ifdef CONFIG_SPI_FLASH_MACRONIX
1972         case BFPT_DWORD15_QER_SR1_BIT6:
1973                 params->quad_enable = macronix_quad_enable;
1974                 break;
1975 #endif
1976 #if defined(CONFIG_SPI_FLASH_SPANSION) || defined(CONFIG_SPI_FLASH_WINBOND)
1977         case BFPT_DWORD15_QER_SR2_BIT1:
1978                 params->quad_enable = spansion_read_cr_quad_enable;
1979                 break;
1980 #endif
1981         default:
1982                 return -EINVAL;
1983         }
1984
1985         return 0;
1986 }
1987
1988 /**
1989  * spi_nor_parse_sfdp() - parse the Serial Flash Discoverable Parameters.
1990  * @nor:                pointer to a 'struct spi_nor'
1991  * @params:             pointer to the 'struct spi_nor_flash_parameter' to be
1992  *                      filled
1993  *
1994  * The Serial Flash Discoverable Parameters are described by the JEDEC JESD216
1995  * specification. This is a standard which tends to supported by almost all
1996  * (Q)SPI memory manufacturers. Those hard-coded tables allow us to learn at
1997  * runtime the main parameters needed to perform basic SPI flash operations such
1998  * as Fast Read, Page Program or Sector Erase commands.
1999  *
2000  * Return: 0 on success, -errno otherwise.
2001  */
2002 static int spi_nor_parse_sfdp(struct spi_nor *nor,
2003                               struct spi_nor_flash_parameter *params)
2004 {
2005         const struct sfdp_parameter_header *param_header, *bfpt_header;
2006         struct sfdp_parameter_header *param_headers = NULL;
2007         struct sfdp_header header;
2008         size_t psize;
2009         int i, err;
2010
2011         /* Get the SFDP header. */
2012         err = spi_nor_read_sfdp(nor, 0, sizeof(header), &header);
2013         if (err < 0)
2014                 return err;
2015
2016         /* Check the SFDP header version. */
2017         if (le32_to_cpu(header.signature) != SFDP_SIGNATURE ||
2018             header.major != SFDP_JESD216_MAJOR)
2019                 return -EINVAL;
2020
2021         /*
2022          * Verify that the first and only mandatory parameter header is a
2023          * Basic Flash Parameter Table header as specified in JESD216.
2024          */
2025         bfpt_header = &header.bfpt_header;
2026         if (SFDP_PARAM_HEADER_ID(bfpt_header) != SFDP_BFPT_ID ||
2027             bfpt_header->major != SFDP_JESD216_MAJOR)
2028                 return -EINVAL;
2029
2030         /*
2031          * Allocate memory then read all parameter headers with a single
2032          * Read SFDP command. These parameter headers will actually be parsed
2033          * twice: a first time to get the latest revision of the basic flash
2034          * parameter table, then a second time to handle the supported optional
2035          * tables.
2036          * Hence we read the parameter headers once for all to reduce the
2037          * processing time. Also we use kmalloc() instead of devm_kmalloc()
2038          * because we don't need to keep these parameter headers: the allocated
2039          * memory is always released with kfree() before exiting this function.
2040          */
2041         if (header.nph) {
2042                 psize = header.nph * sizeof(*param_headers);
2043
2044                 param_headers = kmalloc(psize, GFP_KERNEL);
2045                 if (!param_headers)
2046                         return -ENOMEM;
2047
2048                 err = spi_nor_read_sfdp(nor, sizeof(header),
2049                                         psize, param_headers);
2050                 if (err < 0) {
2051                         dev_err(dev, "failed to read SFDP parameter headers\n");
2052                         goto exit;
2053                 }
2054         }
2055
2056         /*
2057          * Check other parameter headers to get the latest revision of
2058          * the basic flash parameter table.
2059          */
2060         for (i = 0; i < header.nph; i++) {
2061                 param_header = &param_headers[i];
2062
2063                 if (SFDP_PARAM_HEADER_ID(param_header) == SFDP_BFPT_ID &&
2064                     param_header->major == SFDP_JESD216_MAJOR &&
2065                     (param_header->minor > bfpt_header->minor ||
2066                      (param_header->minor == bfpt_header->minor &&
2067                       param_header->length > bfpt_header->length)))
2068                         bfpt_header = param_header;
2069         }
2070
2071         err = spi_nor_parse_bfpt(nor, bfpt_header, params);
2072         if (err)
2073                 goto exit;
2074
2075         /* Parse other parameter headers. */
2076         for (i = 0; i < header.nph; i++) {
2077                 param_header = &param_headers[i];
2078
2079                 switch (SFDP_PARAM_HEADER_ID(param_header)) {
2080                 case SFDP_SECTOR_MAP_ID:
2081                         dev_info(dev, "non-uniform erase sector maps are not supported yet.\n");
2082                         break;
2083
2084                 default:
2085                         break;
2086                 }
2087
2088                 if (err)
2089                         goto exit;
2090         }
2091
2092 exit:
2093         kfree(param_headers);
2094         return err;
2095 }
2096 #else
2097 static int spi_nor_parse_sfdp(struct spi_nor *nor,
2098                               struct spi_nor_flash_parameter *params)
2099 {
2100         return -EINVAL;
2101 }
2102 #endif /* SPI_FLASH_SFDP_SUPPORT */
2103
2104 static int spi_nor_init_params(struct spi_nor *nor,
2105                                const struct flash_info *info,
2106                                struct spi_nor_flash_parameter *params)
2107 {
2108         /* Set legacy flash parameters as default. */
2109         memset(params, 0, sizeof(*params));
2110
2111         /* Set SPI NOR sizes. */
2112         params->size = info->sector_size * info->n_sectors;
2113         params->page_size = info->page_size;
2114
2115         /* (Fast) Read settings. */
2116         params->hwcaps.mask |= SNOR_HWCAPS_READ;
2117         spi_nor_set_read_settings(&params->reads[SNOR_CMD_READ],
2118                                   0, 0, SPINOR_OP_READ,
2119                                   SNOR_PROTO_1_1_1);
2120
2121         if (!(info->flags & SPI_NOR_NO_FR)) {
2122                 params->hwcaps.mask |= SNOR_HWCAPS_READ_FAST;
2123                 spi_nor_set_read_settings(&params->reads[SNOR_CMD_READ_FAST],
2124                                           0, 8, SPINOR_OP_READ_FAST,
2125                                           SNOR_PROTO_1_1_1);
2126         }
2127
2128         if (info->flags & SPI_NOR_DUAL_READ) {
2129                 params->hwcaps.mask |= SNOR_HWCAPS_READ_1_1_2;
2130                 spi_nor_set_read_settings(&params->reads[SNOR_CMD_READ_1_1_2],
2131                                           0, 8, SPINOR_OP_READ_1_1_2,
2132                                           SNOR_PROTO_1_1_2);
2133         }
2134
2135         if (info->flags & SPI_NOR_QUAD_READ) {
2136                 params->hwcaps.mask |= SNOR_HWCAPS_READ_1_1_4;
2137                 spi_nor_set_read_settings(&params->reads[SNOR_CMD_READ_1_1_4],
2138                                           0, 8, SPINOR_OP_READ_1_1_4,
2139                                           SNOR_PROTO_1_1_4);
2140         }
2141
2142         /* Page Program settings. */
2143         params->hwcaps.mask |= SNOR_HWCAPS_PP;
2144         spi_nor_set_pp_settings(&params->page_programs[SNOR_CMD_PP],
2145                                 SPINOR_OP_PP, SNOR_PROTO_1_1_1);
2146
2147         if (info->flags & SPI_NOR_QUAD_READ) {
2148                 params->hwcaps.mask |= SNOR_HWCAPS_PP_1_1_4;
2149                 spi_nor_set_pp_settings(&params->page_programs[SNOR_CMD_PP_1_1_4],
2150                                         SPINOR_OP_PP_1_1_4, SNOR_PROTO_1_1_4);
2151         }
2152
2153         /* Select the procedure to set the Quad Enable bit. */
2154         if (params->hwcaps.mask & (SNOR_HWCAPS_READ_QUAD |
2155                                    SNOR_HWCAPS_PP_QUAD)) {
2156                 switch (JEDEC_MFR(info)) {
2157 #ifdef CONFIG_SPI_FLASH_MACRONIX
2158                 case SNOR_MFR_MACRONIX:
2159                         params->quad_enable = macronix_quad_enable;
2160                         break;
2161 #endif
2162                 case SNOR_MFR_ST:
2163                 case SNOR_MFR_MICRON:
2164                         break;
2165
2166                 default:
2167 #if defined(CONFIG_SPI_FLASH_SPANSION) || defined(CONFIG_SPI_FLASH_WINBOND)
2168                         /* Kept only for backward compatibility purpose. */
2169                         params->quad_enable = spansion_read_cr_quad_enable;
2170 #endif
2171                         break;
2172                 }
2173         }
2174
2175         /* Override the parameters with data read from SFDP tables. */
2176         nor->addr_width = 0;
2177         nor->mtd.erasesize = 0;
2178         if ((info->flags & (SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ)) &&
2179             !(info->flags & SPI_NOR_SKIP_SFDP)) {
2180                 struct spi_nor_flash_parameter sfdp_params;
2181
2182                 memcpy(&sfdp_params, params, sizeof(sfdp_params));
2183                 if (spi_nor_parse_sfdp(nor, &sfdp_params)) {
2184                         nor->addr_width = 0;
2185                         nor->mtd.erasesize = 0;
2186                 } else {
2187                         memcpy(params, &sfdp_params, sizeof(*params));
2188                 }
2189         }
2190
2191         return 0;
2192 }
2193
2194 static int spi_nor_hwcaps2cmd(u32 hwcaps, const int table[][2], size_t size)
2195 {
2196         size_t i;
2197
2198         for (i = 0; i < size; i++)
2199                 if (table[i][0] == (int)hwcaps)
2200                         return table[i][1];
2201
2202         return -EINVAL;
2203 }
2204
2205 static int spi_nor_hwcaps_read2cmd(u32 hwcaps)
2206 {
2207         static const int hwcaps_read2cmd[][2] = {
2208                 { SNOR_HWCAPS_READ,             SNOR_CMD_READ },
2209                 { SNOR_HWCAPS_READ_FAST,        SNOR_CMD_READ_FAST },
2210                 { SNOR_HWCAPS_READ_1_1_1_DTR,   SNOR_CMD_READ_1_1_1_DTR },
2211                 { SNOR_HWCAPS_READ_1_1_2,       SNOR_CMD_READ_1_1_2 },
2212                 { SNOR_HWCAPS_READ_1_2_2,       SNOR_CMD_READ_1_2_2 },
2213                 { SNOR_HWCAPS_READ_2_2_2,       SNOR_CMD_READ_2_2_2 },
2214                 { SNOR_HWCAPS_READ_1_2_2_DTR,   SNOR_CMD_READ_1_2_2_DTR },
2215                 { SNOR_HWCAPS_READ_1_1_4,       SNOR_CMD_READ_1_1_4 },
2216                 { SNOR_HWCAPS_READ_1_4_4,       SNOR_CMD_READ_1_4_4 },
2217                 { SNOR_HWCAPS_READ_4_4_4,       SNOR_CMD_READ_4_4_4 },
2218                 { SNOR_HWCAPS_READ_1_4_4_DTR,   SNOR_CMD_READ_1_4_4_DTR },
2219                 { SNOR_HWCAPS_READ_1_1_8,       SNOR_CMD_READ_1_1_8 },
2220                 { SNOR_HWCAPS_READ_1_8_8,       SNOR_CMD_READ_1_8_8 },
2221                 { SNOR_HWCAPS_READ_8_8_8,       SNOR_CMD_READ_8_8_8 },
2222                 { SNOR_HWCAPS_READ_1_8_8_DTR,   SNOR_CMD_READ_1_8_8_DTR },
2223         };
2224
2225         return spi_nor_hwcaps2cmd(hwcaps, hwcaps_read2cmd,
2226                                   ARRAY_SIZE(hwcaps_read2cmd));
2227 }
2228
2229 static int spi_nor_hwcaps_pp2cmd(u32 hwcaps)
2230 {
2231         static const int hwcaps_pp2cmd[][2] = {
2232                 { SNOR_HWCAPS_PP,               SNOR_CMD_PP },
2233                 { SNOR_HWCAPS_PP_1_1_4,         SNOR_CMD_PP_1_1_4 },
2234                 { SNOR_HWCAPS_PP_1_4_4,         SNOR_CMD_PP_1_4_4 },
2235                 { SNOR_HWCAPS_PP_4_4_4,         SNOR_CMD_PP_4_4_4 },
2236                 { SNOR_HWCAPS_PP_1_1_8,         SNOR_CMD_PP_1_1_8 },
2237                 { SNOR_HWCAPS_PP_1_8_8,         SNOR_CMD_PP_1_8_8 },
2238                 { SNOR_HWCAPS_PP_8_8_8,         SNOR_CMD_PP_8_8_8 },
2239         };
2240
2241         return spi_nor_hwcaps2cmd(hwcaps, hwcaps_pp2cmd,
2242                                   ARRAY_SIZE(hwcaps_pp2cmd));
2243 }
2244
2245 static int spi_nor_select_read(struct spi_nor *nor,
2246                                const struct spi_nor_flash_parameter *params,
2247                                u32 shared_hwcaps)
2248 {
2249         int cmd, best_match = fls(shared_hwcaps & SNOR_HWCAPS_READ_MASK) - 1;
2250         const struct spi_nor_read_command *read;
2251
2252         if (best_match < 0)
2253                 return -EINVAL;
2254
2255         cmd = spi_nor_hwcaps_read2cmd(BIT(best_match));
2256         if (cmd < 0)
2257                 return -EINVAL;
2258
2259         read = &params->reads[cmd];
2260         nor->read_opcode = read->opcode;
2261         nor->read_proto = read->proto;
2262
2263         /*
2264          * In the spi-nor framework, we don't need to make the difference
2265          * between mode clock cycles and wait state clock cycles.
2266          * Indeed, the value of the mode clock cycles is used by a QSPI
2267          * flash memory to know whether it should enter or leave its 0-4-4
2268          * (Continuous Read / XIP) mode.
2269          * eXecution In Place is out of the scope of the mtd sub-system.
2270          * Hence we choose to merge both mode and wait state clock cycles
2271          * into the so called dummy clock cycles.
2272          */
2273         nor->read_dummy = read->num_mode_clocks + read->num_wait_states;
2274         return 0;
2275 }
2276
2277 static int spi_nor_select_pp(struct spi_nor *nor,
2278                              const struct spi_nor_flash_parameter *params,
2279                              u32 shared_hwcaps)
2280 {
2281         int cmd, best_match = fls(shared_hwcaps & SNOR_HWCAPS_PP_MASK) - 1;
2282         const struct spi_nor_pp_command *pp;
2283
2284         if (best_match < 0)
2285                 return -EINVAL;
2286
2287         cmd = spi_nor_hwcaps_pp2cmd(BIT(best_match));
2288         if (cmd < 0)
2289                 return -EINVAL;
2290
2291         pp = &params->page_programs[cmd];
2292         nor->program_opcode = pp->opcode;
2293         nor->write_proto = pp->proto;
2294         return 0;
2295 }
2296
2297 static int spi_nor_select_erase(struct spi_nor *nor,
2298                                 const struct flash_info *info)
2299 {
2300         struct mtd_info *mtd = &nor->mtd;
2301
2302         /* Do nothing if already configured from SFDP. */
2303         if (mtd->erasesize)
2304                 return 0;
2305
2306 #ifdef CONFIG_SPI_FLASH_USE_4K_SECTORS
2307         /* prefer "small sector" erase if possible */
2308         if (info->flags & SECT_4K) {
2309                 nor->erase_opcode = SPINOR_OP_BE_4K;
2310                 mtd->erasesize = 4096;
2311         } else if (info->flags & SECT_4K_PMC) {
2312                 nor->erase_opcode = SPINOR_OP_BE_4K_PMC;
2313                 mtd->erasesize = 4096;
2314         } else
2315 #endif
2316         {
2317                 nor->erase_opcode = SPINOR_OP_SE;
2318                 mtd->erasesize = info->sector_size;
2319         }
2320         return 0;
2321 }
2322
2323 static int spi_nor_setup(struct spi_nor *nor, const struct flash_info *info,
2324                          const struct spi_nor_flash_parameter *params,
2325                          const struct spi_nor_hwcaps *hwcaps)
2326 {
2327         u32 ignored_mask, shared_mask;
2328         bool enable_quad_io;
2329         int err;
2330
2331         /*
2332          * Keep only the hardware capabilities supported by both the SPI
2333          * controller and the SPI flash memory.
2334          */
2335         shared_mask = hwcaps->mask & params->hwcaps.mask;
2336
2337         /* SPI n-n-n protocols are not supported yet. */
2338         ignored_mask = (SNOR_HWCAPS_READ_2_2_2 |
2339                         SNOR_HWCAPS_READ_4_4_4 |
2340                         SNOR_HWCAPS_READ_8_8_8 |
2341                         SNOR_HWCAPS_PP_4_4_4 |
2342                         SNOR_HWCAPS_PP_8_8_8);
2343         if (shared_mask & ignored_mask) {
2344                 dev_dbg(nor->dev,
2345                         "SPI n-n-n protocols are not supported yet.\n");
2346                 shared_mask &= ~ignored_mask;
2347         }
2348
2349         /* Select the (Fast) Read command. */
2350         err = spi_nor_select_read(nor, params, shared_mask);
2351         if (err) {
2352                 dev_dbg(nor->dev,
2353                         "can't select read settings supported by both the SPI controller and memory.\n");
2354                 return err;
2355         }
2356
2357         /* Select the Page Program command. */
2358         err = spi_nor_select_pp(nor, params, shared_mask);
2359         if (err) {
2360                 dev_dbg(nor->dev,
2361                         "can't select write settings supported by both the SPI controller and memory.\n");
2362                 return err;
2363         }
2364
2365         /* Select the Sector Erase command. */
2366         err = spi_nor_select_erase(nor, info);
2367         if (err) {
2368                 dev_dbg(nor->dev,
2369                         "can't select erase settings supported by both the SPI controller and memory.\n");
2370                 return err;
2371         }
2372
2373         /* Enable Quad I/O if needed. */
2374         enable_quad_io = (spi_nor_get_protocol_width(nor->read_proto) == 4 ||
2375                           spi_nor_get_protocol_width(nor->write_proto) == 4);
2376         if (enable_quad_io && params->quad_enable)
2377                 nor->quad_enable = params->quad_enable;
2378         else
2379                 nor->quad_enable = NULL;
2380
2381         return 0;
2382 }
2383
2384 static int spi_nor_init(struct spi_nor *nor)
2385 {
2386         int err;
2387
2388         /*
2389          * Atmel, SST, Intel/Numonyx, and others serial NOR tend to power up
2390          * with the software protection bits set
2391          */
2392         if (JEDEC_MFR(nor->info) == SNOR_MFR_ATMEL ||
2393             JEDEC_MFR(nor->info) == SNOR_MFR_INTEL ||
2394             JEDEC_MFR(nor->info) == SNOR_MFR_SST ||
2395             nor->info->flags & SPI_NOR_HAS_LOCK) {
2396                 write_enable(nor);
2397                 write_sr(nor, 0);
2398                 spi_nor_wait_till_ready(nor);
2399         }
2400
2401         if (nor->quad_enable) {
2402                 err = nor->quad_enable(nor);
2403                 if (err) {
2404                         dev_dbg(nor->dev, "quad mode not supported\n");
2405                         return err;
2406                 }
2407         }
2408
2409         if (nor->addr_width == 4 &&
2410             (JEDEC_MFR(nor->info) != SNOR_MFR_SPANSION) &&
2411             !(nor->info->flags & SPI_NOR_4B_OPCODES)) {
2412                 /*
2413                  * If the RESET# pin isn't hooked up properly, or the system
2414                  * otherwise doesn't perform a reset command in the boot
2415                  * sequence, it's impossible to 100% protect against unexpected
2416                  * reboots (e.g., crashes). Warn the user (or hopefully, system
2417                  * designer) that this is bad.
2418                  */
2419                 if (nor->flags & SNOR_F_BROKEN_RESET)
2420                         printf("enabling reset hack; may not recover from unexpected reboots\n");
2421                 set_4byte(nor, nor->info, 1);
2422         }
2423
2424         return 0;
2425 }
2426
2427 int spi_nor_scan(struct spi_nor *nor)
2428 {
2429         struct spi_nor_flash_parameter params;
2430         const struct flash_info *info = NULL;
2431         struct mtd_info *mtd = &nor->mtd;
2432         struct spi_nor_hwcaps hwcaps = {
2433                 .mask = SNOR_HWCAPS_READ |
2434                         SNOR_HWCAPS_READ_FAST |
2435                         SNOR_HWCAPS_PP,
2436         };
2437         struct spi_slave *spi = nor->spi;
2438         int ret;
2439
2440         /* Reset SPI protocol for all commands. */
2441         nor->reg_proto = SNOR_PROTO_1_1_1;
2442         nor->read_proto = SNOR_PROTO_1_1_1;
2443         nor->write_proto = SNOR_PROTO_1_1_1;
2444         nor->read = spi_nor_read_data;
2445         nor->write = spi_nor_write_data;
2446         nor->read_reg = spi_nor_read_reg;
2447         nor->write_reg = spi_nor_write_reg;
2448
2449         if (spi->mode & SPI_RX_QUAD) {
2450                 hwcaps.mask |= SNOR_HWCAPS_READ_1_1_4;
2451
2452                 if (spi->mode & SPI_TX_QUAD)
2453                         hwcaps.mask |= (SNOR_HWCAPS_READ_1_4_4 |
2454                                         SNOR_HWCAPS_PP_1_1_4 |
2455                                         SNOR_HWCAPS_PP_1_4_4);
2456         } else if (spi->mode & SPI_RX_DUAL) {
2457                 hwcaps.mask |= SNOR_HWCAPS_READ_1_1_2;
2458
2459                 if (spi->mode & SPI_TX_DUAL)
2460                         hwcaps.mask |= SNOR_HWCAPS_READ_1_2_2;
2461         }
2462
2463         info = spi_nor_read_id(nor);
2464         if (IS_ERR_OR_NULL(info))
2465                 return -ENOENT;
2466         /* Parse the Serial Flash Discoverable Parameters table. */
2467         ret = spi_nor_init_params(nor, info, &params);
2468         if (ret)
2469                 return ret;
2470
2471         if (!mtd->name)
2472                 mtd->name = info->name;
2473         mtd->priv = nor;
2474         mtd->type = MTD_NORFLASH;
2475         mtd->writesize = 1;
2476         mtd->flags = MTD_CAP_NORFLASH;
2477         mtd->size = params.size;
2478         mtd->_erase = spi_nor_erase;
2479         mtd->_read = spi_nor_read;
2480
2481 #if defined(CONFIG_SPI_FLASH_STMICRO) || defined(CONFIG_SPI_FLASH_SST)
2482         /* NOR protection support for STmicro/Micron chips and similar */
2483         if (JEDEC_MFR(info) == SNOR_MFR_ST ||
2484             JEDEC_MFR(info) == SNOR_MFR_MICRON ||
2485             JEDEC_MFR(info) == SNOR_MFR_SST ||
2486                         info->flags & SPI_NOR_HAS_LOCK) {
2487                 nor->flash_lock = stm_lock;
2488                 nor->flash_unlock = stm_unlock;
2489                 nor->flash_is_locked = stm_is_locked;
2490         }
2491 #endif
2492
2493 #ifdef CONFIG_SPI_FLASH_SST
2494         /* sst nor chips use AAI word program */
2495         if (info->flags & SST_WRITE)
2496                 mtd->_write = sst_write;
2497         else
2498 #endif
2499                 mtd->_write = spi_nor_write;
2500
2501         if (info->flags & USE_FSR)
2502                 nor->flags |= SNOR_F_USE_FSR;
2503         if (info->flags & SPI_NOR_HAS_TB)
2504                 nor->flags |= SNOR_F_HAS_SR_TB;
2505         if (info->flags & NO_CHIP_ERASE)
2506                 nor->flags |= SNOR_F_NO_OP_CHIP_ERASE;
2507         if (info->flags & USE_CLSR)
2508                 nor->flags |= SNOR_F_USE_CLSR;
2509
2510         if (info->flags & SPI_NOR_NO_ERASE)
2511                 mtd->flags |= MTD_NO_ERASE;
2512
2513         nor->page_size = params.page_size;
2514         mtd->writebufsize = nor->page_size;
2515
2516         /* Some devices cannot do fast-read, no matter what DT tells us */
2517         if ((info->flags & SPI_NOR_NO_FR) || (spi->mode & SPI_RX_SLOW))
2518                 params.hwcaps.mask &= ~SNOR_HWCAPS_READ_FAST;
2519
2520         /*
2521          * Configure the SPI memory:
2522          * - select op codes for (Fast) Read, Page Program and Sector Erase.
2523          * - set the number of dummy cycles (mode cycles + wait states).
2524          * - set the SPI protocols for register and memory accesses.
2525          * - set the Quad Enable bit if needed (required by SPI x-y-4 protos).
2526          */
2527         ret = spi_nor_setup(nor, info, &params, &hwcaps);
2528         if (ret)
2529                 return ret;
2530
2531         if (nor->addr_width) {
2532                 /* already configured from SFDP */
2533         } else if (info->addr_width) {
2534                 nor->addr_width = info->addr_width;
2535         } else if (mtd->size > 0x1000000) {
2536                 /* enable 4-byte addressing if the device exceeds 16MiB */
2537                 nor->addr_width = 4;
2538                 if (JEDEC_MFR(info) == SNOR_MFR_SPANSION ||
2539                     info->flags & SPI_NOR_4B_OPCODES)
2540                         spi_nor_set_4byte_opcodes(nor, info);
2541         } else {
2542                 nor->addr_width = 3;
2543         }
2544
2545         if (nor->addr_width > SPI_NOR_MAX_ADDR_WIDTH) {
2546                 dev_dbg(dev, "address width is too large: %u\n",
2547                         nor->addr_width);
2548                 return -EINVAL;
2549         }
2550
2551         /* Send all the required SPI flash commands to initialize device */
2552         nor->info = info;
2553         ret = spi_nor_init(nor);
2554         if (ret)
2555                 return ret;
2556
2557         nor->name = mtd->name;
2558         nor->size = mtd->size;
2559         nor->erase_size = mtd->erasesize;
2560         nor->sector_size = mtd->erasesize;
2561
2562 #ifndef CONFIG_SPL_BUILD
2563         printf("SF: Detected %s with page size ", nor->name);
2564         print_size(nor->page_size, ", erase size ");
2565         print_size(nor->erase_size, ", total ");
2566         print_size(nor->size, "");
2567         puts("\n");
2568 #endif
2569
2570         return 0;
2571 }