mtd: spi-nor-core: Introduce flash-specific fixup hooks
[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 <log.h>
14 #include <watchdog.h>
15 #include <dm.h>
16 #include <dm/device_compat.h>
17 #include <dm/devres.h>
18 #include <linux/bitops.h>
19 #include <linux/err.h>
20 #include <linux/errno.h>
21 #include <linux/log2.h>
22 #include <linux/math64.h>
23 #include <linux/sizes.h>
24
25 #include <linux/mtd/mtd.h>
26 #include <linux/mtd/spi-nor.h>
27 #include <spi-mem.h>
28 #include <spi.h>
29
30 #include "sf_internal.h"
31
32 /* Define max times to check status register before we give up. */
33
34 /*
35  * For everything but full-chip erase; probably could be much smaller, but kept
36  * around for safety for now
37  */
38
39 #define HZ                                      CONFIG_SYS_HZ
40
41 #define DEFAULT_READY_WAIT_JIFFIES              (40UL * HZ)
42
43 struct sfdp_parameter_header {
44         u8              id_lsb;
45         u8              minor;
46         u8              major;
47         u8              length; /* in double words */
48         u8              parameter_table_pointer[3]; /* byte address */
49         u8              id_msb;
50 };
51
52 #define SFDP_PARAM_HEADER_ID(p) (((p)->id_msb << 8) | (p)->id_lsb)
53 #define SFDP_PARAM_HEADER_PTP(p) \
54         (((p)->parameter_table_pointer[2] << 16) | \
55          ((p)->parameter_table_pointer[1] <<  8) | \
56          ((p)->parameter_table_pointer[0] <<  0))
57
58 #define SFDP_BFPT_ID            0xff00  /* Basic Flash Parameter Table */
59 #define SFDP_SECTOR_MAP_ID      0xff81  /* Sector Map Table */
60 #define SFDP_SST_ID             0x01bf  /* Manufacturer specific Table */
61
62 #define SFDP_SIGNATURE          0x50444653U
63 #define SFDP_JESD216_MAJOR      1
64 #define SFDP_JESD216_MINOR      0
65 #define SFDP_JESD216A_MINOR     5
66 #define SFDP_JESD216B_MINOR     6
67
68 struct sfdp_header {
69         u32             signature; /* Ox50444653U <=> "SFDP" */
70         u8              minor;
71         u8              major;
72         u8              nph; /* 0-base number of parameter headers */
73         u8              unused;
74
75         /* Basic Flash Parameter Table. */
76         struct sfdp_parameter_header    bfpt_header;
77 };
78
79 /* Basic Flash Parameter Table */
80
81 /*
82  * JESD216 rev B defines a Basic Flash Parameter Table of 16 DWORDs.
83  * They are indexed from 1 but C arrays are indexed from 0.
84  */
85 #define BFPT_DWORD(i)           ((i) - 1)
86 #define BFPT_DWORD_MAX          16
87
88 /* The first version of JESB216 defined only 9 DWORDs. */
89 #define BFPT_DWORD_MAX_JESD216                  9
90
91 /* 1st DWORD. */
92 #define BFPT_DWORD1_FAST_READ_1_1_2             BIT(16)
93 #define BFPT_DWORD1_ADDRESS_BYTES_MASK          GENMASK(18, 17)
94 #define BFPT_DWORD1_ADDRESS_BYTES_3_ONLY        (0x0UL << 17)
95 #define BFPT_DWORD1_ADDRESS_BYTES_3_OR_4        (0x1UL << 17)
96 #define BFPT_DWORD1_ADDRESS_BYTES_4_ONLY        (0x2UL << 17)
97 #define BFPT_DWORD1_DTR                         BIT(19)
98 #define BFPT_DWORD1_FAST_READ_1_2_2             BIT(20)
99 #define BFPT_DWORD1_FAST_READ_1_4_4             BIT(21)
100 #define BFPT_DWORD1_FAST_READ_1_1_4             BIT(22)
101
102 /* 5th DWORD. */
103 #define BFPT_DWORD5_FAST_READ_2_2_2             BIT(0)
104 #define BFPT_DWORD5_FAST_READ_4_4_4             BIT(4)
105
106 /* 11th DWORD. */
107 #define BFPT_DWORD11_PAGE_SIZE_SHIFT            4
108 #define BFPT_DWORD11_PAGE_SIZE_MASK             GENMASK(7, 4)
109
110 /* 15th DWORD. */
111
112 /*
113  * (from JESD216 rev B)
114  * Quad Enable Requirements (QER):
115  * - 000b: Device does not have a QE bit. Device detects 1-1-4 and 1-4-4
116  *         reads based on instruction. DQ3/HOLD# functions are hold during
117  *         instruction phase.
118  * - 001b: QE is bit 1 of status register 2. It is set via Write Status with
119  *         two data bytes where bit 1 of the second byte is one.
120  *         [...]
121  *         Writing only one byte to the status register has the side-effect of
122  *         clearing status register 2, including the QE bit. The 100b code is
123  *         used if writing one byte to the status register does not modify
124  *         status register 2.
125  * - 010b: QE is bit 6 of status register 1. It is set via Write Status with
126  *         one data byte where bit 6 is one.
127  *         [...]
128  * - 011b: QE is bit 7 of status register 2. It is set via Write status
129  *         register 2 instruction 3Eh with one data byte where bit 7 is one.
130  *         [...]
131  *         The status register 2 is read using instruction 3Fh.
132  * - 100b: QE is bit 1 of status register 2. It is set via Write Status with
133  *         two data bytes where bit 1 of the second byte is one.
134  *         [...]
135  *         In contrast to the 001b code, writing one byte to the status
136  *         register does not modify status register 2.
137  * - 101b: QE is bit 1 of status register 2. Status register 1 is read using
138  *         Read Status instruction 05h. Status register2 is read using
139  *         instruction 35h. QE is set via Writ Status instruction 01h with
140  *         two data bytes where bit 1 of the second byte is one.
141  *         [...]
142  */
143 #define BFPT_DWORD15_QER_MASK                   GENMASK(22, 20)
144 #define BFPT_DWORD15_QER_NONE                   (0x0UL << 20) /* Micron */
145 #define BFPT_DWORD15_QER_SR2_BIT1_BUGGY         (0x1UL << 20)
146 #define BFPT_DWORD15_QER_SR1_BIT6               (0x2UL << 20) /* Macronix */
147 #define BFPT_DWORD15_QER_SR2_BIT7               (0x3UL << 20)
148 #define BFPT_DWORD15_QER_SR2_BIT1_NO_RD         (0x4UL << 20)
149 #define BFPT_DWORD15_QER_SR2_BIT1               (0x5UL << 20) /* Spansion */
150
151 struct sfdp_bfpt {
152         u32     dwords[BFPT_DWORD_MAX];
153 };
154
155 /**
156  * struct spi_nor_fixups - SPI NOR fixup hooks
157  * @default_init: called after default flash parameters init. Used to tweak
158  *                flash parameters when information provided by the flash_info
159  *                table is incomplete or wrong.
160  * @post_bfpt: called after the BFPT table has been parsed
161  * @post_sfdp: called after SFDP has been parsed (is also called for SPI NORs
162  *             that do not support RDSFDP). Typically used to tweak various
163  *             parameters that could not be extracted by other means (i.e.
164  *             when information provided by the SFDP/flash_info tables are
165  *             incomplete or wrong).
166  *
167  * Those hooks can be used to tweak the SPI NOR configuration when the SFDP
168  * table is broken or not available.
169  */
170 struct spi_nor_fixups {
171         void (*default_init)(struct spi_nor *nor);
172         int (*post_bfpt)(struct spi_nor *nor,
173                          const struct sfdp_parameter_header *bfpt_header,
174                          const struct sfdp_bfpt *bfpt,
175                          struct spi_nor_flash_parameter *params);
176         void (*post_sfdp)(struct spi_nor *nor,
177                           struct spi_nor_flash_parameter *params);
178 };
179
180 static int spi_nor_read_write_reg(struct spi_nor *nor, struct spi_mem_op
181                 *op, void *buf)
182 {
183         if (op->data.dir == SPI_MEM_DATA_IN)
184                 op->data.buf.in = buf;
185         else
186                 op->data.buf.out = buf;
187         return spi_mem_exec_op(nor->spi, op);
188 }
189
190 static int spi_nor_read_reg(struct spi_nor *nor, u8 code, u8 *val, int len)
191 {
192         struct spi_mem_op op = SPI_MEM_OP(SPI_MEM_OP_CMD(code, 1),
193                                           SPI_MEM_OP_NO_ADDR,
194                                           SPI_MEM_OP_NO_DUMMY,
195                                           SPI_MEM_OP_DATA_IN(len, NULL, 1));
196         int ret;
197
198         ret = spi_nor_read_write_reg(nor, &op, val);
199         if (ret < 0)
200                 dev_dbg(nor->dev, "error %d reading %x\n", ret, code);
201
202         return ret;
203 }
204
205 static int spi_nor_write_reg(struct spi_nor *nor, u8 opcode, u8 *buf, int len)
206 {
207         struct spi_mem_op op = SPI_MEM_OP(SPI_MEM_OP_CMD(opcode, 1),
208                                           SPI_MEM_OP_NO_ADDR,
209                                           SPI_MEM_OP_NO_DUMMY,
210                                           SPI_MEM_OP_DATA_OUT(len, NULL, 1));
211
212         return spi_nor_read_write_reg(nor, &op, buf);
213 }
214
215 static ssize_t spi_nor_read_data(struct spi_nor *nor, loff_t from, size_t len,
216                                  u_char *buf)
217 {
218         struct spi_mem_op op =
219                         SPI_MEM_OP(SPI_MEM_OP_CMD(nor->read_opcode, 1),
220                                    SPI_MEM_OP_ADDR(nor->addr_width, from, 1),
221                                    SPI_MEM_OP_DUMMY(nor->read_dummy, 1),
222                                    SPI_MEM_OP_DATA_IN(len, buf, 1));
223         size_t remaining = len;
224         int ret;
225
226         /* get transfer protocols. */
227         op.cmd.buswidth = spi_nor_get_protocol_inst_nbits(nor->read_proto);
228         op.addr.buswidth = spi_nor_get_protocol_addr_nbits(nor->read_proto);
229         op.dummy.buswidth = op.addr.buswidth;
230         op.data.buswidth = spi_nor_get_protocol_data_nbits(nor->read_proto);
231
232         /* convert the dummy cycles to the number of bytes */
233         op.dummy.nbytes = (nor->read_dummy * op.dummy.buswidth) / 8;
234
235         while (remaining) {
236                 op.data.nbytes = remaining < UINT_MAX ? remaining : UINT_MAX;
237                 ret = spi_mem_adjust_op_size(nor->spi, &op);
238                 if (ret)
239                         return ret;
240
241                 ret = spi_mem_exec_op(nor->spi, &op);
242                 if (ret)
243                         return ret;
244
245                 op.addr.val += op.data.nbytes;
246                 remaining -= op.data.nbytes;
247                 op.data.buf.in += op.data.nbytes;
248         }
249
250         return len;
251 }
252
253 static ssize_t spi_nor_write_data(struct spi_nor *nor, loff_t to, size_t len,
254                                   const u_char *buf)
255 {
256         struct spi_mem_op op =
257                         SPI_MEM_OP(SPI_MEM_OP_CMD(nor->program_opcode, 1),
258                                    SPI_MEM_OP_ADDR(nor->addr_width, to, 1),
259                                    SPI_MEM_OP_NO_DUMMY,
260                                    SPI_MEM_OP_DATA_OUT(len, buf, 1));
261         int ret;
262
263         /* get transfer protocols. */
264         op.cmd.buswidth = spi_nor_get_protocol_inst_nbits(nor->write_proto);
265         op.addr.buswidth = spi_nor_get_protocol_addr_nbits(nor->write_proto);
266         op.data.buswidth = spi_nor_get_protocol_data_nbits(nor->write_proto);
267
268         if (nor->program_opcode == SPINOR_OP_AAI_WP && nor->sst_write_second)
269                 op.addr.nbytes = 0;
270
271         ret = spi_mem_adjust_op_size(nor->spi, &op);
272         if (ret)
273                 return ret;
274         op.data.nbytes = len < op.data.nbytes ? len : op.data.nbytes;
275
276         ret = spi_mem_exec_op(nor->spi, &op);
277         if (ret)
278                 return ret;
279
280         return op.data.nbytes;
281 }
282
283 /*
284  * Read the status register, returning its value in the location
285  * Return the status register value.
286  * Returns negative if error occurred.
287  */
288 static int read_sr(struct spi_nor *nor)
289 {
290         int ret;
291         u8 val;
292
293         ret = nor->read_reg(nor, SPINOR_OP_RDSR, &val, 1);
294         if (ret < 0) {
295                 pr_debug("error %d reading SR\n", (int)ret);
296                 return ret;
297         }
298
299         return val;
300 }
301
302 /*
303  * Read the flag status register, returning its value in the location
304  * Return the status register value.
305  * Returns negative if error occurred.
306  */
307 static int read_fsr(struct spi_nor *nor)
308 {
309         int ret;
310         u8 val;
311
312         ret = nor->read_reg(nor, SPINOR_OP_RDFSR, &val, 1);
313         if (ret < 0) {
314                 pr_debug("error %d reading FSR\n", ret);
315                 return ret;
316         }
317
318         return val;
319 }
320
321 /*
322  * Read configuration register, returning its value in the
323  * location. Return the configuration register value.
324  * Returns negative if error occurred.
325  */
326 #if defined(CONFIG_SPI_FLASH_SPANSION) || defined(CONFIG_SPI_FLASH_WINBOND)
327 static int read_cr(struct spi_nor *nor)
328 {
329         int ret;
330         u8 val;
331
332         ret = nor->read_reg(nor, SPINOR_OP_RDCR, &val, 1);
333         if (ret < 0) {
334                 dev_dbg(nor->dev, "error %d reading CR\n", ret);
335                 return ret;
336         }
337
338         return val;
339 }
340 #endif
341
342 /*
343  * Write status register 1 byte
344  * Returns negative if error occurred.
345  */
346 static int write_sr(struct spi_nor *nor, u8 val)
347 {
348         nor->cmd_buf[0] = val;
349         return nor->write_reg(nor, SPINOR_OP_WRSR, nor->cmd_buf, 1);
350 }
351
352 /*
353  * Set write enable latch with Write Enable command.
354  * Returns negative if error occurred.
355  */
356 static int write_enable(struct spi_nor *nor)
357 {
358         return nor->write_reg(nor, SPINOR_OP_WREN, NULL, 0);
359 }
360
361 /*
362  * Send write disable instruction to the chip.
363  */
364 static int write_disable(struct spi_nor *nor)
365 {
366         return nor->write_reg(nor, SPINOR_OP_WRDI, NULL, 0);
367 }
368
369 static struct spi_nor *mtd_to_spi_nor(struct mtd_info *mtd)
370 {
371         return mtd->priv;
372 }
373
374 #ifndef CONFIG_SPI_FLASH_BAR
375 static u8 spi_nor_convert_opcode(u8 opcode, const u8 table[][2], size_t size)
376 {
377         size_t i;
378
379         for (i = 0; i < size; i++)
380                 if (table[i][0] == opcode)
381                         return table[i][1];
382
383         /* No conversion found, keep input op code. */
384         return opcode;
385 }
386
387 static u8 spi_nor_convert_3to4_read(u8 opcode)
388 {
389         static const u8 spi_nor_3to4_read[][2] = {
390                 { SPINOR_OP_READ,       SPINOR_OP_READ_4B },
391                 { SPINOR_OP_READ_FAST,  SPINOR_OP_READ_FAST_4B },
392                 { SPINOR_OP_READ_1_1_2, SPINOR_OP_READ_1_1_2_4B },
393                 { SPINOR_OP_READ_1_2_2, SPINOR_OP_READ_1_2_2_4B },
394                 { SPINOR_OP_READ_1_1_4, SPINOR_OP_READ_1_1_4_4B },
395                 { SPINOR_OP_READ_1_4_4, SPINOR_OP_READ_1_4_4_4B },
396                 { SPINOR_OP_READ_1_1_8, SPINOR_OP_READ_1_1_8_4B },
397                 { SPINOR_OP_READ_1_8_8, SPINOR_OP_READ_1_8_8_4B },
398
399                 { SPINOR_OP_READ_1_1_1_DTR,     SPINOR_OP_READ_1_1_1_DTR_4B },
400                 { SPINOR_OP_READ_1_2_2_DTR,     SPINOR_OP_READ_1_2_2_DTR_4B },
401                 { SPINOR_OP_READ_1_4_4_DTR,     SPINOR_OP_READ_1_4_4_DTR_4B },
402         };
403
404         return spi_nor_convert_opcode(opcode, spi_nor_3to4_read,
405                                       ARRAY_SIZE(spi_nor_3to4_read));
406 }
407
408 static u8 spi_nor_convert_3to4_program(u8 opcode)
409 {
410         static const u8 spi_nor_3to4_program[][2] = {
411                 { SPINOR_OP_PP,         SPINOR_OP_PP_4B },
412                 { SPINOR_OP_PP_1_1_4,   SPINOR_OP_PP_1_1_4_4B },
413                 { SPINOR_OP_PP_1_4_4,   SPINOR_OP_PP_1_4_4_4B },
414                 { SPINOR_OP_PP_1_1_8,   SPINOR_OP_PP_1_1_8_4B },
415                 { SPINOR_OP_PP_1_8_8,   SPINOR_OP_PP_1_8_8_4B },
416         };
417
418         return spi_nor_convert_opcode(opcode, spi_nor_3to4_program,
419                                       ARRAY_SIZE(spi_nor_3to4_program));
420 }
421
422 static u8 spi_nor_convert_3to4_erase(u8 opcode)
423 {
424         static const u8 spi_nor_3to4_erase[][2] = {
425                 { SPINOR_OP_BE_4K,      SPINOR_OP_BE_4K_4B },
426                 { SPINOR_OP_BE_32K,     SPINOR_OP_BE_32K_4B },
427                 { SPINOR_OP_SE,         SPINOR_OP_SE_4B },
428         };
429
430         return spi_nor_convert_opcode(opcode, spi_nor_3to4_erase,
431                                       ARRAY_SIZE(spi_nor_3to4_erase));
432 }
433
434 static void spi_nor_set_4byte_opcodes(struct spi_nor *nor,
435                                       const struct flash_info *info)
436 {
437         /* Do some manufacturer fixups first */
438         switch (JEDEC_MFR(info)) {
439         case SNOR_MFR_SPANSION:
440                 /* No small sector erase for 4-byte command set */
441                 nor->erase_opcode = SPINOR_OP_SE;
442                 nor->mtd.erasesize = info->sector_size;
443                 break;
444
445         default:
446                 break;
447         }
448
449         nor->read_opcode = spi_nor_convert_3to4_read(nor->read_opcode);
450         nor->program_opcode = spi_nor_convert_3to4_program(nor->program_opcode);
451         nor->erase_opcode = spi_nor_convert_3to4_erase(nor->erase_opcode);
452 }
453 #endif /* !CONFIG_SPI_FLASH_BAR */
454
455 /* Enable/disable 4-byte addressing mode. */
456 static int set_4byte(struct spi_nor *nor, const struct flash_info *info,
457                      int enable)
458 {
459         int status;
460         bool need_wren = false;
461         u8 cmd;
462
463         switch (JEDEC_MFR(info)) {
464         case SNOR_MFR_ST:
465         case SNOR_MFR_MICRON:
466                 /* Some Micron need WREN command; all will accept it */
467                 need_wren = true;
468         case SNOR_MFR_ISSI:
469         case SNOR_MFR_MACRONIX:
470         case SNOR_MFR_WINBOND:
471                 if (need_wren)
472                         write_enable(nor);
473
474                 cmd = enable ? SPINOR_OP_EN4B : SPINOR_OP_EX4B;
475                 status = nor->write_reg(nor, cmd, NULL, 0);
476                 if (need_wren)
477                         write_disable(nor);
478
479                 if (!status && !enable &&
480                     JEDEC_MFR(info) == SNOR_MFR_WINBOND) {
481                         /*
482                          * On Winbond W25Q256FV, leaving 4byte mode causes
483                          * the Extended Address Register to be set to 1, so all
484                          * 3-byte-address reads come from the second 16M.
485                          * We must clear the register to enable normal behavior.
486                          */
487                         write_enable(nor);
488                         nor->cmd_buf[0] = 0;
489                         nor->write_reg(nor, SPINOR_OP_WREAR, nor->cmd_buf, 1);
490                         write_disable(nor);
491                 }
492
493                 return status;
494         default:
495                 /* Spansion style */
496                 nor->cmd_buf[0] = enable << 7;
497                 return nor->write_reg(nor, SPINOR_OP_BRWR, nor->cmd_buf, 1);
498         }
499 }
500
501 static int spi_nor_sr_ready(struct spi_nor *nor)
502 {
503         int sr = read_sr(nor);
504
505         if (sr < 0)
506                 return sr;
507
508         if (nor->flags & SNOR_F_USE_CLSR && sr & (SR_E_ERR | SR_P_ERR)) {
509                 if (sr & SR_E_ERR)
510                         dev_dbg(nor->dev, "Erase Error occurred\n");
511                 else
512                         dev_dbg(nor->dev, "Programming Error occurred\n");
513
514                 nor->write_reg(nor, SPINOR_OP_CLSR, NULL, 0);
515                 return -EIO;
516         }
517
518         return !(sr & SR_WIP);
519 }
520
521 static int spi_nor_fsr_ready(struct spi_nor *nor)
522 {
523         int fsr = read_fsr(nor);
524
525         if (fsr < 0)
526                 return fsr;
527
528         if (fsr & (FSR_E_ERR | FSR_P_ERR)) {
529                 if (fsr & FSR_E_ERR)
530                         dev_err(nor->dev, "Erase operation failed.\n");
531                 else
532                         dev_err(nor->dev, "Program operation failed.\n");
533
534                 if (fsr & FSR_PT_ERR)
535                         dev_err(nor->dev,
536                                 "Attempted to modify a protected sector.\n");
537
538                 nor->write_reg(nor, SPINOR_OP_CLFSR, NULL, 0);
539                 return -EIO;
540         }
541
542         return fsr & FSR_READY;
543 }
544
545 static int spi_nor_ready(struct spi_nor *nor)
546 {
547         int sr, fsr;
548
549         sr = spi_nor_sr_ready(nor);
550         if (sr < 0)
551                 return sr;
552         fsr = nor->flags & SNOR_F_USE_FSR ? spi_nor_fsr_ready(nor) : 1;
553         if (fsr < 0)
554                 return fsr;
555         return sr && fsr;
556 }
557
558 /*
559  * Service routine to read status register until ready, or timeout occurs.
560  * Returns non-zero if error.
561  */
562 static int spi_nor_wait_till_ready_with_timeout(struct spi_nor *nor,
563                                                 unsigned long timeout)
564 {
565         unsigned long timebase;
566         int ret;
567
568         timebase = get_timer(0);
569
570         while (get_timer(timebase) < timeout) {
571                 ret = spi_nor_ready(nor);
572                 if (ret < 0)
573                         return ret;
574                 if (ret)
575                         return 0;
576         }
577
578         dev_err(nor->dev, "flash operation timed out\n");
579
580         return -ETIMEDOUT;
581 }
582
583 static int spi_nor_wait_till_ready(struct spi_nor *nor)
584 {
585         return spi_nor_wait_till_ready_with_timeout(nor,
586                                                     DEFAULT_READY_WAIT_JIFFIES);
587 }
588
589 #ifdef CONFIG_SPI_FLASH_BAR
590 /*
591  * This "clean_bar" is necessary in a situation when one was accessing
592  * spi flash memory > 16 MiB by using Bank Address Register's BA24 bit.
593  *
594  * After it the BA24 bit shall be cleared to allow access to correct
595  * memory region after SW reset (by calling "reset" command).
596  *
597  * Otherwise, the BA24 bit may be left set and then after reset, the
598  * ROM would read/write/erase SPL from 16 MiB * bank_sel address.
599  */
600 static int clean_bar(struct spi_nor *nor)
601 {
602         u8 cmd, bank_sel = 0;
603
604         if (nor->bank_curr == 0)
605                 return 0;
606         cmd = nor->bank_write_cmd;
607         nor->bank_curr = 0;
608         write_enable(nor);
609
610         return nor->write_reg(nor, cmd, &bank_sel, 1);
611 }
612
613 static int write_bar(struct spi_nor *nor, u32 offset)
614 {
615         u8 cmd, bank_sel;
616         int ret;
617
618         bank_sel = offset / SZ_16M;
619         if (bank_sel == nor->bank_curr)
620                 goto bar_end;
621
622         cmd = nor->bank_write_cmd;
623         write_enable(nor);
624         ret = nor->write_reg(nor, cmd, &bank_sel, 1);
625         if (ret < 0) {
626                 debug("SF: fail to write bank register\n");
627                 return ret;
628         }
629
630 bar_end:
631         nor->bank_curr = bank_sel;
632         return nor->bank_curr;
633 }
634
635 static int read_bar(struct spi_nor *nor, const struct flash_info *info)
636 {
637         u8 curr_bank = 0;
638         int ret;
639
640         switch (JEDEC_MFR(info)) {
641         case SNOR_MFR_SPANSION:
642                 nor->bank_read_cmd = SPINOR_OP_BRRD;
643                 nor->bank_write_cmd = SPINOR_OP_BRWR;
644                 break;
645         default:
646                 nor->bank_read_cmd = SPINOR_OP_RDEAR;
647                 nor->bank_write_cmd = SPINOR_OP_WREAR;
648         }
649
650         ret = nor->read_reg(nor, nor->bank_read_cmd,
651                                     &curr_bank, 1);
652         if (ret) {
653                 debug("SF: fail to read bank addr register\n");
654                 return ret;
655         }
656         nor->bank_curr = curr_bank;
657
658         return 0;
659 }
660 #endif
661
662 /*
663  * Initiate the erasure of a single sector
664  */
665 static int spi_nor_erase_sector(struct spi_nor *nor, u32 addr)
666 {
667         struct spi_mem_op op =
668                 SPI_MEM_OP(SPI_MEM_OP_CMD(nor->erase_opcode, 1),
669                            SPI_MEM_OP_ADDR(nor->addr_width, addr, 1),
670                            SPI_MEM_OP_NO_DUMMY,
671                            SPI_MEM_OP_NO_DATA);
672
673         if (nor->erase)
674                 return nor->erase(nor, addr);
675
676         /*
677          * Default implementation, if driver doesn't have a specialized HW
678          * control
679          */
680         return spi_mem_exec_op(nor->spi, &op);
681 }
682
683 /*
684  * Erase an address range on the nor chip.  The address range may extend
685  * one or more erase sectors.  Return an error is there is a problem erasing.
686  */
687 static int spi_nor_erase(struct mtd_info *mtd, struct erase_info *instr)
688 {
689         struct spi_nor *nor = mtd_to_spi_nor(mtd);
690         u32 addr, len, rem;
691         int ret;
692
693         dev_dbg(nor->dev, "at 0x%llx, len %lld\n", (long long)instr->addr,
694                 (long long)instr->len);
695
696         if (!instr->len)
697                 return 0;
698
699         div_u64_rem(instr->len, mtd->erasesize, &rem);
700         if (rem)
701                 return -EINVAL;
702
703         addr = instr->addr;
704         len = instr->len;
705
706         while (len) {
707                 WATCHDOG_RESET();
708 #ifdef CONFIG_SPI_FLASH_BAR
709                 ret = write_bar(nor, addr);
710                 if (ret < 0)
711                         return ret;
712 #endif
713                 write_enable(nor);
714
715                 ret = spi_nor_erase_sector(nor, addr);
716                 if (ret)
717                         goto erase_err;
718
719                 addr += mtd->erasesize;
720                 len -= mtd->erasesize;
721
722                 ret = spi_nor_wait_till_ready(nor);
723                 if (ret)
724                         goto erase_err;
725         }
726
727 erase_err:
728 #ifdef CONFIG_SPI_FLASH_BAR
729         ret = clean_bar(nor);
730 #endif
731         write_disable(nor);
732
733         return ret;
734 }
735
736 #if defined(CONFIG_SPI_FLASH_STMICRO) || defined(CONFIG_SPI_FLASH_SST)
737 /* Write status register and ensure bits in mask match written values */
738 static int write_sr_and_check(struct spi_nor *nor, u8 status_new, u8 mask)
739 {
740         int ret;
741
742         write_enable(nor);
743         ret = write_sr(nor, status_new);
744         if (ret)
745                 return ret;
746
747         ret = spi_nor_wait_till_ready(nor);
748         if (ret)
749                 return ret;
750
751         ret = read_sr(nor);
752         if (ret < 0)
753                 return ret;
754
755         return ((ret & mask) != (status_new & mask)) ? -EIO : 0;
756 }
757
758 static void stm_get_locked_range(struct spi_nor *nor, u8 sr, loff_t *ofs,
759                                  uint64_t *len)
760 {
761         struct mtd_info *mtd = &nor->mtd;
762         u8 mask = SR_BP2 | SR_BP1 | SR_BP0;
763         int shift = ffs(mask) - 1;
764         int pow;
765
766         if (!(sr & mask)) {
767                 /* No protection */
768                 *ofs = 0;
769                 *len = 0;
770         } else {
771                 pow = ((sr & mask) ^ mask) >> shift;
772                 *len = mtd->size >> pow;
773                 if (nor->flags & SNOR_F_HAS_SR_TB && sr & SR_TB)
774                         *ofs = 0;
775                 else
776                         *ofs = mtd->size - *len;
777         }
778 }
779
780 /*
781  * Return 1 if the entire region is locked (if @locked is true) or unlocked (if
782  * @locked is false); 0 otherwise
783  */
784 static int stm_check_lock_status_sr(struct spi_nor *nor, loff_t ofs, u64 len,
785                                     u8 sr, bool locked)
786 {
787         loff_t lock_offs;
788         uint64_t lock_len;
789
790         if (!len)
791                 return 1;
792
793         stm_get_locked_range(nor, sr, &lock_offs, &lock_len);
794
795         if (locked)
796                 /* Requested range is a sub-range of locked range */
797                 return (ofs + len <= lock_offs + lock_len) && (ofs >= lock_offs);
798         else
799                 /* Requested range does not overlap with locked range */
800                 return (ofs >= lock_offs + lock_len) || (ofs + len <= lock_offs);
801 }
802
803 static int stm_is_locked_sr(struct spi_nor *nor, loff_t ofs, uint64_t len,
804                             u8 sr)
805 {
806         return stm_check_lock_status_sr(nor, ofs, len, sr, true);
807 }
808
809 static int stm_is_unlocked_sr(struct spi_nor *nor, loff_t ofs, uint64_t len,
810                               u8 sr)
811 {
812         return stm_check_lock_status_sr(nor, ofs, len, sr, false);
813 }
814
815 /*
816  * Lock a region of the flash. Compatible with ST Micro and similar flash.
817  * Supports the block protection bits BP{0,1,2} in the status register
818  * (SR). Does not support these features found in newer SR bitfields:
819  *   - SEC: sector/block protect - only handle SEC=0 (block protect)
820  *   - CMP: complement protect - only support CMP=0 (range is not complemented)
821  *
822  * Support for the following is provided conditionally for some flash:
823  *   - TB: top/bottom protect
824  *
825  * Sample table portion for 8MB flash (Winbond w25q64fw):
826  *
827  *   SEC  |  TB   |  BP2  |  BP1  |  BP0  |  Prot Length  | Protected Portion
828  *  --------------------------------------------------------------------------
829  *    X   |   X   |   0   |   0   |   0   |  NONE         | NONE
830  *    0   |   0   |   0   |   0   |   1   |  128 KB       | Upper 1/64
831  *    0   |   0   |   0   |   1   |   0   |  256 KB       | Upper 1/32
832  *    0   |   0   |   0   |   1   |   1   |  512 KB       | Upper 1/16
833  *    0   |   0   |   1   |   0   |   0   |  1 MB         | Upper 1/8
834  *    0   |   0   |   1   |   0   |   1   |  2 MB         | Upper 1/4
835  *    0   |   0   |   1   |   1   |   0   |  4 MB         | Upper 1/2
836  *    X   |   X   |   1   |   1   |   1   |  8 MB         | ALL
837  *  ------|-------|-------|-------|-------|---------------|-------------------
838  *    0   |   1   |   0   |   0   |   1   |  128 KB       | Lower 1/64
839  *    0   |   1   |   0   |   1   |   0   |  256 KB       | Lower 1/32
840  *    0   |   1   |   0   |   1   |   1   |  512 KB       | Lower 1/16
841  *    0   |   1   |   1   |   0   |   0   |  1 MB         | Lower 1/8
842  *    0   |   1   |   1   |   0   |   1   |  2 MB         | Lower 1/4
843  *    0   |   1   |   1   |   1   |   0   |  4 MB         | Lower 1/2
844  *
845  * Returns negative on errors, 0 on success.
846  */
847 static int stm_lock(struct spi_nor *nor, loff_t ofs, uint64_t len)
848 {
849         struct mtd_info *mtd = &nor->mtd;
850         int status_old, status_new;
851         u8 mask = SR_BP2 | SR_BP1 | SR_BP0;
852         u8 shift = ffs(mask) - 1, pow, val;
853         loff_t lock_len;
854         bool can_be_top = true, can_be_bottom = nor->flags & SNOR_F_HAS_SR_TB;
855         bool use_top;
856
857         status_old = read_sr(nor);
858         if (status_old < 0)
859                 return status_old;
860
861         /* If nothing in our range is unlocked, we don't need to do anything */
862         if (stm_is_locked_sr(nor, ofs, len, status_old))
863                 return 0;
864
865         /* If anything below us is unlocked, we can't use 'bottom' protection */
866         if (!stm_is_locked_sr(nor, 0, ofs, status_old))
867                 can_be_bottom = false;
868
869         /* If anything above us is unlocked, we can't use 'top' protection */
870         if (!stm_is_locked_sr(nor, ofs + len, mtd->size - (ofs + len),
871                               status_old))
872                 can_be_top = false;
873
874         if (!can_be_bottom && !can_be_top)
875                 return -EINVAL;
876
877         /* Prefer top, if both are valid */
878         use_top = can_be_top;
879
880         /* lock_len: length of region that should end up locked */
881         if (use_top)
882                 lock_len = mtd->size - ofs;
883         else
884                 lock_len = ofs + len;
885
886         /*
887          * Need smallest pow such that:
888          *
889          *   1 / (2^pow) <= (len / size)
890          *
891          * so (assuming power-of-2 size) we do:
892          *
893          *   pow = ceil(log2(size / len)) = log2(size) - floor(log2(len))
894          */
895         pow = ilog2(mtd->size) - ilog2(lock_len);
896         val = mask - (pow << shift);
897         if (val & ~mask)
898                 return -EINVAL;
899         /* Don't "lock" with no region! */
900         if (!(val & mask))
901                 return -EINVAL;
902
903         status_new = (status_old & ~mask & ~SR_TB) | val;
904
905         /* Disallow further writes if WP pin is asserted */
906         status_new |= SR_SRWD;
907
908         if (!use_top)
909                 status_new |= SR_TB;
910
911         /* Don't bother if they're the same */
912         if (status_new == status_old)
913                 return 0;
914
915         /* Only modify protection if it will not unlock other areas */
916         if ((status_new & mask) < (status_old & mask))
917                 return -EINVAL;
918
919         return write_sr_and_check(nor, status_new, mask);
920 }
921
922 /*
923  * Unlock a region of the flash. See stm_lock() for more info
924  *
925  * Returns negative on errors, 0 on success.
926  */
927 static int stm_unlock(struct spi_nor *nor, loff_t ofs, uint64_t len)
928 {
929         struct mtd_info *mtd = &nor->mtd;
930         int status_old, status_new;
931         u8 mask = SR_BP2 | SR_BP1 | SR_BP0;
932         u8 shift = ffs(mask) - 1, pow, val;
933         loff_t lock_len;
934         bool can_be_top = true, can_be_bottom = nor->flags & SNOR_F_HAS_SR_TB;
935         bool use_top;
936
937         status_old = read_sr(nor);
938         if (status_old < 0)
939                 return status_old;
940
941         /* If nothing in our range is locked, we don't need to do anything */
942         if (stm_is_unlocked_sr(nor, ofs, len, status_old))
943                 return 0;
944
945         /* If anything below us is locked, we can't use 'top' protection */
946         if (!stm_is_unlocked_sr(nor, 0, ofs, status_old))
947                 can_be_top = false;
948
949         /* If anything above us is locked, we can't use 'bottom' protection */
950         if (!stm_is_unlocked_sr(nor, ofs + len, mtd->size - (ofs + len),
951                                 status_old))
952                 can_be_bottom = false;
953
954         if (!can_be_bottom && !can_be_top)
955                 return -EINVAL;
956
957         /* Prefer top, if both are valid */
958         use_top = can_be_top;
959
960         /* lock_len: length of region that should remain locked */
961         if (use_top)
962                 lock_len = mtd->size - (ofs + len);
963         else
964                 lock_len = ofs;
965
966         /*
967          * Need largest pow such that:
968          *
969          *   1 / (2^pow) >= (len / size)
970          *
971          * so (assuming power-of-2 size) we do:
972          *
973          *   pow = floor(log2(size / len)) = log2(size) - ceil(log2(len))
974          */
975         pow = ilog2(mtd->size) - order_base_2(lock_len);
976         if (lock_len == 0) {
977                 val = 0; /* fully unlocked */
978         } else {
979                 val = mask - (pow << shift);
980                 /* Some power-of-two sizes are not supported */
981                 if (val & ~mask)
982                         return -EINVAL;
983         }
984
985         status_new = (status_old & ~mask & ~SR_TB) | val;
986
987         /* Don't protect status register if we're fully unlocked */
988         if (lock_len == 0)
989                 status_new &= ~SR_SRWD;
990
991         if (!use_top)
992                 status_new |= SR_TB;
993
994         /* Don't bother if they're the same */
995         if (status_new == status_old)
996                 return 0;
997
998         /* Only modify protection if it will not lock other areas */
999         if ((status_new & mask) > (status_old & mask))
1000                 return -EINVAL;
1001
1002         return write_sr_and_check(nor, status_new, mask);
1003 }
1004
1005 /*
1006  * Check if a region of the flash is (completely) locked. See stm_lock() for
1007  * more info.
1008  *
1009  * Returns 1 if entire region is locked, 0 if any portion is unlocked, and
1010  * negative on errors.
1011  */
1012 static int stm_is_locked(struct spi_nor *nor, loff_t ofs, uint64_t len)
1013 {
1014         int status;
1015
1016         status = read_sr(nor);
1017         if (status < 0)
1018                 return status;
1019
1020         return stm_is_locked_sr(nor, ofs, len, status);
1021 }
1022 #endif /* CONFIG_SPI_FLASH_STMICRO */
1023
1024 static const struct flash_info *spi_nor_read_id(struct spi_nor *nor)
1025 {
1026         int                     tmp;
1027         u8                      id[SPI_NOR_MAX_ID_LEN];
1028         const struct flash_info *info;
1029
1030         tmp = nor->read_reg(nor, SPINOR_OP_RDID, id, SPI_NOR_MAX_ID_LEN);
1031         if (tmp < 0) {
1032                 dev_dbg(nor->dev, "error %d reading JEDEC ID\n", tmp);
1033                 return ERR_PTR(tmp);
1034         }
1035
1036         info = spi_nor_ids;
1037         for (; info->name; info++) {
1038                 if (info->id_len) {
1039                         if (!memcmp(info->id, id, info->id_len))
1040                                 return info;
1041                 }
1042         }
1043
1044         dev_err(nor->dev, "unrecognized JEDEC id bytes: %02x, %02x, %02x\n",
1045                 id[0], id[1], id[2]);
1046         return ERR_PTR(-ENODEV);
1047 }
1048
1049 static int spi_nor_read(struct mtd_info *mtd, loff_t from, size_t len,
1050                         size_t *retlen, u_char *buf)
1051 {
1052         struct spi_nor *nor = mtd_to_spi_nor(mtd);
1053         int ret;
1054
1055         dev_dbg(nor->dev, "from 0x%08x, len %zd\n", (u32)from, len);
1056
1057         while (len) {
1058                 loff_t addr = from;
1059                 size_t read_len = len;
1060
1061 #ifdef CONFIG_SPI_FLASH_BAR
1062                 u32 remain_len;
1063
1064                 ret = write_bar(nor, addr);
1065                 if (ret < 0)
1066                         return log_ret(ret);
1067                 remain_len = (SZ_16M * (nor->bank_curr + 1)) - addr;
1068
1069                 if (len < remain_len)
1070                         read_len = len;
1071                 else
1072                         read_len = remain_len;
1073 #endif
1074
1075                 ret = nor->read(nor, addr, read_len, buf);
1076                 if (ret == 0) {
1077                         /* We shouldn't see 0-length reads */
1078                         ret = -EIO;
1079                         goto read_err;
1080                 }
1081                 if (ret < 0)
1082                         goto read_err;
1083
1084                 *retlen += ret;
1085                 buf += ret;
1086                 from += ret;
1087                 len -= ret;
1088         }
1089         ret = 0;
1090
1091 read_err:
1092 #ifdef CONFIG_SPI_FLASH_BAR
1093         ret = clean_bar(nor);
1094 #endif
1095         return ret;
1096 }
1097
1098 #ifdef CONFIG_SPI_FLASH_SST
1099 /*
1100  * sst26 flash series has its own block protection implementation:
1101  * 4x   - 8  KByte blocks - read & write protection bits - upper addresses
1102  * 1x   - 32 KByte blocks - write protection bits
1103  * rest - 64 KByte blocks - write protection bits
1104  * 1x   - 32 KByte blocks - write protection bits
1105  * 4x   - 8  KByte blocks - read & write protection bits - lower addresses
1106  *
1107  * We'll support only per 64k lock/unlock so lower and upper 64 KByte region
1108  * will be treated as single block.
1109  */
1110 #define SST26_BPR_8K_NUM                4
1111 #define SST26_MAX_BPR_REG_LEN           (18 + 1)
1112 #define SST26_BOUND_REG_SIZE            ((32 + SST26_BPR_8K_NUM * 8) * SZ_1K)
1113
1114 enum lock_ctl {
1115         SST26_CTL_LOCK,
1116         SST26_CTL_UNLOCK,
1117         SST26_CTL_CHECK
1118 };
1119
1120 static bool sst26_process_bpr(u32 bpr_size, u8 *cmd, u32 bit, enum lock_ctl ctl)
1121 {
1122         switch (ctl) {
1123         case SST26_CTL_LOCK:
1124                 cmd[bpr_size - (bit / 8) - 1] |= BIT(bit % 8);
1125                 break;
1126         case SST26_CTL_UNLOCK:
1127                 cmd[bpr_size - (bit / 8) - 1] &= ~BIT(bit % 8);
1128                 break;
1129         case SST26_CTL_CHECK:
1130                 return !!(cmd[bpr_size - (bit / 8) - 1] & BIT(bit % 8));
1131         }
1132
1133         return false;
1134 }
1135
1136 /*
1137  * Lock, unlock or check lock status of the flash region of the flash (depending
1138  * on the lock_ctl value)
1139  */
1140 static int sst26_lock_ctl(struct spi_nor *nor, loff_t ofs, uint64_t len, enum lock_ctl ctl)
1141 {
1142         struct mtd_info *mtd = &nor->mtd;
1143         u32 i, bpr_ptr, rptr_64k, lptr_64k, bpr_size;
1144         bool lower_64k = false, upper_64k = false;
1145         u8 bpr_buff[SST26_MAX_BPR_REG_LEN] = {};
1146         int ret;
1147
1148         /* Check length and offset for 64k alignment */
1149         if ((ofs & (SZ_64K - 1)) || (len & (SZ_64K - 1))) {
1150                 dev_err(nor->dev, "length or offset is not 64KiB allighned\n");
1151                 return -EINVAL;
1152         }
1153
1154         if (ofs + len > mtd->size) {
1155                 dev_err(nor->dev, "range is more than device size: %#llx + %#llx > %#llx\n",
1156                         ofs, len, mtd->size);
1157                 return -EINVAL;
1158         }
1159
1160         /* SST26 family has only 16 Mbit, 32 Mbit and 64 Mbit IC */
1161         if (mtd->size != SZ_2M &&
1162             mtd->size != SZ_4M &&
1163             mtd->size != SZ_8M)
1164                 return -EINVAL;
1165
1166         bpr_size = 2 + (mtd->size / SZ_64K / 8);
1167
1168         ret = nor->read_reg(nor, SPINOR_OP_READ_BPR, bpr_buff, bpr_size);
1169         if (ret < 0) {
1170                 dev_err(nor->dev, "fail to read block-protection register\n");
1171                 return ret;
1172         }
1173
1174         rptr_64k = min_t(u32, ofs + len, mtd->size - SST26_BOUND_REG_SIZE);
1175         lptr_64k = max_t(u32, ofs, SST26_BOUND_REG_SIZE);
1176
1177         upper_64k = ((ofs + len) > (mtd->size - SST26_BOUND_REG_SIZE));
1178         lower_64k = (ofs < SST26_BOUND_REG_SIZE);
1179
1180         /* Lower bits in block-protection register are about 64k region */
1181         bpr_ptr = lptr_64k / SZ_64K - 1;
1182
1183         /* Process 64K blocks region */
1184         while (lptr_64k < rptr_64k) {
1185                 if (sst26_process_bpr(bpr_size, bpr_buff, bpr_ptr, ctl))
1186                         return EACCES;
1187
1188                 bpr_ptr++;
1189                 lptr_64k += SZ_64K;
1190         }
1191
1192         /* 32K and 8K region bits in BPR are after 64k region bits */
1193         bpr_ptr = (mtd->size - 2 * SST26_BOUND_REG_SIZE) / SZ_64K;
1194
1195         /* Process lower 32K block region */
1196         if (lower_64k)
1197                 if (sst26_process_bpr(bpr_size, bpr_buff, bpr_ptr, ctl))
1198                         return EACCES;
1199
1200         bpr_ptr++;
1201
1202         /* Process upper 32K block region */
1203         if (upper_64k)
1204                 if (sst26_process_bpr(bpr_size, bpr_buff, bpr_ptr, ctl))
1205                         return EACCES;
1206
1207         bpr_ptr++;
1208
1209         /* Process lower 8K block regions */
1210         for (i = 0; i < SST26_BPR_8K_NUM; i++) {
1211                 if (lower_64k)
1212                         if (sst26_process_bpr(bpr_size, bpr_buff, bpr_ptr, ctl))
1213                                 return EACCES;
1214
1215                 /* In 8K area BPR has both read and write protection bits */
1216                 bpr_ptr += 2;
1217         }
1218
1219         /* Process upper 8K block regions */
1220         for (i = 0; i < SST26_BPR_8K_NUM; i++) {
1221                 if (upper_64k)
1222                         if (sst26_process_bpr(bpr_size, bpr_buff, bpr_ptr, ctl))
1223                                 return EACCES;
1224
1225                 /* In 8K area BPR has both read and write protection bits */
1226                 bpr_ptr += 2;
1227         }
1228
1229         /* If we check region status we don't need to write BPR back */
1230         if (ctl == SST26_CTL_CHECK)
1231                 return 0;
1232
1233         ret = nor->write_reg(nor, SPINOR_OP_WRITE_BPR, bpr_buff, bpr_size);
1234         if (ret < 0) {
1235                 dev_err(nor->dev, "fail to write block-protection register\n");
1236                 return ret;
1237         }
1238
1239         return 0;
1240 }
1241
1242 static int sst26_unlock(struct spi_nor *nor, loff_t ofs, uint64_t len)
1243 {
1244         return sst26_lock_ctl(nor, ofs, len, SST26_CTL_UNLOCK);
1245 }
1246
1247 static int sst26_lock(struct spi_nor *nor, loff_t ofs, uint64_t len)
1248 {
1249         return sst26_lock_ctl(nor, ofs, len, SST26_CTL_LOCK);
1250 }
1251
1252 /*
1253  * Returns EACCES (positive value) if region is locked, 0 if region is unlocked,
1254  * and negative on errors.
1255  */
1256 static int sst26_is_locked(struct spi_nor *nor, loff_t ofs, uint64_t len)
1257 {
1258         /*
1259          * is_locked function is used for check before reading or erasing flash
1260          * region, so offset and length might be not 64k allighned, so adjust
1261          * them to be 64k allighned as sst26_lock_ctl works only with 64k
1262          * allighned regions.
1263          */
1264         ofs -= ofs & (SZ_64K - 1);
1265         len = len & (SZ_64K - 1) ? (len & ~(SZ_64K - 1)) + SZ_64K : len;
1266
1267         return sst26_lock_ctl(nor, ofs, len, SST26_CTL_CHECK);
1268 }
1269
1270 static int sst_write_byteprogram(struct spi_nor *nor, loff_t to, size_t len,
1271                                  size_t *retlen, const u_char *buf)
1272 {
1273         size_t actual;
1274         int ret = 0;
1275
1276         for (actual = 0; actual < len; actual++) {
1277                 nor->program_opcode = SPINOR_OP_BP;
1278
1279                 write_enable(nor);
1280                 /* write one byte. */
1281                 ret = nor->write(nor, to, 1, buf + actual);
1282                 if (ret < 0)
1283                         goto sst_write_err;
1284                 ret = spi_nor_wait_till_ready(nor);
1285                 if (ret)
1286                         goto sst_write_err;
1287                 to++;
1288         }
1289
1290 sst_write_err:
1291         write_disable(nor);
1292         return ret;
1293 }
1294
1295 static int sst_write(struct mtd_info *mtd, loff_t to, size_t len,
1296                      size_t *retlen, const u_char *buf)
1297 {
1298         struct spi_nor *nor = mtd_to_spi_nor(mtd);
1299         struct spi_slave *spi = nor->spi;
1300         size_t actual;
1301         int ret;
1302
1303         dev_dbg(nor->dev, "to 0x%08x, len %zd\n", (u32)to, len);
1304         if (spi->mode & SPI_TX_BYTE)
1305                 return sst_write_byteprogram(nor, to, len, retlen, buf);
1306
1307         write_enable(nor);
1308
1309         nor->sst_write_second = false;
1310
1311         actual = to % 2;
1312         /* Start write from odd address. */
1313         if (actual) {
1314                 nor->program_opcode = SPINOR_OP_BP;
1315
1316                 /* write one byte. */
1317                 ret = nor->write(nor, to, 1, buf);
1318                 if (ret < 0)
1319                         goto sst_write_err;
1320                 ret = spi_nor_wait_till_ready(nor);
1321                 if (ret)
1322                         goto sst_write_err;
1323         }
1324         to += actual;
1325
1326         /* Write out most of the data here. */
1327         for (; actual < len - 1; actual += 2) {
1328                 nor->program_opcode = SPINOR_OP_AAI_WP;
1329
1330                 /* write two bytes. */
1331                 ret = nor->write(nor, to, 2, buf + actual);
1332                 if (ret < 0)
1333                         goto sst_write_err;
1334                 ret = spi_nor_wait_till_ready(nor);
1335                 if (ret)
1336                         goto sst_write_err;
1337                 to += 2;
1338                 nor->sst_write_second = true;
1339         }
1340         nor->sst_write_second = false;
1341
1342         write_disable(nor);
1343         ret = spi_nor_wait_till_ready(nor);
1344         if (ret)
1345                 goto sst_write_err;
1346
1347         /* Write out trailing byte if it exists. */
1348         if (actual != len) {
1349                 write_enable(nor);
1350
1351                 nor->program_opcode = SPINOR_OP_BP;
1352                 ret = nor->write(nor, to, 1, buf + actual);
1353                 if (ret < 0)
1354                         goto sst_write_err;
1355                 ret = spi_nor_wait_till_ready(nor);
1356                 if (ret)
1357                         goto sst_write_err;
1358                 write_disable(nor);
1359                 actual += 1;
1360         }
1361 sst_write_err:
1362         *retlen += actual;
1363         return ret;
1364 }
1365 #endif
1366 /*
1367  * Write an address range to the nor chip.  Data must be written in
1368  * FLASH_PAGESIZE chunks.  The address range may be any size provided
1369  * it is within the physical boundaries.
1370  */
1371 static int spi_nor_write(struct mtd_info *mtd, loff_t to, size_t len,
1372         size_t *retlen, const u_char *buf)
1373 {
1374         struct spi_nor *nor = mtd_to_spi_nor(mtd);
1375         size_t page_offset, page_remain, i;
1376         ssize_t ret;
1377
1378 #ifdef CONFIG_SPI_FLASH_SST
1379         /* sst nor chips use AAI word program */
1380         if (nor->info->flags & SST_WRITE)
1381                 return sst_write(mtd, to, len, retlen, buf);
1382 #endif
1383
1384         dev_dbg(nor->dev, "to 0x%08x, len %zd\n", (u32)to, len);
1385
1386         if (!len)
1387                 return 0;
1388
1389         for (i = 0; i < len; ) {
1390                 ssize_t written;
1391                 loff_t addr = to + i;
1392                 WATCHDOG_RESET();
1393
1394                 /*
1395                  * If page_size is a power of two, the offset can be quickly
1396                  * calculated with an AND operation. On the other cases we
1397                  * need to do a modulus operation (more expensive).
1398                  */
1399                 if (is_power_of_2(nor->page_size)) {
1400                         page_offset = addr & (nor->page_size - 1);
1401                 } else {
1402                         u64 aux = addr;
1403
1404                         page_offset = do_div(aux, nor->page_size);
1405                 }
1406                 /* the size of data remaining on the first page */
1407                 page_remain = min_t(size_t,
1408                                     nor->page_size - page_offset, len - i);
1409
1410 #ifdef CONFIG_SPI_FLASH_BAR
1411                 ret = write_bar(nor, addr);
1412                 if (ret < 0)
1413                         return ret;
1414 #endif
1415                 write_enable(nor);
1416                 ret = nor->write(nor, addr, page_remain, buf + i);
1417                 if (ret < 0)
1418                         goto write_err;
1419                 written = ret;
1420
1421                 ret = spi_nor_wait_till_ready(nor);
1422                 if (ret)
1423                         goto write_err;
1424                 *retlen += written;
1425                 i += written;
1426         }
1427
1428 write_err:
1429 #ifdef CONFIG_SPI_FLASH_BAR
1430         ret = clean_bar(nor);
1431 #endif
1432         return ret;
1433 }
1434
1435 #if defined(CONFIG_SPI_FLASH_MACRONIX) || defined(CONFIG_SPI_FLASH_ISSI)
1436 /**
1437  * macronix_quad_enable() - set QE bit in Status Register.
1438  * @nor:        pointer to a 'struct spi_nor'
1439  *
1440  * Set the Quad Enable (QE) bit in the Status Register.
1441  *
1442  * bit 6 of the Status Register is the QE bit for Macronix like QSPI memories.
1443  *
1444  * Return: 0 on success, -errno otherwise.
1445  */
1446 static int macronix_quad_enable(struct spi_nor *nor)
1447 {
1448         int ret, val;
1449
1450         val = read_sr(nor);
1451         if (val < 0)
1452                 return val;
1453         if (val & SR_QUAD_EN_MX)
1454                 return 0;
1455
1456         write_enable(nor);
1457
1458         write_sr(nor, val | SR_QUAD_EN_MX);
1459
1460         ret = spi_nor_wait_till_ready(nor);
1461         if (ret)
1462                 return ret;
1463
1464         ret = read_sr(nor);
1465         if (!(ret > 0 && (ret & SR_QUAD_EN_MX))) {
1466                 dev_err(nor->dev, "Macronix Quad bit not set\n");
1467                 return -EINVAL;
1468         }
1469
1470         return 0;
1471 }
1472 #endif
1473
1474 #if defined(CONFIG_SPI_FLASH_SPANSION) || defined(CONFIG_SPI_FLASH_WINBOND)
1475 /*
1476  * Write status Register and configuration register with 2 bytes
1477  * The first byte will be written to the status register, while the
1478  * second byte will be written to the configuration register.
1479  * Return negative if error occurred.
1480  */
1481 static int write_sr_cr(struct spi_nor *nor, u8 *sr_cr)
1482 {
1483         int ret;
1484
1485         write_enable(nor);
1486
1487         ret = nor->write_reg(nor, SPINOR_OP_WRSR, sr_cr, 2);
1488         if (ret < 0) {
1489                 dev_dbg(nor->dev,
1490                         "error while writing configuration register\n");
1491                 return -EINVAL;
1492         }
1493
1494         ret = spi_nor_wait_till_ready(nor);
1495         if (ret) {
1496                 dev_dbg(nor->dev,
1497                         "timeout while writing configuration register\n");
1498                 return ret;
1499         }
1500
1501         return 0;
1502 }
1503
1504 /**
1505  * spansion_read_cr_quad_enable() - set QE bit in Configuration Register.
1506  * @nor:        pointer to a 'struct spi_nor'
1507  *
1508  * Set the Quad Enable (QE) bit in the Configuration Register.
1509  * This function should be used with QSPI memories supporting the Read
1510  * Configuration Register (35h) instruction.
1511  *
1512  * bit 1 of the Configuration Register is the QE bit for Spansion like QSPI
1513  * memories.
1514  *
1515  * Return: 0 on success, -errno otherwise.
1516  */
1517 static int spansion_read_cr_quad_enable(struct spi_nor *nor)
1518 {
1519         u8 sr_cr[2];
1520         int ret;
1521
1522         /* Check current Quad Enable bit value. */
1523         ret = read_cr(nor);
1524         if (ret < 0) {
1525                 dev_dbg(nor->dev,
1526                         "error while reading configuration register\n");
1527                 return -EINVAL;
1528         }
1529
1530         if (ret & CR_QUAD_EN_SPAN)
1531                 return 0;
1532
1533         sr_cr[1] = ret | CR_QUAD_EN_SPAN;
1534
1535         /* Keep the current value of the Status Register. */
1536         ret = read_sr(nor);
1537         if (ret < 0) {
1538                 dev_dbg(nor->dev, "error while reading status register\n");
1539                 return -EINVAL;
1540         }
1541         sr_cr[0] = ret;
1542
1543         ret = write_sr_cr(nor, sr_cr);
1544         if (ret)
1545                 return ret;
1546
1547         /* Read back and check it. */
1548         ret = read_cr(nor);
1549         if (!(ret > 0 && (ret & CR_QUAD_EN_SPAN))) {
1550                 dev_dbg(nor->dev, "Spansion Quad bit not set\n");
1551                 return -EINVAL;
1552         }
1553
1554         return 0;
1555 }
1556
1557 #if CONFIG_IS_ENABLED(SPI_FLASH_SFDP_SUPPORT)
1558 /**
1559  * spansion_no_read_cr_quad_enable() - set QE bit in Configuration Register.
1560  * @nor:        pointer to a 'struct spi_nor'
1561  *
1562  * Set the Quad Enable (QE) bit in the Configuration Register.
1563  * This function should be used with QSPI memories not supporting the Read
1564  * Configuration Register (35h) instruction.
1565  *
1566  * bit 1 of the Configuration Register is the QE bit for Spansion like QSPI
1567  * memories.
1568  *
1569  * Return: 0 on success, -errno otherwise.
1570  */
1571 static int spansion_no_read_cr_quad_enable(struct spi_nor *nor)
1572 {
1573         u8 sr_cr[2];
1574         int ret;
1575
1576         /* Keep the current value of the Status Register. */
1577         ret = read_sr(nor);
1578         if (ret < 0) {
1579                 dev_dbg(nor->dev, "error while reading status register\n");
1580                 return -EINVAL;
1581         }
1582         sr_cr[0] = ret;
1583         sr_cr[1] = CR_QUAD_EN_SPAN;
1584
1585         return write_sr_cr(nor, sr_cr);
1586 }
1587
1588 #endif /* CONFIG_SPI_FLASH_SFDP_SUPPORT */
1589 #endif /* CONFIG_SPI_FLASH_SPANSION */
1590
1591 static void
1592 spi_nor_set_read_settings(struct spi_nor_read_command *read,
1593                           u8 num_mode_clocks,
1594                           u8 num_wait_states,
1595                           u8 opcode,
1596                           enum spi_nor_protocol proto)
1597 {
1598         read->num_mode_clocks = num_mode_clocks;
1599         read->num_wait_states = num_wait_states;
1600         read->opcode = opcode;
1601         read->proto = proto;
1602 }
1603
1604 static void
1605 spi_nor_set_pp_settings(struct spi_nor_pp_command *pp,
1606                         u8 opcode,
1607                         enum spi_nor_protocol proto)
1608 {
1609         pp->opcode = opcode;
1610         pp->proto = proto;
1611 }
1612
1613 #if CONFIG_IS_ENABLED(SPI_FLASH_SFDP_SUPPORT)
1614 /*
1615  * Serial Flash Discoverable Parameters (SFDP) parsing.
1616  */
1617
1618 /**
1619  * spi_nor_read_sfdp() - read Serial Flash Discoverable Parameters.
1620  * @nor:        pointer to a 'struct spi_nor'
1621  * @addr:       offset in the SFDP area to start reading data from
1622  * @len:        number of bytes to read
1623  * @buf:        buffer where the SFDP data are copied into (dma-safe memory)
1624  *
1625  * Whatever the actual numbers of bytes for address and dummy cycles are
1626  * for (Fast) Read commands, the Read SFDP (5Ah) instruction is always
1627  * followed by a 3-byte address and 8 dummy clock cycles.
1628  *
1629  * Return: 0 on success, -errno otherwise.
1630  */
1631 static int spi_nor_read_sfdp(struct spi_nor *nor, u32 addr,
1632                              size_t len, void *buf)
1633 {
1634         u8 addr_width, read_opcode, read_dummy;
1635         int ret;
1636
1637         read_opcode = nor->read_opcode;
1638         addr_width = nor->addr_width;
1639         read_dummy = nor->read_dummy;
1640
1641         nor->read_opcode = SPINOR_OP_RDSFDP;
1642         nor->addr_width = 3;
1643         nor->read_dummy = 8;
1644
1645         while (len) {
1646                 ret = nor->read(nor, addr, len, (u8 *)buf);
1647                 if (!ret || ret > len) {
1648                         ret = -EIO;
1649                         goto read_err;
1650                 }
1651                 if (ret < 0)
1652                         goto read_err;
1653
1654                 buf += ret;
1655                 addr += ret;
1656                 len -= ret;
1657         }
1658         ret = 0;
1659
1660 read_err:
1661         nor->read_opcode = read_opcode;
1662         nor->addr_width = addr_width;
1663         nor->read_dummy = read_dummy;
1664
1665         return ret;
1666 }
1667
1668 /* Fast Read settings. */
1669
1670 static void
1671 spi_nor_set_read_settings_from_bfpt(struct spi_nor_read_command *read,
1672                                     u16 half,
1673                                     enum spi_nor_protocol proto)
1674 {
1675         read->num_mode_clocks = (half >> 5) & 0x07;
1676         read->num_wait_states = (half >> 0) & 0x1f;
1677         read->opcode = (half >> 8) & 0xff;
1678         read->proto = proto;
1679 }
1680
1681 struct sfdp_bfpt_read {
1682         /* The Fast Read x-y-z hardware capability in params->hwcaps.mask. */
1683         u32                     hwcaps;
1684
1685         /*
1686          * The <supported_bit> bit in <supported_dword> BFPT DWORD tells us
1687          * whether the Fast Read x-y-z command is supported.
1688          */
1689         u32                     supported_dword;
1690         u32                     supported_bit;
1691
1692         /*
1693          * The half-word at offset <setting_shift> in <setting_dword> BFPT DWORD
1694          * encodes the op code, the number of mode clocks and the number of wait
1695          * states to be used by Fast Read x-y-z command.
1696          */
1697         u32                     settings_dword;
1698         u32                     settings_shift;
1699
1700         /* The SPI protocol for this Fast Read x-y-z command. */
1701         enum spi_nor_protocol   proto;
1702 };
1703
1704 static const struct sfdp_bfpt_read sfdp_bfpt_reads[] = {
1705         /* Fast Read 1-1-2 */
1706         {
1707                 SNOR_HWCAPS_READ_1_1_2,
1708                 BFPT_DWORD(1), BIT(16), /* Supported bit */
1709                 BFPT_DWORD(4), 0,       /* Settings */
1710                 SNOR_PROTO_1_1_2,
1711         },
1712
1713         /* Fast Read 1-2-2 */
1714         {
1715                 SNOR_HWCAPS_READ_1_2_2,
1716                 BFPT_DWORD(1), BIT(20), /* Supported bit */
1717                 BFPT_DWORD(4), 16,      /* Settings */
1718                 SNOR_PROTO_1_2_2,
1719         },
1720
1721         /* Fast Read 2-2-2 */
1722         {
1723                 SNOR_HWCAPS_READ_2_2_2,
1724                 BFPT_DWORD(5),  BIT(0), /* Supported bit */
1725                 BFPT_DWORD(6), 16,      /* Settings */
1726                 SNOR_PROTO_2_2_2,
1727         },
1728
1729         /* Fast Read 1-1-4 */
1730         {
1731                 SNOR_HWCAPS_READ_1_1_4,
1732                 BFPT_DWORD(1), BIT(22), /* Supported bit */
1733                 BFPT_DWORD(3), 16,      /* Settings */
1734                 SNOR_PROTO_1_1_4,
1735         },
1736
1737         /* Fast Read 1-4-4 */
1738         {
1739                 SNOR_HWCAPS_READ_1_4_4,
1740                 BFPT_DWORD(1), BIT(21), /* Supported bit */
1741                 BFPT_DWORD(3), 0,       /* Settings */
1742                 SNOR_PROTO_1_4_4,
1743         },
1744
1745         /* Fast Read 4-4-4 */
1746         {
1747                 SNOR_HWCAPS_READ_4_4_4,
1748                 BFPT_DWORD(5), BIT(4),  /* Supported bit */
1749                 BFPT_DWORD(7), 16,      /* Settings */
1750                 SNOR_PROTO_4_4_4,
1751         },
1752 };
1753
1754 struct sfdp_bfpt_erase {
1755         /*
1756          * The half-word at offset <shift> in DWORD <dwoard> encodes the
1757          * op code and erase sector size to be used by Sector Erase commands.
1758          */
1759         u32                     dword;
1760         u32                     shift;
1761 };
1762
1763 static const struct sfdp_bfpt_erase sfdp_bfpt_erases[] = {
1764         /* Erase Type 1 in DWORD8 bits[15:0] */
1765         {BFPT_DWORD(8), 0},
1766
1767         /* Erase Type 2 in DWORD8 bits[31:16] */
1768         {BFPT_DWORD(8), 16},
1769
1770         /* Erase Type 3 in DWORD9 bits[15:0] */
1771         {BFPT_DWORD(9), 0},
1772
1773         /* Erase Type 4 in DWORD9 bits[31:16] */
1774         {BFPT_DWORD(9), 16},
1775 };
1776
1777 static int spi_nor_hwcaps_read2cmd(u32 hwcaps);
1778
1779 static int
1780 spi_nor_post_bfpt_fixups(struct spi_nor *nor,
1781                          const struct sfdp_parameter_header *bfpt_header,
1782                          const struct sfdp_bfpt *bfpt,
1783                          struct spi_nor_flash_parameter *params)
1784 {
1785         if (nor->fixups && nor->fixups->post_bfpt)
1786                 return nor->fixups->post_bfpt(nor, bfpt_header, bfpt, params);
1787
1788         return 0;
1789 }
1790
1791 /**
1792  * spi_nor_parse_bfpt() - read and parse the Basic Flash Parameter Table.
1793  * @nor:                pointer to a 'struct spi_nor'
1794  * @bfpt_header:        pointer to the 'struct sfdp_parameter_header' describing
1795  *                      the Basic Flash Parameter Table length and version
1796  * @params:             pointer to the 'struct spi_nor_flash_parameter' to be
1797  *                      filled
1798  *
1799  * The Basic Flash Parameter Table is the main and only mandatory table as
1800  * defined by the SFDP (JESD216) specification.
1801  * It provides us with the total size (memory density) of the data array and
1802  * the number of address bytes for Fast Read, Page Program and Sector Erase
1803  * commands.
1804  * For Fast READ commands, it also gives the number of mode clock cycles and
1805  * wait states (regrouped in the number of dummy clock cycles) for each
1806  * supported instruction op code.
1807  * For Page Program, the page size is now available since JESD216 rev A, however
1808  * the supported instruction op codes are still not provided.
1809  * For Sector Erase commands, this table stores the supported instruction op
1810  * codes and the associated sector sizes.
1811  * Finally, the Quad Enable Requirements (QER) are also available since JESD216
1812  * rev A. The QER bits encode the manufacturer dependent procedure to be
1813  * executed to set the Quad Enable (QE) bit in some internal register of the
1814  * Quad SPI memory. Indeed the QE bit, when it exists, must be set before
1815  * sending any Quad SPI command to the memory. Actually, setting the QE bit
1816  * tells the memory to reassign its WP# and HOLD#/RESET# pins to functions IO2
1817  * and IO3 hence enabling 4 (Quad) I/O lines.
1818  *
1819  * Return: 0 on success, -errno otherwise.
1820  */
1821 static int spi_nor_parse_bfpt(struct spi_nor *nor,
1822                               const struct sfdp_parameter_header *bfpt_header,
1823                               struct spi_nor_flash_parameter *params)
1824 {
1825         struct mtd_info *mtd = &nor->mtd;
1826         struct sfdp_bfpt bfpt;
1827         size_t len;
1828         int i, cmd, err;
1829         u32 addr;
1830         u16 half;
1831
1832         /* JESD216 Basic Flash Parameter Table length is at least 9 DWORDs. */
1833         if (bfpt_header->length < BFPT_DWORD_MAX_JESD216)
1834                 return -EINVAL;
1835
1836         /* Read the Basic Flash Parameter Table. */
1837         len = min_t(size_t, sizeof(bfpt),
1838                     bfpt_header->length * sizeof(u32));
1839         addr = SFDP_PARAM_HEADER_PTP(bfpt_header);
1840         memset(&bfpt, 0, sizeof(bfpt));
1841         err = spi_nor_read_sfdp(nor,  addr, len, &bfpt);
1842         if (err < 0)
1843                 return err;
1844
1845         /* Fix endianness of the BFPT DWORDs. */
1846         for (i = 0; i < BFPT_DWORD_MAX; i++)
1847                 bfpt.dwords[i] = le32_to_cpu(bfpt.dwords[i]);
1848
1849         /* Number of address bytes. */
1850         switch (bfpt.dwords[BFPT_DWORD(1)] & BFPT_DWORD1_ADDRESS_BYTES_MASK) {
1851         case BFPT_DWORD1_ADDRESS_BYTES_3_ONLY:
1852                 nor->addr_width = 3;
1853                 break;
1854
1855         case BFPT_DWORD1_ADDRESS_BYTES_4_ONLY:
1856                 nor->addr_width = 4;
1857                 break;
1858
1859         default:
1860                 break;
1861         }
1862
1863         /* Flash Memory Density (in bits). */
1864         params->size = bfpt.dwords[BFPT_DWORD(2)];
1865         if (params->size & BIT(31)) {
1866                 params->size &= ~BIT(31);
1867
1868                 /*
1869                  * Prevent overflows on params->size. Anyway, a NOR of 2^64
1870                  * bits is unlikely to exist so this error probably means
1871                  * the BFPT we are reading is corrupted/wrong.
1872                  */
1873                 if (params->size > 63)
1874                         return -EINVAL;
1875
1876                 params->size = 1ULL << params->size;
1877         } else {
1878                 params->size++;
1879         }
1880         params->size >>= 3; /* Convert to bytes. */
1881
1882         /* Fast Read settings. */
1883         for (i = 0; i < ARRAY_SIZE(sfdp_bfpt_reads); i++) {
1884                 const struct sfdp_bfpt_read *rd = &sfdp_bfpt_reads[i];
1885                 struct spi_nor_read_command *read;
1886
1887                 if (!(bfpt.dwords[rd->supported_dword] & rd->supported_bit)) {
1888                         params->hwcaps.mask &= ~rd->hwcaps;
1889                         continue;
1890                 }
1891
1892                 params->hwcaps.mask |= rd->hwcaps;
1893                 cmd = spi_nor_hwcaps_read2cmd(rd->hwcaps);
1894                 read = &params->reads[cmd];
1895                 half = bfpt.dwords[rd->settings_dword] >> rd->settings_shift;
1896                 spi_nor_set_read_settings_from_bfpt(read, half, rd->proto);
1897         }
1898
1899         /* Sector Erase settings. */
1900         for (i = 0; i < ARRAY_SIZE(sfdp_bfpt_erases); i++) {
1901                 const struct sfdp_bfpt_erase *er = &sfdp_bfpt_erases[i];
1902                 u32 erasesize;
1903                 u8 opcode;
1904
1905                 half = bfpt.dwords[er->dword] >> er->shift;
1906                 erasesize = half & 0xff;
1907
1908                 /* erasesize == 0 means this Erase Type is not supported. */
1909                 if (!erasesize)
1910                         continue;
1911
1912                 erasesize = 1U << erasesize;
1913                 opcode = (half >> 8) & 0xff;
1914 #ifdef CONFIG_SPI_FLASH_USE_4K_SECTORS
1915                 if (erasesize == SZ_4K) {
1916                         nor->erase_opcode = opcode;
1917                         mtd->erasesize = erasesize;
1918                         break;
1919                 }
1920 #endif
1921                 if (!mtd->erasesize || mtd->erasesize < erasesize) {
1922                         nor->erase_opcode = opcode;
1923                         mtd->erasesize = erasesize;
1924                 }
1925         }
1926
1927         /* Stop here if not JESD216 rev A or later. */
1928         if (bfpt_header->length < BFPT_DWORD_MAX)
1929                 return spi_nor_post_bfpt_fixups(nor, bfpt_header, &bfpt,
1930                                                 params);
1931
1932         /* Page size: this field specifies 'N' so the page size = 2^N bytes. */
1933         params->page_size = bfpt.dwords[BFPT_DWORD(11)];
1934         params->page_size &= BFPT_DWORD11_PAGE_SIZE_MASK;
1935         params->page_size >>= BFPT_DWORD11_PAGE_SIZE_SHIFT;
1936         params->page_size = 1U << params->page_size;
1937
1938         /* Quad Enable Requirements. */
1939         switch (bfpt.dwords[BFPT_DWORD(15)] & BFPT_DWORD15_QER_MASK) {
1940         case BFPT_DWORD15_QER_NONE:
1941                 params->quad_enable = NULL;
1942                 break;
1943 #if defined(CONFIG_SPI_FLASH_SPANSION) || defined(CONFIG_SPI_FLASH_WINBOND)
1944         case BFPT_DWORD15_QER_SR2_BIT1_BUGGY:
1945         case BFPT_DWORD15_QER_SR2_BIT1_NO_RD:
1946                 params->quad_enable = spansion_no_read_cr_quad_enable;
1947                 break;
1948 #endif
1949 #if defined(CONFIG_SPI_FLASH_MACRONIX) || defined(CONFIG_SPI_FLASH_ISSI)
1950         case BFPT_DWORD15_QER_SR1_BIT6:
1951                 params->quad_enable = macronix_quad_enable;
1952                 break;
1953 #endif
1954 #if defined(CONFIG_SPI_FLASH_SPANSION) || defined(CONFIG_SPI_FLASH_WINBOND)
1955         case BFPT_DWORD15_QER_SR2_BIT1:
1956                 params->quad_enable = spansion_read_cr_quad_enable;
1957                 break;
1958 #endif
1959         default:
1960                 return -EINVAL;
1961         }
1962
1963         return spi_nor_post_bfpt_fixups(nor, bfpt_header, &bfpt, params);
1964 }
1965
1966 /**
1967  * spi_nor_parse_microchip_sfdp() - parse the Microchip manufacturer specific
1968  * SFDP table.
1969  * @nor:                pointer to a 'struct spi_nor'.
1970  * @param_header:       pointer to the SFDP parameter header.
1971  *
1972  * Return: 0 on success, -errno otherwise.
1973  */
1974 static int
1975 spi_nor_parse_microchip_sfdp(struct spi_nor *nor,
1976                              const struct sfdp_parameter_header *param_header)
1977 {
1978         size_t size;
1979         u32 addr;
1980         int ret;
1981
1982         size = param_header->length * sizeof(u32);
1983         addr = SFDP_PARAM_HEADER_PTP(param_header);
1984
1985         nor->manufacturer_sfdp = devm_kmalloc(nor->dev, size, GFP_KERNEL);
1986         if (!nor->manufacturer_sfdp)
1987                 return -ENOMEM;
1988
1989         ret = spi_nor_read_sfdp(nor, addr, size, nor->manufacturer_sfdp);
1990
1991         return ret;
1992 }
1993
1994 /**
1995  * spi_nor_parse_sfdp() - parse the Serial Flash Discoverable Parameters.
1996  * @nor:                pointer to a 'struct spi_nor'
1997  * @params:             pointer to the 'struct spi_nor_flash_parameter' to be
1998  *                      filled
1999  *
2000  * The Serial Flash Discoverable Parameters are described by the JEDEC JESD216
2001  * specification. This is a standard which tends to supported by almost all
2002  * (Q)SPI memory manufacturers. Those hard-coded tables allow us to learn at
2003  * runtime the main parameters needed to perform basic SPI flash operations such
2004  * as Fast Read, Page Program or Sector Erase commands.
2005  *
2006  * Return: 0 on success, -errno otherwise.
2007  */
2008 static int spi_nor_parse_sfdp(struct spi_nor *nor,
2009                               struct spi_nor_flash_parameter *params)
2010 {
2011         const struct sfdp_parameter_header *param_header, *bfpt_header;
2012         struct sfdp_parameter_header *param_headers = NULL;
2013         struct sfdp_header header;
2014         size_t psize;
2015         int i, err;
2016
2017         /* Get the SFDP header. */
2018         err = spi_nor_read_sfdp(nor, 0, sizeof(header), &header);
2019         if (err < 0)
2020                 return err;
2021
2022         /* Check the SFDP header version. */
2023         if (le32_to_cpu(header.signature) != SFDP_SIGNATURE ||
2024             header.major != SFDP_JESD216_MAJOR)
2025                 return -EINVAL;
2026
2027         /*
2028          * Verify that the first and only mandatory parameter header is a
2029          * Basic Flash Parameter Table header as specified in JESD216.
2030          */
2031         bfpt_header = &header.bfpt_header;
2032         if (SFDP_PARAM_HEADER_ID(bfpt_header) != SFDP_BFPT_ID ||
2033             bfpt_header->major != SFDP_JESD216_MAJOR)
2034                 return -EINVAL;
2035
2036         /*
2037          * Allocate memory then read all parameter headers with a single
2038          * Read SFDP command. These parameter headers will actually be parsed
2039          * twice: a first time to get the latest revision of the basic flash
2040          * parameter table, then a second time to handle the supported optional
2041          * tables.
2042          * Hence we read the parameter headers once for all to reduce the
2043          * processing time. Also we use kmalloc() instead of devm_kmalloc()
2044          * because we don't need to keep these parameter headers: the allocated
2045          * memory is always released with kfree() before exiting this function.
2046          */
2047         if (header.nph) {
2048                 psize = header.nph * sizeof(*param_headers);
2049
2050                 param_headers = kmalloc(psize, GFP_KERNEL);
2051                 if (!param_headers)
2052                         return -ENOMEM;
2053
2054                 err = spi_nor_read_sfdp(nor, sizeof(header),
2055                                         psize, param_headers);
2056                 if (err < 0) {
2057                         dev_err(nor->dev,
2058                                 "failed to read SFDP parameter headers\n");
2059                         goto exit;
2060                 }
2061         }
2062
2063         /*
2064          * Check other parameter headers to get the latest revision of
2065          * the basic flash parameter table.
2066          */
2067         for (i = 0; i < header.nph; i++) {
2068                 param_header = &param_headers[i];
2069
2070                 if (SFDP_PARAM_HEADER_ID(param_header) == SFDP_BFPT_ID &&
2071                     param_header->major == SFDP_JESD216_MAJOR &&
2072                     (param_header->minor > bfpt_header->minor ||
2073                      (param_header->minor == bfpt_header->minor &&
2074                       param_header->length > bfpt_header->length)))
2075                         bfpt_header = param_header;
2076         }
2077
2078         err = spi_nor_parse_bfpt(nor, bfpt_header, params);
2079         if (err)
2080                 goto exit;
2081
2082         /* Parse other parameter headers. */
2083         for (i = 0; i < header.nph; i++) {
2084                 param_header = &param_headers[i];
2085
2086                 switch (SFDP_PARAM_HEADER_ID(param_header)) {
2087                 case SFDP_SECTOR_MAP_ID:
2088                         dev_info(nor->dev,
2089                                  "non-uniform erase sector maps are not supported yet.\n");
2090                         break;
2091
2092                 case SFDP_SST_ID:
2093                         err = spi_nor_parse_microchip_sfdp(nor, param_header);
2094                         break;
2095
2096                 default:
2097                         break;
2098                 }
2099
2100                 if (err) {
2101                         dev_warn(nor->dev,
2102                                  "Failed to parse optional parameter table: %04x\n",
2103                                  SFDP_PARAM_HEADER_ID(param_header));
2104                         /*
2105                          * Let's not drop all information we extracted so far
2106                          * if optional table parsers fail. In case of failing,
2107                          * each optional parser is responsible to roll back to
2108                          * the previously known spi_nor data.
2109                          */
2110                         err = 0;
2111                 }
2112         }
2113
2114 exit:
2115         kfree(param_headers);
2116         return err;
2117 }
2118 #else
2119 static int spi_nor_parse_sfdp(struct spi_nor *nor,
2120                               struct spi_nor_flash_parameter *params)
2121 {
2122         return -EINVAL;
2123 }
2124 #endif /* SPI_FLASH_SFDP_SUPPORT */
2125
2126 /**
2127  * spi_nor_post_sfdp_fixups() - Updates the flash's parameters and settings
2128  * after SFDP has been parsed (is also called for SPI NORs that do not
2129  * support RDSFDP).
2130  * @nor:        pointer to a 'struct spi_nor'
2131  *
2132  * Typically used to tweak various parameters that could not be extracted by
2133  * other means (i.e. when information provided by the SFDP/flash_info tables
2134  * are incomplete or wrong).
2135  */
2136 static void spi_nor_post_sfdp_fixups(struct spi_nor *nor,
2137                                      struct spi_nor_flash_parameter *params)
2138 {
2139         if (nor->fixups && nor->fixups->post_sfdp)
2140                 nor->fixups->post_sfdp(nor, params);
2141 }
2142
2143 static void spi_nor_default_init_fixups(struct spi_nor *nor)
2144 {
2145         if (nor->fixups && nor->fixups->default_init)
2146                 nor->fixups->default_init(nor);
2147 }
2148
2149 static int spi_nor_init_params(struct spi_nor *nor,
2150                                const struct flash_info *info,
2151                                struct spi_nor_flash_parameter *params)
2152 {
2153         /* Set legacy flash parameters as default. */
2154         memset(params, 0, sizeof(*params));
2155
2156         /* Set SPI NOR sizes. */
2157         params->size = info->sector_size * info->n_sectors;
2158         params->page_size = info->page_size;
2159
2160         /* (Fast) Read settings. */
2161         params->hwcaps.mask |= SNOR_HWCAPS_READ;
2162         spi_nor_set_read_settings(&params->reads[SNOR_CMD_READ],
2163                                   0, 0, SPINOR_OP_READ,
2164                                   SNOR_PROTO_1_1_1);
2165
2166         if (!(info->flags & SPI_NOR_NO_FR)) {
2167                 params->hwcaps.mask |= SNOR_HWCAPS_READ_FAST;
2168                 spi_nor_set_read_settings(&params->reads[SNOR_CMD_READ_FAST],
2169                                           0, 8, SPINOR_OP_READ_FAST,
2170                                           SNOR_PROTO_1_1_1);
2171         }
2172
2173         if (info->flags & SPI_NOR_DUAL_READ) {
2174                 params->hwcaps.mask |= SNOR_HWCAPS_READ_1_1_2;
2175                 spi_nor_set_read_settings(&params->reads[SNOR_CMD_READ_1_1_2],
2176                                           0, 8, SPINOR_OP_READ_1_1_2,
2177                                           SNOR_PROTO_1_1_2);
2178         }
2179
2180         if (info->flags & SPI_NOR_QUAD_READ) {
2181                 params->hwcaps.mask |= SNOR_HWCAPS_READ_1_1_4;
2182                 spi_nor_set_read_settings(&params->reads[SNOR_CMD_READ_1_1_4],
2183                                           0, 8, SPINOR_OP_READ_1_1_4,
2184                                           SNOR_PROTO_1_1_4);
2185         }
2186
2187         if (info->flags & SPI_NOR_OCTAL_READ) {
2188                 params->hwcaps.mask |= SNOR_HWCAPS_READ_1_1_8;
2189                 spi_nor_set_read_settings(&params->reads[SNOR_CMD_READ_1_1_8],
2190                                           0, 8, SPINOR_OP_READ_1_1_8,
2191                                           SNOR_PROTO_1_1_8);
2192         }
2193
2194         /* Page Program settings. */
2195         params->hwcaps.mask |= SNOR_HWCAPS_PP;
2196         spi_nor_set_pp_settings(&params->page_programs[SNOR_CMD_PP],
2197                                 SPINOR_OP_PP, SNOR_PROTO_1_1_1);
2198
2199         if (info->flags & SPI_NOR_QUAD_READ) {
2200                 params->hwcaps.mask |= SNOR_HWCAPS_PP_1_1_4;
2201                 spi_nor_set_pp_settings(&params->page_programs[SNOR_CMD_PP_1_1_4],
2202                                         SPINOR_OP_PP_1_1_4, SNOR_PROTO_1_1_4);
2203         }
2204
2205         /* Select the procedure to set the Quad Enable bit. */
2206         if (params->hwcaps.mask & (SNOR_HWCAPS_READ_QUAD |
2207                                    SNOR_HWCAPS_PP_QUAD)) {
2208                 switch (JEDEC_MFR(info)) {
2209 #if defined(CONFIG_SPI_FLASH_MACRONIX) || defined(CONFIG_SPI_FLASH_ISSI)
2210                 case SNOR_MFR_MACRONIX:
2211                 case SNOR_MFR_ISSI:
2212                         params->quad_enable = macronix_quad_enable;
2213                         break;
2214 #endif
2215                 case SNOR_MFR_ST:
2216                 case SNOR_MFR_MICRON:
2217                         break;
2218
2219                 default:
2220 #if defined(CONFIG_SPI_FLASH_SPANSION) || defined(CONFIG_SPI_FLASH_WINBOND)
2221                         /* Kept only for backward compatibility purpose. */
2222                         params->quad_enable = spansion_read_cr_quad_enable;
2223 #endif
2224                         break;
2225                 }
2226         }
2227
2228         spi_nor_default_init_fixups(nor);
2229
2230         /* Override the parameters with data read from SFDP tables. */
2231         nor->addr_width = 0;
2232         nor->mtd.erasesize = 0;
2233         if ((info->flags & (SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ)) &&
2234             !(info->flags & SPI_NOR_SKIP_SFDP)) {
2235                 struct spi_nor_flash_parameter sfdp_params;
2236
2237                 memcpy(&sfdp_params, params, sizeof(sfdp_params));
2238                 if (spi_nor_parse_sfdp(nor, &sfdp_params)) {
2239                         nor->addr_width = 0;
2240                         nor->mtd.erasesize = 0;
2241                 } else {
2242                         memcpy(params, &sfdp_params, sizeof(*params));
2243                 }
2244         }
2245
2246         spi_nor_post_sfdp_fixups(nor, params);
2247
2248         return 0;
2249 }
2250
2251 static int spi_nor_hwcaps2cmd(u32 hwcaps, const int table[][2], size_t size)
2252 {
2253         size_t i;
2254
2255         for (i = 0; i < size; i++)
2256                 if (table[i][0] == (int)hwcaps)
2257                         return table[i][1];
2258
2259         return -EINVAL;
2260 }
2261
2262 static int spi_nor_hwcaps_read2cmd(u32 hwcaps)
2263 {
2264         static const int hwcaps_read2cmd[][2] = {
2265                 { SNOR_HWCAPS_READ,             SNOR_CMD_READ },
2266                 { SNOR_HWCAPS_READ_FAST,        SNOR_CMD_READ_FAST },
2267                 { SNOR_HWCAPS_READ_1_1_1_DTR,   SNOR_CMD_READ_1_1_1_DTR },
2268                 { SNOR_HWCAPS_READ_1_1_2,       SNOR_CMD_READ_1_1_2 },
2269                 { SNOR_HWCAPS_READ_1_2_2,       SNOR_CMD_READ_1_2_2 },
2270                 { SNOR_HWCAPS_READ_2_2_2,       SNOR_CMD_READ_2_2_2 },
2271                 { SNOR_HWCAPS_READ_1_2_2_DTR,   SNOR_CMD_READ_1_2_2_DTR },
2272                 { SNOR_HWCAPS_READ_1_1_4,       SNOR_CMD_READ_1_1_4 },
2273                 { SNOR_HWCAPS_READ_1_4_4,       SNOR_CMD_READ_1_4_4 },
2274                 { SNOR_HWCAPS_READ_4_4_4,       SNOR_CMD_READ_4_4_4 },
2275                 { SNOR_HWCAPS_READ_1_4_4_DTR,   SNOR_CMD_READ_1_4_4_DTR },
2276                 { SNOR_HWCAPS_READ_1_1_8,       SNOR_CMD_READ_1_1_8 },
2277                 { SNOR_HWCAPS_READ_1_8_8,       SNOR_CMD_READ_1_8_8 },
2278                 { SNOR_HWCAPS_READ_8_8_8,       SNOR_CMD_READ_8_8_8 },
2279                 { SNOR_HWCAPS_READ_1_8_8_DTR,   SNOR_CMD_READ_1_8_8_DTR },
2280         };
2281
2282         return spi_nor_hwcaps2cmd(hwcaps, hwcaps_read2cmd,
2283                                   ARRAY_SIZE(hwcaps_read2cmd));
2284 }
2285
2286 static int spi_nor_hwcaps_pp2cmd(u32 hwcaps)
2287 {
2288         static const int hwcaps_pp2cmd[][2] = {
2289                 { SNOR_HWCAPS_PP,               SNOR_CMD_PP },
2290                 { SNOR_HWCAPS_PP_1_1_4,         SNOR_CMD_PP_1_1_4 },
2291                 { SNOR_HWCAPS_PP_1_4_4,         SNOR_CMD_PP_1_4_4 },
2292                 { SNOR_HWCAPS_PP_4_4_4,         SNOR_CMD_PP_4_4_4 },
2293                 { SNOR_HWCAPS_PP_1_1_8,         SNOR_CMD_PP_1_1_8 },
2294                 { SNOR_HWCAPS_PP_1_8_8,         SNOR_CMD_PP_1_8_8 },
2295                 { SNOR_HWCAPS_PP_8_8_8,         SNOR_CMD_PP_8_8_8 },
2296         };
2297
2298         return spi_nor_hwcaps2cmd(hwcaps, hwcaps_pp2cmd,
2299                                   ARRAY_SIZE(hwcaps_pp2cmd));
2300 }
2301
2302 static int spi_nor_select_read(struct spi_nor *nor,
2303                                const struct spi_nor_flash_parameter *params,
2304                                u32 shared_hwcaps)
2305 {
2306         int cmd, best_match = fls(shared_hwcaps & SNOR_HWCAPS_READ_MASK) - 1;
2307         const struct spi_nor_read_command *read;
2308
2309         if (best_match < 0)
2310                 return -EINVAL;
2311
2312         cmd = spi_nor_hwcaps_read2cmd(BIT(best_match));
2313         if (cmd < 0)
2314                 return -EINVAL;
2315
2316         read = &params->reads[cmd];
2317         nor->read_opcode = read->opcode;
2318         nor->read_proto = read->proto;
2319
2320         /*
2321          * In the spi-nor framework, we don't need to make the difference
2322          * between mode clock cycles and wait state clock cycles.
2323          * Indeed, the value of the mode clock cycles is used by a QSPI
2324          * flash memory to know whether it should enter or leave its 0-4-4
2325          * (Continuous Read / XIP) mode.
2326          * eXecution In Place is out of the scope of the mtd sub-system.
2327          * Hence we choose to merge both mode and wait state clock cycles
2328          * into the so called dummy clock cycles.
2329          */
2330         nor->read_dummy = read->num_mode_clocks + read->num_wait_states;
2331         return 0;
2332 }
2333
2334 static int spi_nor_select_pp(struct spi_nor *nor,
2335                              const struct spi_nor_flash_parameter *params,
2336                              u32 shared_hwcaps)
2337 {
2338         int cmd, best_match = fls(shared_hwcaps & SNOR_HWCAPS_PP_MASK) - 1;
2339         const struct spi_nor_pp_command *pp;
2340
2341         if (best_match < 0)
2342                 return -EINVAL;
2343
2344         cmd = spi_nor_hwcaps_pp2cmd(BIT(best_match));
2345         if (cmd < 0)
2346                 return -EINVAL;
2347
2348         pp = &params->page_programs[cmd];
2349         nor->program_opcode = pp->opcode;
2350         nor->write_proto = pp->proto;
2351         return 0;
2352 }
2353
2354 static int spi_nor_select_erase(struct spi_nor *nor,
2355                                 const struct flash_info *info)
2356 {
2357         struct mtd_info *mtd = &nor->mtd;
2358
2359         /* Do nothing if already configured from SFDP. */
2360         if (mtd->erasesize)
2361                 return 0;
2362
2363 #ifdef CONFIG_SPI_FLASH_USE_4K_SECTORS
2364         /* prefer "small sector" erase if possible */
2365         if (info->flags & SECT_4K) {
2366                 nor->erase_opcode = SPINOR_OP_BE_4K;
2367                 mtd->erasesize = 4096;
2368         } else if (info->flags & SECT_4K_PMC) {
2369                 nor->erase_opcode = SPINOR_OP_BE_4K_PMC;
2370                 mtd->erasesize = 4096;
2371         } else
2372 #endif
2373         {
2374                 nor->erase_opcode = SPINOR_OP_SE;
2375                 mtd->erasesize = info->sector_size;
2376         }
2377         return 0;
2378 }
2379
2380 static int spi_nor_default_setup(struct spi_nor *nor,
2381                                  const struct flash_info *info,
2382                                  const struct spi_nor_flash_parameter *params,
2383                                  const struct spi_nor_hwcaps *hwcaps)
2384 {
2385         u32 ignored_mask, shared_mask;
2386         bool enable_quad_io;
2387         int err;
2388
2389         /*
2390          * Keep only the hardware capabilities supported by both the SPI
2391          * controller and the SPI flash memory.
2392          */
2393         shared_mask = hwcaps->mask & params->hwcaps.mask;
2394
2395         /* SPI n-n-n protocols are not supported yet. */
2396         ignored_mask = (SNOR_HWCAPS_READ_2_2_2 |
2397                         SNOR_HWCAPS_READ_4_4_4 |
2398                         SNOR_HWCAPS_READ_8_8_8 |
2399                         SNOR_HWCAPS_PP_4_4_4 |
2400                         SNOR_HWCAPS_PP_8_8_8);
2401         if (shared_mask & ignored_mask) {
2402                 dev_dbg(nor->dev,
2403                         "SPI n-n-n protocols are not supported yet.\n");
2404                 shared_mask &= ~ignored_mask;
2405         }
2406
2407         /* Select the (Fast) Read command. */
2408         err = spi_nor_select_read(nor, params, shared_mask);
2409         if (err) {
2410                 dev_dbg(nor->dev,
2411                         "can't select read settings supported by both the SPI controller and memory.\n");
2412                 return err;
2413         }
2414
2415         /* Select the Page Program command. */
2416         err = spi_nor_select_pp(nor, params, shared_mask);
2417         if (err) {
2418                 dev_dbg(nor->dev,
2419                         "can't select write settings supported by both the SPI controller and memory.\n");
2420                 return err;
2421         }
2422
2423         /* Select the Sector Erase command. */
2424         err = spi_nor_select_erase(nor, info);
2425         if (err) {
2426                 dev_dbg(nor->dev,
2427                         "can't select erase settings supported by both the SPI controller and memory.\n");
2428                 return err;
2429         }
2430
2431         /* Enable Quad I/O if needed. */
2432         enable_quad_io = (spi_nor_get_protocol_width(nor->read_proto) == 4 ||
2433                           spi_nor_get_protocol_width(nor->write_proto) == 4);
2434         if (enable_quad_io && params->quad_enable)
2435                 nor->quad_enable = params->quad_enable;
2436         else
2437                 nor->quad_enable = NULL;
2438
2439         return 0;
2440 }
2441
2442 static int spi_nor_setup(struct spi_nor *nor, const struct flash_info *info,
2443                          const struct spi_nor_flash_parameter *params,
2444                          const struct spi_nor_hwcaps *hwcaps)
2445 {
2446         if (!nor->setup)
2447                 return 0;
2448
2449         return nor->setup(nor, info, params, hwcaps);
2450 }
2451
2452 static int spi_nor_init(struct spi_nor *nor)
2453 {
2454         int err;
2455
2456         /*
2457          * Atmel, SST, Intel/Numonyx, and others serial NOR tend to power up
2458          * with the software protection bits set
2459          */
2460         if (IS_ENABLED(CONFIG_SPI_FLASH_UNLOCK_ALL) &&
2461             (JEDEC_MFR(nor->info) == SNOR_MFR_ATMEL ||
2462              JEDEC_MFR(nor->info) == SNOR_MFR_INTEL ||
2463              JEDEC_MFR(nor->info) == SNOR_MFR_SST ||
2464              nor->info->flags & SPI_NOR_HAS_LOCK)) {
2465                 write_enable(nor);
2466                 write_sr(nor, 0);
2467                 spi_nor_wait_till_ready(nor);
2468         }
2469
2470         if (nor->quad_enable) {
2471                 err = nor->quad_enable(nor);
2472                 if (err) {
2473                         dev_dbg(nor->dev, "quad mode not supported\n");
2474                         return err;
2475                 }
2476         }
2477
2478         if (nor->addr_width == 4 &&
2479             (JEDEC_MFR(nor->info) != SNOR_MFR_SPANSION) &&
2480             !(nor->info->flags & SPI_NOR_4B_OPCODES)) {
2481                 /*
2482                  * If the RESET# pin isn't hooked up properly, or the system
2483                  * otherwise doesn't perform a reset command in the boot
2484                  * sequence, it's impossible to 100% protect against unexpected
2485                  * reboots (e.g., crashes). Warn the user (or hopefully, system
2486                  * designer) that this is bad.
2487                  */
2488                 if (nor->flags & SNOR_F_BROKEN_RESET)
2489                         debug("enabling reset hack; may not recover from unexpected reboots\n");
2490                 set_4byte(nor, nor->info, 1);
2491         }
2492
2493         return 0;
2494 }
2495
2496 void spi_nor_set_fixups(struct spi_nor *nor)
2497 {
2498 }
2499
2500 int spi_nor_scan(struct spi_nor *nor)
2501 {
2502         struct spi_nor_flash_parameter params;
2503         const struct flash_info *info = NULL;
2504         struct mtd_info *mtd = &nor->mtd;
2505         struct spi_nor_hwcaps hwcaps = {
2506                 .mask = SNOR_HWCAPS_READ |
2507                         SNOR_HWCAPS_READ_FAST |
2508                         SNOR_HWCAPS_PP,
2509         };
2510         struct spi_slave *spi = nor->spi;
2511         int ret;
2512
2513         /* Reset SPI protocol for all commands. */
2514         nor->reg_proto = SNOR_PROTO_1_1_1;
2515         nor->read_proto = SNOR_PROTO_1_1_1;
2516         nor->write_proto = SNOR_PROTO_1_1_1;
2517         nor->read = spi_nor_read_data;
2518         nor->write = spi_nor_write_data;
2519         nor->read_reg = spi_nor_read_reg;
2520         nor->write_reg = spi_nor_write_reg;
2521
2522         nor->setup = spi_nor_default_setup;
2523
2524         if (spi->mode & SPI_RX_OCTAL) {
2525                 hwcaps.mask |= SNOR_HWCAPS_READ_1_1_8;
2526
2527                 if (spi->mode & SPI_TX_OCTAL)
2528                         hwcaps.mask |= (SNOR_HWCAPS_READ_1_8_8 |
2529                                         SNOR_HWCAPS_PP_1_1_8 |
2530                                         SNOR_HWCAPS_PP_1_8_8);
2531         } else if (spi->mode & SPI_RX_QUAD) {
2532                 hwcaps.mask |= SNOR_HWCAPS_READ_1_1_4;
2533
2534                 if (spi->mode & SPI_TX_QUAD)
2535                         hwcaps.mask |= (SNOR_HWCAPS_READ_1_4_4 |
2536                                         SNOR_HWCAPS_PP_1_1_4 |
2537                                         SNOR_HWCAPS_PP_1_4_4);
2538         } else if (spi->mode & SPI_RX_DUAL) {
2539                 hwcaps.mask |= SNOR_HWCAPS_READ_1_1_2;
2540
2541                 if (spi->mode & SPI_TX_DUAL)
2542                         hwcaps.mask |= SNOR_HWCAPS_READ_1_2_2;
2543         }
2544
2545         info = spi_nor_read_id(nor);
2546         if (IS_ERR_OR_NULL(info))
2547                 return -ENOENT;
2548         nor->info = info;
2549
2550         spi_nor_set_fixups(nor);
2551
2552         /* Parse the Serial Flash Discoverable Parameters table. */
2553         ret = spi_nor_init_params(nor, info, &params);
2554         if (ret)
2555                 return ret;
2556
2557         if (!mtd->name)
2558                 mtd->name = info->name;
2559         mtd->dev = nor->dev;
2560         mtd->priv = nor;
2561         mtd->type = MTD_NORFLASH;
2562         mtd->writesize = 1;
2563         mtd->flags = MTD_CAP_NORFLASH;
2564         mtd->size = params.size;
2565         mtd->_erase = spi_nor_erase;
2566         mtd->_read = spi_nor_read;
2567         mtd->_write = spi_nor_write;
2568
2569 #if defined(CONFIG_SPI_FLASH_STMICRO) || defined(CONFIG_SPI_FLASH_SST)
2570         /* NOR protection support for STmicro/Micron chips and similar */
2571         if (JEDEC_MFR(info) == SNOR_MFR_ST ||
2572             JEDEC_MFR(info) == SNOR_MFR_MICRON ||
2573             JEDEC_MFR(info) == SNOR_MFR_SST ||
2574                         info->flags & SPI_NOR_HAS_LOCK) {
2575                 nor->flash_lock = stm_lock;
2576                 nor->flash_unlock = stm_unlock;
2577                 nor->flash_is_locked = stm_is_locked;
2578         }
2579 #endif
2580
2581 #ifdef CONFIG_SPI_FLASH_SST
2582         /*
2583          * sst26 series block protection implementation differs from other
2584          * series.
2585          */
2586         if (info->flags & SPI_NOR_HAS_SST26LOCK) {
2587                 nor->flash_lock = sst26_lock;
2588                 nor->flash_unlock = sst26_unlock;
2589                 nor->flash_is_locked = sst26_is_locked;
2590         }
2591 #endif
2592
2593         if (info->flags & USE_FSR)
2594                 nor->flags |= SNOR_F_USE_FSR;
2595         if (info->flags & SPI_NOR_HAS_TB)
2596                 nor->flags |= SNOR_F_HAS_SR_TB;
2597         if (info->flags & NO_CHIP_ERASE)
2598                 nor->flags |= SNOR_F_NO_OP_CHIP_ERASE;
2599         if (info->flags & USE_CLSR)
2600                 nor->flags |= SNOR_F_USE_CLSR;
2601
2602         if (info->flags & SPI_NOR_NO_ERASE)
2603                 mtd->flags |= MTD_NO_ERASE;
2604
2605         nor->page_size = params.page_size;
2606         mtd->writebufsize = nor->page_size;
2607
2608         /* Some devices cannot do fast-read, no matter what DT tells us */
2609         if ((info->flags & SPI_NOR_NO_FR) || (spi->mode & SPI_RX_SLOW))
2610                 params.hwcaps.mask &= ~SNOR_HWCAPS_READ_FAST;
2611
2612         /*
2613          * Configure the SPI memory:
2614          * - select op codes for (Fast) Read, Page Program and Sector Erase.
2615          * - set the number of dummy cycles (mode cycles + wait states).
2616          * - set the SPI protocols for register and memory accesses.
2617          * - set the Quad Enable bit if needed (required by SPI x-y-4 protos).
2618          */
2619         ret = spi_nor_setup(nor, info, &params, &hwcaps);
2620         if (ret)
2621                 return ret;
2622
2623         if (nor->addr_width) {
2624                 /* already configured from SFDP */
2625         } else if (info->addr_width) {
2626                 nor->addr_width = info->addr_width;
2627         } else {
2628                 nor->addr_width = 3;
2629         }
2630
2631         if (nor->addr_width == 3 && mtd->size > SZ_16M) {
2632 #ifndef CONFIG_SPI_FLASH_BAR
2633                 /* enable 4-byte addressing if the device exceeds 16MiB */
2634                 nor->addr_width = 4;
2635                 if (JEDEC_MFR(info) == SNOR_MFR_SPANSION ||
2636                     info->flags & SPI_NOR_4B_OPCODES)
2637                         spi_nor_set_4byte_opcodes(nor, info);
2638 #else
2639         /* Configure the BAR - discover bank cmds and read current bank */
2640         nor->addr_width = 3;
2641         ret = read_bar(nor, info);
2642         if (ret < 0)
2643                 return ret;
2644 #endif
2645         }
2646
2647         if (nor->addr_width > SPI_NOR_MAX_ADDR_WIDTH) {
2648                 dev_dbg(nor->dev, "address width is too large: %u\n",
2649                         nor->addr_width);
2650                 return -EINVAL;
2651         }
2652
2653         /* Send all the required SPI flash commands to initialize device */
2654         ret = spi_nor_init(nor);
2655         if (ret)
2656                 return ret;
2657
2658         nor->name = mtd->name;
2659         nor->size = mtd->size;
2660         nor->erase_size = mtd->erasesize;
2661         nor->sector_size = mtd->erasesize;
2662
2663 #ifndef CONFIG_SPL_BUILD
2664         printf("SF: Detected %s with page size ", nor->name);
2665         print_size(nor->page_size, ", erase size ");
2666         print_size(nor->erase_size, ", total ");
2667         print_size(nor->size, "");
2668         puts("\n");
2669 #endif
2670
2671         return 0;
2672 }
2673
2674 /* U-Boot specific functions, need to extend MTD to support these */
2675 int spi_flash_cmd_get_sw_write_prot(struct spi_nor *nor)
2676 {
2677         int sr = read_sr(nor);
2678
2679         if (sr < 0)
2680                 return sr;
2681
2682         return (sr >> 2) & 7;
2683 }