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