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