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