]> asedeno.scripts.mit.edu Git - linux.git/blob - drivers/mtd/spi-nor/spi-nor.c
Merge tag 'mtd/for-5.6' of git://git.kernel.org/pub/scm/linux/kernel/git/mtd/linux
[linux.git] / drivers / mtd / spi-nor / spi-nor.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Based on m25p80.c, by Mike Lavender (mike@steroidmicros.com), with
4  * influence from lart.c (Abraham Van Der Merwe) and mtd_dataflash.c
5  *
6  * Copyright (C) 2005, Intec Automation Inc.
7  * Copyright (C) 2014, Freescale Semiconductor, Inc.
8  */
9
10 #include <linux/err.h>
11 #include <linux/errno.h>
12 #include <linux/module.h>
13 #include <linux/device.h>
14 #include <linux/mutex.h>
15 #include <linux/math64.h>
16 #include <linux/sizes.h>
17 #include <linux/slab.h>
18 #include <linux/sort.h>
19
20 #include <linux/mtd/mtd.h>
21 #include <linux/of_platform.h>
22 #include <linux/sched/task_stack.h>
23 #include <linux/spi/flash.h>
24 #include <linux/mtd/spi-nor.h>
25
26 /* Define max times to check status register before we give up. */
27
28 /*
29  * For everything but full-chip erase; probably could be much smaller, but kept
30  * around for safety for now
31  */
32 #define DEFAULT_READY_WAIT_JIFFIES              (40UL * HZ)
33
34 /*
35  * For full-chip erase, calibrated to a 2MB flash (M25P16); should be scaled up
36  * for larger flash
37  */
38 #define CHIP_ERASE_2MB_READY_WAIT_JIFFIES       (40UL * HZ)
39
40 #define SPI_NOR_MAX_ID_LEN      6
41 #define SPI_NOR_MAX_ADDR_WIDTH  4
42
43 struct sfdp_parameter_header {
44         u8              id_lsb;
45         u8              minor;
46         u8              major;
47         u8              length; /* in double words */
48         u8              parameter_table_pointer[3]; /* byte address */
49         u8              id_msb;
50 };
51
52 #define SFDP_PARAM_HEADER_ID(p) (((p)->id_msb << 8) | (p)->id_lsb)
53 #define SFDP_PARAM_HEADER_PTP(p) \
54         (((p)->parameter_table_pointer[2] << 16) | \
55          ((p)->parameter_table_pointer[1] <<  8) | \
56          ((p)->parameter_table_pointer[0] <<  0))
57
58 #define SFDP_BFPT_ID            0xff00  /* Basic Flash Parameter Table */
59 #define SFDP_SECTOR_MAP_ID      0xff81  /* Sector Map Table */
60 #define SFDP_4BAIT_ID           0xff84  /* 4-byte Address Instruction Table */
61
62 #define SFDP_SIGNATURE          0x50444653U
63 #define SFDP_JESD216_MAJOR      1
64 #define SFDP_JESD216_MINOR      0
65 #define SFDP_JESD216A_MINOR     5
66 #define SFDP_JESD216B_MINOR     6
67
68 struct sfdp_header {
69         u32             signature; /* Ox50444653U <=> "SFDP" */
70         u8              minor;
71         u8              major;
72         u8              nph; /* 0-base number of parameter headers */
73         u8              unused;
74
75         /* Basic Flash Parameter Table. */
76         struct sfdp_parameter_header    bfpt_header;
77 };
78
79 /* Basic Flash Parameter Table */
80
81 /*
82  * JESD216 rev B defines a Basic Flash Parameter Table of 16 DWORDs.
83  * They are indexed from 1 but C arrays are indexed from 0.
84  */
85 #define BFPT_DWORD(i)           ((i) - 1)
86 #define BFPT_DWORD_MAX          16
87
88 /* The first version of JESD216 defined only 9 DWORDs. */
89 #define BFPT_DWORD_MAX_JESD216                  9
90
91 /* 1st DWORD. */
92 #define BFPT_DWORD1_FAST_READ_1_1_2             BIT(16)
93 #define BFPT_DWORD1_ADDRESS_BYTES_MASK          GENMASK(18, 17)
94 #define BFPT_DWORD1_ADDRESS_BYTES_3_ONLY        (0x0UL << 17)
95 #define BFPT_DWORD1_ADDRESS_BYTES_3_OR_4        (0x1UL << 17)
96 #define BFPT_DWORD1_ADDRESS_BYTES_4_ONLY        (0x2UL << 17)
97 #define BFPT_DWORD1_DTR                         BIT(19)
98 #define BFPT_DWORD1_FAST_READ_1_2_2             BIT(20)
99 #define BFPT_DWORD1_FAST_READ_1_4_4             BIT(21)
100 #define BFPT_DWORD1_FAST_READ_1_1_4             BIT(22)
101
102 /* 5th DWORD. */
103 #define BFPT_DWORD5_FAST_READ_2_2_2             BIT(0)
104 #define BFPT_DWORD5_FAST_READ_4_4_4             BIT(4)
105
106 /* 11th DWORD. */
107 #define BFPT_DWORD11_PAGE_SIZE_SHIFT            4
108 #define BFPT_DWORD11_PAGE_SIZE_MASK             GENMASK(7, 4)
109
110 /* 15th DWORD. */
111
112 /*
113  * (from JESD216 rev B)
114  * Quad Enable Requirements (QER):
115  * - 000b: Device does not have a QE bit. Device detects 1-1-4 and 1-4-4
116  *         reads based on instruction. DQ3/HOLD# functions are hold during
117  *         instruction phase.
118  * - 001b: QE is bit 1 of status register 2. It is set via Write Status with
119  *         two data bytes where bit 1 of the second byte is one.
120  *         [...]
121  *         Writing only one byte to the status register has the side-effect of
122  *         clearing status register 2, including the QE bit. The 100b code is
123  *         used if writing one byte to the status register does not modify
124  *         status register 2.
125  * - 010b: QE is bit 6 of status register 1. It is set via Write Status with
126  *         one data byte where bit 6 is one.
127  *         [...]
128  * - 011b: QE is bit 7 of status register 2. It is set via Write status
129  *         register 2 instruction 3Eh with one data byte where bit 7 is one.
130  *         [...]
131  *         The status register 2 is read using instruction 3Fh.
132  * - 100b: QE is bit 1 of status register 2. It is set via Write Status with
133  *         two data bytes where bit 1 of the second byte is one.
134  *         [...]
135  *         In contrast to the 001b code, writing one byte to the status
136  *         register does not modify status register 2.
137  * - 101b: QE is bit 1 of status register 2. Status register 1 is read using
138  *         Read Status instruction 05h. Status register2 is read using
139  *         instruction 35h. QE is set via Write Status instruction 01h with
140  *         two data bytes where bit 1 of the second byte is one.
141  *         [...]
142  */
143 #define BFPT_DWORD15_QER_MASK                   GENMASK(22, 20)
144 #define BFPT_DWORD15_QER_NONE                   (0x0UL << 20) /* Micron */
145 #define BFPT_DWORD15_QER_SR2_BIT1_BUGGY         (0x1UL << 20)
146 #define BFPT_DWORD15_QER_SR1_BIT6               (0x2UL << 20) /* Macronix */
147 #define BFPT_DWORD15_QER_SR2_BIT7               (0x3UL << 20)
148 #define BFPT_DWORD15_QER_SR2_BIT1_NO_RD         (0x4UL << 20)
149 #define BFPT_DWORD15_QER_SR2_BIT1               (0x5UL << 20) /* Spansion */
150
151 struct sfdp_bfpt {
152         u32     dwords[BFPT_DWORD_MAX];
153 };
154
155 /**
156  * struct spi_nor_fixups - SPI NOR fixup hooks
157  * @default_init: called after default flash parameters init. Used to tweak
158  *                flash parameters when information provided by the flash_info
159  *                table is incomplete or wrong.
160  * @post_bfpt: called after the BFPT table has been parsed
161  * @post_sfdp: called after SFDP has been parsed (is also called for SPI NORs
162  *             that do not support RDSFDP). Typically used to tweak various
163  *             parameters that could not be extracted by other means (i.e.
164  *             when information provided by the SFDP/flash_info tables are
165  *             incomplete or wrong).
166  *
167  * Those hooks can be used to tweak the SPI NOR configuration when the SFDP
168  * table is broken or not available.
169  */
170 struct spi_nor_fixups {
171         void (*default_init)(struct spi_nor *nor);
172         int (*post_bfpt)(struct spi_nor *nor,
173                          const struct sfdp_parameter_header *bfpt_header,
174                          const struct sfdp_bfpt *bfpt,
175                          struct spi_nor_flash_parameter *params);
176         void (*post_sfdp)(struct spi_nor *nor);
177 };
178
179 struct flash_info {
180         char            *name;
181
182         /*
183          * This array stores the ID bytes.
184          * The first three bytes are the JEDIC ID.
185          * JEDEC ID zero means "no ID" (mostly older chips).
186          */
187         u8              id[SPI_NOR_MAX_ID_LEN];
188         u8              id_len;
189
190         /* The size listed here is what works with SPINOR_OP_SE, which isn't
191          * necessarily called a "sector" by the vendor.
192          */
193         unsigned        sector_size;
194         u16             n_sectors;
195
196         u16             page_size;
197         u16             addr_width;
198
199         u32             flags;
200 #define SECT_4K                 BIT(0)  /* SPINOR_OP_BE_4K works uniformly */
201 #define SPI_NOR_NO_ERASE        BIT(1)  /* No erase command needed */
202 #define SST_WRITE               BIT(2)  /* use SST byte programming */
203 #define SPI_NOR_NO_FR           BIT(3)  /* Can't do fastread */
204 #define SECT_4K_PMC             BIT(4)  /* SPINOR_OP_BE_4K_PMC works uniformly */
205 #define SPI_NOR_DUAL_READ       BIT(5)  /* Flash supports Dual Read */
206 #define SPI_NOR_QUAD_READ       BIT(6)  /* Flash supports Quad Read */
207 #define USE_FSR                 BIT(7)  /* use flag status register */
208 #define SPI_NOR_HAS_LOCK        BIT(8)  /* Flash supports lock/unlock via SR */
209 #define SPI_NOR_HAS_TB          BIT(9)  /*
210                                          * Flash SR has Top/Bottom (TB) protect
211                                          * bit. Must be used with
212                                          * SPI_NOR_HAS_LOCK.
213                                          */
214 #define SPI_NOR_XSR_RDY         BIT(10) /*
215                                          * S3AN flashes have specific opcode to
216                                          * read the status register.
217                                          * Flags SPI_NOR_XSR_RDY and SPI_S3AN
218                                          * use the same bit as one implies the
219                                          * other, but we will get rid of
220                                          * SPI_S3AN soon.
221                                          */
222 #define SPI_S3AN                BIT(10) /*
223                                          * Xilinx Spartan 3AN In-System Flash
224                                          * (MFR cannot be used for probing
225                                          * because it has the same value as
226                                          * ATMEL flashes)
227                                          */
228 #define SPI_NOR_4B_OPCODES      BIT(11) /*
229                                          * Use dedicated 4byte address op codes
230                                          * to support memory size above 128Mib.
231                                          */
232 #define NO_CHIP_ERASE           BIT(12) /* Chip does not support chip erase */
233 #define SPI_NOR_SKIP_SFDP       BIT(13) /* Skip parsing of SFDP tables */
234 #define USE_CLSR                BIT(14) /* use CLSR command */
235 #define SPI_NOR_OCTAL_READ      BIT(15) /* Flash supports Octal Read */
236 #define SPI_NOR_TB_SR_BIT6      BIT(16) /*
237                                          * Top/Bottom (TB) is bit 6 of
238                                          * status register. Must be used with
239                                          * SPI_NOR_HAS_TB.
240                                          */
241
242         /* Part specific fixup hooks. */
243         const struct spi_nor_fixups *fixups;
244 };
245
246 #define JEDEC_MFR(info) ((info)->id[0])
247
248 /**
249  * spi_nor_spimem_xfer_data() - helper function to read/write data to
250  *                              flash's memory region
251  * @nor:        pointer to 'struct spi_nor'
252  * @op:         pointer to 'struct spi_mem_op' template for transfer
253  *
254  * Return: number of bytes transferred on success, -errno otherwise
255  */
256 static ssize_t spi_nor_spimem_xfer_data(struct spi_nor *nor,
257                                         struct spi_mem_op *op)
258 {
259         bool usebouncebuf = false;
260         void *rdbuf = NULL;
261         const void *buf;
262         int ret;
263
264         if (op->data.dir == SPI_MEM_DATA_IN)
265                 buf = op->data.buf.in;
266         else
267                 buf = op->data.buf.out;
268
269         if (object_is_on_stack(buf) || !virt_addr_valid(buf))
270                 usebouncebuf = true;
271
272         if (usebouncebuf) {
273                 if (op->data.nbytes > nor->bouncebuf_size)
274                         op->data.nbytes = nor->bouncebuf_size;
275
276                 if (op->data.dir == SPI_MEM_DATA_IN) {
277                         rdbuf = op->data.buf.in;
278                         op->data.buf.in = nor->bouncebuf;
279                 } else {
280                         op->data.buf.out = nor->bouncebuf;
281                         memcpy(nor->bouncebuf, buf,
282                                op->data.nbytes);
283                 }
284         }
285
286         ret = spi_mem_adjust_op_size(nor->spimem, op);
287         if (ret)
288                 return ret;
289
290         ret = spi_mem_exec_op(nor->spimem, op);
291         if (ret)
292                 return ret;
293
294         if (usebouncebuf && op->data.dir == SPI_MEM_DATA_IN)
295                 memcpy(rdbuf, nor->bouncebuf, op->data.nbytes);
296
297         return op->data.nbytes;
298 }
299
300 /**
301  * spi_nor_spimem_read_data() - read data from flash's memory region via
302  *                              spi-mem
303  * @nor:        pointer to 'struct spi_nor'
304  * @from:       offset to read from
305  * @len:        number of bytes to read
306  * @buf:        pointer to dst buffer
307  *
308  * Return: number of bytes read successfully, -errno otherwise
309  */
310 static ssize_t spi_nor_spimem_read_data(struct spi_nor *nor, loff_t from,
311                                         size_t len, u8 *buf)
312 {
313         struct spi_mem_op op =
314                 SPI_MEM_OP(SPI_MEM_OP_CMD(nor->read_opcode, 1),
315                            SPI_MEM_OP_ADDR(nor->addr_width, from, 1),
316                            SPI_MEM_OP_DUMMY(nor->read_dummy, 1),
317                            SPI_MEM_OP_DATA_IN(len, buf, 1));
318
319         /* get transfer protocols. */
320         op.cmd.buswidth = spi_nor_get_protocol_inst_nbits(nor->read_proto);
321         op.addr.buswidth = spi_nor_get_protocol_addr_nbits(nor->read_proto);
322         op.dummy.buswidth = op.addr.buswidth;
323         op.data.buswidth = spi_nor_get_protocol_data_nbits(nor->read_proto);
324
325         /* convert the dummy cycles to the number of bytes */
326         op.dummy.nbytes = (nor->read_dummy * op.dummy.buswidth) / 8;
327
328         return spi_nor_spimem_xfer_data(nor, &op);
329 }
330
331 /**
332  * spi_nor_read_data() - read data from flash memory
333  * @nor:        pointer to 'struct spi_nor'
334  * @from:       offset to read from
335  * @len:        number of bytes to read
336  * @buf:        pointer to dst buffer
337  *
338  * Return: number of bytes read successfully, -errno otherwise
339  */
340 static ssize_t spi_nor_read_data(struct spi_nor *nor, loff_t from, size_t len,
341                                  u8 *buf)
342 {
343         if (nor->spimem)
344                 return spi_nor_spimem_read_data(nor, from, len, buf);
345
346         return nor->controller_ops->read(nor, from, len, buf);
347 }
348
349 /**
350  * spi_nor_spimem_write_data() - write data to flash memory via
351  *                               spi-mem
352  * @nor:        pointer to 'struct spi_nor'
353  * @to:         offset to write to
354  * @len:        number of bytes to write
355  * @buf:        pointer to src buffer
356  *
357  * Return: number of bytes written successfully, -errno otherwise
358  */
359 static ssize_t spi_nor_spimem_write_data(struct spi_nor *nor, loff_t to,
360                                          size_t len, const u8 *buf)
361 {
362         struct spi_mem_op op =
363                 SPI_MEM_OP(SPI_MEM_OP_CMD(nor->program_opcode, 1),
364                            SPI_MEM_OP_ADDR(nor->addr_width, to, 1),
365                            SPI_MEM_OP_NO_DUMMY,
366                            SPI_MEM_OP_DATA_OUT(len, buf, 1));
367
368         op.cmd.buswidth = spi_nor_get_protocol_inst_nbits(nor->write_proto);
369         op.addr.buswidth = spi_nor_get_protocol_addr_nbits(nor->write_proto);
370         op.data.buswidth = spi_nor_get_protocol_data_nbits(nor->write_proto);
371
372         if (nor->program_opcode == SPINOR_OP_AAI_WP && nor->sst_write_second)
373                 op.addr.nbytes = 0;
374
375         return spi_nor_spimem_xfer_data(nor, &op);
376 }
377
378 /**
379  * spi_nor_write_data() - write data to flash memory
380  * @nor:        pointer to 'struct spi_nor'
381  * @to:         offset to write to
382  * @len:        number of bytes to write
383  * @buf:        pointer to src buffer
384  *
385  * Return: number of bytes written successfully, -errno otherwise
386  */
387 static ssize_t spi_nor_write_data(struct spi_nor *nor, loff_t to, size_t len,
388                                   const u8 *buf)
389 {
390         if (nor->spimem)
391                 return spi_nor_spimem_write_data(nor, to, len, buf);
392
393         return nor->controller_ops->write(nor, to, len, buf);
394 }
395
396 /**
397  * spi_nor_write_enable() - Set write enable latch with Write Enable command.
398  * @nor:        pointer to 'struct spi_nor'.
399  *
400  * Return: 0 on success, -errno otherwise.
401  */
402 static int spi_nor_write_enable(struct spi_nor *nor)
403 {
404         int ret;
405
406         if (nor->spimem) {
407                 struct spi_mem_op op =
408                         SPI_MEM_OP(SPI_MEM_OP_CMD(SPINOR_OP_WREN, 1),
409                                    SPI_MEM_OP_NO_ADDR,
410                                    SPI_MEM_OP_NO_DUMMY,
411                                    SPI_MEM_OP_NO_DATA);
412
413                 ret = spi_mem_exec_op(nor->spimem, &op);
414         } else {
415                 ret = nor->controller_ops->write_reg(nor, SPINOR_OP_WREN,
416                                                      NULL, 0);
417         }
418
419         if (ret)
420                 dev_dbg(nor->dev, "error %d on Write Enable\n", ret);
421
422         return ret;
423 }
424
425 /**
426  * spi_nor_write_disable() - Send Write Disable instruction to the chip.
427  * @nor:        pointer to 'struct spi_nor'.
428  *
429  * Return: 0 on success, -errno otherwise.
430  */
431 static int spi_nor_write_disable(struct spi_nor *nor)
432 {
433         int ret;
434
435         if (nor->spimem) {
436                 struct spi_mem_op op =
437                         SPI_MEM_OP(SPI_MEM_OP_CMD(SPINOR_OP_WRDI, 1),
438                                    SPI_MEM_OP_NO_ADDR,
439                                    SPI_MEM_OP_NO_DUMMY,
440                                    SPI_MEM_OP_NO_DATA);
441
442                 ret = spi_mem_exec_op(nor->spimem, &op);
443         } else {
444                 ret = nor->controller_ops->write_reg(nor, SPINOR_OP_WRDI,
445                                                      NULL, 0);
446         }
447
448         if (ret)
449                 dev_dbg(nor->dev, "error %d on Write Disable\n", ret);
450
451         return ret;
452 }
453
454 /**
455  * spi_nor_read_sr() - Read the Status Register.
456  * @nor:        pointer to 'struct spi_nor'.
457  * @sr:         pointer to a DMA-able buffer where the value of the
458  *              Status Register will be written.
459  *
460  * Return: 0 on success, -errno otherwise.
461  */
462 static int spi_nor_read_sr(struct spi_nor *nor, u8 *sr)
463 {
464         int ret;
465
466         if (nor->spimem) {
467                 struct spi_mem_op op =
468                         SPI_MEM_OP(SPI_MEM_OP_CMD(SPINOR_OP_RDSR, 1),
469                                    SPI_MEM_OP_NO_ADDR,
470                                    SPI_MEM_OP_NO_DUMMY,
471                                    SPI_MEM_OP_DATA_IN(1, sr, 1));
472
473                 ret = spi_mem_exec_op(nor->spimem, &op);
474         } else {
475                 ret = nor->controller_ops->read_reg(nor, SPINOR_OP_RDSR,
476                                                     sr, 1);
477         }
478
479         if (ret)
480                 dev_dbg(nor->dev, "error %d reading SR\n", ret);
481
482         return ret;
483 }
484
485 /**
486  * spi_nor_read_fsr() - Read the Flag Status Register.
487  * @nor:        pointer to 'struct spi_nor'
488  * @fsr:        pointer to a DMA-able buffer where the value of the
489  *              Flag Status Register will be written.
490  *
491  * Return: 0 on success, -errno otherwise.
492  */
493 static int spi_nor_read_fsr(struct spi_nor *nor, u8 *fsr)
494 {
495         int ret;
496
497         if (nor->spimem) {
498                 struct spi_mem_op op =
499                         SPI_MEM_OP(SPI_MEM_OP_CMD(SPINOR_OP_RDFSR, 1),
500                                    SPI_MEM_OP_NO_ADDR,
501                                    SPI_MEM_OP_NO_DUMMY,
502                                    SPI_MEM_OP_DATA_IN(1, fsr, 1));
503
504                 ret = spi_mem_exec_op(nor->spimem, &op);
505         } else {
506                 ret = nor->controller_ops->read_reg(nor, SPINOR_OP_RDFSR,
507                                                     fsr, 1);
508         }
509
510         if (ret)
511                 dev_dbg(nor->dev, "error %d reading FSR\n", ret);
512
513         return ret;
514 }
515
516 /**
517  * spi_nor_read_cr() - Read the Configuration Register using the
518  * SPINOR_OP_RDCR (35h) command.
519  * @nor:        pointer to 'struct spi_nor'
520  * @cr:         pointer to a DMA-able buffer where the value of the
521  *              Configuration Register will be written.
522  *
523  * Return: 0 on success, -errno otherwise.
524  */
525 static int spi_nor_read_cr(struct spi_nor *nor, u8 *cr)
526 {
527         int ret;
528
529         if (nor->spimem) {
530                 struct spi_mem_op op =
531                         SPI_MEM_OP(SPI_MEM_OP_CMD(SPINOR_OP_RDCR, 1),
532                                    SPI_MEM_OP_NO_ADDR,
533                                    SPI_MEM_OP_NO_DUMMY,
534                                    SPI_MEM_OP_DATA_IN(1, cr, 1));
535
536                 ret = spi_mem_exec_op(nor->spimem, &op);
537         } else {
538                 ret = nor->controller_ops->read_reg(nor, SPINOR_OP_RDCR, cr, 1);
539         }
540
541         if (ret)
542                 dev_dbg(nor->dev, "error %d reading CR\n", ret);
543
544         return ret;
545 }
546
547 /**
548  * macronix_set_4byte() - Set 4-byte address mode for Macronix flashes.
549  * @nor:        pointer to 'struct spi_nor'.
550  * @enable:     true to enter the 4-byte address mode, false to exit the 4-byte
551  *              address mode.
552  *
553  * Return: 0 on success, -errno otherwise.
554  */
555 static int macronix_set_4byte(struct spi_nor *nor, bool enable)
556 {
557         int ret;
558
559         if (nor->spimem) {
560                 struct spi_mem_op op =
561                         SPI_MEM_OP(SPI_MEM_OP_CMD(enable ?
562                                                   SPINOR_OP_EN4B :
563                                                   SPINOR_OP_EX4B,
564                                                   1),
565                                   SPI_MEM_OP_NO_ADDR,
566                                   SPI_MEM_OP_NO_DUMMY,
567                                   SPI_MEM_OP_NO_DATA);
568
569                 ret = spi_mem_exec_op(nor->spimem, &op);
570         } else {
571                 ret = nor->controller_ops->write_reg(nor,
572                                                      enable ? SPINOR_OP_EN4B :
573                                                               SPINOR_OP_EX4B,
574                                                      NULL, 0);
575         }
576
577         if (ret)
578                 dev_dbg(nor->dev, "error %d setting 4-byte mode\n", ret);
579
580         return ret;
581 }
582
583 /**
584  * st_micron_set_4byte() - Set 4-byte address mode for ST and Micron flashes.
585  * @nor:        pointer to 'struct spi_nor'.
586  * @enable:     true to enter the 4-byte address mode, false to exit the 4-byte
587  *              address mode.
588  *
589  * Return: 0 on success, -errno otherwise.
590  */
591 static int st_micron_set_4byte(struct spi_nor *nor, bool enable)
592 {
593         int ret;
594
595         ret = spi_nor_write_enable(nor);
596         if (ret)
597                 return ret;
598
599         ret = macronix_set_4byte(nor, enable);
600         if (ret)
601                 return ret;
602
603         return spi_nor_write_disable(nor);
604 }
605
606 /**
607  * spansion_set_4byte() - Set 4-byte address mode for Spansion flashes.
608  * @nor:        pointer to 'struct spi_nor'.
609  * @enable:     true to enter the 4-byte address mode, false to exit the 4-byte
610  *              address mode.
611  *
612  * Return: 0 on success, -errno otherwise.
613  */
614 static int spansion_set_4byte(struct spi_nor *nor, bool enable)
615 {
616         int ret;
617
618         nor->bouncebuf[0] = enable << 7;
619
620         if (nor->spimem) {
621                 struct spi_mem_op op =
622                         SPI_MEM_OP(SPI_MEM_OP_CMD(SPINOR_OP_BRWR, 1),
623                                    SPI_MEM_OP_NO_ADDR,
624                                    SPI_MEM_OP_NO_DUMMY,
625                                    SPI_MEM_OP_DATA_OUT(1, nor->bouncebuf, 1));
626
627                 ret = spi_mem_exec_op(nor->spimem, &op);
628         } else {
629                 ret = nor->controller_ops->write_reg(nor, SPINOR_OP_BRWR,
630                                                      nor->bouncebuf, 1);
631         }
632
633         if (ret)
634                 dev_dbg(nor->dev, "error %d setting 4-byte mode\n", ret);
635
636         return ret;
637 }
638
639 /**
640  * spi_nor_write_ear() - Write Extended Address Register.
641  * @nor:        pointer to 'struct spi_nor'.
642  * @ear:        value to write to the Extended Address Register.
643  *
644  * Return: 0 on success, -errno otherwise.
645  */
646 static int spi_nor_write_ear(struct spi_nor *nor, u8 ear)
647 {
648         int ret;
649
650         nor->bouncebuf[0] = ear;
651
652         if (nor->spimem) {
653                 struct spi_mem_op op =
654                         SPI_MEM_OP(SPI_MEM_OP_CMD(SPINOR_OP_WREAR, 1),
655                                    SPI_MEM_OP_NO_ADDR,
656                                    SPI_MEM_OP_NO_DUMMY,
657                                    SPI_MEM_OP_DATA_OUT(1, nor->bouncebuf, 1));
658
659                 ret = spi_mem_exec_op(nor->spimem, &op);
660         } else {
661                 ret = nor->controller_ops->write_reg(nor, SPINOR_OP_WREAR,
662                                                      nor->bouncebuf, 1);
663         }
664
665         if (ret)
666                 dev_dbg(nor->dev, "error %d writing EAR\n", ret);
667
668         return ret;
669 }
670
671 /**
672  * winbond_set_4byte() - Set 4-byte address mode for Winbond flashes.
673  * @nor:        pointer to 'struct spi_nor'.
674  * @enable:     true to enter the 4-byte address mode, false to exit the 4-byte
675  *              address mode.
676  *
677  * Return: 0 on success, -errno otherwise.
678  */
679 static int winbond_set_4byte(struct spi_nor *nor, bool enable)
680 {
681         int ret;
682
683         ret = macronix_set_4byte(nor, enable);
684         if (ret || enable)
685                 return ret;
686
687         /*
688          * On Winbond W25Q256FV, leaving 4byte mode causes the Extended Address
689          * Register to be set to 1, so all 3-byte-address reads come from the
690          * second 16M. We must clear the register to enable normal behavior.
691          */
692         ret = spi_nor_write_enable(nor);
693         if (ret)
694                 return ret;
695
696         ret = spi_nor_write_ear(nor, 0);
697         if (ret)
698                 return ret;
699
700         return spi_nor_write_disable(nor);
701 }
702
703 /**
704  * spi_nor_xread_sr() - Read the Status Register on S3AN flashes.
705  * @nor:        pointer to 'struct spi_nor'.
706  * @sr:         pointer to a DMA-able buffer where the value of the
707  *              Status Register will be written.
708  *
709  * Return: 0 on success, -errno otherwise.
710  */
711 static int spi_nor_xread_sr(struct spi_nor *nor, u8 *sr)
712 {
713         int ret;
714
715         if (nor->spimem) {
716                 struct spi_mem_op op =
717                         SPI_MEM_OP(SPI_MEM_OP_CMD(SPINOR_OP_XRDSR, 1),
718                                    SPI_MEM_OP_NO_ADDR,
719                                    SPI_MEM_OP_NO_DUMMY,
720                                    SPI_MEM_OP_DATA_IN(1, sr, 1));
721
722                 ret = spi_mem_exec_op(nor->spimem, &op);
723         } else {
724                 ret = nor->controller_ops->read_reg(nor, SPINOR_OP_XRDSR,
725                                                     sr, 1);
726         }
727
728         if (ret)
729                 dev_dbg(nor->dev, "error %d reading XRDSR\n", ret);
730
731         return ret;
732 }
733
734 /**
735  * s3an_sr_ready() - Query the Status Register of the S3AN flash to see if the
736  * flash is ready for new commands.
737  * @nor:        pointer to 'struct spi_nor'.
738  *
739  * Return: 0 on success, -errno otherwise.
740  */
741 static int s3an_sr_ready(struct spi_nor *nor)
742 {
743         int ret;
744
745         ret = spi_nor_xread_sr(nor, nor->bouncebuf);
746         if (ret)
747                 return ret;
748
749         return !!(nor->bouncebuf[0] & XSR_RDY);
750 }
751
752 /**
753  * spi_nor_clear_sr() - Clear the Status Register.
754  * @nor:        pointer to 'struct spi_nor'.
755  */
756 static void spi_nor_clear_sr(struct spi_nor *nor)
757 {
758         int ret;
759
760         if (nor->spimem) {
761                 struct spi_mem_op op =
762                         SPI_MEM_OP(SPI_MEM_OP_CMD(SPINOR_OP_CLSR, 1),
763                                    SPI_MEM_OP_NO_ADDR,
764                                    SPI_MEM_OP_NO_DUMMY,
765                                    SPI_MEM_OP_NO_DATA);
766
767                 ret = spi_mem_exec_op(nor->spimem, &op);
768         } else {
769                 ret = nor->controller_ops->write_reg(nor, SPINOR_OP_CLSR,
770                                                      NULL, 0);
771         }
772
773         if (ret)
774                 dev_dbg(nor->dev, "error %d clearing SR\n", ret);
775 }
776
777 /**
778  * spi_nor_sr_ready() - Query the Status Register to see if the flash is ready
779  * for new commands.
780  * @nor:        pointer to 'struct spi_nor'.
781  *
782  * Return: 0 on success, -errno otherwise.
783  */
784 static int spi_nor_sr_ready(struct spi_nor *nor)
785 {
786         int ret = spi_nor_read_sr(nor, nor->bouncebuf);
787
788         if (ret)
789                 return ret;
790
791         if (nor->flags & SNOR_F_USE_CLSR &&
792             nor->bouncebuf[0] & (SR_E_ERR | SR_P_ERR)) {
793                 if (nor->bouncebuf[0] & SR_E_ERR)
794                         dev_err(nor->dev, "Erase Error occurred\n");
795                 else
796                         dev_err(nor->dev, "Programming Error occurred\n");
797
798                 spi_nor_clear_sr(nor);
799                 return -EIO;
800         }
801
802         return !(nor->bouncebuf[0] & SR_WIP);
803 }
804
805 /**
806  * spi_nor_clear_fsr() - Clear the Flag Status Register.
807  * @nor:        pointer to 'struct spi_nor'.
808  */
809 static void spi_nor_clear_fsr(struct spi_nor *nor)
810 {
811         int ret;
812
813         if (nor->spimem) {
814                 struct spi_mem_op op =
815                         SPI_MEM_OP(SPI_MEM_OP_CMD(SPINOR_OP_CLFSR, 1),
816                                    SPI_MEM_OP_NO_ADDR,
817                                    SPI_MEM_OP_NO_DUMMY,
818                                    SPI_MEM_OP_NO_DATA);
819
820                 ret = spi_mem_exec_op(nor->spimem, &op);
821         } else {
822                 ret = nor->controller_ops->write_reg(nor, SPINOR_OP_CLFSR,
823                                                      NULL, 0);
824         }
825
826         if (ret)
827                 dev_dbg(nor->dev, "error %d clearing FSR\n", ret);
828 }
829
830 /**
831  * spi_nor_fsr_ready() - Query the Flag Status Register to see if the flash is
832  * ready for new commands.
833  * @nor:        pointer to 'struct spi_nor'.
834  *
835  * Return: 0 on success, -errno otherwise.
836  */
837 static int spi_nor_fsr_ready(struct spi_nor *nor)
838 {
839         int ret = spi_nor_read_fsr(nor, nor->bouncebuf);
840
841         if (ret)
842                 return ret;
843
844         if (nor->bouncebuf[0] & (FSR_E_ERR | FSR_P_ERR)) {
845                 if (nor->bouncebuf[0] & FSR_E_ERR)
846                         dev_err(nor->dev, "Erase operation failed.\n");
847                 else
848                         dev_err(nor->dev, "Program operation failed.\n");
849
850                 if (nor->bouncebuf[0] & FSR_PT_ERR)
851                         dev_err(nor->dev,
852                         "Attempted to modify a protected sector.\n");
853
854                 spi_nor_clear_fsr(nor);
855                 return -EIO;
856         }
857
858         return nor->bouncebuf[0] & FSR_READY;
859 }
860
861 /**
862  * spi_nor_ready() - Query the flash to see if it is ready for new commands.
863  * @nor:        pointer to 'struct spi_nor'.
864  *
865  * Return: 0 on success, -errno otherwise.
866  */
867 static int spi_nor_ready(struct spi_nor *nor)
868 {
869         int sr, fsr;
870
871         if (nor->flags & SNOR_F_READY_XSR_RDY)
872                 sr = s3an_sr_ready(nor);
873         else
874                 sr = spi_nor_sr_ready(nor);
875         if (sr < 0)
876                 return sr;
877         fsr = nor->flags & SNOR_F_USE_FSR ? spi_nor_fsr_ready(nor) : 1;
878         if (fsr < 0)
879                 return fsr;
880         return sr && fsr;
881 }
882
883 /**
884  * spi_nor_wait_till_ready_with_timeout() - Service routine to read the
885  * Status Register until ready, or timeout occurs.
886  * @nor:                pointer to "struct spi_nor".
887  * @timeout_jiffies:    jiffies to wait until timeout.
888  *
889  * Return: 0 on success, -errno otherwise.
890  */
891 static int spi_nor_wait_till_ready_with_timeout(struct spi_nor *nor,
892                                                 unsigned long timeout_jiffies)
893 {
894         unsigned long deadline;
895         int timeout = 0, ret;
896
897         deadline = jiffies + timeout_jiffies;
898
899         while (!timeout) {
900                 if (time_after_eq(jiffies, deadline))
901                         timeout = 1;
902
903                 ret = spi_nor_ready(nor);
904                 if (ret < 0)
905                         return ret;
906                 if (ret)
907                         return 0;
908
909                 cond_resched();
910         }
911
912         dev_dbg(nor->dev, "flash operation timed out\n");
913
914         return -ETIMEDOUT;
915 }
916
917 /**
918  * spi_nor_wait_till_ready() - Wait for a predefined amount of time for the
919  * flash to be ready, or timeout occurs.
920  * @nor:        pointer to "struct spi_nor".
921  *
922  * Return: 0 on success, -errno otherwise.
923  */
924 static int spi_nor_wait_till_ready(struct spi_nor *nor)
925 {
926         return spi_nor_wait_till_ready_with_timeout(nor,
927                                                     DEFAULT_READY_WAIT_JIFFIES);
928 }
929
930 /**
931  * spi_nor_write_sr() - Write the Status Register.
932  * @nor:        pointer to 'struct spi_nor'.
933  * @sr:         pointer to DMA-able buffer to write to the Status Register.
934  * @len:        number of bytes to write to the Status Register.
935  *
936  * Return: 0 on success, -errno otherwise.
937  */
938 static int spi_nor_write_sr(struct spi_nor *nor, const u8 *sr, size_t len)
939 {
940         int ret;
941
942         ret = spi_nor_write_enable(nor);
943         if (ret)
944                 return ret;
945
946         if (nor->spimem) {
947                 struct spi_mem_op op =
948                         SPI_MEM_OP(SPI_MEM_OP_CMD(SPINOR_OP_WRSR, 1),
949                                    SPI_MEM_OP_NO_ADDR,
950                                    SPI_MEM_OP_NO_DUMMY,
951                                    SPI_MEM_OP_DATA_OUT(len, sr, 1));
952
953                 ret = spi_mem_exec_op(nor->spimem, &op);
954         } else {
955                 ret = nor->controller_ops->write_reg(nor, SPINOR_OP_WRSR,
956                                                      sr, len);
957         }
958
959         if (ret) {
960                 dev_dbg(nor->dev, "error %d writing SR\n", ret);
961                 return ret;
962         }
963
964         return spi_nor_wait_till_ready(nor);
965 }
966
967 /**
968  * spi_nor_write_sr1_and_check() - Write one byte to the Status Register 1 and
969  * ensure that the byte written match the received value.
970  * @nor:        pointer to a 'struct spi_nor'.
971  * @sr1:        byte value to be written to the Status Register.
972  *
973  * Return: 0 on success, -errno otherwise.
974  */
975 static int spi_nor_write_sr1_and_check(struct spi_nor *nor, u8 sr1)
976 {
977         int ret;
978
979         nor->bouncebuf[0] = sr1;
980
981         ret = spi_nor_write_sr(nor, nor->bouncebuf, 1);
982         if (ret)
983                 return ret;
984
985         ret = spi_nor_read_sr(nor, nor->bouncebuf);
986         if (ret)
987                 return ret;
988
989         if (nor->bouncebuf[0] != sr1) {
990                 dev_dbg(nor->dev, "SR1: read back test failed\n");
991                 return -EIO;
992         }
993
994         return 0;
995 }
996
997 /**
998  * spi_nor_write_16bit_sr_and_check() - Write the Status Register 1 and the
999  * Status Register 2 in one shot. Ensure that the byte written in the Status
1000  * Register 1 match the received value, and that the 16-bit Write did not
1001  * affect what was already in the Status Register 2.
1002  * @nor:        pointer to a 'struct spi_nor'.
1003  * @sr1:        byte value to be written to the Status Register 1.
1004  *
1005  * Return: 0 on success, -errno otherwise.
1006  */
1007 static int spi_nor_write_16bit_sr_and_check(struct spi_nor *nor, u8 sr1)
1008 {
1009         int ret;
1010         u8 *sr_cr = nor->bouncebuf;
1011         u8 cr_written;
1012
1013         /* Make sure we don't overwrite the contents of Status Register 2. */
1014         if (!(nor->flags & SNOR_F_NO_READ_CR)) {
1015                 ret = spi_nor_read_cr(nor, &sr_cr[1]);
1016                 if (ret)
1017                         return ret;
1018         } else if (nor->params.quad_enable) {
1019                 /*
1020                  * If the Status Register 2 Read command (35h) is not
1021                  * supported, we should at least be sure we don't
1022                  * change the value of the SR2 Quad Enable bit.
1023                  *
1024                  * We can safely assume that when the Quad Enable method is
1025                  * set, the value of the QE bit is one, as a consequence of the
1026                  * nor->params.quad_enable() call.
1027                  *
1028                  * We can safely assume that the Quad Enable bit is present in
1029                  * the Status Register 2 at BIT(1). According to the JESD216
1030                  * revB standard, BFPT DWORDS[15], bits 22:20, the 16-bit
1031                  * Write Status (01h) command is available just for the cases
1032                  * in which the QE bit is described in SR2 at BIT(1).
1033                  */
1034                 sr_cr[1] = SR2_QUAD_EN_BIT1;
1035         } else {
1036                 sr_cr[1] = 0;
1037         }
1038
1039         sr_cr[0] = sr1;
1040
1041         ret = spi_nor_write_sr(nor, sr_cr, 2);
1042         if (ret)
1043                 return ret;
1044
1045         if (nor->flags & SNOR_F_NO_READ_CR)
1046                 return 0;
1047
1048         cr_written = sr_cr[1];
1049
1050         ret = spi_nor_read_cr(nor, &sr_cr[1]);
1051         if (ret)
1052                 return ret;
1053
1054         if (cr_written != sr_cr[1]) {
1055                 dev_dbg(nor->dev, "CR: read back test failed\n");
1056                 return -EIO;
1057         }
1058
1059         return 0;
1060 }
1061
1062 /**
1063  * spi_nor_write_16bit_cr_and_check() - Write the Status Register 1 and the
1064  * Configuration Register in one shot. Ensure that the byte written in the
1065  * Configuration Register match the received value, and that the 16-bit Write
1066  * did not affect what was already in the Status Register 1.
1067  * @nor:        pointer to a 'struct spi_nor'.
1068  * @cr:         byte value to be written to the Configuration Register.
1069  *
1070  * Return: 0 on success, -errno otherwise.
1071  */
1072 static int spi_nor_write_16bit_cr_and_check(struct spi_nor *nor, u8 cr)
1073 {
1074         int ret;
1075         u8 *sr_cr = nor->bouncebuf;
1076         u8 sr_written;
1077
1078         /* Keep the current value of the Status Register 1. */
1079         ret = spi_nor_read_sr(nor, sr_cr);
1080         if (ret)
1081                 return ret;
1082
1083         sr_cr[1] = cr;
1084
1085         ret = spi_nor_write_sr(nor, sr_cr, 2);
1086         if (ret)
1087                 return ret;
1088
1089         sr_written = sr_cr[0];
1090
1091         ret = spi_nor_read_sr(nor, sr_cr);
1092         if (ret)
1093                 return ret;
1094
1095         if (sr_written != sr_cr[0]) {
1096                 dev_dbg(nor->dev, "SR: Read back test failed\n");
1097                 return -EIO;
1098         }
1099
1100         if (nor->flags & SNOR_F_NO_READ_CR)
1101                 return 0;
1102
1103         ret = spi_nor_read_cr(nor, &sr_cr[1]);
1104         if (ret)
1105                 return ret;
1106
1107         if (cr != sr_cr[1]) {
1108                 dev_dbg(nor->dev, "CR: read back test failed\n");
1109                 return -EIO;
1110         }
1111
1112         return 0;
1113 }
1114
1115 /**
1116  * spi_nor_write_sr_and_check() - Write the Status Register 1 and ensure that
1117  * the byte written match the received value without affecting other bits in the
1118  * Status Register 1 and 2.
1119  * @nor:        pointer to a 'struct spi_nor'.
1120  * @sr1:        byte value to be written to the Status Register.
1121  *
1122  * Return: 0 on success, -errno otherwise.
1123  */
1124 static int spi_nor_write_sr_and_check(struct spi_nor *nor, u8 sr1)
1125 {
1126         if (nor->flags & SNOR_F_HAS_16BIT_SR)
1127                 return spi_nor_write_16bit_sr_and_check(nor, sr1);
1128
1129         return spi_nor_write_sr1_and_check(nor, sr1);
1130 }
1131
1132 /**
1133  * spi_nor_write_sr2() - Write the Status Register 2 using the
1134  * SPINOR_OP_WRSR2 (3eh) command.
1135  * @nor:        pointer to 'struct spi_nor'.
1136  * @sr2:        pointer to DMA-able buffer to write to the Status Register 2.
1137  *
1138  * Return: 0 on success, -errno otherwise.
1139  */
1140 static int spi_nor_write_sr2(struct spi_nor *nor, const u8 *sr2)
1141 {
1142         int ret;
1143
1144         ret = spi_nor_write_enable(nor);
1145         if (ret)
1146                 return ret;
1147
1148         if (nor->spimem) {
1149                 struct spi_mem_op op =
1150                         SPI_MEM_OP(SPI_MEM_OP_CMD(SPINOR_OP_WRSR2, 1),
1151                                    SPI_MEM_OP_NO_ADDR,
1152                                    SPI_MEM_OP_NO_DUMMY,
1153                                    SPI_MEM_OP_DATA_OUT(1, sr2, 1));
1154
1155                 ret = spi_mem_exec_op(nor->spimem, &op);
1156         } else {
1157                 ret = nor->controller_ops->write_reg(nor, SPINOR_OP_WRSR2,
1158                                                      sr2, 1);
1159         }
1160
1161         if (ret) {
1162                 dev_dbg(nor->dev, "error %d writing SR2\n", ret);
1163                 return ret;
1164         }
1165
1166         return spi_nor_wait_till_ready(nor);
1167 }
1168
1169 /**
1170  * spi_nor_read_sr2() - Read the Status Register 2 using the
1171  * SPINOR_OP_RDSR2 (3fh) command.
1172  * @nor:        pointer to 'struct spi_nor'.
1173  * @sr2:        pointer to DMA-able buffer where the value of the
1174  *              Status Register 2 will be written.
1175  *
1176  * Return: 0 on success, -errno otherwise.
1177  */
1178 static int spi_nor_read_sr2(struct spi_nor *nor, u8 *sr2)
1179 {
1180         int ret;
1181
1182         if (nor->spimem) {
1183                 struct spi_mem_op op =
1184                         SPI_MEM_OP(SPI_MEM_OP_CMD(SPINOR_OP_RDSR2, 1),
1185                                    SPI_MEM_OP_NO_ADDR,
1186                                    SPI_MEM_OP_NO_DUMMY,
1187                                    SPI_MEM_OP_DATA_IN(1, sr2, 1));
1188
1189                 ret = spi_mem_exec_op(nor->spimem, &op);
1190         } else {
1191                 ret = nor->controller_ops->read_reg(nor, SPINOR_OP_RDSR2,
1192                                                     sr2, 1);
1193         }
1194
1195         if (ret)
1196                 dev_dbg(nor->dev, "error %d reading SR2\n", ret);
1197
1198         return ret;
1199 }
1200
1201 /**
1202  * spi_nor_erase_chip() - Erase the entire flash memory.
1203  * @nor:        pointer to 'struct spi_nor'.
1204  *
1205  * Return: 0 on success, -errno otherwise.
1206  */
1207 static int spi_nor_erase_chip(struct spi_nor *nor)
1208 {
1209         int ret;
1210
1211         dev_dbg(nor->dev, " %lldKiB\n", (long long)(nor->mtd.size >> 10));
1212
1213         if (nor->spimem) {
1214                 struct spi_mem_op op =
1215                         SPI_MEM_OP(SPI_MEM_OP_CMD(SPINOR_OP_CHIP_ERASE, 1),
1216                                    SPI_MEM_OP_NO_ADDR,
1217                                    SPI_MEM_OP_NO_DUMMY,
1218                                    SPI_MEM_OP_NO_DATA);
1219
1220                 ret = spi_mem_exec_op(nor->spimem, &op);
1221         } else {
1222                 ret = nor->controller_ops->write_reg(nor, SPINOR_OP_CHIP_ERASE,
1223                                                      NULL, 0);
1224         }
1225
1226         if (ret)
1227                 dev_dbg(nor->dev, "error %d erasing chip\n", ret);
1228
1229         return ret;
1230 }
1231
1232 static struct spi_nor *mtd_to_spi_nor(struct mtd_info *mtd)
1233 {
1234         return mtd->priv;
1235 }
1236
1237 static u8 spi_nor_convert_opcode(u8 opcode, const u8 table[][2], size_t size)
1238 {
1239         size_t i;
1240
1241         for (i = 0; i < size; i++)
1242                 if (table[i][0] == opcode)
1243                         return table[i][1];
1244
1245         /* No conversion found, keep input op code. */
1246         return opcode;
1247 }
1248
1249 static u8 spi_nor_convert_3to4_read(u8 opcode)
1250 {
1251         static const u8 spi_nor_3to4_read[][2] = {
1252                 { SPINOR_OP_READ,       SPINOR_OP_READ_4B },
1253                 { SPINOR_OP_READ_FAST,  SPINOR_OP_READ_FAST_4B },
1254                 { SPINOR_OP_READ_1_1_2, SPINOR_OP_READ_1_1_2_4B },
1255                 { SPINOR_OP_READ_1_2_2, SPINOR_OP_READ_1_2_2_4B },
1256                 { SPINOR_OP_READ_1_1_4, SPINOR_OP_READ_1_1_4_4B },
1257                 { SPINOR_OP_READ_1_4_4, SPINOR_OP_READ_1_4_4_4B },
1258                 { SPINOR_OP_READ_1_1_8, SPINOR_OP_READ_1_1_8_4B },
1259                 { SPINOR_OP_READ_1_8_8, SPINOR_OP_READ_1_8_8_4B },
1260
1261                 { SPINOR_OP_READ_1_1_1_DTR,     SPINOR_OP_READ_1_1_1_DTR_4B },
1262                 { SPINOR_OP_READ_1_2_2_DTR,     SPINOR_OP_READ_1_2_2_DTR_4B },
1263                 { SPINOR_OP_READ_1_4_4_DTR,     SPINOR_OP_READ_1_4_4_DTR_4B },
1264         };
1265
1266         return spi_nor_convert_opcode(opcode, spi_nor_3to4_read,
1267                                       ARRAY_SIZE(spi_nor_3to4_read));
1268 }
1269
1270 static u8 spi_nor_convert_3to4_program(u8 opcode)
1271 {
1272         static const u8 spi_nor_3to4_program[][2] = {
1273                 { SPINOR_OP_PP,         SPINOR_OP_PP_4B },
1274                 { SPINOR_OP_PP_1_1_4,   SPINOR_OP_PP_1_1_4_4B },
1275                 { SPINOR_OP_PP_1_4_4,   SPINOR_OP_PP_1_4_4_4B },
1276                 { SPINOR_OP_PP_1_1_8,   SPINOR_OP_PP_1_1_8_4B },
1277                 { SPINOR_OP_PP_1_8_8,   SPINOR_OP_PP_1_8_8_4B },
1278         };
1279
1280         return spi_nor_convert_opcode(opcode, spi_nor_3to4_program,
1281                                       ARRAY_SIZE(spi_nor_3to4_program));
1282 }
1283
1284 static u8 spi_nor_convert_3to4_erase(u8 opcode)
1285 {
1286         static const u8 spi_nor_3to4_erase[][2] = {
1287                 { SPINOR_OP_BE_4K,      SPINOR_OP_BE_4K_4B },
1288                 { SPINOR_OP_BE_32K,     SPINOR_OP_BE_32K_4B },
1289                 { SPINOR_OP_SE,         SPINOR_OP_SE_4B },
1290         };
1291
1292         return spi_nor_convert_opcode(opcode, spi_nor_3to4_erase,
1293                                       ARRAY_SIZE(spi_nor_3to4_erase));
1294 }
1295
1296 static void spi_nor_set_4byte_opcodes(struct spi_nor *nor)
1297 {
1298         nor->read_opcode = spi_nor_convert_3to4_read(nor->read_opcode);
1299         nor->program_opcode = spi_nor_convert_3to4_program(nor->program_opcode);
1300         nor->erase_opcode = spi_nor_convert_3to4_erase(nor->erase_opcode);
1301
1302         if (!spi_nor_has_uniform_erase(nor)) {
1303                 struct spi_nor_erase_map *map = &nor->params.erase_map;
1304                 struct spi_nor_erase_type *erase;
1305                 int i;
1306
1307                 for (i = 0; i < SNOR_ERASE_TYPE_MAX; i++) {
1308                         erase = &map->erase_type[i];
1309                         erase->opcode =
1310                                 spi_nor_convert_3to4_erase(erase->opcode);
1311                 }
1312         }
1313 }
1314
1315 static int spi_nor_lock_and_prep(struct spi_nor *nor)
1316 {
1317         int ret = 0;
1318
1319         mutex_lock(&nor->lock);
1320
1321         if (nor->controller_ops &&  nor->controller_ops->prepare) {
1322                 ret = nor->controller_ops->prepare(nor);
1323                 if (ret) {
1324                         mutex_unlock(&nor->lock);
1325                         return ret;
1326                 }
1327         }
1328         return ret;
1329 }
1330
1331 static void spi_nor_unlock_and_unprep(struct spi_nor *nor)
1332 {
1333         if (nor->controller_ops && nor->controller_ops->unprepare)
1334                 nor->controller_ops->unprepare(nor);
1335         mutex_unlock(&nor->lock);
1336 }
1337
1338 /*
1339  * This code converts an address to the Default Address Mode, that has non
1340  * power of two page sizes. We must support this mode because it is the default
1341  * mode supported by Xilinx tools, it can access the whole flash area and
1342  * changing over to the Power-of-two mode is irreversible and corrupts the
1343  * original data.
1344  * Addr can safely be unsigned int, the biggest S3AN device is smaller than
1345  * 4 MiB.
1346  */
1347 static u32 s3an_convert_addr(struct spi_nor *nor, u32 addr)
1348 {
1349         u32 offset, page;
1350
1351         offset = addr % nor->page_size;
1352         page = addr / nor->page_size;
1353         page <<= (nor->page_size > 512) ? 10 : 9;
1354
1355         return page | offset;
1356 }
1357
1358 static u32 spi_nor_convert_addr(struct spi_nor *nor, loff_t addr)
1359 {
1360         if (!nor->params.convert_addr)
1361                 return addr;
1362
1363         return nor->params.convert_addr(nor, addr);
1364 }
1365
1366 /*
1367  * Initiate the erasure of a single sector
1368  */
1369 static int spi_nor_erase_sector(struct spi_nor *nor, u32 addr)
1370 {
1371         int i;
1372
1373         addr = spi_nor_convert_addr(nor, addr);
1374
1375         if (nor->spimem) {
1376                 struct spi_mem_op op =
1377                         SPI_MEM_OP(SPI_MEM_OP_CMD(nor->erase_opcode, 1),
1378                                    SPI_MEM_OP_ADDR(nor->addr_width, addr, 1),
1379                                    SPI_MEM_OP_NO_DUMMY,
1380                                    SPI_MEM_OP_NO_DATA);
1381
1382                 return spi_mem_exec_op(nor->spimem, &op);
1383         } else if (nor->controller_ops->erase) {
1384                 return nor->controller_ops->erase(nor, addr);
1385         }
1386
1387         /*
1388          * Default implementation, if driver doesn't have a specialized HW
1389          * control
1390          */
1391         for (i = nor->addr_width - 1; i >= 0; i--) {
1392                 nor->bouncebuf[i] = addr & 0xff;
1393                 addr >>= 8;
1394         }
1395
1396         return nor->controller_ops->write_reg(nor, nor->erase_opcode,
1397                                               nor->bouncebuf, nor->addr_width);
1398 }
1399
1400 /**
1401  * spi_nor_div_by_erase_size() - calculate remainder and update new dividend
1402  * @erase:      pointer to a structure that describes a SPI NOR erase type
1403  * @dividend:   dividend value
1404  * @remainder:  pointer to u32 remainder (will be updated)
1405  *
1406  * Return: the result of the division
1407  */
1408 static u64 spi_nor_div_by_erase_size(const struct spi_nor_erase_type *erase,
1409                                      u64 dividend, u32 *remainder)
1410 {
1411         /* JEDEC JESD216B Standard imposes erase sizes to be power of 2. */
1412         *remainder = (u32)dividend & erase->size_mask;
1413         return dividend >> erase->size_shift;
1414 }
1415
1416 /**
1417  * spi_nor_find_best_erase_type() - find the best erase type for the given
1418  *                                  offset in the serial flash memory and the
1419  *                                  number of bytes to erase. The region in
1420  *                                  which the address fits is expected to be
1421  *                                  provided.
1422  * @map:        the erase map of the SPI NOR
1423  * @region:     pointer to a structure that describes a SPI NOR erase region
1424  * @addr:       offset in the serial flash memory
1425  * @len:        number of bytes to erase
1426  *
1427  * Return: a pointer to the best fitted erase type, NULL otherwise.
1428  */
1429 static const struct spi_nor_erase_type *
1430 spi_nor_find_best_erase_type(const struct spi_nor_erase_map *map,
1431                              const struct spi_nor_erase_region *region,
1432                              u64 addr, u32 len)
1433 {
1434         const struct spi_nor_erase_type *erase;
1435         u32 rem;
1436         int i;
1437         u8 erase_mask = region->offset & SNOR_ERASE_TYPE_MASK;
1438
1439         /*
1440          * Erase types are ordered by size, with the smallest erase type at
1441          * index 0.
1442          */
1443         for (i = SNOR_ERASE_TYPE_MAX - 1; i >= 0; i--) {
1444                 /* Does the erase region support the tested erase type? */
1445                 if (!(erase_mask & BIT(i)))
1446                         continue;
1447
1448                 erase = &map->erase_type[i];
1449
1450                 /* Don't erase more than what the user has asked for. */
1451                 if (erase->size > len)
1452                         continue;
1453
1454                 /* Alignment is not mandatory for overlaid regions */
1455                 if (region->offset & SNOR_OVERLAID_REGION)
1456                         return erase;
1457
1458                 spi_nor_div_by_erase_size(erase, addr, &rem);
1459                 if (rem)
1460                         continue;
1461                 else
1462                         return erase;
1463         }
1464
1465         return NULL;
1466 }
1467
1468 /**
1469  * spi_nor_region_next() - get the next spi nor region
1470  * @region:     pointer to a structure that describes a SPI NOR erase region
1471  *
1472  * Return: the next spi nor region or NULL if last region.
1473  */
1474 static struct spi_nor_erase_region *
1475 spi_nor_region_next(struct spi_nor_erase_region *region)
1476 {
1477         if (spi_nor_region_is_last(region))
1478                 return NULL;
1479         region++;
1480         return region;
1481 }
1482
1483 /**
1484  * spi_nor_find_erase_region() - find the region of the serial flash memory in
1485  *                               which the offset fits
1486  * @map:        the erase map of the SPI NOR
1487  * @addr:       offset in the serial flash memory
1488  *
1489  * Return: a pointer to the spi_nor_erase_region struct, ERR_PTR(-errno)
1490  *         otherwise.
1491  */
1492 static struct spi_nor_erase_region *
1493 spi_nor_find_erase_region(const struct spi_nor_erase_map *map, u64 addr)
1494 {
1495         struct spi_nor_erase_region *region = map->regions;
1496         u64 region_start = region->offset & ~SNOR_ERASE_FLAGS_MASK;
1497         u64 region_end = region_start + region->size;
1498
1499         while (addr < region_start || addr >= region_end) {
1500                 region = spi_nor_region_next(region);
1501                 if (!region)
1502                         return ERR_PTR(-EINVAL);
1503
1504                 region_start = region->offset & ~SNOR_ERASE_FLAGS_MASK;
1505                 region_end = region_start + region->size;
1506         }
1507
1508         return region;
1509 }
1510
1511 /**
1512  * spi_nor_init_erase_cmd() - initialize an erase command
1513  * @region:     pointer to a structure that describes a SPI NOR erase region
1514  * @erase:      pointer to a structure that describes a SPI NOR erase type
1515  *
1516  * Return: the pointer to the allocated erase command, ERR_PTR(-errno)
1517  *         otherwise.
1518  */
1519 static struct spi_nor_erase_command *
1520 spi_nor_init_erase_cmd(const struct spi_nor_erase_region *region,
1521                        const struct spi_nor_erase_type *erase)
1522 {
1523         struct spi_nor_erase_command *cmd;
1524
1525         cmd = kmalloc(sizeof(*cmd), GFP_KERNEL);
1526         if (!cmd)
1527                 return ERR_PTR(-ENOMEM);
1528
1529         INIT_LIST_HEAD(&cmd->list);
1530         cmd->opcode = erase->opcode;
1531         cmd->count = 1;
1532
1533         if (region->offset & SNOR_OVERLAID_REGION)
1534                 cmd->size = region->size;
1535         else
1536                 cmd->size = erase->size;
1537
1538         return cmd;
1539 }
1540
1541 /**
1542  * spi_nor_destroy_erase_cmd_list() - destroy erase command list
1543  * @erase_list: list of erase commands
1544  */
1545 static void spi_nor_destroy_erase_cmd_list(struct list_head *erase_list)
1546 {
1547         struct spi_nor_erase_command *cmd, *next;
1548
1549         list_for_each_entry_safe(cmd, next, erase_list, list) {
1550                 list_del(&cmd->list);
1551                 kfree(cmd);
1552         }
1553 }
1554
1555 /**
1556  * spi_nor_init_erase_cmd_list() - initialize erase command list
1557  * @nor:        pointer to a 'struct spi_nor'
1558  * @erase_list: list of erase commands to be executed once we validate that the
1559  *              erase can be performed
1560  * @addr:       offset in the serial flash memory
1561  * @len:        number of bytes to erase
1562  *
1563  * Builds the list of best fitted erase commands and verifies if the erase can
1564  * be performed.
1565  *
1566  * Return: 0 on success, -errno otherwise.
1567  */
1568 static int spi_nor_init_erase_cmd_list(struct spi_nor *nor,
1569                                        struct list_head *erase_list,
1570                                        u64 addr, u32 len)
1571 {
1572         const struct spi_nor_erase_map *map = &nor->params.erase_map;
1573         const struct spi_nor_erase_type *erase, *prev_erase = NULL;
1574         struct spi_nor_erase_region *region;
1575         struct spi_nor_erase_command *cmd = NULL;
1576         u64 region_end;
1577         int ret = -EINVAL;
1578
1579         region = spi_nor_find_erase_region(map, addr);
1580         if (IS_ERR(region))
1581                 return PTR_ERR(region);
1582
1583         region_end = spi_nor_region_end(region);
1584
1585         while (len) {
1586                 erase = spi_nor_find_best_erase_type(map, region, addr, len);
1587                 if (!erase)
1588                         goto destroy_erase_cmd_list;
1589
1590                 if (prev_erase != erase ||
1591                     region->offset & SNOR_OVERLAID_REGION) {
1592                         cmd = spi_nor_init_erase_cmd(region, erase);
1593                         if (IS_ERR(cmd)) {
1594                                 ret = PTR_ERR(cmd);
1595                                 goto destroy_erase_cmd_list;
1596                         }
1597
1598                         list_add_tail(&cmd->list, erase_list);
1599                 } else {
1600                         cmd->count++;
1601                 }
1602
1603                 addr += cmd->size;
1604                 len -= cmd->size;
1605
1606                 if (len && addr >= region_end) {
1607                         region = spi_nor_region_next(region);
1608                         if (!region)
1609                                 goto destroy_erase_cmd_list;
1610                         region_end = spi_nor_region_end(region);
1611                 }
1612
1613                 prev_erase = erase;
1614         }
1615
1616         return 0;
1617
1618 destroy_erase_cmd_list:
1619         spi_nor_destroy_erase_cmd_list(erase_list);
1620         return ret;
1621 }
1622
1623 /**
1624  * spi_nor_erase_multi_sectors() - perform a non-uniform erase
1625  * @nor:        pointer to a 'struct spi_nor'
1626  * @addr:       offset in the serial flash memory
1627  * @len:        number of bytes to erase
1628  *
1629  * Build a list of best fitted erase commands and execute it once we validate
1630  * that the erase can be performed.
1631  *
1632  * Return: 0 on success, -errno otherwise.
1633  */
1634 static int spi_nor_erase_multi_sectors(struct spi_nor *nor, u64 addr, u32 len)
1635 {
1636         LIST_HEAD(erase_list);
1637         struct spi_nor_erase_command *cmd, *next;
1638         int ret;
1639
1640         ret = spi_nor_init_erase_cmd_list(nor, &erase_list, addr, len);
1641         if (ret)
1642                 return ret;
1643
1644         list_for_each_entry_safe(cmd, next, &erase_list, list) {
1645                 nor->erase_opcode = cmd->opcode;
1646                 while (cmd->count) {
1647                         ret = spi_nor_write_enable(nor);
1648                         if (ret)
1649                                 goto destroy_erase_cmd_list;
1650
1651                         ret = spi_nor_erase_sector(nor, addr);
1652                         if (ret)
1653                                 goto destroy_erase_cmd_list;
1654
1655                         addr += cmd->size;
1656                         cmd->count--;
1657
1658                         ret = spi_nor_wait_till_ready(nor);
1659                         if (ret)
1660                                 goto destroy_erase_cmd_list;
1661                 }
1662                 list_del(&cmd->list);
1663                 kfree(cmd);
1664         }
1665
1666         return 0;
1667
1668 destroy_erase_cmd_list:
1669         spi_nor_destroy_erase_cmd_list(&erase_list);
1670         return ret;
1671 }
1672
1673 /*
1674  * Erase an address range on the nor chip.  The address range may extend
1675  * one or more erase sectors.  Return an error is there is a problem erasing.
1676  */
1677 static int spi_nor_erase(struct mtd_info *mtd, struct erase_info *instr)
1678 {
1679         struct spi_nor *nor = mtd_to_spi_nor(mtd);
1680         u32 addr, len;
1681         uint32_t rem;
1682         int ret;
1683
1684         dev_dbg(nor->dev, "at 0x%llx, len %lld\n", (long long)instr->addr,
1685                         (long long)instr->len);
1686
1687         if (spi_nor_has_uniform_erase(nor)) {
1688                 div_u64_rem(instr->len, mtd->erasesize, &rem);
1689                 if (rem)
1690                         return -EINVAL;
1691         }
1692
1693         addr = instr->addr;
1694         len = instr->len;
1695
1696         ret = spi_nor_lock_and_prep(nor);
1697         if (ret)
1698                 return ret;
1699
1700         /* whole-chip erase? */
1701         if (len == mtd->size && !(nor->flags & SNOR_F_NO_OP_CHIP_ERASE)) {
1702                 unsigned long timeout;
1703
1704                 ret = spi_nor_write_enable(nor);
1705                 if (ret)
1706                         goto erase_err;
1707
1708                 ret = spi_nor_erase_chip(nor);
1709                 if (ret)
1710                         goto erase_err;
1711
1712                 /*
1713                  * Scale the timeout linearly with the size of the flash, with
1714                  * a minimum calibrated to an old 2MB flash. We could try to
1715                  * pull these from CFI/SFDP, but these values should be good
1716                  * enough for now.
1717                  */
1718                 timeout = max(CHIP_ERASE_2MB_READY_WAIT_JIFFIES,
1719                               CHIP_ERASE_2MB_READY_WAIT_JIFFIES *
1720                               (unsigned long)(mtd->size / SZ_2M));
1721                 ret = spi_nor_wait_till_ready_with_timeout(nor, timeout);
1722                 if (ret)
1723                         goto erase_err;
1724
1725         /* REVISIT in some cases we could speed up erasing large regions
1726          * by using SPINOR_OP_SE instead of SPINOR_OP_BE_4K.  We may have set up
1727          * to use "small sector erase", but that's not always optimal.
1728          */
1729
1730         /* "sector"-at-a-time erase */
1731         } else if (spi_nor_has_uniform_erase(nor)) {
1732                 while (len) {
1733                         ret = spi_nor_write_enable(nor);
1734                         if (ret)
1735                                 goto erase_err;
1736
1737                         ret = spi_nor_erase_sector(nor, addr);
1738                         if (ret)
1739                                 goto erase_err;
1740
1741                         addr += mtd->erasesize;
1742                         len -= mtd->erasesize;
1743
1744                         ret = spi_nor_wait_till_ready(nor);
1745                         if (ret)
1746                                 goto erase_err;
1747                 }
1748
1749         /* erase multiple sectors */
1750         } else {
1751                 ret = spi_nor_erase_multi_sectors(nor, addr, len);
1752                 if (ret)
1753                         goto erase_err;
1754         }
1755
1756         ret = spi_nor_write_disable(nor);
1757
1758 erase_err:
1759         spi_nor_unlock_and_unprep(nor);
1760
1761         return ret;
1762 }
1763
1764 static void stm_get_locked_range(struct spi_nor *nor, u8 sr, loff_t *ofs,
1765                                  uint64_t *len)
1766 {
1767         struct mtd_info *mtd = &nor->mtd;
1768         u8 mask = SR_BP2 | SR_BP1 | SR_BP0;
1769         u8 tb_mask = SR_TB_BIT5;
1770         int shift = ffs(mask) - 1;
1771         int pow;
1772
1773         if (nor->flags & SNOR_F_HAS_SR_TB_BIT6)
1774                 tb_mask = SR_TB_BIT6;
1775
1776         if (!(sr & mask)) {
1777                 /* No protection */
1778                 *ofs = 0;
1779                 *len = 0;
1780         } else {
1781                 pow = ((sr & mask) ^ mask) >> shift;
1782                 *len = mtd->size >> pow;
1783                 if (nor->flags & SNOR_F_HAS_SR_TB && sr & tb_mask)
1784                         *ofs = 0;
1785                 else
1786                         *ofs = mtd->size - *len;
1787         }
1788 }
1789
1790 /*
1791  * Return 1 if the entire region is locked (if @locked is true) or unlocked (if
1792  * @locked is false); 0 otherwise
1793  */
1794 static int stm_check_lock_status_sr(struct spi_nor *nor, loff_t ofs, uint64_t len,
1795                                     u8 sr, bool locked)
1796 {
1797         loff_t lock_offs;
1798         uint64_t lock_len;
1799
1800         if (!len)
1801                 return 1;
1802
1803         stm_get_locked_range(nor, sr, &lock_offs, &lock_len);
1804
1805         if (locked)
1806                 /* Requested range is a sub-range of locked range */
1807                 return (ofs + len <= lock_offs + lock_len) && (ofs >= lock_offs);
1808         else
1809                 /* Requested range does not overlap with locked range */
1810                 return (ofs >= lock_offs + lock_len) || (ofs + len <= lock_offs);
1811 }
1812
1813 static int stm_is_locked_sr(struct spi_nor *nor, loff_t ofs, uint64_t len,
1814                             u8 sr)
1815 {
1816         return stm_check_lock_status_sr(nor, ofs, len, sr, true);
1817 }
1818
1819 static int stm_is_unlocked_sr(struct spi_nor *nor, loff_t ofs, uint64_t len,
1820                               u8 sr)
1821 {
1822         return stm_check_lock_status_sr(nor, ofs, len, sr, false);
1823 }
1824
1825 /*
1826  * Lock a region of the flash. Compatible with ST Micro and similar flash.
1827  * Supports the block protection bits BP{0,1,2} in the status register
1828  * (SR). Does not support these features found in newer SR bitfields:
1829  *   - SEC: sector/block protect - only handle SEC=0 (block protect)
1830  *   - CMP: complement protect - only support CMP=0 (range is not complemented)
1831  *
1832  * Support for the following is provided conditionally for some flash:
1833  *   - TB: top/bottom protect
1834  *
1835  * Sample table portion for 8MB flash (Winbond w25q64fw):
1836  *
1837  *   SEC  |  TB   |  BP2  |  BP1  |  BP0  |  Prot Length  | Protected Portion
1838  *  --------------------------------------------------------------------------
1839  *    X   |   X   |   0   |   0   |   0   |  NONE         | NONE
1840  *    0   |   0   |   0   |   0   |   1   |  128 KB       | Upper 1/64
1841  *    0   |   0   |   0   |   1   |   0   |  256 KB       | Upper 1/32
1842  *    0   |   0   |   0   |   1   |   1   |  512 KB       | Upper 1/16
1843  *    0   |   0   |   1   |   0   |   0   |  1 MB         | Upper 1/8
1844  *    0   |   0   |   1   |   0   |   1   |  2 MB         | Upper 1/4
1845  *    0   |   0   |   1   |   1   |   0   |  4 MB         | Upper 1/2
1846  *    X   |   X   |   1   |   1   |   1   |  8 MB         | ALL
1847  *  ------|-------|-------|-------|-------|---------------|-------------------
1848  *    0   |   1   |   0   |   0   |   1   |  128 KB       | Lower 1/64
1849  *    0   |   1   |   0   |   1   |   0   |  256 KB       | Lower 1/32
1850  *    0   |   1   |   0   |   1   |   1   |  512 KB       | Lower 1/16
1851  *    0   |   1   |   1   |   0   |   0   |  1 MB         | Lower 1/8
1852  *    0   |   1   |   1   |   0   |   1   |  2 MB         | Lower 1/4
1853  *    0   |   1   |   1   |   1   |   0   |  4 MB         | Lower 1/2
1854  *
1855  * Returns negative on errors, 0 on success.
1856  */
1857 static int stm_lock(struct spi_nor *nor, loff_t ofs, uint64_t len)
1858 {
1859         struct mtd_info *mtd = &nor->mtd;
1860         int ret, status_old, status_new;
1861         u8 mask = SR_BP2 | SR_BP1 | SR_BP0;
1862         u8 tb_mask = SR_TB_BIT5;
1863         u8 shift = ffs(mask) - 1, pow, val;
1864         loff_t lock_len;
1865         bool can_be_top = true, can_be_bottom = nor->flags & SNOR_F_HAS_SR_TB;
1866         bool use_top;
1867
1868         ret = spi_nor_read_sr(nor, nor->bouncebuf);
1869         if (ret)
1870                 return ret;
1871
1872         status_old = nor->bouncebuf[0];
1873
1874         /* If nothing in our range is unlocked, we don't need to do anything */
1875         if (stm_is_locked_sr(nor, ofs, len, status_old))
1876                 return 0;
1877
1878         /* If anything below us is unlocked, we can't use 'bottom' protection */
1879         if (!stm_is_locked_sr(nor, 0, ofs, status_old))
1880                 can_be_bottom = false;
1881
1882         /* If anything above us is unlocked, we can't use 'top' protection */
1883         if (!stm_is_locked_sr(nor, ofs + len, mtd->size - (ofs + len),
1884                                 status_old))
1885                 can_be_top = false;
1886
1887         if (!can_be_bottom && !can_be_top)
1888                 return -EINVAL;
1889
1890         /* Prefer top, if both are valid */
1891         use_top = can_be_top;
1892
1893         /* lock_len: length of region that should end up locked */
1894         if (use_top)
1895                 lock_len = mtd->size - ofs;
1896         else
1897                 lock_len = ofs + len;
1898
1899         if (nor->flags & SNOR_F_HAS_SR_TB_BIT6)
1900                 tb_mask = SR_TB_BIT6;
1901
1902         /*
1903          * Need smallest pow such that:
1904          *
1905          *   1 / (2^pow) <= (len / size)
1906          *
1907          * so (assuming power-of-2 size) we do:
1908          *
1909          *   pow = ceil(log2(size / len)) = log2(size) - floor(log2(len))
1910          */
1911         pow = ilog2(mtd->size) - ilog2(lock_len);
1912         val = mask - (pow << shift);
1913         if (val & ~mask)
1914                 return -EINVAL;
1915         /* Don't "lock" with no region! */
1916         if (!(val & mask))
1917                 return -EINVAL;
1918
1919         status_new = (status_old & ~mask & ~tb_mask) | val;
1920
1921         /* Disallow further writes if WP pin is asserted */
1922         status_new |= SR_SRWD;
1923
1924         if (!use_top)
1925                 status_new |= tb_mask;
1926
1927         /* Don't bother if they're the same */
1928         if (status_new == status_old)
1929                 return 0;
1930
1931         /* Only modify protection if it will not unlock other areas */
1932         if ((status_new & mask) < (status_old & mask))
1933                 return -EINVAL;
1934
1935         return spi_nor_write_sr_and_check(nor, status_new);
1936 }
1937
1938 /*
1939  * Unlock a region of the flash. See stm_lock() for more info
1940  *
1941  * Returns negative on errors, 0 on success.
1942  */
1943 static int stm_unlock(struct spi_nor *nor, loff_t ofs, uint64_t len)
1944 {
1945         struct mtd_info *mtd = &nor->mtd;
1946         int ret, status_old, status_new;
1947         u8 mask = SR_BP2 | SR_BP1 | SR_BP0;
1948         u8 tb_mask = SR_TB_BIT5;
1949         u8 shift = ffs(mask) - 1, pow, val;
1950         loff_t lock_len;
1951         bool can_be_top = true, can_be_bottom = nor->flags & SNOR_F_HAS_SR_TB;
1952         bool use_top;
1953
1954         ret = spi_nor_read_sr(nor, nor->bouncebuf);
1955         if (ret)
1956                 return ret;
1957
1958         status_old = nor->bouncebuf[0];
1959
1960         /* If nothing in our range is locked, we don't need to do anything */
1961         if (stm_is_unlocked_sr(nor, ofs, len, status_old))
1962                 return 0;
1963
1964         /* If anything below us is locked, we can't use 'top' protection */
1965         if (!stm_is_unlocked_sr(nor, 0, ofs, status_old))
1966                 can_be_top = false;
1967
1968         /* If anything above us is locked, we can't use 'bottom' protection */
1969         if (!stm_is_unlocked_sr(nor, ofs + len, mtd->size - (ofs + len),
1970                                 status_old))
1971                 can_be_bottom = false;
1972
1973         if (!can_be_bottom && !can_be_top)
1974                 return -EINVAL;
1975
1976         /* Prefer top, if both are valid */
1977         use_top = can_be_top;
1978
1979         /* lock_len: length of region that should remain locked */
1980         if (use_top)
1981                 lock_len = mtd->size - (ofs + len);
1982         else
1983                 lock_len = ofs;
1984
1985         if (nor->flags & SNOR_F_HAS_SR_TB_BIT6)
1986                 tb_mask = SR_TB_BIT6;
1987         /*
1988          * Need largest pow such that:
1989          *
1990          *   1 / (2^pow) >= (len / size)
1991          *
1992          * so (assuming power-of-2 size) we do:
1993          *
1994          *   pow = floor(log2(size / len)) = log2(size) - ceil(log2(len))
1995          */
1996         pow = ilog2(mtd->size) - order_base_2(lock_len);
1997         if (lock_len == 0) {
1998                 val = 0; /* fully unlocked */
1999         } else {
2000                 val = mask - (pow << shift);
2001                 /* Some power-of-two sizes are not supported */
2002                 if (val & ~mask)
2003                         return -EINVAL;
2004         }
2005
2006         status_new = (status_old & ~mask & ~tb_mask) | val;
2007
2008         /* Don't protect status register if we're fully unlocked */
2009         if (lock_len == 0)
2010                 status_new &= ~SR_SRWD;
2011
2012         if (!use_top)
2013                 status_new |= tb_mask;
2014
2015         /* Don't bother if they're the same */
2016         if (status_new == status_old)
2017                 return 0;
2018
2019         /* Only modify protection if it will not lock other areas */
2020         if ((status_new & mask) > (status_old & mask))
2021                 return -EINVAL;
2022
2023         return spi_nor_write_sr_and_check(nor, status_new);
2024 }
2025
2026 /*
2027  * Check if a region of the flash is (completely) locked. See stm_lock() for
2028  * more info.
2029  *
2030  * Returns 1 if entire region is locked, 0 if any portion is unlocked, and
2031  * negative on errors.
2032  */
2033 static int stm_is_locked(struct spi_nor *nor, loff_t ofs, uint64_t len)
2034 {
2035         int ret;
2036
2037         ret = spi_nor_read_sr(nor, nor->bouncebuf);
2038         if (ret)
2039                 return ret;
2040
2041         return stm_is_locked_sr(nor, ofs, len, nor->bouncebuf[0]);
2042 }
2043
2044 static const struct spi_nor_locking_ops stm_locking_ops = {
2045         .lock = stm_lock,
2046         .unlock = stm_unlock,
2047         .is_locked = stm_is_locked,
2048 };
2049
2050 static int spi_nor_lock(struct mtd_info *mtd, loff_t ofs, uint64_t len)
2051 {
2052         struct spi_nor *nor = mtd_to_spi_nor(mtd);
2053         int ret;
2054
2055         ret = spi_nor_lock_and_prep(nor);
2056         if (ret)
2057                 return ret;
2058
2059         ret = nor->params.locking_ops->lock(nor, ofs, len);
2060
2061         spi_nor_unlock_and_unprep(nor);
2062         return ret;
2063 }
2064
2065 static int spi_nor_unlock(struct mtd_info *mtd, loff_t ofs, uint64_t len)
2066 {
2067         struct spi_nor *nor = mtd_to_spi_nor(mtd);
2068         int ret;
2069
2070         ret = spi_nor_lock_and_prep(nor);
2071         if (ret)
2072                 return ret;
2073
2074         ret = nor->params.locking_ops->unlock(nor, ofs, len);
2075
2076         spi_nor_unlock_and_unprep(nor);
2077         return ret;
2078 }
2079
2080 static int spi_nor_is_locked(struct mtd_info *mtd, loff_t ofs, uint64_t len)
2081 {
2082         struct spi_nor *nor = mtd_to_spi_nor(mtd);
2083         int ret;
2084
2085         ret = spi_nor_lock_and_prep(nor);
2086         if (ret)
2087                 return ret;
2088
2089         ret = nor->params.locking_ops->is_locked(nor, ofs, len);
2090
2091         spi_nor_unlock_and_unprep(nor);
2092         return ret;
2093 }
2094
2095 /**
2096  * spi_nor_sr1_bit6_quad_enable() - Set the Quad Enable BIT(6) in the Status
2097  * Register 1.
2098  * @nor:        pointer to a 'struct spi_nor'
2099  *
2100  * Bit 6 of the Status Register 1 is the QE bit for Macronix like QSPI memories.
2101  *
2102  * Return: 0 on success, -errno otherwise.
2103  */
2104 static int spi_nor_sr1_bit6_quad_enable(struct spi_nor *nor)
2105 {
2106         int ret;
2107
2108         ret = spi_nor_read_sr(nor, nor->bouncebuf);
2109         if (ret)
2110                 return ret;
2111
2112         if (nor->bouncebuf[0] & SR1_QUAD_EN_BIT6)
2113                 return 0;
2114
2115         nor->bouncebuf[0] |= SR1_QUAD_EN_BIT6;
2116
2117         return spi_nor_write_sr1_and_check(nor, nor->bouncebuf[0]);
2118 }
2119
2120 /**
2121  * spi_nor_sr2_bit1_quad_enable() - set the Quad Enable BIT(1) in the Status
2122  * Register 2.
2123  * @nor:       pointer to a 'struct spi_nor'.
2124  *
2125  * Bit 1 of the Status Register 2 is the QE bit for Spansion like QSPI memories.
2126  *
2127  * Return: 0 on success, -errno otherwise.
2128  */
2129 static int spi_nor_sr2_bit1_quad_enable(struct spi_nor *nor)
2130 {
2131         int ret;
2132
2133         if (nor->flags & SNOR_F_NO_READ_CR)
2134                 return spi_nor_write_16bit_cr_and_check(nor, SR2_QUAD_EN_BIT1);
2135
2136         ret = spi_nor_read_cr(nor, nor->bouncebuf);
2137         if (ret)
2138                 return ret;
2139
2140         if (nor->bouncebuf[0] & SR2_QUAD_EN_BIT1)
2141                 return 0;
2142
2143         nor->bouncebuf[0] |= SR2_QUAD_EN_BIT1;
2144
2145         return spi_nor_write_16bit_cr_and_check(nor, nor->bouncebuf[0]);
2146 }
2147
2148 /**
2149  * spi_nor_sr2_bit7_quad_enable() - set QE bit in Status Register 2.
2150  * @nor:        pointer to a 'struct spi_nor'
2151  *
2152  * Set the Quad Enable (QE) bit in the Status Register 2.
2153  *
2154  * This is one of the procedures to set the QE bit described in the SFDP
2155  * (JESD216 rev B) specification but no manufacturer using this procedure has
2156  * been identified yet, hence the name of the function.
2157  *
2158  * Return: 0 on success, -errno otherwise.
2159  */
2160 static int spi_nor_sr2_bit7_quad_enable(struct spi_nor *nor)
2161 {
2162         u8 *sr2 = nor->bouncebuf;
2163         int ret;
2164         u8 sr2_written;
2165
2166         /* Check current Quad Enable bit value. */
2167         ret = spi_nor_read_sr2(nor, sr2);
2168         if (ret)
2169                 return ret;
2170         if (*sr2 & SR2_QUAD_EN_BIT7)
2171                 return 0;
2172
2173         /* Update the Quad Enable bit. */
2174         *sr2 |= SR2_QUAD_EN_BIT7;
2175
2176         ret = spi_nor_write_sr2(nor, sr2);
2177         if (ret)
2178                 return ret;
2179
2180         sr2_written = *sr2;
2181
2182         /* Read back and check it. */
2183         ret = spi_nor_read_sr2(nor, sr2);
2184         if (ret)
2185                 return ret;
2186
2187         if (*sr2 != sr2_written) {
2188                 dev_dbg(nor->dev, "SR2: Read back test failed\n");
2189                 return -EIO;
2190         }
2191
2192         return 0;
2193 }
2194
2195 /* Used when the "_ext_id" is two bytes at most */
2196 #define INFO(_jedec_id, _ext_id, _sector_size, _n_sectors, _flags)      \
2197                 .id = {                                                 \
2198                         ((_jedec_id) >> 16) & 0xff,                     \
2199                         ((_jedec_id) >> 8) & 0xff,                      \
2200                         (_jedec_id) & 0xff,                             \
2201                         ((_ext_id) >> 8) & 0xff,                        \
2202                         (_ext_id) & 0xff,                               \
2203                         },                                              \
2204                 .id_len = (!(_jedec_id) ? 0 : (3 + ((_ext_id) ? 2 : 0))),       \
2205                 .sector_size = (_sector_size),                          \
2206                 .n_sectors = (_n_sectors),                              \
2207                 .page_size = 256,                                       \
2208                 .flags = (_flags),
2209
2210 #define INFO6(_jedec_id, _ext_id, _sector_size, _n_sectors, _flags)     \
2211                 .id = {                                                 \
2212                         ((_jedec_id) >> 16) & 0xff,                     \
2213                         ((_jedec_id) >> 8) & 0xff,                      \
2214                         (_jedec_id) & 0xff,                             \
2215                         ((_ext_id) >> 16) & 0xff,                       \
2216                         ((_ext_id) >> 8) & 0xff,                        \
2217                         (_ext_id) & 0xff,                               \
2218                         },                                              \
2219                 .id_len = 6,                                            \
2220                 .sector_size = (_sector_size),                          \
2221                 .n_sectors = (_n_sectors),                              \
2222                 .page_size = 256,                                       \
2223                 .flags = (_flags),
2224
2225 #define CAT25_INFO(_sector_size, _n_sectors, _page_size, _addr_width, _flags)   \
2226                 .sector_size = (_sector_size),                          \
2227                 .n_sectors = (_n_sectors),                              \
2228                 .page_size = (_page_size),                              \
2229                 .addr_width = (_addr_width),                            \
2230                 .flags = (_flags),
2231
2232 #define S3AN_INFO(_jedec_id, _n_sectors, _page_size)                    \
2233                 .id = {                                                 \
2234                         ((_jedec_id) >> 16) & 0xff,                     \
2235                         ((_jedec_id) >> 8) & 0xff,                      \
2236                         (_jedec_id) & 0xff                              \
2237                         },                                              \
2238                 .id_len = 3,                                            \
2239                 .sector_size = (8*_page_size),                          \
2240                 .n_sectors = (_n_sectors),                              \
2241                 .page_size = _page_size,                                \
2242                 .addr_width = 3,                                        \
2243                 .flags = SPI_NOR_NO_FR | SPI_S3AN,
2244
2245 static int
2246 is25lp256_post_bfpt_fixups(struct spi_nor *nor,
2247                            const struct sfdp_parameter_header *bfpt_header,
2248                            const struct sfdp_bfpt *bfpt,
2249                            struct spi_nor_flash_parameter *params)
2250 {
2251         /*
2252          * IS25LP256 supports 4B opcodes, but the BFPT advertises a
2253          * BFPT_DWORD1_ADDRESS_BYTES_3_ONLY address width.
2254          * Overwrite the address width advertised by the BFPT.
2255          */
2256         if ((bfpt->dwords[BFPT_DWORD(1)] & BFPT_DWORD1_ADDRESS_BYTES_MASK) ==
2257                 BFPT_DWORD1_ADDRESS_BYTES_3_ONLY)
2258                 nor->addr_width = 4;
2259
2260         return 0;
2261 }
2262
2263 static struct spi_nor_fixups is25lp256_fixups = {
2264         .post_bfpt = is25lp256_post_bfpt_fixups,
2265 };
2266
2267 static int
2268 mx25l25635_post_bfpt_fixups(struct spi_nor *nor,
2269                             const struct sfdp_parameter_header *bfpt_header,
2270                             const struct sfdp_bfpt *bfpt,
2271                             struct spi_nor_flash_parameter *params)
2272 {
2273         /*
2274          * MX25L25635F supports 4B opcodes but MX25L25635E does not.
2275          * Unfortunately, Macronix has re-used the same JEDEC ID for both
2276          * variants which prevents us from defining a new entry in the parts
2277          * table.
2278          * We need a way to differentiate MX25L25635E and MX25L25635F, and it
2279          * seems that the F version advertises support for Fast Read 4-4-4 in
2280          * its BFPT table.
2281          */
2282         if (bfpt->dwords[BFPT_DWORD(5)] & BFPT_DWORD5_FAST_READ_4_4_4)
2283                 nor->flags |= SNOR_F_4B_OPCODES;
2284
2285         return 0;
2286 }
2287
2288 static struct spi_nor_fixups mx25l25635_fixups = {
2289         .post_bfpt = mx25l25635_post_bfpt_fixups,
2290 };
2291
2292 static void gd25q256_default_init(struct spi_nor *nor)
2293 {
2294         /*
2295          * Some manufacturer like GigaDevice may use different
2296          * bit to set QE on different memories, so the MFR can't
2297          * indicate the quad_enable method for this case, we need
2298          * to set it in the default_init fixup hook.
2299          */
2300         nor->params.quad_enable = spi_nor_sr1_bit6_quad_enable;
2301 }
2302
2303 static struct spi_nor_fixups gd25q256_fixups = {
2304         .default_init = gd25q256_default_init,
2305 };
2306
2307 /* NOTE: double check command sets and memory organization when you add
2308  * more nor chips.  This current list focusses on newer chips, which
2309  * have been converging on command sets which including JEDEC ID.
2310  *
2311  * All newly added entries should describe *hardware* and should use SECT_4K
2312  * (or SECT_4K_PMC) if hardware supports erasing 4 KiB sectors. For usage
2313  * scenarios excluding small sectors there is config option that can be
2314  * disabled: CONFIG_MTD_SPI_NOR_USE_4K_SECTORS.
2315  * For historical (and compatibility) reasons (before we got above config) some
2316  * old entries may be missing 4K flag.
2317  */
2318 static const struct flash_info spi_nor_ids[] = {
2319         /* Atmel -- some are (confusingly) marketed as "DataFlash" */
2320         { "at25fs010",  INFO(0x1f6601, 0, 32 * 1024,   4, SECT_4K) },
2321         { "at25fs040",  INFO(0x1f6604, 0, 64 * 1024,   8, SECT_4K) },
2322
2323         { "at25df041a", INFO(0x1f4401, 0, 64 * 1024,   8, SECT_4K) },
2324         { "at25df321",  INFO(0x1f4700, 0, 64 * 1024,  64, SECT_4K) },
2325         { "at25df321a", INFO(0x1f4701, 0, 64 * 1024,  64, SECT_4K) },
2326         { "at25df641",  INFO(0x1f4800, 0, 64 * 1024, 128, SECT_4K) },
2327
2328         { "at25sl321",  INFO(0x1f4216, 0, 64 * 1024, 64,
2329                              SECT_4K | SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ) },
2330
2331         { "at26f004",   INFO(0x1f0400, 0, 64 * 1024,  8, SECT_4K) },
2332         { "at26df081a", INFO(0x1f4501, 0, 64 * 1024, 16, SECT_4K) },
2333         { "at26df161a", INFO(0x1f4601, 0, 64 * 1024, 32, SECT_4K) },
2334         { "at26df321",  INFO(0x1f4700, 0, 64 * 1024, 64, SECT_4K) },
2335
2336         { "at45db081d", INFO(0x1f2500, 0, 64 * 1024, 16, SECT_4K) },
2337
2338         /* EON -- en25xxx */
2339         { "en25f32",    INFO(0x1c3116, 0, 64 * 1024,   64, SECT_4K) },
2340         { "en25p32",    INFO(0x1c2016, 0, 64 * 1024,   64, 0) },
2341         { "en25q32b",   INFO(0x1c3016, 0, 64 * 1024,   64, 0) },
2342         { "en25p64",    INFO(0x1c2017, 0, 64 * 1024,  128, 0) },
2343         { "en25q64",    INFO(0x1c3017, 0, 64 * 1024,  128, SECT_4K) },
2344         { "en25q80a",   INFO(0x1c3014, 0, 64 * 1024,   16,
2345                         SECT_4K | SPI_NOR_DUAL_READ) },
2346         { "en25qh16",   INFO(0x1c7015, 0, 64 * 1024,   32,
2347                         SECT_4K | SPI_NOR_DUAL_READ) },
2348         { "en25qh32",   INFO(0x1c7016, 0, 64 * 1024,   64, 0) },
2349         { "en25qh64",   INFO(0x1c7017, 0, 64 * 1024,  128,
2350                         SECT_4K | SPI_NOR_DUAL_READ) },
2351         { "en25qh128",  INFO(0x1c7018, 0, 64 * 1024,  256, 0) },
2352         { "en25qh256",  INFO(0x1c7019, 0, 64 * 1024,  512, 0) },
2353         { "en25s64",    INFO(0x1c3817, 0, 64 * 1024,  128, SECT_4K) },
2354
2355         /* ESMT */
2356         { "f25l32pa", INFO(0x8c2016, 0, 64 * 1024, 64, SECT_4K | SPI_NOR_HAS_LOCK) },
2357         { "f25l32qa", INFO(0x8c4116, 0, 64 * 1024, 64, SECT_4K | SPI_NOR_HAS_LOCK) },
2358         { "f25l64qa", INFO(0x8c4117, 0, 64 * 1024, 128, SECT_4K | SPI_NOR_HAS_LOCK) },
2359
2360         /* Everspin */
2361         { "mr25h128", CAT25_INFO( 16 * 1024, 1, 256, 2, SPI_NOR_NO_ERASE | SPI_NOR_NO_FR) },
2362         { "mr25h256", CAT25_INFO( 32 * 1024, 1, 256, 2, SPI_NOR_NO_ERASE | SPI_NOR_NO_FR) },
2363         { "mr25h10",  CAT25_INFO(128 * 1024, 1, 256, 3, SPI_NOR_NO_ERASE | SPI_NOR_NO_FR) },
2364         { "mr25h40",  CAT25_INFO(512 * 1024, 1, 256, 3, SPI_NOR_NO_ERASE | SPI_NOR_NO_FR) },
2365
2366         /* Fujitsu */
2367         { "mb85rs1mt", INFO(0x047f27, 0, 128 * 1024, 1, SPI_NOR_NO_ERASE) },
2368
2369         /* GigaDevice */
2370         {
2371                 "gd25q16", INFO(0xc84015, 0, 64 * 1024,  32,
2372                         SECT_4K | SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ |
2373                         SPI_NOR_HAS_LOCK | SPI_NOR_HAS_TB)
2374         },
2375         {
2376                 "gd25q32", INFO(0xc84016, 0, 64 * 1024,  64,
2377                         SECT_4K | SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ |
2378                         SPI_NOR_HAS_LOCK | SPI_NOR_HAS_TB)
2379         },
2380         {
2381                 "gd25lq32", INFO(0xc86016, 0, 64 * 1024, 64,
2382                         SECT_4K | SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ |
2383                         SPI_NOR_HAS_LOCK | SPI_NOR_HAS_TB)
2384         },
2385         {
2386                 "gd25q64", INFO(0xc84017, 0, 64 * 1024, 128,
2387                         SECT_4K | SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ |
2388                         SPI_NOR_HAS_LOCK | SPI_NOR_HAS_TB)
2389         },
2390         {
2391                 "gd25lq64c", INFO(0xc86017, 0, 64 * 1024, 128,
2392                         SECT_4K | SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ |
2393                         SPI_NOR_HAS_LOCK | SPI_NOR_HAS_TB)
2394         },
2395         {
2396                 "gd25lq128d", INFO(0xc86018, 0, 64 * 1024, 256,
2397                         SECT_4K | SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ |
2398                         SPI_NOR_HAS_LOCK | SPI_NOR_HAS_TB)
2399         },
2400         {
2401                 "gd25q128", INFO(0xc84018, 0, 64 * 1024, 256,
2402                         SECT_4K | SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ |
2403                         SPI_NOR_HAS_LOCK | SPI_NOR_HAS_TB)
2404         },
2405         {
2406                 "gd25q256", INFO(0xc84019, 0, 64 * 1024, 512,
2407                         SECT_4K | SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ |
2408                         SPI_NOR_4B_OPCODES | SPI_NOR_HAS_LOCK | SPI_NOR_HAS_TB |
2409                         SPI_NOR_TB_SR_BIT6)
2410                         .fixups = &gd25q256_fixups,
2411         },
2412
2413         /* Intel/Numonyx -- xxxs33b */
2414         { "160s33b",  INFO(0x898911, 0, 64 * 1024,  32, 0) },
2415         { "320s33b",  INFO(0x898912, 0, 64 * 1024,  64, 0) },
2416         { "640s33b",  INFO(0x898913, 0, 64 * 1024, 128, 0) },
2417
2418         /* ISSI */
2419         { "is25cd512",  INFO(0x7f9d20, 0, 32 * 1024,   2, SECT_4K) },
2420         { "is25lq040b", INFO(0x9d4013, 0, 64 * 1024,   8,
2421                         SECT_4K | SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ) },
2422         { "is25lp016d", INFO(0x9d6015, 0, 64 * 1024,  32,
2423                         SECT_4K | SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ) },
2424         { "is25lp080d", INFO(0x9d6014, 0, 64 * 1024,  16,
2425                         SECT_4K | SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ) },
2426         { "is25lp032",  INFO(0x9d6016, 0, 64 * 1024,  64,
2427                         SECT_4K | SPI_NOR_DUAL_READ) },
2428         { "is25lp064",  INFO(0x9d6017, 0, 64 * 1024, 128,
2429                         SECT_4K | SPI_NOR_DUAL_READ) },
2430         { "is25lp128",  INFO(0x9d6018, 0, 64 * 1024, 256,
2431                         SECT_4K | SPI_NOR_DUAL_READ) },
2432         { "is25lp256",  INFO(0x9d6019, 0, 64 * 1024, 512,
2433                         SECT_4K | SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ |
2434                         SPI_NOR_4B_OPCODES)
2435                         .fixups = &is25lp256_fixups },
2436         { "is25wp032",  INFO(0x9d7016, 0, 64 * 1024,  64,
2437                         SECT_4K | SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ) },
2438         { "is25wp064",  INFO(0x9d7017, 0, 64 * 1024, 128,
2439                         SECT_4K | SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ) },
2440         { "is25wp128",  INFO(0x9d7018, 0, 64 * 1024, 256,
2441                         SECT_4K | SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ) },
2442         { "is25wp256", INFO(0x9d7019, 0, 64 * 1024, 512,
2443                             SECT_4K | SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ |
2444                             SPI_NOR_4B_OPCODES)
2445                        .fixups = &is25lp256_fixups },
2446
2447         /* Macronix */
2448         { "mx25l512e",   INFO(0xc22010, 0, 64 * 1024,   1, SECT_4K) },
2449         { "mx25l2005a",  INFO(0xc22012, 0, 64 * 1024,   4, SECT_4K) },
2450         { "mx25l4005a",  INFO(0xc22013, 0, 64 * 1024,   8, SECT_4K) },
2451         { "mx25l8005",   INFO(0xc22014, 0, 64 * 1024,  16, 0) },
2452         { "mx25l1606e",  INFO(0xc22015, 0, 64 * 1024,  32, SECT_4K) },
2453         { "mx25l3205d",  INFO(0xc22016, 0, 64 * 1024,  64, SECT_4K) },
2454         { "mx25l3255e",  INFO(0xc29e16, 0, 64 * 1024,  64, SECT_4K) },
2455         { "mx25l6405d",  INFO(0xc22017, 0, 64 * 1024, 128, SECT_4K) },
2456         { "mx25u2033e",  INFO(0xc22532, 0, 64 * 1024,   4, SECT_4K) },
2457         { "mx25u3235f",  INFO(0xc22536, 0, 64 * 1024,  64,
2458                          SECT_4K | SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ) },
2459         { "mx25u4035",   INFO(0xc22533, 0, 64 * 1024,   8, SECT_4K) },
2460         { "mx25u8035",   INFO(0xc22534, 0, 64 * 1024,  16, SECT_4K) },
2461         { "mx25u6435f",  INFO(0xc22537, 0, 64 * 1024, 128, SECT_4K) },
2462         { "mx25l12805d", INFO(0xc22018, 0, 64 * 1024, 256, 0) },
2463         { "mx25l12855e", INFO(0xc22618, 0, 64 * 1024, 256, 0) },
2464         { "mx25r3235f",  INFO(0xc22816, 0, 64 * 1024,  64,
2465                          SECT_4K | SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ) },
2466         { "mx25u12835f", INFO(0xc22538, 0, 64 * 1024, 256,
2467                          SECT_4K | SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ) },
2468         { "mx25l25635e", INFO(0xc22019, 0, 64 * 1024, 512,
2469                          SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ)
2470                          .fixups = &mx25l25635_fixups },
2471         { "mx25u25635f", INFO(0xc22539, 0, 64 * 1024, 512, SECT_4K | SPI_NOR_4B_OPCODES) },
2472         { "mx25v8035f",  INFO(0xc22314, 0, 64 * 1024,  16,
2473                          SECT_4K | SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ) },
2474         { "mx25l25655e", INFO(0xc22619, 0, 64 * 1024, 512, 0) },
2475         { "mx66l51235l", INFO(0xc2201a, 0, 64 * 1024, 1024, SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ | SPI_NOR_4B_OPCODES) },
2476         { "mx66u51235f", INFO(0xc2253a, 0, 64 * 1024, 1024, SECT_4K | SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ | SPI_NOR_4B_OPCODES) },
2477         { "mx66l1g45g",  INFO(0xc2201b, 0, 64 * 1024, 2048, SECT_4K | SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ) },
2478         { "mx66l1g55g",  INFO(0xc2261b, 0, 64 * 1024, 2048, SPI_NOR_QUAD_READ) },
2479
2480         /* Micron <--> ST Micro */
2481         { "n25q016a",    INFO(0x20bb15, 0, 64 * 1024,   32, SECT_4K | SPI_NOR_QUAD_READ) },
2482         { "n25q032",     INFO(0x20ba16, 0, 64 * 1024,   64, SPI_NOR_QUAD_READ) },
2483         { "n25q032a",    INFO(0x20bb16, 0, 64 * 1024,   64, SPI_NOR_QUAD_READ) },
2484         { "n25q064",     INFO(0x20ba17, 0, 64 * 1024,  128, SECT_4K | SPI_NOR_QUAD_READ) },
2485         { "n25q064a",    INFO(0x20bb17, 0, 64 * 1024,  128, SECT_4K | SPI_NOR_QUAD_READ) },
2486         { "n25q128a11",  INFO(0x20bb18, 0, 64 * 1024,  256, SECT_4K |
2487                               USE_FSR | SPI_NOR_QUAD_READ) },
2488         { "n25q128a13",  INFO(0x20ba18, 0, 64 * 1024,  256, SECT_4K |
2489                               USE_FSR | SPI_NOR_QUAD_READ) },
2490         { "mt25ql256a",  INFO6(0x20ba19, 0x104400, 64 * 1024,  512,
2491                                SECT_4K | USE_FSR | SPI_NOR_DUAL_READ |
2492                                SPI_NOR_QUAD_READ | SPI_NOR_4B_OPCODES) },
2493         { "n25q256a",    INFO(0x20ba19, 0, 64 * 1024,  512, SECT_4K |
2494                               USE_FSR | SPI_NOR_DUAL_READ |
2495                               SPI_NOR_QUAD_READ) },
2496         { "mt25qu256a",  INFO6(0x20bb19, 0x104400, 64 * 1024,  512,
2497                                SECT_4K | USE_FSR | SPI_NOR_DUAL_READ |
2498                                SPI_NOR_QUAD_READ | SPI_NOR_4B_OPCODES) },
2499         { "n25q256ax1",  INFO(0x20bb19, 0, 64 * 1024,  512, SECT_4K |
2500                               USE_FSR | SPI_NOR_QUAD_READ) },
2501         { "mt25ql512a",  INFO6(0x20ba20, 0x104400, 64 * 1024, 1024,
2502                                SECT_4K | USE_FSR | SPI_NOR_DUAL_READ |
2503                                SPI_NOR_QUAD_READ | SPI_NOR_4B_OPCODES) },
2504         { "n25q512ax3",  INFO(0x20ba20, 0, 64 * 1024, 1024, SECT_4K | USE_FSR | SPI_NOR_QUAD_READ) },
2505         { "mt25qu512a",  INFO6(0x20bb20, 0x104400, 64 * 1024, 1024,
2506                                SECT_4K | USE_FSR | SPI_NOR_DUAL_READ |
2507                                SPI_NOR_QUAD_READ | SPI_NOR_4B_OPCODES) },
2508         { "n25q512a",    INFO(0x20bb20, 0, 64 * 1024, 1024, SECT_4K |
2509                               USE_FSR | SPI_NOR_QUAD_READ) },
2510         { "n25q00",      INFO(0x20ba21, 0, 64 * 1024, 2048, SECT_4K | USE_FSR | SPI_NOR_QUAD_READ | NO_CHIP_ERASE) },
2511         { "n25q00a",     INFO(0x20bb21, 0, 64 * 1024, 2048, SECT_4K | USE_FSR | SPI_NOR_QUAD_READ | NO_CHIP_ERASE) },
2512         { "mt25ql02g",   INFO(0x20ba22, 0, 64 * 1024, 4096,
2513                               SECT_4K | USE_FSR | SPI_NOR_QUAD_READ |
2514                               NO_CHIP_ERASE) },
2515         { "mt25qu02g",   INFO(0x20bb22, 0, 64 * 1024, 4096, SECT_4K | USE_FSR | SPI_NOR_QUAD_READ | NO_CHIP_ERASE) },
2516
2517         /* Micron */
2518         {
2519                 "mt35xu512aba", INFO(0x2c5b1a, 0, 128 * 1024, 512,
2520                         SECT_4K | USE_FSR | SPI_NOR_OCTAL_READ |
2521                         SPI_NOR_4B_OPCODES)
2522         },
2523         { "mt35xu02g",  INFO(0x2c5b1c, 0, 128 * 1024, 2048,
2524                              SECT_4K | USE_FSR | SPI_NOR_OCTAL_READ |
2525                              SPI_NOR_4B_OPCODES) },
2526
2527         /* PMC */
2528         { "pm25lv512",   INFO(0,        0, 32 * 1024,    2, SECT_4K_PMC) },
2529         { "pm25lv010",   INFO(0,        0, 32 * 1024,    4, SECT_4K_PMC) },
2530         { "pm25lq032",   INFO(0x7f9d46, 0, 64 * 1024,   64, SECT_4K) },
2531
2532         /* Spansion/Cypress -- single (large) sector size only, at least
2533          * for the chips listed here (without boot sectors).
2534          */
2535         { "s25sl032p",  INFO(0x010215, 0x4d00,  64 * 1024,  64, SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ) },
2536         { "s25sl064p",  INFO(0x010216, 0x4d00,  64 * 1024, 128, SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ) },
2537         { "s25fl128s0", INFO6(0x012018, 0x4d0080, 256 * 1024, 64,
2538                         SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ | USE_CLSR) },
2539         { "s25fl128s1", INFO6(0x012018, 0x4d0180, 64 * 1024, 256,
2540                         SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ | USE_CLSR) },
2541         { "s25fl256s0", INFO(0x010219, 0x4d00, 256 * 1024, 128, USE_CLSR) },
2542         { "s25fl256s1", INFO(0x010219, 0x4d01,  64 * 1024, 512, SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ | USE_CLSR) },
2543         { "s25fl512s",  INFO6(0x010220, 0x4d0080, 256 * 1024, 256,
2544                         SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ |
2545                         SPI_NOR_HAS_LOCK | USE_CLSR) },
2546         { "s25fs512s",  INFO6(0x010220, 0x4d0081, 256 * 1024, 256, SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ | USE_CLSR) },
2547         { "s70fl01gs",  INFO(0x010221, 0x4d00, 256 * 1024, 256, 0) },
2548         { "s25sl12800", INFO(0x012018, 0x0300, 256 * 1024,  64, 0) },
2549         { "s25sl12801", INFO(0x012018, 0x0301,  64 * 1024, 256, 0) },
2550         { "s25fl129p0", INFO(0x012018, 0x4d00, 256 * 1024,  64, SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ | USE_CLSR) },
2551         { "s25fl129p1", INFO(0x012018, 0x4d01,  64 * 1024, 256, SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ | USE_CLSR) },
2552         { "s25sl004a",  INFO(0x010212,      0,  64 * 1024,   8, 0) },
2553         { "s25sl008a",  INFO(0x010213,      0,  64 * 1024,  16, 0) },
2554         { "s25sl016a",  INFO(0x010214,      0,  64 * 1024,  32, 0) },
2555         { "s25sl032a",  INFO(0x010215,      0,  64 * 1024,  64, 0) },
2556         { "s25sl064a",  INFO(0x010216,      0,  64 * 1024, 128, 0) },
2557         { "s25fl004k",  INFO(0xef4013,      0,  64 * 1024,   8, SECT_4K | SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ) },
2558         { "s25fl008k",  INFO(0xef4014,      0,  64 * 1024,  16, SECT_4K | SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ) },
2559         { "s25fl016k",  INFO(0xef4015,      0,  64 * 1024,  32, SECT_4K | SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ) },
2560         { "s25fl064k",  INFO(0xef4017,      0,  64 * 1024, 128, SECT_4K) },
2561         { "s25fl116k",  INFO(0x014015,      0,  64 * 1024,  32, SECT_4K | SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ) },
2562         { "s25fl132k",  INFO(0x014016,      0,  64 * 1024,  64, SECT_4K) },
2563         { "s25fl164k",  INFO(0x014017,      0,  64 * 1024, 128, SECT_4K) },
2564         { "s25fl204k",  INFO(0x014013,      0,  64 * 1024,   8, SECT_4K | SPI_NOR_DUAL_READ) },
2565         { "s25fl208k",  INFO(0x014014,      0,  64 * 1024,  16, SECT_4K | SPI_NOR_DUAL_READ) },
2566         { "s25fl064l",  INFO(0x016017,      0,  64 * 1024, 128, SECT_4K | SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ | SPI_NOR_4B_OPCODES) },
2567         { "s25fl128l",  INFO(0x016018,      0,  64 * 1024, 256, SECT_4K | SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ | SPI_NOR_4B_OPCODES) },
2568         { "s25fl256l",  INFO(0x016019,      0,  64 * 1024, 512, SECT_4K | SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ | SPI_NOR_4B_OPCODES) },
2569
2570         /* SST -- large erase sizes are "overlays", "sectors" are 4K */
2571         { "sst25vf040b", INFO(0xbf258d, 0, 64 * 1024,  8, SECT_4K | SST_WRITE) },
2572         { "sst25vf080b", INFO(0xbf258e, 0, 64 * 1024, 16, SECT_4K | SST_WRITE) },
2573         { "sst25vf016b", INFO(0xbf2541, 0, 64 * 1024, 32, SECT_4K | SST_WRITE) },
2574         { "sst25vf032b", INFO(0xbf254a, 0, 64 * 1024, 64, SECT_4K | SST_WRITE) },
2575         { "sst25vf064c", INFO(0xbf254b, 0, 64 * 1024, 128, SECT_4K) },
2576         { "sst25wf512",  INFO(0xbf2501, 0, 64 * 1024,  1, SECT_4K | SST_WRITE) },
2577         { "sst25wf010",  INFO(0xbf2502, 0, 64 * 1024,  2, SECT_4K | SST_WRITE) },
2578         { "sst25wf020",  INFO(0xbf2503, 0, 64 * 1024,  4, SECT_4K | SST_WRITE) },
2579         { "sst25wf020a", INFO(0x621612, 0, 64 * 1024,  4, SECT_4K) },
2580         { "sst25wf040b", INFO(0x621613, 0, 64 * 1024,  8, SECT_4K) },
2581         { "sst25wf040",  INFO(0xbf2504, 0, 64 * 1024,  8, SECT_4K | SST_WRITE) },
2582         { "sst25wf080",  INFO(0xbf2505, 0, 64 * 1024, 16, SECT_4K | SST_WRITE) },
2583         { "sst26wf016b", INFO(0xbf2651, 0, 64 * 1024, 32, SECT_4K |
2584                               SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ) },
2585         { "sst26vf016b", INFO(0xbf2641, 0, 64 * 1024, 32, SECT_4K |
2586                               SPI_NOR_DUAL_READ) },
2587         { "sst26vf064b", INFO(0xbf2643, 0, 64 * 1024, 128, SECT_4K | SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ) },
2588
2589         /* ST Microelectronics -- newer production may have feature updates */
2590         { "m25p05",  INFO(0x202010,  0,  32 * 1024,   2, 0) },
2591         { "m25p10",  INFO(0x202011,  0,  32 * 1024,   4, 0) },
2592         { "m25p20",  INFO(0x202012,  0,  64 * 1024,   4, 0) },
2593         { "m25p40",  INFO(0x202013,  0,  64 * 1024,   8, 0) },
2594         { "m25p80",  INFO(0x202014,  0,  64 * 1024,  16, 0) },
2595         { "m25p16",  INFO(0x202015,  0,  64 * 1024,  32, 0) },
2596         { "m25p32",  INFO(0x202016,  0,  64 * 1024,  64, 0) },
2597         { "m25p64",  INFO(0x202017,  0,  64 * 1024, 128, 0) },
2598         { "m25p128", INFO(0x202018,  0, 256 * 1024,  64, 0) },
2599
2600         { "m25p05-nonjedec",  INFO(0, 0,  32 * 1024,   2, 0) },
2601         { "m25p10-nonjedec",  INFO(0, 0,  32 * 1024,   4, 0) },
2602         { "m25p20-nonjedec",  INFO(0, 0,  64 * 1024,   4, 0) },
2603         { "m25p40-nonjedec",  INFO(0, 0,  64 * 1024,   8, 0) },
2604         { "m25p80-nonjedec",  INFO(0, 0,  64 * 1024,  16, 0) },
2605         { "m25p16-nonjedec",  INFO(0, 0,  64 * 1024,  32, 0) },
2606         { "m25p32-nonjedec",  INFO(0, 0,  64 * 1024,  64, 0) },
2607         { "m25p64-nonjedec",  INFO(0, 0,  64 * 1024, 128, 0) },
2608         { "m25p128-nonjedec", INFO(0, 0, 256 * 1024,  64, 0) },
2609
2610         { "m45pe10", INFO(0x204011,  0, 64 * 1024,    2, 0) },
2611         { "m45pe80", INFO(0x204014,  0, 64 * 1024,   16, 0) },
2612         { "m45pe16", INFO(0x204015,  0, 64 * 1024,   32, 0) },
2613
2614         { "m25pe20", INFO(0x208012,  0, 64 * 1024,  4,       0) },
2615         { "m25pe80", INFO(0x208014,  0, 64 * 1024, 16,       0) },
2616         { "m25pe16", INFO(0x208015,  0, 64 * 1024, 32, SECT_4K) },
2617
2618         { "m25px16",    INFO(0x207115,  0, 64 * 1024, 32, SECT_4K) },
2619         { "m25px32",    INFO(0x207116,  0, 64 * 1024, 64, SECT_4K) },
2620         { "m25px32-s0", INFO(0x207316,  0, 64 * 1024, 64, SECT_4K) },
2621         { "m25px32-s1", INFO(0x206316,  0, 64 * 1024, 64, SECT_4K) },
2622         { "m25px64",    INFO(0x207117,  0, 64 * 1024, 128, 0) },
2623         { "m25px80",    INFO(0x207114,  0, 64 * 1024, 16, 0) },
2624
2625         /* Winbond -- w25x "blocks" are 64K, "sectors" are 4KiB */
2626         { "w25x05", INFO(0xef3010, 0, 64 * 1024,  1,  SECT_4K) },
2627         { "w25x10", INFO(0xef3011, 0, 64 * 1024,  2,  SECT_4K) },
2628         { "w25x20", INFO(0xef3012, 0, 64 * 1024,  4,  SECT_4K) },
2629         { "w25x40", INFO(0xef3013, 0, 64 * 1024,  8,  SECT_4K) },
2630         { "w25x80", INFO(0xef3014, 0, 64 * 1024,  16, SECT_4K) },
2631         { "w25x16", INFO(0xef3015, 0, 64 * 1024,  32, SECT_4K) },
2632         {
2633                 "w25q16dw", INFO(0xef6015, 0, 64 * 1024,  32,
2634                         SECT_4K | SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ |
2635                         SPI_NOR_HAS_LOCK | SPI_NOR_HAS_TB)
2636         },
2637         { "w25x32", INFO(0xef3016, 0, 64 * 1024,  64, SECT_4K) },
2638         {
2639                 "w25q16jv-im/jm", INFO(0xef7015, 0, 64 * 1024,  32,
2640                         SECT_4K | SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ |
2641                         SPI_NOR_HAS_LOCK | SPI_NOR_HAS_TB)
2642         },
2643         { "w25q20cl", INFO(0xef4012, 0, 64 * 1024,  4, SECT_4K) },
2644         { "w25q20bw", INFO(0xef5012, 0, 64 * 1024,  4, SECT_4K) },
2645         { "w25q20ew", INFO(0xef6012, 0, 64 * 1024,  4, SECT_4K) },
2646         { "w25q32", INFO(0xef4016, 0, 64 * 1024,  64, SECT_4K) },
2647         {
2648                 "w25q32dw", INFO(0xef6016, 0, 64 * 1024,  64,
2649                         SECT_4K | SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ |
2650                         SPI_NOR_HAS_LOCK | SPI_NOR_HAS_TB)
2651         },
2652         {
2653                 "w25q32jv", INFO(0xef7016, 0, 64 * 1024,  64,
2654                         SECT_4K | SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ |
2655                         SPI_NOR_HAS_LOCK | SPI_NOR_HAS_TB)
2656         },
2657         {
2658                 "w25q32jwm", INFO(0xef8016, 0, 64 * 1024,  64,
2659                         SECT_4K | SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ |
2660                         SPI_NOR_HAS_LOCK | SPI_NOR_HAS_TB)
2661         },
2662         { "w25x64", INFO(0xef3017, 0, 64 * 1024, 128, SECT_4K) },
2663         { "w25q64", INFO(0xef4017, 0, 64 * 1024, 128, SECT_4K) },
2664         {
2665                 "w25q64dw", INFO(0xef6017, 0, 64 * 1024, 128,
2666                         SECT_4K | SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ |
2667                         SPI_NOR_HAS_LOCK | SPI_NOR_HAS_TB)
2668         },
2669         {
2670                 "w25q128fw", INFO(0xef6018, 0, 64 * 1024, 256,
2671                         SECT_4K | SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ |
2672                         SPI_NOR_HAS_LOCK | SPI_NOR_HAS_TB)
2673         },
2674         {
2675                 "w25q128jv", INFO(0xef7018, 0, 64 * 1024, 256,
2676                         SECT_4K | SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ |
2677                         SPI_NOR_HAS_LOCK | SPI_NOR_HAS_TB)
2678         },
2679         { "w25q80", INFO(0xef5014, 0, 64 * 1024,  16, SECT_4K) },
2680         { "w25q80bl", INFO(0xef4014, 0, 64 * 1024,  16, SECT_4K) },
2681         { "w25q128", INFO(0xef4018, 0, 64 * 1024, 256, SECT_4K) },
2682         { "w25q256", INFO(0xef4019, 0, 64 * 1024, 512,
2683                           SECT_4K | SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ |
2684                           SPI_NOR_4B_OPCODES) },
2685         { "w25q256jvm", INFO(0xef7019, 0, 64 * 1024, 512,
2686                              SECT_4K | SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ) },
2687         { "w25q256jw", INFO(0xef6019, 0, 64 * 1024, 512,
2688                              SECT_4K | SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ) },
2689         { "w25m512jv", INFO(0xef7119, 0, 64 * 1024, 1024,
2690                         SECT_4K | SPI_NOR_QUAD_READ | SPI_NOR_DUAL_READ) },
2691
2692         /* Catalyst / On Semiconductor -- non-JEDEC */
2693         { "cat25c11", CAT25_INFO(  16, 8, 16, 1, SPI_NOR_NO_ERASE | SPI_NOR_NO_FR) },
2694         { "cat25c03", CAT25_INFO(  32, 8, 16, 2, SPI_NOR_NO_ERASE | SPI_NOR_NO_FR) },
2695         { "cat25c09", CAT25_INFO( 128, 8, 32, 2, SPI_NOR_NO_ERASE | SPI_NOR_NO_FR) },
2696         { "cat25c17", CAT25_INFO( 256, 8, 32, 2, SPI_NOR_NO_ERASE | SPI_NOR_NO_FR) },
2697         { "cat25128", CAT25_INFO(2048, 8, 64, 2, SPI_NOR_NO_ERASE | SPI_NOR_NO_FR) },
2698
2699         /* Xilinx S3AN Internal Flash */
2700         { "3S50AN", S3AN_INFO(0x1f2200, 64, 264) },
2701         { "3S200AN", S3AN_INFO(0x1f2400, 256, 264) },
2702         { "3S400AN", S3AN_INFO(0x1f2400, 256, 264) },
2703         { "3S700AN", S3AN_INFO(0x1f2500, 512, 264) },
2704         { "3S1400AN", S3AN_INFO(0x1f2600, 512, 528) },
2705
2706         /* XMC (Wuhan Xinxin Semiconductor Manufacturing Corp.) */
2707         { "XM25QH64A", INFO(0x207017, 0, 64 * 1024, 128, SECT_4K | SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ) },
2708         { "XM25QH128A", INFO(0x207018, 0, 64 * 1024, 256, SECT_4K | SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ) },
2709         { },
2710 };
2711
2712 static const struct flash_info *spi_nor_read_id(struct spi_nor *nor)
2713 {
2714         int                     tmp;
2715         u8                      *id = nor->bouncebuf;
2716         const struct flash_info *info;
2717
2718         if (nor->spimem) {
2719                 struct spi_mem_op op =
2720                         SPI_MEM_OP(SPI_MEM_OP_CMD(SPINOR_OP_RDID, 1),
2721                                    SPI_MEM_OP_NO_ADDR,
2722                                    SPI_MEM_OP_NO_DUMMY,
2723                                    SPI_MEM_OP_DATA_IN(SPI_NOR_MAX_ID_LEN, id, 1));
2724
2725                 tmp = spi_mem_exec_op(nor->spimem, &op);
2726         } else {
2727                 tmp = nor->controller_ops->read_reg(nor, SPINOR_OP_RDID, id,
2728                                                     SPI_NOR_MAX_ID_LEN);
2729         }
2730         if (tmp) {
2731                 dev_dbg(nor->dev, "error %d reading JEDEC ID\n", tmp);
2732                 return ERR_PTR(tmp);
2733         }
2734
2735         for (tmp = 0; tmp < ARRAY_SIZE(spi_nor_ids) - 1; tmp++) {
2736                 info = &spi_nor_ids[tmp];
2737                 if (info->id_len) {
2738                         if (!memcmp(info->id, id, info->id_len))
2739                                 return &spi_nor_ids[tmp];
2740                 }
2741         }
2742         dev_err(nor->dev, "unrecognized JEDEC id bytes: %*ph\n",
2743                 SPI_NOR_MAX_ID_LEN, id);
2744         return ERR_PTR(-ENODEV);
2745 }
2746
2747 static int spi_nor_read(struct mtd_info *mtd, loff_t from, size_t len,
2748                         size_t *retlen, u_char *buf)
2749 {
2750         struct spi_nor *nor = mtd_to_spi_nor(mtd);
2751         ssize_t ret;
2752
2753         dev_dbg(nor->dev, "from 0x%08x, len %zd\n", (u32)from, len);
2754
2755         ret = spi_nor_lock_and_prep(nor);
2756         if (ret)
2757                 return ret;
2758
2759         while (len) {
2760                 loff_t addr = from;
2761
2762                 addr = spi_nor_convert_addr(nor, addr);
2763
2764                 ret = spi_nor_read_data(nor, addr, len, buf);
2765                 if (ret == 0) {
2766                         /* We shouldn't see 0-length reads */
2767                         ret = -EIO;
2768                         goto read_err;
2769                 }
2770                 if (ret < 0)
2771                         goto read_err;
2772
2773                 WARN_ON(ret > len);
2774                 *retlen += ret;
2775                 buf += ret;
2776                 from += ret;
2777                 len -= ret;
2778         }
2779         ret = 0;
2780
2781 read_err:
2782         spi_nor_unlock_and_unprep(nor);
2783         return ret;
2784 }
2785
2786 static int sst_write(struct mtd_info *mtd, loff_t to, size_t len,
2787                 size_t *retlen, const u_char *buf)
2788 {
2789         struct spi_nor *nor = mtd_to_spi_nor(mtd);
2790         size_t actual = 0;
2791         int ret;
2792
2793         dev_dbg(nor->dev, "to 0x%08x, len %zd\n", (u32)to, len);
2794
2795         ret = spi_nor_lock_and_prep(nor);
2796         if (ret)
2797                 return ret;
2798
2799         ret = spi_nor_write_enable(nor);
2800         if (ret)
2801                 goto out;
2802
2803         nor->sst_write_second = false;
2804
2805         /* Start write from odd address. */
2806         if (to % 2) {
2807                 nor->program_opcode = SPINOR_OP_BP;
2808
2809                 /* write one byte. */
2810                 ret = spi_nor_write_data(nor, to, 1, buf);
2811                 if (ret < 0)
2812                         goto out;
2813                 WARN(ret != 1, "While writing 1 byte written %i bytes\n", ret);
2814                 ret = spi_nor_wait_till_ready(nor);
2815                 if (ret)
2816                         goto out;
2817
2818                 to++;
2819                 actual++;
2820         }
2821
2822         /* Write out most of the data here. */
2823         for (; actual < len - 1; actual += 2) {
2824                 nor->program_opcode = SPINOR_OP_AAI_WP;
2825
2826                 /* write two bytes. */
2827                 ret = spi_nor_write_data(nor, to, 2, buf + actual);
2828                 if (ret < 0)
2829                         goto out;
2830                 WARN(ret != 2, "While writing 2 bytes written %i bytes\n", ret);
2831                 ret = spi_nor_wait_till_ready(nor);
2832                 if (ret)
2833                         goto out;
2834                 to += 2;
2835                 nor->sst_write_second = true;
2836         }
2837         nor->sst_write_second = false;
2838
2839         ret = spi_nor_write_disable(nor);
2840         if (ret)
2841                 goto out;
2842
2843         ret = spi_nor_wait_till_ready(nor);
2844         if (ret)
2845                 goto out;
2846
2847         /* Write out trailing byte if it exists. */
2848         if (actual != len) {
2849                 ret = spi_nor_write_enable(nor);
2850                 if (ret)
2851                         goto out;
2852
2853                 nor->program_opcode = SPINOR_OP_BP;
2854                 ret = spi_nor_write_data(nor, to, 1, buf + actual);
2855                 if (ret < 0)
2856                         goto out;
2857                 WARN(ret != 1, "While writing 1 byte written %i bytes\n", ret);
2858                 ret = spi_nor_wait_till_ready(nor);
2859                 if (ret)
2860                         goto out;
2861
2862                 actual += 1;
2863
2864                 ret = spi_nor_write_disable(nor);
2865         }
2866 out:
2867         *retlen += actual;
2868         spi_nor_unlock_and_unprep(nor);
2869         return ret;
2870 }
2871
2872 /*
2873  * Write an address range to the nor chip.  Data must be written in
2874  * FLASH_PAGESIZE chunks.  The address range may be any size provided
2875  * it is within the physical boundaries.
2876  */
2877 static int spi_nor_write(struct mtd_info *mtd, loff_t to, size_t len,
2878         size_t *retlen, const u_char *buf)
2879 {
2880         struct spi_nor *nor = mtd_to_spi_nor(mtd);
2881         size_t page_offset, page_remain, i;
2882         ssize_t ret;
2883
2884         dev_dbg(nor->dev, "to 0x%08x, len %zd\n", (u32)to, len);
2885
2886         ret = spi_nor_lock_and_prep(nor);
2887         if (ret)
2888                 return ret;
2889
2890         for (i = 0; i < len; ) {
2891                 ssize_t written;
2892                 loff_t addr = to + i;
2893
2894                 /*
2895                  * If page_size is a power of two, the offset can be quickly
2896                  * calculated with an AND operation. On the other cases we
2897                  * need to do a modulus operation (more expensive).
2898                  * Power of two numbers have only one bit set and we can use
2899                  * the instruction hweight32 to detect if we need to do a
2900                  * modulus (do_div()) or not.
2901                  */
2902                 if (hweight32(nor->page_size) == 1) {
2903                         page_offset = addr & (nor->page_size - 1);
2904                 } else {
2905                         uint64_t aux = addr;
2906
2907                         page_offset = do_div(aux, nor->page_size);
2908                 }
2909                 /* the size of data remaining on the first page */
2910                 page_remain = min_t(size_t,
2911                                     nor->page_size - page_offset, len - i);
2912
2913                 addr = spi_nor_convert_addr(nor, addr);
2914
2915                 ret = spi_nor_write_enable(nor);
2916                 if (ret)
2917                         goto write_err;
2918
2919                 ret = spi_nor_write_data(nor, addr, page_remain, buf + i);
2920                 if (ret < 0)
2921                         goto write_err;
2922                 written = ret;
2923
2924                 ret = spi_nor_wait_till_ready(nor);
2925                 if (ret)
2926                         goto write_err;
2927                 *retlen += written;
2928                 i += written;
2929         }
2930
2931 write_err:
2932         spi_nor_unlock_and_unprep(nor);
2933         return ret;
2934 }
2935
2936 static int spi_nor_check(struct spi_nor *nor)
2937 {
2938         if (!nor->dev ||
2939             (!nor->spimem && !nor->controller_ops) ||
2940             (!nor->spimem && nor->controller_ops &&
2941             (!nor->controller_ops->read ||
2942              !nor->controller_ops->write ||
2943              !nor->controller_ops->read_reg ||
2944              !nor->controller_ops->write_reg))) {
2945                 pr_err("spi-nor: please fill all the necessary fields!\n");
2946                 return -EINVAL;
2947         }
2948
2949         if (nor->spimem && nor->controller_ops) {
2950                 dev_err(nor->dev, "nor->spimem and nor->controller_ops are mutually exclusive, please set just one of them.\n");
2951                 return -EINVAL;
2952         }
2953
2954         return 0;
2955 }
2956
2957 static int s3an_nor_setup(struct spi_nor *nor,
2958                           const struct spi_nor_hwcaps *hwcaps)
2959 {
2960         int ret;
2961
2962         ret = spi_nor_xread_sr(nor, nor->bouncebuf);
2963         if (ret)
2964                 return ret;
2965
2966         nor->erase_opcode = SPINOR_OP_XSE;
2967         nor->program_opcode = SPINOR_OP_XPP;
2968         nor->read_opcode = SPINOR_OP_READ;
2969         nor->flags |= SNOR_F_NO_OP_CHIP_ERASE;
2970
2971         /*
2972          * This flashes have a page size of 264 or 528 bytes (known as
2973          * Default addressing mode). It can be changed to a more standard
2974          * Power of two mode where the page size is 256/512. This comes
2975          * with a price: there is 3% less of space, the data is corrupted
2976          * and the page size cannot be changed back to default addressing
2977          * mode.
2978          *
2979          * The current addressing mode can be read from the XRDSR register
2980          * and should not be changed, because is a destructive operation.
2981          */
2982         if (nor->bouncebuf[0] & XSR_PAGESIZE) {
2983                 /* Flash in Power of 2 mode */
2984                 nor->page_size = (nor->page_size == 264) ? 256 : 512;
2985                 nor->mtd.writebufsize = nor->page_size;
2986                 nor->mtd.size = 8 * nor->page_size * nor->info->n_sectors;
2987                 nor->mtd.erasesize = 8 * nor->page_size;
2988         } else {
2989                 /* Flash in Default addressing mode */
2990                 nor->params.convert_addr = s3an_convert_addr;
2991                 nor->mtd.erasesize = nor->info->sector_size;
2992         }
2993
2994         return 0;
2995 }
2996
2997 static void
2998 spi_nor_set_read_settings(struct spi_nor_read_command *read,
2999                           u8 num_mode_clocks,
3000                           u8 num_wait_states,
3001                           u8 opcode,
3002                           enum spi_nor_protocol proto)
3003 {
3004         read->num_mode_clocks = num_mode_clocks;
3005         read->num_wait_states = num_wait_states;
3006         read->opcode = opcode;
3007         read->proto = proto;
3008 }
3009
3010 static void
3011 spi_nor_set_pp_settings(struct spi_nor_pp_command *pp,
3012                         u8 opcode,
3013                         enum spi_nor_protocol proto)
3014 {
3015         pp->opcode = opcode;
3016         pp->proto = proto;
3017 }
3018
3019 static int spi_nor_hwcaps2cmd(u32 hwcaps, const int table[][2], size_t size)
3020 {
3021         size_t i;
3022
3023         for (i = 0; i < size; i++)
3024                 if (table[i][0] == (int)hwcaps)
3025                         return table[i][1];
3026
3027         return -EINVAL;
3028 }
3029
3030 static int spi_nor_hwcaps_read2cmd(u32 hwcaps)
3031 {
3032         static const int hwcaps_read2cmd[][2] = {
3033                 { SNOR_HWCAPS_READ,             SNOR_CMD_READ },
3034                 { SNOR_HWCAPS_READ_FAST,        SNOR_CMD_READ_FAST },
3035                 { SNOR_HWCAPS_READ_1_1_1_DTR,   SNOR_CMD_READ_1_1_1_DTR },
3036                 { SNOR_HWCAPS_READ_1_1_2,       SNOR_CMD_READ_1_1_2 },
3037                 { SNOR_HWCAPS_READ_1_2_2,       SNOR_CMD_READ_1_2_2 },
3038                 { SNOR_HWCAPS_READ_2_2_2,       SNOR_CMD_READ_2_2_2 },
3039                 { SNOR_HWCAPS_READ_1_2_2_DTR,   SNOR_CMD_READ_1_2_2_DTR },
3040                 { SNOR_HWCAPS_READ_1_1_4,       SNOR_CMD_READ_1_1_4 },
3041                 { SNOR_HWCAPS_READ_1_4_4,       SNOR_CMD_READ_1_4_4 },
3042                 { SNOR_HWCAPS_READ_4_4_4,       SNOR_CMD_READ_4_4_4 },
3043                 { SNOR_HWCAPS_READ_1_4_4_DTR,   SNOR_CMD_READ_1_4_4_DTR },
3044                 { SNOR_HWCAPS_READ_1_1_8,       SNOR_CMD_READ_1_1_8 },
3045                 { SNOR_HWCAPS_READ_1_8_8,       SNOR_CMD_READ_1_8_8 },
3046                 { SNOR_HWCAPS_READ_8_8_8,       SNOR_CMD_READ_8_8_8 },
3047                 { SNOR_HWCAPS_READ_1_8_8_DTR,   SNOR_CMD_READ_1_8_8_DTR },
3048         };
3049
3050         return spi_nor_hwcaps2cmd(hwcaps, hwcaps_read2cmd,
3051                                   ARRAY_SIZE(hwcaps_read2cmd));
3052 }
3053
3054 static int spi_nor_hwcaps_pp2cmd(u32 hwcaps)
3055 {
3056         static const int hwcaps_pp2cmd[][2] = {
3057                 { SNOR_HWCAPS_PP,               SNOR_CMD_PP },
3058                 { SNOR_HWCAPS_PP_1_1_4,         SNOR_CMD_PP_1_1_4 },
3059                 { SNOR_HWCAPS_PP_1_4_4,         SNOR_CMD_PP_1_4_4 },
3060                 { SNOR_HWCAPS_PP_4_4_4,         SNOR_CMD_PP_4_4_4 },
3061                 { SNOR_HWCAPS_PP_1_1_8,         SNOR_CMD_PP_1_1_8 },
3062                 { SNOR_HWCAPS_PP_1_8_8,         SNOR_CMD_PP_1_8_8 },
3063                 { SNOR_HWCAPS_PP_8_8_8,         SNOR_CMD_PP_8_8_8 },
3064         };
3065
3066         return spi_nor_hwcaps2cmd(hwcaps, hwcaps_pp2cmd,
3067                                   ARRAY_SIZE(hwcaps_pp2cmd));
3068 }
3069
3070 /*
3071  * Serial Flash Discoverable Parameters (SFDP) parsing.
3072  */
3073
3074 /**
3075  * spi_nor_read_raw() - raw read of serial flash memory. read_opcode,
3076  *                      addr_width and read_dummy members of the struct spi_nor
3077  *                      should be previously
3078  * set.
3079  * @nor:        pointer to a 'struct spi_nor'
3080  * @addr:       offset in the serial flash memory
3081  * @len:        number of bytes to read
3082  * @buf:        buffer where the data is copied into (dma-safe memory)
3083  *
3084  * Return: 0 on success, -errno otherwise.
3085  */
3086 static int spi_nor_read_raw(struct spi_nor *nor, u32 addr, size_t len, u8 *buf)
3087 {
3088         ssize_t ret;
3089
3090         while (len) {
3091                 ret = spi_nor_read_data(nor, addr, len, buf);
3092                 if (ret < 0)
3093                         return ret;
3094                 if (!ret || ret > len)
3095                         return -EIO;
3096
3097                 buf += ret;
3098                 addr += ret;
3099                 len -= ret;
3100         }
3101         return 0;
3102 }
3103
3104 /**
3105  * spi_nor_read_sfdp() - read Serial Flash Discoverable Parameters.
3106  * @nor:        pointer to a 'struct spi_nor'
3107  * @addr:       offset in the SFDP area to start reading data from
3108  * @len:        number of bytes to read
3109  * @buf:        buffer where the SFDP data are copied into (dma-safe memory)
3110  *
3111  * Whatever the actual numbers of bytes for address and dummy cycles are
3112  * for (Fast) Read commands, the Read SFDP (5Ah) instruction is always
3113  * followed by a 3-byte address and 8 dummy clock cycles.
3114  *
3115  * Return: 0 on success, -errno otherwise.
3116  */
3117 static int spi_nor_read_sfdp(struct spi_nor *nor, u32 addr,
3118                              size_t len, void *buf)
3119 {
3120         u8 addr_width, read_opcode, read_dummy;
3121         int ret;
3122
3123         read_opcode = nor->read_opcode;
3124         addr_width = nor->addr_width;
3125         read_dummy = nor->read_dummy;
3126
3127         nor->read_opcode = SPINOR_OP_RDSFDP;
3128         nor->addr_width = 3;
3129         nor->read_dummy = 8;
3130
3131         ret = spi_nor_read_raw(nor, addr, len, buf);
3132
3133         nor->read_opcode = read_opcode;
3134         nor->addr_width = addr_width;
3135         nor->read_dummy = read_dummy;
3136
3137         return ret;
3138 }
3139
3140 /**
3141  * spi_nor_spimem_check_op - check if the operation is supported
3142  *                           by controller
3143  *@nor:        pointer to a 'struct spi_nor'
3144  *@op:         pointer to op template to be checked
3145  *
3146  * Returns 0 if operation is supported, -ENOTSUPP otherwise.
3147  */
3148 static int spi_nor_spimem_check_op(struct spi_nor *nor,
3149                                    struct spi_mem_op *op)
3150 {
3151         /*
3152          * First test with 4 address bytes. The opcode itself might
3153          * be a 3B addressing opcode but we don't care, because
3154          * SPI controller implementation should not check the opcode,
3155          * but just the sequence.
3156          */
3157         op->addr.nbytes = 4;
3158         if (!spi_mem_supports_op(nor->spimem, op)) {
3159                 if (nor->mtd.size > SZ_16M)
3160                         return -ENOTSUPP;
3161
3162                 /* If flash size <= 16MB, 3 address bytes are sufficient */
3163                 op->addr.nbytes = 3;
3164                 if (!spi_mem_supports_op(nor->spimem, op))
3165                         return -ENOTSUPP;
3166         }
3167
3168         return 0;
3169 }
3170
3171 /**
3172  * spi_nor_spimem_check_readop - check if the read op is supported
3173  *                               by controller
3174  *@nor:         pointer to a 'struct spi_nor'
3175  *@read:        pointer to op template to be checked
3176  *
3177  * Returns 0 if operation is supported, -ENOTSUPP otherwise.
3178  */
3179 static int spi_nor_spimem_check_readop(struct spi_nor *nor,
3180                                        const struct spi_nor_read_command *read)
3181 {
3182         struct spi_mem_op op = SPI_MEM_OP(SPI_MEM_OP_CMD(read->opcode, 1),
3183                                           SPI_MEM_OP_ADDR(3, 0, 1),
3184                                           SPI_MEM_OP_DUMMY(0, 1),
3185                                           SPI_MEM_OP_DATA_IN(0, NULL, 1));
3186
3187         op.cmd.buswidth = spi_nor_get_protocol_inst_nbits(read->proto);
3188         op.addr.buswidth = spi_nor_get_protocol_addr_nbits(read->proto);
3189         op.data.buswidth = spi_nor_get_protocol_data_nbits(read->proto);
3190         op.dummy.buswidth = op.addr.buswidth;
3191         op.dummy.nbytes = (read->num_mode_clocks + read->num_wait_states) *
3192                           op.dummy.buswidth / 8;
3193
3194         return spi_nor_spimem_check_op(nor, &op);
3195 }
3196
3197 /**
3198  * spi_nor_spimem_check_pp - check if the page program op is supported
3199  *                           by controller
3200  *@nor:         pointer to a 'struct spi_nor'
3201  *@pp:          pointer to op template to be checked
3202  *
3203  * Returns 0 if operation is supported, -ENOTSUPP otherwise.
3204  */
3205 static int spi_nor_spimem_check_pp(struct spi_nor *nor,
3206                                    const struct spi_nor_pp_command *pp)
3207 {
3208         struct spi_mem_op op = SPI_MEM_OP(SPI_MEM_OP_CMD(pp->opcode, 1),
3209                                           SPI_MEM_OP_ADDR(3, 0, 1),
3210                                           SPI_MEM_OP_NO_DUMMY,
3211                                           SPI_MEM_OP_DATA_OUT(0, NULL, 1));
3212
3213         op.cmd.buswidth = spi_nor_get_protocol_inst_nbits(pp->proto);
3214         op.addr.buswidth = spi_nor_get_protocol_addr_nbits(pp->proto);
3215         op.data.buswidth = spi_nor_get_protocol_data_nbits(pp->proto);
3216
3217         return spi_nor_spimem_check_op(nor, &op);
3218 }
3219
3220 /**
3221  * spi_nor_spimem_adjust_hwcaps - Find optimal Read/Write protocol
3222  *                                based on SPI controller capabilities
3223  * @nor:        pointer to a 'struct spi_nor'
3224  * @hwcaps:     pointer to resulting capabilities after adjusting
3225  *              according to controller and flash's capability
3226  */
3227 static void
3228 spi_nor_spimem_adjust_hwcaps(struct spi_nor *nor, u32 *hwcaps)
3229 {
3230         struct spi_nor_flash_parameter *params =  &nor->params;
3231         unsigned int cap;
3232
3233         /* DTR modes are not supported yet, mask them all. */
3234         *hwcaps &= ~SNOR_HWCAPS_DTR;
3235
3236         /* X-X-X modes are not supported yet, mask them all. */
3237         *hwcaps &= ~SNOR_HWCAPS_X_X_X;
3238
3239         for (cap = 0; cap < sizeof(*hwcaps) * BITS_PER_BYTE; cap++) {
3240                 int rdidx, ppidx;
3241
3242                 if (!(*hwcaps & BIT(cap)))
3243                         continue;
3244
3245                 rdidx = spi_nor_hwcaps_read2cmd(BIT(cap));
3246                 if (rdidx >= 0 &&
3247                     spi_nor_spimem_check_readop(nor, &params->reads[rdidx]))
3248                         *hwcaps &= ~BIT(cap);
3249
3250                 ppidx = spi_nor_hwcaps_pp2cmd(BIT(cap));
3251                 if (ppidx < 0)
3252                         continue;
3253
3254                 if (spi_nor_spimem_check_pp(nor,
3255                                             &params->page_programs[ppidx]))
3256                         *hwcaps &= ~BIT(cap);
3257         }
3258 }
3259
3260 /**
3261  * spi_nor_read_sfdp_dma_unsafe() - read Serial Flash Discoverable Parameters.
3262  * @nor:        pointer to a 'struct spi_nor'
3263  * @addr:       offset in the SFDP area to start reading data from
3264  * @len:        number of bytes to read
3265  * @buf:        buffer where the SFDP data are copied into
3266  *
3267  * Wrap spi_nor_read_sfdp() using a kmalloc'ed bounce buffer as @buf is now not
3268  * guaranteed to be dma-safe.
3269  *
3270  * Return: -ENOMEM if kmalloc() fails, the return code of spi_nor_read_sfdp()
3271  *          otherwise.
3272  */
3273 static int spi_nor_read_sfdp_dma_unsafe(struct spi_nor *nor, u32 addr,
3274                                         size_t len, void *buf)
3275 {
3276         void *dma_safe_buf;
3277         int ret;
3278
3279         dma_safe_buf = kmalloc(len, GFP_KERNEL);
3280         if (!dma_safe_buf)
3281                 return -ENOMEM;
3282
3283         ret = spi_nor_read_sfdp(nor, addr, len, dma_safe_buf);
3284         memcpy(buf, dma_safe_buf, len);
3285         kfree(dma_safe_buf);
3286
3287         return ret;
3288 }
3289
3290 /* Fast Read settings. */
3291
3292 static void
3293 spi_nor_set_read_settings_from_bfpt(struct spi_nor_read_command *read,
3294                                     u16 half,
3295                                     enum spi_nor_protocol proto)
3296 {
3297         read->num_mode_clocks = (half >> 5) & 0x07;
3298         read->num_wait_states = (half >> 0) & 0x1f;
3299         read->opcode = (half >> 8) & 0xff;
3300         read->proto = proto;
3301 }
3302
3303 struct sfdp_bfpt_read {
3304         /* The Fast Read x-y-z hardware capability in params->hwcaps.mask. */
3305         u32                     hwcaps;
3306
3307         /*
3308          * The <supported_bit> bit in <supported_dword> BFPT DWORD tells us
3309          * whether the Fast Read x-y-z command is supported.
3310          */
3311         u32                     supported_dword;
3312         u32                     supported_bit;
3313
3314         /*
3315          * The half-word at offset <setting_shift> in <setting_dword> BFPT DWORD
3316          * encodes the op code, the number of mode clocks and the number of wait
3317          * states to be used by Fast Read x-y-z command.
3318          */
3319         u32                     settings_dword;
3320         u32                     settings_shift;
3321
3322         /* The SPI protocol for this Fast Read x-y-z command. */
3323         enum spi_nor_protocol   proto;
3324 };
3325
3326 static const struct sfdp_bfpt_read sfdp_bfpt_reads[] = {
3327         /* Fast Read 1-1-2 */
3328         {
3329                 SNOR_HWCAPS_READ_1_1_2,
3330                 BFPT_DWORD(1), BIT(16), /* Supported bit */
3331                 BFPT_DWORD(4), 0,       /* Settings */
3332                 SNOR_PROTO_1_1_2,
3333         },
3334
3335         /* Fast Read 1-2-2 */
3336         {
3337                 SNOR_HWCAPS_READ_1_2_2,
3338                 BFPT_DWORD(1), BIT(20), /* Supported bit */
3339                 BFPT_DWORD(4), 16,      /* Settings */
3340                 SNOR_PROTO_1_2_2,
3341         },
3342
3343         /* Fast Read 2-2-2 */
3344         {
3345                 SNOR_HWCAPS_READ_2_2_2,
3346                 BFPT_DWORD(5),  BIT(0), /* Supported bit */
3347                 BFPT_DWORD(6), 16,      /* Settings */
3348                 SNOR_PROTO_2_2_2,
3349         },
3350
3351         /* Fast Read 1-1-4 */
3352         {
3353                 SNOR_HWCAPS_READ_1_1_4,
3354                 BFPT_DWORD(1), BIT(22), /* Supported bit */
3355                 BFPT_DWORD(3), 16,      /* Settings */
3356                 SNOR_PROTO_1_1_4,
3357         },
3358
3359         /* Fast Read 1-4-4 */
3360         {
3361                 SNOR_HWCAPS_READ_1_4_4,
3362                 BFPT_DWORD(1), BIT(21), /* Supported bit */
3363                 BFPT_DWORD(3), 0,       /* Settings */
3364                 SNOR_PROTO_1_4_4,
3365         },
3366
3367         /* Fast Read 4-4-4 */
3368         {
3369                 SNOR_HWCAPS_READ_4_4_4,
3370                 BFPT_DWORD(5), BIT(4),  /* Supported bit */
3371                 BFPT_DWORD(7), 16,      /* Settings */
3372                 SNOR_PROTO_4_4_4,
3373         },
3374 };
3375
3376 struct sfdp_bfpt_erase {
3377         /*
3378          * The half-word at offset <shift> in DWORD <dwoard> encodes the
3379          * op code and erase sector size to be used by Sector Erase commands.
3380          */
3381         u32                     dword;
3382         u32                     shift;
3383 };
3384
3385 static const struct sfdp_bfpt_erase sfdp_bfpt_erases[] = {
3386         /* Erase Type 1 in DWORD8 bits[15:0] */
3387         {BFPT_DWORD(8), 0},
3388
3389         /* Erase Type 2 in DWORD8 bits[31:16] */
3390         {BFPT_DWORD(8), 16},
3391
3392         /* Erase Type 3 in DWORD9 bits[15:0] */
3393         {BFPT_DWORD(9), 0},
3394
3395         /* Erase Type 4 in DWORD9 bits[31:16] */
3396         {BFPT_DWORD(9), 16},
3397 };
3398
3399 /**
3400  * spi_nor_set_erase_type() - set a SPI NOR erase type
3401  * @erase:      pointer to a structure that describes a SPI NOR erase type
3402  * @size:       the size of the sector/block erased by the erase type
3403  * @opcode:     the SPI command op code to erase the sector/block
3404  */
3405 static void spi_nor_set_erase_type(struct spi_nor_erase_type *erase,
3406                                    u32 size, u8 opcode)
3407 {
3408         erase->size = size;
3409         erase->opcode = opcode;
3410         /* JEDEC JESD216B Standard imposes erase sizes to be power of 2. */
3411         erase->size_shift = ffs(erase->size) - 1;
3412         erase->size_mask = (1 << erase->size_shift) - 1;
3413 }
3414
3415 /**
3416  * spi_nor_set_erase_settings_from_bfpt() - set erase type settings from BFPT
3417  * @erase:      pointer to a structure that describes a SPI NOR erase type
3418  * @size:       the size of the sector/block erased by the erase type
3419  * @opcode:     the SPI command op code to erase the sector/block
3420  * @i:          erase type index as sorted in the Basic Flash Parameter Table
3421  *
3422  * The supported Erase Types will be sorted at init in ascending order, with
3423  * the smallest Erase Type size being the first member in the erase_type array
3424  * of the spi_nor_erase_map structure. Save the Erase Type index as sorted in
3425  * the Basic Flash Parameter Table since it will be used later on to
3426  * synchronize with the supported Erase Types defined in SFDP optional tables.
3427  */
3428 static void
3429 spi_nor_set_erase_settings_from_bfpt(struct spi_nor_erase_type *erase,
3430                                      u32 size, u8 opcode, u8 i)
3431 {
3432         erase->idx = i;
3433         spi_nor_set_erase_type(erase, size, opcode);
3434 }
3435
3436 /**
3437  * spi_nor_map_cmp_erase_type() - compare the map's erase types by size
3438  * @l:  member in the left half of the map's erase_type array
3439  * @r:  member in the right half of the map's erase_type array
3440  *
3441  * Comparison function used in the sort() call to sort in ascending order the
3442  * map's erase types, the smallest erase type size being the first member in the
3443  * sorted erase_type array.
3444  *
3445  * Return: the result of @l->size - @r->size
3446  */
3447 static int spi_nor_map_cmp_erase_type(const void *l, const void *r)
3448 {
3449         const struct spi_nor_erase_type *left = l, *right = r;
3450
3451         return left->size - right->size;
3452 }
3453
3454 /**
3455  * spi_nor_sort_erase_mask() - sort erase mask
3456  * @map:        the erase map of the SPI NOR
3457  * @erase_mask: the erase type mask to be sorted
3458  *
3459  * Replicate the sort done for the map's erase types in BFPT: sort the erase
3460  * mask in ascending order with the smallest erase type size starting from
3461  * BIT(0) in the sorted erase mask.
3462  *
3463  * Return: sorted erase mask.
3464  */
3465 static u8 spi_nor_sort_erase_mask(struct spi_nor_erase_map *map, u8 erase_mask)
3466 {
3467         struct spi_nor_erase_type *erase_type = map->erase_type;
3468         int i;
3469         u8 sorted_erase_mask = 0;
3470
3471         if (!erase_mask)
3472                 return 0;
3473
3474         /* Replicate the sort done for the map's erase types. */
3475         for (i = 0; i < SNOR_ERASE_TYPE_MAX; i++)
3476                 if (erase_type[i].size && erase_mask & BIT(erase_type[i].idx))
3477                         sorted_erase_mask |= BIT(i);
3478
3479         return sorted_erase_mask;
3480 }
3481
3482 /**
3483  * spi_nor_regions_sort_erase_types() - sort erase types in each region
3484  * @map:        the erase map of the SPI NOR
3485  *
3486  * Function assumes that the erase types defined in the erase map are already
3487  * sorted in ascending order, with the smallest erase type size being the first
3488  * member in the erase_type array. It replicates the sort done for the map's
3489  * erase types. Each region's erase bitmask will indicate which erase types are
3490  * supported from the sorted erase types defined in the erase map.
3491  * Sort the all region's erase type at init in order to speed up the process of
3492  * finding the best erase command at runtime.
3493  */
3494 static void spi_nor_regions_sort_erase_types(struct spi_nor_erase_map *map)
3495 {
3496         struct spi_nor_erase_region *region = map->regions;
3497         u8 region_erase_mask, sorted_erase_mask;
3498
3499         while (region) {
3500                 region_erase_mask = region->offset & SNOR_ERASE_TYPE_MASK;
3501
3502                 sorted_erase_mask = spi_nor_sort_erase_mask(map,
3503                                                             region_erase_mask);
3504
3505                 /* Overwrite erase mask. */
3506                 region->offset = (region->offset & ~SNOR_ERASE_TYPE_MASK) |
3507                                  sorted_erase_mask;
3508
3509                 region = spi_nor_region_next(region);
3510         }
3511 }
3512
3513 /**
3514  * spi_nor_init_uniform_erase_map() - Initialize uniform erase map
3515  * @map:                the erase map of the SPI NOR
3516  * @erase_mask:         bitmask encoding erase types that can erase the entire
3517  *                      flash memory
3518  * @flash_size:         the spi nor flash memory size
3519  */
3520 static void spi_nor_init_uniform_erase_map(struct spi_nor_erase_map *map,
3521                                            u8 erase_mask, u64 flash_size)
3522 {
3523         /* Offset 0 with erase_mask and SNOR_LAST_REGION bit set */
3524         map->uniform_region.offset = (erase_mask & SNOR_ERASE_TYPE_MASK) |
3525                                      SNOR_LAST_REGION;
3526         map->uniform_region.size = flash_size;
3527         map->regions = &map->uniform_region;
3528         map->uniform_erase_type = erase_mask;
3529 }
3530
3531 static int
3532 spi_nor_post_bfpt_fixups(struct spi_nor *nor,
3533                          const struct sfdp_parameter_header *bfpt_header,
3534                          const struct sfdp_bfpt *bfpt,
3535                          struct spi_nor_flash_parameter *params)
3536 {
3537         if (nor->info->fixups && nor->info->fixups->post_bfpt)
3538                 return nor->info->fixups->post_bfpt(nor, bfpt_header, bfpt,
3539                                                     params);
3540
3541         return 0;
3542 }
3543
3544 /**
3545  * spi_nor_parse_bfpt() - read and parse the Basic Flash Parameter Table.
3546  * @nor:                pointer to a 'struct spi_nor'
3547  * @bfpt_header:        pointer to the 'struct sfdp_parameter_header' describing
3548  *                      the Basic Flash Parameter Table length and version
3549  * @params:             pointer to the 'struct spi_nor_flash_parameter' to be
3550  *                      filled
3551  *
3552  * The Basic Flash Parameter Table is the main and only mandatory table as
3553  * defined by the SFDP (JESD216) specification.
3554  * It provides us with the total size (memory density) of the data array and
3555  * the number of address bytes for Fast Read, Page Program and Sector Erase
3556  * commands.
3557  * For Fast READ commands, it also gives the number of mode clock cycles and
3558  * wait states (regrouped in the number of dummy clock cycles) for each
3559  * supported instruction op code.
3560  * For Page Program, the page size is now available since JESD216 rev A, however
3561  * the supported instruction op codes are still not provided.
3562  * For Sector Erase commands, this table stores the supported instruction op
3563  * codes and the associated sector sizes.
3564  * Finally, the Quad Enable Requirements (QER) are also available since JESD216
3565  * rev A. The QER bits encode the manufacturer dependent procedure to be
3566  * executed to set the Quad Enable (QE) bit in some internal register of the
3567  * Quad SPI memory. Indeed the QE bit, when it exists, must be set before
3568  * sending any Quad SPI command to the memory. Actually, setting the QE bit
3569  * tells the memory to reassign its WP# and HOLD#/RESET# pins to functions IO2
3570  * and IO3 hence enabling 4 (Quad) I/O lines.
3571  *
3572  * Return: 0 on success, -errno otherwise.
3573  */
3574 static int spi_nor_parse_bfpt(struct spi_nor *nor,
3575                               const struct sfdp_parameter_header *bfpt_header,
3576                               struct spi_nor_flash_parameter *params)
3577 {
3578         struct spi_nor_erase_map *map = &params->erase_map;
3579         struct spi_nor_erase_type *erase_type = map->erase_type;
3580         struct sfdp_bfpt bfpt;
3581         size_t len;
3582         int i, cmd, err;
3583         u32 addr;
3584         u16 half;
3585         u8 erase_mask;
3586
3587         /* JESD216 Basic Flash Parameter Table length is at least 9 DWORDs. */
3588         if (bfpt_header->length < BFPT_DWORD_MAX_JESD216)
3589                 return -EINVAL;
3590
3591         /* Read the Basic Flash Parameter Table. */
3592         len = min_t(size_t, sizeof(bfpt),
3593                     bfpt_header->length * sizeof(u32));
3594         addr = SFDP_PARAM_HEADER_PTP(bfpt_header);
3595         memset(&bfpt, 0, sizeof(bfpt));
3596         err = spi_nor_read_sfdp_dma_unsafe(nor,  addr, len, &bfpt);
3597         if (err < 0)
3598                 return err;
3599
3600         /* Fix endianness of the BFPT DWORDs. */
3601         for (i = 0; i < BFPT_DWORD_MAX; i++)
3602                 bfpt.dwords[i] = le32_to_cpu(bfpt.dwords[i]);
3603
3604         /* Number of address bytes. */
3605         switch (bfpt.dwords[BFPT_DWORD(1)] & BFPT_DWORD1_ADDRESS_BYTES_MASK) {
3606         case BFPT_DWORD1_ADDRESS_BYTES_3_ONLY:
3607                 nor->addr_width = 3;
3608                 break;
3609
3610         case BFPT_DWORD1_ADDRESS_BYTES_4_ONLY:
3611                 nor->addr_width = 4;
3612                 break;
3613
3614         default:
3615                 break;
3616         }
3617
3618         /* Flash Memory Density (in bits). */
3619         params->size = bfpt.dwords[BFPT_DWORD(2)];
3620         if (params->size & BIT(31)) {
3621                 params->size &= ~BIT(31);
3622
3623                 /*
3624                  * Prevent overflows on params->size. Anyway, a NOR of 2^64
3625                  * bits is unlikely to exist so this error probably means
3626                  * the BFPT we are reading is corrupted/wrong.
3627                  */
3628                 if (params->size > 63)
3629                         return -EINVAL;
3630
3631                 params->size = 1ULL << params->size;
3632         } else {
3633                 params->size++;
3634         }
3635         params->size >>= 3; /* Convert to bytes. */
3636
3637         /* Fast Read settings. */
3638         for (i = 0; i < ARRAY_SIZE(sfdp_bfpt_reads); i++) {
3639                 const struct sfdp_bfpt_read *rd = &sfdp_bfpt_reads[i];
3640                 struct spi_nor_read_command *read;
3641
3642                 if (!(bfpt.dwords[rd->supported_dword] & rd->supported_bit)) {
3643                         params->hwcaps.mask &= ~rd->hwcaps;
3644                         continue;
3645                 }
3646
3647                 params->hwcaps.mask |= rd->hwcaps;
3648                 cmd = spi_nor_hwcaps_read2cmd(rd->hwcaps);
3649                 read = &params->reads[cmd];
3650                 half = bfpt.dwords[rd->settings_dword] >> rd->settings_shift;
3651                 spi_nor_set_read_settings_from_bfpt(read, half, rd->proto);
3652         }
3653
3654         /*
3655          * Sector Erase settings. Reinitialize the uniform erase map using the
3656          * Erase Types defined in the bfpt table.
3657          */
3658         erase_mask = 0;
3659         memset(&params->erase_map, 0, sizeof(params->erase_map));
3660         for (i = 0; i < ARRAY_SIZE(sfdp_bfpt_erases); i++) {
3661                 const struct sfdp_bfpt_erase *er = &sfdp_bfpt_erases[i];
3662                 u32 erasesize;
3663                 u8 opcode;
3664
3665                 half = bfpt.dwords[er->dword] >> er->shift;
3666                 erasesize = half & 0xff;
3667
3668                 /* erasesize == 0 means this Erase Type is not supported. */
3669                 if (!erasesize)
3670                         continue;
3671
3672                 erasesize = 1U << erasesize;
3673                 opcode = (half >> 8) & 0xff;
3674                 erase_mask |= BIT(i);
3675                 spi_nor_set_erase_settings_from_bfpt(&erase_type[i], erasesize,
3676                                                      opcode, i);
3677         }
3678         spi_nor_init_uniform_erase_map(map, erase_mask, params->size);
3679         /*
3680          * Sort all the map's Erase Types in ascending order with the smallest
3681          * erase size being the first member in the erase_type array.
3682          */
3683         sort(erase_type, SNOR_ERASE_TYPE_MAX, sizeof(erase_type[0]),
3684              spi_nor_map_cmp_erase_type, NULL);
3685         /*
3686          * Sort the erase types in the uniform region in order to update the
3687          * uniform_erase_type bitmask. The bitmask will be used later on when
3688          * selecting the uniform erase.
3689          */
3690         spi_nor_regions_sort_erase_types(map);
3691         map->uniform_erase_type = map->uniform_region.offset &
3692                                   SNOR_ERASE_TYPE_MASK;
3693
3694         /* Stop here if not JESD216 rev A or later. */
3695         if (bfpt_header->length < BFPT_DWORD_MAX)
3696                 return spi_nor_post_bfpt_fixups(nor, bfpt_header, &bfpt,
3697                                                 params);
3698
3699         /* Page size: this field specifies 'N' so the page size = 2^N bytes. */
3700         params->page_size = bfpt.dwords[BFPT_DWORD(11)];
3701         params->page_size &= BFPT_DWORD11_PAGE_SIZE_MASK;
3702         params->page_size >>= BFPT_DWORD11_PAGE_SIZE_SHIFT;
3703         params->page_size = 1U << params->page_size;
3704
3705         /* Quad Enable Requirements. */
3706         switch (bfpt.dwords[BFPT_DWORD(15)] & BFPT_DWORD15_QER_MASK) {
3707         case BFPT_DWORD15_QER_NONE:
3708                 params->quad_enable = NULL;
3709                 break;
3710
3711         case BFPT_DWORD15_QER_SR2_BIT1_BUGGY:
3712                 /*
3713                  * Writing only one byte to the Status Register has the
3714                  * side-effect of clearing Status Register 2.
3715                  */
3716         case BFPT_DWORD15_QER_SR2_BIT1_NO_RD:
3717                 /*
3718                  * Read Configuration Register (35h) instruction is not
3719                  * supported.
3720                  */
3721                 nor->flags |= SNOR_F_HAS_16BIT_SR | SNOR_F_NO_READ_CR;
3722                 params->quad_enable = spi_nor_sr2_bit1_quad_enable;
3723                 break;
3724
3725         case BFPT_DWORD15_QER_SR1_BIT6:
3726                 nor->flags &= ~SNOR_F_HAS_16BIT_SR;
3727                 params->quad_enable = spi_nor_sr1_bit6_quad_enable;
3728                 break;
3729
3730         case BFPT_DWORD15_QER_SR2_BIT7:
3731                 nor->flags &= ~SNOR_F_HAS_16BIT_SR;
3732                 params->quad_enable = spi_nor_sr2_bit7_quad_enable;
3733                 break;
3734
3735         case BFPT_DWORD15_QER_SR2_BIT1:
3736                 /*
3737                  * JESD216 rev B or later does not specify if writing only one
3738                  * byte to the Status Register clears or not the Status
3739                  * Register 2, so let's be cautious and keep the default
3740                  * assumption of a 16-bit Write Status (01h) command.
3741                  */
3742                 nor->flags |= SNOR_F_HAS_16BIT_SR;
3743
3744                 params->quad_enable = spi_nor_sr2_bit1_quad_enable;
3745                 break;
3746
3747         default:
3748                 return -EINVAL;
3749         }
3750
3751         return spi_nor_post_bfpt_fixups(nor, bfpt_header, &bfpt, params);
3752 }
3753
3754 #define SMPT_CMD_ADDRESS_LEN_MASK               GENMASK(23, 22)
3755 #define SMPT_CMD_ADDRESS_LEN_0                  (0x0UL << 22)
3756 #define SMPT_CMD_ADDRESS_LEN_3                  (0x1UL << 22)
3757 #define SMPT_CMD_ADDRESS_LEN_4                  (0x2UL << 22)
3758 #define SMPT_CMD_ADDRESS_LEN_USE_CURRENT        (0x3UL << 22)
3759
3760 #define SMPT_CMD_READ_DUMMY_MASK                GENMASK(19, 16)
3761 #define SMPT_CMD_READ_DUMMY_SHIFT               16
3762 #define SMPT_CMD_READ_DUMMY(_cmd) \
3763         (((_cmd) & SMPT_CMD_READ_DUMMY_MASK) >> SMPT_CMD_READ_DUMMY_SHIFT)
3764 #define SMPT_CMD_READ_DUMMY_IS_VARIABLE         0xfUL
3765
3766 #define SMPT_CMD_READ_DATA_MASK                 GENMASK(31, 24)
3767 #define SMPT_CMD_READ_DATA_SHIFT                24
3768 #define SMPT_CMD_READ_DATA(_cmd) \
3769         (((_cmd) & SMPT_CMD_READ_DATA_MASK) >> SMPT_CMD_READ_DATA_SHIFT)
3770
3771 #define SMPT_CMD_OPCODE_MASK                    GENMASK(15, 8)
3772 #define SMPT_CMD_OPCODE_SHIFT                   8
3773 #define SMPT_CMD_OPCODE(_cmd) \
3774         (((_cmd) & SMPT_CMD_OPCODE_MASK) >> SMPT_CMD_OPCODE_SHIFT)
3775
3776 #define SMPT_MAP_REGION_COUNT_MASK              GENMASK(23, 16)
3777 #define SMPT_MAP_REGION_COUNT_SHIFT             16
3778 #define SMPT_MAP_REGION_COUNT(_header) \
3779         ((((_header) & SMPT_MAP_REGION_COUNT_MASK) >> \
3780           SMPT_MAP_REGION_COUNT_SHIFT) + 1)
3781
3782 #define SMPT_MAP_ID_MASK                        GENMASK(15, 8)
3783 #define SMPT_MAP_ID_SHIFT                       8
3784 #define SMPT_MAP_ID(_header) \
3785         (((_header) & SMPT_MAP_ID_MASK) >> SMPT_MAP_ID_SHIFT)
3786
3787 #define SMPT_MAP_REGION_SIZE_MASK               GENMASK(31, 8)
3788 #define SMPT_MAP_REGION_SIZE_SHIFT              8
3789 #define SMPT_MAP_REGION_SIZE(_region) \
3790         (((((_region) & SMPT_MAP_REGION_SIZE_MASK) >> \
3791            SMPT_MAP_REGION_SIZE_SHIFT) + 1) * 256)
3792
3793 #define SMPT_MAP_REGION_ERASE_TYPE_MASK         GENMASK(3, 0)
3794 #define SMPT_MAP_REGION_ERASE_TYPE(_region) \
3795         ((_region) & SMPT_MAP_REGION_ERASE_TYPE_MASK)
3796
3797 #define SMPT_DESC_TYPE_MAP                      BIT(1)
3798 #define SMPT_DESC_END                           BIT(0)
3799
3800 /**
3801  * spi_nor_smpt_addr_width() - return the address width used in the
3802  *                             configuration detection command.
3803  * @nor:        pointer to a 'struct spi_nor'
3804  * @settings:   configuration detection command descriptor, dword1
3805  */
3806 static u8 spi_nor_smpt_addr_width(const struct spi_nor *nor, const u32 settings)
3807 {
3808         switch (settings & SMPT_CMD_ADDRESS_LEN_MASK) {
3809         case SMPT_CMD_ADDRESS_LEN_0:
3810                 return 0;
3811         case SMPT_CMD_ADDRESS_LEN_3:
3812                 return 3;
3813         case SMPT_CMD_ADDRESS_LEN_4:
3814                 return 4;
3815         case SMPT_CMD_ADDRESS_LEN_USE_CURRENT:
3816                 /* fall through */
3817         default:
3818                 return nor->addr_width;
3819         }
3820 }
3821
3822 /**
3823  * spi_nor_smpt_read_dummy() - return the configuration detection command read
3824  *                             latency, in clock cycles.
3825  * @nor:        pointer to a 'struct spi_nor'
3826  * @settings:   configuration detection command descriptor, dword1
3827  *
3828  * Return: the number of dummy cycles for an SMPT read
3829  */
3830 static u8 spi_nor_smpt_read_dummy(const struct spi_nor *nor, const u32 settings)
3831 {
3832         u8 read_dummy = SMPT_CMD_READ_DUMMY(settings);
3833
3834         if (read_dummy == SMPT_CMD_READ_DUMMY_IS_VARIABLE)
3835                 return nor->read_dummy;
3836         return read_dummy;
3837 }
3838
3839 /**
3840  * spi_nor_get_map_in_use() - get the configuration map in use
3841  * @nor:        pointer to a 'struct spi_nor'
3842  * @smpt:       pointer to the sector map parameter table
3843  * @smpt_len:   sector map parameter table length
3844  *
3845  * Return: pointer to the map in use, ERR_PTR(-errno) otherwise.
3846  */
3847 static const u32 *spi_nor_get_map_in_use(struct spi_nor *nor, const u32 *smpt,
3848                                          u8 smpt_len)
3849 {
3850         const u32 *ret;
3851         u8 *buf;
3852         u32 addr;
3853         int err;
3854         u8 i;
3855         u8 addr_width, read_opcode, read_dummy;
3856         u8 read_data_mask, map_id;
3857
3858         /* Use a kmalloc'ed bounce buffer to guarantee it is DMA-able. */
3859         buf = kmalloc(sizeof(*buf), GFP_KERNEL);
3860         if (!buf)
3861                 return ERR_PTR(-ENOMEM);
3862
3863         addr_width = nor->addr_width;
3864         read_dummy = nor->read_dummy;
3865         read_opcode = nor->read_opcode;
3866
3867         map_id = 0;
3868         /* Determine if there are any optional Detection Command Descriptors */
3869         for (i = 0; i < smpt_len; i += 2) {
3870                 if (smpt[i] & SMPT_DESC_TYPE_MAP)
3871                         break;
3872
3873                 read_data_mask = SMPT_CMD_READ_DATA(smpt[i]);
3874                 nor->addr_width = spi_nor_smpt_addr_width(nor, smpt[i]);
3875                 nor->read_dummy = spi_nor_smpt_read_dummy(nor, smpt[i]);
3876                 nor->read_opcode = SMPT_CMD_OPCODE(smpt[i]);
3877                 addr = smpt[i + 1];
3878
3879                 err = spi_nor_read_raw(nor, addr, 1, buf);
3880                 if (err) {
3881                         ret = ERR_PTR(err);
3882                         goto out;
3883                 }
3884
3885                 /*
3886                  * Build an index value that is used to select the Sector Map
3887                  * Configuration that is currently in use.
3888                  */
3889                 map_id = map_id << 1 | !!(*buf & read_data_mask);
3890         }
3891
3892         /*
3893          * If command descriptors are provided, they always precede map
3894          * descriptors in the table. There is no need to start the iteration
3895          * over smpt array all over again.
3896          *
3897          * Find the matching configuration map.
3898          */
3899         ret = ERR_PTR(-EINVAL);
3900         while (i < smpt_len) {
3901                 if (SMPT_MAP_ID(smpt[i]) == map_id) {
3902                         ret = smpt + i;
3903                         break;
3904                 }
3905
3906                 /*
3907                  * If there are no more configuration map descriptors and no
3908                  * configuration ID matched the configuration identifier, the
3909                  * sector address map is unknown.
3910                  */
3911                 if (smpt[i] & SMPT_DESC_END)
3912                         break;
3913
3914                 /* increment the table index to the next map */
3915                 i += SMPT_MAP_REGION_COUNT(smpt[i]) + 1;
3916         }
3917
3918         /* fall through */
3919 out:
3920         kfree(buf);
3921         nor->addr_width = addr_width;
3922         nor->read_dummy = read_dummy;
3923         nor->read_opcode = read_opcode;
3924         return ret;
3925 }
3926
3927 /**
3928  * spi_nor_region_check_overlay() - set overlay bit when the region is overlaid
3929  * @region:     pointer to a structure that describes a SPI NOR erase region
3930  * @erase:      pointer to a structure that describes a SPI NOR erase type
3931  * @erase_type: erase type bitmask
3932  */
3933 static void
3934 spi_nor_region_check_overlay(struct spi_nor_erase_region *region,
3935                              const struct spi_nor_erase_type *erase,
3936                              const u8 erase_type)
3937 {
3938         int i;
3939
3940         for (i = 0; i < SNOR_ERASE_TYPE_MAX; i++) {
3941                 if (!(erase_type & BIT(i)))
3942                         continue;
3943                 if (region->size & erase[i].size_mask) {
3944                         spi_nor_region_mark_overlay(region);
3945                         return;
3946                 }
3947         }
3948 }
3949
3950 /**
3951  * spi_nor_init_non_uniform_erase_map() - initialize the non-uniform erase map
3952  * @nor:        pointer to a 'struct spi_nor'
3953  * @params:     pointer to a duplicate 'struct spi_nor_flash_parameter' that is
3954  *              used for storing SFDP parsed data
3955  * @smpt:       pointer to the sector map parameter table
3956  *
3957  * Return: 0 on success, -errno otherwise.
3958  */
3959 static int
3960 spi_nor_init_non_uniform_erase_map(struct spi_nor *nor,
3961                                    struct spi_nor_flash_parameter *params,
3962                                    const u32 *smpt)
3963 {
3964         struct spi_nor_erase_map *map = &params->erase_map;
3965         struct spi_nor_erase_type *erase = map->erase_type;
3966         struct spi_nor_erase_region *region;
3967         u64 offset;
3968         u32 region_count;
3969         int i, j;
3970         u8 uniform_erase_type, save_uniform_erase_type;
3971         u8 erase_type, regions_erase_type;
3972
3973         region_count = SMPT_MAP_REGION_COUNT(*smpt);
3974         /*
3975          * The regions will be freed when the driver detaches from the
3976          * device.
3977          */
3978         region = devm_kcalloc(nor->dev, region_count, sizeof(*region),
3979                               GFP_KERNEL);
3980         if (!region)
3981                 return -ENOMEM;
3982         map->regions = region;
3983
3984         uniform_erase_type = 0xff;
3985         regions_erase_type = 0;
3986         offset = 0;
3987         /* Populate regions. */
3988         for (i = 0; i < region_count; i++) {
3989                 j = i + 1; /* index for the region dword */
3990                 region[i].size = SMPT_MAP_REGION_SIZE(smpt[j]);
3991                 erase_type = SMPT_MAP_REGION_ERASE_TYPE(smpt[j]);
3992                 region[i].offset = offset | erase_type;
3993
3994                 spi_nor_region_check_overlay(&region[i], erase, erase_type);
3995
3996                 /*
3997                  * Save the erase types that are supported in all regions and
3998                  * can erase the entire flash memory.
3999                  */
4000                 uniform_erase_type &= erase_type;
4001
4002                 /*
4003                  * regions_erase_type mask will indicate all the erase types
4004                  * supported in this configuration map.
4005                  */
4006                 regions_erase_type |= erase_type;
4007
4008                 offset = (region[i].offset & ~SNOR_ERASE_FLAGS_MASK) +
4009                          region[i].size;
4010         }
4011
4012         save_uniform_erase_type = map->uniform_erase_type;
4013         map->uniform_erase_type = spi_nor_sort_erase_mask(map,
4014                                                           uniform_erase_type);
4015
4016         if (!regions_erase_type) {
4017                 /*
4018                  * Roll back to the previous uniform_erase_type mask, SMPT is
4019                  * broken.
4020                  */
4021                 map->uniform_erase_type = save_uniform_erase_type;
4022                 return -EINVAL;
4023         }
4024
4025         /*
4026          * BFPT advertises all the erase types supported by all the possible
4027          * map configurations. Mask out the erase types that are not supported
4028          * by the current map configuration.
4029          */
4030         for (i = 0; i < SNOR_ERASE_TYPE_MAX; i++)
4031                 if (!(regions_erase_type & BIT(erase[i].idx)))
4032                         spi_nor_set_erase_type(&erase[i], 0, 0xFF);
4033
4034         spi_nor_region_mark_end(&region[i - 1]);
4035
4036         return 0;
4037 }
4038
4039 /**
4040  * spi_nor_parse_smpt() - parse Sector Map Parameter Table
4041  * @nor:                pointer to a 'struct spi_nor'
4042  * @smpt_header:        sector map parameter table header
4043  * @params:             pointer to a duplicate 'struct spi_nor_flash_parameter'
4044  *                      that is used for storing SFDP parsed data
4045  *
4046  * This table is optional, but when available, we parse it to identify the
4047  * location and size of sectors within the main data array of the flash memory
4048  * device and to identify which Erase Types are supported by each sector.
4049  *
4050  * Return: 0 on success, -errno otherwise.
4051  */
4052 static int spi_nor_parse_smpt(struct spi_nor *nor,
4053                               const struct sfdp_parameter_header *smpt_header,
4054                               struct spi_nor_flash_parameter *params)
4055 {
4056         const u32 *sector_map;
4057         u32 *smpt;
4058         size_t len;
4059         u32 addr;
4060         int i, ret;
4061
4062         /* Read the Sector Map Parameter Table. */
4063         len = smpt_header->length * sizeof(*smpt);
4064         smpt = kmalloc(len, GFP_KERNEL);
4065         if (!smpt)
4066                 return -ENOMEM;
4067
4068         addr = SFDP_PARAM_HEADER_PTP(smpt_header);
4069         ret = spi_nor_read_sfdp(nor, addr, len, smpt);
4070         if (ret)
4071                 goto out;
4072
4073         /* Fix endianness of the SMPT DWORDs. */
4074         for (i = 0; i < smpt_header->length; i++)
4075                 smpt[i] = le32_to_cpu(smpt[i]);
4076
4077         sector_map = spi_nor_get_map_in_use(nor, smpt, smpt_header->length);
4078         if (IS_ERR(sector_map)) {
4079                 ret = PTR_ERR(sector_map);
4080                 goto out;
4081         }
4082
4083         ret = spi_nor_init_non_uniform_erase_map(nor, params, sector_map);
4084         if (ret)
4085                 goto out;
4086
4087         spi_nor_regions_sort_erase_types(&params->erase_map);
4088         /* fall through */
4089 out:
4090         kfree(smpt);
4091         return ret;
4092 }
4093
4094 #define SFDP_4BAIT_DWORD_MAX    2
4095
4096 struct sfdp_4bait {
4097         /* The hardware capability. */
4098         u32             hwcaps;
4099
4100         /*
4101          * The <supported_bit> bit in DWORD1 of the 4BAIT tells us whether
4102          * the associated 4-byte address op code is supported.
4103          */
4104         u32             supported_bit;
4105 };
4106
4107 /**
4108  * spi_nor_parse_4bait() - parse the 4-Byte Address Instruction Table
4109  * @nor:                pointer to a 'struct spi_nor'.
4110  * @param_header:       pointer to the 'struct sfdp_parameter_header' describing
4111  *                      the 4-Byte Address Instruction Table length and version.
4112  * @params:             pointer to the 'struct spi_nor_flash_parameter' to be.
4113  *
4114  * Return: 0 on success, -errno otherwise.
4115  */
4116 static int spi_nor_parse_4bait(struct spi_nor *nor,
4117                                const struct sfdp_parameter_header *param_header,
4118                                struct spi_nor_flash_parameter *params)
4119 {
4120         static const struct sfdp_4bait reads[] = {
4121                 { SNOR_HWCAPS_READ,             BIT(0) },
4122                 { SNOR_HWCAPS_READ_FAST,        BIT(1) },
4123                 { SNOR_HWCAPS_READ_1_1_2,       BIT(2) },
4124                 { SNOR_HWCAPS_READ_1_2_2,       BIT(3) },
4125                 { SNOR_HWCAPS_READ_1_1_4,       BIT(4) },
4126                 { SNOR_HWCAPS_READ_1_4_4,       BIT(5) },
4127                 { SNOR_HWCAPS_READ_1_1_1_DTR,   BIT(13) },
4128                 { SNOR_HWCAPS_READ_1_2_2_DTR,   BIT(14) },
4129                 { SNOR_HWCAPS_READ_1_4_4_DTR,   BIT(15) },
4130         };
4131         static const struct sfdp_4bait programs[] = {
4132                 { SNOR_HWCAPS_PP,               BIT(6) },
4133                 { SNOR_HWCAPS_PP_1_1_4,         BIT(7) },
4134                 { SNOR_HWCAPS_PP_1_4_4,         BIT(8) },
4135         };
4136         static const struct sfdp_4bait erases[SNOR_ERASE_TYPE_MAX] = {
4137                 { 0u /* not used */,            BIT(9) },
4138                 { 0u /* not used */,            BIT(10) },
4139                 { 0u /* not used */,            BIT(11) },
4140                 { 0u /* not used */,            BIT(12) },
4141         };
4142         struct spi_nor_pp_command *params_pp = params->page_programs;
4143         struct spi_nor_erase_map *map = &params->erase_map;
4144         struct spi_nor_erase_type *erase_type = map->erase_type;
4145         u32 *dwords;
4146         size_t len;
4147         u32 addr, discard_hwcaps, read_hwcaps, pp_hwcaps, erase_mask;
4148         int i, ret;
4149
4150         if (param_header->major != SFDP_JESD216_MAJOR ||
4151             param_header->length < SFDP_4BAIT_DWORD_MAX)
4152                 return -EINVAL;
4153
4154         /* Read the 4-byte Address Instruction Table. */
4155         len = sizeof(*dwords) * SFDP_4BAIT_DWORD_MAX;
4156
4157         /* Use a kmalloc'ed bounce buffer to guarantee it is DMA-able. */
4158         dwords = kmalloc(len, GFP_KERNEL);
4159         if (!dwords)
4160                 return -ENOMEM;
4161
4162         addr = SFDP_PARAM_HEADER_PTP(param_header);
4163         ret = spi_nor_read_sfdp(nor, addr, len, dwords);
4164         if (ret)
4165                 goto out;
4166
4167         /* Fix endianness of the 4BAIT DWORDs. */
4168         for (i = 0; i < SFDP_4BAIT_DWORD_MAX; i++)
4169                 dwords[i] = le32_to_cpu(dwords[i]);
4170
4171         /*
4172          * Compute the subset of (Fast) Read commands for which the 4-byte
4173          * version is supported.
4174          */
4175         discard_hwcaps = 0;
4176         read_hwcaps = 0;
4177         for (i = 0; i < ARRAY_SIZE(reads); i++) {
4178                 const struct sfdp_4bait *read = &reads[i];
4179
4180                 discard_hwcaps |= read->hwcaps;
4181                 if ((params->hwcaps.mask & read->hwcaps) &&
4182                     (dwords[0] & read->supported_bit))
4183                         read_hwcaps |= read->hwcaps;
4184         }
4185
4186         /*
4187          * Compute the subset of Page Program commands for which the 4-byte
4188          * version is supported.
4189          */
4190         pp_hwcaps = 0;
4191         for (i = 0; i < ARRAY_SIZE(programs); i++) {
4192                 const struct sfdp_4bait *program = &programs[i];
4193
4194                 /*
4195                  * The 4 Byte Address Instruction (Optional) Table is the only
4196                  * SFDP table that indicates support for Page Program Commands.
4197                  * Bypass the params->hwcaps.mask and consider 4BAIT the biggest
4198                  * authority for specifying Page Program support.
4199                  */
4200                 discard_hwcaps |= program->hwcaps;
4201                 if (dwords[0] & program->supported_bit)
4202                         pp_hwcaps |= program->hwcaps;
4203         }
4204
4205         /*
4206          * Compute the subset of Sector Erase commands for which the 4-byte
4207          * version is supported.
4208          */
4209         erase_mask = 0;
4210         for (i = 0; i < SNOR_ERASE_TYPE_MAX; i++) {
4211                 const struct sfdp_4bait *erase = &erases[i];
4212
4213                 if (dwords[0] & erase->supported_bit)
4214                         erase_mask |= BIT(i);
4215         }
4216
4217         /* Replicate the sort done for the map's erase types in BFPT. */
4218         erase_mask = spi_nor_sort_erase_mask(map, erase_mask);
4219
4220         /*
4221          * We need at least one 4-byte op code per read, program and erase
4222          * operation; the .read(), .write() and .erase() hooks share the
4223          * nor->addr_width value.
4224          */
4225         if (!read_hwcaps || !pp_hwcaps || !erase_mask)
4226                 goto out;
4227
4228         /*
4229          * Discard all operations from the 4-byte instruction set which are
4230          * not supported by this memory.
4231          */
4232         params->hwcaps.mask &= ~discard_hwcaps;
4233         params->hwcaps.mask |= (read_hwcaps | pp_hwcaps);
4234
4235         /* Use the 4-byte address instruction set. */
4236         for (i = 0; i < SNOR_CMD_READ_MAX; i++) {
4237                 struct spi_nor_read_command *read_cmd = &params->reads[i];
4238
4239                 read_cmd->opcode = spi_nor_convert_3to4_read(read_cmd->opcode);
4240         }
4241
4242         /* 4BAIT is the only SFDP table that indicates page program support. */
4243         if (pp_hwcaps & SNOR_HWCAPS_PP)
4244                 spi_nor_set_pp_settings(&params_pp[SNOR_CMD_PP],
4245                                         SPINOR_OP_PP_4B, SNOR_PROTO_1_1_1);
4246         if (pp_hwcaps & SNOR_HWCAPS_PP_1_1_4)
4247                 spi_nor_set_pp_settings(&params_pp[SNOR_CMD_PP_1_1_4],
4248                                         SPINOR_OP_PP_1_1_4_4B,
4249                                         SNOR_PROTO_1_1_4);
4250         if (pp_hwcaps & SNOR_HWCAPS_PP_1_4_4)
4251                 spi_nor_set_pp_settings(&params_pp[SNOR_CMD_PP_1_4_4],
4252                                         SPINOR_OP_PP_1_4_4_4B,
4253                                         SNOR_PROTO_1_4_4);
4254
4255         for (i = 0; i < SNOR_ERASE_TYPE_MAX; i++) {
4256                 if (erase_mask & BIT(i))
4257                         erase_type[i].opcode = (dwords[1] >>
4258                                                 erase_type[i].idx * 8) & 0xFF;
4259                 else
4260                         spi_nor_set_erase_type(&erase_type[i], 0u, 0xFF);
4261         }
4262
4263         /*
4264          * We set SNOR_F_HAS_4BAIT in order to skip spi_nor_set_4byte_opcodes()
4265          * later because we already did the conversion to 4byte opcodes. Also,
4266          * this latest function implements a legacy quirk for the erase size of
4267          * Spansion memory. However this quirk is no longer needed with new
4268          * SFDP compliant memories.
4269          */
4270         nor->addr_width = 4;
4271         nor->flags |= SNOR_F_4B_OPCODES | SNOR_F_HAS_4BAIT;
4272
4273         /* fall through */
4274 out:
4275         kfree(dwords);
4276         return ret;
4277 }
4278
4279 /**
4280  * spi_nor_parse_sfdp() - parse the Serial Flash Discoverable Parameters.
4281  * @nor:                pointer to a 'struct spi_nor'
4282  * @params:             pointer to the 'struct spi_nor_flash_parameter' to be
4283  *                      filled
4284  *
4285  * The Serial Flash Discoverable Parameters are described by the JEDEC JESD216
4286  * specification. This is a standard which tends to supported by almost all
4287  * (Q)SPI memory manufacturers. Those hard-coded tables allow us to learn at
4288  * runtime the main parameters needed to perform basic SPI flash operations such
4289  * as Fast Read, Page Program or Sector Erase commands.
4290  *
4291  * Return: 0 on success, -errno otherwise.
4292  */
4293 static int spi_nor_parse_sfdp(struct spi_nor *nor,
4294                               struct spi_nor_flash_parameter *params)
4295 {
4296         const struct sfdp_parameter_header *param_header, *bfpt_header;
4297         struct sfdp_parameter_header *param_headers = NULL;
4298         struct sfdp_header header;
4299         struct device *dev = nor->dev;
4300         size_t psize;
4301         int i, err;
4302
4303         /* Get the SFDP header. */
4304         err = spi_nor_read_sfdp_dma_unsafe(nor, 0, sizeof(header), &header);
4305         if (err < 0)
4306                 return err;
4307
4308         /* Check the SFDP header version. */
4309         if (le32_to_cpu(header.signature) != SFDP_SIGNATURE ||
4310             header.major != SFDP_JESD216_MAJOR)
4311                 return -EINVAL;
4312
4313         /*
4314          * Verify that the first and only mandatory parameter header is a
4315          * Basic Flash Parameter Table header as specified in JESD216.
4316          */
4317         bfpt_header = &header.bfpt_header;
4318         if (SFDP_PARAM_HEADER_ID(bfpt_header) != SFDP_BFPT_ID ||
4319             bfpt_header->major != SFDP_JESD216_MAJOR)
4320                 return -EINVAL;
4321
4322         /*
4323          * Allocate memory then read all parameter headers with a single
4324          * Read SFDP command. These parameter headers will actually be parsed
4325          * twice: a first time to get the latest revision of the basic flash
4326          * parameter table, then a second time to handle the supported optional
4327          * tables.
4328          * Hence we read the parameter headers once for all to reduce the
4329          * processing time. Also we use kmalloc() instead of devm_kmalloc()
4330          * because we don't need to keep these parameter headers: the allocated
4331          * memory is always released with kfree() before exiting this function.
4332          */
4333         if (header.nph) {
4334                 psize = header.nph * sizeof(*param_headers);
4335
4336                 param_headers = kmalloc(psize, GFP_KERNEL);
4337                 if (!param_headers)
4338                         return -ENOMEM;
4339
4340                 err = spi_nor_read_sfdp(nor, sizeof(header),
4341                                         psize, param_headers);
4342                 if (err < 0) {
4343                         dev_dbg(dev, "failed to read SFDP parameter headers\n");
4344                         goto exit;
4345                 }
4346         }
4347
4348         /*
4349          * Check other parameter headers to get the latest revision of
4350          * the basic flash parameter table.
4351          */
4352         for (i = 0; i < header.nph; i++) {
4353                 param_header = &param_headers[i];
4354
4355                 if (SFDP_PARAM_HEADER_ID(param_header) == SFDP_BFPT_ID &&
4356                     param_header->major == SFDP_JESD216_MAJOR &&
4357                     (param_header->minor > bfpt_header->minor ||
4358                      (param_header->minor == bfpt_header->minor &&
4359                       param_header->length > bfpt_header->length)))
4360                         bfpt_header = param_header;
4361         }
4362
4363         err = spi_nor_parse_bfpt(nor, bfpt_header, params);
4364         if (err)
4365                 goto exit;
4366
4367         /* Parse optional parameter tables. */
4368         for (i = 0; i < header.nph; i++) {
4369                 param_header = &param_headers[i];
4370
4371                 switch (SFDP_PARAM_HEADER_ID(param_header)) {
4372                 case SFDP_SECTOR_MAP_ID:
4373                         err = spi_nor_parse_smpt(nor, param_header, params);
4374                         break;
4375
4376                 case SFDP_4BAIT_ID:
4377                         err = spi_nor_parse_4bait(nor, param_header, params);
4378                         break;
4379
4380                 default:
4381                         break;
4382                 }
4383
4384                 if (err) {
4385                         dev_warn(dev, "Failed to parse optional parameter table: %04x\n",
4386                                  SFDP_PARAM_HEADER_ID(param_header));
4387                         /*
4388                          * Let's not drop all information we extracted so far
4389                          * if optional table parsers fail. In case of failing,
4390                          * each optional parser is responsible to roll back to
4391                          * the previously known spi_nor data.
4392                          */
4393                         err = 0;
4394                 }
4395         }
4396
4397 exit:
4398         kfree(param_headers);
4399         return err;
4400 }
4401
4402 static int spi_nor_select_read(struct spi_nor *nor,
4403                                u32 shared_hwcaps)
4404 {
4405         int cmd, best_match = fls(shared_hwcaps & SNOR_HWCAPS_READ_MASK) - 1;
4406         const struct spi_nor_read_command *read;
4407
4408         if (best_match < 0)
4409                 return -EINVAL;
4410
4411         cmd = spi_nor_hwcaps_read2cmd(BIT(best_match));
4412         if (cmd < 0)
4413                 return -EINVAL;
4414
4415         read = &nor->params.reads[cmd];
4416         nor->read_opcode = read->opcode;
4417         nor->read_proto = read->proto;
4418
4419         /*
4420          * In the spi-nor framework, we don't need to make the difference
4421          * between mode clock cycles and wait state clock cycles.
4422          * Indeed, the value of the mode clock cycles is used by a QSPI
4423          * flash memory to know whether it should enter or leave its 0-4-4
4424          * (Continuous Read / XIP) mode.
4425          * eXecution In Place is out of the scope of the mtd sub-system.
4426          * Hence we choose to merge both mode and wait state clock cycles
4427          * into the so called dummy clock cycles.
4428          */
4429         nor->read_dummy = read->num_mode_clocks + read->num_wait_states;
4430         return 0;
4431 }
4432
4433 static int spi_nor_select_pp(struct spi_nor *nor,
4434                              u32 shared_hwcaps)
4435 {
4436         int cmd, best_match = fls(shared_hwcaps & SNOR_HWCAPS_PP_MASK) - 1;
4437         const struct spi_nor_pp_command *pp;
4438
4439         if (best_match < 0)
4440                 return -EINVAL;
4441
4442         cmd = spi_nor_hwcaps_pp2cmd(BIT(best_match));
4443         if (cmd < 0)
4444                 return -EINVAL;
4445
4446         pp = &nor->params.page_programs[cmd];
4447         nor->program_opcode = pp->opcode;
4448         nor->write_proto = pp->proto;
4449         return 0;
4450 }
4451
4452 /**
4453  * spi_nor_select_uniform_erase() - select optimum uniform erase type
4454  * @map:                the erase map of the SPI NOR
4455  * @wanted_size:        the erase type size to search for. Contains the value of
4456  *                      info->sector_size or of the "small sector" size in case
4457  *                      CONFIG_MTD_SPI_NOR_USE_4K_SECTORS is defined.
4458  *
4459  * Once the optimum uniform sector erase command is found, disable all the
4460  * other.
4461  *
4462  * Return: pointer to erase type on success, NULL otherwise.
4463  */
4464 static const struct spi_nor_erase_type *
4465 spi_nor_select_uniform_erase(struct spi_nor_erase_map *map,
4466                              const u32 wanted_size)
4467 {
4468         const struct spi_nor_erase_type *tested_erase, *erase = NULL;
4469         int i;
4470         u8 uniform_erase_type = map->uniform_erase_type;
4471
4472         for (i = SNOR_ERASE_TYPE_MAX - 1; i >= 0; i--) {
4473                 if (!(uniform_erase_type & BIT(i)))
4474                         continue;
4475
4476                 tested_erase = &map->erase_type[i];
4477
4478                 /*
4479                  * If the current erase size is the one, stop here:
4480                  * we have found the right uniform Sector Erase command.
4481                  */
4482                 if (tested_erase->size == wanted_size) {
4483                         erase = tested_erase;
4484                         break;
4485                 }
4486
4487                 /*
4488                  * Otherwise, the current erase size is still a valid canditate.
4489                  * Select the biggest valid candidate.
4490                  */
4491                 if (!erase && tested_erase->size)
4492                         erase = tested_erase;
4493                         /* keep iterating to find the wanted_size */
4494         }
4495
4496         if (!erase)
4497                 return NULL;
4498
4499         /* Disable all other Sector Erase commands. */
4500         map->uniform_erase_type &= ~SNOR_ERASE_TYPE_MASK;
4501         map->uniform_erase_type |= BIT(erase - map->erase_type);
4502         return erase;
4503 }
4504
4505 static int spi_nor_select_erase(struct spi_nor *nor)
4506 {
4507         struct spi_nor_erase_map *map = &nor->params.erase_map;
4508         const struct spi_nor_erase_type *erase = NULL;
4509         struct mtd_info *mtd = &nor->mtd;
4510         u32 wanted_size = nor->info->sector_size;
4511         int i;
4512
4513         /*
4514          * The previous implementation handling Sector Erase commands assumed
4515          * that the SPI flash memory has an uniform layout then used only one
4516          * of the supported erase sizes for all Sector Erase commands.
4517          * So to be backward compatible, the new implementation also tries to
4518          * manage the SPI flash memory as uniform with a single erase sector
4519          * size, when possible.
4520          */
4521 #ifdef CONFIG_MTD_SPI_NOR_USE_4K_SECTORS
4522         /* prefer "small sector" erase if possible */
4523         wanted_size = 4096u;
4524 #endif
4525
4526         if (spi_nor_has_uniform_erase(nor)) {
4527                 erase = spi_nor_select_uniform_erase(map, wanted_size);
4528                 if (!erase)
4529                         return -EINVAL;
4530                 nor->erase_opcode = erase->opcode;
4531                 mtd->erasesize = erase->size;
4532                 return 0;
4533         }
4534
4535         /*
4536          * For non-uniform SPI flash memory, set mtd->erasesize to the
4537          * maximum erase sector size. No need to set nor->erase_opcode.
4538          */
4539         for (i = SNOR_ERASE_TYPE_MAX - 1; i >= 0; i--) {
4540                 if (map->erase_type[i].size) {
4541                         erase = &map->erase_type[i];
4542                         break;
4543                 }
4544         }
4545
4546         if (!erase)
4547                 return -EINVAL;
4548
4549         mtd->erasesize = erase->size;
4550         return 0;
4551 }
4552
4553 static int spi_nor_default_setup(struct spi_nor *nor,
4554                                  const struct spi_nor_hwcaps *hwcaps)
4555 {
4556         struct spi_nor_flash_parameter *params = &nor->params;
4557         u32 ignored_mask, shared_mask;
4558         int err;
4559
4560         /*
4561          * Keep only the hardware capabilities supported by both the SPI
4562          * controller and the SPI flash memory.
4563          */
4564         shared_mask = hwcaps->mask & params->hwcaps.mask;
4565
4566         if (nor->spimem) {
4567                 /*
4568                  * When called from spi_nor_probe(), all caps are set and we
4569                  * need to discard some of them based on what the SPI
4570                  * controller actually supports (using spi_mem_supports_op()).
4571                  */
4572                 spi_nor_spimem_adjust_hwcaps(nor, &shared_mask);
4573         } else {
4574                 /*
4575                  * SPI n-n-n protocols are not supported when the SPI
4576                  * controller directly implements the spi_nor interface.
4577                  * Yet another reason to switch to spi-mem.
4578                  */
4579                 ignored_mask = SNOR_HWCAPS_X_X_X;
4580                 if (shared_mask & ignored_mask) {
4581                         dev_dbg(nor->dev,
4582                                 "SPI n-n-n protocols are not supported.\n");
4583                         shared_mask &= ~ignored_mask;
4584                 }
4585         }
4586
4587         /* Select the (Fast) Read command. */
4588         err = spi_nor_select_read(nor, shared_mask);
4589         if (err) {
4590                 dev_dbg(nor->dev,
4591                         "can't select read settings supported by both the SPI controller and memory.\n");
4592                 return err;
4593         }
4594
4595         /* Select the Page Program command. */
4596         err = spi_nor_select_pp(nor, shared_mask);
4597         if (err) {
4598                 dev_dbg(nor->dev,
4599                         "can't select write settings supported by both the SPI controller and memory.\n");
4600                 return err;
4601         }
4602
4603         /* Select the Sector Erase command. */
4604         err = spi_nor_select_erase(nor);
4605         if (err) {
4606                 dev_dbg(nor->dev,
4607                         "can't select erase settings supported by both the SPI controller and memory.\n");
4608                 return err;
4609         }
4610
4611         return 0;
4612 }
4613
4614 static int spi_nor_setup(struct spi_nor *nor,
4615                          const struct spi_nor_hwcaps *hwcaps)
4616 {
4617         if (!nor->params.setup)
4618                 return 0;
4619
4620         return nor->params.setup(nor, hwcaps);
4621 }
4622
4623 static void atmel_set_default_init(struct spi_nor *nor)
4624 {
4625         nor->flags |= SNOR_F_HAS_LOCK;
4626 }
4627
4628 static void intel_set_default_init(struct spi_nor *nor)
4629 {
4630         nor->flags |= SNOR_F_HAS_LOCK;
4631 }
4632
4633 static void issi_set_default_init(struct spi_nor *nor)
4634 {
4635         nor->params.quad_enable = spi_nor_sr1_bit6_quad_enable;
4636 }
4637
4638 static void macronix_set_default_init(struct spi_nor *nor)
4639 {
4640         nor->params.quad_enable = spi_nor_sr1_bit6_quad_enable;
4641         nor->params.set_4byte = macronix_set_4byte;
4642 }
4643
4644 static void sst_set_default_init(struct spi_nor *nor)
4645 {
4646         nor->flags |= SNOR_F_HAS_LOCK;
4647 }
4648
4649 static void st_micron_set_default_init(struct spi_nor *nor)
4650 {
4651         nor->flags |= SNOR_F_HAS_LOCK;
4652         nor->flags &= ~SNOR_F_HAS_16BIT_SR;
4653         nor->params.quad_enable = NULL;
4654         nor->params.set_4byte = st_micron_set_4byte;
4655 }
4656
4657 static void winbond_set_default_init(struct spi_nor *nor)
4658 {
4659         nor->params.set_4byte = winbond_set_4byte;
4660 }
4661
4662 /**
4663  * spi_nor_manufacturer_init_params() - Initialize the flash's parameters and
4664  * settings based on MFR register and ->default_init() hook.
4665  * @nor:        pointer to a 'struct spi-nor'.
4666  */
4667 static void spi_nor_manufacturer_init_params(struct spi_nor *nor)
4668 {
4669         /* Init flash parameters based on MFR */
4670         switch (JEDEC_MFR(nor->info)) {
4671         case SNOR_MFR_ATMEL:
4672                 atmel_set_default_init(nor);
4673                 break;
4674
4675         case SNOR_MFR_INTEL:
4676                 intel_set_default_init(nor);
4677                 break;
4678
4679         case SNOR_MFR_ISSI:
4680                 issi_set_default_init(nor);
4681                 break;
4682
4683         case SNOR_MFR_MACRONIX:
4684                 macronix_set_default_init(nor);
4685                 break;
4686
4687         case SNOR_MFR_ST:
4688         case SNOR_MFR_MICRON:
4689                 st_micron_set_default_init(nor);
4690                 break;
4691
4692         case SNOR_MFR_SST:
4693                 sst_set_default_init(nor);
4694                 break;
4695
4696         case SNOR_MFR_WINBOND:
4697                 winbond_set_default_init(nor);
4698                 break;
4699
4700         default:
4701                 break;
4702         }
4703
4704         if (nor->info->fixups && nor->info->fixups->default_init)
4705                 nor->info->fixups->default_init(nor);
4706 }
4707
4708 /**
4709  * spi_nor_sfdp_init_params() - Initialize the flash's parameters and settings
4710  * based on JESD216 SFDP standard.
4711  * @nor:        pointer to a 'struct spi-nor'.
4712  *
4713  * The method has a roll-back mechanism: in case the SFDP parsing fails, the
4714  * legacy flash parameters and settings will be restored.
4715  */
4716 static void spi_nor_sfdp_init_params(struct spi_nor *nor)
4717 {
4718         struct spi_nor_flash_parameter sfdp_params;
4719
4720         memcpy(&sfdp_params, &nor->params, sizeof(sfdp_params));
4721
4722         if (spi_nor_parse_sfdp(nor, &sfdp_params)) {
4723                 nor->addr_width = 0;
4724                 nor->flags &= ~SNOR_F_4B_OPCODES;
4725         } else {
4726                 memcpy(&nor->params, &sfdp_params, sizeof(nor->params));
4727         }
4728 }
4729
4730 /**
4731  * spi_nor_info_init_params() - Initialize the flash's parameters and settings
4732  * based on nor->info data.
4733  * @nor:        pointer to a 'struct spi-nor'.
4734  */
4735 static void spi_nor_info_init_params(struct spi_nor *nor)
4736 {
4737         struct spi_nor_flash_parameter *params = &nor->params;
4738         struct spi_nor_erase_map *map = &params->erase_map;
4739         const struct flash_info *info = nor->info;
4740         struct device_node *np = spi_nor_get_flash_node(nor);
4741         u8 i, erase_mask;
4742
4743         /* Initialize legacy flash parameters and settings. */
4744         params->quad_enable = spi_nor_sr2_bit1_quad_enable;
4745         params->set_4byte = spansion_set_4byte;
4746         params->setup = spi_nor_default_setup;
4747         /* Default to 16-bit Write Status (01h) Command */
4748         nor->flags |= SNOR_F_HAS_16BIT_SR;
4749
4750         /* Set SPI NOR sizes. */
4751         params->size = (u64)info->sector_size * info->n_sectors;
4752         params->page_size = info->page_size;
4753
4754         if (!(info->flags & SPI_NOR_NO_FR)) {
4755                 /* Default to Fast Read for DT and non-DT platform devices. */
4756                 params->hwcaps.mask |= SNOR_HWCAPS_READ_FAST;
4757
4758                 /* Mask out Fast Read if not requested at DT instantiation. */
4759                 if (np && !of_property_read_bool(np, "m25p,fast-read"))
4760                         params->hwcaps.mask &= ~SNOR_HWCAPS_READ_FAST;
4761         }
4762
4763         /* (Fast) Read settings. */
4764         params->hwcaps.mask |= SNOR_HWCAPS_READ;
4765         spi_nor_set_read_settings(&params->reads[SNOR_CMD_READ],
4766                                   0, 0, SPINOR_OP_READ,
4767                                   SNOR_PROTO_1_1_1);
4768
4769         if (params->hwcaps.mask & SNOR_HWCAPS_READ_FAST)
4770                 spi_nor_set_read_settings(&params->reads[SNOR_CMD_READ_FAST],
4771                                           0, 8, SPINOR_OP_READ_FAST,
4772                                           SNOR_PROTO_1_1_1);
4773
4774         if (info->flags & SPI_NOR_DUAL_READ) {
4775                 params->hwcaps.mask |= SNOR_HWCAPS_READ_1_1_2;
4776                 spi_nor_set_read_settings(&params->reads[SNOR_CMD_READ_1_1_2],
4777                                           0, 8, SPINOR_OP_READ_1_1_2,
4778                                           SNOR_PROTO_1_1_2);
4779         }
4780
4781         if (info->flags & SPI_NOR_QUAD_READ) {
4782                 params->hwcaps.mask |= SNOR_HWCAPS_READ_1_1_4;
4783                 spi_nor_set_read_settings(&params->reads[SNOR_CMD_READ_1_1_4],
4784                                           0, 8, SPINOR_OP_READ_1_1_4,
4785                                           SNOR_PROTO_1_1_4);
4786         }
4787
4788         if (info->flags & SPI_NOR_OCTAL_READ) {
4789                 params->hwcaps.mask |= SNOR_HWCAPS_READ_1_1_8;
4790                 spi_nor_set_read_settings(&params->reads[SNOR_CMD_READ_1_1_8],
4791                                           0, 8, SPINOR_OP_READ_1_1_8,
4792                                           SNOR_PROTO_1_1_8);
4793         }
4794
4795         /* Page Program settings. */
4796         params->hwcaps.mask |= SNOR_HWCAPS_PP;
4797         spi_nor_set_pp_settings(&params->page_programs[SNOR_CMD_PP],
4798                                 SPINOR_OP_PP, SNOR_PROTO_1_1_1);
4799
4800         /*
4801          * Sector Erase settings. Sort Erase Types in ascending order, with the
4802          * smallest erase size starting at BIT(0).
4803          */
4804         erase_mask = 0;
4805         i = 0;
4806         if (info->flags & SECT_4K_PMC) {
4807                 erase_mask |= BIT(i);
4808                 spi_nor_set_erase_type(&map->erase_type[i], 4096u,
4809                                        SPINOR_OP_BE_4K_PMC);
4810                 i++;
4811         } else if (info->flags & SECT_4K) {
4812                 erase_mask |= BIT(i);
4813                 spi_nor_set_erase_type(&map->erase_type[i], 4096u,
4814                                        SPINOR_OP_BE_4K);
4815                 i++;
4816         }
4817         erase_mask |= BIT(i);
4818         spi_nor_set_erase_type(&map->erase_type[i], info->sector_size,
4819                                SPINOR_OP_SE);
4820         spi_nor_init_uniform_erase_map(map, erase_mask, params->size);
4821 }
4822
4823 static void spansion_post_sfdp_fixups(struct spi_nor *nor)
4824 {
4825         if (nor->params.size <= SZ_16M)
4826                 return;
4827
4828         nor->flags |= SNOR_F_4B_OPCODES;
4829         /* No small sector erase for 4-byte command set */
4830         nor->erase_opcode = SPINOR_OP_SE;
4831         nor->mtd.erasesize = nor->info->sector_size;
4832 }
4833
4834 static void s3an_post_sfdp_fixups(struct spi_nor *nor)
4835 {
4836         nor->params.setup = s3an_nor_setup;
4837 }
4838
4839 /**
4840  * spi_nor_post_sfdp_fixups() - Updates the flash's parameters and settings
4841  * after SFDP has been parsed (is also called for SPI NORs that do not
4842  * support RDSFDP).
4843  * @nor:        pointer to a 'struct spi_nor'
4844  *
4845  * Typically used to tweak various parameters that could not be extracted by
4846  * other means (i.e. when information provided by the SFDP/flash_info tables
4847  * are incomplete or wrong).
4848  */
4849 static void spi_nor_post_sfdp_fixups(struct spi_nor *nor)
4850 {
4851         switch (JEDEC_MFR(nor->info)) {
4852         case SNOR_MFR_SPANSION:
4853                 spansion_post_sfdp_fixups(nor);
4854                 break;
4855
4856         default:
4857                 break;
4858         }
4859
4860         if (nor->info->flags & SPI_S3AN)
4861                 s3an_post_sfdp_fixups(nor);
4862
4863         if (nor->info->fixups && nor->info->fixups->post_sfdp)
4864                 nor->info->fixups->post_sfdp(nor);
4865 }
4866
4867 /**
4868  * spi_nor_late_init_params() - Late initialization of default flash parameters.
4869  * @nor:        pointer to a 'struct spi_nor'
4870  *
4871  * Used to set default flash parameters and settings when the ->default_init()
4872  * hook or the SFDP parser let voids.
4873  */
4874 static void spi_nor_late_init_params(struct spi_nor *nor)
4875 {
4876         /*
4877          * NOR protection support. When locking_ops are not provided, we pick
4878          * the default ones.
4879          */
4880         if (nor->flags & SNOR_F_HAS_LOCK && !nor->params.locking_ops)
4881                 nor->params.locking_ops = &stm_locking_ops;
4882 }
4883
4884 /**
4885  * spi_nor_init_params() - Initialize the flash's parameters and settings.
4886  * @nor:        pointer to a 'struct spi-nor'.
4887  *
4888  * The flash parameters and settings are initialized based on a sequence of
4889  * calls that are ordered by priority:
4890  *
4891  * 1/ Default flash parameters initialization. The initializations are done
4892  *    based on nor->info data:
4893  *              spi_nor_info_init_params()
4894  *
4895  * which can be overwritten by:
4896  * 2/ Manufacturer flash parameters initialization. The initializations are
4897  *    done based on MFR register, or when the decisions can not be done solely
4898  *    based on MFR, by using specific flash_info tweeks, ->default_init():
4899  *              spi_nor_manufacturer_init_params()
4900  *
4901  * which can be overwritten by:
4902  * 3/ SFDP flash parameters initialization. JESD216 SFDP is a standard and
4903  *    should be more accurate that the above.
4904  *              spi_nor_sfdp_init_params()
4905  *
4906  *    Please note that there is a ->post_bfpt() fixup hook that can overwrite
4907  *    the flash parameters and settings immediately after parsing the Basic
4908  *    Flash Parameter Table.
4909  *
4910  * which can be overwritten by:
4911  * 4/ Post SFDP flash parameters initialization. Used to tweak various
4912  *    parameters that could not be extracted by other means (i.e. when
4913  *    information provided by the SFDP/flash_info tables are incomplete or
4914  *    wrong).
4915  *              spi_nor_post_sfdp_fixups()
4916  *
4917  * 5/ Late default flash parameters initialization, used when the
4918  * ->default_init() hook or the SFDP parser do not set specific params.
4919  *              spi_nor_late_init_params()
4920  */
4921 static void spi_nor_init_params(struct spi_nor *nor)
4922 {
4923         spi_nor_info_init_params(nor);
4924
4925         spi_nor_manufacturer_init_params(nor);
4926
4927         if ((nor->info->flags & (SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ)) &&
4928             !(nor->info->flags & SPI_NOR_SKIP_SFDP))
4929                 spi_nor_sfdp_init_params(nor);
4930
4931         spi_nor_post_sfdp_fixups(nor);
4932
4933         spi_nor_late_init_params(nor);
4934 }
4935
4936 /**
4937  * spi_nor_quad_enable() - enable Quad I/O if needed.
4938  * @nor:                pointer to a 'struct spi_nor'
4939  *
4940  * Return: 0 on success, -errno otherwise.
4941  */
4942 static int spi_nor_quad_enable(struct spi_nor *nor)
4943 {
4944         if (!nor->params.quad_enable)
4945                 return 0;
4946
4947         if (!(spi_nor_get_protocol_width(nor->read_proto) == 4 ||
4948               spi_nor_get_protocol_width(nor->write_proto) == 4))
4949                 return 0;
4950
4951         return nor->params.quad_enable(nor);
4952 }
4953
4954 /**
4955  * spi_nor_unlock_all() - Unlocks the entire flash memory array.
4956  * @nor:        pointer to a 'struct spi_nor'.
4957  *
4958  * Some SPI NOR flashes are write protected by default after a power-on reset
4959  * cycle, in order to avoid inadvertent writes during power-up. Backward
4960  * compatibility imposes to unlock the entire flash memory array at power-up
4961  * by default.
4962  */
4963 static int spi_nor_unlock_all(struct spi_nor *nor)
4964 {
4965         if (nor->flags & SNOR_F_HAS_LOCK)
4966                 return spi_nor_unlock(&nor->mtd, 0, nor->params.size);
4967
4968         return 0;
4969 }
4970
4971 static int spi_nor_init(struct spi_nor *nor)
4972 {
4973         int err;
4974
4975         err = spi_nor_quad_enable(nor);
4976         if (err) {
4977                 dev_dbg(nor->dev, "quad mode not supported\n");
4978                 return err;
4979         }
4980
4981         err = spi_nor_unlock_all(nor);
4982         if (err) {
4983                 dev_dbg(nor->dev, "Failed to unlock the entire flash memory array\n");
4984                 return err;
4985         }
4986
4987         if (nor->addr_width == 4 && !(nor->flags & SNOR_F_4B_OPCODES)) {
4988                 /*
4989                  * If the RESET# pin isn't hooked up properly, or the system
4990                  * otherwise doesn't perform a reset command in the boot
4991                  * sequence, it's impossible to 100% protect against unexpected
4992                  * reboots (e.g., crashes). Warn the user (or hopefully, system
4993                  * designer) that this is bad.
4994                  */
4995                 WARN_ONCE(nor->flags & SNOR_F_BROKEN_RESET,
4996                           "enabling reset hack; may not recover from unexpected reboots\n");
4997                 nor->params.set_4byte(nor, true);
4998         }
4999
5000         return 0;
5001 }
5002
5003 /* mtd resume handler */
5004 static void spi_nor_resume(struct mtd_info *mtd)
5005 {
5006         struct spi_nor *nor = mtd_to_spi_nor(mtd);
5007         struct device *dev = nor->dev;
5008         int ret;
5009
5010         /* re-initialize the nor chip */
5011         ret = spi_nor_init(nor);
5012         if (ret)
5013                 dev_err(dev, "resume() failed\n");
5014 }
5015
5016 void spi_nor_restore(struct spi_nor *nor)
5017 {
5018         /* restore the addressing mode */
5019         if (nor->addr_width == 4 && !(nor->flags & SNOR_F_4B_OPCODES) &&
5020             nor->flags & SNOR_F_BROKEN_RESET)
5021                 nor->params.set_4byte(nor, false);
5022 }
5023 EXPORT_SYMBOL_GPL(spi_nor_restore);
5024
5025 static const struct flash_info *spi_nor_match_id(const char *name)
5026 {
5027         const struct flash_info *id = spi_nor_ids;
5028
5029         while (id->name) {
5030                 if (!strcmp(name, id->name))
5031                         return id;
5032                 id++;
5033         }
5034         return NULL;
5035 }
5036
5037 static int spi_nor_set_addr_width(struct spi_nor *nor)
5038 {
5039         if (nor->addr_width) {
5040                 /* already configured from SFDP */
5041         } else if (nor->info->addr_width) {
5042                 nor->addr_width = nor->info->addr_width;
5043         } else if (nor->mtd.size > 0x1000000) {
5044                 /* enable 4-byte addressing if the device exceeds 16MiB */
5045                 nor->addr_width = 4;
5046         } else {
5047                 nor->addr_width = 3;
5048         }
5049
5050         if (nor->addr_width > SPI_NOR_MAX_ADDR_WIDTH) {
5051                 dev_dbg(nor->dev, "address width is too large: %u\n",
5052                         nor->addr_width);
5053                 return -EINVAL;
5054         }
5055
5056         /* Set 4byte opcodes when possible. */
5057         if (nor->addr_width == 4 && nor->flags & SNOR_F_4B_OPCODES &&
5058             !(nor->flags & SNOR_F_HAS_4BAIT))
5059                 spi_nor_set_4byte_opcodes(nor);
5060
5061         return 0;
5062 }
5063
5064 static void spi_nor_debugfs_init(struct spi_nor *nor,
5065                                  const struct flash_info *info)
5066 {
5067         struct mtd_info *mtd = &nor->mtd;
5068
5069         mtd->dbg.partname = info->name;
5070         mtd->dbg.partid = devm_kasprintf(nor->dev, GFP_KERNEL, "spi-nor:%*phN",
5071                                          info->id_len, info->id);
5072 }
5073
5074 static const struct flash_info *spi_nor_get_flash_info(struct spi_nor *nor,
5075                                                        const char *name)
5076 {
5077         const struct flash_info *info = NULL;
5078
5079         if (name)
5080                 info = spi_nor_match_id(name);
5081         /* Try to auto-detect if chip name wasn't specified or not found */
5082         if (!info)
5083                 info = spi_nor_read_id(nor);
5084         if (IS_ERR_OR_NULL(info))
5085                 return ERR_PTR(-ENOENT);
5086
5087         /*
5088          * If caller has specified name of flash model that can normally be
5089          * detected using JEDEC, let's verify it.
5090          */
5091         if (name && info->id_len) {
5092                 const struct flash_info *jinfo;
5093
5094                 jinfo = spi_nor_read_id(nor);
5095                 if (IS_ERR(jinfo)) {
5096                         return jinfo;
5097                 } else if (jinfo != info) {
5098                         /*
5099                          * JEDEC knows better, so overwrite platform ID. We
5100                          * can't trust partitions any longer, but we'll let
5101                          * mtd apply them anyway, since some partitions may be
5102                          * marked read-only, and we don't want to lose that
5103                          * information, even if it's not 100% accurate.
5104                          */
5105                         dev_warn(nor->dev, "found %s, expected %s\n",
5106                                  jinfo->name, info->name);
5107                         info = jinfo;
5108                 }
5109         }
5110
5111         return info;
5112 }
5113
5114 int spi_nor_scan(struct spi_nor *nor, const char *name,
5115                  const struct spi_nor_hwcaps *hwcaps)
5116 {
5117         const struct flash_info *info;
5118         struct device *dev = nor->dev;
5119         struct mtd_info *mtd = &nor->mtd;
5120         struct device_node *np = spi_nor_get_flash_node(nor);
5121         struct spi_nor_flash_parameter *params = &nor->params;
5122         int ret;
5123         int i;
5124
5125         ret = spi_nor_check(nor);
5126         if (ret)
5127                 return ret;
5128
5129         /* Reset SPI protocol for all commands. */
5130         nor->reg_proto = SNOR_PROTO_1_1_1;
5131         nor->read_proto = SNOR_PROTO_1_1_1;
5132         nor->write_proto = SNOR_PROTO_1_1_1;
5133
5134         /*
5135          * We need the bounce buffer early to read/write registers when going
5136          * through the spi-mem layer (buffers have to be DMA-able).
5137          * For spi-mem drivers, we'll reallocate a new buffer if
5138          * nor->page_size turns out to be greater than PAGE_SIZE (which
5139          * shouldn't happen before long since NOR pages are usually less
5140          * than 1KB) after spi_nor_scan() returns.
5141          */
5142         nor->bouncebuf_size = PAGE_SIZE;
5143         nor->bouncebuf = devm_kmalloc(dev, nor->bouncebuf_size,
5144                                       GFP_KERNEL);
5145         if (!nor->bouncebuf)
5146                 return -ENOMEM;
5147
5148         info = spi_nor_get_flash_info(nor, name);
5149         if (IS_ERR(info))
5150                 return PTR_ERR(info);
5151
5152         nor->info = info;
5153
5154         spi_nor_debugfs_init(nor, info);
5155
5156         mutex_init(&nor->lock);
5157
5158         /*
5159          * Make sure the XSR_RDY flag is set before calling
5160          * spi_nor_wait_till_ready(). Xilinx S3AN share MFR
5161          * with Atmel spi-nor
5162          */
5163         if (info->flags & SPI_NOR_XSR_RDY)
5164                 nor->flags |=  SNOR_F_READY_XSR_RDY;
5165
5166         if (info->flags & SPI_NOR_HAS_LOCK)
5167                 nor->flags |= SNOR_F_HAS_LOCK;
5168
5169         /* Init flash parameters based on flash_info struct and SFDP */
5170         spi_nor_init_params(nor);
5171
5172         if (!mtd->name)
5173                 mtd->name = dev_name(dev);
5174         mtd->priv = nor;
5175         mtd->type = MTD_NORFLASH;
5176         mtd->writesize = 1;
5177         mtd->flags = MTD_CAP_NORFLASH;
5178         mtd->size = params->size;
5179         mtd->_erase = spi_nor_erase;
5180         mtd->_read = spi_nor_read;
5181         mtd->_resume = spi_nor_resume;
5182
5183         if (nor->params.locking_ops) {
5184                 mtd->_lock = spi_nor_lock;
5185                 mtd->_unlock = spi_nor_unlock;
5186                 mtd->_is_locked = spi_nor_is_locked;
5187         }
5188
5189         /* sst nor chips use AAI word program */
5190         if (info->flags & SST_WRITE)
5191                 mtd->_write = sst_write;
5192         else
5193                 mtd->_write = spi_nor_write;
5194
5195         if (info->flags & USE_FSR)
5196                 nor->flags |= SNOR_F_USE_FSR;
5197         if (info->flags & SPI_NOR_HAS_TB) {
5198                 nor->flags |= SNOR_F_HAS_SR_TB;
5199                 if (info->flags & SPI_NOR_TB_SR_BIT6)
5200                         nor->flags |= SNOR_F_HAS_SR_TB_BIT6;
5201         }
5202
5203         if (info->flags & NO_CHIP_ERASE)
5204                 nor->flags |= SNOR_F_NO_OP_CHIP_ERASE;
5205         if (info->flags & USE_CLSR)
5206                 nor->flags |= SNOR_F_USE_CLSR;
5207
5208         if (info->flags & SPI_NOR_NO_ERASE)
5209                 mtd->flags |= MTD_NO_ERASE;
5210
5211         mtd->dev.parent = dev;
5212         nor->page_size = params->page_size;
5213         mtd->writebufsize = nor->page_size;
5214
5215         if (of_property_read_bool(np, "broken-flash-reset"))
5216                 nor->flags |= SNOR_F_BROKEN_RESET;
5217
5218         /*
5219          * Configure the SPI memory:
5220          * - select op codes for (Fast) Read, Page Program and Sector Erase.
5221          * - set the number of dummy cycles (mode cycles + wait states).
5222          * - set the SPI protocols for register and memory accesses.
5223          */
5224         ret = spi_nor_setup(nor, hwcaps);
5225         if (ret)
5226                 return ret;
5227
5228         if (info->flags & SPI_NOR_4B_OPCODES)
5229                 nor->flags |= SNOR_F_4B_OPCODES;
5230
5231         ret = spi_nor_set_addr_width(nor);
5232         if (ret)
5233                 return ret;
5234
5235         /* Send all the required SPI flash commands to initialize device */
5236         ret = spi_nor_init(nor);
5237         if (ret)
5238                 return ret;
5239
5240         dev_info(dev, "%s (%lld Kbytes)\n", info->name,
5241                         (long long)mtd->size >> 10);
5242
5243         dev_dbg(dev,
5244                 "mtd .name = %s, .size = 0x%llx (%lldMiB), "
5245                 ".erasesize = 0x%.8x (%uKiB) .numeraseregions = %d\n",
5246                 mtd->name, (long long)mtd->size, (long long)(mtd->size >> 20),
5247                 mtd->erasesize, mtd->erasesize / 1024, mtd->numeraseregions);
5248
5249         if (mtd->numeraseregions)
5250                 for (i = 0; i < mtd->numeraseregions; i++)
5251                         dev_dbg(dev,
5252                                 "mtd.eraseregions[%d] = { .offset = 0x%llx, "
5253                                 ".erasesize = 0x%.8x (%uKiB), "
5254                                 ".numblocks = %d }\n",
5255                                 i, (long long)mtd->eraseregions[i].offset,
5256                                 mtd->eraseregions[i].erasesize,
5257                                 mtd->eraseregions[i].erasesize / 1024,
5258                                 mtd->eraseregions[i].numblocks);
5259         return 0;
5260 }
5261 EXPORT_SYMBOL_GPL(spi_nor_scan);
5262
5263 static int spi_nor_probe(struct spi_mem *spimem)
5264 {
5265         struct spi_device *spi = spimem->spi;
5266         struct flash_platform_data *data = dev_get_platdata(&spi->dev);
5267         struct spi_nor *nor;
5268         /*
5269          * Enable all caps by default. The core will mask them after
5270          * checking what's really supported using spi_mem_supports_op().
5271          */
5272         const struct spi_nor_hwcaps hwcaps = { .mask = SNOR_HWCAPS_ALL };
5273         char *flash_name;
5274         int ret;
5275
5276         nor = devm_kzalloc(&spi->dev, sizeof(*nor), GFP_KERNEL);
5277         if (!nor)
5278                 return -ENOMEM;
5279
5280         nor->spimem = spimem;
5281         nor->dev = &spi->dev;
5282         spi_nor_set_flash_node(nor, spi->dev.of_node);
5283
5284         spi_mem_set_drvdata(spimem, nor);
5285
5286         if (data && data->name)
5287                 nor->mtd.name = data->name;
5288
5289         if (!nor->mtd.name)
5290                 nor->mtd.name = spi_mem_get_name(spimem);
5291
5292         /*
5293          * For some (historical?) reason many platforms provide two different
5294          * names in flash_platform_data: "name" and "type". Quite often name is
5295          * set to "m25p80" and then "type" provides a real chip name.
5296          * If that's the case, respect "type" and ignore a "name".
5297          */
5298         if (data && data->type)
5299                 flash_name = data->type;
5300         else if (!strcmp(spi->modalias, "spi-nor"))
5301                 flash_name = NULL; /* auto-detect */
5302         else
5303                 flash_name = spi->modalias;
5304
5305         ret = spi_nor_scan(nor, flash_name, &hwcaps);
5306         if (ret)
5307                 return ret;
5308
5309         /*
5310          * None of the existing parts have > 512B pages, but let's play safe
5311          * and add this logic so that if anyone ever adds support for such
5312          * a NOR we don't end up with buffer overflows.
5313          */
5314         if (nor->page_size > PAGE_SIZE) {
5315                 nor->bouncebuf_size = nor->page_size;
5316                 devm_kfree(nor->dev, nor->bouncebuf);
5317                 nor->bouncebuf = devm_kmalloc(nor->dev,
5318                                               nor->bouncebuf_size,
5319                                               GFP_KERNEL);
5320                 if (!nor->bouncebuf)
5321                         return -ENOMEM;
5322         }
5323
5324         return mtd_device_register(&nor->mtd, data ? data->parts : NULL,
5325                                    data ? data->nr_parts : 0);
5326 }
5327
5328 static int spi_nor_remove(struct spi_mem *spimem)
5329 {
5330         struct spi_nor *nor = spi_mem_get_drvdata(spimem);
5331
5332         spi_nor_restore(nor);
5333
5334         /* Clean up MTD stuff. */
5335         return mtd_device_unregister(&nor->mtd);
5336 }
5337
5338 static void spi_nor_shutdown(struct spi_mem *spimem)
5339 {
5340         struct spi_nor *nor = spi_mem_get_drvdata(spimem);
5341
5342         spi_nor_restore(nor);
5343 }
5344
5345 /*
5346  * Do NOT add to this array without reading the following:
5347  *
5348  * Historically, many flash devices are bound to this driver by their name. But
5349  * since most of these flash are compatible to some extent, and their
5350  * differences can often be differentiated by the JEDEC read-ID command, we
5351  * encourage new users to add support to the spi-nor library, and simply bind
5352  * against a generic string here (e.g., "jedec,spi-nor").
5353  *
5354  * Many flash names are kept here in this list (as well as in spi-nor.c) to
5355  * keep them available as module aliases for existing platforms.
5356  */
5357 static const struct spi_device_id spi_nor_dev_ids[] = {
5358         /*
5359          * Allow non-DT platform devices to bind to the "spi-nor" modalias, and
5360          * hack around the fact that the SPI core does not provide uevent
5361          * matching for .of_match_table
5362          */
5363         {"spi-nor"},
5364
5365         /*
5366          * Entries not used in DTs that should be safe to drop after replacing
5367          * them with "spi-nor" in platform data.
5368          */
5369         {"s25sl064a"},  {"w25x16"},     {"m25p10"},     {"m25px64"},
5370
5371         /*
5372          * Entries that were used in DTs without "jedec,spi-nor" fallback and
5373          * should be kept for backward compatibility.
5374          */
5375         {"at25df321a"}, {"at25df641"},  {"at26df081a"},
5376         {"mx25l4005a"}, {"mx25l1606e"}, {"mx25l6405d"}, {"mx25l12805d"},
5377         {"mx25l25635e"},{"mx66l51235l"},
5378         {"n25q064"},    {"n25q128a11"}, {"n25q128a13"}, {"n25q512a"},
5379         {"s25fl256s1"}, {"s25fl512s"},  {"s25sl12801"}, {"s25fl008k"},
5380         {"s25fl064k"},
5381         {"sst25vf040b"},{"sst25vf016b"},{"sst25vf032b"},{"sst25wf040"},
5382         {"m25p40"},     {"m25p80"},     {"m25p16"},     {"m25p32"},
5383         {"m25p64"},     {"m25p128"},
5384         {"w25x80"},     {"w25x32"},     {"w25q32"},     {"w25q32dw"},
5385         {"w25q80bl"},   {"w25q128"},    {"w25q256"},
5386
5387         /* Flashes that can't be detected using JEDEC */
5388         {"m25p05-nonjedec"},    {"m25p10-nonjedec"},    {"m25p20-nonjedec"},
5389         {"m25p40-nonjedec"},    {"m25p80-nonjedec"},    {"m25p16-nonjedec"},
5390         {"m25p32-nonjedec"},    {"m25p64-nonjedec"},    {"m25p128-nonjedec"},
5391
5392         /* Everspin MRAMs (non-JEDEC) */
5393         { "mr25h128" }, /* 128 Kib, 40 MHz */
5394         { "mr25h256" }, /* 256 Kib, 40 MHz */
5395         { "mr25h10" },  /*   1 Mib, 40 MHz */
5396         { "mr25h40" },  /*   4 Mib, 40 MHz */
5397
5398         { },
5399 };
5400 MODULE_DEVICE_TABLE(spi, spi_nor_dev_ids);
5401
5402 static const struct of_device_id spi_nor_of_table[] = {
5403         /*
5404          * Generic compatibility for SPI NOR that can be identified by the
5405          * JEDEC READ ID opcode (0x9F). Use this, if possible.
5406          */
5407         { .compatible = "jedec,spi-nor" },
5408         { /* sentinel */ },
5409 };
5410 MODULE_DEVICE_TABLE(of, spi_nor_of_table);
5411
5412 /*
5413  * REVISIT: many of these chips have deep power-down modes, which
5414  * should clearly be entered on suspend() to minimize power use.
5415  * And also when they're otherwise idle...
5416  */
5417 static struct spi_mem_driver spi_nor_driver = {
5418         .spidrv = {
5419                 .driver = {
5420                         .name = "spi-nor",
5421                         .of_match_table = spi_nor_of_table,
5422                 },
5423                 .id_table = spi_nor_dev_ids,
5424         },
5425         .probe = spi_nor_probe,
5426         .remove = spi_nor_remove,
5427         .shutdown = spi_nor_shutdown,
5428 };
5429 module_spi_mem_driver(spi_nor_driver);
5430
5431 MODULE_LICENSE("GPL v2");
5432 MODULE_AUTHOR("Huang Shijie <shijie8@gmail.com>");
5433 MODULE_AUTHOR("Mike Lavender");
5434 MODULE_DESCRIPTION("framework for SPI NOR");