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