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