f8d566996900995f3f102c584a585a722c097810
[platform/kernel/u-boot.git] / drivers / mtd / spi / spi-nor-core.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  * Synced from Linux v4.19
10  */
11
12 #include <common.h>
13 #include <display_options.h>
14 #include <log.h>
15 #include <watchdog.h>
16 #include <dm.h>
17 #include <dm/device_compat.h>
18 #include <dm/devres.h>
19 #include <linux/bitops.h>
20 #include <linux/err.h>
21 #include <linux/errno.h>
22 #include <linux/log2.h>
23 #include <linux/math64.h>
24 #include <linux/sizes.h>
25 #include <linux/bitfield.h>
26 #include <linux/delay.h>
27
28 #include <linux/mtd/mtd.h>
29 #include <linux/mtd/spi-nor.h>
30 #include <mtd/cfi_flash.h>
31 #include <spi-mem.h>
32 #include <spi.h>
33
34 #include "sf_internal.h"
35
36 /* Define max times to check status register before we give up. */
37
38 /*
39  * For everything but full-chip erase; probably could be much smaller, but kept
40  * around for safety for now
41  */
42
43 #define HZ                                      CONFIG_SYS_HZ
44
45 #define DEFAULT_READY_WAIT_JIFFIES              (40UL * HZ)
46
47 #define ROUND_UP_TO(x, y)       (((x) + (y) - 1) / (y) * (y))
48
49 struct sfdp_parameter_header {
50         u8              id_lsb;
51         u8              minor;
52         u8              major;
53         u8              length; /* in double words */
54         u8              parameter_table_pointer[3]; /* byte address */
55         u8              id_msb;
56 };
57
58 #define SFDP_PARAM_HEADER_ID(p) (((p)->id_msb << 8) | (p)->id_lsb)
59 #define SFDP_PARAM_HEADER_PTP(p) \
60         (((p)->parameter_table_pointer[2] << 16) | \
61          ((p)->parameter_table_pointer[1] <<  8) | \
62          ((p)->parameter_table_pointer[0] <<  0))
63
64 #define SFDP_BFPT_ID            0xff00  /* Basic Flash Parameter Table */
65 #define SFDP_SECTOR_MAP_ID      0xff81  /* Sector Map Table */
66 #define SFDP_SST_ID             0x01bf  /* Manufacturer specific Table */
67 #define SFDP_PROFILE1_ID        0xff05  /* xSPI Profile 1.0 Table */
68 #define SFDP_SCCR_MAP_ID        0xff87  /*
69                                          * Status, Control and Configuration
70                                          * Register Map.
71                                          */
72
73 #define SFDP_SIGNATURE          0x50444653U
74 #define SFDP_JESD216_MAJOR      1
75 #define SFDP_JESD216_MINOR      0
76 #define SFDP_JESD216A_MINOR     5
77 #define SFDP_JESD216B_MINOR     6
78
79 struct sfdp_header {
80         u32             signature; /* Ox50444653U <=> "SFDP" */
81         u8              minor;
82         u8              major;
83         u8              nph; /* 0-base number of parameter headers */
84         u8              unused;
85
86         /* Basic Flash Parameter Table. */
87         struct sfdp_parameter_header    bfpt_header;
88 };
89
90 /* Basic Flash Parameter Table */
91
92 /*
93  * JESD216 rev D defines a Basic Flash Parameter Table of 20 DWORDs.
94  * They are indexed from 1 but C arrays are indexed from 0.
95  */
96 #define BFPT_DWORD(i)           ((i) - 1)
97 #define BFPT_DWORD_MAX          20
98
99 /* The first version of JESB216 defined only 9 DWORDs. */
100 #define BFPT_DWORD_MAX_JESD216                  9
101 #define BFPT_DWORD_MAX_JESD216B                 16
102
103 /* 1st DWORD. */
104 #define BFPT_DWORD1_FAST_READ_1_1_2             BIT(16)
105 #define BFPT_DWORD1_ADDRESS_BYTES_MASK          GENMASK(18, 17)
106 #define BFPT_DWORD1_ADDRESS_BYTES_3_ONLY        (0x0UL << 17)
107 #define BFPT_DWORD1_ADDRESS_BYTES_3_OR_4        (0x1UL << 17)
108 #define BFPT_DWORD1_ADDRESS_BYTES_4_ONLY        (0x2UL << 17)
109 #define BFPT_DWORD1_DTR                         BIT(19)
110 #define BFPT_DWORD1_FAST_READ_1_2_2             BIT(20)
111 #define BFPT_DWORD1_FAST_READ_1_4_4             BIT(21)
112 #define BFPT_DWORD1_FAST_READ_1_1_4             BIT(22)
113
114 /* 5th DWORD. */
115 #define BFPT_DWORD5_FAST_READ_2_2_2             BIT(0)
116 #define BFPT_DWORD5_FAST_READ_4_4_4             BIT(4)
117
118 /* 11th DWORD. */
119 #define BFPT_DWORD11_PAGE_SIZE_SHIFT            4
120 #define BFPT_DWORD11_PAGE_SIZE_MASK             GENMASK(7, 4)
121
122 /* 15th DWORD. */
123
124 /*
125  * (from JESD216 rev B)
126  * Quad Enable Requirements (QER):
127  * - 000b: Device does not have a QE bit. Device detects 1-1-4 and 1-4-4
128  *         reads based on instruction. DQ3/HOLD# functions are hold during
129  *         instruction phase.
130  * - 001b: QE is bit 1 of status register 2. It is set via Write Status with
131  *         two data bytes where bit 1 of the second byte is one.
132  *         [...]
133  *         Writing only one byte to the status register has the side-effect of
134  *         clearing status register 2, including the QE bit. The 100b code is
135  *         used if writing one byte to the status register does not modify
136  *         status register 2.
137  * - 010b: QE is bit 6 of status register 1. It is set via Write Status with
138  *         one data byte where bit 6 is one.
139  *         [...]
140  * - 011b: QE is bit 7 of status register 2. It is set via Write status
141  *         register 2 instruction 3Eh with one data byte where bit 7 is one.
142  *         [...]
143  *         The status register 2 is read using instruction 3Fh.
144  * - 100b: QE is bit 1 of status register 2. It is set via Write Status with
145  *         two data bytes where bit 1 of the second byte is one.
146  *         [...]
147  *         In contrast to the 001b code, writing one byte to the status
148  *         register does not modify status register 2.
149  * - 101b: QE is bit 1 of status register 2. Status register 1 is read using
150  *         Read Status instruction 05h. Status register2 is read using
151  *         instruction 35h. QE is set via Writ Status instruction 01h with
152  *         two data bytes where bit 1 of the second byte is one.
153  *         [...]
154  */
155 #define BFPT_DWORD15_QER_MASK                   GENMASK(22, 20)
156 #define BFPT_DWORD15_QER_NONE                   (0x0UL << 20) /* Micron */
157 #define BFPT_DWORD15_QER_SR2_BIT1_BUGGY         (0x1UL << 20)
158 #define BFPT_DWORD15_QER_SR1_BIT6               (0x2UL << 20) /* Macronix */
159 #define BFPT_DWORD15_QER_SR2_BIT7               (0x3UL << 20)
160 #define BFPT_DWORD15_QER_SR2_BIT1_NO_RD         (0x4UL << 20)
161 #define BFPT_DWORD15_QER_SR2_BIT1               (0x5UL << 20) /* Spansion */
162
163 #define BFPT_DWORD16_SOFT_RST                   BIT(12)
164
165 #define BFPT_DWORD18_CMD_EXT_MASK               GENMASK(30, 29)
166 #define BFPT_DWORD18_CMD_EXT_REP                (0x0UL << 29) /* Repeat */
167 #define BFPT_DWORD18_CMD_EXT_INV                (0x1UL << 29) /* Invert */
168 #define BFPT_DWORD18_CMD_EXT_RES                (0x2UL << 29) /* Reserved */
169 #define BFPT_DWORD18_CMD_EXT_16B                (0x3UL << 29) /* 16-bit opcode */
170
171 /* xSPI Profile 1.0 table (from JESD216D.01). */
172 #define PROFILE1_DWORD1_RD_FAST_CMD             GENMASK(15, 8)
173 #define PROFILE1_DWORD1_RDSR_DUMMY              BIT(28)
174 #define PROFILE1_DWORD1_RDSR_ADDR_BYTES         BIT(29)
175 #define PROFILE1_DWORD4_DUMMY_200MHZ            GENMASK(11, 7)
176 #define PROFILE1_DWORD5_DUMMY_166MHZ            GENMASK(31, 27)
177 #define PROFILE1_DWORD5_DUMMY_133MHZ            GENMASK(21, 17)
178 #define PROFILE1_DWORD5_DUMMY_100MHZ            GENMASK(11, 7)
179 #define PROFILE1_DUMMY_DEFAULT                  20
180
181 /* Status, Control and Configuration Register Map(SCCR) */
182 #define SCCR_DWORD22_OCTAL_DTR_EN_VOLATILE      BIT(31)
183
184 struct sfdp_bfpt {
185         u32     dwords[BFPT_DWORD_MAX];
186 };
187
188 /**
189  * struct spi_nor_fixups - SPI NOR fixup hooks
190  * @default_init: called after default flash parameters init. Used to tweak
191  *                flash parameters when information provided by the flash_info
192  *                table is incomplete or wrong.
193  * @post_bfpt: called after the BFPT table has been parsed
194  * @post_sfdp: called after SFDP has been parsed (is also called for SPI NORs
195  *             that do not support RDSFDP). Typically used to tweak various
196  *             parameters that could not be extracted by other means (i.e.
197  *             when information provided by the SFDP/flash_info tables are
198  *             incomplete or wrong).
199  *
200  * Those hooks can be used to tweak the SPI NOR configuration when the SFDP
201  * table is broken or not available.
202  */
203 struct spi_nor_fixups {
204         void (*default_init)(struct spi_nor *nor);
205         int (*post_bfpt)(struct spi_nor *nor,
206                          const struct sfdp_parameter_header *bfpt_header,
207                          const struct sfdp_bfpt *bfpt,
208                          struct spi_nor_flash_parameter *params);
209         void (*post_sfdp)(struct spi_nor *nor,
210                           struct spi_nor_flash_parameter *params);
211 };
212
213 #define SPI_NOR_SRST_SLEEP_LEN                  200
214
215 /**
216  * spi_nor_get_cmd_ext() - Get the command opcode extension based on the
217  *                         extension type.
218  * @nor:                pointer to a 'struct spi_nor'
219  * @op:                 pointer to the 'struct spi_mem_op' whose properties
220  *                      need to be initialized.
221  *
222  * Right now, only "repeat" and "invert" are supported.
223  *
224  * Return: The opcode extension.
225  */
226 static u8 spi_nor_get_cmd_ext(const struct spi_nor *nor,
227                               const struct spi_mem_op *op)
228 {
229         switch (nor->cmd_ext_type) {
230         case SPI_NOR_EXT_INVERT:
231                 return ~op->cmd.opcode;
232
233         case SPI_NOR_EXT_REPEAT:
234                 return op->cmd.opcode;
235
236         default:
237                 dev_dbg(nor->dev, "Unknown command extension type\n");
238                 return 0;
239         }
240 }
241
242 /**
243  * spi_nor_setup_op() - Set up common properties of a spi-mem op.
244  * @nor:                pointer to a 'struct spi_nor'
245  * @op:                 pointer to the 'struct spi_mem_op' whose properties
246  *                      need to be initialized.
247  * @proto:              the protocol from which the properties need to be set.
248  */
249 void spi_nor_setup_op(const struct spi_nor *nor,
250                       struct spi_mem_op *op,
251                       const enum spi_nor_protocol proto)
252 {
253         u8 ext;
254
255         op->cmd.buswidth = spi_nor_get_protocol_inst_nbits(proto);
256
257         if (op->addr.nbytes)
258                 op->addr.buswidth = spi_nor_get_protocol_addr_nbits(proto);
259
260         if (op->dummy.nbytes)
261                 op->dummy.buswidth = spi_nor_get_protocol_addr_nbits(proto);
262
263         if (op->data.nbytes)
264                 op->data.buswidth = spi_nor_get_protocol_data_nbits(proto);
265
266         if (spi_nor_protocol_is_dtr(proto)) {
267                 /*
268                  * spi-mem supports mixed DTR modes, but right now we can only
269                  * have all phases either DTR or STR. IOW, spi-mem can have
270                  * something like 4S-4D-4D, but spi-nor can't. So, set all 4
271                  * phases to either DTR or STR.
272                  */
273                 op->cmd.dtr = op->addr.dtr = op->dummy.dtr =
274                         op->data.dtr = true;
275
276                 /* 2 bytes per clock cycle in DTR mode. */
277                 op->dummy.nbytes *= 2;
278
279                 ext = spi_nor_get_cmd_ext(nor, op);
280                 op->cmd.opcode = (op->cmd.opcode << 8) | ext;
281                 op->cmd.nbytes = 2;
282         }
283 }
284
285 static int spi_nor_read_write_reg(struct spi_nor *nor, struct spi_mem_op
286                 *op, void *buf)
287 {
288         if (op->data.dir == SPI_MEM_DATA_IN)
289                 op->data.buf.in = buf;
290         else
291                 op->data.buf.out = buf;
292         return spi_mem_exec_op(nor->spi, op);
293 }
294
295 static int spi_nor_read_reg(struct spi_nor *nor, u8 code, u8 *val, int len)
296 {
297         struct spi_mem_op op = SPI_MEM_OP(SPI_MEM_OP_CMD(code, 0),
298                                           SPI_MEM_OP_NO_ADDR,
299                                           SPI_MEM_OP_NO_DUMMY,
300                                           SPI_MEM_OP_DATA_IN(len, NULL, 0));
301         int ret;
302
303         spi_nor_setup_op(nor, &op, nor->reg_proto);
304
305         ret = spi_nor_read_write_reg(nor, &op, val);
306         if (ret < 0)
307                 dev_dbg(nor->dev, "error %d reading %x\n", ret, code);
308
309         return ret;
310 }
311
312 static int spi_nor_write_reg(struct spi_nor *nor, u8 opcode, u8 *buf, int len)
313 {
314         struct spi_mem_op op = SPI_MEM_OP(SPI_MEM_OP_CMD(opcode, 0),
315                                           SPI_MEM_OP_NO_ADDR,
316                                           SPI_MEM_OP_NO_DUMMY,
317                                           SPI_MEM_OP_DATA_OUT(len, NULL, 0));
318
319         spi_nor_setup_op(nor, &op, nor->reg_proto);
320
321         if (len == 0)
322                 op.data.dir = SPI_MEM_NO_DATA;
323
324         return spi_nor_read_write_reg(nor, &op, buf);
325 }
326
327 #ifdef CONFIG_SPI_FLASH_SPANSION
328 static int spansion_read_any_reg(struct spi_nor *nor, u32 addr, u8 dummy,
329                                  u8 *val)
330 {
331         struct spi_mem_op op =
332                         SPI_MEM_OP(SPI_MEM_OP_CMD(SPINOR_OP_RDAR, 1),
333                                    SPI_MEM_OP_ADDR(nor->addr_width, addr, 1),
334                                    SPI_MEM_OP_DUMMY(dummy / 8, 1),
335                                    SPI_MEM_OP_DATA_IN(1, NULL, 1));
336
337         return spi_nor_read_write_reg(nor, &op, val);
338 }
339
340 static int spansion_write_any_reg(struct spi_nor *nor, u32 addr, u8 val)
341 {
342         struct spi_mem_op op =
343                         SPI_MEM_OP(SPI_MEM_OP_CMD(SPINOR_OP_WRAR, 1),
344                                    SPI_MEM_OP_ADDR(nor->addr_width, addr, 1),
345                                    SPI_MEM_OP_NO_DUMMY,
346                                    SPI_MEM_OP_DATA_OUT(1, NULL, 1));
347
348         return spi_nor_read_write_reg(nor, &op, &val);
349 }
350 #endif
351
352 static ssize_t spi_nor_read_data(struct spi_nor *nor, loff_t from, size_t len,
353                                  u_char *buf)
354 {
355         struct spi_mem_op op =
356                         SPI_MEM_OP(SPI_MEM_OP_CMD(nor->read_opcode, 0),
357                                    SPI_MEM_OP_ADDR(nor->addr_width, from, 0),
358                                    SPI_MEM_OP_DUMMY(nor->read_dummy, 0),
359                                    SPI_MEM_OP_DATA_IN(len, buf, 0));
360         size_t remaining = len;
361         int ret;
362
363         spi_nor_setup_op(nor, &op, nor->read_proto);
364
365         /* convert the dummy cycles to the number of bytes */
366         op.dummy.nbytes = (nor->read_dummy * op.dummy.buswidth) / 8;
367         if (spi_nor_protocol_is_dtr(nor->read_proto))
368                 op.dummy.nbytes *= 2;
369
370         while (remaining) {
371                 op.data.nbytes = remaining < UINT_MAX ? remaining : UINT_MAX;
372
373                 if (CONFIG_IS_ENABLED(SPI_DIRMAP) && nor->dirmap.rdesc) {
374                         /*
375                          * Record current operation information which may be used
376                          * when the address or data length exceeds address mapping.
377                          */
378                         memcpy(&nor->dirmap.rdesc->info.op_tmpl, &op,
379                                sizeof(struct spi_mem_op));
380                         ret = spi_mem_dirmap_read(nor->dirmap.rdesc,
381                                                   op.addr.val, op.data.nbytes,
382                                                   op.data.buf.in);
383                         if (ret < 0)
384                                 return ret;
385                         op.data.nbytes = ret;
386                 } else {
387                         ret = spi_mem_adjust_op_size(nor->spi, &op);
388                         if (ret)
389                                 return ret;
390
391                         ret = spi_mem_exec_op(nor->spi, &op);
392                         if (ret)
393                                 return ret;
394                 }
395
396                 op.addr.val += op.data.nbytes;
397                 remaining -= op.data.nbytes;
398                 op.data.buf.in += op.data.nbytes;
399         }
400
401         return len;
402 }
403
404 static ssize_t spi_nor_write_data(struct spi_nor *nor, loff_t to, size_t len,
405                                   const u_char *buf)
406 {
407         struct spi_mem_op op =
408                         SPI_MEM_OP(SPI_MEM_OP_CMD(nor->program_opcode, 0),
409                                    SPI_MEM_OP_ADDR(nor->addr_width, to, 0),
410                                    SPI_MEM_OP_NO_DUMMY,
411                                    SPI_MEM_OP_DATA_OUT(len, buf, 0));
412         int ret;
413
414         if (nor->program_opcode == SPINOR_OP_AAI_WP && nor->sst_write_second)
415                 op.addr.nbytes = 0;
416
417         spi_nor_setup_op(nor, &op, nor->write_proto);
418
419         if (CONFIG_IS_ENABLED(SPI_DIRMAP) && nor->dirmap.wdesc) {
420                 memcpy(&nor->dirmap.wdesc->info.op_tmpl, &op,
421                        sizeof(struct spi_mem_op));
422                 op.data.nbytes = spi_mem_dirmap_write(nor->dirmap.wdesc, op.addr.val,
423                                                       op.data.nbytes, op.data.buf.out);
424         } else {
425                 ret = spi_mem_adjust_op_size(nor->spi, &op);
426                 if (ret)
427                         return ret;
428                 op.data.nbytes = len < op.data.nbytes ? len : op.data.nbytes;
429
430                 ret = spi_mem_exec_op(nor->spi, &op);
431                 if (ret)
432                         return ret;
433         }
434
435         return op.data.nbytes;
436 }
437
438 /*
439  * Read the status register, returning its value in the location
440  * Return the status register value.
441  * Returns negative if error occurred.
442  */
443 static int read_sr(struct spi_nor *nor)
444 {
445         struct spi_mem_op op;
446         int ret;
447         u8 val[2];
448         u8 addr_nbytes, dummy;
449
450         if (nor->reg_proto == SNOR_PROTO_8_8_8_DTR) {
451                 addr_nbytes = nor->rdsr_addr_nbytes;
452                 dummy = nor->rdsr_dummy;
453         } else {
454                 addr_nbytes = 0;
455                 dummy = 0;
456         }
457
458         op = (struct spi_mem_op)SPI_MEM_OP(SPI_MEM_OP_CMD(SPINOR_OP_RDSR, 0),
459                                            SPI_MEM_OP_ADDR(addr_nbytes, 0, 0),
460                                            SPI_MEM_OP_DUMMY(dummy, 0),
461                                            SPI_MEM_OP_DATA_IN(1, NULL, 0));
462
463         spi_nor_setup_op(nor, &op, nor->reg_proto);
464
465         /*
466          * We don't want to read only one byte in DTR mode. So, read 2 and then
467          * discard the second byte.
468          */
469         if (spi_nor_protocol_is_dtr(nor->reg_proto))
470                 op.data.nbytes = 2;
471
472         ret = spi_nor_read_write_reg(nor, &op, val);
473         if (ret < 0) {
474                 pr_debug("error %d reading SR\n", (int)ret);
475                 return ret;
476         }
477
478         return *val;
479 }
480
481 /*
482  * Read the flag status register, returning its value in the location
483  * Return the status register value.
484  * Returns negative if error occurred.
485  */
486 static int read_fsr(struct spi_nor *nor)
487 {
488         struct spi_mem_op op;
489         int ret;
490         u8 val[2];
491         u8 addr_nbytes, dummy;
492
493         if (nor->reg_proto == SNOR_PROTO_8_8_8_DTR) {
494                 addr_nbytes = nor->rdsr_addr_nbytes;
495                 dummy = nor->rdsr_dummy;
496         } else {
497                 addr_nbytes = 0;
498                 dummy = 0;
499         }
500
501         op = (struct spi_mem_op)SPI_MEM_OP(SPI_MEM_OP_CMD(SPINOR_OP_RDFSR, 0),
502                                            SPI_MEM_OP_ADDR(addr_nbytes, 0, 0),
503                                            SPI_MEM_OP_DUMMY(dummy, 0),
504                                            SPI_MEM_OP_DATA_IN(1, NULL, 0));
505
506         spi_nor_setup_op(nor, &op, nor->reg_proto);
507
508         /*
509          * We don't want to read only one byte in DTR mode. So, read 2 and then
510          * discard the second byte.
511          */
512         if (spi_nor_protocol_is_dtr(nor->reg_proto))
513                 op.data.nbytes = 2;
514
515         ret = spi_nor_read_write_reg(nor, &op, val);
516         if (ret < 0) {
517                 pr_debug("error %d reading FSR\n", ret);
518                 return ret;
519         }
520
521         return *val;
522 }
523
524 /*
525  * Read configuration register, returning its value in the
526  * location. Return the configuration register value.
527  * Returns negative if error occurred.
528  */
529 #if defined(CONFIG_SPI_FLASH_SPANSION) || defined(CONFIG_SPI_FLASH_WINBOND)
530 static int read_cr(struct spi_nor *nor)
531 {
532         int ret;
533         u8 val;
534
535         ret = nor->read_reg(nor, SPINOR_OP_RDCR, &val, 1);
536         if (ret < 0) {
537                 dev_dbg(nor->dev, "error %d reading CR\n", ret);
538                 return ret;
539         }
540
541         return val;
542 }
543 #endif
544
545 /*
546  * Write status register 1 byte
547  * Returns negative if error occurred.
548  */
549 static int write_sr(struct spi_nor *nor, u8 val)
550 {
551         nor->cmd_buf[0] = val;
552         return nor->write_reg(nor, SPINOR_OP_WRSR, nor->cmd_buf, 1);
553 }
554
555 /*
556  * Set write enable latch with Write Enable command.
557  * Returns negative if error occurred.
558  */
559 static int write_enable(struct spi_nor *nor)
560 {
561         return nor->write_reg(nor, SPINOR_OP_WREN, NULL, 0);
562 }
563
564 /*
565  * Send write disable instruction to the chip.
566  */
567 static int write_disable(struct spi_nor *nor)
568 {
569         return nor->write_reg(nor, SPINOR_OP_WRDI, NULL, 0);
570 }
571
572 static struct spi_nor *mtd_to_spi_nor(struct mtd_info *mtd)
573 {
574         return mtd->priv;
575 }
576
577 #ifndef CONFIG_SPI_FLASH_BAR
578 static u8 spi_nor_convert_opcode(u8 opcode, const u8 table[][2], size_t size)
579 {
580         size_t i;
581
582         for (i = 0; i < size; i++)
583                 if (table[i][0] == opcode)
584                         return table[i][1];
585
586         /* No conversion found, keep input op code. */
587         return opcode;
588 }
589
590 static u8 spi_nor_convert_3to4_read(u8 opcode)
591 {
592         static const u8 spi_nor_3to4_read[][2] = {
593                 { SPINOR_OP_READ,       SPINOR_OP_READ_4B },
594                 { SPINOR_OP_READ_FAST,  SPINOR_OP_READ_FAST_4B },
595                 { SPINOR_OP_READ_1_1_2, SPINOR_OP_READ_1_1_2_4B },
596                 { SPINOR_OP_READ_1_2_2, SPINOR_OP_READ_1_2_2_4B },
597                 { SPINOR_OP_READ_1_1_4, SPINOR_OP_READ_1_1_4_4B },
598                 { SPINOR_OP_READ_1_4_4, SPINOR_OP_READ_1_4_4_4B },
599                 { SPINOR_OP_READ_1_1_8, SPINOR_OP_READ_1_1_8_4B },
600                 { SPINOR_OP_READ_1_8_8, SPINOR_OP_READ_1_8_8_4B },
601
602                 { SPINOR_OP_READ_1_1_1_DTR,     SPINOR_OP_READ_1_1_1_DTR_4B },
603                 { SPINOR_OP_READ_1_2_2_DTR,     SPINOR_OP_READ_1_2_2_DTR_4B },
604                 { SPINOR_OP_READ_1_4_4_DTR,     SPINOR_OP_READ_1_4_4_DTR_4B },
605         };
606
607         return spi_nor_convert_opcode(opcode, spi_nor_3to4_read,
608                                       ARRAY_SIZE(spi_nor_3to4_read));
609 }
610
611 static u8 spi_nor_convert_3to4_program(u8 opcode)
612 {
613         static const u8 spi_nor_3to4_program[][2] = {
614                 { SPINOR_OP_PP,         SPINOR_OP_PP_4B },
615                 { SPINOR_OP_PP_1_1_4,   SPINOR_OP_PP_1_1_4_4B },
616                 { SPINOR_OP_PP_1_4_4,   SPINOR_OP_PP_1_4_4_4B },
617                 { SPINOR_OP_PP_1_1_8,   SPINOR_OP_PP_1_1_8_4B },
618                 { SPINOR_OP_PP_1_8_8,   SPINOR_OP_PP_1_8_8_4B },
619         };
620
621         return spi_nor_convert_opcode(opcode, spi_nor_3to4_program,
622                                       ARRAY_SIZE(spi_nor_3to4_program));
623 }
624
625 static u8 spi_nor_convert_3to4_erase(u8 opcode)
626 {
627         static const u8 spi_nor_3to4_erase[][2] = {
628                 { SPINOR_OP_BE_4K,      SPINOR_OP_BE_4K_4B },
629                 { SPINOR_OP_BE_32K,     SPINOR_OP_BE_32K_4B },
630                 { SPINOR_OP_SE,         SPINOR_OP_SE_4B },
631         };
632
633         return spi_nor_convert_opcode(opcode, spi_nor_3to4_erase,
634                                       ARRAY_SIZE(spi_nor_3to4_erase));
635 }
636
637 static void spi_nor_set_4byte_opcodes(struct spi_nor *nor,
638                                       const struct flash_info *info)
639 {
640         /* Do some manufacturer fixups first */
641         switch (JEDEC_MFR(info)) {
642         case SNOR_MFR_SPANSION:
643                 /* No small sector erase for 4-byte command set */
644                 nor->erase_opcode = SPINOR_OP_SE;
645                 nor->mtd.erasesize = info->sector_size;
646                 break;
647
648         default:
649                 break;
650         }
651
652         nor->read_opcode = spi_nor_convert_3to4_read(nor->read_opcode);
653         nor->program_opcode = spi_nor_convert_3to4_program(nor->program_opcode);
654         nor->erase_opcode = spi_nor_convert_3to4_erase(nor->erase_opcode);
655 }
656 #endif /* !CONFIG_SPI_FLASH_BAR */
657
658 /* Enable/disable 4-byte addressing mode. */
659 static int set_4byte(struct spi_nor *nor, const struct flash_info *info,
660                      int enable)
661 {
662         int status;
663         bool need_wren = false;
664         u8 cmd;
665
666         switch (JEDEC_MFR(info)) {
667         case SNOR_MFR_ST:
668         case SNOR_MFR_MICRON:
669                 /* Some Micron need WREN command; all will accept it */
670                 need_wren = true;
671         case SNOR_MFR_ISSI:
672         case SNOR_MFR_MACRONIX:
673         case SNOR_MFR_WINBOND:
674                 if (need_wren)
675                         write_enable(nor);
676
677                 cmd = enable ? SPINOR_OP_EN4B : SPINOR_OP_EX4B;
678                 status = nor->write_reg(nor, cmd, NULL, 0);
679                 if (need_wren)
680                         write_disable(nor);
681
682                 if (!status && !enable &&
683                     JEDEC_MFR(info) == SNOR_MFR_WINBOND) {
684                         /*
685                          * On Winbond W25Q256FV, leaving 4byte mode causes
686                          * the Extended Address Register to be set to 1, so all
687                          * 3-byte-address reads come from the second 16M.
688                          * We must clear the register to enable normal behavior.
689                          */
690                         write_enable(nor);
691                         nor->cmd_buf[0] = 0;
692                         nor->write_reg(nor, SPINOR_OP_WREAR, nor->cmd_buf, 1);
693                         write_disable(nor);
694                 }
695
696                 return status;
697         case SNOR_MFR_CYPRESS:
698                 cmd = enable ? SPINOR_OP_EN4B : SPINOR_OP_EX4B_CYPRESS;
699                 return nor->write_reg(nor, cmd, NULL, 0);
700         default:
701                 /* Spansion style */
702                 nor->cmd_buf[0] = enable << 7;
703                 return nor->write_reg(nor, SPINOR_OP_BRWR, nor->cmd_buf, 1);
704         }
705 }
706
707 #ifdef CONFIG_SPI_FLASH_SPANSION
708 /*
709  * Read status register 1 by using Read Any Register command to support multi
710  * die package parts.
711  */
712 static int spansion_sr_ready(struct spi_nor *nor, u32 addr_base, u8 dummy)
713 {
714         u32 reg_addr = addr_base + SPINOR_REG_ADDR_STR1V;
715         u8 sr;
716         int ret;
717
718         ret = spansion_read_any_reg(nor, reg_addr, dummy, &sr);
719         if (ret < 0)
720                 return ret;
721
722         if (sr & (SR_E_ERR | SR_P_ERR)) {
723                 if (sr & SR_E_ERR)
724                         dev_dbg(nor->dev, "Erase Error occurred\n");
725                 else
726                         dev_dbg(nor->dev, "Programming Error occurred\n");
727
728                 nor->write_reg(nor, SPINOR_OP_CLSR, NULL, 0);
729                 return -EIO;
730         }
731
732         return !(sr & SR_WIP);
733 }
734 #endif
735
736 static int spi_nor_sr_ready(struct spi_nor *nor)
737 {
738         int sr = read_sr(nor);
739
740         if (sr < 0)
741                 return sr;
742
743         if (nor->flags & SNOR_F_USE_CLSR && sr & (SR_E_ERR | SR_P_ERR)) {
744                 if (sr & SR_E_ERR)
745                         dev_dbg(nor->dev, "Erase Error occurred\n");
746                 else
747                         dev_dbg(nor->dev, "Programming Error occurred\n");
748
749                 nor->write_reg(nor, SPINOR_OP_CLSR, NULL, 0);
750                 return -EIO;
751         }
752
753         return !(sr & SR_WIP);
754 }
755
756 static int spi_nor_fsr_ready(struct spi_nor *nor)
757 {
758         int fsr = read_fsr(nor);
759
760         if (fsr < 0)
761                 return fsr;
762
763         if (fsr & (FSR_E_ERR | FSR_P_ERR)) {
764                 if (fsr & FSR_E_ERR)
765                         dev_err(nor->dev, "Erase operation failed.\n");
766                 else
767                         dev_err(nor->dev, "Program operation failed.\n");
768
769                 if (fsr & FSR_PT_ERR)
770                         dev_err(nor->dev,
771                                 "Attempted to modify a protected sector.\n");
772
773                 nor->write_reg(nor, SPINOR_OP_CLFSR, NULL, 0);
774                 return -EIO;
775         }
776
777         return fsr & FSR_READY;
778 }
779
780 static int spi_nor_default_ready(struct spi_nor *nor)
781 {
782         int sr, fsr;
783
784         sr = spi_nor_sr_ready(nor);
785         if (sr < 0)
786                 return sr;
787         fsr = nor->flags & SNOR_F_USE_FSR ? spi_nor_fsr_ready(nor) : 1;
788         if (fsr < 0)
789                 return fsr;
790         return sr && fsr;
791 }
792
793 static int spi_nor_ready(struct spi_nor *nor)
794 {
795         if (nor->ready)
796                 return nor->ready(nor);
797
798         return spi_nor_default_ready(nor);
799 }
800
801 /*
802  * Service routine to read status register until ready, or timeout occurs.
803  * Returns non-zero if error.
804  */
805 static int spi_nor_wait_till_ready_with_timeout(struct spi_nor *nor,
806                                                 unsigned long timeout)
807 {
808         unsigned long timebase;
809         int ret;
810
811         timebase = get_timer(0);
812
813         while (get_timer(timebase) < timeout) {
814                 ret = spi_nor_ready(nor);
815                 if (ret < 0)
816                         return ret;
817                 if (ret)
818                         return 0;
819         }
820
821         dev_err(nor->dev, "flash operation timed out\n");
822
823         return -ETIMEDOUT;
824 }
825
826 static int spi_nor_wait_till_ready(struct spi_nor *nor)
827 {
828         return spi_nor_wait_till_ready_with_timeout(nor,
829                                                     DEFAULT_READY_WAIT_JIFFIES);
830 }
831
832 #ifdef CONFIG_SPI_FLASH_BAR
833 /*
834  * This "clean_bar" is necessary in a situation when one was accessing
835  * spi flash memory > 16 MiB by using Bank Address Register's BA24 bit.
836  *
837  * After it the BA24 bit shall be cleared to allow access to correct
838  * memory region after SW reset (by calling "reset" command).
839  *
840  * Otherwise, the BA24 bit may be left set and then after reset, the
841  * ROM would read/write/erase SPL from 16 MiB * bank_sel address.
842  */
843 static int clean_bar(struct spi_nor *nor)
844 {
845         u8 cmd, bank_sel = 0;
846
847         if (nor->bank_curr == 0)
848                 return 0;
849         cmd = nor->bank_write_cmd;
850         nor->bank_curr = 0;
851         write_enable(nor);
852
853         return nor->write_reg(nor, cmd, &bank_sel, 1);
854 }
855
856 static int write_bar(struct spi_nor *nor, u32 offset)
857 {
858         u8 cmd, bank_sel;
859         int ret;
860
861         bank_sel = offset / SZ_16M;
862         if (bank_sel == nor->bank_curr)
863                 goto bar_end;
864
865         cmd = nor->bank_write_cmd;
866         write_enable(nor);
867         ret = nor->write_reg(nor, cmd, &bank_sel, 1);
868         if (ret < 0) {
869                 debug("SF: fail to write bank register\n");
870                 return ret;
871         }
872
873 bar_end:
874         nor->bank_curr = bank_sel;
875         return nor->bank_curr;
876 }
877
878 static int read_bar(struct spi_nor *nor, const struct flash_info *info)
879 {
880         u8 curr_bank = 0;
881         int ret;
882
883         switch (JEDEC_MFR(info)) {
884         case SNOR_MFR_SPANSION:
885                 nor->bank_read_cmd = SPINOR_OP_BRRD;
886                 nor->bank_write_cmd = SPINOR_OP_BRWR;
887                 break;
888         default:
889                 nor->bank_read_cmd = SPINOR_OP_RDEAR;
890                 nor->bank_write_cmd = SPINOR_OP_WREAR;
891         }
892
893         ret = nor->read_reg(nor, nor->bank_read_cmd,
894                                     &curr_bank, 1);
895         if (ret) {
896                 debug("SF: fail to read bank addr register\n");
897                 return ret;
898         }
899         nor->bank_curr = curr_bank;
900
901         return 0;
902 }
903 #endif
904
905 /*
906  * Initiate the erasure of a single sector. Returns the number of bytes erased
907  * on success, a negative error code on error.
908  */
909 static int spi_nor_erase_sector(struct spi_nor *nor, u32 addr)
910 {
911         struct spi_mem_op op =
912                 SPI_MEM_OP(SPI_MEM_OP_CMD(nor->erase_opcode, 0),
913                            SPI_MEM_OP_ADDR(nor->addr_width, addr, 0),
914                            SPI_MEM_OP_NO_DUMMY,
915                            SPI_MEM_OP_NO_DATA);
916         int ret;
917
918         spi_nor_setup_op(nor, &op, nor->write_proto);
919
920         if (nor->erase)
921                 return nor->erase(nor, addr);
922
923         /*
924          * Default implementation, if driver doesn't have a specialized HW
925          * control
926          */
927         ret = spi_mem_exec_op(nor->spi, &op);
928         if (ret)
929                 return ret;
930
931         return nor->mtd.erasesize;
932 }
933
934 /*
935  * Erase an address range on the nor chip.  The address range may extend
936  * one or more erase sectors.  Return an error is there is a problem erasing.
937  */
938 static int spi_nor_erase(struct mtd_info *mtd, struct erase_info *instr)
939 {
940         struct spi_nor *nor = mtd_to_spi_nor(mtd);
941         bool addr_known = false;
942         u32 addr, len, rem;
943         int ret, err;
944
945         dev_dbg(nor->dev, "at 0x%llx, len %lld\n", (long long)instr->addr,
946                 (long long)instr->len);
947
948         div_u64_rem(instr->len, mtd->erasesize, &rem);
949         if (rem) {
950                 ret = -EINVAL;
951                 goto err;
952         }
953
954         addr = instr->addr;
955         len = instr->len;
956
957         instr->state = MTD_ERASING;
958         addr_known = true;
959
960         while (len) {
961                 schedule();
962                 if (!IS_ENABLED(CONFIG_SPL_BUILD) && ctrlc()) {
963                         addr_known = false;
964                         ret = -EINTR;
965                         goto erase_err;
966                 }
967 #ifdef CONFIG_SPI_FLASH_BAR
968                 ret = write_bar(nor, addr);
969                 if (ret < 0)
970                         goto erase_err;
971 #endif
972                 ret = write_enable(nor);
973                 if (ret < 0)
974                         goto erase_err;
975
976                 ret = spi_nor_erase_sector(nor, addr);
977                 if (ret < 0)
978                         goto erase_err;
979
980                 addr += ret;
981                 len -= ret;
982
983                 ret = spi_nor_wait_till_ready(nor);
984                 if (ret)
985                         goto erase_err;
986         }
987
988         addr_known = false;
989 erase_err:
990 #ifdef CONFIG_SPI_FLASH_BAR
991         err = clean_bar(nor);
992         if (!ret)
993                 ret = err;
994 #endif
995         err = write_disable(nor);
996         if (!ret)
997                 ret = err;
998
999 err:
1000         if (ret) {
1001                 instr->fail_addr = addr_known ? addr : MTD_FAIL_ADDR_UNKNOWN;
1002                 instr->state = MTD_ERASE_FAILED;
1003         } else {
1004                 instr->state = MTD_ERASE_DONE;
1005         }
1006
1007         return ret;
1008 }
1009
1010 #ifdef CONFIG_SPI_FLASH_SPANSION
1011 /**
1012  * spansion_erase_non_uniform() - erase non-uniform sectors for Spansion/Cypress
1013  *                                chips
1014  * @nor:        pointer to a 'struct spi_nor'
1015  * @addr:       address of the sector to erase
1016  * @opcode_4k:  opcode for 4K sector erase
1017  * @ovlsz_top:  size of overlaid portion at the top address
1018  * @ovlsz_btm:  size of overlaid portion at the bottom address
1019  *
1020  * Erase an address range on the nor chip that can contain 4KB sectors overlaid
1021  * on top and/or bottom. The appropriate erase opcode and size are chosen by
1022  * address to erase and size of overlaid portion.
1023  *
1024  * Return: number of bytes erased on success, -errno otherwise.
1025  */
1026 static int spansion_erase_non_uniform(struct spi_nor *nor, u32 addr,
1027                                       u8 opcode_4k, u32 ovlsz_top,
1028                                       u32 ovlsz_btm)
1029 {
1030         struct spi_mem_op op =
1031                 SPI_MEM_OP(SPI_MEM_OP_CMD(nor->erase_opcode, 0),
1032                            SPI_MEM_OP_ADDR(nor->addr_width, addr, 0),
1033                            SPI_MEM_OP_NO_DUMMY,
1034                            SPI_MEM_OP_NO_DATA);
1035         struct mtd_info *mtd = &nor->mtd;
1036         u32 erasesize;
1037         int ret;
1038
1039         /* 4KB sectors */
1040         if (op.addr.val < ovlsz_btm ||
1041             op.addr.val >= mtd->size - ovlsz_top) {
1042                 op.cmd.opcode = opcode_4k;
1043                 erasesize = SZ_4K;
1044
1045         /* Non-overlaid portion in the normal sector at the bottom */
1046         } else if (op.addr.val == ovlsz_btm) {
1047                 op.cmd.opcode = nor->erase_opcode;
1048                 erasesize = mtd->erasesize - ovlsz_btm;
1049
1050         /* Non-overlaid portion in the normal sector at the top */
1051         } else if (op.addr.val == mtd->size - mtd->erasesize) {
1052                 op.cmd.opcode = nor->erase_opcode;
1053                 erasesize = mtd->erasesize - ovlsz_top;
1054
1055         /* Normal sectors */
1056         } else {
1057                 op.cmd.opcode = nor->erase_opcode;
1058                 erasesize = mtd->erasesize;
1059         }
1060
1061         spi_nor_setup_op(nor, &op, nor->write_proto);
1062
1063         ret = spi_mem_exec_op(nor->spi, &op);
1064         if (ret)
1065                 return ret;
1066
1067         return erasesize;
1068 }
1069 #endif
1070
1071 #if defined(CONFIG_SPI_FLASH_STMICRO) || defined(CONFIG_SPI_FLASH_SST)
1072 /* Write status register and ensure bits in mask match written values */
1073 static int write_sr_and_check(struct spi_nor *nor, u8 status_new, u8 mask)
1074 {
1075         int ret;
1076
1077         write_enable(nor);
1078         ret = write_sr(nor, status_new);
1079         if (ret)
1080                 return ret;
1081
1082         ret = spi_nor_wait_till_ready(nor);
1083         if (ret)
1084                 return ret;
1085
1086         ret = read_sr(nor);
1087         if (ret < 0)
1088                 return ret;
1089
1090         return ((ret & mask) != (status_new & mask)) ? -EIO : 0;
1091 }
1092
1093 static void stm_get_locked_range(struct spi_nor *nor, u8 sr, loff_t *ofs,
1094                                  uint64_t *len)
1095 {
1096         struct mtd_info *mtd = &nor->mtd;
1097         u8 mask = SR_BP2 | SR_BP1 | SR_BP0;
1098         int shift = ffs(mask) - 1;
1099         int pow;
1100
1101         if (!(sr & mask)) {
1102                 /* No protection */
1103                 *ofs = 0;
1104                 *len = 0;
1105         } else {
1106                 pow = ((sr & mask) ^ mask) >> shift;
1107                 *len = mtd->size >> pow;
1108                 if (nor->flags & SNOR_F_HAS_SR_TB && sr & SR_TB)
1109                         *ofs = 0;
1110                 else
1111                         *ofs = mtd->size - *len;
1112         }
1113 }
1114
1115 /*
1116  * Return 1 if the entire region is locked (if @locked is true) or unlocked (if
1117  * @locked is false); 0 otherwise
1118  */
1119 static int stm_check_lock_status_sr(struct spi_nor *nor, loff_t ofs, u64 len,
1120                                     u8 sr, bool locked)
1121 {
1122         loff_t lock_offs;
1123         uint64_t lock_len;
1124
1125         if (!len)
1126                 return 1;
1127
1128         stm_get_locked_range(nor, sr, &lock_offs, &lock_len);
1129
1130         if (locked)
1131                 /* Requested range is a sub-range of locked range */
1132                 return (ofs + len <= lock_offs + lock_len) && (ofs >= lock_offs);
1133         else
1134                 /* Requested range does not overlap with locked range */
1135                 return (ofs >= lock_offs + lock_len) || (ofs + len <= lock_offs);
1136 }
1137
1138 static int stm_is_locked_sr(struct spi_nor *nor, loff_t ofs, uint64_t len,
1139                             u8 sr)
1140 {
1141         return stm_check_lock_status_sr(nor, ofs, len, sr, true);
1142 }
1143
1144 static int stm_is_unlocked_sr(struct spi_nor *nor, loff_t ofs, uint64_t len,
1145                               u8 sr)
1146 {
1147         return stm_check_lock_status_sr(nor, ofs, len, sr, false);
1148 }
1149
1150 /*
1151  * Lock a region of the flash. Compatible with ST Micro and similar flash.
1152  * Supports the block protection bits BP{0,1,2} in the status register
1153  * (SR). Does not support these features found in newer SR bitfields:
1154  *   - SEC: sector/block protect - only handle SEC=0 (block protect)
1155  *   - CMP: complement protect - only support CMP=0 (range is not complemented)
1156  *
1157  * Support for the following is provided conditionally for some flash:
1158  *   - TB: top/bottom protect
1159  *
1160  * Sample table portion for 8MB flash (Winbond w25q64fw):
1161  *
1162  *   SEC  |  TB   |  BP2  |  BP1  |  BP0  |  Prot Length  | Protected Portion
1163  *  --------------------------------------------------------------------------
1164  *    X   |   X   |   0   |   0   |   0   |  NONE         | NONE
1165  *    0   |   0   |   0   |   0   |   1   |  128 KB       | Upper 1/64
1166  *    0   |   0   |   0   |   1   |   0   |  256 KB       | Upper 1/32
1167  *    0   |   0   |   0   |   1   |   1   |  512 KB       | Upper 1/16
1168  *    0   |   0   |   1   |   0   |   0   |  1 MB         | Upper 1/8
1169  *    0   |   0   |   1   |   0   |   1   |  2 MB         | Upper 1/4
1170  *    0   |   0   |   1   |   1   |   0   |  4 MB         | Upper 1/2
1171  *    X   |   X   |   1   |   1   |   1   |  8 MB         | ALL
1172  *  ------|-------|-------|-------|-------|---------------|-------------------
1173  *    0   |   1   |   0   |   0   |   1   |  128 KB       | Lower 1/64
1174  *    0   |   1   |   0   |   1   |   0   |  256 KB       | Lower 1/32
1175  *    0   |   1   |   0   |   1   |   1   |  512 KB       | Lower 1/16
1176  *    0   |   1   |   1   |   0   |   0   |  1 MB         | Lower 1/8
1177  *    0   |   1   |   1   |   0   |   1   |  2 MB         | Lower 1/4
1178  *    0   |   1   |   1   |   1   |   0   |  4 MB         | Lower 1/2
1179  *
1180  * Returns negative on errors, 0 on success.
1181  */
1182 static int stm_lock(struct spi_nor *nor, loff_t ofs, uint64_t len)
1183 {
1184         struct mtd_info *mtd = &nor->mtd;
1185         int status_old, status_new;
1186         u8 mask = SR_BP2 | SR_BP1 | SR_BP0;
1187         u8 shift = ffs(mask) - 1, pow, val;
1188         loff_t lock_len;
1189         bool can_be_top = true, can_be_bottom = nor->flags & SNOR_F_HAS_SR_TB;
1190         bool use_top;
1191
1192         status_old = read_sr(nor);
1193         if (status_old < 0)
1194                 return status_old;
1195
1196         /* If nothing in our range is unlocked, we don't need to do anything */
1197         if (stm_is_locked_sr(nor, ofs, len, status_old))
1198                 return 0;
1199
1200         /* If anything below us is unlocked, we can't use 'bottom' protection */
1201         if (!stm_is_locked_sr(nor, 0, ofs, status_old))
1202                 can_be_bottom = false;
1203
1204         /* If anything above us is unlocked, we can't use 'top' protection */
1205         if (!stm_is_locked_sr(nor, ofs + len, mtd->size - (ofs + len),
1206                               status_old))
1207                 can_be_top = false;
1208
1209         if (!can_be_bottom && !can_be_top)
1210                 return -EINVAL;
1211
1212         /* Prefer top, if both are valid */
1213         use_top = can_be_top;
1214
1215         /* lock_len: length of region that should end up locked */
1216         if (use_top)
1217                 lock_len = mtd->size - ofs;
1218         else
1219                 lock_len = ofs + len;
1220
1221         /*
1222          * Need smallest pow such that:
1223          *
1224          *   1 / (2^pow) <= (len / size)
1225          *
1226          * so (assuming power-of-2 size) we do:
1227          *
1228          *   pow = ceil(log2(size / len)) = log2(size) - floor(log2(len))
1229          */
1230         pow = ilog2(mtd->size) - ilog2(lock_len);
1231         val = mask - (pow << shift);
1232         if (val & ~mask)
1233                 return -EINVAL;
1234         /* Don't "lock" with no region! */
1235         if (!(val & mask))
1236                 return -EINVAL;
1237
1238         status_new = (status_old & ~mask & ~SR_TB) | val;
1239
1240         /* Disallow further writes if WP pin is asserted */
1241         status_new |= SR_SRWD;
1242
1243         if (!use_top)
1244                 status_new |= SR_TB;
1245
1246         /* Don't bother if they're the same */
1247         if (status_new == status_old)
1248                 return 0;
1249
1250         /* Only modify protection if it will not unlock other areas */
1251         if ((status_new & mask) < (status_old & mask))
1252                 return -EINVAL;
1253
1254         return write_sr_and_check(nor, status_new, mask);
1255 }
1256
1257 /*
1258  * Unlock a region of the flash. See stm_lock() for more info
1259  *
1260  * Returns negative on errors, 0 on success.
1261  */
1262 static int stm_unlock(struct spi_nor *nor, loff_t ofs, uint64_t len)
1263 {
1264         struct mtd_info *mtd = &nor->mtd;
1265         int status_old, status_new;
1266         u8 mask = SR_BP2 | SR_BP1 | SR_BP0;
1267         u8 shift = ffs(mask) - 1, pow, val;
1268         loff_t lock_len;
1269         bool can_be_top = true, can_be_bottom = nor->flags & SNOR_F_HAS_SR_TB;
1270         bool use_top;
1271
1272         status_old = read_sr(nor);
1273         if (status_old < 0)
1274                 return status_old;
1275
1276         /* If nothing in our range is locked, we don't need to do anything */
1277         if (stm_is_unlocked_sr(nor, ofs, len, status_old))
1278                 return 0;
1279
1280         /* If anything below us is locked, we can't use 'top' protection */
1281         if (!stm_is_unlocked_sr(nor, 0, ofs, status_old))
1282                 can_be_top = false;
1283
1284         /* If anything above us is locked, we can't use 'bottom' protection */
1285         if (!stm_is_unlocked_sr(nor, ofs + len, mtd->size - (ofs + len),
1286                                 status_old))
1287                 can_be_bottom = false;
1288
1289         if (!can_be_bottom && !can_be_top)
1290                 return -EINVAL;
1291
1292         /* Prefer top, if both are valid */
1293         use_top = can_be_top;
1294
1295         /* lock_len: length of region that should remain locked */
1296         if (use_top)
1297                 lock_len = mtd->size - (ofs + len);
1298         else
1299                 lock_len = ofs;
1300
1301         /*
1302          * Need largest pow such that:
1303          *
1304          *   1 / (2^pow) >= (len / size)
1305          *
1306          * so (assuming power-of-2 size) we do:
1307          *
1308          *   pow = floor(log2(size / len)) = log2(size) - ceil(log2(len))
1309          */
1310         pow = ilog2(mtd->size) - order_base_2(lock_len);
1311         if (lock_len == 0) {
1312                 val = 0; /* fully unlocked */
1313         } else {
1314                 val = mask - (pow << shift);
1315                 /* Some power-of-two sizes are not supported */
1316                 if (val & ~mask)
1317                         return -EINVAL;
1318         }
1319
1320         status_new = (status_old & ~mask & ~SR_TB) | val;
1321
1322         /* Don't protect status register if we're fully unlocked */
1323         if (lock_len == 0)
1324                 status_new &= ~SR_SRWD;
1325
1326         if (!use_top)
1327                 status_new |= SR_TB;
1328
1329         /* Don't bother if they're the same */
1330         if (status_new == status_old)
1331                 return 0;
1332
1333         /* Only modify protection if it will not lock other areas */
1334         if ((status_new & mask) > (status_old & mask))
1335                 return -EINVAL;
1336
1337         return write_sr_and_check(nor, status_new, mask);
1338 }
1339
1340 /*
1341  * Check if a region of the flash is (completely) unlocked. See stm_lock() for
1342  * more info.
1343  *
1344  * Returns 1 if entire region is unlocked, 0 if any portion is locked, and
1345  * negative on errors.
1346  */
1347 static int stm_is_unlocked(struct spi_nor *nor, loff_t ofs, uint64_t len)
1348 {
1349         int status;
1350
1351         status = read_sr(nor);
1352         if (status < 0)
1353                 return status;
1354
1355         return stm_is_unlocked_sr(nor, ofs, len, status);
1356 }
1357 #endif /* CONFIG_SPI_FLASH_STMICRO */
1358
1359 static const struct flash_info *spi_nor_read_id(struct spi_nor *nor)
1360 {
1361         int                     tmp;
1362         u8                      id[SPI_NOR_MAX_ID_LEN];
1363         const struct flash_info *info;
1364
1365         tmp = nor->read_reg(nor, SPINOR_OP_RDID, id, SPI_NOR_MAX_ID_LEN);
1366         if (tmp < 0) {
1367                 dev_dbg(nor->dev, "error %d reading JEDEC ID\n", tmp);
1368                 return ERR_PTR(tmp);
1369         }
1370
1371         info = spi_nor_ids;
1372         for (; info->name; info++) {
1373                 if (info->id_len) {
1374                         if (!memcmp(info->id, id, info->id_len))
1375                                 return info;
1376                 }
1377         }
1378
1379         dev_err(nor->dev, "unrecognized JEDEC id bytes: %02x, %02x, %02x\n",
1380                 id[0], id[1], id[2]);
1381         return ERR_PTR(-ENODEV);
1382 }
1383
1384 static int spi_nor_read(struct mtd_info *mtd, loff_t from, size_t len,
1385                         size_t *retlen, u_char *buf)
1386 {
1387         struct spi_nor *nor = mtd_to_spi_nor(mtd);
1388         int ret;
1389
1390         dev_dbg(nor->dev, "from 0x%08x, len %zd\n", (u32)from, len);
1391
1392         while (len) {
1393                 loff_t addr = from;
1394                 size_t read_len = len;
1395
1396 #ifdef CONFIG_SPI_FLASH_BAR
1397                 u32 remain_len;
1398
1399                 ret = write_bar(nor, addr);
1400                 if (ret < 0)
1401                         return log_ret(ret);
1402                 remain_len = (SZ_16M * (nor->bank_curr + 1)) - addr;
1403
1404                 if (len < remain_len)
1405                         read_len = len;
1406                 else
1407                         read_len = remain_len;
1408 #endif
1409
1410                 ret = nor->read(nor, addr, read_len, buf);
1411                 if (ret == 0) {
1412                         /* We shouldn't see 0-length reads */
1413                         ret = -EIO;
1414                         goto read_err;
1415                 }
1416                 if (ret < 0)
1417                         goto read_err;
1418
1419                 *retlen += ret;
1420                 buf += ret;
1421                 from += ret;
1422                 len -= ret;
1423         }
1424         ret = 0;
1425
1426 read_err:
1427 #ifdef CONFIG_SPI_FLASH_BAR
1428         ret = clean_bar(nor);
1429 #endif
1430         return ret;
1431 }
1432
1433 #ifdef CONFIG_SPI_FLASH_SST
1434 /*
1435  * sst26 flash series has its own block protection implementation:
1436  * 4x   - 8  KByte blocks - read & write protection bits - upper addresses
1437  * 1x   - 32 KByte blocks - write protection bits
1438  * rest - 64 KByte blocks - write protection bits
1439  * 1x   - 32 KByte blocks - write protection bits
1440  * 4x   - 8  KByte blocks - read & write protection bits - lower addresses
1441  *
1442  * We'll support only per 64k lock/unlock so lower and upper 64 KByte region
1443  * will be treated as single block.
1444  */
1445 #define SST26_BPR_8K_NUM                4
1446 #define SST26_MAX_BPR_REG_LEN           (18 + 1)
1447 #define SST26_BOUND_REG_SIZE            ((32 + SST26_BPR_8K_NUM * 8) * SZ_1K)
1448
1449 enum lock_ctl {
1450         SST26_CTL_LOCK,
1451         SST26_CTL_UNLOCK,
1452         SST26_CTL_CHECK
1453 };
1454
1455 static bool sst26_process_bpr(u32 bpr_size, u8 *cmd, u32 bit, enum lock_ctl ctl)
1456 {
1457         switch (ctl) {
1458         case SST26_CTL_LOCK:
1459                 cmd[bpr_size - (bit / 8) - 1] |= BIT(bit % 8);
1460                 break;
1461         case SST26_CTL_UNLOCK:
1462                 cmd[bpr_size - (bit / 8) - 1] &= ~BIT(bit % 8);
1463                 break;
1464         case SST26_CTL_CHECK:
1465                 return !!(cmd[bpr_size - (bit / 8) - 1] & BIT(bit % 8));
1466         }
1467
1468         return false;
1469 }
1470
1471 /*
1472  * Lock, unlock or check lock status of the flash region of the flash (depending
1473  * on the lock_ctl value)
1474  */
1475 static int sst26_lock_ctl(struct spi_nor *nor, loff_t ofs, uint64_t len, enum lock_ctl ctl)
1476 {
1477         struct mtd_info *mtd = &nor->mtd;
1478         u32 i, bpr_ptr, rptr_64k, lptr_64k, bpr_size;
1479         bool lower_64k = false, upper_64k = false;
1480         u8 bpr_buff[SST26_MAX_BPR_REG_LEN] = {};
1481         int ret;
1482
1483         /* Check length and offset for 64k alignment */
1484         if ((ofs & (SZ_64K - 1)) || (len & (SZ_64K - 1))) {
1485                 dev_err(nor->dev, "length or offset is not 64KiB allighned\n");
1486                 return -EINVAL;
1487         }
1488
1489         if (ofs + len > mtd->size) {
1490                 dev_err(nor->dev, "range is more than device size: %#llx + %#llx > %#llx\n",
1491                         ofs, len, mtd->size);
1492                 return -EINVAL;
1493         }
1494
1495         /* SST26 family has only 16 Mbit, 32 Mbit and 64 Mbit IC */
1496         if (mtd->size != SZ_2M &&
1497             mtd->size != SZ_4M &&
1498             mtd->size != SZ_8M)
1499                 return -EINVAL;
1500
1501         bpr_size = 2 + (mtd->size / SZ_64K / 8);
1502
1503         ret = nor->read_reg(nor, SPINOR_OP_READ_BPR, bpr_buff, bpr_size);
1504         if (ret < 0) {
1505                 dev_err(nor->dev, "fail to read block-protection register\n");
1506                 return ret;
1507         }
1508
1509         rptr_64k = min_t(u32, ofs + len, mtd->size - SST26_BOUND_REG_SIZE);
1510         lptr_64k = max_t(u32, ofs, SST26_BOUND_REG_SIZE);
1511
1512         upper_64k = ((ofs + len) > (mtd->size - SST26_BOUND_REG_SIZE));
1513         lower_64k = (ofs < SST26_BOUND_REG_SIZE);
1514
1515         /* Lower bits in block-protection register are about 64k region */
1516         bpr_ptr = lptr_64k / SZ_64K - 1;
1517
1518         /* Process 64K blocks region */
1519         while (lptr_64k < rptr_64k) {
1520                 if (sst26_process_bpr(bpr_size, bpr_buff, bpr_ptr, ctl))
1521                         return EACCES;
1522
1523                 bpr_ptr++;
1524                 lptr_64k += SZ_64K;
1525         }
1526
1527         /* 32K and 8K region bits in BPR are after 64k region bits */
1528         bpr_ptr = (mtd->size - 2 * SST26_BOUND_REG_SIZE) / SZ_64K;
1529
1530         /* Process lower 32K block region */
1531         if (lower_64k)
1532                 if (sst26_process_bpr(bpr_size, bpr_buff, bpr_ptr, ctl))
1533                         return EACCES;
1534
1535         bpr_ptr++;
1536
1537         /* Process upper 32K block region */
1538         if (upper_64k)
1539                 if (sst26_process_bpr(bpr_size, bpr_buff, bpr_ptr, ctl))
1540                         return EACCES;
1541
1542         bpr_ptr++;
1543
1544         /* Process lower 8K block regions */
1545         for (i = 0; i < SST26_BPR_8K_NUM; i++) {
1546                 if (lower_64k)
1547                         if (sst26_process_bpr(bpr_size, bpr_buff, bpr_ptr, ctl))
1548                                 return EACCES;
1549
1550                 /* In 8K area BPR has both read and write protection bits */
1551                 bpr_ptr += 2;
1552         }
1553
1554         /* Process upper 8K block regions */
1555         for (i = 0; i < SST26_BPR_8K_NUM; i++) {
1556                 if (upper_64k)
1557                         if (sst26_process_bpr(bpr_size, bpr_buff, bpr_ptr, ctl))
1558                                 return EACCES;
1559
1560                 /* In 8K area BPR has both read and write protection bits */
1561                 bpr_ptr += 2;
1562         }
1563
1564         /* If we check region status we don't need to write BPR back */
1565         if (ctl == SST26_CTL_CHECK)
1566                 return 0;
1567
1568         ret = nor->write_reg(nor, SPINOR_OP_WRITE_BPR, bpr_buff, bpr_size);
1569         if (ret < 0) {
1570                 dev_err(nor->dev, "fail to write block-protection register\n");
1571                 return ret;
1572         }
1573
1574         return 0;
1575 }
1576
1577 static int sst26_unlock(struct spi_nor *nor, loff_t ofs, uint64_t len)
1578 {
1579         return sst26_lock_ctl(nor, ofs, len, SST26_CTL_UNLOCK);
1580 }
1581
1582 static int sst26_lock(struct spi_nor *nor, loff_t ofs, uint64_t len)
1583 {
1584         return sst26_lock_ctl(nor, ofs, len, SST26_CTL_LOCK);
1585 }
1586
1587 /*
1588  * Returns EACCES (positive value) if region is (partially) locked, 0 if region
1589  * is completely unlocked, and negative on errors.
1590  */
1591 static int sst26_is_unlocked(struct spi_nor *nor, loff_t ofs, uint64_t len)
1592 {
1593         /*
1594          * is_unlocked function is used for check before reading or erasing
1595          * flash region, so offset and length might be not 64k aligned, so
1596          * adjust them to be 64k aligned as sst26_lock_ctl works only with 64k
1597          * aligned regions.
1598          */
1599         ofs -= ofs & (SZ_64K - 1);
1600         len = len & (SZ_64K - 1) ? (len & ~(SZ_64K - 1)) + SZ_64K : len;
1601
1602         return sst26_lock_ctl(nor, ofs, len, SST26_CTL_CHECK);
1603 }
1604
1605 static int sst_write_byteprogram(struct spi_nor *nor, loff_t to, size_t len,
1606                                  size_t *retlen, const u_char *buf)
1607 {
1608         size_t actual;
1609         int ret = 0;
1610
1611         for (actual = 0; actual < len; actual++) {
1612                 nor->program_opcode = SPINOR_OP_BP;
1613
1614                 write_enable(nor);
1615                 /* write one byte. */
1616                 ret = nor->write(nor, to, 1, buf + actual);
1617                 if (ret < 0)
1618                         goto sst_write_err;
1619                 ret = spi_nor_wait_till_ready(nor);
1620                 if (ret)
1621                         goto sst_write_err;
1622                 to++;
1623         }
1624
1625 sst_write_err:
1626         write_disable(nor);
1627         return ret;
1628 }
1629
1630 static int sst_write(struct mtd_info *mtd, loff_t to, size_t len,
1631                      size_t *retlen, const u_char *buf)
1632 {
1633         struct spi_nor *nor = mtd_to_spi_nor(mtd);
1634         struct spi_slave *spi = nor->spi;
1635         size_t actual;
1636         int ret;
1637
1638         dev_dbg(nor->dev, "to 0x%08x, len %zd\n", (u32)to, len);
1639         if (spi->mode & SPI_TX_BYTE)
1640                 return sst_write_byteprogram(nor, to, len, retlen, buf);
1641
1642         write_enable(nor);
1643
1644         nor->sst_write_second = false;
1645
1646         actual = to % 2;
1647         /* Start write from odd address. */
1648         if (actual) {
1649                 nor->program_opcode = SPINOR_OP_BP;
1650
1651                 /* write one byte. */
1652                 ret = nor->write(nor, to, 1, buf);
1653                 if (ret < 0)
1654                         goto sst_write_err;
1655                 ret = spi_nor_wait_till_ready(nor);
1656                 if (ret)
1657                         goto sst_write_err;
1658         }
1659         to += actual;
1660
1661         /* Write out most of the data here. */
1662         for (; actual < len - 1; actual += 2) {
1663                 nor->program_opcode = SPINOR_OP_AAI_WP;
1664
1665                 /* write two bytes. */
1666                 ret = nor->write(nor, to, 2, buf + actual);
1667                 if (ret < 0)
1668                         goto sst_write_err;
1669                 ret = spi_nor_wait_till_ready(nor);
1670                 if (ret)
1671                         goto sst_write_err;
1672                 to += 2;
1673                 nor->sst_write_second = true;
1674         }
1675         nor->sst_write_second = false;
1676
1677         write_disable(nor);
1678         ret = spi_nor_wait_till_ready(nor);
1679         if (ret)
1680                 goto sst_write_err;
1681
1682         /* Write out trailing byte if it exists. */
1683         if (actual != len) {
1684                 write_enable(nor);
1685
1686                 nor->program_opcode = SPINOR_OP_BP;
1687                 ret = nor->write(nor, to, 1, buf + actual);
1688                 if (ret < 0)
1689                         goto sst_write_err;
1690                 ret = spi_nor_wait_till_ready(nor);
1691                 if (ret)
1692                         goto sst_write_err;
1693                 write_disable(nor);
1694                 actual += 1;
1695         }
1696 sst_write_err:
1697         *retlen += actual;
1698         return ret;
1699 }
1700 #endif
1701 /*
1702  * Write an address range to the nor chip.  Data must be written in
1703  * FLASH_PAGESIZE chunks.  The address range may be any size provided
1704  * it is within the physical boundaries.
1705  */
1706 static int spi_nor_write(struct mtd_info *mtd, loff_t to, size_t len,
1707         size_t *retlen, const u_char *buf)
1708 {
1709         struct spi_nor *nor = mtd_to_spi_nor(mtd);
1710         size_t page_offset, page_remain, i;
1711         ssize_t ret;
1712
1713 #ifdef CONFIG_SPI_FLASH_SST
1714         /* sst nor chips use AAI word program */
1715         if (nor->info->flags & SST_WRITE)
1716                 return sst_write(mtd, to, len, retlen, buf);
1717 #endif
1718
1719         dev_dbg(nor->dev, "to 0x%08x, len %zd\n", (u32)to, len);
1720
1721         for (i = 0; i < len; ) {
1722                 ssize_t written;
1723                 loff_t addr = to + i;
1724                 schedule();
1725
1726                 /*
1727                  * If page_size is a power of two, the offset can be quickly
1728                  * calculated with an AND operation. On the other cases we
1729                  * need to do a modulus operation (more expensive).
1730                  */
1731                 if (is_power_of_2(nor->page_size)) {
1732                         page_offset = addr & (nor->page_size - 1);
1733                 } else {
1734                         u64 aux = addr;
1735
1736                         page_offset = do_div(aux, nor->page_size);
1737                 }
1738                 /* the size of data remaining on the first page */
1739                 page_remain = min_t(size_t,
1740                                     nor->page_size - page_offset, len - i);
1741
1742 #ifdef CONFIG_SPI_FLASH_BAR
1743                 ret = write_bar(nor, addr);
1744                 if (ret < 0)
1745                         return ret;
1746 #endif
1747                 write_enable(nor);
1748                 ret = nor->write(nor, addr, page_remain, buf + i);
1749                 if (ret < 0)
1750                         goto write_err;
1751                 written = ret;
1752
1753                 ret = spi_nor_wait_till_ready(nor);
1754                 if (ret)
1755                         goto write_err;
1756                 *retlen += written;
1757                 i += written;
1758         }
1759
1760 write_err:
1761 #ifdef CONFIG_SPI_FLASH_BAR
1762         ret = clean_bar(nor);
1763 #endif
1764         return ret;
1765 }
1766
1767 #if defined(CONFIG_SPI_FLASH_MACRONIX) || defined(CONFIG_SPI_FLASH_ISSI)
1768 /**
1769  * macronix_quad_enable() - set QE bit in Status Register.
1770  * @nor:        pointer to a 'struct spi_nor'
1771  *
1772  * Set the Quad Enable (QE) bit in the Status Register.
1773  *
1774  * bit 6 of the Status Register is the QE bit for Macronix like QSPI memories.
1775  *
1776  * Return: 0 on success, -errno otherwise.
1777  */
1778 static int macronix_quad_enable(struct spi_nor *nor)
1779 {
1780         int ret, val;
1781
1782         val = read_sr(nor);
1783         if (val < 0)
1784                 return val;
1785         if (val & SR_QUAD_EN_MX)
1786                 return 0;
1787
1788         write_enable(nor);
1789
1790         write_sr(nor, val | SR_QUAD_EN_MX);
1791
1792         ret = spi_nor_wait_till_ready(nor);
1793         if (ret)
1794                 return ret;
1795
1796         ret = read_sr(nor);
1797         if (!(ret > 0 && (ret & SR_QUAD_EN_MX))) {
1798                 dev_err(nor->dev, "Macronix Quad bit not set\n");
1799                 return -EINVAL;
1800         }
1801
1802         return 0;
1803 }
1804 #endif
1805
1806 #ifdef CONFIG_SPI_FLASH_SPANSION
1807 /**
1808  * spansion_quad_enable_volatile() - enable Quad I/O mode in volatile register.
1809  * @nor:        pointer to a 'struct spi_nor'
1810  * @addr_base:  base address of register (can be >0 in multi-die parts)
1811  * @dummy:      number of dummy cycles for register read
1812  *
1813  * It is recommended to update volatile registers in the field application due
1814  * to a risk of the non-volatile registers corruption by power interrupt. This
1815  * function sets Quad Enable bit in CFR1 volatile.
1816  *
1817  * Return: 0 on success, -errno otherwise.
1818  */
1819 static int spansion_quad_enable_volatile(struct spi_nor *nor, u32 addr_base,
1820                                          u8 dummy)
1821 {
1822         u32 addr = addr_base + SPINOR_REG_ADDR_CFR1V;
1823
1824         u8 cr;
1825         int ret;
1826
1827         /* Check current Quad Enable bit value. */
1828         ret = spansion_read_any_reg(nor, addr, dummy, &cr);
1829         if (ret < 0) {
1830                 dev_dbg(nor->dev,
1831                         "error while reading configuration register\n");
1832                 return -EINVAL;
1833         }
1834
1835         if (cr & CR_QUAD_EN_SPAN)
1836                 return 0;
1837
1838         cr |= CR_QUAD_EN_SPAN;
1839
1840         write_enable(nor);
1841
1842         ret = spansion_write_any_reg(nor, addr, cr);
1843
1844         if (ret < 0) {
1845                 dev_dbg(nor->dev,
1846                         "error while writing configuration register\n");
1847                 return -EINVAL;
1848         }
1849
1850         /* Read back and check it. */
1851         ret = spansion_read_any_reg(nor, addr, dummy, &cr);
1852         if (ret || !(cr & CR_QUAD_EN_SPAN)) {
1853                 dev_dbg(nor->dev, "Spansion Quad bit not set\n");
1854                 return -EINVAL;
1855         }
1856
1857         return 0;
1858 }
1859 #endif
1860
1861 #if defined(CONFIG_SPI_FLASH_SPANSION) || defined(CONFIG_SPI_FLASH_WINBOND)
1862 /*
1863  * Write status Register and configuration register with 2 bytes
1864  * The first byte will be written to the status register, while the
1865  * second byte will be written to the configuration register.
1866  * Return negative if error occurred.
1867  */
1868 static int write_sr_cr(struct spi_nor *nor, u8 *sr_cr)
1869 {
1870         int ret;
1871
1872         write_enable(nor);
1873
1874         ret = nor->write_reg(nor, SPINOR_OP_WRSR, sr_cr, 2);
1875         if (ret < 0) {
1876                 dev_dbg(nor->dev,
1877                         "error while writing configuration register\n");
1878                 return -EINVAL;
1879         }
1880
1881         ret = spi_nor_wait_till_ready(nor);
1882         if (ret) {
1883                 dev_dbg(nor->dev,
1884                         "timeout while writing configuration register\n");
1885                 return ret;
1886         }
1887
1888         return 0;
1889 }
1890
1891 /**
1892  * spansion_read_cr_quad_enable() - set QE bit in Configuration Register.
1893  * @nor:        pointer to a 'struct spi_nor'
1894  *
1895  * Set the Quad Enable (QE) bit in the Configuration Register.
1896  * This function should be used with QSPI memories supporting the Read
1897  * Configuration Register (35h) instruction.
1898  *
1899  * bit 1 of the Configuration Register is the QE bit for Spansion like QSPI
1900  * memories.
1901  *
1902  * Return: 0 on success, -errno otherwise.
1903  */
1904 static int spansion_read_cr_quad_enable(struct spi_nor *nor)
1905 {
1906         u8 sr_cr[2];
1907         int ret;
1908
1909         /* Check current Quad Enable bit value. */
1910         ret = read_cr(nor);
1911         if (ret < 0) {
1912                 dev_dbg(nor->dev,
1913                         "error while reading configuration register\n");
1914                 return -EINVAL;
1915         }
1916
1917         if (ret & CR_QUAD_EN_SPAN)
1918                 return 0;
1919
1920         sr_cr[1] = ret | CR_QUAD_EN_SPAN;
1921
1922         /* Keep the current value of the Status Register. */
1923         ret = read_sr(nor);
1924         if (ret < 0) {
1925                 dev_dbg(nor->dev, "error while reading status register\n");
1926                 return -EINVAL;
1927         }
1928         sr_cr[0] = ret;
1929
1930         ret = write_sr_cr(nor, sr_cr);
1931         if (ret)
1932                 return ret;
1933
1934         /* Read back and check it. */
1935         ret = read_cr(nor);
1936         if (!(ret > 0 && (ret & CR_QUAD_EN_SPAN))) {
1937                 dev_dbg(nor->dev, "Spansion Quad bit not set\n");
1938                 return -EINVAL;
1939         }
1940
1941         return 0;
1942 }
1943
1944 #if CONFIG_IS_ENABLED(SPI_FLASH_SFDP_SUPPORT)
1945 /**
1946  * spansion_no_read_cr_quad_enable() - set QE bit in Configuration Register.
1947  * @nor:        pointer to a 'struct spi_nor'
1948  *
1949  * Set the Quad Enable (QE) bit in the Configuration Register.
1950  * This function should be used with QSPI memories not supporting the Read
1951  * Configuration Register (35h) instruction.
1952  *
1953  * bit 1 of the Configuration Register is the QE bit for Spansion like QSPI
1954  * memories.
1955  *
1956  * Return: 0 on success, -errno otherwise.
1957  */
1958 static int spansion_no_read_cr_quad_enable(struct spi_nor *nor)
1959 {
1960         u8 sr_cr[2];
1961         int ret;
1962
1963         /* Keep the current value of the Status Register. */
1964         ret = read_sr(nor);
1965         if (ret < 0) {
1966                 dev_dbg(nor->dev, "error while reading status register\n");
1967                 return -EINVAL;
1968         }
1969         sr_cr[0] = ret;
1970         sr_cr[1] = CR_QUAD_EN_SPAN;
1971
1972         return write_sr_cr(nor, sr_cr);
1973 }
1974
1975 #endif /* CONFIG_SPI_FLASH_SFDP_SUPPORT */
1976 #endif /* CONFIG_SPI_FLASH_SPANSION */
1977
1978 static void
1979 spi_nor_set_read_settings(struct spi_nor_read_command *read,
1980                           u8 num_mode_clocks,
1981                           u8 num_wait_states,
1982                           u8 opcode,
1983                           enum spi_nor_protocol proto)
1984 {
1985         read->num_mode_clocks = num_mode_clocks;
1986         read->num_wait_states = num_wait_states;
1987         read->opcode = opcode;
1988         read->proto = proto;
1989 }
1990
1991 static void
1992 spi_nor_set_pp_settings(struct spi_nor_pp_command *pp,
1993                         u8 opcode,
1994                         enum spi_nor_protocol proto)
1995 {
1996         pp->opcode = opcode;
1997         pp->proto = proto;
1998 }
1999
2000 #if CONFIG_IS_ENABLED(SPI_FLASH_SFDP_SUPPORT)
2001 /*
2002  * Serial Flash Discoverable Parameters (SFDP) parsing.
2003  */
2004
2005 /**
2006  * spi_nor_read_sfdp() - read Serial Flash Discoverable Parameters.
2007  * @nor:        pointer to a 'struct spi_nor'
2008  * @addr:       offset in the SFDP area to start reading data from
2009  * @len:        number of bytes to read
2010  * @buf:        buffer where the SFDP data are copied into (dma-safe memory)
2011  *
2012  * Whatever the actual numbers of bytes for address and dummy cycles are
2013  * for (Fast) Read commands, the Read SFDP (5Ah) instruction is always
2014  * followed by a 3-byte address and 8 dummy clock cycles.
2015  *
2016  * Return: 0 on success, -errno otherwise.
2017  */
2018 static int spi_nor_read_sfdp(struct spi_nor *nor, u32 addr,
2019                              size_t len, void *buf)
2020 {
2021         u8 addr_width, read_opcode, read_dummy;
2022         int ret;
2023
2024         read_opcode = nor->read_opcode;
2025         addr_width = nor->addr_width;
2026         read_dummy = nor->read_dummy;
2027
2028         nor->read_opcode = SPINOR_OP_RDSFDP;
2029         nor->addr_width = 3;
2030         nor->read_dummy = 8;
2031
2032         while (len) {
2033                 ret = nor->read(nor, addr, len, (u8 *)buf);
2034                 if (!ret || ret > len) {
2035                         ret = -EIO;
2036                         goto read_err;
2037                 }
2038                 if (ret < 0)
2039                         goto read_err;
2040
2041                 buf += ret;
2042                 addr += ret;
2043                 len -= ret;
2044         }
2045         ret = 0;
2046
2047 read_err:
2048         nor->read_opcode = read_opcode;
2049         nor->addr_width = addr_width;
2050         nor->read_dummy = read_dummy;
2051
2052         return ret;
2053 }
2054
2055 /* Fast Read settings. */
2056
2057 static void
2058 spi_nor_set_read_settings_from_bfpt(struct spi_nor_read_command *read,
2059                                     u16 half,
2060                                     enum spi_nor_protocol proto)
2061 {
2062         read->num_mode_clocks = (half >> 5) & 0x07;
2063         read->num_wait_states = (half >> 0) & 0x1f;
2064         read->opcode = (half >> 8) & 0xff;
2065         read->proto = proto;
2066 }
2067
2068 struct sfdp_bfpt_read {
2069         /* The Fast Read x-y-z hardware capability in params->hwcaps.mask. */
2070         u32                     hwcaps;
2071
2072         /*
2073          * The <supported_bit> bit in <supported_dword> BFPT DWORD tells us
2074          * whether the Fast Read x-y-z command is supported.
2075          */
2076         u32                     supported_dword;
2077         u32                     supported_bit;
2078
2079         /*
2080          * The half-word at offset <setting_shift> in <setting_dword> BFPT DWORD
2081          * encodes the op code, the number of mode clocks and the number of wait
2082          * states to be used by Fast Read x-y-z command.
2083          */
2084         u32                     settings_dword;
2085         u32                     settings_shift;
2086
2087         /* The SPI protocol for this Fast Read x-y-z command. */
2088         enum spi_nor_protocol   proto;
2089 };
2090
2091 static const struct sfdp_bfpt_read sfdp_bfpt_reads[] = {
2092         /* Fast Read 1-1-2 */
2093         {
2094                 SNOR_HWCAPS_READ_1_1_2,
2095                 BFPT_DWORD(1), BIT(16), /* Supported bit */
2096                 BFPT_DWORD(4), 0,       /* Settings */
2097                 SNOR_PROTO_1_1_2,
2098         },
2099
2100         /* Fast Read 1-2-2 */
2101         {
2102                 SNOR_HWCAPS_READ_1_2_2,
2103                 BFPT_DWORD(1), BIT(20), /* Supported bit */
2104                 BFPT_DWORD(4), 16,      /* Settings */
2105                 SNOR_PROTO_1_2_2,
2106         },
2107
2108         /* Fast Read 2-2-2 */
2109         {
2110                 SNOR_HWCAPS_READ_2_2_2,
2111                 BFPT_DWORD(5),  BIT(0), /* Supported bit */
2112                 BFPT_DWORD(6), 16,      /* Settings */
2113                 SNOR_PROTO_2_2_2,
2114         },
2115
2116         /* Fast Read 1-1-4 */
2117         {
2118                 SNOR_HWCAPS_READ_1_1_4,
2119                 BFPT_DWORD(1), BIT(22), /* Supported bit */
2120                 BFPT_DWORD(3), 16,      /* Settings */
2121                 SNOR_PROTO_1_1_4,
2122         },
2123
2124         /* Fast Read 1-4-4 */
2125         {
2126                 SNOR_HWCAPS_READ_1_4_4,
2127                 BFPT_DWORD(1), BIT(21), /* Supported bit */
2128                 BFPT_DWORD(3), 0,       /* Settings */
2129                 SNOR_PROTO_1_4_4,
2130         },
2131
2132         /* Fast Read 4-4-4 */
2133         {
2134                 SNOR_HWCAPS_READ_4_4_4,
2135                 BFPT_DWORD(5), BIT(4),  /* Supported bit */
2136                 BFPT_DWORD(7), 16,      /* Settings */
2137                 SNOR_PROTO_4_4_4,
2138         },
2139 };
2140
2141 struct sfdp_bfpt_erase {
2142         /*
2143          * The half-word at offset <shift> in DWORD <dwoard> encodes the
2144          * op code and erase sector size to be used by Sector Erase commands.
2145          */
2146         u32                     dword;
2147         u32                     shift;
2148 };
2149
2150 static const struct sfdp_bfpt_erase sfdp_bfpt_erases[] = {
2151         /* Erase Type 1 in DWORD8 bits[15:0] */
2152         {BFPT_DWORD(8), 0},
2153
2154         /* Erase Type 2 in DWORD8 bits[31:16] */
2155         {BFPT_DWORD(8), 16},
2156
2157         /* Erase Type 3 in DWORD9 bits[15:0] */
2158         {BFPT_DWORD(9), 0},
2159
2160         /* Erase Type 4 in DWORD9 bits[31:16] */
2161         {BFPT_DWORD(9), 16},
2162 };
2163
2164 static int spi_nor_hwcaps_read2cmd(u32 hwcaps);
2165
2166 static int
2167 spi_nor_post_bfpt_fixups(struct spi_nor *nor,
2168                          const struct sfdp_parameter_header *bfpt_header,
2169                          const struct sfdp_bfpt *bfpt,
2170                          struct spi_nor_flash_parameter *params)
2171 {
2172         if (nor->fixups && nor->fixups->post_bfpt)
2173                 return nor->fixups->post_bfpt(nor, bfpt_header, bfpt, params);
2174
2175         return 0;
2176 }
2177
2178 /**
2179  * spi_nor_parse_bfpt() - read and parse the Basic Flash Parameter Table.
2180  * @nor:                pointer to a 'struct spi_nor'
2181  * @bfpt_header:        pointer to the 'struct sfdp_parameter_header' describing
2182  *                      the Basic Flash Parameter Table length and version
2183  * @params:             pointer to the 'struct spi_nor_flash_parameter' to be
2184  *                      filled
2185  *
2186  * The Basic Flash Parameter Table is the main and only mandatory table as
2187  * defined by the SFDP (JESD216) specification.
2188  * It provides us with the total size (memory density) of the data array and
2189  * the number of address bytes for Fast Read, Page Program and Sector Erase
2190  * commands.
2191  * For Fast READ commands, it also gives the number of mode clock cycles and
2192  * wait states (regrouped in the number of dummy clock cycles) for each
2193  * supported instruction op code.
2194  * For Page Program, the page size is now available since JESD216 rev A, however
2195  * the supported instruction op codes are still not provided.
2196  * For Sector Erase commands, this table stores the supported instruction op
2197  * codes and the associated sector sizes.
2198  * Finally, the Quad Enable Requirements (QER) are also available since JESD216
2199  * rev A. The QER bits encode the manufacturer dependent procedure to be
2200  * executed to set the Quad Enable (QE) bit in some internal register of the
2201  * Quad SPI memory. Indeed the QE bit, when it exists, must be set before
2202  * sending any Quad SPI command to the memory. Actually, setting the QE bit
2203  * tells the memory to reassign its WP# and HOLD#/RESET# pins to functions IO2
2204  * and IO3 hence enabling 4 (Quad) I/O lines.
2205  *
2206  * Return: 0 on success, -errno otherwise.
2207  */
2208 static int spi_nor_parse_bfpt(struct spi_nor *nor,
2209                               const struct sfdp_parameter_header *bfpt_header,
2210                               struct spi_nor_flash_parameter *params)
2211 {
2212         struct mtd_info *mtd = &nor->mtd;
2213         struct sfdp_bfpt bfpt;
2214         size_t len;
2215         int i, cmd, err;
2216         u32 addr;
2217         u16 half;
2218
2219         /* JESD216 Basic Flash Parameter Table length is at least 9 DWORDs. */
2220         if (bfpt_header->length < BFPT_DWORD_MAX_JESD216)
2221                 return -EINVAL;
2222
2223         /* Read the Basic Flash Parameter Table. */
2224         len = min_t(size_t, sizeof(bfpt),
2225                     bfpt_header->length * sizeof(u32));
2226         addr = SFDP_PARAM_HEADER_PTP(bfpt_header);
2227         memset(&bfpt, 0, sizeof(bfpt));
2228         err = spi_nor_read_sfdp(nor,  addr, len, &bfpt);
2229         if (err < 0)
2230                 return err;
2231
2232         /* Fix endianness of the BFPT DWORDs. */
2233         for (i = 0; i < BFPT_DWORD_MAX; i++)
2234                 bfpt.dwords[i] = le32_to_cpu(bfpt.dwords[i]);
2235
2236         /* Number of address bytes. */
2237         switch (bfpt.dwords[BFPT_DWORD(1)] & BFPT_DWORD1_ADDRESS_BYTES_MASK) {
2238         case BFPT_DWORD1_ADDRESS_BYTES_3_ONLY:
2239         case BFPT_DWORD1_ADDRESS_BYTES_3_OR_4:
2240                 nor->addr_width = 3;
2241                 break;
2242
2243         case BFPT_DWORD1_ADDRESS_BYTES_4_ONLY:
2244                 nor->addr_width = 4;
2245                 break;
2246
2247         default:
2248                 break;
2249         }
2250
2251         /* Flash Memory Density (in bits). */
2252         params->size = bfpt.dwords[BFPT_DWORD(2)];
2253         if (params->size & BIT(31)) {
2254                 params->size &= ~BIT(31);
2255
2256                 /*
2257                  * Prevent overflows on params->size. Anyway, a NOR of 2^64
2258                  * bits is unlikely to exist so this error probably means
2259                  * the BFPT we are reading is corrupted/wrong.
2260                  */
2261                 if (params->size > 63)
2262                         return -EINVAL;
2263
2264                 params->size = 1ULL << params->size;
2265         } else {
2266                 params->size++;
2267         }
2268         params->size >>= 3; /* Convert to bytes. */
2269
2270         /* Fast Read settings. */
2271         for (i = 0; i < ARRAY_SIZE(sfdp_bfpt_reads); i++) {
2272                 const struct sfdp_bfpt_read *rd = &sfdp_bfpt_reads[i];
2273                 struct spi_nor_read_command *read;
2274
2275                 if (!(bfpt.dwords[rd->supported_dword] & rd->supported_bit)) {
2276                         params->hwcaps.mask &= ~rd->hwcaps;
2277                         continue;
2278                 }
2279
2280                 params->hwcaps.mask |= rd->hwcaps;
2281                 cmd = spi_nor_hwcaps_read2cmd(rd->hwcaps);
2282                 read = &params->reads[cmd];
2283                 half = bfpt.dwords[rd->settings_dword] >> rd->settings_shift;
2284                 spi_nor_set_read_settings_from_bfpt(read, half, rd->proto);
2285         }
2286
2287         /* Sector Erase settings. */
2288         for (i = 0; i < ARRAY_SIZE(sfdp_bfpt_erases); i++) {
2289                 const struct sfdp_bfpt_erase *er = &sfdp_bfpt_erases[i];
2290                 u32 erasesize;
2291                 u8 opcode;
2292
2293                 half = bfpt.dwords[er->dword] >> er->shift;
2294                 erasesize = half & 0xff;
2295
2296                 /* erasesize == 0 means this Erase Type is not supported. */
2297                 if (!erasesize)
2298                         continue;
2299
2300                 erasesize = 1U << erasesize;
2301                 opcode = (half >> 8) & 0xff;
2302 #ifdef CONFIG_SPI_FLASH_USE_4K_SECTORS
2303                 if (erasesize == SZ_4K) {
2304                         nor->erase_opcode = opcode;
2305                         mtd->erasesize = erasesize;
2306                         break;
2307                 }
2308 #endif
2309                 if (!mtd->erasesize || mtd->erasesize < erasesize) {
2310                         nor->erase_opcode = opcode;
2311                         mtd->erasesize = erasesize;
2312                 }
2313         }
2314
2315         /* Stop here if not JESD216 rev A or later. */
2316         if (bfpt_header->length == BFPT_DWORD_MAX_JESD216)
2317                 return spi_nor_post_bfpt_fixups(nor, bfpt_header, &bfpt,
2318                                                 params);
2319
2320         /* Page size: this field specifies 'N' so the page size = 2^N bytes. */
2321         params->page_size = bfpt.dwords[BFPT_DWORD(11)];
2322         params->page_size &= BFPT_DWORD11_PAGE_SIZE_MASK;
2323         params->page_size >>= BFPT_DWORD11_PAGE_SIZE_SHIFT;
2324         params->page_size = 1U << params->page_size;
2325
2326         /* Quad Enable Requirements. */
2327         switch (bfpt.dwords[BFPT_DWORD(15)] & BFPT_DWORD15_QER_MASK) {
2328         case BFPT_DWORD15_QER_NONE:
2329                 params->quad_enable = NULL;
2330                 break;
2331 #if defined(CONFIG_SPI_FLASH_SPANSION) || defined(CONFIG_SPI_FLASH_WINBOND)
2332         case BFPT_DWORD15_QER_SR2_BIT1_BUGGY:
2333         case BFPT_DWORD15_QER_SR2_BIT1_NO_RD:
2334                 params->quad_enable = spansion_no_read_cr_quad_enable;
2335                 break;
2336 #endif
2337 #if defined(CONFIG_SPI_FLASH_MACRONIX) || defined(CONFIG_SPI_FLASH_ISSI)
2338         case BFPT_DWORD15_QER_SR1_BIT6:
2339                 params->quad_enable = macronix_quad_enable;
2340                 break;
2341 #endif
2342 #if defined(CONFIG_SPI_FLASH_SPANSION) || defined(CONFIG_SPI_FLASH_WINBOND)
2343         case BFPT_DWORD15_QER_SR2_BIT1:
2344                 params->quad_enable = spansion_read_cr_quad_enable;
2345                 break;
2346 #endif
2347         default:
2348                 dev_dbg(nor->dev, "BFPT QER reserved value used\n");
2349                 break;
2350         }
2351
2352         /* Soft Reset support. */
2353         if (bfpt.dwords[BFPT_DWORD(16)] & BFPT_DWORD16_SOFT_RST)
2354                 nor->flags |= SNOR_F_SOFT_RESET;
2355
2356         /* Stop here if JESD216 rev B. */
2357         if (bfpt_header->length == BFPT_DWORD_MAX_JESD216B)
2358                 return spi_nor_post_bfpt_fixups(nor, bfpt_header, &bfpt,
2359                                                 params);
2360
2361         /* 8D-8D-8D command extension. */
2362         switch (bfpt.dwords[BFPT_DWORD(18)] & BFPT_DWORD18_CMD_EXT_MASK) {
2363         case BFPT_DWORD18_CMD_EXT_REP:
2364                 nor->cmd_ext_type = SPI_NOR_EXT_REPEAT;
2365                 break;
2366
2367         case BFPT_DWORD18_CMD_EXT_INV:
2368                 nor->cmd_ext_type = SPI_NOR_EXT_INVERT;
2369                 break;
2370
2371         case BFPT_DWORD18_CMD_EXT_RES:
2372                 return -EINVAL;
2373
2374         case BFPT_DWORD18_CMD_EXT_16B:
2375                 dev_err(nor->dev, "16-bit opcodes not supported\n");
2376                 return -ENOTSUPP;
2377         }
2378
2379         return spi_nor_post_bfpt_fixups(nor, bfpt_header, &bfpt, params);
2380 }
2381
2382 /**
2383  * spi_nor_parse_microchip_sfdp() - parse the Microchip manufacturer specific
2384  * SFDP table.
2385  * @nor:                pointer to a 'struct spi_nor'.
2386  * @param_header:       pointer to the SFDP parameter header.
2387  *
2388  * Return: 0 on success, -errno otherwise.
2389  */
2390 static int
2391 spi_nor_parse_microchip_sfdp(struct spi_nor *nor,
2392                              const struct sfdp_parameter_header *param_header)
2393 {
2394         size_t size;
2395         u32 addr;
2396         int ret;
2397
2398         size = param_header->length * sizeof(u32);
2399         addr = SFDP_PARAM_HEADER_PTP(param_header);
2400
2401         nor->manufacturer_sfdp = devm_kmalloc(nor->dev, size, GFP_KERNEL);
2402         if (!nor->manufacturer_sfdp)
2403                 return -ENOMEM;
2404
2405         ret = spi_nor_read_sfdp(nor, addr, size, nor->manufacturer_sfdp);
2406
2407         return ret;
2408 }
2409
2410 /**
2411  * spi_nor_parse_profile1() - parse the xSPI Profile 1.0 table
2412  * @nor:                pointer to a 'struct spi_nor'
2413  * @profile1_header:    pointer to the 'struct sfdp_parameter_header' describing
2414  *                      the 4-Byte Address Instruction Table length and version.
2415  * @params:             pointer to the 'struct spi_nor_flash_parameter' to be.
2416  *
2417  * Return: 0 on success, -errno otherwise.
2418  */
2419 static int spi_nor_parse_profile1(struct spi_nor *nor,
2420                                   const struct sfdp_parameter_header *profile1_header,
2421                                   struct spi_nor_flash_parameter *params)
2422 {
2423         u32 *table, opcode, addr;
2424         size_t len;
2425         int ret, i;
2426         u8 dummy;
2427
2428         len = profile1_header->length * sizeof(*table);
2429         table = kmalloc(len, GFP_KERNEL);
2430         if (!table)
2431                 return -ENOMEM;
2432
2433         addr = SFDP_PARAM_HEADER_PTP(profile1_header);
2434         ret = spi_nor_read_sfdp(nor, addr, len, table);
2435         if (ret)
2436                 goto out;
2437
2438         /* Fix endianness of the table DWORDs. */
2439         for (i = 0; i < profile1_header->length; i++)
2440                 table[i] = le32_to_cpu(table[i]);
2441
2442         /* Get 8D-8D-8D fast read opcode and dummy cycles. */
2443         opcode = FIELD_GET(PROFILE1_DWORD1_RD_FAST_CMD, table[0]);
2444
2445         /*
2446          * We don't know what speed the controller is running at. Find the
2447          * dummy cycles for the fastest frequency the flash can run at to be
2448          * sure we are never short of dummy cycles. A value of 0 means the
2449          * frequency is not supported.
2450          *
2451          * Default to PROFILE1_DUMMY_DEFAULT if we don't find anything, and let
2452          * flashes set the correct value if needed in their fixup hooks.
2453          */
2454         dummy = FIELD_GET(PROFILE1_DWORD4_DUMMY_200MHZ, table[3]);
2455         if (!dummy)
2456                 dummy = FIELD_GET(PROFILE1_DWORD5_DUMMY_166MHZ, table[4]);
2457         if (!dummy)
2458                 dummy = FIELD_GET(PROFILE1_DWORD5_DUMMY_133MHZ, table[4]);
2459         if (!dummy)
2460                 dummy = FIELD_GET(PROFILE1_DWORD5_DUMMY_100MHZ, table[4]);
2461         if (!dummy)
2462                 dummy = PROFILE1_DUMMY_DEFAULT;
2463
2464         /* Round up to an even value to avoid tripping controllers up. */
2465         dummy = ROUND_UP_TO(dummy, 2);
2466
2467         /* Update the fast read settings. */
2468         spi_nor_set_read_settings(&params->reads[SNOR_CMD_READ_8_8_8_DTR],
2469                                   0, dummy, opcode,
2470                                   SNOR_PROTO_8_8_8_DTR);
2471
2472         /*
2473          * Set the Read Status Register dummy cycles and dummy address bytes.
2474          */
2475         if (table[0] & PROFILE1_DWORD1_RDSR_DUMMY)
2476                 params->rdsr_dummy = 8;
2477         else
2478                 params->rdsr_dummy = 4;
2479
2480         if (table[0] & PROFILE1_DWORD1_RDSR_ADDR_BYTES)
2481                 params->rdsr_addr_nbytes = 4;
2482         else
2483                 params->rdsr_addr_nbytes = 0;
2484
2485 out:
2486         kfree(table);
2487         return ret;
2488 }
2489
2490 /**
2491  * spi_nor_parse_sccr() - Parse the Status, Control and Configuration Register
2492  *                        Map.
2493  * @nor:                  pointer to a 'struct spi_nor'
2494  * @sccr_header:          pointer to the 'struct sfdp_parameter_header' describing
2495  *                        the SCCR Map table length and version.
2496  *
2497  * Return: 0 on success, -errno otherwise.
2498  */
2499 static int spi_nor_parse_sccr(struct spi_nor *nor,
2500                               const struct sfdp_parameter_header *sccr_header)
2501 {
2502         u32 *table, addr;
2503         size_t len;
2504         int ret, i;
2505
2506         len = sccr_header->length * sizeof(*table);
2507         table = kmalloc(len, GFP_KERNEL);
2508         if (!table)
2509                 return -ENOMEM;
2510
2511         addr = SFDP_PARAM_HEADER_PTP(sccr_header);
2512         ret = spi_nor_read_sfdp(nor, addr, len, table);
2513         if (ret)
2514                 goto out;
2515
2516         /* Fix endianness of the table DWORDs. */
2517         for (i = 0; i < sccr_header->length; i++)
2518                 table[i] = le32_to_cpu(table[i]);
2519
2520         if (FIELD_GET(SCCR_DWORD22_OCTAL_DTR_EN_VOLATILE, table[22]))
2521                 nor->flags |= SNOR_F_IO_MODE_EN_VOLATILE;
2522
2523 out:
2524         kfree(table);
2525         return ret;
2526 }
2527
2528 /**
2529  * spi_nor_parse_sfdp() - parse the Serial Flash Discoverable Parameters.
2530  * @nor:                pointer to a 'struct spi_nor'
2531  * @params:             pointer to the 'struct spi_nor_flash_parameter' to be
2532  *                      filled
2533  *
2534  * The Serial Flash Discoverable Parameters are described by the JEDEC JESD216
2535  * specification. This is a standard which tends to supported by almost all
2536  * (Q)SPI memory manufacturers. Those hard-coded tables allow us to learn at
2537  * runtime the main parameters needed to perform basic SPI flash operations such
2538  * as Fast Read, Page Program or Sector Erase commands.
2539  *
2540  * Return: 0 on success, -errno otherwise.
2541  */
2542 static int spi_nor_parse_sfdp(struct spi_nor *nor,
2543                               struct spi_nor_flash_parameter *params)
2544 {
2545         const struct sfdp_parameter_header *param_header, *bfpt_header;
2546         struct sfdp_parameter_header *param_headers = NULL;
2547         struct sfdp_header header;
2548         size_t psize;
2549         int i, err;
2550
2551         /* Get the SFDP header. */
2552         err = spi_nor_read_sfdp(nor, 0, sizeof(header), &header);
2553         if (err < 0)
2554                 return err;
2555
2556         /* Check the SFDP header version. */
2557         if (le32_to_cpu(header.signature) != SFDP_SIGNATURE ||
2558             header.major != SFDP_JESD216_MAJOR)
2559                 return -EINVAL;
2560
2561         /*
2562          * Verify that the first and only mandatory parameter header is a
2563          * Basic Flash Parameter Table header as specified in JESD216.
2564          */
2565         bfpt_header = &header.bfpt_header;
2566         if (SFDP_PARAM_HEADER_ID(bfpt_header) != SFDP_BFPT_ID ||
2567             bfpt_header->major != SFDP_JESD216_MAJOR)
2568                 return -EINVAL;
2569
2570         /*
2571          * Allocate memory then read all parameter headers with a single
2572          * Read SFDP command. These parameter headers will actually be parsed
2573          * twice: a first time to get the latest revision of the basic flash
2574          * parameter table, then a second time to handle the supported optional
2575          * tables.
2576          * Hence we read the parameter headers once for all to reduce the
2577          * processing time. Also we use kmalloc() instead of devm_kmalloc()
2578          * because we don't need to keep these parameter headers: the allocated
2579          * memory is always released with kfree() before exiting this function.
2580          */
2581         if (header.nph) {
2582                 psize = header.nph * sizeof(*param_headers);
2583
2584                 param_headers = kmalloc(psize, GFP_KERNEL);
2585                 if (!param_headers)
2586                         return -ENOMEM;
2587
2588                 err = spi_nor_read_sfdp(nor, sizeof(header),
2589                                         psize, param_headers);
2590                 if (err < 0) {
2591                         dev_err(nor->dev,
2592                                 "failed to read SFDP parameter headers\n");
2593                         goto exit;
2594                 }
2595         }
2596
2597         /*
2598          * Check other parameter headers to get the latest revision of
2599          * the basic flash parameter table.
2600          */
2601         for (i = 0; i < header.nph; i++) {
2602                 param_header = &param_headers[i];
2603
2604                 if (SFDP_PARAM_HEADER_ID(param_header) == SFDP_BFPT_ID &&
2605                     param_header->major == SFDP_JESD216_MAJOR &&
2606                     (param_header->minor > bfpt_header->minor ||
2607                      (param_header->minor == bfpt_header->minor &&
2608                       param_header->length > bfpt_header->length)))
2609                         bfpt_header = param_header;
2610         }
2611
2612         err = spi_nor_parse_bfpt(nor, bfpt_header, params);
2613         if (err)
2614                 goto exit;
2615
2616         /* Parse other parameter headers. */
2617         for (i = 0; i < header.nph; i++) {
2618                 param_header = &param_headers[i];
2619
2620                 switch (SFDP_PARAM_HEADER_ID(param_header)) {
2621                 case SFDP_SECTOR_MAP_ID:
2622                         dev_info(nor->dev,
2623                                  "non-uniform erase sector maps are not supported yet.\n");
2624                         break;
2625
2626                 case SFDP_SST_ID:
2627                         err = spi_nor_parse_microchip_sfdp(nor, param_header);
2628                         break;
2629
2630                 case SFDP_PROFILE1_ID:
2631                         err = spi_nor_parse_profile1(nor, param_header, params);
2632                         break;
2633
2634                 case SFDP_SCCR_MAP_ID:
2635                         err = spi_nor_parse_sccr(nor, param_header);
2636                         break;
2637
2638                 default:
2639                         break;
2640                 }
2641
2642                 if (err) {
2643                         dev_warn(nor->dev,
2644                                  "Failed to parse optional parameter table: %04x\n",
2645                                  SFDP_PARAM_HEADER_ID(param_header));
2646                         /*
2647                          * Let's not drop all information we extracted so far
2648                          * if optional table parsers fail. In case of failing,
2649                          * each optional parser is responsible to roll back to
2650                          * the previously known spi_nor data.
2651                          */
2652                         err = 0;
2653                 }
2654         }
2655
2656 exit:
2657         kfree(param_headers);
2658         return err;
2659 }
2660 #else
2661 static int spi_nor_parse_sfdp(struct spi_nor *nor,
2662                               struct spi_nor_flash_parameter *params)
2663 {
2664         return -EINVAL;
2665 }
2666 #endif /* SPI_FLASH_SFDP_SUPPORT */
2667
2668 /**
2669  * spi_nor_post_sfdp_fixups() - Updates the flash's parameters and settings
2670  * after SFDP has been parsed (is also called for SPI NORs that do not
2671  * support RDSFDP).
2672  * @nor:        pointer to a 'struct spi_nor'
2673  *
2674  * Typically used to tweak various parameters that could not be extracted by
2675  * other means (i.e. when information provided by the SFDP/flash_info tables
2676  * are incomplete or wrong).
2677  */
2678 static void spi_nor_post_sfdp_fixups(struct spi_nor *nor,
2679                                      struct spi_nor_flash_parameter *params)
2680 {
2681         if (nor->fixups && nor->fixups->post_sfdp)
2682                 nor->fixups->post_sfdp(nor, params);
2683 }
2684
2685 static void spi_nor_default_init_fixups(struct spi_nor *nor)
2686 {
2687         if (nor->fixups && nor->fixups->default_init)
2688                 nor->fixups->default_init(nor);
2689 }
2690
2691 static int spi_nor_init_params(struct spi_nor *nor,
2692                                const struct flash_info *info,
2693                                struct spi_nor_flash_parameter *params)
2694 {
2695         /* Set legacy flash parameters as default. */
2696         memset(params, 0, sizeof(*params));
2697
2698         /* Set SPI NOR sizes. */
2699         params->size = info->sector_size * info->n_sectors;
2700         params->page_size = info->page_size;
2701
2702         if (!(info->flags & SPI_NOR_NO_FR)) {
2703                 /* Default to Fast Read for DT and non-DT platform devices. */
2704                 params->hwcaps.mask |= SNOR_HWCAPS_READ_FAST;
2705
2706                 /* Mask out Fast Read if not requested at DT instantiation. */
2707 #if CONFIG_IS_ENABLED(DM_SPI)
2708                 if (!ofnode_read_bool(dev_ofnode(nor->spi->dev),
2709                                       "m25p,fast-read"))
2710                         params->hwcaps.mask &= ~SNOR_HWCAPS_READ_FAST;
2711 #endif
2712         }
2713
2714         /* (Fast) Read settings. */
2715         params->hwcaps.mask |= SNOR_HWCAPS_READ;
2716         spi_nor_set_read_settings(&params->reads[SNOR_CMD_READ],
2717                                   0, 0, SPINOR_OP_READ,
2718                                   SNOR_PROTO_1_1_1);
2719
2720         if (params->hwcaps.mask & SNOR_HWCAPS_READ_FAST)
2721                 spi_nor_set_read_settings(&params->reads[SNOR_CMD_READ_FAST],
2722                                           0, 8, SPINOR_OP_READ_FAST,
2723                                           SNOR_PROTO_1_1_1);
2724
2725         if (info->flags & SPI_NOR_DUAL_READ) {
2726                 params->hwcaps.mask |= SNOR_HWCAPS_READ_1_1_2;
2727                 spi_nor_set_read_settings(&params->reads[SNOR_CMD_READ_1_1_2],
2728                                           0, 8, SPINOR_OP_READ_1_1_2,
2729                                           SNOR_PROTO_1_1_2);
2730         }
2731
2732         if (info->flags & SPI_NOR_QUAD_READ) {
2733                 params->hwcaps.mask |= SNOR_HWCAPS_READ_1_1_4;
2734                 spi_nor_set_read_settings(&params->reads[SNOR_CMD_READ_1_1_4],
2735                                           0, 8, SPINOR_OP_READ_1_1_4,
2736                                           SNOR_PROTO_1_1_4);
2737         }
2738
2739         if (info->flags & SPI_NOR_OCTAL_READ) {
2740                 params->hwcaps.mask |= SNOR_HWCAPS_READ_1_1_8;
2741                 spi_nor_set_read_settings(&params->reads[SNOR_CMD_READ_1_1_8],
2742                                           0, 8, SPINOR_OP_READ_1_1_8,
2743                                           SNOR_PROTO_1_1_8);
2744         }
2745
2746         if (info->flags & SPI_NOR_OCTAL_DTR_READ) {
2747                 params->hwcaps.mask |= SNOR_HWCAPS_READ_8_8_8_DTR;
2748                 spi_nor_set_read_settings(&params->reads[SNOR_CMD_READ_8_8_8_DTR],
2749                                           0, 20, SPINOR_OP_READ_FAST,
2750                                           SNOR_PROTO_8_8_8_DTR);
2751         }
2752
2753         /* Page Program settings. */
2754         params->hwcaps.mask |= SNOR_HWCAPS_PP;
2755         spi_nor_set_pp_settings(&params->page_programs[SNOR_CMD_PP],
2756                                 SPINOR_OP_PP, SNOR_PROTO_1_1_1);
2757
2758         /*
2759          * Since xSPI Page Program opcode is backward compatible with
2760          * Legacy SPI, use Legacy SPI opcode there as well.
2761          */
2762         spi_nor_set_pp_settings(&params->page_programs[SNOR_CMD_PP_8_8_8_DTR],
2763                                 SPINOR_OP_PP, SNOR_PROTO_8_8_8_DTR);
2764
2765         if (info->flags & SPI_NOR_QUAD_READ) {
2766                 params->hwcaps.mask |= SNOR_HWCAPS_PP_1_1_4;
2767                 spi_nor_set_pp_settings(&params->page_programs[SNOR_CMD_PP_1_1_4],
2768                                         SPINOR_OP_PP_1_1_4, SNOR_PROTO_1_1_4);
2769         }
2770
2771         /* Select the procedure to set the Quad Enable bit. */
2772         if (params->hwcaps.mask & (SNOR_HWCAPS_READ_QUAD |
2773                                    SNOR_HWCAPS_PP_QUAD)) {
2774                 switch (JEDEC_MFR(info)) {
2775 #if defined(CONFIG_SPI_FLASH_MACRONIX) || defined(CONFIG_SPI_FLASH_ISSI)
2776                 case SNOR_MFR_MACRONIX:
2777                 case SNOR_MFR_ISSI:
2778                         params->quad_enable = macronix_quad_enable;
2779                         break;
2780 #endif
2781                 case SNOR_MFR_ST:
2782                 case SNOR_MFR_MICRON:
2783                         break;
2784
2785                 default:
2786 #if defined(CONFIG_SPI_FLASH_SPANSION) || defined(CONFIG_SPI_FLASH_WINBOND)
2787                         /* Kept only for backward compatibility purpose. */
2788                         params->quad_enable = spansion_read_cr_quad_enable;
2789 #endif
2790                         break;
2791                 }
2792         }
2793
2794         spi_nor_default_init_fixups(nor);
2795
2796         /* Override the parameters with data read from SFDP tables. */
2797         nor->addr_width = 0;
2798         nor->mtd.erasesize = 0;
2799         if ((info->flags & (SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ |
2800              SPI_NOR_OCTAL_DTR_READ)) &&
2801             !(info->flags & SPI_NOR_SKIP_SFDP)) {
2802                 struct spi_nor_flash_parameter sfdp_params;
2803
2804                 memcpy(&sfdp_params, params, sizeof(sfdp_params));
2805                 if (spi_nor_parse_sfdp(nor, &sfdp_params)) {
2806                         nor->addr_width = 0;
2807                         nor->mtd.erasesize = 0;
2808                 } else {
2809                         memcpy(params, &sfdp_params, sizeof(*params));
2810                 }
2811         }
2812
2813         spi_nor_post_sfdp_fixups(nor, params);
2814
2815         return 0;
2816 }
2817
2818 static int spi_nor_hwcaps2cmd(u32 hwcaps, const int table[][2], size_t size)
2819 {
2820         size_t i;
2821
2822         for (i = 0; i < size; i++)
2823                 if (table[i][0] == (int)hwcaps)
2824                         return table[i][1];
2825
2826         return -EINVAL;
2827 }
2828
2829 static int spi_nor_hwcaps_read2cmd(u32 hwcaps)
2830 {
2831         static const int hwcaps_read2cmd[][2] = {
2832                 { SNOR_HWCAPS_READ,             SNOR_CMD_READ },
2833                 { SNOR_HWCAPS_READ_FAST,        SNOR_CMD_READ_FAST },
2834                 { SNOR_HWCAPS_READ_1_1_1_DTR,   SNOR_CMD_READ_1_1_1_DTR },
2835                 { SNOR_HWCAPS_READ_1_1_2,       SNOR_CMD_READ_1_1_2 },
2836                 { SNOR_HWCAPS_READ_1_2_2,       SNOR_CMD_READ_1_2_2 },
2837                 { SNOR_HWCAPS_READ_2_2_2,       SNOR_CMD_READ_2_2_2 },
2838                 { SNOR_HWCAPS_READ_1_2_2_DTR,   SNOR_CMD_READ_1_2_2_DTR },
2839                 { SNOR_HWCAPS_READ_1_1_4,       SNOR_CMD_READ_1_1_4 },
2840                 { SNOR_HWCAPS_READ_1_4_4,       SNOR_CMD_READ_1_4_4 },
2841                 { SNOR_HWCAPS_READ_4_4_4,       SNOR_CMD_READ_4_4_4 },
2842                 { SNOR_HWCAPS_READ_1_4_4_DTR,   SNOR_CMD_READ_1_4_4_DTR },
2843                 { SNOR_HWCAPS_READ_1_1_8,       SNOR_CMD_READ_1_1_8 },
2844                 { SNOR_HWCAPS_READ_1_8_8,       SNOR_CMD_READ_1_8_8 },
2845                 { SNOR_HWCAPS_READ_8_8_8,       SNOR_CMD_READ_8_8_8 },
2846                 { SNOR_HWCAPS_READ_1_8_8_DTR,   SNOR_CMD_READ_1_8_8_DTR },
2847                 { SNOR_HWCAPS_READ_8_8_8_DTR,   SNOR_CMD_READ_8_8_8_DTR },
2848         };
2849
2850         return spi_nor_hwcaps2cmd(hwcaps, hwcaps_read2cmd,
2851                                   ARRAY_SIZE(hwcaps_read2cmd));
2852 }
2853
2854 static int spi_nor_hwcaps_pp2cmd(u32 hwcaps)
2855 {
2856         static const int hwcaps_pp2cmd[][2] = {
2857                 { SNOR_HWCAPS_PP,               SNOR_CMD_PP },
2858                 { SNOR_HWCAPS_PP_1_1_4,         SNOR_CMD_PP_1_1_4 },
2859                 { SNOR_HWCAPS_PP_1_4_4,         SNOR_CMD_PP_1_4_4 },
2860                 { SNOR_HWCAPS_PP_4_4_4,         SNOR_CMD_PP_4_4_4 },
2861                 { SNOR_HWCAPS_PP_1_1_8,         SNOR_CMD_PP_1_1_8 },
2862                 { SNOR_HWCAPS_PP_1_8_8,         SNOR_CMD_PP_1_8_8 },
2863                 { SNOR_HWCAPS_PP_8_8_8,         SNOR_CMD_PP_8_8_8 },
2864                 { SNOR_HWCAPS_PP_8_8_8_DTR,     SNOR_CMD_PP_8_8_8_DTR },
2865         };
2866
2867         return spi_nor_hwcaps2cmd(hwcaps, hwcaps_pp2cmd,
2868                                   ARRAY_SIZE(hwcaps_pp2cmd));
2869 }
2870
2871 #ifdef CONFIG_SPI_FLASH_SMART_HWCAPS
2872 /**
2873  * spi_nor_check_op - check if the operation is supported by controller
2874  * @nor:        pointer to a 'struct spi_nor'
2875  * @op:         pointer to op template to be checked
2876  *
2877  * Returns 0 if operation is supported, -ENOTSUPP otherwise.
2878  */
2879 static int spi_nor_check_op(struct spi_nor *nor,
2880                             struct spi_mem_op *op)
2881 {
2882         /*
2883          * First test with 4 address bytes. The opcode itself might be a 3B
2884          * addressing opcode but we don't care, because SPI controller
2885          * implementation should not check the opcode, but just the sequence.
2886          */
2887         op->addr.nbytes = 4;
2888         if (!spi_mem_supports_op(nor->spi, op)) {
2889                 if (nor->mtd.size > SZ_16M)
2890                         return -ENOTSUPP;
2891
2892                 /* If flash size <= 16MB, 3 address bytes are sufficient */
2893                 op->addr.nbytes = 3;
2894                 if (!spi_mem_supports_op(nor->spi, op))
2895                         return -ENOTSUPP;
2896         }
2897
2898         return 0;
2899 }
2900
2901 /**
2902  * spi_nor_check_readop - check if the read op is supported by controller
2903  * @nor:         pointer to a 'struct spi_nor'
2904  * @read:        pointer to op template to be checked
2905  *
2906  * Returns 0 if operation is supported, -ENOTSUPP otherwise.
2907  */
2908 static int spi_nor_check_readop(struct spi_nor *nor,
2909                                 const struct spi_nor_read_command *read)
2910 {
2911         struct spi_mem_op op = SPI_MEM_OP(SPI_MEM_OP_CMD(read->opcode, 0),
2912                                           SPI_MEM_OP_ADDR(3, 0, 0),
2913                                           SPI_MEM_OP_DUMMY(1, 0),
2914                                           SPI_MEM_OP_DATA_IN(2, NULL, 0));
2915
2916         spi_nor_setup_op(nor, &op, read->proto);
2917
2918         op.dummy.nbytes = (read->num_mode_clocks + read->num_wait_states) *
2919                           op.dummy.buswidth / 8;
2920         if (spi_nor_protocol_is_dtr(nor->read_proto))
2921                 op.dummy.nbytes *= 2;
2922
2923         return spi_nor_check_op(nor, &op);
2924 }
2925
2926 /**
2927  * spi_nor_check_pp - check if the page program op is supported by controller
2928  * @nor:         pointer to a 'struct spi_nor'
2929  * @pp:          pointer to op template to be checked
2930  *
2931  * Returns 0 if operation is supported, -ENOTSUPP otherwise.
2932  */
2933 static int spi_nor_check_pp(struct spi_nor *nor,
2934                             const struct spi_nor_pp_command *pp)
2935 {
2936         struct spi_mem_op op = SPI_MEM_OP(SPI_MEM_OP_CMD(pp->opcode, 0),
2937                                           SPI_MEM_OP_ADDR(3, 0, 0),
2938                                           SPI_MEM_OP_NO_DUMMY,
2939                                           SPI_MEM_OP_DATA_OUT(2, NULL, 0));
2940
2941         spi_nor_setup_op(nor, &op, pp->proto);
2942
2943         return spi_nor_check_op(nor, &op);
2944 }
2945
2946 /**
2947  * spi_nor_adjust_hwcaps - Find optimal Read/Write protocol based on SPI
2948  *                         controller capabilities
2949  * @nor:        pointer to a 'struct spi_nor'
2950  * @params:     pointer to the 'struct spi_nor_flash_parameter'
2951  *              representing SPI NOR flash capabilities
2952  * @hwcaps:     pointer to resulting capabilities after adjusting
2953  *              according to controller and flash's capability
2954  *
2955  * Discard caps based on what the SPI controller actually supports (using
2956  * spi_mem_supports_op()).
2957  */
2958 static void
2959 spi_nor_adjust_hwcaps(struct spi_nor *nor,
2960                       const struct spi_nor_flash_parameter *params,
2961                       u32 *hwcaps)
2962 {
2963         unsigned int cap;
2964
2965         /*
2966          * Start by assuming the controller supports every capability.
2967          * We will mask them after checking what's really supported
2968          * using spi_mem_supports_op().
2969          */
2970         *hwcaps = SNOR_HWCAPS_ALL & params->hwcaps.mask;
2971
2972         /* X-X-X modes are not supported yet, mask them all. */
2973         *hwcaps &= ~SNOR_HWCAPS_X_X_X;
2974
2975         /*
2976          * If the reset line is broken, we do not want to enter a stateful
2977          * mode.
2978          */
2979         if (nor->flags & SNOR_F_BROKEN_RESET)
2980                 *hwcaps &= ~(SNOR_HWCAPS_X_X_X | SNOR_HWCAPS_X_X_X_DTR);
2981
2982         for (cap = 0; cap < sizeof(*hwcaps) * BITS_PER_BYTE; cap++) {
2983                 int rdidx, ppidx;
2984
2985                 if (!(*hwcaps & BIT(cap)))
2986                         continue;
2987
2988                 rdidx = spi_nor_hwcaps_read2cmd(BIT(cap));
2989                 if (rdidx >= 0 &&
2990                     spi_nor_check_readop(nor, &params->reads[rdidx]))
2991                         *hwcaps &= ~BIT(cap);
2992
2993                 ppidx = spi_nor_hwcaps_pp2cmd(BIT(cap));
2994                 if (ppidx < 0)
2995                         continue;
2996
2997                 if (spi_nor_check_pp(nor, &params->page_programs[ppidx]))
2998                         *hwcaps &= ~BIT(cap);
2999         }
3000 }
3001 #else
3002 /**
3003  * spi_nor_adjust_hwcaps - Find optimal Read/Write protocol based on SPI
3004  *                         controller capabilities
3005  * @nor:        pointer to a 'struct spi_nor'
3006  * @params:     pointer to the 'struct spi_nor_flash_parameter'
3007  *              representing SPI NOR flash capabilities
3008  * @hwcaps:     pointer to resulting capabilities after adjusting
3009  *              according to controller and flash's capability
3010  *
3011  * Select caps based on what the SPI controller and SPI flash both support.
3012  */
3013 static void
3014 spi_nor_adjust_hwcaps(struct spi_nor *nor,
3015                       const struct spi_nor_flash_parameter *params,
3016                       u32 *hwcaps)
3017 {
3018         struct spi_slave *spi = nor->spi;
3019         u32 ignored_mask = (SNOR_HWCAPS_READ_2_2_2 |
3020                             SNOR_HWCAPS_READ_4_4_4 |
3021                             SNOR_HWCAPS_READ_8_8_8 |
3022                             SNOR_HWCAPS_PP_4_4_4   |
3023                             SNOR_HWCAPS_PP_8_8_8);
3024         u32 spi_hwcaps = (SNOR_HWCAPS_READ | SNOR_HWCAPS_READ_FAST |
3025                           SNOR_HWCAPS_PP);
3026
3027         /* Get the hardware capabilities the SPI controller supports. */
3028         if (spi->mode & SPI_RX_OCTAL) {
3029                 spi_hwcaps |= SNOR_HWCAPS_READ_1_1_8;
3030
3031                 if (spi->mode & SPI_TX_OCTAL)
3032                         spi_hwcaps |= (SNOR_HWCAPS_READ_1_8_8 |
3033                                         SNOR_HWCAPS_PP_1_1_8 |
3034                                         SNOR_HWCAPS_PP_1_8_8);
3035         } else if (spi->mode & SPI_RX_QUAD) {
3036                 spi_hwcaps |= SNOR_HWCAPS_READ_1_1_4;
3037
3038                 if (spi->mode & SPI_TX_QUAD)
3039                         spi_hwcaps |= (SNOR_HWCAPS_READ_1_4_4 |
3040                                         SNOR_HWCAPS_PP_1_1_4 |
3041                                         SNOR_HWCAPS_PP_1_4_4);
3042         } else if (spi->mode & SPI_RX_DUAL) {
3043                 spi_hwcaps |= SNOR_HWCAPS_READ_1_1_2;
3044
3045                 if (spi->mode & SPI_TX_DUAL)
3046                         spi_hwcaps |= SNOR_HWCAPS_READ_1_2_2;
3047         }
3048
3049         /*
3050          * Keep only the hardware capabilities supported by both the SPI
3051          * controller and the SPI flash memory.
3052          */
3053         *hwcaps = spi_hwcaps & params->hwcaps.mask;
3054         if (*hwcaps & ignored_mask) {
3055                 dev_dbg(nor->dev,
3056                         "SPI n-n-n protocols are not supported yet.\n");
3057                 *hwcaps &= ~ignored_mask;
3058         }
3059 }
3060 #endif /* CONFIG_SPI_FLASH_SMART_HWCAPS */
3061
3062 static int spi_nor_select_read(struct spi_nor *nor,
3063                                const struct spi_nor_flash_parameter *params,
3064                                u32 shared_hwcaps)
3065 {
3066         int cmd, best_match = fls(shared_hwcaps & SNOR_HWCAPS_READ_MASK) - 1;
3067         const struct spi_nor_read_command *read;
3068
3069         if (best_match < 0)
3070                 return -EINVAL;
3071
3072         cmd = spi_nor_hwcaps_read2cmd(BIT(best_match));
3073         if (cmd < 0)
3074                 return -EINVAL;
3075
3076         read = &params->reads[cmd];
3077         nor->read_opcode = read->opcode;
3078         nor->read_proto = read->proto;
3079
3080         /*
3081          * In the spi-nor framework, we don't need to make the difference
3082          * between mode clock cycles and wait state clock cycles.
3083          * Indeed, the value of the mode clock cycles is used by a QSPI
3084          * flash memory to know whether it should enter or leave its 0-4-4
3085          * (Continuous Read / XIP) mode.
3086          * eXecution In Place is out of the scope of the mtd sub-system.
3087          * Hence we choose to merge both mode and wait state clock cycles
3088          * into the so called dummy clock cycles.
3089          */
3090         nor->read_dummy = read->num_mode_clocks + read->num_wait_states;
3091         return 0;
3092 }
3093
3094 static int spi_nor_select_pp(struct spi_nor *nor,
3095                              const struct spi_nor_flash_parameter *params,
3096                              u32 shared_hwcaps)
3097 {
3098         int cmd, best_match = fls(shared_hwcaps & SNOR_HWCAPS_PP_MASK) - 1;
3099         const struct spi_nor_pp_command *pp;
3100
3101         if (best_match < 0)
3102                 return -EINVAL;
3103
3104         cmd = spi_nor_hwcaps_pp2cmd(BIT(best_match));
3105         if (cmd < 0)
3106                 return -EINVAL;
3107
3108         pp = &params->page_programs[cmd];
3109         nor->program_opcode = pp->opcode;
3110         nor->write_proto = pp->proto;
3111         return 0;
3112 }
3113
3114 static int spi_nor_select_erase(struct spi_nor *nor,
3115                                 const struct flash_info *info)
3116 {
3117         struct mtd_info *mtd = &nor->mtd;
3118
3119         /* Do nothing if already configured from SFDP. */
3120         if (mtd->erasesize)
3121                 return 0;
3122
3123 #ifdef CONFIG_SPI_FLASH_USE_4K_SECTORS
3124         /* prefer "small sector" erase if possible */
3125         if (info->flags & SECT_4K) {
3126                 nor->erase_opcode = SPINOR_OP_BE_4K;
3127                 mtd->erasesize = 4096;
3128         } else if (info->flags & SECT_4K_PMC) {
3129                 nor->erase_opcode = SPINOR_OP_BE_4K_PMC;
3130                 mtd->erasesize = 4096;
3131         } else
3132 #endif
3133         {
3134                 nor->erase_opcode = SPINOR_OP_SE;
3135                 mtd->erasesize = info->sector_size;
3136         }
3137         return 0;
3138 }
3139
3140 static int spi_nor_default_setup(struct spi_nor *nor,
3141                                  const struct flash_info *info,
3142                                  const struct spi_nor_flash_parameter *params)
3143 {
3144         u32 shared_mask;
3145         bool enable_quad_io;
3146         int err;
3147
3148         spi_nor_adjust_hwcaps(nor, params, &shared_mask);
3149
3150         /* Select the (Fast) Read command. */
3151         err = spi_nor_select_read(nor, params, shared_mask);
3152         if (err) {
3153                 dev_dbg(nor->dev,
3154                         "can't select read settings supported by both the SPI controller and memory.\n");
3155                 return err;
3156         }
3157
3158         /* Select the Page Program command. */
3159         err = spi_nor_select_pp(nor, params, shared_mask);
3160         if (err) {
3161                 dev_dbg(nor->dev,
3162                         "can't select write settings supported by both the SPI controller and memory.\n");
3163                 return err;
3164         }
3165
3166         /* Select the Sector Erase command. */
3167         err = spi_nor_select_erase(nor, info);
3168         if (err) {
3169                 dev_dbg(nor->dev,
3170                         "can't select erase settings supported by both the SPI controller and memory.\n");
3171                 return err;
3172         }
3173
3174         /* Enable Quad I/O if needed. */
3175         enable_quad_io = (spi_nor_get_protocol_width(nor->read_proto) == 4 ||
3176                           spi_nor_get_protocol_width(nor->write_proto) == 4);
3177         if (enable_quad_io && params->quad_enable)
3178                 nor->quad_enable = params->quad_enable;
3179         else
3180                 nor->quad_enable = NULL;
3181
3182         return 0;
3183 }
3184
3185 static int spi_nor_setup(struct spi_nor *nor, const struct flash_info *info,
3186                          const struct spi_nor_flash_parameter *params)
3187 {
3188         if (!nor->setup)
3189                 return 0;
3190
3191         return nor->setup(nor, info, params);
3192 }
3193
3194 #ifdef CONFIG_SPI_FLASH_SPANSION
3195 static int s25hx_t_mdp_ready(struct spi_nor *nor)
3196 {
3197         u32 addr;
3198         int ret;
3199
3200         for (addr = 0; addr < nor->mtd.size; addr += SZ_128M) {
3201                 ret = spansion_sr_ready(nor, addr, 0);
3202                 if (!ret)
3203                         return ret;
3204         }
3205
3206         return 1;
3207 }
3208
3209 static int s25hx_t_quad_enable(struct spi_nor *nor)
3210 {
3211         u32 addr;
3212         int ret;
3213
3214         for (addr = 0; addr < nor->mtd.size; addr += SZ_128M) {
3215                 ret = spansion_quad_enable_volatile(nor, addr, 0);
3216                 if (ret)
3217                         return ret;
3218         }
3219
3220         return 0;
3221 }
3222
3223 static int s25hx_t_erase_non_uniform(struct spi_nor *nor, loff_t addr)
3224 {
3225         /* Support 32 x 4KB sectors at bottom */
3226         return spansion_erase_non_uniform(nor, addr, SPINOR_OP_BE_4K_4B, 0,
3227                                           SZ_128K);
3228 }
3229
3230 static int s25hx_t_setup(struct spi_nor *nor, const struct flash_info *info,
3231                          const struct spi_nor_flash_parameter *params)
3232 {
3233         int ret;
3234         u8 cfr3v;
3235
3236 #ifdef CONFIG_SPI_FLASH_BAR
3237         return -ENOTSUPP; /* Bank Address Register is not supported */
3238 #endif
3239         /*
3240          * Read CFR3V to check if uniform sector is selected. If not, assign an
3241          * erase hook that supports non-uniform erase.
3242          */
3243         ret = spansion_read_any_reg(nor, SPINOR_REG_ADDR_CFR3V, 0, &cfr3v);
3244         if (ret)
3245                 return ret;
3246         if (!(cfr3v & CFR3V_UNHYSA))
3247                 nor->erase = s25hx_t_erase_non_uniform;
3248
3249         /*
3250          * For the multi-die package parts, the ready() hook is needed to check
3251          * all dies' status via read any register.
3252          */
3253         if (nor->mtd.size > SZ_128M)
3254                 nor->ready = s25hx_t_mdp_ready;
3255
3256         return spi_nor_default_setup(nor, info, params);
3257 }
3258
3259 static void s25hx_t_default_init(struct spi_nor *nor)
3260 {
3261         nor->setup = s25hx_t_setup;
3262 }
3263
3264 static int s25hx_t_post_bfpt_fixup(struct spi_nor *nor,
3265                                    const struct sfdp_parameter_header *header,
3266                                    const struct sfdp_bfpt *bfpt,
3267                                    struct spi_nor_flash_parameter *params)
3268 {
3269         int ret;
3270         u32 addr;
3271         u8 cfr3v;
3272
3273         /* erase size in case it is set to 4K from BFPT */
3274         nor->erase_opcode = SPINOR_OP_SE_4B;
3275         nor->mtd.erasesize = nor->info->sector_size;
3276
3277         ret = set_4byte(nor, nor->info, 1);
3278         if (ret)
3279                 return ret;
3280         nor->addr_width = 4;
3281
3282         /*
3283          * The page_size is set to 512B from BFPT, but it actually depends on
3284          * the configuration register. Look up the CFR3V and determine the
3285          * page_size. For multi-die package parts, use 512B only when the all
3286          * dies are configured to 512B buffer.
3287          */
3288         for (addr = 0; addr < params->size; addr += SZ_128M) {
3289                 ret = spansion_read_any_reg(nor, addr + SPINOR_REG_ADDR_CFR3V,
3290                                             0, &cfr3v);
3291                 if (ret)
3292                         return ret;
3293
3294                 if (!(cfr3v & CFR3V_PGMBUF)) {
3295                         params->page_size = 256;
3296                         return 0;
3297                 }
3298         }
3299         params->page_size = 512;
3300
3301         return 0;
3302 }
3303
3304 static void s25hx_t_post_sfdp_fixup(struct spi_nor *nor,
3305                                     struct spi_nor_flash_parameter *params)
3306 {
3307         /* READ_FAST_4B (0Ch) requires mode cycles*/
3308         params->reads[SNOR_CMD_READ_FAST].num_mode_clocks = 8;
3309         /* PP_1_1_4 is not supported */
3310         params->hwcaps.mask &= ~SNOR_HWCAPS_PP_1_1_4;
3311         /* Use volatile register to enable quad */
3312         params->quad_enable = s25hx_t_quad_enable;
3313 }
3314
3315 static struct spi_nor_fixups s25hx_t_fixups = {
3316         .default_init = s25hx_t_default_init,
3317         .post_bfpt = s25hx_t_post_bfpt_fixup,
3318         .post_sfdp = s25hx_t_post_sfdp_fixup,
3319 };
3320
3321 static int s25fl256l_setup(struct spi_nor *nor, const struct flash_info *info,
3322                            const struct spi_nor_flash_parameter *params)
3323 {
3324         return -ENOTSUPP; /* Bank Address Register is not supported */
3325 }
3326
3327 static void s25fl256l_default_init(struct spi_nor *nor)
3328 {
3329         nor->setup = s25fl256l_setup;
3330 }
3331
3332 static struct spi_nor_fixups s25fl256l_fixups = {
3333         .default_init = s25fl256l_default_init,
3334 };
3335 #endif
3336
3337 #ifdef CONFIG_SPI_FLASH_S28HX_T
3338 /**
3339  * spi_nor_cypress_octal_dtr_enable() - Enable octal DTR on Cypress flashes.
3340  * @nor:                pointer to a 'struct spi_nor'
3341  *
3342  * This also sets the memory access latency cycles to 24 to allow the flash to
3343  * run at up to 200MHz.
3344  *
3345  * Return: 0 on success, -errno otherwise.
3346  */
3347 static int spi_nor_cypress_octal_dtr_enable(struct spi_nor *nor)
3348 {
3349         struct spi_mem_op op;
3350         u8 buf;
3351         u8 addr_width = 3;
3352         int ret;
3353
3354         /* Use 24 dummy cycles for memory array reads. */
3355         ret = write_enable(nor);
3356         if (ret)
3357                 return ret;
3358
3359         buf = SPINOR_REG_CYPRESS_CFR2V_MEMLAT_11_24;
3360         op = (struct spi_mem_op)SPI_MEM_OP(SPI_MEM_OP_CMD(SPINOR_OP_WR_ANY_REG, 1),
3361                         SPI_MEM_OP_ADDR(addr_width, SPINOR_REG_CYPRESS_CFR2V, 1),
3362                         SPI_MEM_OP_NO_DUMMY,
3363                         SPI_MEM_OP_DATA_OUT(1, &buf, 1));
3364         ret = spi_mem_exec_op(nor->spi, &op);
3365         if (ret) {
3366                 dev_warn(nor->dev,
3367                          "failed to set default memory latency value: %d\n",
3368                          ret);
3369                 return ret;
3370         }
3371         ret = spi_nor_wait_till_ready(nor);
3372         if (ret)
3373                 return ret;
3374
3375         nor->read_dummy = 24;
3376
3377         /* Set the octal and DTR enable bits. */
3378         ret = write_enable(nor);
3379         if (ret)
3380                 return ret;
3381
3382         buf = SPINOR_REG_CYPRESS_CFR5V_OCT_DTR_EN;
3383         op = (struct spi_mem_op)SPI_MEM_OP(SPI_MEM_OP_CMD(SPINOR_OP_WR_ANY_REG, 1),
3384                         SPI_MEM_OP_ADDR(addr_width, SPINOR_REG_CYPRESS_CFR5V, 1),
3385                         SPI_MEM_OP_NO_DUMMY,
3386                         SPI_MEM_OP_DATA_OUT(1, &buf, 1));
3387         ret = spi_mem_exec_op(nor->spi, &op);
3388         if (ret) {
3389                 dev_warn(nor->dev, "Failed to enable octal DTR mode\n");
3390                 return ret;
3391         }
3392
3393         return 0;
3394 }
3395
3396 static int s28hx_t_erase_non_uniform(struct spi_nor *nor, loff_t addr)
3397 {
3398         /* Factory default configuration: 32 x 4 KiB sectors at bottom. */
3399         return spansion_erase_non_uniform(nor, addr, SPINOR_OP_S28_SE_4K,
3400                                           0, SZ_128K);
3401 }
3402
3403 static int s28hx_t_setup(struct spi_nor *nor, const struct flash_info *info,
3404                          const struct spi_nor_flash_parameter *params)
3405 {
3406         struct spi_mem_op op;
3407         u8 buf;
3408         u8 addr_width = 3;
3409         int ret;
3410
3411         ret = spi_nor_wait_till_ready(nor);
3412         if (ret)
3413                 return ret;
3414
3415         /*
3416          * Check CFR3V to check if non-uniform sector mode is selected. If it
3417          * is, set the erase hook to the non-uniform erase procedure.
3418          */
3419         op = (struct spi_mem_op)
3420                 SPI_MEM_OP(SPI_MEM_OP_CMD(SPINOR_OP_RD_ANY_REG, 1),
3421                            SPI_MEM_OP_ADDR(addr_width,
3422                                            SPINOR_REG_CYPRESS_CFR3V, 1),
3423                            SPI_MEM_OP_NO_DUMMY,
3424                            SPI_MEM_OP_DATA_IN(1, &buf, 1));
3425
3426         ret = spi_mem_exec_op(nor->spi, &op);
3427         if (ret)
3428                 return ret;
3429
3430         if (!(buf & SPINOR_REG_CYPRESS_CFR3V_UNISECT))
3431                 nor->erase = s28hx_t_erase_non_uniform;
3432
3433         return spi_nor_default_setup(nor, info, params);
3434 }
3435
3436 static void s28hx_t_default_init(struct spi_nor *nor)
3437 {
3438         nor->octal_dtr_enable = spi_nor_cypress_octal_dtr_enable;
3439         nor->setup = s28hx_t_setup;
3440 }
3441
3442 static void s28hx_t_post_sfdp_fixup(struct spi_nor *nor,
3443                                     struct spi_nor_flash_parameter *params)
3444 {
3445         /*
3446          * On older versions of the flash the xSPI Profile 1.0 table has the
3447          * 8D-8D-8D Fast Read opcode as 0x00. But it actually should be 0xEE.
3448          */
3449         if (params->reads[SNOR_CMD_READ_8_8_8_DTR].opcode == 0)
3450                 params->reads[SNOR_CMD_READ_8_8_8_DTR].opcode =
3451                         SPINOR_OP_CYPRESS_RD_FAST;
3452
3453         params->hwcaps.mask |= SNOR_HWCAPS_PP_8_8_8_DTR;
3454
3455         /* This flash is also missing the 4-byte Page Program opcode bit. */
3456         spi_nor_set_pp_settings(&params->page_programs[SNOR_CMD_PP],
3457                                 SPINOR_OP_PP_4B, SNOR_PROTO_1_1_1);
3458         /*
3459          * Since xSPI Page Program opcode is backward compatible with
3460          * Legacy SPI, use Legacy SPI opcode there as well.
3461          */
3462         spi_nor_set_pp_settings(&params->page_programs[SNOR_CMD_PP_8_8_8_DTR],
3463                                 SPINOR_OP_PP_4B, SNOR_PROTO_8_8_8_DTR);
3464
3465         /*
3466          * The xSPI Profile 1.0 table advertises the number of additional
3467          * address bytes needed for Read Status Register command as 0 but the
3468          * actual value for that is 4.
3469          */
3470         params->rdsr_addr_nbytes = 4;
3471 }
3472
3473 static int s28hx_t_post_bfpt_fixup(struct spi_nor *nor,
3474                                    const struct sfdp_parameter_header *bfpt_header,
3475                                    const struct sfdp_bfpt *bfpt,
3476                                    struct spi_nor_flash_parameter *params)
3477 {
3478         struct spi_mem_op op;
3479         u8 buf;
3480         u8 addr_width = 3;
3481         int ret;
3482
3483         /*
3484          * The BFPT table advertises a 512B page size but the page size is
3485          * actually configurable (with the default being 256B). Read from
3486          * CFR3V[4] and set the correct size.
3487          */
3488         op = (struct spi_mem_op)
3489                 SPI_MEM_OP(SPI_MEM_OP_CMD(SPINOR_OP_RD_ANY_REG, 1),
3490                            SPI_MEM_OP_ADDR(addr_width, SPINOR_REG_CYPRESS_CFR3V, 1),
3491                            SPI_MEM_OP_NO_DUMMY,
3492                            SPI_MEM_OP_DATA_IN(1, &buf, 1));
3493         ret = spi_mem_exec_op(nor->spi, &op);
3494         if (ret)
3495                 return ret;
3496
3497         if (buf & SPINOR_REG_CYPRESS_CFR3V_PGSZ)
3498                 params->page_size = 512;
3499         else
3500                 params->page_size = 256;
3501
3502         /*
3503          * The BFPT advertises that it supports 4k erases, and the datasheet
3504          * says the same. But 4k erases did not work when testing. So, use 256k
3505          * erases for now.
3506          */
3507         nor->erase_opcode = SPINOR_OP_SE_4B;
3508         nor->mtd.erasesize = 0x40000;
3509
3510         return 0;
3511 }
3512
3513 static struct spi_nor_fixups s28hx_t_fixups = {
3514         .default_init = s28hx_t_default_init,
3515         .post_sfdp = s28hx_t_post_sfdp_fixup,
3516         .post_bfpt = s28hx_t_post_bfpt_fixup,
3517 };
3518 #endif /* CONFIG_SPI_FLASH_S28HX_T */
3519
3520 #ifdef CONFIG_SPI_FLASH_MT35XU
3521 static int spi_nor_micron_octal_dtr_enable(struct spi_nor *nor)
3522 {
3523         struct spi_mem_op op;
3524         u8 buf;
3525         u8 addr_width = 3;
3526         int ret;
3527
3528         /* Set dummy cycles for Fast Read to the default of 20. */
3529         ret = write_enable(nor);
3530         if (ret)
3531                 return ret;
3532
3533         buf = 20;
3534         op = (struct spi_mem_op)
3535                 SPI_MEM_OP(SPI_MEM_OP_CMD(SPINOR_OP_MT_WR_ANY_REG, 1),
3536                            SPI_MEM_OP_ADDR(addr_width, SPINOR_REG_MT_CFR1V, 1),
3537                            SPI_MEM_OP_NO_DUMMY,
3538                            SPI_MEM_OP_DATA_OUT(1, &buf, 1));
3539         ret = spi_mem_exec_op(nor->spi, &op);
3540         if (ret)
3541                 return ret;
3542
3543         ret = spi_nor_wait_till_ready(nor);
3544         if (ret)
3545                 return ret;
3546
3547         nor->read_dummy = 20;
3548
3549         ret = write_enable(nor);
3550         if (ret)
3551                 return ret;
3552
3553         buf = SPINOR_MT_OCT_DTR;
3554         op = (struct spi_mem_op)
3555                 SPI_MEM_OP(SPI_MEM_OP_CMD(SPINOR_OP_MT_WR_ANY_REG, 1),
3556                            SPI_MEM_OP_ADDR(addr_width, SPINOR_REG_MT_CFR0V, 1),
3557                            SPI_MEM_OP_NO_DUMMY,
3558                            SPI_MEM_OP_DATA_OUT(1, &buf, 1));
3559         ret = spi_mem_exec_op(nor->spi, &op);
3560         if (ret) {
3561                 dev_err(nor->dev, "Failed to enable octal DTR mode\n");
3562                 return ret;
3563         }
3564
3565         return 0;
3566 }
3567
3568 static void mt35xu512aba_default_init(struct spi_nor *nor)
3569 {
3570         nor->octal_dtr_enable = spi_nor_micron_octal_dtr_enable;
3571 }
3572
3573 static void mt35xu512aba_post_sfdp_fixup(struct spi_nor *nor,
3574                                          struct spi_nor_flash_parameter *params)
3575 {
3576         /* Set the Fast Read settings. */
3577         params->hwcaps.mask |= SNOR_HWCAPS_READ_8_8_8_DTR;
3578         spi_nor_set_read_settings(&params->reads[SNOR_CMD_READ_8_8_8_DTR],
3579                                   0, 20, SPINOR_OP_MT_DTR_RD,
3580                                   SNOR_PROTO_8_8_8_DTR);
3581
3582         params->hwcaps.mask |= SNOR_HWCAPS_PP_8_8_8_DTR;
3583
3584         nor->cmd_ext_type = SPI_NOR_EXT_REPEAT;
3585         params->rdsr_dummy = 8;
3586         params->rdsr_addr_nbytes = 0;
3587
3588         /*
3589          * The BFPT quad enable field is set to a reserved value so the quad
3590          * enable function is ignored by spi_nor_parse_bfpt(). Make sure we
3591          * disable it.
3592          */
3593         params->quad_enable = NULL;
3594 }
3595
3596 static struct spi_nor_fixups mt35xu512aba_fixups = {
3597         .default_init = mt35xu512aba_default_init,
3598         .post_sfdp = mt35xu512aba_post_sfdp_fixup,
3599 };
3600 #endif /* CONFIG_SPI_FLASH_MT35XU */
3601
3602 #if CONFIG_IS_ENABLED(SPI_FLASH_MACRONIX)
3603 /**
3604  * spi_nor_macronix_octal_dtr_enable() - Enable octal DTR on Macronix flashes.
3605  * @nor:        pointer to a 'struct spi_nor'
3606  *
3607  * Set Macronix max dummy cycles 20 to allow the flash to run at fastest frequency.
3608  *
3609  * Return: 0 on success, -errno otherwise.
3610  */
3611 static int spi_nor_macronix_octal_dtr_enable(struct spi_nor *nor)
3612 {
3613         struct spi_mem_op op;
3614         int ret;
3615         u8 buf;
3616
3617         ret = write_enable(nor);
3618         if (ret)
3619                 return ret;
3620
3621         buf = SPINOR_REG_MXIC_DC_20;
3622         op = (struct spi_mem_op)
3623                 SPI_MEM_OP(SPI_MEM_OP_CMD(SPINOR_OP_WR_CR2, 1),
3624                            SPI_MEM_OP_ADDR(4, SPINOR_REG_MXIC_CR2_DC, 1),
3625                            SPI_MEM_OP_NO_DUMMY,
3626                            SPI_MEM_OP_DATA_OUT(1, &buf, 1));
3627
3628         ret = spi_mem_exec_op(nor->spi, &op);
3629         if (ret)
3630                 return ret;
3631
3632         ret = spi_nor_wait_till_ready(nor);
3633         if (ret)
3634                 return ret;
3635
3636         nor->read_dummy = MXIC_MAX_DC;
3637         ret = write_enable(nor);
3638         if (ret)
3639                 return ret;
3640
3641         buf = SPINOR_REG_MXIC_OPI_DTR_EN;
3642         op = (struct spi_mem_op)
3643                 SPI_MEM_OP(SPI_MEM_OP_CMD(SPINOR_OP_WR_CR2, 1),
3644                            SPI_MEM_OP_ADDR(4, SPINOR_REG_MXIC_CR2_MODE, 1),
3645                            SPI_MEM_OP_NO_DUMMY,
3646                            SPI_MEM_OP_DATA_OUT(1, &buf, 1));
3647
3648         ret = spi_mem_exec_op(nor->spi, &op);
3649         if (ret) {
3650                 dev_err(nor->dev, "Failed to enable octal DTR mode\n");
3651                 return ret;
3652         }
3653         nor->reg_proto = SNOR_PROTO_8_8_8_DTR;
3654
3655         return 0;
3656 }
3657
3658 static void macronix_octal_default_init(struct spi_nor *nor)
3659 {
3660         nor->octal_dtr_enable = spi_nor_macronix_octal_dtr_enable;
3661 }
3662
3663 static void macronix_octal_post_sfdp_fixup(struct spi_nor *nor,
3664                                          struct spi_nor_flash_parameter *params)
3665 {
3666         /*
3667          * Adding SNOR_HWCAPS_PP_8_8_8_DTR in hwcaps.mask when
3668          * SPI_NOR_OCTAL_DTR_READ flag exists.
3669          */
3670         if (params->hwcaps.mask & SNOR_HWCAPS_READ_8_8_8_DTR)
3671                 params->hwcaps.mask |= SNOR_HWCAPS_PP_8_8_8_DTR;
3672 }
3673
3674 static struct spi_nor_fixups macronix_octal_fixups = {
3675         .default_init = macronix_octal_default_init,
3676         .post_sfdp = macronix_octal_post_sfdp_fixup,
3677 };
3678 #endif /* CONFIG_SPI_FLASH_MACRONIX */
3679
3680 /** spi_nor_octal_dtr_enable() - enable Octal DTR I/O if needed
3681  * @nor:                 pointer to a 'struct spi_nor'
3682  *
3683  * Return: 0 on success, -errno otherwise.
3684  */
3685 static int spi_nor_octal_dtr_enable(struct spi_nor *nor)
3686 {
3687         int ret;
3688
3689         if (!nor->octal_dtr_enable)
3690                 return 0;
3691
3692         if (!(nor->read_proto == SNOR_PROTO_8_8_8_DTR &&
3693               nor->write_proto == SNOR_PROTO_8_8_8_DTR))
3694                 return 0;
3695
3696         if (!(nor->flags & SNOR_F_IO_MODE_EN_VOLATILE))
3697                 return 0;
3698
3699         ret = nor->octal_dtr_enable(nor);
3700         if (ret)
3701                 return ret;
3702
3703         nor->reg_proto = SNOR_PROTO_8_8_8_DTR;
3704
3705         return 0;
3706 }
3707
3708 static int spi_nor_init(struct spi_nor *nor)
3709 {
3710         int err;
3711
3712         err = spi_nor_octal_dtr_enable(nor);
3713         if (err) {
3714                 dev_dbg(nor->dev, "Octal DTR mode not supported\n");
3715                 return err;
3716         }
3717
3718         /*
3719          * Atmel, SST, Intel/Numonyx, and others serial NOR tend to power up
3720          * with the software protection bits set
3721          */
3722         if (IS_ENABLED(CONFIG_SPI_FLASH_UNLOCK_ALL) &&
3723             (JEDEC_MFR(nor->info) == SNOR_MFR_ATMEL ||
3724              JEDEC_MFR(nor->info) == SNOR_MFR_INTEL ||
3725              JEDEC_MFR(nor->info) == SNOR_MFR_SST ||
3726              nor->info->flags & SPI_NOR_HAS_LOCK)) {
3727                 write_enable(nor);
3728                 write_sr(nor, 0);
3729                 spi_nor_wait_till_ready(nor);
3730         }
3731
3732         if (nor->quad_enable) {
3733                 err = nor->quad_enable(nor);
3734                 if (err) {
3735                         dev_dbg(nor->dev, "quad mode not supported\n");
3736                         return err;
3737                 }
3738         }
3739
3740         if (nor->addr_width == 4 &&
3741             !(nor->info->flags & SPI_NOR_OCTAL_DTR_READ) &&
3742             (JEDEC_MFR(nor->info) != SNOR_MFR_SPANSION) &&
3743             !(nor->info->flags & SPI_NOR_4B_OPCODES)) {
3744                 /*
3745                  * If the RESET# pin isn't hooked up properly, or the system
3746                  * otherwise doesn't perform a reset command in the boot
3747                  * sequence, it's impossible to 100% protect against unexpected
3748                  * reboots (e.g., crashes). Warn the user (or hopefully, system
3749                  * designer) that this is bad.
3750                  */
3751                 if (nor->flags & SNOR_F_BROKEN_RESET)
3752                         debug("enabling reset hack; may not recover from unexpected reboots\n");
3753                 set_4byte(nor, nor->info, 1);
3754         }
3755
3756         return 0;
3757 }
3758
3759 #ifdef CONFIG_SPI_FLASH_SOFT_RESET
3760 /**
3761  * spi_nor_soft_reset() - perform the JEDEC Software Reset sequence
3762  * @nor:        the spi_nor structure
3763  *
3764  * This function can be used to switch from Octal DTR mode to legacy mode on a
3765  * flash that supports it. The soft reset is executed in Octal DTR mode.
3766  *
3767  * Return: 0 for success, -errno for failure.
3768  */
3769 static int spi_nor_soft_reset(struct spi_nor *nor)
3770 {
3771         struct spi_mem_op op;
3772         int ret;
3773         enum spi_nor_cmd_ext ext;
3774
3775         ext = nor->cmd_ext_type;
3776         if (nor->cmd_ext_type == SPI_NOR_EXT_NONE) {
3777                 nor->cmd_ext_type = SPI_NOR_EXT_REPEAT;
3778 #if CONFIG_IS_ENABLED(SPI_NOR_BOOT_SOFT_RESET_EXT_INVERT)
3779                 nor->cmd_ext_type = SPI_NOR_EXT_INVERT;
3780 #endif /* SPI_NOR_BOOT_SOFT_RESET_EXT_INVERT */
3781         }
3782
3783         op = (struct spi_mem_op)SPI_MEM_OP(SPI_MEM_OP_CMD(SPINOR_OP_SRSTEN, 0),
3784                         SPI_MEM_OP_NO_DUMMY,
3785                         SPI_MEM_OP_NO_ADDR,
3786                         SPI_MEM_OP_NO_DATA);
3787         spi_nor_setup_op(nor, &op, SNOR_PROTO_8_8_8_DTR);
3788         ret = spi_mem_exec_op(nor->spi, &op);
3789         if (ret) {
3790                 dev_warn(nor->dev, "Software reset enable failed: %d\n", ret);
3791                 goto out;
3792         }
3793
3794         op = (struct spi_mem_op)SPI_MEM_OP(SPI_MEM_OP_CMD(SPINOR_OP_SRST, 0),
3795                         SPI_MEM_OP_NO_DUMMY,
3796                         SPI_MEM_OP_NO_ADDR,
3797                         SPI_MEM_OP_NO_DATA);
3798         spi_nor_setup_op(nor, &op, SNOR_PROTO_8_8_8_DTR);
3799         ret = spi_mem_exec_op(nor->spi, &op);
3800         if (ret) {
3801                 dev_warn(nor->dev, "Software reset failed: %d\n", ret);
3802                 goto out;
3803         }
3804
3805         /*
3806          * Software Reset is not instant, and the delay varies from flash to
3807          * flash. Looking at a few flashes, most range somewhere below 100
3808          * microseconds. So, wait for 200ms just to be sure.
3809          */
3810         udelay(SPI_NOR_SRST_SLEEP_LEN);
3811
3812 out:
3813         nor->cmd_ext_type = ext;
3814         return ret;
3815 }
3816 #endif /* CONFIG_SPI_FLASH_SOFT_RESET */
3817
3818 int spi_nor_remove(struct spi_nor *nor)
3819 {
3820 #ifdef CONFIG_SPI_FLASH_SOFT_RESET
3821         if (nor->info->flags & SPI_NOR_OCTAL_DTR_READ &&
3822             nor->flags & SNOR_F_SOFT_RESET)
3823                 return spi_nor_soft_reset(nor);
3824 #endif
3825
3826         return 0;
3827 }
3828
3829 void spi_nor_set_fixups(struct spi_nor *nor)
3830 {
3831 #ifdef CONFIG_SPI_FLASH_SPANSION
3832         if (JEDEC_MFR(nor->info) == SNOR_MFR_CYPRESS) {
3833                 switch (nor->info->id[1]) {
3834                 case 0x2a: /* S25HL (QSPI, 3.3V) */
3835                 case 0x2b: /* S25HS (QSPI, 1.8V) */
3836                         nor->fixups = &s25hx_t_fixups;
3837                         break;
3838
3839 #ifdef CONFIG_SPI_FLASH_S28HX_T
3840                 case 0x5a: /* S28HL (Octal, 3.3V) */
3841                 case 0x5b: /* S28HS (Octal, 1.8V) */
3842                         nor->fixups = &s28hx_t_fixups;
3843                         break;
3844 #endif
3845
3846                 default:
3847                         break;
3848                 }
3849         }
3850
3851         if (CONFIG_IS_ENABLED(SPI_FLASH_BAR) &&
3852             !strcmp(nor->info->name, "s25fl256l"))
3853                 nor->fixups = &s25fl256l_fixups;
3854 #endif
3855
3856 #ifdef CONFIG_SPI_FLASH_MT35XU
3857         if (!strcmp(nor->info->name, "mt35xu512aba"))
3858                 nor->fixups = &mt35xu512aba_fixups;
3859 #endif
3860
3861 #if CONFIG_IS_ENABLED(SPI_FLASH_MACRONIX)
3862         nor->fixups = &macronix_octal_fixups;
3863 #endif /* SPI_FLASH_MACRONIX */
3864 }
3865
3866 int spi_nor_scan(struct spi_nor *nor)
3867 {
3868         struct spi_nor_flash_parameter params;
3869         const struct flash_info *info = NULL;
3870         struct mtd_info *mtd = &nor->mtd;
3871         struct spi_slave *spi = nor->spi;
3872         int ret;
3873         int cfi_mtd_nb = 0;
3874
3875 #ifdef CONFIG_FLASH_CFI_MTD
3876         cfi_mtd_nb = CFI_FLASH_BANKS;
3877 #endif
3878
3879         /* Reset SPI protocol for all commands. */
3880         nor->reg_proto = SNOR_PROTO_1_1_1;
3881         nor->read_proto = SNOR_PROTO_1_1_1;
3882         nor->write_proto = SNOR_PROTO_1_1_1;
3883         nor->read = spi_nor_read_data;
3884         nor->write = spi_nor_write_data;
3885         nor->read_reg = spi_nor_read_reg;
3886         nor->write_reg = spi_nor_write_reg;
3887
3888         nor->setup = spi_nor_default_setup;
3889
3890 #ifdef CONFIG_SPI_FLASH_SOFT_RESET_ON_BOOT
3891         /*
3892          * When the flash is handed to us in a stateful mode like 8D-8D-8D, it
3893          * is difficult to detect the mode the flash is in. One option is to
3894          * read SFDP in all modes and see which one gives the correct "SFDP"
3895          * signature, but not all flashes support SFDP in 8D-8D-8D mode.
3896          *
3897          * Further, even if you detect the mode of the flash via SFDP, you
3898          * still have the problem of actually reading the ID. The Read ID
3899          * command is not standardized across flash vendors. Flashes can have
3900          * different dummy cycles needed for reading the ID. Some flashes even
3901          * expect a 4-byte dummy address with the Read ID command. All this
3902          * information cannot be obtained from the SFDP table.
3903          *
3904          * So, perform a Software Reset sequence before reading the ID and
3905          * initializing the flash. A Soft Reset will bring back the flash in
3906          * its default protocol mode assuming no non-volatile configuration was
3907          * set. This will let us detect the flash even if ROM hands it to us in
3908          * Octal DTR mode.
3909          *
3910          * To accommodate cases where there is more than one flash on a board,
3911          * and only one of them needs a soft reset, failure to reset is not
3912          * made fatal, and we still try to read ID if possible.
3913          */
3914         spi_nor_soft_reset(nor);
3915 #endif /* CONFIG_SPI_FLASH_SOFT_RESET_ON_BOOT */
3916
3917         info = spi_nor_read_id(nor);
3918         if (IS_ERR_OR_NULL(info))
3919                 return -ENOENT;
3920         nor->info = info;
3921
3922         spi_nor_set_fixups(nor);
3923
3924         /* Parse the Serial Flash Discoverable Parameters table. */
3925         ret = spi_nor_init_params(nor, info, &params);
3926         if (ret)
3927                 return ret;
3928
3929         if (!mtd->name) {
3930                 sprintf(nor->mtd_name, "%s%d",
3931                         MTD_DEV_TYPE(MTD_DEV_TYPE_NOR),
3932                         cfi_mtd_nb + dev_seq(nor->dev));
3933                 mtd->name = nor->mtd_name;
3934         }
3935         mtd->dev = nor->dev;
3936         mtd->priv = nor;
3937         mtd->type = MTD_NORFLASH;
3938         mtd->writesize = 1;
3939         mtd->flags = MTD_CAP_NORFLASH;
3940         mtd->size = params.size;
3941         mtd->_erase = spi_nor_erase;
3942         mtd->_read = spi_nor_read;
3943         mtd->_write = spi_nor_write;
3944
3945 #if defined(CONFIG_SPI_FLASH_STMICRO) || defined(CONFIG_SPI_FLASH_SST)
3946         /* NOR protection support for STmicro/Micron chips and similar */
3947         if (JEDEC_MFR(info) == SNOR_MFR_ST ||
3948             JEDEC_MFR(info) == SNOR_MFR_MICRON ||
3949             JEDEC_MFR(info) == SNOR_MFR_SST ||
3950                         info->flags & SPI_NOR_HAS_LOCK) {
3951                 nor->flash_lock = stm_lock;
3952                 nor->flash_unlock = stm_unlock;
3953                 nor->flash_is_unlocked = stm_is_unlocked;
3954         }
3955 #endif
3956
3957 #ifdef CONFIG_SPI_FLASH_SST
3958         /*
3959          * sst26 series block protection implementation differs from other
3960          * series.
3961          */
3962         if (info->flags & SPI_NOR_HAS_SST26LOCK) {
3963                 nor->flash_lock = sst26_lock;
3964                 nor->flash_unlock = sst26_unlock;
3965                 nor->flash_is_unlocked = sst26_is_unlocked;
3966         }
3967 #endif
3968
3969         if (info->flags & USE_FSR)
3970                 nor->flags |= SNOR_F_USE_FSR;
3971         if (info->flags & SPI_NOR_HAS_TB)
3972                 nor->flags |= SNOR_F_HAS_SR_TB;
3973         if (info->flags & NO_CHIP_ERASE)
3974                 nor->flags |= SNOR_F_NO_OP_CHIP_ERASE;
3975         if (info->flags & USE_CLSR)
3976                 nor->flags |= SNOR_F_USE_CLSR;
3977
3978         if (info->flags & SPI_NOR_NO_ERASE)
3979                 mtd->flags |= MTD_NO_ERASE;
3980
3981         nor->page_size = params.page_size;
3982         mtd->writebufsize = nor->page_size;
3983
3984         /* Some devices cannot do fast-read, no matter what DT tells us */
3985         if ((info->flags & SPI_NOR_NO_FR) || (spi->mode & SPI_RX_SLOW))
3986                 params.hwcaps.mask &= ~SNOR_HWCAPS_READ_FAST;
3987
3988         /*
3989          * Configure the SPI memory:
3990          * - select op codes for (Fast) Read, Page Program and Sector Erase.
3991          * - set the number of dummy cycles (mode cycles + wait states).
3992          * - set the SPI protocols for register and memory accesses.
3993          * - set the Quad Enable bit if needed (required by SPI x-y-4 protos).
3994          */
3995         ret = spi_nor_setup(nor, info, &params);
3996         if (ret)
3997                 return ret;
3998
3999         if (spi_nor_protocol_is_dtr(nor->read_proto)) {
4000                  /* Always use 4-byte addresses in DTR mode. */
4001                 nor->addr_width = 4;
4002         } else if (nor->addr_width) {
4003                 /* already configured from SFDP */
4004         } else if (info->addr_width) {
4005                 nor->addr_width = info->addr_width;
4006         } else {
4007                 nor->addr_width = 3;
4008         }
4009
4010         if (nor->addr_width == 3 && mtd->size > SZ_16M) {
4011 #ifndef CONFIG_SPI_FLASH_BAR
4012                 /* enable 4-byte addressing if the device exceeds 16MiB */
4013                 nor->addr_width = 4;
4014                 if (JEDEC_MFR(info) == SNOR_MFR_SPANSION ||
4015                     info->flags & SPI_NOR_4B_OPCODES)
4016                         spi_nor_set_4byte_opcodes(nor, info);
4017 #else
4018         /* Configure the BAR - discover bank cmds and read current bank */
4019         nor->addr_width = 3;
4020         ret = read_bar(nor, info);
4021         if (ret < 0)
4022                 return ret;
4023 #endif
4024         }
4025
4026         if (nor->addr_width > SPI_NOR_MAX_ADDR_WIDTH) {
4027                 dev_dbg(nor->dev, "address width is too large: %u\n",
4028                         nor->addr_width);
4029                 return -EINVAL;
4030         }
4031
4032         /* Send all the required SPI flash commands to initialize device */
4033         ret = spi_nor_init(nor);
4034         if (ret)
4035                 return ret;
4036
4037         nor->rdsr_dummy = params.rdsr_dummy;
4038         nor->rdsr_addr_nbytes = params.rdsr_addr_nbytes;
4039         nor->name = info->name;
4040         nor->size = mtd->size;
4041         nor->erase_size = mtd->erasesize;
4042         nor->sector_size = mtd->erasesize;
4043
4044 #ifndef CONFIG_SPL_BUILD
4045         printf("SF: Detected %s with page size ", nor->name);
4046         print_size(nor->page_size, ", erase size ");
4047         print_size(nor->erase_size, ", total ");
4048         print_size(nor->size, "");
4049         puts("\n");
4050 #endif
4051
4052         return 0;
4053 }
4054
4055 /* U-Boot specific functions, need to extend MTD to support these */
4056 int spi_flash_cmd_get_sw_write_prot(struct spi_nor *nor)
4057 {
4058         int sr = read_sr(nor);
4059
4060         if (sr < 0)
4061                 return sr;
4062
4063         return (sr >> 2) & 7;
4064 }