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