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