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.
6 * Additional technical information is available on
7 * http://www.linux-mtd.infradead.org/doc/nand.html
13 * David Woodhouse for adding multichip support
15 * Aleph One Ltd. and Toby Churchill Ltd. for supporting the
16 * rework for 2K page size chips
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
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.
30 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
32 #if CONFIG_IS_ENABLED(OF_CONTROL)
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>
47 #include <linux/errno.h>
49 /* Define default oob placement schemes for large and small page devices */
50 #ifdef CONFIG_SYS_NAND_DRIVER_ECC_LAYOUT
51 static struct nand_ecclayout nand_oob_8 = {
61 static struct nand_ecclayout nand_oob_16 = {
63 .eccpos = {0, 1, 2, 3, 6, 7},
69 static struct nand_ecclayout nand_oob_64 = {
72 40, 41, 42, 43, 44, 45, 46, 47,
73 48, 49, 50, 51, 52, 53, 54, 55,
74 56, 57, 58, 59, 60, 61, 62, 63},
80 static struct nand_ecclayout nand_oob_128 = {
83 80, 81, 82, 83, 84, 85, 86, 87,
84 88, 89, 90, 91, 92, 93, 94, 95,
85 96, 97, 98, 99, 100, 101, 102, 103,
86 104, 105, 106, 107, 108, 109, 110, 111,
87 112, 113, 114, 115, 116, 117, 118, 119,
88 120, 121, 122, 123, 124, 125, 126, 127},
95 static int nand_get_device(struct mtd_info *mtd, int new_state);
97 static int nand_do_write_oob(struct mtd_info *mtd, loff_t to,
98 struct mtd_oob_ops *ops);
101 * For devices which display every fart in the system on a separate LED. Is
102 * compiled away when LED support is disabled.
104 DEFINE_LED_TRIGGER(nand_led_trigger);
106 static int check_offs_len(struct mtd_info *mtd,
107 loff_t ofs, uint64_t len)
109 struct nand_chip *chip = mtd_to_nand(mtd);
112 /* Start address must align on block boundary */
113 if (ofs & ((1ULL << chip->phys_erase_shift) - 1)) {
114 pr_debug("%s: unaligned address\n", __func__);
118 /* Length must align on block boundary */
119 if (len & ((1ULL << chip->phys_erase_shift) - 1)) {
120 pr_debug("%s: length not block aligned\n", __func__);
128 * nand_release_device - [GENERIC] release chip
129 * @mtd: MTD device structure
131 * Release chip lock and wake up anyone waiting on the device.
133 static void nand_release_device(struct mtd_info *mtd)
135 struct nand_chip *chip = mtd_to_nand(mtd);
137 /* De-select the NAND device */
138 chip->select_chip(mtd, -1);
142 * nand_read_byte - [DEFAULT] read one byte from the chip
143 * @mtd: MTD device structure
145 * Default read function for 8bit buswidth
147 uint8_t nand_read_byte(struct mtd_info *mtd)
149 struct nand_chip *chip = mtd_to_nand(mtd);
150 return readb(chip->IO_ADDR_R);
154 * nand_read_byte16 - [DEFAULT] read one byte endianness aware from the chip
155 * @mtd: MTD device structure
157 * Default read function for 16bit buswidth with endianness conversion.
160 static uint8_t nand_read_byte16(struct mtd_info *mtd)
162 struct nand_chip *chip = mtd_to_nand(mtd);
163 return (uint8_t) cpu_to_le16(readw(chip->IO_ADDR_R));
167 * nand_read_word - [DEFAULT] read one word from the chip
168 * @mtd: MTD device structure
170 * Default read function for 16bit buswidth without endianness conversion.
172 static u16 nand_read_word(struct mtd_info *mtd)
174 struct nand_chip *chip = mtd_to_nand(mtd);
175 return readw(chip->IO_ADDR_R);
179 * nand_select_chip - [DEFAULT] control CE line
180 * @mtd: MTD device structure
181 * @chipnr: chipnumber to select, -1 for deselect
183 * Default select function for 1 chip devices.
185 static void nand_select_chip(struct mtd_info *mtd, int chipnr)
187 struct nand_chip *chip = mtd_to_nand(mtd);
191 chip->cmd_ctrl(mtd, NAND_CMD_NONE, 0 | NAND_CTRL_CHANGE);
202 * nand_write_byte - [DEFAULT] write single byte to chip
203 * @mtd: MTD device structure
204 * @byte: value to write
206 * Default function to write a byte to I/O[7:0]
208 static void nand_write_byte(struct mtd_info *mtd, uint8_t byte)
210 struct nand_chip *chip = mtd_to_nand(mtd);
212 chip->write_buf(mtd, &byte, 1);
216 * nand_write_byte16 - [DEFAULT] write single byte to a chip with width 16
217 * @mtd: MTD device structure
218 * @byte: value to write
220 * Default function to write a byte to I/O[7:0] on a 16-bit wide chip.
222 static void nand_write_byte16(struct mtd_info *mtd, uint8_t byte)
224 struct nand_chip *chip = mtd_to_nand(mtd);
225 uint16_t word = byte;
228 * It's not entirely clear what should happen to I/O[15:8] when writing
229 * a byte. The ONFi spec (Revision 3.1; 2012-09-19, Section 2.16) reads:
231 * When the host supports a 16-bit bus width, only data is
232 * transferred at the 16-bit width. All address and command line
233 * transfers shall use only the lower 8-bits of the data bus. During
234 * command transfers, the host may place any value on the upper
235 * 8-bits of the data bus. During address transfers, the host shall
236 * set the upper 8-bits of the data bus to 00h.
238 * One user of the write_byte callback is nand_onfi_set_features. The
239 * four parameters are specified to be written to I/O[7:0], but this is
240 * neither an address nor a command transfer. Let's assume a 0 on the
241 * upper I/O lines is OK.
243 chip->write_buf(mtd, (uint8_t *)&word, 2);
246 static void iowrite8_rep(void *addr, const uint8_t *buf, int len)
250 for (i = 0; i < len; i++)
251 writeb(buf[i], addr);
253 static void ioread8_rep(void *addr, uint8_t *buf, int len)
257 for (i = 0; i < len; i++)
258 buf[i] = readb(addr);
261 static void ioread16_rep(void *addr, void *buf, int len)
264 u16 *p = (u16 *) buf;
266 for (i = 0; i < len; i++)
270 static void iowrite16_rep(void *addr, void *buf, int len)
273 u16 *p = (u16 *) buf;
275 for (i = 0; i < len; i++)
280 * nand_write_buf - [DEFAULT] write buffer to chip
281 * @mtd: MTD device structure
283 * @len: number of bytes to write
285 * Default write function for 8bit buswidth.
287 void nand_write_buf(struct mtd_info *mtd, const uint8_t *buf, int len)
289 struct nand_chip *chip = mtd_to_nand(mtd);
291 iowrite8_rep(chip->IO_ADDR_W, buf, len);
295 * nand_read_buf - [DEFAULT] read chip data into buffer
296 * @mtd: MTD device structure
297 * @buf: buffer to store date
298 * @len: number of bytes to read
300 * Default read function for 8bit buswidth.
302 void nand_read_buf(struct mtd_info *mtd, uint8_t *buf, int len)
304 struct nand_chip *chip = mtd_to_nand(mtd);
306 ioread8_rep(chip->IO_ADDR_R, buf, len);
310 * nand_write_buf16 - [DEFAULT] write buffer to chip
311 * @mtd: MTD device structure
313 * @len: number of bytes to write
315 * Default write function for 16bit buswidth.
317 void nand_write_buf16(struct mtd_info *mtd, const uint8_t *buf, int len)
319 struct nand_chip *chip = mtd_to_nand(mtd);
320 u16 *p = (u16 *) buf;
322 iowrite16_rep(chip->IO_ADDR_W, p, len >> 1);
326 * nand_read_buf16 - [DEFAULT] read chip data into buffer
327 * @mtd: MTD device structure
328 * @buf: buffer to store date
329 * @len: number of bytes to read
331 * Default read function for 16bit buswidth.
333 void nand_read_buf16(struct mtd_info *mtd, uint8_t *buf, int len)
335 struct nand_chip *chip = mtd_to_nand(mtd);
336 u16 *p = (u16 *) buf;
338 ioread16_rep(chip->IO_ADDR_R, p, len >> 1);
342 * nand_block_bad - [DEFAULT] Read bad block marker from the chip
343 * @mtd: MTD device structure
344 * @ofs: offset from device start
346 * Check, if the block is bad.
348 static int nand_block_bad(struct mtd_info *mtd, loff_t ofs)
350 int page, res = 0, i = 0;
351 struct nand_chip *chip = mtd_to_nand(mtd);
354 if (chip->bbt_options & NAND_BBT_SCANLASTPAGE)
355 ofs += mtd->erasesize - mtd->writesize;
357 page = (int)(ofs >> chip->page_shift) & chip->pagemask;
360 if (chip->options & NAND_BUSWIDTH_16) {
361 chip->cmdfunc(mtd, NAND_CMD_READOOB,
362 chip->badblockpos & 0xFE, page);
363 bad = cpu_to_le16(chip->read_word(mtd));
364 if (chip->badblockpos & 0x1)
369 chip->cmdfunc(mtd, NAND_CMD_READOOB, chip->badblockpos,
371 bad = chip->read_byte(mtd);
374 if (likely(chip->badblockbits == 8))
377 res = hweight8(bad) < chip->badblockbits;
378 ofs += mtd->writesize;
379 page = (int)(ofs >> chip->page_shift) & chip->pagemask;
381 } while (!res && i < 2 && (chip->bbt_options & NAND_BBT_SCAN2NDPAGE));
387 * nand_default_block_markbad - [DEFAULT] mark a block bad via bad block marker
388 * @mtd: MTD device structure
389 * @ofs: offset from device start
391 * This is the default implementation, which can be overridden by a hardware
392 * specific driver. It provides the details for writing a bad block marker to a
395 static int nand_default_block_markbad(struct mtd_info *mtd, loff_t ofs)
397 struct nand_chip *chip = mtd_to_nand(mtd);
398 struct mtd_oob_ops ops;
399 uint8_t buf[2] = { 0, 0 };
400 int ret = 0, res, i = 0;
402 memset(&ops, 0, sizeof(ops));
404 ops.ooboffs = chip->badblockpos;
405 if (chip->options & NAND_BUSWIDTH_16) {
406 ops.ooboffs &= ~0x01;
407 ops.len = ops.ooblen = 2;
409 ops.len = ops.ooblen = 1;
411 ops.mode = MTD_OPS_PLACE_OOB;
413 /* Write to first/last page(s) if necessary */
414 if (chip->bbt_options & NAND_BBT_SCANLASTPAGE)
415 ofs += mtd->erasesize - mtd->writesize;
417 res = nand_do_write_oob(mtd, ofs, &ops);
422 ofs += mtd->writesize;
423 } while ((chip->bbt_options & NAND_BBT_SCAN2NDPAGE) && i < 2);
429 * nand_block_markbad_lowlevel - mark a block bad
430 * @mtd: MTD device structure
431 * @ofs: offset from device start
433 * This function performs the generic NAND bad block marking steps (i.e., bad
434 * block table(s) and/or marker(s)). We only allow the hardware driver to
435 * specify how to write bad block markers to OOB (chip->block_markbad).
437 * We try operations in the following order:
438 * (1) erase the affected block, to allow OOB marker to be written cleanly
439 * (2) write bad block marker to OOB area of affected block (unless flag
440 * NAND_BBT_NO_OOB_BBM is present)
442 * Note that we retain the first error encountered in (2) or (3), finish the
443 * procedures, and dump the error in the end.
445 static int nand_block_markbad_lowlevel(struct mtd_info *mtd, loff_t ofs)
447 struct nand_chip *chip = mtd_to_nand(mtd);
450 if (!(chip->bbt_options & NAND_BBT_NO_OOB_BBM)) {
451 struct erase_info einfo;
453 /* Attempt erase before marking OOB */
454 memset(&einfo, 0, sizeof(einfo));
457 einfo.len = 1ULL << chip->phys_erase_shift;
458 nand_erase_nand(mtd, &einfo, 0);
460 /* Write bad block marker to OOB */
461 nand_get_device(mtd, FL_WRITING);
462 ret = chip->block_markbad(mtd, ofs);
463 nand_release_device(mtd);
466 /* Mark block bad in BBT */
468 res = nand_markbad_bbt(mtd, ofs);
474 mtd->ecc_stats.badblocks++;
480 * nand_check_wp - [GENERIC] check if the chip is write protected
481 * @mtd: MTD device structure
483 * Check, if the device is write protected. The function expects, that the
484 * device is already selected.
486 static int nand_check_wp(struct mtd_info *mtd)
488 struct nand_chip *chip = mtd_to_nand(mtd);
492 /* Broken xD cards report WP despite being writable */
493 if (chip->options & NAND_BROKEN_XD)
496 /* Check the WP bit */
497 ret = nand_status_op(chip, &status);
501 return status & NAND_STATUS_WP ? 0 : 1;
505 * nand_block_isreserved - [GENERIC] Check if a block is marked reserved.
506 * @mtd: MTD device structure
507 * @ofs: offset from device start
509 * Check if the block is marked as reserved.
511 static int nand_block_isreserved(struct mtd_info *mtd, loff_t ofs)
513 struct nand_chip *chip = mtd_to_nand(mtd);
517 /* Return info from the table */
518 return nand_isreserved_bbt(mtd, ofs);
522 * nand_block_checkbad - [GENERIC] Check if a block is marked bad
523 * @mtd: MTD device structure
524 * @ofs: offset from device start
525 * @allowbbt: 1, if its allowed to access the bbt area
527 * Check, if the block is bad. Either by reading the bad block table or
528 * calling of the scan function.
530 static int nand_block_checkbad(struct mtd_info *mtd, loff_t ofs, int allowbbt)
532 struct nand_chip *chip = mtd_to_nand(mtd);
534 if (!(chip->options & NAND_SKIP_BBTSCAN) &&
535 !(chip->options & NAND_BBT_SCANNED)) {
536 chip->options |= NAND_BBT_SCANNED;
541 return chip->block_bad(mtd, ofs);
543 /* Return info from the table */
544 return nand_isbad_bbt(mtd, ofs, allowbbt);
548 * nand_wait_ready - [GENERIC] Wait for the ready pin after commands.
549 * @mtd: MTD device structure
551 * Wait for the ready pin after a command, and warn if a timeout occurs.
553 void nand_wait_ready(struct mtd_info *mtd)
555 struct nand_chip *chip = mtd_to_nand(mtd);
556 u32 timeo = (CONFIG_SYS_HZ * 400) / 1000;
559 time_start = get_timer(0);
560 /* Wait until command is processed or timeout occurs */
561 while (get_timer(time_start) < timeo) {
563 if (chip->dev_ready(mtd))
567 if (!chip->dev_ready(mtd))
568 pr_warn("timeout while waiting for chip to become ready\n");
570 EXPORT_SYMBOL_GPL(nand_wait_ready);
573 * nand_wait_status_ready - [GENERIC] Wait for the ready status after commands.
574 * @mtd: MTD device structure
575 * @timeo: Timeout in ms
577 * Wait for status ready (i.e. command done) or timeout.
579 static void nand_wait_status_ready(struct mtd_info *mtd, unsigned long timeo)
581 register struct nand_chip *chip = mtd_to_nand(mtd);
585 timeo = (CONFIG_SYS_HZ * timeo) / 1000;
586 time_start = get_timer(0);
587 while (get_timer(time_start) < timeo) {
590 ret = nand_read_data_op(chip, &status, sizeof(status), true);
594 if (status & NAND_STATUS_READY)
601 * nand_command - [DEFAULT] Send command to NAND device
602 * @mtd: MTD device structure
603 * @command: the command to be sent
604 * @column: the column address for this command, -1 if none
605 * @page_addr: the page address for this command, -1 if none
607 * Send command to NAND device. This function is used for small page devices
608 * (512 Bytes per page).
610 static void nand_command(struct mtd_info *mtd, unsigned int command,
611 int column, int page_addr)
613 register struct nand_chip *chip = mtd_to_nand(mtd);
614 int ctrl = NAND_CTRL_CLE | NAND_CTRL_CHANGE;
616 /* Write out the command to the device */
617 if (command == NAND_CMD_SEQIN) {
620 if (column >= mtd->writesize) {
622 column -= mtd->writesize;
623 readcmd = NAND_CMD_READOOB;
624 } else if (column < 256) {
625 /* First 256 bytes --> READ0 */
626 readcmd = NAND_CMD_READ0;
629 readcmd = NAND_CMD_READ1;
631 chip->cmd_ctrl(mtd, readcmd, ctrl);
632 ctrl &= ~NAND_CTRL_CHANGE;
634 chip->cmd_ctrl(mtd, command, ctrl);
636 /* Address cycle, when necessary */
637 ctrl = NAND_CTRL_ALE | NAND_CTRL_CHANGE;
638 /* Serially input address */
640 /* Adjust columns for 16 bit buswidth */
641 if (chip->options & NAND_BUSWIDTH_16 &&
642 !nand_opcode_8bits(command))
644 chip->cmd_ctrl(mtd, column, ctrl);
645 ctrl &= ~NAND_CTRL_CHANGE;
647 if (page_addr != -1) {
648 chip->cmd_ctrl(mtd, page_addr, ctrl);
649 ctrl &= ~NAND_CTRL_CHANGE;
650 chip->cmd_ctrl(mtd, page_addr >> 8, ctrl);
651 if (chip->options & NAND_ROW_ADDR_3)
652 chip->cmd_ctrl(mtd, page_addr >> 16, ctrl);
654 chip->cmd_ctrl(mtd, NAND_CMD_NONE, NAND_NCE | NAND_CTRL_CHANGE);
657 * Program and erase have their own busy handlers status and sequential
662 case NAND_CMD_PAGEPROG:
663 case NAND_CMD_ERASE1:
664 case NAND_CMD_ERASE2:
666 case NAND_CMD_STATUS:
667 case NAND_CMD_READID:
668 case NAND_CMD_SET_FEATURES:
674 udelay(chip->chip_delay);
675 chip->cmd_ctrl(mtd, NAND_CMD_STATUS,
676 NAND_CTRL_CLE | NAND_CTRL_CHANGE);
678 NAND_CMD_NONE, NAND_NCE | NAND_CTRL_CHANGE);
679 /* EZ-NAND can take upto 250ms as per ONFi v4.0 */
680 nand_wait_status_ready(mtd, 250);
683 /* This applies to read commands */
686 * If we don't have access to the busy pin, we apply the given
689 if (!chip->dev_ready) {
690 udelay(chip->chip_delay);
695 * Apply this short delay always to ensure that we do wait tWB in
696 * any case on any machine.
700 nand_wait_ready(mtd);
704 * nand_command_lp - [DEFAULT] Send command to NAND large page device
705 * @mtd: MTD device structure
706 * @command: the command to be sent
707 * @column: the column address for this command, -1 if none
708 * @page_addr: the page address for this command, -1 if none
710 * Send command to NAND device. This is the version for the new large page
711 * devices. We don't have the separate regions as we have in the small page
712 * devices. We must emulate NAND_CMD_READOOB to keep the code compatible.
714 static void nand_command_lp(struct mtd_info *mtd, unsigned int command,
715 int column, int page_addr)
717 register struct nand_chip *chip = mtd_to_nand(mtd);
719 /* Emulate NAND_CMD_READOOB */
720 if (command == NAND_CMD_READOOB) {
721 column += mtd->writesize;
722 command = NAND_CMD_READ0;
725 /* Command latch cycle */
726 chip->cmd_ctrl(mtd, command, NAND_NCE | NAND_CLE | NAND_CTRL_CHANGE);
728 if (column != -1 || page_addr != -1) {
729 int ctrl = NAND_CTRL_CHANGE | NAND_NCE | NAND_ALE;
731 /* Serially input address */
733 /* Adjust columns for 16 bit buswidth */
734 if (chip->options & NAND_BUSWIDTH_16 &&
735 !nand_opcode_8bits(command))
737 chip->cmd_ctrl(mtd, column, ctrl);
738 ctrl &= ~NAND_CTRL_CHANGE;
739 chip->cmd_ctrl(mtd, column >> 8, ctrl);
741 if (page_addr != -1) {
742 chip->cmd_ctrl(mtd, page_addr, ctrl);
743 chip->cmd_ctrl(mtd, page_addr >> 8,
744 NAND_NCE | NAND_ALE);
745 if (chip->options & NAND_ROW_ADDR_3)
746 chip->cmd_ctrl(mtd, page_addr >> 16,
747 NAND_NCE | NAND_ALE);
750 chip->cmd_ctrl(mtd, NAND_CMD_NONE, NAND_NCE | NAND_CTRL_CHANGE);
753 * Program and erase have their own busy handlers status, sequential
754 * in and status need no delay.
758 case NAND_CMD_CACHEDPROG:
759 case NAND_CMD_PAGEPROG:
760 case NAND_CMD_ERASE1:
761 case NAND_CMD_ERASE2:
764 case NAND_CMD_STATUS:
765 case NAND_CMD_READID:
766 case NAND_CMD_SET_FEATURES:
772 udelay(chip->chip_delay);
773 chip->cmd_ctrl(mtd, NAND_CMD_STATUS,
774 NAND_NCE | NAND_CLE | NAND_CTRL_CHANGE);
775 chip->cmd_ctrl(mtd, NAND_CMD_NONE,
776 NAND_NCE | NAND_CTRL_CHANGE);
777 /* EZ-NAND can take upto 250ms as per ONFi v4.0 */
778 nand_wait_status_ready(mtd, 250);
781 case NAND_CMD_RNDOUT:
782 /* No ready / busy check necessary */
783 chip->cmd_ctrl(mtd, NAND_CMD_RNDOUTSTART,
784 NAND_NCE | NAND_CLE | NAND_CTRL_CHANGE);
785 chip->cmd_ctrl(mtd, NAND_CMD_NONE,
786 NAND_NCE | NAND_CTRL_CHANGE);
790 chip->cmd_ctrl(mtd, NAND_CMD_READSTART,
791 NAND_NCE | NAND_CLE | NAND_CTRL_CHANGE);
792 chip->cmd_ctrl(mtd, NAND_CMD_NONE,
793 NAND_NCE | NAND_CTRL_CHANGE);
795 /* This applies to read commands */
798 * If we don't have access to the busy pin, we apply the given
801 if (!chip->dev_ready) {
802 udelay(chip->chip_delay);
808 * Apply this short delay always to ensure that we do wait tWB in
809 * any case on any machine.
813 nand_wait_ready(mtd);
817 * panic_nand_get_device - [GENERIC] Get chip for selected access
818 * @chip: the nand chip descriptor
819 * @mtd: MTD device structure
820 * @new_state: the state which is requested
822 * Used when in panic, no locks are taken.
824 static void panic_nand_get_device(struct nand_chip *chip,
825 struct mtd_info *mtd, int new_state)
827 /* Hardware controller shared among independent devices */
828 chip->controller->active = chip;
829 chip->state = new_state;
833 * nand_get_device - [GENERIC] Get chip for selected access
834 * @mtd: MTD device structure
835 * @new_state: the state which is requested
837 * Get the device and lock it for exclusive access
840 nand_get_device(struct mtd_info *mtd, int new_state)
842 struct nand_chip *chip = mtd_to_nand(mtd);
843 chip->state = new_state;
848 * panic_nand_wait - [GENERIC] wait until the command is done
849 * @mtd: MTD device structure
850 * @chip: NAND chip structure
853 * Wait for command done. This is a helper function for nand_wait used when
854 * we are in interrupt context. May happen when in panic and trying to write
855 * an oops through mtdoops.
857 static void panic_nand_wait(struct mtd_info *mtd, struct nand_chip *chip,
861 for (i = 0; i < timeo; i++) {
862 if (chip->dev_ready) {
863 if (chip->dev_ready(mtd))
869 ret = nand_read_data_op(chip, &status, sizeof(status),
874 if (status & NAND_STATUS_READY)
882 * nand_wait - [DEFAULT] wait until the command is done
883 * @mtd: MTD device structure
884 * @chip: NAND chip structure
886 * Wait for command done. This applies to erase and program only.
888 static int nand_wait(struct mtd_info *mtd, struct nand_chip *chip)
890 unsigned long timeo = 400;
894 led_trigger_event(nand_led_trigger, LED_FULL);
897 * Apply this short delay always to ensure that we do wait tWB in any
898 * case on any machine.
902 ret = nand_status_op(chip, NULL);
906 u32 timer = (CONFIG_SYS_HZ * timeo) / 1000;
909 time_start = get_timer(0);
910 while (get_timer(time_start) < timer) {
911 if (chip->dev_ready) {
912 if (chip->dev_ready(mtd))
915 ret = nand_read_data_op(chip, &status,
916 sizeof(status), true);
920 if (status & NAND_STATUS_READY)
924 led_trigger_event(nand_led_trigger, LED_OFF);
926 ret = nand_read_data_op(chip, &status, sizeof(status), true);
930 /* This can happen if in case of timeout or buggy dev_ready */
931 WARN_ON(!(status & NAND_STATUS_READY));
936 * nand_reset_data_interface - Reset data interface and timings
937 * @chip: The NAND chip
938 * @chipnr: Internal die id
940 * Reset the Data interface and timings to ONFI mode 0.
942 * Returns 0 for success or negative error code otherwise.
944 static int nand_reset_data_interface(struct nand_chip *chip, int chipnr)
946 struct mtd_info *mtd = nand_to_mtd(chip);
947 const struct nand_data_interface *conf;
950 if (!chip->setup_data_interface)
954 * The ONFI specification says:
956 * To transition from NV-DDR or NV-DDR2 to the SDR data
957 * interface, the host shall use the Reset (FFh) command
958 * using SDR timing mode 0. A device in any timing mode is
959 * required to recognize Reset (FFh) command issued in SDR
963 * Configure the data interface in SDR mode and set the
964 * timings to timing mode 0.
967 conf = nand_get_default_data_interface();
968 ret = chip->setup_data_interface(mtd, chipnr, conf);
970 pr_err("Failed to configure data interface to SDR timing mode 0\n");
976 * nand_setup_data_interface - Setup the best data interface and timings
977 * @chip: The NAND chip
978 * @chipnr: Internal die id
980 * Find and configure the best data interface and NAND timings supported by
981 * the chip and the driver.
982 * First tries to retrieve supported timing modes from ONFI information,
983 * and if the NAND chip does not support ONFI, relies on the
984 * ->onfi_timing_mode_default specified in the nand_ids table.
986 * Returns 0 for success or negative error code otherwise.
988 static int nand_setup_data_interface(struct nand_chip *chip, int chipnr)
990 struct mtd_info *mtd = nand_to_mtd(chip);
993 if (!chip->setup_data_interface || !chip->data_interface)
997 * Ensure the timing mode has been changed on the chip side
998 * before changing timings on the controller side.
1000 if (chip->onfi_version) {
1001 u8 tmode_param[ONFI_SUBFEATURE_PARAM_LEN] = {
1002 chip->onfi_timing_mode_default,
1005 ret = chip->onfi_set_features(mtd, chip,
1006 ONFI_FEATURE_ADDR_TIMING_MODE,
1012 ret = chip->setup_data_interface(mtd, chipnr, chip->data_interface);
1018 * nand_init_data_interface - find the best data interface and timings
1019 * @chip: The NAND chip
1021 * Find the best data interface and NAND timings supported by the chip
1023 * First tries to retrieve supported timing modes from ONFI information,
1024 * and if the NAND chip does not support ONFI, relies on the
1025 * ->onfi_timing_mode_default specified in the nand_ids table. After this
1026 * function nand_chip->data_interface is initialized with the best timing mode
1029 * Returns 0 for success or negative error code otherwise.
1031 static int nand_init_data_interface(struct nand_chip *chip)
1033 struct mtd_info *mtd = nand_to_mtd(chip);
1034 int modes, mode, ret;
1036 if (!chip->setup_data_interface)
1040 * First try to identify the best timings from ONFI parameters and
1041 * if the NAND does not support ONFI, fallback to the default ONFI
1044 modes = onfi_get_async_timing_mode(chip);
1045 if (modes == ONFI_TIMING_MODE_UNKNOWN) {
1046 if (!chip->onfi_timing_mode_default)
1049 modes = GENMASK(chip->onfi_timing_mode_default, 0);
1052 chip->data_interface = kzalloc(sizeof(*chip->data_interface),
1054 if (!chip->data_interface)
1057 for (mode = fls(modes) - 1; mode >= 0; mode--) {
1058 ret = onfi_init_data_interface(chip, chip->data_interface,
1059 NAND_SDR_IFACE, mode);
1063 /* Pass -1 to only */
1064 ret = chip->setup_data_interface(mtd,
1065 NAND_DATA_IFACE_CHECK_ONLY,
1066 chip->data_interface);
1068 chip->onfi_timing_mode_default = mode;
1076 static void __maybe_unused nand_release_data_interface(struct nand_chip *chip)
1078 kfree(chip->data_interface);
1082 * nand_read_page_op - Do a READ PAGE operation
1083 * @chip: The NAND chip
1084 * @page: page to read
1085 * @offset_in_page: offset within the page
1086 * @buf: buffer used to store the data
1087 * @len: length of the buffer
1089 * This function issues a READ PAGE operation.
1090 * This function does not select/unselect the CS line.
1092 * Returns 0 on success, a negative error code otherwise.
1094 int nand_read_page_op(struct nand_chip *chip, unsigned int page,
1095 unsigned int offset_in_page, void *buf, unsigned int len)
1097 struct mtd_info *mtd = nand_to_mtd(chip);
1102 if (offset_in_page + len > mtd->writesize + mtd->oobsize)
1105 chip->cmdfunc(mtd, NAND_CMD_READ0, offset_in_page, page);
1107 chip->read_buf(mtd, buf, len);
1111 EXPORT_SYMBOL_GPL(nand_read_page_op);
1114 * nand_read_param_page_op - Do a READ PARAMETER PAGE operation
1115 * @chip: The NAND chip
1116 * @page: parameter page to read
1117 * @buf: buffer used to store the data
1118 * @len: length of the buffer
1120 * This function issues a READ PARAMETER PAGE operation.
1121 * This function does not select/unselect the CS line.
1123 * Returns 0 on success, a negative error code otherwise.
1125 static int nand_read_param_page_op(struct nand_chip *chip, u8 page, void *buf,
1128 struct mtd_info *mtd = nand_to_mtd(chip);
1135 chip->cmdfunc(mtd, NAND_CMD_PARAM, page, -1);
1136 for (i = 0; i < len; i++)
1137 p[i] = chip->read_byte(mtd);
1143 * nand_change_read_column_op - Do a CHANGE READ COLUMN operation
1144 * @chip: The NAND chip
1145 * @offset_in_page: offset within the page
1146 * @buf: buffer used to store the data
1147 * @len: length of the buffer
1148 * @force_8bit: force 8-bit bus access
1150 * This function issues a CHANGE READ COLUMN operation.
1151 * This function does not select/unselect the CS line.
1153 * Returns 0 on success, a negative error code otherwise.
1155 int nand_change_read_column_op(struct nand_chip *chip,
1156 unsigned int offset_in_page, void *buf,
1157 unsigned int len, bool force_8bit)
1159 struct mtd_info *mtd = nand_to_mtd(chip);
1164 if (offset_in_page + len > mtd->writesize + mtd->oobsize)
1167 chip->cmdfunc(mtd, NAND_CMD_RNDOUT, offset_in_page, -1);
1169 chip->read_buf(mtd, buf, len);
1173 EXPORT_SYMBOL_GPL(nand_change_read_column_op);
1176 * nand_read_oob_op - Do a READ OOB operation
1177 * @chip: The NAND chip
1178 * @page: page to read
1179 * @offset_in_oob: offset within the OOB area
1180 * @buf: buffer used to store the data
1181 * @len: length of the buffer
1183 * This function issues a READ OOB operation.
1184 * This function does not select/unselect the CS line.
1186 * Returns 0 on success, a negative error code otherwise.
1188 int nand_read_oob_op(struct nand_chip *chip, unsigned int page,
1189 unsigned int offset_in_oob, void *buf, unsigned int len)
1191 struct mtd_info *mtd = nand_to_mtd(chip);
1196 if (offset_in_oob + len > mtd->oobsize)
1199 chip->cmdfunc(mtd, NAND_CMD_READOOB, offset_in_oob, page);
1201 chip->read_buf(mtd, buf, len);
1205 EXPORT_SYMBOL_GPL(nand_read_oob_op);
1208 * nand_prog_page_begin_op - starts a PROG PAGE operation
1209 * @chip: The NAND chip
1210 * @page: page to write
1211 * @offset_in_page: offset within the page
1212 * @buf: buffer containing the data to write to the page
1213 * @len: length of the buffer
1215 * This function issues the first half of a PROG PAGE operation.
1216 * This function does not select/unselect the CS line.
1218 * Returns 0 on success, a negative error code otherwise.
1220 int nand_prog_page_begin_op(struct nand_chip *chip, unsigned int page,
1221 unsigned int offset_in_page, const void *buf,
1224 struct mtd_info *mtd = nand_to_mtd(chip);
1229 if (offset_in_page + len > mtd->writesize + mtd->oobsize)
1232 chip->cmdfunc(mtd, NAND_CMD_SEQIN, offset_in_page, page);
1235 chip->write_buf(mtd, buf, len);
1239 EXPORT_SYMBOL_GPL(nand_prog_page_begin_op);
1242 * nand_prog_page_end_op - ends a PROG PAGE operation
1243 * @chip: The NAND chip
1245 * This function issues the second half of a PROG PAGE operation.
1246 * This function does not select/unselect the CS line.
1248 * Returns 0 on success, a negative error code otherwise.
1250 int nand_prog_page_end_op(struct nand_chip *chip)
1252 struct mtd_info *mtd = nand_to_mtd(chip);
1255 chip->cmdfunc(mtd, NAND_CMD_PAGEPROG, -1, -1);
1257 status = chip->waitfunc(mtd, chip);
1258 if (status & NAND_STATUS_FAIL)
1263 EXPORT_SYMBOL_GPL(nand_prog_page_end_op);
1266 * nand_prog_page_op - Do a full PROG PAGE operation
1267 * @chip: The NAND chip
1268 * @page: page to write
1269 * @offset_in_page: offset within the page
1270 * @buf: buffer containing the data to write to the page
1271 * @len: length of the buffer
1273 * This function issues a full PROG PAGE operation.
1274 * This function does not select/unselect the CS line.
1276 * Returns 0 on success, a negative error code otherwise.
1278 int nand_prog_page_op(struct nand_chip *chip, unsigned int page,
1279 unsigned int offset_in_page, const void *buf,
1282 struct mtd_info *mtd = nand_to_mtd(chip);
1288 if (offset_in_page + len > mtd->writesize + mtd->oobsize)
1291 chip->cmdfunc(mtd, NAND_CMD_SEQIN, offset_in_page, page);
1292 chip->write_buf(mtd, buf, len);
1293 chip->cmdfunc(mtd, NAND_CMD_PAGEPROG, -1, -1);
1295 status = chip->waitfunc(mtd, chip);
1296 if (status & NAND_STATUS_FAIL)
1301 EXPORT_SYMBOL_GPL(nand_prog_page_op);
1304 * nand_change_write_column_op - Do a CHANGE WRITE COLUMN operation
1305 * @chip: The NAND chip
1306 * @offset_in_page: offset within the page
1307 * @buf: buffer containing the data to send to the NAND
1308 * @len: length of the buffer
1309 * @force_8bit: force 8-bit bus access
1311 * This function issues a CHANGE WRITE COLUMN operation.
1312 * This function does not select/unselect the CS line.
1314 * Returns 0 on success, a negative error code otherwise.
1316 int nand_change_write_column_op(struct nand_chip *chip,
1317 unsigned int offset_in_page,
1318 const void *buf, unsigned int len,
1321 struct mtd_info *mtd = nand_to_mtd(chip);
1326 if (offset_in_page + len > mtd->writesize + mtd->oobsize)
1329 chip->cmdfunc(mtd, NAND_CMD_RNDIN, offset_in_page, -1);
1331 chip->write_buf(mtd, buf, len);
1335 EXPORT_SYMBOL_GPL(nand_change_write_column_op);
1338 * nand_readid_op - Do a READID operation
1339 * @chip: The NAND chip
1340 * @addr: address cycle to pass after the READID command
1341 * @buf: buffer used to store the ID
1342 * @len: length of the buffer
1344 * This function sends a READID command and reads back the ID returned by the
1346 * This function does not select/unselect the CS line.
1348 * Returns 0 on success, a negative error code otherwise.
1350 int nand_readid_op(struct nand_chip *chip, u8 addr, void *buf,
1353 struct mtd_info *mtd = nand_to_mtd(chip);
1360 chip->cmdfunc(mtd, NAND_CMD_READID, addr, -1);
1362 for (i = 0; i < len; i++)
1363 id[i] = chip->read_byte(mtd);
1367 EXPORT_SYMBOL_GPL(nand_readid_op);
1370 * nand_status_op - Do a STATUS operation
1371 * @chip: The NAND chip
1372 * @status: out variable to store the NAND status
1374 * This function sends a STATUS command and reads back the status returned by
1376 * This function does not select/unselect the CS line.
1378 * Returns 0 on success, a negative error code otherwise.
1380 int nand_status_op(struct nand_chip *chip, u8 *status)
1382 struct mtd_info *mtd = nand_to_mtd(chip);
1384 chip->cmdfunc(mtd, NAND_CMD_STATUS, -1, -1);
1386 *status = chip->read_byte(mtd);
1390 EXPORT_SYMBOL_GPL(nand_status_op);
1393 * nand_exit_status_op - Exit a STATUS operation
1394 * @chip: The NAND chip
1396 * This function sends a READ0 command to cancel the effect of the STATUS
1397 * command to avoid reading only the status until a new read command is sent.
1399 * This function does not select/unselect the CS line.
1401 * Returns 0 on success, a negative error code otherwise.
1403 int nand_exit_status_op(struct nand_chip *chip)
1405 struct mtd_info *mtd = nand_to_mtd(chip);
1407 chip->cmdfunc(mtd, NAND_CMD_READ0, -1, -1);
1411 EXPORT_SYMBOL_GPL(nand_exit_status_op);
1414 * nand_erase_op - Do an erase operation
1415 * @chip: The NAND chip
1416 * @eraseblock: block to erase
1418 * This function sends an ERASE command and waits for the NAND to be ready
1420 * This function does not select/unselect the CS line.
1422 * Returns 0 on success, a negative error code otherwise.
1424 int nand_erase_op(struct nand_chip *chip, unsigned int eraseblock)
1426 struct mtd_info *mtd = nand_to_mtd(chip);
1427 unsigned int page = eraseblock <<
1428 (chip->phys_erase_shift - chip->page_shift);
1431 chip->cmdfunc(mtd, NAND_CMD_ERASE1, -1, page);
1432 chip->cmdfunc(mtd, NAND_CMD_ERASE2, -1, -1);
1434 status = chip->waitfunc(mtd, chip);
1438 if (status & NAND_STATUS_FAIL)
1443 EXPORT_SYMBOL_GPL(nand_erase_op);
1446 * nand_set_features_op - Do a SET FEATURES operation
1447 * @chip: The NAND chip
1448 * @feature: feature id
1449 * @data: 4 bytes of data
1451 * This function sends a SET FEATURES command and waits for the NAND to be
1452 * ready before returning.
1453 * This function does not select/unselect the CS line.
1455 * Returns 0 on success, a negative error code otherwise.
1457 static int nand_set_features_op(struct nand_chip *chip, u8 feature,
1460 struct mtd_info *mtd = nand_to_mtd(chip);
1461 const u8 *params = data;
1464 chip->cmdfunc(mtd, NAND_CMD_SET_FEATURES, feature, -1);
1465 for (i = 0; i < ONFI_SUBFEATURE_PARAM_LEN; ++i)
1466 chip->write_byte(mtd, params[i]);
1468 status = chip->waitfunc(mtd, chip);
1469 if (status & NAND_STATUS_FAIL)
1476 * nand_get_features_op - Do a GET FEATURES operation
1477 * @chip: The NAND chip
1478 * @feature: feature id
1479 * @data: 4 bytes of data
1481 * This function sends a GET FEATURES command and waits for the NAND to be
1482 * ready before returning.
1483 * This function does not select/unselect the CS line.
1485 * Returns 0 on success, a negative error code otherwise.
1487 static int nand_get_features_op(struct nand_chip *chip, u8 feature,
1490 struct mtd_info *mtd = nand_to_mtd(chip);
1494 chip->cmdfunc(mtd, NAND_CMD_GET_FEATURES, feature, -1);
1495 for (i = 0; i < ONFI_SUBFEATURE_PARAM_LEN; ++i)
1496 params[i] = chip->read_byte(mtd);
1502 * nand_reset_op - Do a reset operation
1503 * @chip: The NAND chip
1505 * This function sends a RESET command and waits for the NAND to be ready
1507 * This function does not select/unselect the CS line.
1509 * Returns 0 on success, a negative error code otherwise.
1511 int nand_reset_op(struct nand_chip *chip)
1513 struct mtd_info *mtd = nand_to_mtd(chip);
1515 chip->cmdfunc(mtd, NAND_CMD_RESET, -1, -1);
1519 EXPORT_SYMBOL_GPL(nand_reset_op);
1522 * nand_read_data_op - Read data from the NAND
1523 * @chip: The NAND chip
1524 * @buf: buffer used to store the data
1525 * @len: length of the buffer
1526 * @force_8bit: force 8-bit bus access
1528 * This function does a raw data read on the bus. Usually used after launching
1529 * another NAND operation like nand_read_page_op().
1530 * This function does not select/unselect the CS line.
1532 * Returns 0 on success, a negative error code otherwise.
1534 int nand_read_data_op(struct nand_chip *chip, void *buf, unsigned int len,
1537 struct mtd_info *mtd = nand_to_mtd(chip);
1546 for (i = 0; i < len; i++)
1547 p[i] = chip->read_byte(mtd);
1549 chip->read_buf(mtd, buf, len);
1554 EXPORT_SYMBOL_GPL(nand_read_data_op);
1557 * nand_write_data_op - Write data from the NAND
1558 * @chip: The NAND chip
1559 * @buf: buffer containing the data to send on the bus
1560 * @len: length of the buffer
1561 * @force_8bit: force 8-bit bus access
1563 * This function does a raw data write on the bus. Usually used after launching
1564 * another NAND operation like nand_write_page_begin_op().
1565 * This function does not select/unselect the CS line.
1567 * Returns 0 on success, a negative error code otherwise.
1569 int nand_write_data_op(struct nand_chip *chip, const void *buf,
1570 unsigned int len, bool force_8bit)
1572 struct mtd_info *mtd = nand_to_mtd(chip);
1581 for (i = 0; i < len; i++)
1582 chip->write_byte(mtd, p[i]);
1584 chip->write_buf(mtd, buf, len);
1589 EXPORT_SYMBOL_GPL(nand_write_data_op);
1592 * nand_reset - Reset and initialize a NAND device
1593 * @chip: The NAND chip
1594 * @chipnr: Internal die id
1596 * Returns 0 for success or negative error code otherwise
1598 int nand_reset(struct nand_chip *chip, int chipnr)
1600 struct mtd_info *mtd = nand_to_mtd(chip);
1603 ret = nand_reset_data_interface(chip, chipnr);
1608 * The CS line has to be released before we can apply the new NAND
1609 * interface settings, hence this weird ->select_chip() dance.
1611 chip->select_chip(mtd, chipnr);
1612 ret = nand_reset_op(chip);
1613 chip->select_chip(mtd, -1);
1617 chip->select_chip(mtd, chipnr);
1618 ret = nand_setup_data_interface(chip, chipnr);
1619 chip->select_chip(mtd, -1);
1627 * nand_check_erased_buf - check if a buffer contains (almost) only 0xff data
1628 * @buf: buffer to test
1629 * @len: buffer length
1630 * @bitflips_threshold: maximum number of bitflips
1632 * Check if a buffer contains only 0xff, which means the underlying region
1633 * has been erased and is ready to be programmed.
1634 * The bitflips_threshold specify the maximum number of bitflips before
1635 * considering the region is not erased.
1636 * Note: The logic of this function has been extracted from the memweight
1637 * implementation, except that nand_check_erased_buf function exit before
1638 * testing the whole buffer if the number of bitflips exceed the
1639 * bitflips_threshold value.
1641 * Returns a positive number of bitflips less than or equal to
1642 * bitflips_threshold, or -ERROR_CODE for bitflips in excess of the
1645 static int nand_check_erased_buf(void *buf, int len, int bitflips_threshold)
1647 const unsigned char *bitmap = buf;
1651 for (; len && ((uintptr_t)bitmap) % sizeof(long);
1653 weight = hweight8(*bitmap);
1654 bitflips += BITS_PER_BYTE - weight;
1655 if (unlikely(bitflips > bitflips_threshold))
1659 for (; len >= 4; len -= 4, bitmap += 4) {
1660 weight = hweight32(*((u32 *)bitmap));
1661 bitflips += 32 - weight;
1662 if (unlikely(bitflips > bitflips_threshold))
1666 for (; len > 0; len--, bitmap++) {
1667 weight = hweight8(*bitmap);
1668 bitflips += BITS_PER_BYTE - weight;
1669 if (unlikely(bitflips > bitflips_threshold))
1677 * nand_check_erased_ecc_chunk - check if an ECC chunk contains (almost) only
1679 * @data: data buffer to test
1680 * @datalen: data length
1682 * @ecclen: ECC length
1683 * @extraoob: extra OOB buffer
1684 * @extraooblen: extra OOB length
1685 * @bitflips_threshold: maximum number of bitflips
1687 * Check if a data buffer and its associated ECC and OOB data contains only
1688 * 0xff pattern, which means the underlying region has been erased and is
1689 * ready to be programmed.
1690 * The bitflips_threshold specify the maximum number of bitflips before
1691 * considering the region as not erased.
1694 * 1/ ECC algorithms are working on pre-defined block sizes which are usually
1695 * different from the NAND page size. When fixing bitflips, ECC engines will
1696 * report the number of errors per chunk, and the NAND core infrastructure
1697 * expect you to return the maximum number of bitflips for the whole page.
1698 * This is why you should always use this function on a single chunk and
1699 * not on the whole page. After checking each chunk you should update your
1700 * max_bitflips value accordingly.
1701 * 2/ When checking for bitflips in erased pages you should not only check
1702 * the payload data but also their associated ECC data, because a user might
1703 * have programmed almost all bits to 1 but a few. In this case, we
1704 * shouldn't consider the chunk as erased, and checking ECC bytes prevent
1706 * 3/ The extraoob argument is optional, and should be used if some of your OOB
1707 * data are protected by the ECC engine.
1708 * It could also be used if you support subpages and want to attach some
1709 * extra OOB data to an ECC chunk.
1711 * Returns a positive number of bitflips less than or equal to
1712 * bitflips_threshold, or -ERROR_CODE for bitflips in excess of the
1713 * threshold. In case of success, the passed buffers are filled with 0xff.
1715 int nand_check_erased_ecc_chunk(void *data, int datalen,
1716 void *ecc, int ecclen,
1717 void *extraoob, int extraooblen,
1718 int bitflips_threshold)
1720 int data_bitflips = 0, ecc_bitflips = 0, extraoob_bitflips = 0;
1722 data_bitflips = nand_check_erased_buf(data, datalen,
1723 bitflips_threshold);
1724 if (data_bitflips < 0)
1725 return data_bitflips;
1727 bitflips_threshold -= data_bitflips;
1729 ecc_bitflips = nand_check_erased_buf(ecc, ecclen, bitflips_threshold);
1730 if (ecc_bitflips < 0)
1731 return ecc_bitflips;
1733 bitflips_threshold -= ecc_bitflips;
1735 extraoob_bitflips = nand_check_erased_buf(extraoob, extraooblen,
1736 bitflips_threshold);
1737 if (extraoob_bitflips < 0)
1738 return extraoob_bitflips;
1741 memset(data, 0xff, datalen);
1744 memset(ecc, 0xff, ecclen);
1746 if (extraoob_bitflips)
1747 memset(extraoob, 0xff, extraooblen);
1749 return data_bitflips + ecc_bitflips + extraoob_bitflips;
1751 EXPORT_SYMBOL(nand_check_erased_ecc_chunk);
1754 * nand_read_page_raw - [INTERN] read raw page data without ecc
1755 * @mtd: mtd info structure
1756 * @chip: nand chip info structure
1757 * @buf: buffer to store read data
1758 * @oob_required: caller requires OOB data read to chip->oob_poi
1759 * @page: page number to read
1761 * Not for syndrome calculating ECC controllers, which use a special oob layout.
1763 static int nand_read_page_raw(struct mtd_info *mtd, struct nand_chip *chip,
1764 uint8_t *buf, int oob_required, int page)
1768 ret = nand_read_data_op(chip, buf, mtd->writesize, false);
1773 ret = nand_read_data_op(chip, chip->oob_poi, mtd->oobsize,
1783 * nand_read_page_raw_syndrome - [INTERN] read raw page data without ecc
1784 * @mtd: mtd info structure
1785 * @chip: nand chip info structure
1786 * @buf: buffer to store read data
1787 * @oob_required: caller requires OOB data read to chip->oob_poi
1788 * @page: page number to read
1790 * We need a special oob layout and handling even when OOB isn't used.
1792 static int nand_read_page_raw_syndrome(struct mtd_info *mtd,
1793 struct nand_chip *chip, uint8_t *buf,
1794 int oob_required, int page)
1796 int eccsize = chip->ecc.size;
1797 int eccbytes = chip->ecc.bytes;
1798 uint8_t *oob = chip->oob_poi;
1799 int steps, size, ret;
1801 for (steps = chip->ecc.steps; steps > 0; steps--) {
1802 ret = nand_read_data_op(chip, buf, eccsize, false);
1808 if (chip->ecc.prepad) {
1809 ret = nand_read_data_op(chip, oob, chip->ecc.prepad,
1814 oob += chip->ecc.prepad;
1817 ret = nand_read_data_op(chip, oob, eccbytes, false);
1823 if (chip->ecc.postpad) {
1824 ret = nand_read_data_op(chip, oob, chip->ecc.postpad,
1829 oob += chip->ecc.postpad;
1833 size = mtd->oobsize - (oob - chip->oob_poi);
1835 ret = nand_read_data_op(chip, oob, size, false);
1844 * nand_read_page_swecc - [REPLACEABLE] software ECC based page read function
1845 * @mtd: mtd info structure
1846 * @chip: nand chip info structure
1847 * @buf: buffer to store read data
1848 * @oob_required: caller requires OOB data read to chip->oob_poi
1849 * @page: page number to read
1851 static int nand_read_page_swecc(struct mtd_info *mtd, struct nand_chip *chip,
1852 uint8_t *buf, int oob_required, int page)
1854 int i, eccsize = chip->ecc.size;
1855 int eccbytes = chip->ecc.bytes;
1856 int eccsteps = chip->ecc.steps;
1858 uint8_t *ecc_calc = chip->buffers->ecccalc;
1859 uint8_t *ecc_code = chip->buffers->ecccode;
1860 uint32_t *eccpos = chip->ecc.layout->eccpos;
1861 unsigned int max_bitflips = 0;
1863 chip->ecc.read_page_raw(mtd, chip, buf, 1, page);
1865 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize)
1866 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
1868 for (i = 0; i < chip->ecc.total; i++)
1869 ecc_code[i] = chip->oob_poi[eccpos[i]];
1871 eccsteps = chip->ecc.steps;
1874 for (i = 0 ; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
1877 stat = chip->ecc.correct(mtd, p, &ecc_code[i], &ecc_calc[i]);
1879 mtd->ecc_stats.failed++;
1881 mtd->ecc_stats.corrected += stat;
1882 max_bitflips = max_t(unsigned int, max_bitflips, stat);
1885 return max_bitflips;
1889 * nand_read_subpage - [REPLACEABLE] ECC based sub-page read function
1890 * @mtd: mtd info structure
1891 * @chip: nand chip info structure
1892 * @data_offs: offset of requested data within the page
1893 * @readlen: data length
1894 * @bufpoi: buffer to store read data
1895 * @page: page number to read
1897 static int nand_read_subpage(struct mtd_info *mtd, struct nand_chip *chip,
1898 uint32_t data_offs, uint32_t readlen, uint8_t *bufpoi,
1901 int start_step, end_step, num_steps;
1902 uint32_t *eccpos = chip->ecc.layout->eccpos;
1904 int data_col_addr, i, gaps = 0;
1905 int datafrag_len, eccfrag_len, aligned_len, aligned_pos;
1906 int busw = (chip->options & NAND_BUSWIDTH_16) ? 2 : 1;
1908 unsigned int max_bitflips = 0;
1911 /* Column address within the page aligned to ECC size (256bytes) */
1912 start_step = data_offs / chip->ecc.size;
1913 end_step = (data_offs + readlen - 1) / chip->ecc.size;
1914 num_steps = end_step - start_step + 1;
1915 index = start_step * chip->ecc.bytes;
1917 /* Data size aligned to ECC ecc.size */
1918 datafrag_len = num_steps * chip->ecc.size;
1919 eccfrag_len = num_steps * chip->ecc.bytes;
1921 data_col_addr = start_step * chip->ecc.size;
1922 /* If we read not a page aligned data */
1923 if (data_col_addr != 0)
1924 chip->cmdfunc(mtd, NAND_CMD_RNDOUT, data_col_addr, -1);
1926 p = bufpoi + data_col_addr;
1927 ret = nand_read_data_op(chip, p, datafrag_len, false);
1932 for (i = 0; i < eccfrag_len ; i += chip->ecc.bytes, p += chip->ecc.size)
1933 chip->ecc.calculate(mtd, p, &chip->buffers->ecccalc[i]);
1936 * The performance is faster if we position offsets according to
1937 * ecc.pos. Let's make sure that there are no gaps in ECC positions.
1939 for (i = 0; i < eccfrag_len - 1; i++) {
1940 if (eccpos[i + index] + 1 != eccpos[i + index + 1]) {
1946 ret = nand_change_read_column_op(chip, mtd->writesize,
1947 chip->oob_poi, mtd->oobsize,
1953 * Send the command to read the particular ECC bytes take care
1954 * about buswidth alignment in read_buf.
1956 aligned_pos = eccpos[index] & ~(busw - 1);
1957 aligned_len = eccfrag_len;
1958 if (eccpos[index] & (busw - 1))
1960 if (eccpos[index + (num_steps * chip->ecc.bytes)] & (busw - 1))
1963 ret = nand_change_read_column_op(chip,
1964 mtd->writesize + aligned_pos,
1965 &chip->oob_poi[aligned_pos],
1966 aligned_len, false);
1971 for (i = 0; i < eccfrag_len; i++)
1972 chip->buffers->ecccode[i] = chip->oob_poi[eccpos[i + index]];
1974 p = bufpoi + data_col_addr;
1975 for (i = 0; i < eccfrag_len ; i += chip->ecc.bytes, p += chip->ecc.size) {
1978 stat = chip->ecc.correct(mtd, p,
1979 &chip->buffers->ecccode[i], &chip->buffers->ecccalc[i]);
1980 if (stat == -EBADMSG &&
1981 (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
1982 /* check for empty pages with bitflips */
1983 stat = nand_check_erased_ecc_chunk(p, chip->ecc.size,
1984 &chip->buffers->ecccode[i],
1987 chip->ecc.strength);
1991 mtd->ecc_stats.failed++;
1993 mtd->ecc_stats.corrected += stat;
1994 max_bitflips = max_t(unsigned int, max_bitflips, stat);
1997 return max_bitflips;
2001 * nand_read_page_hwecc - [REPLACEABLE] hardware ECC based page read function
2002 * @mtd: mtd info structure
2003 * @chip: nand chip info structure
2004 * @buf: buffer to store read data
2005 * @oob_required: caller requires OOB data read to chip->oob_poi
2006 * @page: page number to read
2008 * Not for syndrome calculating ECC controllers which need a special oob layout.
2010 static int nand_read_page_hwecc(struct mtd_info *mtd, struct nand_chip *chip,
2011 uint8_t *buf, int oob_required, int page)
2013 int i, eccsize = chip->ecc.size;
2014 int eccbytes = chip->ecc.bytes;
2015 int eccsteps = chip->ecc.steps;
2017 uint8_t *ecc_calc = chip->buffers->ecccalc;
2018 uint8_t *ecc_code = chip->buffers->ecccode;
2019 uint32_t *eccpos = chip->ecc.layout->eccpos;
2020 unsigned int max_bitflips = 0;
2023 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
2024 chip->ecc.hwctl(mtd, NAND_ECC_READ);
2026 ret = nand_read_data_op(chip, p, eccsize, false);
2030 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
2033 ret = nand_read_data_op(chip, chip->oob_poi, mtd->oobsize, false);
2037 for (i = 0; i < chip->ecc.total; i++)
2038 ecc_code[i] = chip->oob_poi[eccpos[i]];
2040 eccsteps = chip->ecc.steps;
2043 for (i = 0 ; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
2046 stat = chip->ecc.correct(mtd, p, &ecc_code[i], &ecc_calc[i]);
2047 if (stat == -EBADMSG &&
2048 (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
2049 /* check for empty pages with bitflips */
2050 stat = nand_check_erased_ecc_chunk(p, eccsize,
2051 &ecc_code[i], eccbytes,
2053 chip->ecc.strength);
2057 mtd->ecc_stats.failed++;
2059 mtd->ecc_stats.corrected += stat;
2060 max_bitflips = max_t(unsigned int, max_bitflips, stat);
2063 return max_bitflips;
2067 * nand_read_page_hwecc_oob_first - [REPLACEABLE] hw ecc, read oob first
2068 * @mtd: mtd info structure
2069 * @chip: nand chip info structure
2070 * @buf: buffer to store read data
2071 * @oob_required: caller requires OOB data read to chip->oob_poi
2072 * @page: page number to read
2074 * Hardware ECC for large page chips, require OOB to be read first. For this
2075 * ECC mode, the write_page method is re-used from ECC_HW. These methods
2076 * read/write ECC from the OOB area, unlike the ECC_HW_SYNDROME support with
2077 * multiple ECC steps, follows the "infix ECC" scheme and reads/writes ECC from
2078 * the data area, by overwriting the NAND manufacturer bad block markings.
2080 static int nand_read_page_hwecc_oob_first(struct mtd_info *mtd,
2081 struct nand_chip *chip, uint8_t *buf, int oob_required, int page)
2083 int i, eccsize = chip->ecc.size;
2084 int eccbytes = chip->ecc.bytes;
2085 int eccsteps = chip->ecc.steps;
2087 uint8_t *ecc_code = chip->buffers->ecccode;
2088 uint32_t *eccpos = chip->ecc.layout->eccpos;
2089 uint8_t *ecc_calc = chip->buffers->ecccalc;
2090 unsigned int max_bitflips = 0;
2093 /* Read the OOB area first */
2094 ret = nand_read_oob_op(chip, page, 0, chip->oob_poi, mtd->oobsize);
2098 ret = nand_read_page_op(chip, page, 0, NULL, 0);
2102 for (i = 0; i < chip->ecc.total; i++)
2103 ecc_code[i] = chip->oob_poi[eccpos[i]];
2105 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
2108 chip->ecc.hwctl(mtd, NAND_ECC_READ);
2110 ret = nand_read_data_op(chip, p, eccsize, false);
2114 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
2116 stat = chip->ecc.correct(mtd, p, &ecc_code[i], NULL);
2117 if (stat == -EBADMSG &&
2118 (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
2119 /* check for empty pages with bitflips */
2120 stat = nand_check_erased_ecc_chunk(p, eccsize,
2121 &ecc_code[i], eccbytes,
2123 chip->ecc.strength);
2127 mtd->ecc_stats.failed++;
2129 mtd->ecc_stats.corrected += stat;
2130 max_bitflips = max_t(unsigned int, max_bitflips, stat);
2133 return max_bitflips;
2137 * nand_read_page_syndrome - [REPLACEABLE] hardware ECC syndrome based page read
2138 * @mtd: mtd info structure
2139 * @chip: nand chip info structure
2140 * @buf: buffer to store read data
2141 * @oob_required: caller requires OOB data read to chip->oob_poi
2142 * @page: page number to read
2144 * The hw generator calculates the error syndrome automatically. Therefore we
2145 * need a special oob layout and handling.
2147 static int nand_read_page_syndrome(struct mtd_info *mtd, struct nand_chip *chip,
2148 uint8_t *buf, int oob_required, int page)
2150 int ret, i, eccsize = chip->ecc.size;
2151 int eccbytes = chip->ecc.bytes;
2152 int eccsteps = chip->ecc.steps;
2153 int eccpadbytes = eccbytes + chip->ecc.prepad + chip->ecc.postpad;
2155 uint8_t *oob = chip->oob_poi;
2156 unsigned int max_bitflips = 0;
2158 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
2161 chip->ecc.hwctl(mtd, NAND_ECC_READ);
2163 ret = nand_read_data_op(chip, p, eccsize, false);
2167 if (chip->ecc.prepad) {
2168 ret = nand_read_data_op(chip, oob, chip->ecc.prepad,
2173 oob += chip->ecc.prepad;
2176 chip->ecc.hwctl(mtd, NAND_ECC_READSYN);
2178 ret = nand_read_data_op(chip, oob, eccbytes, false);
2182 stat = chip->ecc.correct(mtd, p, oob, NULL);
2186 if (chip->ecc.postpad) {
2187 ret = nand_read_data_op(chip, oob, chip->ecc.postpad,
2192 oob += chip->ecc.postpad;
2195 if (stat == -EBADMSG &&
2196 (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
2197 /* check for empty pages with bitflips */
2198 stat = nand_check_erased_ecc_chunk(p, chip->ecc.size,
2202 chip->ecc.strength);
2206 mtd->ecc_stats.failed++;
2208 mtd->ecc_stats.corrected += stat;
2209 max_bitflips = max_t(unsigned int, max_bitflips, stat);
2213 /* Calculate remaining oob bytes */
2214 i = mtd->oobsize - (oob - chip->oob_poi);
2216 ret = nand_read_data_op(chip, oob, i, false);
2221 return max_bitflips;
2225 * nand_transfer_oob - [INTERN] Transfer oob to client buffer
2226 * @chip: nand chip structure
2227 * @oob: oob destination address
2228 * @ops: oob ops structure
2229 * @len: size of oob to transfer
2231 static uint8_t *nand_transfer_oob(struct nand_chip *chip, uint8_t *oob,
2232 struct mtd_oob_ops *ops, size_t len)
2234 switch (ops->mode) {
2236 case MTD_OPS_PLACE_OOB:
2238 memcpy(oob, chip->oob_poi + ops->ooboffs, len);
2241 case MTD_OPS_AUTO_OOB: {
2242 struct nand_oobfree *free = chip->ecc.layout->oobfree;
2243 uint32_t boffs = 0, roffs = ops->ooboffs;
2246 for (; free->length && len; free++, len -= bytes) {
2247 /* Read request not from offset 0? */
2248 if (unlikely(roffs)) {
2249 if (roffs >= free->length) {
2250 roffs -= free->length;
2253 boffs = free->offset + roffs;
2254 bytes = min_t(size_t, len,
2255 (free->length - roffs));
2258 bytes = min_t(size_t, len, free->length);
2259 boffs = free->offset;
2261 memcpy(oob, chip->oob_poi + boffs, bytes);
2273 * nand_setup_read_retry - [INTERN] Set the READ RETRY mode
2274 * @mtd: MTD device structure
2275 * @retry_mode: the retry mode to use
2277 * Some vendors supply a special command to shift the Vt threshold, to be used
2278 * when there are too many bitflips in a page (i.e., ECC error). After setting
2279 * a new threshold, the host should retry reading the page.
2281 static int nand_setup_read_retry(struct mtd_info *mtd, int retry_mode)
2283 struct nand_chip *chip = mtd_to_nand(mtd);
2285 pr_debug("setting READ RETRY mode %d\n", retry_mode);
2287 if (retry_mode >= chip->read_retries)
2290 if (!chip->setup_read_retry)
2293 return chip->setup_read_retry(mtd, retry_mode);
2297 * nand_do_read_ops - [INTERN] Read data with ECC
2298 * @mtd: MTD device structure
2299 * @from: offset to read from
2300 * @ops: oob ops structure
2302 * Internal function. Called with chip held.
2304 static int nand_do_read_ops(struct mtd_info *mtd, loff_t from,
2305 struct mtd_oob_ops *ops)
2307 int chipnr, page, realpage, col, bytes, aligned, oob_required;
2308 struct nand_chip *chip = mtd_to_nand(mtd);
2310 uint32_t readlen = ops->len;
2311 uint32_t oobreadlen = ops->ooblen;
2312 uint32_t max_oobsize = mtd_oobavail(mtd, ops);
2314 uint8_t *bufpoi, *oob, *buf;
2316 unsigned int max_bitflips = 0;
2318 bool ecc_fail = false;
2320 chipnr = (int)(from >> chip->chip_shift);
2321 chip->select_chip(mtd, chipnr);
2323 realpage = (int)(from >> chip->page_shift);
2324 page = realpage & chip->pagemask;
2326 col = (int)(from & (mtd->writesize - 1));
2330 oob_required = oob ? 1 : 0;
2333 unsigned int ecc_failures = mtd->ecc_stats.failed;
2336 bytes = min(mtd->writesize - col, readlen);
2337 aligned = (bytes == mtd->writesize);
2341 else if (chip->options & NAND_USE_BOUNCE_BUFFER)
2342 use_bufpoi = !IS_ALIGNED((unsigned long)buf,
2347 /* Is the current page in the buffer? */
2348 if (realpage != chip->pagebuf || oob) {
2349 bufpoi = use_bufpoi ? chip->buffers->databuf : buf;
2351 if (use_bufpoi && aligned)
2352 pr_debug("%s: using read bounce buffer for buf@%p\n",
2356 if (nand_standard_page_accessors(&chip->ecc)) {
2357 ret = nand_read_page_op(chip, page, 0, NULL, 0);
2363 * Now read the page into the buffer. Absent an error,
2364 * the read methods return max bitflips per ecc step.
2366 if (unlikely(ops->mode == MTD_OPS_RAW))
2367 ret = chip->ecc.read_page_raw(mtd, chip, bufpoi,
2370 else if (!aligned && NAND_HAS_SUBPAGE_READ(chip) &&
2372 ret = chip->ecc.read_subpage(mtd, chip,
2376 ret = chip->ecc.read_page(mtd, chip, bufpoi,
2377 oob_required, page);
2380 /* Invalidate page cache */
2385 max_bitflips = max_t(unsigned int, max_bitflips, ret);
2387 /* Transfer not aligned data */
2389 if (!NAND_HAS_SUBPAGE_READ(chip) && !oob &&
2390 !(mtd->ecc_stats.failed - ecc_failures) &&
2391 (ops->mode != MTD_OPS_RAW)) {
2392 chip->pagebuf = realpage;
2393 chip->pagebuf_bitflips = ret;
2395 /* Invalidate page cache */
2398 memcpy(buf, chip->buffers->databuf + col, bytes);
2401 if (unlikely(oob)) {
2402 int toread = min(oobreadlen, max_oobsize);
2405 oob = nand_transfer_oob(chip,
2407 oobreadlen -= toread;
2411 if (chip->options & NAND_NEED_READRDY) {
2412 /* Apply delay or wait for ready/busy pin */
2413 if (!chip->dev_ready)
2414 udelay(chip->chip_delay);
2416 nand_wait_ready(mtd);
2419 if (mtd->ecc_stats.failed - ecc_failures) {
2420 if (retry_mode + 1 < chip->read_retries) {
2422 ret = nand_setup_read_retry(mtd,
2427 /* Reset failures; retry */
2428 mtd->ecc_stats.failed = ecc_failures;
2431 /* No more retry modes; real failure */
2438 memcpy(buf, chip->buffers->databuf + col, bytes);
2440 max_bitflips = max_t(unsigned int, max_bitflips,
2441 chip->pagebuf_bitflips);
2446 /* Reset to retry mode 0 */
2448 ret = nand_setup_read_retry(mtd, 0);
2457 /* For subsequent reads align to page boundary */
2459 /* Increment page address */
2462 page = realpage & chip->pagemask;
2463 /* Check, if we cross a chip boundary */
2466 chip->select_chip(mtd, -1);
2467 chip->select_chip(mtd, chipnr);
2470 chip->select_chip(mtd, -1);
2472 ops->retlen = ops->len - (size_t) readlen;
2474 ops->oobretlen = ops->ooblen - oobreadlen;
2482 return max_bitflips;
2486 * nand_read_oob_std - [REPLACEABLE] the most common OOB data read function
2487 * @mtd: mtd info structure
2488 * @chip: nand chip info structure
2489 * @page: page number to read
2491 static int nand_read_oob_std(struct mtd_info *mtd, struct nand_chip *chip,
2494 return nand_read_oob_op(chip, page, 0, chip->oob_poi, mtd->oobsize);
2498 * nand_read_oob_syndrome - [REPLACEABLE] OOB data read function for HW ECC
2500 * @mtd: mtd info structure
2501 * @chip: nand chip info structure
2502 * @page: page number to read
2504 static int nand_read_oob_syndrome(struct mtd_info *mtd, struct nand_chip *chip,
2507 int length = mtd->oobsize;
2508 int chunk = chip->ecc.bytes + chip->ecc.prepad + chip->ecc.postpad;
2509 int eccsize = chip->ecc.size;
2510 uint8_t *bufpoi = chip->oob_poi;
2511 int i, toread, sndrnd = 0, pos, ret;
2513 ret = nand_read_page_op(chip, page, chip->ecc.size, NULL, 0);
2517 for (i = 0; i < chip->ecc.steps; i++) {
2521 pos = eccsize + i * (eccsize + chunk);
2522 if (mtd->writesize > 512)
2523 ret = nand_change_read_column_op(chip, pos,
2527 ret = nand_read_page_op(chip, page, pos, NULL,
2534 toread = min_t(int, length, chunk);
2536 ret = nand_read_data_op(chip, bufpoi, toread, false);
2544 ret = nand_read_data_op(chip, bufpoi, length, false);
2553 * nand_write_oob_std - [REPLACEABLE] the most common OOB data write function
2554 * @mtd: mtd info structure
2555 * @chip: nand chip info structure
2556 * @page: page number to write
2558 static int nand_write_oob_std(struct mtd_info *mtd, struct nand_chip *chip,
2561 return nand_prog_page_op(chip, page, mtd->writesize, chip->oob_poi,
2566 * nand_write_oob_syndrome - [REPLACEABLE] OOB data write function for HW ECC
2567 * with syndrome - only for large page flash
2568 * @mtd: mtd info structure
2569 * @chip: nand chip info structure
2570 * @page: page number to write
2572 static int nand_write_oob_syndrome(struct mtd_info *mtd,
2573 struct nand_chip *chip, int page)
2575 int chunk = chip->ecc.bytes + chip->ecc.prepad + chip->ecc.postpad;
2576 int eccsize = chip->ecc.size, length = mtd->oobsize;
2577 int ret, i, len, pos, sndcmd = 0, steps = chip->ecc.steps;
2578 const uint8_t *bufpoi = chip->oob_poi;
2581 * data-ecc-data-ecc ... ecc-oob
2583 * data-pad-ecc-pad-data-pad .... ecc-pad-oob
2585 if (!chip->ecc.prepad && !chip->ecc.postpad) {
2586 pos = steps * (eccsize + chunk);
2591 ret = nand_prog_page_begin_op(chip, page, pos, NULL, 0);
2595 for (i = 0; i < steps; i++) {
2597 if (mtd->writesize <= 512) {
2598 uint32_t fill = 0xFFFFFFFF;
2602 int num = min_t(int, len, 4);
2604 ret = nand_write_data_op(chip, &fill,
2612 pos = eccsize + i * (eccsize + chunk);
2613 ret = nand_change_write_column_op(chip, pos,
2621 len = min_t(int, length, chunk);
2623 ret = nand_write_data_op(chip, bufpoi, len, false);
2631 ret = nand_write_data_op(chip, bufpoi, length, false);
2636 return nand_prog_page_end_op(chip);
2640 * nand_do_read_oob - [INTERN] NAND read out-of-band
2641 * @mtd: MTD device structure
2642 * @from: offset to read from
2643 * @ops: oob operations description structure
2645 * NAND read out-of-band data from the spare area.
2647 static int nand_do_read_oob(struct mtd_info *mtd, loff_t from,
2648 struct mtd_oob_ops *ops)
2650 int page, realpage, chipnr;
2651 struct nand_chip *chip = mtd_to_nand(mtd);
2652 struct mtd_ecc_stats stats;
2653 int readlen = ops->ooblen;
2655 uint8_t *buf = ops->oobbuf;
2658 pr_debug("%s: from = 0x%08Lx, len = %i\n",
2659 __func__, (unsigned long long)from, readlen);
2661 stats = mtd->ecc_stats;
2663 len = mtd_oobavail(mtd, ops);
2665 if (unlikely(ops->ooboffs >= len)) {
2666 pr_debug("%s: attempt to start read outside oob\n",
2671 /* Do not allow reads past end of device */
2672 if (unlikely(from >= mtd->size ||
2673 ops->ooboffs + readlen > ((mtd->size >> chip->page_shift) -
2674 (from >> chip->page_shift)) * len)) {
2675 pr_debug("%s: attempt to read beyond end of device\n",
2680 chipnr = (int)(from >> chip->chip_shift);
2681 chip->select_chip(mtd, chipnr);
2683 /* Shift to get page */
2684 realpage = (int)(from >> chip->page_shift);
2685 page = realpage & chip->pagemask;
2690 if (ops->mode == MTD_OPS_RAW)
2691 ret = chip->ecc.read_oob_raw(mtd, chip, page);
2693 ret = chip->ecc.read_oob(mtd, chip, page);
2698 len = min(len, readlen);
2699 buf = nand_transfer_oob(chip, buf, ops, len);
2701 if (chip->options & NAND_NEED_READRDY) {
2702 /* Apply delay or wait for ready/busy pin */
2703 if (!chip->dev_ready)
2704 udelay(chip->chip_delay);
2706 nand_wait_ready(mtd);
2713 /* Increment page address */
2716 page = realpage & chip->pagemask;
2717 /* Check, if we cross a chip boundary */
2720 chip->select_chip(mtd, -1);
2721 chip->select_chip(mtd, chipnr);
2724 chip->select_chip(mtd, -1);
2726 ops->oobretlen = ops->ooblen - readlen;
2731 if (mtd->ecc_stats.failed - stats.failed)
2734 return mtd->ecc_stats.corrected - stats.corrected ? -EUCLEAN : 0;
2738 * nand_read_oob - [MTD Interface] NAND read data and/or out-of-band
2739 * @mtd: MTD device structure
2740 * @from: offset to read from
2741 * @ops: oob operation description structure
2743 * NAND read data and/or out-of-band data.
2745 static int nand_read_oob(struct mtd_info *mtd, loff_t from,
2746 struct mtd_oob_ops *ops)
2748 int ret = -ENOTSUPP;
2752 /* Do not allow reads past end of device */
2753 if (ops->datbuf && (from + ops->len) > mtd->size) {
2754 pr_debug("%s: attempt to read beyond end of device\n",
2759 nand_get_device(mtd, FL_READING);
2761 switch (ops->mode) {
2762 case MTD_OPS_PLACE_OOB:
2763 case MTD_OPS_AUTO_OOB:
2772 ret = nand_do_read_oob(mtd, from, ops);
2774 ret = nand_do_read_ops(mtd, from, ops);
2777 nand_release_device(mtd);
2783 * nand_write_page_raw - [INTERN] raw page write function
2784 * @mtd: mtd info structure
2785 * @chip: nand chip info structure
2787 * @oob_required: must write chip->oob_poi to OOB
2788 * @page: page number to write
2790 * Not for syndrome calculating ECC controllers, which use a special oob layout.
2792 static int nand_write_page_raw(struct mtd_info *mtd, struct nand_chip *chip,
2793 const uint8_t *buf, int oob_required, int page)
2797 ret = nand_write_data_op(chip, buf, mtd->writesize, false);
2802 ret = nand_write_data_op(chip, chip->oob_poi, mtd->oobsize,
2812 * nand_write_page_raw_syndrome - [INTERN] raw page write function
2813 * @mtd: mtd info structure
2814 * @chip: nand chip info structure
2816 * @oob_required: must write chip->oob_poi to OOB
2817 * @page: page number to write
2819 * We need a special oob layout and handling even when ECC isn't checked.
2821 static int nand_write_page_raw_syndrome(struct mtd_info *mtd,
2822 struct nand_chip *chip,
2823 const uint8_t *buf, int oob_required,
2826 int eccsize = chip->ecc.size;
2827 int eccbytes = chip->ecc.bytes;
2828 uint8_t *oob = chip->oob_poi;
2829 int steps, size, ret;
2831 for (steps = chip->ecc.steps; steps > 0; steps--) {
2832 ret = nand_write_data_op(chip, buf, eccsize, false);
2838 if (chip->ecc.prepad) {
2839 ret = nand_write_data_op(chip, oob, chip->ecc.prepad,
2844 oob += chip->ecc.prepad;
2847 ret = nand_write_data_op(chip, oob, eccbytes, false);
2853 if (chip->ecc.postpad) {
2854 ret = nand_write_data_op(chip, oob, chip->ecc.postpad,
2859 oob += chip->ecc.postpad;
2863 size = mtd->oobsize - (oob - chip->oob_poi);
2865 ret = nand_write_data_op(chip, oob, size, false);
2873 * nand_write_page_swecc - [REPLACEABLE] software ECC based page write function
2874 * @mtd: mtd info structure
2875 * @chip: nand chip info structure
2877 * @oob_required: must write chip->oob_poi to OOB
2878 * @page: page number to write
2880 static int nand_write_page_swecc(struct mtd_info *mtd, struct nand_chip *chip,
2881 const uint8_t *buf, int oob_required,
2884 int i, eccsize = chip->ecc.size;
2885 int eccbytes = chip->ecc.bytes;
2886 int eccsteps = chip->ecc.steps;
2887 uint8_t *ecc_calc = chip->buffers->ecccalc;
2888 const uint8_t *p = buf;
2889 uint32_t *eccpos = chip->ecc.layout->eccpos;
2891 /* Software ECC calculation */
2892 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize)
2893 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
2895 for (i = 0; i < chip->ecc.total; i++)
2896 chip->oob_poi[eccpos[i]] = ecc_calc[i];
2898 return chip->ecc.write_page_raw(mtd, chip, buf, 1, page);
2902 * nand_write_page_hwecc - [REPLACEABLE] hardware ECC based page write function
2903 * @mtd: mtd info structure
2904 * @chip: nand chip info structure
2906 * @oob_required: must write chip->oob_poi to OOB
2907 * @page: page number to write
2909 static int nand_write_page_hwecc(struct mtd_info *mtd, struct nand_chip *chip,
2910 const uint8_t *buf, int oob_required,
2913 int i, eccsize = chip->ecc.size;
2914 int eccbytes = chip->ecc.bytes;
2915 int eccsteps = chip->ecc.steps;
2916 uint8_t *ecc_calc = chip->buffers->ecccalc;
2917 const uint8_t *p = buf;
2918 uint32_t *eccpos = chip->ecc.layout->eccpos;
2921 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
2922 chip->ecc.hwctl(mtd, NAND_ECC_WRITE);
2924 ret = nand_write_data_op(chip, p, eccsize, false);
2928 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
2931 for (i = 0; i < chip->ecc.total; i++)
2932 chip->oob_poi[eccpos[i]] = ecc_calc[i];
2934 ret = nand_write_data_op(chip, chip->oob_poi, mtd->oobsize, false);
2943 * nand_write_subpage_hwecc - [REPLACEABLE] hardware ECC based subpage write
2944 * @mtd: mtd info structure
2945 * @chip: nand chip info structure
2946 * @offset: column address of subpage within the page
2947 * @data_len: data length
2949 * @oob_required: must write chip->oob_poi to OOB
2950 * @page: page number to write
2952 static int nand_write_subpage_hwecc(struct mtd_info *mtd,
2953 struct nand_chip *chip, uint32_t offset,
2954 uint32_t data_len, const uint8_t *buf,
2955 int oob_required, int page)
2957 uint8_t *oob_buf = chip->oob_poi;
2958 uint8_t *ecc_calc = chip->buffers->ecccalc;
2959 int ecc_size = chip->ecc.size;
2960 int ecc_bytes = chip->ecc.bytes;
2961 int ecc_steps = chip->ecc.steps;
2962 uint32_t *eccpos = chip->ecc.layout->eccpos;
2963 uint32_t start_step = offset / ecc_size;
2964 uint32_t end_step = (offset + data_len - 1) / ecc_size;
2965 int oob_bytes = mtd->oobsize / ecc_steps;
2969 for (step = 0; step < ecc_steps; step++) {
2970 /* configure controller for WRITE access */
2971 chip->ecc.hwctl(mtd, NAND_ECC_WRITE);
2973 /* write data (untouched subpages already masked by 0xFF) */
2974 ret = nand_write_data_op(chip, buf, ecc_size, false);
2978 /* mask ECC of un-touched subpages by padding 0xFF */
2979 if ((step < start_step) || (step > end_step))
2980 memset(ecc_calc, 0xff, ecc_bytes);
2982 chip->ecc.calculate(mtd, buf, ecc_calc);
2984 /* mask OOB of un-touched subpages by padding 0xFF */
2985 /* if oob_required, preserve OOB metadata of written subpage */
2986 if (!oob_required || (step < start_step) || (step > end_step))
2987 memset(oob_buf, 0xff, oob_bytes);
2990 ecc_calc += ecc_bytes;
2991 oob_buf += oob_bytes;
2994 /* copy calculated ECC for whole page to chip->buffer->oob */
2995 /* this include masked-value(0xFF) for unwritten subpages */
2996 ecc_calc = chip->buffers->ecccalc;
2997 for (i = 0; i < chip->ecc.total; i++)
2998 chip->oob_poi[eccpos[i]] = ecc_calc[i];
3000 /* write OOB buffer to NAND device */
3001 ret = nand_write_data_op(chip, chip->oob_poi, mtd->oobsize, false);
3010 * nand_write_page_syndrome - [REPLACEABLE] hardware ECC syndrome based page write
3011 * @mtd: mtd info structure
3012 * @chip: nand chip info structure
3014 * @oob_required: must write chip->oob_poi to OOB
3015 * @page: page number to write
3017 * The hw generator calculates the error syndrome automatically. Therefore we
3018 * need a special oob layout and handling.
3020 static int nand_write_page_syndrome(struct mtd_info *mtd,
3021 struct nand_chip *chip,
3022 const uint8_t *buf, int oob_required,
3025 int i, eccsize = chip->ecc.size;
3026 int eccbytes = chip->ecc.bytes;
3027 int eccsteps = chip->ecc.steps;
3028 const uint8_t *p = buf;
3029 uint8_t *oob = chip->oob_poi;
3032 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
3033 chip->ecc.hwctl(mtd, NAND_ECC_WRITE);
3035 ret = nand_write_data_op(chip, p, eccsize, false);
3039 if (chip->ecc.prepad) {
3040 ret = nand_write_data_op(chip, oob, chip->ecc.prepad,
3045 oob += chip->ecc.prepad;
3048 chip->ecc.calculate(mtd, p, oob);
3050 ret = nand_write_data_op(chip, oob, eccbytes, false);
3056 if (chip->ecc.postpad) {
3057 ret = nand_write_data_op(chip, oob, chip->ecc.postpad,
3062 oob += chip->ecc.postpad;
3066 /* Calculate remaining oob bytes */
3067 i = mtd->oobsize - (oob - chip->oob_poi);
3069 ret = nand_write_data_op(chip, oob, i, false);
3078 * nand_write_page - [REPLACEABLE] write one page
3079 * @mtd: MTD device structure
3080 * @chip: NAND chip descriptor
3081 * @offset: address offset within the page
3082 * @data_len: length of actual data to be written
3083 * @buf: the data to write
3084 * @oob_required: must write chip->oob_poi to OOB
3085 * @page: page number to write
3086 * @raw: use _raw version of write_page
3088 static int nand_write_page(struct mtd_info *mtd, struct nand_chip *chip,
3089 uint32_t offset, int data_len, const uint8_t *buf,
3090 int oob_required, int page, int raw)
3092 int status, subpage;
3094 if (!(chip->options & NAND_NO_SUBPAGE_WRITE) &&
3095 chip->ecc.write_subpage)
3096 subpage = offset || (data_len < mtd->writesize);
3100 if (nand_standard_page_accessors(&chip->ecc)) {
3101 status = nand_prog_page_begin_op(chip, page, 0, NULL, 0);
3107 status = chip->ecc.write_page_raw(mtd, chip, buf,
3108 oob_required, page);
3110 status = chip->ecc.write_subpage(mtd, chip, offset, data_len,
3111 buf, oob_required, page);
3113 status = chip->ecc.write_page(mtd, chip, buf, oob_required,
3119 if (nand_standard_page_accessors(&chip->ecc))
3120 return nand_prog_page_end_op(chip);
3126 * nand_fill_oob - [INTERN] Transfer client buffer to oob
3127 * @mtd: MTD device structure
3128 * @oob: oob data buffer
3129 * @len: oob data write length
3130 * @ops: oob ops structure
3132 static uint8_t *nand_fill_oob(struct mtd_info *mtd, uint8_t *oob, size_t len,
3133 struct mtd_oob_ops *ops)
3135 struct nand_chip *chip = mtd_to_nand(mtd);
3138 * Initialise to all 0xFF, to avoid the possibility of left over OOB
3139 * data from a previous OOB read.
3141 memset(chip->oob_poi, 0xff, mtd->oobsize);
3143 switch (ops->mode) {
3145 case MTD_OPS_PLACE_OOB:
3147 memcpy(chip->oob_poi + ops->ooboffs, oob, len);
3150 case MTD_OPS_AUTO_OOB: {
3151 struct nand_oobfree *free = chip->ecc.layout->oobfree;
3152 uint32_t boffs = 0, woffs = ops->ooboffs;
3155 for (; free->length && len; free++, len -= bytes) {
3156 /* Write request not from offset 0? */
3157 if (unlikely(woffs)) {
3158 if (woffs >= free->length) {
3159 woffs -= free->length;
3162 boffs = free->offset + woffs;
3163 bytes = min_t(size_t, len,
3164 (free->length - woffs));
3167 bytes = min_t(size_t, len, free->length);
3168 boffs = free->offset;
3170 memcpy(chip->oob_poi + boffs, oob, bytes);
3181 #define NOTALIGNED(x) ((x & (chip->subpagesize - 1)) != 0)
3184 * nand_do_write_ops - [INTERN] NAND write with ECC
3185 * @mtd: MTD device structure
3186 * @to: offset to write to
3187 * @ops: oob operations description structure
3189 * NAND write with ECC.
3191 static int nand_do_write_ops(struct mtd_info *mtd, loff_t to,
3192 struct mtd_oob_ops *ops)
3194 int chipnr, realpage, page, column;
3195 struct nand_chip *chip = mtd_to_nand(mtd);
3196 uint32_t writelen = ops->len;
3198 uint32_t oobwritelen = ops->ooblen;
3199 uint32_t oobmaxlen = mtd_oobavail(mtd, ops);
3201 uint8_t *oob = ops->oobbuf;
3202 uint8_t *buf = ops->datbuf;
3204 int oob_required = oob ? 1 : 0;
3210 /* Reject writes, which are not page aligned */
3211 if (NOTALIGNED(to)) {
3212 pr_notice("%s: attempt to write non page aligned data\n",
3217 column = to & (mtd->writesize - 1);
3219 chipnr = (int)(to >> chip->chip_shift);
3220 chip->select_chip(mtd, chipnr);
3222 /* Check, if it is write protected */
3223 if (nand_check_wp(mtd)) {
3228 realpage = (int)(to >> chip->page_shift);
3229 page = realpage & chip->pagemask;
3231 /* Invalidate the page cache, when we write to the cached page */
3232 if (to <= ((loff_t)chip->pagebuf << chip->page_shift) &&
3233 ((loff_t)chip->pagebuf << chip->page_shift) < (to + ops->len))
3236 /* Don't allow multipage oob writes with offset */
3237 if (oob && ops->ooboffs && (ops->ooboffs + ops->ooblen > oobmaxlen)) {
3243 int bytes = mtd->writesize;
3244 uint8_t *wbuf = buf;
3246 int part_pagewr = (column || writelen < mtd->writesize);
3250 else if (chip->options & NAND_USE_BOUNCE_BUFFER)
3251 use_bufpoi = !IS_ALIGNED((unsigned long)buf,
3257 /* Partial page write?, or need to use bounce buffer */
3259 pr_debug("%s: using write bounce buffer for buf@%p\n",
3262 bytes = min_t(int, bytes - column, writelen);
3264 memset(chip->buffers->databuf, 0xff, mtd->writesize);
3265 memcpy(&chip->buffers->databuf[column], buf, bytes);
3266 wbuf = chip->buffers->databuf;
3269 if (unlikely(oob)) {
3270 size_t len = min(oobwritelen, oobmaxlen);
3271 oob = nand_fill_oob(mtd, oob, len, ops);
3274 /* We still need to erase leftover OOB data */
3275 memset(chip->oob_poi, 0xff, mtd->oobsize);
3277 ret = chip->write_page(mtd, chip, column, bytes, wbuf,
3279 (ops->mode == MTD_OPS_RAW));
3291 page = realpage & chip->pagemask;
3292 /* Check, if we cross a chip boundary */
3295 chip->select_chip(mtd, -1);
3296 chip->select_chip(mtd, chipnr);
3300 ops->retlen = ops->len - writelen;
3302 ops->oobretlen = ops->ooblen;
3305 chip->select_chip(mtd, -1);
3310 * panic_nand_write - [MTD Interface] NAND write with ECC
3311 * @mtd: MTD device structure
3312 * @to: offset to write to
3313 * @len: number of bytes to write
3314 * @retlen: pointer to variable to store the number of written bytes
3315 * @buf: the data to write
3317 * NAND write with ECC. Used when performing writes in interrupt context, this
3318 * may for example be called by mtdoops when writing an oops while in panic.
3320 static int panic_nand_write(struct mtd_info *mtd, loff_t to, size_t len,
3321 size_t *retlen, const uint8_t *buf)
3323 struct nand_chip *chip = mtd_to_nand(mtd);
3324 struct mtd_oob_ops ops;
3327 /* Wait for the device to get ready */
3328 panic_nand_wait(mtd, chip, 400);
3330 /* Grab the device */
3331 panic_nand_get_device(chip, mtd, FL_WRITING);
3333 memset(&ops, 0, sizeof(ops));
3335 ops.datbuf = (uint8_t *)buf;
3336 ops.mode = MTD_OPS_PLACE_OOB;
3338 ret = nand_do_write_ops(mtd, to, &ops);
3340 *retlen = ops.retlen;
3345 * nand_do_write_oob - [MTD Interface] NAND write out-of-band
3346 * @mtd: MTD device structure
3347 * @to: offset to write to
3348 * @ops: oob operation description structure
3350 * NAND write out-of-band.
3352 static int nand_do_write_oob(struct mtd_info *mtd, loff_t to,
3353 struct mtd_oob_ops *ops)
3355 int chipnr, page, status, len;
3356 struct nand_chip *chip = mtd_to_nand(mtd);
3358 pr_debug("%s: to = 0x%08x, len = %i\n",
3359 __func__, (unsigned int)to, (int)ops->ooblen);
3361 len = mtd_oobavail(mtd, ops);
3363 /* Do not allow write past end of page */
3364 if ((ops->ooboffs + ops->ooblen) > len) {
3365 pr_debug("%s: attempt to write past end of page\n",
3370 if (unlikely(ops->ooboffs >= len)) {
3371 pr_debug("%s: attempt to start write outside oob\n",
3376 /* Do not allow write past end of device */
3377 if (unlikely(to >= mtd->size ||
3378 ops->ooboffs + ops->ooblen >
3379 ((mtd->size >> chip->page_shift) -
3380 (to >> chip->page_shift)) * len)) {
3381 pr_debug("%s: attempt to write beyond end of device\n",
3386 chipnr = (int)(to >> chip->chip_shift);
3389 * Reset the chip. Some chips (like the Toshiba TC5832DC found in one
3390 * of my DiskOnChip 2000 test units) will clear the whole data page too
3391 * if we don't do this. I have no clue why, but I seem to have 'fixed'
3392 * it in the doc2000 driver in August 1999. dwmw2.
3394 nand_reset(chip, chipnr);
3396 chip->select_chip(mtd, chipnr);
3398 /* Shift to get page */
3399 page = (int)(to >> chip->page_shift);
3401 /* Check, if it is write protected */
3402 if (nand_check_wp(mtd)) {
3403 chip->select_chip(mtd, -1);
3407 /* Invalidate the page cache, if we write to the cached page */
3408 if (page == chip->pagebuf)
3411 nand_fill_oob(mtd, ops->oobbuf, ops->ooblen, ops);
3413 if (ops->mode == MTD_OPS_RAW)
3414 status = chip->ecc.write_oob_raw(mtd, chip, page & chip->pagemask);
3416 status = chip->ecc.write_oob(mtd, chip, page & chip->pagemask);
3418 chip->select_chip(mtd, -1);
3423 ops->oobretlen = ops->ooblen;
3429 * nand_write_oob - [MTD Interface] NAND write data and/or out-of-band
3430 * @mtd: MTD device structure
3431 * @to: offset to write to
3432 * @ops: oob operation description structure
3434 static int nand_write_oob(struct mtd_info *mtd, loff_t to,
3435 struct mtd_oob_ops *ops)
3437 int ret = -ENOTSUPP;
3441 /* Do not allow writes past end of device */
3442 if (ops->datbuf && (to + ops->len) > mtd->size) {
3443 pr_debug("%s: attempt to write beyond end of device\n",
3448 nand_get_device(mtd, FL_WRITING);
3450 switch (ops->mode) {
3451 case MTD_OPS_PLACE_OOB:
3452 case MTD_OPS_AUTO_OOB:
3461 ret = nand_do_write_oob(mtd, to, ops);
3463 ret = nand_do_write_ops(mtd, to, ops);
3466 nand_release_device(mtd);
3471 * single_erase - [GENERIC] NAND standard block erase command function
3472 * @mtd: MTD device structure
3473 * @page: the page address of the block which will be erased
3475 * Standard erase command for NAND chips. Returns NAND status.
3477 static int single_erase(struct mtd_info *mtd, int page)
3479 struct nand_chip *chip = mtd_to_nand(mtd);
3480 unsigned int eraseblock;
3482 /* Send commands to erase a block */
3483 eraseblock = page >> (chip->phys_erase_shift - chip->page_shift);
3485 return nand_erase_op(chip, eraseblock);
3489 * nand_erase - [MTD Interface] erase block(s)
3490 * @mtd: MTD device structure
3491 * @instr: erase instruction
3493 * Erase one ore more blocks.
3495 static int nand_erase(struct mtd_info *mtd, struct erase_info *instr)
3497 return nand_erase_nand(mtd, instr, 0);
3501 * nand_erase_nand - [INTERN] erase block(s)
3502 * @mtd: MTD device structure
3503 * @instr: erase instruction
3504 * @allowbbt: allow erasing the bbt area
3506 * Erase one ore more blocks.
3508 int nand_erase_nand(struct mtd_info *mtd, struct erase_info *instr,
3511 int page, status, pages_per_block, ret, chipnr;
3512 struct nand_chip *chip = mtd_to_nand(mtd);
3515 pr_debug("%s: start = 0x%012llx, len = %llu\n",
3516 __func__, (unsigned long long)instr->addr,
3517 (unsigned long long)instr->len);
3519 if (check_offs_len(mtd, instr->addr, instr->len))
3522 /* Grab the lock and see if the device is available */
3523 nand_get_device(mtd, FL_ERASING);
3525 /* Shift to get first page */
3526 page = (int)(instr->addr >> chip->page_shift);
3527 chipnr = (int)(instr->addr >> chip->chip_shift);
3529 /* Calculate pages in each block */
3530 pages_per_block = 1 << (chip->phys_erase_shift - chip->page_shift);
3532 /* Select the NAND device */
3533 chip->select_chip(mtd, chipnr);
3535 /* Check, if it is write protected */
3536 if (nand_check_wp(mtd)) {
3537 pr_debug("%s: device is write protected!\n",
3539 instr->state = MTD_ERASE_FAILED;
3543 /* Loop through the pages */
3546 instr->state = MTD_ERASING;
3551 /* Check if we have a bad block, we do not erase bad blocks! */
3552 if (!instr->scrub && nand_block_checkbad(mtd, ((loff_t) page) <<
3553 chip->page_shift, allowbbt)) {
3554 pr_warn("%s: attempt to erase a bad block at page 0x%08x\n",
3556 instr->state = MTD_ERASE_FAILED;
3561 * Invalidate the page cache, if we erase the block which
3562 * contains the current cached page.
3564 if (page <= chip->pagebuf && chip->pagebuf <
3565 (page + pages_per_block))
3568 status = chip->erase(mtd, page & chip->pagemask);
3570 /* See if block erase succeeded */
3571 if (status & NAND_STATUS_FAIL) {
3572 pr_debug("%s: failed erase, page 0x%08x\n",
3574 instr->state = MTD_ERASE_FAILED;
3576 ((loff_t)page << chip->page_shift);
3580 /* Increment page address and decrement length */
3581 len -= (1ULL << chip->phys_erase_shift);
3582 page += pages_per_block;
3584 /* Check, if we cross a chip boundary */
3585 if (len && !(page & chip->pagemask)) {
3587 chip->select_chip(mtd, -1);
3588 chip->select_chip(mtd, chipnr);
3591 instr->state = MTD_ERASE_DONE;
3595 ret = instr->state == MTD_ERASE_DONE ? 0 : -EIO;
3597 /* Deselect and wake up anyone waiting on the device */
3598 chip->select_chip(mtd, -1);
3599 nand_release_device(mtd);
3601 /* Do call back function */
3603 mtd_erase_callback(instr);
3605 /* Return more or less happy */
3610 * nand_sync - [MTD Interface] sync
3611 * @mtd: MTD device structure
3613 * Sync is actually a wait for chip ready function.
3615 static void nand_sync(struct mtd_info *mtd)
3617 pr_debug("%s: called\n", __func__);
3619 /* Grab the lock and see if the device is available */
3620 nand_get_device(mtd, FL_SYNCING);
3621 /* Release it and go back */
3622 nand_release_device(mtd);
3626 * nand_block_isbad - [MTD Interface] Check if block at offset is bad
3627 * @mtd: MTD device structure
3628 * @offs: offset relative to mtd start
3630 static int nand_block_isbad(struct mtd_info *mtd, loff_t offs)
3632 struct nand_chip *chip = mtd_to_nand(mtd);
3633 int chipnr = (int)(offs >> chip->chip_shift);
3636 /* Select the NAND device */
3637 nand_get_device(mtd, FL_READING);
3638 chip->select_chip(mtd, chipnr);
3640 ret = nand_block_checkbad(mtd, offs, 0);
3642 chip->select_chip(mtd, -1);
3643 nand_release_device(mtd);
3649 * nand_block_markbad - [MTD Interface] Mark block at the given offset as bad
3650 * @mtd: MTD device structure
3651 * @ofs: offset relative to mtd start
3653 static int nand_block_markbad(struct mtd_info *mtd, loff_t ofs)
3657 ret = nand_block_isbad(mtd, ofs);
3659 /* If it was bad already, return success and do nothing */
3665 return nand_block_markbad_lowlevel(mtd, ofs);
3669 * nand_onfi_set_features- [REPLACEABLE] set features for ONFI nand
3670 * @mtd: MTD device structure
3671 * @chip: nand chip info structure
3672 * @addr: feature address.
3673 * @subfeature_param: the subfeature parameters, a four bytes array.
3675 static int nand_onfi_set_features(struct mtd_info *mtd, struct nand_chip *chip,
3676 int addr, uint8_t *subfeature_param)
3678 #ifdef CONFIG_SYS_NAND_ONFI_DETECTION
3679 if (!chip->onfi_version ||
3680 !(le16_to_cpu(chip->onfi_params.opt_cmd)
3681 & ONFI_OPT_CMD_SET_GET_FEATURES))
3685 return nand_set_features_op(chip, addr, subfeature_param);
3689 * nand_onfi_get_features- [REPLACEABLE] get features for ONFI nand
3690 * @mtd: MTD device structure
3691 * @chip: nand chip info structure
3692 * @addr: feature address.
3693 * @subfeature_param: the subfeature parameters, a four bytes array.
3695 static int nand_onfi_get_features(struct mtd_info *mtd, struct nand_chip *chip,
3696 int addr, uint8_t *subfeature_param)
3698 #ifdef CONFIG_SYS_NAND_ONFI_DETECTION
3699 if (!chip->onfi_version ||
3700 !(le16_to_cpu(chip->onfi_params.opt_cmd)
3701 & ONFI_OPT_CMD_SET_GET_FEATURES))
3705 return nand_get_features_op(chip, addr, subfeature_param);
3708 /* Set default functions */
3709 static void nand_set_defaults(struct nand_chip *chip, int busw)
3711 /* check for proper chip_delay setup, set 20us if not */
3712 if (!chip->chip_delay)
3713 chip->chip_delay = 20;
3715 /* check, if a user supplied command function given */
3716 if (chip->cmdfunc == NULL)
3717 chip->cmdfunc = nand_command;
3719 /* check, if a user supplied wait function given */
3720 if (chip->waitfunc == NULL)
3721 chip->waitfunc = nand_wait;
3723 if (!chip->select_chip)
3724 chip->select_chip = nand_select_chip;
3726 /* set for ONFI nand */
3727 if (!chip->onfi_set_features)
3728 chip->onfi_set_features = nand_onfi_set_features;
3729 if (!chip->onfi_get_features)
3730 chip->onfi_get_features = nand_onfi_get_features;
3732 /* If called twice, pointers that depend on busw may need to be reset */
3733 if (!chip->read_byte || chip->read_byte == nand_read_byte)
3734 chip->read_byte = busw ? nand_read_byte16 : nand_read_byte;
3735 if (!chip->read_word)
3736 chip->read_word = nand_read_word;
3737 if (!chip->block_bad)
3738 chip->block_bad = nand_block_bad;
3739 if (!chip->block_markbad)
3740 chip->block_markbad = nand_default_block_markbad;
3741 if (!chip->write_buf || chip->write_buf == nand_write_buf)
3742 chip->write_buf = busw ? nand_write_buf16 : nand_write_buf;
3743 if (!chip->write_byte || chip->write_byte == nand_write_byte)
3744 chip->write_byte = busw ? nand_write_byte16 : nand_write_byte;
3745 if (!chip->read_buf || chip->read_buf == nand_read_buf)
3746 chip->read_buf = busw ? nand_read_buf16 : nand_read_buf;
3747 if (!chip->scan_bbt)
3748 chip->scan_bbt = nand_default_bbt;
3750 if (!chip->controller) {
3751 chip->controller = &chip->hwcontrol;
3752 spin_lock_init(&chip->controller->lock);
3753 init_waitqueue_head(&chip->controller->wq);
3756 if (!chip->buf_align)
3757 chip->buf_align = 1;
3760 /* Sanitize ONFI strings so we can safely print them */
3761 static void sanitize_string(char *s, size_t len)
3765 /* Null terminate */
3768 /* Remove non printable chars */
3769 for (i = 0; i < len - 1; i++) {
3770 if (s[i] < ' ' || s[i] > 127)
3774 /* Remove trailing spaces */
3778 static u16 onfi_crc16(u16 crc, u8 const *p, size_t len)
3783 for (i = 0; i < 8; i++)
3784 crc = (crc << 1) ^ ((crc & 0x8000) ? 0x8005 : 0);
3790 #ifdef CONFIG_SYS_NAND_ONFI_DETECTION
3791 /* Parse the Extended Parameter Page. */
3792 static int nand_flash_detect_ext_param_page(struct mtd_info *mtd,
3793 struct nand_chip *chip, struct nand_onfi_params *p)
3795 struct onfi_ext_param_page *ep;
3796 struct onfi_ext_section *s;
3797 struct onfi_ext_ecc_info *ecc;
3803 len = le16_to_cpu(p->ext_param_page_length) * 16;
3804 ep = kmalloc(len, GFP_KERNEL);
3808 /* Send our own NAND_CMD_PARAM. */
3809 ret = nand_read_param_page_op(chip, 0, NULL, 0);
3813 /* Use the Change Read Column command to skip the ONFI param pages. */
3814 ret = nand_change_read_column_op(chip,
3815 sizeof(*p) * p->num_of_param_pages,
3821 if ((onfi_crc16(ONFI_CRC_BASE, ((uint8_t *)ep) + 2, len - 2)
3822 != le16_to_cpu(ep->crc))) {
3823 pr_debug("fail in the CRC.\n");
3828 * Check the signature.
3829 * Do not strictly follow the ONFI spec, maybe changed in future.
3831 if (strncmp((char *)ep->sig, "EPPS", 4)) {
3832 pr_debug("The signature is invalid.\n");
3836 /* find the ECC section. */
3837 cursor = (uint8_t *)(ep + 1);
3838 for (i = 0; i < ONFI_EXT_SECTION_MAX; i++) {
3839 s = ep->sections + i;
3840 if (s->type == ONFI_SECTION_TYPE_2)
3842 cursor += s->length * 16;
3844 if (i == ONFI_EXT_SECTION_MAX) {
3845 pr_debug("We can not find the ECC section.\n");
3849 /* get the info we want. */
3850 ecc = (struct onfi_ext_ecc_info *)cursor;
3852 if (!ecc->codeword_size) {
3853 pr_debug("Invalid codeword size\n");
3857 chip->ecc_strength_ds = ecc->ecc_bits;
3858 chip->ecc_step_ds = 1 << ecc->codeword_size;
3866 static int nand_setup_read_retry_micron(struct mtd_info *mtd, int retry_mode)
3868 struct nand_chip *chip = mtd_to_nand(mtd);
3869 uint8_t feature[ONFI_SUBFEATURE_PARAM_LEN] = {retry_mode};
3871 return chip->onfi_set_features(mtd, chip, ONFI_FEATURE_ADDR_READ_RETRY,
3876 * Configure chip properties from Micron vendor-specific ONFI table
3878 static void nand_onfi_detect_micron(struct nand_chip *chip,
3879 struct nand_onfi_params *p)
3881 struct nand_onfi_vendor_micron *micron = (void *)p->vendor;
3883 if (le16_to_cpu(p->vendor_revision) < 1)
3886 chip->read_retries = micron->read_retry_options;
3887 chip->setup_read_retry = nand_setup_read_retry_micron;
3891 * Check if the NAND chip is ONFI compliant, returns 1 if it is, 0 otherwise.
3893 static int nand_flash_detect_onfi(struct mtd_info *mtd, struct nand_chip *chip,
3896 struct nand_onfi_params *p = &chip->onfi_params;
3900 /* Try ONFI for unknown chip or LP */
3901 ret = nand_readid_op(chip, 0x20, id, sizeof(id));
3902 if (ret || strncmp(id, "ONFI", 4))
3905 ret = nand_read_param_page_op(chip, 0, NULL, 0);
3909 for (i = 0; i < 3; i++) {
3910 ret = nand_read_data_op(chip, p, sizeof(*p), true);
3914 if (onfi_crc16(ONFI_CRC_BASE, (uint8_t *)p, 254) ==
3915 le16_to_cpu(p->crc)) {
3921 pr_err("Could not find valid ONFI parameter page; aborting\n");
3926 val = le16_to_cpu(p->revision);
3928 chip->onfi_version = 23;
3929 else if (val & (1 << 4))
3930 chip->onfi_version = 22;
3931 else if (val & (1 << 3))
3932 chip->onfi_version = 21;
3933 else if (val & (1 << 2))
3934 chip->onfi_version = 20;
3935 else if (val & (1 << 1))
3936 chip->onfi_version = 10;
3938 if (!chip->onfi_version) {
3939 pr_info("unsupported ONFI version: %d\n", val);
3943 sanitize_string(p->manufacturer, sizeof(p->manufacturer));
3944 sanitize_string(p->model, sizeof(p->model));
3946 mtd->name = p->model;
3948 mtd->writesize = le32_to_cpu(p->byte_per_page);
3951 * pages_per_block and blocks_per_lun may not be a power-of-2 size
3952 * (don't ask me who thought of this...). MTD assumes that these
3953 * dimensions will be power-of-2, so just truncate the remaining area.
3955 mtd->erasesize = 1 << (fls(le32_to_cpu(p->pages_per_block)) - 1);
3956 mtd->erasesize *= mtd->writesize;
3958 mtd->oobsize = le16_to_cpu(p->spare_bytes_per_page);
3960 /* See erasesize comment */
3961 chip->chipsize = 1 << (fls(le32_to_cpu(p->blocks_per_lun)) - 1);
3962 chip->chipsize *= (uint64_t)mtd->erasesize * p->lun_count;
3963 chip->bits_per_cell = p->bits_per_cell;
3965 if (onfi_feature(chip) & ONFI_FEATURE_16_BIT_BUS)
3966 *busw = NAND_BUSWIDTH_16;
3970 if (p->ecc_bits != 0xff) {
3971 chip->ecc_strength_ds = p->ecc_bits;
3972 chip->ecc_step_ds = 512;
3973 } else if (chip->onfi_version >= 21 &&
3974 (onfi_feature(chip) & ONFI_FEATURE_EXT_PARAM_PAGE)) {
3977 * The nand_flash_detect_ext_param_page() uses the
3978 * Change Read Column command which maybe not supported
3979 * by the chip->cmdfunc. So try to update the chip->cmdfunc
3980 * now. We do not replace user supplied command function.
3982 if (mtd->writesize > 512 && chip->cmdfunc == nand_command)
3983 chip->cmdfunc = nand_command_lp;
3985 /* The Extended Parameter Page is supported since ONFI 2.1. */
3986 if (nand_flash_detect_ext_param_page(mtd, chip, p))
3987 pr_warn("Failed to detect ONFI extended param page\n");
3989 pr_warn("Could not retrieve ONFI ECC requirements\n");
3992 if (p->jedec_id == NAND_MFR_MICRON)
3993 nand_onfi_detect_micron(chip, p);
3998 static int nand_flash_detect_onfi(struct mtd_info *mtd, struct nand_chip *chip,
4006 * Check if the NAND chip is JEDEC compliant, returns 1 if it is, 0 otherwise.
4008 static int nand_flash_detect_jedec(struct mtd_info *mtd, struct nand_chip *chip,
4011 struct nand_jedec_params *p = &chip->jedec_params;
4012 struct jedec_ecc_info *ecc;
4016 /* Try JEDEC for unknown chip or LP */
4017 ret = nand_readid_op(chip, 0x40, id, sizeof(id));
4018 if (ret || strncmp(id, "JEDEC", sizeof(id)))
4021 ret = nand_read_param_page_op(chip, 0x40, NULL, 0);
4025 for (i = 0; i < 3; i++) {
4026 ret = nand_read_data_op(chip, p, sizeof(*p), true);
4030 if (onfi_crc16(ONFI_CRC_BASE, (uint8_t *)p, 510) ==
4031 le16_to_cpu(p->crc))
4036 pr_err("Could not find valid JEDEC parameter page; aborting\n");
4041 val = le16_to_cpu(p->revision);
4043 chip->jedec_version = 10;
4044 else if (val & (1 << 1))
4045 chip->jedec_version = 1; /* vendor specific version */
4047 if (!chip->jedec_version) {
4048 pr_info("unsupported JEDEC version: %d\n", val);
4052 sanitize_string(p->manufacturer, sizeof(p->manufacturer));
4053 sanitize_string(p->model, sizeof(p->model));
4055 mtd->name = p->model;
4057 mtd->writesize = le32_to_cpu(p->byte_per_page);
4059 /* Please reference to the comment for nand_flash_detect_onfi. */
4060 mtd->erasesize = 1 << (fls(le32_to_cpu(p->pages_per_block)) - 1);
4061 mtd->erasesize *= mtd->writesize;
4063 mtd->oobsize = le16_to_cpu(p->spare_bytes_per_page);
4065 /* Please reference to the comment for nand_flash_detect_onfi. */
4066 chip->chipsize = 1 << (fls(le32_to_cpu(p->blocks_per_lun)) - 1);
4067 chip->chipsize *= (uint64_t)mtd->erasesize * p->lun_count;
4068 chip->bits_per_cell = p->bits_per_cell;
4070 if (jedec_feature(chip) & JEDEC_FEATURE_16_BIT_BUS)
4071 *busw = NAND_BUSWIDTH_16;
4076 ecc = &p->ecc_info[0];
4078 if (ecc->codeword_size >= 9) {
4079 chip->ecc_strength_ds = ecc->ecc_bits;
4080 chip->ecc_step_ds = 1 << ecc->codeword_size;
4082 pr_warn("Invalid codeword size\n");
4089 * nand_id_has_period - Check if an ID string has a given wraparound period
4090 * @id_data: the ID string
4091 * @arrlen: the length of the @id_data array
4092 * @period: the period of repitition
4094 * Check if an ID string is repeated within a given sequence of bytes at
4095 * specific repetition interval period (e.g., {0x20,0x01,0x7F,0x20} has a
4096 * period of 3). This is a helper function for nand_id_len(). Returns non-zero
4097 * if the repetition has a period of @period; otherwise, returns zero.
4099 static int nand_id_has_period(u8 *id_data, int arrlen, int period)
4102 for (i = 0; i < period; i++)
4103 for (j = i + period; j < arrlen; j += period)
4104 if (id_data[i] != id_data[j])
4110 * nand_id_len - Get the length of an ID string returned by CMD_READID
4111 * @id_data: the ID string
4112 * @arrlen: the length of the @id_data array
4114 * Returns the length of the ID string, according to known wraparound/trailing
4115 * zero patterns. If no pattern exists, returns the length of the array.
4117 static int nand_id_len(u8 *id_data, int arrlen)
4119 int last_nonzero, period;
4121 /* Find last non-zero byte */
4122 for (last_nonzero = arrlen - 1; last_nonzero >= 0; last_nonzero--)
4123 if (id_data[last_nonzero])
4127 if (last_nonzero < 0)
4130 /* Calculate wraparound period */
4131 for (period = 1; period < arrlen; period++)
4132 if (nand_id_has_period(id_data, arrlen, period))
4135 /* There's a repeated pattern */
4136 if (period < arrlen)
4139 /* There are trailing zeros */
4140 if (last_nonzero < arrlen - 1)
4141 return last_nonzero + 1;
4143 /* No pattern detected */
4147 /* Extract the bits of per cell from the 3rd byte of the extended ID */
4148 static int nand_get_bits_per_cell(u8 cellinfo)
4152 bits = cellinfo & NAND_CI_CELLTYPE_MSK;
4153 bits >>= NAND_CI_CELLTYPE_SHIFT;
4158 * Many new NAND share similar device ID codes, which represent the size of the
4159 * chip. The rest of the parameters must be decoded according to generic or
4160 * manufacturer-specific "extended ID" decoding patterns.
4162 static void nand_decode_ext_id(struct mtd_info *mtd, struct nand_chip *chip,
4163 u8 id_data[8], int *busw)
4166 /* The 3rd id byte holds MLC / multichip data */
4167 chip->bits_per_cell = nand_get_bits_per_cell(id_data[2]);
4168 /* The 4th id byte is the important one */
4171 id_len = nand_id_len(id_data, 8);
4174 * Field definitions are in the following datasheets:
4175 * Old style (4,5 byte ID): Samsung K9GAG08U0M (p.32)
4176 * New Samsung (6 byte ID): Samsung K9GAG08U0F (p.44)
4177 * Hynix MLC (6 byte ID): Hynix H27UBG8T2B (p.22)
4179 * Check for ID length, non-zero 6th byte, cell type, and Hynix/Samsung
4180 * ID to decide what to do.
4182 if (id_len == 6 && id_data[0] == NAND_MFR_SAMSUNG &&
4183 !nand_is_slc(chip) && id_data[5] != 0x00) {
4185 mtd->writesize = 2048 << (extid & 0x03);
4188 switch (((extid >> 2) & 0x04) | (extid & 0x03)) {
4208 default: /* Other cases are "reserved" (unknown) */
4209 mtd->oobsize = 1024;
4213 /* Calc blocksize */
4214 mtd->erasesize = (128 * 1024) <<
4215 (((extid >> 1) & 0x04) | (extid & 0x03));
4217 } else if (id_len == 6 && id_data[0] == NAND_MFR_HYNIX &&
4218 !nand_is_slc(chip)) {
4222 mtd->writesize = 2048 << (extid & 0x03);
4225 switch (((extid >> 2) & 0x04) | (extid & 0x03)) {
4249 /* Calc blocksize */
4250 tmp = ((extid >> 1) & 0x04) | (extid & 0x03);
4252 mtd->erasesize = (128 * 1024) << tmp;
4253 else if (tmp == 0x03)
4254 mtd->erasesize = 768 * 1024;
4256 mtd->erasesize = (64 * 1024) << tmp;
4260 mtd->writesize = 1024 << (extid & 0x03);
4263 mtd->oobsize = (8 << (extid & 0x01)) *
4264 (mtd->writesize >> 9);
4266 /* Calc blocksize. Blocksize is multiples of 64KiB */
4267 mtd->erasesize = (64 * 1024) << (extid & 0x03);
4269 /* Get buswidth information */
4270 *busw = (extid & 0x01) ? NAND_BUSWIDTH_16 : 0;
4273 * Toshiba 24nm raw SLC (i.e., not BENAND) have 32B OOB per
4274 * 512B page. For Toshiba SLC, we decode the 5th/6th byte as
4276 * - ID byte 6, bits[2:0]: 100b -> 43nm, 101b -> 32nm,
4278 * - ID byte 5, bit[7]: 1 -> BENAND, 0 -> raw SLC
4280 if (id_len >= 6 && id_data[0] == NAND_MFR_TOSHIBA &&
4281 nand_is_slc(chip) &&
4282 (id_data[5] & 0x7) == 0x6 /* 24nm */ &&
4283 !(id_data[4] & 0x80) /* !BENAND */) {
4284 mtd->oobsize = 32 * mtd->writesize >> 9;
4291 * Old devices have chip data hardcoded in the device ID table. nand_decode_id
4292 * decodes a matching ID table entry and assigns the MTD size parameters for
4295 static void nand_decode_id(struct mtd_info *mtd, struct nand_chip *chip,
4296 struct nand_flash_dev *type, u8 id_data[8],
4299 int maf_id = id_data[0];
4301 mtd->erasesize = type->erasesize;
4302 mtd->writesize = type->pagesize;
4303 mtd->oobsize = mtd->writesize / 32;
4304 *busw = type->options & NAND_BUSWIDTH_16;
4306 /* All legacy ID NAND are small-page, SLC */
4307 chip->bits_per_cell = 1;
4310 * Check for Spansion/AMD ID + repeating 5th, 6th byte since
4311 * some Spansion chips have erasesize that conflicts with size
4312 * listed in nand_ids table.
4313 * Data sheet (5 byte ID): Spansion S30ML-P ORNAND (p.39)
4315 if (maf_id == NAND_MFR_AMD && id_data[4] != 0x00 && id_data[5] == 0x00
4316 && id_data[6] == 0x00 && id_data[7] == 0x00
4317 && mtd->writesize == 512) {
4318 mtd->erasesize = 128 * 1024;
4319 mtd->erasesize <<= ((id_data[3] & 0x03) << 1);
4324 * Set the bad block marker/indicator (BBM/BBI) patterns according to some
4325 * heuristic patterns using various detected parameters (e.g., manufacturer,
4326 * page size, cell-type information).
4328 static void nand_decode_bbm_options(struct mtd_info *mtd,
4329 struct nand_chip *chip, u8 id_data[8])
4331 int maf_id = id_data[0];
4333 /* Set the bad block position */
4334 if (mtd->writesize > 512 || (chip->options & NAND_BUSWIDTH_16))
4335 chip->badblockpos = NAND_LARGE_BADBLOCK_POS;
4337 chip->badblockpos = NAND_SMALL_BADBLOCK_POS;
4340 * Bad block marker is stored in the last page of each block on Samsung
4341 * and Hynix MLC devices; stored in first two pages of each block on
4342 * Micron devices with 2KiB pages and on SLC Samsung, Hynix, Toshiba,
4343 * AMD/Spansion, and Macronix. All others scan only the first page.
4345 if (!nand_is_slc(chip) &&
4346 (maf_id == NAND_MFR_SAMSUNG ||
4347 maf_id == NAND_MFR_HYNIX))
4348 chip->bbt_options |= NAND_BBT_SCANLASTPAGE;
4349 else if ((nand_is_slc(chip) &&
4350 (maf_id == NAND_MFR_SAMSUNG ||
4351 maf_id == NAND_MFR_HYNIX ||
4352 maf_id == NAND_MFR_TOSHIBA ||
4353 maf_id == NAND_MFR_AMD ||
4354 maf_id == NAND_MFR_MACRONIX)) ||
4355 (mtd->writesize == 2048 &&
4356 maf_id == NAND_MFR_MICRON))
4357 chip->bbt_options |= NAND_BBT_SCAN2NDPAGE;
4360 static inline bool is_full_id_nand(struct nand_flash_dev *type)
4362 return type->id_len;
4365 static bool find_full_id_nand(struct mtd_info *mtd, struct nand_chip *chip,
4366 struct nand_flash_dev *type, u8 *id_data, int *busw)
4368 if (!strncmp((char *)type->id, (char *)id_data, type->id_len)) {
4369 mtd->writesize = type->pagesize;
4370 mtd->erasesize = type->erasesize;
4371 mtd->oobsize = type->oobsize;
4373 chip->bits_per_cell = nand_get_bits_per_cell(id_data[2]);
4374 chip->chipsize = (uint64_t)type->chipsize << 20;
4375 chip->options |= type->options;
4376 chip->ecc_strength_ds = NAND_ECC_STRENGTH(type);
4377 chip->ecc_step_ds = NAND_ECC_STEP(type);
4378 chip->onfi_timing_mode_default =
4379 type->onfi_timing_mode_default;
4381 *busw = type->options & NAND_BUSWIDTH_16;
4384 mtd->name = type->name;
4392 * Get the flash and manufacturer id and lookup if the type is supported.
4394 struct nand_flash_dev *nand_get_flash_type(struct mtd_info *mtd,
4395 struct nand_chip *chip,
4396 int *maf_id, int *dev_id,
4397 struct nand_flash_dev *type)
4404 * Reset the chip, required by some chips (e.g. Micron MT29FxGxxxxx)
4407 ret = nand_reset(chip, 0);
4409 return ERR_PTR(ret);
4411 /* Select the device */
4412 chip->select_chip(mtd, 0);
4414 /* Send the command for reading device ID */
4415 ret = nand_readid_op(chip, 0, id_data, 2);
4417 return ERR_PTR(ret);
4419 /* Read manufacturer and device IDs */
4420 *maf_id = id_data[0];
4421 *dev_id = id_data[1];
4424 * Try again to make sure, as some systems the bus-hold or other
4425 * interface concerns can cause random data which looks like a
4426 * possibly credible NAND flash to appear. If the two results do
4427 * not match, ignore the device completely.
4430 /* Read entire ID string */
4431 ret = nand_readid_op(chip, 0, id_data, 8);
4433 return ERR_PTR(ret);
4435 if (id_data[0] != *maf_id || id_data[1] != *dev_id) {
4436 pr_info("second ID read did not match %02x,%02x against %02x,%02x\n",
4437 *maf_id, *dev_id, id_data[0], id_data[1]);
4438 return ERR_PTR(-ENODEV);
4442 type = nand_flash_ids;
4444 for (; type->name != NULL; type++) {
4445 if (is_full_id_nand(type)) {
4446 if (find_full_id_nand(mtd, chip, type, id_data, &busw))
4448 } else if (*dev_id == type->dev_id) {
4453 chip->onfi_version = 0;
4454 if (!type->name || !type->pagesize) {
4455 /* Check if the chip is ONFI compliant */
4456 if (nand_flash_detect_onfi(mtd, chip, &busw))
4459 /* Check if the chip is JEDEC compliant */
4460 if (nand_flash_detect_jedec(mtd, chip, &busw))
4465 return ERR_PTR(-ENODEV);
4468 mtd->name = type->name;
4470 chip->chipsize = (uint64_t)type->chipsize << 20;
4472 if (!type->pagesize) {
4473 /* Decode parameters from extended ID */
4474 nand_decode_ext_id(mtd, chip, id_data, &busw);
4476 nand_decode_id(mtd, chip, type, id_data, &busw);
4478 /* Get chip options */
4479 chip->options |= type->options;
4482 * Check if chip is not a Samsung device. Do not clear the
4483 * options for chips which do not have an extended id.
4485 if (*maf_id != NAND_MFR_SAMSUNG && !type->pagesize)
4486 chip->options &= ~NAND_SAMSUNG_LP_OPTIONS;
4489 /* Try to identify manufacturer */
4490 for (maf_idx = 0; nand_manuf_ids[maf_idx].id != 0x0; maf_idx++) {
4491 if (nand_manuf_ids[maf_idx].id == *maf_id)
4495 if (chip->options & NAND_BUSWIDTH_AUTO) {
4496 WARN_ON(chip->options & NAND_BUSWIDTH_16);
4497 chip->options |= busw;
4498 nand_set_defaults(chip, busw);
4499 } else if (busw != (chip->options & NAND_BUSWIDTH_16)) {
4501 * Check, if buswidth is correct. Hardware drivers should set
4504 pr_info("device found, Manufacturer ID: 0x%02x, Chip ID: 0x%02x\n",
4506 pr_info("%s %s\n", nand_manuf_ids[maf_idx].name, mtd->name);
4507 pr_warn("bus width %d instead %d bit\n",
4508 (chip->options & NAND_BUSWIDTH_16) ? 16 : 8,
4510 return ERR_PTR(-EINVAL);
4513 nand_decode_bbm_options(mtd, chip, id_data);
4515 /* Calculate the address shift from the page size */
4516 chip->page_shift = ffs(mtd->writesize) - 1;
4517 /* Convert chipsize to number of pages per chip -1 */
4518 chip->pagemask = (chip->chipsize >> chip->page_shift) - 1;
4520 chip->bbt_erase_shift = chip->phys_erase_shift =
4521 ffs(mtd->erasesize) - 1;
4522 if (chip->chipsize & 0xffffffff)
4523 chip->chip_shift = ffs((unsigned)chip->chipsize) - 1;
4525 chip->chip_shift = ffs((unsigned)(chip->chipsize >> 32));
4526 chip->chip_shift += 32 - 1;
4529 if (chip->chip_shift - chip->page_shift > 16)
4530 chip->options |= NAND_ROW_ADDR_3;
4532 chip->badblockbits = 8;
4533 chip->erase = single_erase;
4535 /* Do not replace user supplied command function! */
4536 if (mtd->writesize > 512 && chip->cmdfunc == nand_command)
4537 chip->cmdfunc = nand_command_lp;
4539 pr_info("device found, Manufacturer ID: 0x%02x, Chip ID: 0x%02x\n",
4542 #ifdef CONFIG_SYS_NAND_ONFI_DETECTION
4543 if (chip->onfi_version)
4544 pr_info("%s %s\n", nand_manuf_ids[maf_idx].name,
4545 chip->onfi_params.model);
4546 else if (chip->jedec_version)
4547 pr_info("%s %s\n", nand_manuf_ids[maf_idx].name,
4548 chip->jedec_params.model);
4550 pr_info("%s %s\n", nand_manuf_ids[maf_idx].name,
4553 if (chip->jedec_version)
4554 pr_info("%s %s\n", nand_manuf_ids[maf_idx].name,
4555 chip->jedec_params.model);
4557 pr_info("%s %s\n", nand_manuf_ids[maf_idx].name,
4560 pr_info("%s %s\n", nand_manuf_ids[maf_idx].name,
4564 pr_info("%d MiB, %s, erase size: %d KiB, page size: %d, OOB size: %d\n",
4565 (int)(chip->chipsize >> 20), nand_is_slc(chip) ? "SLC" : "MLC",
4566 mtd->erasesize >> 10, mtd->writesize, mtd->oobsize);
4569 EXPORT_SYMBOL(nand_get_flash_type);
4571 #if CONFIG_IS_ENABLED(OF_CONTROL)
4572 DECLARE_GLOBAL_DATA_PTR;
4574 static int nand_dt_init(struct mtd_info *mtd, struct nand_chip *chip, int node)
4576 int ret, ecc_mode = -1, ecc_strength, ecc_step;
4577 const void *blob = gd->fdt_blob;
4580 ret = fdtdec_get_int(blob, node, "nand-bus-width", -1);
4582 chip->options |= NAND_BUSWIDTH_16;
4584 if (fdtdec_get_bool(blob, node, "nand-on-flash-bbt"))
4585 chip->bbt_options |= NAND_BBT_USE_FLASH;
4587 str = fdt_getprop(blob, node, "nand-ecc-mode", NULL);
4589 if (!strcmp(str, "none"))
4590 ecc_mode = NAND_ECC_NONE;
4591 else if (!strcmp(str, "soft"))
4592 ecc_mode = NAND_ECC_SOFT;
4593 else if (!strcmp(str, "hw"))
4594 ecc_mode = NAND_ECC_HW;
4595 else if (!strcmp(str, "hw_syndrome"))
4596 ecc_mode = NAND_ECC_HW_SYNDROME;
4597 else if (!strcmp(str, "hw_oob_first"))
4598 ecc_mode = NAND_ECC_HW_OOB_FIRST;
4599 else if (!strcmp(str, "soft_bch"))
4600 ecc_mode = NAND_ECC_SOFT_BCH;
4604 ecc_strength = fdtdec_get_int(blob, node, "nand-ecc-strength", -1);
4605 ecc_step = fdtdec_get_int(blob, node, "nand-ecc-step-size", -1);
4607 if ((ecc_step >= 0 && !(ecc_strength >= 0)) ||
4608 (!(ecc_step >= 0) && ecc_strength >= 0)) {
4609 pr_err("must set both strength and step size in DT\n");
4614 chip->ecc.mode = ecc_mode;
4616 if (ecc_strength >= 0)
4617 chip->ecc.strength = ecc_strength;
4620 chip->ecc.size = ecc_step;
4622 if (fdt_getprop(blob, node, "nand-ecc-maximize", NULL))
4623 chip->ecc.options |= NAND_ECC_MAXIMIZE;
4628 static int nand_dt_init(struct mtd_info *mtd, struct nand_chip *chip, int node)
4632 #endif /* CONFIG_IS_ENABLED(OF_CONTROL) */
4635 * nand_scan_ident - [NAND Interface] Scan for the NAND device
4636 * @mtd: MTD device structure
4637 * @maxchips: number of chips to scan for
4638 * @table: alternative NAND ID table
4640 * This is the first phase of the normal nand_scan() function. It reads the
4641 * flash ID and sets up MTD fields accordingly.
4644 int nand_scan_ident(struct mtd_info *mtd, int maxchips,
4645 struct nand_flash_dev *table)
4647 int i, nand_maf_id, nand_dev_id;
4648 struct nand_chip *chip = mtd_to_nand(mtd);
4649 struct nand_flash_dev *type;
4652 if (chip->flash_node) {
4653 ret = nand_dt_init(mtd, chip, chip->flash_node);
4658 /* Set the default functions */
4659 nand_set_defaults(chip, chip->options & NAND_BUSWIDTH_16);
4661 /* Read the flash type */
4662 type = nand_get_flash_type(mtd, chip, &nand_maf_id,
4663 &nand_dev_id, table);
4666 if (!(chip->options & NAND_SCAN_SILENT_NODEV))
4667 pr_warn("No NAND device found\n");
4668 chip->select_chip(mtd, -1);
4669 return PTR_ERR(type);
4672 /* Initialize the ->data_interface field. */
4673 ret = nand_init_data_interface(chip);
4678 * Setup the data interface correctly on the chip and controller side.
4679 * This explicit call to nand_setup_data_interface() is only required
4680 * for the first die, because nand_reset() has been called before
4681 * ->data_interface and ->default_onfi_timing_mode were set.
4682 * For the other dies, nand_reset() will automatically switch to the
4685 ret = nand_setup_data_interface(chip, 0);
4689 chip->select_chip(mtd, -1);
4691 /* Check for a chip array */
4692 for (i = 1; i < maxchips; i++) {
4695 /* See comment in nand_get_flash_type for reset */
4696 nand_reset(chip, i);
4698 chip->select_chip(mtd, i);
4699 /* Send the command for reading device ID */
4700 nand_readid_op(chip, 0, id, sizeof(id));
4702 /* Read manufacturer and device IDs */
4703 if (nand_maf_id != id[0] || nand_dev_id != id[1]) {
4704 chip->select_chip(mtd, -1);
4707 chip->select_chip(mtd, -1);
4712 pr_info("%d chips detected\n", i);
4715 /* Store the number of chips and calc total size for mtd */
4717 mtd->size = i * chip->chipsize;
4721 EXPORT_SYMBOL(nand_scan_ident);
4724 * nand_check_ecc_caps - check the sanity of preset ECC settings
4725 * @chip: nand chip info structure
4726 * @caps: ECC caps info structure
4727 * @oobavail: OOB size that the ECC engine can use
4729 * When ECC step size and strength are already set, check if they are supported
4730 * by the controller and the calculated ECC bytes fit within the chip's OOB.
4731 * On success, the calculated ECC bytes is set.
4733 int nand_check_ecc_caps(struct nand_chip *chip,
4734 const struct nand_ecc_caps *caps, int oobavail)
4736 struct mtd_info *mtd = nand_to_mtd(chip);
4737 const struct nand_ecc_step_info *stepinfo;
4738 int preset_step = chip->ecc.size;
4739 int preset_strength = chip->ecc.strength;
4740 int nsteps, ecc_bytes;
4743 if (WARN_ON(oobavail < 0))
4746 if (!preset_step || !preset_strength)
4749 nsteps = mtd->writesize / preset_step;
4751 for (i = 0; i < caps->nstepinfos; i++) {
4752 stepinfo = &caps->stepinfos[i];
4754 if (stepinfo->stepsize != preset_step)
4757 for (j = 0; j < stepinfo->nstrengths; j++) {
4758 if (stepinfo->strengths[j] != preset_strength)
4761 ecc_bytes = caps->calc_ecc_bytes(preset_step,
4763 if (WARN_ON_ONCE(ecc_bytes < 0))
4766 if (ecc_bytes * nsteps > oobavail) {
4767 pr_err("ECC (step, strength) = (%d, %d) does not fit in OOB",
4768 preset_step, preset_strength);
4772 chip->ecc.bytes = ecc_bytes;
4778 pr_err("ECC (step, strength) = (%d, %d) not supported on this controller",
4779 preset_step, preset_strength);
4783 EXPORT_SYMBOL_GPL(nand_check_ecc_caps);
4786 * nand_match_ecc_req - meet the chip's requirement with least ECC bytes
4787 * @chip: nand chip info structure
4788 * @caps: ECC engine caps info structure
4789 * @oobavail: OOB size that the ECC engine can use
4791 * If a chip's ECC requirement is provided, try to meet it with the least
4792 * number of ECC bytes (i.e. with the largest number of OOB-free bytes).
4793 * On success, the chosen ECC settings are set.
4795 int nand_match_ecc_req(struct nand_chip *chip,
4796 const struct nand_ecc_caps *caps, int oobavail)
4798 struct mtd_info *mtd = nand_to_mtd(chip);
4799 const struct nand_ecc_step_info *stepinfo;
4800 int req_step = chip->ecc_step_ds;
4801 int req_strength = chip->ecc_strength_ds;
4802 int req_corr, step_size, strength, nsteps, ecc_bytes, ecc_bytes_total;
4803 int best_step, best_strength, best_ecc_bytes;
4804 int best_ecc_bytes_total = INT_MAX;
4807 if (WARN_ON(oobavail < 0))
4810 /* No information provided by the NAND chip */
4811 if (!req_step || !req_strength)
4814 /* number of correctable bits the chip requires in a page */
4815 req_corr = mtd->writesize / req_step * req_strength;
4817 for (i = 0; i < caps->nstepinfos; i++) {
4818 stepinfo = &caps->stepinfos[i];
4819 step_size = stepinfo->stepsize;
4821 for (j = 0; j < stepinfo->nstrengths; j++) {
4822 strength = stepinfo->strengths[j];
4825 * If both step size and strength are smaller than the
4826 * chip's requirement, it is not easy to compare the
4827 * resulted reliability.
4829 if (step_size < req_step && strength < req_strength)
4832 if (mtd->writesize % step_size)
4835 nsteps = mtd->writesize / step_size;
4837 ecc_bytes = caps->calc_ecc_bytes(step_size, strength);
4838 if (WARN_ON_ONCE(ecc_bytes < 0))
4840 ecc_bytes_total = ecc_bytes * nsteps;
4842 if (ecc_bytes_total > oobavail ||
4843 strength * nsteps < req_corr)
4847 * We assume the best is to meet the chip's requrement
4848 * with the least number of ECC bytes.
4850 if (ecc_bytes_total < best_ecc_bytes_total) {
4851 best_ecc_bytes_total = ecc_bytes_total;
4852 best_step = step_size;
4853 best_strength = strength;
4854 best_ecc_bytes = ecc_bytes;
4859 if (best_ecc_bytes_total == INT_MAX)
4862 chip->ecc.size = best_step;
4863 chip->ecc.strength = best_strength;
4864 chip->ecc.bytes = best_ecc_bytes;
4868 EXPORT_SYMBOL_GPL(nand_match_ecc_req);
4871 * nand_maximize_ecc - choose the max ECC strength available
4872 * @chip: nand chip info structure
4873 * @caps: ECC engine caps info structure
4874 * @oobavail: OOB size that the ECC engine can use
4876 * Choose the max ECC strength that is supported on the controller, and can fit
4877 * within the chip's OOB. On success, the chosen ECC settings are set.
4879 int nand_maximize_ecc(struct nand_chip *chip,
4880 const struct nand_ecc_caps *caps, int oobavail)
4882 struct mtd_info *mtd = nand_to_mtd(chip);
4883 const struct nand_ecc_step_info *stepinfo;
4884 int step_size, strength, nsteps, ecc_bytes, corr;
4887 int best_strength, best_ecc_bytes;
4890 if (WARN_ON(oobavail < 0))
4893 for (i = 0; i < caps->nstepinfos; i++) {
4894 stepinfo = &caps->stepinfos[i];
4895 step_size = stepinfo->stepsize;
4897 /* If chip->ecc.size is already set, respect it */
4898 if (chip->ecc.size && step_size != chip->ecc.size)
4901 for (j = 0; j < stepinfo->nstrengths; j++) {
4902 strength = stepinfo->strengths[j];
4904 if (mtd->writesize % step_size)
4907 nsteps = mtd->writesize / step_size;
4909 ecc_bytes = caps->calc_ecc_bytes(step_size, strength);
4910 if (WARN_ON_ONCE(ecc_bytes < 0))
4913 if (ecc_bytes * nsteps > oobavail)
4916 corr = strength * nsteps;
4919 * If the number of correctable bits is the same,
4920 * bigger step_size has more reliability.
4922 if (corr > best_corr ||
4923 (corr == best_corr && step_size > best_step)) {
4925 best_step = step_size;
4926 best_strength = strength;
4927 best_ecc_bytes = ecc_bytes;
4935 chip->ecc.size = best_step;
4936 chip->ecc.strength = best_strength;
4937 chip->ecc.bytes = best_ecc_bytes;
4941 EXPORT_SYMBOL_GPL(nand_maximize_ecc);
4944 * Check if the chip configuration meet the datasheet requirements.
4946 * If our configuration corrects A bits per B bytes and the minimum
4947 * required correction level is X bits per Y bytes, then we must ensure
4948 * both of the following are true:
4950 * (1) A / B >= X / Y
4953 * Requirement (1) ensures we can correct for the required bitflip density.
4954 * Requirement (2) ensures we can correct even when all bitflips are clumped
4955 * in the same sector.
4957 static bool nand_ecc_strength_good(struct mtd_info *mtd)
4959 struct nand_chip *chip = mtd_to_nand(mtd);
4960 struct nand_ecc_ctrl *ecc = &chip->ecc;
4963 if (ecc->size == 0 || chip->ecc_step_ds == 0)
4964 /* Not enough information */
4968 * We get the number of corrected bits per page to compare
4969 * the correction density.
4971 corr = (mtd->writesize * ecc->strength) / ecc->size;
4972 ds_corr = (mtd->writesize * chip->ecc_strength_ds) / chip->ecc_step_ds;
4974 return corr >= ds_corr && ecc->strength >= chip->ecc_strength_ds;
4977 static bool invalid_ecc_page_accessors(struct nand_chip *chip)
4979 struct nand_ecc_ctrl *ecc = &chip->ecc;
4981 if (nand_standard_page_accessors(ecc))
4985 * NAND_ECC_CUSTOM_PAGE_ACCESS flag is set, make sure the NAND
4986 * controller driver implements all the page accessors because
4987 * default helpers are not suitable when the core does not
4988 * send the READ0/PAGEPROG commands.
4990 return (!ecc->read_page || !ecc->write_page ||
4991 !ecc->read_page_raw || !ecc->write_page_raw ||
4992 (NAND_HAS_SUBPAGE_READ(chip) && !ecc->read_subpage) ||
4993 (NAND_HAS_SUBPAGE_WRITE(chip) && !ecc->write_subpage &&
4994 ecc->hwctl && ecc->calculate));
4998 * nand_scan_tail - [NAND Interface] Scan for the NAND device
4999 * @mtd: MTD device structure
5001 * This is the second phase of the normal nand_scan() function. It fills out
5002 * all the uninitialized function pointers with the defaults and scans for a
5003 * bad block table if appropriate.
5005 int nand_scan_tail(struct mtd_info *mtd)
5008 struct nand_chip *chip = mtd_to_nand(mtd);
5009 struct nand_ecc_ctrl *ecc = &chip->ecc;
5010 struct nand_buffers *nbuf;
5012 /* New bad blocks should be marked in OOB, flash-based BBT, or both */
5013 BUG_ON((chip->bbt_options & NAND_BBT_NO_OOB_BBM) &&
5014 !(chip->bbt_options & NAND_BBT_USE_FLASH));
5016 if (invalid_ecc_page_accessors(chip)) {
5017 pr_err("Invalid ECC page accessors setup\n");
5021 if (!(chip->options & NAND_OWN_BUFFERS)) {
5022 nbuf = kzalloc(sizeof(struct nand_buffers), GFP_KERNEL);
5023 chip->buffers = nbuf;
5029 /* Set the internal oob buffer location, just after the page data */
5030 chip->oob_poi = chip->buffers->databuf + mtd->writesize;
5033 * If no default placement scheme is given, select an appropriate one.
5035 if (!ecc->layout && (ecc->mode != NAND_ECC_SOFT_BCH)) {
5036 switch (mtd->oobsize) {
5037 #ifdef CONFIG_SYS_NAND_DRIVER_ECC_LAYOUT
5039 ecc->layout = &nand_oob_8;
5042 ecc->layout = &nand_oob_16;
5045 ecc->layout = &nand_oob_64;
5048 ecc->layout = &nand_oob_128;
5052 pr_warn("No oob scheme defined for oobsize %d\n",
5058 if (!chip->write_page)
5059 chip->write_page = nand_write_page;
5062 * Check ECC mode, default to software if 3byte/512byte hardware ECC is
5063 * selected and we have 256 byte pagesize fallback to software ECC
5066 switch (ecc->mode) {
5067 case NAND_ECC_HW_OOB_FIRST:
5068 /* Similar to NAND_ECC_HW, but a separate read_page handle */
5069 if (!ecc->calculate || !ecc->correct || !ecc->hwctl) {
5070 pr_warn("No ECC functions supplied; hardware ECC not possible\n");
5073 if (!ecc->read_page)
5074 ecc->read_page = nand_read_page_hwecc_oob_first;
5077 /* Use standard hwecc read page function? */
5078 if (!ecc->read_page)
5079 ecc->read_page = nand_read_page_hwecc;
5080 if (!ecc->write_page)
5081 ecc->write_page = nand_write_page_hwecc;
5082 if (!ecc->read_page_raw)
5083 ecc->read_page_raw = nand_read_page_raw;
5084 if (!ecc->write_page_raw)
5085 ecc->write_page_raw = nand_write_page_raw;
5087 ecc->read_oob = nand_read_oob_std;
5088 if (!ecc->write_oob)
5089 ecc->write_oob = nand_write_oob_std;
5090 if (!ecc->read_subpage)
5091 ecc->read_subpage = nand_read_subpage;
5092 if (!ecc->write_subpage && ecc->hwctl && ecc->calculate)
5093 ecc->write_subpage = nand_write_subpage_hwecc;
5095 case NAND_ECC_HW_SYNDROME:
5096 if ((!ecc->calculate || !ecc->correct || !ecc->hwctl) &&
5098 ecc->read_page == nand_read_page_hwecc ||
5100 ecc->write_page == nand_write_page_hwecc)) {
5101 pr_warn("No ECC functions supplied; hardware ECC not possible\n");
5104 /* Use standard syndrome read/write page function? */
5105 if (!ecc->read_page)
5106 ecc->read_page = nand_read_page_syndrome;
5107 if (!ecc->write_page)
5108 ecc->write_page = nand_write_page_syndrome;
5109 if (!ecc->read_page_raw)
5110 ecc->read_page_raw = nand_read_page_raw_syndrome;
5111 if (!ecc->write_page_raw)
5112 ecc->write_page_raw = nand_write_page_raw_syndrome;
5114 ecc->read_oob = nand_read_oob_syndrome;
5115 if (!ecc->write_oob)
5116 ecc->write_oob = nand_write_oob_syndrome;
5118 if (mtd->writesize >= ecc->size) {
5119 if (!ecc->strength) {
5120 pr_warn("Driver must set ecc.strength when using hardware ECC\n");
5125 pr_warn("%d byte HW ECC not possible on %d byte page size, fallback to SW ECC\n",
5126 ecc->size, mtd->writesize);
5127 ecc->mode = NAND_ECC_SOFT;
5130 ecc->calculate = nand_calculate_ecc;
5131 ecc->correct = nand_correct_data;
5132 ecc->read_page = nand_read_page_swecc;
5133 ecc->read_subpage = nand_read_subpage;
5134 ecc->write_page = nand_write_page_swecc;
5135 ecc->read_page_raw = nand_read_page_raw;
5136 ecc->write_page_raw = nand_write_page_raw;
5137 ecc->read_oob = nand_read_oob_std;
5138 ecc->write_oob = nand_write_oob_std;
5145 case NAND_ECC_SOFT_BCH:
5146 if (!mtd_nand_has_bch()) {
5147 pr_warn("CONFIG_MTD_NAND_ECC_BCH not enabled\n");
5150 ecc->calculate = nand_bch_calculate_ecc;
5151 ecc->correct = nand_bch_correct_data;
5152 ecc->read_page = nand_read_page_swecc;
5153 ecc->read_subpage = nand_read_subpage;
5154 ecc->write_page = nand_write_page_swecc;
5155 ecc->read_page_raw = nand_read_page_raw;
5156 ecc->write_page_raw = nand_write_page_raw;
5157 ecc->read_oob = nand_read_oob_std;
5158 ecc->write_oob = nand_write_oob_std;
5160 * Board driver should supply ecc.size and ecc.strength values
5161 * to select how many bits are correctable. Otherwise, default
5162 * to 4 bits for large page devices.
5164 if (!ecc->size && (mtd->oobsize >= 64)) {
5169 /* See nand_bch_init() for details. */
5171 ecc->priv = nand_bch_init(mtd);
5173 pr_warn("BCH ECC initialization failed!\n");
5179 pr_warn("NAND_ECC_NONE selected by board driver. This is not recommended!\n");
5180 ecc->read_page = nand_read_page_raw;
5181 ecc->write_page = nand_write_page_raw;
5182 ecc->read_oob = nand_read_oob_std;
5183 ecc->read_page_raw = nand_read_page_raw;
5184 ecc->write_page_raw = nand_write_page_raw;
5185 ecc->write_oob = nand_write_oob_std;
5186 ecc->size = mtd->writesize;
5192 pr_warn("Invalid NAND_ECC_MODE %d\n", ecc->mode);
5196 /* For many systems, the standard OOB write also works for raw */
5197 if (!ecc->read_oob_raw)
5198 ecc->read_oob_raw = ecc->read_oob;
5199 if (!ecc->write_oob_raw)
5200 ecc->write_oob_raw = ecc->write_oob;
5203 * The number of bytes available for a client to place data into
5204 * the out of band area.
5208 for (i = 0; ecc->layout->oobfree[i].length; i++)
5209 mtd->oobavail += ecc->layout->oobfree[i].length;
5212 /* ECC sanity check: warn if it's too weak */
5213 if (!nand_ecc_strength_good(mtd))
5214 pr_warn("WARNING: %s: the ECC used on your system is too weak compared to the one required by the NAND chip\n",
5218 * Set the number of read / write steps for one page depending on ECC
5221 ecc->steps = mtd->writesize / ecc->size;
5222 if (ecc->steps * ecc->size != mtd->writesize) {
5223 pr_warn("Invalid ECC parameters\n");
5226 ecc->total = ecc->steps * ecc->bytes;
5228 /* Allow subpage writes up to ecc.steps. Not possible for MLC flash */
5229 if (!(chip->options & NAND_NO_SUBPAGE_WRITE) && nand_is_slc(chip)) {
5230 switch (ecc->steps) {
5232 mtd->subpage_sft = 1;
5237 mtd->subpage_sft = 2;
5241 chip->subpagesize = mtd->writesize >> mtd->subpage_sft;
5243 /* Initialize state */
5244 chip->state = FL_READY;
5246 /* Invalidate the pagebuffer reference */
5249 /* Large page NAND with SOFT_ECC should support subpage reads */
5250 switch (ecc->mode) {
5252 case NAND_ECC_SOFT_BCH:
5253 if (chip->page_shift > 9)
5254 chip->options |= NAND_SUBPAGE_READ;
5261 /* Fill in remaining MTD driver data */
5262 mtd->type = nand_is_slc(chip) ? MTD_NANDFLASH : MTD_MLCNANDFLASH;
5263 mtd->flags = (chip->options & NAND_ROM) ? MTD_CAP_ROM :
5265 mtd->_erase = nand_erase;
5266 mtd->_panic_write = panic_nand_write;
5267 mtd->_read_oob = nand_read_oob;
5268 mtd->_write_oob = nand_write_oob;
5269 mtd->_sync = nand_sync;
5271 mtd->_unlock = NULL;
5272 mtd->_block_isreserved = nand_block_isreserved;
5273 mtd->_block_isbad = nand_block_isbad;
5274 mtd->_block_markbad = nand_block_markbad;
5275 mtd->writebufsize = mtd->writesize;
5277 /* propagate ecc info to mtd_info */
5278 mtd->ecclayout = ecc->layout;
5279 mtd->ecc_strength = ecc->strength;
5280 mtd->ecc_step_size = ecc->size;
5282 * Initialize bitflip_threshold to its default prior scan_bbt() call.
5283 * scan_bbt() might invoke mtd_read(), thus bitflip_threshold must be
5286 if (!mtd->bitflip_threshold)
5287 mtd->bitflip_threshold = DIV_ROUND_UP(mtd->ecc_strength * 3, 4);
5291 EXPORT_SYMBOL(nand_scan_tail);
5294 * nand_scan - [NAND Interface] Scan for the NAND device
5295 * @mtd: MTD device structure
5296 * @maxchips: number of chips to scan for
5298 * This fills out all the uninitialized function pointers with the defaults.
5299 * The flash ID is read and the mtd/chip structures are filled with the
5300 * appropriate values.
5302 int nand_scan(struct mtd_info *mtd, int maxchips)
5306 ret = nand_scan_ident(mtd, maxchips, NULL);
5308 ret = nand_scan_tail(mtd);
5311 EXPORT_SYMBOL(nand_scan);
5313 MODULE_LICENSE("GPL");
5316 MODULE_DESCRIPTION("Generic NAND flash driver code");