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