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