GNU Linux-libre 4.14.266-gnu1
[releases.git] / drivers / mtd / spi-nor / spi-nor.c
1 /*
2  * Based on m25p80.c, by Mike Lavender (mike@steroidmicros.com), with
3  * influence from lart.c (Abraham Van Der Merwe) and mtd_dataflash.c
4  *
5  * Copyright (C) 2005, Intec Automation Inc.
6  * Copyright (C) 2014, Freescale Semiconductor, Inc.
7  *
8  * This code is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License version 2 as
10  * published by the Free Software Foundation.
11  */
12
13 #include <linux/err.h>
14 #include <linux/errno.h>
15 #include <linux/module.h>
16 #include <linux/device.h>
17 #include <linux/mutex.h>
18 #include <linux/math64.h>
19 #include <linux/sizes.h>
20 #include <linux/slab.h>
21
22 #include <linux/mtd/mtd.h>
23 #include <linux/of_platform.h>
24 #include <linux/spi/flash.h>
25 #include <linux/mtd/spi-nor.h>
26
27 /* Define max times to check status register before we give up. */
28
29 /*
30  * For everything but full-chip erase; probably could be much smaller, but kept
31  * around for safety for now
32  */
33 #define DEFAULT_READY_WAIT_JIFFIES              (40UL * HZ)
34
35 /*
36  * For full-chip erase, calibrated to a 2MB flash (M25P16); should be scaled up
37  * for larger flash
38  */
39 #define CHIP_ERASE_2MB_READY_WAIT_JIFFIES       (40UL * HZ)
40
41 #define SPI_NOR_MAX_ID_LEN      6
42 #define SPI_NOR_MAX_ADDR_WIDTH  4
43
44 struct flash_info {
45         char            *name;
46
47         /*
48          * This array stores the ID bytes.
49          * The first three bytes are the JEDIC ID.
50          * JEDEC ID zero means "no ID" (mostly older chips).
51          */
52         u8              id[SPI_NOR_MAX_ID_LEN];
53         u8              id_len;
54
55         /* The size listed here is what works with SPINOR_OP_SE, which isn't
56          * necessarily called a "sector" by the vendor.
57          */
58         unsigned        sector_size;
59         u16             n_sectors;
60
61         u16             page_size;
62         u16             addr_width;
63
64         u16             flags;
65 #define SECT_4K                 BIT(0)  /* SPINOR_OP_BE_4K works uniformly */
66 #define SPI_NOR_NO_ERASE        BIT(1)  /* No erase command needed */
67 #define SST_WRITE               BIT(2)  /* use SST byte programming */
68 #define SPI_NOR_NO_FR           BIT(3)  /* Can't do fastread */
69 #define SECT_4K_PMC             BIT(4)  /* SPINOR_OP_BE_4K_PMC works uniformly */
70 #define SPI_NOR_DUAL_READ       BIT(5)  /* Flash supports Dual Read */
71 #define SPI_NOR_QUAD_READ       BIT(6)  /* Flash supports Quad Read */
72 #define USE_FSR                 BIT(7)  /* use flag status register */
73 #define SPI_NOR_HAS_LOCK        BIT(8)  /* Flash supports lock/unlock via SR */
74 #define SPI_NOR_HAS_TB          BIT(9)  /*
75                                          * Flash SR has Top/Bottom (TB) protect
76                                          * bit. Must be used with
77                                          * SPI_NOR_HAS_LOCK.
78                                          */
79 #define SPI_S3AN                BIT(10) /*
80                                          * Xilinx Spartan 3AN In-System Flash
81                                          * (MFR cannot be used for probing
82                                          * because it has the same value as
83                                          * ATMEL flashes)
84                                          */
85 #define SPI_NOR_4B_OPCODES      BIT(11) /*
86                                          * Use dedicated 4byte address op codes
87                                          * to support memory size above 128Mib.
88                                          */
89 #define NO_CHIP_ERASE           BIT(12) /* Chip does not support chip erase */
90 #define SPI_NOR_SKIP_SFDP       BIT(13) /* Skip parsing of SFDP tables */
91 #define USE_CLSR                BIT(14) /* use CLSR command */
92 };
93
94 #define JEDEC_MFR(info) ((info)->id[0])
95
96 static const struct flash_info *spi_nor_match_id(const char *name);
97
98 /*
99  * Read the status register, returning its value in the location
100  * Return the status register value.
101  * Returns negative if error occurred.
102  */
103 static int read_sr(struct spi_nor *nor)
104 {
105         int ret;
106         u8 val;
107
108         ret = nor->read_reg(nor, SPINOR_OP_RDSR, &val, 1);
109         if (ret < 0) {
110                 pr_err("error %d reading SR\n", (int) ret);
111                 return ret;
112         }
113
114         return val;
115 }
116
117 /*
118  * Read the flag status register, returning its value in the location
119  * Return the status register value.
120  * Returns negative if error occurred.
121  */
122 static int read_fsr(struct spi_nor *nor)
123 {
124         int ret;
125         u8 val;
126
127         ret = nor->read_reg(nor, SPINOR_OP_RDFSR, &val, 1);
128         if (ret < 0) {
129                 pr_err("error %d reading FSR\n", ret);
130                 return ret;
131         }
132
133         return val;
134 }
135
136 /*
137  * Read configuration register, returning its value in the
138  * location. Return the configuration register value.
139  * Returns negative if error occurred.
140  */
141 static int read_cr(struct spi_nor *nor)
142 {
143         int ret;
144         u8 val;
145
146         ret = nor->read_reg(nor, SPINOR_OP_RDCR, &val, 1);
147         if (ret < 0) {
148                 dev_err(nor->dev, "error %d reading CR\n", ret);
149                 return ret;
150         }
151
152         return val;
153 }
154
155 /*
156  * Write status register 1 byte
157  * Returns negative if error occurred.
158  */
159 static inline int write_sr(struct spi_nor *nor, u8 val)
160 {
161         nor->cmd_buf[0] = val;
162         return nor->write_reg(nor, SPINOR_OP_WRSR, nor->cmd_buf, 1);
163 }
164
165 /*
166  * Set write enable latch with Write Enable command.
167  * Returns negative if error occurred.
168  */
169 static inline int write_enable(struct spi_nor *nor)
170 {
171         return nor->write_reg(nor, SPINOR_OP_WREN, NULL, 0);
172 }
173
174 /*
175  * Send write disable instruction to the chip.
176  */
177 static inline int write_disable(struct spi_nor *nor)
178 {
179         return nor->write_reg(nor, SPINOR_OP_WRDI, NULL, 0);
180 }
181
182 static inline struct spi_nor *mtd_to_spi_nor(struct mtd_info *mtd)
183 {
184         return mtd->priv;
185 }
186
187
188 static u8 spi_nor_convert_opcode(u8 opcode, const u8 table[][2], size_t size)
189 {
190         size_t i;
191
192         for (i = 0; i < size; i++)
193                 if (table[i][0] == opcode)
194                         return table[i][1];
195
196         /* No conversion found, keep input op code. */
197         return opcode;
198 }
199
200 static inline u8 spi_nor_convert_3to4_read(u8 opcode)
201 {
202         static const u8 spi_nor_3to4_read[][2] = {
203                 { SPINOR_OP_READ,       SPINOR_OP_READ_4B },
204                 { SPINOR_OP_READ_FAST,  SPINOR_OP_READ_FAST_4B },
205                 { SPINOR_OP_READ_1_1_2, SPINOR_OP_READ_1_1_2_4B },
206                 { SPINOR_OP_READ_1_2_2, SPINOR_OP_READ_1_2_2_4B },
207                 { SPINOR_OP_READ_1_1_4, SPINOR_OP_READ_1_1_4_4B },
208                 { SPINOR_OP_READ_1_4_4, SPINOR_OP_READ_1_4_4_4B },
209
210                 { SPINOR_OP_READ_1_1_1_DTR,     SPINOR_OP_READ_1_1_1_DTR_4B },
211                 { SPINOR_OP_READ_1_2_2_DTR,     SPINOR_OP_READ_1_2_2_DTR_4B },
212                 { SPINOR_OP_READ_1_4_4_DTR,     SPINOR_OP_READ_1_4_4_DTR_4B },
213         };
214
215         return spi_nor_convert_opcode(opcode, spi_nor_3to4_read,
216                                       ARRAY_SIZE(spi_nor_3to4_read));
217 }
218
219 static inline u8 spi_nor_convert_3to4_program(u8 opcode)
220 {
221         static const u8 spi_nor_3to4_program[][2] = {
222                 { SPINOR_OP_PP,         SPINOR_OP_PP_4B },
223                 { SPINOR_OP_PP_1_1_4,   SPINOR_OP_PP_1_1_4_4B },
224                 { SPINOR_OP_PP_1_4_4,   SPINOR_OP_PP_1_4_4_4B },
225         };
226
227         return spi_nor_convert_opcode(opcode, spi_nor_3to4_program,
228                                       ARRAY_SIZE(spi_nor_3to4_program));
229 }
230
231 static inline u8 spi_nor_convert_3to4_erase(u8 opcode)
232 {
233         static const u8 spi_nor_3to4_erase[][2] = {
234                 { SPINOR_OP_BE_4K,      SPINOR_OP_BE_4K_4B },
235                 { SPINOR_OP_BE_32K,     SPINOR_OP_BE_32K_4B },
236                 { SPINOR_OP_SE,         SPINOR_OP_SE_4B },
237         };
238
239         return spi_nor_convert_opcode(opcode, spi_nor_3to4_erase,
240                                       ARRAY_SIZE(spi_nor_3to4_erase));
241 }
242
243 static void spi_nor_set_4byte_opcodes(struct spi_nor *nor,
244                                       const struct flash_info *info)
245 {
246         /* Do some manufacturer fixups first */
247         switch (JEDEC_MFR(info)) {
248         case SNOR_MFR_SPANSION:
249                 /* No small sector erase for 4-byte command set */
250                 nor->erase_opcode = SPINOR_OP_SE;
251                 nor->mtd.erasesize = info->sector_size;
252                 break;
253
254         default:
255                 break;
256         }
257
258         nor->read_opcode = spi_nor_convert_3to4_read(nor->read_opcode);
259         nor->program_opcode = spi_nor_convert_3to4_program(nor->program_opcode);
260         nor->erase_opcode = spi_nor_convert_3to4_erase(nor->erase_opcode);
261 }
262
263 /* Enable/disable 4-byte addressing mode. */
264 static inline int set_4byte(struct spi_nor *nor, const struct flash_info *info,
265                             int enable)
266 {
267         int status;
268         bool need_wren = false;
269         u8 cmd;
270
271         switch (JEDEC_MFR(info)) {
272         case SNOR_MFR_MICRON:
273                 /* Some Micron need WREN command; all will accept it */
274                 need_wren = true;
275         case SNOR_MFR_MACRONIX:
276         case SNOR_MFR_WINBOND:
277                 if (need_wren)
278                         write_enable(nor);
279
280                 cmd = enable ? SPINOR_OP_EN4B : SPINOR_OP_EX4B;
281                 status = nor->write_reg(nor, cmd, NULL, 0);
282                 if (need_wren)
283                         write_disable(nor);
284
285                 return status;
286         default:
287                 /* Spansion style */
288                 nor->cmd_buf[0] = enable << 7;
289                 return nor->write_reg(nor, SPINOR_OP_BRWR, nor->cmd_buf, 1);
290         }
291 }
292
293 static int s3an_sr_ready(struct spi_nor *nor)
294 {
295         int ret;
296         u8 val;
297
298         ret = nor->read_reg(nor, SPINOR_OP_XRDSR, &val, 1);
299         if (ret < 0) {
300                 dev_err(nor->dev, "error %d reading XRDSR\n", (int) ret);
301                 return ret;
302         }
303
304         return !!(val & XSR_RDY);
305 }
306
307 static inline int spi_nor_sr_ready(struct spi_nor *nor)
308 {
309         int sr = read_sr(nor);
310         if (sr < 0)
311                 return sr;
312
313         if (nor->flags & SNOR_F_USE_CLSR && sr & (SR_E_ERR | SR_P_ERR)) {
314                 if (sr & SR_E_ERR)
315                         dev_err(nor->dev, "Erase Error occurred\n");
316                 else
317                         dev_err(nor->dev, "Programming Error occurred\n");
318
319                 nor->write_reg(nor, SPINOR_OP_CLSR, NULL, 0);
320                 return -EIO;
321         }
322
323         return !(sr & SR_WIP);
324 }
325
326 static inline int spi_nor_fsr_ready(struct spi_nor *nor)
327 {
328         int fsr = read_fsr(nor);
329         if (fsr < 0)
330                 return fsr;
331         else
332                 return fsr & FSR_READY;
333 }
334
335 static int spi_nor_ready(struct spi_nor *nor)
336 {
337         int sr, fsr;
338
339         if (nor->flags & SNOR_F_READY_XSR_RDY)
340                 sr = s3an_sr_ready(nor);
341         else
342                 sr = spi_nor_sr_ready(nor);
343         if (sr < 0)
344                 return sr;
345         fsr = nor->flags & SNOR_F_USE_FSR ? spi_nor_fsr_ready(nor) : 1;
346         if (fsr < 0)
347                 return fsr;
348         return sr && fsr;
349 }
350
351 /*
352  * Service routine to read status register until ready, or timeout occurs.
353  * Returns non-zero if error.
354  */
355 static int spi_nor_wait_till_ready_with_timeout(struct spi_nor *nor,
356                                                 unsigned long timeout_jiffies)
357 {
358         unsigned long deadline;
359         int timeout = 0, ret;
360
361         deadline = jiffies + timeout_jiffies;
362
363         while (!timeout) {
364                 if (time_after_eq(jiffies, deadline))
365                         timeout = 1;
366
367                 ret = spi_nor_ready(nor);
368                 if (ret < 0)
369                         return ret;
370                 if (ret)
371                         return 0;
372
373                 cond_resched();
374         }
375
376         dev_err(nor->dev, "flash operation timed out\n");
377
378         return -ETIMEDOUT;
379 }
380
381 static int spi_nor_wait_till_ready(struct spi_nor *nor)
382 {
383         return spi_nor_wait_till_ready_with_timeout(nor,
384                                                     DEFAULT_READY_WAIT_JIFFIES);
385 }
386
387 /*
388  * Erase the whole flash memory
389  *
390  * Returns 0 if successful, non-zero otherwise.
391  */
392 static int erase_chip(struct spi_nor *nor)
393 {
394         dev_dbg(nor->dev, " %lldKiB\n", (long long)(nor->mtd.size >> 10));
395
396         return nor->write_reg(nor, SPINOR_OP_CHIP_ERASE, NULL, 0);
397 }
398
399 static int spi_nor_lock_and_prep(struct spi_nor *nor, enum spi_nor_ops ops)
400 {
401         int ret = 0;
402
403         mutex_lock(&nor->lock);
404
405         if (nor->prepare) {
406                 ret = nor->prepare(nor, ops);
407                 if (ret) {
408                         dev_err(nor->dev, "failed in the preparation.\n");
409                         mutex_unlock(&nor->lock);
410                         return ret;
411                 }
412         }
413         return ret;
414 }
415
416 static void spi_nor_unlock_and_unprep(struct spi_nor *nor, enum spi_nor_ops ops)
417 {
418         if (nor->unprepare)
419                 nor->unprepare(nor, ops);
420         mutex_unlock(&nor->lock);
421 }
422
423 /*
424  * This code converts an address to the Default Address Mode, that has non
425  * power of two page sizes. We must support this mode because it is the default
426  * mode supported by Xilinx tools, it can access the whole flash area and
427  * changing over to the Power-of-two mode is irreversible and corrupts the
428  * original data.
429  * Addr can safely be unsigned int, the biggest S3AN device is smaller than
430  * 4 MiB.
431  */
432 static loff_t spi_nor_s3an_addr_convert(struct spi_nor *nor, unsigned int addr)
433 {
434         unsigned int offset;
435         unsigned int page;
436
437         offset = addr % nor->page_size;
438         page = addr / nor->page_size;
439         page <<= (nor->page_size > 512) ? 10 : 9;
440
441         return page | offset;
442 }
443
444 /*
445  * Initiate the erasure of a single sector
446  */
447 static int spi_nor_erase_sector(struct spi_nor *nor, u32 addr)
448 {
449         u8 buf[SPI_NOR_MAX_ADDR_WIDTH];
450         int i;
451
452         if (nor->flags & SNOR_F_S3AN_ADDR_DEFAULT)
453                 addr = spi_nor_s3an_addr_convert(nor, addr);
454
455         if (nor->erase)
456                 return nor->erase(nor, addr);
457
458         /*
459          * Default implementation, if driver doesn't have a specialized HW
460          * control
461          */
462         for (i = nor->addr_width - 1; i >= 0; i--) {
463                 buf[i] = addr & 0xff;
464                 addr >>= 8;
465         }
466
467         return nor->write_reg(nor, nor->erase_opcode, buf, nor->addr_width);
468 }
469
470 /*
471  * Erase an address range on the nor chip.  The address range may extend
472  * one or more erase sectors.  Return an error is there is a problem erasing.
473  */
474 static int spi_nor_erase(struct mtd_info *mtd, struct erase_info *instr)
475 {
476         struct spi_nor *nor = mtd_to_spi_nor(mtd);
477         u32 addr, len;
478         uint32_t rem;
479         int ret;
480
481         dev_dbg(nor->dev, "at 0x%llx, len %lld\n", (long long)instr->addr,
482                         (long long)instr->len);
483
484         div_u64_rem(instr->len, mtd->erasesize, &rem);
485         if (rem)
486                 return -EINVAL;
487
488         addr = instr->addr;
489         len = instr->len;
490
491         ret = spi_nor_lock_and_prep(nor, SPI_NOR_OPS_ERASE);
492         if (ret)
493                 return ret;
494
495         /* whole-chip erase? */
496         if (len == mtd->size && !(nor->flags & SNOR_F_NO_OP_CHIP_ERASE)) {
497                 unsigned long timeout;
498
499                 write_enable(nor);
500
501                 if (erase_chip(nor)) {
502                         ret = -EIO;
503                         goto erase_err;
504                 }
505
506                 /*
507                  * Scale the timeout linearly with the size of the flash, with
508                  * a minimum calibrated to an old 2MB flash. We could try to
509                  * pull these from CFI/SFDP, but these values should be good
510                  * enough for now.
511                  */
512                 timeout = max(CHIP_ERASE_2MB_READY_WAIT_JIFFIES,
513                               CHIP_ERASE_2MB_READY_WAIT_JIFFIES *
514                               (unsigned long)(mtd->size / SZ_2M));
515                 ret = spi_nor_wait_till_ready_with_timeout(nor, timeout);
516                 if (ret)
517                         goto erase_err;
518
519         /* REVISIT in some cases we could speed up erasing large regions
520          * by using SPINOR_OP_SE instead of SPINOR_OP_BE_4K.  We may have set up
521          * to use "small sector erase", but that's not always optimal.
522          */
523
524         /* "sector"-at-a-time erase */
525         } else {
526                 while (len) {
527                         write_enable(nor);
528
529                         ret = spi_nor_erase_sector(nor, addr);
530                         if (ret)
531                                 goto erase_err;
532
533                         addr += mtd->erasesize;
534                         len -= mtd->erasesize;
535
536                         ret = spi_nor_wait_till_ready(nor);
537                         if (ret)
538                                 goto erase_err;
539                 }
540         }
541
542         write_disable(nor);
543
544 erase_err:
545         spi_nor_unlock_and_unprep(nor, SPI_NOR_OPS_ERASE);
546
547         instr->state = ret ? MTD_ERASE_FAILED : MTD_ERASE_DONE;
548         mtd_erase_callback(instr);
549
550         return ret;
551 }
552
553 static void stm_get_locked_range(struct spi_nor *nor, u8 sr, loff_t *ofs,
554                                  uint64_t *len)
555 {
556         struct mtd_info *mtd = &nor->mtd;
557         u8 mask = SR_BP2 | SR_BP1 | SR_BP0;
558         int shift = ffs(mask) - 1;
559         int pow;
560
561         if (!(sr & mask)) {
562                 /* No protection */
563                 *ofs = 0;
564                 *len = 0;
565         } else {
566                 pow = ((sr & mask) ^ mask) >> shift;
567                 *len = mtd->size >> pow;
568                 if (nor->flags & SNOR_F_HAS_SR_TB && sr & SR_TB)
569                         *ofs = 0;
570                 else
571                         *ofs = mtd->size - *len;
572         }
573 }
574
575 /*
576  * Return 1 if the entire region is locked (if @locked is true) or unlocked (if
577  * @locked is false); 0 otherwise
578  */
579 static int stm_check_lock_status_sr(struct spi_nor *nor, loff_t ofs, uint64_t len,
580                                     u8 sr, bool locked)
581 {
582         loff_t lock_offs;
583         uint64_t lock_len;
584
585         if (!len)
586                 return 1;
587
588         stm_get_locked_range(nor, sr, &lock_offs, &lock_len);
589
590         if (locked)
591                 /* Requested range is a sub-range of locked range */
592                 return (ofs + len <= lock_offs + lock_len) && (ofs >= lock_offs);
593         else
594                 /* Requested range does not overlap with locked range */
595                 return (ofs >= lock_offs + lock_len) || (ofs + len <= lock_offs);
596 }
597
598 static int stm_is_locked_sr(struct spi_nor *nor, loff_t ofs, uint64_t len,
599                             u8 sr)
600 {
601         return stm_check_lock_status_sr(nor, ofs, len, sr, true);
602 }
603
604 static int stm_is_unlocked_sr(struct spi_nor *nor, loff_t ofs, uint64_t len,
605                               u8 sr)
606 {
607         return stm_check_lock_status_sr(nor, ofs, len, sr, false);
608 }
609
610 /*
611  * Lock a region of the flash. Compatible with ST Micro and similar flash.
612  * Supports the block protection bits BP{0,1,2} in the status register
613  * (SR). Does not support these features found in newer SR bitfields:
614  *   - SEC: sector/block protect - only handle SEC=0 (block protect)
615  *   - CMP: complement protect - only support CMP=0 (range is not complemented)
616  *
617  * Support for the following is provided conditionally for some flash:
618  *   - TB: top/bottom protect
619  *
620  * Sample table portion for 8MB flash (Winbond w25q64fw):
621  *
622  *   SEC  |  TB   |  BP2  |  BP1  |  BP0  |  Prot Length  | Protected Portion
623  *  --------------------------------------------------------------------------
624  *    X   |   X   |   0   |   0   |   0   |  NONE         | NONE
625  *    0   |   0   |   0   |   0   |   1   |  128 KB       | Upper 1/64
626  *    0   |   0   |   0   |   1   |   0   |  256 KB       | Upper 1/32
627  *    0   |   0   |   0   |   1   |   1   |  512 KB       | Upper 1/16
628  *    0   |   0   |   1   |   0   |   0   |  1 MB         | Upper 1/8
629  *    0   |   0   |   1   |   0   |   1   |  2 MB         | Upper 1/4
630  *    0   |   0   |   1   |   1   |   0   |  4 MB         | Upper 1/2
631  *    X   |   X   |   1   |   1   |   1   |  8 MB         | ALL
632  *  ------|-------|-------|-------|-------|---------------|-------------------
633  *    0   |   1   |   0   |   0   |   1   |  128 KB       | Lower 1/64
634  *    0   |   1   |   0   |   1   |   0   |  256 KB       | Lower 1/32
635  *    0   |   1   |   0   |   1   |   1   |  512 KB       | Lower 1/16
636  *    0   |   1   |   1   |   0   |   0   |  1 MB         | Lower 1/8
637  *    0   |   1   |   1   |   0   |   1   |  2 MB         | Lower 1/4
638  *    0   |   1   |   1   |   1   |   0   |  4 MB         | Lower 1/2
639  *
640  * Returns negative on errors, 0 on success.
641  */
642 static int stm_lock(struct spi_nor *nor, loff_t ofs, uint64_t len)
643 {
644         struct mtd_info *mtd = &nor->mtd;
645         int status_old, status_new;
646         u8 mask = SR_BP2 | SR_BP1 | SR_BP0;
647         u8 shift = ffs(mask) - 1, pow, val;
648         loff_t lock_len;
649         bool can_be_top = true, can_be_bottom = nor->flags & SNOR_F_HAS_SR_TB;
650         bool use_top;
651         int ret;
652
653         status_old = read_sr(nor);
654         if (status_old < 0)
655                 return status_old;
656
657         /* If nothing in our range is unlocked, we don't need to do anything */
658         if (stm_is_locked_sr(nor, ofs, len, status_old))
659                 return 0;
660
661         /* If anything below us is unlocked, we can't use 'bottom' protection */
662         if (!stm_is_locked_sr(nor, 0, ofs, status_old))
663                 can_be_bottom = false;
664
665         /* If anything above us is unlocked, we can't use 'top' protection */
666         if (!stm_is_locked_sr(nor, ofs + len, mtd->size - (ofs + len),
667                                 status_old))
668                 can_be_top = false;
669
670         if (!can_be_bottom && !can_be_top)
671                 return -EINVAL;
672
673         /* Prefer top, if both are valid */
674         use_top = can_be_top;
675
676         /* lock_len: length of region that should end up locked */
677         if (use_top)
678                 lock_len = mtd->size - ofs;
679         else
680                 lock_len = ofs + len;
681
682         /*
683          * Need smallest pow such that:
684          *
685          *   1 / (2^pow) <= (len / size)
686          *
687          * so (assuming power-of-2 size) we do:
688          *
689          *   pow = ceil(log2(size / len)) = log2(size) - floor(log2(len))
690          */
691         pow = ilog2(mtd->size) - ilog2(lock_len);
692         val = mask - (pow << shift);
693         if (val & ~mask)
694                 return -EINVAL;
695         /* Don't "lock" with no region! */
696         if (!(val & mask))
697                 return -EINVAL;
698
699         status_new = (status_old & ~mask & ~SR_TB) | val;
700
701         /* Disallow further writes if WP pin is asserted */
702         status_new |= SR_SRWD;
703
704         if (!use_top)
705                 status_new |= SR_TB;
706
707         /* Don't bother if they're the same */
708         if (status_new == status_old)
709                 return 0;
710
711         /* Only modify protection if it will not unlock other areas */
712         if ((status_new & mask) < (status_old & mask))
713                 return -EINVAL;
714
715         write_enable(nor);
716         ret = write_sr(nor, status_new);
717         if (ret)
718                 return ret;
719         return spi_nor_wait_till_ready(nor);
720 }
721
722 /*
723  * Unlock a region of the flash. See stm_lock() for more info
724  *
725  * Returns negative on errors, 0 on success.
726  */
727 static int stm_unlock(struct spi_nor *nor, loff_t ofs, uint64_t len)
728 {
729         struct mtd_info *mtd = &nor->mtd;
730         int status_old, status_new;
731         u8 mask = SR_BP2 | SR_BP1 | SR_BP0;
732         u8 shift = ffs(mask) - 1, pow, val;
733         loff_t lock_len;
734         bool can_be_top = true, can_be_bottom = nor->flags & SNOR_F_HAS_SR_TB;
735         bool use_top;
736         int ret;
737
738         status_old = read_sr(nor);
739         if (status_old < 0)
740                 return status_old;
741
742         /* If nothing in our range is locked, we don't need to do anything */
743         if (stm_is_unlocked_sr(nor, ofs, len, status_old))
744                 return 0;
745
746         /* If anything below us is locked, we can't use 'top' protection */
747         if (!stm_is_unlocked_sr(nor, 0, ofs, status_old))
748                 can_be_top = false;
749
750         /* If anything above us is locked, we can't use 'bottom' protection */
751         if (!stm_is_unlocked_sr(nor, ofs + len, mtd->size - (ofs + len),
752                                 status_old))
753                 can_be_bottom = false;
754
755         if (!can_be_bottom && !can_be_top)
756                 return -EINVAL;
757
758         /* Prefer top, if both are valid */
759         use_top = can_be_top;
760
761         /* lock_len: length of region that should remain locked */
762         if (use_top)
763                 lock_len = mtd->size - (ofs + len);
764         else
765                 lock_len = ofs;
766
767         /*
768          * Need largest pow such that:
769          *
770          *   1 / (2^pow) >= (len / size)
771          *
772          * so (assuming power-of-2 size) we do:
773          *
774          *   pow = floor(log2(size / len)) = log2(size) - ceil(log2(len))
775          */
776         pow = ilog2(mtd->size) - order_base_2(lock_len);
777         if (lock_len == 0) {
778                 val = 0; /* fully unlocked */
779         } else {
780                 val = mask - (pow << shift);
781                 /* Some power-of-two sizes are not supported */
782                 if (val & ~mask)
783                         return -EINVAL;
784         }
785
786         status_new = (status_old & ~mask & ~SR_TB) | val;
787
788         /* Don't protect status register if we're fully unlocked */
789         if (lock_len == 0)
790                 status_new &= ~SR_SRWD;
791
792         if (!use_top)
793                 status_new |= SR_TB;
794
795         /* Don't bother if they're the same */
796         if (status_new == status_old)
797                 return 0;
798
799         /* Only modify protection if it will not lock other areas */
800         if ((status_new & mask) > (status_old & mask))
801                 return -EINVAL;
802
803         write_enable(nor);
804         ret = write_sr(nor, status_new);
805         if (ret)
806                 return ret;
807         return spi_nor_wait_till_ready(nor);
808 }
809
810 /*
811  * Check if a region of the flash is (completely) locked. See stm_lock() for
812  * more info.
813  *
814  * Returns 1 if entire region is locked, 0 if any portion is unlocked, and
815  * negative on errors.
816  */
817 static int stm_is_locked(struct spi_nor *nor, loff_t ofs, uint64_t len)
818 {
819         int status;
820
821         status = read_sr(nor);
822         if (status < 0)
823                 return status;
824
825         return stm_is_locked_sr(nor, ofs, len, status);
826 }
827
828 static int spi_nor_lock(struct mtd_info *mtd, loff_t ofs, uint64_t len)
829 {
830         struct spi_nor *nor = mtd_to_spi_nor(mtd);
831         int ret;
832
833         ret = spi_nor_lock_and_prep(nor, SPI_NOR_OPS_LOCK);
834         if (ret)
835                 return ret;
836
837         ret = nor->flash_lock(nor, ofs, len);
838
839         spi_nor_unlock_and_unprep(nor, SPI_NOR_OPS_UNLOCK);
840         return ret;
841 }
842
843 static int spi_nor_unlock(struct mtd_info *mtd, loff_t ofs, uint64_t len)
844 {
845         struct spi_nor *nor = mtd_to_spi_nor(mtd);
846         int ret;
847
848         ret = spi_nor_lock_and_prep(nor, SPI_NOR_OPS_UNLOCK);
849         if (ret)
850                 return ret;
851
852         ret = nor->flash_unlock(nor, ofs, len);
853
854         spi_nor_unlock_and_unprep(nor, SPI_NOR_OPS_LOCK);
855         return ret;
856 }
857
858 static int spi_nor_is_locked(struct mtd_info *mtd, loff_t ofs, uint64_t len)
859 {
860         struct spi_nor *nor = mtd_to_spi_nor(mtd);
861         int ret;
862
863         ret = spi_nor_lock_and_prep(nor, SPI_NOR_OPS_UNLOCK);
864         if (ret)
865                 return ret;
866
867         ret = nor->flash_is_locked(nor, ofs, len);
868
869         spi_nor_unlock_and_unprep(nor, SPI_NOR_OPS_LOCK);
870         return ret;
871 }
872
873 /* Used when the "_ext_id" is two bytes at most */
874 #define INFO(_jedec_id, _ext_id, _sector_size, _n_sectors, _flags)      \
875                 .id = {                                                 \
876                         ((_jedec_id) >> 16) & 0xff,                     \
877                         ((_jedec_id) >> 8) & 0xff,                      \
878                         (_jedec_id) & 0xff,                             \
879                         ((_ext_id) >> 8) & 0xff,                        \
880                         (_ext_id) & 0xff,                               \
881                         },                                              \
882                 .id_len = (!(_jedec_id) ? 0 : (3 + ((_ext_id) ? 2 : 0))),       \
883                 .sector_size = (_sector_size),                          \
884                 .n_sectors = (_n_sectors),                              \
885                 .page_size = 256,                                       \
886                 .flags = (_flags),
887
888 #define INFO6(_jedec_id, _ext_id, _sector_size, _n_sectors, _flags)     \
889                 .id = {                                                 \
890                         ((_jedec_id) >> 16) & 0xff,                     \
891                         ((_jedec_id) >> 8) & 0xff,                      \
892                         (_jedec_id) & 0xff,                             \
893                         ((_ext_id) >> 16) & 0xff,                       \
894                         ((_ext_id) >> 8) & 0xff,                        \
895                         (_ext_id) & 0xff,                               \
896                         },                                              \
897                 .id_len = 6,                                            \
898                 .sector_size = (_sector_size),                          \
899                 .n_sectors = (_n_sectors),                              \
900                 .page_size = 256,                                       \
901                 .flags = (_flags),
902
903 #define CAT25_INFO(_sector_size, _n_sectors, _page_size, _addr_width, _flags)   \
904                 .sector_size = (_sector_size),                          \
905                 .n_sectors = (_n_sectors),                              \
906                 .page_size = (_page_size),                              \
907                 .addr_width = (_addr_width),                            \
908                 .flags = (_flags),
909
910 #define S3AN_INFO(_jedec_id, _n_sectors, _page_size)                    \
911                 .id = {                                                 \
912                         ((_jedec_id) >> 16) & 0xff,                     \
913                         ((_jedec_id) >> 8) & 0xff,                      \
914                         (_jedec_id) & 0xff                              \
915                         },                                              \
916                 .id_len = 3,                                            \
917                 .sector_size = (8*_page_size),                          \
918                 .n_sectors = (_n_sectors),                              \
919                 .page_size = _page_size,                                \
920                 .addr_width = 3,                                        \
921                 .flags = SPI_NOR_NO_FR | SPI_S3AN,
922
923 /* NOTE: double check command sets and memory organization when you add
924  * more nor chips.  This current list focusses on newer chips, which
925  * have been converging on command sets which including JEDEC ID.
926  *
927  * All newly added entries should describe *hardware* and should use SECT_4K
928  * (or SECT_4K_PMC) if hardware supports erasing 4 KiB sectors. For usage
929  * scenarios excluding small sectors there is config option that can be
930  * disabled: CONFIG_MTD_SPI_NOR_USE_4K_SECTORS.
931  * For historical (and compatibility) reasons (before we got above config) some
932  * old entries may be missing 4K flag.
933  */
934 static const struct flash_info spi_nor_ids[] = {
935         /* Atmel -- some are (confusingly) marketed as "DataFlash" */
936         { "at25fs010",  INFO(0x1f6601, 0, 32 * 1024,   4, SECT_4K) },
937         { "at25fs040",  INFO(0x1f6604, 0, 64 * 1024,   8, SECT_4K) },
938
939         { "at25df041a", INFO(0x1f4401, 0, 64 * 1024,   8, SECT_4K) },
940         { "at25df321",  INFO(0x1f4700, 0, 64 * 1024,  64, SECT_4K) },
941         { "at25df321a", INFO(0x1f4701, 0, 64 * 1024,  64, SECT_4K) },
942         { "at25df641",  INFO(0x1f4800, 0, 64 * 1024, 128, SECT_4K) },
943
944         { "at26f004",   INFO(0x1f0400, 0, 64 * 1024,  8, SECT_4K) },
945         { "at26df081a", INFO(0x1f4501, 0, 64 * 1024, 16, SECT_4K) },
946         { "at26df161a", INFO(0x1f4601, 0, 64 * 1024, 32, SECT_4K) },
947         { "at26df321",  INFO(0x1f4700, 0, 64 * 1024, 64, SECT_4K) },
948
949         { "at45db081d", INFO(0x1f2500, 0, 64 * 1024, 16, SECT_4K) },
950
951         /* EON -- en25xxx */
952         { "en25f32",    INFO(0x1c3116, 0, 64 * 1024,   64, SECT_4K) },
953         { "en25p32",    INFO(0x1c2016, 0, 64 * 1024,   64, 0) },
954         { "en25q32b",   INFO(0x1c3016, 0, 64 * 1024,   64, 0) },
955         { "en25p64",    INFO(0x1c2017, 0, 64 * 1024,  128, 0) },
956         { "en25q64",    INFO(0x1c3017, 0, 64 * 1024,  128, SECT_4K) },
957         { "en25qh128",  INFO(0x1c7018, 0, 64 * 1024,  256, 0) },
958         { "en25qh256",  INFO(0x1c7019, 0, 64 * 1024,  512, 0) },
959         { "en25s64",    INFO(0x1c3817, 0, 64 * 1024,  128, SECT_4K) },
960
961         /* ESMT */
962         { "f25l32pa", INFO(0x8c2016, 0, 64 * 1024, 64, SECT_4K | SPI_NOR_HAS_LOCK) },
963         { "f25l32qa", INFO(0x8c4116, 0, 64 * 1024, 64, SECT_4K | SPI_NOR_HAS_LOCK) },
964         { "f25l64qa", INFO(0x8c4117, 0, 64 * 1024, 128, SECT_4K | SPI_NOR_HAS_LOCK) },
965
966         /* Everspin */
967         { "mr25h256", CAT25_INFO( 32 * 1024, 1, 256, 2, SPI_NOR_NO_ERASE | SPI_NOR_NO_FR) },
968         { "mr25h10",  CAT25_INFO(128 * 1024, 1, 256, 3, SPI_NOR_NO_ERASE | SPI_NOR_NO_FR) },
969         { "mr25h40",  CAT25_INFO(512 * 1024, 1, 256, 3, SPI_NOR_NO_ERASE | SPI_NOR_NO_FR) },
970
971         /* Fujitsu */
972         { "mb85rs1mt", INFO(0x047f27, 0, 128 * 1024, 1, SPI_NOR_NO_ERASE) },
973
974         /* GigaDevice */
975         {
976                 "gd25q16", INFO(0xc84015, 0, 64 * 1024,  32,
977                         SECT_4K | SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ |
978                         SPI_NOR_HAS_LOCK | SPI_NOR_HAS_TB)
979         },
980         {
981                 "gd25q32", INFO(0xc84016, 0, 64 * 1024,  64,
982                         SECT_4K | SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ |
983                         SPI_NOR_HAS_LOCK | SPI_NOR_HAS_TB)
984         },
985         {
986                 "gd25q64", INFO(0xc84017, 0, 64 * 1024, 128,
987                         SECT_4K | SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ |
988                         SPI_NOR_HAS_LOCK | SPI_NOR_HAS_TB)
989         },
990         {
991                 "gd25lq64c", INFO(0xc86017, 0, 64 * 1024, 128,
992                         SECT_4K | SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ |
993                         SPI_NOR_HAS_LOCK | SPI_NOR_HAS_TB)
994         },
995         {
996                 "gd25q128", INFO(0xc84018, 0, 64 * 1024, 256,
997                         SECT_4K | SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ |
998                         SPI_NOR_HAS_LOCK | SPI_NOR_HAS_TB)
999         },
1000
1001         /* Intel/Numonyx -- xxxs33b */
1002         { "160s33b",  INFO(0x898911, 0, 64 * 1024,  32, 0) },
1003         { "320s33b",  INFO(0x898912, 0, 64 * 1024,  64, 0) },
1004         { "640s33b",  INFO(0x898913, 0, 64 * 1024, 128, 0) },
1005
1006         /* ISSI */
1007         { "is25cd512", INFO(0x7f9d20, 0, 32 * 1024,   2, SECT_4K) },
1008         { "is25wp032", INFO(0x9d7016, 0, 64 * 1024,  64,
1009                         SECT_4K | SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ) },
1010         { "is25wp064", INFO(0x9d7017, 0, 64 * 1024, 128,
1011                         SECT_4K | SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ) },
1012         { "is25wp128", INFO(0x9d7018, 0, 64 * 1024, 256,
1013                         SECT_4K | SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ) },
1014
1015         /* Macronix */
1016         { "mx25l512e",   INFO(0xc22010, 0, 64 * 1024,   1, SECT_4K) },
1017         { "mx25l2005a",  INFO(0xc22012, 0, 64 * 1024,   4, SECT_4K) },
1018         { "mx25l4005a",  INFO(0xc22013, 0, 64 * 1024,   8, SECT_4K) },
1019         { "mx25l8005",   INFO(0xc22014, 0, 64 * 1024,  16, 0) },
1020         { "mx25l1606e",  INFO(0xc22015, 0, 64 * 1024,  32, SECT_4K) },
1021         { "mx25l3205d",  INFO(0xc22016, 0, 64 * 1024,  64, SECT_4K) },
1022         { "mx25l3255e",  INFO(0xc29e16, 0, 64 * 1024,  64, SECT_4K) },
1023         { "mx25l6405d",  INFO(0xc22017, 0, 64 * 1024, 128, SECT_4K) },
1024         { "mx25u2033e",  INFO(0xc22532, 0, 64 * 1024,   4, SECT_4K) },
1025         { "mx25u4035",   INFO(0xc22533, 0, 64 * 1024,   8, SECT_4K) },
1026         { "mx25u8035",   INFO(0xc22534, 0, 64 * 1024,  16, SECT_4K) },
1027         { "mx25u6435f",  INFO(0xc22537, 0, 64 * 1024, 128, SECT_4K) },
1028         { "mx25l12805d", INFO(0xc22018, 0, 64 * 1024, 256, 0) },
1029         { "mx25l12855e", INFO(0xc22618, 0, 64 * 1024, 256, 0) },
1030         { "mx25l25635e", INFO(0xc22019, 0, 64 * 1024, 512, SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ) },
1031         { "mx25u25635f", INFO(0xc22539, 0, 64 * 1024, 512, SECT_4K | SPI_NOR_4B_OPCODES) },
1032         { "mx25l25655e", INFO(0xc22619, 0, 64 * 1024, 512, 0) },
1033         { "mx66l51235l", INFO(0xc2201a, 0, 64 * 1024, 1024, SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ | SPI_NOR_4B_OPCODES) },
1034         { "mx66u51235f", INFO(0xc2253a, 0, 64 * 1024, 1024, SECT_4K | SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ | SPI_NOR_4B_OPCODES) },
1035         { "mx66l1g45g",  INFO(0xc2201b, 0, 64 * 1024, 2048, SECT_4K | SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ) },
1036         { "mx66l1g55g",  INFO(0xc2261b, 0, 64 * 1024, 2048, SPI_NOR_QUAD_READ) },
1037
1038         /* Micron */
1039         { "n25q016a",    INFO(0x20bb15, 0, 64 * 1024,   32, SECT_4K | SPI_NOR_QUAD_READ) },
1040         { "n25q032",     INFO(0x20ba16, 0, 64 * 1024,   64, SPI_NOR_QUAD_READ) },
1041         { "n25q032a",    INFO(0x20bb16, 0, 64 * 1024,   64, SPI_NOR_QUAD_READ) },
1042         { "n25q064",     INFO(0x20ba17, 0, 64 * 1024,  128, SECT_4K | SPI_NOR_QUAD_READ) },
1043         { "n25q064a",    INFO(0x20bb17, 0, 64 * 1024,  128, SECT_4K | SPI_NOR_QUAD_READ) },
1044         { "n25q128a11",  INFO(0x20bb18, 0, 64 * 1024,  256, SECT_4K | SPI_NOR_QUAD_READ) },
1045         { "n25q128a13",  INFO(0x20ba18, 0, 64 * 1024,  256, SECT_4K | SPI_NOR_QUAD_READ) },
1046         { "n25q256a",    INFO(0x20ba19, 0, 64 * 1024,  512, SECT_4K | SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ) },
1047         { "n25q256ax1",  INFO(0x20bb19, 0, 64 * 1024,  512, SECT_4K | SPI_NOR_QUAD_READ) },
1048         { "n25q512a",    INFO(0x20bb20, 0, 64 * 1024, 1024, SECT_4K | USE_FSR | SPI_NOR_QUAD_READ) },
1049         { "n25q512ax3",  INFO(0x20ba20, 0, 64 * 1024, 1024, SECT_4K | USE_FSR | SPI_NOR_QUAD_READ) },
1050         { "n25q00",      INFO(0x20ba21, 0, 64 * 1024, 2048, SECT_4K | USE_FSR | SPI_NOR_QUAD_READ | NO_CHIP_ERASE) },
1051         { "n25q00a",     INFO(0x20bb21, 0, 64 * 1024, 2048, SECT_4K | USE_FSR | SPI_NOR_QUAD_READ | NO_CHIP_ERASE) },
1052
1053         /* PMC */
1054         { "pm25lv512",   INFO(0,        0, 32 * 1024,    2, SECT_4K_PMC) },
1055         { "pm25lv010",   INFO(0,        0, 32 * 1024,    4, SECT_4K_PMC) },
1056         { "pm25lq032",   INFO(0x7f9d46, 0, 64 * 1024,   64, SECT_4K) },
1057
1058         /* Spansion -- single (large) sector size only, at least
1059          * for the chips listed here (without boot sectors).
1060          */
1061         { "s25sl032p",  INFO(0x010215, 0x4d00,  64 * 1024,  64, SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ) },
1062         { "s25sl064p",  INFO(0x010216, 0x4d00,  64 * 1024, 128, SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ) },
1063         { "s25fl256s0", INFO(0x010219, 0x4d00, 256 * 1024, 128, USE_CLSR) },
1064         { "s25fl256s1", INFO(0x010219, 0x4d01,  64 * 1024, 512, SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ | USE_CLSR) },
1065         { "s25fl512s",  INFO(0x010220, 0x4d00, 256 * 1024, 256, SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ | USE_CLSR) },
1066         { "s70fl01gs",  INFO(0x010221, 0x4d00, 256 * 1024, 256, 0) },
1067         { "s25sl12800", INFO(0x012018, 0x0300, 256 * 1024,  64, 0) },
1068         { "s25sl12801", INFO(0x012018, 0x0301,  64 * 1024, 256, 0) },
1069         { "s25fl128s",  INFO6(0x012018, 0x4d0180, 64 * 1024, 256, SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ | USE_CLSR) },
1070         { "s25fl129p0", INFO(0x012018, 0x4d00, 256 * 1024,  64, SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ | USE_CLSR) },
1071         { "s25fl129p1", INFO(0x012018, 0x4d01,  64 * 1024, 256, SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ | USE_CLSR) },
1072         { "s25sl004a",  INFO(0x010212,      0,  64 * 1024,   8, 0) },
1073         { "s25sl008a",  INFO(0x010213,      0,  64 * 1024,  16, 0) },
1074         { "s25sl016a",  INFO(0x010214,      0,  64 * 1024,  32, 0) },
1075         { "s25sl032a",  INFO(0x010215,      0,  64 * 1024,  64, 0) },
1076         { "s25sl064a",  INFO(0x010216,      0,  64 * 1024, 128, 0) },
1077         { "s25fl004k",  INFO(0xef4013,      0,  64 * 1024,   8, SECT_4K | SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ) },
1078         { "s25fl008k",  INFO(0xef4014,      0,  64 * 1024,  16, SECT_4K | SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ) },
1079         { "s25fl016k",  INFO(0xef4015,      0,  64 * 1024,  32, SECT_4K | SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ) },
1080         { "s25fl064k",  INFO(0xef4017,      0,  64 * 1024, 128, SECT_4K) },
1081         { "s25fl116k",  INFO(0x014015,      0,  64 * 1024,  32, SECT_4K | SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ) },
1082         { "s25fl132k",  INFO(0x014016,      0,  64 * 1024,  64, SECT_4K) },
1083         { "s25fl164k",  INFO(0x014017,      0,  64 * 1024, 128, SECT_4K) },
1084         { "s25fl204k",  INFO(0x014013,      0,  64 * 1024,   8, SECT_4K | SPI_NOR_DUAL_READ) },
1085         { "s25fl208k",  INFO(0x014014,      0,  64 * 1024,  16, SECT_4K | SPI_NOR_DUAL_READ) },
1086         { "s25fl064l",  INFO(0x016017,      0,  64 * 1024, 128, SECT_4K | SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ | SPI_NOR_4B_OPCODES) },
1087
1088         /* SST -- large erase sizes are "overlays", "sectors" are 4K */
1089         { "sst25vf040b", INFO(0xbf258d, 0, 64 * 1024,  8, SECT_4K | SST_WRITE) },
1090         { "sst25vf080b", INFO(0xbf258e, 0, 64 * 1024, 16, SECT_4K | SST_WRITE) },
1091         { "sst25vf016b", INFO(0xbf2541, 0, 64 * 1024, 32, SECT_4K | SST_WRITE) },
1092         { "sst25vf032b", INFO(0xbf254a, 0, 64 * 1024, 64, SECT_4K | SST_WRITE) },
1093         { "sst25vf064c", INFO(0xbf254b, 0, 64 * 1024, 128, SECT_4K) },
1094         { "sst25wf512",  INFO(0xbf2501, 0, 64 * 1024,  1, SECT_4K | SST_WRITE) },
1095         { "sst25wf010",  INFO(0xbf2502, 0, 64 * 1024,  2, SECT_4K | SST_WRITE) },
1096         { "sst25wf020",  INFO(0xbf2503, 0, 64 * 1024,  4, SECT_4K | SST_WRITE) },
1097         { "sst25wf020a", INFO(0x621612, 0, 64 * 1024,  4, SECT_4K) },
1098         { "sst25wf040b", INFO(0x621613, 0, 64 * 1024,  8, SECT_4K) },
1099         { "sst25wf040",  INFO(0xbf2504, 0, 64 * 1024,  8, SECT_4K | SST_WRITE) },
1100         { "sst25wf080",  INFO(0xbf2505, 0, 64 * 1024, 16, SECT_4K | SST_WRITE) },
1101         { "sst26vf064b", INFO(0xbf2643, 0, 64 * 1024, 128, SECT_4K | SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ) },
1102
1103         /* ST Microelectronics -- newer production may have feature updates */
1104         { "m25p05",  INFO(0x202010,  0,  32 * 1024,   2, 0) },
1105         { "m25p10",  INFO(0x202011,  0,  32 * 1024,   4, 0) },
1106         { "m25p20",  INFO(0x202012,  0,  64 * 1024,   4, 0) },
1107         { "m25p40",  INFO(0x202013,  0,  64 * 1024,   8, 0) },
1108         { "m25p80",  INFO(0x202014,  0,  64 * 1024,  16, 0) },
1109         { "m25p16",  INFO(0x202015,  0,  64 * 1024,  32, 0) },
1110         { "m25p32",  INFO(0x202016,  0,  64 * 1024,  64, 0) },
1111         { "m25p64",  INFO(0x202017,  0,  64 * 1024, 128, 0) },
1112         { "m25p128", INFO(0x202018,  0, 256 * 1024,  64, 0) },
1113
1114         { "m25p05-nonjedec",  INFO(0, 0,  32 * 1024,   2, 0) },
1115         { "m25p10-nonjedec",  INFO(0, 0,  32 * 1024,   4, 0) },
1116         { "m25p20-nonjedec",  INFO(0, 0,  64 * 1024,   4, 0) },
1117         { "m25p40-nonjedec",  INFO(0, 0,  64 * 1024,   8, 0) },
1118         { "m25p80-nonjedec",  INFO(0, 0,  64 * 1024,  16, 0) },
1119         { "m25p16-nonjedec",  INFO(0, 0,  64 * 1024,  32, 0) },
1120         { "m25p32-nonjedec",  INFO(0, 0,  64 * 1024,  64, 0) },
1121         { "m25p64-nonjedec",  INFO(0, 0,  64 * 1024, 128, 0) },
1122         { "m25p128-nonjedec", INFO(0, 0, 256 * 1024,  64, 0) },
1123
1124         { "m45pe10", INFO(0x204011,  0, 64 * 1024,    2, 0) },
1125         { "m45pe80", INFO(0x204014,  0, 64 * 1024,   16, 0) },
1126         { "m45pe16", INFO(0x204015,  0, 64 * 1024,   32, 0) },
1127
1128         { "m25pe20", INFO(0x208012,  0, 64 * 1024,  4,       0) },
1129         { "m25pe80", INFO(0x208014,  0, 64 * 1024, 16,       0) },
1130         { "m25pe16", INFO(0x208015,  0, 64 * 1024, 32, SECT_4K) },
1131
1132         { "m25px16",    INFO(0x207115,  0, 64 * 1024, 32, SECT_4K) },
1133         { "m25px32",    INFO(0x207116,  0, 64 * 1024, 64, SECT_4K) },
1134         { "m25px32-s0", INFO(0x207316,  0, 64 * 1024, 64, SECT_4K) },
1135         { "m25px32-s1", INFO(0x206316,  0, 64 * 1024, 64, SECT_4K) },
1136         { "m25px64",    INFO(0x207117,  0, 64 * 1024, 128, 0) },
1137         { "m25px80",    INFO(0x207114,  0, 64 * 1024, 16, 0) },
1138
1139         /* Winbond -- w25x "blocks" are 64K, "sectors" are 4KiB */
1140         { "w25x05", INFO(0xef3010, 0, 64 * 1024,  1,  SECT_4K) },
1141         { "w25x10", INFO(0xef3011, 0, 64 * 1024,  2,  SECT_4K) },
1142         { "w25x20", INFO(0xef3012, 0, 64 * 1024,  4,  SECT_4K) },
1143         { "w25x40", INFO(0xef3013, 0, 64 * 1024,  8,  SECT_4K) },
1144         { "w25x80", INFO(0xef3014, 0, 64 * 1024,  16, SECT_4K) },
1145         { "w25x16", INFO(0xef3015, 0, 64 * 1024,  32, SECT_4K) },
1146         { "w25x32", INFO(0xef3016, 0, 64 * 1024,  64, SECT_4K) },
1147         { "w25q20cl", INFO(0xef4012, 0, 64 * 1024,  4, SECT_4K) },
1148         { "w25q20bw", INFO(0xef5012, 0, 64 * 1024,  4, SECT_4K) },
1149         { "w25q20ew", INFO(0xef6012, 0, 64 * 1024,  4, SECT_4K) },
1150         { "w25q32", INFO(0xef4016, 0, 64 * 1024,  64, SECT_4K) },
1151         {
1152                 "w25q32dw", INFO(0xef6016, 0, 64 * 1024,  64,
1153                         SECT_4K | SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ |
1154                         SPI_NOR_HAS_LOCK | SPI_NOR_HAS_TB)
1155         },
1156         { "w25x64", INFO(0xef3017, 0, 64 * 1024, 128, SECT_4K) },
1157         { "w25q64", INFO(0xef4017, 0, 64 * 1024, 128, SECT_4K) },
1158         {
1159                 "w25q64dw", INFO(0xef6017, 0, 64 * 1024, 128,
1160                         SECT_4K | SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ |
1161                         SPI_NOR_HAS_LOCK | SPI_NOR_HAS_TB)
1162         },
1163         {
1164                 "w25q128fw", INFO(0xef6018, 0, 64 * 1024, 256,
1165                         SECT_4K | SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ |
1166                         SPI_NOR_HAS_LOCK | SPI_NOR_HAS_TB)
1167         },
1168         { "w25q80", INFO(0xef5014, 0, 64 * 1024,  16, SECT_4K) },
1169         { "w25q80bl", INFO(0xef4014, 0, 64 * 1024,  16, SECT_4K) },
1170         { "w25q128", INFO(0xef4018, 0, 64 * 1024, 256, SECT_4K) },
1171         { "w25q256", INFO(0xef4019, 0, 64 * 1024, 512, SECT_4K | SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ) },
1172         { "w25m512jv", INFO(0xef7119, 0, 64 * 1024, 1024,
1173                         SECT_4K | SPI_NOR_QUAD_READ | SPI_NOR_DUAL_READ) },
1174
1175         /* Catalyst / On Semiconductor -- non-JEDEC */
1176         { "cat25c11", CAT25_INFO(  16, 8, 16, 1, SPI_NOR_NO_ERASE | SPI_NOR_NO_FR) },
1177         { "cat25c03", CAT25_INFO(  32, 8, 16, 2, SPI_NOR_NO_ERASE | SPI_NOR_NO_FR) },
1178         { "cat25c09", CAT25_INFO( 128, 8, 32, 2, SPI_NOR_NO_ERASE | SPI_NOR_NO_FR) },
1179         { "cat25c17", CAT25_INFO( 256, 8, 32, 2, SPI_NOR_NO_ERASE | SPI_NOR_NO_FR) },
1180         { "cat25128", CAT25_INFO(2048, 8, 64, 2, SPI_NOR_NO_ERASE | SPI_NOR_NO_FR) },
1181
1182         /* Xilinx S3AN Internal Flash */
1183         { "3S50AN", S3AN_INFO(0x1f2200, 64, 264) },
1184         { "3S200AN", S3AN_INFO(0x1f2400, 256, 264) },
1185         { "3S400AN", S3AN_INFO(0x1f2400, 256, 264) },
1186         { "3S700AN", S3AN_INFO(0x1f2500, 512, 264) },
1187         { "3S1400AN", S3AN_INFO(0x1f2600, 512, 528) },
1188         { },
1189 };
1190
1191 static const struct flash_info *spi_nor_read_id(struct spi_nor *nor)
1192 {
1193         int                     tmp;
1194         u8                      id[SPI_NOR_MAX_ID_LEN];
1195         const struct flash_info *info;
1196
1197         tmp = nor->read_reg(nor, SPINOR_OP_RDID, id, SPI_NOR_MAX_ID_LEN);
1198         if (tmp < 0) {
1199                 dev_dbg(nor->dev, "error %d reading JEDEC ID\n", tmp);
1200                 return ERR_PTR(tmp);
1201         }
1202
1203         for (tmp = 0; tmp < ARRAY_SIZE(spi_nor_ids) - 1; tmp++) {
1204                 info = &spi_nor_ids[tmp];
1205                 if (info->id_len) {
1206                         if (!memcmp(info->id, id, info->id_len))
1207                                 return &spi_nor_ids[tmp];
1208                 }
1209         }
1210         dev_err(nor->dev, "unrecognized JEDEC id bytes: %02x, %02x, %02x\n",
1211                 id[0], id[1], id[2]);
1212         return ERR_PTR(-ENODEV);
1213 }
1214
1215 static int spi_nor_read(struct mtd_info *mtd, loff_t from, size_t len,
1216                         size_t *retlen, u_char *buf)
1217 {
1218         struct spi_nor *nor = mtd_to_spi_nor(mtd);
1219         ssize_t ret;
1220
1221         dev_dbg(nor->dev, "from 0x%08x, len %zd\n", (u32)from, len);
1222
1223         ret = spi_nor_lock_and_prep(nor, SPI_NOR_OPS_READ);
1224         if (ret)
1225                 return ret;
1226
1227         while (len) {
1228                 loff_t addr = from;
1229
1230                 if (nor->flags & SNOR_F_S3AN_ADDR_DEFAULT)
1231                         addr = spi_nor_s3an_addr_convert(nor, addr);
1232
1233                 ret = nor->read(nor, addr, len, buf);
1234                 if (ret == 0) {
1235                         /* We shouldn't see 0-length reads */
1236                         ret = -EIO;
1237                         goto read_err;
1238                 }
1239                 if (ret < 0)
1240                         goto read_err;
1241
1242                 WARN_ON(ret > len);
1243                 *retlen += ret;
1244                 buf += ret;
1245                 from += ret;
1246                 len -= ret;
1247         }
1248         ret = 0;
1249
1250 read_err:
1251         spi_nor_unlock_and_unprep(nor, SPI_NOR_OPS_READ);
1252         return ret;
1253 }
1254
1255 static int sst_write(struct mtd_info *mtd, loff_t to, size_t len,
1256                 size_t *retlen, const u_char *buf)
1257 {
1258         struct spi_nor *nor = mtd_to_spi_nor(mtd);
1259         size_t actual;
1260         int ret;
1261
1262         dev_dbg(nor->dev, "to 0x%08x, len %zd\n", (u32)to, len);
1263
1264         ret = spi_nor_lock_and_prep(nor, SPI_NOR_OPS_WRITE);
1265         if (ret)
1266                 return ret;
1267
1268         write_enable(nor);
1269
1270         nor->sst_write_second = false;
1271
1272         actual = to % 2;
1273         /* Start write from odd address. */
1274         if (actual) {
1275                 nor->program_opcode = SPINOR_OP_BP;
1276
1277                 /* write one byte. */
1278                 ret = nor->write(nor, to, 1, buf);
1279                 if (ret < 0)
1280                         goto sst_write_err;
1281                 WARN(ret != 1, "While writing 1 byte written %i bytes\n",
1282                      (int)ret);
1283                 ret = spi_nor_wait_till_ready(nor);
1284                 if (ret)
1285                         goto sst_write_err;
1286         }
1287         to += actual;
1288
1289         /* Write out most of the data here. */
1290         for (; actual < len - 1; actual += 2) {
1291                 nor->program_opcode = SPINOR_OP_AAI_WP;
1292
1293                 /* write two bytes. */
1294                 ret = nor->write(nor, to, 2, buf + actual);
1295                 if (ret < 0)
1296                         goto sst_write_err;
1297                 WARN(ret != 2, "While writing 2 bytes written %i bytes\n",
1298                      (int)ret);
1299                 ret = spi_nor_wait_till_ready(nor);
1300                 if (ret)
1301                         goto sst_write_err;
1302                 to += 2;
1303                 nor->sst_write_second = true;
1304         }
1305         nor->sst_write_second = false;
1306
1307         write_disable(nor);
1308         ret = spi_nor_wait_till_ready(nor);
1309         if (ret)
1310                 goto sst_write_err;
1311
1312         /* Write out trailing byte if it exists. */
1313         if (actual != len) {
1314                 write_enable(nor);
1315
1316                 nor->program_opcode = SPINOR_OP_BP;
1317                 ret = nor->write(nor, to, 1, buf + actual);
1318                 if (ret < 0)
1319                         goto sst_write_err;
1320                 WARN(ret != 1, "While writing 1 byte written %i bytes\n",
1321                      (int)ret);
1322                 ret = spi_nor_wait_till_ready(nor);
1323                 if (ret)
1324                         goto sst_write_err;
1325                 write_disable(nor);
1326                 actual += 1;
1327         }
1328 sst_write_err:
1329         *retlen += actual;
1330         spi_nor_unlock_and_unprep(nor, SPI_NOR_OPS_WRITE);
1331         return ret;
1332 }
1333
1334 /*
1335  * Write an address range to the nor chip.  Data must be written in
1336  * FLASH_PAGESIZE chunks.  The address range may be any size provided
1337  * it is within the physical boundaries.
1338  */
1339 static int spi_nor_write(struct mtd_info *mtd, loff_t to, size_t len,
1340         size_t *retlen, const u_char *buf)
1341 {
1342         struct spi_nor *nor = mtd_to_spi_nor(mtd);
1343         size_t page_offset, page_remain, i;
1344         ssize_t ret;
1345
1346         dev_dbg(nor->dev, "to 0x%08x, len %zd\n", (u32)to, len);
1347
1348         ret = spi_nor_lock_and_prep(nor, SPI_NOR_OPS_WRITE);
1349         if (ret)
1350                 return ret;
1351
1352         for (i = 0; i < len; ) {
1353                 ssize_t written;
1354                 loff_t addr = to + i;
1355
1356                 /*
1357                  * If page_size is a power of two, the offset can be quickly
1358                  * calculated with an AND operation. On the other cases we
1359                  * need to do a modulus operation (more expensive).
1360                  * Power of two numbers have only one bit set and we can use
1361                  * the instruction hweight32 to detect if we need to do a
1362                  * modulus (do_div()) or not.
1363                  */
1364                 if (hweight32(nor->page_size) == 1) {
1365                         page_offset = addr & (nor->page_size - 1);
1366                 } else {
1367                         uint64_t aux = addr;
1368
1369                         page_offset = do_div(aux, nor->page_size);
1370                 }
1371                 /* the size of data remaining on the first page */
1372                 page_remain = min_t(size_t,
1373                                     nor->page_size - page_offset, len - i);
1374
1375                 if (nor->flags & SNOR_F_S3AN_ADDR_DEFAULT)
1376                         addr = spi_nor_s3an_addr_convert(nor, addr);
1377
1378                 write_enable(nor);
1379                 ret = nor->write(nor, addr, page_remain, buf + i);
1380                 if (ret < 0)
1381                         goto write_err;
1382                 written = ret;
1383
1384                 ret = spi_nor_wait_till_ready(nor);
1385                 if (ret)
1386                         goto write_err;
1387                 *retlen += written;
1388                 i += written;
1389                 if (written != page_remain) {
1390                         dev_err(nor->dev,
1391                                 "While writing %zu bytes written %zd bytes\n",
1392                                 page_remain, written);
1393                         ret = -EIO;
1394                         goto write_err;
1395                 }
1396         }
1397
1398 write_err:
1399         spi_nor_unlock_and_unprep(nor, SPI_NOR_OPS_WRITE);
1400         return ret;
1401 }
1402
1403 /**
1404  * macronix_quad_enable() - set QE bit in Status Register.
1405  * @nor:        pointer to a 'struct spi_nor'
1406  *
1407  * Set the Quad Enable (QE) bit in the Status Register.
1408  *
1409  * bit 6 of the Status Register is the QE bit for Macronix like QSPI memories.
1410  *
1411  * Return: 0 on success, -errno otherwise.
1412  */
1413 static int macronix_quad_enable(struct spi_nor *nor)
1414 {
1415         int ret, val;
1416
1417         val = read_sr(nor);
1418         if (val < 0)
1419                 return val;
1420         if (val & SR_QUAD_EN_MX)
1421                 return 0;
1422
1423         write_enable(nor);
1424
1425         write_sr(nor, val | SR_QUAD_EN_MX);
1426
1427         ret = spi_nor_wait_till_ready(nor);
1428         if (ret)
1429                 return ret;
1430
1431         ret = read_sr(nor);
1432         if (!(ret > 0 && (ret & SR_QUAD_EN_MX))) {
1433                 dev_err(nor->dev, "Macronix Quad bit not set\n");
1434                 return -EINVAL;
1435         }
1436
1437         return 0;
1438 }
1439
1440 /*
1441  * Write status Register and configuration register with 2 bytes
1442  * The first byte will be written to the status register, while the
1443  * second byte will be written to the configuration register.
1444  * Return negative if error occurred.
1445  */
1446 static int write_sr_cr(struct spi_nor *nor, u8 *sr_cr)
1447 {
1448         ssize_t ret;
1449
1450         write_enable(nor);
1451
1452         ret = nor->write_reg(nor, SPINOR_OP_WRSR, sr_cr, 2);
1453         if (ret < 0) {
1454                 dev_err(nor->dev,
1455                         "error while writing configuration register\n");
1456                 return -EINVAL;
1457         }
1458
1459         ret = spi_nor_wait_till_ready(nor);
1460         if (ret) {
1461                 dev_err(nor->dev,
1462                         "timeout while writing configuration register\n");
1463                 return ret;
1464         }
1465
1466         return 0;
1467 }
1468
1469 /**
1470  * spansion_quad_enable() - set QE bit in Configuraiton Register.
1471  * @nor:        pointer to a 'struct spi_nor'
1472  *
1473  * Set the Quad Enable (QE) bit in the Configuration Register.
1474  * This function is kept for legacy purpose because it has been used for a
1475  * long time without anybody complaining but it should be considered as
1476  * deprecated and maybe buggy.
1477  * First, this function doesn't care about the previous values of the Status
1478  * and Configuration Registers when it sets the QE bit (bit 1) in the
1479  * Configuration Register: all other bits are cleared, which may have unwanted
1480  * side effects like removing some block protections.
1481  * Secondly, it uses the Read Configuration Register (35h) instruction though
1482  * some very old and few memories don't support this instruction. If a pull-up
1483  * resistor is present on the MISO/IO1 line, we might still be able to pass the
1484  * "read back" test because the QSPI memory doesn't recognize the command,
1485  * so leaves the MISO/IO1 line state unchanged, hence read_cr() returns 0xFF.
1486  *
1487  * bit 1 of the Configuration Register is the QE bit for Spansion like QSPI
1488  * memories.
1489  *
1490  * Return: 0 on success, -errno otherwise.
1491  */
1492 static int spansion_quad_enable(struct spi_nor *nor)
1493 {
1494         u8 sr_cr[2] = {0, CR_QUAD_EN_SPAN};
1495         int ret;
1496
1497         ret = write_sr_cr(nor, sr_cr);
1498         if (ret)
1499                 return ret;
1500
1501         /* read back and check it */
1502         ret = read_cr(nor);
1503         if (!(ret > 0 && (ret & CR_QUAD_EN_SPAN))) {
1504                 dev_err(nor->dev, "Spansion Quad bit not set\n");
1505                 return -EINVAL;
1506         }
1507
1508         return 0;
1509 }
1510
1511 /**
1512  * spansion_no_read_cr_quad_enable() - set QE bit in Configuration Register.
1513  * @nor:        pointer to a 'struct spi_nor'
1514  *
1515  * Set the Quad Enable (QE) bit in the Configuration Register.
1516  * This function should be used with QSPI memories not supporting the Read
1517  * Configuration Register (35h) instruction.
1518  *
1519  * bit 1 of the Configuration Register is the QE bit for Spansion like QSPI
1520  * memories.
1521  *
1522  * Return: 0 on success, -errno otherwise.
1523  */
1524 static int spansion_no_read_cr_quad_enable(struct spi_nor *nor)
1525 {
1526         u8 sr_cr[2];
1527         int ret;
1528
1529         /* Keep the current value of the Status Register. */
1530         ret = read_sr(nor);
1531         if (ret < 0) {
1532                 dev_err(nor->dev, "error while reading status register\n");
1533                 return -EINVAL;
1534         }
1535         sr_cr[0] = ret;
1536         sr_cr[1] = CR_QUAD_EN_SPAN;
1537
1538         return write_sr_cr(nor, sr_cr);
1539 }
1540
1541 /**
1542  * spansion_read_cr_quad_enable() - set QE bit in Configuration Register.
1543  * @nor:        pointer to a 'struct spi_nor'
1544  *
1545  * Set the Quad Enable (QE) bit in the Configuration Register.
1546  * This function should be used with QSPI memories supporting the Read
1547  * Configuration Register (35h) instruction.
1548  *
1549  * bit 1 of the Configuration Register is the QE bit for Spansion like QSPI
1550  * memories.
1551  *
1552  * Return: 0 on success, -errno otherwise.
1553  */
1554 static int spansion_read_cr_quad_enable(struct spi_nor *nor)
1555 {
1556         struct device *dev = nor->dev;
1557         u8 sr_cr[2];
1558         int ret;
1559
1560         /* Check current Quad Enable bit value. */
1561         ret = read_cr(nor);
1562         if (ret < 0) {
1563                 dev_err(dev, "error while reading configuration register\n");
1564                 return -EINVAL;
1565         }
1566
1567         if (ret & CR_QUAD_EN_SPAN)
1568                 return 0;
1569
1570         sr_cr[1] = ret | CR_QUAD_EN_SPAN;
1571
1572         /* Keep the current value of the Status Register. */
1573         ret = read_sr(nor);
1574         if (ret < 0) {
1575                 dev_err(dev, "error while reading status register\n");
1576                 return -EINVAL;
1577         }
1578         sr_cr[0] = ret;
1579
1580         ret = write_sr_cr(nor, sr_cr);
1581         if (ret)
1582                 return ret;
1583
1584         /* Read back and check it. */
1585         ret = read_cr(nor);
1586         if (!(ret > 0 && (ret & CR_QUAD_EN_SPAN))) {
1587                 dev_err(nor->dev, "Spansion Quad bit not set\n");
1588                 return -EINVAL;
1589         }
1590
1591         return 0;
1592 }
1593
1594 /**
1595  * sr2_bit7_quad_enable() - set QE bit in Status Register 2.
1596  * @nor:        pointer to a 'struct spi_nor'
1597  *
1598  * Set the Quad Enable (QE) bit in the Status Register 2.
1599  *
1600  * This is one of the procedures to set the QE bit described in the SFDP
1601  * (JESD216 rev B) specification but no manufacturer using this procedure has
1602  * been identified yet, hence the name of the function.
1603  *
1604  * Return: 0 on success, -errno otherwise.
1605  */
1606 static int sr2_bit7_quad_enable(struct spi_nor *nor)
1607 {
1608         u8 sr2;
1609         int ret;
1610
1611         /* Check current Quad Enable bit value. */
1612         ret = nor->read_reg(nor, SPINOR_OP_RDSR2, &sr2, 1);
1613         if (ret)
1614                 return ret;
1615         if (sr2 & SR2_QUAD_EN_BIT7)
1616                 return 0;
1617
1618         /* Update the Quad Enable bit. */
1619         sr2 |= SR2_QUAD_EN_BIT7;
1620
1621         write_enable(nor);
1622
1623         ret = nor->write_reg(nor, SPINOR_OP_WRSR2, &sr2, 1);
1624         if (ret < 0) {
1625                 dev_err(nor->dev, "error while writing status register 2\n");
1626                 return -EINVAL;
1627         }
1628
1629         ret = spi_nor_wait_till_ready(nor);
1630         if (ret < 0) {
1631                 dev_err(nor->dev, "timeout while writing status register 2\n");
1632                 return ret;
1633         }
1634
1635         /* Read back and check it. */
1636         ret = nor->read_reg(nor, SPINOR_OP_RDSR2, &sr2, 1);
1637         if (!(ret > 0 && (sr2 & SR2_QUAD_EN_BIT7))) {
1638                 dev_err(nor->dev, "SR2 Quad bit not set\n");
1639                 return -EINVAL;
1640         }
1641
1642         return 0;
1643 }
1644
1645 static int spi_nor_check(struct spi_nor *nor)
1646 {
1647         if (!nor->dev || !nor->read || !nor->write ||
1648                 !nor->read_reg || !nor->write_reg) {
1649                 pr_err("spi-nor: please fill all the necessary fields!\n");
1650                 return -EINVAL;
1651         }
1652
1653         return 0;
1654 }
1655
1656 static int s3an_nor_scan(const struct flash_info *info, struct spi_nor *nor)
1657 {
1658         int ret;
1659         u8 val;
1660
1661         ret = nor->read_reg(nor, SPINOR_OP_XRDSR, &val, 1);
1662         if (ret < 0) {
1663                 dev_err(nor->dev, "error %d reading XRDSR\n", (int) ret);
1664                 return ret;
1665         }
1666
1667         nor->erase_opcode = SPINOR_OP_XSE;
1668         nor->program_opcode = SPINOR_OP_XPP;
1669         nor->read_opcode = SPINOR_OP_READ;
1670         nor->flags |= SNOR_F_NO_OP_CHIP_ERASE;
1671
1672         /*
1673          * This flashes have a page size of 264 or 528 bytes (known as
1674          * Default addressing mode). It can be changed to a more standard
1675          * Power of two mode where the page size is 256/512. This comes
1676          * with a price: there is 3% less of space, the data is corrupted
1677          * and the page size cannot be changed back to default addressing
1678          * mode.
1679          *
1680          * The current addressing mode can be read from the XRDSR register
1681          * and should not be changed, because is a destructive operation.
1682          */
1683         if (val & XSR_PAGESIZE) {
1684                 /* Flash in Power of 2 mode */
1685                 nor->page_size = (nor->page_size == 264) ? 256 : 512;
1686                 nor->mtd.writebufsize = nor->page_size;
1687                 nor->mtd.size = 8 * nor->page_size * info->n_sectors;
1688                 nor->mtd.erasesize = 8 * nor->page_size;
1689         } else {
1690                 /* Flash in Default addressing mode */
1691                 nor->flags |= SNOR_F_S3AN_ADDR_DEFAULT;
1692         }
1693
1694         return 0;
1695 }
1696
1697 struct spi_nor_read_command {
1698         u8                      num_mode_clocks;
1699         u8                      num_wait_states;
1700         u8                      opcode;
1701         enum spi_nor_protocol   proto;
1702 };
1703
1704 struct spi_nor_pp_command {
1705         u8                      opcode;
1706         enum spi_nor_protocol   proto;
1707 };
1708
1709 enum spi_nor_read_command_index {
1710         SNOR_CMD_READ,
1711         SNOR_CMD_READ_FAST,
1712         SNOR_CMD_READ_1_1_1_DTR,
1713
1714         /* Dual SPI */
1715         SNOR_CMD_READ_1_1_2,
1716         SNOR_CMD_READ_1_2_2,
1717         SNOR_CMD_READ_2_2_2,
1718         SNOR_CMD_READ_1_2_2_DTR,
1719
1720         /* Quad SPI */
1721         SNOR_CMD_READ_1_1_4,
1722         SNOR_CMD_READ_1_4_4,
1723         SNOR_CMD_READ_4_4_4,
1724         SNOR_CMD_READ_1_4_4_DTR,
1725
1726         /* Octo SPI */
1727         SNOR_CMD_READ_1_1_8,
1728         SNOR_CMD_READ_1_8_8,
1729         SNOR_CMD_READ_8_8_8,
1730         SNOR_CMD_READ_1_8_8_DTR,
1731
1732         SNOR_CMD_READ_MAX
1733 };
1734
1735 enum spi_nor_pp_command_index {
1736         SNOR_CMD_PP,
1737
1738         /* Quad SPI */
1739         SNOR_CMD_PP_1_1_4,
1740         SNOR_CMD_PP_1_4_4,
1741         SNOR_CMD_PP_4_4_4,
1742
1743         /* Octo SPI */
1744         SNOR_CMD_PP_1_1_8,
1745         SNOR_CMD_PP_1_8_8,
1746         SNOR_CMD_PP_8_8_8,
1747
1748         SNOR_CMD_PP_MAX
1749 };
1750
1751 struct spi_nor_flash_parameter {
1752         u64                             size;
1753         u32                             page_size;
1754
1755         struct spi_nor_hwcaps           hwcaps;
1756         struct spi_nor_read_command     reads[SNOR_CMD_READ_MAX];
1757         struct spi_nor_pp_command       page_programs[SNOR_CMD_PP_MAX];
1758
1759         int (*quad_enable)(struct spi_nor *nor);
1760 };
1761
1762 static void
1763 spi_nor_set_read_settings(struct spi_nor_read_command *read,
1764                           u8 num_mode_clocks,
1765                           u8 num_wait_states,
1766                           u8 opcode,
1767                           enum spi_nor_protocol proto)
1768 {
1769         read->num_mode_clocks = num_mode_clocks;
1770         read->num_wait_states = num_wait_states;
1771         read->opcode = opcode;
1772         read->proto = proto;
1773 }
1774
1775 static void
1776 spi_nor_set_pp_settings(struct spi_nor_pp_command *pp,
1777                         u8 opcode,
1778                         enum spi_nor_protocol proto)
1779 {
1780         pp->opcode = opcode;
1781         pp->proto = proto;
1782 }
1783
1784 /*
1785  * Serial Flash Discoverable Parameters (SFDP) parsing.
1786  */
1787
1788 /**
1789  * spi_nor_read_sfdp() - read Serial Flash Discoverable Parameters.
1790  * @nor:        pointer to a 'struct spi_nor'
1791  * @addr:       offset in the SFDP area to start reading data from
1792  * @len:        number of bytes to read
1793  * @buf:        buffer where the SFDP data are copied into (dma-safe memory)
1794  *
1795  * Whatever the actual numbers of bytes for address and dummy cycles are
1796  * for (Fast) Read commands, the Read SFDP (5Ah) instruction is always
1797  * followed by a 3-byte address and 8 dummy clock cycles.
1798  *
1799  * Return: 0 on success, -errno otherwise.
1800  */
1801 static int spi_nor_read_sfdp(struct spi_nor *nor, u32 addr,
1802                              size_t len, void *buf)
1803 {
1804         u8 addr_width, read_opcode, read_dummy;
1805         int ret;
1806
1807         read_opcode = nor->read_opcode;
1808         addr_width = nor->addr_width;
1809         read_dummy = nor->read_dummy;
1810
1811         nor->read_opcode = SPINOR_OP_RDSFDP;
1812         nor->addr_width = 3;
1813         nor->read_dummy = 8;
1814
1815         while (len) {
1816                 ret = nor->read(nor, addr, len, (u8 *)buf);
1817                 if (!ret || ret > len) {
1818                         ret = -EIO;
1819                         goto read_err;
1820                 }
1821                 if (ret < 0)
1822                         goto read_err;
1823
1824                 buf += ret;
1825                 addr += ret;
1826                 len -= ret;
1827         }
1828         ret = 0;
1829
1830 read_err:
1831         nor->read_opcode = read_opcode;
1832         nor->addr_width = addr_width;
1833         nor->read_dummy = read_dummy;
1834
1835         return ret;
1836 }
1837
1838 /**
1839  * spi_nor_read_sfdp_dma_unsafe() - read Serial Flash Discoverable Parameters.
1840  * @nor:        pointer to a 'struct spi_nor'
1841  * @addr:       offset in the SFDP area to start reading data from
1842  * @len:        number of bytes to read
1843  * @buf:        buffer where the SFDP data are copied into
1844  *
1845  * Wrap spi_nor_read_sfdp() using a kmalloc'ed bounce buffer as @buf is now not
1846  * guaranteed to be dma-safe.
1847  *
1848  * Return: -ENOMEM if kmalloc() fails, the return code of spi_nor_read_sfdp()
1849  *          otherwise.
1850  */
1851 static int spi_nor_read_sfdp_dma_unsafe(struct spi_nor *nor, u32 addr,
1852                                         size_t len, void *buf)
1853 {
1854         void *dma_safe_buf;
1855         int ret;
1856
1857         dma_safe_buf = kmalloc(len, GFP_KERNEL);
1858         if (!dma_safe_buf)
1859                 return -ENOMEM;
1860
1861         ret = spi_nor_read_sfdp(nor, addr, len, dma_safe_buf);
1862         memcpy(buf, dma_safe_buf, len);
1863         kfree(dma_safe_buf);
1864
1865         return ret;
1866 }
1867
1868 struct sfdp_parameter_header {
1869         u8              id_lsb;
1870         u8              minor;
1871         u8              major;
1872         u8              length; /* in double words */
1873         u8              parameter_table_pointer[3]; /* byte address */
1874         u8              id_msb;
1875 };
1876
1877 #define SFDP_PARAM_HEADER_ID(p) (((p)->id_msb << 8) | (p)->id_lsb)
1878 #define SFDP_PARAM_HEADER_PTP(p) \
1879         (((p)->parameter_table_pointer[2] << 16) | \
1880          ((p)->parameter_table_pointer[1] <<  8) | \
1881          ((p)->parameter_table_pointer[0] <<  0))
1882
1883 #define SFDP_BFPT_ID            0xff00  /* Basic Flash Parameter Table */
1884 #define SFDP_SECTOR_MAP_ID      0xff81  /* Sector Map Table */
1885
1886 #define SFDP_SIGNATURE          0x50444653U
1887 #define SFDP_JESD216_MAJOR      1
1888 #define SFDP_JESD216_MINOR      0
1889 #define SFDP_JESD216A_MINOR     5
1890 #define SFDP_JESD216B_MINOR     6
1891
1892 struct sfdp_header {
1893         u32             signature; /* Ox50444653U <=> "SFDP" */
1894         u8              minor;
1895         u8              major;
1896         u8              nph; /* 0-base number of parameter headers */
1897         u8              unused;
1898
1899         /* Basic Flash Parameter Table. */
1900         struct sfdp_parameter_header    bfpt_header;
1901 };
1902
1903 /* Basic Flash Parameter Table */
1904
1905 /*
1906  * JESD216 rev B defines a Basic Flash Parameter Table of 16 DWORDs.
1907  * They are indexed from 1 but C arrays are indexed from 0.
1908  */
1909 #define BFPT_DWORD(i)           ((i) - 1)
1910 #define BFPT_DWORD_MAX          16
1911
1912 /* The first version of JESB216 defined only 9 DWORDs. */
1913 #define BFPT_DWORD_MAX_JESD216                  9
1914
1915 /* 1st DWORD. */
1916 #define BFPT_DWORD1_FAST_READ_1_1_2             BIT(16)
1917 #define BFPT_DWORD1_ADDRESS_BYTES_MASK          GENMASK(18, 17)
1918 #define BFPT_DWORD1_ADDRESS_BYTES_3_ONLY        (0x0UL << 17)
1919 #define BFPT_DWORD1_ADDRESS_BYTES_3_OR_4        (0x1UL << 17)
1920 #define BFPT_DWORD1_ADDRESS_BYTES_4_ONLY        (0x2UL << 17)
1921 #define BFPT_DWORD1_DTR                         BIT(19)
1922 #define BFPT_DWORD1_FAST_READ_1_2_2             BIT(20)
1923 #define BFPT_DWORD1_FAST_READ_1_4_4             BIT(21)
1924 #define BFPT_DWORD1_FAST_READ_1_1_4             BIT(22)
1925
1926 /* 5th DWORD. */
1927 #define BFPT_DWORD5_FAST_READ_2_2_2             BIT(0)
1928 #define BFPT_DWORD5_FAST_READ_4_4_4             BIT(4)
1929
1930 /* 11th DWORD. */
1931 #define BFPT_DWORD11_PAGE_SIZE_SHIFT            4
1932 #define BFPT_DWORD11_PAGE_SIZE_MASK             GENMASK(7, 4)
1933
1934 /* 15th DWORD. */
1935
1936 /*
1937  * (from JESD216 rev B)
1938  * Quad Enable Requirements (QER):
1939  * - 000b: Device does not have a QE bit. Device detects 1-1-4 and 1-4-4
1940  *         reads based on instruction. DQ3/HOLD# functions are hold during
1941  *         instruction phase.
1942  * - 001b: QE is bit 1 of status register 2. It is set via Write Status with
1943  *         two data bytes where bit 1 of the second byte is one.
1944  *         [...]
1945  *         Writing only one byte to the status register has the side-effect of
1946  *         clearing status register 2, including the QE bit. The 100b code is
1947  *         used if writing one byte to the status register does not modify
1948  *         status register 2.
1949  * - 010b: QE is bit 6 of status register 1. It is set via Write Status with
1950  *         one data byte where bit 6 is one.
1951  *         [...]
1952  * - 011b: QE is bit 7 of status register 2. It is set via Write status
1953  *         register 2 instruction 3Eh with one data byte where bit 7 is one.
1954  *         [...]
1955  *         The status register 2 is read using instruction 3Fh.
1956  * - 100b: QE is bit 1 of status register 2. It is set via Write Status with
1957  *         two data bytes where bit 1 of the second byte is one.
1958  *         [...]
1959  *         In contrast to the 001b code, writing one byte to the status
1960  *         register does not modify status register 2.
1961  * - 101b: QE is bit 1 of status register 2. Status register 1 is read using
1962  *         Read Status instruction 05h. Status register2 is read using
1963  *         instruction 35h. QE is set via Writ Status instruction 01h with
1964  *         two data bytes where bit 1 of the second byte is one.
1965  *         [...]
1966  */
1967 #define BFPT_DWORD15_QER_MASK                   GENMASK(22, 20)
1968 #define BFPT_DWORD15_QER_NONE                   (0x0UL << 20) /* Micron */
1969 #define BFPT_DWORD15_QER_SR2_BIT1_BUGGY         (0x1UL << 20)
1970 #define BFPT_DWORD15_QER_SR1_BIT6               (0x2UL << 20) /* Macronix */
1971 #define BFPT_DWORD15_QER_SR2_BIT7               (0x3UL << 20)
1972 #define BFPT_DWORD15_QER_SR2_BIT1_NO_RD         (0x4UL << 20)
1973 #define BFPT_DWORD15_QER_SR2_BIT1               (0x5UL << 20) /* Spansion */
1974
1975 struct sfdp_bfpt {
1976         u32     dwords[BFPT_DWORD_MAX];
1977 };
1978
1979 /* Fast Read settings. */
1980
1981 static inline void
1982 spi_nor_set_read_settings_from_bfpt(struct spi_nor_read_command *read,
1983                                     u16 half,
1984                                     enum spi_nor_protocol proto)
1985 {
1986         read->num_mode_clocks = (half >> 5) & 0x07;
1987         read->num_wait_states = (half >> 0) & 0x1f;
1988         read->opcode = (half >> 8) & 0xff;
1989         read->proto = proto;
1990 }
1991
1992 struct sfdp_bfpt_read {
1993         /* The Fast Read x-y-z hardware capability in params->hwcaps.mask. */
1994         u32                     hwcaps;
1995
1996         /*
1997          * The <supported_bit> bit in <supported_dword> BFPT DWORD tells us
1998          * whether the Fast Read x-y-z command is supported.
1999          */
2000         u32                     supported_dword;
2001         u32                     supported_bit;
2002
2003         /*
2004          * The half-word at offset <setting_shift> in <setting_dword> BFPT DWORD
2005          * encodes the op code, the number of mode clocks and the number of wait
2006          * states to be used by Fast Read x-y-z command.
2007          */
2008         u32                     settings_dword;
2009         u32                     settings_shift;
2010
2011         /* The SPI protocol for this Fast Read x-y-z command. */
2012         enum spi_nor_protocol   proto;
2013 };
2014
2015 static const struct sfdp_bfpt_read sfdp_bfpt_reads[] = {
2016         /* Fast Read 1-1-2 */
2017         {
2018                 SNOR_HWCAPS_READ_1_1_2,
2019                 BFPT_DWORD(1), BIT(16), /* Supported bit */
2020                 BFPT_DWORD(4), 0,       /* Settings */
2021                 SNOR_PROTO_1_1_2,
2022         },
2023
2024         /* Fast Read 1-2-2 */
2025         {
2026                 SNOR_HWCAPS_READ_1_2_2,
2027                 BFPT_DWORD(1), BIT(20), /* Supported bit */
2028                 BFPT_DWORD(4), 16,      /* Settings */
2029                 SNOR_PROTO_1_2_2,
2030         },
2031
2032         /* Fast Read 2-2-2 */
2033         {
2034                 SNOR_HWCAPS_READ_2_2_2,
2035                 BFPT_DWORD(5),  BIT(0), /* Supported bit */
2036                 BFPT_DWORD(6), 16,      /* Settings */
2037                 SNOR_PROTO_2_2_2,
2038         },
2039
2040         /* Fast Read 1-1-4 */
2041         {
2042                 SNOR_HWCAPS_READ_1_1_4,
2043                 BFPT_DWORD(1), BIT(22), /* Supported bit */
2044                 BFPT_DWORD(3), 16,      /* Settings */
2045                 SNOR_PROTO_1_1_4,
2046         },
2047
2048         /* Fast Read 1-4-4 */
2049         {
2050                 SNOR_HWCAPS_READ_1_4_4,
2051                 BFPT_DWORD(1), BIT(21), /* Supported bit */
2052                 BFPT_DWORD(3), 0,       /* Settings */
2053                 SNOR_PROTO_1_4_4,
2054         },
2055
2056         /* Fast Read 4-4-4 */
2057         {
2058                 SNOR_HWCAPS_READ_4_4_4,
2059                 BFPT_DWORD(5), BIT(4),  /* Supported bit */
2060                 BFPT_DWORD(7), 16,      /* Settings */
2061                 SNOR_PROTO_4_4_4,
2062         },
2063 };
2064
2065 struct sfdp_bfpt_erase {
2066         /*
2067          * The half-word at offset <shift> in DWORD <dwoard> encodes the
2068          * op code and erase sector size to be used by Sector Erase commands.
2069          */
2070         u32                     dword;
2071         u32                     shift;
2072 };
2073
2074 static const struct sfdp_bfpt_erase sfdp_bfpt_erases[] = {
2075         /* Erase Type 1 in DWORD8 bits[15:0] */
2076         {BFPT_DWORD(8), 0},
2077
2078         /* Erase Type 2 in DWORD8 bits[31:16] */
2079         {BFPT_DWORD(8), 16},
2080
2081         /* Erase Type 3 in DWORD9 bits[15:0] */
2082         {BFPT_DWORD(9), 0},
2083
2084         /* Erase Type 4 in DWORD9 bits[31:16] */
2085         {BFPT_DWORD(9), 16},
2086 };
2087
2088 static int spi_nor_hwcaps_read2cmd(u32 hwcaps);
2089
2090 /**
2091  * spi_nor_parse_bfpt() - read and parse the Basic Flash Parameter Table.
2092  * @nor:                pointer to a 'struct spi_nor'
2093  * @bfpt_header:        pointer to the 'struct sfdp_parameter_header' describing
2094  *                      the Basic Flash Parameter Table length and version
2095  * @params:             pointer to the 'struct spi_nor_flash_parameter' to be
2096  *                      filled
2097  *
2098  * The Basic Flash Parameter Table is the main and only mandatory table as
2099  * defined by the SFDP (JESD216) specification.
2100  * It provides us with the total size (memory density) of the data array and
2101  * the number of address bytes for Fast Read, Page Program and Sector Erase
2102  * commands.
2103  * For Fast READ commands, it also gives the number of mode clock cycles and
2104  * wait states (regrouped in the number of dummy clock cycles) for each
2105  * supported instruction op code.
2106  * For Page Program, the page size is now available since JESD216 rev A, however
2107  * the supported instruction op codes are still not provided.
2108  * For Sector Erase commands, this table stores the supported instruction op
2109  * codes and the associated sector sizes.
2110  * Finally, the Quad Enable Requirements (QER) are also available since JESD216
2111  * rev A. The QER bits encode the manufacturer dependent procedure to be
2112  * executed to set the Quad Enable (QE) bit in some internal register of the
2113  * Quad SPI memory. Indeed the QE bit, when it exists, must be set before
2114  * sending any Quad SPI command to the memory. Actually, setting the QE bit
2115  * tells the memory to reassign its WP# and HOLD#/RESET# pins to functions IO2
2116  * and IO3 hence enabling 4 (Quad) I/O lines.
2117  *
2118  * Return: 0 on success, -errno otherwise.
2119  */
2120 static int spi_nor_parse_bfpt(struct spi_nor *nor,
2121                               const struct sfdp_parameter_header *bfpt_header,
2122                               struct spi_nor_flash_parameter *params)
2123 {
2124         struct mtd_info *mtd = &nor->mtd;
2125         struct sfdp_bfpt bfpt;
2126         size_t len;
2127         int i, cmd, err;
2128         u32 addr;
2129         u16 half;
2130
2131         /* JESD216 Basic Flash Parameter Table length is at least 9 DWORDs. */
2132         if (bfpt_header->length < BFPT_DWORD_MAX_JESD216)
2133                 return -EINVAL;
2134
2135         /* Read the Basic Flash Parameter Table. */
2136         len = min_t(size_t, sizeof(bfpt),
2137                     bfpt_header->length * sizeof(u32));
2138         addr = SFDP_PARAM_HEADER_PTP(bfpt_header);
2139         memset(&bfpt, 0, sizeof(bfpt));
2140         err = spi_nor_read_sfdp_dma_unsafe(nor,  addr, len, &bfpt);
2141         if (err < 0)
2142                 return err;
2143
2144         /* Fix endianness of the BFPT DWORDs. */
2145         for (i = 0; i < BFPT_DWORD_MAX; i++)
2146                 bfpt.dwords[i] = le32_to_cpu(bfpt.dwords[i]);
2147
2148         /* Number of address bytes. */
2149         switch (bfpt.dwords[BFPT_DWORD(1)] & BFPT_DWORD1_ADDRESS_BYTES_MASK) {
2150         case BFPT_DWORD1_ADDRESS_BYTES_3_ONLY:
2151                 nor->addr_width = 3;
2152                 break;
2153
2154         case BFPT_DWORD1_ADDRESS_BYTES_4_ONLY:
2155                 nor->addr_width = 4;
2156                 break;
2157
2158         default:
2159                 break;
2160         }
2161
2162         /* Flash Memory Density (in bits). */
2163         params->size = bfpt.dwords[BFPT_DWORD(2)];
2164         if (params->size & BIT(31)) {
2165                 params->size &= ~BIT(31);
2166
2167                 /*
2168                  * Prevent overflows on params->size. Anyway, a NOR of 2^64
2169                  * bits is unlikely to exist so this error probably means
2170                  * the BFPT we are reading is corrupted/wrong.
2171                  */
2172                 if (params->size > 63)
2173                         return -EINVAL;
2174
2175                 params->size = 1ULL << params->size;
2176         } else {
2177                 params->size++;
2178         }
2179         params->size >>= 3; /* Convert to bytes. */
2180
2181         /* Fast Read settings. */
2182         for (i = 0; i < ARRAY_SIZE(sfdp_bfpt_reads); i++) {
2183                 const struct sfdp_bfpt_read *rd = &sfdp_bfpt_reads[i];
2184                 struct spi_nor_read_command *read;
2185
2186                 if (!(bfpt.dwords[rd->supported_dword] & rd->supported_bit)) {
2187                         params->hwcaps.mask &= ~rd->hwcaps;
2188                         continue;
2189                 }
2190
2191                 params->hwcaps.mask |= rd->hwcaps;
2192                 cmd = spi_nor_hwcaps_read2cmd(rd->hwcaps);
2193                 read = &params->reads[cmd];
2194                 half = bfpt.dwords[rd->settings_dword] >> rd->settings_shift;
2195                 spi_nor_set_read_settings_from_bfpt(read, half, rd->proto);
2196         }
2197
2198         /* Sector Erase settings. */
2199         for (i = 0; i < ARRAY_SIZE(sfdp_bfpt_erases); i++) {
2200                 const struct sfdp_bfpt_erase *er = &sfdp_bfpt_erases[i];
2201                 u32 erasesize;
2202                 u8 opcode;
2203
2204                 half = bfpt.dwords[er->dword] >> er->shift;
2205                 erasesize = half & 0xff;
2206
2207                 /* erasesize == 0 means this Erase Type is not supported. */
2208                 if (!erasesize)
2209                         continue;
2210
2211                 erasesize = 1U << erasesize;
2212                 opcode = (half >> 8) & 0xff;
2213 #ifdef CONFIG_MTD_SPI_NOR_USE_4K_SECTORS
2214                 if (erasesize == SZ_4K) {
2215                         nor->erase_opcode = opcode;
2216                         mtd->erasesize = erasesize;
2217                         break;
2218                 }
2219 #endif
2220                 if (!mtd->erasesize || mtd->erasesize < erasesize) {
2221                         nor->erase_opcode = opcode;
2222                         mtd->erasesize = erasesize;
2223                 }
2224         }
2225
2226         /* Stop here if not JESD216 rev A or later. */
2227         if (bfpt_header->length < BFPT_DWORD_MAX)
2228                 return 0;
2229
2230         /* Page size: this field specifies 'N' so the page size = 2^N bytes. */
2231         params->page_size = bfpt.dwords[BFPT_DWORD(11)];
2232         params->page_size &= BFPT_DWORD11_PAGE_SIZE_MASK;
2233         params->page_size >>= BFPT_DWORD11_PAGE_SIZE_SHIFT;
2234         params->page_size = 1U << params->page_size;
2235
2236         /* Quad Enable Requirements. */
2237         switch (bfpt.dwords[BFPT_DWORD(15)] & BFPT_DWORD15_QER_MASK) {
2238         case BFPT_DWORD15_QER_NONE:
2239                 params->quad_enable = NULL;
2240                 break;
2241
2242         case BFPT_DWORD15_QER_SR2_BIT1_BUGGY:
2243         case BFPT_DWORD15_QER_SR2_BIT1_NO_RD:
2244                 params->quad_enable = spansion_no_read_cr_quad_enable;
2245                 break;
2246
2247         case BFPT_DWORD15_QER_SR1_BIT6:
2248                 params->quad_enable = macronix_quad_enable;
2249                 break;
2250
2251         case BFPT_DWORD15_QER_SR2_BIT7:
2252                 params->quad_enable = sr2_bit7_quad_enable;
2253                 break;
2254
2255         case BFPT_DWORD15_QER_SR2_BIT1:
2256                 params->quad_enable = spansion_read_cr_quad_enable;
2257                 break;
2258
2259         default:
2260                 return -EINVAL;
2261         }
2262
2263         return 0;
2264 }
2265
2266 /**
2267  * spi_nor_parse_sfdp() - parse the Serial Flash Discoverable Parameters.
2268  * @nor:                pointer to a 'struct spi_nor'
2269  * @params:             pointer to the 'struct spi_nor_flash_parameter' to be
2270  *                      filled
2271  *
2272  * The Serial Flash Discoverable Parameters are described by the JEDEC JESD216
2273  * specification. This is a standard which tends to supported by almost all
2274  * (Q)SPI memory manufacturers. Those hard-coded tables allow us to learn at
2275  * runtime the main parameters needed to perform basic SPI flash operations such
2276  * as Fast Read, Page Program or Sector Erase commands.
2277  *
2278  * Return: 0 on success, -errno otherwise.
2279  */
2280 static int spi_nor_parse_sfdp(struct spi_nor *nor,
2281                               struct spi_nor_flash_parameter *params)
2282 {
2283         const struct sfdp_parameter_header *param_header, *bfpt_header;
2284         struct sfdp_parameter_header *param_headers = NULL;
2285         struct sfdp_header header;
2286         struct device *dev = nor->dev;
2287         size_t psize;
2288         int i, err;
2289
2290         /* Get the SFDP header. */
2291         err = spi_nor_read_sfdp_dma_unsafe(nor, 0, sizeof(header), &header);
2292         if (err < 0)
2293                 return err;
2294
2295         /* Check the SFDP header version. */
2296         if (le32_to_cpu(header.signature) != SFDP_SIGNATURE ||
2297             header.major != SFDP_JESD216_MAJOR ||
2298             header.minor < SFDP_JESD216_MINOR)
2299                 return -EINVAL;
2300
2301         /*
2302          * Verify that the first and only mandatory parameter header is a
2303          * Basic Flash Parameter Table header as specified in JESD216.
2304          */
2305         bfpt_header = &header.bfpt_header;
2306         if (SFDP_PARAM_HEADER_ID(bfpt_header) != SFDP_BFPT_ID ||
2307             bfpt_header->major != SFDP_JESD216_MAJOR)
2308                 return -EINVAL;
2309
2310         /*
2311          * Allocate memory then read all parameter headers with a single
2312          * Read SFDP command. These parameter headers will actually be parsed
2313          * twice: a first time to get the latest revision of the basic flash
2314          * parameter table, then a second time to handle the supported optional
2315          * tables.
2316          * Hence we read the parameter headers once for all to reduce the
2317          * processing time. Also we use kmalloc() instead of devm_kmalloc()
2318          * because we don't need to keep these parameter headers: the allocated
2319          * memory is always released with kfree() before exiting this function.
2320          */
2321         if (header.nph) {
2322                 psize = header.nph * sizeof(*param_headers);
2323
2324                 param_headers = kmalloc(psize, GFP_KERNEL);
2325                 if (!param_headers)
2326                         return -ENOMEM;
2327
2328                 err = spi_nor_read_sfdp(nor, sizeof(header),
2329                                         psize, param_headers);
2330                 if (err < 0) {
2331                         dev_err(dev, "failed to read SFDP parameter headers\n");
2332                         goto exit;
2333                 }
2334         }
2335
2336         /*
2337          * Check other parameter headers to get the latest revision of
2338          * the basic flash parameter table.
2339          */
2340         for (i = 0; i < header.nph; i++) {
2341                 param_header = &param_headers[i];
2342
2343                 if (SFDP_PARAM_HEADER_ID(param_header) == SFDP_BFPT_ID &&
2344                     param_header->major == SFDP_JESD216_MAJOR &&
2345                     (param_header->minor > bfpt_header->minor ||
2346                      (param_header->minor == bfpt_header->minor &&
2347                       param_header->length > bfpt_header->length)))
2348                         bfpt_header = param_header;
2349         }
2350
2351         err = spi_nor_parse_bfpt(nor, bfpt_header, params);
2352         if (err)
2353                 goto exit;
2354
2355         /* Parse other parameter headers. */
2356         for (i = 0; i < header.nph; i++) {
2357                 param_header = &param_headers[i];
2358
2359                 switch (SFDP_PARAM_HEADER_ID(param_header)) {
2360                 case SFDP_SECTOR_MAP_ID:
2361                         dev_info(dev, "non-uniform erase sector maps are not supported yet.\n");
2362                         break;
2363
2364                 default:
2365                         break;
2366                 }
2367
2368                 if (err)
2369                         goto exit;
2370         }
2371
2372 exit:
2373         kfree(param_headers);
2374         return err;
2375 }
2376
2377 static int spi_nor_init_params(struct spi_nor *nor,
2378                                const struct flash_info *info,
2379                                struct spi_nor_flash_parameter *params)
2380 {
2381         /* Set legacy flash parameters as default. */
2382         memset(params, 0, sizeof(*params));
2383
2384         /* Set SPI NOR sizes. */
2385         params->size = (u64)info->sector_size * info->n_sectors;
2386         params->page_size = info->page_size;
2387
2388         /* (Fast) Read settings. */
2389         params->hwcaps.mask |= SNOR_HWCAPS_READ;
2390         spi_nor_set_read_settings(&params->reads[SNOR_CMD_READ],
2391                                   0, 0, SPINOR_OP_READ,
2392                                   SNOR_PROTO_1_1_1);
2393
2394         if (!(info->flags & SPI_NOR_NO_FR)) {
2395                 params->hwcaps.mask |= SNOR_HWCAPS_READ_FAST;
2396                 spi_nor_set_read_settings(&params->reads[SNOR_CMD_READ_FAST],
2397                                           0, 8, SPINOR_OP_READ_FAST,
2398                                           SNOR_PROTO_1_1_1);
2399         }
2400
2401         if (info->flags & SPI_NOR_DUAL_READ) {
2402                 params->hwcaps.mask |= SNOR_HWCAPS_READ_1_1_2;
2403                 spi_nor_set_read_settings(&params->reads[SNOR_CMD_READ_1_1_2],
2404                                           0, 8, SPINOR_OP_READ_1_1_2,
2405                                           SNOR_PROTO_1_1_2);
2406         }
2407
2408         if (info->flags & SPI_NOR_QUAD_READ) {
2409                 params->hwcaps.mask |= SNOR_HWCAPS_READ_1_1_4;
2410                 spi_nor_set_read_settings(&params->reads[SNOR_CMD_READ_1_1_4],
2411                                           0, 8, SPINOR_OP_READ_1_1_4,
2412                                           SNOR_PROTO_1_1_4);
2413         }
2414
2415         /* Page Program settings. */
2416         params->hwcaps.mask |= SNOR_HWCAPS_PP;
2417         spi_nor_set_pp_settings(&params->page_programs[SNOR_CMD_PP],
2418                                 SPINOR_OP_PP, SNOR_PROTO_1_1_1);
2419
2420         /* Select the procedure to set the Quad Enable bit. */
2421         if (params->hwcaps.mask & (SNOR_HWCAPS_READ_QUAD |
2422                                    SNOR_HWCAPS_PP_QUAD)) {
2423                 switch (JEDEC_MFR(info)) {
2424                 case SNOR_MFR_MACRONIX:
2425                         params->quad_enable = macronix_quad_enable;
2426                         break;
2427
2428                 case SNOR_MFR_MICRON:
2429                         break;
2430
2431                 default:
2432                         /* Kept only for backward compatibility purpose. */
2433                         params->quad_enable = spansion_quad_enable;
2434                         break;
2435                 }
2436         }
2437
2438         /* Override the parameters with data read from SFDP tables. */
2439         nor->addr_width = 0;
2440         nor->mtd.erasesize = 0;
2441         if ((info->flags & (SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ)) &&
2442             !(info->flags & SPI_NOR_SKIP_SFDP)) {
2443                 struct spi_nor_flash_parameter sfdp_params;
2444
2445                 memcpy(&sfdp_params, params, sizeof(sfdp_params));
2446                 if (spi_nor_parse_sfdp(nor, &sfdp_params)) {
2447                         nor->addr_width = 0;
2448                         nor->mtd.erasesize = 0;
2449                 } else {
2450                         memcpy(params, &sfdp_params, sizeof(*params));
2451                 }
2452         }
2453
2454         return 0;
2455 }
2456
2457 static int spi_nor_hwcaps2cmd(u32 hwcaps, const int table[][2], size_t size)
2458 {
2459         size_t i;
2460
2461         for (i = 0; i < size; i++)
2462                 if (table[i][0] == (int)hwcaps)
2463                         return table[i][1];
2464
2465         return -EINVAL;
2466 }
2467
2468 static int spi_nor_hwcaps_read2cmd(u32 hwcaps)
2469 {
2470         static const int hwcaps_read2cmd[][2] = {
2471                 { SNOR_HWCAPS_READ,             SNOR_CMD_READ },
2472                 { SNOR_HWCAPS_READ_FAST,        SNOR_CMD_READ_FAST },
2473                 { SNOR_HWCAPS_READ_1_1_1_DTR,   SNOR_CMD_READ_1_1_1_DTR },
2474                 { SNOR_HWCAPS_READ_1_1_2,       SNOR_CMD_READ_1_1_2 },
2475                 { SNOR_HWCAPS_READ_1_2_2,       SNOR_CMD_READ_1_2_2 },
2476                 { SNOR_HWCAPS_READ_2_2_2,       SNOR_CMD_READ_2_2_2 },
2477                 { SNOR_HWCAPS_READ_1_2_2_DTR,   SNOR_CMD_READ_1_2_2_DTR },
2478                 { SNOR_HWCAPS_READ_1_1_4,       SNOR_CMD_READ_1_1_4 },
2479                 { SNOR_HWCAPS_READ_1_4_4,       SNOR_CMD_READ_1_4_4 },
2480                 { SNOR_HWCAPS_READ_4_4_4,       SNOR_CMD_READ_4_4_4 },
2481                 { SNOR_HWCAPS_READ_1_4_4_DTR,   SNOR_CMD_READ_1_4_4_DTR },
2482                 { SNOR_HWCAPS_READ_1_1_8,       SNOR_CMD_READ_1_1_8 },
2483                 { SNOR_HWCAPS_READ_1_8_8,       SNOR_CMD_READ_1_8_8 },
2484                 { SNOR_HWCAPS_READ_8_8_8,       SNOR_CMD_READ_8_8_8 },
2485                 { SNOR_HWCAPS_READ_1_8_8_DTR,   SNOR_CMD_READ_1_8_8_DTR },
2486         };
2487
2488         return spi_nor_hwcaps2cmd(hwcaps, hwcaps_read2cmd,
2489                                   ARRAY_SIZE(hwcaps_read2cmd));
2490 }
2491
2492 static int spi_nor_hwcaps_pp2cmd(u32 hwcaps)
2493 {
2494         static const int hwcaps_pp2cmd[][2] = {
2495                 { SNOR_HWCAPS_PP,               SNOR_CMD_PP },
2496                 { SNOR_HWCAPS_PP_1_1_4,         SNOR_CMD_PP_1_1_4 },
2497                 { SNOR_HWCAPS_PP_1_4_4,         SNOR_CMD_PP_1_4_4 },
2498                 { SNOR_HWCAPS_PP_4_4_4,         SNOR_CMD_PP_4_4_4 },
2499                 { SNOR_HWCAPS_PP_1_1_8,         SNOR_CMD_PP_1_1_8 },
2500                 { SNOR_HWCAPS_PP_1_8_8,         SNOR_CMD_PP_1_8_8 },
2501                 { SNOR_HWCAPS_PP_8_8_8,         SNOR_CMD_PP_8_8_8 },
2502         };
2503
2504         return spi_nor_hwcaps2cmd(hwcaps, hwcaps_pp2cmd,
2505                                   ARRAY_SIZE(hwcaps_pp2cmd));
2506 }
2507
2508 static int spi_nor_select_read(struct spi_nor *nor,
2509                                const struct spi_nor_flash_parameter *params,
2510                                u32 shared_hwcaps)
2511 {
2512         int cmd, best_match = fls(shared_hwcaps & SNOR_HWCAPS_READ_MASK) - 1;
2513         const struct spi_nor_read_command *read;
2514
2515         if (best_match < 0)
2516                 return -EINVAL;
2517
2518         cmd = spi_nor_hwcaps_read2cmd(BIT(best_match));
2519         if (cmd < 0)
2520                 return -EINVAL;
2521
2522         read = &params->reads[cmd];
2523         nor->read_opcode = read->opcode;
2524         nor->read_proto = read->proto;
2525
2526         /*
2527          * In the spi-nor framework, we don't need to make the difference
2528          * between mode clock cycles and wait state clock cycles.
2529          * Indeed, the value of the mode clock cycles is used by a QSPI
2530          * flash memory to know whether it should enter or leave its 0-4-4
2531          * (Continuous Read / XIP) mode.
2532          * eXecution In Place is out of the scope of the mtd sub-system.
2533          * Hence we choose to merge both mode and wait state clock cycles
2534          * into the so called dummy clock cycles.
2535          */
2536         nor->read_dummy = read->num_mode_clocks + read->num_wait_states;
2537         return 0;
2538 }
2539
2540 static int spi_nor_select_pp(struct spi_nor *nor,
2541                              const struct spi_nor_flash_parameter *params,
2542                              u32 shared_hwcaps)
2543 {
2544         int cmd, best_match = fls(shared_hwcaps & SNOR_HWCAPS_PP_MASK) - 1;
2545         const struct spi_nor_pp_command *pp;
2546
2547         if (best_match < 0)
2548                 return -EINVAL;
2549
2550         cmd = spi_nor_hwcaps_pp2cmd(BIT(best_match));
2551         if (cmd < 0)
2552                 return -EINVAL;
2553
2554         pp = &params->page_programs[cmd];
2555         nor->program_opcode = pp->opcode;
2556         nor->write_proto = pp->proto;
2557         return 0;
2558 }
2559
2560 static int spi_nor_select_erase(struct spi_nor *nor,
2561                                 const struct flash_info *info)
2562 {
2563         struct mtd_info *mtd = &nor->mtd;
2564
2565         /* Do nothing if already configured from SFDP. */
2566         if (mtd->erasesize)
2567                 return 0;
2568
2569 #ifdef CONFIG_MTD_SPI_NOR_USE_4K_SECTORS
2570         /* prefer "small sector" erase if possible */
2571         if (info->flags & SECT_4K) {
2572                 nor->erase_opcode = SPINOR_OP_BE_4K;
2573                 mtd->erasesize = 4096;
2574         } else if (info->flags & SECT_4K_PMC) {
2575                 nor->erase_opcode = SPINOR_OP_BE_4K_PMC;
2576                 mtd->erasesize = 4096;
2577         } else
2578 #endif
2579         {
2580                 nor->erase_opcode = SPINOR_OP_SE;
2581                 mtd->erasesize = info->sector_size;
2582         }
2583         return 0;
2584 }
2585
2586 static int spi_nor_setup(struct spi_nor *nor, const struct flash_info *info,
2587                          const struct spi_nor_flash_parameter *params,
2588                          const struct spi_nor_hwcaps *hwcaps)
2589 {
2590         u32 ignored_mask, shared_mask;
2591         bool enable_quad_io;
2592         int err;
2593
2594         /*
2595          * Keep only the hardware capabilities supported by both the SPI
2596          * controller and the SPI flash memory.
2597          */
2598         shared_mask = hwcaps->mask & params->hwcaps.mask;
2599
2600         /* SPI n-n-n protocols are not supported yet. */
2601         ignored_mask = (SNOR_HWCAPS_READ_2_2_2 |
2602                         SNOR_HWCAPS_READ_4_4_4 |
2603                         SNOR_HWCAPS_READ_8_8_8 |
2604                         SNOR_HWCAPS_PP_4_4_4 |
2605                         SNOR_HWCAPS_PP_8_8_8);
2606         if (shared_mask & ignored_mask) {
2607                 dev_dbg(nor->dev,
2608                         "SPI n-n-n protocols are not supported yet.\n");
2609                 shared_mask &= ~ignored_mask;
2610         }
2611
2612         /* Select the (Fast) Read command. */
2613         err = spi_nor_select_read(nor, params, shared_mask);
2614         if (err) {
2615                 dev_err(nor->dev,
2616                         "can't select read settings supported by both the SPI controller and memory.\n");
2617                 return err;
2618         }
2619
2620         /* Select the Page Program command. */
2621         err = spi_nor_select_pp(nor, params, shared_mask);
2622         if (err) {
2623                 dev_err(nor->dev,
2624                         "can't select write settings supported by both the SPI controller and memory.\n");
2625                 return err;
2626         }
2627
2628         /* Select the Sector Erase command. */
2629         err = spi_nor_select_erase(nor, info);
2630         if (err) {
2631                 dev_err(nor->dev,
2632                         "can't select erase settings supported by both the SPI controller and memory.\n");
2633                 return err;
2634         }
2635
2636         /* Enable Quad I/O if needed. */
2637         enable_quad_io = (spi_nor_get_protocol_width(nor->read_proto) == 4 ||
2638                           spi_nor_get_protocol_width(nor->write_proto) == 4);
2639         if (enable_quad_io && params->quad_enable) {
2640                 err = params->quad_enable(nor);
2641                 if (err) {
2642                         dev_err(nor->dev, "quad mode not supported\n");
2643                         return err;
2644                 }
2645         }
2646
2647         return 0;
2648 }
2649
2650 int spi_nor_scan(struct spi_nor *nor, const char *name,
2651                  const struct spi_nor_hwcaps *hwcaps)
2652 {
2653         struct spi_nor_flash_parameter params;
2654         const struct flash_info *info = NULL;
2655         struct device *dev = nor->dev;
2656         struct mtd_info *mtd = &nor->mtd;
2657         struct device_node *np = spi_nor_get_flash_node(nor);
2658         int ret;
2659         int i;
2660
2661         ret = spi_nor_check(nor);
2662         if (ret)
2663                 return ret;
2664
2665         /* Reset SPI protocol for all commands. */
2666         nor->reg_proto = SNOR_PROTO_1_1_1;
2667         nor->read_proto = SNOR_PROTO_1_1_1;
2668         nor->write_proto = SNOR_PROTO_1_1_1;
2669
2670         if (name)
2671                 info = spi_nor_match_id(name);
2672         /* Try to auto-detect if chip name wasn't specified or not found */
2673         if (!info)
2674                 info = spi_nor_read_id(nor);
2675         if (IS_ERR_OR_NULL(info))
2676                 return -ENOENT;
2677
2678         /*
2679          * If caller has specified name of flash model that can normally be
2680          * detected using JEDEC, let's verify it.
2681          */
2682         if (name && info->id_len) {
2683                 const struct flash_info *jinfo;
2684
2685                 jinfo = spi_nor_read_id(nor);
2686                 if (IS_ERR(jinfo)) {
2687                         return PTR_ERR(jinfo);
2688                 } else if (jinfo != info) {
2689                         /*
2690                          * JEDEC knows better, so overwrite platform ID. We
2691                          * can't trust partitions any longer, but we'll let
2692                          * mtd apply them anyway, since some partitions may be
2693                          * marked read-only, and we don't want to lose that
2694                          * information, even if it's not 100% accurate.
2695                          */
2696                         dev_warn(dev, "found %s, expected %s\n",
2697                                  jinfo->name, info->name);
2698                         info = jinfo;
2699                 }
2700         }
2701
2702         mutex_init(&nor->lock);
2703
2704         /*
2705          * Make sure the XSR_RDY flag is set before calling
2706          * spi_nor_wait_till_ready(). Xilinx S3AN share MFR
2707          * with Atmel spi-nor
2708          */
2709         if (info->flags & SPI_S3AN)
2710                 nor->flags |=  SNOR_F_READY_XSR_RDY;
2711
2712         /* Parse the Serial Flash Discoverable Parameters table. */
2713         ret = spi_nor_init_params(nor, info, &params);
2714         if (ret)
2715                 return ret;
2716
2717         /*
2718          * Atmel, SST, Intel/Numonyx, and others serial NOR tend to power up
2719          * with the software protection bits set
2720          */
2721
2722         if (JEDEC_MFR(info) == SNOR_MFR_ATMEL ||
2723             JEDEC_MFR(info) == SNOR_MFR_INTEL ||
2724             JEDEC_MFR(info) == SNOR_MFR_SST ||
2725             info->flags & SPI_NOR_HAS_LOCK) {
2726                 write_enable(nor);
2727                 write_sr(nor, 0);
2728                 spi_nor_wait_till_ready(nor);
2729         }
2730
2731         if (!mtd->name)
2732                 mtd->name = dev_name(dev);
2733         mtd->priv = nor;
2734         mtd->type = MTD_NORFLASH;
2735         mtd->writesize = 1;
2736         mtd->flags = MTD_CAP_NORFLASH;
2737         mtd->size = params.size;
2738         mtd->_erase = spi_nor_erase;
2739         mtd->_read = spi_nor_read;
2740
2741         /* NOR protection support for STmicro/Micron chips and similar */
2742         if (JEDEC_MFR(info) == SNOR_MFR_MICRON ||
2743                         info->flags & SPI_NOR_HAS_LOCK) {
2744                 nor->flash_lock = stm_lock;
2745                 nor->flash_unlock = stm_unlock;
2746                 nor->flash_is_locked = stm_is_locked;
2747         }
2748
2749         if (nor->flash_lock && nor->flash_unlock && nor->flash_is_locked) {
2750                 mtd->_lock = spi_nor_lock;
2751                 mtd->_unlock = spi_nor_unlock;
2752                 mtd->_is_locked = spi_nor_is_locked;
2753         }
2754
2755         /* sst nor chips use AAI word program */
2756         if (info->flags & SST_WRITE)
2757                 mtd->_write = sst_write;
2758         else
2759                 mtd->_write = spi_nor_write;
2760
2761         if (info->flags & USE_FSR)
2762                 nor->flags |= SNOR_F_USE_FSR;
2763         if (info->flags & SPI_NOR_HAS_TB)
2764                 nor->flags |= SNOR_F_HAS_SR_TB;
2765         if (info->flags & NO_CHIP_ERASE)
2766                 nor->flags |= SNOR_F_NO_OP_CHIP_ERASE;
2767         if (info->flags & USE_CLSR)
2768                 nor->flags |= SNOR_F_USE_CLSR;
2769
2770         if (info->flags & SPI_NOR_NO_ERASE)
2771                 mtd->flags |= MTD_NO_ERASE;
2772
2773         mtd->dev.parent = dev;
2774         nor->page_size = params.page_size;
2775         mtd->writebufsize = nor->page_size;
2776
2777         if (np) {
2778                 /* If we were instantiated by DT, use it */
2779                 if (of_property_read_bool(np, "m25p,fast-read"))
2780                         params.hwcaps.mask |= SNOR_HWCAPS_READ_FAST;
2781                 else
2782                         params.hwcaps.mask &= ~SNOR_HWCAPS_READ_FAST;
2783         } else {
2784                 /* If we weren't instantiated by DT, default to fast-read */
2785                 params.hwcaps.mask |= SNOR_HWCAPS_READ_FAST;
2786         }
2787
2788         /* Some devices cannot do fast-read, no matter what DT tells us */
2789         if (info->flags & SPI_NOR_NO_FR)
2790                 params.hwcaps.mask &= ~SNOR_HWCAPS_READ_FAST;
2791
2792         /*
2793          * Configure the SPI memory:
2794          * - select op codes for (Fast) Read, Page Program and Sector Erase.
2795          * - set the number of dummy cycles (mode cycles + wait states).
2796          * - set the SPI protocols for register and memory accesses.
2797          * - set the Quad Enable bit if needed (required by SPI x-y-4 protos).
2798          */
2799         ret = spi_nor_setup(nor, info, &params, hwcaps);
2800         if (ret)
2801                 return ret;
2802
2803         if (nor->addr_width) {
2804                 /* already configured from SFDP */
2805         } else if (info->addr_width) {
2806                 nor->addr_width = info->addr_width;
2807         } else if (mtd->size > 0x1000000) {
2808                 /* enable 4-byte addressing if the device exceeds 16MiB */
2809                 nor->addr_width = 4;
2810                 if (JEDEC_MFR(info) == SNOR_MFR_SPANSION ||
2811                     info->flags & SPI_NOR_4B_OPCODES)
2812                         spi_nor_set_4byte_opcodes(nor, info);
2813                 else
2814                         set_4byte(nor, info, 1);
2815         } else {
2816                 nor->addr_width = 3;
2817         }
2818
2819         if (nor->addr_width > SPI_NOR_MAX_ADDR_WIDTH) {
2820                 dev_err(dev, "address width is too large: %u\n",
2821                         nor->addr_width);
2822                 return -EINVAL;
2823         }
2824
2825         if (info->flags & SPI_S3AN) {
2826                 ret = s3an_nor_scan(info, nor);
2827                 if (ret)
2828                         return ret;
2829         }
2830
2831         dev_info(dev, "%s (%lld Kbytes)\n", info->name,
2832                         (long long)mtd->size >> 10);
2833
2834         dev_dbg(dev,
2835                 "mtd .name = %s, .size = 0x%llx (%lldMiB), "
2836                 ".erasesize = 0x%.8x (%uKiB) .numeraseregions = %d\n",
2837                 mtd->name, (long long)mtd->size, (long long)(mtd->size >> 20),
2838                 mtd->erasesize, mtd->erasesize / 1024, mtd->numeraseregions);
2839
2840         if (mtd->numeraseregions)
2841                 for (i = 0; i < mtd->numeraseregions; i++)
2842                         dev_dbg(dev,
2843                                 "mtd.eraseregions[%d] = { .offset = 0x%llx, "
2844                                 ".erasesize = 0x%.8x (%uKiB), "
2845                                 ".numblocks = %d }\n",
2846                                 i, (long long)mtd->eraseregions[i].offset,
2847                                 mtd->eraseregions[i].erasesize,
2848                                 mtd->eraseregions[i].erasesize / 1024,
2849                                 mtd->eraseregions[i].numblocks);
2850         return 0;
2851 }
2852 EXPORT_SYMBOL_GPL(spi_nor_scan);
2853
2854 static const struct flash_info *spi_nor_match_id(const char *name)
2855 {
2856         const struct flash_info *id = spi_nor_ids;
2857
2858         while (id->name) {
2859                 if (!strcmp(name, id->name))
2860                         return id;
2861                 id++;
2862         }
2863         return NULL;
2864 }
2865
2866 MODULE_LICENSE("GPL");
2867 MODULE_AUTHOR("Huang Shijie <shijie8@gmail.com>");
2868 MODULE_AUTHOR("Mike Lavender");
2869 MODULE_DESCRIPTION("framework for SPI NOR");