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  */
spi_nor_get_cmd_ext(const struct spi_nor * nor,const struct spi_mem_op * op)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  */
spi_nor_spimem_setup_op(const struct spi_nor * nor,struct spi_mem_op * op,const enum spi_nor_protocol proto)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  */
spi_nor_spimem_bounce(struct spi_nor * nor,struct spi_mem_op * op)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  */
spi_nor_spimem_exec_op(struct spi_nor * nor,struct spi_mem_op * op)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 
spi_nor_controller_ops_read_reg(struct spi_nor * nor,u8 opcode,u8 * buf,size_t len)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 
spi_nor_controller_ops_write_reg(struct spi_nor * nor,u8 opcode,const u8 * buf,size_t len)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 
spi_nor_controller_ops_erase(struct spi_nor * nor,loff_t offs)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  */
spi_nor_spimem_read_data(struct spi_nor * nor,loff_t from,size_t len,u8 * buf)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  */
spi_nor_read_data(struct spi_nor * nor,loff_t from,size_t len,u8 * buf)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  */
spi_nor_spimem_write_data(struct spi_nor * nor,loff_t to,size_t len,const u8 * buf)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  */
spi_nor_write_data(struct spi_nor * nor,loff_t to,size_t len,const u8 * buf)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  */
spi_nor_read_any_reg(struct spi_nor * nor,struct spi_mem_op * op,enum spi_nor_protocol proto)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  */
spi_nor_write_any_volatile_reg(struct spi_nor * nor,struct spi_mem_op * op,enum spi_nor_protocol proto)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  */
spi_nor_write_enable(struct spi_nor * nor)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  */
spi_nor_write_disable(struct spi_nor * nor)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  */
spi_nor_read_id(struct spi_nor * nor,u8 naddr,u8 ndummy,u8 * id,enum spi_nor_protocol proto)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  */
spi_nor_read_sr(struct spi_nor * nor,u8 * sr)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  */
spi_nor_read_cr(struct spi_nor * nor,u8 * cr)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  */
spi_nor_set_4byte_addr_mode(struct spi_nor * nor,bool enable)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  */
spansion_set_4byte_addr_mode(struct spi_nor * nor,bool enable)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  */
spi_nor_sr_ready(struct spi_nor * nor)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  */
spi_nor_ready(struct spi_nor * nor)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  */
spi_nor_wait_till_ready_with_timeout(struct spi_nor * nor,unsigned long timeout_jiffies)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  */
spi_nor_wait_till_ready(struct spi_nor * nor)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  */
spi_nor_global_block_unlock(struct spi_nor * nor)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  */
spi_nor_write_sr(struct spi_nor * nor,const u8 * sr,size_t len)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  */
spi_nor_write_sr1_and_check(struct spi_nor * nor,u8 sr1)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  */
spi_nor_write_16bit_sr_and_check(struct spi_nor * nor,u8 sr1)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  */
spi_nor_write_16bit_cr_and_check(struct spi_nor * nor,u8 cr)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  */
spi_nor_write_sr_and_check(struct spi_nor * nor,u8 sr1)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  */
spi_nor_write_sr2(struct spi_nor * nor,const u8 * sr2)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  */
spi_nor_read_sr2(struct spi_nor * nor,u8 * sr2)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  */
spi_nor_erase_chip(struct spi_nor * nor)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 
spi_nor_convert_opcode(u8 opcode,const u8 table[][2],size_t size)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 
spi_nor_convert_3to4_read(u8 opcode)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 
spi_nor_convert_3to4_program(u8 opcode)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 
spi_nor_convert_3to4_erase(u8 opcode)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 
spi_nor_has_uniform_erase(const struct spi_nor * nor)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 
spi_nor_set_4byte_opcodes(struct spi_nor * nor)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 
spi_nor_lock_and_prep(struct spi_nor * nor)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 
spi_nor_unlock_and_unprep(struct spi_nor * nor)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 
spi_nor_convert_addr(struct spi_nor * nor,loff_t addr)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  */
spi_nor_erase_sector(struct spi_nor * nor,u32 addr)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  */
spi_nor_div_by_erase_size(const struct spi_nor_erase_type * erase,u64 dividend,u32 * remainder)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 *
spi_nor_find_best_erase_type(const struct spi_nor_erase_map * map,const struct spi_nor_erase_region * region,u64 addr,u32 len)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 
spi_nor_region_is_last(const struct spi_nor_erase_region * region)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 
spi_nor_region_end(const struct spi_nor_erase_region * region)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 *
spi_nor_region_next(struct spi_nor_erase_region * 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 *
spi_nor_find_erase_region(const struct spi_nor_erase_map * map,u64 addr)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 *
spi_nor_init_erase_cmd(const struct spi_nor_erase_region * region,const struct spi_nor_erase_type * erase)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  */
spi_nor_destroy_erase_cmd_list(struct list_head * erase_list)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  */
spi_nor_init_erase_cmd_list(struct spi_nor * nor,struct list_head * erase_list,u64 addr,u32 len)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  */
spi_nor_erase_multi_sectors(struct spi_nor * nor,u64 addr,u32 len)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  */
spi_nor_erase(struct mtd_info * mtd,struct erase_info * instr)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  */
spi_nor_sr1_bit6_quad_enable(struct spi_nor * nor)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  */
spi_nor_sr2_bit1_quad_enable(struct spi_nor * nor)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  */
spi_nor_sr2_bit7_quad_enable(struct spi_nor * nor)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 
spi_nor_match_id(struct spi_nor * nor,const u8 * id)1638 static const struct flash_info *spi_nor_match_id(struct spi_nor *nor,
1639 						 const u8 *id)
1640 {
1641 	const struct flash_info *part;
1642 	unsigned int i, j;
1643 
1644 	for (i = 0; i < ARRAY_SIZE(manufacturers); i++) {
1645 		for (j = 0; j < manufacturers[i]->nparts; j++) {
1646 			part = &manufacturers[i]->parts[j];
1647 			if (part->id_len &&
1648 			    !memcmp(part->id, id, part->id_len)) {
1649 				nor->manufacturer = manufacturers[i];
1650 				return part;
1651 			}
1652 		}
1653 	}
1654 
1655 	return NULL;
1656 }
1657 
spi_nor_detect(struct spi_nor * nor)1658 static const struct flash_info *spi_nor_detect(struct spi_nor *nor)
1659 {
1660 	const struct flash_info *info;
1661 	u8 *id = nor->bouncebuf;
1662 	int ret;
1663 
1664 	ret = spi_nor_read_id(nor, 0, 0, id, nor->reg_proto);
1665 	if (ret) {
1666 		dev_dbg(nor->dev, "error %d reading JEDEC ID\n", ret);
1667 		return ERR_PTR(ret);
1668 	}
1669 
1670 	info = spi_nor_match_id(nor, id);
1671 	if (!info) {
1672 		dev_err(nor->dev, "unrecognized JEDEC id bytes: %*ph\n",
1673 			SPI_NOR_MAX_ID_LEN, id);
1674 		return ERR_PTR(-ENODEV);
1675 	}
1676 	return info;
1677 }
1678 
spi_nor_read(struct mtd_info * mtd,loff_t from,size_t len,size_t * retlen,u_char * buf)1679 static int spi_nor_read(struct mtd_info *mtd, loff_t from, size_t len,
1680 			size_t *retlen, u_char *buf)
1681 {
1682 	struct spi_nor *nor = mtd_to_spi_nor(mtd);
1683 	ssize_t ret;
1684 
1685 	dev_dbg(nor->dev, "from 0x%08x, len %zd\n", (u32)from, len);
1686 
1687 	ret = spi_nor_lock_and_prep(nor);
1688 	if (ret)
1689 		return ret;
1690 
1691 	while (len) {
1692 		loff_t addr = from;
1693 
1694 		addr = spi_nor_convert_addr(nor, addr);
1695 
1696 		ret = spi_nor_read_data(nor, addr, len, buf);
1697 		if (ret == 0) {
1698 			/* We shouldn't see 0-length reads */
1699 			ret = -EIO;
1700 			goto read_err;
1701 		}
1702 		if (ret < 0)
1703 			goto read_err;
1704 
1705 		WARN_ON(ret > len);
1706 		*retlen += ret;
1707 		buf += ret;
1708 		from += ret;
1709 		len -= ret;
1710 	}
1711 	ret = 0;
1712 
1713 read_err:
1714 	spi_nor_unlock_and_unprep(nor);
1715 	return ret;
1716 }
1717 
1718 /*
1719  * Write an address range to the nor chip.  Data must be written in
1720  * FLASH_PAGESIZE chunks.  The address range may be any size provided
1721  * it is within the physical boundaries.
1722  */
spi_nor_write(struct mtd_info * mtd,loff_t to,size_t len,size_t * retlen,const u_char * buf)1723 static int spi_nor_write(struct mtd_info *mtd, loff_t to, size_t len,
1724 	size_t *retlen, const u_char *buf)
1725 {
1726 	struct spi_nor *nor = mtd_to_spi_nor(mtd);
1727 	size_t page_offset, page_remain, i;
1728 	ssize_t ret;
1729 	u32 page_size = nor->params->page_size;
1730 
1731 	dev_dbg(nor->dev, "to 0x%08x, len %zd\n", (u32)to, len);
1732 
1733 	ret = spi_nor_lock_and_prep(nor);
1734 	if (ret)
1735 		return ret;
1736 
1737 	for (i = 0; i < len; ) {
1738 		ssize_t written;
1739 		loff_t addr = to + i;
1740 
1741 		/*
1742 		 * If page_size is a power of two, the offset can be quickly
1743 		 * calculated with an AND operation. On the other cases we
1744 		 * need to do a modulus operation (more expensive).
1745 		 */
1746 		if (is_power_of_2(page_size)) {
1747 			page_offset = addr & (page_size - 1);
1748 		} else {
1749 			uint64_t aux = addr;
1750 
1751 			page_offset = do_div(aux, page_size);
1752 		}
1753 		/* the size of data remaining on the first page */
1754 		page_remain = min_t(size_t, page_size - page_offset, len - i);
1755 
1756 		addr = spi_nor_convert_addr(nor, addr);
1757 
1758 		ret = spi_nor_write_enable(nor);
1759 		if (ret)
1760 			goto write_err;
1761 
1762 		ret = spi_nor_write_data(nor, addr, page_remain, buf + i);
1763 		if (ret < 0)
1764 			goto write_err;
1765 		written = ret;
1766 
1767 		ret = spi_nor_wait_till_ready(nor);
1768 		if (ret)
1769 			goto write_err;
1770 		*retlen += written;
1771 		i += written;
1772 	}
1773 
1774 write_err:
1775 	spi_nor_unlock_and_unprep(nor);
1776 	return ret;
1777 }
1778 
spi_nor_check(struct spi_nor * nor)1779 static int spi_nor_check(struct spi_nor *nor)
1780 {
1781 	if (!nor->dev ||
1782 	    (!nor->spimem && !nor->controller_ops) ||
1783 	    (!nor->spimem && nor->controller_ops &&
1784 	    (!nor->controller_ops->read ||
1785 	     !nor->controller_ops->write ||
1786 	     !nor->controller_ops->read_reg ||
1787 	     !nor->controller_ops->write_reg))) {
1788 		pr_err("spi-nor: please fill all the necessary fields!\n");
1789 		return -EINVAL;
1790 	}
1791 
1792 	if (nor->spimem && nor->controller_ops) {
1793 		dev_err(nor->dev, "nor->spimem and nor->controller_ops are mutually exclusive, please set just one of them.\n");
1794 		return -EINVAL;
1795 	}
1796 
1797 	return 0;
1798 }
1799 
1800 void
spi_nor_set_read_settings(struct spi_nor_read_command * read,u8 num_mode_clocks,u8 num_wait_states,u8 opcode,enum spi_nor_protocol proto)1801 spi_nor_set_read_settings(struct spi_nor_read_command *read,
1802 			  u8 num_mode_clocks,
1803 			  u8 num_wait_states,
1804 			  u8 opcode,
1805 			  enum spi_nor_protocol proto)
1806 {
1807 	read->num_mode_clocks = num_mode_clocks;
1808 	read->num_wait_states = num_wait_states;
1809 	read->opcode = opcode;
1810 	read->proto = proto;
1811 }
1812 
spi_nor_set_pp_settings(struct spi_nor_pp_command * pp,u8 opcode,enum spi_nor_protocol proto)1813 void spi_nor_set_pp_settings(struct spi_nor_pp_command *pp, u8 opcode,
1814 			     enum spi_nor_protocol proto)
1815 {
1816 	pp->opcode = opcode;
1817 	pp->proto = proto;
1818 }
1819 
spi_nor_hwcaps2cmd(u32 hwcaps,const int table[][2],size_t size)1820 static int spi_nor_hwcaps2cmd(u32 hwcaps, const int table[][2], size_t size)
1821 {
1822 	size_t i;
1823 
1824 	for (i = 0; i < size; i++)
1825 		if (table[i][0] == (int)hwcaps)
1826 			return table[i][1];
1827 
1828 	return -EINVAL;
1829 }
1830 
spi_nor_hwcaps_read2cmd(u32 hwcaps)1831 int spi_nor_hwcaps_read2cmd(u32 hwcaps)
1832 {
1833 	static const int hwcaps_read2cmd[][2] = {
1834 		{ SNOR_HWCAPS_READ,		SNOR_CMD_READ },
1835 		{ SNOR_HWCAPS_READ_FAST,	SNOR_CMD_READ_FAST },
1836 		{ SNOR_HWCAPS_READ_1_1_1_DTR,	SNOR_CMD_READ_1_1_1_DTR },
1837 		{ SNOR_HWCAPS_READ_1_1_2,	SNOR_CMD_READ_1_1_2 },
1838 		{ SNOR_HWCAPS_READ_1_2_2,	SNOR_CMD_READ_1_2_2 },
1839 		{ SNOR_HWCAPS_READ_2_2_2,	SNOR_CMD_READ_2_2_2 },
1840 		{ SNOR_HWCAPS_READ_1_2_2_DTR,	SNOR_CMD_READ_1_2_2_DTR },
1841 		{ SNOR_HWCAPS_READ_1_1_4,	SNOR_CMD_READ_1_1_4 },
1842 		{ SNOR_HWCAPS_READ_1_4_4,	SNOR_CMD_READ_1_4_4 },
1843 		{ SNOR_HWCAPS_READ_4_4_4,	SNOR_CMD_READ_4_4_4 },
1844 		{ SNOR_HWCAPS_READ_1_4_4_DTR,	SNOR_CMD_READ_1_4_4_DTR },
1845 		{ SNOR_HWCAPS_READ_1_1_8,	SNOR_CMD_READ_1_1_8 },
1846 		{ SNOR_HWCAPS_READ_1_8_8,	SNOR_CMD_READ_1_8_8 },
1847 		{ SNOR_HWCAPS_READ_8_8_8,	SNOR_CMD_READ_8_8_8 },
1848 		{ SNOR_HWCAPS_READ_1_8_8_DTR,	SNOR_CMD_READ_1_8_8_DTR },
1849 		{ SNOR_HWCAPS_READ_8_8_8_DTR,	SNOR_CMD_READ_8_8_8_DTR },
1850 	};
1851 
1852 	return spi_nor_hwcaps2cmd(hwcaps, hwcaps_read2cmd,
1853 				  ARRAY_SIZE(hwcaps_read2cmd));
1854 }
1855 
spi_nor_hwcaps_pp2cmd(u32 hwcaps)1856 int spi_nor_hwcaps_pp2cmd(u32 hwcaps)
1857 {
1858 	static const int hwcaps_pp2cmd[][2] = {
1859 		{ SNOR_HWCAPS_PP,		SNOR_CMD_PP },
1860 		{ SNOR_HWCAPS_PP_1_1_4,		SNOR_CMD_PP_1_1_4 },
1861 		{ SNOR_HWCAPS_PP_1_4_4,		SNOR_CMD_PP_1_4_4 },
1862 		{ SNOR_HWCAPS_PP_4_4_4,		SNOR_CMD_PP_4_4_4 },
1863 		{ SNOR_HWCAPS_PP_1_1_8,		SNOR_CMD_PP_1_1_8 },
1864 		{ SNOR_HWCAPS_PP_1_8_8,		SNOR_CMD_PP_1_8_8 },
1865 		{ SNOR_HWCAPS_PP_8_8_8,		SNOR_CMD_PP_8_8_8 },
1866 		{ SNOR_HWCAPS_PP_8_8_8_DTR,	SNOR_CMD_PP_8_8_8_DTR },
1867 	};
1868 
1869 	return spi_nor_hwcaps2cmd(hwcaps, hwcaps_pp2cmd,
1870 				  ARRAY_SIZE(hwcaps_pp2cmd));
1871 }
1872 
1873 /**
1874  * spi_nor_spimem_check_op - check if the operation is supported
1875  *                           by controller
1876  *@nor:        pointer to a 'struct spi_nor'
1877  *@op:         pointer to op template to be checked
1878  *
1879  * Returns 0 if operation is supported, -EOPNOTSUPP otherwise.
1880  */
spi_nor_spimem_check_op(struct spi_nor * nor,struct spi_mem_op * op)1881 static int spi_nor_spimem_check_op(struct spi_nor *nor,
1882 				   struct spi_mem_op *op)
1883 {
1884 	/*
1885 	 * First test with 4 address bytes. The opcode itself might
1886 	 * be a 3B addressing opcode but we don't care, because
1887 	 * SPI controller implementation should not check the opcode,
1888 	 * but just the sequence.
1889 	 */
1890 	op->addr.nbytes = 4;
1891 	if (!spi_mem_supports_op(nor->spimem, op)) {
1892 		if (nor->params->size > SZ_16M)
1893 			return -EOPNOTSUPP;
1894 
1895 		/* If flash size <= 16MB, 3 address bytes are sufficient */
1896 		op->addr.nbytes = 3;
1897 		if (!spi_mem_supports_op(nor->spimem, op))
1898 			return -EOPNOTSUPP;
1899 	}
1900 
1901 	return 0;
1902 }
1903 
1904 /**
1905  * spi_nor_spimem_check_readop - check if the read op is supported
1906  *                               by controller
1907  *@nor:         pointer to a 'struct spi_nor'
1908  *@read:        pointer to op template to be checked
1909  *
1910  * Returns 0 if operation is supported, -EOPNOTSUPP otherwise.
1911  */
spi_nor_spimem_check_readop(struct spi_nor * nor,const struct spi_nor_read_command * read)1912 static int spi_nor_spimem_check_readop(struct spi_nor *nor,
1913 				       const struct spi_nor_read_command *read)
1914 {
1915 	struct spi_mem_op op = SPI_NOR_READ_OP(read->opcode);
1916 
1917 	spi_nor_spimem_setup_op(nor, &op, read->proto);
1918 
1919 	/* convert the dummy cycles to the number of bytes */
1920 	op.dummy.nbytes = (read->num_mode_clocks + read->num_wait_states) *
1921 			  op.dummy.buswidth / 8;
1922 	if (spi_nor_protocol_is_dtr(nor->read_proto))
1923 		op.dummy.nbytes *= 2;
1924 
1925 	return spi_nor_spimem_check_op(nor, &op);
1926 }
1927 
1928 /**
1929  * spi_nor_spimem_check_pp - check if the page program op is supported
1930  *                           by controller
1931  *@nor:         pointer to a 'struct spi_nor'
1932  *@pp:          pointer to op template to be checked
1933  *
1934  * Returns 0 if operation is supported, -EOPNOTSUPP otherwise.
1935  */
spi_nor_spimem_check_pp(struct spi_nor * nor,const struct spi_nor_pp_command * pp)1936 static int spi_nor_spimem_check_pp(struct spi_nor *nor,
1937 				   const struct spi_nor_pp_command *pp)
1938 {
1939 	struct spi_mem_op op = SPI_NOR_PP_OP(pp->opcode);
1940 
1941 	spi_nor_spimem_setup_op(nor, &op, pp->proto);
1942 
1943 	return spi_nor_spimem_check_op(nor, &op);
1944 }
1945 
1946 /**
1947  * spi_nor_spimem_adjust_hwcaps - Find optimal Read/Write protocol
1948  *                                based on SPI controller capabilities
1949  * @nor:        pointer to a 'struct spi_nor'
1950  * @hwcaps:     pointer to resulting capabilities after adjusting
1951  *              according to controller and flash's capability
1952  */
1953 static void
spi_nor_spimem_adjust_hwcaps(struct spi_nor * nor,u32 * hwcaps)1954 spi_nor_spimem_adjust_hwcaps(struct spi_nor *nor, u32 *hwcaps)
1955 {
1956 	struct spi_nor_flash_parameter *params = nor->params;
1957 	unsigned int cap;
1958 
1959 	/* X-X-X modes are not supported yet, mask them all. */
1960 	*hwcaps &= ~SNOR_HWCAPS_X_X_X;
1961 
1962 	/*
1963 	 * If the reset line is broken, we do not want to enter a stateful
1964 	 * mode.
1965 	 */
1966 	if (nor->flags & SNOR_F_BROKEN_RESET)
1967 		*hwcaps &= ~(SNOR_HWCAPS_X_X_X | SNOR_HWCAPS_X_X_X_DTR);
1968 
1969 	for (cap = 0; cap < sizeof(*hwcaps) * BITS_PER_BYTE; cap++) {
1970 		int rdidx, ppidx;
1971 
1972 		if (!(*hwcaps & BIT(cap)))
1973 			continue;
1974 
1975 		rdidx = spi_nor_hwcaps_read2cmd(BIT(cap));
1976 		if (rdidx >= 0 &&
1977 		    spi_nor_spimem_check_readop(nor, &params->reads[rdidx]))
1978 			*hwcaps &= ~BIT(cap);
1979 
1980 		ppidx = spi_nor_hwcaps_pp2cmd(BIT(cap));
1981 		if (ppidx < 0)
1982 			continue;
1983 
1984 		if (spi_nor_spimem_check_pp(nor,
1985 					    &params->page_programs[ppidx]))
1986 			*hwcaps &= ~BIT(cap);
1987 	}
1988 }
1989 
1990 /**
1991  * spi_nor_set_erase_type() - set a SPI NOR erase type
1992  * @erase:	pointer to a structure that describes a SPI NOR erase type
1993  * @size:	the size of the sector/block erased by the erase type
1994  * @opcode:	the SPI command op code to erase the sector/block
1995  */
spi_nor_set_erase_type(struct spi_nor_erase_type * erase,u32 size,u8 opcode)1996 void spi_nor_set_erase_type(struct spi_nor_erase_type *erase, u32 size,
1997 			    u8 opcode)
1998 {
1999 	erase->size = size;
2000 	erase->opcode = opcode;
2001 	/* JEDEC JESD216B Standard imposes erase sizes to be power of 2. */
2002 	erase->size_shift = ffs(erase->size) - 1;
2003 	erase->size_mask = (1 << erase->size_shift) - 1;
2004 }
2005 
2006 /**
2007  * spi_nor_init_uniform_erase_map() - Initialize uniform erase map
2008  * @map:		the erase map of the SPI NOR
2009  * @erase_mask:		bitmask encoding erase types that can erase the entire
2010  *			flash memory
2011  * @flash_size:		the spi nor flash memory size
2012  */
spi_nor_init_uniform_erase_map(struct spi_nor_erase_map * map,u8 erase_mask,u64 flash_size)2013 void spi_nor_init_uniform_erase_map(struct spi_nor_erase_map *map,
2014 				    u8 erase_mask, u64 flash_size)
2015 {
2016 	/* Offset 0 with erase_mask and SNOR_LAST_REGION bit set */
2017 	map->uniform_region.offset = (erase_mask & SNOR_ERASE_TYPE_MASK) |
2018 				     SNOR_LAST_REGION;
2019 	map->uniform_region.size = flash_size;
2020 	map->regions = &map->uniform_region;
2021 	map->uniform_erase_type = erase_mask;
2022 }
2023 
spi_nor_post_bfpt_fixups(struct spi_nor * nor,const struct sfdp_parameter_header * bfpt_header,const struct sfdp_bfpt * bfpt)2024 int spi_nor_post_bfpt_fixups(struct spi_nor *nor,
2025 			     const struct sfdp_parameter_header *bfpt_header,
2026 			     const struct sfdp_bfpt *bfpt)
2027 {
2028 	int ret;
2029 
2030 	if (nor->manufacturer && nor->manufacturer->fixups &&
2031 	    nor->manufacturer->fixups->post_bfpt) {
2032 		ret = nor->manufacturer->fixups->post_bfpt(nor, bfpt_header,
2033 							   bfpt);
2034 		if (ret)
2035 			return ret;
2036 	}
2037 
2038 	if (nor->info->fixups && nor->info->fixups->post_bfpt)
2039 		return nor->info->fixups->post_bfpt(nor, bfpt_header, bfpt);
2040 
2041 	return 0;
2042 }
2043 
spi_nor_select_read(struct spi_nor * nor,u32 shared_hwcaps)2044 static int spi_nor_select_read(struct spi_nor *nor,
2045 			       u32 shared_hwcaps)
2046 {
2047 	int cmd, best_match = fls(shared_hwcaps & SNOR_HWCAPS_READ_MASK) - 1;
2048 	const struct spi_nor_read_command *read;
2049 
2050 	if (best_match < 0)
2051 		return -EINVAL;
2052 
2053 	cmd = spi_nor_hwcaps_read2cmd(BIT(best_match));
2054 	if (cmd < 0)
2055 		return -EINVAL;
2056 
2057 	read = &nor->params->reads[cmd];
2058 	nor->read_opcode = read->opcode;
2059 	nor->read_proto = read->proto;
2060 
2061 	/*
2062 	 * In the SPI NOR framework, we don't need to make the difference
2063 	 * between mode clock cycles and wait state clock cycles.
2064 	 * Indeed, the value of the mode clock cycles is used by a QSPI
2065 	 * flash memory to know whether it should enter or leave its 0-4-4
2066 	 * (Continuous Read / XIP) mode.
2067 	 * eXecution In Place is out of the scope of the mtd sub-system.
2068 	 * Hence we choose to merge both mode and wait state clock cycles
2069 	 * into the so called dummy clock cycles.
2070 	 */
2071 	nor->read_dummy = read->num_mode_clocks + read->num_wait_states;
2072 	return 0;
2073 }
2074 
spi_nor_select_pp(struct spi_nor * nor,u32 shared_hwcaps)2075 static int spi_nor_select_pp(struct spi_nor *nor,
2076 			     u32 shared_hwcaps)
2077 {
2078 	int cmd, best_match = fls(shared_hwcaps & SNOR_HWCAPS_PP_MASK) - 1;
2079 	const struct spi_nor_pp_command *pp;
2080 
2081 	if (best_match < 0)
2082 		return -EINVAL;
2083 
2084 	cmd = spi_nor_hwcaps_pp2cmd(BIT(best_match));
2085 	if (cmd < 0)
2086 		return -EINVAL;
2087 
2088 	pp = &nor->params->page_programs[cmd];
2089 	nor->program_opcode = pp->opcode;
2090 	nor->write_proto = pp->proto;
2091 	return 0;
2092 }
2093 
2094 /**
2095  * spi_nor_select_uniform_erase() - select optimum uniform erase type
2096  * @map:		the erase map of the SPI NOR
2097  * @wanted_size:	the erase type size to search for. Contains the value of
2098  *			info->sector_size or of the "small sector" size in case
2099  *			CONFIG_MTD_SPI_NOR_USE_4K_SECTORS is defined.
2100  *
2101  * Once the optimum uniform sector erase command is found, disable all the
2102  * other.
2103  *
2104  * Return: pointer to erase type on success, NULL otherwise.
2105  */
2106 static const struct spi_nor_erase_type *
spi_nor_select_uniform_erase(struct spi_nor_erase_map * map,const u32 wanted_size)2107 spi_nor_select_uniform_erase(struct spi_nor_erase_map *map,
2108 			     const u32 wanted_size)
2109 {
2110 	const struct spi_nor_erase_type *tested_erase, *erase = NULL;
2111 	int i;
2112 	u8 uniform_erase_type = map->uniform_erase_type;
2113 
2114 	for (i = SNOR_ERASE_TYPE_MAX - 1; i >= 0; i--) {
2115 		if (!(uniform_erase_type & BIT(i)))
2116 			continue;
2117 
2118 		tested_erase = &map->erase_type[i];
2119 
2120 		/*
2121 		 * If the current erase size is the one, stop here:
2122 		 * we have found the right uniform Sector Erase command.
2123 		 */
2124 		if (tested_erase->size == wanted_size) {
2125 			erase = tested_erase;
2126 			break;
2127 		}
2128 
2129 		/*
2130 		 * Otherwise, the current erase size is still a valid candidate.
2131 		 * Select the biggest valid candidate.
2132 		 */
2133 		if (!erase && tested_erase->size)
2134 			erase = tested_erase;
2135 			/* keep iterating to find the wanted_size */
2136 	}
2137 
2138 	if (!erase)
2139 		return NULL;
2140 
2141 	/* Disable all other Sector Erase commands. */
2142 	map->uniform_erase_type &= ~SNOR_ERASE_TYPE_MASK;
2143 	map->uniform_erase_type |= BIT(erase - map->erase_type);
2144 	return erase;
2145 }
2146 
spi_nor_select_erase(struct spi_nor * nor)2147 static int spi_nor_select_erase(struct spi_nor *nor)
2148 {
2149 	struct spi_nor_erase_map *map = &nor->params->erase_map;
2150 	const struct spi_nor_erase_type *erase = NULL;
2151 	struct mtd_info *mtd = &nor->mtd;
2152 	u32 wanted_size = nor->info->sector_size;
2153 	int i;
2154 
2155 	/*
2156 	 * The previous implementation handling Sector Erase commands assumed
2157 	 * that the SPI flash memory has an uniform layout then used only one
2158 	 * of the supported erase sizes for all Sector Erase commands.
2159 	 * So to be backward compatible, the new implementation also tries to
2160 	 * manage the SPI flash memory as uniform with a single erase sector
2161 	 * size, when possible.
2162 	 */
2163 #ifdef CONFIG_MTD_SPI_NOR_USE_4K_SECTORS
2164 	/* prefer "small sector" erase if possible */
2165 	wanted_size = 4096u;
2166 #endif
2167 
2168 	if (spi_nor_has_uniform_erase(nor)) {
2169 		erase = spi_nor_select_uniform_erase(map, wanted_size);
2170 		if (!erase)
2171 			return -EINVAL;
2172 		nor->erase_opcode = erase->opcode;
2173 		mtd->erasesize = erase->size;
2174 		return 0;
2175 	}
2176 
2177 	/*
2178 	 * For non-uniform SPI flash memory, set mtd->erasesize to the
2179 	 * maximum erase sector size. No need to set nor->erase_opcode.
2180 	 */
2181 	for (i = SNOR_ERASE_TYPE_MAX - 1; i >= 0; i--) {
2182 		if (map->erase_type[i].size) {
2183 			erase = &map->erase_type[i];
2184 			break;
2185 		}
2186 	}
2187 
2188 	if (!erase)
2189 		return -EINVAL;
2190 
2191 	mtd->erasesize = erase->size;
2192 	return 0;
2193 }
2194 
spi_nor_default_setup(struct spi_nor * nor,const struct spi_nor_hwcaps * hwcaps)2195 static int spi_nor_default_setup(struct spi_nor *nor,
2196 				 const struct spi_nor_hwcaps *hwcaps)
2197 {
2198 	struct spi_nor_flash_parameter *params = nor->params;
2199 	u32 ignored_mask, shared_mask;
2200 	int err;
2201 
2202 	/*
2203 	 * Keep only the hardware capabilities supported by both the SPI
2204 	 * controller and the SPI flash memory.
2205 	 */
2206 	shared_mask = hwcaps->mask & params->hwcaps.mask;
2207 
2208 	if (nor->spimem) {
2209 		/*
2210 		 * When called from spi_nor_probe(), all caps are set and we
2211 		 * need to discard some of them based on what the SPI
2212 		 * controller actually supports (using spi_mem_supports_op()).
2213 		 */
2214 		spi_nor_spimem_adjust_hwcaps(nor, &shared_mask);
2215 	} else {
2216 		/*
2217 		 * SPI n-n-n protocols are not supported when the SPI
2218 		 * controller directly implements the spi_nor interface.
2219 		 * Yet another reason to switch to spi-mem.
2220 		 */
2221 		ignored_mask = SNOR_HWCAPS_X_X_X | SNOR_HWCAPS_X_X_X_DTR;
2222 		if (shared_mask & ignored_mask) {
2223 			dev_dbg(nor->dev,
2224 				"SPI n-n-n protocols are not supported.\n");
2225 			shared_mask &= ~ignored_mask;
2226 		}
2227 	}
2228 
2229 	/* Select the (Fast) Read command. */
2230 	err = spi_nor_select_read(nor, shared_mask);
2231 	if (err) {
2232 		dev_dbg(nor->dev,
2233 			"can't select read settings supported by both the SPI controller and memory.\n");
2234 		return err;
2235 	}
2236 
2237 	/* Select the Page Program command. */
2238 	err = spi_nor_select_pp(nor, shared_mask);
2239 	if (err) {
2240 		dev_dbg(nor->dev,
2241 			"can't select write settings supported by both the SPI controller and memory.\n");
2242 		return err;
2243 	}
2244 
2245 	/* Select the Sector Erase command. */
2246 	err = spi_nor_select_erase(nor);
2247 	if (err) {
2248 		dev_dbg(nor->dev,
2249 			"can't select erase settings supported by both the SPI controller and memory.\n");
2250 		return err;
2251 	}
2252 
2253 	return 0;
2254 }
2255 
spi_nor_set_addr_nbytes(struct spi_nor * nor)2256 static int spi_nor_set_addr_nbytes(struct spi_nor *nor)
2257 {
2258 	if (nor->params->addr_nbytes) {
2259 		nor->addr_nbytes = nor->params->addr_nbytes;
2260 	} else if (nor->read_proto == SNOR_PROTO_8_8_8_DTR) {
2261 		/*
2262 		 * In 8D-8D-8D mode, one byte takes half a cycle to transfer. So
2263 		 * in this protocol an odd addr_nbytes cannot be used because
2264 		 * then the address phase would only span a cycle and a half.
2265 		 * Half a cycle would be left over. We would then have to start
2266 		 * the dummy phase in the middle of a cycle and so too the data
2267 		 * phase, and we will end the transaction with half a cycle left
2268 		 * over.
2269 		 *
2270 		 * Force all 8D-8D-8D flashes to use an addr_nbytes of 4 to
2271 		 * avoid this situation.
2272 		 */
2273 		nor->addr_nbytes = 4;
2274 	} else if (nor->info->addr_nbytes) {
2275 		nor->addr_nbytes = nor->info->addr_nbytes;
2276 	} else {
2277 		nor->addr_nbytes = 3;
2278 	}
2279 
2280 	if (nor->addr_nbytes == 3 && nor->params->size > 0x1000000) {
2281 		/* enable 4-byte addressing if the device exceeds 16MiB */
2282 		nor->addr_nbytes = 4;
2283 	}
2284 
2285 	if (nor->addr_nbytes > SPI_NOR_MAX_ADDR_NBYTES) {
2286 		dev_dbg(nor->dev, "The number of address bytes is too large: %u\n",
2287 			nor->addr_nbytes);
2288 		return -EINVAL;
2289 	}
2290 
2291 	/* Set 4byte opcodes when possible. */
2292 	if (nor->addr_nbytes == 4 && nor->flags & SNOR_F_4B_OPCODES &&
2293 	    !(nor->flags & SNOR_F_HAS_4BAIT))
2294 		spi_nor_set_4byte_opcodes(nor);
2295 
2296 	return 0;
2297 }
2298 
spi_nor_setup(struct spi_nor * nor,const struct spi_nor_hwcaps * hwcaps)2299 static int spi_nor_setup(struct spi_nor *nor,
2300 			 const struct spi_nor_hwcaps *hwcaps)
2301 {
2302 	int ret;
2303 
2304 	if (nor->params->setup)
2305 		ret = nor->params->setup(nor, hwcaps);
2306 	else
2307 		ret = spi_nor_default_setup(nor, hwcaps);
2308 	if (ret)
2309 		return ret;
2310 
2311 	return spi_nor_set_addr_nbytes(nor);
2312 }
2313 
2314 /**
2315  * spi_nor_manufacturer_init_params() - Initialize the flash's parameters and
2316  * settings based on MFR register and ->default_init() hook.
2317  * @nor:	pointer to a 'struct spi_nor'.
2318  */
spi_nor_manufacturer_init_params(struct spi_nor * nor)2319 static void spi_nor_manufacturer_init_params(struct spi_nor *nor)
2320 {
2321 	if (nor->manufacturer && nor->manufacturer->fixups &&
2322 	    nor->manufacturer->fixups->default_init)
2323 		nor->manufacturer->fixups->default_init(nor);
2324 
2325 	if (nor->info->fixups && nor->info->fixups->default_init)
2326 		nor->info->fixups->default_init(nor);
2327 }
2328 
2329 /**
2330  * spi_nor_no_sfdp_init_params() - Initialize the flash's parameters and
2331  * settings based on nor->info->sfdp_flags. This method should be called only by
2332  * flashes that do not define SFDP tables. If the flash supports SFDP but the
2333  * information is wrong and the settings from this function can not be retrieved
2334  * by parsing SFDP, one should instead use the fixup hooks and update the wrong
2335  * bits.
2336  * @nor:	pointer to a 'struct spi_nor'.
2337  */
spi_nor_no_sfdp_init_params(struct spi_nor * nor)2338 static void spi_nor_no_sfdp_init_params(struct spi_nor *nor)
2339 {
2340 	struct spi_nor_flash_parameter *params = nor->params;
2341 	struct spi_nor_erase_map *map = &params->erase_map;
2342 	const u8 no_sfdp_flags = nor->info->no_sfdp_flags;
2343 	u8 i, erase_mask;
2344 
2345 	if (no_sfdp_flags & SPI_NOR_DUAL_READ) {
2346 		params->hwcaps.mask |= SNOR_HWCAPS_READ_1_1_2;
2347 		spi_nor_set_read_settings(&params->reads[SNOR_CMD_READ_1_1_2],
2348 					  0, 8, SPINOR_OP_READ_1_1_2,
2349 					  SNOR_PROTO_1_1_2);
2350 	}
2351 
2352 	if (no_sfdp_flags & SPI_NOR_QUAD_READ) {
2353 		params->hwcaps.mask |= SNOR_HWCAPS_READ_1_1_4;
2354 		spi_nor_set_read_settings(&params->reads[SNOR_CMD_READ_1_1_4],
2355 					  0, 8, SPINOR_OP_READ_1_1_4,
2356 					  SNOR_PROTO_1_1_4);
2357 	}
2358 
2359 	if (no_sfdp_flags & SPI_NOR_OCTAL_READ) {
2360 		params->hwcaps.mask |= SNOR_HWCAPS_READ_1_1_8;
2361 		spi_nor_set_read_settings(&params->reads[SNOR_CMD_READ_1_1_8],
2362 					  0, 8, SPINOR_OP_READ_1_1_8,
2363 					  SNOR_PROTO_1_1_8);
2364 	}
2365 
2366 	if (no_sfdp_flags & SPI_NOR_OCTAL_DTR_READ) {
2367 		params->hwcaps.mask |= SNOR_HWCAPS_READ_8_8_8_DTR;
2368 		spi_nor_set_read_settings(&params->reads[SNOR_CMD_READ_8_8_8_DTR],
2369 					  0, 20, SPINOR_OP_READ_FAST,
2370 					  SNOR_PROTO_8_8_8_DTR);
2371 	}
2372 
2373 	if (no_sfdp_flags & SPI_NOR_OCTAL_DTR_PP) {
2374 		params->hwcaps.mask |= SNOR_HWCAPS_PP_8_8_8_DTR;
2375 		/*
2376 		 * Since xSPI Page Program opcode is backward compatible with
2377 		 * Legacy SPI, use Legacy SPI opcode there as well.
2378 		 */
2379 		spi_nor_set_pp_settings(&params->page_programs[SNOR_CMD_PP_8_8_8_DTR],
2380 					SPINOR_OP_PP, SNOR_PROTO_8_8_8_DTR);
2381 	}
2382 
2383 	/*
2384 	 * Sector Erase settings. Sort Erase Types in ascending order, with the
2385 	 * smallest erase size starting at BIT(0).
2386 	 */
2387 	erase_mask = 0;
2388 	i = 0;
2389 	if (no_sfdp_flags & SECT_4K) {
2390 		erase_mask |= BIT(i);
2391 		spi_nor_set_erase_type(&map->erase_type[i], 4096u,
2392 				       SPINOR_OP_BE_4K);
2393 		i++;
2394 	}
2395 	erase_mask |= BIT(i);
2396 	spi_nor_set_erase_type(&map->erase_type[i], nor->info->sector_size,
2397 			       SPINOR_OP_SE);
2398 	spi_nor_init_uniform_erase_map(map, erase_mask, params->size);
2399 }
2400 
2401 /**
2402  * spi_nor_init_flags() - Initialize NOR flags for settings that are not defined
2403  * in the JESD216 SFDP standard, thus can not be retrieved when parsing SFDP.
2404  * @nor:	pointer to a 'struct spi_nor'
2405  */
spi_nor_init_flags(struct spi_nor * nor)2406 static void spi_nor_init_flags(struct spi_nor *nor)
2407 {
2408 	struct device_node *np = spi_nor_get_flash_node(nor);
2409 	const u16 flags = nor->info->flags;
2410 
2411 	if (of_property_read_bool(np, "broken-flash-reset"))
2412 		nor->flags |= SNOR_F_BROKEN_RESET;
2413 
2414 	if (flags & SPI_NOR_SWP_IS_VOLATILE)
2415 		nor->flags |= SNOR_F_SWP_IS_VOLATILE;
2416 
2417 	if (flags & SPI_NOR_HAS_LOCK)
2418 		nor->flags |= SNOR_F_HAS_LOCK;
2419 
2420 	if (flags & SPI_NOR_HAS_TB) {
2421 		nor->flags |= SNOR_F_HAS_SR_TB;
2422 		if (flags & SPI_NOR_TB_SR_BIT6)
2423 			nor->flags |= SNOR_F_HAS_SR_TB_BIT6;
2424 	}
2425 
2426 	if (flags & SPI_NOR_4BIT_BP) {
2427 		nor->flags |= SNOR_F_HAS_4BIT_BP;
2428 		if (flags & SPI_NOR_BP3_SR_BIT6)
2429 			nor->flags |= SNOR_F_HAS_SR_BP3_BIT6;
2430 	}
2431 
2432 	if (flags & NO_CHIP_ERASE)
2433 		nor->flags |= SNOR_F_NO_OP_CHIP_ERASE;
2434 }
2435 
2436 /**
2437  * spi_nor_init_fixup_flags() - Initialize NOR flags for settings that can not
2438  * be discovered by SFDP for this particular flash because the SFDP table that
2439  * indicates this support is not defined in the flash. In case the table for
2440  * this support is defined but has wrong values, one should instead use a
2441  * post_sfdp() hook to set the SNOR_F equivalent flag.
2442  * @nor:       pointer to a 'struct spi_nor'
2443  */
spi_nor_init_fixup_flags(struct spi_nor * nor)2444 static void spi_nor_init_fixup_flags(struct spi_nor *nor)
2445 {
2446 	const u8 fixup_flags = nor->info->fixup_flags;
2447 
2448 	if (fixup_flags & SPI_NOR_4B_OPCODES)
2449 		nor->flags |= SNOR_F_4B_OPCODES;
2450 
2451 	if (fixup_flags & SPI_NOR_IO_MODE_EN_VOLATILE)
2452 		nor->flags |= SNOR_F_IO_MODE_EN_VOLATILE;
2453 }
2454 
2455 /**
2456  * spi_nor_late_init_params() - Late initialization of default flash parameters.
2457  * @nor:	pointer to a 'struct spi_nor'
2458  *
2459  * Used to initialize flash parameters that are not declared in the JESD216
2460  * SFDP standard, or where SFDP tables are not defined at all.
2461  * Will replace the spi_nor_manufacturer_init_params() method.
2462  */
spi_nor_late_init_params(struct spi_nor * nor)2463 static void spi_nor_late_init_params(struct spi_nor *nor)
2464 {
2465 	if (nor->manufacturer && nor->manufacturer->fixups &&
2466 	    nor->manufacturer->fixups->late_init)
2467 		nor->manufacturer->fixups->late_init(nor);
2468 
2469 	if (nor->info->fixups && nor->info->fixups->late_init)
2470 		nor->info->fixups->late_init(nor);
2471 
2472 	spi_nor_init_flags(nor);
2473 	spi_nor_init_fixup_flags(nor);
2474 
2475 	/*
2476 	 * NOR protection support. When locking_ops are not provided, we pick
2477 	 * the default ones.
2478 	 */
2479 	if (nor->flags & SNOR_F_HAS_LOCK && !nor->params->locking_ops)
2480 		spi_nor_init_default_locking_ops(nor);
2481 }
2482 
2483 /**
2484  * spi_nor_sfdp_init_params_deprecated() - Deprecated way of initializing flash
2485  * parameters and settings based on JESD216 SFDP standard.
2486  * @nor:	pointer to a 'struct spi_nor'.
2487  *
2488  * The method has a roll-back mechanism: in case the SFDP parsing fails, the
2489  * legacy flash parameters and settings will be restored.
2490  */
spi_nor_sfdp_init_params_deprecated(struct spi_nor * nor)2491 static void spi_nor_sfdp_init_params_deprecated(struct spi_nor *nor)
2492 {
2493 	struct spi_nor_flash_parameter sfdp_params;
2494 
2495 	memcpy(&sfdp_params, nor->params, sizeof(sfdp_params));
2496 
2497 	if (spi_nor_parse_sfdp(nor)) {
2498 		memcpy(nor->params, &sfdp_params, sizeof(*nor->params));
2499 		nor->flags &= ~SNOR_F_4B_OPCODES;
2500 	}
2501 }
2502 
2503 /**
2504  * spi_nor_init_params_deprecated() - Deprecated way of initializing flash
2505  * parameters and settings.
2506  * @nor:	pointer to a 'struct spi_nor'.
2507  *
2508  * The method assumes that flash doesn't support SFDP so it initializes flash
2509  * parameters in spi_nor_no_sfdp_init_params() which later on can be overwritten
2510  * when parsing SFDP, if supported.
2511  */
spi_nor_init_params_deprecated(struct spi_nor * nor)2512 static void spi_nor_init_params_deprecated(struct spi_nor *nor)
2513 {
2514 	spi_nor_no_sfdp_init_params(nor);
2515 
2516 	spi_nor_manufacturer_init_params(nor);
2517 
2518 	if (nor->info->no_sfdp_flags & (SPI_NOR_DUAL_READ |
2519 					SPI_NOR_QUAD_READ |
2520 					SPI_NOR_OCTAL_READ |
2521 					SPI_NOR_OCTAL_DTR_READ))
2522 		spi_nor_sfdp_init_params_deprecated(nor);
2523 }
2524 
2525 /**
2526  * spi_nor_init_default_params() - Default initialization of flash parameters
2527  * and settings. Done for all flashes, regardless is they define SFDP tables
2528  * or not.
2529  * @nor:	pointer to a 'struct spi_nor'.
2530  */
spi_nor_init_default_params(struct spi_nor * nor)2531 static void spi_nor_init_default_params(struct spi_nor *nor)
2532 {
2533 	struct spi_nor_flash_parameter *params = nor->params;
2534 	const struct flash_info *info = nor->info;
2535 	struct device_node *np = spi_nor_get_flash_node(nor);
2536 
2537 	params->quad_enable = spi_nor_sr2_bit1_quad_enable;
2538 	params->set_4byte_addr_mode = spansion_set_4byte_addr_mode;
2539 	params->otp.org = &info->otp_org;
2540 
2541 	/* Default to 16-bit Write Status (01h) Command */
2542 	nor->flags |= SNOR_F_HAS_16BIT_SR;
2543 
2544 	/* Set SPI NOR sizes. */
2545 	params->writesize = 1;
2546 	params->size = (u64)info->sector_size * info->n_sectors;
2547 	params->page_size = info->page_size;
2548 
2549 	if (!(info->flags & SPI_NOR_NO_FR)) {
2550 		/* Default to Fast Read for DT and non-DT platform devices. */
2551 		params->hwcaps.mask |= SNOR_HWCAPS_READ_FAST;
2552 
2553 		/* Mask out Fast Read if not requested at DT instantiation. */
2554 		if (np && !of_property_read_bool(np, "m25p,fast-read"))
2555 			params->hwcaps.mask &= ~SNOR_HWCAPS_READ_FAST;
2556 	}
2557 
2558 	/* (Fast) Read settings. */
2559 	params->hwcaps.mask |= SNOR_HWCAPS_READ;
2560 	spi_nor_set_read_settings(&params->reads[SNOR_CMD_READ],
2561 				  0, 0, SPINOR_OP_READ,
2562 				  SNOR_PROTO_1_1_1);
2563 
2564 	if (params->hwcaps.mask & SNOR_HWCAPS_READ_FAST)
2565 		spi_nor_set_read_settings(&params->reads[SNOR_CMD_READ_FAST],
2566 					  0, 8, SPINOR_OP_READ_FAST,
2567 					  SNOR_PROTO_1_1_1);
2568 	/* Page Program settings. */
2569 	params->hwcaps.mask |= SNOR_HWCAPS_PP;
2570 	spi_nor_set_pp_settings(&params->page_programs[SNOR_CMD_PP],
2571 				SPINOR_OP_PP, SNOR_PROTO_1_1_1);
2572 }
2573 
2574 /**
2575  * spi_nor_init_params() - Initialize the flash's parameters and settings.
2576  * @nor:	pointer to a 'struct spi_nor'.
2577  *
2578  * The flash parameters and settings are initialized based on a sequence of
2579  * calls that are ordered by priority:
2580  *
2581  * 1/ Default flash parameters initialization. The initializations are done
2582  *    based on nor->info data:
2583  *		spi_nor_info_init_params()
2584  *
2585  * which can be overwritten by:
2586  * 2/ Manufacturer flash parameters initialization. The initializations are
2587  *    done based on MFR register, or when the decisions can not be done solely
2588  *    based on MFR, by using specific flash_info tweeks, ->default_init():
2589  *		spi_nor_manufacturer_init_params()
2590  *
2591  * which can be overwritten by:
2592  * 3/ SFDP flash parameters initialization. JESD216 SFDP is a standard and
2593  *    should be more accurate that the above.
2594  *		spi_nor_parse_sfdp() or spi_nor_no_sfdp_init_params()
2595  *
2596  *    Please note that there is a ->post_bfpt() fixup hook that can overwrite
2597  *    the flash parameters and settings immediately after parsing the Basic
2598  *    Flash Parameter Table.
2599  *    spi_nor_post_sfdp_fixups() is called after the SFDP tables are parsed.
2600  *    It is used to tweak various flash parameters when information provided
2601  *    by the SFDP tables are wrong.
2602  *
2603  * which can be overwritten by:
2604  * 4/ Late flash parameters initialization, used to initialize flash
2605  * parameters that are not declared in the JESD216 SFDP standard, or where SFDP
2606  * tables are not defined at all.
2607  *		spi_nor_late_init_params()
2608  *
2609  * Return: 0 on success, -errno otherwise.
2610  */
spi_nor_init_params(struct spi_nor * nor)2611 static int spi_nor_init_params(struct spi_nor *nor)
2612 {
2613 	int ret;
2614 
2615 	nor->params = devm_kzalloc(nor->dev, sizeof(*nor->params), GFP_KERNEL);
2616 	if (!nor->params)
2617 		return -ENOMEM;
2618 
2619 	spi_nor_init_default_params(nor);
2620 
2621 	if (nor->info->parse_sfdp) {
2622 		ret = spi_nor_parse_sfdp(nor);
2623 		if (ret) {
2624 			dev_err(nor->dev, "BFPT parsing failed. Please consider using SPI_NOR_SKIP_SFDP when declaring the flash\n");
2625 			return ret;
2626 		}
2627 	} else if (nor->info->no_sfdp_flags & SPI_NOR_SKIP_SFDP) {
2628 		spi_nor_no_sfdp_init_params(nor);
2629 	} else {
2630 		spi_nor_init_params_deprecated(nor);
2631 	}
2632 
2633 	spi_nor_late_init_params(nor);
2634 
2635 	return 0;
2636 }
2637 
2638 /** spi_nor_octal_dtr_enable() - enable Octal DTR I/O if needed
2639  * @nor:                 pointer to a 'struct spi_nor'
2640  * @enable:              whether to enable or disable Octal DTR
2641  *
2642  * Return: 0 on success, -errno otherwise.
2643  */
spi_nor_octal_dtr_enable(struct spi_nor * nor,bool enable)2644 static int spi_nor_octal_dtr_enable(struct spi_nor *nor, bool enable)
2645 {
2646 	int ret;
2647 
2648 	if (!nor->params->octal_dtr_enable)
2649 		return 0;
2650 
2651 	if (!(nor->read_proto == SNOR_PROTO_8_8_8_DTR &&
2652 	      nor->write_proto == SNOR_PROTO_8_8_8_DTR))
2653 		return 0;
2654 
2655 	if (!(nor->flags & SNOR_F_IO_MODE_EN_VOLATILE))
2656 		return 0;
2657 
2658 	ret = nor->params->octal_dtr_enable(nor, enable);
2659 	if (ret)
2660 		return ret;
2661 
2662 	if (enable)
2663 		nor->reg_proto = SNOR_PROTO_8_8_8_DTR;
2664 	else
2665 		nor->reg_proto = SNOR_PROTO_1_1_1;
2666 
2667 	return 0;
2668 }
2669 
2670 /**
2671  * spi_nor_quad_enable() - enable Quad I/O if needed.
2672  * @nor:                pointer to a 'struct spi_nor'
2673  *
2674  * Return: 0 on success, -errno otherwise.
2675  */
spi_nor_quad_enable(struct spi_nor * nor)2676 static int spi_nor_quad_enable(struct spi_nor *nor)
2677 {
2678 	if (!nor->params->quad_enable)
2679 		return 0;
2680 
2681 	if (!(spi_nor_get_protocol_width(nor->read_proto) == 4 ||
2682 	      spi_nor_get_protocol_width(nor->write_proto) == 4))
2683 		return 0;
2684 
2685 	return nor->params->quad_enable(nor);
2686 }
2687 
spi_nor_init(struct spi_nor * nor)2688 static int spi_nor_init(struct spi_nor *nor)
2689 {
2690 	int err;
2691 
2692 	err = spi_nor_octal_dtr_enable(nor, true);
2693 	if (err) {
2694 		dev_dbg(nor->dev, "octal mode not supported\n");
2695 		return err;
2696 	}
2697 
2698 	err = spi_nor_quad_enable(nor);
2699 	if (err) {
2700 		dev_dbg(nor->dev, "quad mode not supported\n");
2701 		return err;
2702 	}
2703 
2704 	/*
2705 	 * Some SPI NOR flashes are write protected by default after a power-on
2706 	 * reset cycle, in order to avoid inadvertent writes during power-up.
2707 	 * Backward compatibility imposes to unlock the entire flash memory
2708 	 * array at power-up by default. Depending on the kernel configuration
2709 	 * (1) do nothing, (2) always unlock the entire flash array or (3)
2710 	 * unlock the entire flash array only when the software write
2711 	 * protection bits are volatile. The latter is indicated by
2712 	 * SNOR_F_SWP_IS_VOLATILE.
2713 	 */
2714 	if (IS_ENABLED(CONFIG_MTD_SPI_NOR_SWP_DISABLE) ||
2715 	    (IS_ENABLED(CONFIG_MTD_SPI_NOR_SWP_DISABLE_ON_VOLATILE) &&
2716 	     nor->flags & SNOR_F_SWP_IS_VOLATILE))
2717 		spi_nor_try_unlock_all(nor);
2718 
2719 	if (nor->addr_nbytes == 4 &&
2720 	    nor->read_proto != SNOR_PROTO_8_8_8_DTR &&
2721 	    !(nor->flags & SNOR_F_4B_OPCODES)) {
2722 		/*
2723 		 * If the RESET# pin isn't hooked up properly, or the system
2724 		 * otherwise doesn't perform a reset command in the boot
2725 		 * sequence, it's impossible to 100% protect against unexpected
2726 		 * reboots (e.g., crashes). Warn the user (or hopefully, system
2727 		 * designer) that this is bad.
2728 		 */
2729 		WARN_ONCE(nor->flags & SNOR_F_BROKEN_RESET,
2730 			  "enabling reset hack; may not recover from unexpected reboots\n");
2731 		err = nor->params->set_4byte_addr_mode(nor, true);
2732 		if (err && err != -ENOTSUPP)
2733 			return err;
2734 	}
2735 
2736 	return 0;
2737 }
2738 
2739 /**
2740  * spi_nor_soft_reset() - Perform a software reset
2741  * @nor:	pointer to 'struct spi_nor'
2742  *
2743  * Performs a "Soft Reset and Enter Default Protocol Mode" sequence which resets
2744  * the device to its power-on-reset state. This is useful when the software has
2745  * made some changes to device (volatile) registers and needs to reset it before
2746  * shutting down, for example.
2747  *
2748  * Not every flash supports this sequence. The same set of opcodes might be used
2749  * for some other operation on a flash that does not support this. Support for
2750  * this sequence can be discovered via SFDP in the BFPT table.
2751  *
2752  * Return: 0 on success, -errno otherwise.
2753  */
spi_nor_soft_reset(struct spi_nor * nor)2754 static void spi_nor_soft_reset(struct spi_nor *nor)
2755 {
2756 	struct spi_mem_op op;
2757 	int ret;
2758 
2759 	op = (struct spi_mem_op)SPINOR_SRSTEN_OP;
2760 
2761 	spi_nor_spimem_setup_op(nor, &op, nor->reg_proto);
2762 
2763 	ret = spi_mem_exec_op(nor->spimem, &op);
2764 	if (ret) {
2765 		dev_warn(nor->dev, "Software reset failed: %d\n", ret);
2766 		return;
2767 	}
2768 
2769 	op = (struct spi_mem_op)SPINOR_SRST_OP;
2770 
2771 	spi_nor_spimem_setup_op(nor, &op, nor->reg_proto);
2772 
2773 	ret = spi_mem_exec_op(nor->spimem, &op);
2774 	if (ret) {
2775 		dev_warn(nor->dev, "Software reset failed: %d\n", ret);
2776 		return;
2777 	}
2778 
2779 	/*
2780 	 * Software Reset is not instant, and the delay varies from flash to
2781 	 * flash. Looking at a few flashes, most range somewhere below 100
2782 	 * microseconds. So, sleep for a range of 200-400 us.
2783 	 */
2784 	usleep_range(SPI_NOR_SRST_SLEEP_MIN, SPI_NOR_SRST_SLEEP_MAX);
2785 }
2786 
2787 /* mtd suspend handler */
spi_nor_suspend(struct mtd_info * mtd)2788 static int spi_nor_suspend(struct mtd_info *mtd)
2789 {
2790 	struct spi_nor *nor = mtd_to_spi_nor(mtd);
2791 	int ret;
2792 
2793 	/* Disable octal DTR mode if we enabled it. */
2794 	ret = spi_nor_octal_dtr_enable(nor, false);
2795 	if (ret)
2796 		dev_err(nor->dev, "suspend() failed\n");
2797 
2798 	return ret;
2799 }
2800 
2801 /* mtd resume handler */
spi_nor_resume(struct mtd_info * mtd)2802 static void spi_nor_resume(struct mtd_info *mtd)
2803 {
2804 	struct spi_nor *nor = mtd_to_spi_nor(mtd);
2805 	struct device *dev = nor->dev;
2806 	int ret;
2807 
2808 	/* re-initialize the nor chip */
2809 	ret = spi_nor_init(nor);
2810 	if (ret)
2811 		dev_err(dev, "resume() failed\n");
2812 }
2813 
spi_nor_get_device(struct mtd_info * mtd)2814 static int spi_nor_get_device(struct mtd_info *mtd)
2815 {
2816 	struct mtd_info *master = mtd_get_master(mtd);
2817 	struct spi_nor *nor = mtd_to_spi_nor(master);
2818 	struct device *dev;
2819 
2820 	if (nor->spimem)
2821 		dev = nor->spimem->spi->controller->dev.parent;
2822 	else
2823 		dev = nor->dev;
2824 
2825 	if (!try_module_get(dev->driver->owner))
2826 		return -ENODEV;
2827 
2828 	return 0;
2829 }
2830 
spi_nor_put_device(struct mtd_info * mtd)2831 static void spi_nor_put_device(struct mtd_info *mtd)
2832 {
2833 	struct mtd_info *master = mtd_get_master(mtd);
2834 	struct spi_nor *nor = mtd_to_spi_nor(master);
2835 	struct device *dev;
2836 
2837 	if (nor->spimem)
2838 		dev = nor->spimem->spi->controller->dev.parent;
2839 	else
2840 		dev = nor->dev;
2841 
2842 	module_put(dev->driver->owner);
2843 }
2844 
spi_nor_restore(struct spi_nor * nor)2845 void spi_nor_restore(struct spi_nor *nor)
2846 {
2847 	/* restore the addressing mode */
2848 	if (nor->addr_nbytes == 4 && !(nor->flags & SNOR_F_4B_OPCODES) &&
2849 	    nor->flags & SNOR_F_BROKEN_RESET)
2850 		nor->params->set_4byte_addr_mode(nor, false);
2851 
2852 	if (nor->flags & SNOR_F_SOFT_RESET)
2853 		spi_nor_soft_reset(nor);
2854 }
2855 EXPORT_SYMBOL_GPL(spi_nor_restore);
2856 
spi_nor_match_name(struct spi_nor * nor,const char * name)2857 static const struct flash_info *spi_nor_match_name(struct spi_nor *nor,
2858 						   const char *name)
2859 {
2860 	unsigned int i, j;
2861 
2862 	for (i = 0; i < ARRAY_SIZE(manufacturers); i++) {
2863 		for (j = 0; j < manufacturers[i]->nparts; j++) {
2864 			if (!strcmp(name, manufacturers[i]->parts[j].name)) {
2865 				nor->manufacturer = manufacturers[i];
2866 				return &manufacturers[i]->parts[j];
2867 			}
2868 		}
2869 	}
2870 
2871 	return NULL;
2872 }
2873 
spi_nor_get_flash_info(struct spi_nor * nor,const char * name)2874 static const struct flash_info *spi_nor_get_flash_info(struct spi_nor *nor,
2875 						       const char *name)
2876 {
2877 	const struct flash_info *info = NULL;
2878 
2879 	if (name)
2880 		info = spi_nor_match_name(nor, name);
2881 	/* Try to auto-detect if chip name wasn't specified or not found */
2882 	if (!info)
2883 		return spi_nor_detect(nor);
2884 
2885 	/*
2886 	 * If caller has specified name of flash model that can normally be
2887 	 * detected using JEDEC, let's verify it.
2888 	 */
2889 	if (name && info->id_len) {
2890 		const struct flash_info *jinfo;
2891 
2892 		jinfo = spi_nor_detect(nor);
2893 		if (IS_ERR(jinfo)) {
2894 			return jinfo;
2895 		} else if (jinfo != info) {
2896 			/*
2897 			 * JEDEC knows better, so overwrite platform ID. We
2898 			 * can't trust partitions any longer, but we'll let
2899 			 * mtd apply them anyway, since some partitions may be
2900 			 * marked read-only, and we don't want to lose that
2901 			 * information, even if it's not 100% accurate.
2902 			 */
2903 			dev_warn(nor->dev, "found %s, expected %s\n",
2904 				 jinfo->name, info->name);
2905 			info = jinfo;
2906 		}
2907 	}
2908 
2909 	return info;
2910 }
2911 
spi_nor_set_mtd_info(struct spi_nor * nor)2912 static void spi_nor_set_mtd_info(struct spi_nor *nor)
2913 {
2914 	struct mtd_info *mtd = &nor->mtd;
2915 	struct device *dev = nor->dev;
2916 
2917 	spi_nor_set_mtd_locking_ops(nor);
2918 	spi_nor_set_mtd_otp_ops(nor);
2919 
2920 	mtd->dev.parent = dev;
2921 	if (!mtd->name)
2922 		mtd->name = dev_name(dev);
2923 	mtd->type = MTD_NORFLASH;
2924 	mtd->flags = MTD_CAP_NORFLASH;
2925 	if (nor->info->flags & SPI_NOR_NO_ERASE)
2926 		mtd->flags |= MTD_NO_ERASE;
2927 	else
2928 		mtd->_erase = spi_nor_erase;
2929 	mtd->writesize = nor->params->writesize;
2930 	mtd->writebufsize = nor->params->page_size;
2931 	mtd->size = nor->params->size;
2932 	mtd->_read = spi_nor_read;
2933 	/* Might be already set by some SST flashes. */
2934 	if (!mtd->_write)
2935 		mtd->_write = spi_nor_write;
2936 	mtd->_suspend = spi_nor_suspend;
2937 	mtd->_resume = spi_nor_resume;
2938 	mtd->_get_device = spi_nor_get_device;
2939 	mtd->_put_device = spi_nor_put_device;
2940 }
2941 
spi_nor_scan(struct spi_nor * nor,const char * name,const struct spi_nor_hwcaps * hwcaps)2942 int spi_nor_scan(struct spi_nor *nor, const char *name,
2943 		 const struct spi_nor_hwcaps *hwcaps)
2944 {
2945 	const struct flash_info *info;
2946 	struct device *dev = nor->dev;
2947 	struct mtd_info *mtd = &nor->mtd;
2948 	int ret;
2949 	int i;
2950 
2951 	ret = spi_nor_check(nor);
2952 	if (ret)
2953 		return ret;
2954 
2955 	/* Reset SPI protocol for all commands. */
2956 	nor->reg_proto = SNOR_PROTO_1_1_1;
2957 	nor->read_proto = SNOR_PROTO_1_1_1;
2958 	nor->write_proto = SNOR_PROTO_1_1_1;
2959 
2960 	/*
2961 	 * We need the bounce buffer early to read/write registers when going
2962 	 * through the spi-mem layer (buffers have to be DMA-able).
2963 	 * For spi-mem drivers, we'll reallocate a new buffer if
2964 	 * nor->params->page_size turns out to be greater than PAGE_SIZE (which
2965 	 * shouldn't happen before long since NOR pages are usually less
2966 	 * than 1KB) after spi_nor_scan() returns.
2967 	 */
2968 	nor->bouncebuf_size = PAGE_SIZE;
2969 	nor->bouncebuf = devm_kmalloc(dev, nor->bouncebuf_size,
2970 				      GFP_KERNEL);
2971 	if (!nor->bouncebuf)
2972 		return -ENOMEM;
2973 
2974 	info = spi_nor_get_flash_info(nor, name);
2975 	if (IS_ERR(info))
2976 		return PTR_ERR(info);
2977 
2978 	nor->info = info;
2979 
2980 	mutex_init(&nor->lock);
2981 
2982 	/* Init flash parameters based on flash_info struct and SFDP */
2983 	ret = spi_nor_init_params(nor);
2984 	if (ret)
2985 		return ret;
2986 
2987 	/*
2988 	 * Configure the SPI memory:
2989 	 * - select op codes for (Fast) Read, Page Program and Sector Erase.
2990 	 * - set the number of dummy cycles (mode cycles + wait states).
2991 	 * - set the SPI protocols for register and memory accesses.
2992 	 * - set the number of address bytes.
2993 	 */
2994 	ret = spi_nor_setup(nor, hwcaps);
2995 	if (ret)
2996 		return ret;
2997 
2998 	/* Send all the required SPI flash commands to initialize device */
2999 	ret = spi_nor_init(nor);
3000 	if (ret)
3001 		return ret;
3002 
3003 	/* No mtd_info fields should be used up to this point. */
3004 	spi_nor_set_mtd_info(nor);
3005 
3006 	dev_info(dev, "%s (%lld Kbytes)\n", info->name,
3007 			(long long)mtd->size >> 10);
3008 
3009 	dev_dbg(dev,
3010 		"mtd .name = %s, .size = 0x%llx (%lldMiB), "
3011 		".erasesize = 0x%.8x (%uKiB) .numeraseregions = %d\n",
3012 		mtd->name, (long long)mtd->size, (long long)(mtd->size >> 20),
3013 		mtd->erasesize, mtd->erasesize / 1024, mtd->numeraseregions);
3014 
3015 	if (mtd->numeraseregions)
3016 		for (i = 0; i < mtd->numeraseregions; i++)
3017 			dev_dbg(dev,
3018 				"mtd.eraseregions[%d] = { .offset = 0x%llx, "
3019 				".erasesize = 0x%.8x (%uKiB), "
3020 				".numblocks = %d }\n",
3021 				i, (long long)mtd->eraseregions[i].offset,
3022 				mtd->eraseregions[i].erasesize,
3023 				mtd->eraseregions[i].erasesize / 1024,
3024 				mtd->eraseregions[i].numblocks);
3025 	return 0;
3026 }
3027 EXPORT_SYMBOL_GPL(spi_nor_scan);
3028 
spi_nor_create_read_dirmap(struct spi_nor * nor)3029 static int spi_nor_create_read_dirmap(struct spi_nor *nor)
3030 {
3031 	struct spi_mem_dirmap_info info = {
3032 		.op_tmpl = SPI_MEM_OP(SPI_MEM_OP_CMD(nor->read_opcode, 0),
3033 				      SPI_MEM_OP_ADDR(nor->addr_nbytes, 0, 0),
3034 				      SPI_MEM_OP_DUMMY(nor->read_dummy, 0),
3035 				      SPI_MEM_OP_DATA_IN(0, NULL, 0)),
3036 		.offset = 0,
3037 		.length = nor->params->size,
3038 	};
3039 	struct spi_mem_op *op = &info.op_tmpl;
3040 
3041 	spi_nor_spimem_setup_op(nor, op, nor->read_proto);
3042 
3043 	/* convert the dummy cycles to the number of bytes */
3044 	op->dummy.nbytes = (nor->read_dummy * op->dummy.buswidth) / 8;
3045 	if (spi_nor_protocol_is_dtr(nor->read_proto))
3046 		op->dummy.nbytes *= 2;
3047 
3048 	/*
3049 	 * Since spi_nor_spimem_setup_op() only sets buswidth when the number
3050 	 * of data bytes is non-zero, the data buswidth won't be set here. So,
3051 	 * do it explicitly.
3052 	 */
3053 	op->data.buswidth = spi_nor_get_protocol_data_nbits(nor->read_proto);
3054 
3055 	nor->dirmap.rdesc = devm_spi_mem_dirmap_create(nor->dev, nor->spimem,
3056 						       &info);
3057 	return PTR_ERR_OR_ZERO(nor->dirmap.rdesc);
3058 }
3059 
spi_nor_create_write_dirmap(struct spi_nor * nor)3060 static int spi_nor_create_write_dirmap(struct spi_nor *nor)
3061 {
3062 	struct spi_mem_dirmap_info info = {
3063 		.op_tmpl = SPI_MEM_OP(SPI_MEM_OP_CMD(nor->program_opcode, 0),
3064 				      SPI_MEM_OP_ADDR(nor->addr_nbytes, 0, 0),
3065 				      SPI_MEM_OP_NO_DUMMY,
3066 				      SPI_MEM_OP_DATA_OUT(0, NULL, 0)),
3067 		.offset = 0,
3068 		.length = nor->params->size,
3069 	};
3070 	struct spi_mem_op *op = &info.op_tmpl;
3071 
3072 	if (nor->program_opcode == SPINOR_OP_AAI_WP && nor->sst_write_second)
3073 		op->addr.nbytes = 0;
3074 
3075 	spi_nor_spimem_setup_op(nor, op, nor->write_proto);
3076 
3077 	/*
3078 	 * Since spi_nor_spimem_setup_op() only sets buswidth when the number
3079 	 * of data bytes is non-zero, the data buswidth won't be set here. So,
3080 	 * do it explicitly.
3081 	 */
3082 	op->data.buswidth = spi_nor_get_protocol_data_nbits(nor->write_proto);
3083 
3084 	nor->dirmap.wdesc = devm_spi_mem_dirmap_create(nor->dev, nor->spimem,
3085 						       &info);
3086 	return PTR_ERR_OR_ZERO(nor->dirmap.wdesc);
3087 }
3088 
spi_nor_probe(struct spi_mem * spimem)3089 static int spi_nor_probe(struct spi_mem *spimem)
3090 {
3091 	struct spi_device *spi = spimem->spi;
3092 	struct flash_platform_data *data = dev_get_platdata(&spi->dev);
3093 	struct spi_nor *nor;
3094 	/*
3095 	 * Enable all caps by default. The core will mask them after
3096 	 * checking what's really supported using spi_mem_supports_op().
3097 	 */
3098 	const struct spi_nor_hwcaps hwcaps = { .mask = SNOR_HWCAPS_ALL };
3099 	char *flash_name;
3100 	int ret;
3101 
3102 	nor = devm_kzalloc(&spi->dev, sizeof(*nor), GFP_KERNEL);
3103 	if (!nor)
3104 		return -ENOMEM;
3105 
3106 	nor->spimem = spimem;
3107 	nor->dev = &spi->dev;
3108 	spi_nor_set_flash_node(nor, spi->dev.of_node);
3109 
3110 	spi_mem_set_drvdata(spimem, nor);
3111 
3112 	if (data && data->name)
3113 		nor->mtd.name = data->name;
3114 
3115 	if (!nor->mtd.name)
3116 		nor->mtd.name = spi_mem_get_name(spimem);
3117 
3118 	/*
3119 	 * For some (historical?) reason many platforms provide two different
3120 	 * names in flash_platform_data: "name" and "type". Quite often name is
3121 	 * set to "m25p80" and then "type" provides a real chip name.
3122 	 * If that's the case, respect "type" and ignore a "name".
3123 	 */
3124 	if (data && data->type)
3125 		flash_name = data->type;
3126 	else if (!strcmp(spi->modalias, "spi-nor"))
3127 		flash_name = NULL; /* auto-detect */
3128 	else
3129 		flash_name = spi->modalias;
3130 
3131 	ret = spi_nor_scan(nor, flash_name, &hwcaps);
3132 	if (ret)
3133 		return ret;
3134 
3135 	spi_nor_debugfs_register(nor);
3136 
3137 	/*
3138 	 * None of the existing parts have > 512B pages, but let's play safe
3139 	 * and add this logic so that if anyone ever adds support for such
3140 	 * a NOR we don't end up with buffer overflows.
3141 	 */
3142 	if (nor->params->page_size > PAGE_SIZE) {
3143 		nor->bouncebuf_size = nor->params->page_size;
3144 		devm_kfree(nor->dev, nor->bouncebuf);
3145 		nor->bouncebuf = devm_kmalloc(nor->dev,
3146 					      nor->bouncebuf_size,
3147 					      GFP_KERNEL);
3148 		if (!nor->bouncebuf)
3149 			return -ENOMEM;
3150 	}
3151 
3152 	ret = spi_nor_create_read_dirmap(nor);
3153 	if (ret)
3154 		return ret;
3155 
3156 	ret = spi_nor_create_write_dirmap(nor);
3157 	if (ret)
3158 		return ret;
3159 
3160 	return mtd_device_register(&nor->mtd, data ? data->parts : NULL,
3161 				   data ? data->nr_parts : 0);
3162 }
3163 
spi_nor_remove(struct spi_mem * spimem)3164 static int spi_nor_remove(struct spi_mem *spimem)
3165 {
3166 	struct spi_nor *nor = spi_mem_get_drvdata(spimem);
3167 
3168 	spi_nor_restore(nor);
3169 
3170 	/* Clean up MTD stuff. */
3171 	return mtd_device_unregister(&nor->mtd);
3172 }
3173 
spi_nor_shutdown(struct spi_mem * spimem)3174 static void spi_nor_shutdown(struct spi_mem *spimem)
3175 {
3176 	struct spi_nor *nor = spi_mem_get_drvdata(spimem);
3177 
3178 	spi_nor_restore(nor);
3179 }
3180 
3181 /*
3182  * Do NOT add to this array without reading the following:
3183  *
3184  * Historically, many flash devices are bound to this driver by their name. But
3185  * since most of these flash are compatible to some extent, and their
3186  * differences can often be differentiated by the JEDEC read-ID command, we
3187  * encourage new users to add support to the spi-nor library, and simply bind
3188  * against a generic string here (e.g., "jedec,spi-nor").
3189  *
3190  * Many flash names are kept here in this list to keep them available
3191  * as module aliases for existing platforms.
3192  */
3193 static const struct spi_device_id spi_nor_dev_ids[] = {
3194 	/*
3195 	 * Allow non-DT platform devices to bind to the "spi-nor" modalias, and
3196 	 * hack around the fact that the SPI core does not provide uevent
3197 	 * matching for .of_match_table
3198 	 */
3199 	{"spi-nor"},
3200 
3201 	/*
3202 	 * Entries not used in DTs that should be safe to drop after replacing
3203 	 * them with "spi-nor" in platform data.
3204 	 */
3205 	{"s25sl064a"},	{"w25x16"},	{"m25p10"},	{"m25px64"},
3206 
3207 	/*
3208 	 * Entries that were used in DTs without "jedec,spi-nor" fallback and
3209 	 * should be kept for backward compatibility.
3210 	 */
3211 	{"at25df321a"},	{"at25df641"},	{"at26df081a"},
3212 	{"mx25l4005a"},	{"mx25l1606e"},	{"mx25l6405d"},	{"mx25l12805d"},
3213 	{"mx25l25635e"},{"mx66l51235l"},
3214 	{"n25q064"},	{"n25q128a11"},	{"n25q128a13"},	{"n25q512a"},
3215 	{"s25fl256s1"},	{"s25fl512s"},	{"s25sl12801"},	{"s25fl008k"},
3216 	{"s25fl064k"},
3217 	{"sst25vf040b"},{"sst25vf016b"},{"sst25vf032b"},{"sst25wf040"},
3218 	{"m25p40"},	{"m25p80"},	{"m25p16"},	{"m25p32"},
3219 	{"m25p64"},	{"m25p128"},
3220 	{"w25x80"},	{"w25x32"},	{"w25q32"},	{"w25q32dw"},
3221 	{"w25q80bl"},	{"w25q128"},	{"w25q256"},
3222 
3223 	/* Flashes that can't be detected using JEDEC */
3224 	{"m25p05-nonjedec"},	{"m25p10-nonjedec"},	{"m25p20-nonjedec"},
3225 	{"m25p40-nonjedec"},	{"m25p80-nonjedec"},	{"m25p16-nonjedec"},
3226 	{"m25p32-nonjedec"},	{"m25p64-nonjedec"},	{"m25p128-nonjedec"},
3227 
3228 	/* Everspin MRAMs (non-JEDEC) */
3229 	{ "mr25h128" }, /* 128 Kib, 40 MHz */
3230 	{ "mr25h256" }, /* 256 Kib, 40 MHz */
3231 	{ "mr25h10" },  /*   1 Mib, 40 MHz */
3232 	{ "mr25h40" },  /*   4 Mib, 40 MHz */
3233 
3234 	{ },
3235 };
3236 MODULE_DEVICE_TABLE(spi, spi_nor_dev_ids);
3237 
3238 static const struct of_device_id spi_nor_of_table[] = {
3239 	/*
3240 	 * Generic compatibility for SPI NOR that can be identified by the
3241 	 * JEDEC READ ID opcode (0x9F). Use this, if possible.
3242 	 */
3243 	{ .compatible = "jedec,spi-nor" },
3244 	{ /* sentinel */ },
3245 };
3246 MODULE_DEVICE_TABLE(of, spi_nor_of_table);
3247 
3248 /*
3249  * REVISIT: many of these chips have deep power-down modes, which
3250  * should clearly be entered on suspend() to minimize power use.
3251  * And also when they're otherwise idle...
3252  */
3253 static struct spi_mem_driver spi_nor_driver = {
3254 	.spidrv = {
3255 		.driver = {
3256 			.name = "spi-nor",
3257 			.of_match_table = spi_nor_of_table,
3258 			.dev_groups = spi_nor_sysfs_groups,
3259 		},
3260 		.id_table = spi_nor_dev_ids,
3261 	},
3262 	.probe = spi_nor_probe,
3263 	.remove = spi_nor_remove,
3264 	.shutdown = spi_nor_shutdown,
3265 };
3266 module_spi_mem_driver(spi_nor_driver);
3267 
3268 MODULE_LICENSE("GPL v2");
3269 MODULE_AUTHOR("Huang Shijie <shijie8@gmail.com>");
3270 MODULE_AUTHOR("Mike Lavender");
3271 MODULE_DESCRIPTION("framework for SPI NOR");
3272