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