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