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