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