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