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