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