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