• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  *  Overview:
3  *   This is the generic MTD driver for NAND flash devices. It should be
4  *   capable of working with almost all NAND chips currently available.
5  *
6  *	Additional technical information is available on
7  *	http://www.linux-mtd.infradead.org/doc/nand.html
8  *
9  *  Copyright (C) 2000 Steven J. Hill (sjhill@realitydiluted.com)
10  *		  2002-2006 Thomas Gleixner (tglx@linutronix.de)
11  *
12  *  Credits:
13  *	David Woodhouse for adding multichip support
14  *
15  *	Aleph One Ltd. and Toby Churchill Ltd. for supporting the
16  *	rework for 2K page size chips
17  *
18  *  TODO:
19  *	Enable cached programming for 2k page size chips
20  *	Check, if mtd->ecctype should be set to MTD_ECC_HW
21  *	if we have HW ECC support.
22  *	BBT table is not serialized, has to be fixed
23  *
24  * This program is free software; you can redistribute it and/or modify
25  * it under the terms of the GNU General Public License version 2 as
26  * published by the Free Software Foundation.
27  *
28  */
29 
30 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
31 #include <common.h>
32 #if CONFIG_IS_ENABLED(OF_CONTROL)
33 #include <fdtdec.h>
34 #endif
35 #include <malloc.h>
36 #include <watchdog.h>
37 #include <linux/err.h>
38 #include <linux/compat.h>
39 #include <linux/mtd/mtd.h>
40 #include <linux/mtd/rawnand.h>
41 #include <linux/mtd/nand_ecc.h>
42 #include <linux/mtd/nand_bch.h>
43 #ifdef CONFIG_MTD_PARTITIONS
44 #include <linux/mtd/partitions.h>
45 #endif
46 #include <asm/io.h>
47 #include <linux/errno.h>
48 
49 /* Define default oob placement schemes for large and small page devices */
50 #ifndef CONFIG_SYS_NAND_DRIVER_ECC_LAYOUT
51 static struct nand_ecclayout nand_oob_8 = {
52 	.eccbytes = 3,
53 	.eccpos = {0, 1, 2},
54 	.oobfree = {
55 		{.offset = 3,
56 		 .length = 2},
57 		{.offset = 6,
58 		 .length = 2} }
59 };
60 
61 static struct nand_ecclayout nand_oob_16 = {
62 	.eccbytes = 6,
63 	.eccpos = {0, 1, 2, 3, 6, 7},
64 	.oobfree = {
65 		{.offset = 8,
66 		 . length = 8} }
67 };
68 
69 static struct nand_ecclayout nand_oob_64 = {
70 	.eccbytes = 24,
71 	.eccpos = {
72 		   40, 41, 42, 43, 44, 45, 46, 47,
73 		   48, 49, 50, 51, 52, 53, 54, 55,
74 		   56, 57, 58, 59, 60, 61, 62, 63},
75 	.oobfree = {
76 		{.offset = 2,
77 		 .length = 38} }
78 };
79 
80 static struct nand_ecclayout nand_oob_128 = {
81 	.eccbytes = 48,
82 	.eccpos = {
83 		   80, 81, 82, 83, 84, 85, 86, 87,
84 		   88, 89, 90, 91, 92, 93, 94, 95,
85 		   96, 97, 98, 99, 100, 101, 102, 103,
86 		   104, 105, 106, 107, 108, 109, 110, 111,
87 		   112, 113, 114, 115, 116, 117, 118, 119,
88 		   120, 121, 122, 123, 124, 125, 126, 127},
89 	.oobfree = {
90 		{.offset = 2,
91 		 .length = 78} }
92 };
93 #endif
94 
95 static int nand_get_device(struct mtd_info *mtd, int new_state);
96 
97 static int nand_do_write_oob(struct mtd_info *mtd, loff_t to,
98 			     struct mtd_oob_ops *ops);
99 
100 /*
101  * For devices which display every fart in the system on a separate LED. Is
102  * compiled away when LED support is disabled.
103  */
104 DEFINE_LED_TRIGGER(nand_led_trigger);
105 
check_offs_len(struct mtd_info * mtd,loff_t ofs,uint64_t len)106 static int check_offs_len(struct mtd_info *mtd,
107 					loff_t ofs, uint64_t len)
108 {
109 	struct nand_chip *chip = mtd_to_nand(mtd);
110 	int ret = 0;
111 
112 	/* Start address must align on block boundary */
113 	if (ofs & ((1ULL << chip->phys_erase_shift) - 1)) {
114 		pr_debug("%s: unaligned address\n", __func__);
115 		ret = -EINVAL;
116 	}
117 
118 	/* Length must align on block boundary */
119 	if (len & ((1ULL << chip->phys_erase_shift) - 1)) {
120 		pr_debug("%s: length not block aligned\n", __func__);
121 		ret = -EINVAL;
122 	}
123 
124 	return ret;
125 }
126 
127 /**
128  * nand_release_device - [GENERIC] release chip
129  * @mtd: MTD device structure
130  *
131  * Release chip lock and wake up anyone waiting on the device.
132  */
nand_release_device(struct mtd_info * mtd)133 static void nand_release_device(struct mtd_info *mtd)
134 {
135 	struct nand_chip *chip = mtd_to_nand(mtd);
136 
137 	/* De-select the NAND device */
138 	chip->select_chip(mtd, -1);
139 }
140 
141 /**
142  * nand_read_byte - [DEFAULT] read one byte from the chip
143  * @mtd: MTD device structure
144  *
145  * Default read function for 8bit buswidth
146  */
nand_read_byte(struct mtd_info * mtd)147 uint8_t nand_read_byte(struct mtd_info *mtd)
148 {
149 	struct nand_chip *chip = mtd_to_nand(mtd);
150 	return readb(chip->IO_ADDR_R);
151 }
152 
153 /**
154  * nand_read_byte16 - [DEFAULT] read one byte endianness aware from the chip
155  * @mtd: MTD device structure
156  *
157  * Default read function for 16bit buswidth with endianness conversion.
158  *
159  */
nand_read_byte16(struct mtd_info * mtd)160 static uint8_t nand_read_byte16(struct mtd_info *mtd)
161 {
162 	struct nand_chip *chip = mtd_to_nand(mtd);
163 	return (uint8_t) cpu_to_le16(readw(chip->IO_ADDR_R));
164 }
165 
166 /**
167  * nand_read_word - [DEFAULT] read one word from the chip
168  * @mtd: MTD device structure
169  *
170  * Default read function for 16bit buswidth without endianness conversion.
171  */
nand_read_word(struct mtd_info * mtd)172 static u16 nand_read_word(struct mtd_info *mtd)
173 {
174 	struct nand_chip *chip = mtd_to_nand(mtd);
175 	return readw(chip->IO_ADDR_R);
176 }
177 
178 /**
179  * nand_select_chip - [DEFAULT] control CE line
180  * @mtd: MTD device structure
181  * @chipnr: chipnumber to select, -1 for deselect
182  *
183  * Default select function for 1 chip devices.
184  */
nand_select_chip(struct mtd_info * mtd,int chipnr)185 static void nand_select_chip(struct mtd_info *mtd, int chipnr)
186 {
187 	struct nand_chip *chip = mtd_to_nand(mtd);
188 
189 	switch (chipnr) {
190 	case -1:
191 		chip->cmd_ctrl(mtd, NAND_CMD_NONE, 0 | NAND_CTRL_CHANGE);
192 		break;
193 	case 0:
194 		break;
195 
196 	default:
197 		BUG();
198 	}
199 }
200 
201 /**
202  * nand_write_byte - [DEFAULT] write single byte to chip
203  * @mtd: MTD device structure
204  * @byte: value to write
205  *
206  * Default function to write a byte to I/O[7:0]
207  */
nand_write_byte(struct mtd_info * mtd,uint8_t byte)208 static void nand_write_byte(struct mtd_info *mtd, uint8_t byte)
209 {
210 	struct nand_chip *chip = mtd_to_nand(mtd);
211 
212 	chip->write_buf(mtd, &byte, 1);
213 }
214 
215 /**
216  * nand_write_byte16 - [DEFAULT] write single byte to a chip with width 16
217  * @mtd: MTD device structure
218  * @byte: value to write
219  *
220  * Default function to write a byte to I/O[7:0] on a 16-bit wide chip.
221  */
nand_write_byte16(struct mtd_info * mtd,uint8_t byte)222 static void nand_write_byte16(struct mtd_info *mtd, uint8_t byte)
223 {
224 	struct nand_chip *chip = mtd_to_nand(mtd);
225 	uint16_t word = byte;
226 
227 	/*
228 	 * It's not entirely clear what should happen to I/O[15:8] when writing
229 	 * a byte. The ONFi spec (Revision 3.1; 2012-09-19, Section 2.16) reads:
230 	 *
231 	 *    When the host supports a 16-bit bus width, only data is
232 	 *    transferred at the 16-bit width. All address and command line
233 	 *    transfers shall use only the lower 8-bits of the data bus. During
234 	 *    command transfers, the host may place any value on the upper
235 	 *    8-bits of the data bus. During address transfers, the host shall
236 	 *    set the upper 8-bits of the data bus to 00h.
237 	 *
238 	 * One user of the write_byte callback is nand_onfi_set_features. The
239 	 * four parameters are specified to be written to I/O[7:0], but this is
240 	 * neither an address nor a command transfer. Let's assume a 0 on the
241 	 * upper I/O lines is OK.
242 	 */
243 	chip->write_buf(mtd, (uint8_t *)&word, 2);
244 }
245 
iowrite8_rep(void * addr,const uint8_t * buf,int len)246 static void iowrite8_rep(void *addr, const uint8_t *buf, int len)
247 {
248 	int i;
249 
250 	for (i = 0; i < len; i++)
251 		writeb(buf[i], addr);
252 }
ioread8_rep(void * addr,uint8_t * buf,int len)253 static void ioread8_rep(void *addr, uint8_t *buf, int len)
254 {
255 	int i;
256 
257 	for (i = 0; i < len; i++)
258 		buf[i] = readb(addr);
259 }
260 
ioread16_rep(void * addr,void * buf,int len)261 static void ioread16_rep(void *addr, void *buf, int len)
262 {
263 	int i;
264  	u16 *p = (u16 *) buf;
265 
266 	for (i = 0; i < len; i++)
267 		p[i] = readw(addr);
268 }
269 
iowrite16_rep(void * addr,void * buf,int len)270 static void iowrite16_rep(void *addr, void *buf, int len)
271 {
272 	int i;
273         u16 *p = (u16 *) buf;
274 
275         for (i = 0; i < len; i++)
276                 writew(p[i], addr);
277 }
278 
279 /**
280  * nand_write_buf - [DEFAULT] write buffer to chip
281  * @mtd: MTD device structure
282  * @buf: data buffer
283  * @len: number of bytes to write
284  *
285  * Default write function for 8bit buswidth.
286  */
nand_write_buf(struct mtd_info * mtd,const uint8_t * buf,int len)287 void nand_write_buf(struct mtd_info *mtd, const uint8_t *buf, int len)
288 {
289 	struct nand_chip *chip = mtd_to_nand(mtd);
290 
291 	iowrite8_rep(chip->IO_ADDR_W, buf, len);
292 }
293 
294 /**
295  * nand_read_buf - [DEFAULT] read chip data into buffer
296  * @mtd: MTD device structure
297  * @buf: buffer to store date
298  * @len: number of bytes to read
299  *
300  * Default read function for 8bit buswidth.
301  */
nand_read_buf(struct mtd_info * mtd,uint8_t * buf,int len)302 void nand_read_buf(struct mtd_info *mtd, uint8_t *buf, int len)
303 {
304 	struct nand_chip *chip = mtd_to_nand(mtd);
305 
306 	ioread8_rep(chip->IO_ADDR_R, buf, len);
307 }
308 
309 /**
310  * nand_write_buf16 - [DEFAULT] write buffer to chip
311  * @mtd: MTD device structure
312  * @buf: data buffer
313  * @len: number of bytes to write
314  *
315  * Default write function for 16bit buswidth.
316  */
nand_write_buf16(struct mtd_info * mtd,const uint8_t * buf,int len)317 void nand_write_buf16(struct mtd_info *mtd, const uint8_t *buf, int len)
318 {
319 	struct nand_chip *chip = mtd_to_nand(mtd);
320 	u16 *p = (u16 *) buf;
321 
322 	iowrite16_rep(chip->IO_ADDR_W, p, len >> 1);
323 }
324 
325 /**
326  * nand_read_buf16 - [DEFAULT] read chip data into buffer
327  * @mtd: MTD device structure
328  * @buf: buffer to store date
329  * @len: number of bytes to read
330  *
331  * Default read function for 16bit buswidth.
332  */
nand_read_buf16(struct mtd_info * mtd,uint8_t * buf,int len)333 void nand_read_buf16(struct mtd_info *mtd, uint8_t *buf, int len)
334 {
335 	struct nand_chip *chip = mtd_to_nand(mtd);
336 	u16 *p = (u16 *) buf;
337 
338 	ioread16_rep(chip->IO_ADDR_R, p, len >> 1);
339 }
340 
341 /**
342  * nand_block_bad - [DEFAULT] Read bad block marker from the chip
343  * @mtd: MTD device structure
344  * @ofs: offset from device start
345  *
346  * Check, if the block is bad.
347  */
nand_block_bad(struct mtd_info * mtd,loff_t ofs)348 static int nand_block_bad(struct mtd_info *mtd, loff_t ofs)
349 {
350 	int page, res = 0, i = 0;
351 	struct nand_chip *chip = mtd_to_nand(mtd);
352 	u16 bad;
353 
354 	if (chip->bbt_options & NAND_BBT_SCANLASTPAGE)
355 		ofs += mtd->erasesize - mtd->writesize;
356 
357 	page = (int)(ofs >> chip->page_shift) & chip->pagemask;
358 
359 	do {
360 		if (chip->options & NAND_BUSWIDTH_16) {
361 			chip->cmdfunc(mtd, NAND_CMD_READOOB,
362 					chip->badblockpos & 0xFE, page);
363 			bad = cpu_to_le16(chip->read_word(mtd));
364 			if (chip->badblockpos & 0x1)
365 				bad >>= 8;
366 			else
367 				bad &= 0xFF;
368 		} else {
369 			chip->cmdfunc(mtd, NAND_CMD_READOOB, chip->badblockpos,
370 					page);
371 			bad = chip->read_byte(mtd);
372 		}
373 
374 		if (likely(chip->badblockbits == 8))
375 			res = bad != 0xFF;
376 		else
377 			res = hweight8(bad) < chip->badblockbits;
378 		ofs += mtd->writesize;
379 		page = (int)(ofs >> chip->page_shift) & chip->pagemask;
380 		i++;
381 	} while (!res && i < 2 && (chip->bbt_options & NAND_BBT_SCAN2NDPAGE));
382 
383 	return res;
384 }
385 
386 /**
387  * nand_default_block_markbad - [DEFAULT] mark a block bad via bad block marker
388  * @mtd: MTD device structure
389  * @ofs: offset from device start
390  *
391  * This is the default implementation, which can be overridden by a hardware
392  * specific driver. It provides the details for writing a bad block marker to a
393  * block.
394  */
nand_default_block_markbad(struct mtd_info * mtd,loff_t ofs)395 static int nand_default_block_markbad(struct mtd_info *mtd, loff_t ofs)
396 {
397 	struct nand_chip *chip = mtd_to_nand(mtd);
398 	struct mtd_oob_ops ops;
399 	uint8_t buf[2] = { 0, 0 };
400 	int ret = 0, res, i = 0;
401 
402 	memset(&ops, 0, sizeof(ops));
403 	ops.oobbuf = buf;
404 	ops.ooboffs = chip->badblockpos;
405 	if (chip->options & NAND_BUSWIDTH_16) {
406 		ops.ooboffs &= ~0x01;
407 		ops.len = ops.ooblen = 2;
408 	} else {
409 		ops.len = ops.ooblen = 1;
410 	}
411 	ops.mode = MTD_OPS_PLACE_OOB;
412 
413 	/* Write to first/last page(s) if necessary */
414 	if (chip->bbt_options & NAND_BBT_SCANLASTPAGE)
415 		ofs += mtd->erasesize - mtd->writesize;
416 	do {
417 		res = nand_do_write_oob(mtd, ofs, &ops);
418 		if (!ret)
419 			ret = res;
420 
421 		i++;
422 		ofs += mtd->writesize;
423 	} while ((chip->bbt_options & NAND_BBT_SCAN2NDPAGE) && i < 2);
424 
425 	return ret;
426 }
427 
428 /**
429  * nand_block_markbad_lowlevel - mark a block bad
430  * @mtd: MTD device structure
431  * @ofs: offset from device start
432  *
433  * This function performs the generic NAND bad block marking steps (i.e., bad
434  * block table(s) and/or marker(s)). We only allow the hardware driver to
435  * specify how to write bad block markers to OOB (chip->block_markbad).
436  *
437  * We try operations in the following order:
438  *  (1) erase the affected block, to allow OOB marker to be written cleanly
439  *  (2) write bad block marker to OOB area of affected block (unless flag
440  *      NAND_BBT_NO_OOB_BBM is present)
441  *  (3) update the BBT
442  * Note that we retain the first error encountered in (2) or (3), finish the
443  * procedures, and dump the error in the end.
444 */
nand_block_markbad_lowlevel(struct mtd_info * mtd,loff_t ofs)445 static int nand_block_markbad_lowlevel(struct mtd_info *mtd, loff_t ofs)
446 {
447 	struct nand_chip *chip = mtd_to_nand(mtd);
448 	int res, ret = 0;
449 
450 	if (!(chip->bbt_options & NAND_BBT_NO_OOB_BBM)) {
451 		struct erase_info einfo;
452 
453 		/* Attempt erase before marking OOB */
454 		memset(&einfo, 0, sizeof(einfo));
455 		einfo.mtd = mtd;
456 		einfo.addr = ofs;
457 		einfo.len = 1ULL << chip->phys_erase_shift;
458 		nand_erase_nand(mtd, &einfo, 0);
459 
460 		/* Write bad block marker to OOB */
461 		nand_get_device(mtd, FL_WRITING);
462 		ret = chip->block_markbad(mtd, ofs);
463 		nand_release_device(mtd);
464 	}
465 
466 	/* Mark block bad in BBT */
467 	if (chip->bbt) {
468 		res = nand_markbad_bbt(mtd, ofs);
469 		if (!ret)
470 			ret = res;
471 	}
472 
473 	if (!ret)
474 		mtd->ecc_stats.badblocks++;
475 
476 	return ret;
477 }
478 
479 /**
480  * nand_check_wp - [GENERIC] check if the chip is write protected
481  * @mtd: MTD device structure
482  *
483  * Check, if the device is write protected. The function expects, that the
484  * device is already selected.
485  */
nand_check_wp(struct mtd_info * mtd)486 static int nand_check_wp(struct mtd_info *mtd)
487 {
488 	struct nand_chip *chip = mtd_to_nand(mtd);
489 	u8 status;
490 	int ret;
491 
492 	/* Broken xD cards report WP despite being writable */
493 	if (chip->options & NAND_BROKEN_XD)
494 		return 0;
495 
496 	/* Check the WP bit */
497 	ret = nand_status_op(chip, &status);
498 	if (ret)
499 		return ret;
500 
501 	return status & NAND_STATUS_WP ? 0 : 1;
502 }
503 
504 /**
505  * nand_block_isreserved - [GENERIC] Check if a block is marked reserved.
506  * @mtd: MTD device structure
507  * @ofs: offset from device start
508  *
509  * Check if the block is marked as reserved.
510  */
nand_block_isreserved(struct mtd_info * mtd,loff_t ofs)511 static int nand_block_isreserved(struct mtd_info *mtd, loff_t ofs)
512 {
513 	struct nand_chip *chip = mtd_to_nand(mtd);
514 
515 	if (!chip->bbt)
516 		return 0;
517 	/* Return info from the table */
518 	return nand_isreserved_bbt(mtd, ofs);
519 }
520 
521 /**
522  * nand_block_checkbad - [GENERIC] Check if a block is marked bad
523  * @mtd: MTD device structure
524  * @ofs: offset from device start
525  * @allowbbt: 1, if its allowed to access the bbt area
526  *
527  * Check, if the block is bad. Either by reading the bad block table or
528  * calling of the scan function.
529  */
nand_block_checkbad(struct mtd_info * mtd,loff_t ofs,int allowbbt)530 static int nand_block_checkbad(struct mtd_info *mtd, loff_t ofs, int allowbbt)
531 {
532 	struct nand_chip *chip = mtd_to_nand(mtd);
533 
534 	if (!(chip->options & NAND_SKIP_BBTSCAN) &&
535 	    !(chip->options & NAND_BBT_SCANNED)) {
536 		chip->options |= NAND_BBT_SCANNED;
537 		chip->scan_bbt(mtd);
538 	}
539 
540 	if (!chip->bbt)
541 		return chip->block_bad(mtd, ofs);
542 
543 	/* Return info from the table */
544 	return nand_isbad_bbt(mtd, ofs, allowbbt);
545 }
546 
547 /**
548  * nand_wait_ready - [GENERIC] Wait for the ready pin after commands.
549  * @mtd: MTD device structure
550  *
551  * Wait for the ready pin after a command, and warn if a timeout occurs.
552  */
nand_wait_ready(struct mtd_info * mtd)553 void nand_wait_ready(struct mtd_info *mtd)
554 {
555 	struct nand_chip *chip = mtd_to_nand(mtd);
556 	u32 timeo = (CONFIG_SYS_HZ * 400) / 1000;
557 	u32 time_start;
558 
559 	time_start = get_timer(0);
560 	/* Wait until command is processed or timeout occurs */
561 	while (get_timer(time_start) < timeo) {
562 		if (chip->dev_ready)
563 			if (chip->dev_ready(mtd))
564 				break;
565 	}
566 
567 	if (!chip->dev_ready(mtd))
568 		pr_warn("timeout while waiting for chip to become ready\n");
569 }
570 EXPORT_SYMBOL_GPL(nand_wait_ready);
571 
572 /**
573  * nand_wait_status_ready - [GENERIC] Wait for the ready status after commands.
574  * @mtd: MTD device structure
575  * @timeo: Timeout in ms
576  *
577  * Wait for status ready (i.e. command done) or timeout.
578  */
nand_wait_status_ready(struct mtd_info * mtd,unsigned long timeo)579 static void nand_wait_status_ready(struct mtd_info *mtd, unsigned long timeo)
580 {
581 	register struct nand_chip *chip = mtd_to_nand(mtd);
582 	u32 time_start;
583 	int ret;
584 
585 	timeo = (CONFIG_SYS_HZ * timeo) / 1000;
586 	time_start = get_timer(0);
587 	while (get_timer(time_start) < timeo) {
588 		u8 status;
589 
590 		ret = nand_read_data_op(chip, &status, sizeof(status), true);
591 		if (ret)
592 			return;
593 
594 		if (status & NAND_STATUS_READY)
595 			break;
596 		WATCHDOG_RESET();
597 	}
598 };
599 
600 /**
601  * nand_command - [DEFAULT] Send command to NAND device
602  * @mtd: MTD device structure
603  * @command: the command to be sent
604  * @column: the column address for this command, -1 if none
605  * @page_addr: the page address for this command, -1 if none
606  *
607  * Send command to NAND device. This function is used for small page devices
608  * (512 Bytes per page).
609  */
nand_command(struct mtd_info * mtd,unsigned int command,int column,int page_addr)610 static void nand_command(struct mtd_info *mtd, unsigned int command,
611 			 int column, int page_addr)
612 {
613 	register struct nand_chip *chip = mtd_to_nand(mtd);
614 	int ctrl = NAND_CTRL_CLE | NAND_CTRL_CHANGE;
615 
616 	/* Write out the command to the device */
617 	if (command == NAND_CMD_SEQIN) {
618 		int readcmd;
619 
620 		if (column >= mtd->writesize) {
621 			/* OOB area */
622 			column -= mtd->writesize;
623 			readcmd = NAND_CMD_READOOB;
624 		} else if (column < 256) {
625 			/* First 256 bytes --> READ0 */
626 			readcmd = NAND_CMD_READ0;
627 		} else {
628 			column -= 256;
629 			readcmd = NAND_CMD_READ1;
630 		}
631 		chip->cmd_ctrl(mtd, readcmd, ctrl);
632 		ctrl &= ~NAND_CTRL_CHANGE;
633 	}
634 	chip->cmd_ctrl(mtd, command, ctrl);
635 
636 	/* Address cycle, when necessary */
637 	ctrl = NAND_CTRL_ALE | NAND_CTRL_CHANGE;
638 	/* Serially input address */
639 	if (column != -1) {
640 		/* Adjust columns for 16 bit buswidth */
641 		if (chip->options & NAND_BUSWIDTH_16 &&
642 				!nand_opcode_8bits(command))
643 			column >>= 1;
644 		chip->cmd_ctrl(mtd, column, ctrl);
645 		ctrl &= ~NAND_CTRL_CHANGE;
646 	}
647 	if (page_addr != -1) {
648 		chip->cmd_ctrl(mtd, page_addr, ctrl);
649 		ctrl &= ~NAND_CTRL_CHANGE;
650 		chip->cmd_ctrl(mtd, page_addr >> 8, ctrl);
651 		if (chip->options & NAND_ROW_ADDR_3)
652 			chip->cmd_ctrl(mtd, page_addr >> 16, ctrl);
653 	}
654 	chip->cmd_ctrl(mtd, NAND_CMD_NONE, NAND_NCE | NAND_CTRL_CHANGE);
655 
656 	/*
657 	 * Program and erase have their own busy handlers status and sequential
658 	 * in needs no delay
659 	 */
660 	switch (command) {
661 
662 	case NAND_CMD_PAGEPROG:
663 	case NAND_CMD_ERASE1:
664 	case NAND_CMD_ERASE2:
665 	case NAND_CMD_SEQIN:
666 	case NAND_CMD_STATUS:
667 	case NAND_CMD_READID:
668 	case NAND_CMD_SET_FEATURES:
669 		return;
670 
671 	case NAND_CMD_RESET:
672 		if (chip->dev_ready)
673 			break;
674 		udelay(chip->chip_delay);
675 		chip->cmd_ctrl(mtd, NAND_CMD_STATUS,
676 			       NAND_CTRL_CLE | NAND_CTRL_CHANGE);
677 		chip->cmd_ctrl(mtd,
678 			       NAND_CMD_NONE, NAND_NCE | NAND_CTRL_CHANGE);
679 		/* EZ-NAND can take upto 250ms as per ONFi v4.0 */
680 		nand_wait_status_ready(mtd, 250);
681 		return;
682 
683 		/* This applies to read commands */
684 	default:
685 		/*
686 		 * If we don't have access to the busy pin, we apply the given
687 		 * command delay
688 		 */
689 		if (!chip->dev_ready) {
690 			udelay(chip->chip_delay);
691 			return;
692 		}
693 	}
694 	/*
695 	 * Apply this short delay always to ensure that we do wait tWB in
696 	 * any case on any machine.
697 	 */
698 	ndelay(100);
699 
700 	nand_wait_ready(mtd);
701 }
702 
703 /**
704  * nand_command_lp - [DEFAULT] Send command to NAND large page device
705  * @mtd: MTD device structure
706  * @command: the command to be sent
707  * @column: the column address for this command, -1 if none
708  * @page_addr: the page address for this command, -1 if none
709  *
710  * Send command to NAND device. This is the version for the new large page
711  * devices. We don't have the separate regions as we have in the small page
712  * devices. We must emulate NAND_CMD_READOOB to keep the code compatible.
713  */
nand_command_lp(struct mtd_info * mtd,unsigned int command,int column,int page_addr)714 static void nand_command_lp(struct mtd_info *mtd, unsigned int command,
715 			    int column, int page_addr)
716 {
717 	register struct nand_chip *chip = mtd_to_nand(mtd);
718 
719 	/* Emulate NAND_CMD_READOOB */
720 	if (command == NAND_CMD_READOOB) {
721 		column += mtd->writesize;
722 		command = NAND_CMD_READ0;
723 	}
724 
725 	/* Command latch cycle */
726 	chip->cmd_ctrl(mtd, command, NAND_NCE | NAND_CLE | NAND_CTRL_CHANGE);
727 
728 	if (column != -1 || page_addr != -1) {
729 		int ctrl = NAND_CTRL_CHANGE | NAND_NCE | NAND_ALE;
730 
731 		/* Serially input address */
732 		if (column != -1) {
733 			/* Adjust columns for 16 bit buswidth */
734 			if (chip->options & NAND_BUSWIDTH_16 &&
735 					!nand_opcode_8bits(command))
736 				column >>= 1;
737 			chip->cmd_ctrl(mtd, column, ctrl);
738 			ctrl &= ~NAND_CTRL_CHANGE;
739 			chip->cmd_ctrl(mtd, column >> 8, ctrl);
740 		}
741 		if (page_addr != -1) {
742 			chip->cmd_ctrl(mtd, page_addr, ctrl);
743 			chip->cmd_ctrl(mtd, page_addr >> 8,
744 				       NAND_NCE | NAND_ALE);
745 			if (chip->options & NAND_ROW_ADDR_3)
746 				chip->cmd_ctrl(mtd, page_addr >> 16,
747 					       NAND_NCE | NAND_ALE);
748 		}
749 	}
750 	chip->cmd_ctrl(mtd, NAND_CMD_NONE, NAND_NCE | NAND_CTRL_CHANGE);
751 
752 	/*
753 	 * Program and erase have their own busy handlers status, sequential
754 	 * in and status need no delay.
755 	 */
756 	switch (command) {
757 
758 	case NAND_CMD_CACHEDPROG:
759 	case NAND_CMD_PAGEPROG:
760 	case NAND_CMD_ERASE1:
761 	case NAND_CMD_ERASE2:
762 	case NAND_CMD_SEQIN:
763 	case NAND_CMD_RNDIN:
764 	case NAND_CMD_STATUS:
765 	case NAND_CMD_READID:
766 	case NAND_CMD_SET_FEATURES:
767 		return;
768 
769 	case NAND_CMD_RESET:
770 		if (chip->dev_ready)
771 			break;
772 		udelay(chip->chip_delay);
773 		chip->cmd_ctrl(mtd, NAND_CMD_STATUS,
774 			       NAND_NCE | NAND_CLE | NAND_CTRL_CHANGE);
775 		chip->cmd_ctrl(mtd, NAND_CMD_NONE,
776 			       NAND_NCE | NAND_CTRL_CHANGE);
777 		/* EZ-NAND can take upto 250ms as per ONFi v4.0 */
778 		nand_wait_status_ready(mtd, 250);
779 		return;
780 
781 	case NAND_CMD_RNDOUT:
782 		/* No ready / busy check necessary */
783 		chip->cmd_ctrl(mtd, NAND_CMD_RNDOUTSTART,
784 			       NAND_NCE | NAND_CLE | NAND_CTRL_CHANGE);
785 		chip->cmd_ctrl(mtd, NAND_CMD_NONE,
786 			       NAND_NCE | NAND_CTRL_CHANGE);
787 		return;
788 
789 	case NAND_CMD_READ0:
790 		chip->cmd_ctrl(mtd, NAND_CMD_READSTART,
791 			       NAND_NCE | NAND_CLE | NAND_CTRL_CHANGE);
792 		chip->cmd_ctrl(mtd, NAND_CMD_NONE,
793 			       NAND_NCE | NAND_CTRL_CHANGE);
794 
795 		/* This applies to read commands */
796 	default:
797 		/*
798 		 * If we don't have access to the busy pin, we apply the given
799 		 * command delay.
800 		 */
801 		if (!chip->dev_ready) {
802 			udelay(chip->chip_delay);
803 			return;
804 		}
805 	}
806 
807 	/*
808 	 * Apply this short delay always to ensure that we do wait tWB in
809 	 * any case on any machine.
810 	 */
811 	ndelay(100);
812 
813 	nand_wait_ready(mtd);
814 }
815 
816 /**
817  * panic_nand_get_device - [GENERIC] Get chip for selected access
818  * @chip: the nand chip descriptor
819  * @mtd: MTD device structure
820  * @new_state: the state which is requested
821  *
822  * Used when in panic, no locks are taken.
823  */
panic_nand_get_device(struct nand_chip * chip,struct mtd_info * mtd,int new_state)824 static void panic_nand_get_device(struct nand_chip *chip,
825 		      struct mtd_info *mtd, int new_state)
826 {
827 	/* Hardware controller shared among independent devices */
828 	chip->controller->active = chip;
829 	chip->state = new_state;
830 }
831 
832 /**
833  * nand_get_device - [GENERIC] Get chip for selected access
834  * @mtd: MTD device structure
835  * @new_state: the state which is requested
836  *
837  * Get the device and lock it for exclusive access
838  */
839 static int
nand_get_device(struct mtd_info * mtd,int new_state)840 nand_get_device(struct mtd_info *mtd, int new_state)
841 {
842 	struct nand_chip *chip = mtd_to_nand(mtd);
843 	chip->state = new_state;
844 	return 0;
845 }
846 
847 /**
848  * panic_nand_wait - [GENERIC] wait until the command is done
849  * @mtd: MTD device structure
850  * @chip: NAND chip structure
851  * @timeo: timeout
852  *
853  * Wait for command done. This is a helper function for nand_wait used when
854  * we are in interrupt context. May happen when in panic and trying to write
855  * an oops through mtdoops.
856  */
panic_nand_wait(struct mtd_info * mtd,struct nand_chip * chip,unsigned long timeo)857 static void panic_nand_wait(struct mtd_info *mtd, struct nand_chip *chip,
858 			    unsigned long timeo)
859 {
860 	int i;
861 	for (i = 0; i < timeo; i++) {
862 		if (chip->dev_ready) {
863 			if (chip->dev_ready(mtd))
864 				break;
865 		} else {
866 			int ret;
867 			u8 status;
868 
869 			ret = nand_read_data_op(chip, &status, sizeof(status),
870 						true);
871 			if (ret)
872 				return;
873 
874 			if (status & NAND_STATUS_READY)
875 				break;
876 		}
877 		mdelay(1);
878 	}
879 }
880 
881 /**
882  * nand_wait - [DEFAULT] wait until the command is done
883  * @mtd: MTD device structure
884  * @chip: NAND chip structure
885  *
886  * Wait for command done. This applies to erase and program only.
887  */
nand_wait(struct mtd_info * mtd,struct nand_chip * chip)888 static int nand_wait(struct mtd_info *mtd, struct nand_chip *chip)
889 {
890 	unsigned long timeo = 400;
891 	u8 status;
892 	int ret;
893 
894 	led_trigger_event(nand_led_trigger, LED_FULL);
895 
896 	/*
897 	 * Apply this short delay always to ensure that we do wait tWB in any
898 	 * case on any machine.
899 	 */
900 	ndelay(100);
901 
902 	ret = nand_status_op(chip, NULL);
903 	if (ret)
904 		return ret;
905 
906  	u32 timer = (CONFIG_SYS_HZ * timeo) / 1000;
907  	u32 time_start;
908 
909  	time_start = get_timer(0);
910  	while (get_timer(time_start) < timer) {
911 		if (chip->dev_ready) {
912 			if (chip->dev_ready(mtd))
913 				break;
914 		} else {
915 			ret = nand_read_data_op(chip, &status,
916 						sizeof(status), true);
917 			if (ret)
918 				return ret;
919 
920 			if (status & NAND_STATUS_READY)
921 				break;
922 		}
923 	}
924 	led_trigger_event(nand_led_trigger, LED_OFF);
925 
926 	ret = nand_read_data_op(chip, &status, sizeof(status), true);
927 	if (ret)
928 		return ret;
929 
930 	/* This can happen if in case of timeout or buggy dev_ready */
931 	WARN_ON(!(status & NAND_STATUS_READY));
932 	return status;
933 }
934 
935 /**
936  * nand_reset_data_interface - Reset data interface and timings
937  * @chip: The NAND chip
938  * @chipnr: Internal die id
939  *
940  * Reset the Data interface and timings to ONFI mode 0.
941  *
942  * Returns 0 for success or negative error code otherwise.
943  */
nand_reset_data_interface(struct nand_chip * chip,int chipnr)944 static int nand_reset_data_interface(struct nand_chip *chip, int chipnr)
945 {
946 	struct mtd_info *mtd = nand_to_mtd(chip);
947 	const struct nand_data_interface *conf;
948 	int ret;
949 
950 	if (!chip->setup_data_interface)
951 		return 0;
952 
953 	/*
954 	 * The ONFI specification says:
955 	 * "
956 	 * To transition from NV-DDR or NV-DDR2 to the SDR data
957 	 * interface, the host shall use the Reset (FFh) command
958 	 * using SDR timing mode 0. A device in any timing mode is
959 	 * required to recognize Reset (FFh) command issued in SDR
960 	 * timing mode 0.
961 	 * "
962 	 *
963 	 * Configure the data interface in SDR mode and set the
964 	 * timings to timing mode 0.
965 	 */
966 
967 	conf = nand_get_default_data_interface();
968 	ret = chip->setup_data_interface(mtd, chipnr, conf);
969 	if (ret)
970 		pr_err("Failed to configure data interface to SDR timing mode 0\n");
971 
972 	return ret;
973 }
974 
975 /**
976  * nand_setup_data_interface - Setup the best data interface and timings
977  * @chip: The NAND chip
978  * @chipnr: Internal die id
979  *
980  * Find and configure the best data interface and NAND timings supported by
981  * the chip and the driver.
982  * First tries to retrieve supported timing modes from ONFI information,
983  * and if the NAND chip does not support ONFI, relies on the
984  * ->onfi_timing_mode_default specified in the nand_ids table.
985  *
986  * Returns 0 for success or negative error code otherwise.
987  */
nand_setup_data_interface(struct nand_chip * chip,int chipnr)988 static int nand_setup_data_interface(struct nand_chip *chip, int chipnr)
989 {
990 	struct mtd_info *mtd = nand_to_mtd(chip);
991 	int ret;
992 
993 	if (!chip->setup_data_interface || !chip->data_interface)
994 		return 0;
995 
996 	/*
997 	 * Ensure the timing mode has been changed on the chip side
998 	 * before changing timings on the controller side.
999 	 */
1000 	if (chip->onfi_version) {
1001 		u8 tmode_param[ONFI_SUBFEATURE_PARAM_LEN] = {
1002 			chip->onfi_timing_mode_default,
1003 		};
1004 
1005 		ret = chip->onfi_set_features(mtd, chip,
1006 				ONFI_FEATURE_ADDR_TIMING_MODE,
1007 				tmode_param);
1008 		if (ret)
1009 			goto err;
1010 	}
1011 
1012 	ret = chip->setup_data_interface(mtd, chipnr, chip->data_interface);
1013 err:
1014 	return ret;
1015 }
1016 
1017 /**
1018  * nand_init_data_interface - find the best data interface and timings
1019  * @chip: The NAND chip
1020  *
1021  * Find the best data interface and NAND timings supported by the chip
1022  * and the driver.
1023  * First tries to retrieve supported timing modes from ONFI information,
1024  * and if the NAND chip does not support ONFI, relies on the
1025  * ->onfi_timing_mode_default specified in the nand_ids table. After this
1026  * function nand_chip->data_interface is initialized with the best timing mode
1027  * available.
1028  *
1029  * Returns 0 for success or negative error code otherwise.
1030  */
nand_init_data_interface(struct nand_chip * chip)1031 static int nand_init_data_interface(struct nand_chip *chip)
1032 {
1033 	struct mtd_info *mtd = nand_to_mtd(chip);
1034 	int modes, mode, ret;
1035 
1036 	if (!chip->setup_data_interface)
1037 		return 0;
1038 
1039 	/*
1040 	 * First try to identify the best timings from ONFI parameters and
1041 	 * if the NAND does not support ONFI, fallback to the default ONFI
1042 	 * timing mode.
1043 	 */
1044 	modes = onfi_get_async_timing_mode(chip);
1045 	if (modes == ONFI_TIMING_MODE_UNKNOWN) {
1046 		if (!chip->onfi_timing_mode_default)
1047 			return 0;
1048 
1049 		modes = GENMASK(chip->onfi_timing_mode_default, 0);
1050 	}
1051 
1052 	chip->data_interface = kzalloc(sizeof(*chip->data_interface),
1053 				       GFP_KERNEL);
1054 	if (!chip->data_interface)
1055 		return -ENOMEM;
1056 
1057 	for (mode = fls(modes) - 1; mode >= 0; mode--) {
1058 		ret = onfi_init_data_interface(chip, chip->data_interface,
1059 					       NAND_SDR_IFACE, mode);
1060 		if (ret)
1061 			continue;
1062 
1063 		/* Pass -1 to only */
1064 		ret = chip->setup_data_interface(mtd,
1065 						 NAND_DATA_IFACE_CHECK_ONLY,
1066 						 chip->data_interface);
1067 		if (!ret) {
1068 			chip->onfi_timing_mode_default = mode;
1069 			break;
1070 		}
1071 	}
1072 
1073 	return 0;
1074 }
1075 
nand_release_data_interface(struct nand_chip * chip)1076 static void __maybe_unused nand_release_data_interface(struct nand_chip *chip)
1077 {
1078 	kfree(chip->data_interface);
1079 }
1080 
1081 /**
1082  * nand_read_page_op - Do a READ PAGE operation
1083  * @chip: The NAND chip
1084  * @page: page to read
1085  * @offset_in_page: offset within the page
1086  * @buf: buffer used to store the data
1087  * @len: length of the buffer
1088  *
1089  * This function issues a READ PAGE operation.
1090  * This function does not select/unselect the CS line.
1091  *
1092  * Returns 0 on success, a negative error code otherwise.
1093  */
nand_read_page_op(struct nand_chip * chip,unsigned int page,unsigned int offset_in_page,void * buf,unsigned int len)1094 int nand_read_page_op(struct nand_chip *chip, unsigned int page,
1095 		      unsigned int offset_in_page, void *buf, unsigned int len)
1096 {
1097 	struct mtd_info *mtd = nand_to_mtd(chip);
1098 
1099 	if (len && !buf)
1100 		return -EINVAL;
1101 
1102 	if (offset_in_page + len > mtd->writesize + mtd->oobsize)
1103 		return -EINVAL;
1104 
1105 	chip->cmdfunc(mtd, NAND_CMD_READ0, offset_in_page, page);
1106 	if (len)
1107 		chip->read_buf(mtd, buf, len);
1108 
1109 	return 0;
1110 }
1111 EXPORT_SYMBOL_GPL(nand_read_page_op);
1112 
1113 /**
1114  * nand_read_param_page_op - Do a READ PARAMETER PAGE operation
1115  * @chip: The NAND chip
1116  * @page: parameter page to read
1117  * @buf: buffer used to store the data
1118  * @len: length of the buffer
1119  *
1120  * This function issues a READ PARAMETER PAGE operation.
1121  * This function does not select/unselect the CS line.
1122  *
1123  * Returns 0 on success, a negative error code otherwise.
1124  */
nand_read_param_page_op(struct nand_chip * chip,u8 page,void * buf,unsigned int len)1125 static int nand_read_param_page_op(struct nand_chip *chip, u8 page, void *buf,
1126 				   unsigned int len)
1127 {
1128 	struct mtd_info *mtd = nand_to_mtd(chip);
1129 	unsigned int i;
1130 	u8 *p = buf;
1131 
1132 	if (len && !buf)
1133 		return -EINVAL;
1134 
1135 	chip->cmdfunc(mtd, NAND_CMD_PARAM, page, -1);
1136 	for (i = 0; i < len; i++)
1137 		p[i] = chip->read_byte(mtd);
1138 
1139 	return 0;
1140 }
1141 
1142 /**
1143  * nand_change_read_column_op - Do a CHANGE READ COLUMN operation
1144  * @chip: The NAND chip
1145  * @offset_in_page: offset within the page
1146  * @buf: buffer used to store the data
1147  * @len: length of the buffer
1148  * @force_8bit: force 8-bit bus access
1149  *
1150  * This function issues a CHANGE READ COLUMN operation.
1151  * This function does not select/unselect the CS line.
1152  *
1153  * Returns 0 on success, a negative error code otherwise.
1154  */
nand_change_read_column_op(struct nand_chip * chip,unsigned int offset_in_page,void * buf,unsigned int len,bool force_8bit)1155 int nand_change_read_column_op(struct nand_chip *chip,
1156 			       unsigned int offset_in_page, void *buf,
1157 			       unsigned int len, bool force_8bit)
1158 {
1159 	struct mtd_info *mtd = nand_to_mtd(chip);
1160 
1161 	if (len && !buf)
1162 		return -EINVAL;
1163 
1164 	if (offset_in_page + len > mtd->writesize + mtd->oobsize)
1165 		return -EINVAL;
1166 
1167 	chip->cmdfunc(mtd, NAND_CMD_RNDOUT, offset_in_page, -1);
1168 	if (len)
1169 		chip->read_buf(mtd, buf, len);
1170 
1171 	return 0;
1172 }
1173 EXPORT_SYMBOL_GPL(nand_change_read_column_op);
1174 
1175 /**
1176  * nand_read_oob_op - Do a READ OOB operation
1177  * @chip: The NAND chip
1178  * @page: page to read
1179  * @offset_in_oob: offset within the OOB area
1180  * @buf: buffer used to store the data
1181  * @len: length of the buffer
1182  *
1183  * This function issues a READ OOB operation.
1184  * This function does not select/unselect the CS line.
1185  *
1186  * Returns 0 on success, a negative error code otherwise.
1187  */
nand_read_oob_op(struct nand_chip * chip,unsigned int page,unsigned int offset_in_oob,void * buf,unsigned int len)1188 int nand_read_oob_op(struct nand_chip *chip, unsigned int page,
1189 		     unsigned int offset_in_oob, void *buf, unsigned int len)
1190 {
1191 	struct mtd_info *mtd = nand_to_mtd(chip);
1192 
1193 	if (len && !buf)
1194 		return -EINVAL;
1195 
1196 	if (offset_in_oob + len > mtd->oobsize)
1197 		return -EINVAL;
1198 
1199 	chip->cmdfunc(mtd, NAND_CMD_READOOB, offset_in_oob, page);
1200 	if (len)
1201 		chip->read_buf(mtd, buf, len);
1202 
1203 	return 0;
1204 }
1205 EXPORT_SYMBOL_GPL(nand_read_oob_op);
1206 
1207 /**
1208  * nand_prog_page_begin_op - starts a PROG PAGE operation
1209  * @chip: The NAND chip
1210  * @page: page to write
1211  * @offset_in_page: offset within the page
1212  * @buf: buffer containing the data to write to the page
1213  * @len: length of the buffer
1214  *
1215  * This function issues the first half of a PROG PAGE operation.
1216  * This function does not select/unselect the CS line.
1217  *
1218  * Returns 0 on success, a negative error code otherwise.
1219  */
nand_prog_page_begin_op(struct nand_chip * chip,unsigned int page,unsigned int offset_in_page,const void * buf,unsigned int len)1220 int nand_prog_page_begin_op(struct nand_chip *chip, unsigned int page,
1221 			    unsigned int offset_in_page, const void *buf,
1222 			    unsigned int len)
1223 {
1224 	struct mtd_info *mtd = nand_to_mtd(chip);
1225 
1226 	if (len && !buf)
1227 		return -EINVAL;
1228 
1229 	if (offset_in_page + len > mtd->writesize + mtd->oobsize)
1230 		return -EINVAL;
1231 
1232 	chip->cmdfunc(mtd, NAND_CMD_SEQIN, offset_in_page, page);
1233 
1234 	if (buf)
1235 		chip->write_buf(mtd, buf, len);
1236 
1237 	return 0;
1238 }
1239 EXPORT_SYMBOL_GPL(nand_prog_page_begin_op);
1240 
1241 /**
1242  * nand_prog_page_end_op - ends a PROG PAGE operation
1243  * @chip: The NAND chip
1244  *
1245  * This function issues the second half of a PROG PAGE operation.
1246  * This function does not select/unselect the CS line.
1247  *
1248  * Returns 0 on success, a negative error code otherwise.
1249  */
nand_prog_page_end_op(struct nand_chip * chip)1250 int nand_prog_page_end_op(struct nand_chip *chip)
1251 {
1252 	struct mtd_info *mtd = nand_to_mtd(chip);
1253 	int status;
1254 
1255 	chip->cmdfunc(mtd, NAND_CMD_PAGEPROG, -1, -1);
1256 
1257 	status = chip->waitfunc(mtd, chip);
1258 	if (status & NAND_STATUS_FAIL)
1259 		return -EIO;
1260 
1261 	return 0;
1262 }
1263 EXPORT_SYMBOL_GPL(nand_prog_page_end_op);
1264 
1265 /**
1266  * nand_prog_page_op - Do a full PROG PAGE operation
1267  * @chip: The NAND chip
1268  * @page: page to write
1269  * @offset_in_page: offset within the page
1270  * @buf: buffer containing the data to write to the page
1271  * @len: length of the buffer
1272  *
1273  * This function issues a full PROG PAGE operation.
1274  * This function does not select/unselect the CS line.
1275  *
1276  * Returns 0 on success, a negative error code otherwise.
1277  */
nand_prog_page_op(struct nand_chip * chip,unsigned int page,unsigned int offset_in_page,const void * buf,unsigned int len)1278 int nand_prog_page_op(struct nand_chip *chip, unsigned int page,
1279 		      unsigned int offset_in_page, const void *buf,
1280 		      unsigned int len)
1281 {
1282 	struct mtd_info *mtd = nand_to_mtd(chip);
1283 	int status;
1284 
1285 	if (!len || !buf)
1286 		return -EINVAL;
1287 
1288 	if (offset_in_page + len > mtd->writesize + mtd->oobsize)
1289 		return -EINVAL;
1290 
1291 	chip->cmdfunc(mtd, NAND_CMD_SEQIN, offset_in_page, page);
1292 	chip->write_buf(mtd, buf, len);
1293 	chip->cmdfunc(mtd, NAND_CMD_PAGEPROG, -1, -1);
1294 
1295 	status = chip->waitfunc(mtd, chip);
1296 	if (status & NAND_STATUS_FAIL)
1297 		return -EIO;
1298 
1299 	return 0;
1300 }
1301 EXPORT_SYMBOL_GPL(nand_prog_page_op);
1302 
1303 /**
1304  * nand_change_write_column_op - Do a CHANGE WRITE COLUMN operation
1305  * @chip: The NAND chip
1306  * @offset_in_page: offset within the page
1307  * @buf: buffer containing the data to send to the NAND
1308  * @len: length of the buffer
1309  * @force_8bit: force 8-bit bus access
1310  *
1311  * This function issues a CHANGE WRITE COLUMN operation.
1312  * This function does not select/unselect the CS line.
1313  *
1314  * Returns 0 on success, a negative error code otherwise.
1315  */
nand_change_write_column_op(struct nand_chip * chip,unsigned int offset_in_page,const void * buf,unsigned int len,bool force_8bit)1316 int nand_change_write_column_op(struct nand_chip *chip,
1317 				unsigned int offset_in_page,
1318 				const void *buf, unsigned int len,
1319 				bool force_8bit)
1320 {
1321 	struct mtd_info *mtd = nand_to_mtd(chip);
1322 
1323 	if (len && !buf)
1324 		return -EINVAL;
1325 
1326 	if (offset_in_page + len > mtd->writesize + mtd->oobsize)
1327 		return -EINVAL;
1328 
1329 	chip->cmdfunc(mtd, NAND_CMD_RNDIN, offset_in_page, -1);
1330 	if (len)
1331 		chip->write_buf(mtd, buf, len);
1332 
1333 	return 0;
1334 }
1335 EXPORT_SYMBOL_GPL(nand_change_write_column_op);
1336 
1337 /**
1338  * nand_readid_op - Do a READID operation
1339  * @chip: The NAND chip
1340  * @addr: address cycle to pass after the READID command
1341  * @buf: buffer used to store the ID
1342  * @len: length of the buffer
1343  *
1344  * This function sends a READID command and reads back the ID returned by the
1345  * NAND.
1346  * This function does not select/unselect the CS line.
1347  *
1348  * Returns 0 on success, a negative error code otherwise.
1349  */
nand_readid_op(struct nand_chip * chip,u8 addr,void * buf,unsigned int len)1350 int nand_readid_op(struct nand_chip *chip, u8 addr, void *buf,
1351 		   unsigned int len)
1352 {
1353 	struct mtd_info *mtd = nand_to_mtd(chip);
1354 	unsigned int i;
1355 	u8 *id = buf;
1356 
1357 	if (len && !buf)
1358 		return -EINVAL;
1359 
1360 	chip->cmdfunc(mtd, NAND_CMD_READID, addr, -1);
1361 
1362 	for (i = 0; i < len; i++)
1363 		id[i] = chip->read_byte(mtd);
1364 
1365 	return 0;
1366 }
1367 EXPORT_SYMBOL_GPL(nand_readid_op);
1368 
1369 /**
1370  * nand_status_op - Do a STATUS operation
1371  * @chip: The NAND chip
1372  * @status: out variable to store the NAND status
1373  *
1374  * This function sends a STATUS command and reads back the status returned by
1375  * the NAND.
1376  * This function does not select/unselect the CS line.
1377  *
1378  * Returns 0 on success, a negative error code otherwise.
1379  */
nand_status_op(struct nand_chip * chip,u8 * status)1380 int nand_status_op(struct nand_chip *chip, u8 *status)
1381 {
1382 	struct mtd_info *mtd = nand_to_mtd(chip);
1383 
1384 	chip->cmdfunc(mtd, NAND_CMD_STATUS, -1, -1);
1385 	if (status)
1386 		*status = chip->read_byte(mtd);
1387 
1388 	return 0;
1389 }
1390 EXPORT_SYMBOL_GPL(nand_status_op);
1391 
1392 /**
1393  * nand_exit_status_op - Exit a STATUS operation
1394  * @chip: The NAND chip
1395  *
1396  * This function sends a READ0 command to cancel the effect of the STATUS
1397  * command to avoid reading only the status until a new read command is sent.
1398  *
1399  * This function does not select/unselect the CS line.
1400  *
1401  * Returns 0 on success, a negative error code otherwise.
1402  */
nand_exit_status_op(struct nand_chip * chip)1403 int nand_exit_status_op(struct nand_chip *chip)
1404 {
1405 	struct mtd_info *mtd = nand_to_mtd(chip);
1406 
1407 	chip->cmdfunc(mtd, NAND_CMD_READ0, -1, -1);
1408 
1409 	return 0;
1410 }
1411 EXPORT_SYMBOL_GPL(nand_exit_status_op);
1412 
1413 /**
1414  * nand_erase_op - Do an erase operation
1415  * @chip: The NAND chip
1416  * @eraseblock: block to erase
1417  *
1418  * This function sends an ERASE command and waits for the NAND to be ready
1419  * before returning.
1420  * This function does not select/unselect the CS line.
1421  *
1422  * Returns 0 on success, a negative error code otherwise.
1423  */
nand_erase_op(struct nand_chip * chip,unsigned int eraseblock)1424 int nand_erase_op(struct nand_chip *chip, unsigned int eraseblock)
1425 {
1426 	struct mtd_info *mtd = nand_to_mtd(chip);
1427 	unsigned int page = eraseblock <<
1428 			    (chip->phys_erase_shift - chip->page_shift);
1429 	int status;
1430 
1431 	chip->cmdfunc(mtd, NAND_CMD_ERASE1, -1, page);
1432 	chip->cmdfunc(mtd, NAND_CMD_ERASE2, -1, -1);
1433 
1434 	status = chip->waitfunc(mtd, chip);
1435 	if (status < 0)
1436 		return status;
1437 
1438 	if (status & NAND_STATUS_FAIL)
1439 		return -EIO;
1440 
1441 	return 0;
1442 }
1443 EXPORT_SYMBOL_GPL(nand_erase_op);
1444 
1445 /**
1446  * nand_set_features_op - Do a SET FEATURES operation
1447  * @chip: The NAND chip
1448  * @feature: feature id
1449  * @data: 4 bytes of data
1450  *
1451  * This function sends a SET FEATURES command and waits for the NAND to be
1452  * ready before returning.
1453  * This function does not select/unselect the CS line.
1454  *
1455  * Returns 0 on success, a negative error code otherwise.
1456  */
nand_set_features_op(struct nand_chip * chip,u8 feature,const void * data)1457 static int nand_set_features_op(struct nand_chip *chip, u8 feature,
1458 				const void *data)
1459 {
1460 	struct mtd_info *mtd = nand_to_mtd(chip);
1461 	const u8 *params = data;
1462 	int i, status;
1463 
1464 	chip->cmdfunc(mtd, NAND_CMD_SET_FEATURES, feature, -1);
1465 	for (i = 0; i < ONFI_SUBFEATURE_PARAM_LEN; ++i)
1466 		chip->write_byte(mtd, params[i]);
1467 
1468 	status = chip->waitfunc(mtd, chip);
1469 	if (status & NAND_STATUS_FAIL)
1470 		return -EIO;
1471 
1472 	return 0;
1473 }
1474 
1475 /**
1476  * nand_get_features_op - Do a GET FEATURES operation
1477  * @chip: The NAND chip
1478  * @feature: feature id
1479  * @data: 4 bytes of data
1480  *
1481  * This function sends a GET FEATURES command and waits for the NAND to be
1482  * ready before returning.
1483  * This function does not select/unselect the CS line.
1484  *
1485  * Returns 0 on success, a negative error code otherwise.
1486  */
nand_get_features_op(struct nand_chip * chip,u8 feature,void * data)1487 static int nand_get_features_op(struct nand_chip *chip, u8 feature,
1488 				void *data)
1489 {
1490 	struct mtd_info *mtd = nand_to_mtd(chip);
1491 	u8 *params = data;
1492 	int i;
1493 
1494 	chip->cmdfunc(mtd, NAND_CMD_GET_FEATURES, feature, -1);
1495 	for (i = 0; i < ONFI_SUBFEATURE_PARAM_LEN; ++i)
1496 		params[i] = chip->read_byte(mtd);
1497 
1498 	return 0;
1499 }
1500 
1501 /**
1502  * nand_reset_op - Do a reset operation
1503  * @chip: The NAND chip
1504  *
1505  * This function sends a RESET command and waits for the NAND to be ready
1506  * before returning.
1507  * This function does not select/unselect the CS line.
1508  *
1509  * Returns 0 on success, a negative error code otherwise.
1510  */
nand_reset_op(struct nand_chip * chip)1511 int nand_reset_op(struct nand_chip *chip)
1512 {
1513 	struct mtd_info *mtd = nand_to_mtd(chip);
1514 
1515 	chip->cmdfunc(mtd, NAND_CMD_RESET, -1, -1);
1516 
1517 	return 0;
1518 }
1519 EXPORT_SYMBOL_GPL(nand_reset_op);
1520 
1521 /**
1522  * nand_read_data_op - Read data from the NAND
1523  * @chip: The NAND chip
1524  * @buf: buffer used to store the data
1525  * @len: length of the buffer
1526  * @force_8bit: force 8-bit bus access
1527  *
1528  * This function does a raw data read on the bus. Usually used after launching
1529  * another NAND operation like nand_read_page_op().
1530  * This function does not select/unselect the CS line.
1531  *
1532  * Returns 0 on success, a negative error code otherwise.
1533  */
nand_read_data_op(struct nand_chip * chip,void * buf,unsigned int len,bool force_8bit)1534 int nand_read_data_op(struct nand_chip *chip, void *buf, unsigned int len,
1535 		      bool force_8bit)
1536 {
1537 	struct mtd_info *mtd = nand_to_mtd(chip);
1538 
1539 	if (!len || !buf)
1540 		return -EINVAL;
1541 
1542 	if (force_8bit) {
1543 		u8 *p = buf;
1544 		unsigned int i;
1545 
1546 		for (i = 0; i < len; i++)
1547 			p[i] = chip->read_byte(mtd);
1548 	} else {
1549 		chip->read_buf(mtd, buf, len);
1550 	}
1551 
1552 	return 0;
1553 }
1554 EXPORT_SYMBOL_GPL(nand_read_data_op);
1555 
1556 /**
1557  * nand_write_data_op - Write data from the NAND
1558  * @chip: The NAND chip
1559  * @buf: buffer containing the data to send on the bus
1560  * @len: length of the buffer
1561  * @force_8bit: force 8-bit bus access
1562  *
1563  * This function does a raw data write on the bus. Usually used after launching
1564  * another NAND operation like nand_write_page_begin_op().
1565  * This function does not select/unselect the CS line.
1566  *
1567  * Returns 0 on success, a negative error code otherwise.
1568  */
nand_write_data_op(struct nand_chip * chip,const void * buf,unsigned int len,bool force_8bit)1569 int nand_write_data_op(struct nand_chip *chip, const void *buf,
1570 		       unsigned int len, bool force_8bit)
1571 {
1572 	struct mtd_info *mtd = nand_to_mtd(chip);
1573 
1574 	if (!len || !buf)
1575 		return -EINVAL;
1576 
1577 	if (force_8bit) {
1578 		const u8 *p = buf;
1579 		unsigned int i;
1580 
1581 		for (i = 0; i < len; i++)
1582 			chip->write_byte(mtd, p[i]);
1583 	} else {
1584 		chip->write_buf(mtd, buf, len);
1585 	}
1586 
1587 	return 0;
1588 }
1589 EXPORT_SYMBOL_GPL(nand_write_data_op);
1590 
1591 /**
1592  * nand_reset - Reset and initialize a NAND device
1593  * @chip: The NAND chip
1594  * @chipnr: Internal die id
1595  *
1596  * Returns 0 for success or negative error code otherwise
1597  */
nand_reset(struct nand_chip * chip,int chipnr)1598 int nand_reset(struct nand_chip *chip, int chipnr)
1599 {
1600 	struct mtd_info *mtd = nand_to_mtd(chip);
1601 	int ret;
1602 
1603 	ret = nand_reset_data_interface(chip, chipnr);
1604 	if (ret)
1605 		return ret;
1606 
1607 	/*
1608 	 * The CS line has to be released before we can apply the new NAND
1609 	 * interface settings, hence this weird ->select_chip() dance.
1610 	 */
1611 	chip->select_chip(mtd, chipnr);
1612 	ret = nand_reset_op(chip);
1613 	chip->select_chip(mtd, -1);
1614 	if (ret)
1615 		return ret;
1616 
1617 	chip->select_chip(mtd, chipnr);
1618 	ret = nand_setup_data_interface(chip, chipnr);
1619 	chip->select_chip(mtd, -1);
1620 	if (ret)
1621 		return ret;
1622 
1623 	return 0;
1624 }
1625 
1626 /**
1627  * nand_check_erased_buf - check if a buffer contains (almost) only 0xff data
1628  * @buf: buffer to test
1629  * @len: buffer length
1630  * @bitflips_threshold: maximum number of bitflips
1631  *
1632  * Check if a buffer contains only 0xff, which means the underlying region
1633  * has been erased and is ready to be programmed.
1634  * The bitflips_threshold specify the maximum number of bitflips before
1635  * considering the region is not erased.
1636  * Note: The logic of this function has been extracted from the memweight
1637  * implementation, except that nand_check_erased_buf function exit before
1638  * testing the whole buffer if the number of bitflips exceed the
1639  * bitflips_threshold value.
1640  *
1641  * Returns a positive number of bitflips less than or equal to
1642  * bitflips_threshold, or -ERROR_CODE for bitflips in excess of the
1643  * threshold.
1644  */
nand_check_erased_buf(void * buf,int len,int bitflips_threshold)1645 static int nand_check_erased_buf(void *buf, int len, int bitflips_threshold)
1646 {
1647 	const unsigned char *bitmap = buf;
1648 	int bitflips = 0;
1649 	int weight;
1650 
1651 	for (; len && ((uintptr_t)bitmap) % sizeof(long);
1652 	     len--, bitmap++) {
1653 		weight = hweight8(*bitmap);
1654 		bitflips += BITS_PER_BYTE - weight;
1655 		if (unlikely(bitflips > bitflips_threshold))
1656 			return -EBADMSG;
1657 	}
1658 
1659 	for (; len >= 4; len -= 4, bitmap += 4) {
1660 		weight = hweight32(*((u32 *)bitmap));
1661 		bitflips += 32 - weight;
1662 		if (unlikely(bitflips > bitflips_threshold))
1663 			return -EBADMSG;
1664 	}
1665 
1666 	for (; len > 0; len--, bitmap++) {
1667 		weight = hweight8(*bitmap);
1668 		bitflips += BITS_PER_BYTE - weight;
1669 		if (unlikely(bitflips > bitflips_threshold))
1670 			return -EBADMSG;
1671 	}
1672 
1673 	return bitflips;
1674 }
1675 
1676 /**
1677  * nand_check_erased_ecc_chunk - check if an ECC chunk contains (almost) only
1678  *				 0xff data
1679  * @data: data buffer to test
1680  * @datalen: data length
1681  * @ecc: ECC buffer
1682  * @ecclen: ECC length
1683  * @extraoob: extra OOB buffer
1684  * @extraooblen: extra OOB length
1685  * @bitflips_threshold: maximum number of bitflips
1686  *
1687  * Check if a data buffer and its associated ECC and OOB data contains only
1688  * 0xff pattern, which means the underlying region has been erased and is
1689  * ready to be programmed.
1690  * The bitflips_threshold specify the maximum number of bitflips before
1691  * considering the region as not erased.
1692  *
1693  * Note:
1694  * 1/ ECC algorithms are working on pre-defined block sizes which are usually
1695  *    different from the NAND page size. When fixing bitflips, ECC engines will
1696  *    report the number of errors per chunk, and the NAND core infrastructure
1697  *    expect you to return the maximum number of bitflips for the whole page.
1698  *    This is why you should always use this function on a single chunk and
1699  *    not on the whole page. After checking each chunk you should update your
1700  *    max_bitflips value accordingly.
1701  * 2/ When checking for bitflips in erased pages you should not only check
1702  *    the payload data but also their associated ECC data, because a user might
1703  *    have programmed almost all bits to 1 but a few. In this case, we
1704  *    shouldn't consider the chunk as erased, and checking ECC bytes prevent
1705  *    this case.
1706  * 3/ The extraoob argument is optional, and should be used if some of your OOB
1707  *    data are protected by the ECC engine.
1708  *    It could also be used if you support subpages and want to attach some
1709  *    extra OOB data to an ECC chunk.
1710  *
1711  * Returns a positive number of bitflips less than or equal to
1712  * bitflips_threshold, or -ERROR_CODE for bitflips in excess of the
1713  * threshold. In case of success, the passed buffers are filled with 0xff.
1714  */
nand_check_erased_ecc_chunk(void * data,int datalen,void * ecc,int ecclen,void * extraoob,int extraooblen,int bitflips_threshold)1715 int nand_check_erased_ecc_chunk(void *data, int datalen,
1716 				void *ecc, int ecclen,
1717 				void *extraoob, int extraooblen,
1718 				int bitflips_threshold)
1719 {
1720 	int data_bitflips = 0, ecc_bitflips = 0, extraoob_bitflips = 0;
1721 
1722 	data_bitflips = nand_check_erased_buf(data, datalen,
1723 					      bitflips_threshold);
1724 	if (data_bitflips < 0)
1725 		return data_bitflips;
1726 
1727 	bitflips_threshold -= data_bitflips;
1728 
1729 	ecc_bitflips = nand_check_erased_buf(ecc, ecclen, bitflips_threshold);
1730 	if (ecc_bitflips < 0)
1731 		return ecc_bitflips;
1732 
1733 	bitflips_threshold -= ecc_bitflips;
1734 
1735 	extraoob_bitflips = nand_check_erased_buf(extraoob, extraooblen,
1736 						  bitflips_threshold);
1737 	if (extraoob_bitflips < 0)
1738 		return extraoob_bitflips;
1739 
1740 	if (data_bitflips)
1741 		memset(data, 0xff, datalen);
1742 
1743 	if (ecc_bitflips)
1744 		memset(ecc, 0xff, ecclen);
1745 
1746 	if (extraoob_bitflips)
1747 		memset(extraoob, 0xff, extraooblen);
1748 
1749 	return data_bitflips + ecc_bitflips + extraoob_bitflips;
1750 }
1751 EXPORT_SYMBOL(nand_check_erased_ecc_chunk);
1752 
1753 /**
1754  * nand_read_page_raw - [INTERN] read raw page data without ecc
1755  * @mtd: mtd info structure
1756  * @chip: nand chip info structure
1757  * @buf: buffer to store read data
1758  * @oob_required: caller requires OOB data read to chip->oob_poi
1759  * @page: page number to read
1760  *
1761  * Not for syndrome calculating ECC controllers, which use a special oob layout.
1762  */
nand_read_page_raw(struct mtd_info * mtd,struct nand_chip * chip,uint8_t * buf,int oob_required,int page)1763 static int nand_read_page_raw(struct mtd_info *mtd, struct nand_chip *chip,
1764 			      uint8_t *buf, int oob_required, int page)
1765 {
1766 	int ret;
1767 
1768 	ret = nand_read_data_op(chip, buf, mtd->writesize, false);
1769 	if (ret)
1770 		return ret;
1771 
1772 	if (oob_required) {
1773 		ret = nand_read_data_op(chip, chip->oob_poi, mtd->oobsize,
1774 					false);
1775 		if (ret)
1776 			return ret;
1777 	}
1778 
1779 	return 0;
1780 }
1781 
1782 /**
1783  * nand_read_page_raw_syndrome - [INTERN] read raw page data without ecc
1784  * @mtd: mtd info structure
1785  * @chip: nand chip info structure
1786  * @buf: buffer to store read data
1787  * @oob_required: caller requires OOB data read to chip->oob_poi
1788  * @page: page number to read
1789  *
1790  * We need a special oob layout and handling even when OOB isn't used.
1791  */
nand_read_page_raw_syndrome(struct mtd_info * mtd,struct nand_chip * chip,uint8_t * buf,int oob_required,int page)1792 static int nand_read_page_raw_syndrome(struct mtd_info *mtd,
1793 				       struct nand_chip *chip, uint8_t *buf,
1794 				       int oob_required, int page)
1795 {
1796 	int eccsize = chip->ecc.size;
1797 	int eccbytes = chip->ecc.bytes;
1798 	uint8_t *oob = chip->oob_poi;
1799 	int steps, size, ret;
1800 
1801 	for (steps = chip->ecc.steps; steps > 0; steps--) {
1802 		ret = nand_read_data_op(chip, buf, eccsize, false);
1803 		if (ret)
1804 			return ret;
1805 
1806 		buf += eccsize;
1807 
1808 		if (chip->ecc.prepad) {
1809 			ret = nand_read_data_op(chip, oob, chip->ecc.prepad,
1810 						false);
1811 			if (ret)
1812 				return ret;
1813 
1814 			oob += chip->ecc.prepad;
1815 		}
1816 
1817 		ret = nand_read_data_op(chip, oob, eccbytes, false);
1818 		if (ret)
1819 			return ret;
1820 
1821 		oob += eccbytes;
1822 
1823 		if (chip->ecc.postpad) {
1824 			ret = nand_read_data_op(chip, oob, chip->ecc.postpad,
1825 						false);
1826 			if (ret)
1827 				return ret;
1828 
1829 			oob += chip->ecc.postpad;
1830 		}
1831 	}
1832 
1833 	size = mtd->oobsize - (oob - chip->oob_poi);
1834 	if (size) {
1835 		ret = nand_read_data_op(chip, oob, size, false);
1836 		if (ret)
1837 			return ret;
1838 	}
1839 
1840 	return 0;
1841 }
1842 
1843 /**
1844  * nand_read_page_swecc - [REPLACEABLE] software ECC based page read function
1845  * @mtd: mtd info structure
1846  * @chip: nand chip info structure
1847  * @buf: buffer to store read data
1848  * @oob_required: caller requires OOB data read to chip->oob_poi
1849  * @page: page number to read
1850  */
nand_read_page_swecc(struct mtd_info * mtd,struct nand_chip * chip,uint8_t * buf,int oob_required,int page)1851 static int nand_read_page_swecc(struct mtd_info *mtd, struct nand_chip *chip,
1852 				uint8_t *buf, int oob_required, int page)
1853 {
1854 	int i, eccsize = chip->ecc.size;
1855 	int eccbytes = chip->ecc.bytes;
1856 	int eccsteps = chip->ecc.steps;
1857 	uint8_t *p = buf;
1858 	uint8_t *ecc_calc = chip->buffers->ecccalc;
1859 	uint8_t *ecc_code = chip->buffers->ecccode;
1860 	uint32_t *eccpos = chip->ecc.layout->eccpos;
1861 	unsigned int max_bitflips = 0;
1862 
1863 	chip->ecc.read_page_raw(mtd, chip, buf, 1, page);
1864 
1865 	for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize)
1866 		chip->ecc.calculate(mtd, p, &ecc_calc[i]);
1867 
1868 	for (i = 0; i < chip->ecc.total; i++)
1869 		ecc_code[i] = chip->oob_poi[eccpos[i]];
1870 
1871 	eccsteps = chip->ecc.steps;
1872 	p = buf;
1873 
1874 	for (i = 0 ; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
1875 		int stat;
1876 
1877 		stat = chip->ecc.correct(mtd, p, &ecc_code[i], &ecc_calc[i]);
1878 		if (stat < 0) {
1879 			mtd->ecc_stats.failed++;
1880 		} else {
1881 			mtd->ecc_stats.corrected += stat;
1882 			max_bitflips = max_t(unsigned int, max_bitflips, stat);
1883 		}
1884 	}
1885 	return max_bitflips;
1886 }
1887 
1888 /**
1889  * nand_read_subpage - [REPLACEABLE] ECC based sub-page read function
1890  * @mtd: mtd info structure
1891  * @chip: nand chip info structure
1892  * @data_offs: offset of requested data within the page
1893  * @readlen: data length
1894  * @bufpoi: buffer to store read data
1895  * @page: page number to read
1896  */
nand_read_subpage(struct mtd_info * mtd,struct nand_chip * chip,uint32_t data_offs,uint32_t readlen,uint8_t * bufpoi,int page)1897 static int nand_read_subpage(struct mtd_info *mtd, struct nand_chip *chip,
1898 			uint32_t data_offs, uint32_t readlen, uint8_t *bufpoi,
1899 			int page)
1900 {
1901 	int start_step, end_step, num_steps;
1902 	uint32_t *eccpos = chip->ecc.layout->eccpos;
1903 	uint8_t *p;
1904 	int data_col_addr, i, gaps = 0;
1905 	int datafrag_len, eccfrag_len, aligned_len, aligned_pos;
1906 	int busw = (chip->options & NAND_BUSWIDTH_16) ? 2 : 1;
1907 	int index;
1908 	unsigned int max_bitflips = 0;
1909 	int ret;
1910 
1911 	/* Column address within the page aligned to ECC size (256bytes) */
1912 	start_step = data_offs / chip->ecc.size;
1913 	end_step = (data_offs + readlen - 1) / chip->ecc.size;
1914 	num_steps = end_step - start_step + 1;
1915 	index = start_step * chip->ecc.bytes;
1916 
1917 	/* Data size aligned to ECC ecc.size */
1918 	datafrag_len = num_steps * chip->ecc.size;
1919 	eccfrag_len = num_steps * chip->ecc.bytes;
1920 
1921 	data_col_addr = start_step * chip->ecc.size;
1922 	/* If we read not a page aligned data */
1923 	if (data_col_addr != 0)
1924 		chip->cmdfunc(mtd, NAND_CMD_RNDOUT, data_col_addr, -1);
1925 
1926 	p = bufpoi + data_col_addr;
1927 	ret = nand_read_data_op(chip, p, datafrag_len, false);
1928 	if (ret)
1929 		return ret;
1930 
1931 	/* Calculate ECC */
1932 	for (i = 0; i < eccfrag_len ; i += chip->ecc.bytes, p += chip->ecc.size)
1933 		chip->ecc.calculate(mtd, p, &chip->buffers->ecccalc[i]);
1934 
1935 	/*
1936 	 * The performance is faster if we position offsets according to
1937 	 * ecc.pos. Let's make sure that there are no gaps in ECC positions.
1938 	 */
1939 	for (i = 0; i < eccfrag_len - 1; i++) {
1940 		if (eccpos[i + index] + 1 != eccpos[i + index + 1]) {
1941 			gaps = 1;
1942 			break;
1943 		}
1944 	}
1945 	if (gaps) {
1946 		ret = nand_change_read_column_op(chip, mtd->writesize,
1947 						 chip->oob_poi, mtd->oobsize,
1948 						 false);
1949 		if (ret)
1950 			return ret;
1951 	} else {
1952 		/*
1953 		 * Send the command to read the particular ECC bytes take care
1954 		 * about buswidth alignment in read_buf.
1955 		 */
1956 		aligned_pos = eccpos[index] & ~(busw - 1);
1957 		aligned_len = eccfrag_len;
1958 		if (eccpos[index] & (busw - 1))
1959 			aligned_len++;
1960 		if (eccpos[index + (num_steps * chip->ecc.bytes)] & (busw - 1))
1961 			aligned_len++;
1962 
1963 		ret = nand_change_read_column_op(chip,
1964 						 mtd->writesize + aligned_pos,
1965 						 &chip->oob_poi[aligned_pos],
1966 						 aligned_len, false);
1967 		if (ret)
1968 			return ret;
1969 	}
1970 
1971 	for (i = 0; i < eccfrag_len; i++)
1972 		chip->buffers->ecccode[i] = chip->oob_poi[eccpos[i + index]];
1973 
1974 	p = bufpoi + data_col_addr;
1975 	for (i = 0; i < eccfrag_len ; i += chip->ecc.bytes, p += chip->ecc.size) {
1976 		int stat;
1977 
1978 		stat = chip->ecc.correct(mtd, p,
1979 			&chip->buffers->ecccode[i], &chip->buffers->ecccalc[i]);
1980 		if (stat == -EBADMSG &&
1981 		    (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
1982 			/* check for empty pages with bitflips */
1983 			stat = nand_check_erased_ecc_chunk(p, chip->ecc.size,
1984 						&chip->buffers->ecccode[i],
1985 						chip->ecc.bytes,
1986 						NULL, 0,
1987 						chip->ecc.strength);
1988 		}
1989 
1990 		if (stat < 0) {
1991 			mtd->ecc_stats.failed++;
1992 		} else {
1993 			mtd->ecc_stats.corrected += stat;
1994 			max_bitflips = max_t(unsigned int, max_bitflips, stat);
1995 		}
1996 	}
1997 	return max_bitflips;
1998 }
1999 
2000 /**
2001  * nand_read_page_hwecc - [REPLACEABLE] hardware ECC based page read function
2002  * @mtd: mtd info structure
2003  * @chip: nand chip info structure
2004  * @buf: buffer to store read data
2005  * @oob_required: caller requires OOB data read to chip->oob_poi
2006  * @page: page number to read
2007  *
2008  * Not for syndrome calculating ECC controllers which need a special oob layout.
2009  */
nand_read_page_hwecc(struct mtd_info * mtd,struct nand_chip * chip,uint8_t * buf,int oob_required,int page)2010 static int nand_read_page_hwecc(struct mtd_info *mtd, struct nand_chip *chip,
2011 				uint8_t *buf, int oob_required, int page)
2012 {
2013 	int i, eccsize = chip->ecc.size;
2014 	int eccbytes = chip->ecc.bytes;
2015 	int eccsteps = chip->ecc.steps;
2016 	uint8_t *p = buf;
2017 	uint8_t *ecc_calc = chip->buffers->ecccalc;
2018 	uint8_t *ecc_code = chip->buffers->ecccode;
2019 	uint32_t *eccpos = chip->ecc.layout->eccpos;
2020 	unsigned int max_bitflips = 0;
2021 	int ret;
2022 
2023 	for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
2024 		chip->ecc.hwctl(mtd, NAND_ECC_READ);
2025 
2026 		ret = nand_read_data_op(chip, p, eccsize, false);
2027 		if (ret)
2028 			return ret;
2029 
2030 		chip->ecc.calculate(mtd, p, &ecc_calc[i]);
2031 	}
2032 
2033 	ret = nand_read_data_op(chip, chip->oob_poi, mtd->oobsize, false);
2034 	if (ret)
2035 		return ret;
2036 
2037 	for (i = 0; i < chip->ecc.total; i++)
2038 		ecc_code[i] = chip->oob_poi[eccpos[i]];
2039 
2040 	eccsteps = chip->ecc.steps;
2041 	p = buf;
2042 
2043 	for (i = 0 ; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
2044 		int stat;
2045 
2046 		stat = chip->ecc.correct(mtd, p, &ecc_code[i], &ecc_calc[i]);
2047 		if (stat == -EBADMSG &&
2048 		    (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
2049 			/* check for empty pages with bitflips */
2050 			stat = nand_check_erased_ecc_chunk(p, eccsize,
2051 						&ecc_code[i], eccbytes,
2052 						NULL, 0,
2053 						chip->ecc.strength);
2054 		}
2055 
2056 		if (stat < 0) {
2057 			mtd->ecc_stats.failed++;
2058 		} else {
2059 			mtd->ecc_stats.corrected += stat;
2060 			max_bitflips = max_t(unsigned int, max_bitflips, stat);
2061 		}
2062 	}
2063 	return max_bitflips;
2064 }
2065 
2066 /**
2067  * nand_read_page_hwecc_oob_first - [REPLACEABLE] hw ecc, read oob first
2068  * @mtd: mtd info structure
2069  * @chip: nand chip info structure
2070  * @buf: buffer to store read data
2071  * @oob_required: caller requires OOB data read to chip->oob_poi
2072  * @page: page number to read
2073  *
2074  * Hardware ECC for large page chips, require OOB to be read first. For this
2075  * ECC mode, the write_page method is re-used from ECC_HW. These methods
2076  * read/write ECC from the OOB area, unlike the ECC_HW_SYNDROME support with
2077  * multiple ECC steps, follows the "infix ECC" scheme and reads/writes ECC from
2078  * the data area, by overwriting the NAND manufacturer bad block markings.
2079  */
nand_read_page_hwecc_oob_first(struct mtd_info * mtd,struct nand_chip * chip,uint8_t * buf,int oob_required,int page)2080 static int nand_read_page_hwecc_oob_first(struct mtd_info *mtd,
2081 	struct nand_chip *chip, uint8_t *buf, int oob_required, int page)
2082 {
2083 	int i, eccsize = chip->ecc.size;
2084 	int eccbytes = chip->ecc.bytes;
2085 	int eccsteps = chip->ecc.steps;
2086 	uint8_t *p = buf;
2087 	uint8_t *ecc_code = chip->buffers->ecccode;
2088 	uint32_t *eccpos = chip->ecc.layout->eccpos;
2089 	uint8_t *ecc_calc = chip->buffers->ecccalc;
2090 	unsigned int max_bitflips = 0;
2091 	int ret;
2092 
2093 	/* Read the OOB area first */
2094 	ret = nand_read_oob_op(chip, page, 0, chip->oob_poi, mtd->oobsize);
2095 	if (ret)
2096 		return ret;
2097 
2098 	ret = nand_read_page_op(chip, page, 0, NULL, 0);
2099 	if (ret)
2100 		return ret;
2101 
2102 	for (i = 0; i < chip->ecc.total; i++)
2103 		ecc_code[i] = chip->oob_poi[eccpos[i]];
2104 
2105 	for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
2106 		int stat;
2107 
2108 		chip->ecc.hwctl(mtd, NAND_ECC_READ);
2109 
2110 		ret = nand_read_data_op(chip, p, eccsize, false);
2111 		if (ret)
2112 			return ret;
2113 
2114 		chip->ecc.calculate(mtd, p, &ecc_calc[i]);
2115 
2116 		stat = chip->ecc.correct(mtd, p, &ecc_code[i], NULL);
2117 		if (stat == -EBADMSG &&
2118 		    (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
2119 			/* check for empty pages with bitflips */
2120 			stat = nand_check_erased_ecc_chunk(p, eccsize,
2121 						&ecc_code[i], eccbytes,
2122 						NULL, 0,
2123 						chip->ecc.strength);
2124 		}
2125 
2126 		if (stat < 0) {
2127 			mtd->ecc_stats.failed++;
2128 		} else {
2129 			mtd->ecc_stats.corrected += stat;
2130 			max_bitflips = max_t(unsigned int, max_bitflips, stat);
2131 		}
2132 	}
2133 	return max_bitflips;
2134 }
2135 
2136 /**
2137  * nand_read_page_syndrome - [REPLACEABLE] hardware ECC syndrome based page read
2138  * @mtd: mtd info structure
2139  * @chip: nand chip info structure
2140  * @buf: buffer to store read data
2141  * @oob_required: caller requires OOB data read to chip->oob_poi
2142  * @page: page number to read
2143  *
2144  * The hw generator calculates the error syndrome automatically. Therefore we
2145  * need a special oob layout and handling.
2146  */
nand_read_page_syndrome(struct mtd_info * mtd,struct nand_chip * chip,uint8_t * buf,int oob_required,int page)2147 static int nand_read_page_syndrome(struct mtd_info *mtd, struct nand_chip *chip,
2148 				   uint8_t *buf, int oob_required, int page)
2149 {
2150 	int ret, i, eccsize = chip->ecc.size;
2151 	int eccbytes = chip->ecc.bytes;
2152 	int eccsteps = chip->ecc.steps;
2153 	int eccpadbytes = eccbytes + chip->ecc.prepad + chip->ecc.postpad;
2154 	uint8_t *p = buf;
2155 	uint8_t *oob = chip->oob_poi;
2156 	unsigned int max_bitflips = 0;
2157 
2158 	for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
2159 		int stat;
2160 
2161 		chip->ecc.hwctl(mtd, NAND_ECC_READ);
2162 
2163 		ret = nand_read_data_op(chip, p, eccsize, false);
2164 		if (ret)
2165 			return ret;
2166 
2167 		if (chip->ecc.prepad) {
2168 			ret = nand_read_data_op(chip, oob, chip->ecc.prepad,
2169 						false);
2170 			if (ret)
2171 				return ret;
2172 
2173 			oob += chip->ecc.prepad;
2174 		}
2175 
2176 		chip->ecc.hwctl(mtd, NAND_ECC_READSYN);
2177 
2178 		ret = nand_read_data_op(chip, oob, eccbytes, false);
2179 		if (ret)
2180 			return ret;
2181 
2182 		stat = chip->ecc.correct(mtd, p, oob, NULL);
2183 
2184 		oob += eccbytes;
2185 
2186 		if (chip->ecc.postpad) {
2187 			ret = nand_read_data_op(chip, oob, chip->ecc.postpad,
2188 						false);
2189 			if (ret)
2190 				return ret;
2191 
2192 			oob += chip->ecc.postpad;
2193 		}
2194 
2195 		if (stat == -EBADMSG &&
2196 		    (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
2197 			/* check for empty pages with bitflips */
2198 			stat = nand_check_erased_ecc_chunk(p, chip->ecc.size,
2199 							   oob - eccpadbytes,
2200 							   eccpadbytes,
2201 							   NULL, 0,
2202 							   chip->ecc.strength);
2203 		}
2204 
2205 		if (stat < 0) {
2206 			mtd->ecc_stats.failed++;
2207 		} else {
2208 			mtd->ecc_stats.corrected += stat;
2209 			max_bitflips = max_t(unsigned int, max_bitflips, stat);
2210 		}
2211 	}
2212 
2213 	/* Calculate remaining oob bytes */
2214 	i = mtd->oobsize - (oob - chip->oob_poi);
2215 	if (i) {
2216 		ret = nand_read_data_op(chip, oob, i, false);
2217 		if (ret)
2218 			return ret;
2219 	}
2220 
2221 	return max_bitflips;
2222 }
2223 
2224 /**
2225  * nand_transfer_oob - [INTERN] Transfer oob to client buffer
2226  * @chip: nand chip structure
2227  * @oob: oob destination address
2228  * @ops: oob ops structure
2229  * @len: size of oob to transfer
2230  */
nand_transfer_oob(struct nand_chip * chip,uint8_t * oob,struct mtd_oob_ops * ops,size_t len)2231 static uint8_t *nand_transfer_oob(struct nand_chip *chip, uint8_t *oob,
2232 				  struct mtd_oob_ops *ops, size_t len)
2233 {
2234 	switch (ops->mode) {
2235 
2236 	case MTD_OPS_PLACE_OOB:
2237 	case MTD_OPS_RAW:
2238 		memcpy(oob, chip->oob_poi + ops->ooboffs, len);
2239 		return oob + len;
2240 
2241 	case MTD_OPS_AUTO_OOB: {
2242 		struct nand_oobfree *free = chip->ecc.layout->oobfree;
2243 		uint32_t boffs = 0, roffs = ops->ooboffs;
2244 		size_t bytes = 0;
2245 
2246 		for (; free->length && len; free++, len -= bytes) {
2247 			/* Read request not from offset 0? */
2248 			if (unlikely(roffs)) {
2249 				if (roffs >= free->length) {
2250 					roffs -= free->length;
2251 					continue;
2252 				}
2253 				boffs = free->offset + roffs;
2254 				bytes = min_t(size_t, len,
2255 					      (free->length - roffs));
2256 				roffs = 0;
2257 			} else {
2258 				bytes = min_t(size_t, len, free->length);
2259 				boffs = free->offset;
2260 			}
2261 			memcpy(oob, chip->oob_poi + boffs, bytes);
2262 			oob += bytes;
2263 		}
2264 		return oob;
2265 	}
2266 	default:
2267 		BUG();
2268 	}
2269 	return NULL;
2270 }
2271 
2272 /**
2273  * nand_setup_read_retry - [INTERN] Set the READ RETRY mode
2274  * @mtd: MTD device structure
2275  * @retry_mode: the retry mode to use
2276  *
2277  * Some vendors supply a special command to shift the Vt threshold, to be used
2278  * when there are too many bitflips in a page (i.e., ECC error). After setting
2279  * a new threshold, the host should retry reading the page.
2280  */
nand_setup_read_retry(struct mtd_info * mtd,int retry_mode)2281 static int nand_setup_read_retry(struct mtd_info *mtd, int retry_mode)
2282 {
2283 	struct nand_chip *chip = mtd_to_nand(mtd);
2284 
2285 	pr_debug("setting READ RETRY mode %d\n", retry_mode);
2286 
2287 	if (retry_mode >= chip->read_retries)
2288 		return -EINVAL;
2289 
2290 	if (!chip->setup_read_retry)
2291 		return -EOPNOTSUPP;
2292 
2293 	return chip->setup_read_retry(mtd, retry_mode);
2294 }
2295 
2296 /**
2297  * nand_do_read_ops - [INTERN] Read data with ECC
2298  * @mtd: MTD device structure
2299  * @from: offset to read from
2300  * @ops: oob ops structure
2301  *
2302  * Internal function. Called with chip held.
2303  */
nand_do_read_ops(struct mtd_info * mtd,loff_t from,struct mtd_oob_ops * ops)2304 static int nand_do_read_ops(struct mtd_info *mtd, loff_t from,
2305 			    struct mtd_oob_ops *ops)
2306 {
2307 	int chipnr, page, realpage, col, bytes, aligned, oob_required;
2308 	struct nand_chip *chip = mtd_to_nand(mtd);
2309 	int ret = 0;
2310 	uint32_t readlen = ops->len;
2311 	uint32_t oobreadlen = ops->ooblen;
2312 	uint32_t max_oobsize = mtd_oobavail(mtd, ops);
2313 
2314 	uint8_t *bufpoi, *oob, *buf;
2315 	int use_bufpoi;
2316 	unsigned int max_bitflips = 0;
2317 	int retry_mode = 0;
2318 	bool ecc_fail = false;
2319 
2320 	chipnr = (int)(from >> chip->chip_shift);
2321 	chip->select_chip(mtd, chipnr);
2322 
2323 	realpage = (int)(from >> chip->page_shift);
2324 	page = realpage & chip->pagemask;
2325 
2326 	col = (int)(from & (mtd->writesize - 1));
2327 
2328 	buf = ops->datbuf;
2329 	oob = ops->oobbuf;
2330 	oob_required = oob ? 1 : 0;
2331 
2332 	while (1) {
2333 		unsigned int ecc_failures = mtd->ecc_stats.failed;
2334 
2335 		WATCHDOG_RESET();
2336 		bytes = min(mtd->writesize - col, readlen);
2337 		aligned = (bytes == mtd->writesize);
2338 
2339 		if (!aligned)
2340 			use_bufpoi = 1;
2341 		else if (chip->options & NAND_USE_BOUNCE_BUFFER)
2342 			use_bufpoi = !IS_ALIGNED((unsigned long)buf,
2343 						 chip->buf_align);
2344 		else
2345 			use_bufpoi = 0;
2346 
2347 		/* Is the current page in the buffer? */
2348 		if (realpage != chip->pagebuf || oob) {
2349 			bufpoi = use_bufpoi ? chip->buffers->databuf : buf;
2350 
2351 			if (use_bufpoi && aligned)
2352 				pr_debug("%s: using read bounce buffer for buf@%p\n",
2353 						 __func__, buf);
2354 
2355 read_retry:
2356 			if (nand_standard_page_accessors(&chip->ecc)) {
2357 				ret = nand_read_page_op(chip, page, 0, NULL, 0);
2358 				if (ret)
2359 					break;
2360 			}
2361 
2362 			/*
2363 			 * Now read the page into the buffer.  Absent an error,
2364 			 * the read methods return max bitflips per ecc step.
2365 			 */
2366 			if (unlikely(ops->mode == MTD_OPS_RAW))
2367 				ret = chip->ecc.read_page_raw(mtd, chip, bufpoi,
2368 							      oob_required,
2369 							      page);
2370 			else if (!aligned && NAND_HAS_SUBPAGE_READ(chip) &&
2371 				 !oob)
2372 				ret = chip->ecc.read_subpage(mtd, chip,
2373 							col, bytes, bufpoi,
2374 							page);
2375 			else
2376 				ret = chip->ecc.read_page(mtd, chip, bufpoi,
2377 							  oob_required, page);
2378 			if (ret < 0) {
2379 				if (use_bufpoi)
2380 					/* Invalidate page cache */
2381 					chip->pagebuf = -1;
2382 				break;
2383 			}
2384 
2385 			max_bitflips = max_t(unsigned int, max_bitflips, ret);
2386 
2387 			/* Transfer not aligned data */
2388 			if (use_bufpoi) {
2389 				if (!NAND_HAS_SUBPAGE_READ(chip) && !oob &&
2390 				    !(mtd->ecc_stats.failed - ecc_failures) &&
2391 				    (ops->mode != MTD_OPS_RAW)) {
2392 					chip->pagebuf = realpage;
2393 					chip->pagebuf_bitflips = ret;
2394 				} else {
2395 					/* Invalidate page cache */
2396 					chip->pagebuf = -1;
2397 				}
2398 				memcpy(buf, chip->buffers->databuf + col, bytes);
2399 			}
2400 
2401 			if (unlikely(oob)) {
2402 				int toread = min(oobreadlen, max_oobsize);
2403 
2404 				if (toread) {
2405 					oob = nand_transfer_oob(chip,
2406 						oob, ops, toread);
2407 					oobreadlen -= toread;
2408 				}
2409 			}
2410 
2411 			if (chip->options & NAND_NEED_READRDY) {
2412 				/* Apply delay or wait for ready/busy pin */
2413 				if (!chip->dev_ready)
2414 					udelay(chip->chip_delay);
2415 				else
2416 					nand_wait_ready(mtd);
2417 			}
2418 
2419 			if (mtd->ecc_stats.failed - ecc_failures) {
2420 				if (retry_mode + 1 < chip->read_retries) {
2421 					retry_mode++;
2422 					ret = nand_setup_read_retry(mtd,
2423 							retry_mode);
2424 					if (ret < 0)
2425 						break;
2426 
2427 					/* Reset failures; retry */
2428 					mtd->ecc_stats.failed = ecc_failures;
2429 					goto read_retry;
2430 				} else {
2431 					/* No more retry modes; real failure */
2432 					ecc_fail = true;
2433 				}
2434 			}
2435 
2436 			buf += bytes;
2437 		} else {
2438 			memcpy(buf, chip->buffers->databuf + col, bytes);
2439 			buf += bytes;
2440 			max_bitflips = max_t(unsigned int, max_bitflips,
2441 					     chip->pagebuf_bitflips);
2442 		}
2443 
2444 		readlen -= bytes;
2445 
2446 		/* Reset to retry mode 0 */
2447 		if (retry_mode) {
2448 			ret = nand_setup_read_retry(mtd, 0);
2449 			if (ret < 0)
2450 				break;
2451 			retry_mode = 0;
2452 		}
2453 
2454 		if (!readlen)
2455 			break;
2456 
2457 		/* For subsequent reads align to page boundary */
2458 		col = 0;
2459 		/* Increment page address */
2460 		realpage++;
2461 
2462 		page = realpage & chip->pagemask;
2463 		/* Check, if we cross a chip boundary */
2464 		if (!page) {
2465 			chipnr++;
2466 			chip->select_chip(mtd, -1);
2467 			chip->select_chip(mtd, chipnr);
2468 		}
2469 	}
2470 	chip->select_chip(mtd, -1);
2471 
2472 	ops->retlen = ops->len - (size_t) readlen;
2473 	if (oob)
2474 		ops->oobretlen = ops->ooblen - oobreadlen;
2475 
2476 	if (ret < 0)
2477 		return ret;
2478 
2479 	if (ecc_fail)
2480 		return -EBADMSG;
2481 
2482 	return max_bitflips;
2483 }
2484 
2485 /**
2486  * nand_read_oob_std - [REPLACEABLE] the most common OOB data read function
2487  * @mtd: mtd info structure
2488  * @chip: nand chip info structure
2489  * @page: page number to read
2490  */
nand_read_oob_std(struct mtd_info * mtd,struct nand_chip * chip,int page)2491 static int nand_read_oob_std(struct mtd_info *mtd, struct nand_chip *chip,
2492 			     int page)
2493 {
2494 	return nand_read_oob_op(chip, page, 0, chip->oob_poi, mtd->oobsize);
2495 }
2496 
2497 /**
2498  * nand_read_oob_syndrome - [REPLACEABLE] OOB data read function for HW ECC
2499  *			    with syndromes
2500  * @mtd: mtd info structure
2501  * @chip: nand chip info structure
2502  * @page: page number to read
2503  */
nand_read_oob_syndrome(struct mtd_info * mtd,struct nand_chip * chip,int page)2504 static int nand_read_oob_syndrome(struct mtd_info *mtd, struct nand_chip *chip,
2505 				  int page)
2506 {
2507 	int length = mtd->oobsize;
2508 	int chunk = chip->ecc.bytes + chip->ecc.prepad + chip->ecc.postpad;
2509 	int eccsize = chip->ecc.size;
2510 	uint8_t *bufpoi = chip->oob_poi;
2511 	int i, toread, sndrnd = 0, pos, ret;
2512 
2513 	ret = nand_read_page_op(chip, page, chip->ecc.size, NULL, 0);
2514 	if (ret)
2515 		return ret;
2516 
2517 	for (i = 0; i < chip->ecc.steps; i++) {
2518 		if (sndrnd) {
2519 			int ret;
2520 
2521 			pos = eccsize + i * (eccsize + chunk);
2522 			if (mtd->writesize > 512)
2523 				ret = nand_change_read_column_op(chip, pos,
2524 								 NULL, 0,
2525 								 false);
2526 			else
2527 				ret = nand_read_page_op(chip, page, pos, NULL,
2528 							0);
2529 
2530 			if (ret)
2531 				return ret;
2532 		} else
2533 			sndrnd = 1;
2534 		toread = min_t(int, length, chunk);
2535 
2536 		ret = nand_read_data_op(chip, bufpoi, toread, false);
2537 		if (ret)
2538 			return ret;
2539 
2540 		bufpoi += toread;
2541 		length -= toread;
2542 	}
2543 	if (length > 0) {
2544 		ret = nand_read_data_op(chip, bufpoi, length, false);
2545 		if (ret)
2546 			return ret;
2547 	}
2548 
2549 	return 0;
2550 }
2551 
2552 /**
2553  * nand_write_oob_std - [REPLACEABLE] the most common OOB data write function
2554  * @mtd: mtd info structure
2555  * @chip: nand chip info structure
2556  * @page: page number to write
2557  */
nand_write_oob_std(struct mtd_info * mtd,struct nand_chip * chip,int page)2558 static int nand_write_oob_std(struct mtd_info *mtd, struct nand_chip *chip,
2559 			      int page)
2560 {
2561 	return nand_prog_page_op(chip, page, mtd->writesize, chip->oob_poi,
2562 				 mtd->oobsize);
2563 }
2564 
2565 /**
2566  * nand_write_oob_syndrome - [REPLACEABLE] OOB data write function for HW ECC
2567  *			     with syndrome - only for large page flash
2568  * @mtd: mtd info structure
2569  * @chip: nand chip info structure
2570  * @page: page number to write
2571  */
nand_write_oob_syndrome(struct mtd_info * mtd,struct nand_chip * chip,int page)2572 static int nand_write_oob_syndrome(struct mtd_info *mtd,
2573 				   struct nand_chip *chip, int page)
2574 {
2575 	int chunk = chip->ecc.bytes + chip->ecc.prepad + chip->ecc.postpad;
2576 	int eccsize = chip->ecc.size, length = mtd->oobsize;
2577 	int ret, i, len, pos, sndcmd = 0, steps = chip->ecc.steps;
2578 	const uint8_t *bufpoi = chip->oob_poi;
2579 
2580 	/*
2581 	 * data-ecc-data-ecc ... ecc-oob
2582 	 * or
2583 	 * data-pad-ecc-pad-data-pad .... ecc-pad-oob
2584 	 */
2585 	if (!chip->ecc.prepad && !chip->ecc.postpad) {
2586 		pos = steps * (eccsize + chunk);
2587 		steps = 0;
2588 	} else
2589 		pos = eccsize;
2590 
2591 	ret = nand_prog_page_begin_op(chip, page, pos, NULL, 0);
2592 	if (ret)
2593 		return ret;
2594 
2595 	for (i = 0; i < steps; i++) {
2596 		if (sndcmd) {
2597 			if (mtd->writesize <= 512) {
2598 				uint32_t fill = 0xFFFFFFFF;
2599 
2600 				len = eccsize;
2601 				while (len > 0) {
2602 					int num = min_t(int, len, 4);
2603 
2604 					ret = nand_write_data_op(chip, &fill,
2605 								 num, false);
2606 					if (ret)
2607 						return ret;
2608 
2609 					len -= num;
2610 				}
2611 			} else {
2612 				pos = eccsize + i * (eccsize + chunk);
2613 				ret = nand_change_write_column_op(chip, pos,
2614 								  NULL, 0,
2615 								  false);
2616 				if (ret)
2617 					return ret;
2618 			}
2619 		} else
2620 			sndcmd = 1;
2621 		len = min_t(int, length, chunk);
2622 
2623 		ret = nand_write_data_op(chip, bufpoi, len, false);
2624 		if (ret)
2625 			return ret;
2626 
2627 		bufpoi += len;
2628 		length -= len;
2629 	}
2630 	if (length > 0) {
2631 		ret = nand_write_data_op(chip, bufpoi, length, false);
2632 		if (ret)
2633 			return ret;
2634 	}
2635 
2636 	return nand_prog_page_end_op(chip);
2637 }
2638 
2639 /**
2640  * nand_do_read_oob - [INTERN] NAND read out-of-band
2641  * @mtd: MTD device structure
2642  * @from: offset to read from
2643  * @ops: oob operations description structure
2644  *
2645  * NAND read out-of-band data from the spare area.
2646  */
nand_do_read_oob(struct mtd_info * mtd,loff_t from,struct mtd_oob_ops * ops)2647 static int nand_do_read_oob(struct mtd_info *mtd, loff_t from,
2648 			    struct mtd_oob_ops *ops)
2649 {
2650 	int page, realpage, chipnr;
2651 	struct nand_chip *chip = mtd_to_nand(mtd);
2652 	struct mtd_ecc_stats stats;
2653 	int readlen = ops->ooblen;
2654 	int len;
2655 	uint8_t *buf = ops->oobbuf;
2656 	int ret = 0;
2657 
2658 	pr_debug("%s: from = 0x%08Lx, len = %i\n",
2659 			__func__, (unsigned long long)from, readlen);
2660 
2661 	stats = mtd->ecc_stats;
2662 
2663 	len = mtd_oobavail(mtd, ops);
2664 
2665 	if (unlikely(ops->ooboffs >= len)) {
2666 		pr_debug("%s: attempt to start read outside oob\n",
2667 				__func__);
2668 		return -EINVAL;
2669 	}
2670 
2671 	/* Do not allow reads past end of device */
2672 	if (unlikely(from >= mtd->size ||
2673 		     ops->ooboffs + readlen > ((mtd->size >> chip->page_shift) -
2674 					(from >> chip->page_shift)) * len)) {
2675 		pr_debug("%s: attempt to read beyond end of device\n",
2676 				__func__);
2677 		return -EINVAL;
2678 	}
2679 
2680 	chipnr = (int)(from >> chip->chip_shift);
2681 	chip->select_chip(mtd, chipnr);
2682 
2683 	/* Shift to get page */
2684 	realpage = (int)(from >> chip->page_shift);
2685 	page = realpage & chip->pagemask;
2686 
2687 	while (1) {
2688 		WATCHDOG_RESET();
2689 
2690 		if (ops->mode == MTD_OPS_RAW)
2691 			ret = chip->ecc.read_oob_raw(mtd, chip, page);
2692 		else
2693 			ret = chip->ecc.read_oob(mtd, chip, page);
2694 
2695 		if (ret < 0)
2696 			break;
2697 
2698 		len = min(len, readlen);
2699 		buf = nand_transfer_oob(chip, buf, ops, len);
2700 
2701 		if (chip->options & NAND_NEED_READRDY) {
2702 			/* Apply delay or wait for ready/busy pin */
2703 			if (!chip->dev_ready)
2704 				udelay(chip->chip_delay);
2705 			else
2706 				nand_wait_ready(mtd);
2707 		}
2708 
2709 		readlen -= len;
2710 		if (!readlen)
2711 			break;
2712 
2713 		/* Increment page address */
2714 		realpage++;
2715 
2716 		page = realpage & chip->pagemask;
2717 		/* Check, if we cross a chip boundary */
2718 		if (!page) {
2719 			chipnr++;
2720 			chip->select_chip(mtd, -1);
2721 			chip->select_chip(mtd, chipnr);
2722 		}
2723 	}
2724 	chip->select_chip(mtd, -1);
2725 
2726 	ops->oobretlen = ops->ooblen - readlen;
2727 
2728 	if (ret < 0)
2729 		return ret;
2730 
2731 	if (mtd->ecc_stats.failed - stats.failed)
2732 		return -EBADMSG;
2733 
2734 	return  mtd->ecc_stats.corrected - stats.corrected ? -EUCLEAN : 0;
2735 }
2736 
2737 /**
2738  * nand_read_oob - [MTD Interface] NAND read data and/or out-of-band
2739  * @mtd: MTD device structure
2740  * @from: offset to read from
2741  * @ops: oob operation description structure
2742  *
2743  * NAND read data and/or out-of-band data.
2744  */
nand_read_oob(struct mtd_info * mtd,loff_t from,struct mtd_oob_ops * ops)2745 static int nand_read_oob(struct mtd_info *mtd, loff_t from,
2746 			 struct mtd_oob_ops *ops)
2747 {
2748 	int ret = -ENOTSUPP;
2749 
2750 	ops->retlen = 0;
2751 
2752 	/* Do not allow reads past end of device */
2753 	if (ops->datbuf && (from + ops->len) > mtd->size) {
2754 		pr_debug("%s: attempt to read beyond end of device\n",
2755 				__func__);
2756 		return -EINVAL;
2757 	}
2758 
2759 	nand_get_device(mtd, FL_READING);
2760 
2761 	switch (ops->mode) {
2762 	case MTD_OPS_PLACE_OOB:
2763 	case MTD_OPS_AUTO_OOB:
2764 	case MTD_OPS_RAW:
2765 		break;
2766 
2767 	default:
2768 		goto out;
2769 	}
2770 
2771 	if (!ops->datbuf)
2772 		ret = nand_do_read_oob(mtd, from, ops);
2773 	else
2774 		ret = nand_do_read_ops(mtd, from, ops);
2775 
2776 out:
2777 	nand_release_device(mtd);
2778 	return ret;
2779 }
2780 
2781 
2782 /**
2783  * nand_write_page_raw - [INTERN] raw page write function
2784  * @mtd: mtd info structure
2785  * @chip: nand chip info structure
2786  * @buf: data buffer
2787  * @oob_required: must write chip->oob_poi to OOB
2788  * @page: page number to write
2789  *
2790  * Not for syndrome calculating ECC controllers, which use a special oob layout.
2791  */
nand_write_page_raw(struct mtd_info * mtd,struct nand_chip * chip,const uint8_t * buf,int oob_required,int page)2792 static int nand_write_page_raw(struct mtd_info *mtd, struct nand_chip *chip,
2793 			       const uint8_t *buf, int oob_required, int page)
2794 {
2795 	int ret;
2796 
2797 	ret = nand_write_data_op(chip, buf, mtd->writesize, false);
2798 	if (ret)
2799 		return ret;
2800 
2801 	if (oob_required) {
2802 		ret = nand_write_data_op(chip, chip->oob_poi, mtd->oobsize,
2803 					 false);
2804 		if (ret)
2805 			return ret;
2806 	}
2807 
2808 	return 0;
2809 }
2810 
2811 /**
2812  * nand_write_page_raw_syndrome - [INTERN] raw page write function
2813  * @mtd: mtd info structure
2814  * @chip: nand chip info structure
2815  * @buf: data buffer
2816  * @oob_required: must write chip->oob_poi to OOB
2817  * @page: page number to write
2818  *
2819  * We need a special oob layout and handling even when ECC isn't checked.
2820  */
nand_write_page_raw_syndrome(struct mtd_info * mtd,struct nand_chip * chip,const uint8_t * buf,int oob_required,int page)2821 static int nand_write_page_raw_syndrome(struct mtd_info *mtd,
2822 					struct nand_chip *chip,
2823 					const uint8_t *buf, int oob_required,
2824 					int page)
2825 {
2826 	int eccsize = chip->ecc.size;
2827 	int eccbytes = chip->ecc.bytes;
2828 	uint8_t *oob = chip->oob_poi;
2829 	int steps, size, ret;
2830 
2831 	for (steps = chip->ecc.steps; steps > 0; steps--) {
2832 		ret = nand_write_data_op(chip, buf, eccsize, false);
2833 		if (ret)
2834 			return ret;
2835 
2836 		buf += eccsize;
2837 
2838 		if (chip->ecc.prepad) {
2839 			ret = nand_write_data_op(chip, oob, chip->ecc.prepad,
2840 						 false);
2841 			if (ret)
2842 				return ret;
2843 
2844 			oob += chip->ecc.prepad;
2845 		}
2846 
2847 		ret = nand_write_data_op(chip, oob, eccbytes, false);
2848 		if (ret)
2849 			return ret;
2850 
2851 		oob += eccbytes;
2852 
2853 		if (chip->ecc.postpad) {
2854 			ret = nand_write_data_op(chip, oob, chip->ecc.postpad,
2855 						 false);
2856 			if (ret)
2857 				return ret;
2858 
2859 			oob += chip->ecc.postpad;
2860 		}
2861 	}
2862 
2863 	size = mtd->oobsize - (oob - chip->oob_poi);
2864 	if (size) {
2865 		ret = nand_write_data_op(chip, oob, size, false);
2866 		if (ret)
2867 			return ret;
2868 	}
2869 
2870 	return 0;
2871 }
2872 /**
2873  * nand_write_page_swecc - [REPLACEABLE] software ECC based page write function
2874  * @mtd: mtd info structure
2875  * @chip: nand chip info structure
2876  * @buf: data buffer
2877  * @oob_required: must write chip->oob_poi to OOB
2878  * @page: page number to write
2879  */
nand_write_page_swecc(struct mtd_info * mtd,struct nand_chip * chip,const uint8_t * buf,int oob_required,int page)2880 static int nand_write_page_swecc(struct mtd_info *mtd, struct nand_chip *chip,
2881 				 const uint8_t *buf, int oob_required,
2882 				 int page)
2883 {
2884 	int i, eccsize = chip->ecc.size;
2885 	int eccbytes = chip->ecc.bytes;
2886 	int eccsteps = chip->ecc.steps;
2887 	uint8_t *ecc_calc = chip->buffers->ecccalc;
2888 	const uint8_t *p = buf;
2889 	uint32_t *eccpos = chip->ecc.layout->eccpos;
2890 
2891 	/* Software ECC calculation */
2892 	for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize)
2893 		chip->ecc.calculate(mtd, p, &ecc_calc[i]);
2894 
2895 	for (i = 0; i < chip->ecc.total; i++)
2896 		chip->oob_poi[eccpos[i]] = ecc_calc[i];
2897 
2898 	return chip->ecc.write_page_raw(mtd, chip, buf, 1, page);
2899 }
2900 
2901 /**
2902  * nand_write_page_hwecc - [REPLACEABLE] hardware ECC based page write function
2903  * @mtd: mtd info structure
2904  * @chip: nand chip info structure
2905  * @buf: data buffer
2906  * @oob_required: must write chip->oob_poi to OOB
2907  * @page: page number to write
2908  */
nand_write_page_hwecc(struct mtd_info * mtd,struct nand_chip * chip,const uint8_t * buf,int oob_required,int page)2909 static int nand_write_page_hwecc(struct mtd_info *mtd, struct nand_chip *chip,
2910 				  const uint8_t *buf, int oob_required,
2911 				  int page)
2912 {
2913 	int i, eccsize = chip->ecc.size;
2914 	int eccbytes = chip->ecc.bytes;
2915 	int eccsteps = chip->ecc.steps;
2916 	uint8_t *ecc_calc = chip->buffers->ecccalc;
2917 	const uint8_t *p = buf;
2918 	uint32_t *eccpos = chip->ecc.layout->eccpos;
2919 	int ret;
2920 
2921 	for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
2922 		chip->ecc.hwctl(mtd, NAND_ECC_WRITE);
2923 
2924 		ret = nand_write_data_op(chip, p, eccsize, false);
2925 		if (ret)
2926 			return ret;
2927 
2928 		chip->ecc.calculate(mtd, p, &ecc_calc[i]);
2929 	}
2930 
2931 	for (i = 0; i < chip->ecc.total; i++)
2932 		chip->oob_poi[eccpos[i]] = ecc_calc[i];
2933 
2934 	ret = nand_write_data_op(chip, chip->oob_poi, mtd->oobsize, false);
2935 	if (ret)
2936 		return ret;
2937 
2938 	return 0;
2939 }
2940 
2941 
2942 /**
2943  * nand_write_subpage_hwecc - [REPLACEABLE] hardware ECC based subpage write
2944  * @mtd:	mtd info structure
2945  * @chip:	nand chip info structure
2946  * @offset:	column address of subpage within the page
2947  * @data_len:	data length
2948  * @buf:	data buffer
2949  * @oob_required: must write chip->oob_poi to OOB
2950  * @page: page number to write
2951  */
nand_write_subpage_hwecc(struct mtd_info * mtd,struct nand_chip * chip,uint32_t offset,uint32_t data_len,const uint8_t * buf,int oob_required,int page)2952 static int nand_write_subpage_hwecc(struct mtd_info *mtd,
2953 				struct nand_chip *chip, uint32_t offset,
2954 				uint32_t data_len, const uint8_t *buf,
2955 				int oob_required, int page)
2956 {
2957 	uint8_t *oob_buf  = chip->oob_poi;
2958 	uint8_t *ecc_calc = chip->buffers->ecccalc;
2959 	int ecc_size      = chip->ecc.size;
2960 	int ecc_bytes     = chip->ecc.bytes;
2961 	int ecc_steps     = chip->ecc.steps;
2962 	uint32_t *eccpos  = chip->ecc.layout->eccpos;
2963 	uint32_t start_step = offset / ecc_size;
2964 	uint32_t end_step   = (offset + data_len - 1) / ecc_size;
2965 	int oob_bytes       = mtd->oobsize / ecc_steps;
2966 	int step, i;
2967 	int ret;
2968 
2969 	for (step = 0; step < ecc_steps; step++) {
2970 		/* configure controller for WRITE access */
2971 		chip->ecc.hwctl(mtd, NAND_ECC_WRITE);
2972 
2973 		/* write data (untouched subpages already masked by 0xFF) */
2974 		ret = nand_write_data_op(chip, buf, ecc_size, false);
2975 		if (ret)
2976 			return ret;
2977 
2978 		/* mask ECC of un-touched subpages by padding 0xFF */
2979 		if ((step < start_step) || (step > end_step))
2980 			memset(ecc_calc, 0xff, ecc_bytes);
2981 		else
2982 			chip->ecc.calculate(mtd, buf, ecc_calc);
2983 
2984 		/* mask OOB of un-touched subpages by padding 0xFF */
2985 		/* if oob_required, preserve OOB metadata of written subpage */
2986 		if (!oob_required || (step < start_step) || (step > end_step))
2987 			memset(oob_buf, 0xff, oob_bytes);
2988 
2989 		buf += ecc_size;
2990 		ecc_calc += ecc_bytes;
2991 		oob_buf  += oob_bytes;
2992 	}
2993 
2994 	/* copy calculated ECC for whole page to chip->buffer->oob */
2995 	/* this include masked-value(0xFF) for unwritten subpages */
2996 	ecc_calc = chip->buffers->ecccalc;
2997 	for (i = 0; i < chip->ecc.total; i++)
2998 		chip->oob_poi[eccpos[i]] = ecc_calc[i];
2999 
3000 	/* write OOB buffer to NAND device */
3001 	ret = nand_write_data_op(chip, chip->oob_poi, mtd->oobsize, false);
3002 	if (ret)
3003 		return ret;
3004 
3005 	return 0;
3006 }
3007 
3008 
3009 /**
3010  * nand_write_page_syndrome - [REPLACEABLE] hardware ECC syndrome based page write
3011  * @mtd: mtd info structure
3012  * @chip: nand chip info structure
3013  * @buf: data buffer
3014  * @oob_required: must write chip->oob_poi to OOB
3015  * @page: page number to write
3016  *
3017  * The hw generator calculates the error syndrome automatically. Therefore we
3018  * need a special oob layout and handling.
3019  */
nand_write_page_syndrome(struct mtd_info * mtd,struct nand_chip * chip,const uint8_t * buf,int oob_required,int page)3020 static int nand_write_page_syndrome(struct mtd_info *mtd,
3021 				    struct nand_chip *chip,
3022 				    const uint8_t *buf, int oob_required,
3023 				    int page)
3024 {
3025 	int i, eccsize = chip->ecc.size;
3026 	int eccbytes = chip->ecc.bytes;
3027 	int eccsteps = chip->ecc.steps;
3028 	const uint8_t *p = buf;
3029 	uint8_t *oob = chip->oob_poi;
3030 	int ret;
3031 
3032 	for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
3033 		chip->ecc.hwctl(mtd, NAND_ECC_WRITE);
3034 
3035 		ret = nand_write_data_op(chip, p, eccsize, false);
3036 		if (ret)
3037 			return ret;
3038 
3039 		if (chip->ecc.prepad) {
3040 			ret = nand_write_data_op(chip, oob, chip->ecc.prepad,
3041 						 false);
3042 			if (ret)
3043 				return ret;
3044 
3045 			oob += chip->ecc.prepad;
3046 		}
3047 
3048 		chip->ecc.calculate(mtd, p, oob);
3049 
3050 		ret = nand_write_data_op(chip, oob, eccbytes, false);
3051 		if (ret)
3052 			return ret;
3053 
3054 		oob += eccbytes;
3055 
3056 		if (chip->ecc.postpad) {
3057 			ret = nand_write_data_op(chip, oob, chip->ecc.postpad,
3058 						 false);
3059 			if (ret)
3060 				return ret;
3061 
3062 			oob += chip->ecc.postpad;
3063 		}
3064 	}
3065 
3066 	/* Calculate remaining oob bytes */
3067 	i = mtd->oobsize - (oob - chip->oob_poi);
3068 	if (i) {
3069 		ret = nand_write_data_op(chip, oob, i, false);
3070 		if (ret)
3071 			return ret;
3072 	}
3073 
3074 	return 0;
3075 }
3076 
3077 /**
3078  * nand_write_page - [REPLACEABLE] write one page
3079  * @mtd: MTD device structure
3080  * @chip: NAND chip descriptor
3081  * @offset: address offset within the page
3082  * @data_len: length of actual data to be written
3083  * @buf: the data to write
3084  * @oob_required: must write chip->oob_poi to OOB
3085  * @page: page number to write
3086  * @raw: use _raw version of write_page
3087  */
nand_write_page(struct mtd_info * mtd,struct nand_chip * chip,uint32_t offset,int data_len,const uint8_t * buf,int oob_required,int page,int raw)3088 static int nand_write_page(struct mtd_info *mtd, struct nand_chip *chip,
3089 		uint32_t offset, int data_len, const uint8_t *buf,
3090 		int oob_required, int page, int raw)
3091 {
3092 	int status, subpage;
3093 
3094 	if (!(chip->options & NAND_NO_SUBPAGE_WRITE) &&
3095 		chip->ecc.write_subpage)
3096 		subpage = offset || (data_len < mtd->writesize);
3097 	else
3098 		subpage = 0;
3099 
3100 	if (nand_standard_page_accessors(&chip->ecc)) {
3101 		status = nand_prog_page_begin_op(chip, page, 0, NULL, 0);
3102 		if (status)
3103 			return status;
3104 	}
3105 
3106 	if (unlikely(raw))
3107 		status = chip->ecc.write_page_raw(mtd, chip, buf,
3108 						  oob_required, page);
3109 	else if (subpage)
3110 		status = chip->ecc.write_subpage(mtd, chip, offset, data_len,
3111 						 buf, oob_required, page);
3112 	else
3113 		status = chip->ecc.write_page(mtd, chip, buf, oob_required,
3114 					      page);
3115 
3116 	if (status < 0)
3117 		return status;
3118 
3119 	if (nand_standard_page_accessors(&chip->ecc))
3120 		return nand_prog_page_end_op(chip);
3121 
3122 	return 0;
3123 }
3124 
3125 /**
3126  * nand_fill_oob - [INTERN] Transfer client buffer to oob
3127  * @mtd: MTD device structure
3128  * @oob: oob data buffer
3129  * @len: oob data write length
3130  * @ops: oob ops structure
3131  */
nand_fill_oob(struct mtd_info * mtd,uint8_t * oob,size_t len,struct mtd_oob_ops * ops)3132 static uint8_t *nand_fill_oob(struct mtd_info *mtd, uint8_t *oob, size_t len,
3133 			      struct mtd_oob_ops *ops)
3134 {
3135 	struct nand_chip *chip = mtd_to_nand(mtd);
3136 
3137 	/*
3138 	 * Initialise to all 0xFF, to avoid the possibility of left over OOB
3139 	 * data from a previous OOB read.
3140 	 */
3141 	memset(chip->oob_poi, 0xff, mtd->oobsize);
3142 
3143 	switch (ops->mode) {
3144 
3145 	case MTD_OPS_PLACE_OOB:
3146 	case MTD_OPS_RAW:
3147 		memcpy(chip->oob_poi + ops->ooboffs, oob, len);
3148 		return oob + len;
3149 
3150 	case MTD_OPS_AUTO_OOB: {
3151 		struct nand_oobfree *free = chip->ecc.layout->oobfree;
3152 		uint32_t boffs = 0, woffs = ops->ooboffs;
3153 		size_t bytes = 0;
3154 
3155 		for (; free->length && len; free++, len -= bytes) {
3156 			/* Write request not from offset 0? */
3157 			if (unlikely(woffs)) {
3158 				if (woffs >= free->length) {
3159 					woffs -= free->length;
3160 					continue;
3161 				}
3162 				boffs = free->offset + woffs;
3163 				bytes = min_t(size_t, len,
3164 					      (free->length - woffs));
3165 				woffs = 0;
3166 			} else {
3167 				bytes = min_t(size_t, len, free->length);
3168 				boffs = free->offset;
3169 			}
3170 			memcpy(chip->oob_poi + boffs, oob, bytes);
3171 			oob += bytes;
3172 		}
3173 		return oob;
3174 	}
3175 	default:
3176 		BUG();
3177 	}
3178 	return NULL;
3179 }
3180 
3181 #define NOTALIGNED(x)	((x & (chip->subpagesize - 1)) != 0)
3182 
3183 /**
3184  * nand_do_write_ops - [INTERN] NAND write with ECC
3185  * @mtd: MTD device structure
3186  * @to: offset to write to
3187  * @ops: oob operations description structure
3188  *
3189  * NAND write with ECC.
3190  */
nand_do_write_ops(struct mtd_info * mtd,loff_t to,struct mtd_oob_ops * ops)3191 static int nand_do_write_ops(struct mtd_info *mtd, loff_t to,
3192 			     struct mtd_oob_ops *ops)
3193 {
3194 	int chipnr, realpage, page, column;
3195 	struct nand_chip *chip = mtd_to_nand(mtd);
3196 	uint32_t writelen = ops->len;
3197 
3198 	uint32_t oobwritelen = ops->ooblen;
3199 	uint32_t oobmaxlen = mtd_oobavail(mtd, ops);
3200 
3201 	uint8_t *oob = ops->oobbuf;
3202 	uint8_t *buf = ops->datbuf;
3203 	int ret;
3204 	int oob_required = oob ? 1 : 0;
3205 
3206 	ops->retlen = 0;
3207 	if (!writelen)
3208 		return 0;
3209 
3210 	/* Reject writes, which are not page aligned */
3211 	if (NOTALIGNED(to)) {
3212 		pr_notice("%s: attempt to write non page aligned data\n",
3213 			   __func__);
3214 		return -EINVAL;
3215 	}
3216 
3217 	column = to & (mtd->writesize - 1);
3218 
3219 	chipnr = (int)(to >> chip->chip_shift);
3220 	chip->select_chip(mtd, chipnr);
3221 
3222 	/* Check, if it is write protected */
3223 	if (nand_check_wp(mtd)) {
3224 		ret = -EIO;
3225 		goto err_out;
3226 	}
3227 
3228 	realpage = (int)(to >> chip->page_shift);
3229 	page = realpage & chip->pagemask;
3230 
3231 	/* Invalidate the page cache, when we write to the cached page */
3232 	if (to <= ((loff_t)chip->pagebuf << chip->page_shift) &&
3233 	    ((loff_t)chip->pagebuf << chip->page_shift) < (to + ops->len))
3234 		chip->pagebuf = -1;
3235 
3236 	/* Don't allow multipage oob writes with offset */
3237 	if (oob && ops->ooboffs && (ops->ooboffs + ops->ooblen > oobmaxlen)) {
3238 		ret = -EINVAL;
3239 		goto err_out;
3240 	}
3241 
3242 	while (1) {
3243 		int bytes = mtd->writesize;
3244 		uint8_t *wbuf = buf;
3245 		int use_bufpoi;
3246 		int part_pagewr = (column || writelen < mtd->writesize);
3247 
3248 		if (part_pagewr)
3249 			use_bufpoi = 1;
3250 		else if (chip->options & NAND_USE_BOUNCE_BUFFER)
3251 			use_bufpoi = !IS_ALIGNED((unsigned long)buf,
3252 						 chip->buf_align);
3253 		else
3254 			use_bufpoi = 0;
3255 
3256 		WATCHDOG_RESET();
3257 		/* Partial page write?, or need to use bounce buffer */
3258 		if (use_bufpoi) {
3259 			pr_debug("%s: using write bounce buffer for buf@%p\n",
3260 					 __func__, buf);
3261 			if (part_pagewr)
3262 				bytes = min_t(int, bytes - column, writelen);
3263 			chip->pagebuf = -1;
3264 			memset(chip->buffers->databuf, 0xff, mtd->writesize);
3265 			memcpy(&chip->buffers->databuf[column], buf, bytes);
3266 			wbuf = chip->buffers->databuf;
3267 		}
3268 
3269 		if (unlikely(oob)) {
3270 			size_t len = min(oobwritelen, oobmaxlen);
3271 			oob = nand_fill_oob(mtd, oob, len, ops);
3272 			oobwritelen -= len;
3273 		} else {
3274 			/* We still need to erase leftover OOB data */
3275 			memset(chip->oob_poi, 0xff, mtd->oobsize);
3276 		}
3277 		ret = chip->write_page(mtd, chip, column, bytes, wbuf,
3278 					oob_required, page,
3279 					(ops->mode == MTD_OPS_RAW));
3280 		if (ret)
3281 			break;
3282 
3283 		writelen -= bytes;
3284 		if (!writelen)
3285 			break;
3286 
3287 		column = 0;
3288 		buf += bytes;
3289 		realpage++;
3290 
3291 		page = realpage & chip->pagemask;
3292 		/* Check, if we cross a chip boundary */
3293 		if (!page) {
3294 			chipnr++;
3295 			chip->select_chip(mtd, -1);
3296 			chip->select_chip(mtd, chipnr);
3297 		}
3298 	}
3299 
3300 	ops->retlen = ops->len - writelen;
3301 	if (unlikely(oob))
3302 		ops->oobretlen = ops->ooblen;
3303 
3304 err_out:
3305 	chip->select_chip(mtd, -1);
3306 	return ret;
3307 }
3308 
3309 /**
3310  * panic_nand_write - [MTD Interface] NAND write with ECC
3311  * @mtd: MTD device structure
3312  * @to: offset to write to
3313  * @len: number of bytes to write
3314  * @retlen: pointer to variable to store the number of written bytes
3315  * @buf: the data to write
3316  *
3317  * NAND write with ECC. Used when performing writes in interrupt context, this
3318  * may for example be called by mtdoops when writing an oops while in panic.
3319  */
panic_nand_write(struct mtd_info * mtd,loff_t to,size_t len,size_t * retlen,const uint8_t * buf)3320 static int panic_nand_write(struct mtd_info *mtd, loff_t to, size_t len,
3321 			    size_t *retlen, const uint8_t *buf)
3322 {
3323 	struct nand_chip *chip = mtd_to_nand(mtd);
3324 	struct mtd_oob_ops ops;
3325 	int ret;
3326 
3327 	/* Wait for the device to get ready */
3328 	panic_nand_wait(mtd, chip, 400);
3329 
3330 	/* Grab the device */
3331 	panic_nand_get_device(chip, mtd, FL_WRITING);
3332 
3333 	memset(&ops, 0, sizeof(ops));
3334 	ops.len = len;
3335 	ops.datbuf = (uint8_t *)buf;
3336 	ops.mode = MTD_OPS_PLACE_OOB;
3337 
3338 	ret = nand_do_write_ops(mtd, to, &ops);
3339 
3340 	*retlen = ops.retlen;
3341 	return ret;
3342 }
3343 
3344 /**
3345  * nand_do_write_oob - [MTD Interface] NAND write out-of-band
3346  * @mtd: MTD device structure
3347  * @to: offset to write to
3348  * @ops: oob operation description structure
3349  *
3350  * NAND write out-of-band.
3351  */
nand_do_write_oob(struct mtd_info * mtd,loff_t to,struct mtd_oob_ops * ops)3352 static int nand_do_write_oob(struct mtd_info *mtd, loff_t to,
3353 			     struct mtd_oob_ops *ops)
3354 {
3355 	int chipnr, page, status, len;
3356 	struct nand_chip *chip = mtd_to_nand(mtd);
3357 
3358 	pr_debug("%s: to = 0x%08x, len = %i\n",
3359 			 __func__, (unsigned int)to, (int)ops->ooblen);
3360 
3361 	len = mtd_oobavail(mtd, ops);
3362 
3363 	/* Do not allow write past end of page */
3364 	if ((ops->ooboffs + ops->ooblen) > len) {
3365 		pr_debug("%s: attempt to write past end of page\n",
3366 				__func__);
3367 		return -EINVAL;
3368 	}
3369 
3370 	if (unlikely(ops->ooboffs >= len)) {
3371 		pr_debug("%s: attempt to start write outside oob\n",
3372 				__func__);
3373 		return -EINVAL;
3374 	}
3375 
3376 	/* Do not allow write past end of device */
3377 	if (unlikely(to >= mtd->size ||
3378 		     ops->ooboffs + ops->ooblen >
3379 			((mtd->size >> chip->page_shift) -
3380 			 (to >> chip->page_shift)) * len)) {
3381 		pr_debug("%s: attempt to write beyond end of device\n",
3382 				__func__);
3383 		return -EINVAL;
3384 	}
3385 
3386 	chipnr = (int)(to >> chip->chip_shift);
3387 
3388 	/*
3389 	 * Reset the chip. Some chips (like the Toshiba TC5832DC found in one
3390 	 * of my DiskOnChip 2000 test units) will clear the whole data page too
3391 	 * if we don't do this. I have no clue why, but I seem to have 'fixed'
3392 	 * it in the doc2000 driver in August 1999.  dwmw2.
3393 	 */
3394 	nand_reset(chip, chipnr);
3395 
3396 	chip->select_chip(mtd, chipnr);
3397 
3398 	/* Shift to get page */
3399 	page = (int)(to >> chip->page_shift);
3400 
3401 	/* Check, if it is write protected */
3402 	if (nand_check_wp(mtd)) {
3403 		chip->select_chip(mtd, -1);
3404 		return -EROFS;
3405 	}
3406 
3407 	/* Invalidate the page cache, if we write to the cached page */
3408 	if (page == chip->pagebuf)
3409 		chip->pagebuf = -1;
3410 
3411 	nand_fill_oob(mtd, ops->oobbuf, ops->ooblen, ops);
3412 
3413 	if (ops->mode == MTD_OPS_RAW)
3414 		status = chip->ecc.write_oob_raw(mtd, chip, page & chip->pagemask);
3415 	else
3416 		status = chip->ecc.write_oob(mtd, chip, page & chip->pagemask);
3417 
3418 	chip->select_chip(mtd, -1);
3419 
3420 	if (status)
3421 		return status;
3422 
3423 	ops->oobretlen = ops->ooblen;
3424 
3425 	return 0;
3426 }
3427 
3428 /**
3429  * nand_write_oob - [MTD Interface] NAND write data and/or out-of-band
3430  * @mtd: MTD device structure
3431  * @to: offset to write to
3432  * @ops: oob operation description structure
3433  */
nand_write_oob(struct mtd_info * mtd,loff_t to,struct mtd_oob_ops * ops)3434 static int nand_write_oob(struct mtd_info *mtd, loff_t to,
3435 			  struct mtd_oob_ops *ops)
3436 {
3437 	int ret = -ENOTSUPP;
3438 
3439 	ops->retlen = 0;
3440 
3441 	/* Do not allow writes past end of device */
3442 	if (ops->datbuf && (to + ops->len) > mtd->size) {
3443 		pr_debug("%s: attempt to write beyond end of device\n",
3444 				__func__);
3445 		return -EINVAL;
3446 	}
3447 
3448 	nand_get_device(mtd, FL_WRITING);
3449 
3450 	switch (ops->mode) {
3451 	case MTD_OPS_PLACE_OOB:
3452 	case MTD_OPS_AUTO_OOB:
3453 	case MTD_OPS_RAW:
3454 		break;
3455 
3456 	default:
3457 		goto out;
3458 	}
3459 
3460 	if (!ops->datbuf)
3461 		ret = nand_do_write_oob(mtd, to, ops);
3462 	else
3463 		ret = nand_do_write_ops(mtd, to, ops);
3464 
3465 out:
3466 	nand_release_device(mtd);
3467 	return ret;
3468 }
3469 
3470 /**
3471  * single_erase - [GENERIC] NAND standard block erase command function
3472  * @mtd: MTD device structure
3473  * @page: the page address of the block which will be erased
3474  *
3475  * Standard erase command for NAND chips. Returns NAND status.
3476  */
single_erase(struct mtd_info * mtd,int page)3477 static int single_erase(struct mtd_info *mtd, int page)
3478 {
3479 	struct nand_chip *chip = mtd_to_nand(mtd);
3480 	unsigned int eraseblock;
3481 
3482 	/* Send commands to erase a block */
3483 	eraseblock = page >> (chip->phys_erase_shift - chip->page_shift);
3484 
3485 	return nand_erase_op(chip, eraseblock);
3486 }
3487 
3488 /**
3489  * nand_erase - [MTD Interface] erase block(s)
3490  * @mtd: MTD device structure
3491  * @instr: erase instruction
3492  *
3493  * Erase one ore more blocks.
3494  */
nand_erase(struct mtd_info * mtd,struct erase_info * instr)3495 static int nand_erase(struct mtd_info *mtd, struct erase_info *instr)
3496 {
3497 	return nand_erase_nand(mtd, instr, 0);
3498 }
3499 
3500 /**
3501  * nand_erase_nand - [INTERN] erase block(s)
3502  * @mtd: MTD device structure
3503  * @instr: erase instruction
3504  * @allowbbt: allow erasing the bbt area
3505  *
3506  * Erase one ore more blocks.
3507  */
nand_erase_nand(struct mtd_info * mtd,struct erase_info * instr,int allowbbt)3508 int nand_erase_nand(struct mtd_info *mtd, struct erase_info *instr,
3509 		    int allowbbt)
3510 {
3511 	int page, status, pages_per_block, ret, chipnr;
3512 	struct nand_chip *chip = mtd_to_nand(mtd);
3513 	loff_t len;
3514 
3515 	pr_debug("%s: start = 0x%012llx, len = %llu\n",
3516 			__func__, (unsigned long long)instr->addr,
3517 			(unsigned long long)instr->len);
3518 
3519 	if (check_offs_len(mtd, instr->addr, instr->len))
3520 		return -EINVAL;
3521 
3522 	/* Grab the lock and see if the device is available */
3523 	nand_get_device(mtd, FL_ERASING);
3524 
3525 	/* Shift to get first page */
3526 	page = (int)(instr->addr >> chip->page_shift);
3527 	chipnr = (int)(instr->addr >> chip->chip_shift);
3528 
3529 	/* Calculate pages in each block */
3530 	pages_per_block = 1 << (chip->phys_erase_shift - chip->page_shift);
3531 
3532 	/* Select the NAND device */
3533 	chip->select_chip(mtd, chipnr);
3534 
3535 	/* Check, if it is write protected */
3536 	if (nand_check_wp(mtd)) {
3537 		pr_debug("%s: device is write protected!\n",
3538 				__func__);
3539 		instr->state = MTD_ERASE_FAILED;
3540 		goto erase_exit;
3541 	}
3542 
3543 	/* Loop through the pages */
3544 	len = instr->len;
3545 
3546 	instr->state = MTD_ERASING;
3547 
3548 	while (len) {
3549 		WATCHDOG_RESET();
3550 
3551 		/* Check if we have a bad block, we do not erase bad blocks! */
3552 		if (!instr->scrub && nand_block_checkbad(mtd, ((loff_t) page) <<
3553 					chip->page_shift, allowbbt)) {
3554 			pr_warn("%s: attempt to erase a bad block at page 0x%08x\n",
3555 				    __func__, page);
3556 			instr->state = MTD_ERASE_FAILED;
3557 			goto erase_exit;
3558 		}
3559 
3560 		/*
3561 		 * Invalidate the page cache, if we erase the block which
3562 		 * contains the current cached page.
3563 		 */
3564 		if (page <= chip->pagebuf && chip->pagebuf <
3565 		    (page + pages_per_block))
3566 			chip->pagebuf = -1;
3567 
3568 		status = chip->erase(mtd, page & chip->pagemask);
3569 
3570 		/* See if block erase succeeded */
3571 		if (status & NAND_STATUS_FAIL) {
3572 			pr_debug("%s: failed erase, page 0x%08x\n",
3573 					__func__, page);
3574 			instr->state = MTD_ERASE_FAILED;
3575 			instr->fail_addr =
3576 				((loff_t)page << chip->page_shift);
3577 			goto erase_exit;
3578 		}
3579 
3580 		/* Increment page address and decrement length */
3581 		len -= (1ULL << chip->phys_erase_shift);
3582 		page += pages_per_block;
3583 
3584 		/* Check, if we cross a chip boundary */
3585 		if (len && !(page & chip->pagemask)) {
3586 			chipnr++;
3587 			chip->select_chip(mtd, -1);
3588 			chip->select_chip(mtd, chipnr);
3589 		}
3590 	}
3591 	instr->state = MTD_ERASE_DONE;
3592 
3593 erase_exit:
3594 
3595 	ret = instr->state == MTD_ERASE_DONE ? 0 : -EIO;
3596 
3597 	/* Deselect and wake up anyone waiting on the device */
3598 	chip->select_chip(mtd, -1);
3599 	nand_release_device(mtd);
3600 
3601 	/* Do call back function */
3602 	if (!ret)
3603 		mtd_erase_callback(instr);
3604 
3605 	/* Return more or less happy */
3606 	return ret;
3607 }
3608 
3609 /**
3610  * nand_sync - [MTD Interface] sync
3611  * @mtd: MTD device structure
3612  *
3613  * Sync is actually a wait for chip ready function.
3614  */
nand_sync(struct mtd_info * mtd)3615 static void nand_sync(struct mtd_info *mtd)
3616 {
3617 	pr_debug("%s: called\n", __func__);
3618 
3619 	/* Grab the lock and see if the device is available */
3620 	nand_get_device(mtd, FL_SYNCING);
3621 	/* Release it and go back */
3622 	nand_release_device(mtd);
3623 }
3624 
3625 /**
3626  * nand_block_isbad - [MTD Interface] Check if block at offset is bad
3627  * @mtd: MTD device structure
3628  * @offs: offset relative to mtd start
3629  */
nand_block_isbad(struct mtd_info * mtd,loff_t offs)3630 static int nand_block_isbad(struct mtd_info *mtd, loff_t offs)
3631 {
3632 	struct nand_chip *chip = mtd_to_nand(mtd);
3633 	int chipnr = (int)(offs >> chip->chip_shift);
3634 	int ret;
3635 
3636 	/* Select the NAND device */
3637 	nand_get_device(mtd, FL_READING);
3638 	chip->select_chip(mtd, chipnr);
3639 
3640 	ret = nand_block_checkbad(mtd, offs, 0);
3641 
3642 	chip->select_chip(mtd, -1);
3643 	nand_release_device(mtd);
3644 
3645 	return ret;
3646 }
3647 
3648 /**
3649  * nand_block_markbad - [MTD Interface] Mark block at the given offset as bad
3650  * @mtd: MTD device structure
3651  * @ofs: offset relative to mtd start
3652  */
nand_block_markbad(struct mtd_info * mtd,loff_t ofs)3653 static int nand_block_markbad(struct mtd_info *mtd, loff_t ofs)
3654 {
3655 	int ret;
3656 
3657 	ret = nand_block_isbad(mtd, ofs);
3658 	if (ret) {
3659 		/* If it was bad already, return success and do nothing */
3660 		if (ret > 0)
3661 			return 0;
3662 		return ret;
3663 	}
3664 
3665 	return nand_block_markbad_lowlevel(mtd, ofs);
3666 }
3667 
3668 /**
3669  * nand_onfi_set_features- [REPLACEABLE] set features for ONFI nand
3670  * @mtd: MTD device structure
3671  * @chip: nand chip info structure
3672  * @addr: feature address.
3673  * @subfeature_param: the subfeature parameters, a four bytes array.
3674  */
nand_onfi_set_features(struct mtd_info * mtd,struct nand_chip * chip,int addr,uint8_t * subfeature_param)3675 static int nand_onfi_set_features(struct mtd_info *mtd, struct nand_chip *chip,
3676 			int addr, uint8_t *subfeature_param)
3677 {
3678 #ifdef CONFIG_SYS_NAND_ONFI_DETECTION
3679 	if (!chip->onfi_version ||
3680 	    !(le16_to_cpu(chip->onfi_params.opt_cmd)
3681 	      & ONFI_OPT_CMD_SET_GET_FEATURES))
3682 		return -ENOTSUPP;
3683 #endif
3684 
3685 	return nand_set_features_op(chip, addr, subfeature_param);
3686 }
3687 
3688 /**
3689  * nand_onfi_get_features- [REPLACEABLE] get features for ONFI nand
3690  * @mtd: MTD device structure
3691  * @chip: nand chip info structure
3692  * @addr: feature address.
3693  * @subfeature_param: the subfeature parameters, a four bytes array.
3694  */
nand_onfi_get_features(struct mtd_info * mtd,struct nand_chip * chip,int addr,uint8_t * subfeature_param)3695 static int nand_onfi_get_features(struct mtd_info *mtd, struct nand_chip *chip,
3696 			int addr, uint8_t *subfeature_param)
3697 {
3698 #ifdef CONFIG_SYS_NAND_ONFI_DETECTION
3699 	if (!chip->onfi_version ||
3700 	    !(le16_to_cpu(chip->onfi_params.opt_cmd)
3701 	      & ONFI_OPT_CMD_SET_GET_FEATURES))
3702 		return -ENOTSUPP;
3703 #endif
3704 
3705 	return nand_get_features_op(chip, addr, subfeature_param);
3706 }
3707 
3708 /* Set default functions */
nand_set_defaults(struct nand_chip * chip,int busw)3709 static void nand_set_defaults(struct nand_chip *chip, int busw)
3710 {
3711 	/* check for proper chip_delay setup, set 20us if not */
3712 	if (!chip->chip_delay)
3713 		chip->chip_delay = 20;
3714 
3715 	/* check, if a user supplied command function given */
3716 	if (chip->cmdfunc == NULL)
3717 		chip->cmdfunc = nand_command;
3718 
3719 	/* check, if a user supplied wait function given */
3720 	if (chip->waitfunc == NULL)
3721 		chip->waitfunc = nand_wait;
3722 
3723 	if (!chip->select_chip)
3724 		chip->select_chip = nand_select_chip;
3725 
3726 	/* set for ONFI nand */
3727 	if (!chip->onfi_set_features)
3728 		chip->onfi_set_features = nand_onfi_set_features;
3729 	if (!chip->onfi_get_features)
3730 		chip->onfi_get_features = nand_onfi_get_features;
3731 
3732 	/* If called twice, pointers that depend on busw may need to be reset */
3733 	if (!chip->read_byte || chip->read_byte == nand_read_byte)
3734 		chip->read_byte = busw ? nand_read_byte16 : nand_read_byte;
3735 	if (!chip->read_word)
3736 		chip->read_word = nand_read_word;
3737 	if (!chip->block_bad)
3738 		chip->block_bad = nand_block_bad;
3739 	if (!chip->block_markbad)
3740 		chip->block_markbad = nand_default_block_markbad;
3741 	if (!chip->write_buf || chip->write_buf == nand_write_buf)
3742 		chip->write_buf = busw ? nand_write_buf16 : nand_write_buf;
3743 	if (!chip->write_byte || chip->write_byte == nand_write_byte)
3744 		chip->write_byte = busw ? nand_write_byte16 : nand_write_byte;
3745 	if (!chip->read_buf || chip->read_buf == nand_read_buf)
3746 		chip->read_buf = busw ? nand_read_buf16 : nand_read_buf;
3747 	if (!chip->scan_bbt)
3748 		chip->scan_bbt = nand_default_bbt;
3749 
3750 	if (!chip->controller) {
3751 		chip->controller = &chip->hwcontrol;
3752 		spin_lock_init(&chip->controller->lock);
3753 		init_waitqueue_head(&chip->controller->wq);
3754 	}
3755 
3756 	if (!chip->buf_align)
3757 		chip->buf_align = 1;
3758 }
3759 
3760 /* Sanitize ONFI strings so we can safely print them */
sanitize_string(char * s,size_t len)3761 static void sanitize_string(char *s, size_t len)
3762 {
3763 	ssize_t i;
3764 
3765 	/* Null terminate */
3766 	s[len - 1] = 0;
3767 
3768 	/* Remove non printable chars */
3769 	for (i = 0; i < len - 1; i++) {
3770 		if (s[i] < ' ' || s[i] > 127)
3771 			s[i] = '?';
3772 	}
3773 
3774 	/* Remove trailing spaces */
3775 	strim(s);
3776 }
3777 
onfi_crc16(u16 crc,u8 const * p,size_t len)3778 static u16 onfi_crc16(u16 crc, u8 const *p, size_t len)
3779 {
3780 	int i;
3781 	while (len--) {
3782 		crc ^= *p++ << 8;
3783 		for (i = 0; i < 8; i++)
3784 			crc = (crc << 1) ^ ((crc & 0x8000) ? 0x8005 : 0);
3785 	}
3786 
3787 	return crc;
3788 }
3789 
3790 #ifdef CONFIG_SYS_NAND_ONFI_DETECTION
3791 /* Parse the Extended Parameter Page. */
nand_flash_detect_ext_param_page(struct mtd_info * mtd,struct nand_chip * chip,struct nand_onfi_params * p)3792 static int nand_flash_detect_ext_param_page(struct mtd_info *mtd,
3793 		struct nand_chip *chip, struct nand_onfi_params *p)
3794 {
3795 	struct onfi_ext_param_page *ep;
3796 	struct onfi_ext_section *s;
3797 	struct onfi_ext_ecc_info *ecc;
3798 	uint8_t *cursor;
3799 	int ret;
3800 	int len;
3801 	int i;
3802 
3803 	len = le16_to_cpu(p->ext_param_page_length) * 16;
3804 	ep = kmalloc(len, GFP_KERNEL);
3805 	if (!ep)
3806 		return -ENOMEM;
3807 
3808 	/* Send our own NAND_CMD_PARAM. */
3809 	ret = nand_read_param_page_op(chip, 0, NULL, 0);
3810 	if (ret)
3811 		goto ext_out;
3812 
3813 	/* Use the Change Read Column command to skip the ONFI param pages. */
3814 	ret = nand_change_read_column_op(chip,
3815 					 sizeof(*p) * p->num_of_param_pages,
3816 					 ep, len, true);
3817 	if (ret)
3818 		goto ext_out;
3819 
3820 	ret = -EINVAL;
3821 	if ((onfi_crc16(ONFI_CRC_BASE, ((uint8_t *)ep) + 2, len - 2)
3822 		!= le16_to_cpu(ep->crc))) {
3823 		pr_debug("fail in the CRC.\n");
3824 		goto ext_out;
3825 	}
3826 
3827 	/*
3828 	 * Check the signature.
3829 	 * Do not strictly follow the ONFI spec, maybe changed in future.
3830 	 */
3831 	if (strncmp((char *)ep->sig, "EPPS", 4)) {
3832 		pr_debug("The signature is invalid.\n");
3833 		goto ext_out;
3834 	}
3835 
3836 	/* find the ECC section. */
3837 	cursor = (uint8_t *)(ep + 1);
3838 	for (i = 0; i < ONFI_EXT_SECTION_MAX; i++) {
3839 		s = ep->sections + i;
3840 		if (s->type == ONFI_SECTION_TYPE_2)
3841 			break;
3842 		cursor += s->length * 16;
3843 	}
3844 	if (i == ONFI_EXT_SECTION_MAX) {
3845 		pr_debug("We can not find the ECC section.\n");
3846 		goto ext_out;
3847 	}
3848 
3849 	/* get the info we want. */
3850 	ecc = (struct onfi_ext_ecc_info *)cursor;
3851 
3852 	if (!ecc->codeword_size) {
3853 		pr_debug("Invalid codeword size\n");
3854 		goto ext_out;
3855 	}
3856 
3857 	chip->ecc_strength_ds = ecc->ecc_bits;
3858 	chip->ecc_step_ds = 1 << ecc->codeword_size;
3859 	ret = 0;
3860 
3861 ext_out:
3862 	kfree(ep);
3863 	return ret;
3864 }
3865 
nand_setup_read_retry_micron(struct mtd_info * mtd,int retry_mode)3866 static int nand_setup_read_retry_micron(struct mtd_info *mtd, int retry_mode)
3867 {
3868 	struct nand_chip *chip = mtd_to_nand(mtd);
3869 	uint8_t feature[ONFI_SUBFEATURE_PARAM_LEN] = {retry_mode};
3870 
3871 	return chip->onfi_set_features(mtd, chip, ONFI_FEATURE_ADDR_READ_RETRY,
3872 			feature);
3873 }
3874 
3875 /*
3876  * Configure chip properties from Micron vendor-specific ONFI table
3877  */
nand_onfi_detect_micron(struct nand_chip * chip,struct nand_onfi_params * p)3878 static void nand_onfi_detect_micron(struct nand_chip *chip,
3879 		struct nand_onfi_params *p)
3880 {
3881 	struct nand_onfi_vendor_micron *micron = (void *)p->vendor;
3882 
3883 	if (le16_to_cpu(p->vendor_revision) < 1)
3884 		return;
3885 
3886 	chip->read_retries = micron->read_retry_options;
3887 	chip->setup_read_retry = nand_setup_read_retry_micron;
3888 }
3889 
3890 /*
3891  * Check if the NAND chip is ONFI compliant, returns 1 if it is, 0 otherwise.
3892  */
nand_flash_detect_onfi(struct mtd_info * mtd,struct nand_chip * chip,int * busw)3893 static int nand_flash_detect_onfi(struct mtd_info *mtd, struct nand_chip *chip,
3894 					int *busw)
3895 {
3896 	struct nand_onfi_params *p = &chip->onfi_params;
3897 	char id[4];
3898 	int i, ret, val;
3899 
3900 	/* Try ONFI for unknown chip or LP */
3901 	ret = nand_readid_op(chip, 0x20, id, sizeof(id));
3902 	if (ret || strncmp(id, "ONFI", 4))
3903 		return 0;
3904 
3905 	ret = nand_read_param_page_op(chip, 0, NULL, 0);
3906 	if (ret)
3907 		return 0;
3908 
3909 	for (i = 0; i < 3; i++) {
3910 		ret = nand_read_data_op(chip, p, sizeof(*p), true);
3911 		if (ret)
3912 			return 0;
3913 
3914 		if (onfi_crc16(ONFI_CRC_BASE, (uint8_t *)p, 254) ==
3915 				le16_to_cpu(p->crc)) {
3916 			break;
3917 		}
3918 	}
3919 
3920 	if (i == 3) {
3921 		pr_err("Could not find valid ONFI parameter page; aborting\n");
3922 		return 0;
3923 	}
3924 
3925 	/* Check version */
3926 	val = le16_to_cpu(p->revision);
3927 	if (val & (1 << 5))
3928 		chip->onfi_version = 23;
3929 	else if (val & (1 << 4))
3930 		chip->onfi_version = 22;
3931 	else if (val & (1 << 3))
3932 		chip->onfi_version = 21;
3933 	else if (val & (1 << 2))
3934 		chip->onfi_version = 20;
3935 	else if (val & (1 << 1))
3936 		chip->onfi_version = 10;
3937 
3938 	if (!chip->onfi_version) {
3939 		pr_info("unsupported ONFI version: %d\n", val);
3940 		return 0;
3941 	}
3942 
3943 	sanitize_string(p->manufacturer, sizeof(p->manufacturer));
3944 	sanitize_string(p->model, sizeof(p->model));
3945 	if (!mtd->name)
3946 		mtd->name = p->model;
3947 
3948 	mtd->writesize = le32_to_cpu(p->byte_per_page);
3949 
3950 	/*
3951 	 * pages_per_block and blocks_per_lun may not be a power-of-2 size
3952 	 * (don't ask me who thought of this...). MTD assumes that these
3953 	 * dimensions will be power-of-2, so just truncate the remaining area.
3954 	 */
3955 	mtd->erasesize = 1 << (fls(le32_to_cpu(p->pages_per_block)) - 1);
3956 	mtd->erasesize *= mtd->writesize;
3957 
3958 	mtd->oobsize = le16_to_cpu(p->spare_bytes_per_page);
3959 
3960 	/* See erasesize comment */
3961 	chip->chipsize = 1 << (fls(le32_to_cpu(p->blocks_per_lun)) - 1);
3962 	chip->chipsize *= (uint64_t)mtd->erasesize * p->lun_count;
3963 	chip->bits_per_cell = p->bits_per_cell;
3964 
3965 	if (onfi_feature(chip) & ONFI_FEATURE_16_BIT_BUS)
3966 		*busw = NAND_BUSWIDTH_16;
3967 	else
3968 		*busw = 0;
3969 
3970 	if (p->ecc_bits != 0xff) {
3971 		chip->ecc_strength_ds = p->ecc_bits;
3972 		chip->ecc_step_ds = 512;
3973 	} else if (chip->onfi_version >= 21 &&
3974 		(onfi_feature(chip) & ONFI_FEATURE_EXT_PARAM_PAGE)) {
3975 
3976 		/*
3977 		 * The nand_flash_detect_ext_param_page() uses the
3978 		 * Change Read Column command which maybe not supported
3979 		 * by the chip->cmdfunc. So try to update the chip->cmdfunc
3980 		 * now. We do not replace user supplied command function.
3981 		 */
3982 		if (mtd->writesize > 512 && chip->cmdfunc == nand_command)
3983 			chip->cmdfunc = nand_command_lp;
3984 
3985 		/* The Extended Parameter Page is supported since ONFI 2.1. */
3986 		if (nand_flash_detect_ext_param_page(mtd, chip, p))
3987 			pr_warn("Failed to detect ONFI extended param page\n");
3988 	} else {
3989 		pr_warn("Could not retrieve ONFI ECC requirements\n");
3990 	}
3991 
3992 	if (p->jedec_id == NAND_MFR_MICRON)
3993 		nand_onfi_detect_micron(chip, p);
3994 
3995 	return 1;
3996 }
3997 #else
nand_flash_detect_onfi(struct mtd_info * mtd,struct nand_chip * chip,int * busw)3998 static int nand_flash_detect_onfi(struct mtd_info *mtd, struct nand_chip *chip,
3999 					int *busw)
4000 {
4001 	return 0;
4002 }
4003 #endif
4004 
4005 /*
4006  * Check if the NAND chip is JEDEC compliant, returns 1 if it is, 0 otherwise.
4007  */
nand_flash_detect_jedec(struct mtd_info * mtd,struct nand_chip * chip,int * busw)4008 static int nand_flash_detect_jedec(struct mtd_info *mtd, struct nand_chip *chip,
4009 					int *busw)
4010 {
4011 	struct nand_jedec_params *p = &chip->jedec_params;
4012 	struct jedec_ecc_info *ecc;
4013 	char id[5];
4014 	int i, val, ret;
4015 
4016 	/* Try JEDEC for unknown chip or LP */
4017 	ret = nand_readid_op(chip, 0x40, id, sizeof(id));
4018 	if (ret || strncmp(id, "JEDEC", sizeof(id)))
4019 		return 0;
4020 
4021 	ret = nand_read_param_page_op(chip, 0x40, NULL, 0);
4022 	if (ret)
4023 		return 0;
4024 
4025 	for (i = 0; i < 3; i++) {
4026 		ret = nand_read_data_op(chip, p, sizeof(*p), true);
4027 		if (ret)
4028 			return 0;
4029 
4030 		if (onfi_crc16(ONFI_CRC_BASE, (uint8_t *)p, 510) ==
4031 				le16_to_cpu(p->crc))
4032 			break;
4033 	}
4034 
4035 	if (i == 3) {
4036 		pr_err("Could not find valid JEDEC parameter page; aborting\n");
4037 		return 0;
4038 	}
4039 
4040 	/* Check version */
4041 	val = le16_to_cpu(p->revision);
4042 	if (val & (1 << 2))
4043 		chip->jedec_version = 10;
4044 	else if (val & (1 << 1))
4045 		chip->jedec_version = 1; /* vendor specific version */
4046 
4047 	if (!chip->jedec_version) {
4048 		pr_info("unsupported JEDEC version: %d\n", val);
4049 		return 0;
4050 	}
4051 
4052 	sanitize_string(p->manufacturer, sizeof(p->manufacturer));
4053 	sanitize_string(p->model, sizeof(p->model));
4054 	if (!mtd->name)
4055 		mtd->name = p->model;
4056 
4057 	mtd->writesize = le32_to_cpu(p->byte_per_page);
4058 
4059 	/* Please reference to the comment for nand_flash_detect_onfi. */
4060 	mtd->erasesize = 1 << (fls(le32_to_cpu(p->pages_per_block)) - 1);
4061 	mtd->erasesize *= mtd->writesize;
4062 
4063 	mtd->oobsize = le16_to_cpu(p->spare_bytes_per_page);
4064 
4065 	/* Please reference to the comment for nand_flash_detect_onfi. */
4066 	chip->chipsize = 1 << (fls(le32_to_cpu(p->blocks_per_lun)) - 1);
4067 	chip->chipsize *= (uint64_t)mtd->erasesize * p->lun_count;
4068 	chip->bits_per_cell = p->bits_per_cell;
4069 
4070 	if (jedec_feature(chip) & JEDEC_FEATURE_16_BIT_BUS)
4071 		*busw = NAND_BUSWIDTH_16;
4072 	else
4073 		*busw = 0;
4074 
4075 	/* ECC info */
4076 	ecc = &p->ecc_info[0];
4077 
4078 	if (ecc->codeword_size >= 9) {
4079 		chip->ecc_strength_ds = ecc->ecc_bits;
4080 		chip->ecc_step_ds = 1 << ecc->codeword_size;
4081 	} else {
4082 		pr_warn("Invalid codeword size\n");
4083 	}
4084 
4085 	return 1;
4086 }
4087 
4088 /*
4089  * nand_id_has_period - Check if an ID string has a given wraparound period
4090  * @id_data: the ID string
4091  * @arrlen: the length of the @id_data array
4092  * @period: the period of repitition
4093  *
4094  * Check if an ID string is repeated within a given sequence of bytes at
4095  * specific repetition interval period (e.g., {0x20,0x01,0x7F,0x20} has a
4096  * period of 3). This is a helper function for nand_id_len(). Returns non-zero
4097  * if the repetition has a period of @period; otherwise, returns zero.
4098  */
nand_id_has_period(u8 * id_data,int arrlen,int period)4099 static int nand_id_has_period(u8 *id_data, int arrlen, int period)
4100 {
4101 	int i, j;
4102 	for (i = 0; i < period; i++)
4103 		for (j = i + period; j < arrlen; j += period)
4104 			if (id_data[i] != id_data[j])
4105 				return 0;
4106 	return 1;
4107 }
4108 
4109 /*
4110  * nand_id_len - Get the length of an ID string returned by CMD_READID
4111  * @id_data: the ID string
4112  * @arrlen: the length of the @id_data array
4113 
4114  * Returns the length of the ID string, according to known wraparound/trailing
4115  * zero patterns. If no pattern exists, returns the length of the array.
4116  */
nand_id_len(u8 * id_data,int arrlen)4117 static int nand_id_len(u8 *id_data, int arrlen)
4118 {
4119 	int last_nonzero, period;
4120 
4121 	/* Find last non-zero byte */
4122 	for (last_nonzero = arrlen - 1; last_nonzero >= 0; last_nonzero--)
4123 		if (id_data[last_nonzero])
4124 			break;
4125 
4126 	/* All zeros */
4127 	if (last_nonzero < 0)
4128 		return 0;
4129 
4130 	/* Calculate wraparound period */
4131 	for (period = 1; period < arrlen; period++)
4132 		if (nand_id_has_period(id_data, arrlen, period))
4133 			break;
4134 
4135 	/* There's a repeated pattern */
4136 	if (period < arrlen)
4137 		return period;
4138 
4139 	/* There are trailing zeros */
4140 	if (last_nonzero < arrlen - 1)
4141 		return last_nonzero + 1;
4142 
4143 	/* No pattern detected */
4144 	return arrlen;
4145 }
4146 
4147 /* Extract the bits of per cell from the 3rd byte of the extended ID */
nand_get_bits_per_cell(u8 cellinfo)4148 static int nand_get_bits_per_cell(u8 cellinfo)
4149 {
4150 	int bits;
4151 
4152 	bits = cellinfo & NAND_CI_CELLTYPE_MSK;
4153 	bits >>= NAND_CI_CELLTYPE_SHIFT;
4154 	return bits + 1;
4155 }
4156 
4157 /*
4158  * Many new NAND share similar device ID codes, which represent the size of the
4159  * chip. The rest of the parameters must be decoded according to generic or
4160  * manufacturer-specific "extended ID" decoding patterns.
4161  */
nand_decode_ext_id(struct mtd_info * mtd,struct nand_chip * chip,u8 id_data[8],int * busw)4162 static void nand_decode_ext_id(struct mtd_info *mtd, struct nand_chip *chip,
4163 				u8 id_data[8], int *busw)
4164 {
4165 	int extid, id_len;
4166 	/* The 3rd id byte holds MLC / multichip data */
4167 	chip->bits_per_cell = nand_get_bits_per_cell(id_data[2]);
4168 	/* The 4th id byte is the important one */
4169 	extid = id_data[3];
4170 
4171 	id_len = nand_id_len(id_data, 8);
4172 
4173 	/*
4174 	 * Field definitions are in the following datasheets:
4175 	 * Old style (4,5 byte ID): Samsung K9GAG08U0M (p.32)
4176 	 * New Samsung (6 byte ID): Samsung K9GAG08U0F (p.44)
4177 	 * Hynix MLC   (6 byte ID): Hynix H27UBG8T2B (p.22)
4178 	 *
4179 	 * Check for ID length, non-zero 6th byte, cell type, and Hynix/Samsung
4180 	 * ID to decide what to do.
4181 	 */
4182 	if (id_len == 6 && id_data[0] == NAND_MFR_SAMSUNG &&
4183 			!nand_is_slc(chip) && id_data[5] != 0x00) {
4184 		/* Calc pagesize */
4185 		mtd->writesize = 2048 << (extid & 0x03);
4186 		extid >>= 2;
4187 		/* Calc oobsize */
4188 		switch (((extid >> 2) & 0x04) | (extid & 0x03)) {
4189 		case 1:
4190 			mtd->oobsize = 128;
4191 			break;
4192 		case 2:
4193 			mtd->oobsize = 218;
4194 			break;
4195 		case 3:
4196 			mtd->oobsize = 400;
4197 			break;
4198 		case 4:
4199 			mtd->oobsize = 436;
4200 			break;
4201 		case 5:
4202 			mtd->oobsize = 512;
4203 			break;
4204 		case 6:
4205 			mtd->oobsize = 640;
4206 			break;
4207 		case 7:
4208 		default: /* Other cases are "reserved" (unknown) */
4209 			mtd->oobsize = 1024;
4210 			break;
4211 		}
4212 		extid >>= 2;
4213 		/* Calc blocksize */
4214 		mtd->erasesize = (128 * 1024) <<
4215 			(((extid >> 1) & 0x04) | (extid & 0x03));
4216 		*busw = 0;
4217 	} else if (id_len == 6 && id_data[0] == NAND_MFR_HYNIX &&
4218 			!nand_is_slc(chip)) {
4219 		unsigned int tmp;
4220 
4221 		/* Calc pagesize */
4222 		mtd->writesize = 2048 << (extid & 0x03);
4223 		extid >>= 2;
4224 		/* Calc oobsize */
4225 		switch (((extid >> 2) & 0x04) | (extid & 0x03)) {
4226 		case 0:
4227 			mtd->oobsize = 128;
4228 			break;
4229 		case 1:
4230 			mtd->oobsize = 224;
4231 			break;
4232 		case 2:
4233 			mtd->oobsize = 448;
4234 			break;
4235 		case 3:
4236 			mtd->oobsize = 64;
4237 			break;
4238 		case 4:
4239 			mtd->oobsize = 32;
4240 			break;
4241 		case 5:
4242 			mtd->oobsize = 16;
4243 			break;
4244 		default:
4245 			mtd->oobsize = 640;
4246 			break;
4247 		}
4248 		extid >>= 2;
4249 		/* Calc blocksize */
4250 		tmp = ((extid >> 1) & 0x04) | (extid & 0x03);
4251 		if (tmp < 0x03)
4252 			mtd->erasesize = (128 * 1024) << tmp;
4253 		else if (tmp == 0x03)
4254 			mtd->erasesize = 768 * 1024;
4255 		else
4256 			mtd->erasesize = (64 * 1024) << tmp;
4257 		*busw = 0;
4258 	} else {
4259 		/* Calc pagesize */
4260 		mtd->writesize = 1024 << (extid & 0x03);
4261 		extid >>= 2;
4262 		/* Calc oobsize */
4263 		mtd->oobsize = (8 << (extid & 0x01)) *
4264 			(mtd->writesize >> 9);
4265 		extid >>= 2;
4266 		/* Calc blocksize. Blocksize is multiples of 64KiB */
4267 		mtd->erasesize = (64 * 1024) << (extid & 0x03);
4268 		extid >>= 2;
4269 		/* Get buswidth information */
4270 		*busw = (extid & 0x01) ? NAND_BUSWIDTH_16 : 0;
4271 
4272 		/*
4273 		 * Toshiba 24nm raw SLC (i.e., not BENAND) have 32B OOB per
4274 		 * 512B page. For Toshiba SLC, we decode the 5th/6th byte as
4275 		 * follows:
4276 		 * - ID byte 6, bits[2:0]: 100b -> 43nm, 101b -> 32nm,
4277 		 *                         110b -> 24nm
4278 		 * - ID byte 5, bit[7]:    1 -> BENAND, 0 -> raw SLC
4279 		 */
4280 		if (id_len >= 6 && id_data[0] == NAND_MFR_TOSHIBA &&
4281 				nand_is_slc(chip) &&
4282 				(id_data[5] & 0x7) == 0x6 /* 24nm */ &&
4283 				!(id_data[4] & 0x80) /* !BENAND */) {
4284 			mtd->oobsize = 32 * mtd->writesize >> 9;
4285 		}
4286 
4287 	}
4288 }
4289 
4290 /*
4291  * Old devices have chip data hardcoded in the device ID table. nand_decode_id
4292  * decodes a matching ID table entry and assigns the MTD size parameters for
4293  * the chip.
4294  */
nand_decode_id(struct mtd_info * mtd,struct nand_chip * chip,struct nand_flash_dev * type,u8 id_data[8],int * busw)4295 static void nand_decode_id(struct mtd_info *mtd, struct nand_chip *chip,
4296 				struct nand_flash_dev *type, u8 id_data[8],
4297 				int *busw)
4298 {
4299 	int maf_id = id_data[0];
4300 
4301 	mtd->erasesize = type->erasesize;
4302 	mtd->writesize = type->pagesize;
4303 	mtd->oobsize = mtd->writesize / 32;
4304 	*busw = type->options & NAND_BUSWIDTH_16;
4305 
4306 	/* All legacy ID NAND are small-page, SLC */
4307 	chip->bits_per_cell = 1;
4308 
4309 	/*
4310 	 * Check for Spansion/AMD ID + repeating 5th, 6th byte since
4311 	 * some Spansion chips have erasesize that conflicts with size
4312 	 * listed in nand_ids table.
4313 	 * Data sheet (5 byte ID): Spansion S30ML-P ORNAND (p.39)
4314 	 */
4315 	if (maf_id == NAND_MFR_AMD && id_data[4] != 0x00 && id_data[5] == 0x00
4316 			&& id_data[6] == 0x00 && id_data[7] == 0x00
4317 			&& mtd->writesize == 512) {
4318 		mtd->erasesize = 128 * 1024;
4319 		mtd->erasesize <<= ((id_data[3] & 0x03) << 1);
4320 	}
4321 }
4322 
4323 /*
4324  * Set the bad block marker/indicator (BBM/BBI) patterns according to some
4325  * heuristic patterns using various detected parameters (e.g., manufacturer,
4326  * page size, cell-type information).
4327  */
nand_decode_bbm_options(struct mtd_info * mtd,struct nand_chip * chip,u8 id_data[8])4328 static void nand_decode_bbm_options(struct mtd_info *mtd,
4329 				    struct nand_chip *chip, u8 id_data[8])
4330 {
4331 	int maf_id = id_data[0];
4332 
4333 	/* Set the bad block position */
4334 	if (mtd->writesize > 512 || (chip->options & NAND_BUSWIDTH_16))
4335 		chip->badblockpos = NAND_LARGE_BADBLOCK_POS;
4336 	else
4337 		chip->badblockpos = NAND_SMALL_BADBLOCK_POS;
4338 
4339 	/*
4340 	 * Bad block marker is stored in the last page of each block on Samsung
4341 	 * and Hynix MLC devices; stored in first two pages of each block on
4342 	 * Micron devices with 2KiB pages and on SLC Samsung, Hynix, Toshiba,
4343 	 * AMD/Spansion, and Macronix.  All others scan only the first page.
4344 	 */
4345 	if (!nand_is_slc(chip) &&
4346 			(maf_id == NAND_MFR_SAMSUNG ||
4347 			 maf_id == NAND_MFR_HYNIX))
4348 		chip->bbt_options |= NAND_BBT_SCANLASTPAGE;
4349 	else if ((nand_is_slc(chip) &&
4350 				(maf_id == NAND_MFR_SAMSUNG ||
4351 				 maf_id == NAND_MFR_HYNIX ||
4352 				 maf_id == NAND_MFR_TOSHIBA ||
4353 				 maf_id == NAND_MFR_AMD ||
4354 				 maf_id == NAND_MFR_MACRONIX)) ||
4355 			(mtd->writesize == 2048 &&
4356 			 maf_id == NAND_MFR_MICRON))
4357 		chip->bbt_options |= NAND_BBT_SCAN2NDPAGE;
4358 }
4359 
is_full_id_nand(struct nand_flash_dev * type)4360 static inline bool is_full_id_nand(struct nand_flash_dev *type)
4361 {
4362 	return type->id_len;
4363 }
4364 
find_full_id_nand(struct mtd_info * mtd,struct nand_chip * chip,struct nand_flash_dev * type,u8 * id_data,int * busw)4365 static bool find_full_id_nand(struct mtd_info *mtd, struct nand_chip *chip,
4366 		   struct nand_flash_dev *type, u8 *id_data, int *busw)
4367 {
4368 	if (!strncmp((char *)type->id, (char *)id_data, type->id_len)) {
4369 		mtd->writesize = type->pagesize;
4370 		mtd->erasesize = type->erasesize;
4371 		mtd->oobsize = type->oobsize;
4372 
4373 		chip->bits_per_cell = nand_get_bits_per_cell(id_data[2]);
4374 		chip->chipsize = (uint64_t)type->chipsize << 20;
4375 		chip->options |= type->options;
4376 		chip->ecc_strength_ds = NAND_ECC_STRENGTH(type);
4377 		chip->ecc_step_ds = NAND_ECC_STEP(type);
4378 		chip->onfi_timing_mode_default =
4379 					type->onfi_timing_mode_default;
4380 
4381 		*busw = type->options & NAND_BUSWIDTH_16;
4382 
4383 		if (!mtd->name)
4384 			mtd->name = type->name;
4385 
4386 		return true;
4387 	}
4388 	return false;
4389 }
4390 
4391 /*
4392  * Get the flash and manufacturer id and lookup if the type is supported.
4393  */
nand_get_flash_type(struct mtd_info * mtd,struct nand_chip * chip,int * maf_id,int * dev_id,struct nand_flash_dev * type)4394 struct nand_flash_dev *nand_get_flash_type(struct mtd_info *mtd,
4395 						  struct nand_chip *chip,
4396 						  int *maf_id, int *dev_id,
4397 						  struct nand_flash_dev *type)
4398 {
4399 	int busw, ret;
4400 	int maf_idx;
4401 	u8 id_data[8];
4402 
4403 	/*
4404 	 * Reset the chip, required by some chips (e.g. Micron MT29FxGxxxxx)
4405 	 * after power-up.
4406 	 */
4407 	ret = nand_reset(chip, 0);
4408 	if (ret)
4409 		return ERR_PTR(ret);
4410 
4411 	/* Select the device */
4412 	chip->select_chip(mtd, 0);
4413 
4414 	/* Send the command for reading device ID */
4415 	ret = nand_readid_op(chip, 0, id_data, 2);
4416 	if (ret)
4417 		return ERR_PTR(ret);
4418 
4419 	/* Read manufacturer and device IDs */
4420 	*maf_id = id_data[0];
4421 	*dev_id = id_data[1];
4422 
4423 	/*
4424 	 * Try again to make sure, as some systems the bus-hold or other
4425 	 * interface concerns can cause random data which looks like a
4426 	 * possibly credible NAND flash to appear. If the two results do
4427 	 * not match, ignore the device completely.
4428 	 */
4429 
4430 	/* Read entire ID string */
4431 	ret = nand_readid_op(chip, 0, id_data, 8);
4432 	if (ret)
4433 		return ERR_PTR(ret);
4434 
4435 	if (id_data[0] != *maf_id || id_data[1] != *dev_id) {
4436 		pr_info("second ID read did not match %02x,%02x against %02x,%02x\n",
4437 			*maf_id, *dev_id, id_data[0], id_data[1]);
4438 		return ERR_PTR(-ENODEV);
4439 	}
4440 
4441 	if (!type)
4442 		type = nand_flash_ids;
4443 
4444 	for (; type->name != NULL; type++) {
4445 		if (is_full_id_nand(type)) {
4446 			if (find_full_id_nand(mtd, chip, type, id_data, &busw))
4447 				goto ident_done;
4448 		} else if (*dev_id == type->dev_id) {
4449 			break;
4450 		}
4451 	}
4452 
4453 	chip->onfi_version = 0;
4454 	if (!type->name || !type->pagesize) {
4455 		/* Check if the chip is ONFI compliant */
4456 		if (nand_flash_detect_onfi(mtd, chip, &busw))
4457 			goto ident_done;
4458 
4459 		/* Check if the chip is JEDEC compliant */
4460 		if (nand_flash_detect_jedec(mtd, chip, &busw))
4461 			goto ident_done;
4462 	}
4463 
4464 	if (!type->name)
4465 		return ERR_PTR(-ENODEV);
4466 
4467 	if (!mtd->name)
4468 		mtd->name = type->name;
4469 
4470 	chip->chipsize = (uint64_t)type->chipsize << 20;
4471 
4472 	if (!type->pagesize) {
4473 		/* Decode parameters from extended ID */
4474 		nand_decode_ext_id(mtd, chip, id_data, &busw);
4475 	} else {
4476 		nand_decode_id(mtd, chip, type, id_data, &busw);
4477 	}
4478 	/* Get chip options */
4479 	chip->options |= type->options;
4480 
4481 	/*
4482 	 * Check if chip is not a Samsung device. Do not clear the
4483 	 * options for chips which do not have an extended id.
4484 	 */
4485 	if (*maf_id != NAND_MFR_SAMSUNG && !type->pagesize)
4486 		chip->options &= ~NAND_SAMSUNG_LP_OPTIONS;
4487 ident_done:
4488 
4489 	/* Try to identify manufacturer */
4490 	for (maf_idx = 0; nand_manuf_ids[maf_idx].id != 0x0; maf_idx++) {
4491 		if (nand_manuf_ids[maf_idx].id == *maf_id)
4492 			break;
4493 	}
4494 
4495 	if (chip->options & NAND_BUSWIDTH_AUTO) {
4496 		WARN_ON(chip->options & NAND_BUSWIDTH_16);
4497 		chip->options |= busw;
4498 		nand_set_defaults(chip, busw);
4499 	} else if (busw != (chip->options & NAND_BUSWIDTH_16)) {
4500 		/*
4501 		 * Check, if buswidth is correct. Hardware drivers should set
4502 		 * chip correct!
4503 		 */
4504 		pr_info("device found, Manufacturer ID: 0x%02x, Chip ID: 0x%02x\n",
4505 			*maf_id, *dev_id);
4506 		pr_info("%s %s\n", nand_manuf_ids[maf_idx].name, mtd->name);
4507 		pr_warn("bus width %d instead %d bit\n",
4508 			   (chip->options & NAND_BUSWIDTH_16) ? 16 : 8,
4509 			   busw ? 16 : 8);
4510 		return ERR_PTR(-EINVAL);
4511 	}
4512 
4513 	nand_decode_bbm_options(mtd, chip, id_data);
4514 
4515 	/* Calculate the address shift from the page size */
4516 	chip->page_shift = ffs(mtd->writesize) - 1;
4517 	/* Convert chipsize to number of pages per chip -1 */
4518 	chip->pagemask = (chip->chipsize >> chip->page_shift) - 1;
4519 
4520 	chip->bbt_erase_shift = chip->phys_erase_shift =
4521 		ffs(mtd->erasesize) - 1;
4522 	if (chip->chipsize & 0xffffffff)
4523 		chip->chip_shift = ffs((unsigned)chip->chipsize) - 1;
4524 	else {
4525 		chip->chip_shift = ffs((unsigned)(chip->chipsize >> 32));
4526 		chip->chip_shift += 32 - 1;
4527 	}
4528 
4529 	if (chip->chip_shift - chip->page_shift > 16)
4530 		chip->options |= NAND_ROW_ADDR_3;
4531 
4532 	chip->badblockbits = 8;
4533 	chip->erase = single_erase;
4534 
4535 	/* Do not replace user supplied command function! */
4536 	if (mtd->writesize > 512 && chip->cmdfunc == nand_command)
4537 		chip->cmdfunc = nand_command_lp;
4538 
4539 	pr_info("device found, Manufacturer ID: 0x%02x, Chip ID: 0x%02x\n",
4540 		*maf_id, *dev_id);
4541 
4542 #ifdef CONFIG_SYS_NAND_ONFI_DETECTION
4543 	if (chip->onfi_version)
4544 		pr_info("%s %s\n", nand_manuf_ids[maf_idx].name,
4545 				chip->onfi_params.model);
4546 	else if (chip->jedec_version)
4547 		pr_info("%s %s\n", nand_manuf_ids[maf_idx].name,
4548 				chip->jedec_params.model);
4549 	else
4550 		pr_info("%s %s\n", nand_manuf_ids[maf_idx].name,
4551 				type->name);
4552 #else
4553 	if (chip->jedec_version)
4554 		pr_info("%s %s\n", nand_manuf_ids[maf_idx].name,
4555 				chip->jedec_params.model);
4556 	else
4557 		pr_info("%s %s\n", nand_manuf_ids[maf_idx].name,
4558 				type->name);
4559 
4560 	pr_info("%s %s\n", nand_manuf_ids[maf_idx].name,
4561 		type->name);
4562 #endif
4563 
4564 	pr_info("%d MiB, %s, erase size: %d KiB, page size: %d, OOB size: %d\n",
4565 		(int)(chip->chipsize >> 20), nand_is_slc(chip) ? "SLC" : "MLC",
4566 		mtd->erasesize >> 10, mtd->writesize, mtd->oobsize);
4567 	return type;
4568 }
4569 EXPORT_SYMBOL(nand_get_flash_type);
4570 
4571 #if CONFIG_IS_ENABLED(OF_CONTROL)
4572 DECLARE_GLOBAL_DATA_PTR;
4573 
nand_dt_init(struct mtd_info * mtd,struct nand_chip * chip,int node)4574 static int nand_dt_init(struct mtd_info *mtd, struct nand_chip *chip, int node)
4575 {
4576 	int ret, ecc_mode = -1, ecc_strength, ecc_step;
4577 	const void *blob = gd->fdt_blob;
4578 	const char *str;
4579 
4580 	ret = fdtdec_get_int(blob, node, "nand-bus-width", -1);
4581 	if (ret == 16)
4582 		chip->options |= NAND_BUSWIDTH_16;
4583 
4584 	if (fdtdec_get_bool(blob, node, "nand-on-flash-bbt"))
4585 		chip->bbt_options |= NAND_BBT_USE_FLASH;
4586 
4587 	str = fdt_getprop(blob, node, "nand-ecc-mode", NULL);
4588 	if (str) {
4589 		if (!strcmp(str, "none"))
4590 			ecc_mode = NAND_ECC_NONE;
4591 		else if (!strcmp(str, "soft"))
4592 			ecc_mode = NAND_ECC_SOFT;
4593 		else if (!strcmp(str, "hw"))
4594 			ecc_mode = NAND_ECC_HW;
4595 		else if (!strcmp(str, "hw_syndrome"))
4596 			ecc_mode = NAND_ECC_HW_SYNDROME;
4597 		else if (!strcmp(str, "hw_oob_first"))
4598 			ecc_mode = NAND_ECC_HW_OOB_FIRST;
4599 		else if (!strcmp(str, "soft_bch"))
4600 			ecc_mode = NAND_ECC_SOFT_BCH;
4601 	}
4602 
4603 
4604 	ecc_strength = fdtdec_get_int(blob, node, "nand-ecc-strength", -1);
4605 	ecc_step = fdtdec_get_int(blob, node, "nand-ecc-step-size", -1);
4606 
4607 	if ((ecc_step >= 0 && !(ecc_strength >= 0)) ||
4608 	    (!(ecc_step >= 0) && ecc_strength >= 0)) {
4609 		pr_err("must set both strength and step size in DT\n");
4610 		return -EINVAL;
4611 	}
4612 
4613 	if (ecc_mode >= 0)
4614 		chip->ecc.mode = ecc_mode;
4615 
4616 	if (ecc_strength >= 0)
4617 		chip->ecc.strength = ecc_strength;
4618 
4619 	if (ecc_step > 0)
4620 		chip->ecc.size = ecc_step;
4621 
4622 	if (fdt_getprop(blob, node, "nand-ecc-maximize", NULL))
4623 		chip->ecc.options |= NAND_ECC_MAXIMIZE;
4624 
4625 	return 0;
4626 }
4627 #else
nand_dt_init(struct mtd_info * mtd,struct nand_chip * chip,int node)4628 static int nand_dt_init(struct mtd_info *mtd, struct nand_chip *chip, int node)
4629 {
4630 	return 0;
4631 }
4632 #endif /* CONFIG_IS_ENABLED(OF_CONTROL) */
4633 
4634 /**
4635  * nand_scan_ident - [NAND Interface] Scan for the NAND device
4636  * @mtd: MTD device structure
4637  * @maxchips: number of chips to scan for
4638  * @table: alternative NAND ID table
4639  *
4640  * This is the first phase of the normal nand_scan() function. It reads the
4641  * flash ID and sets up MTD fields accordingly.
4642  *
4643  */
nand_scan_ident(struct mtd_info * mtd,int maxchips,struct nand_flash_dev * table)4644 int nand_scan_ident(struct mtd_info *mtd, int maxchips,
4645 		    struct nand_flash_dev *table)
4646 {
4647 	int i, nand_maf_id, nand_dev_id;
4648 	struct nand_chip *chip = mtd_to_nand(mtd);
4649 	struct nand_flash_dev *type;
4650 	int ret;
4651 
4652 	if (chip->flash_node) {
4653 		ret = nand_dt_init(mtd, chip, chip->flash_node);
4654 		if (ret)
4655 			return ret;
4656 	}
4657 
4658 	/* Set the default functions */
4659 	nand_set_defaults(chip, chip->options & NAND_BUSWIDTH_16);
4660 
4661 	/* Read the flash type */
4662 	type = nand_get_flash_type(mtd, chip, &nand_maf_id,
4663 				   &nand_dev_id, table);
4664 
4665 	if (IS_ERR(type)) {
4666 		if (!(chip->options & NAND_SCAN_SILENT_NODEV))
4667 			pr_warn("No NAND device found\n");
4668 		chip->select_chip(mtd, -1);
4669 		return PTR_ERR(type);
4670 	}
4671 
4672 	/* Initialize the ->data_interface field. */
4673 	ret = nand_init_data_interface(chip);
4674 	if (ret)
4675 		return ret;
4676 
4677 	/*
4678 	 * Setup the data interface correctly on the chip and controller side.
4679 	 * This explicit call to nand_setup_data_interface() is only required
4680 	 * for the first die, because nand_reset() has been called before
4681 	 * ->data_interface and ->default_onfi_timing_mode were set.
4682 	 * For the other dies, nand_reset() will automatically switch to the
4683 	 * best mode for us.
4684 	 */
4685 	ret = nand_setup_data_interface(chip, 0);
4686 	if (ret)
4687 		return ret;
4688 
4689 	chip->select_chip(mtd, -1);
4690 
4691 	/* Check for a chip array */
4692 	for (i = 1; i < maxchips; i++) {
4693 		u8 id[2];
4694 
4695 		/* See comment in nand_get_flash_type for reset */
4696 		nand_reset(chip, i);
4697 
4698 		chip->select_chip(mtd, i);
4699 		/* Send the command for reading device ID */
4700 		nand_readid_op(chip, 0, id, sizeof(id));
4701 
4702 		/* Read manufacturer and device IDs */
4703 		if (nand_maf_id != id[0] || nand_dev_id != id[1]) {
4704 			chip->select_chip(mtd, -1);
4705 			break;
4706 		}
4707 		chip->select_chip(mtd, -1);
4708 	}
4709 
4710 #ifdef DEBUG
4711 	if (i > 1)
4712 		pr_info("%d chips detected\n", i);
4713 #endif
4714 
4715 	/* Store the number of chips and calc total size for mtd */
4716 	chip->numchips = i;
4717 	mtd->size = i * chip->chipsize;
4718 
4719 	return 0;
4720 }
4721 EXPORT_SYMBOL(nand_scan_ident);
4722 
4723 /**
4724  * nand_check_ecc_caps - check the sanity of preset ECC settings
4725  * @chip: nand chip info structure
4726  * @caps: ECC caps info structure
4727  * @oobavail: OOB size that the ECC engine can use
4728  *
4729  * When ECC step size and strength are already set, check if they are supported
4730  * by the controller and the calculated ECC bytes fit within the chip's OOB.
4731  * On success, the calculated ECC bytes is set.
4732  */
nand_check_ecc_caps(struct nand_chip * chip,const struct nand_ecc_caps * caps,int oobavail)4733 int nand_check_ecc_caps(struct nand_chip *chip,
4734 			const struct nand_ecc_caps *caps, int oobavail)
4735 {
4736 	struct mtd_info *mtd = nand_to_mtd(chip);
4737 	const struct nand_ecc_step_info *stepinfo;
4738 	int preset_step = chip->ecc.size;
4739 	int preset_strength = chip->ecc.strength;
4740 	int nsteps, ecc_bytes;
4741 	int i, j;
4742 
4743 	if (WARN_ON(oobavail < 0))
4744 		return -EINVAL;
4745 
4746 	if (!preset_step || !preset_strength)
4747 		return -ENODATA;
4748 
4749 	nsteps = mtd->writesize / preset_step;
4750 
4751 	for (i = 0; i < caps->nstepinfos; i++) {
4752 		stepinfo = &caps->stepinfos[i];
4753 
4754 		if (stepinfo->stepsize != preset_step)
4755 			continue;
4756 
4757 		for (j = 0; j < stepinfo->nstrengths; j++) {
4758 			if (stepinfo->strengths[j] != preset_strength)
4759 				continue;
4760 
4761 			ecc_bytes = caps->calc_ecc_bytes(preset_step,
4762 							 preset_strength);
4763 			if (WARN_ON_ONCE(ecc_bytes < 0))
4764 				return ecc_bytes;
4765 
4766 			if (ecc_bytes * nsteps > oobavail) {
4767 				pr_err("ECC (step, strength) = (%d, %d) does not fit in OOB",
4768 				       preset_step, preset_strength);
4769 				return -ENOSPC;
4770 			}
4771 
4772 			chip->ecc.bytes = ecc_bytes;
4773 
4774 			return 0;
4775 		}
4776 	}
4777 
4778 	pr_err("ECC (step, strength) = (%d, %d) not supported on this controller",
4779 	       preset_step, preset_strength);
4780 
4781 	return -ENOTSUPP;
4782 }
4783 EXPORT_SYMBOL_GPL(nand_check_ecc_caps);
4784 
4785 /**
4786  * nand_match_ecc_req - meet the chip's requirement with least ECC bytes
4787  * @chip: nand chip info structure
4788  * @caps: ECC engine caps info structure
4789  * @oobavail: OOB size that the ECC engine can use
4790  *
4791  * If a chip's ECC requirement is provided, try to meet it with the least
4792  * number of ECC bytes (i.e. with the largest number of OOB-free bytes).
4793  * On success, the chosen ECC settings are set.
4794  */
nand_match_ecc_req(struct nand_chip * chip,const struct nand_ecc_caps * caps,int oobavail)4795 int nand_match_ecc_req(struct nand_chip *chip,
4796 		       const struct nand_ecc_caps *caps, int oobavail)
4797 {
4798 	struct mtd_info *mtd = nand_to_mtd(chip);
4799 	const struct nand_ecc_step_info *stepinfo;
4800 	int req_step = chip->ecc_step_ds;
4801 	int req_strength = chip->ecc_strength_ds;
4802 	int req_corr, step_size, strength, nsteps, ecc_bytes, ecc_bytes_total;
4803 	int best_step, best_strength, best_ecc_bytes;
4804 	int best_ecc_bytes_total = INT_MAX;
4805 	int i, j;
4806 
4807 	if (WARN_ON(oobavail < 0))
4808 		return -EINVAL;
4809 
4810 	/* No information provided by the NAND chip */
4811 	if (!req_step || !req_strength)
4812 		return -ENOTSUPP;
4813 
4814 	/* number of correctable bits the chip requires in a page */
4815 	req_corr = mtd->writesize / req_step * req_strength;
4816 
4817 	for (i = 0; i < caps->nstepinfos; i++) {
4818 		stepinfo = &caps->stepinfos[i];
4819 		step_size = stepinfo->stepsize;
4820 
4821 		for (j = 0; j < stepinfo->nstrengths; j++) {
4822 			strength = stepinfo->strengths[j];
4823 
4824 			/*
4825 			 * If both step size and strength are smaller than the
4826 			 * chip's requirement, it is not easy to compare the
4827 			 * resulted reliability.
4828 			 */
4829 			if (step_size < req_step && strength < req_strength)
4830 				continue;
4831 
4832 			if (mtd->writesize % step_size)
4833 				continue;
4834 
4835 			nsteps = mtd->writesize / step_size;
4836 
4837 			ecc_bytes = caps->calc_ecc_bytes(step_size, strength);
4838 			if (WARN_ON_ONCE(ecc_bytes < 0))
4839 				continue;
4840 			ecc_bytes_total = ecc_bytes * nsteps;
4841 
4842 			if (ecc_bytes_total > oobavail ||
4843 			    strength * nsteps < req_corr)
4844 				continue;
4845 
4846 			/*
4847 			 * We assume the best is to meet the chip's requrement
4848 			 * with the least number of ECC bytes.
4849 			 */
4850 			if (ecc_bytes_total < best_ecc_bytes_total) {
4851 				best_ecc_bytes_total = ecc_bytes_total;
4852 				best_step = step_size;
4853 				best_strength = strength;
4854 				best_ecc_bytes = ecc_bytes;
4855 			}
4856 		}
4857 	}
4858 
4859 	if (best_ecc_bytes_total == INT_MAX)
4860 		return -ENOTSUPP;
4861 
4862 	chip->ecc.size = best_step;
4863 	chip->ecc.strength = best_strength;
4864 	chip->ecc.bytes = best_ecc_bytes;
4865 
4866 	return 0;
4867 }
4868 EXPORT_SYMBOL_GPL(nand_match_ecc_req);
4869 
4870 /**
4871  * nand_maximize_ecc - choose the max ECC strength available
4872  * @chip: nand chip info structure
4873  * @caps: ECC engine caps info structure
4874  * @oobavail: OOB size that the ECC engine can use
4875  *
4876  * Choose the max ECC strength that is supported on the controller, and can fit
4877  * within the chip's OOB.  On success, the chosen ECC settings are set.
4878  */
nand_maximize_ecc(struct nand_chip * chip,const struct nand_ecc_caps * caps,int oobavail)4879 int nand_maximize_ecc(struct nand_chip *chip,
4880 		      const struct nand_ecc_caps *caps, int oobavail)
4881 {
4882 	struct mtd_info *mtd = nand_to_mtd(chip);
4883 	const struct nand_ecc_step_info *stepinfo;
4884 	int step_size, strength, nsteps, ecc_bytes, corr;
4885 	int best_corr = 0;
4886 	int best_step = 0;
4887 	int best_strength, best_ecc_bytes;
4888 	int i, j;
4889 
4890 	if (WARN_ON(oobavail < 0))
4891 		return -EINVAL;
4892 
4893 	for (i = 0; i < caps->nstepinfos; i++) {
4894 		stepinfo = &caps->stepinfos[i];
4895 		step_size = stepinfo->stepsize;
4896 
4897 		/* If chip->ecc.size is already set, respect it */
4898 		if (chip->ecc.size && step_size != chip->ecc.size)
4899 			continue;
4900 
4901 		for (j = 0; j < stepinfo->nstrengths; j++) {
4902 			strength = stepinfo->strengths[j];
4903 
4904 			if (mtd->writesize % step_size)
4905 				continue;
4906 
4907 			nsteps = mtd->writesize / step_size;
4908 
4909 			ecc_bytes = caps->calc_ecc_bytes(step_size, strength);
4910 			if (WARN_ON_ONCE(ecc_bytes < 0))
4911 				continue;
4912 
4913 			if (ecc_bytes * nsteps > oobavail)
4914 				continue;
4915 
4916 			corr = strength * nsteps;
4917 
4918 			/*
4919 			 * If the number of correctable bits is the same,
4920 			 * bigger step_size has more reliability.
4921 			 */
4922 			if (corr > best_corr ||
4923 			    (corr == best_corr && step_size > best_step)) {
4924 				best_corr = corr;
4925 				best_step = step_size;
4926 				best_strength = strength;
4927 				best_ecc_bytes = ecc_bytes;
4928 			}
4929 		}
4930 	}
4931 
4932 	if (!best_corr)
4933 		return -ENOTSUPP;
4934 
4935 	chip->ecc.size = best_step;
4936 	chip->ecc.strength = best_strength;
4937 	chip->ecc.bytes = best_ecc_bytes;
4938 
4939 	return 0;
4940 }
4941 EXPORT_SYMBOL_GPL(nand_maximize_ecc);
4942 
4943 /*
4944  * Check if the chip configuration meet the datasheet requirements.
4945 
4946  * If our configuration corrects A bits per B bytes and the minimum
4947  * required correction level is X bits per Y bytes, then we must ensure
4948  * both of the following are true:
4949  *
4950  * (1) A / B >= X / Y
4951  * (2) A >= X
4952  *
4953  * Requirement (1) ensures we can correct for the required bitflip density.
4954  * Requirement (2) ensures we can correct even when all bitflips are clumped
4955  * in the same sector.
4956  */
nand_ecc_strength_good(struct mtd_info * mtd)4957 static bool nand_ecc_strength_good(struct mtd_info *mtd)
4958 {
4959 	struct nand_chip *chip = mtd_to_nand(mtd);
4960 	struct nand_ecc_ctrl *ecc = &chip->ecc;
4961 	int corr, ds_corr;
4962 
4963 	if (ecc->size == 0 || chip->ecc_step_ds == 0)
4964 		/* Not enough information */
4965 		return true;
4966 
4967 	/*
4968 	 * We get the number of corrected bits per page to compare
4969 	 * the correction density.
4970 	 */
4971 	corr = (mtd->writesize * ecc->strength) / ecc->size;
4972 	ds_corr = (mtd->writesize * chip->ecc_strength_ds) / chip->ecc_step_ds;
4973 
4974 	return corr >= ds_corr && ecc->strength >= chip->ecc_strength_ds;
4975 }
4976 
invalid_ecc_page_accessors(struct nand_chip * chip)4977 static bool invalid_ecc_page_accessors(struct nand_chip *chip)
4978 {
4979 	struct nand_ecc_ctrl *ecc = &chip->ecc;
4980 
4981 	if (nand_standard_page_accessors(ecc))
4982 		return false;
4983 
4984 	/*
4985 	 * NAND_ECC_CUSTOM_PAGE_ACCESS flag is set, make sure the NAND
4986 	 * controller driver implements all the page accessors because
4987 	 * default helpers are not suitable when the core does not
4988 	 * send the READ0/PAGEPROG commands.
4989 	 */
4990 	return (!ecc->read_page || !ecc->write_page ||
4991 		!ecc->read_page_raw || !ecc->write_page_raw ||
4992 		(NAND_HAS_SUBPAGE_READ(chip) && !ecc->read_subpage) ||
4993 		(NAND_HAS_SUBPAGE_WRITE(chip) && !ecc->write_subpage &&
4994 		 ecc->hwctl && ecc->calculate));
4995 }
4996 
4997 /**
4998  * nand_scan_tail - [NAND Interface] Scan for the NAND device
4999  * @mtd: MTD device structure
5000  *
5001  * This is the second phase of the normal nand_scan() function. It fills out
5002  * all the uninitialized function pointers with the defaults and scans for a
5003  * bad block table if appropriate.
5004  */
nand_scan_tail(struct mtd_info * mtd)5005 int nand_scan_tail(struct mtd_info *mtd)
5006 {
5007 	int i;
5008 	struct nand_chip *chip = mtd_to_nand(mtd);
5009 	struct nand_ecc_ctrl *ecc = &chip->ecc;
5010 	struct nand_buffers *nbuf;
5011 
5012 	/* New bad blocks should be marked in OOB, flash-based BBT, or both */
5013 	BUG_ON((chip->bbt_options & NAND_BBT_NO_OOB_BBM) &&
5014 			!(chip->bbt_options & NAND_BBT_USE_FLASH));
5015 
5016 	if (invalid_ecc_page_accessors(chip)) {
5017 		pr_err("Invalid ECC page accessors setup\n");
5018 		return -EINVAL;
5019 	}
5020 
5021 	if (!(chip->options & NAND_OWN_BUFFERS)) {
5022 		nbuf = kzalloc(sizeof(struct nand_buffers), GFP_KERNEL);
5023 		chip->buffers = nbuf;
5024 	} else {
5025 		if (!chip->buffers)
5026 			return -ENOMEM;
5027 	}
5028 
5029 	/* Set the internal oob buffer location, just after the page data */
5030 	chip->oob_poi = chip->buffers->databuf + mtd->writesize;
5031 
5032 	/*
5033 	 * If no default placement scheme is given, select an appropriate one.
5034 	 */
5035 	if (!ecc->layout && (ecc->mode != NAND_ECC_SOFT_BCH)) {
5036 		switch (mtd->oobsize) {
5037 #ifndef CONFIG_SYS_NAND_DRIVER_ECC_LAYOUT
5038 		case 8:
5039 			ecc->layout = &nand_oob_8;
5040 			break;
5041 		case 16:
5042 			ecc->layout = &nand_oob_16;
5043 			break;
5044 		case 64:
5045 			ecc->layout = &nand_oob_64;
5046 			break;
5047 		case 128:
5048 			ecc->layout = &nand_oob_128;
5049 			break;
5050 #endif
5051 		default:
5052 			pr_warn("No oob scheme defined for oobsize %d\n",
5053 				   mtd->oobsize);
5054 			BUG();
5055 		}
5056 	}
5057 
5058 	if (!chip->write_page)
5059 		chip->write_page = nand_write_page;
5060 
5061 	/*
5062 	 * Check ECC mode, default to software if 3byte/512byte hardware ECC is
5063 	 * selected and we have 256 byte pagesize fallback to software ECC
5064 	 */
5065 
5066 	switch (ecc->mode) {
5067 	case NAND_ECC_HW_OOB_FIRST:
5068 		/* Similar to NAND_ECC_HW, but a separate read_page handle */
5069 		if (!ecc->calculate || !ecc->correct || !ecc->hwctl) {
5070 			pr_warn("No ECC functions supplied; hardware ECC not possible\n");
5071 			BUG();
5072 		}
5073 		if (!ecc->read_page)
5074 			ecc->read_page = nand_read_page_hwecc_oob_first;
5075 
5076 	case NAND_ECC_HW:
5077 		/* Use standard hwecc read page function? */
5078 		if (!ecc->read_page)
5079 			ecc->read_page = nand_read_page_hwecc;
5080 		if (!ecc->write_page)
5081 			ecc->write_page = nand_write_page_hwecc;
5082 		if (!ecc->read_page_raw)
5083 			ecc->read_page_raw = nand_read_page_raw;
5084 		if (!ecc->write_page_raw)
5085 			ecc->write_page_raw = nand_write_page_raw;
5086 		if (!ecc->read_oob)
5087 			ecc->read_oob = nand_read_oob_std;
5088 		if (!ecc->write_oob)
5089 			ecc->write_oob = nand_write_oob_std;
5090 		if (!ecc->read_subpage)
5091 			ecc->read_subpage = nand_read_subpage;
5092 		if (!ecc->write_subpage && ecc->hwctl && ecc->calculate)
5093 			ecc->write_subpage = nand_write_subpage_hwecc;
5094 
5095 	case NAND_ECC_HW_SYNDROME:
5096 		if ((!ecc->calculate || !ecc->correct || !ecc->hwctl) &&
5097 		    (!ecc->read_page ||
5098 		     ecc->read_page == nand_read_page_hwecc ||
5099 		     !ecc->write_page ||
5100 		     ecc->write_page == nand_write_page_hwecc)) {
5101 			pr_warn("No ECC functions supplied; hardware ECC not possible\n");
5102 			BUG();
5103 		}
5104 		/* Use standard syndrome read/write page function? */
5105 		if (!ecc->read_page)
5106 			ecc->read_page = nand_read_page_syndrome;
5107 		if (!ecc->write_page)
5108 			ecc->write_page = nand_write_page_syndrome;
5109 		if (!ecc->read_page_raw)
5110 			ecc->read_page_raw = nand_read_page_raw_syndrome;
5111 		if (!ecc->write_page_raw)
5112 			ecc->write_page_raw = nand_write_page_raw_syndrome;
5113 		if (!ecc->read_oob)
5114 			ecc->read_oob = nand_read_oob_syndrome;
5115 		if (!ecc->write_oob)
5116 			ecc->write_oob = nand_write_oob_syndrome;
5117 
5118 		if (mtd->writesize >= ecc->size) {
5119 			if (!ecc->strength) {
5120 				pr_warn("Driver must set ecc.strength when using hardware ECC\n");
5121 				BUG();
5122 			}
5123 			break;
5124 		}
5125 		pr_warn("%d byte HW ECC not possible on %d byte page size, fallback to SW ECC\n",
5126 			ecc->size, mtd->writesize);
5127 		ecc->mode = NAND_ECC_SOFT;
5128 
5129 	case NAND_ECC_SOFT:
5130 		ecc->calculate = nand_calculate_ecc;
5131 		ecc->correct = nand_correct_data;
5132 		ecc->read_page = nand_read_page_swecc;
5133 		ecc->read_subpage = nand_read_subpage;
5134 		ecc->write_page = nand_write_page_swecc;
5135 		ecc->read_page_raw = nand_read_page_raw;
5136 		ecc->write_page_raw = nand_write_page_raw;
5137 		ecc->read_oob = nand_read_oob_std;
5138 		ecc->write_oob = nand_write_oob_std;
5139 		if (!ecc->size)
5140 			ecc->size = 256;
5141 		ecc->bytes = 3;
5142 		ecc->strength = 1;
5143 		break;
5144 
5145 	case NAND_ECC_SOFT_BCH:
5146 		if (!mtd_nand_has_bch()) {
5147 			pr_warn("CONFIG_MTD_NAND_ECC_BCH not enabled\n");
5148 			BUG();
5149 		}
5150 		ecc->calculate = nand_bch_calculate_ecc;
5151 		ecc->correct = nand_bch_correct_data;
5152 		ecc->read_page = nand_read_page_swecc;
5153 		ecc->read_subpage = nand_read_subpage;
5154 		ecc->write_page = nand_write_page_swecc;
5155 		ecc->read_page_raw = nand_read_page_raw;
5156 		ecc->write_page_raw = nand_write_page_raw;
5157 		ecc->read_oob = nand_read_oob_std;
5158 		ecc->write_oob = nand_write_oob_std;
5159 		/*
5160 		 * Board driver should supply ecc.size and ecc.strength values
5161 		 * to select how many bits are correctable. Otherwise, default
5162 		 * to 4 bits for large page devices.
5163 		 */
5164 		if (!ecc->size && (mtd->oobsize >= 64)) {
5165 			ecc->size = 512;
5166 			ecc->strength = 4;
5167 		}
5168 
5169 		/* See nand_bch_init() for details. */
5170 		ecc->bytes = 0;
5171 		ecc->priv = nand_bch_init(mtd);
5172 		if (!ecc->priv) {
5173 			pr_warn("BCH ECC initialization failed!\n");
5174 			BUG();
5175 		}
5176 		break;
5177 
5178 	case NAND_ECC_NONE:
5179 		pr_warn("NAND_ECC_NONE selected by board driver. This is not recommended!\n");
5180 		ecc->read_page = nand_read_page_raw;
5181 		ecc->write_page = nand_write_page_raw;
5182 		ecc->read_oob = nand_read_oob_std;
5183 		ecc->read_page_raw = nand_read_page_raw;
5184 		ecc->write_page_raw = nand_write_page_raw;
5185 		ecc->write_oob = nand_write_oob_std;
5186 		ecc->size = mtd->writesize;
5187 		ecc->bytes = 0;
5188 		ecc->strength = 0;
5189 		break;
5190 
5191 	default:
5192 		pr_warn("Invalid NAND_ECC_MODE %d\n", ecc->mode);
5193 		BUG();
5194 	}
5195 
5196 	/* For many systems, the standard OOB write also works for raw */
5197 	if (!ecc->read_oob_raw)
5198 		ecc->read_oob_raw = ecc->read_oob;
5199 	if (!ecc->write_oob_raw)
5200 		ecc->write_oob_raw = ecc->write_oob;
5201 
5202 	/*
5203 	 * The number of bytes available for a client to place data into
5204 	 * the out of band area.
5205 	 */
5206 	mtd->oobavail = 0;
5207 	if (ecc->layout) {
5208 		for (i = 0; ecc->layout->oobfree[i].length; i++)
5209 			mtd->oobavail += ecc->layout->oobfree[i].length;
5210 	}
5211 
5212 	/* ECC sanity check: warn if it's too weak */
5213 	if (!nand_ecc_strength_good(mtd))
5214 		pr_warn("WARNING: %s: the ECC used on your system is too weak compared to the one required by the NAND chip\n",
5215 			mtd->name);
5216 
5217 	/*
5218 	 * Set the number of read / write steps for one page depending on ECC
5219 	 * mode.
5220 	 */
5221 	ecc->steps = mtd->writesize / ecc->size;
5222 	if (ecc->steps * ecc->size != mtd->writesize) {
5223 		pr_warn("Invalid ECC parameters\n");
5224 		BUG();
5225 	}
5226 	ecc->total = ecc->steps * ecc->bytes;
5227 
5228 	/* Allow subpage writes up to ecc.steps. Not possible for MLC flash */
5229 	if (!(chip->options & NAND_NO_SUBPAGE_WRITE) && nand_is_slc(chip)) {
5230 		switch (ecc->steps) {
5231 		case 2:
5232 			mtd->subpage_sft = 1;
5233 			break;
5234 		case 4:
5235 		case 8:
5236 		case 16:
5237 			mtd->subpage_sft = 2;
5238 			break;
5239 		}
5240 	}
5241 	chip->subpagesize = mtd->writesize >> mtd->subpage_sft;
5242 
5243 	/* Initialize state */
5244 	chip->state = FL_READY;
5245 
5246 	/* Invalidate the pagebuffer reference */
5247 	chip->pagebuf = -1;
5248 
5249 	/* Large page NAND with SOFT_ECC should support subpage reads */
5250 	switch (ecc->mode) {
5251 	case NAND_ECC_SOFT:
5252 	case NAND_ECC_SOFT_BCH:
5253 		if (chip->page_shift > 9)
5254 			chip->options |= NAND_SUBPAGE_READ;
5255 		break;
5256 
5257 	default:
5258 		break;
5259 	}
5260 
5261 	/* Fill in remaining MTD driver data */
5262 	mtd->type = nand_is_slc(chip) ? MTD_NANDFLASH : MTD_MLCNANDFLASH;
5263 	mtd->flags = (chip->options & NAND_ROM) ? MTD_CAP_ROM :
5264 						MTD_CAP_NANDFLASH;
5265 	mtd->_erase = nand_erase;
5266 	mtd->_panic_write = panic_nand_write;
5267 	mtd->_read_oob = nand_read_oob;
5268 	mtd->_write_oob = nand_write_oob;
5269 	mtd->_sync = nand_sync;
5270 	mtd->_lock = NULL;
5271 	mtd->_unlock = NULL;
5272 	mtd->_block_isreserved = nand_block_isreserved;
5273 	mtd->_block_isbad = nand_block_isbad;
5274 	mtd->_block_markbad = nand_block_markbad;
5275 	mtd->writebufsize = mtd->writesize;
5276 
5277 	/* propagate ecc info to mtd_info */
5278 	mtd->ecclayout = ecc->layout;
5279 	mtd->ecc_strength = ecc->strength;
5280 	mtd->ecc_step_size = ecc->size;
5281 	/*
5282 	 * Initialize bitflip_threshold to its default prior scan_bbt() call.
5283 	 * scan_bbt() might invoke mtd_read(), thus bitflip_threshold must be
5284 	 * properly set.
5285 	 */
5286 	if (!mtd->bitflip_threshold)
5287 		mtd->bitflip_threshold = DIV_ROUND_UP(mtd->ecc_strength * 3, 4);
5288 
5289 	return 0;
5290 }
5291 EXPORT_SYMBOL(nand_scan_tail);
5292 
5293 /**
5294  * nand_scan - [NAND Interface] Scan for the NAND device
5295  * @mtd: MTD device structure
5296  * @maxchips: number of chips to scan for
5297  *
5298  * This fills out all the uninitialized function pointers with the defaults.
5299  * The flash ID is read and the mtd/chip structures are filled with the
5300  * appropriate values.
5301  */
nand_scan(struct mtd_info * mtd,int maxchips)5302 int nand_scan(struct mtd_info *mtd, int maxchips)
5303 {
5304 	int ret;
5305 
5306 	ret = nand_scan_ident(mtd, maxchips, NULL);
5307 	if (!ret)
5308 		ret = nand_scan_tail(mtd);
5309 	return ret;
5310 }
5311 EXPORT_SYMBOL(nand_scan);
5312 
5313 MODULE_LICENSE("GPL");
5314 MODULE_AUTHOR("Steven J. Hill <sjhill@realitydiluted.com>");
5315 MODULE_AUTHOR("Thomas Gleixner <tglx@linutronix.de>");
5316 MODULE_DESCRIPTION("Generic NAND flash driver code");
5317