GNU Linux-libre 5.10.153-gnu1
[releases.git] / drivers / mtd / 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
10 #include <linux/err.h>
11 #include <linux/errno.h>
12 #include <linux/module.h>
13 #include <linux/device.h>
14 #include <linux/mutex.h>
15 #include <linux/math64.h>
16 #include <linux/sizes.h>
17 #include <linux/slab.h>
18
19 #include <linux/mtd/mtd.h>
20 #include <linux/of_platform.h>
21 #include <linux/sched/task_stack.h>
22 #include <linux/spi/flash.h>
23 #include <linux/mtd/spi-nor.h>
24
25 #include "core.h"
26
27 /* Define max times to check status register before we give up. */
28
29 /*
30  * For everything but full-chip erase; probably could be much smaller, but kept
31  * around for safety for now
32  */
33 #define DEFAULT_READY_WAIT_JIFFIES              (40UL * HZ)
34
35 /*
36  * For full-chip erase, calibrated to a 2MB flash (M25P16); should be scaled up
37  * for larger flash
38  */
39 #define CHIP_ERASE_2MB_READY_WAIT_JIFFIES       (40UL * HZ)
40
41 #define SPI_NOR_MAX_ADDR_WIDTH  4
42
43 /**
44  * spi_nor_spimem_bounce() - check if a bounce buffer is needed for the data
45  *                           transfer
46  * @nor:        pointer to 'struct spi_nor'
47  * @op:         pointer to 'struct spi_mem_op' template for transfer
48  *
49  * If we have to use the bounce buffer, the data field in @op will be updated.
50  *
51  * Return: true if the bounce buffer is needed, false if not
52  */
53 static bool spi_nor_spimem_bounce(struct spi_nor *nor, struct spi_mem_op *op)
54 {
55         /* op->data.buf.in occupies the same memory as op->data.buf.out */
56         if (object_is_on_stack(op->data.buf.in) ||
57             !virt_addr_valid(op->data.buf.in)) {
58                 if (op->data.nbytes > nor->bouncebuf_size)
59                         op->data.nbytes = nor->bouncebuf_size;
60                 op->data.buf.in = nor->bouncebuf;
61                 return true;
62         }
63
64         return false;
65 }
66
67 /**
68  * spi_nor_spimem_exec_op() - execute a memory operation
69  * @nor:        pointer to 'struct spi_nor'
70  * @op:         pointer to 'struct spi_mem_op' template for transfer
71  *
72  * Return: 0 on success, -error otherwise.
73  */
74 static int spi_nor_spimem_exec_op(struct spi_nor *nor, struct spi_mem_op *op)
75 {
76         int error;
77
78         error = spi_mem_adjust_op_size(nor->spimem, op);
79         if (error)
80                 return error;
81
82         return spi_mem_exec_op(nor->spimem, op);
83 }
84
85 /**
86  * spi_nor_spimem_read_data() - read data from flash's memory region via
87  *                              spi-mem
88  * @nor:        pointer to 'struct spi_nor'
89  * @from:       offset to read from
90  * @len:        number of bytes to read
91  * @buf:        pointer to dst buffer
92  *
93  * Return: number of bytes read successfully, -errno otherwise
94  */
95 static ssize_t spi_nor_spimem_read_data(struct spi_nor *nor, loff_t from,
96                                         size_t len, u8 *buf)
97 {
98         struct spi_mem_op op =
99                 SPI_MEM_OP(SPI_MEM_OP_CMD(nor->read_opcode, 1),
100                            SPI_MEM_OP_ADDR(nor->addr_width, from, 1),
101                            SPI_MEM_OP_DUMMY(nor->read_dummy, 1),
102                            SPI_MEM_OP_DATA_IN(len, buf, 1));
103         bool usebouncebuf;
104         ssize_t nbytes;
105         int error;
106
107         /* get transfer protocols. */
108         op.cmd.buswidth = spi_nor_get_protocol_inst_nbits(nor->read_proto);
109         op.addr.buswidth = spi_nor_get_protocol_addr_nbits(nor->read_proto);
110         op.dummy.buswidth = op.addr.buswidth;
111         op.data.buswidth = spi_nor_get_protocol_data_nbits(nor->read_proto);
112
113         /* convert the dummy cycles to the number of bytes */
114         op.dummy.nbytes = (nor->read_dummy * op.dummy.buswidth) / 8;
115
116         usebouncebuf = spi_nor_spimem_bounce(nor, &op);
117
118         if (nor->dirmap.rdesc) {
119                 nbytes = spi_mem_dirmap_read(nor->dirmap.rdesc, op.addr.val,
120                                              op.data.nbytes, op.data.buf.in);
121         } else {
122                 error = spi_nor_spimem_exec_op(nor, &op);
123                 if (error)
124                         return error;
125                 nbytes = op.data.nbytes;
126         }
127
128         if (usebouncebuf && nbytes > 0)
129                 memcpy(buf, op.data.buf.in, nbytes);
130
131         return nbytes;
132 }
133
134 /**
135  * spi_nor_read_data() - read data from flash memory
136  * @nor:        pointer to 'struct spi_nor'
137  * @from:       offset to read from
138  * @len:        number of bytes to read
139  * @buf:        pointer to dst buffer
140  *
141  * Return: number of bytes read successfully, -errno otherwise
142  */
143 ssize_t spi_nor_read_data(struct spi_nor *nor, loff_t from, size_t len, u8 *buf)
144 {
145         if (nor->spimem)
146                 return spi_nor_spimem_read_data(nor, from, len, buf);
147
148         return nor->controller_ops->read(nor, from, len, buf);
149 }
150
151 /**
152  * spi_nor_spimem_write_data() - write data to flash memory via
153  *                               spi-mem
154  * @nor:        pointer to 'struct spi_nor'
155  * @to:         offset to write to
156  * @len:        number of bytes to write
157  * @buf:        pointer to src buffer
158  *
159  * Return: number of bytes written successfully, -errno otherwise
160  */
161 static ssize_t spi_nor_spimem_write_data(struct spi_nor *nor, loff_t to,
162                                          size_t len, const u8 *buf)
163 {
164         struct spi_mem_op op =
165                 SPI_MEM_OP(SPI_MEM_OP_CMD(nor->program_opcode, 1),
166                            SPI_MEM_OP_ADDR(nor->addr_width, to, 1),
167                            SPI_MEM_OP_NO_DUMMY,
168                            SPI_MEM_OP_DATA_OUT(len, buf, 1));
169         ssize_t nbytes;
170         int error;
171
172         op.cmd.buswidth = spi_nor_get_protocol_inst_nbits(nor->write_proto);
173         op.addr.buswidth = spi_nor_get_protocol_addr_nbits(nor->write_proto);
174         op.data.buswidth = spi_nor_get_protocol_data_nbits(nor->write_proto);
175
176         if (nor->program_opcode == SPINOR_OP_AAI_WP && nor->sst_write_second)
177                 op.addr.nbytes = 0;
178
179         if (spi_nor_spimem_bounce(nor, &op))
180                 memcpy(nor->bouncebuf, buf, op.data.nbytes);
181
182         if (nor->dirmap.wdesc) {
183                 nbytes = spi_mem_dirmap_write(nor->dirmap.wdesc, op.addr.val,
184                                               op.data.nbytes, op.data.buf.out);
185         } else {
186                 error = spi_nor_spimem_exec_op(nor, &op);
187                 if (error)
188                         return error;
189                 nbytes = op.data.nbytes;
190         }
191
192         return nbytes;
193 }
194
195 /**
196  * spi_nor_write_data() - write data to flash memory
197  * @nor:        pointer to 'struct spi_nor'
198  * @to:         offset to write to
199  * @len:        number of bytes to write
200  * @buf:        pointer to src buffer
201  *
202  * Return: number of bytes written successfully, -errno otherwise
203  */
204 ssize_t spi_nor_write_data(struct spi_nor *nor, loff_t to, size_t len,
205                            const u8 *buf)
206 {
207         if (nor->spimem)
208                 return spi_nor_spimem_write_data(nor, to, len, buf);
209
210         return nor->controller_ops->write(nor, to, len, buf);
211 }
212
213 /**
214  * spi_nor_write_enable() - Set write enable latch with Write Enable command.
215  * @nor:        pointer to 'struct spi_nor'.
216  *
217  * Return: 0 on success, -errno otherwise.
218  */
219 int spi_nor_write_enable(struct spi_nor *nor)
220 {
221         int ret;
222
223         if (nor->spimem) {
224                 struct spi_mem_op op =
225                         SPI_MEM_OP(SPI_MEM_OP_CMD(SPINOR_OP_WREN, 1),
226                                    SPI_MEM_OP_NO_ADDR,
227                                    SPI_MEM_OP_NO_DUMMY,
228                                    SPI_MEM_OP_NO_DATA);
229
230                 ret = spi_mem_exec_op(nor->spimem, &op);
231         } else {
232                 ret = nor->controller_ops->write_reg(nor, SPINOR_OP_WREN,
233                                                      NULL, 0);
234         }
235
236         if (ret)
237                 dev_dbg(nor->dev, "error %d on Write Enable\n", ret);
238
239         return ret;
240 }
241
242 /**
243  * spi_nor_write_disable() - Send Write Disable instruction to the chip.
244  * @nor:        pointer to 'struct spi_nor'.
245  *
246  * Return: 0 on success, -errno otherwise.
247  */
248 int spi_nor_write_disable(struct spi_nor *nor)
249 {
250         int ret;
251
252         if (nor->spimem) {
253                 struct spi_mem_op op =
254                         SPI_MEM_OP(SPI_MEM_OP_CMD(SPINOR_OP_WRDI, 1),
255                                    SPI_MEM_OP_NO_ADDR,
256                                    SPI_MEM_OP_NO_DUMMY,
257                                    SPI_MEM_OP_NO_DATA);
258
259                 ret = spi_mem_exec_op(nor->spimem, &op);
260         } else {
261                 ret = nor->controller_ops->write_reg(nor, SPINOR_OP_WRDI,
262                                                      NULL, 0);
263         }
264
265         if (ret)
266                 dev_dbg(nor->dev, "error %d on Write Disable\n", ret);
267
268         return ret;
269 }
270
271 /**
272  * spi_nor_read_sr() - Read the Status Register.
273  * @nor:        pointer to 'struct spi_nor'.
274  * @sr:         pointer to a DMA-able buffer where the value of the
275  *              Status Register will be written.
276  *
277  * Return: 0 on success, -errno otherwise.
278  */
279 static int spi_nor_read_sr(struct spi_nor *nor, u8 *sr)
280 {
281         int ret;
282
283         if (nor->spimem) {
284                 struct spi_mem_op op =
285                         SPI_MEM_OP(SPI_MEM_OP_CMD(SPINOR_OP_RDSR, 1),
286                                    SPI_MEM_OP_NO_ADDR,
287                                    SPI_MEM_OP_NO_DUMMY,
288                                    SPI_MEM_OP_DATA_IN(1, sr, 1));
289
290                 ret = spi_mem_exec_op(nor->spimem, &op);
291         } else {
292                 ret = nor->controller_ops->read_reg(nor, SPINOR_OP_RDSR,
293                                                     sr, 1);
294         }
295
296         if (ret)
297                 dev_dbg(nor->dev, "error %d reading SR\n", ret);
298
299         return ret;
300 }
301
302 /**
303  * spi_nor_read_fsr() - Read the Flag Status Register.
304  * @nor:        pointer to 'struct spi_nor'
305  * @fsr:        pointer to a DMA-able buffer where the value of the
306  *              Flag Status Register will be written.
307  *
308  * Return: 0 on success, -errno otherwise.
309  */
310 static int spi_nor_read_fsr(struct spi_nor *nor, u8 *fsr)
311 {
312         int ret;
313
314         if (nor->spimem) {
315                 struct spi_mem_op op =
316                         SPI_MEM_OP(SPI_MEM_OP_CMD(SPINOR_OP_RDFSR, 1),
317                                    SPI_MEM_OP_NO_ADDR,
318                                    SPI_MEM_OP_NO_DUMMY,
319                                    SPI_MEM_OP_DATA_IN(1, fsr, 1));
320
321                 ret = spi_mem_exec_op(nor->spimem, &op);
322         } else {
323                 ret = nor->controller_ops->read_reg(nor, SPINOR_OP_RDFSR,
324                                                     fsr, 1);
325         }
326
327         if (ret)
328                 dev_dbg(nor->dev, "error %d reading FSR\n", ret);
329
330         return ret;
331 }
332
333 /**
334  * spi_nor_read_cr() - Read the Configuration Register using the
335  * SPINOR_OP_RDCR (35h) command.
336  * @nor:        pointer to 'struct spi_nor'
337  * @cr:         pointer to a DMA-able buffer where the value of the
338  *              Configuration Register will be written.
339  *
340  * Return: 0 on success, -errno otherwise.
341  */
342 static int spi_nor_read_cr(struct spi_nor *nor, u8 *cr)
343 {
344         int ret;
345
346         if (nor->spimem) {
347                 struct spi_mem_op op =
348                         SPI_MEM_OP(SPI_MEM_OP_CMD(SPINOR_OP_RDCR, 1),
349                                    SPI_MEM_OP_NO_ADDR,
350                                    SPI_MEM_OP_NO_DUMMY,
351                                    SPI_MEM_OP_DATA_IN(1, cr, 1));
352
353                 ret = spi_mem_exec_op(nor->spimem, &op);
354         } else {
355                 ret = nor->controller_ops->read_reg(nor, SPINOR_OP_RDCR, cr, 1);
356         }
357
358         if (ret)
359                 dev_dbg(nor->dev, "error %d reading CR\n", ret);
360
361         return ret;
362 }
363
364 /**
365  * spi_nor_set_4byte_addr_mode() - Enter/Exit 4-byte address mode.
366  * @nor:        pointer to 'struct spi_nor'.
367  * @enable:     true to enter the 4-byte address mode, false to exit the 4-byte
368  *              address mode.
369  *
370  * Return: 0 on success, -errno otherwise.
371  */
372 int spi_nor_set_4byte_addr_mode(struct spi_nor *nor, bool enable)
373 {
374         int ret;
375
376         if (nor->spimem) {
377                 struct spi_mem_op op =
378                         SPI_MEM_OP(SPI_MEM_OP_CMD(enable ?
379                                                   SPINOR_OP_EN4B :
380                                                   SPINOR_OP_EX4B,
381                                                   1),
382                                   SPI_MEM_OP_NO_ADDR,
383                                   SPI_MEM_OP_NO_DUMMY,
384                                   SPI_MEM_OP_NO_DATA);
385
386                 ret = spi_mem_exec_op(nor->spimem, &op);
387         } else {
388                 ret = nor->controller_ops->write_reg(nor,
389                                                      enable ? SPINOR_OP_EN4B :
390                                                               SPINOR_OP_EX4B,
391                                                      NULL, 0);
392         }
393
394         if (ret)
395                 dev_dbg(nor->dev, "error %d setting 4-byte mode\n", ret);
396
397         return ret;
398 }
399
400 /**
401  * spansion_set_4byte_addr_mode() - Set 4-byte address mode for Spansion
402  * flashes.
403  * @nor:        pointer to 'struct spi_nor'.
404  * @enable:     true to enter the 4-byte address mode, false to exit the 4-byte
405  *              address mode.
406  *
407  * Return: 0 on success, -errno otherwise.
408  */
409 static int spansion_set_4byte_addr_mode(struct spi_nor *nor, bool enable)
410 {
411         int ret;
412
413         nor->bouncebuf[0] = enable << 7;
414
415         if (nor->spimem) {
416                 struct spi_mem_op op =
417                         SPI_MEM_OP(SPI_MEM_OP_CMD(SPINOR_OP_BRWR, 1),
418                                    SPI_MEM_OP_NO_ADDR,
419                                    SPI_MEM_OP_NO_DUMMY,
420                                    SPI_MEM_OP_DATA_OUT(1, nor->bouncebuf, 1));
421
422                 ret = spi_mem_exec_op(nor->spimem, &op);
423         } else {
424                 ret = nor->controller_ops->write_reg(nor, SPINOR_OP_BRWR,
425                                                      nor->bouncebuf, 1);
426         }
427
428         if (ret)
429                 dev_dbg(nor->dev, "error %d setting 4-byte mode\n", ret);
430
431         return ret;
432 }
433
434 /**
435  * spi_nor_write_ear() - Write Extended Address Register.
436  * @nor:        pointer to 'struct spi_nor'.
437  * @ear:        value to write to the Extended Address Register.
438  *
439  * Return: 0 on success, -errno otherwise.
440  */
441 int spi_nor_write_ear(struct spi_nor *nor, u8 ear)
442 {
443         int ret;
444
445         nor->bouncebuf[0] = ear;
446
447         if (nor->spimem) {
448                 struct spi_mem_op op =
449                         SPI_MEM_OP(SPI_MEM_OP_CMD(SPINOR_OP_WREAR, 1),
450                                    SPI_MEM_OP_NO_ADDR,
451                                    SPI_MEM_OP_NO_DUMMY,
452                                    SPI_MEM_OP_DATA_OUT(1, nor->bouncebuf, 1));
453
454                 ret = spi_mem_exec_op(nor->spimem, &op);
455         } else {
456                 ret = nor->controller_ops->write_reg(nor, SPINOR_OP_WREAR,
457                                                      nor->bouncebuf, 1);
458         }
459
460         if (ret)
461                 dev_dbg(nor->dev, "error %d writing EAR\n", ret);
462
463         return ret;
464 }
465
466 /**
467  * spi_nor_xread_sr() - Read the Status Register on S3AN flashes.
468  * @nor:        pointer to 'struct spi_nor'.
469  * @sr:         pointer to a DMA-able buffer where the value of the
470  *              Status Register will be written.
471  *
472  * Return: 0 on success, -errno otherwise.
473  */
474 int spi_nor_xread_sr(struct spi_nor *nor, u8 *sr)
475 {
476         int ret;
477
478         if (nor->spimem) {
479                 struct spi_mem_op op =
480                         SPI_MEM_OP(SPI_MEM_OP_CMD(SPINOR_OP_XRDSR, 1),
481                                    SPI_MEM_OP_NO_ADDR,
482                                    SPI_MEM_OP_NO_DUMMY,
483                                    SPI_MEM_OP_DATA_IN(1, sr, 1));
484
485                 ret = spi_mem_exec_op(nor->spimem, &op);
486         } else {
487                 ret = nor->controller_ops->read_reg(nor, SPINOR_OP_XRDSR,
488                                                     sr, 1);
489         }
490
491         if (ret)
492                 dev_dbg(nor->dev, "error %d reading XRDSR\n", ret);
493
494         return ret;
495 }
496
497 /**
498  * spi_nor_xsr_ready() - Query the Status Register of the S3AN flash to see if
499  * the flash is ready for new commands.
500  * @nor:        pointer to 'struct spi_nor'.
501  *
502  * Return: 1 if ready, 0 if not ready, -errno on errors.
503  */
504 static int spi_nor_xsr_ready(struct spi_nor *nor)
505 {
506         int ret;
507
508         ret = spi_nor_xread_sr(nor, nor->bouncebuf);
509         if (ret)
510                 return ret;
511
512         return !!(nor->bouncebuf[0] & XSR_RDY);
513 }
514
515 /**
516  * spi_nor_clear_sr() - Clear the Status Register.
517  * @nor:        pointer to 'struct spi_nor'.
518  */
519 static void spi_nor_clear_sr(struct spi_nor *nor)
520 {
521         int ret;
522
523         if (nor->spimem) {
524                 struct spi_mem_op op =
525                         SPI_MEM_OP(SPI_MEM_OP_CMD(SPINOR_OP_CLSR, 1),
526                                    SPI_MEM_OP_NO_ADDR,
527                                    SPI_MEM_OP_NO_DUMMY,
528                                    SPI_MEM_OP_NO_DATA);
529
530                 ret = spi_mem_exec_op(nor->spimem, &op);
531         } else {
532                 ret = nor->controller_ops->write_reg(nor, SPINOR_OP_CLSR,
533                                                      NULL, 0);
534         }
535
536         if (ret)
537                 dev_dbg(nor->dev, "error %d clearing SR\n", ret);
538 }
539
540 /**
541  * spi_nor_sr_ready() - Query the Status Register to see if the flash is ready
542  * for new commands.
543  * @nor:        pointer to 'struct spi_nor'.
544  *
545  * Return: 1 if ready, 0 if not ready, -errno on errors.
546  */
547 static int spi_nor_sr_ready(struct spi_nor *nor)
548 {
549         int ret = spi_nor_read_sr(nor, nor->bouncebuf);
550
551         if (ret)
552                 return ret;
553
554         if (nor->flags & SNOR_F_USE_CLSR &&
555             nor->bouncebuf[0] & (SR_E_ERR | SR_P_ERR)) {
556                 if (nor->bouncebuf[0] & SR_E_ERR)
557                         dev_err(nor->dev, "Erase Error occurred\n");
558                 else
559                         dev_err(nor->dev, "Programming Error occurred\n");
560
561                 spi_nor_clear_sr(nor);
562
563                 /*
564                  * WEL bit remains set to one when an erase or page program
565                  * error occurs. Issue a Write Disable command to protect
566                  * against inadvertent writes that can possibly corrupt the
567                  * contents of the memory.
568                  */
569                 ret = spi_nor_write_disable(nor);
570                 if (ret)
571                         return ret;
572
573                 return -EIO;
574         }
575
576         return !(nor->bouncebuf[0] & SR_WIP);
577 }
578
579 /**
580  * spi_nor_clear_fsr() - Clear the Flag Status Register.
581  * @nor:        pointer to 'struct spi_nor'.
582  */
583 static void spi_nor_clear_fsr(struct spi_nor *nor)
584 {
585         int ret;
586
587         if (nor->spimem) {
588                 struct spi_mem_op op =
589                         SPI_MEM_OP(SPI_MEM_OP_CMD(SPINOR_OP_CLFSR, 1),
590                                    SPI_MEM_OP_NO_ADDR,
591                                    SPI_MEM_OP_NO_DUMMY,
592                                    SPI_MEM_OP_NO_DATA);
593
594                 ret = spi_mem_exec_op(nor->spimem, &op);
595         } else {
596                 ret = nor->controller_ops->write_reg(nor, SPINOR_OP_CLFSR,
597                                                      NULL, 0);
598         }
599
600         if (ret)
601                 dev_dbg(nor->dev, "error %d clearing FSR\n", ret);
602 }
603
604 /**
605  * spi_nor_fsr_ready() - Query the Flag Status Register to see if the flash is
606  * ready for new commands.
607  * @nor:        pointer to 'struct spi_nor'.
608  *
609  * Return: 1 if ready, 0 if not ready, -errno on errors.
610  */
611 static int spi_nor_fsr_ready(struct spi_nor *nor)
612 {
613         int ret = spi_nor_read_fsr(nor, nor->bouncebuf);
614
615         if (ret)
616                 return ret;
617
618         if (nor->bouncebuf[0] & (FSR_E_ERR | FSR_P_ERR)) {
619                 if (nor->bouncebuf[0] & FSR_E_ERR)
620                         dev_err(nor->dev, "Erase operation failed.\n");
621                 else
622                         dev_err(nor->dev, "Program operation failed.\n");
623
624                 if (nor->bouncebuf[0] & FSR_PT_ERR)
625                         dev_err(nor->dev,
626                         "Attempted to modify a protected sector.\n");
627
628                 spi_nor_clear_fsr(nor);
629
630                 /*
631                  * WEL bit remains set to one when an erase or page program
632                  * error occurs. Issue a Write Disable command to protect
633                  * against inadvertent writes that can possibly corrupt the
634                  * contents of the memory.
635                  */
636                 ret = spi_nor_write_disable(nor);
637                 if (ret)
638                         return ret;
639
640                 return -EIO;
641         }
642
643         return !!(nor->bouncebuf[0] & FSR_READY);
644 }
645
646 /**
647  * spi_nor_ready() - Query the flash to see if it is ready for new commands.
648  * @nor:        pointer to 'struct spi_nor'.
649  *
650  * Return: 1 if ready, 0 if not ready, -errno on errors.
651  */
652 static int spi_nor_ready(struct spi_nor *nor)
653 {
654         int sr, fsr;
655
656         if (nor->flags & SNOR_F_READY_XSR_RDY)
657                 sr = spi_nor_xsr_ready(nor);
658         else
659                 sr = spi_nor_sr_ready(nor);
660         if (sr < 0)
661                 return sr;
662         fsr = nor->flags & SNOR_F_USE_FSR ? spi_nor_fsr_ready(nor) : 1;
663         if (fsr < 0)
664                 return fsr;
665         return sr && fsr;
666 }
667
668 /**
669  * spi_nor_wait_till_ready_with_timeout() - Service routine to read the
670  * Status Register until ready, or timeout occurs.
671  * @nor:                pointer to "struct spi_nor".
672  * @timeout_jiffies:    jiffies to wait until timeout.
673  *
674  * Return: 0 on success, -errno otherwise.
675  */
676 static int spi_nor_wait_till_ready_with_timeout(struct spi_nor *nor,
677                                                 unsigned long timeout_jiffies)
678 {
679         unsigned long deadline;
680         int timeout = 0, ret;
681
682         deadline = jiffies + timeout_jiffies;
683
684         while (!timeout) {
685                 if (time_after_eq(jiffies, deadline))
686                         timeout = 1;
687
688                 ret = spi_nor_ready(nor);
689                 if (ret < 0)
690                         return ret;
691                 if (ret)
692                         return 0;
693
694                 cond_resched();
695         }
696
697         dev_dbg(nor->dev, "flash operation timed out\n");
698
699         return -ETIMEDOUT;
700 }
701
702 /**
703  * spi_nor_wait_till_ready() - Wait for a predefined amount of time for the
704  * flash to be ready, or timeout occurs.
705  * @nor:        pointer to "struct spi_nor".
706  *
707  * Return: 0 on success, -errno otherwise.
708  */
709 int spi_nor_wait_till_ready(struct spi_nor *nor)
710 {
711         return spi_nor_wait_till_ready_with_timeout(nor,
712                                                     DEFAULT_READY_WAIT_JIFFIES);
713 }
714
715 /**
716  * spi_nor_write_sr() - Write the Status Register.
717  * @nor:        pointer to 'struct spi_nor'.
718  * @sr:         pointer to DMA-able buffer to write to the Status Register.
719  * @len:        number of bytes to write to the Status Register.
720  *
721  * Return: 0 on success, -errno otherwise.
722  */
723 static int spi_nor_write_sr(struct spi_nor *nor, const u8 *sr, size_t len)
724 {
725         int ret;
726
727         ret = spi_nor_write_enable(nor);
728         if (ret)
729                 return ret;
730
731         if (nor->spimem) {
732                 struct spi_mem_op op =
733                         SPI_MEM_OP(SPI_MEM_OP_CMD(SPINOR_OP_WRSR, 1),
734                                    SPI_MEM_OP_NO_ADDR,
735                                    SPI_MEM_OP_NO_DUMMY,
736                                    SPI_MEM_OP_DATA_OUT(len, sr, 1));
737
738                 ret = spi_mem_exec_op(nor->spimem, &op);
739         } else {
740                 ret = nor->controller_ops->write_reg(nor, SPINOR_OP_WRSR,
741                                                      sr, len);
742         }
743
744         if (ret) {
745                 dev_dbg(nor->dev, "error %d writing SR\n", ret);
746                 return ret;
747         }
748
749         return spi_nor_wait_till_ready(nor);
750 }
751
752 /**
753  * spi_nor_write_sr1_and_check() - Write one byte to the Status Register 1 and
754  * ensure that the byte written match the received value.
755  * @nor:        pointer to a 'struct spi_nor'.
756  * @sr1:        byte value to be written to the Status Register.
757  *
758  * Return: 0 on success, -errno otherwise.
759  */
760 static int spi_nor_write_sr1_and_check(struct spi_nor *nor, u8 sr1)
761 {
762         int ret;
763
764         nor->bouncebuf[0] = sr1;
765
766         ret = spi_nor_write_sr(nor, nor->bouncebuf, 1);
767         if (ret)
768                 return ret;
769
770         ret = spi_nor_read_sr(nor, nor->bouncebuf);
771         if (ret)
772                 return ret;
773
774         if (nor->bouncebuf[0] != sr1) {
775                 dev_dbg(nor->dev, "SR1: read back test failed\n");
776                 return -EIO;
777         }
778
779         return 0;
780 }
781
782 /**
783  * spi_nor_write_16bit_sr_and_check() - Write the Status Register 1 and the
784  * Status Register 2 in one shot. Ensure that the byte written in the Status
785  * Register 1 match the received value, and that the 16-bit Write did not
786  * affect what was already in the Status Register 2.
787  * @nor:        pointer to a 'struct spi_nor'.
788  * @sr1:        byte value to be written to the Status Register 1.
789  *
790  * Return: 0 on success, -errno otherwise.
791  */
792 static int spi_nor_write_16bit_sr_and_check(struct spi_nor *nor, u8 sr1)
793 {
794         int ret;
795         u8 *sr_cr = nor->bouncebuf;
796         u8 cr_written;
797
798         /* Make sure we don't overwrite the contents of Status Register 2. */
799         if (!(nor->flags & SNOR_F_NO_READ_CR)) {
800                 ret = spi_nor_read_cr(nor, &sr_cr[1]);
801                 if (ret)
802                         return ret;
803         } else if (nor->params->quad_enable) {
804                 /*
805                  * If the Status Register 2 Read command (35h) is not
806                  * supported, we should at least be sure we don't
807                  * change the value of the SR2 Quad Enable bit.
808                  *
809                  * We can safely assume that when the Quad Enable method is
810                  * set, the value of the QE bit is one, as a consequence of the
811                  * nor->params->quad_enable() call.
812                  *
813                  * We can safely assume that the Quad Enable bit is present in
814                  * the Status Register 2 at BIT(1). According to the JESD216
815                  * revB standard, BFPT DWORDS[15], bits 22:20, the 16-bit
816                  * Write Status (01h) command is available just for the cases
817                  * in which the QE bit is described in SR2 at BIT(1).
818                  */
819                 sr_cr[1] = SR2_QUAD_EN_BIT1;
820         } else {
821                 sr_cr[1] = 0;
822         }
823
824         sr_cr[0] = sr1;
825
826         ret = spi_nor_write_sr(nor, sr_cr, 2);
827         if (ret)
828                 return ret;
829
830         ret = spi_nor_read_sr(nor, sr_cr);
831         if (ret)
832                 return ret;
833
834         if (sr1 != sr_cr[0]) {
835                 dev_dbg(nor->dev, "SR: Read back test failed\n");
836                 return -EIO;
837         }
838
839         if (nor->flags & SNOR_F_NO_READ_CR)
840                 return 0;
841
842         cr_written = sr_cr[1];
843
844         ret = spi_nor_read_cr(nor, &sr_cr[1]);
845         if (ret)
846                 return ret;
847
848         if (cr_written != sr_cr[1]) {
849                 dev_dbg(nor->dev, "CR: read back test failed\n");
850                 return -EIO;
851         }
852
853         return 0;
854 }
855
856 /**
857  * spi_nor_write_16bit_cr_and_check() - Write the Status Register 1 and the
858  * Configuration Register in one shot. Ensure that the byte written in the
859  * Configuration Register match the received value, and that the 16-bit Write
860  * did not affect what was already in the Status Register 1.
861  * @nor:        pointer to a 'struct spi_nor'.
862  * @cr:         byte value to be written to the Configuration Register.
863  *
864  * Return: 0 on success, -errno otherwise.
865  */
866 static int spi_nor_write_16bit_cr_and_check(struct spi_nor *nor, u8 cr)
867 {
868         int ret;
869         u8 *sr_cr = nor->bouncebuf;
870         u8 sr_written;
871
872         /* Keep the current value of the Status Register 1. */
873         ret = spi_nor_read_sr(nor, sr_cr);
874         if (ret)
875                 return ret;
876
877         sr_cr[1] = cr;
878
879         ret = spi_nor_write_sr(nor, sr_cr, 2);
880         if (ret)
881                 return ret;
882
883         sr_written = sr_cr[0];
884
885         ret = spi_nor_read_sr(nor, sr_cr);
886         if (ret)
887                 return ret;
888
889         if (sr_written != sr_cr[0]) {
890                 dev_dbg(nor->dev, "SR: Read back test failed\n");
891                 return -EIO;
892         }
893
894         if (nor->flags & SNOR_F_NO_READ_CR)
895                 return 0;
896
897         ret = spi_nor_read_cr(nor, &sr_cr[1]);
898         if (ret)
899                 return ret;
900
901         if (cr != sr_cr[1]) {
902                 dev_dbg(nor->dev, "CR: read back test failed\n");
903                 return -EIO;
904         }
905
906         return 0;
907 }
908
909 /**
910  * spi_nor_write_sr_and_check() - Write the Status Register 1 and ensure that
911  * the byte written match the received value without affecting other bits in the
912  * Status Register 1 and 2.
913  * @nor:        pointer to a 'struct spi_nor'.
914  * @sr1:        byte value to be written to the Status Register.
915  *
916  * Return: 0 on success, -errno otherwise.
917  */
918 int spi_nor_write_sr_and_check(struct spi_nor *nor, u8 sr1)
919 {
920         if (nor->flags & SNOR_F_HAS_16BIT_SR)
921                 return spi_nor_write_16bit_sr_and_check(nor, sr1);
922
923         return spi_nor_write_sr1_and_check(nor, sr1);
924 }
925
926 /**
927  * spi_nor_write_sr2() - Write the Status Register 2 using the
928  * SPINOR_OP_WRSR2 (3eh) command.
929  * @nor:        pointer to 'struct spi_nor'.
930  * @sr2:        pointer to DMA-able buffer to write to the Status Register 2.
931  *
932  * Return: 0 on success, -errno otherwise.
933  */
934 static int spi_nor_write_sr2(struct spi_nor *nor, const u8 *sr2)
935 {
936         int ret;
937
938         ret = spi_nor_write_enable(nor);
939         if (ret)
940                 return ret;
941
942         if (nor->spimem) {
943                 struct spi_mem_op op =
944                         SPI_MEM_OP(SPI_MEM_OP_CMD(SPINOR_OP_WRSR2, 1),
945                                    SPI_MEM_OP_NO_ADDR,
946                                    SPI_MEM_OP_NO_DUMMY,
947                                    SPI_MEM_OP_DATA_OUT(1, sr2, 1));
948
949                 ret = spi_mem_exec_op(nor->spimem, &op);
950         } else {
951                 ret = nor->controller_ops->write_reg(nor, SPINOR_OP_WRSR2,
952                                                      sr2, 1);
953         }
954
955         if (ret) {
956                 dev_dbg(nor->dev, "error %d writing SR2\n", ret);
957                 return ret;
958         }
959
960         return spi_nor_wait_till_ready(nor);
961 }
962
963 /**
964  * spi_nor_read_sr2() - Read the Status Register 2 using the
965  * SPINOR_OP_RDSR2 (3fh) command.
966  * @nor:        pointer to 'struct spi_nor'.
967  * @sr2:        pointer to DMA-able buffer where the value of the
968  *              Status Register 2 will be written.
969  *
970  * Return: 0 on success, -errno otherwise.
971  */
972 static int spi_nor_read_sr2(struct spi_nor *nor, u8 *sr2)
973 {
974         int ret;
975
976         if (nor->spimem) {
977                 struct spi_mem_op op =
978                         SPI_MEM_OP(SPI_MEM_OP_CMD(SPINOR_OP_RDSR2, 1),
979                                    SPI_MEM_OP_NO_ADDR,
980                                    SPI_MEM_OP_NO_DUMMY,
981                                    SPI_MEM_OP_DATA_IN(1, sr2, 1));
982
983                 ret = spi_mem_exec_op(nor->spimem, &op);
984         } else {
985                 ret = nor->controller_ops->read_reg(nor, SPINOR_OP_RDSR2,
986                                                     sr2, 1);
987         }
988
989         if (ret)
990                 dev_dbg(nor->dev, "error %d reading SR2\n", ret);
991
992         return ret;
993 }
994
995 /**
996  * spi_nor_erase_chip() - Erase the entire flash memory.
997  * @nor:        pointer to 'struct spi_nor'.
998  *
999  * Return: 0 on success, -errno otherwise.
1000  */
1001 static int spi_nor_erase_chip(struct spi_nor *nor)
1002 {
1003         int ret;
1004
1005         dev_dbg(nor->dev, " %lldKiB\n", (long long)(nor->mtd.size >> 10));
1006
1007         if (nor->spimem) {
1008                 struct spi_mem_op op =
1009                         SPI_MEM_OP(SPI_MEM_OP_CMD(SPINOR_OP_CHIP_ERASE, 1),
1010                                    SPI_MEM_OP_NO_ADDR,
1011                                    SPI_MEM_OP_NO_DUMMY,
1012                                    SPI_MEM_OP_NO_DATA);
1013
1014                 ret = spi_mem_exec_op(nor->spimem, &op);
1015         } else {
1016                 ret = nor->controller_ops->write_reg(nor, SPINOR_OP_CHIP_ERASE,
1017                                                      NULL, 0);
1018         }
1019
1020         if (ret)
1021                 dev_dbg(nor->dev, "error %d erasing chip\n", ret);
1022
1023         return ret;
1024 }
1025
1026 static u8 spi_nor_convert_opcode(u8 opcode, const u8 table[][2], size_t size)
1027 {
1028         size_t i;
1029
1030         for (i = 0; i < size; i++)
1031                 if (table[i][0] == opcode)
1032                         return table[i][1];
1033
1034         /* No conversion found, keep input op code. */
1035         return opcode;
1036 }
1037
1038 u8 spi_nor_convert_3to4_read(u8 opcode)
1039 {
1040         static const u8 spi_nor_3to4_read[][2] = {
1041                 { SPINOR_OP_READ,       SPINOR_OP_READ_4B },
1042                 { SPINOR_OP_READ_FAST,  SPINOR_OP_READ_FAST_4B },
1043                 { SPINOR_OP_READ_1_1_2, SPINOR_OP_READ_1_1_2_4B },
1044                 { SPINOR_OP_READ_1_2_2, SPINOR_OP_READ_1_2_2_4B },
1045                 { SPINOR_OP_READ_1_1_4, SPINOR_OP_READ_1_1_4_4B },
1046                 { SPINOR_OP_READ_1_4_4, SPINOR_OP_READ_1_4_4_4B },
1047                 { SPINOR_OP_READ_1_1_8, SPINOR_OP_READ_1_1_8_4B },
1048                 { SPINOR_OP_READ_1_8_8, SPINOR_OP_READ_1_8_8_4B },
1049
1050                 { SPINOR_OP_READ_1_1_1_DTR,     SPINOR_OP_READ_1_1_1_DTR_4B },
1051                 { SPINOR_OP_READ_1_2_2_DTR,     SPINOR_OP_READ_1_2_2_DTR_4B },
1052                 { SPINOR_OP_READ_1_4_4_DTR,     SPINOR_OP_READ_1_4_4_DTR_4B },
1053         };
1054
1055         return spi_nor_convert_opcode(opcode, spi_nor_3to4_read,
1056                                       ARRAY_SIZE(spi_nor_3to4_read));
1057 }
1058
1059 static u8 spi_nor_convert_3to4_program(u8 opcode)
1060 {
1061         static const u8 spi_nor_3to4_program[][2] = {
1062                 { SPINOR_OP_PP,         SPINOR_OP_PP_4B },
1063                 { SPINOR_OP_PP_1_1_4,   SPINOR_OP_PP_1_1_4_4B },
1064                 { SPINOR_OP_PP_1_4_4,   SPINOR_OP_PP_1_4_4_4B },
1065                 { SPINOR_OP_PP_1_1_8,   SPINOR_OP_PP_1_1_8_4B },
1066                 { SPINOR_OP_PP_1_8_8,   SPINOR_OP_PP_1_8_8_4B },
1067         };
1068
1069         return spi_nor_convert_opcode(opcode, spi_nor_3to4_program,
1070                                       ARRAY_SIZE(spi_nor_3to4_program));
1071 }
1072
1073 static u8 spi_nor_convert_3to4_erase(u8 opcode)
1074 {
1075         static const u8 spi_nor_3to4_erase[][2] = {
1076                 { SPINOR_OP_BE_4K,      SPINOR_OP_BE_4K_4B },
1077                 { SPINOR_OP_BE_32K,     SPINOR_OP_BE_32K_4B },
1078                 { SPINOR_OP_SE,         SPINOR_OP_SE_4B },
1079         };
1080
1081         return spi_nor_convert_opcode(opcode, spi_nor_3to4_erase,
1082                                       ARRAY_SIZE(spi_nor_3to4_erase));
1083 }
1084
1085 static bool spi_nor_has_uniform_erase(const struct spi_nor *nor)
1086 {
1087         return !!nor->params->erase_map.uniform_erase_type;
1088 }
1089
1090 static void spi_nor_set_4byte_opcodes(struct spi_nor *nor)
1091 {
1092         nor->read_opcode = spi_nor_convert_3to4_read(nor->read_opcode);
1093         nor->program_opcode = spi_nor_convert_3to4_program(nor->program_opcode);
1094         nor->erase_opcode = spi_nor_convert_3to4_erase(nor->erase_opcode);
1095
1096         if (!spi_nor_has_uniform_erase(nor)) {
1097                 struct spi_nor_erase_map *map = &nor->params->erase_map;
1098                 struct spi_nor_erase_type *erase;
1099                 int i;
1100
1101                 for (i = 0; i < SNOR_ERASE_TYPE_MAX; i++) {
1102                         erase = &map->erase_type[i];
1103                         erase->opcode =
1104                                 spi_nor_convert_3to4_erase(erase->opcode);
1105                 }
1106         }
1107 }
1108
1109 int spi_nor_lock_and_prep(struct spi_nor *nor)
1110 {
1111         int ret = 0;
1112
1113         mutex_lock(&nor->lock);
1114
1115         if (nor->controller_ops &&  nor->controller_ops->prepare) {
1116                 ret = nor->controller_ops->prepare(nor);
1117                 if (ret) {
1118                         mutex_unlock(&nor->lock);
1119                         return ret;
1120                 }
1121         }
1122         return ret;
1123 }
1124
1125 void spi_nor_unlock_and_unprep(struct spi_nor *nor)
1126 {
1127         if (nor->controller_ops && nor->controller_ops->unprepare)
1128                 nor->controller_ops->unprepare(nor);
1129         mutex_unlock(&nor->lock);
1130 }
1131
1132 static u32 spi_nor_convert_addr(struct spi_nor *nor, loff_t addr)
1133 {
1134         if (!nor->params->convert_addr)
1135                 return addr;
1136
1137         return nor->params->convert_addr(nor, addr);
1138 }
1139
1140 /*
1141  * Initiate the erasure of a single sector
1142  */
1143 static int spi_nor_erase_sector(struct spi_nor *nor, u32 addr)
1144 {
1145         int i;
1146
1147         addr = spi_nor_convert_addr(nor, addr);
1148
1149         if (nor->spimem) {
1150                 struct spi_mem_op op =
1151                         SPI_MEM_OP(SPI_MEM_OP_CMD(nor->erase_opcode, 1),
1152                                    SPI_MEM_OP_ADDR(nor->addr_width, addr, 1),
1153                                    SPI_MEM_OP_NO_DUMMY,
1154                                    SPI_MEM_OP_NO_DATA);
1155
1156                 return spi_mem_exec_op(nor->spimem, &op);
1157         } else if (nor->controller_ops->erase) {
1158                 return nor->controller_ops->erase(nor, addr);
1159         }
1160
1161         /*
1162          * Default implementation, if driver doesn't have a specialized HW
1163          * control
1164          */
1165         for (i = nor->addr_width - 1; i >= 0; i--) {
1166                 nor->bouncebuf[i] = addr & 0xff;
1167                 addr >>= 8;
1168         }
1169
1170         return nor->controller_ops->write_reg(nor, nor->erase_opcode,
1171                                               nor->bouncebuf, nor->addr_width);
1172 }
1173
1174 /**
1175  * spi_nor_div_by_erase_size() - calculate remainder and update new dividend
1176  * @erase:      pointer to a structure that describes a SPI NOR erase type
1177  * @dividend:   dividend value
1178  * @remainder:  pointer to u32 remainder (will be updated)
1179  *
1180  * Return: the result of the division
1181  */
1182 static u64 spi_nor_div_by_erase_size(const struct spi_nor_erase_type *erase,
1183                                      u64 dividend, u32 *remainder)
1184 {
1185         /* JEDEC JESD216B Standard imposes erase sizes to be power of 2. */
1186         *remainder = (u32)dividend & erase->size_mask;
1187         return dividend >> erase->size_shift;
1188 }
1189
1190 /**
1191  * spi_nor_find_best_erase_type() - find the best erase type for the given
1192  *                                  offset in the serial flash memory and the
1193  *                                  number of bytes to erase. The region in
1194  *                                  which the address fits is expected to be
1195  *                                  provided.
1196  * @map:        the erase map of the SPI NOR
1197  * @region:     pointer to a structure that describes a SPI NOR erase region
1198  * @addr:       offset in the serial flash memory
1199  * @len:        number of bytes to erase
1200  *
1201  * Return: a pointer to the best fitted erase type, NULL otherwise.
1202  */
1203 static const struct spi_nor_erase_type *
1204 spi_nor_find_best_erase_type(const struct spi_nor_erase_map *map,
1205                              const struct spi_nor_erase_region *region,
1206                              u64 addr, u32 len)
1207 {
1208         const struct spi_nor_erase_type *erase;
1209         u32 rem;
1210         int i;
1211         u8 erase_mask = region->offset & SNOR_ERASE_TYPE_MASK;
1212
1213         /*
1214          * Erase types are ordered by size, with the smallest erase type at
1215          * index 0.
1216          */
1217         for (i = SNOR_ERASE_TYPE_MAX - 1; i >= 0; i--) {
1218                 /* Does the erase region support the tested erase type? */
1219                 if (!(erase_mask & BIT(i)))
1220                         continue;
1221
1222                 erase = &map->erase_type[i];
1223
1224                 /* Alignment is not mandatory for overlaid regions */
1225                 if (region->offset & SNOR_OVERLAID_REGION &&
1226                     region->size <= len)
1227                         return erase;
1228
1229                 /* Don't erase more than what the user has asked for. */
1230                 if (erase->size > len)
1231                         continue;
1232
1233                 spi_nor_div_by_erase_size(erase, addr, &rem);
1234                 if (rem)
1235                         continue;
1236                 else
1237                         return erase;
1238         }
1239
1240         return NULL;
1241 }
1242
1243 static u64 spi_nor_region_is_last(const struct spi_nor_erase_region *region)
1244 {
1245         return region->offset & SNOR_LAST_REGION;
1246 }
1247
1248 static u64 spi_nor_region_end(const struct spi_nor_erase_region *region)
1249 {
1250         return (region->offset & ~SNOR_ERASE_FLAGS_MASK) + region->size;
1251 }
1252
1253 /**
1254  * spi_nor_region_next() - get the next spi nor region
1255  * @region:     pointer to a structure that describes a SPI NOR erase region
1256  *
1257  * Return: the next spi nor region or NULL if last region.
1258  */
1259 struct spi_nor_erase_region *
1260 spi_nor_region_next(struct spi_nor_erase_region *region)
1261 {
1262         if (spi_nor_region_is_last(region))
1263                 return NULL;
1264         region++;
1265         return region;
1266 }
1267
1268 /**
1269  * spi_nor_find_erase_region() - find the region of the serial flash memory in
1270  *                               which the offset fits
1271  * @map:        the erase map of the SPI NOR
1272  * @addr:       offset in the serial flash memory
1273  *
1274  * Return: a pointer to the spi_nor_erase_region struct, ERR_PTR(-errno)
1275  *         otherwise.
1276  */
1277 static struct spi_nor_erase_region *
1278 spi_nor_find_erase_region(const struct spi_nor_erase_map *map, u64 addr)
1279 {
1280         struct spi_nor_erase_region *region = map->regions;
1281         u64 region_start = region->offset & ~SNOR_ERASE_FLAGS_MASK;
1282         u64 region_end = region_start + region->size;
1283
1284         while (addr < region_start || addr >= region_end) {
1285                 region = spi_nor_region_next(region);
1286                 if (!region)
1287                         return ERR_PTR(-EINVAL);
1288
1289                 region_start = region->offset & ~SNOR_ERASE_FLAGS_MASK;
1290                 region_end = region_start + region->size;
1291         }
1292
1293         return region;
1294 }
1295
1296 /**
1297  * spi_nor_init_erase_cmd() - initialize an erase command
1298  * @region:     pointer to a structure that describes a SPI NOR erase region
1299  * @erase:      pointer to a structure that describes a SPI NOR erase type
1300  *
1301  * Return: the pointer to the allocated erase command, ERR_PTR(-errno)
1302  *         otherwise.
1303  */
1304 static struct spi_nor_erase_command *
1305 spi_nor_init_erase_cmd(const struct spi_nor_erase_region *region,
1306                        const struct spi_nor_erase_type *erase)
1307 {
1308         struct spi_nor_erase_command *cmd;
1309
1310         cmd = kmalloc(sizeof(*cmd), GFP_KERNEL);
1311         if (!cmd)
1312                 return ERR_PTR(-ENOMEM);
1313
1314         INIT_LIST_HEAD(&cmd->list);
1315         cmd->opcode = erase->opcode;
1316         cmd->count = 1;
1317
1318         if (region->offset & SNOR_OVERLAID_REGION)
1319                 cmd->size = region->size;
1320         else
1321                 cmd->size = erase->size;
1322
1323         return cmd;
1324 }
1325
1326 /**
1327  * spi_nor_destroy_erase_cmd_list() - destroy erase command list
1328  * @erase_list: list of erase commands
1329  */
1330 static void spi_nor_destroy_erase_cmd_list(struct list_head *erase_list)
1331 {
1332         struct spi_nor_erase_command *cmd, *next;
1333
1334         list_for_each_entry_safe(cmd, next, erase_list, list) {
1335                 list_del(&cmd->list);
1336                 kfree(cmd);
1337         }
1338 }
1339
1340 /**
1341  * spi_nor_init_erase_cmd_list() - initialize erase command list
1342  * @nor:        pointer to a 'struct spi_nor'
1343  * @erase_list: list of erase commands to be executed once we validate that the
1344  *              erase can be performed
1345  * @addr:       offset in the serial flash memory
1346  * @len:        number of bytes to erase
1347  *
1348  * Builds the list of best fitted erase commands and verifies if the erase can
1349  * be performed.
1350  *
1351  * Return: 0 on success, -errno otherwise.
1352  */
1353 static int spi_nor_init_erase_cmd_list(struct spi_nor *nor,
1354                                        struct list_head *erase_list,
1355                                        u64 addr, u32 len)
1356 {
1357         const struct spi_nor_erase_map *map = &nor->params->erase_map;
1358         const struct spi_nor_erase_type *erase, *prev_erase = NULL;
1359         struct spi_nor_erase_region *region;
1360         struct spi_nor_erase_command *cmd = NULL;
1361         u64 region_end;
1362         int ret = -EINVAL;
1363
1364         region = spi_nor_find_erase_region(map, addr);
1365         if (IS_ERR(region))
1366                 return PTR_ERR(region);
1367
1368         region_end = spi_nor_region_end(region);
1369
1370         while (len) {
1371                 erase = spi_nor_find_best_erase_type(map, region, addr, len);
1372                 if (!erase)
1373                         goto destroy_erase_cmd_list;
1374
1375                 if (prev_erase != erase ||
1376                     erase->size != cmd->size ||
1377                     region->offset & SNOR_OVERLAID_REGION) {
1378                         cmd = spi_nor_init_erase_cmd(region, erase);
1379                         if (IS_ERR(cmd)) {
1380                                 ret = PTR_ERR(cmd);
1381                                 goto destroy_erase_cmd_list;
1382                         }
1383
1384                         list_add_tail(&cmd->list, erase_list);
1385                 } else {
1386                         cmd->count++;
1387                 }
1388
1389                 addr += cmd->size;
1390                 len -= cmd->size;
1391
1392                 if (len && addr >= region_end) {
1393                         region = spi_nor_region_next(region);
1394                         if (!region)
1395                                 goto destroy_erase_cmd_list;
1396                         region_end = spi_nor_region_end(region);
1397                 }
1398
1399                 prev_erase = erase;
1400         }
1401
1402         return 0;
1403
1404 destroy_erase_cmd_list:
1405         spi_nor_destroy_erase_cmd_list(erase_list);
1406         return ret;
1407 }
1408
1409 /**
1410  * spi_nor_erase_multi_sectors() - perform a non-uniform erase
1411  * @nor:        pointer to a 'struct spi_nor'
1412  * @addr:       offset in the serial flash memory
1413  * @len:        number of bytes to erase
1414  *
1415  * Build a list of best fitted erase commands and execute it once we validate
1416  * that the erase can be performed.
1417  *
1418  * Return: 0 on success, -errno otherwise.
1419  */
1420 static int spi_nor_erase_multi_sectors(struct spi_nor *nor, u64 addr, u32 len)
1421 {
1422         LIST_HEAD(erase_list);
1423         struct spi_nor_erase_command *cmd, *next;
1424         int ret;
1425
1426         ret = spi_nor_init_erase_cmd_list(nor, &erase_list, addr, len);
1427         if (ret)
1428                 return ret;
1429
1430         list_for_each_entry_safe(cmd, next, &erase_list, list) {
1431                 nor->erase_opcode = cmd->opcode;
1432                 while (cmd->count) {
1433                         ret = spi_nor_write_enable(nor);
1434                         if (ret)
1435                                 goto destroy_erase_cmd_list;
1436
1437                         ret = spi_nor_erase_sector(nor, addr);
1438                         if (ret)
1439                                 goto destroy_erase_cmd_list;
1440
1441                         addr += cmd->size;
1442                         cmd->count--;
1443
1444                         ret = spi_nor_wait_till_ready(nor);
1445                         if (ret)
1446                                 goto destroy_erase_cmd_list;
1447                 }
1448                 list_del(&cmd->list);
1449                 kfree(cmd);
1450         }
1451
1452         return 0;
1453
1454 destroy_erase_cmd_list:
1455         spi_nor_destroy_erase_cmd_list(&erase_list);
1456         return ret;
1457 }
1458
1459 /*
1460  * Erase an address range on the nor chip.  The address range may extend
1461  * one or more erase sectors.  Return an error is there is a problem erasing.
1462  */
1463 static int spi_nor_erase(struct mtd_info *mtd, struct erase_info *instr)
1464 {
1465         struct spi_nor *nor = mtd_to_spi_nor(mtd);
1466         u32 addr, len;
1467         uint32_t rem;
1468         int ret;
1469
1470         dev_dbg(nor->dev, "at 0x%llx, len %lld\n", (long long)instr->addr,
1471                         (long long)instr->len);
1472
1473         if (spi_nor_has_uniform_erase(nor)) {
1474                 div_u64_rem(instr->len, mtd->erasesize, &rem);
1475                 if (rem)
1476                         return -EINVAL;
1477         }
1478
1479         addr = instr->addr;
1480         len = instr->len;
1481
1482         ret = spi_nor_lock_and_prep(nor);
1483         if (ret)
1484                 return ret;
1485
1486         /* whole-chip erase? */
1487         if (len == mtd->size && !(nor->flags & SNOR_F_NO_OP_CHIP_ERASE)) {
1488                 unsigned long timeout;
1489
1490                 ret = spi_nor_write_enable(nor);
1491                 if (ret)
1492                         goto erase_err;
1493
1494                 ret = spi_nor_erase_chip(nor);
1495                 if (ret)
1496                         goto erase_err;
1497
1498                 /*
1499                  * Scale the timeout linearly with the size of the flash, with
1500                  * a minimum calibrated to an old 2MB flash. We could try to
1501                  * pull these from CFI/SFDP, but these values should be good
1502                  * enough for now.
1503                  */
1504                 timeout = max(CHIP_ERASE_2MB_READY_WAIT_JIFFIES,
1505                               CHIP_ERASE_2MB_READY_WAIT_JIFFIES *
1506                               (unsigned long)(mtd->size / SZ_2M));
1507                 ret = spi_nor_wait_till_ready_with_timeout(nor, timeout);
1508                 if (ret)
1509                         goto erase_err;
1510
1511         /* REVISIT in some cases we could speed up erasing large regions
1512          * by using SPINOR_OP_SE instead of SPINOR_OP_BE_4K.  We may have set up
1513          * to use "small sector erase", but that's not always optimal.
1514          */
1515
1516         /* "sector"-at-a-time erase */
1517         } else if (spi_nor_has_uniform_erase(nor)) {
1518                 while (len) {
1519                         ret = spi_nor_write_enable(nor);
1520                         if (ret)
1521                                 goto erase_err;
1522
1523                         ret = spi_nor_erase_sector(nor, addr);
1524                         if (ret)
1525                                 goto erase_err;
1526
1527                         addr += mtd->erasesize;
1528                         len -= mtd->erasesize;
1529
1530                         ret = spi_nor_wait_till_ready(nor);
1531                         if (ret)
1532                                 goto erase_err;
1533                 }
1534
1535         /* erase multiple sectors */
1536         } else {
1537                 ret = spi_nor_erase_multi_sectors(nor, addr, len);
1538                 if (ret)
1539                         goto erase_err;
1540         }
1541
1542         ret = spi_nor_write_disable(nor);
1543
1544 erase_err:
1545         spi_nor_unlock_and_unprep(nor);
1546
1547         return ret;
1548 }
1549
1550 static u8 spi_nor_get_sr_bp_mask(struct spi_nor *nor)
1551 {
1552         u8 mask = SR_BP2 | SR_BP1 | SR_BP0;
1553
1554         if (nor->flags & SNOR_F_HAS_SR_BP3_BIT6)
1555                 return mask | SR_BP3_BIT6;
1556
1557         if (nor->flags & SNOR_F_HAS_4BIT_BP)
1558                 return mask | SR_BP3;
1559
1560         return mask;
1561 }
1562
1563 static u8 spi_nor_get_sr_tb_mask(struct spi_nor *nor)
1564 {
1565         if (nor->flags & SNOR_F_HAS_SR_TB_BIT6)
1566                 return SR_TB_BIT6;
1567         else
1568                 return SR_TB_BIT5;
1569 }
1570
1571 static u64 spi_nor_get_min_prot_length_sr(struct spi_nor *nor)
1572 {
1573         unsigned int bp_slots, bp_slots_needed;
1574         u8 mask = spi_nor_get_sr_bp_mask(nor);
1575
1576         /* Reserved one for "protect none" and one for "protect all". */
1577         bp_slots = (1 << hweight8(mask)) - 2;
1578         bp_slots_needed = ilog2(nor->info->n_sectors);
1579
1580         if (bp_slots_needed > bp_slots)
1581                 return nor->info->sector_size <<
1582                         (bp_slots_needed - bp_slots);
1583         else
1584                 return nor->info->sector_size;
1585 }
1586
1587 static void spi_nor_get_locked_range_sr(struct spi_nor *nor, u8 sr, loff_t *ofs,
1588                                         uint64_t *len)
1589 {
1590         struct mtd_info *mtd = &nor->mtd;
1591         u64 min_prot_len;
1592         u8 mask = spi_nor_get_sr_bp_mask(nor);
1593         u8 tb_mask = spi_nor_get_sr_tb_mask(nor);
1594         u8 bp, val = sr & mask;
1595
1596         if (nor->flags & SNOR_F_HAS_SR_BP3_BIT6 && val & SR_BP3_BIT6)
1597                 val = (val & ~SR_BP3_BIT6) | SR_BP3;
1598
1599         bp = val >> SR_BP_SHIFT;
1600
1601         if (!bp) {
1602                 /* No protection */
1603                 *ofs = 0;
1604                 *len = 0;
1605                 return;
1606         }
1607
1608         min_prot_len = spi_nor_get_min_prot_length_sr(nor);
1609         *len = min_prot_len << (bp - 1);
1610
1611         if (*len > mtd->size)
1612                 *len = mtd->size;
1613
1614         if (nor->flags & SNOR_F_HAS_SR_TB && sr & tb_mask)
1615                 *ofs = 0;
1616         else
1617                 *ofs = mtd->size - *len;
1618 }
1619
1620 /*
1621  * Return 1 if the entire region is locked (if @locked is true) or unlocked (if
1622  * @locked is false); 0 otherwise
1623  */
1624 static int spi_nor_check_lock_status_sr(struct spi_nor *nor, loff_t ofs,
1625                                         uint64_t len, u8 sr, bool locked)
1626 {
1627         loff_t lock_offs;
1628         uint64_t lock_len;
1629
1630         if (!len)
1631                 return 1;
1632
1633         spi_nor_get_locked_range_sr(nor, sr, &lock_offs, &lock_len);
1634
1635         if (locked)
1636                 /* Requested range is a sub-range of locked range */
1637                 return (ofs + len <= lock_offs + lock_len) && (ofs >= lock_offs);
1638         else
1639                 /* Requested range does not overlap with locked range */
1640                 return (ofs >= lock_offs + lock_len) || (ofs + len <= lock_offs);
1641 }
1642
1643 static int spi_nor_is_locked_sr(struct spi_nor *nor, loff_t ofs, uint64_t len,
1644                                 u8 sr)
1645 {
1646         return spi_nor_check_lock_status_sr(nor, ofs, len, sr, true);
1647 }
1648
1649 static int spi_nor_is_unlocked_sr(struct spi_nor *nor, loff_t ofs, uint64_t len,
1650                                   u8 sr)
1651 {
1652         return spi_nor_check_lock_status_sr(nor, ofs, len, sr, false);
1653 }
1654
1655 /*
1656  * Lock a region of the flash. Compatible with ST Micro and similar flash.
1657  * Supports the block protection bits BP{0,1,2}/BP{0,1,2,3} in the status
1658  * register
1659  * (SR). Does not support these features found in newer SR bitfields:
1660  *   - SEC: sector/block protect - only handle SEC=0 (block protect)
1661  *   - CMP: complement protect - only support CMP=0 (range is not complemented)
1662  *
1663  * Support for the following is provided conditionally for some flash:
1664  *   - TB: top/bottom protect
1665  *
1666  * Sample table portion for 8MB flash (Winbond w25q64fw):
1667  *
1668  *   SEC  |  TB   |  BP2  |  BP1  |  BP0  |  Prot Length  | Protected Portion
1669  *  --------------------------------------------------------------------------
1670  *    X   |   X   |   0   |   0   |   0   |  NONE         | NONE
1671  *    0   |   0   |   0   |   0   |   1   |  128 KB       | Upper 1/64
1672  *    0   |   0   |   0   |   1   |   0   |  256 KB       | Upper 1/32
1673  *    0   |   0   |   0   |   1   |   1   |  512 KB       | Upper 1/16
1674  *    0   |   0   |   1   |   0   |   0   |  1 MB         | Upper 1/8
1675  *    0   |   0   |   1   |   0   |   1   |  2 MB         | Upper 1/4
1676  *    0   |   0   |   1   |   1   |   0   |  4 MB         | Upper 1/2
1677  *    X   |   X   |   1   |   1   |   1   |  8 MB         | ALL
1678  *  ------|-------|-------|-------|-------|---------------|-------------------
1679  *    0   |   1   |   0   |   0   |   1   |  128 KB       | Lower 1/64
1680  *    0   |   1   |   0   |   1   |   0   |  256 KB       | Lower 1/32
1681  *    0   |   1   |   0   |   1   |   1   |  512 KB       | Lower 1/16
1682  *    0   |   1   |   1   |   0   |   0   |  1 MB         | Lower 1/8
1683  *    0   |   1   |   1   |   0   |   1   |  2 MB         | Lower 1/4
1684  *    0   |   1   |   1   |   1   |   0   |  4 MB         | Lower 1/2
1685  *
1686  * Returns negative on errors, 0 on success.
1687  */
1688 static int spi_nor_sr_lock(struct spi_nor *nor, loff_t ofs, uint64_t len)
1689 {
1690         struct mtd_info *mtd = &nor->mtd;
1691         u64 min_prot_len;
1692         int ret, status_old, status_new;
1693         u8 mask = spi_nor_get_sr_bp_mask(nor);
1694         u8 tb_mask = spi_nor_get_sr_tb_mask(nor);
1695         u8 pow, val;
1696         loff_t lock_len;
1697         bool can_be_top = true, can_be_bottom = nor->flags & SNOR_F_HAS_SR_TB;
1698         bool use_top;
1699
1700         ret = spi_nor_read_sr(nor, nor->bouncebuf);
1701         if (ret)
1702                 return ret;
1703
1704         status_old = nor->bouncebuf[0];
1705
1706         /* If nothing in our range is unlocked, we don't need to do anything */
1707         if (spi_nor_is_locked_sr(nor, ofs, len, status_old))
1708                 return 0;
1709
1710         /* If anything below us is unlocked, we can't use 'bottom' protection */
1711         if (!spi_nor_is_locked_sr(nor, 0, ofs, status_old))
1712                 can_be_bottom = false;
1713
1714         /* If anything above us is unlocked, we can't use 'top' protection */
1715         if (!spi_nor_is_locked_sr(nor, ofs + len, mtd->size - (ofs + len),
1716                                   status_old))
1717                 can_be_top = false;
1718
1719         if (!can_be_bottom && !can_be_top)
1720                 return -EINVAL;
1721
1722         /* Prefer top, if both are valid */
1723         use_top = can_be_top;
1724
1725         /* lock_len: length of region that should end up locked */
1726         if (use_top)
1727                 lock_len = mtd->size - ofs;
1728         else
1729                 lock_len = ofs + len;
1730
1731         if (lock_len == mtd->size) {
1732                 val = mask;
1733         } else {
1734                 min_prot_len = spi_nor_get_min_prot_length_sr(nor);
1735                 pow = ilog2(lock_len) - ilog2(min_prot_len) + 1;
1736                 val = pow << SR_BP_SHIFT;
1737
1738                 if (nor->flags & SNOR_F_HAS_SR_BP3_BIT6 && val & SR_BP3)
1739                         val = (val & ~SR_BP3) | SR_BP3_BIT6;
1740
1741                 if (val & ~mask)
1742                         return -EINVAL;
1743
1744                 /* Don't "lock" with no region! */
1745                 if (!(val & mask))
1746                         return -EINVAL;
1747         }
1748
1749         status_new = (status_old & ~mask & ~tb_mask) | val;
1750
1751         /* Disallow further writes if WP pin is asserted */
1752         status_new |= SR_SRWD;
1753
1754         if (!use_top)
1755                 status_new |= tb_mask;
1756
1757         /* Don't bother if they're the same */
1758         if (status_new == status_old)
1759                 return 0;
1760
1761         /* Only modify protection if it will not unlock other areas */
1762         if ((status_new & mask) < (status_old & mask))
1763                 return -EINVAL;
1764
1765         return spi_nor_write_sr_and_check(nor, status_new);
1766 }
1767
1768 /*
1769  * Unlock a region of the flash. See spi_nor_sr_lock() for more info
1770  *
1771  * Returns negative on errors, 0 on success.
1772  */
1773 static int spi_nor_sr_unlock(struct spi_nor *nor, loff_t ofs, uint64_t len)
1774 {
1775         struct mtd_info *mtd = &nor->mtd;
1776         u64 min_prot_len;
1777         int ret, status_old, status_new;
1778         u8 mask = spi_nor_get_sr_bp_mask(nor);
1779         u8 tb_mask = spi_nor_get_sr_tb_mask(nor);
1780         u8 pow, val;
1781         loff_t lock_len;
1782         bool can_be_top = true, can_be_bottom = nor->flags & SNOR_F_HAS_SR_TB;
1783         bool use_top;
1784
1785         ret = spi_nor_read_sr(nor, nor->bouncebuf);
1786         if (ret)
1787                 return ret;
1788
1789         status_old = nor->bouncebuf[0];
1790
1791         /* If nothing in our range is locked, we don't need to do anything */
1792         if (spi_nor_is_unlocked_sr(nor, ofs, len, status_old))
1793                 return 0;
1794
1795         /* If anything below us is locked, we can't use 'top' protection */
1796         if (!spi_nor_is_unlocked_sr(nor, 0, ofs, status_old))
1797                 can_be_top = false;
1798
1799         /* If anything above us is locked, we can't use 'bottom' protection */
1800         if (!spi_nor_is_unlocked_sr(nor, ofs + len, mtd->size - (ofs + len),
1801                                     status_old))
1802                 can_be_bottom = false;
1803
1804         if (!can_be_bottom && !can_be_top)
1805                 return -EINVAL;
1806
1807         /* Prefer top, if both are valid */
1808         use_top = can_be_top;
1809
1810         /* lock_len: length of region that should remain locked */
1811         if (use_top)
1812                 lock_len = mtd->size - (ofs + len);
1813         else
1814                 lock_len = ofs;
1815
1816         if (lock_len == 0) {
1817                 val = 0; /* fully unlocked */
1818         } else {
1819                 min_prot_len = spi_nor_get_min_prot_length_sr(nor);
1820                 pow = ilog2(lock_len) - ilog2(min_prot_len) + 1;
1821                 val = pow << SR_BP_SHIFT;
1822
1823                 if (nor->flags & SNOR_F_HAS_SR_BP3_BIT6 && val & SR_BP3)
1824                         val = (val & ~SR_BP3) | SR_BP3_BIT6;
1825
1826                 /* Some power-of-two sizes are not supported */
1827                 if (val & ~mask)
1828                         return -EINVAL;
1829         }
1830
1831         status_new = (status_old & ~mask & ~tb_mask) | val;
1832
1833         /* Don't protect status register if we're fully unlocked */
1834         if (lock_len == 0)
1835                 status_new &= ~SR_SRWD;
1836
1837         if (!use_top)
1838                 status_new |= tb_mask;
1839
1840         /* Don't bother if they're the same */
1841         if (status_new == status_old)
1842                 return 0;
1843
1844         /* Only modify protection if it will not lock other areas */
1845         if ((status_new & mask) > (status_old & mask))
1846                 return -EINVAL;
1847
1848         return spi_nor_write_sr_and_check(nor, status_new);
1849 }
1850
1851 /*
1852  * Check if a region of the flash is (completely) locked. See spi_nor_sr_lock()
1853  * for more info.
1854  *
1855  * Returns 1 if entire region is locked, 0 if any portion is unlocked, and
1856  * negative on errors.
1857  */
1858 static int spi_nor_sr_is_locked(struct spi_nor *nor, loff_t ofs, uint64_t len)
1859 {
1860         int ret;
1861
1862         ret = spi_nor_read_sr(nor, nor->bouncebuf);
1863         if (ret)
1864                 return ret;
1865
1866         return spi_nor_is_locked_sr(nor, ofs, len, nor->bouncebuf[0]);
1867 }
1868
1869 static const struct spi_nor_locking_ops spi_nor_sr_locking_ops = {
1870         .lock = spi_nor_sr_lock,
1871         .unlock = spi_nor_sr_unlock,
1872         .is_locked = spi_nor_sr_is_locked,
1873 };
1874
1875 static int spi_nor_lock(struct mtd_info *mtd, loff_t ofs, uint64_t len)
1876 {
1877         struct spi_nor *nor = mtd_to_spi_nor(mtd);
1878         int ret;
1879
1880         ret = spi_nor_lock_and_prep(nor);
1881         if (ret)
1882                 return ret;
1883
1884         ret = nor->params->locking_ops->lock(nor, ofs, len);
1885
1886         spi_nor_unlock_and_unprep(nor);
1887         return ret;
1888 }
1889
1890 static int spi_nor_unlock(struct mtd_info *mtd, loff_t ofs, uint64_t len)
1891 {
1892         struct spi_nor *nor = mtd_to_spi_nor(mtd);
1893         int ret;
1894
1895         ret = spi_nor_lock_and_prep(nor);
1896         if (ret)
1897                 return ret;
1898
1899         ret = nor->params->locking_ops->unlock(nor, ofs, len);
1900
1901         spi_nor_unlock_and_unprep(nor);
1902         return ret;
1903 }
1904
1905 static int spi_nor_is_locked(struct mtd_info *mtd, loff_t ofs, uint64_t len)
1906 {
1907         struct spi_nor *nor = mtd_to_spi_nor(mtd);
1908         int ret;
1909
1910         ret = spi_nor_lock_and_prep(nor);
1911         if (ret)
1912                 return ret;
1913
1914         ret = nor->params->locking_ops->is_locked(nor, ofs, len);
1915
1916         spi_nor_unlock_and_unprep(nor);
1917         return ret;
1918 }
1919
1920 /**
1921  * spi_nor_sr1_bit6_quad_enable() - Set the Quad Enable BIT(6) in the Status
1922  * Register 1.
1923  * @nor:        pointer to a 'struct spi_nor'
1924  *
1925  * Bit 6 of the Status Register 1 is the QE bit for Macronix like QSPI memories.
1926  *
1927  * Return: 0 on success, -errno otherwise.
1928  */
1929 int spi_nor_sr1_bit6_quad_enable(struct spi_nor *nor)
1930 {
1931         int ret;
1932
1933         ret = spi_nor_read_sr(nor, nor->bouncebuf);
1934         if (ret)
1935                 return ret;
1936
1937         if (nor->bouncebuf[0] & SR1_QUAD_EN_BIT6)
1938                 return 0;
1939
1940         nor->bouncebuf[0] |= SR1_QUAD_EN_BIT6;
1941
1942         return spi_nor_write_sr1_and_check(nor, nor->bouncebuf[0]);
1943 }
1944
1945 /**
1946  * spi_nor_sr2_bit1_quad_enable() - set the Quad Enable BIT(1) in the Status
1947  * Register 2.
1948  * @nor:       pointer to a 'struct spi_nor'.
1949  *
1950  * Bit 1 of the Status Register 2 is the QE bit for Spansion like QSPI memories.
1951  *
1952  * Return: 0 on success, -errno otherwise.
1953  */
1954 int spi_nor_sr2_bit1_quad_enable(struct spi_nor *nor)
1955 {
1956         int ret;
1957
1958         if (nor->flags & SNOR_F_NO_READ_CR)
1959                 return spi_nor_write_16bit_cr_and_check(nor, SR2_QUAD_EN_BIT1);
1960
1961         ret = spi_nor_read_cr(nor, nor->bouncebuf);
1962         if (ret)
1963                 return ret;
1964
1965         if (nor->bouncebuf[0] & SR2_QUAD_EN_BIT1)
1966                 return 0;
1967
1968         nor->bouncebuf[0] |= SR2_QUAD_EN_BIT1;
1969
1970         return spi_nor_write_16bit_cr_and_check(nor, nor->bouncebuf[0]);
1971 }
1972
1973 /**
1974  * spi_nor_sr2_bit7_quad_enable() - set QE bit in Status Register 2.
1975  * @nor:        pointer to a 'struct spi_nor'
1976  *
1977  * Set the Quad Enable (QE) bit in the Status Register 2.
1978  *
1979  * This is one of the procedures to set the QE bit described in the SFDP
1980  * (JESD216 rev B) specification but no manufacturer using this procedure has
1981  * been identified yet, hence the name of the function.
1982  *
1983  * Return: 0 on success, -errno otherwise.
1984  */
1985 int spi_nor_sr2_bit7_quad_enable(struct spi_nor *nor)
1986 {
1987         u8 *sr2 = nor->bouncebuf;
1988         int ret;
1989         u8 sr2_written;
1990
1991         /* Check current Quad Enable bit value. */
1992         ret = spi_nor_read_sr2(nor, sr2);
1993         if (ret)
1994                 return ret;
1995         if (*sr2 & SR2_QUAD_EN_BIT7)
1996                 return 0;
1997
1998         /* Update the Quad Enable bit. */
1999         *sr2 |= SR2_QUAD_EN_BIT7;
2000
2001         ret = spi_nor_write_sr2(nor, sr2);
2002         if (ret)
2003                 return ret;
2004
2005         sr2_written = *sr2;
2006
2007         /* Read back and check it. */
2008         ret = spi_nor_read_sr2(nor, sr2);
2009         if (ret)
2010                 return ret;
2011
2012         if (*sr2 != sr2_written) {
2013                 dev_dbg(nor->dev, "SR2: Read back test failed\n");
2014                 return -EIO;
2015         }
2016
2017         return 0;
2018 }
2019
2020 static const struct spi_nor_manufacturer *manufacturers[] = {
2021         &spi_nor_atmel,
2022         &spi_nor_catalyst,
2023         &spi_nor_eon,
2024         &spi_nor_esmt,
2025         &spi_nor_everspin,
2026         &spi_nor_fujitsu,
2027         &spi_nor_gigadevice,
2028         &spi_nor_intel,
2029         &spi_nor_issi,
2030         &spi_nor_macronix,
2031         &spi_nor_micron,
2032         &spi_nor_st,
2033         &spi_nor_spansion,
2034         &spi_nor_sst,
2035         &spi_nor_winbond,
2036         &spi_nor_xilinx,
2037         &spi_nor_xmc,
2038 };
2039
2040 static const struct flash_info *
2041 spi_nor_search_part_by_id(const struct flash_info *parts, unsigned int nparts,
2042                           const u8 *id)
2043 {
2044         unsigned int i;
2045
2046         for (i = 0; i < nparts; i++) {
2047                 if (parts[i].id_len &&
2048                     !memcmp(parts[i].id, id, parts[i].id_len))
2049                         return &parts[i];
2050         }
2051
2052         return NULL;
2053 }
2054
2055 static const struct flash_info *spi_nor_read_id(struct spi_nor *nor)
2056 {
2057         const struct flash_info *info;
2058         u8 *id = nor->bouncebuf;
2059         unsigned int i;
2060         int ret;
2061
2062         if (nor->spimem) {
2063                 struct spi_mem_op op =
2064                         SPI_MEM_OP(SPI_MEM_OP_CMD(SPINOR_OP_RDID, 1),
2065                                    SPI_MEM_OP_NO_ADDR,
2066                                    SPI_MEM_OP_NO_DUMMY,
2067                                    SPI_MEM_OP_DATA_IN(SPI_NOR_MAX_ID_LEN, id, 1));
2068
2069                 ret = spi_mem_exec_op(nor->spimem, &op);
2070         } else {
2071                 ret = nor->controller_ops->read_reg(nor, SPINOR_OP_RDID, id,
2072                                                     SPI_NOR_MAX_ID_LEN);
2073         }
2074         if (ret) {
2075                 dev_dbg(nor->dev, "error %d reading JEDEC ID\n", ret);
2076                 return ERR_PTR(ret);
2077         }
2078
2079         for (i = 0; i < ARRAY_SIZE(manufacturers); i++) {
2080                 info = spi_nor_search_part_by_id(manufacturers[i]->parts,
2081                                                  manufacturers[i]->nparts,
2082                                                  id);
2083                 if (info) {
2084                         nor->manufacturer = manufacturers[i];
2085                         return info;
2086                 }
2087         }
2088
2089         dev_err(nor->dev, "unrecognized JEDEC id bytes: %*ph\n",
2090                 SPI_NOR_MAX_ID_LEN, id);
2091         return ERR_PTR(-ENODEV);
2092 }
2093
2094 static int spi_nor_read(struct mtd_info *mtd, loff_t from, size_t len,
2095                         size_t *retlen, u_char *buf)
2096 {
2097         struct spi_nor *nor = mtd_to_spi_nor(mtd);
2098         ssize_t ret;
2099
2100         dev_dbg(nor->dev, "from 0x%08x, len %zd\n", (u32)from, len);
2101
2102         ret = spi_nor_lock_and_prep(nor);
2103         if (ret)
2104                 return ret;
2105
2106         while (len) {
2107                 loff_t addr = from;
2108
2109                 addr = spi_nor_convert_addr(nor, addr);
2110
2111                 ret = spi_nor_read_data(nor, addr, len, buf);
2112                 if (ret == 0) {
2113                         /* We shouldn't see 0-length reads */
2114                         ret = -EIO;
2115                         goto read_err;
2116                 }
2117                 if (ret < 0)
2118                         goto read_err;
2119
2120                 WARN_ON(ret > len);
2121                 *retlen += ret;
2122                 buf += ret;
2123                 from += ret;
2124                 len -= ret;
2125         }
2126         ret = 0;
2127
2128 read_err:
2129         spi_nor_unlock_and_unprep(nor);
2130         return ret;
2131 }
2132
2133 /*
2134  * Write an address range to the nor chip.  Data must be written in
2135  * FLASH_PAGESIZE chunks.  The address range may be any size provided
2136  * it is within the physical boundaries.
2137  */
2138 static int spi_nor_write(struct mtd_info *mtd, loff_t to, size_t len,
2139         size_t *retlen, const u_char *buf)
2140 {
2141         struct spi_nor *nor = mtd_to_spi_nor(mtd);
2142         size_t page_offset, page_remain, i;
2143         ssize_t ret;
2144
2145         dev_dbg(nor->dev, "to 0x%08x, len %zd\n", (u32)to, len);
2146
2147         ret = spi_nor_lock_and_prep(nor);
2148         if (ret)
2149                 return ret;
2150
2151         for (i = 0; i < len; ) {
2152                 ssize_t written;
2153                 loff_t addr = to + i;
2154
2155                 /*
2156                  * If page_size is a power of two, the offset can be quickly
2157                  * calculated with an AND operation. On the other cases we
2158                  * need to do a modulus operation (more expensive).
2159                  * Power of two numbers have only one bit set and we can use
2160                  * the instruction hweight32 to detect if we need to do a
2161                  * modulus (do_div()) or not.
2162                  */
2163                 if (hweight32(nor->page_size) == 1) {
2164                         page_offset = addr & (nor->page_size - 1);
2165                 } else {
2166                         uint64_t aux = addr;
2167
2168                         page_offset = do_div(aux, nor->page_size);
2169                 }
2170                 /* the size of data remaining on the first page */
2171                 page_remain = min_t(size_t,
2172                                     nor->page_size - page_offset, len - i);
2173
2174                 addr = spi_nor_convert_addr(nor, addr);
2175
2176                 ret = spi_nor_write_enable(nor);
2177                 if (ret)
2178                         goto write_err;
2179
2180                 ret = spi_nor_write_data(nor, addr, page_remain, buf + i);
2181                 if (ret < 0)
2182                         goto write_err;
2183                 written = ret;
2184
2185                 ret = spi_nor_wait_till_ready(nor);
2186                 if (ret)
2187                         goto write_err;
2188                 *retlen += written;
2189                 i += written;
2190         }
2191
2192 write_err:
2193         spi_nor_unlock_and_unprep(nor);
2194         return ret;
2195 }
2196
2197 static int spi_nor_check(struct spi_nor *nor)
2198 {
2199         if (!nor->dev ||
2200             (!nor->spimem && !nor->controller_ops) ||
2201             (!nor->spimem && nor->controller_ops &&
2202             (!nor->controller_ops->read ||
2203              !nor->controller_ops->write ||
2204              !nor->controller_ops->read_reg ||
2205              !nor->controller_ops->write_reg))) {
2206                 pr_err("spi-nor: please fill all the necessary fields!\n");
2207                 return -EINVAL;
2208         }
2209
2210         if (nor->spimem && nor->controller_ops) {
2211                 dev_err(nor->dev, "nor->spimem and nor->controller_ops are mutually exclusive, please set just one of them.\n");
2212                 return -EINVAL;
2213         }
2214
2215         return 0;
2216 }
2217
2218 static void
2219 spi_nor_set_read_settings(struct spi_nor_read_command *read,
2220                           u8 num_mode_clocks,
2221                           u8 num_wait_states,
2222                           u8 opcode,
2223                           enum spi_nor_protocol proto)
2224 {
2225         read->num_mode_clocks = num_mode_clocks;
2226         read->num_wait_states = num_wait_states;
2227         read->opcode = opcode;
2228         read->proto = proto;
2229 }
2230
2231 void spi_nor_set_pp_settings(struct spi_nor_pp_command *pp, u8 opcode,
2232                              enum spi_nor_protocol proto)
2233 {
2234         pp->opcode = opcode;
2235         pp->proto = proto;
2236 }
2237
2238 static int spi_nor_hwcaps2cmd(u32 hwcaps, const int table[][2], size_t size)
2239 {
2240         size_t i;
2241
2242         for (i = 0; i < size; i++)
2243                 if (table[i][0] == (int)hwcaps)
2244                         return table[i][1];
2245
2246         return -EINVAL;
2247 }
2248
2249 int spi_nor_hwcaps_read2cmd(u32 hwcaps)
2250 {
2251         static const int hwcaps_read2cmd[][2] = {
2252                 { SNOR_HWCAPS_READ,             SNOR_CMD_READ },
2253                 { SNOR_HWCAPS_READ_FAST,        SNOR_CMD_READ_FAST },
2254                 { SNOR_HWCAPS_READ_1_1_1_DTR,   SNOR_CMD_READ_1_1_1_DTR },
2255                 { SNOR_HWCAPS_READ_1_1_2,       SNOR_CMD_READ_1_1_2 },
2256                 { SNOR_HWCAPS_READ_1_2_2,       SNOR_CMD_READ_1_2_2 },
2257                 { SNOR_HWCAPS_READ_2_2_2,       SNOR_CMD_READ_2_2_2 },
2258                 { SNOR_HWCAPS_READ_1_2_2_DTR,   SNOR_CMD_READ_1_2_2_DTR },
2259                 { SNOR_HWCAPS_READ_1_1_4,       SNOR_CMD_READ_1_1_4 },
2260                 { SNOR_HWCAPS_READ_1_4_4,       SNOR_CMD_READ_1_4_4 },
2261                 { SNOR_HWCAPS_READ_4_4_4,       SNOR_CMD_READ_4_4_4 },
2262                 { SNOR_HWCAPS_READ_1_4_4_DTR,   SNOR_CMD_READ_1_4_4_DTR },
2263                 { SNOR_HWCAPS_READ_1_1_8,       SNOR_CMD_READ_1_1_8 },
2264                 { SNOR_HWCAPS_READ_1_8_8,       SNOR_CMD_READ_1_8_8 },
2265                 { SNOR_HWCAPS_READ_8_8_8,       SNOR_CMD_READ_8_8_8 },
2266                 { SNOR_HWCAPS_READ_1_8_8_DTR,   SNOR_CMD_READ_1_8_8_DTR },
2267         };
2268
2269         return spi_nor_hwcaps2cmd(hwcaps, hwcaps_read2cmd,
2270                                   ARRAY_SIZE(hwcaps_read2cmd));
2271 }
2272
2273 static int spi_nor_hwcaps_pp2cmd(u32 hwcaps)
2274 {
2275         static const int hwcaps_pp2cmd[][2] = {
2276                 { SNOR_HWCAPS_PP,               SNOR_CMD_PP },
2277                 { SNOR_HWCAPS_PP_1_1_4,         SNOR_CMD_PP_1_1_4 },
2278                 { SNOR_HWCAPS_PP_1_4_4,         SNOR_CMD_PP_1_4_4 },
2279                 { SNOR_HWCAPS_PP_4_4_4,         SNOR_CMD_PP_4_4_4 },
2280                 { SNOR_HWCAPS_PP_1_1_8,         SNOR_CMD_PP_1_1_8 },
2281                 { SNOR_HWCAPS_PP_1_8_8,         SNOR_CMD_PP_1_8_8 },
2282                 { SNOR_HWCAPS_PP_8_8_8,         SNOR_CMD_PP_8_8_8 },
2283         };
2284
2285         return spi_nor_hwcaps2cmd(hwcaps, hwcaps_pp2cmd,
2286                                   ARRAY_SIZE(hwcaps_pp2cmd));
2287 }
2288
2289 /**
2290  * spi_nor_spimem_check_op - check if the operation is supported
2291  *                           by controller
2292  *@nor:        pointer to a 'struct spi_nor'
2293  *@op:         pointer to op template to be checked
2294  *
2295  * Returns 0 if operation is supported, -ENOTSUPP otherwise.
2296  */
2297 static int spi_nor_spimem_check_op(struct spi_nor *nor,
2298                                    struct spi_mem_op *op)
2299 {
2300         /*
2301          * First test with 4 address bytes. The opcode itself might
2302          * be a 3B addressing opcode but we don't care, because
2303          * SPI controller implementation should not check the opcode,
2304          * but just the sequence.
2305          */
2306         op->addr.nbytes = 4;
2307         if (!spi_mem_supports_op(nor->spimem, op)) {
2308                 if (nor->mtd.size > SZ_16M)
2309                         return -ENOTSUPP;
2310
2311                 /* If flash size <= 16MB, 3 address bytes are sufficient */
2312                 op->addr.nbytes = 3;
2313                 if (!spi_mem_supports_op(nor->spimem, op))
2314                         return -ENOTSUPP;
2315         }
2316
2317         return 0;
2318 }
2319
2320 /**
2321  * spi_nor_spimem_check_readop - check if the read op is supported
2322  *                               by controller
2323  *@nor:         pointer to a 'struct spi_nor'
2324  *@read:        pointer to op template to be checked
2325  *
2326  * Returns 0 if operation is supported, -ENOTSUPP otherwise.
2327  */
2328 static int spi_nor_spimem_check_readop(struct spi_nor *nor,
2329                                        const struct spi_nor_read_command *read)
2330 {
2331         struct spi_mem_op op = SPI_MEM_OP(SPI_MEM_OP_CMD(read->opcode, 1),
2332                                           SPI_MEM_OP_ADDR(3, 0, 1),
2333                                           SPI_MEM_OP_DUMMY(0, 1),
2334                                           SPI_MEM_OP_DATA_IN(0, NULL, 1));
2335
2336         op.cmd.buswidth = spi_nor_get_protocol_inst_nbits(read->proto);
2337         op.addr.buswidth = spi_nor_get_protocol_addr_nbits(read->proto);
2338         op.data.buswidth = spi_nor_get_protocol_data_nbits(read->proto);
2339         op.dummy.buswidth = op.addr.buswidth;
2340         op.dummy.nbytes = (read->num_mode_clocks + read->num_wait_states) *
2341                           op.dummy.buswidth / 8;
2342
2343         return spi_nor_spimem_check_op(nor, &op);
2344 }
2345
2346 /**
2347  * spi_nor_spimem_check_pp - check if the page program op is supported
2348  *                           by controller
2349  *@nor:         pointer to a 'struct spi_nor'
2350  *@pp:          pointer to op template to be checked
2351  *
2352  * Returns 0 if operation is supported, -ENOTSUPP otherwise.
2353  */
2354 static int spi_nor_spimem_check_pp(struct spi_nor *nor,
2355                                    const struct spi_nor_pp_command *pp)
2356 {
2357         struct spi_mem_op op = SPI_MEM_OP(SPI_MEM_OP_CMD(pp->opcode, 1),
2358                                           SPI_MEM_OP_ADDR(3, 0, 1),
2359                                           SPI_MEM_OP_NO_DUMMY,
2360                                           SPI_MEM_OP_DATA_OUT(0, NULL, 1));
2361
2362         op.cmd.buswidth = spi_nor_get_protocol_inst_nbits(pp->proto);
2363         op.addr.buswidth = spi_nor_get_protocol_addr_nbits(pp->proto);
2364         op.data.buswidth = spi_nor_get_protocol_data_nbits(pp->proto);
2365
2366         return spi_nor_spimem_check_op(nor, &op);
2367 }
2368
2369 /**
2370  * spi_nor_spimem_adjust_hwcaps - Find optimal Read/Write protocol
2371  *                                based on SPI controller capabilities
2372  * @nor:        pointer to a 'struct spi_nor'
2373  * @hwcaps:     pointer to resulting capabilities after adjusting
2374  *              according to controller and flash's capability
2375  */
2376 static void
2377 spi_nor_spimem_adjust_hwcaps(struct spi_nor *nor, u32 *hwcaps)
2378 {
2379         struct spi_nor_flash_parameter *params = nor->params;
2380         unsigned int cap;
2381
2382         /* DTR modes are not supported yet, mask them all. */
2383         *hwcaps &= ~SNOR_HWCAPS_DTR;
2384
2385         /* X-X-X modes are not supported yet, mask them all. */
2386         *hwcaps &= ~SNOR_HWCAPS_X_X_X;
2387
2388         for (cap = 0; cap < sizeof(*hwcaps) * BITS_PER_BYTE; cap++) {
2389                 int rdidx, ppidx;
2390
2391                 if (!(*hwcaps & BIT(cap)))
2392                         continue;
2393
2394                 rdidx = spi_nor_hwcaps_read2cmd(BIT(cap));
2395                 if (rdidx >= 0 &&
2396                     spi_nor_spimem_check_readop(nor, &params->reads[rdidx]))
2397                         *hwcaps &= ~BIT(cap);
2398
2399                 ppidx = spi_nor_hwcaps_pp2cmd(BIT(cap));
2400                 if (ppidx < 0)
2401                         continue;
2402
2403                 if (spi_nor_spimem_check_pp(nor,
2404                                             &params->page_programs[ppidx]))
2405                         *hwcaps &= ~BIT(cap);
2406         }
2407 }
2408
2409 /**
2410  * spi_nor_set_erase_type() - set a SPI NOR erase type
2411  * @erase:      pointer to a structure that describes a SPI NOR erase type
2412  * @size:       the size of the sector/block erased by the erase type
2413  * @opcode:     the SPI command op code to erase the sector/block
2414  */
2415 void spi_nor_set_erase_type(struct spi_nor_erase_type *erase, u32 size,
2416                             u8 opcode)
2417 {
2418         erase->size = size;
2419         erase->opcode = opcode;
2420         /* JEDEC JESD216B Standard imposes erase sizes to be power of 2. */
2421         erase->size_shift = ffs(erase->size) - 1;
2422         erase->size_mask = (1 << erase->size_shift) - 1;
2423 }
2424
2425 /**
2426  * spi_nor_init_uniform_erase_map() - Initialize uniform erase map
2427  * @map:                the erase map of the SPI NOR
2428  * @erase_mask:         bitmask encoding erase types that can erase the entire
2429  *                      flash memory
2430  * @flash_size:         the spi nor flash memory size
2431  */
2432 void spi_nor_init_uniform_erase_map(struct spi_nor_erase_map *map,
2433                                     u8 erase_mask, u64 flash_size)
2434 {
2435         /* Offset 0 with erase_mask and SNOR_LAST_REGION bit set */
2436         map->uniform_region.offset = (erase_mask & SNOR_ERASE_TYPE_MASK) |
2437                                      SNOR_LAST_REGION;
2438         map->uniform_region.size = flash_size;
2439         map->regions = &map->uniform_region;
2440         map->uniform_erase_type = erase_mask;
2441 }
2442
2443 int spi_nor_post_bfpt_fixups(struct spi_nor *nor,
2444                              const struct sfdp_parameter_header *bfpt_header,
2445                              const struct sfdp_bfpt *bfpt,
2446                              struct spi_nor_flash_parameter *params)
2447 {
2448         int ret;
2449
2450         if (nor->manufacturer && nor->manufacturer->fixups &&
2451             nor->manufacturer->fixups->post_bfpt) {
2452                 ret = nor->manufacturer->fixups->post_bfpt(nor, bfpt_header,
2453                                                            bfpt, params);
2454                 if (ret)
2455                         return ret;
2456         }
2457
2458         if (nor->info->fixups && nor->info->fixups->post_bfpt)
2459                 return nor->info->fixups->post_bfpt(nor, bfpt_header, bfpt,
2460                                                     params);
2461
2462         return 0;
2463 }
2464
2465 static int spi_nor_select_read(struct spi_nor *nor,
2466                                u32 shared_hwcaps)
2467 {
2468         int cmd, best_match = fls(shared_hwcaps & SNOR_HWCAPS_READ_MASK) - 1;
2469         const struct spi_nor_read_command *read;
2470
2471         if (best_match < 0)
2472                 return -EINVAL;
2473
2474         cmd = spi_nor_hwcaps_read2cmd(BIT(best_match));
2475         if (cmd < 0)
2476                 return -EINVAL;
2477
2478         read = &nor->params->reads[cmd];
2479         nor->read_opcode = read->opcode;
2480         nor->read_proto = read->proto;
2481
2482         /*
2483          * In the SPI NOR framework, we don't need to make the difference
2484          * between mode clock cycles and wait state clock cycles.
2485          * Indeed, the value of the mode clock cycles is used by a QSPI
2486          * flash memory to know whether it should enter or leave its 0-4-4
2487          * (Continuous Read / XIP) mode.
2488          * eXecution In Place is out of the scope of the mtd sub-system.
2489          * Hence we choose to merge both mode and wait state clock cycles
2490          * into the so called dummy clock cycles.
2491          */
2492         nor->read_dummy = read->num_mode_clocks + read->num_wait_states;
2493         return 0;
2494 }
2495
2496 static int spi_nor_select_pp(struct spi_nor *nor,
2497                              u32 shared_hwcaps)
2498 {
2499         int cmd, best_match = fls(shared_hwcaps & SNOR_HWCAPS_PP_MASK) - 1;
2500         const struct spi_nor_pp_command *pp;
2501
2502         if (best_match < 0)
2503                 return -EINVAL;
2504
2505         cmd = spi_nor_hwcaps_pp2cmd(BIT(best_match));
2506         if (cmd < 0)
2507                 return -EINVAL;
2508
2509         pp = &nor->params->page_programs[cmd];
2510         nor->program_opcode = pp->opcode;
2511         nor->write_proto = pp->proto;
2512         return 0;
2513 }
2514
2515 /**
2516  * spi_nor_select_uniform_erase() - select optimum uniform erase type
2517  * @map:                the erase map of the SPI NOR
2518  * @wanted_size:        the erase type size to search for. Contains the value of
2519  *                      info->sector_size or of the "small sector" size in case
2520  *                      CONFIG_MTD_SPI_NOR_USE_4K_SECTORS is defined.
2521  *
2522  * Once the optimum uniform sector erase command is found, disable all the
2523  * other.
2524  *
2525  * Return: pointer to erase type on success, NULL otherwise.
2526  */
2527 static const struct spi_nor_erase_type *
2528 spi_nor_select_uniform_erase(struct spi_nor_erase_map *map,
2529                              const u32 wanted_size)
2530 {
2531         const struct spi_nor_erase_type *tested_erase, *erase = NULL;
2532         int i;
2533         u8 uniform_erase_type = map->uniform_erase_type;
2534
2535         for (i = SNOR_ERASE_TYPE_MAX - 1; i >= 0; i--) {
2536                 if (!(uniform_erase_type & BIT(i)))
2537                         continue;
2538
2539                 tested_erase = &map->erase_type[i];
2540
2541                 /*
2542                  * If the current erase size is the one, stop here:
2543                  * we have found the right uniform Sector Erase command.
2544                  */
2545                 if (tested_erase->size == wanted_size) {
2546                         erase = tested_erase;
2547                         break;
2548                 }
2549
2550                 /*
2551                  * Otherwise, the current erase size is still a valid canditate.
2552                  * Select the biggest valid candidate.
2553                  */
2554                 if (!erase && tested_erase->size)
2555                         erase = tested_erase;
2556                         /* keep iterating to find the wanted_size */
2557         }
2558
2559         if (!erase)
2560                 return NULL;
2561
2562         /* Disable all other Sector Erase commands. */
2563         map->uniform_erase_type &= ~SNOR_ERASE_TYPE_MASK;
2564         map->uniform_erase_type |= BIT(erase - map->erase_type);
2565         return erase;
2566 }
2567
2568 static int spi_nor_select_erase(struct spi_nor *nor)
2569 {
2570         struct spi_nor_erase_map *map = &nor->params->erase_map;
2571         const struct spi_nor_erase_type *erase = NULL;
2572         struct mtd_info *mtd = &nor->mtd;
2573         u32 wanted_size = nor->info->sector_size;
2574         int i;
2575
2576         /*
2577          * The previous implementation handling Sector Erase commands assumed
2578          * that the SPI flash memory has an uniform layout then used only one
2579          * of the supported erase sizes for all Sector Erase commands.
2580          * So to be backward compatible, the new implementation also tries to
2581          * manage the SPI flash memory as uniform with a single erase sector
2582          * size, when possible.
2583          */
2584 #ifdef CONFIG_MTD_SPI_NOR_USE_4K_SECTORS
2585         /* prefer "small sector" erase if possible */
2586         wanted_size = 4096u;
2587 #endif
2588
2589         if (spi_nor_has_uniform_erase(nor)) {
2590                 erase = spi_nor_select_uniform_erase(map, wanted_size);
2591                 if (!erase)
2592                         return -EINVAL;
2593                 nor->erase_opcode = erase->opcode;
2594                 mtd->erasesize = erase->size;
2595                 return 0;
2596         }
2597
2598         /*
2599          * For non-uniform SPI flash memory, set mtd->erasesize to the
2600          * maximum erase sector size. No need to set nor->erase_opcode.
2601          */
2602         for (i = SNOR_ERASE_TYPE_MAX - 1; i >= 0; i--) {
2603                 if (map->erase_type[i].size) {
2604                         erase = &map->erase_type[i];
2605                         break;
2606                 }
2607         }
2608
2609         if (!erase)
2610                 return -EINVAL;
2611
2612         mtd->erasesize = erase->size;
2613         return 0;
2614 }
2615
2616 static int spi_nor_default_setup(struct spi_nor *nor,
2617                                  const struct spi_nor_hwcaps *hwcaps)
2618 {
2619         struct spi_nor_flash_parameter *params = nor->params;
2620         u32 ignored_mask, shared_mask;
2621         int err;
2622
2623         /*
2624          * Keep only the hardware capabilities supported by both the SPI
2625          * controller and the SPI flash memory.
2626          */
2627         shared_mask = hwcaps->mask & params->hwcaps.mask;
2628
2629         if (nor->spimem) {
2630                 /*
2631                  * When called from spi_nor_probe(), all caps are set and we
2632                  * need to discard some of them based on what the SPI
2633                  * controller actually supports (using spi_mem_supports_op()).
2634                  */
2635                 spi_nor_spimem_adjust_hwcaps(nor, &shared_mask);
2636         } else {
2637                 /*
2638                  * SPI n-n-n protocols are not supported when the SPI
2639                  * controller directly implements the spi_nor interface.
2640                  * Yet another reason to switch to spi-mem.
2641                  */
2642                 ignored_mask = SNOR_HWCAPS_X_X_X;
2643                 if (shared_mask & ignored_mask) {
2644                         dev_dbg(nor->dev,
2645                                 "SPI n-n-n protocols are not supported.\n");
2646                         shared_mask &= ~ignored_mask;
2647                 }
2648         }
2649
2650         /* Select the (Fast) Read command. */
2651         err = spi_nor_select_read(nor, shared_mask);
2652         if (err) {
2653                 dev_dbg(nor->dev,
2654                         "can't select read settings supported by both the SPI controller and memory.\n");
2655                 return err;
2656         }
2657
2658         /* Select the Page Program command. */
2659         err = spi_nor_select_pp(nor, shared_mask);
2660         if (err) {
2661                 dev_dbg(nor->dev,
2662                         "can't select write settings supported by both the SPI controller and memory.\n");
2663                 return err;
2664         }
2665
2666         /* Select the Sector Erase command. */
2667         err = spi_nor_select_erase(nor);
2668         if (err) {
2669                 dev_dbg(nor->dev,
2670                         "can't select erase settings supported by both the SPI controller and memory.\n");
2671                 return err;
2672         }
2673
2674         return 0;
2675 }
2676
2677 static int spi_nor_setup(struct spi_nor *nor,
2678                          const struct spi_nor_hwcaps *hwcaps)
2679 {
2680         if (!nor->params->setup)
2681                 return 0;
2682
2683         return nor->params->setup(nor, hwcaps);
2684 }
2685
2686 /**
2687  * spi_nor_manufacturer_init_params() - Initialize the flash's parameters and
2688  * settings based on MFR register and ->default_init() hook.
2689  * @nor:        pointer to a 'struct spi_nor'.
2690  */
2691 static void spi_nor_manufacturer_init_params(struct spi_nor *nor)
2692 {
2693         if (nor->manufacturer && nor->manufacturer->fixups &&
2694             nor->manufacturer->fixups->default_init)
2695                 nor->manufacturer->fixups->default_init(nor);
2696
2697         if (nor->info->fixups && nor->info->fixups->default_init)
2698                 nor->info->fixups->default_init(nor);
2699 }
2700
2701 /**
2702  * spi_nor_sfdp_init_params() - Initialize the flash's parameters and settings
2703  * based on JESD216 SFDP standard.
2704  * @nor:        pointer to a 'struct spi_nor'.
2705  *
2706  * The method has a roll-back mechanism: in case the SFDP parsing fails, the
2707  * legacy flash parameters and settings will be restored.
2708  */
2709 static void spi_nor_sfdp_init_params(struct spi_nor *nor)
2710 {
2711         struct spi_nor_flash_parameter sfdp_params;
2712
2713         memcpy(&sfdp_params, nor->params, sizeof(sfdp_params));
2714
2715         if (spi_nor_parse_sfdp(nor, nor->params)) {
2716                 memcpy(nor->params, &sfdp_params, sizeof(*nor->params));
2717                 nor->addr_width = 0;
2718                 nor->flags &= ~SNOR_F_4B_OPCODES;
2719         }
2720 }
2721
2722 /**
2723  * spi_nor_info_init_params() - Initialize the flash's parameters and settings
2724  * based on nor->info data.
2725  * @nor:        pointer to a 'struct spi_nor'.
2726  */
2727 static void spi_nor_info_init_params(struct spi_nor *nor)
2728 {
2729         struct spi_nor_flash_parameter *params = nor->params;
2730         struct spi_nor_erase_map *map = &params->erase_map;
2731         const struct flash_info *info = nor->info;
2732         struct device_node *np = spi_nor_get_flash_node(nor);
2733         u8 i, erase_mask;
2734
2735         /* Initialize legacy flash parameters and settings. */
2736         params->quad_enable = spi_nor_sr2_bit1_quad_enable;
2737         params->set_4byte_addr_mode = spansion_set_4byte_addr_mode;
2738         params->setup = spi_nor_default_setup;
2739         /* Default to 16-bit Write Status (01h) Command */
2740         nor->flags |= SNOR_F_HAS_16BIT_SR;
2741
2742         /* Set SPI NOR sizes. */
2743         params->size = (u64)info->sector_size * info->n_sectors;
2744         params->page_size = info->page_size;
2745
2746         if (!(info->flags & SPI_NOR_NO_FR)) {
2747                 /* Default to Fast Read for DT and non-DT platform devices. */
2748                 params->hwcaps.mask |= SNOR_HWCAPS_READ_FAST;
2749
2750                 /* Mask out Fast Read if not requested at DT instantiation. */
2751                 if (np && !of_property_read_bool(np, "m25p,fast-read"))
2752                         params->hwcaps.mask &= ~SNOR_HWCAPS_READ_FAST;
2753         }
2754
2755         /* (Fast) Read settings. */
2756         params->hwcaps.mask |= SNOR_HWCAPS_READ;
2757         spi_nor_set_read_settings(&params->reads[SNOR_CMD_READ],
2758                                   0, 0, SPINOR_OP_READ,
2759                                   SNOR_PROTO_1_1_1);
2760
2761         if (params->hwcaps.mask & SNOR_HWCAPS_READ_FAST)
2762                 spi_nor_set_read_settings(&params->reads[SNOR_CMD_READ_FAST],
2763                                           0, 8, SPINOR_OP_READ_FAST,
2764                                           SNOR_PROTO_1_1_1);
2765
2766         if (info->flags & SPI_NOR_DUAL_READ) {
2767                 params->hwcaps.mask |= SNOR_HWCAPS_READ_1_1_2;
2768                 spi_nor_set_read_settings(&params->reads[SNOR_CMD_READ_1_1_2],
2769                                           0, 8, SPINOR_OP_READ_1_1_2,
2770                                           SNOR_PROTO_1_1_2);
2771         }
2772
2773         if (info->flags & SPI_NOR_QUAD_READ) {
2774                 params->hwcaps.mask |= SNOR_HWCAPS_READ_1_1_4;
2775                 spi_nor_set_read_settings(&params->reads[SNOR_CMD_READ_1_1_4],
2776                                           0, 8, SPINOR_OP_READ_1_1_4,
2777                                           SNOR_PROTO_1_1_4);
2778         }
2779
2780         if (info->flags & SPI_NOR_OCTAL_READ) {
2781                 params->hwcaps.mask |= SNOR_HWCAPS_READ_1_1_8;
2782                 spi_nor_set_read_settings(&params->reads[SNOR_CMD_READ_1_1_8],
2783                                           0, 8, SPINOR_OP_READ_1_1_8,
2784                                           SNOR_PROTO_1_1_8);
2785         }
2786
2787         /* Page Program settings. */
2788         params->hwcaps.mask |= SNOR_HWCAPS_PP;
2789         spi_nor_set_pp_settings(&params->page_programs[SNOR_CMD_PP],
2790                                 SPINOR_OP_PP, SNOR_PROTO_1_1_1);
2791
2792         /*
2793          * Sector Erase settings. Sort Erase Types in ascending order, with the
2794          * smallest erase size starting at BIT(0).
2795          */
2796         erase_mask = 0;
2797         i = 0;
2798         if (info->flags & SECT_4K_PMC) {
2799                 erase_mask |= BIT(i);
2800                 spi_nor_set_erase_type(&map->erase_type[i], 4096u,
2801                                        SPINOR_OP_BE_4K_PMC);
2802                 i++;
2803         } else if (info->flags & SECT_4K) {
2804                 erase_mask |= BIT(i);
2805                 spi_nor_set_erase_type(&map->erase_type[i], 4096u,
2806                                        SPINOR_OP_BE_4K);
2807                 i++;
2808         }
2809         erase_mask |= BIT(i);
2810         spi_nor_set_erase_type(&map->erase_type[i], info->sector_size,
2811                                SPINOR_OP_SE);
2812         spi_nor_init_uniform_erase_map(map, erase_mask, params->size);
2813 }
2814
2815 /**
2816  * spi_nor_post_sfdp_fixups() - Updates the flash's parameters and settings
2817  * after SFDP has been parsed (is also called for SPI NORs that do not
2818  * support RDSFDP).
2819  * @nor:        pointer to a 'struct spi_nor'
2820  *
2821  * Typically used to tweak various parameters that could not be extracted by
2822  * other means (i.e. when information provided by the SFDP/flash_info tables
2823  * are incomplete or wrong).
2824  */
2825 static void spi_nor_post_sfdp_fixups(struct spi_nor *nor)
2826 {
2827         if (nor->manufacturer && nor->manufacturer->fixups &&
2828             nor->manufacturer->fixups->post_sfdp)
2829                 nor->manufacturer->fixups->post_sfdp(nor);
2830
2831         if (nor->info->fixups && nor->info->fixups->post_sfdp)
2832                 nor->info->fixups->post_sfdp(nor);
2833 }
2834
2835 /**
2836  * spi_nor_late_init_params() - Late initialization of default flash parameters.
2837  * @nor:        pointer to a 'struct spi_nor'
2838  *
2839  * Used to set default flash parameters and settings when the ->default_init()
2840  * hook or the SFDP parser let voids.
2841  */
2842 static void spi_nor_late_init_params(struct spi_nor *nor)
2843 {
2844         /*
2845          * NOR protection support. When locking_ops are not provided, we pick
2846          * the default ones.
2847          */
2848         if (nor->flags & SNOR_F_HAS_LOCK && !nor->params->locking_ops)
2849                 nor->params->locking_ops = &spi_nor_sr_locking_ops;
2850 }
2851
2852 /**
2853  * spi_nor_init_params() - Initialize the flash's parameters and settings.
2854  * @nor:        pointer to a 'struct spi_nor'.
2855  *
2856  * The flash parameters and settings are initialized based on a sequence of
2857  * calls that are ordered by priority:
2858  *
2859  * 1/ Default flash parameters initialization. The initializations are done
2860  *    based on nor->info data:
2861  *              spi_nor_info_init_params()
2862  *
2863  * which can be overwritten by:
2864  * 2/ Manufacturer flash parameters initialization. The initializations are
2865  *    done based on MFR register, or when the decisions can not be done solely
2866  *    based on MFR, by using specific flash_info tweeks, ->default_init():
2867  *              spi_nor_manufacturer_init_params()
2868  *
2869  * which can be overwritten by:
2870  * 3/ SFDP flash parameters initialization. JESD216 SFDP is a standard and
2871  *    should be more accurate that the above.
2872  *              spi_nor_sfdp_init_params()
2873  *
2874  *    Please note that there is a ->post_bfpt() fixup hook that can overwrite
2875  *    the flash parameters and settings immediately after parsing the Basic
2876  *    Flash Parameter Table.
2877  *
2878  * which can be overwritten by:
2879  * 4/ Post SFDP flash parameters initialization. Used to tweak various
2880  *    parameters that could not be extracted by other means (i.e. when
2881  *    information provided by the SFDP/flash_info tables are incomplete or
2882  *    wrong).
2883  *              spi_nor_post_sfdp_fixups()
2884  *
2885  * 5/ Late default flash parameters initialization, used when the
2886  * ->default_init() hook or the SFDP parser do not set specific params.
2887  *              spi_nor_late_init_params()
2888  */
2889 static int spi_nor_init_params(struct spi_nor *nor)
2890 {
2891         nor->params = devm_kzalloc(nor->dev, sizeof(*nor->params), GFP_KERNEL);
2892         if (!nor->params)
2893                 return -ENOMEM;
2894
2895         spi_nor_info_init_params(nor);
2896
2897         spi_nor_manufacturer_init_params(nor);
2898
2899         if ((nor->info->flags & (SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ)) &&
2900             !(nor->info->flags & SPI_NOR_SKIP_SFDP))
2901                 spi_nor_sfdp_init_params(nor);
2902
2903         spi_nor_post_sfdp_fixups(nor);
2904
2905         spi_nor_late_init_params(nor);
2906
2907         return 0;
2908 }
2909
2910 /**
2911  * spi_nor_quad_enable() - enable Quad I/O if needed.
2912  * @nor:                pointer to a 'struct spi_nor'
2913  *
2914  * Return: 0 on success, -errno otherwise.
2915  */
2916 static int spi_nor_quad_enable(struct spi_nor *nor)
2917 {
2918         if (!nor->params->quad_enable)
2919                 return 0;
2920
2921         if (!(spi_nor_get_protocol_width(nor->read_proto) == 4 ||
2922               spi_nor_get_protocol_width(nor->write_proto) == 4))
2923                 return 0;
2924
2925         return nor->params->quad_enable(nor);
2926 }
2927
2928 /**
2929  * spi_nor_try_unlock_all() - Tries to unlock the entire flash memory array.
2930  * @nor:        pointer to a 'struct spi_nor'.
2931  *
2932  * Some SPI NOR flashes are write protected by default after a power-on reset
2933  * cycle, in order to avoid inadvertent writes during power-up. Backward
2934  * compatibility imposes to unlock the entire flash memory array at power-up
2935  * by default.
2936  *
2937  * Unprotecting the entire flash array will fail for boards which are hardware
2938  * write-protected. Thus any errors are ignored.
2939  */
2940 static void spi_nor_try_unlock_all(struct spi_nor *nor)
2941 {
2942         int ret;
2943
2944         if (!(nor->flags & SNOR_F_HAS_LOCK))
2945                 return;
2946
2947         ret = spi_nor_unlock(&nor->mtd, 0, nor->params->size);
2948         if (ret)
2949                 dev_dbg(nor->dev, "Failed to unlock the entire flash memory array\n");
2950 }
2951
2952 static int spi_nor_init(struct spi_nor *nor)
2953 {
2954         int err;
2955
2956         err = spi_nor_quad_enable(nor);
2957         if (err) {
2958                 dev_dbg(nor->dev, "quad mode not supported\n");
2959                 return err;
2960         }
2961
2962         spi_nor_try_unlock_all(nor);
2963
2964         if (nor->addr_width == 4 && !(nor->flags & SNOR_F_4B_OPCODES)) {
2965                 /*
2966                  * If the RESET# pin isn't hooked up properly, or the system
2967                  * otherwise doesn't perform a reset command in the boot
2968                  * sequence, it's impossible to 100% protect against unexpected
2969                  * reboots (e.g., crashes). Warn the user (or hopefully, system
2970                  * designer) that this is bad.
2971                  */
2972                 WARN_ONCE(nor->flags & SNOR_F_BROKEN_RESET,
2973                           "enabling reset hack; may not recover from unexpected reboots\n");
2974                 nor->params->set_4byte_addr_mode(nor, true);
2975         }
2976
2977         return 0;
2978 }
2979
2980 /* mtd resume handler */
2981 static void spi_nor_resume(struct mtd_info *mtd)
2982 {
2983         struct spi_nor *nor = mtd_to_spi_nor(mtd);
2984         struct device *dev = nor->dev;
2985         int ret;
2986
2987         /* re-initialize the nor chip */
2988         ret = spi_nor_init(nor);
2989         if (ret)
2990                 dev_err(dev, "resume() failed\n");
2991 }
2992
2993 static int spi_nor_get_device(struct mtd_info *mtd)
2994 {
2995         struct mtd_info *master = mtd_get_master(mtd);
2996         struct spi_nor *nor = mtd_to_spi_nor(master);
2997         struct device *dev;
2998
2999         if (nor->spimem)
3000                 dev = nor->spimem->spi->controller->dev.parent;
3001         else
3002                 dev = nor->dev;
3003
3004         if (!try_module_get(dev->driver->owner))
3005                 return -ENODEV;
3006
3007         return 0;
3008 }
3009
3010 static void spi_nor_put_device(struct mtd_info *mtd)
3011 {
3012         struct mtd_info *master = mtd_get_master(mtd);
3013         struct spi_nor *nor = mtd_to_spi_nor(master);
3014         struct device *dev;
3015
3016         if (nor->spimem)
3017                 dev = nor->spimem->spi->controller->dev.parent;
3018         else
3019                 dev = nor->dev;
3020
3021         module_put(dev->driver->owner);
3022 }
3023
3024 void spi_nor_restore(struct spi_nor *nor)
3025 {
3026         /* restore the addressing mode */
3027         if (nor->addr_width == 4 && !(nor->flags & SNOR_F_4B_OPCODES) &&
3028             nor->flags & SNOR_F_BROKEN_RESET)
3029                 nor->params->set_4byte_addr_mode(nor, false);
3030 }
3031 EXPORT_SYMBOL_GPL(spi_nor_restore);
3032
3033 static const struct flash_info *spi_nor_match_id(struct spi_nor *nor,
3034                                                  const char *name)
3035 {
3036         unsigned int i, j;
3037
3038         for (i = 0; i < ARRAY_SIZE(manufacturers); i++) {
3039                 for (j = 0; j < manufacturers[i]->nparts; j++) {
3040                         if (!strcmp(name, manufacturers[i]->parts[j].name)) {
3041                                 nor->manufacturer = manufacturers[i];
3042                                 return &manufacturers[i]->parts[j];
3043                         }
3044                 }
3045         }
3046
3047         return NULL;
3048 }
3049
3050 static int spi_nor_set_addr_width(struct spi_nor *nor)
3051 {
3052         if (nor->addr_width) {
3053                 /* already configured from SFDP */
3054         } else if (nor->info->addr_width) {
3055                 nor->addr_width = nor->info->addr_width;
3056         } else {
3057                 nor->addr_width = 3;
3058         }
3059
3060         if (nor->addr_width == 3 && nor->mtd.size > 0x1000000) {
3061                 /* enable 4-byte addressing if the device exceeds 16MiB */
3062                 nor->addr_width = 4;
3063         }
3064
3065         if (nor->addr_width > SPI_NOR_MAX_ADDR_WIDTH) {
3066                 dev_dbg(nor->dev, "address width is too large: %u\n",
3067                         nor->addr_width);
3068                 return -EINVAL;
3069         }
3070
3071         /* Set 4byte opcodes when possible. */
3072         if (nor->addr_width == 4 && nor->flags & SNOR_F_4B_OPCODES &&
3073             !(nor->flags & SNOR_F_HAS_4BAIT))
3074                 spi_nor_set_4byte_opcodes(nor);
3075
3076         return 0;
3077 }
3078
3079 static void spi_nor_debugfs_init(struct spi_nor *nor,
3080                                  const struct flash_info *info)
3081 {
3082         struct mtd_info *mtd = &nor->mtd;
3083
3084         mtd->dbg.partname = info->name;
3085         mtd->dbg.partid = devm_kasprintf(nor->dev, GFP_KERNEL, "spi-nor:%*phN",
3086                                          info->id_len, info->id);
3087 }
3088
3089 static const struct flash_info *spi_nor_get_flash_info(struct spi_nor *nor,
3090                                                        const char *name)
3091 {
3092         const struct flash_info *info = NULL;
3093
3094         if (name)
3095                 info = spi_nor_match_id(nor, name);
3096         /* Try to auto-detect if chip name wasn't specified or not found */
3097         if (!info)
3098                 info = spi_nor_read_id(nor);
3099         if (IS_ERR_OR_NULL(info))
3100                 return ERR_PTR(-ENOENT);
3101
3102         /*
3103          * If caller has specified name of flash model that can normally be
3104          * detected using JEDEC, let's verify it.
3105          */
3106         if (name && info->id_len) {
3107                 const struct flash_info *jinfo;
3108
3109                 jinfo = spi_nor_read_id(nor);
3110                 if (IS_ERR(jinfo)) {
3111                         return jinfo;
3112                 } else if (jinfo != info) {
3113                         /*
3114                          * JEDEC knows better, so overwrite platform ID. We
3115                          * can't trust partitions any longer, but we'll let
3116                          * mtd apply them anyway, since some partitions may be
3117                          * marked read-only, and we don't want to lose that
3118                          * information, even if it's not 100% accurate.
3119                          */
3120                         dev_warn(nor->dev, "found %s, expected %s\n",
3121                                  jinfo->name, info->name);
3122                         info = jinfo;
3123                 }
3124         }
3125
3126         return info;
3127 }
3128
3129 int spi_nor_scan(struct spi_nor *nor, const char *name,
3130                  const struct spi_nor_hwcaps *hwcaps)
3131 {
3132         const struct flash_info *info;
3133         struct device *dev = nor->dev;
3134         struct mtd_info *mtd = &nor->mtd;
3135         struct device_node *np = spi_nor_get_flash_node(nor);
3136         int ret;
3137         int i;
3138
3139         ret = spi_nor_check(nor);
3140         if (ret)
3141                 return ret;
3142
3143         /* Reset SPI protocol for all commands. */
3144         nor->reg_proto = SNOR_PROTO_1_1_1;
3145         nor->read_proto = SNOR_PROTO_1_1_1;
3146         nor->write_proto = SNOR_PROTO_1_1_1;
3147
3148         /*
3149          * We need the bounce buffer early to read/write registers when going
3150          * through the spi-mem layer (buffers have to be DMA-able).
3151          * For spi-mem drivers, we'll reallocate a new buffer if
3152          * nor->page_size turns out to be greater than PAGE_SIZE (which
3153          * shouldn't happen before long since NOR pages are usually less
3154          * than 1KB) after spi_nor_scan() returns.
3155          */
3156         nor->bouncebuf_size = PAGE_SIZE;
3157         nor->bouncebuf = devm_kmalloc(dev, nor->bouncebuf_size,
3158                                       GFP_KERNEL);
3159         if (!nor->bouncebuf)
3160                 return -ENOMEM;
3161
3162         info = spi_nor_get_flash_info(nor, name);
3163         if (IS_ERR(info))
3164                 return PTR_ERR(info);
3165
3166         nor->info = info;
3167
3168         spi_nor_debugfs_init(nor, info);
3169
3170         mutex_init(&nor->lock);
3171
3172         /*
3173          * Make sure the XSR_RDY flag is set before calling
3174          * spi_nor_wait_till_ready(). Xilinx S3AN share MFR
3175          * with Atmel SPI NOR.
3176          */
3177         if (info->flags & SPI_NOR_XSR_RDY)
3178                 nor->flags |=  SNOR_F_READY_XSR_RDY;
3179
3180         if (info->flags & SPI_NOR_HAS_LOCK)
3181                 nor->flags |= SNOR_F_HAS_LOCK;
3182
3183         mtd->_write = spi_nor_write;
3184
3185         /* Init flash parameters based on flash_info struct and SFDP */
3186         ret = spi_nor_init_params(nor);
3187         if (ret)
3188                 return ret;
3189
3190         if (!mtd->name)
3191                 mtd->name = dev_name(dev);
3192         mtd->priv = nor;
3193         mtd->type = MTD_NORFLASH;
3194         mtd->writesize = 1;
3195         mtd->flags = MTD_CAP_NORFLASH;
3196         mtd->size = nor->params->size;
3197         mtd->_erase = spi_nor_erase;
3198         mtd->_read = spi_nor_read;
3199         mtd->_resume = spi_nor_resume;
3200         mtd->_get_device = spi_nor_get_device;
3201         mtd->_put_device = spi_nor_put_device;
3202
3203         if (nor->params->locking_ops) {
3204                 mtd->_lock = spi_nor_lock;
3205                 mtd->_unlock = spi_nor_unlock;
3206                 mtd->_is_locked = spi_nor_is_locked;
3207         }
3208
3209         if (info->flags & USE_FSR)
3210                 nor->flags |= SNOR_F_USE_FSR;
3211         if (info->flags & SPI_NOR_HAS_TB) {
3212                 nor->flags |= SNOR_F_HAS_SR_TB;
3213                 if (info->flags & SPI_NOR_TB_SR_BIT6)
3214                         nor->flags |= SNOR_F_HAS_SR_TB_BIT6;
3215         }
3216
3217         if (info->flags & NO_CHIP_ERASE)
3218                 nor->flags |= SNOR_F_NO_OP_CHIP_ERASE;
3219         if (info->flags & USE_CLSR)
3220                 nor->flags |= SNOR_F_USE_CLSR;
3221
3222         if (info->flags & SPI_NOR_4BIT_BP) {
3223                 nor->flags |= SNOR_F_HAS_4BIT_BP;
3224                 if (info->flags & SPI_NOR_BP3_SR_BIT6)
3225                         nor->flags |= SNOR_F_HAS_SR_BP3_BIT6;
3226         }
3227
3228         if (info->flags & SPI_NOR_NO_ERASE)
3229                 mtd->flags |= MTD_NO_ERASE;
3230
3231         mtd->dev.parent = dev;
3232         nor->page_size = nor->params->page_size;
3233         mtd->writebufsize = nor->page_size;
3234
3235         if (of_property_read_bool(np, "broken-flash-reset"))
3236                 nor->flags |= SNOR_F_BROKEN_RESET;
3237
3238         /*
3239          * Configure the SPI memory:
3240          * - select op codes for (Fast) Read, Page Program and Sector Erase.
3241          * - set the number of dummy cycles (mode cycles + wait states).
3242          * - set the SPI protocols for register and memory accesses.
3243          */
3244         ret = spi_nor_setup(nor, hwcaps);
3245         if (ret)
3246                 return ret;
3247
3248         if (info->flags & SPI_NOR_4B_OPCODES)
3249                 nor->flags |= SNOR_F_4B_OPCODES;
3250
3251         ret = spi_nor_set_addr_width(nor);
3252         if (ret)
3253                 return ret;
3254
3255         /* Send all the required SPI flash commands to initialize device */
3256         ret = spi_nor_init(nor);
3257         if (ret)
3258                 return ret;
3259
3260         dev_info(dev, "%s (%lld Kbytes)\n", info->name,
3261                         (long long)mtd->size >> 10);
3262
3263         dev_dbg(dev,
3264                 "mtd .name = %s, .size = 0x%llx (%lldMiB), "
3265                 ".erasesize = 0x%.8x (%uKiB) .numeraseregions = %d\n",
3266                 mtd->name, (long long)mtd->size, (long long)(mtd->size >> 20),
3267                 mtd->erasesize, mtd->erasesize / 1024, mtd->numeraseregions);
3268
3269         if (mtd->numeraseregions)
3270                 for (i = 0; i < mtd->numeraseregions; i++)
3271                         dev_dbg(dev,
3272                                 "mtd.eraseregions[%d] = { .offset = 0x%llx, "
3273                                 ".erasesize = 0x%.8x (%uKiB), "
3274                                 ".numblocks = %d }\n",
3275                                 i, (long long)mtd->eraseregions[i].offset,
3276                                 mtd->eraseregions[i].erasesize,
3277                                 mtd->eraseregions[i].erasesize / 1024,
3278                                 mtd->eraseregions[i].numblocks);
3279         return 0;
3280 }
3281 EXPORT_SYMBOL_GPL(spi_nor_scan);
3282
3283 static int spi_nor_create_read_dirmap(struct spi_nor *nor)
3284 {
3285         struct spi_mem_dirmap_info info = {
3286                 .op_tmpl = SPI_MEM_OP(SPI_MEM_OP_CMD(nor->read_opcode, 1),
3287                                       SPI_MEM_OP_ADDR(nor->addr_width, 0, 1),
3288                                       SPI_MEM_OP_DUMMY(nor->read_dummy, 1),
3289                                       SPI_MEM_OP_DATA_IN(0, NULL, 1)),
3290                 .offset = 0,
3291                 .length = nor->mtd.size,
3292         };
3293         struct spi_mem_op *op = &info.op_tmpl;
3294
3295         /* get transfer protocols. */
3296         op->cmd.buswidth = spi_nor_get_protocol_inst_nbits(nor->read_proto);
3297         op->addr.buswidth = spi_nor_get_protocol_addr_nbits(nor->read_proto);
3298         op->dummy.buswidth = op->addr.buswidth;
3299         op->data.buswidth = spi_nor_get_protocol_data_nbits(nor->read_proto);
3300
3301         /* convert the dummy cycles to the number of bytes */
3302         op->dummy.nbytes = (nor->read_dummy * op->dummy.buswidth) / 8;
3303
3304         nor->dirmap.rdesc = devm_spi_mem_dirmap_create(nor->dev, nor->spimem,
3305                                                        &info);
3306         return PTR_ERR_OR_ZERO(nor->dirmap.rdesc);
3307 }
3308
3309 static int spi_nor_create_write_dirmap(struct spi_nor *nor)
3310 {
3311         struct spi_mem_dirmap_info info = {
3312                 .op_tmpl = SPI_MEM_OP(SPI_MEM_OP_CMD(nor->program_opcode, 1),
3313                                       SPI_MEM_OP_ADDR(nor->addr_width, 0, 1),
3314                                       SPI_MEM_OP_NO_DUMMY,
3315                                       SPI_MEM_OP_DATA_OUT(0, NULL, 1)),
3316                 .offset = 0,
3317                 .length = nor->mtd.size,
3318         };
3319         struct spi_mem_op *op = &info.op_tmpl;
3320
3321         /* get transfer protocols. */
3322         op->cmd.buswidth = spi_nor_get_protocol_inst_nbits(nor->write_proto);
3323         op->addr.buswidth = spi_nor_get_protocol_addr_nbits(nor->write_proto);
3324         op->dummy.buswidth = op->addr.buswidth;
3325         op->data.buswidth = spi_nor_get_protocol_data_nbits(nor->write_proto);
3326
3327         if (nor->program_opcode == SPINOR_OP_AAI_WP && nor->sst_write_second)
3328                 op->addr.nbytes = 0;
3329
3330         nor->dirmap.wdesc = devm_spi_mem_dirmap_create(nor->dev, nor->spimem,
3331                                                        &info);
3332         return PTR_ERR_OR_ZERO(nor->dirmap.wdesc);
3333 }
3334
3335 static int spi_nor_probe(struct spi_mem *spimem)
3336 {
3337         struct spi_device *spi = spimem->spi;
3338         struct flash_platform_data *data = dev_get_platdata(&spi->dev);
3339         struct spi_nor *nor;
3340         /*
3341          * Enable all caps by default. The core will mask them after
3342          * checking what's really supported using spi_mem_supports_op().
3343          */
3344         const struct spi_nor_hwcaps hwcaps = { .mask = SNOR_HWCAPS_ALL };
3345         char *flash_name;
3346         int ret;
3347
3348         nor = devm_kzalloc(&spi->dev, sizeof(*nor), GFP_KERNEL);
3349         if (!nor)
3350                 return -ENOMEM;
3351
3352         nor->spimem = spimem;
3353         nor->dev = &spi->dev;
3354         spi_nor_set_flash_node(nor, spi->dev.of_node);
3355
3356         spi_mem_set_drvdata(spimem, nor);
3357
3358         if (data && data->name)
3359                 nor->mtd.name = data->name;
3360
3361         if (!nor->mtd.name)
3362                 nor->mtd.name = spi_mem_get_name(spimem);
3363
3364         /*
3365          * For some (historical?) reason many platforms provide two different
3366          * names in flash_platform_data: "name" and "type". Quite often name is
3367          * set to "m25p80" and then "type" provides a real chip name.
3368          * If that's the case, respect "type" and ignore a "name".
3369          */
3370         if (data && data->type)
3371                 flash_name = data->type;
3372         else if (!strcmp(spi->modalias, "spi-nor"))
3373                 flash_name = NULL; /* auto-detect */
3374         else
3375                 flash_name = spi->modalias;
3376
3377         ret = spi_nor_scan(nor, flash_name, &hwcaps);
3378         if (ret)
3379                 return ret;
3380
3381         /*
3382          * None of the existing parts have > 512B pages, but let's play safe
3383          * and add this logic so that if anyone ever adds support for such
3384          * a NOR we don't end up with buffer overflows.
3385          */
3386         if (nor->page_size > PAGE_SIZE) {
3387                 nor->bouncebuf_size = nor->page_size;
3388                 devm_kfree(nor->dev, nor->bouncebuf);
3389                 nor->bouncebuf = devm_kmalloc(nor->dev,
3390                                               nor->bouncebuf_size,
3391                                               GFP_KERNEL);
3392                 if (!nor->bouncebuf)
3393                         return -ENOMEM;
3394         }
3395
3396         ret = spi_nor_create_read_dirmap(nor);
3397         if (ret)
3398                 return ret;
3399
3400         ret = spi_nor_create_write_dirmap(nor);
3401         if (ret)
3402                 return ret;
3403
3404         return mtd_device_register(&nor->mtd, data ? data->parts : NULL,
3405                                    data ? data->nr_parts : 0);
3406 }
3407
3408 static int spi_nor_remove(struct spi_mem *spimem)
3409 {
3410         struct spi_nor *nor = spi_mem_get_drvdata(spimem);
3411
3412         spi_nor_restore(nor);
3413
3414         /* Clean up MTD stuff. */
3415         return mtd_device_unregister(&nor->mtd);
3416 }
3417
3418 static void spi_nor_shutdown(struct spi_mem *spimem)
3419 {
3420         struct spi_nor *nor = spi_mem_get_drvdata(spimem);
3421
3422         spi_nor_restore(nor);
3423 }
3424
3425 /*
3426  * Do NOT add to this array without reading the following:
3427  *
3428  * Historically, many flash devices are bound to this driver by their name. But
3429  * since most of these flash are compatible to some extent, and their
3430  * differences can often be differentiated by the JEDEC read-ID command, we
3431  * encourage new users to add support to the spi-nor library, and simply bind
3432  * against a generic string here (e.g., "jedec,spi-nor").
3433  *
3434  * Many flash names are kept here in this list (as well as in spi-nor.c) to
3435  * keep them available as module aliases for existing platforms.
3436  */
3437 static const struct spi_device_id spi_nor_dev_ids[] = {
3438         /*
3439          * Allow non-DT platform devices to bind to the "spi-nor" modalias, and
3440          * hack around the fact that the SPI core does not provide uevent
3441          * matching for .of_match_table
3442          */
3443         {"spi-nor"},
3444
3445         /*
3446          * Entries not used in DTs that should be safe to drop after replacing
3447          * them with "spi-nor" in platform data.
3448          */
3449         {"s25sl064a"},  {"w25x16"},     {"m25p10"},     {"m25px64"},
3450
3451         /*
3452          * Entries that were used in DTs without "jedec,spi-nor" fallback and
3453          * should be kept for backward compatibility.
3454          */
3455         {"at25df321a"}, {"at25df641"},  {"at26df081a"},
3456         {"mx25l4005a"}, {"mx25l1606e"}, {"mx25l6405d"}, {"mx25l12805d"},
3457         {"mx25l25635e"},{"mx66l51235l"},
3458         {"n25q064"},    {"n25q128a11"}, {"n25q128a13"}, {"n25q512a"},
3459         {"s25fl256s1"}, {"s25fl512s"},  {"s25sl12801"}, {"s25fl008k"},
3460         {"s25fl064k"},
3461         {"sst25vf040b"},{"sst25vf016b"},{"sst25vf032b"},{"sst25wf040"},
3462         {"m25p40"},     {"m25p80"},     {"m25p16"},     {"m25p32"},
3463         {"m25p64"},     {"m25p128"},
3464         {"w25x80"},     {"w25x32"},     {"w25q32"},     {"w25q32dw"},
3465         {"w25q80bl"},   {"w25q128"},    {"w25q256"},
3466
3467         /* Flashes that can't be detected using JEDEC */
3468         {"m25p05-nonjedec"},    {"m25p10-nonjedec"},    {"m25p20-nonjedec"},
3469         {"m25p40-nonjedec"},    {"m25p80-nonjedec"},    {"m25p16-nonjedec"},
3470         {"m25p32-nonjedec"},    {"m25p64-nonjedec"},    {"m25p128-nonjedec"},
3471
3472         /* Everspin MRAMs (non-JEDEC) */
3473         { "mr25h128" }, /* 128 Kib, 40 MHz */
3474         { "mr25h256" }, /* 256 Kib, 40 MHz */
3475         { "mr25h10" },  /*   1 Mib, 40 MHz */
3476         { "mr25h40" },  /*   4 Mib, 40 MHz */
3477
3478         { },
3479 };
3480 MODULE_DEVICE_TABLE(spi, spi_nor_dev_ids);
3481
3482 static const struct of_device_id spi_nor_of_table[] = {
3483         /*
3484          * Generic compatibility for SPI NOR that can be identified by the
3485          * JEDEC READ ID opcode (0x9F). Use this, if possible.
3486          */
3487         { .compatible = "jedec,spi-nor" },
3488         { /* sentinel */ },
3489 };
3490 MODULE_DEVICE_TABLE(of, spi_nor_of_table);
3491
3492 /*
3493  * REVISIT: many of these chips have deep power-down modes, which
3494  * should clearly be entered on suspend() to minimize power use.
3495  * And also when they're otherwise idle...
3496  */
3497 static struct spi_mem_driver spi_nor_driver = {
3498         .spidrv = {
3499                 .driver = {
3500                         .name = "spi-nor",
3501                         .of_match_table = spi_nor_of_table,
3502                 },
3503                 .id_table = spi_nor_dev_ids,
3504         },
3505         .probe = spi_nor_probe,
3506         .remove = spi_nor_remove,
3507         .shutdown = spi_nor_shutdown,
3508 };
3509 module_spi_mem_driver(spi_nor_driver);
3510
3511 MODULE_LICENSE("GPL v2");
3512 MODULE_AUTHOR("Huang Shijie <shijie8@gmail.com>");
3513 MODULE_AUTHOR("Mike Lavender");
3514 MODULE_DESCRIPTION("framework for SPI NOR");