rockchip: rk3399: Add Nanopi M4 2GB board support
[platform/kernel/u-boot.git] / drivers / mtd / spi / spi-nor-core.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Based on m25p80.c, by Mike Lavender (mike@steroidmicros.com), with
4  * influence from lart.c (Abraham Van Der Merwe) and mtd_dataflash.c
5  *
6  * Copyright (C) 2005, Intec Automation Inc.
7  * Copyright (C) 2014, Freescale Semiconductor, Inc.
8  *
9  * Synced from Linux v4.19
10  */
11
12 #include <common.h>
13 #include <dm/device_compat.h>
14 #include <dm/devres.h>
15 #include <linux/err.h>
16 #include <linux/errno.h>
17 #include <linux/log2.h>
18 #include <linux/math64.h>
19 #include <linux/sizes.h>
20
21 #include <linux/mtd/mtd.h>
22 #include <linux/mtd/spi-nor.h>
23 #include <spi-mem.h>
24 #include <spi.h>
25
26 #include "sf_internal.h"
27
28 /* Define max times to check status register before we give up. */
29
30 /*
31  * For everything but full-chip erase; probably could be much smaller, but kept
32  * around for safety for now
33  */
34
35 #define HZ                                      CONFIG_SYS_HZ
36
37 #define DEFAULT_READY_WAIT_JIFFIES              (40UL * HZ)
38
39 static int spi_nor_read_write_reg(struct spi_nor *nor, struct spi_mem_op
40                 *op, void *buf)
41 {
42         if (op->data.dir == SPI_MEM_DATA_IN)
43                 op->data.buf.in = buf;
44         else
45                 op->data.buf.out = buf;
46         return spi_mem_exec_op(nor->spi, op);
47 }
48
49 static int spi_nor_read_reg(struct spi_nor *nor, u8 code, u8 *val, int len)
50 {
51         struct spi_mem_op op = SPI_MEM_OP(SPI_MEM_OP_CMD(code, 1),
52                                           SPI_MEM_OP_NO_ADDR,
53                                           SPI_MEM_OP_NO_DUMMY,
54                                           SPI_MEM_OP_DATA_IN(len, NULL, 1));
55         int ret;
56
57         ret = spi_nor_read_write_reg(nor, &op, val);
58         if (ret < 0)
59                 dev_dbg(&flash->spimem->spi->dev, "error %d reading %x\n", ret,
60                         code);
61
62         return ret;
63 }
64
65 static int spi_nor_write_reg(struct spi_nor *nor, u8 opcode, u8 *buf, int len)
66 {
67         struct spi_mem_op op = SPI_MEM_OP(SPI_MEM_OP_CMD(opcode, 1),
68                                           SPI_MEM_OP_NO_ADDR,
69                                           SPI_MEM_OP_NO_DUMMY,
70                                           SPI_MEM_OP_DATA_OUT(len, NULL, 1));
71
72         return spi_nor_read_write_reg(nor, &op, buf);
73 }
74
75 static ssize_t spi_nor_read_data(struct spi_nor *nor, loff_t from, size_t len,
76                                  u_char *buf)
77 {
78         struct spi_mem_op op =
79                         SPI_MEM_OP(SPI_MEM_OP_CMD(nor->read_opcode, 1),
80                                    SPI_MEM_OP_ADDR(nor->addr_width, from, 1),
81                                    SPI_MEM_OP_DUMMY(nor->read_dummy, 1),
82                                    SPI_MEM_OP_DATA_IN(len, buf, 1));
83         size_t remaining = len;
84         int ret;
85
86         /* get transfer protocols. */
87         op.cmd.buswidth = spi_nor_get_protocol_inst_nbits(nor->read_proto);
88         op.addr.buswidth = spi_nor_get_protocol_addr_nbits(nor->read_proto);
89         op.dummy.buswidth = op.addr.buswidth;
90         op.data.buswidth = spi_nor_get_protocol_data_nbits(nor->read_proto);
91
92         /* convert the dummy cycles to the number of bytes */
93         op.dummy.nbytes = (nor->read_dummy * op.dummy.buswidth) / 8;
94
95         while (remaining) {
96                 op.data.nbytes = remaining < UINT_MAX ? remaining : UINT_MAX;
97                 ret = spi_mem_adjust_op_size(nor->spi, &op);
98                 if (ret)
99                         return ret;
100
101                 ret = spi_mem_exec_op(nor->spi, &op);
102                 if (ret)
103                         return ret;
104
105                 op.addr.val += op.data.nbytes;
106                 remaining -= op.data.nbytes;
107                 op.data.buf.in += op.data.nbytes;
108         }
109
110         return len;
111 }
112
113 static ssize_t spi_nor_write_data(struct spi_nor *nor, loff_t to, size_t len,
114                                   const u_char *buf)
115 {
116         struct spi_mem_op op =
117                         SPI_MEM_OP(SPI_MEM_OP_CMD(nor->program_opcode, 1),
118                                    SPI_MEM_OP_ADDR(nor->addr_width, to, 1),
119                                    SPI_MEM_OP_NO_DUMMY,
120                                    SPI_MEM_OP_DATA_OUT(len, buf, 1));
121         int ret;
122
123         /* get transfer protocols. */
124         op.cmd.buswidth = spi_nor_get_protocol_inst_nbits(nor->write_proto);
125         op.addr.buswidth = spi_nor_get_protocol_addr_nbits(nor->write_proto);
126         op.data.buswidth = spi_nor_get_protocol_data_nbits(nor->write_proto);
127
128         if (nor->program_opcode == SPINOR_OP_AAI_WP && nor->sst_write_second)
129                 op.addr.nbytes = 0;
130
131         ret = spi_mem_adjust_op_size(nor->spi, &op);
132         if (ret)
133                 return ret;
134         op.data.nbytes = len < op.data.nbytes ? len : op.data.nbytes;
135
136         ret = spi_mem_exec_op(nor->spi, &op);
137         if (ret)
138                 return ret;
139
140         return op.data.nbytes;
141 }
142
143 /*
144  * Read the status register, returning its value in the location
145  * Return the status register value.
146  * Returns negative if error occurred.
147  */
148 static int read_sr(struct spi_nor *nor)
149 {
150         int ret;
151         u8 val;
152
153         ret = nor->read_reg(nor, SPINOR_OP_RDSR, &val, 1);
154         if (ret < 0) {
155                 pr_debug("error %d reading SR\n", (int)ret);
156                 return ret;
157         }
158
159         return val;
160 }
161
162 /*
163  * Read the flag status register, returning its value in the location
164  * Return the status register value.
165  * Returns negative if error occurred.
166  */
167 static int read_fsr(struct spi_nor *nor)
168 {
169         int ret;
170         u8 val;
171
172         ret = nor->read_reg(nor, SPINOR_OP_RDFSR, &val, 1);
173         if (ret < 0) {
174                 pr_debug("error %d reading FSR\n", ret);
175                 return ret;
176         }
177
178         return val;
179 }
180
181 /*
182  * Read configuration register, returning its value in the
183  * location. Return the configuration register value.
184  * Returns negative if error occurred.
185  */
186 #if defined(CONFIG_SPI_FLASH_SPANSION) || defined(CONFIG_SPI_FLASH_WINBOND)
187 static int read_cr(struct spi_nor *nor)
188 {
189         int ret;
190         u8 val;
191
192         ret = nor->read_reg(nor, SPINOR_OP_RDCR, &val, 1);
193         if (ret < 0) {
194                 dev_dbg(nor->dev, "error %d reading CR\n", ret);
195                 return ret;
196         }
197
198         return val;
199 }
200 #endif
201
202 /*
203  * Write status register 1 byte
204  * Returns negative if error occurred.
205  */
206 static int write_sr(struct spi_nor *nor, u8 val)
207 {
208         nor->cmd_buf[0] = val;
209         return nor->write_reg(nor, SPINOR_OP_WRSR, nor->cmd_buf, 1);
210 }
211
212 /*
213  * Set write enable latch with Write Enable command.
214  * Returns negative if error occurred.
215  */
216 static int write_enable(struct spi_nor *nor)
217 {
218         return nor->write_reg(nor, SPINOR_OP_WREN, NULL, 0);
219 }
220
221 /*
222  * Send write disable instruction to the chip.
223  */
224 static int write_disable(struct spi_nor *nor)
225 {
226         return nor->write_reg(nor, SPINOR_OP_WRDI, NULL, 0);
227 }
228
229 static struct spi_nor *mtd_to_spi_nor(struct mtd_info *mtd)
230 {
231         return mtd->priv;
232 }
233
234 #ifndef CONFIG_SPI_FLASH_BAR
235 static u8 spi_nor_convert_opcode(u8 opcode, const u8 table[][2], size_t size)
236 {
237         size_t i;
238
239         for (i = 0; i < size; i++)
240                 if (table[i][0] == opcode)
241                         return table[i][1];
242
243         /* No conversion found, keep input op code. */
244         return opcode;
245 }
246
247 static u8 spi_nor_convert_3to4_read(u8 opcode)
248 {
249         static const u8 spi_nor_3to4_read[][2] = {
250                 { SPINOR_OP_READ,       SPINOR_OP_READ_4B },
251                 { SPINOR_OP_READ_FAST,  SPINOR_OP_READ_FAST_4B },
252                 { SPINOR_OP_READ_1_1_2, SPINOR_OP_READ_1_1_2_4B },
253                 { SPINOR_OP_READ_1_2_2, SPINOR_OP_READ_1_2_2_4B },
254                 { SPINOR_OP_READ_1_1_4, SPINOR_OP_READ_1_1_4_4B },
255                 { SPINOR_OP_READ_1_4_4, SPINOR_OP_READ_1_4_4_4B },
256                 { SPINOR_OP_READ_1_1_8, SPINOR_OP_READ_1_1_8_4B },
257                 { SPINOR_OP_READ_1_8_8, SPINOR_OP_READ_1_8_8_4B },
258
259                 { SPINOR_OP_READ_1_1_1_DTR,     SPINOR_OP_READ_1_1_1_DTR_4B },
260                 { SPINOR_OP_READ_1_2_2_DTR,     SPINOR_OP_READ_1_2_2_DTR_4B },
261                 { SPINOR_OP_READ_1_4_4_DTR,     SPINOR_OP_READ_1_4_4_DTR_4B },
262         };
263
264         return spi_nor_convert_opcode(opcode, spi_nor_3to4_read,
265                                       ARRAY_SIZE(spi_nor_3to4_read));
266 }
267
268 static u8 spi_nor_convert_3to4_program(u8 opcode)
269 {
270         static const u8 spi_nor_3to4_program[][2] = {
271                 { SPINOR_OP_PP,         SPINOR_OP_PP_4B },
272                 { SPINOR_OP_PP_1_1_4,   SPINOR_OP_PP_1_1_4_4B },
273                 { SPINOR_OP_PP_1_4_4,   SPINOR_OP_PP_1_4_4_4B },
274                 { SPINOR_OP_PP_1_1_8,   SPINOR_OP_PP_1_1_8_4B },
275                 { SPINOR_OP_PP_1_8_8,   SPINOR_OP_PP_1_8_8_4B },
276         };
277
278         return spi_nor_convert_opcode(opcode, spi_nor_3to4_program,
279                                       ARRAY_SIZE(spi_nor_3to4_program));
280 }
281
282 static u8 spi_nor_convert_3to4_erase(u8 opcode)
283 {
284         static const u8 spi_nor_3to4_erase[][2] = {
285                 { SPINOR_OP_BE_4K,      SPINOR_OP_BE_4K_4B },
286                 { SPINOR_OP_BE_32K,     SPINOR_OP_BE_32K_4B },
287                 { SPINOR_OP_SE,         SPINOR_OP_SE_4B },
288         };
289
290         return spi_nor_convert_opcode(opcode, spi_nor_3to4_erase,
291                                       ARRAY_SIZE(spi_nor_3to4_erase));
292 }
293
294 static void spi_nor_set_4byte_opcodes(struct spi_nor *nor,
295                                       const struct flash_info *info)
296 {
297         /* Do some manufacturer fixups first */
298         switch (JEDEC_MFR(info)) {
299         case SNOR_MFR_SPANSION:
300                 /* No small sector erase for 4-byte command set */
301                 nor->erase_opcode = SPINOR_OP_SE;
302                 nor->mtd.erasesize = info->sector_size;
303                 break;
304
305         default:
306                 break;
307         }
308
309         nor->read_opcode = spi_nor_convert_3to4_read(nor->read_opcode);
310         nor->program_opcode = spi_nor_convert_3to4_program(nor->program_opcode);
311         nor->erase_opcode = spi_nor_convert_3to4_erase(nor->erase_opcode);
312 }
313 #endif /* !CONFIG_SPI_FLASH_BAR */
314
315 /* Enable/disable 4-byte addressing mode. */
316 static int set_4byte(struct spi_nor *nor, const struct flash_info *info,
317                      int enable)
318 {
319         int status;
320         bool need_wren = false;
321         u8 cmd;
322
323         switch (JEDEC_MFR(info)) {
324         case SNOR_MFR_ST:
325         case SNOR_MFR_MICRON:
326                 /* Some Micron need WREN command; all will accept it */
327                 need_wren = true;
328         case SNOR_MFR_MACRONIX:
329         case SNOR_MFR_WINBOND:
330                 if (need_wren)
331                         write_enable(nor);
332
333                 cmd = enable ? SPINOR_OP_EN4B : SPINOR_OP_EX4B;
334                 status = nor->write_reg(nor, cmd, NULL, 0);
335                 if (need_wren)
336                         write_disable(nor);
337
338                 if (!status && !enable &&
339                     JEDEC_MFR(info) == SNOR_MFR_WINBOND) {
340                         /*
341                          * On Winbond W25Q256FV, leaving 4byte mode causes
342                          * the Extended Address Register to be set to 1, so all
343                          * 3-byte-address reads come from the second 16M.
344                          * We must clear the register to enable normal behavior.
345                          */
346                         write_enable(nor);
347                         nor->cmd_buf[0] = 0;
348                         nor->write_reg(nor, SPINOR_OP_WREAR, nor->cmd_buf, 1);
349                         write_disable(nor);
350                 }
351
352                 return status;
353         default:
354                 /* Spansion style */
355                 nor->cmd_buf[0] = enable << 7;
356                 return nor->write_reg(nor, SPINOR_OP_BRWR, nor->cmd_buf, 1);
357         }
358 }
359
360 static int spi_nor_sr_ready(struct spi_nor *nor)
361 {
362         int sr = read_sr(nor);
363
364         if (sr < 0)
365                 return sr;
366
367         if (nor->flags & SNOR_F_USE_CLSR && sr & (SR_E_ERR | SR_P_ERR)) {
368                 if (sr & SR_E_ERR)
369                         dev_dbg(nor->dev, "Erase Error occurred\n");
370                 else
371                         dev_dbg(nor->dev, "Programming Error occurred\n");
372
373                 nor->write_reg(nor, SPINOR_OP_CLSR, NULL, 0);
374                 return -EIO;
375         }
376
377         return !(sr & SR_WIP);
378 }
379
380 static int spi_nor_fsr_ready(struct spi_nor *nor)
381 {
382         int fsr = read_fsr(nor);
383
384         if (fsr < 0)
385                 return fsr;
386
387         if (fsr & (FSR_E_ERR | FSR_P_ERR)) {
388                 if (fsr & FSR_E_ERR)
389                         dev_err(nor->dev, "Erase operation failed.\n");
390                 else
391                         dev_err(nor->dev, "Program operation failed.\n");
392
393                 if (fsr & FSR_PT_ERR)
394                         dev_err(nor->dev,
395                                 "Attempted to modify a protected sector.\n");
396
397                 nor->write_reg(nor, SPINOR_OP_CLFSR, NULL, 0);
398                 return -EIO;
399         }
400
401         return fsr & FSR_READY;
402 }
403
404 static int spi_nor_ready(struct spi_nor *nor)
405 {
406         int sr, fsr;
407
408         sr = spi_nor_sr_ready(nor);
409         if (sr < 0)
410                 return sr;
411         fsr = nor->flags & SNOR_F_USE_FSR ? spi_nor_fsr_ready(nor) : 1;
412         if (fsr < 0)
413                 return fsr;
414         return sr && fsr;
415 }
416
417 /*
418  * Service routine to read status register until ready, or timeout occurs.
419  * Returns non-zero if error.
420  */
421 static int spi_nor_wait_till_ready_with_timeout(struct spi_nor *nor,
422                                                 unsigned long timeout)
423 {
424         unsigned long timebase;
425         int ret;
426
427         timebase = get_timer(0);
428
429         while (get_timer(timebase) < timeout) {
430                 ret = spi_nor_ready(nor);
431                 if (ret < 0)
432                         return ret;
433                 if (ret)
434                         return 0;
435         }
436
437         dev_err(nor->dev, "flash operation timed out\n");
438
439         return -ETIMEDOUT;
440 }
441
442 static int spi_nor_wait_till_ready(struct spi_nor *nor)
443 {
444         return spi_nor_wait_till_ready_with_timeout(nor,
445                                                     DEFAULT_READY_WAIT_JIFFIES);
446 }
447
448 #ifdef CONFIG_SPI_FLASH_BAR
449 /*
450  * This "clean_bar" is necessary in a situation when one was accessing
451  * spi flash memory > 16 MiB by using Bank Address Register's BA24 bit.
452  *
453  * After it the BA24 bit shall be cleared to allow access to correct
454  * memory region after SW reset (by calling "reset" command).
455  *
456  * Otherwise, the BA24 bit may be left set and then after reset, the
457  * ROM would read/write/erase SPL from 16 MiB * bank_sel address.
458  */
459 static int clean_bar(struct spi_nor *nor)
460 {
461         u8 cmd, bank_sel = 0;
462
463         if (nor->bank_curr == 0)
464                 return 0;
465         cmd = nor->bank_write_cmd;
466         nor->bank_curr = 0;
467         write_enable(nor);
468
469         return nor->write_reg(nor, cmd, &bank_sel, 1);
470 }
471
472 static int write_bar(struct spi_nor *nor, u32 offset)
473 {
474         u8 cmd, bank_sel;
475         int ret;
476
477         bank_sel = offset / SZ_16M;
478         if (bank_sel == nor->bank_curr)
479                 goto bar_end;
480
481         cmd = nor->bank_write_cmd;
482         write_enable(nor);
483         ret = nor->write_reg(nor, cmd, &bank_sel, 1);
484         if (ret < 0) {
485                 debug("SF: fail to write bank register\n");
486                 return ret;
487         }
488
489 bar_end:
490         nor->bank_curr = bank_sel;
491         return nor->bank_curr;
492 }
493
494 static int read_bar(struct spi_nor *nor, const struct flash_info *info)
495 {
496         u8 curr_bank = 0;
497         int ret;
498
499         switch (JEDEC_MFR(info)) {
500         case SNOR_MFR_SPANSION:
501                 nor->bank_read_cmd = SPINOR_OP_BRRD;
502                 nor->bank_write_cmd = SPINOR_OP_BRWR;
503                 break;
504         default:
505                 nor->bank_read_cmd = SPINOR_OP_RDEAR;
506                 nor->bank_write_cmd = SPINOR_OP_WREAR;
507         }
508
509         ret = nor->read_reg(nor, nor->bank_read_cmd,
510                                     &curr_bank, 1);
511         if (ret) {
512                 debug("SF: fail to read bank addr register\n");
513                 return ret;
514         }
515         nor->bank_curr = curr_bank;
516
517         return 0;
518 }
519 #endif
520
521 /*
522  * Initiate the erasure of a single sector
523  */
524 static int spi_nor_erase_sector(struct spi_nor *nor, u32 addr)
525 {
526         struct spi_mem_op op =
527                 SPI_MEM_OP(SPI_MEM_OP_CMD(nor->erase_opcode, 1),
528                            SPI_MEM_OP_ADDR(nor->addr_width, addr, 1),
529                            SPI_MEM_OP_NO_DUMMY,
530                            SPI_MEM_OP_NO_DATA);
531
532         if (nor->erase)
533                 return nor->erase(nor, addr);
534
535         /*
536          * Default implementation, if driver doesn't have a specialized HW
537          * control
538          */
539         return spi_mem_exec_op(nor->spi, &op);
540 }
541
542 /*
543  * Erase an address range on the nor chip.  The address range may extend
544  * one or more erase sectors.  Return an error is there is a problem erasing.
545  */
546 static int spi_nor_erase(struct mtd_info *mtd, struct erase_info *instr)
547 {
548         struct spi_nor *nor = mtd_to_spi_nor(mtd);
549         u32 addr, len, rem;
550         int ret;
551
552         dev_dbg(nor->dev, "at 0x%llx, len %lld\n", (long long)instr->addr,
553                 (long long)instr->len);
554
555         if (!instr->len)
556                 return 0;
557
558         div_u64_rem(instr->len, mtd->erasesize, &rem);
559         if (rem)
560                 return -EINVAL;
561
562         addr = instr->addr;
563         len = instr->len;
564
565         while (len) {
566 #ifdef CONFIG_SPI_FLASH_BAR
567                 ret = write_bar(nor, addr);
568                 if (ret < 0)
569                         return ret;
570 #endif
571                 write_enable(nor);
572
573                 ret = spi_nor_erase_sector(nor, addr);
574                 if (ret)
575                         goto erase_err;
576
577                 addr += mtd->erasesize;
578                 len -= mtd->erasesize;
579
580                 ret = spi_nor_wait_till_ready(nor);
581                 if (ret)
582                         goto erase_err;
583         }
584
585 erase_err:
586 #ifdef CONFIG_SPI_FLASH_BAR
587         ret = clean_bar(nor);
588 #endif
589         write_disable(nor);
590
591         return ret;
592 }
593
594 #if defined(CONFIG_SPI_FLASH_STMICRO) || defined(CONFIG_SPI_FLASH_SST)
595 /* Write status register and ensure bits in mask match written values */
596 static int write_sr_and_check(struct spi_nor *nor, u8 status_new, u8 mask)
597 {
598         int ret;
599
600         write_enable(nor);
601         ret = write_sr(nor, status_new);
602         if (ret)
603                 return ret;
604
605         ret = spi_nor_wait_till_ready(nor);
606         if (ret)
607                 return ret;
608
609         ret = read_sr(nor);
610         if (ret < 0)
611                 return ret;
612
613         return ((ret & mask) != (status_new & mask)) ? -EIO : 0;
614 }
615
616 static void stm_get_locked_range(struct spi_nor *nor, u8 sr, loff_t *ofs,
617                                  uint64_t *len)
618 {
619         struct mtd_info *mtd = &nor->mtd;
620         u8 mask = SR_BP2 | SR_BP1 | SR_BP0;
621         int shift = ffs(mask) - 1;
622         int pow;
623
624         if (!(sr & mask)) {
625                 /* No protection */
626                 *ofs = 0;
627                 *len = 0;
628         } else {
629                 pow = ((sr & mask) ^ mask) >> shift;
630                 *len = mtd->size >> pow;
631                 if (nor->flags & SNOR_F_HAS_SR_TB && sr & SR_TB)
632                         *ofs = 0;
633                 else
634                         *ofs = mtd->size - *len;
635         }
636 }
637
638 /*
639  * Return 1 if the entire region is locked (if @locked is true) or unlocked (if
640  * @locked is false); 0 otherwise
641  */
642 static int stm_check_lock_status_sr(struct spi_nor *nor, loff_t ofs, u64 len,
643                                     u8 sr, bool locked)
644 {
645         loff_t lock_offs;
646         uint64_t lock_len;
647
648         if (!len)
649                 return 1;
650
651         stm_get_locked_range(nor, sr, &lock_offs, &lock_len);
652
653         if (locked)
654                 /* Requested range is a sub-range of locked range */
655                 return (ofs + len <= lock_offs + lock_len) && (ofs >= lock_offs);
656         else
657                 /* Requested range does not overlap with locked range */
658                 return (ofs >= lock_offs + lock_len) || (ofs + len <= lock_offs);
659 }
660
661 static int stm_is_locked_sr(struct spi_nor *nor, loff_t ofs, uint64_t len,
662                             u8 sr)
663 {
664         return stm_check_lock_status_sr(nor, ofs, len, sr, true);
665 }
666
667 static int stm_is_unlocked_sr(struct spi_nor *nor, loff_t ofs, uint64_t len,
668                               u8 sr)
669 {
670         return stm_check_lock_status_sr(nor, ofs, len, sr, false);
671 }
672
673 /*
674  * Lock a region of the flash. Compatible with ST Micro and similar flash.
675  * Supports the block protection bits BP{0,1,2} in the status register
676  * (SR). Does not support these features found in newer SR bitfields:
677  *   - SEC: sector/block protect - only handle SEC=0 (block protect)
678  *   - CMP: complement protect - only support CMP=0 (range is not complemented)
679  *
680  * Support for the following is provided conditionally for some flash:
681  *   - TB: top/bottom protect
682  *
683  * Sample table portion for 8MB flash (Winbond w25q64fw):
684  *
685  *   SEC  |  TB   |  BP2  |  BP1  |  BP0  |  Prot Length  | Protected Portion
686  *  --------------------------------------------------------------------------
687  *    X   |   X   |   0   |   0   |   0   |  NONE         | NONE
688  *    0   |   0   |   0   |   0   |   1   |  128 KB       | Upper 1/64
689  *    0   |   0   |   0   |   1   |   0   |  256 KB       | Upper 1/32
690  *    0   |   0   |   0   |   1   |   1   |  512 KB       | Upper 1/16
691  *    0   |   0   |   1   |   0   |   0   |  1 MB         | Upper 1/8
692  *    0   |   0   |   1   |   0   |   1   |  2 MB         | Upper 1/4
693  *    0   |   0   |   1   |   1   |   0   |  4 MB         | Upper 1/2
694  *    X   |   X   |   1   |   1   |   1   |  8 MB         | ALL
695  *  ------|-------|-------|-------|-------|---------------|-------------------
696  *    0   |   1   |   0   |   0   |   1   |  128 KB       | Lower 1/64
697  *    0   |   1   |   0   |   1   |   0   |  256 KB       | Lower 1/32
698  *    0   |   1   |   0   |   1   |   1   |  512 KB       | Lower 1/16
699  *    0   |   1   |   1   |   0   |   0   |  1 MB         | Lower 1/8
700  *    0   |   1   |   1   |   0   |   1   |  2 MB         | Lower 1/4
701  *    0   |   1   |   1   |   1   |   0   |  4 MB         | Lower 1/2
702  *
703  * Returns negative on errors, 0 on success.
704  */
705 static int stm_lock(struct spi_nor *nor, loff_t ofs, uint64_t len)
706 {
707         struct mtd_info *mtd = &nor->mtd;
708         int status_old, status_new;
709         u8 mask = SR_BP2 | SR_BP1 | SR_BP0;
710         u8 shift = ffs(mask) - 1, pow, val;
711         loff_t lock_len;
712         bool can_be_top = true, can_be_bottom = nor->flags & SNOR_F_HAS_SR_TB;
713         bool use_top;
714
715         status_old = read_sr(nor);
716         if (status_old < 0)
717                 return status_old;
718
719         /* If nothing in our range is unlocked, we don't need to do anything */
720         if (stm_is_locked_sr(nor, ofs, len, status_old))
721                 return 0;
722
723         /* If anything below us is unlocked, we can't use 'bottom' protection */
724         if (!stm_is_locked_sr(nor, 0, ofs, status_old))
725                 can_be_bottom = false;
726
727         /* If anything above us is unlocked, we can't use 'top' protection */
728         if (!stm_is_locked_sr(nor, ofs + len, mtd->size - (ofs + len),
729                               status_old))
730                 can_be_top = false;
731
732         if (!can_be_bottom && !can_be_top)
733                 return -EINVAL;
734
735         /* Prefer top, if both are valid */
736         use_top = can_be_top;
737
738         /* lock_len: length of region that should end up locked */
739         if (use_top)
740                 lock_len = mtd->size - ofs;
741         else
742                 lock_len = ofs + len;
743
744         /*
745          * Need smallest pow such that:
746          *
747          *   1 / (2^pow) <= (len / size)
748          *
749          * so (assuming power-of-2 size) we do:
750          *
751          *   pow = ceil(log2(size / len)) = log2(size) - floor(log2(len))
752          */
753         pow = ilog2(mtd->size) - ilog2(lock_len);
754         val = mask - (pow << shift);
755         if (val & ~mask)
756                 return -EINVAL;
757         /* Don't "lock" with no region! */
758         if (!(val & mask))
759                 return -EINVAL;
760
761         status_new = (status_old & ~mask & ~SR_TB) | val;
762
763         /* Disallow further writes if WP pin is asserted */
764         status_new |= SR_SRWD;
765
766         if (!use_top)
767                 status_new |= SR_TB;
768
769         /* Don't bother if they're the same */
770         if (status_new == status_old)
771                 return 0;
772
773         /* Only modify protection if it will not unlock other areas */
774         if ((status_new & mask) < (status_old & mask))
775                 return -EINVAL;
776
777         return write_sr_and_check(nor, status_new, mask);
778 }
779
780 /*
781  * Unlock a region of the flash. See stm_lock() for more info
782  *
783  * Returns negative on errors, 0 on success.
784  */
785 static int stm_unlock(struct spi_nor *nor, loff_t ofs, uint64_t len)
786 {
787         struct mtd_info *mtd = &nor->mtd;
788         int status_old, status_new;
789         u8 mask = SR_BP2 | SR_BP1 | SR_BP0;
790         u8 shift = ffs(mask) - 1, pow, val;
791         loff_t lock_len;
792         bool can_be_top = true, can_be_bottom = nor->flags & SNOR_F_HAS_SR_TB;
793         bool use_top;
794
795         status_old = read_sr(nor);
796         if (status_old < 0)
797                 return status_old;
798
799         /* If nothing in our range is locked, we don't need to do anything */
800         if (stm_is_unlocked_sr(nor, ofs, len, status_old))
801                 return 0;
802
803         /* If anything below us is locked, we can't use 'top' protection */
804         if (!stm_is_unlocked_sr(nor, 0, ofs, status_old))
805                 can_be_top = false;
806
807         /* If anything above us is locked, we can't use 'bottom' protection */
808         if (!stm_is_unlocked_sr(nor, ofs + len, mtd->size - (ofs + len),
809                                 status_old))
810                 can_be_bottom = false;
811
812         if (!can_be_bottom && !can_be_top)
813                 return -EINVAL;
814
815         /* Prefer top, if both are valid */
816         use_top = can_be_top;
817
818         /* lock_len: length of region that should remain locked */
819         if (use_top)
820                 lock_len = mtd->size - (ofs + len);
821         else
822                 lock_len = ofs;
823
824         /*
825          * Need largest pow such that:
826          *
827          *   1 / (2^pow) >= (len / size)
828          *
829          * so (assuming power-of-2 size) we do:
830          *
831          *   pow = floor(log2(size / len)) = log2(size) - ceil(log2(len))
832          */
833         pow = ilog2(mtd->size) - order_base_2(lock_len);
834         if (lock_len == 0) {
835                 val = 0; /* fully unlocked */
836         } else {
837                 val = mask - (pow << shift);
838                 /* Some power-of-two sizes are not supported */
839                 if (val & ~mask)
840                         return -EINVAL;
841         }
842
843         status_new = (status_old & ~mask & ~SR_TB) | val;
844
845         /* Don't protect status register if we're fully unlocked */
846         if (lock_len == 0)
847                 status_new &= ~SR_SRWD;
848
849         if (!use_top)
850                 status_new |= SR_TB;
851
852         /* Don't bother if they're the same */
853         if (status_new == status_old)
854                 return 0;
855
856         /* Only modify protection if it will not lock other areas */
857         if ((status_new & mask) > (status_old & mask))
858                 return -EINVAL;
859
860         return write_sr_and_check(nor, status_new, mask);
861 }
862
863 /*
864  * Check if a region of the flash is (completely) locked. See stm_lock() for
865  * more info.
866  *
867  * Returns 1 if entire region is locked, 0 if any portion is unlocked, and
868  * negative on errors.
869  */
870 static int stm_is_locked(struct spi_nor *nor, loff_t ofs, uint64_t len)
871 {
872         int status;
873
874         status = read_sr(nor);
875         if (status < 0)
876                 return status;
877
878         return stm_is_locked_sr(nor, ofs, len, status);
879 }
880 #endif /* CONFIG_SPI_FLASH_STMICRO */
881
882 static const struct flash_info *spi_nor_read_id(struct spi_nor *nor)
883 {
884         int                     tmp;
885         u8                      id[SPI_NOR_MAX_ID_LEN];
886         const struct flash_info *info;
887
888         tmp = nor->read_reg(nor, SPINOR_OP_RDID, id, SPI_NOR_MAX_ID_LEN);
889         if (tmp < 0) {
890                 dev_dbg(nor->dev, "error %d reading JEDEC ID\n", tmp);
891                 return ERR_PTR(tmp);
892         }
893
894         info = spi_nor_ids;
895         for (; info->name; info++) {
896                 if (info->id_len) {
897                         if (!memcmp(info->id, id, info->id_len))
898                                 return info;
899                 }
900         }
901
902         dev_err(nor->dev, "unrecognized JEDEC id bytes: %02x, %02x, %02x\n",
903                 id[0], id[1], id[2]);
904         return ERR_PTR(-ENODEV);
905 }
906
907 static int spi_nor_read(struct mtd_info *mtd, loff_t from, size_t len,
908                         size_t *retlen, u_char *buf)
909 {
910         struct spi_nor *nor = mtd_to_spi_nor(mtd);
911         int ret;
912
913         dev_dbg(nor->dev, "from 0x%08x, len %zd\n", (u32)from, len);
914
915         while (len) {
916                 loff_t addr = from;
917                 size_t read_len = len;
918
919 #ifdef CONFIG_SPI_FLASH_BAR
920                 u32 remain_len;
921
922                 ret = write_bar(nor, addr);
923                 if (ret < 0)
924                         return log_ret(ret);
925                 remain_len = (SZ_16M * (nor->bank_curr + 1)) - addr;
926
927                 if (len < remain_len)
928                         read_len = len;
929                 else
930                         read_len = remain_len;
931 #endif
932
933                 ret = nor->read(nor, addr, read_len, buf);
934                 if (ret == 0) {
935                         /* We shouldn't see 0-length reads */
936                         ret = -EIO;
937                         goto read_err;
938                 }
939                 if (ret < 0)
940                         goto read_err;
941
942                 *retlen += ret;
943                 buf += ret;
944                 from += ret;
945                 len -= ret;
946         }
947         ret = 0;
948
949 read_err:
950 #ifdef CONFIG_SPI_FLASH_BAR
951         ret = clean_bar(nor);
952 #endif
953         return ret;
954 }
955
956 #ifdef CONFIG_SPI_FLASH_SST
957 /*
958  * sst26 flash series has its own block protection implementation:
959  * 4x   - 8  KByte blocks - read & write protection bits - upper addresses
960  * 1x   - 32 KByte blocks - write protection bits
961  * rest - 64 KByte blocks - write protection bits
962  * 1x   - 32 KByte blocks - write protection bits
963  * 4x   - 8  KByte blocks - read & write protection bits - lower addresses
964  *
965  * We'll support only per 64k lock/unlock so lower and upper 64 KByte region
966  * will be treated as single block.
967  */
968 #define SST26_BPR_8K_NUM                4
969 #define SST26_MAX_BPR_REG_LEN           (18 + 1)
970 #define SST26_BOUND_REG_SIZE            ((32 + SST26_BPR_8K_NUM * 8) * SZ_1K)
971
972 enum lock_ctl {
973         SST26_CTL_LOCK,
974         SST26_CTL_UNLOCK,
975         SST26_CTL_CHECK
976 };
977
978 static bool sst26_process_bpr(u32 bpr_size, u8 *cmd, u32 bit, enum lock_ctl ctl)
979 {
980         switch (ctl) {
981         case SST26_CTL_LOCK:
982                 cmd[bpr_size - (bit / 8) - 1] |= BIT(bit % 8);
983                 break;
984         case SST26_CTL_UNLOCK:
985                 cmd[bpr_size - (bit / 8) - 1] &= ~BIT(bit % 8);
986                 break;
987         case SST26_CTL_CHECK:
988                 return !!(cmd[bpr_size - (bit / 8) - 1] & BIT(bit % 8));
989         }
990
991         return false;
992 }
993
994 /*
995  * Lock, unlock or check lock status of the flash region of the flash (depending
996  * on the lock_ctl value)
997  */
998 static int sst26_lock_ctl(struct spi_nor *nor, loff_t ofs, uint64_t len, enum lock_ctl ctl)
999 {
1000         struct mtd_info *mtd = &nor->mtd;
1001         u32 i, bpr_ptr, rptr_64k, lptr_64k, bpr_size;
1002         bool lower_64k = false, upper_64k = false;
1003         u8 bpr_buff[SST26_MAX_BPR_REG_LEN] = {};
1004         int ret;
1005
1006         /* Check length and offset for 64k alignment */
1007         if ((ofs & (SZ_64K - 1)) || (len & (SZ_64K - 1))) {
1008                 dev_err(nor->dev, "length or offset is not 64KiB allighned\n");
1009                 return -EINVAL;
1010         }
1011
1012         if (ofs + len > mtd->size) {
1013                 dev_err(nor->dev, "range is more than device size: %#llx + %#llx > %#llx\n",
1014                         ofs, len, mtd->size);
1015                 return -EINVAL;
1016         }
1017
1018         /* SST26 family has only 16 Mbit, 32 Mbit and 64 Mbit IC */
1019         if (mtd->size != SZ_2M &&
1020             mtd->size != SZ_4M &&
1021             mtd->size != SZ_8M)
1022                 return -EINVAL;
1023
1024         bpr_size = 2 + (mtd->size / SZ_64K / 8);
1025
1026         ret = nor->read_reg(nor, SPINOR_OP_READ_BPR, bpr_buff, bpr_size);
1027         if (ret < 0) {
1028                 dev_err(nor->dev, "fail to read block-protection register\n");
1029                 return ret;
1030         }
1031
1032         rptr_64k = min_t(u32, ofs + len, mtd->size - SST26_BOUND_REG_SIZE);
1033         lptr_64k = max_t(u32, ofs, SST26_BOUND_REG_SIZE);
1034
1035         upper_64k = ((ofs + len) > (mtd->size - SST26_BOUND_REG_SIZE));
1036         lower_64k = (ofs < SST26_BOUND_REG_SIZE);
1037
1038         /* Lower bits in block-protection register are about 64k region */
1039         bpr_ptr = lptr_64k / SZ_64K - 1;
1040
1041         /* Process 64K blocks region */
1042         while (lptr_64k < rptr_64k) {
1043                 if (sst26_process_bpr(bpr_size, bpr_buff, bpr_ptr, ctl))
1044                         return EACCES;
1045
1046                 bpr_ptr++;
1047                 lptr_64k += SZ_64K;
1048         }
1049
1050         /* 32K and 8K region bits in BPR are after 64k region bits */
1051         bpr_ptr = (mtd->size - 2 * SST26_BOUND_REG_SIZE) / SZ_64K;
1052
1053         /* Process lower 32K block region */
1054         if (lower_64k)
1055                 if (sst26_process_bpr(bpr_size, bpr_buff, bpr_ptr, ctl))
1056                         return EACCES;
1057
1058         bpr_ptr++;
1059
1060         /* Process upper 32K block region */
1061         if (upper_64k)
1062                 if (sst26_process_bpr(bpr_size, bpr_buff, bpr_ptr, ctl))
1063                         return EACCES;
1064
1065         bpr_ptr++;
1066
1067         /* Process lower 8K block regions */
1068         for (i = 0; i < SST26_BPR_8K_NUM; i++) {
1069                 if (lower_64k)
1070                         if (sst26_process_bpr(bpr_size, bpr_buff, bpr_ptr, ctl))
1071                                 return EACCES;
1072
1073                 /* In 8K area BPR has both read and write protection bits */
1074                 bpr_ptr += 2;
1075         }
1076
1077         /* Process upper 8K block regions */
1078         for (i = 0; i < SST26_BPR_8K_NUM; i++) {
1079                 if (upper_64k)
1080                         if (sst26_process_bpr(bpr_size, bpr_buff, bpr_ptr, ctl))
1081                                 return EACCES;
1082
1083                 /* In 8K area BPR has both read and write protection bits */
1084                 bpr_ptr += 2;
1085         }
1086
1087         /* If we check region status we don't need to write BPR back */
1088         if (ctl == SST26_CTL_CHECK)
1089                 return 0;
1090
1091         ret = nor->write_reg(nor, SPINOR_OP_WRITE_BPR, bpr_buff, bpr_size);
1092         if (ret < 0) {
1093                 dev_err(nor->dev, "fail to write block-protection register\n");
1094                 return ret;
1095         }
1096
1097         return 0;
1098 }
1099
1100 static int sst26_unlock(struct spi_nor *nor, loff_t ofs, uint64_t len)
1101 {
1102         return sst26_lock_ctl(nor, ofs, len, SST26_CTL_UNLOCK);
1103 }
1104
1105 static int sst26_lock(struct spi_nor *nor, loff_t ofs, uint64_t len)
1106 {
1107         return sst26_lock_ctl(nor, ofs, len, SST26_CTL_LOCK);
1108 }
1109
1110 /*
1111  * Returns EACCES (positive value) if region is locked, 0 if region is unlocked,
1112  * and negative on errors.
1113  */
1114 static int sst26_is_locked(struct spi_nor *nor, loff_t ofs, uint64_t len)
1115 {
1116         /*
1117          * is_locked function is used for check before reading or erasing flash
1118          * region, so offset and length might be not 64k allighned, so adjust
1119          * them to be 64k allighned as sst26_lock_ctl works only with 64k
1120          * allighned regions.
1121          */
1122         ofs -= ofs & (SZ_64K - 1);
1123         len = len & (SZ_64K - 1) ? (len & ~(SZ_64K - 1)) + SZ_64K : len;
1124
1125         return sst26_lock_ctl(nor, ofs, len, SST26_CTL_CHECK);
1126 }
1127
1128 static int sst_write_byteprogram(struct spi_nor *nor, loff_t to, size_t len,
1129                                  size_t *retlen, const u_char *buf)
1130 {
1131         size_t actual;
1132         int ret = 0;
1133
1134         for (actual = 0; actual < len; actual++) {
1135                 nor->program_opcode = SPINOR_OP_BP;
1136
1137                 write_enable(nor);
1138                 /* write one byte. */
1139                 ret = nor->write(nor, to, 1, buf + actual);
1140                 if (ret < 0)
1141                         goto sst_write_err;
1142                 ret = spi_nor_wait_till_ready(nor);
1143                 if (ret)
1144                         goto sst_write_err;
1145                 to++;
1146         }
1147
1148 sst_write_err:
1149         write_disable(nor);
1150         return ret;
1151 }
1152
1153 static int sst_write(struct mtd_info *mtd, loff_t to, size_t len,
1154                      size_t *retlen, const u_char *buf)
1155 {
1156         struct spi_nor *nor = mtd_to_spi_nor(mtd);
1157         struct spi_slave *spi = nor->spi;
1158         size_t actual;
1159         int ret;
1160
1161         dev_dbg(nor->dev, "to 0x%08x, len %zd\n", (u32)to, len);
1162         if (spi->mode & SPI_TX_BYTE)
1163                 return sst_write_byteprogram(nor, to, len, retlen, buf);
1164
1165         write_enable(nor);
1166
1167         nor->sst_write_second = false;
1168
1169         actual = to % 2;
1170         /* Start write from odd address. */
1171         if (actual) {
1172                 nor->program_opcode = SPINOR_OP_BP;
1173
1174                 /* write one byte. */
1175                 ret = nor->write(nor, to, 1, buf);
1176                 if (ret < 0)
1177                         goto sst_write_err;
1178                 ret = spi_nor_wait_till_ready(nor);
1179                 if (ret)
1180                         goto sst_write_err;
1181         }
1182         to += actual;
1183
1184         /* Write out most of the data here. */
1185         for (; actual < len - 1; actual += 2) {
1186                 nor->program_opcode = SPINOR_OP_AAI_WP;
1187
1188                 /* write two bytes. */
1189                 ret = nor->write(nor, to, 2, buf + actual);
1190                 if (ret < 0)
1191                         goto sst_write_err;
1192                 ret = spi_nor_wait_till_ready(nor);
1193                 if (ret)
1194                         goto sst_write_err;
1195                 to += 2;
1196                 nor->sst_write_second = true;
1197         }
1198         nor->sst_write_second = false;
1199
1200         write_disable(nor);
1201         ret = spi_nor_wait_till_ready(nor);
1202         if (ret)
1203                 goto sst_write_err;
1204
1205         /* Write out trailing byte if it exists. */
1206         if (actual != len) {
1207                 write_enable(nor);
1208
1209                 nor->program_opcode = SPINOR_OP_BP;
1210                 ret = nor->write(nor, to, 1, buf + actual);
1211                 if (ret < 0)
1212                         goto sst_write_err;
1213                 ret = spi_nor_wait_till_ready(nor);
1214                 if (ret)
1215                         goto sst_write_err;
1216                 write_disable(nor);
1217                 actual += 1;
1218         }
1219 sst_write_err:
1220         *retlen += actual;
1221         return ret;
1222 }
1223 #endif
1224 /*
1225  * Write an address range to the nor chip.  Data must be written in
1226  * FLASH_PAGESIZE chunks.  The address range may be any size provided
1227  * it is within the physical boundaries.
1228  */
1229 static int spi_nor_write(struct mtd_info *mtd, loff_t to, size_t len,
1230         size_t *retlen, const u_char *buf)
1231 {
1232         struct spi_nor *nor = mtd_to_spi_nor(mtd);
1233         size_t page_offset, page_remain, i;
1234         ssize_t ret;
1235
1236         dev_dbg(nor->dev, "to 0x%08x, len %zd\n", (u32)to, len);
1237
1238         if (!len)
1239                 return 0;
1240
1241         for (i = 0; i < len; ) {
1242                 ssize_t written;
1243                 loff_t addr = to + i;
1244
1245                 /*
1246                  * If page_size is a power of two, the offset can be quickly
1247                  * calculated with an AND operation. On the other cases we
1248                  * need to do a modulus operation (more expensive).
1249                  * Power of two numbers have only one bit set and we can use
1250                  * the instruction hweight32 to detect if we need to do a
1251                  * modulus (do_div()) or not.
1252                  */
1253                 if (hweight32(nor->page_size) == 1) {
1254                         page_offset = addr & (nor->page_size - 1);
1255                 } else {
1256                         u64 aux = addr;
1257
1258                         page_offset = do_div(aux, nor->page_size);
1259                 }
1260                 /* the size of data remaining on the first page */
1261                 page_remain = min_t(size_t,
1262                                     nor->page_size - page_offset, len - i);
1263
1264 #ifdef CONFIG_SPI_FLASH_BAR
1265                 ret = write_bar(nor, addr);
1266                 if (ret < 0)
1267                         return ret;
1268 #endif
1269                 write_enable(nor);
1270                 ret = nor->write(nor, addr, page_remain, buf + i);
1271                 if (ret < 0)
1272                         goto write_err;
1273                 written = ret;
1274
1275                 ret = spi_nor_wait_till_ready(nor);
1276                 if (ret)
1277                         goto write_err;
1278                 *retlen += written;
1279                 i += written;
1280         }
1281
1282 write_err:
1283 #ifdef CONFIG_SPI_FLASH_BAR
1284         ret = clean_bar(nor);
1285 #endif
1286         return ret;
1287 }
1288
1289 #ifdef CONFIG_SPI_FLASH_MACRONIX
1290 /**
1291  * macronix_quad_enable() - set QE bit in Status Register.
1292  * @nor:        pointer to a 'struct spi_nor'
1293  *
1294  * Set the Quad Enable (QE) bit in the Status Register.
1295  *
1296  * bit 6 of the Status Register is the QE bit for Macronix like QSPI memories.
1297  *
1298  * Return: 0 on success, -errno otherwise.
1299  */
1300 static int macronix_quad_enable(struct spi_nor *nor)
1301 {
1302         int ret, val;
1303
1304         val = read_sr(nor);
1305         if (val < 0)
1306                 return val;
1307         if (val & SR_QUAD_EN_MX)
1308                 return 0;
1309
1310         write_enable(nor);
1311
1312         write_sr(nor, val | SR_QUAD_EN_MX);
1313
1314         ret = spi_nor_wait_till_ready(nor);
1315         if (ret)
1316                 return ret;
1317
1318         ret = read_sr(nor);
1319         if (!(ret > 0 && (ret & SR_QUAD_EN_MX))) {
1320                 dev_err(nor->dev, "Macronix Quad bit not set\n");
1321                 return -EINVAL;
1322         }
1323
1324         return 0;
1325 }
1326 #endif
1327
1328 #if defined(CONFIG_SPI_FLASH_SPANSION) || defined(CONFIG_SPI_FLASH_WINBOND)
1329 /*
1330  * Write status Register and configuration register with 2 bytes
1331  * The first byte will be written to the status register, while the
1332  * second byte will be written to the configuration register.
1333  * Return negative if error occurred.
1334  */
1335 static int write_sr_cr(struct spi_nor *nor, u8 *sr_cr)
1336 {
1337         int ret;
1338
1339         write_enable(nor);
1340
1341         ret = nor->write_reg(nor, SPINOR_OP_WRSR, sr_cr, 2);
1342         if (ret < 0) {
1343                 dev_dbg(nor->dev,
1344                         "error while writing configuration register\n");
1345                 return -EINVAL;
1346         }
1347
1348         ret = spi_nor_wait_till_ready(nor);
1349         if (ret) {
1350                 dev_dbg(nor->dev,
1351                         "timeout while writing configuration register\n");
1352                 return ret;
1353         }
1354
1355         return 0;
1356 }
1357
1358 /**
1359  * spansion_read_cr_quad_enable() - set QE bit in Configuration Register.
1360  * @nor:        pointer to a 'struct spi_nor'
1361  *
1362  * Set the Quad Enable (QE) bit in the Configuration Register.
1363  * This function should be used with QSPI memories supporting the Read
1364  * Configuration Register (35h) instruction.
1365  *
1366  * bit 1 of the Configuration Register is the QE bit for Spansion like QSPI
1367  * memories.
1368  *
1369  * Return: 0 on success, -errno otherwise.
1370  */
1371 static int spansion_read_cr_quad_enable(struct spi_nor *nor)
1372 {
1373         u8 sr_cr[2];
1374         int ret;
1375
1376         /* Check current Quad Enable bit value. */
1377         ret = read_cr(nor);
1378         if (ret < 0) {
1379                 dev_dbg(dev, "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(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(dev, "failed to read SFDP parameter headers\n");
2075                         goto exit;
2076                 }
2077         }
2078
2079         /*
2080          * Check other parameter headers to get the latest revision of
2081          * the basic flash parameter table.
2082          */
2083         for (i = 0; i < header.nph; i++) {
2084                 param_header = &param_headers[i];
2085
2086                 if (SFDP_PARAM_HEADER_ID(param_header) == SFDP_BFPT_ID &&
2087                     param_header->major == SFDP_JESD216_MAJOR &&
2088                     (param_header->minor > bfpt_header->minor ||
2089                      (param_header->minor == bfpt_header->minor &&
2090                       param_header->length > bfpt_header->length)))
2091                         bfpt_header = param_header;
2092         }
2093
2094         err = spi_nor_parse_bfpt(nor, bfpt_header, params);
2095         if (err)
2096                 goto exit;
2097
2098         /* Parse other parameter headers. */
2099         for (i = 0; i < header.nph; i++) {
2100                 param_header = &param_headers[i];
2101
2102                 switch (SFDP_PARAM_HEADER_ID(param_header)) {
2103                 case SFDP_SECTOR_MAP_ID:
2104                         dev_info(dev, "non-uniform erase sector maps are not supported yet.\n");
2105                         break;
2106
2107                 case SFDP_SST_ID:
2108                         err = spi_nor_parse_microchip_sfdp(nor, param_header);
2109                         break;
2110
2111                 default:
2112                         break;
2113                 }
2114
2115                 if (err) {
2116                         dev_warn(dev, "Failed to parse optional parameter table: %04x\n",
2117                                  SFDP_PARAM_HEADER_ID(param_header));
2118                         /*
2119                          * Let's not drop all information we extracted so far
2120                          * if optional table parsers fail. In case of failing,
2121                          * each optional parser is responsible to roll back to
2122                          * the previously known spi_nor data.
2123                          */
2124                         err = 0;
2125                 }
2126         }
2127
2128 exit:
2129         kfree(param_headers);
2130         return err;
2131 }
2132 #else
2133 static int spi_nor_parse_sfdp(struct spi_nor *nor,
2134                               struct spi_nor_flash_parameter *params)
2135 {
2136         return -EINVAL;
2137 }
2138 #endif /* SPI_FLASH_SFDP_SUPPORT */
2139
2140 static int spi_nor_init_params(struct spi_nor *nor,
2141                                const struct flash_info *info,
2142                                struct spi_nor_flash_parameter *params)
2143 {
2144         /* Set legacy flash parameters as default. */
2145         memset(params, 0, sizeof(*params));
2146
2147         /* Set SPI NOR sizes. */
2148         params->size = info->sector_size * info->n_sectors;
2149         params->page_size = info->page_size;
2150
2151         /* (Fast) Read settings. */
2152         params->hwcaps.mask |= SNOR_HWCAPS_READ;
2153         spi_nor_set_read_settings(&params->reads[SNOR_CMD_READ],
2154                                   0, 0, SPINOR_OP_READ,
2155                                   SNOR_PROTO_1_1_1);
2156
2157         if (!(info->flags & SPI_NOR_NO_FR)) {
2158                 params->hwcaps.mask |= SNOR_HWCAPS_READ_FAST;
2159                 spi_nor_set_read_settings(&params->reads[SNOR_CMD_READ_FAST],
2160                                           0, 8, SPINOR_OP_READ_FAST,
2161                                           SNOR_PROTO_1_1_1);
2162         }
2163
2164         if (info->flags & SPI_NOR_DUAL_READ) {
2165                 params->hwcaps.mask |= SNOR_HWCAPS_READ_1_1_2;
2166                 spi_nor_set_read_settings(&params->reads[SNOR_CMD_READ_1_1_2],
2167                                           0, 8, SPINOR_OP_READ_1_1_2,
2168                                           SNOR_PROTO_1_1_2);
2169         }
2170
2171         if (info->flags & SPI_NOR_QUAD_READ) {
2172                 params->hwcaps.mask |= SNOR_HWCAPS_READ_1_1_4;
2173                 spi_nor_set_read_settings(&params->reads[SNOR_CMD_READ_1_1_4],
2174                                           0, 8, SPINOR_OP_READ_1_1_4,
2175                                           SNOR_PROTO_1_1_4);
2176         }
2177
2178         if (info->flags & SPI_NOR_OCTAL_READ) {
2179                 params->hwcaps.mask |= SNOR_HWCAPS_READ_1_1_8;
2180                 spi_nor_set_read_settings(&params->reads[SNOR_CMD_READ_1_1_8],
2181                                           0, 8, SPINOR_OP_READ_1_1_8,
2182                                           SNOR_PROTO_1_1_8);
2183         }
2184
2185         /* Page Program settings. */
2186         params->hwcaps.mask |= SNOR_HWCAPS_PP;
2187         spi_nor_set_pp_settings(&params->page_programs[SNOR_CMD_PP],
2188                                 SPINOR_OP_PP, SNOR_PROTO_1_1_1);
2189
2190         if (info->flags & SPI_NOR_QUAD_READ) {
2191                 params->hwcaps.mask |= SNOR_HWCAPS_PP_1_1_4;
2192                 spi_nor_set_pp_settings(&params->page_programs[SNOR_CMD_PP_1_1_4],
2193                                         SPINOR_OP_PP_1_1_4, SNOR_PROTO_1_1_4);
2194         }
2195
2196         /* Select the procedure to set the Quad Enable bit. */
2197         if (params->hwcaps.mask & (SNOR_HWCAPS_READ_QUAD |
2198                                    SNOR_HWCAPS_PP_QUAD)) {
2199                 switch (JEDEC_MFR(info)) {
2200 #ifdef CONFIG_SPI_FLASH_MACRONIX
2201                 case SNOR_MFR_MACRONIX:
2202                         params->quad_enable = macronix_quad_enable;
2203                         break;
2204 #endif
2205                 case SNOR_MFR_ST:
2206                 case SNOR_MFR_MICRON:
2207                         break;
2208
2209                 default:
2210 #if defined(CONFIG_SPI_FLASH_SPANSION) || defined(CONFIG_SPI_FLASH_WINBOND)
2211                         /* Kept only for backward compatibility purpose. */
2212                         params->quad_enable = spansion_read_cr_quad_enable;
2213 #endif
2214                         break;
2215                 }
2216         }
2217
2218         /* Override the parameters with data read from SFDP tables. */
2219         nor->addr_width = 0;
2220         nor->mtd.erasesize = 0;
2221         if ((info->flags & (SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ)) &&
2222             !(info->flags & SPI_NOR_SKIP_SFDP)) {
2223                 struct spi_nor_flash_parameter sfdp_params;
2224
2225                 memcpy(&sfdp_params, params, sizeof(sfdp_params));
2226                 if (spi_nor_parse_sfdp(nor, &sfdp_params)) {
2227                         nor->addr_width = 0;
2228                         nor->mtd.erasesize = 0;
2229                 } else {
2230                         memcpy(params, &sfdp_params, sizeof(*params));
2231                 }
2232         }
2233
2234         return 0;
2235 }
2236
2237 static int spi_nor_hwcaps2cmd(u32 hwcaps, const int table[][2], size_t size)
2238 {
2239         size_t i;
2240
2241         for (i = 0; i < size; i++)
2242                 if (table[i][0] == (int)hwcaps)
2243                         return table[i][1];
2244
2245         return -EINVAL;
2246 }
2247
2248 static int spi_nor_hwcaps_read2cmd(u32 hwcaps)
2249 {
2250         static const int hwcaps_read2cmd[][2] = {
2251                 { SNOR_HWCAPS_READ,             SNOR_CMD_READ },
2252                 { SNOR_HWCAPS_READ_FAST,        SNOR_CMD_READ_FAST },
2253                 { SNOR_HWCAPS_READ_1_1_1_DTR,   SNOR_CMD_READ_1_1_1_DTR },
2254                 { SNOR_HWCAPS_READ_1_1_2,       SNOR_CMD_READ_1_1_2 },
2255                 { SNOR_HWCAPS_READ_1_2_2,       SNOR_CMD_READ_1_2_2 },
2256                 { SNOR_HWCAPS_READ_2_2_2,       SNOR_CMD_READ_2_2_2 },
2257                 { SNOR_HWCAPS_READ_1_2_2_DTR,   SNOR_CMD_READ_1_2_2_DTR },
2258                 { SNOR_HWCAPS_READ_1_1_4,       SNOR_CMD_READ_1_1_4 },
2259                 { SNOR_HWCAPS_READ_1_4_4,       SNOR_CMD_READ_1_4_4 },
2260                 { SNOR_HWCAPS_READ_4_4_4,       SNOR_CMD_READ_4_4_4 },
2261                 { SNOR_HWCAPS_READ_1_4_4_DTR,   SNOR_CMD_READ_1_4_4_DTR },
2262                 { SNOR_HWCAPS_READ_1_1_8,       SNOR_CMD_READ_1_1_8 },
2263                 { SNOR_HWCAPS_READ_1_8_8,       SNOR_CMD_READ_1_8_8 },
2264                 { SNOR_HWCAPS_READ_8_8_8,       SNOR_CMD_READ_8_8_8 },
2265                 { SNOR_HWCAPS_READ_1_8_8_DTR,   SNOR_CMD_READ_1_8_8_DTR },
2266         };
2267
2268         return spi_nor_hwcaps2cmd(hwcaps, hwcaps_read2cmd,
2269                                   ARRAY_SIZE(hwcaps_read2cmd));
2270 }
2271
2272 static int spi_nor_hwcaps_pp2cmd(u32 hwcaps)
2273 {
2274         static const int hwcaps_pp2cmd[][2] = {
2275                 { SNOR_HWCAPS_PP,               SNOR_CMD_PP },
2276                 { SNOR_HWCAPS_PP_1_1_4,         SNOR_CMD_PP_1_1_4 },
2277                 { SNOR_HWCAPS_PP_1_4_4,         SNOR_CMD_PP_1_4_4 },
2278                 { SNOR_HWCAPS_PP_4_4_4,         SNOR_CMD_PP_4_4_4 },
2279                 { SNOR_HWCAPS_PP_1_1_8,         SNOR_CMD_PP_1_1_8 },
2280                 { SNOR_HWCAPS_PP_1_8_8,         SNOR_CMD_PP_1_8_8 },
2281                 { SNOR_HWCAPS_PP_8_8_8,         SNOR_CMD_PP_8_8_8 },
2282         };
2283
2284         return spi_nor_hwcaps2cmd(hwcaps, hwcaps_pp2cmd,
2285                                   ARRAY_SIZE(hwcaps_pp2cmd));
2286 }
2287
2288 static int spi_nor_select_read(struct spi_nor *nor,
2289                                const struct spi_nor_flash_parameter *params,
2290                                u32 shared_hwcaps)
2291 {
2292         int cmd, best_match = fls(shared_hwcaps & SNOR_HWCAPS_READ_MASK) - 1;
2293         const struct spi_nor_read_command *read;
2294
2295         if (best_match < 0)
2296                 return -EINVAL;
2297
2298         cmd = spi_nor_hwcaps_read2cmd(BIT(best_match));
2299         if (cmd < 0)
2300                 return -EINVAL;
2301
2302         read = &params->reads[cmd];
2303         nor->read_opcode = read->opcode;
2304         nor->read_proto = read->proto;
2305
2306         /*
2307          * In the spi-nor framework, we don't need to make the difference
2308          * between mode clock cycles and wait state clock cycles.
2309          * Indeed, the value of the mode clock cycles is used by a QSPI
2310          * flash memory to know whether it should enter or leave its 0-4-4
2311          * (Continuous Read / XIP) mode.
2312          * eXecution In Place is out of the scope of the mtd sub-system.
2313          * Hence we choose to merge both mode and wait state clock cycles
2314          * into the so called dummy clock cycles.
2315          */
2316         nor->read_dummy = read->num_mode_clocks + read->num_wait_states;
2317         return 0;
2318 }
2319
2320 static int spi_nor_select_pp(struct spi_nor *nor,
2321                              const struct spi_nor_flash_parameter *params,
2322                              u32 shared_hwcaps)
2323 {
2324         int cmd, best_match = fls(shared_hwcaps & SNOR_HWCAPS_PP_MASK) - 1;
2325         const struct spi_nor_pp_command *pp;
2326
2327         if (best_match < 0)
2328                 return -EINVAL;
2329
2330         cmd = spi_nor_hwcaps_pp2cmd(BIT(best_match));
2331         if (cmd < 0)
2332                 return -EINVAL;
2333
2334         pp = &params->page_programs[cmd];
2335         nor->program_opcode = pp->opcode;
2336         nor->write_proto = pp->proto;
2337         return 0;
2338 }
2339
2340 static int spi_nor_select_erase(struct spi_nor *nor,
2341                                 const struct flash_info *info)
2342 {
2343         struct mtd_info *mtd = &nor->mtd;
2344
2345         /* Do nothing if already configured from SFDP. */
2346         if (mtd->erasesize)
2347                 return 0;
2348
2349 #ifdef CONFIG_SPI_FLASH_USE_4K_SECTORS
2350         /* prefer "small sector" erase if possible */
2351         if (info->flags & SECT_4K) {
2352                 nor->erase_opcode = SPINOR_OP_BE_4K;
2353                 mtd->erasesize = 4096;
2354         } else if (info->flags & SECT_4K_PMC) {
2355                 nor->erase_opcode = SPINOR_OP_BE_4K_PMC;
2356                 mtd->erasesize = 4096;
2357         } else
2358 #endif
2359         {
2360                 nor->erase_opcode = SPINOR_OP_SE;
2361                 mtd->erasesize = info->sector_size;
2362         }
2363         return 0;
2364 }
2365
2366 static int spi_nor_setup(struct spi_nor *nor, const struct flash_info *info,
2367                          const struct spi_nor_flash_parameter *params,
2368                          const struct spi_nor_hwcaps *hwcaps)
2369 {
2370         u32 ignored_mask, shared_mask;
2371         bool enable_quad_io;
2372         int err;
2373
2374         /*
2375          * Keep only the hardware capabilities supported by both the SPI
2376          * controller and the SPI flash memory.
2377          */
2378         shared_mask = hwcaps->mask & params->hwcaps.mask;
2379
2380         /* SPI n-n-n protocols are not supported yet. */
2381         ignored_mask = (SNOR_HWCAPS_READ_2_2_2 |
2382                         SNOR_HWCAPS_READ_4_4_4 |
2383                         SNOR_HWCAPS_READ_8_8_8 |
2384                         SNOR_HWCAPS_PP_4_4_4 |
2385                         SNOR_HWCAPS_PP_8_8_8);
2386         if (shared_mask & ignored_mask) {
2387                 dev_dbg(nor->dev,
2388                         "SPI n-n-n protocols are not supported yet.\n");
2389                 shared_mask &= ~ignored_mask;
2390         }
2391
2392         /* Select the (Fast) Read command. */
2393         err = spi_nor_select_read(nor, params, shared_mask);
2394         if (err) {
2395                 dev_dbg(nor->dev,
2396                         "can't select read settings supported by both the SPI controller and memory.\n");
2397                 return err;
2398         }
2399
2400         /* Select the Page Program command. */
2401         err = spi_nor_select_pp(nor, params, shared_mask);
2402         if (err) {
2403                 dev_dbg(nor->dev,
2404                         "can't select write settings supported by both the SPI controller and memory.\n");
2405                 return err;
2406         }
2407
2408         /* Select the Sector Erase command. */
2409         err = spi_nor_select_erase(nor, info);
2410         if (err) {
2411                 dev_dbg(nor->dev,
2412                         "can't select erase settings supported by both the SPI controller and memory.\n");
2413                 return err;
2414         }
2415
2416         /* Enable Quad I/O if needed. */
2417         enable_quad_io = (spi_nor_get_protocol_width(nor->read_proto) == 4 ||
2418                           spi_nor_get_protocol_width(nor->write_proto) == 4);
2419         if (enable_quad_io && params->quad_enable)
2420                 nor->quad_enable = params->quad_enable;
2421         else
2422                 nor->quad_enable = NULL;
2423
2424         return 0;
2425 }
2426
2427 static int spi_nor_init(struct spi_nor *nor)
2428 {
2429         int err;
2430
2431         /*
2432          * Atmel, SST, Intel/Numonyx, and others serial NOR tend to power up
2433          * with the software protection bits set
2434          */
2435         if (JEDEC_MFR(nor->info) == SNOR_MFR_ATMEL ||
2436             JEDEC_MFR(nor->info) == SNOR_MFR_INTEL ||
2437             JEDEC_MFR(nor->info) == SNOR_MFR_SST ||
2438             nor->info->flags & SPI_NOR_HAS_LOCK) {
2439                 write_enable(nor);
2440                 write_sr(nor, 0);
2441                 spi_nor_wait_till_ready(nor);
2442         }
2443
2444         if (nor->quad_enable) {
2445                 err = nor->quad_enable(nor);
2446                 if (err) {
2447                         dev_dbg(nor->dev, "quad mode not supported\n");
2448                         return err;
2449                 }
2450         }
2451
2452         if (nor->addr_width == 4 &&
2453             (JEDEC_MFR(nor->info) != SNOR_MFR_SPANSION) &&
2454             !(nor->info->flags & SPI_NOR_4B_OPCODES)) {
2455                 /*
2456                  * If the RESET# pin isn't hooked up properly, or the system
2457                  * otherwise doesn't perform a reset command in the boot
2458                  * sequence, it's impossible to 100% protect against unexpected
2459                  * reboots (e.g., crashes). Warn the user (or hopefully, system
2460                  * designer) that this is bad.
2461                  */
2462                 if (nor->flags & SNOR_F_BROKEN_RESET)
2463                         printf("enabling reset hack; may not recover from unexpected reboots\n");
2464                 set_4byte(nor, nor->info, 1);
2465         }
2466
2467         return 0;
2468 }
2469
2470 int spi_nor_scan(struct spi_nor *nor)
2471 {
2472         struct spi_nor_flash_parameter params;
2473         const struct flash_info *info = NULL;
2474         struct mtd_info *mtd = &nor->mtd;
2475         struct spi_nor_hwcaps hwcaps = {
2476                 .mask = SNOR_HWCAPS_READ |
2477                         SNOR_HWCAPS_READ_FAST |
2478                         SNOR_HWCAPS_PP,
2479         };
2480         struct spi_slave *spi = nor->spi;
2481         int ret;
2482
2483         /* Reset SPI protocol for all commands. */
2484         nor->reg_proto = SNOR_PROTO_1_1_1;
2485         nor->read_proto = SNOR_PROTO_1_1_1;
2486         nor->write_proto = SNOR_PROTO_1_1_1;
2487         nor->read = spi_nor_read_data;
2488         nor->write = spi_nor_write_data;
2489         nor->read_reg = spi_nor_read_reg;
2490         nor->write_reg = spi_nor_write_reg;
2491
2492         if (spi->mode & SPI_RX_OCTAL) {
2493                 hwcaps.mask |= SNOR_HWCAPS_READ_1_1_8;
2494
2495                 if (spi->mode & SPI_TX_OCTAL)
2496                         hwcaps.mask |= (SNOR_HWCAPS_READ_1_8_8 |
2497                                         SNOR_HWCAPS_PP_1_1_8 |
2498                                         SNOR_HWCAPS_PP_1_8_8);
2499         } else if (spi->mode & SPI_RX_QUAD) {
2500                 hwcaps.mask |= SNOR_HWCAPS_READ_1_1_4;
2501
2502                 if (spi->mode & SPI_TX_QUAD)
2503                         hwcaps.mask |= (SNOR_HWCAPS_READ_1_4_4 |
2504                                         SNOR_HWCAPS_PP_1_1_4 |
2505                                         SNOR_HWCAPS_PP_1_4_4);
2506         } else if (spi->mode & SPI_RX_DUAL) {
2507                 hwcaps.mask |= SNOR_HWCAPS_READ_1_1_2;
2508
2509                 if (spi->mode & SPI_TX_DUAL)
2510                         hwcaps.mask |= SNOR_HWCAPS_READ_1_2_2;
2511         }
2512
2513         info = spi_nor_read_id(nor);
2514         if (IS_ERR_OR_NULL(info))
2515                 return -ENOENT;
2516         /* Parse the Serial Flash Discoverable Parameters table. */
2517         ret = spi_nor_init_params(nor, info, &params);
2518         if (ret)
2519                 return ret;
2520
2521         if (!mtd->name)
2522                 mtd->name = info->name;
2523         mtd->priv = nor;
2524         mtd->type = MTD_NORFLASH;
2525         mtd->writesize = 1;
2526         mtd->flags = MTD_CAP_NORFLASH;
2527         mtd->size = params.size;
2528         mtd->_erase = spi_nor_erase;
2529         mtd->_read = spi_nor_read;
2530
2531 #if defined(CONFIG_SPI_FLASH_STMICRO) || defined(CONFIG_SPI_FLASH_SST)
2532         /* NOR protection support for STmicro/Micron chips and similar */
2533         if (JEDEC_MFR(info) == SNOR_MFR_ST ||
2534             JEDEC_MFR(info) == SNOR_MFR_MICRON ||
2535             JEDEC_MFR(info) == SNOR_MFR_SST ||
2536                         info->flags & SPI_NOR_HAS_LOCK) {
2537                 nor->flash_lock = stm_lock;
2538                 nor->flash_unlock = stm_unlock;
2539                 nor->flash_is_locked = stm_is_locked;
2540         }
2541 #endif
2542
2543 #ifdef CONFIG_SPI_FLASH_SST
2544         /*
2545          * sst26 series block protection implementation differs from other
2546          * series.
2547          */
2548         if (info->flags & SPI_NOR_HAS_SST26LOCK) {
2549                 nor->flash_lock = sst26_lock;
2550                 nor->flash_unlock = sst26_unlock;
2551                 nor->flash_is_locked = sst26_is_locked;
2552         }
2553
2554         /* sst nor chips use AAI word program */
2555         if (info->flags & SST_WRITE)
2556                 mtd->_write = sst_write;
2557         else
2558 #endif
2559                 mtd->_write = spi_nor_write;
2560
2561         if (info->flags & USE_FSR)
2562                 nor->flags |= SNOR_F_USE_FSR;
2563         if (info->flags & SPI_NOR_HAS_TB)
2564                 nor->flags |= SNOR_F_HAS_SR_TB;
2565         if (info->flags & NO_CHIP_ERASE)
2566                 nor->flags |= SNOR_F_NO_OP_CHIP_ERASE;
2567         if (info->flags & USE_CLSR)
2568                 nor->flags |= SNOR_F_USE_CLSR;
2569
2570         if (info->flags & SPI_NOR_NO_ERASE)
2571                 mtd->flags |= MTD_NO_ERASE;
2572
2573         nor->page_size = params.page_size;
2574         mtd->writebufsize = nor->page_size;
2575
2576         /* Some devices cannot do fast-read, no matter what DT tells us */
2577         if ((info->flags & SPI_NOR_NO_FR) || (spi->mode & SPI_RX_SLOW))
2578                 params.hwcaps.mask &= ~SNOR_HWCAPS_READ_FAST;
2579
2580         /*
2581          * Configure the SPI memory:
2582          * - select op codes for (Fast) Read, Page Program and Sector Erase.
2583          * - set the number of dummy cycles (mode cycles + wait states).
2584          * - set the SPI protocols for register and memory accesses.
2585          * - set the Quad Enable bit if needed (required by SPI x-y-4 protos).
2586          */
2587         ret = spi_nor_setup(nor, info, &params, &hwcaps);
2588         if (ret)
2589                 return ret;
2590
2591         if (nor->addr_width) {
2592                 /* already configured from SFDP */
2593         } else if (info->addr_width) {
2594                 nor->addr_width = info->addr_width;
2595         } else if (mtd->size > SZ_16M) {
2596 #ifndef CONFIG_SPI_FLASH_BAR
2597                 /* enable 4-byte addressing if the device exceeds 16MiB */
2598                 nor->addr_width = 4;
2599                 if (JEDEC_MFR(info) == SNOR_MFR_SPANSION ||
2600                     info->flags & SPI_NOR_4B_OPCODES)
2601                         spi_nor_set_4byte_opcodes(nor, info);
2602 #else
2603         /* Configure the BAR - discover bank cmds and read current bank */
2604         nor->addr_width = 3;
2605         ret = read_bar(nor, info);
2606         if (ret < 0)
2607                 return ret;
2608 #endif
2609         } else {
2610                 nor->addr_width = 3;
2611         }
2612
2613         if (nor->addr_width > SPI_NOR_MAX_ADDR_WIDTH) {
2614                 dev_dbg(dev, "address width is too large: %u\n",
2615                         nor->addr_width);
2616                 return -EINVAL;
2617         }
2618
2619         /* Send all the required SPI flash commands to initialize device */
2620         nor->info = info;
2621         ret = spi_nor_init(nor);
2622         if (ret)
2623                 return ret;
2624
2625         nor->name = mtd->name;
2626         nor->size = mtd->size;
2627         nor->erase_size = mtd->erasesize;
2628         nor->sector_size = mtd->erasesize;
2629
2630 #ifndef CONFIG_SPL_BUILD
2631         printf("SF: Detected %s with page size ", nor->name);
2632         print_size(nor->page_size, ", erase size ");
2633         print_size(nor->erase_size, ", total ");
2634         print_size(nor->size, "");
2635         puts("\n");
2636 #endif
2637
2638         return 0;
2639 }
2640
2641 /* U-Boot specific functions, need to extend MTD to support these */
2642 int spi_flash_cmd_get_sw_write_prot(struct spi_nor *nor)
2643 {
2644         int sr = read_sr(nor);
2645
2646         if (sr < 0)
2647                 return sr;
2648
2649         return (sr >> 2) & 7;
2650 }