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