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
9 * Copyright (C) 2000 Steven J. Hill (sjhill@realitydiluted.com)
10 * 2002-2006 Thomas Gleixner (tglx@linutronix.de)
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)
38 #include <dm/devres.h>
39 #include <linux/bitops.h>
40 #include <linux/bug.h>
41 #include <linux/delay.h>
42 #include <linux/err.h>
43 #include <linux/compat.h>
44 #include <linux/mtd/mtd.h>
45 #include <linux/mtd/rawnand.h>
46 #include <linux/mtd/nand_ecc.h>
47 #include <linux/mtd/nand_bch.h>
48 #ifdef CONFIG_MTD_PARTITIONS
49 #include <linux/mtd/partitions.h>
52 #include <linux/errno.h>
54 /* Define default oob placement schemes for large and small page devices */
55 #ifndef CONFIG_SYS_NAND_DRIVER_ECC_LAYOUT
56 static struct nand_ecclayout nand_oob_8 = {
66 static struct nand_ecclayout nand_oob_16 = {
68 .eccpos = {0, 1, 2, 3, 6, 7},
74 static struct nand_ecclayout nand_oob_64 = {
77 40, 41, 42, 43, 44, 45, 46, 47,
78 48, 49, 50, 51, 52, 53, 54, 55,
79 56, 57, 58, 59, 60, 61, 62, 63},
85 static struct nand_ecclayout nand_oob_128 = {
88 80, 81, 82, 83, 84, 85, 86, 87,
89 88, 89, 90, 91, 92, 93, 94, 95,
90 96, 97, 98, 99, 100, 101, 102, 103,
91 104, 105, 106, 107, 108, 109, 110, 111,
92 112, 113, 114, 115, 116, 117, 118, 119,
93 120, 121, 122, 123, 124, 125, 126, 127},
100 static int nand_get_device(struct mtd_info *mtd, int new_state);
102 static int nand_do_write_oob(struct mtd_info *mtd, loff_t to,
103 struct mtd_oob_ops *ops);
106 * For devices which display every fart in the system on a separate LED. Is
107 * compiled away when LED support is disabled.
109 DEFINE_LED_TRIGGER(nand_led_trigger);
111 static int check_offs_len(struct mtd_info *mtd,
112 loff_t ofs, uint64_t len)
114 struct nand_chip *chip = mtd_to_nand(mtd);
117 /* Start address must align on block boundary */
118 if (ofs & ((1ULL << chip->phys_erase_shift) - 1)) {
119 pr_debug("%s: unaligned address\n", __func__);
123 /* Length must align on block boundary */
124 if (len & ((1ULL << chip->phys_erase_shift) - 1)) {
125 pr_debug("%s: length not block aligned\n", __func__);
133 * nand_release_device - [GENERIC] release chip
134 * @mtd: MTD device structure
136 * Release chip lock and wake up anyone waiting on the device.
138 static void nand_release_device(struct mtd_info *mtd)
140 struct nand_chip *chip = mtd_to_nand(mtd);
142 /* De-select the NAND device */
143 chip->select_chip(mtd, -1);
147 * nand_read_byte - [DEFAULT] read one byte from the chip
148 * @mtd: MTD device structure
150 * Default read function for 8bit buswidth
152 uint8_t nand_read_byte(struct mtd_info *mtd)
154 struct nand_chip *chip = mtd_to_nand(mtd);
155 return readb(chip->IO_ADDR_R);
159 * nand_read_byte16 - [DEFAULT] read one byte endianness aware from the chip
160 * @mtd: MTD device structure
162 * Default read function for 16bit buswidth with endianness conversion.
165 static uint8_t nand_read_byte16(struct mtd_info *mtd)
167 struct nand_chip *chip = mtd_to_nand(mtd);
168 return (uint8_t) cpu_to_le16(readw(chip->IO_ADDR_R));
172 * nand_read_word - [DEFAULT] read one word from the chip
173 * @mtd: MTD device structure
175 * Default read function for 16bit buswidth without endianness conversion.
177 static u16 nand_read_word(struct mtd_info *mtd)
179 struct nand_chip *chip = mtd_to_nand(mtd);
180 return readw(chip->IO_ADDR_R);
184 * nand_select_chip - [DEFAULT] control CE line
185 * @mtd: MTD device structure
186 * @chipnr: chipnumber to select, -1 for deselect
188 * Default select function for 1 chip devices.
190 static void nand_select_chip(struct mtd_info *mtd, int chipnr)
192 struct nand_chip *chip = mtd_to_nand(mtd);
196 chip->cmd_ctrl(mtd, NAND_CMD_NONE, 0 | NAND_CTRL_CHANGE);
207 * nand_write_byte - [DEFAULT] write single byte to chip
208 * @mtd: MTD device structure
209 * @byte: value to write
211 * Default function to write a byte to I/O[7:0]
213 static void nand_write_byte(struct mtd_info *mtd, uint8_t byte)
215 struct nand_chip *chip = mtd_to_nand(mtd);
217 chip->write_buf(mtd, &byte, 1);
221 * nand_write_byte16 - [DEFAULT] write single byte to a chip with width 16
222 * @mtd: MTD device structure
223 * @byte: value to write
225 * Default function to write a byte to I/O[7:0] on a 16-bit wide chip.
227 static void nand_write_byte16(struct mtd_info *mtd, uint8_t byte)
229 struct nand_chip *chip = mtd_to_nand(mtd);
230 uint16_t word = byte;
233 * It's not entirely clear what should happen to I/O[15:8] when writing
234 * a byte. The ONFi spec (Revision 3.1; 2012-09-19, Section 2.16) reads:
236 * When the host supports a 16-bit bus width, only data is
237 * transferred at the 16-bit width. All address and command line
238 * transfers shall use only the lower 8-bits of the data bus. During
239 * command transfers, the host may place any value on the upper
240 * 8-bits of the data bus. During address transfers, the host shall
241 * set the upper 8-bits of the data bus to 00h.
243 * One user of the write_byte callback is nand_onfi_set_features. The
244 * four parameters are specified to be written to I/O[7:0], but this is
245 * neither an address nor a command transfer. Let's assume a 0 on the
246 * upper I/O lines is OK.
248 chip->write_buf(mtd, (uint8_t *)&word, 2);
251 static void iowrite8_rep(void *addr, const uint8_t *buf, int len)
255 for (i = 0; i < len; i++)
256 writeb(buf[i], addr);
258 static void ioread8_rep(void *addr, uint8_t *buf, int len)
262 for (i = 0; i < len; i++)
263 buf[i] = readb(addr);
266 static void ioread16_rep(void *addr, void *buf, int len)
269 u16 *p = (u16 *) buf;
271 for (i = 0; i < len; i++)
275 static void iowrite16_rep(void *addr, void *buf, int len)
278 u16 *p = (u16 *) buf;
280 for (i = 0; i < len; i++)
285 * nand_write_buf - [DEFAULT] write buffer to chip
286 * @mtd: MTD device structure
288 * @len: number of bytes to write
290 * Default write function for 8bit buswidth.
292 void nand_write_buf(struct mtd_info *mtd, const uint8_t *buf, int len)
294 struct nand_chip *chip = mtd_to_nand(mtd);
296 iowrite8_rep(chip->IO_ADDR_W, buf, len);
300 * nand_read_buf - [DEFAULT] read chip data into buffer
301 * @mtd: MTD device structure
302 * @buf: buffer to store date
303 * @len: number of bytes to read
305 * Default read function for 8bit buswidth.
307 void nand_read_buf(struct mtd_info *mtd, uint8_t *buf, int len)
309 struct nand_chip *chip = mtd_to_nand(mtd);
311 ioread8_rep(chip->IO_ADDR_R, buf, len);
315 * nand_write_buf16 - [DEFAULT] write buffer to chip
316 * @mtd: MTD device structure
318 * @len: number of bytes to write
320 * Default write function for 16bit buswidth.
322 void nand_write_buf16(struct mtd_info *mtd, const uint8_t *buf, int len)
324 struct nand_chip *chip = mtd_to_nand(mtd);
325 u16 *p = (u16 *) buf;
327 iowrite16_rep(chip->IO_ADDR_W, p, len >> 1);
331 * nand_read_buf16 - [DEFAULT] read chip data into buffer
332 * @mtd: MTD device structure
333 * @buf: buffer to store date
334 * @len: number of bytes to read
336 * Default read function for 16bit buswidth.
338 void nand_read_buf16(struct mtd_info *mtd, uint8_t *buf, int len)
340 struct nand_chip *chip = mtd_to_nand(mtd);
341 u16 *p = (u16 *) buf;
343 ioread16_rep(chip->IO_ADDR_R, p, len >> 1);
347 * nand_block_bad - [DEFAULT] Read bad block marker from the chip
348 * @mtd: MTD device structure
349 * @ofs: offset from device start
351 * Check, if the block is bad.
353 static int nand_block_bad(struct mtd_info *mtd, loff_t ofs)
355 int page, res = 0, i = 0;
356 struct nand_chip *chip = mtd_to_nand(mtd);
359 if (chip->bbt_options & NAND_BBT_SCANLASTPAGE)
360 ofs += mtd->erasesize - mtd->writesize;
362 page = (int)(ofs >> chip->page_shift) & chip->pagemask;
365 if (chip->options & NAND_BUSWIDTH_16) {
366 chip->cmdfunc(mtd, NAND_CMD_READOOB,
367 chip->badblockpos & 0xFE, page);
368 bad = cpu_to_le16(chip->read_word(mtd));
369 if (chip->badblockpos & 0x1)
374 chip->cmdfunc(mtd, NAND_CMD_READOOB, chip->badblockpos,
376 bad = chip->read_byte(mtd);
379 if (likely(chip->badblockbits == 8))
382 res = hweight8(bad) < chip->badblockbits;
383 ofs += mtd->writesize;
384 page = (int)(ofs >> chip->page_shift) & chip->pagemask;
386 } while (!res && i < 2 && (chip->bbt_options & NAND_BBT_SCAN2NDPAGE));
392 * nand_default_block_markbad - [DEFAULT] mark a block bad via bad block marker
393 * @mtd: MTD device structure
394 * @ofs: offset from device start
396 * This is the default implementation, which can be overridden by a hardware
397 * specific driver. It provides the details for writing a bad block marker to a
400 static int nand_default_block_markbad(struct mtd_info *mtd, loff_t ofs)
402 struct nand_chip *chip = mtd_to_nand(mtd);
403 struct mtd_oob_ops ops;
404 uint8_t buf[2] = { 0, 0 };
405 int ret = 0, res, i = 0;
407 memset(&ops, 0, sizeof(ops));
409 ops.ooboffs = chip->badblockpos;
410 if (chip->options & NAND_BUSWIDTH_16) {
411 ops.ooboffs &= ~0x01;
412 ops.len = ops.ooblen = 2;
414 ops.len = ops.ooblen = 1;
416 ops.mode = MTD_OPS_PLACE_OOB;
418 /* Write to first/last page(s) if necessary */
419 if (chip->bbt_options & NAND_BBT_SCANLASTPAGE)
420 ofs += mtd->erasesize - mtd->writesize;
422 res = nand_do_write_oob(mtd, ofs, &ops);
427 ofs += mtd->writesize;
428 } while ((chip->bbt_options & NAND_BBT_SCAN2NDPAGE) && i < 2);
434 * nand_block_markbad_lowlevel - mark a block bad
435 * @mtd: MTD device structure
436 * @ofs: offset from device start
438 * This function performs the generic NAND bad block marking steps (i.e., bad
439 * block table(s) and/or marker(s)). We only allow the hardware driver to
440 * specify how to write bad block markers to OOB (chip->block_markbad).
442 * We try operations in the following order:
443 * (1) erase the affected block, to allow OOB marker to be written cleanly
444 * (2) write bad block marker to OOB area of affected block (unless flag
445 * NAND_BBT_NO_OOB_BBM is present)
447 * Note that we retain the first error encountered in (2) or (3), finish the
448 * procedures, and dump the error in the end.
450 static int nand_block_markbad_lowlevel(struct mtd_info *mtd, loff_t ofs)
452 struct nand_chip *chip = mtd_to_nand(mtd);
455 if (!(chip->bbt_options & NAND_BBT_NO_OOB_BBM)) {
456 struct erase_info einfo;
458 /* Attempt erase before marking OOB */
459 memset(&einfo, 0, sizeof(einfo));
462 einfo.len = 1ULL << chip->phys_erase_shift;
463 nand_erase_nand(mtd, &einfo, 0);
465 /* Write bad block marker to OOB */
466 nand_get_device(mtd, FL_WRITING);
467 ret = chip->block_markbad(mtd, ofs);
468 nand_release_device(mtd);
471 /* Mark block bad in BBT */
473 res = nand_markbad_bbt(mtd, ofs);
479 mtd->ecc_stats.badblocks++;
485 * nand_check_wp - [GENERIC] check if the chip is write protected
486 * @mtd: MTD device structure
488 * Check, if the device is write protected. The function expects, that the
489 * device is already selected.
491 static int nand_check_wp(struct mtd_info *mtd)
493 struct nand_chip *chip = mtd_to_nand(mtd);
497 /* Broken xD cards report WP despite being writable */
498 if (chip->options & NAND_BROKEN_XD)
501 /* Check the WP bit */
502 ret = nand_status_op(chip, &status);
506 return status & NAND_STATUS_WP ? 0 : 1;
510 * nand_block_isreserved - [GENERIC] Check if a block is marked reserved.
511 * @mtd: MTD device structure
512 * @ofs: offset from device start
514 * Check if the block is marked as reserved.
516 static int nand_block_isreserved(struct mtd_info *mtd, loff_t ofs)
518 struct nand_chip *chip = mtd_to_nand(mtd);
522 /* Return info from the table */
523 return nand_isreserved_bbt(mtd, ofs);
527 * nand_block_checkbad - [GENERIC] Check if a block is marked bad
528 * @mtd: MTD device structure
529 * @ofs: offset from device start
530 * @allowbbt: 1, if its allowed to access the bbt area
532 * Check, if the block is bad. Either by reading the bad block table or
533 * calling of the scan function.
535 static int nand_block_checkbad(struct mtd_info *mtd, loff_t ofs, int allowbbt)
537 struct nand_chip *chip = mtd_to_nand(mtd);
539 if (!(chip->options & NAND_SKIP_BBTSCAN) &&
540 !(chip->options & NAND_BBT_SCANNED)) {
541 chip->options |= NAND_BBT_SCANNED;
546 return chip->block_bad(mtd, ofs);
548 /* Return info from the table */
549 return nand_isbad_bbt(mtd, ofs, allowbbt);
553 * nand_wait_ready - [GENERIC] Wait for the ready pin after commands.
554 * @mtd: MTD device structure
556 * Wait for the ready pin after a command, and warn if a timeout occurs.
558 void nand_wait_ready(struct mtd_info *mtd)
560 struct nand_chip *chip = mtd_to_nand(mtd);
561 u32 timeo = (CONFIG_SYS_HZ * 400) / 1000;
564 time_start = get_timer(0);
565 /* Wait until command is processed or timeout occurs */
566 while (get_timer(time_start) < timeo) {
568 if (chip->dev_ready(mtd))
572 if (!chip->dev_ready(mtd))
573 pr_warn("timeout while waiting for chip to become ready\n");
575 EXPORT_SYMBOL_GPL(nand_wait_ready);
578 * nand_wait_status_ready - [GENERIC] Wait for the ready status after commands.
579 * @mtd: MTD device structure
580 * @timeo: Timeout in ms
582 * Wait for status ready (i.e. command done) or timeout.
584 static void nand_wait_status_ready(struct mtd_info *mtd, unsigned long timeo)
586 register struct nand_chip *chip = mtd_to_nand(mtd);
590 timeo = (CONFIG_SYS_HZ * timeo) / 1000;
591 time_start = get_timer(0);
592 while (get_timer(time_start) < timeo) {
595 ret = nand_read_data_op(chip, &status, sizeof(status), true);
599 if (status & NAND_STATUS_READY)
606 * nand_command - [DEFAULT] Send command to NAND device
607 * @mtd: MTD device structure
608 * @command: the command to be sent
609 * @column: the column address for this command, -1 if none
610 * @page_addr: the page address for this command, -1 if none
612 * Send command to NAND device. This function is used for small page devices
613 * (512 Bytes per page).
615 static void nand_command(struct mtd_info *mtd, unsigned int command,
616 int column, int page_addr)
618 register struct nand_chip *chip = mtd_to_nand(mtd);
619 int ctrl = NAND_CTRL_CLE | NAND_CTRL_CHANGE;
621 /* Write out the command to the device */
622 if (command == NAND_CMD_SEQIN) {
625 if (column >= mtd->writesize) {
627 column -= mtd->writesize;
628 readcmd = NAND_CMD_READOOB;
629 } else if (column < 256) {
630 /* First 256 bytes --> READ0 */
631 readcmd = NAND_CMD_READ0;
634 readcmd = NAND_CMD_READ1;
636 chip->cmd_ctrl(mtd, readcmd, ctrl);
637 ctrl &= ~NAND_CTRL_CHANGE;
639 chip->cmd_ctrl(mtd, command, ctrl);
641 /* Address cycle, when necessary */
642 ctrl = NAND_CTRL_ALE | NAND_CTRL_CHANGE;
643 /* Serially input address */
645 /* Adjust columns for 16 bit buswidth */
646 if (chip->options & NAND_BUSWIDTH_16 &&
647 !nand_opcode_8bits(command))
649 chip->cmd_ctrl(mtd, column, ctrl);
650 ctrl &= ~NAND_CTRL_CHANGE;
652 if (page_addr != -1) {
653 chip->cmd_ctrl(mtd, page_addr, ctrl);
654 ctrl &= ~NAND_CTRL_CHANGE;
655 chip->cmd_ctrl(mtd, page_addr >> 8, ctrl);
656 if (chip->options & NAND_ROW_ADDR_3)
657 chip->cmd_ctrl(mtd, page_addr >> 16, ctrl);
659 chip->cmd_ctrl(mtd, NAND_CMD_NONE, NAND_NCE | NAND_CTRL_CHANGE);
662 * Program and erase have their own busy handlers status and sequential
667 case NAND_CMD_PAGEPROG:
668 case NAND_CMD_ERASE1:
669 case NAND_CMD_ERASE2:
671 case NAND_CMD_STATUS:
672 case NAND_CMD_READID:
673 case NAND_CMD_SET_FEATURES:
679 udelay(chip->chip_delay);
680 chip->cmd_ctrl(mtd, NAND_CMD_STATUS,
681 NAND_CTRL_CLE | NAND_CTRL_CHANGE);
683 NAND_CMD_NONE, NAND_NCE | NAND_CTRL_CHANGE);
684 /* EZ-NAND can take upto 250ms as per ONFi v4.0 */
685 nand_wait_status_ready(mtd, 250);
688 /* This applies to read commands */
691 * If we don't have access to the busy pin, we apply the given
694 if (!chip->dev_ready) {
695 udelay(chip->chip_delay);
700 * Apply this short delay always to ensure that we do wait tWB in
701 * any case on any machine.
705 nand_wait_ready(mtd);
709 * nand_command_lp - [DEFAULT] Send command to NAND large page device
710 * @mtd: MTD device structure
711 * @command: the command to be sent
712 * @column: the column address for this command, -1 if none
713 * @page_addr: the page address for this command, -1 if none
715 * Send command to NAND device. This is the version for the new large page
716 * devices. We don't have the separate regions as we have in the small page
717 * devices. We must emulate NAND_CMD_READOOB to keep the code compatible.
719 static void nand_command_lp(struct mtd_info *mtd, unsigned int command,
720 int column, int page_addr)
722 register struct nand_chip *chip = mtd_to_nand(mtd);
724 /* Emulate NAND_CMD_READOOB */
725 if (command == NAND_CMD_READOOB) {
726 column += mtd->writesize;
727 command = NAND_CMD_READ0;
730 /* Command latch cycle */
731 chip->cmd_ctrl(mtd, command, NAND_NCE | NAND_CLE | NAND_CTRL_CHANGE);
733 if (column != -1 || page_addr != -1) {
734 int ctrl = NAND_CTRL_CHANGE | NAND_NCE | NAND_ALE;
736 /* Serially input address */
738 /* Adjust columns for 16 bit buswidth */
739 if (chip->options & NAND_BUSWIDTH_16 &&
740 !nand_opcode_8bits(command))
742 chip->cmd_ctrl(mtd, column, ctrl);
743 ctrl &= ~NAND_CTRL_CHANGE;
744 chip->cmd_ctrl(mtd, column >> 8, ctrl);
746 if (page_addr != -1) {
747 chip->cmd_ctrl(mtd, page_addr, ctrl);
748 chip->cmd_ctrl(mtd, page_addr >> 8,
749 NAND_NCE | NAND_ALE);
750 if (chip->options & NAND_ROW_ADDR_3)
751 chip->cmd_ctrl(mtd, page_addr >> 16,
752 NAND_NCE | NAND_ALE);
755 chip->cmd_ctrl(mtd, NAND_CMD_NONE, NAND_NCE | NAND_CTRL_CHANGE);
758 * Program and erase have their own busy handlers status, sequential
759 * in and status need no delay.
763 case NAND_CMD_CACHEDPROG:
764 case NAND_CMD_PAGEPROG:
765 case NAND_CMD_ERASE1:
766 case NAND_CMD_ERASE2:
769 case NAND_CMD_STATUS:
770 case NAND_CMD_READID:
771 case NAND_CMD_SET_FEATURES:
777 udelay(chip->chip_delay);
778 chip->cmd_ctrl(mtd, NAND_CMD_STATUS,
779 NAND_NCE | NAND_CLE | NAND_CTRL_CHANGE);
780 chip->cmd_ctrl(mtd, NAND_CMD_NONE,
781 NAND_NCE | NAND_CTRL_CHANGE);
782 /* EZ-NAND can take upto 250ms as per ONFi v4.0 */
783 nand_wait_status_ready(mtd, 250);
786 case NAND_CMD_RNDOUT:
787 /* No ready / busy check necessary */
788 chip->cmd_ctrl(mtd, NAND_CMD_RNDOUTSTART,
789 NAND_NCE | NAND_CLE | NAND_CTRL_CHANGE);
790 chip->cmd_ctrl(mtd, NAND_CMD_NONE,
791 NAND_NCE | NAND_CTRL_CHANGE);
795 chip->cmd_ctrl(mtd, NAND_CMD_READSTART,
796 NAND_NCE | NAND_CLE | NAND_CTRL_CHANGE);
797 chip->cmd_ctrl(mtd, NAND_CMD_NONE,
798 NAND_NCE | NAND_CTRL_CHANGE);
800 /* This applies to read commands */
803 * If we don't have access to the busy pin, we apply the given
806 if (!chip->dev_ready) {
807 udelay(chip->chip_delay);
813 * Apply this short delay always to ensure that we do wait tWB in
814 * any case on any machine.
818 nand_wait_ready(mtd);
822 * panic_nand_get_device - [GENERIC] Get chip for selected access
823 * @chip: the nand chip descriptor
824 * @mtd: MTD device structure
825 * @new_state: the state which is requested
827 * Used when in panic, no locks are taken.
829 static void panic_nand_get_device(struct nand_chip *chip,
830 struct mtd_info *mtd, int new_state)
832 /* Hardware controller shared among independent devices */
833 chip->controller->active = chip;
834 chip->state = new_state;
838 * nand_get_device - [GENERIC] Get chip for selected access
839 * @mtd: MTD device structure
840 * @new_state: the state which is requested
842 * Get the device and lock it for exclusive access
845 nand_get_device(struct mtd_info *mtd, int new_state)
847 struct nand_chip *chip = mtd_to_nand(mtd);
848 chip->state = new_state;
853 * panic_nand_wait - [GENERIC] wait until the command is done
854 * @mtd: MTD device structure
855 * @chip: NAND chip structure
858 * Wait for command done. This is a helper function for nand_wait used when
859 * we are in interrupt context. May happen when in panic and trying to write
860 * an oops through mtdoops.
862 static void panic_nand_wait(struct mtd_info *mtd, struct nand_chip *chip,
866 for (i = 0; i < timeo; i++) {
867 if (chip->dev_ready) {
868 if (chip->dev_ready(mtd))
874 ret = nand_read_data_op(chip, &status, sizeof(status),
879 if (status & NAND_STATUS_READY)
887 * nand_wait - [DEFAULT] wait until the command is done
888 * @mtd: MTD device structure
889 * @chip: NAND chip structure
891 * Wait for command done. This applies to erase and program only.
893 static int nand_wait(struct mtd_info *mtd, struct nand_chip *chip)
895 unsigned long timeo = 400;
899 led_trigger_event(nand_led_trigger, LED_FULL);
902 * Apply this short delay always to ensure that we do wait tWB in any
903 * case on any machine.
907 ret = nand_status_op(chip, NULL);
911 u32 timer = (CONFIG_SYS_HZ * timeo) / 1000;
914 time_start = get_timer(0);
915 while (get_timer(time_start) < timer) {
916 if (chip->dev_ready) {
917 if (chip->dev_ready(mtd))
920 ret = nand_read_data_op(chip, &status,
921 sizeof(status), true);
925 if (status & NAND_STATUS_READY)
929 led_trigger_event(nand_led_trigger, LED_OFF);
931 ret = nand_read_data_op(chip, &status, sizeof(status), true);
935 /* This can happen if in case of timeout or buggy dev_ready */
936 WARN_ON(!(status & NAND_STATUS_READY));
941 * nand_reset_data_interface - Reset data interface and timings
942 * @chip: The NAND chip
943 * @chipnr: Internal die id
945 * Reset the Data interface and timings to ONFI mode 0.
947 * Returns 0 for success or negative error code otherwise.
949 static int nand_reset_data_interface(struct nand_chip *chip, int chipnr)
951 struct mtd_info *mtd = nand_to_mtd(chip);
952 const struct nand_data_interface *conf;
955 if (!chip->setup_data_interface)
959 * The ONFI specification says:
961 * To transition from NV-DDR or NV-DDR2 to the SDR data
962 * interface, the host shall use the Reset (FFh) command
963 * using SDR timing mode 0. A device in any timing mode is
964 * required to recognize Reset (FFh) command issued in SDR
968 * Configure the data interface in SDR mode and set the
969 * timings to timing mode 0.
972 conf = nand_get_default_data_interface();
973 ret = chip->setup_data_interface(mtd, chipnr, conf);
975 pr_err("Failed to configure data interface to SDR timing mode 0\n");
981 * nand_setup_data_interface - Setup the best data interface and timings
982 * @chip: The NAND chip
983 * @chipnr: Internal die id
985 * Find and configure the best data interface and NAND timings supported by
986 * the chip and the driver.
987 * First tries to retrieve supported timing modes from ONFI information,
988 * and if the NAND chip does not support ONFI, relies on the
989 * ->onfi_timing_mode_default specified in the nand_ids table.
991 * Returns 0 for success or negative error code otherwise.
993 static int nand_setup_data_interface(struct nand_chip *chip, int chipnr)
995 struct mtd_info *mtd = nand_to_mtd(chip);
998 if (!chip->setup_data_interface || !chip->data_interface)
1002 * Ensure the timing mode has been changed on the chip side
1003 * before changing timings on the controller side.
1005 if (chip->onfi_version) {
1006 u8 tmode_param[ONFI_SUBFEATURE_PARAM_LEN] = {
1007 chip->onfi_timing_mode_default,
1010 ret = chip->onfi_set_features(mtd, chip,
1011 ONFI_FEATURE_ADDR_TIMING_MODE,
1017 ret = chip->setup_data_interface(mtd, chipnr, chip->data_interface);
1023 * nand_init_data_interface - find the best data interface and timings
1024 * @chip: The NAND chip
1026 * Find the best data interface and NAND timings supported by the chip
1028 * First tries to retrieve supported timing modes from ONFI information,
1029 * and if the NAND chip does not support ONFI, relies on the
1030 * ->onfi_timing_mode_default specified in the nand_ids table. After this
1031 * function nand_chip->data_interface is initialized with the best timing mode
1034 * Returns 0 for success or negative error code otherwise.
1036 static int nand_init_data_interface(struct nand_chip *chip)
1038 struct mtd_info *mtd = nand_to_mtd(chip);
1039 int modes, mode, ret;
1041 if (!chip->setup_data_interface)
1045 * First try to identify the best timings from ONFI parameters and
1046 * if the NAND does not support ONFI, fallback to the default ONFI
1049 modes = onfi_get_async_timing_mode(chip);
1050 if (modes == ONFI_TIMING_MODE_UNKNOWN) {
1051 if (!chip->onfi_timing_mode_default)
1054 modes = GENMASK(chip->onfi_timing_mode_default, 0);
1057 chip->data_interface = kzalloc(sizeof(*chip->data_interface),
1059 if (!chip->data_interface)
1062 for (mode = fls(modes) - 1; mode >= 0; mode--) {
1063 ret = onfi_init_data_interface(chip, chip->data_interface,
1064 NAND_SDR_IFACE, mode);
1068 /* Pass -1 to only */
1069 ret = chip->setup_data_interface(mtd,
1070 NAND_DATA_IFACE_CHECK_ONLY,
1071 chip->data_interface);
1073 chip->onfi_timing_mode_default = mode;
1081 static void __maybe_unused nand_release_data_interface(struct nand_chip *chip)
1083 kfree(chip->data_interface);
1087 * nand_read_page_op - Do a READ PAGE operation
1088 * @chip: The NAND chip
1089 * @page: page to read
1090 * @offset_in_page: offset within the page
1091 * @buf: buffer used to store the data
1092 * @len: length of the buffer
1094 * This function issues a READ PAGE operation.
1095 * This function does not select/unselect the CS line.
1097 * Returns 0 on success, a negative error code otherwise.
1099 int nand_read_page_op(struct nand_chip *chip, unsigned int page,
1100 unsigned int offset_in_page, void *buf, unsigned int len)
1102 struct mtd_info *mtd = nand_to_mtd(chip);
1107 if (offset_in_page + len > mtd->writesize + mtd->oobsize)
1110 chip->cmdfunc(mtd, NAND_CMD_READ0, offset_in_page, page);
1112 chip->read_buf(mtd, buf, len);
1116 EXPORT_SYMBOL_GPL(nand_read_page_op);
1119 * nand_read_param_page_op - Do a READ PARAMETER PAGE operation
1120 * @chip: The NAND chip
1121 * @page: parameter page to read
1122 * @buf: buffer used to store the data
1123 * @len: length of the buffer
1125 * This function issues a READ PARAMETER PAGE operation.
1126 * This function does not select/unselect the CS line.
1128 * Returns 0 on success, a negative error code otherwise.
1130 static int nand_read_param_page_op(struct nand_chip *chip, u8 page, void *buf,
1133 struct mtd_info *mtd = nand_to_mtd(chip);
1140 chip->cmdfunc(mtd, NAND_CMD_PARAM, page, -1);
1141 for (i = 0; i < len; i++)
1142 p[i] = chip->read_byte(mtd);
1148 * nand_change_read_column_op - Do a CHANGE READ COLUMN operation
1149 * @chip: The NAND chip
1150 * @offset_in_page: offset within the page
1151 * @buf: buffer used to store the data
1152 * @len: length of the buffer
1153 * @force_8bit: force 8-bit bus access
1155 * This function issues a CHANGE READ COLUMN operation.
1156 * This function does not select/unselect the CS line.
1158 * Returns 0 on success, a negative error code otherwise.
1160 int nand_change_read_column_op(struct nand_chip *chip,
1161 unsigned int offset_in_page, void *buf,
1162 unsigned int len, bool force_8bit)
1164 struct mtd_info *mtd = nand_to_mtd(chip);
1169 if (offset_in_page + len > mtd->writesize + mtd->oobsize)
1172 chip->cmdfunc(mtd, NAND_CMD_RNDOUT, offset_in_page, -1);
1174 chip->read_buf(mtd, buf, len);
1178 EXPORT_SYMBOL_GPL(nand_change_read_column_op);
1181 * nand_read_oob_op - Do a READ OOB operation
1182 * @chip: The NAND chip
1183 * @page: page to read
1184 * @offset_in_oob: offset within the OOB area
1185 * @buf: buffer used to store the data
1186 * @len: length of the buffer
1188 * This function issues a READ OOB operation.
1189 * This function does not select/unselect the CS line.
1191 * Returns 0 on success, a negative error code otherwise.
1193 int nand_read_oob_op(struct nand_chip *chip, unsigned int page,
1194 unsigned int offset_in_oob, void *buf, unsigned int len)
1196 struct mtd_info *mtd = nand_to_mtd(chip);
1201 if (offset_in_oob + len > mtd->oobsize)
1204 chip->cmdfunc(mtd, NAND_CMD_READOOB, offset_in_oob, page);
1206 chip->read_buf(mtd, buf, len);
1210 EXPORT_SYMBOL_GPL(nand_read_oob_op);
1213 * nand_prog_page_begin_op - starts a PROG PAGE operation
1214 * @chip: The NAND chip
1215 * @page: page to write
1216 * @offset_in_page: offset within the page
1217 * @buf: buffer containing the data to write to the page
1218 * @len: length of the buffer
1220 * This function issues the first half of a PROG PAGE operation.
1221 * This function does not select/unselect the CS line.
1223 * Returns 0 on success, a negative error code otherwise.
1225 int nand_prog_page_begin_op(struct nand_chip *chip, unsigned int page,
1226 unsigned int offset_in_page, const void *buf,
1229 struct mtd_info *mtd = nand_to_mtd(chip);
1234 if (offset_in_page + len > mtd->writesize + mtd->oobsize)
1237 chip->cmdfunc(mtd, NAND_CMD_SEQIN, offset_in_page, page);
1240 chip->write_buf(mtd, buf, len);
1244 EXPORT_SYMBOL_GPL(nand_prog_page_begin_op);
1247 * nand_prog_page_end_op - ends a PROG PAGE operation
1248 * @chip: The NAND chip
1250 * This function issues the second half of a PROG PAGE operation.
1251 * This function does not select/unselect the CS line.
1253 * Returns 0 on success, a negative error code otherwise.
1255 int nand_prog_page_end_op(struct nand_chip *chip)
1257 struct mtd_info *mtd = nand_to_mtd(chip);
1260 chip->cmdfunc(mtd, NAND_CMD_PAGEPROG, -1, -1);
1262 status = chip->waitfunc(mtd, chip);
1263 if (status & NAND_STATUS_FAIL)
1268 EXPORT_SYMBOL_GPL(nand_prog_page_end_op);
1271 * nand_prog_page_op - Do a full PROG PAGE operation
1272 * @chip: The NAND chip
1273 * @page: page to write
1274 * @offset_in_page: offset within the page
1275 * @buf: buffer containing the data to write to the page
1276 * @len: length of the buffer
1278 * This function issues a full PROG PAGE operation.
1279 * This function does not select/unselect the CS line.
1281 * Returns 0 on success, a negative error code otherwise.
1283 int nand_prog_page_op(struct nand_chip *chip, unsigned int page,
1284 unsigned int offset_in_page, const void *buf,
1287 struct mtd_info *mtd = nand_to_mtd(chip);
1293 if (offset_in_page + len > mtd->writesize + mtd->oobsize)
1296 chip->cmdfunc(mtd, NAND_CMD_SEQIN, offset_in_page, page);
1297 chip->write_buf(mtd, buf, len);
1298 chip->cmdfunc(mtd, NAND_CMD_PAGEPROG, -1, -1);
1300 status = chip->waitfunc(mtd, chip);
1301 if (status & NAND_STATUS_FAIL)
1306 EXPORT_SYMBOL_GPL(nand_prog_page_op);
1309 * nand_change_write_column_op - Do a CHANGE WRITE COLUMN operation
1310 * @chip: The NAND chip
1311 * @offset_in_page: offset within the page
1312 * @buf: buffer containing the data to send to the NAND
1313 * @len: length of the buffer
1314 * @force_8bit: force 8-bit bus access
1316 * This function issues a CHANGE WRITE COLUMN operation.
1317 * This function does not select/unselect the CS line.
1319 * Returns 0 on success, a negative error code otherwise.
1321 int nand_change_write_column_op(struct nand_chip *chip,
1322 unsigned int offset_in_page,
1323 const void *buf, unsigned int len,
1326 struct mtd_info *mtd = nand_to_mtd(chip);
1331 if (offset_in_page + len > mtd->writesize + mtd->oobsize)
1334 chip->cmdfunc(mtd, NAND_CMD_RNDIN, offset_in_page, -1);
1336 chip->write_buf(mtd, buf, len);
1340 EXPORT_SYMBOL_GPL(nand_change_write_column_op);
1343 * nand_readid_op - Do a READID operation
1344 * @chip: The NAND chip
1345 * @addr: address cycle to pass after the READID command
1346 * @buf: buffer used to store the ID
1347 * @len: length of the buffer
1349 * This function sends a READID command and reads back the ID returned by the
1351 * This function does not select/unselect the CS line.
1353 * Returns 0 on success, a negative error code otherwise.
1355 int nand_readid_op(struct nand_chip *chip, u8 addr, void *buf,
1358 struct mtd_info *mtd = nand_to_mtd(chip);
1365 chip->cmdfunc(mtd, NAND_CMD_READID, addr, -1);
1367 for (i = 0; i < len; i++)
1368 id[i] = chip->read_byte(mtd);
1372 EXPORT_SYMBOL_GPL(nand_readid_op);
1375 * nand_status_op - Do a STATUS operation
1376 * @chip: The NAND chip
1377 * @status: out variable to store the NAND status
1379 * This function sends a STATUS command and reads back the status returned by
1381 * This function does not select/unselect the CS line.
1383 * Returns 0 on success, a negative error code otherwise.
1385 int nand_status_op(struct nand_chip *chip, u8 *status)
1387 struct mtd_info *mtd = nand_to_mtd(chip);
1389 chip->cmdfunc(mtd, NAND_CMD_STATUS, -1, -1);
1391 *status = chip->read_byte(mtd);
1395 EXPORT_SYMBOL_GPL(nand_status_op);
1398 * nand_exit_status_op - Exit a STATUS operation
1399 * @chip: The NAND chip
1401 * This function sends a READ0 command to cancel the effect of the STATUS
1402 * command to avoid reading only the status until a new read command is sent.
1404 * This function does not select/unselect the CS line.
1406 * Returns 0 on success, a negative error code otherwise.
1408 int nand_exit_status_op(struct nand_chip *chip)
1410 struct mtd_info *mtd = nand_to_mtd(chip);
1412 chip->cmdfunc(mtd, NAND_CMD_READ0, -1, -1);
1416 EXPORT_SYMBOL_GPL(nand_exit_status_op);
1419 * nand_erase_op - Do an erase operation
1420 * @chip: The NAND chip
1421 * @eraseblock: block to erase
1423 * This function sends an ERASE command and waits for the NAND to be ready
1425 * This function does not select/unselect the CS line.
1427 * Returns 0 on success, a negative error code otherwise.
1429 int nand_erase_op(struct nand_chip *chip, unsigned int eraseblock)
1431 struct mtd_info *mtd = nand_to_mtd(chip);
1432 unsigned int page = eraseblock <<
1433 (chip->phys_erase_shift - chip->page_shift);
1436 chip->cmdfunc(mtd, NAND_CMD_ERASE1, -1, page);
1437 chip->cmdfunc(mtd, NAND_CMD_ERASE2, -1, -1);
1439 status = chip->waitfunc(mtd, chip);
1443 if (status & NAND_STATUS_FAIL)
1448 EXPORT_SYMBOL_GPL(nand_erase_op);
1451 * nand_set_features_op - Do a SET FEATURES operation
1452 * @chip: The NAND chip
1453 * @feature: feature id
1454 * @data: 4 bytes of data
1456 * This function sends a SET FEATURES command and waits for the NAND to be
1457 * ready before returning.
1458 * This function does not select/unselect the CS line.
1460 * Returns 0 on success, a negative error code otherwise.
1462 static int nand_set_features_op(struct nand_chip *chip, u8 feature,
1465 struct mtd_info *mtd = nand_to_mtd(chip);
1466 const u8 *params = data;
1469 chip->cmdfunc(mtd, NAND_CMD_SET_FEATURES, feature, -1);
1470 for (i = 0; i < ONFI_SUBFEATURE_PARAM_LEN; ++i)
1471 chip->write_byte(mtd, params[i]);
1473 status = chip->waitfunc(mtd, chip);
1474 if (status & NAND_STATUS_FAIL)
1481 * nand_get_features_op - Do a GET FEATURES operation
1482 * @chip: The NAND chip
1483 * @feature: feature id
1484 * @data: 4 bytes of data
1486 * This function sends a GET FEATURES command and waits for the NAND to be
1487 * ready before returning.
1488 * This function does not select/unselect the CS line.
1490 * Returns 0 on success, a negative error code otherwise.
1492 static int nand_get_features_op(struct nand_chip *chip, u8 feature,
1495 struct mtd_info *mtd = nand_to_mtd(chip);
1499 chip->cmdfunc(mtd, NAND_CMD_GET_FEATURES, feature, -1);
1500 for (i = 0; i < ONFI_SUBFEATURE_PARAM_LEN; ++i)
1501 params[i] = chip->read_byte(mtd);
1507 * nand_reset_op - Do a reset operation
1508 * @chip: The NAND chip
1510 * This function sends a RESET command and waits for the NAND to be ready
1512 * This function does not select/unselect the CS line.
1514 * Returns 0 on success, a negative error code otherwise.
1516 int nand_reset_op(struct nand_chip *chip)
1518 struct mtd_info *mtd = nand_to_mtd(chip);
1520 chip->cmdfunc(mtd, NAND_CMD_RESET, -1, -1);
1524 EXPORT_SYMBOL_GPL(nand_reset_op);
1527 * nand_read_data_op - Read data from the NAND
1528 * @chip: The NAND chip
1529 * @buf: buffer used to store the data
1530 * @len: length of the buffer
1531 * @force_8bit: force 8-bit bus access
1533 * This function does a raw data read on the bus. Usually used after launching
1534 * another NAND operation like nand_read_page_op().
1535 * This function does not select/unselect the CS line.
1537 * Returns 0 on success, a negative error code otherwise.
1539 int nand_read_data_op(struct nand_chip *chip, void *buf, unsigned int len,
1542 struct mtd_info *mtd = nand_to_mtd(chip);
1551 for (i = 0; i < len; i++)
1552 p[i] = chip->read_byte(mtd);
1554 chip->read_buf(mtd, buf, len);
1559 EXPORT_SYMBOL_GPL(nand_read_data_op);
1562 * nand_write_data_op - Write data from the NAND
1563 * @chip: The NAND chip
1564 * @buf: buffer containing the data to send on the bus
1565 * @len: length of the buffer
1566 * @force_8bit: force 8-bit bus access
1568 * This function does a raw data write on the bus. Usually used after launching
1569 * another NAND operation like nand_write_page_begin_op().
1570 * This function does not select/unselect the CS line.
1572 * Returns 0 on success, a negative error code otherwise.
1574 int nand_write_data_op(struct nand_chip *chip, const void *buf,
1575 unsigned int len, bool force_8bit)
1577 struct mtd_info *mtd = nand_to_mtd(chip);
1586 for (i = 0; i < len; i++)
1587 chip->write_byte(mtd, p[i]);
1589 chip->write_buf(mtd, buf, len);
1594 EXPORT_SYMBOL_GPL(nand_write_data_op);
1597 * nand_reset - Reset and initialize a NAND device
1598 * @chip: The NAND chip
1599 * @chipnr: Internal die id
1601 * Returns 0 for success or negative error code otherwise
1603 int nand_reset(struct nand_chip *chip, int chipnr)
1605 struct mtd_info *mtd = nand_to_mtd(chip);
1608 ret = nand_reset_data_interface(chip, chipnr);
1613 * The CS line has to be released before we can apply the new NAND
1614 * interface settings, hence this weird ->select_chip() dance.
1616 chip->select_chip(mtd, chipnr);
1617 ret = nand_reset_op(chip);
1618 chip->select_chip(mtd, -1);
1622 chip->select_chip(mtd, chipnr);
1623 ret = nand_setup_data_interface(chip, chipnr);
1624 chip->select_chip(mtd, -1);
1632 * nand_check_erased_buf - check if a buffer contains (almost) only 0xff data
1633 * @buf: buffer to test
1634 * @len: buffer length
1635 * @bitflips_threshold: maximum number of bitflips
1637 * Check if a buffer contains only 0xff, which means the underlying region
1638 * has been erased and is ready to be programmed.
1639 * The bitflips_threshold specify the maximum number of bitflips before
1640 * considering the region is not erased.
1641 * Note: The logic of this function has been extracted from the memweight
1642 * implementation, except that nand_check_erased_buf function exit before
1643 * testing the whole buffer if the number of bitflips exceed the
1644 * bitflips_threshold value.
1646 * Returns a positive number of bitflips less than or equal to
1647 * bitflips_threshold, or -ERROR_CODE for bitflips in excess of the
1650 static int nand_check_erased_buf(void *buf, int len, int bitflips_threshold)
1652 const unsigned char *bitmap = buf;
1656 for (; len && ((uintptr_t)bitmap) % sizeof(long);
1658 weight = hweight8(*bitmap);
1659 bitflips += BITS_PER_BYTE - weight;
1660 if (unlikely(bitflips > bitflips_threshold))
1664 for (; len >= 4; len -= 4, bitmap += 4) {
1665 weight = hweight32(*((u32 *)bitmap));
1666 bitflips += 32 - weight;
1667 if (unlikely(bitflips > bitflips_threshold))
1671 for (; len > 0; len--, bitmap++) {
1672 weight = hweight8(*bitmap);
1673 bitflips += BITS_PER_BYTE - weight;
1674 if (unlikely(bitflips > bitflips_threshold))
1682 * nand_check_erased_ecc_chunk - check if an ECC chunk contains (almost) only
1684 * @data: data buffer to test
1685 * @datalen: data length
1687 * @ecclen: ECC length
1688 * @extraoob: extra OOB buffer
1689 * @extraooblen: extra OOB length
1690 * @bitflips_threshold: maximum number of bitflips
1692 * Check if a data buffer and its associated ECC and OOB data contains only
1693 * 0xff pattern, which means the underlying region has been erased and is
1694 * ready to be programmed.
1695 * The bitflips_threshold specify the maximum number of bitflips before
1696 * considering the region as not erased.
1699 * 1/ ECC algorithms are working on pre-defined block sizes which are usually
1700 * different from the NAND page size. When fixing bitflips, ECC engines will
1701 * report the number of errors per chunk, and the NAND core infrastructure
1702 * expect you to return the maximum number of bitflips for the whole page.
1703 * This is why you should always use this function on a single chunk and
1704 * not on the whole page. After checking each chunk you should update your
1705 * max_bitflips value accordingly.
1706 * 2/ When checking for bitflips in erased pages you should not only check
1707 * the payload data but also their associated ECC data, because a user might
1708 * have programmed almost all bits to 1 but a few. In this case, we
1709 * shouldn't consider the chunk as erased, and checking ECC bytes prevent
1711 * 3/ The extraoob argument is optional, and should be used if some of your OOB
1712 * data are protected by the ECC engine.
1713 * It could also be used if you support subpages and want to attach some
1714 * extra OOB data to an ECC chunk.
1716 * Returns a positive number of bitflips less than or equal to
1717 * bitflips_threshold, or -ERROR_CODE for bitflips in excess of the
1718 * threshold. In case of success, the passed buffers are filled with 0xff.
1720 int nand_check_erased_ecc_chunk(void *data, int datalen,
1721 void *ecc, int ecclen,
1722 void *extraoob, int extraooblen,
1723 int bitflips_threshold)
1725 int data_bitflips = 0, ecc_bitflips = 0, extraoob_bitflips = 0;
1727 data_bitflips = nand_check_erased_buf(data, datalen,
1728 bitflips_threshold);
1729 if (data_bitflips < 0)
1730 return data_bitflips;
1732 bitflips_threshold -= data_bitflips;
1734 ecc_bitflips = nand_check_erased_buf(ecc, ecclen, bitflips_threshold);
1735 if (ecc_bitflips < 0)
1736 return ecc_bitflips;
1738 bitflips_threshold -= ecc_bitflips;
1740 extraoob_bitflips = nand_check_erased_buf(extraoob, extraooblen,
1741 bitflips_threshold);
1742 if (extraoob_bitflips < 0)
1743 return extraoob_bitflips;
1746 memset(data, 0xff, datalen);
1749 memset(ecc, 0xff, ecclen);
1751 if (extraoob_bitflips)
1752 memset(extraoob, 0xff, extraooblen);
1754 return data_bitflips + ecc_bitflips + extraoob_bitflips;
1756 EXPORT_SYMBOL(nand_check_erased_ecc_chunk);
1759 * nand_read_page_raw - [INTERN] read raw page data without ecc
1760 * @mtd: mtd info structure
1761 * @chip: nand chip info structure
1762 * @buf: buffer to store read data
1763 * @oob_required: caller requires OOB data read to chip->oob_poi
1764 * @page: page number to read
1766 * Not for syndrome calculating ECC controllers, which use a special oob layout.
1768 static int nand_read_page_raw(struct mtd_info *mtd, struct nand_chip *chip,
1769 uint8_t *buf, int oob_required, int page)
1773 ret = nand_read_data_op(chip, buf, mtd->writesize, false);
1778 ret = nand_read_data_op(chip, chip->oob_poi, mtd->oobsize,
1788 * nand_read_page_raw_syndrome - [INTERN] read raw page data without ecc
1789 * @mtd: mtd info structure
1790 * @chip: nand chip info structure
1791 * @buf: buffer to store read data
1792 * @oob_required: caller requires OOB data read to chip->oob_poi
1793 * @page: page number to read
1795 * We need a special oob layout and handling even when OOB isn't used.
1797 static int nand_read_page_raw_syndrome(struct mtd_info *mtd,
1798 struct nand_chip *chip, uint8_t *buf,
1799 int oob_required, int page)
1801 int eccsize = chip->ecc.size;
1802 int eccbytes = chip->ecc.bytes;
1803 uint8_t *oob = chip->oob_poi;
1804 int steps, size, ret;
1806 for (steps = chip->ecc.steps; steps > 0; steps--) {
1807 ret = nand_read_data_op(chip, buf, eccsize, false);
1813 if (chip->ecc.prepad) {
1814 ret = nand_read_data_op(chip, oob, chip->ecc.prepad,
1819 oob += chip->ecc.prepad;
1822 ret = nand_read_data_op(chip, oob, eccbytes, false);
1828 if (chip->ecc.postpad) {
1829 ret = nand_read_data_op(chip, oob, chip->ecc.postpad,
1834 oob += chip->ecc.postpad;
1838 size = mtd->oobsize - (oob - chip->oob_poi);
1840 ret = nand_read_data_op(chip, oob, size, false);
1849 * nand_read_page_swecc - [REPLACEABLE] software ECC based page read function
1850 * @mtd: mtd info structure
1851 * @chip: nand chip info structure
1852 * @buf: buffer to store read data
1853 * @oob_required: caller requires OOB data read to chip->oob_poi
1854 * @page: page number to read
1856 static int nand_read_page_swecc(struct mtd_info *mtd, struct nand_chip *chip,
1857 uint8_t *buf, int oob_required, int page)
1859 int i, eccsize = chip->ecc.size;
1860 int eccbytes = chip->ecc.bytes;
1861 int eccsteps = chip->ecc.steps;
1863 uint8_t *ecc_calc = chip->buffers->ecccalc;
1864 uint8_t *ecc_code = chip->buffers->ecccode;
1865 uint32_t *eccpos = chip->ecc.layout->eccpos;
1866 unsigned int max_bitflips = 0;
1868 chip->ecc.read_page_raw(mtd, chip, buf, 1, page);
1870 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize)
1871 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
1873 for (i = 0; i < chip->ecc.total; i++)
1874 ecc_code[i] = chip->oob_poi[eccpos[i]];
1876 eccsteps = chip->ecc.steps;
1879 for (i = 0 ; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
1882 stat = chip->ecc.correct(mtd, p, &ecc_code[i], &ecc_calc[i]);
1884 mtd->ecc_stats.failed++;
1886 mtd->ecc_stats.corrected += stat;
1887 max_bitflips = max_t(unsigned int, max_bitflips, stat);
1890 return max_bitflips;
1894 * nand_read_subpage - [REPLACEABLE] ECC based sub-page read function
1895 * @mtd: mtd info structure
1896 * @chip: nand chip info structure
1897 * @data_offs: offset of requested data within the page
1898 * @readlen: data length
1899 * @bufpoi: buffer to store read data
1900 * @page: page number to read
1902 static int nand_read_subpage(struct mtd_info *mtd, struct nand_chip *chip,
1903 uint32_t data_offs, uint32_t readlen, uint8_t *bufpoi,
1906 int start_step, end_step, num_steps;
1907 uint32_t *eccpos = chip->ecc.layout->eccpos;
1909 int data_col_addr, i, gaps = 0;
1910 int datafrag_len, eccfrag_len, aligned_len, aligned_pos;
1911 int busw = (chip->options & NAND_BUSWIDTH_16) ? 2 : 1;
1913 unsigned int max_bitflips = 0;
1916 /* Column address within the page aligned to ECC size (256bytes) */
1917 start_step = data_offs / chip->ecc.size;
1918 end_step = (data_offs + readlen - 1) / chip->ecc.size;
1919 num_steps = end_step - start_step + 1;
1920 index = start_step * chip->ecc.bytes;
1922 /* Data size aligned to ECC ecc.size */
1923 datafrag_len = num_steps * chip->ecc.size;
1924 eccfrag_len = num_steps * chip->ecc.bytes;
1926 data_col_addr = start_step * chip->ecc.size;
1927 /* If we read not a page aligned data */
1928 if (data_col_addr != 0)
1929 chip->cmdfunc(mtd, NAND_CMD_RNDOUT, data_col_addr, -1);
1931 p = bufpoi + data_col_addr;
1932 ret = nand_read_data_op(chip, p, datafrag_len, false);
1937 for (i = 0; i < eccfrag_len ; i += chip->ecc.bytes, p += chip->ecc.size)
1938 chip->ecc.calculate(mtd, p, &chip->buffers->ecccalc[i]);
1941 * The performance is faster if we position offsets according to
1942 * ecc.pos. Let's make sure that there are no gaps in ECC positions.
1944 for (i = 0; i < eccfrag_len - 1; i++) {
1945 if (eccpos[i + index] + 1 != eccpos[i + index + 1]) {
1951 ret = nand_change_read_column_op(chip, mtd->writesize,
1952 chip->oob_poi, mtd->oobsize,
1958 * Send the command to read the particular ECC bytes take care
1959 * about buswidth alignment in read_buf.
1961 aligned_pos = eccpos[index] & ~(busw - 1);
1962 aligned_len = eccfrag_len;
1963 if (eccpos[index] & (busw - 1))
1965 if (eccpos[index + (num_steps * chip->ecc.bytes)] & (busw - 1))
1968 ret = nand_change_read_column_op(chip,
1969 mtd->writesize + aligned_pos,
1970 &chip->oob_poi[aligned_pos],
1971 aligned_len, false);
1976 for (i = 0; i < eccfrag_len; i++)
1977 chip->buffers->ecccode[i] = chip->oob_poi[eccpos[i + index]];
1979 p = bufpoi + data_col_addr;
1980 for (i = 0; i < eccfrag_len ; i += chip->ecc.bytes, p += chip->ecc.size) {
1983 stat = chip->ecc.correct(mtd, p,
1984 &chip->buffers->ecccode[i], &chip->buffers->ecccalc[i]);
1985 if (stat == -EBADMSG &&
1986 (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
1987 /* check for empty pages with bitflips */
1988 stat = nand_check_erased_ecc_chunk(p, chip->ecc.size,
1989 &chip->buffers->ecccode[i],
1992 chip->ecc.strength);
1996 mtd->ecc_stats.failed++;
1998 mtd->ecc_stats.corrected += stat;
1999 max_bitflips = max_t(unsigned int, max_bitflips, stat);
2002 return max_bitflips;
2006 * nand_read_page_hwecc - [REPLACEABLE] hardware ECC based page read function
2007 * @mtd: mtd info structure
2008 * @chip: nand chip info structure
2009 * @buf: buffer to store read data
2010 * @oob_required: caller requires OOB data read to chip->oob_poi
2011 * @page: page number to read
2013 * Not for syndrome calculating ECC controllers which need a special oob layout.
2015 static int nand_read_page_hwecc(struct mtd_info *mtd, struct nand_chip *chip,
2016 uint8_t *buf, int oob_required, int page)
2018 int i, eccsize = chip->ecc.size;
2019 int eccbytes = chip->ecc.bytes;
2020 int eccsteps = chip->ecc.steps;
2022 uint8_t *ecc_calc = chip->buffers->ecccalc;
2023 uint8_t *ecc_code = chip->buffers->ecccode;
2024 uint32_t *eccpos = chip->ecc.layout->eccpos;
2025 unsigned int max_bitflips = 0;
2028 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
2029 chip->ecc.hwctl(mtd, NAND_ECC_READ);
2031 ret = nand_read_data_op(chip, p, eccsize, false);
2035 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
2038 ret = nand_read_data_op(chip, chip->oob_poi, mtd->oobsize, false);
2042 for (i = 0; i < chip->ecc.total; i++)
2043 ecc_code[i] = chip->oob_poi[eccpos[i]];
2045 eccsteps = chip->ecc.steps;
2048 for (i = 0 ; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
2051 stat = chip->ecc.correct(mtd, p, &ecc_code[i], &ecc_calc[i]);
2052 if (stat == -EBADMSG &&
2053 (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
2054 /* check for empty pages with bitflips */
2055 stat = nand_check_erased_ecc_chunk(p, eccsize,
2056 &ecc_code[i], eccbytes,
2058 chip->ecc.strength);
2062 mtd->ecc_stats.failed++;
2064 mtd->ecc_stats.corrected += stat;
2065 max_bitflips = max_t(unsigned int, max_bitflips, stat);
2068 return max_bitflips;
2072 * nand_read_page_hwecc_oob_first - [REPLACEABLE] hw ecc, read oob first
2073 * @mtd: mtd info structure
2074 * @chip: nand chip info structure
2075 * @buf: buffer to store read data
2076 * @oob_required: caller requires OOB data read to chip->oob_poi
2077 * @page: page number to read
2079 * Hardware ECC for large page chips, require OOB to be read first. For this
2080 * ECC mode, the write_page method is re-used from ECC_HW. These methods
2081 * read/write ECC from the OOB area, unlike the ECC_HW_SYNDROME support with
2082 * multiple ECC steps, follows the "infix ECC" scheme and reads/writes ECC from
2083 * the data area, by overwriting the NAND manufacturer bad block markings.
2085 static int nand_read_page_hwecc_oob_first(struct mtd_info *mtd,
2086 struct nand_chip *chip, uint8_t *buf, int oob_required, int page)
2088 int i, eccsize = chip->ecc.size;
2089 int eccbytes = chip->ecc.bytes;
2090 int eccsteps = chip->ecc.steps;
2092 uint8_t *ecc_code = chip->buffers->ecccode;
2093 uint32_t *eccpos = chip->ecc.layout->eccpos;
2094 uint8_t *ecc_calc = chip->buffers->ecccalc;
2095 unsigned int max_bitflips = 0;
2098 /* Read the OOB area first */
2099 ret = nand_read_oob_op(chip, page, 0, chip->oob_poi, mtd->oobsize);
2103 ret = nand_read_page_op(chip, page, 0, NULL, 0);
2107 for (i = 0; i < chip->ecc.total; i++)
2108 ecc_code[i] = chip->oob_poi[eccpos[i]];
2110 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
2113 chip->ecc.hwctl(mtd, NAND_ECC_READ);
2115 ret = nand_read_data_op(chip, p, eccsize, false);
2119 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
2121 stat = chip->ecc.correct(mtd, p, &ecc_code[i], NULL);
2122 if (stat == -EBADMSG &&
2123 (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
2124 /* check for empty pages with bitflips */
2125 stat = nand_check_erased_ecc_chunk(p, eccsize,
2126 &ecc_code[i], eccbytes,
2128 chip->ecc.strength);
2132 mtd->ecc_stats.failed++;
2134 mtd->ecc_stats.corrected += stat;
2135 max_bitflips = max_t(unsigned int, max_bitflips, stat);
2138 return max_bitflips;
2142 * nand_read_page_syndrome - [REPLACEABLE] hardware ECC syndrome based page read
2143 * @mtd: mtd info structure
2144 * @chip: nand chip info structure
2145 * @buf: buffer to store read data
2146 * @oob_required: caller requires OOB data read to chip->oob_poi
2147 * @page: page number to read
2149 * The hw generator calculates the error syndrome automatically. Therefore we
2150 * need a special oob layout and handling.
2152 static int nand_read_page_syndrome(struct mtd_info *mtd, struct nand_chip *chip,
2153 uint8_t *buf, int oob_required, int page)
2155 int ret, i, eccsize = chip->ecc.size;
2156 int eccbytes = chip->ecc.bytes;
2157 int eccsteps = chip->ecc.steps;
2158 int eccpadbytes = eccbytes + chip->ecc.prepad + chip->ecc.postpad;
2160 uint8_t *oob = chip->oob_poi;
2161 unsigned int max_bitflips = 0;
2163 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
2166 chip->ecc.hwctl(mtd, NAND_ECC_READ);
2168 ret = nand_read_data_op(chip, p, eccsize, false);
2172 if (chip->ecc.prepad) {
2173 ret = nand_read_data_op(chip, oob, chip->ecc.prepad,
2178 oob += chip->ecc.prepad;
2181 chip->ecc.hwctl(mtd, NAND_ECC_READSYN);
2183 ret = nand_read_data_op(chip, oob, eccbytes, false);
2187 stat = chip->ecc.correct(mtd, p, oob, NULL);
2191 if (chip->ecc.postpad) {
2192 ret = nand_read_data_op(chip, oob, chip->ecc.postpad,
2197 oob += chip->ecc.postpad;
2200 if (stat == -EBADMSG &&
2201 (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
2202 /* check for empty pages with bitflips */
2203 stat = nand_check_erased_ecc_chunk(p, chip->ecc.size,
2207 chip->ecc.strength);
2211 mtd->ecc_stats.failed++;
2213 mtd->ecc_stats.corrected += stat;
2214 max_bitflips = max_t(unsigned int, max_bitflips, stat);
2218 /* Calculate remaining oob bytes */
2219 i = mtd->oobsize - (oob - chip->oob_poi);
2221 ret = nand_read_data_op(chip, oob, i, false);
2226 return max_bitflips;
2230 * nand_transfer_oob - [INTERN] Transfer oob to client buffer
2231 * @chip: nand chip structure
2232 * @oob: oob destination address
2233 * @ops: oob ops structure
2234 * @len: size of oob to transfer
2236 static uint8_t *nand_transfer_oob(struct nand_chip *chip, uint8_t *oob,
2237 struct mtd_oob_ops *ops, size_t len)
2239 switch (ops->mode) {
2241 case MTD_OPS_PLACE_OOB:
2243 memcpy(oob, chip->oob_poi + ops->ooboffs, len);
2246 case MTD_OPS_AUTO_OOB: {
2247 struct nand_oobfree *free = chip->ecc.layout->oobfree;
2248 uint32_t boffs = 0, roffs = ops->ooboffs;
2251 for (; free->length && len; free++, len -= bytes) {
2252 /* Read request not from offset 0? */
2253 if (unlikely(roffs)) {
2254 if (roffs >= free->length) {
2255 roffs -= free->length;
2258 boffs = free->offset + roffs;
2259 bytes = min_t(size_t, len,
2260 (free->length - roffs));
2263 bytes = min_t(size_t, len, free->length);
2264 boffs = free->offset;
2266 memcpy(oob, chip->oob_poi + boffs, bytes);
2278 * nand_setup_read_retry - [INTERN] Set the READ RETRY mode
2279 * @mtd: MTD device structure
2280 * @retry_mode: the retry mode to use
2282 * Some vendors supply a special command to shift the Vt threshold, to be used
2283 * when there are too many bitflips in a page (i.e., ECC error). After setting
2284 * a new threshold, the host should retry reading the page.
2286 static int nand_setup_read_retry(struct mtd_info *mtd, int retry_mode)
2288 struct nand_chip *chip = mtd_to_nand(mtd);
2290 pr_debug("setting READ RETRY mode %d\n", retry_mode);
2292 if (retry_mode >= chip->read_retries)
2295 if (!chip->setup_read_retry)
2298 return chip->setup_read_retry(mtd, retry_mode);
2302 * nand_do_read_ops - [INTERN] Read data with ECC
2303 * @mtd: MTD device structure
2304 * @from: offset to read from
2305 * @ops: oob ops structure
2307 * Internal function. Called with chip held.
2309 static int nand_do_read_ops(struct mtd_info *mtd, loff_t from,
2310 struct mtd_oob_ops *ops)
2312 int chipnr, page, realpage, col, bytes, aligned, oob_required;
2313 struct nand_chip *chip = mtd_to_nand(mtd);
2315 uint32_t readlen = ops->len;
2316 uint32_t oobreadlen = ops->ooblen;
2317 uint32_t max_oobsize = mtd_oobavail(mtd, ops);
2319 uint8_t *bufpoi, *oob, *buf;
2321 unsigned int max_bitflips = 0;
2323 bool ecc_fail = false;
2325 chipnr = (int)(from >> chip->chip_shift);
2326 chip->select_chip(mtd, chipnr);
2328 realpage = (int)(from >> chip->page_shift);
2329 page = realpage & chip->pagemask;
2331 col = (int)(from & (mtd->writesize - 1));
2335 oob_required = oob ? 1 : 0;
2338 unsigned int ecc_failures = mtd->ecc_stats.failed;
2341 bytes = min(mtd->writesize - col, readlen);
2342 aligned = (bytes == mtd->writesize);
2346 else if (chip->options & NAND_USE_BOUNCE_BUFFER)
2347 use_bufpoi = !IS_ALIGNED((unsigned long)buf,
2352 /* Is the current page in the buffer? */
2353 if (realpage != chip->pagebuf || oob) {
2354 bufpoi = use_bufpoi ? chip->buffers->databuf : buf;
2356 if (use_bufpoi && aligned)
2357 pr_debug("%s: using read bounce buffer for buf@%p\n",
2361 if (nand_standard_page_accessors(&chip->ecc)) {
2362 ret = nand_read_page_op(chip, page, 0, NULL, 0);
2368 * Now read the page into the buffer. Absent an error,
2369 * the read methods return max bitflips per ecc step.
2371 if (unlikely(ops->mode == MTD_OPS_RAW))
2372 ret = chip->ecc.read_page_raw(mtd, chip, bufpoi,
2375 else if (!aligned && NAND_HAS_SUBPAGE_READ(chip) &&
2377 ret = chip->ecc.read_subpage(mtd, chip,
2381 ret = chip->ecc.read_page(mtd, chip, bufpoi,
2382 oob_required, page);
2385 /* Invalidate page cache */
2390 max_bitflips = max_t(unsigned int, max_bitflips, ret);
2392 /* Transfer not aligned data */
2394 if (!NAND_HAS_SUBPAGE_READ(chip) && !oob &&
2395 !(mtd->ecc_stats.failed - ecc_failures) &&
2396 (ops->mode != MTD_OPS_RAW)) {
2397 chip->pagebuf = realpage;
2398 chip->pagebuf_bitflips = ret;
2400 /* Invalidate page cache */
2403 memcpy(buf, chip->buffers->databuf + col, bytes);
2406 if (unlikely(oob)) {
2407 int toread = min(oobreadlen, max_oobsize);
2410 oob = nand_transfer_oob(chip,
2412 oobreadlen -= toread;
2416 if (chip->options & NAND_NEED_READRDY) {
2417 /* Apply delay or wait for ready/busy pin */
2418 if (!chip->dev_ready)
2419 udelay(chip->chip_delay);
2421 nand_wait_ready(mtd);
2424 if (mtd->ecc_stats.failed - ecc_failures) {
2425 if (retry_mode + 1 < chip->read_retries) {
2427 ret = nand_setup_read_retry(mtd,
2432 /* Reset failures; retry */
2433 mtd->ecc_stats.failed = ecc_failures;
2436 /* No more retry modes; real failure */
2443 memcpy(buf, chip->buffers->databuf + col, bytes);
2445 max_bitflips = max_t(unsigned int, max_bitflips,
2446 chip->pagebuf_bitflips);
2451 /* Reset to retry mode 0 */
2453 ret = nand_setup_read_retry(mtd, 0);
2462 /* For subsequent reads align to page boundary */
2464 /* Increment page address */
2467 page = realpage & chip->pagemask;
2468 /* Check, if we cross a chip boundary */
2471 chip->select_chip(mtd, -1);
2472 chip->select_chip(mtd, chipnr);
2475 chip->select_chip(mtd, -1);
2477 ops->retlen = ops->len - (size_t) readlen;
2479 ops->oobretlen = ops->ooblen - oobreadlen;
2487 return max_bitflips;
2491 * nand_read_oob_std - [REPLACEABLE] the most common OOB data read function
2492 * @mtd: mtd info structure
2493 * @chip: nand chip info structure
2494 * @page: page number to read
2496 static int nand_read_oob_std(struct mtd_info *mtd, struct nand_chip *chip,
2499 return nand_read_oob_op(chip, page, 0, chip->oob_poi, mtd->oobsize);
2503 * nand_read_oob_syndrome - [REPLACEABLE] OOB data read function for HW ECC
2505 * @mtd: mtd info structure
2506 * @chip: nand chip info structure
2507 * @page: page number to read
2509 static int nand_read_oob_syndrome(struct mtd_info *mtd, struct nand_chip *chip,
2512 int length = mtd->oobsize;
2513 int chunk = chip->ecc.bytes + chip->ecc.prepad + chip->ecc.postpad;
2514 int eccsize = chip->ecc.size;
2515 uint8_t *bufpoi = chip->oob_poi;
2516 int i, toread, sndrnd = 0, pos, ret;
2518 ret = nand_read_page_op(chip, page, chip->ecc.size, NULL, 0);
2522 for (i = 0; i < chip->ecc.steps; i++) {
2526 pos = eccsize + i * (eccsize + chunk);
2527 if (mtd->writesize > 512)
2528 ret = nand_change_read_column_op(chip, pos,
2532 ret = nand_read_page_op(chip, page, pos, NULL,
2539 toread = min_t(int, length, chunk);
2541 ret = nand_read_data_op(chip, bufpoi, toread, false);
2549 ret = nand_read_data_op(chip, bufpoi, length, false);
2558 * nand_write_oob_std - [REPLACEABLE] the most common OOB data write function
2559 * @mtd: mtd info structure
2560 * @chip: nand chip info structure
2561 * @page: page number to write
2563 static int nand_write_oob_std(struct mtd_info *mtd, struct nand_chip *chip,
2566 return nand_prog_page_op(chip, page, mtd->writesize, chip->oob_poi,
2571 * nand_write_oob_syndrome - [REPLACEABLE] OOB data write function for HW ECC
2572 * with syndrome - only for large page flash
2573 * @mtd: mtd info structure
2574 * @chip: nand chip info structure
2575 * @page: page number to write
2577 static int nand_write_oob_syndrome(struct mtd_info *mtd,
2578 struct nand_chip *chip, int page)
2580 int chunk = chip->ecc.bytes + chip->ecc.prepad + chip->ecc.postpad;
2581 int eccsize = chip->ecc.size, length = mtd->oobsize;
2582 int ret, i, len, pos, sndcmd = 0, steps = chip->ecc.steps;
2583 const uint8_t *bufpoi = chip->oob_poi;
2586 * data-ecc-data-ecc ... ecc-oob
2588 * data-pad-ecc-pad-data-pad .... ecc-pad-oob
2590 if (!chip->ecc.prepad && !chip->ecc.postpad) {
2591 pos = steps * (eccsize + chunk);
2596 ret = nand_prog_page_begin_op(chip, page, pos, NULL, 0);
2600 for (i = 0; i < steps; i++) {
2602 if (mtd->writesize <= 512) {
2603 uint32_t fill = 0xFFFFFFFF;
2607 int num = min_t(int, len, 4);
2609 ret = nand_write_data_op(chip, &fill,
2617 pos = eccsize + i * (eccsize + chunk);
2618 ret = nand_change_write_column_op(chip, pos,
2626 len = min_t(int, length, chunk);
2628 ret = nand_write_data_op(chip, bufpoi, len, false);
2636 ret = nand_write_data_op(chip, bufpoi, length, false);
2641 return nand_prog_page_end_op(chip);
2645 * nand_do_read_oob - [INTERN] NAND read out-of-band
2646 * @mtd: MTD device structure
2647 * @from: offset to read from
2648 * @ops: oob operations description structure
2650 * NAND read out-of-band data from the spare area.
2652 static int nand_do_read_oob(struct mtd_info *mtd, loff_t from,
2653 struct mtd_oob_ops *ops)
2655 int page, realpage, chipnr;
2656 struct nand_chip *chip = mtd_to_nand(mtd);
2657 struct mtd_ecc_stats stats;
2658 int readlen = ops->ooblen;
2660 uint8_t *buf = ops->oobbuf;
2663 pr_debug("%s: from = 0x%08Lx, len = %i\n",
2664 __func__, (unsigned long long)from, readlen);
2666 stats = mtd->ecc_stats;
2668 len = mtd_oobavail(mtd, ops);
2670 if (unlikely(ops->ooboffs >= len)) {
2671 pr_debug("%s: attempt to start read outside oob\n",
2676 /* Do not allow reads past end of device */
2677 if (unlikely(from >= mtd->size ||
2678 ops->ooboffs + readlen > ((mtd->size >> chip->page_shift) -
2679 (from >> chip->page_shift)) * len)) {
2680 pr_debug("%s: attempt to read beyond end of device\n",
2685 chipnr = (int)(from >> chip->chip_shift);
2686 chip->select_chip(mtd, chipnr);
2688 /* Shift to get page */
2689 realpage = (int)(from >> chip->page_shift);
2690 page = realpage & chip->pagemask;
2695 if (ops->mode == MTD_OPS_RAW)
2696 ret = chip->ecc.read_oob_raw(mtd, chip, page);
2698 ret = chip->ecc.read_oob(mtd, chip, page);
2703 len = min(len, readlen);
2704 buf = nand_transfer_oob(chip, buf, ops, len);
2706 if (chip->options & NAND_NEED_READRDY) {
2707 /* Apply delay or wait for ready/busy pin */
2708 if (!chip->dev_ready)
2709 udelay(chip->chip_delay);
2711 nand_wait_ready(mtd);
2718 /* Increment page address */
2721 page = realpage & chip->pagemask;
2722 /* Check, if we cross a chip boundary */
2725 chip->select_chip(mtd, -1);
2726 chip->select_chip(mtd, chipnr);
2729 chip->select_chip(mtd, -1);
2731 ops->oobretlen = ops->ooblen - readlen;
2736 if (mtd->ecc_stats.failed - stats.failed)
2739 return mtd->ecc_stats.corrected - stats.corrected ? -EUCLEAN : 0;
2743 * nand_read_oob - [MTD Interface] NAND read data and/or out-of-band
2744 * @mtd: MTD device structure
2745 * @from: offset to read from
2746 * @ops: oob operation description structure
2748 * NAND read data and/or out-of-band data.
2750 static int nand_read_oob(struct mtd_info *mtd, loff_t from,
2751 struct mtd_oob_ops *ops)
2753 int ret = -ENOTSUPP;
2757 /* Do not allow reads past end of device */
2758 if (ops->datbuf && (from + ops->len) > mtd->size) {
2759 pr_debug("%s: attempt to read beyond end of device\n",
2764 nand_get_device(mtd, FL_READING);
2766 switch (ops->mode) {
2767 case MTD_OPS_PLACE_OOB:
2768 case MTD_OPS_AUTO_OOB:
2777 ret = nand_do_read_oob(mtd, from, ops);
2779 ret = nand_do_read_ops(mtd, from, ops);
2782 nand_release_device(mtd);
2788 * nand_write_page_raw - [INTERN] raw page write function
2789 * @mtd: mtd info structure
2790 * @chip: nand chip info structure
2792 * @oob_required: must write chip->oob_poi to OOB
2793 * @page: page number to write
2795 * Not for syndrome calculating ECC controllers, which use a special oob layout.
2797 static int nand_write_page_raw(struct mtd_info *mtd, struct nand_chip *chip,
2798 const uint8_t *buf, int oob_required, int page)
2802 ret = nand_write_data_op(chip, buf, mtd->writesize, false);
2807 ret = nand_write_data_op(chip, chip->oob_poi, mtd->oobsize,
2817 * nand_write_page_raw_syndrome - [INTERN] raw page write function
2818 * @mtd: mtd info structure
2819 * @chip: nand chip info structure
2821 * @oob_required: must write chip->oob_poi to OOB
2822 * @page: page number to write
2824 * We need a special oob layout and handling even when ECC isn't checked.
2826 static int nand_write_page_raw_syndrome(struct mtd_info *mtd,
2827 struct nand_chip *chip,
2828 const uint8_t *buf, int oob_required,
2831 int eccsize = chip->ecc.size;
2832 int eccbytes = chip->ecc.bytes;
2833 uint8_t *oob = chip->oob_poi;
2834 int steps, size, ret;
2836 for (steps = chip->ecc.steps; steps > 0; steps--) {
2837 ret = nand_write_data_op(chip, buf, eccsize, false);
2843 if (chip->ecc.prepad) {
2844 ret = nand_write_data_op(chip, oob, chip->ecc.prepad,
2849 oob += chip->ecc.prepad;
2852 ret = nand_write_data_op(chip, oob, eccbytes, false);
2858 if (chip->ecc.postpad) {
2859 ret = nand_write_data_op(chip, oob, chip->ecc.postpad,
2864 oob += chip->ecc.postpad;
2868 size = mtd->oobsize - (oob - chip->oob_poi);
2870 ret = nand_write_data_op(chip, oob, size, false);
2878 * nand_write_page_swecc - [REPLACEABLE] software ECC based page write function
2879 * @mtd: mtd info structure
2880 * @chip: nand chip info structure
2882 * @oob_required: must write chip->oob_poi to OOB
2883 * @page: page number to write
2885 static int nand_write_page_swecc(struct mtd_info *mtd, struct nand_chip *chip,
2886 const uint8_t *buf, int oob_required,
2889 int i, eccsize = chip->ecc.size;
2890 int eccbytes = chip->ecc.bytes;
2891 int eccsteps = chip->ecc.steps;
2892 uint8_t *ecc_calc = chip->buffers->ecccalc;
2893 const uint8_t *p = buf;
2894 uint32_t *eccpos = chip->ecc.layout->eccpos;
2896 /* Software ECC calculation */
2897 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize)
2898 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
2900 for (i = 0; i < chip->ecc.total; i++)
2901 chip->oob_poi[eccpos[i]] = ecc_calc[i];
2903 return chip->ecc.write_page_raw(mtd, chip, buf, 1, page);
2907 * nand_write_page_hwecc - [REPLACEABLE] hardware ECC based page write function
2908 * @mtd: mtd info structure
2909 * @chip: nand chip info structure
2911 * @oob_required: must write chip->oob_poi to OOB
2912 * @page: page number to write
2914 static int nand_write_page_hwecc(struct mtd_info *mtd, struct nand_chip *chip,
2915 const uint8_t *buf, int oob_required,
2918 int i, eccsize = chip->ecc.size;
2919 int eccbytes = chip->ecc.bytes;
2920 int eccsteps = chip->ecc.steps;
2921 uint8_t *ecc_calc = chip->buffers->ecccalc;
2922 const uint8_t *p = buf;
2923 uint32_t *eccpos = chip->ecc.layout->eccpos;
2926 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
2927 chip->ecc.hwctl(mtd, NAND_ECC_WRITE);
2929 ret = nand_write_data_op(chip, p, eccsize, false);
2933 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
2936 for (i = 0; i < chip->ecc.total; i++)
2937 chip->oob_poi[eccpos[i]] = ecc_calc[i];
2939 ret = nand_write_data_op(chip, chip->oob_poi, mtd->oobsize, false);
2948 * nand_write_subpage_hwecc - [REPLACEABLE] hardware ECC based subpage write
2949 * @mtd: mtd info structure
2950 * @chip: nand chip info structure
2951 * @offset: column address of subpage within the page
2952 * @data_len: data length
2954 * @oob_required: must write chip->oob_poi to OOB
2955 * @page: page number to write
2957 static int nand_write_subpage_hwecc(struct mtd_info *mtd,
2958 struct nand_chip *chip, uint32_t offset,
2959 uint32_t data_len, const uint8_t *buf,
2960 int oob_required, int page)
2962 uint8_t *oob_buf = chip->oob_poi;
2963 uint8_t *ecc_calc = chip->buffers->ecccalc;
2964 int ecc_size = chip->ecc.size;
2965 int ecc_bytes = chip->ecc.bytes;
2966 int ecc_steps = chip->ecc.steps;
2967 uint32_t *eccpos = chip->ecc.layout->eccpos;
2968 uint32_t start_step = offset / ecc_size;
2969 uint32_t end_step = (offset + data_len - 1) / ecc_size;
2970 int oob_bytes = mtd->oobsize / ecc_steps;
2974 for (step = 0; step < ecc_steps; step++) {
2975 /* configure controller for WRITE access */
2976 chip->ecc.hwctl(mtd, NAND_ECC_WRITE);
2978 /* write data (untouched subpages already masked by 0xFF) */
2979 ret = nand_write_data_op(chip, buf, ecc_size, false);
2983 /* mask ECC of un-touched subpages by padding 0xFF */
2984 if ((step < start_step) || (step > end_step))
2985 memset(ecc_calc, 0xff, ecc_bytes);
2987 chip->ecc.calculate(mtd, buf, ecc_calc);
2989 /* mask OOB of un-touched subpages by padding 0xFF */
2990 /* if oob_required, preserve OOB metadata of written subpage */
2991 if (!oob_required || (step < start_step) || (step > end_step))
2992 memset(oob_buf, 0xff, oob_bytes);
2995 ecc_calc += ecc_bytes;
2996 oob_buf += oob_bytes;
2999 /* copy calculated ECC for whole page to chip->buffer->oob */
3000 /* this include masked-value(0xFF) for unwritten subpages */
3001 ecc_calc = chip->buffers->ecccalc;
3002 for (i = 0; i < chip->ecc.total; i++)
3003 chip->oob_poi[eccpos[i]] = ecc_calc[i];
3005 /* write OOB buffer to NAND device */
3006 ret = nand_write_data_op(chip, chip->oob_poi, mtd->oobsize, false);
3015 * nand_write_page_syndrome - [REPLACEABLE] hardware ECC syndrome based page write
3016 * @mtd: mtd info structure
3017 * @chip: nand chip info structure
3019 * @oob_required: must write chip->oob_poi to OOB
3020 * @page: page number to write
3022 * The hw generator calculates the error syndrome automatically. Therefore we
3023 * need a special oob layout and handling.
3025 static int nand_write_page_syndrome(struct mtd_info *mtd,
3026 struct nand_chip *chip,
3027 const uint8_t *buf, int oob_required,
3030 int i, eccsize = chip->ecc.size;
3031 int eccbytes = chip->ecc.bytes;
3032 int eccsteps = chip->ecc.steps;
3033 const uint8_t *p = buf;
3034 uint8_t *oob = chip->oob_poi;
3037 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
3038 chip->ecc.hwctl(mtd, NAND_ECC_WRITE);
3040 ret = nand_write_data_op(chip, p, eccsize, false);
3044 if (chip->ecc.prepad) {
3045 ret = nand_write_data_op(chip, oob, chip->ecc.prepad,
3050 oob += chip->ecc.prepad;
3053 chip->ecc.calculate(mtd, p, oob);
3055 ret = nand_write_data_op(chip, oob, eccbytes, false);
3061 if (chip->ecc.postpad) {
3062 ret = nand_write_data_op(chip, oob, chip->ecc.postpad,
3067 oob += chip->ecc.postpad;
3071 /* Calculate remaining oob bytes */
3072 i = mtd->oobsize - (oob - chip->oob_poi);
3074 ret = nand_write_data_op(chip, oob, i, false);
3083 * nand_write_page - [REPLACEABLE] write one page
3084 * @mtd: MTD device structure
3085 * @chip: NAND chip descriptor
3086 * @offset: address offset within the page
3087 * @data_len: length of actual data to be written
3088 * @buf: the data to write
3089 * @oob_required: must write chip->oob_poi to OOB
3090 * @page: page number to write
3091 * @raw: use _raw version of write_page
3093 static int nand_write_page(struct mtd_info *mtd, struct nand_chip *chip,
3094 uint32_t offset, int data_len, const uint8_t *buf,
3095 int oob_required, int page, int raw)
3097 int status, subpage;
3099 if (!(chip->options & NAND_NO_SUBPAGE_WRITE) &&
3100 chip->ecc.write_subpage)
3101 subpage = offset || (data_len < mtd->writesize);
3105 if (nand_standard_page_accessors(&chip->ecc)) {
3106 status = nand_prog_page_begin_op(chip, page, 0, NULL, 0);
3112 status = chip->ecc.write_page_raw(mtd, chip, buf,
3113 oob_required, page);
3115 status = chip->ecc.write_subpage(mtd, chip, offset, data_len,
3116 buf, oob_required, page);
3118 status = chip->ecc.write_page(mtd, chip, buf, oob_required,
3124 if (nand_standard_page_accessors(&chip->ecc))
3125 return nand_prog_page_end_op(chip);
3131 * nand_fill_oob - [INTERN] Transfer client buffer to oob
3132 * @mtd: MTD device structure
3133 * @oob: oob data buffer
3134 * @len: oob data write length
3135 * @ops: oob ops structure
3137 static uint8_t *nand_fill_oob(struct mtd_info *mtd, uint8_t *oob, size_t len,
3138 struct mtd_oob_ops *ops)
3140 struct nand_chip *chip = mtd_to_nand(mtd);
3143 * Initialise to all 0xFF, to avoid the possibility of left over OOB
3144 * data from a previous OOB read.
3146 memset(chip->oob_poi, 0xff, mtd->oobsize);
3148 switch (ops->mode) {
3150 case MTD_OPS_PLACE_OOB:
3152 memcpy(chip->oob_poi + ops->ooboffs, oob, len);
3155 case MTD_OPS_AUTO_OOB: {
3156 struct nand_oobfree *free = chip->ecc.layout->oobfree;
3157 uint32_t boffs = 0, woffs = ops->ooboffs;
3160 for (; free->length && len; free++, len -= bytes) {
3161 /* Write request not from offset 0? */
3162 if (unlikely(woffs)) {
3163 if (woffs >= free->length) {
3164 woffs -= free->length;
3167 boffs = free->offset + woffs;
3168 bytes = min_t(size_t, len,
3169 (free->length - woffs));
3172 bytes = min_t(size_t, len, free->length);
3173 boffs = free->offset;
3175 memcpy(chip->oob_poi + boffs, oob, bytes);
3186 #define NOTALIGNED(x) ((x & (chip->subpagesize - 1)) != 0)
3189 * nand_do_write_ops - [INTERN] NAND write with ECC
3190 * @mtd: MTD device structure
3191 * @to: offset to write to
3192 * @ops: oob operations description structure
3194 * NAND write with ECC.
3196 static int nand_do_write_ops(struct mtd_info *mtd, loff_t to,
3197 struct mtd_oob_ops *ops)
3199 int chipnr, realpage, page, column;
3200 struct nand_chip *chip = mtd_to_nand(mtd);
3201 uint32_t writelen = ops->len;
3203 uint32_t oobwritelen = ops->ooblen;
3204 uint32_t oobmaxlen = mtd_oobavail(mtd, ops);
3206 uint8_t *oob = ops->oobbuf;
3207 uint8_t *buf = ops->datbuf;
3209 int oob_required = oob ? 1 : 0;
3215 /* Reject writes, which are not page aligned */
3216 if (NOTALIGNED(to)) {
3217 pr_notice("%s: attempt to write non page aligned data\n",
3222 column = to & (mtd->writesize - 1);
3224 chipnr = (int)(to >> chip->chip_shift);
3225 chip->select_chip(mtd, chipnr);
3227 /* Check, if it is write protected */
3228 if (nand_check_wp(mtd)) {
3233 realpage = (int)(to >> chip->page_shift);
3234 page = realpage & chip->pagemask;
3236 /* Invalidate the page cache, when we write to the cached page */
3237 if (to <= ((loff_t)chip->pagebuf << chip->page_shift) &&
3238 ((loff_t)chip->pagebuf << chip->page_shift) < (to + ops->len))
3241 /* Don't allow multipage oob writes with offset */
3242 if (oob && ops->ooboffs && (ops->ooboffs + ops->ooblen > oobmaxlen)) {
3248 int bytes = mtd->writesize;
3249 uint8_t *wbuf = buf;
3251 int part_pagewr = (column || writelen < mtd->writesize);
3255 else if (chip->options & NAND_USE_BOUNCE_BUFFER)
3256 use_bufpoi = !IS_ALIGNED((unsigned long)buf,
3262 /* Partial page write?, or need to use bounce buffer */
3264 pr_debug("%s: using write bounce buffer for buf@%p\n",
3267 bytes = min_t(int, bytes - column, writelen);
3269 memset(chip->buffers->databuf, 0xff, mtd->writesize);
3270 memcpy(&chip->buffers->databuf[column], buf, bytes);
3271 wbuf = chip->buffers->databuf;
3274 if (unlikely(oob)) {
3275 size_t len = min(oobwritelen, oobmaxlen);
3276 oob = nand_fill_oob(mtd, oob, len, ops);
3279 /* We still need to erase leftover OOB data */
3280 memset(chip->oob_poi, 0xff, mtd->oobsize);
3282 ret = chip->write_page(mtd, chip, column, bytes, wbuf,
3284 (ops->mode == MTD_OPS_RAW));
3296 page = realpage & chip->pagemask;
3297 /* Check, if we cross a chip boundary */
3300 chip->select_chip(mtd, -1);
3301 chip->select_chip(mtd, chipnr);
3305 ops->retlen = ops->len - writelen;
3307 ops->oobretlen = ops->ooblen;
3310 chip->select_chip(mtd, -1);
3315 * panic_nand_write - [MTD Interface] NAND write with ECC
3316 * @mtd: MTD device structure
3317 * @to: offset to write to
3318 * @len: number of bytes to write
3319 * @retlen: pointer to variable to store the number of written bytes
3320 * @buf: the data to write
3322 * NAND write with ECC. Used when performing writes in interrupt context, this
3323 * may for example be called by mtdoops when writing an oops while in panic.
3325 static int panic_nand_write(struct mtd_info *mtd, loff_t to, size_t len,
3326 size_t *retlen, const uint8_t *buf)
3328 struct nand_chip *chip = mtd_to_nand(mtd);
3329 struct mtd_oob_ops ops;
3332 /* Wait for the device to get ready */
3333 panic_nand_wait(mtd, chip, 400);
3335 /* Grab the device */
3336 panic_nand_get_device(chip, mtd, FL_WRITING);
3338 memset(&ops, 0, sizeof(ops));
3340 ops.datbuf = (uint8_t *)buf;
3341 ops.mode = MTD_OPS_PLACE_OOB;
3343 ret = nand_do_write_ops(mtd, to, &ops);
3345 *retlen = ops.retlen;
3350 * nand_do_write_oob - [MTD Interface] NAND write out-of-band
3351 * @mtd: MTD device structure
3352 * @to: offset to write to
3353 * @ops: oob operation description structure
3355 * NAND write out-of-band.
3357 static int nand_do_write_oob(struct mtd_info *mtd, loff_t to,
3358 struct mtd_oob_ops *ops)
3360 int chipnr, page, status, len;
3361 struct nand_chip *chip = mtd_to_nand(mtd);
3363 pr_debug("%s: to = 0x%08x, len = %i\n",
3364 __func__, (unsigned int)to, (int)ops->ooblen);
3366 len = mtd_oobavail(mtd, ops);
3368 /* Do not allow write past end of page */
3369 if ((ops->ooboffs + ops->ooblen) > len) {
3370 pr_debug("%s: attempt to write past end of page\n",
3375 if (unlikely(ops->ooboffs >= len)) {
3376 pr_debug("%s: attempt to start write outside oob\n",
3381 /* Do not allow write past end of device */
3382 if (unlikely(to >= mtd->size ||
3383 ops->ooboffs + ops->ooblen >
3384 ((mtd->size >> chip->page_shift) -
3385 (to >> chip->page_shift)) * len)) {
3386 pr_debug("%s: attempt to write beyond end of device\n",
3391 chipnr = (int)(to >> chip->chip_shift);
3394 * Reset the chip. Some chips (like the Toshiba TC5832DC found in one
3395 * of my DiskOnChip 2000 test units) will clear the whole data page too
3396 * if we don't do this. I have no clue why, but I seem to have 'fixed'
3397 * it in the doc2000 driver in August 1999. dwmw2.
3399 nand_reset(chip, chipnr);
3401 chip->select_chip(mtd, chipnr);
3403 /* Shift to get page */
3404 page = (int)(to >> chip->page_shift);
3406 /* Check, if it is write protected */
3407 if (nand_check_wp(mtd)) {
3408 chip->select_chip(mtd, -1);
3412 /* Invalidate the page cache, if we write to the cached page */
3413 if (page == chip->pagebuf)
3416 nand_fill_oob(mtd, ops->oobbuf, ops->ooblen, ops);
3418 if (ops->mode == MTD_OPS_RAW)
3419 status = chip->ecc.write_oob_raw(mtd, chip, page & chip->pagemask);
3421 status = chip->ecc.write_oob(mtd, chip, page & chip->pagemask);
3423 chip->select_chip(mtd, -1);
3428 ops->oobretlen = ops->ooblen;
3434 * nand_write_oob - [MTD Interface] NAND write data and/or out-of-band
3435 * @mtd: MTD device structure
3436 * @to: offset to write to
3437 * @ops: oob operation description structure
3439 static int nand_write_oob(struct mtd_info *mtd, loff_t to,
3440 struct mtd_oob_ops *ops)
3442 int ret = -ENOTSUPP;
3446 /* Do not allow writes past end of device */
3447 if (ops->datbuf && (to + ops->len) > mtd->size) {
3448 pr_debug("%s: attempt to write beyond end of device\n",
3453 nand_get_device(mtd, FL_WRITING);
3455 switch (ops->mode) {
3456 case MTD_OPS_PLACE_OOB:
3457 case MTD_OPS_AUTO_OOB:
3466 ret = nand_do_write_oob(mtd, to, ops);
3468 ret = nand_do_write_ops(mtd, to, ops);
3471 nand_release_device(mtd);
3476 * single_erase - [GENERIC] NAND standard block erase command function
3477 * @mtd: MTD device structure
3478 * @page: the page address of the block which will be erased
3480 * Standard erase command for NAND chips. Returns NAND status.
3482 static int single_erase(struct mtd_info *mtd, int page)
3484 struct nand_chip *chip = mtd_to_nand(mtd);
3485 unsigned int eraseblock;
3487 /* Send commands to erase a block */
3488 eraseblock = page >> (chip->phys_erase_shift - chip->page_shift);
3490 return nand_erase_op(chip, eraseblock);
3494 * nand_erase - [MTD Interface] erase block(s)
3495 * @mtd: MTD device structure
3496 * @instr: erase instruction
3498 * Erase one ore more blocks.
3500 static int nand_erase(struct mtd_info *mtd, struct erase_info *instr)
3502 return nand_erase_nand(mtd, instr, 0);
3506 * nand_erase_nand - [INTERN] erase block(s)
3507 * @mtd: MTD device structure
3508 * @instr: erase instruction
3509 * @allowbbt: allow erasing the bbt area
3511 * Erase one ore more blocks.
3513 int nand_erase_nand(struct mtd_info *mtd, struct erase_info *instr,
3516 int page, status, pages_per_block, ret, chipnr;
3517 struct nand_chip *chip = mtd_to_nand(mtd);
3520 pr_debug("%s: start = 0x%012llx, len = %llu\n",
3521 __func__, (unsigned long long)instr->addr,
3522 (unsigned long long)instr->len);
3524 if (check_offs_len(mtd, instr->addr, instr->len))
3527 /* Grab the lock and see if the device is available */
3528 nand_get_device(mtd, FL_ERASING);
3530 /* Shift to get first page */
3531 page = (int)(instr->addr >> chip->page_shift);
3532 chipnr = (int)(instr->addr >> chip->chip_shift);
3534 /* Calculate pages in each block */
3535 pages_per_block = 1 << (chip->phys_erase_shift - chip->page_shift);
3537 /* Select the NAND device */
3538 chip->select_chip(mtd, chipnr);
3540 /* Check, if it is write protected */
3541 if (nand_check_wp(mtd)) {
3542 pr_debug("%s: device is write protected!\n",
3544 instr->state = MTD_ERASE_FAILED;
3548 /* Loop through the pages */
3551 instr->state = MTD_ERASING;
3556 /* Check if we have a bad block, we do not erase bad blocks! */
3557 if (!instr->scrub && nand_block_checkbad(mtd, ((loff_t) page) <<
3558 chip->page_shift, allowbbt)) {
3559 pr_warn("%s: attempt to erase a bad block at page 0x%08x\n",
3561 instr->state = MTD_ERASE_FAILED;
3566 * Invalidate the page cache, if we erase the block which
3567 * contains the current cached page.
3569 if (page <= chip->pagebuf && chip->pagebuf <
3570 (page + pages_per_block))
3573 status = chip->erase(mtd, page & chip->pagemask);
3575 /* See if block erase succeeded */
3576 if (status & NAND_STATUS_FAIL) {
3577 pr_debug("%s: failed erase, page 0x%08x\n",
3579 instr->state = MTD_ERASE_FAILED;
3581 ((loff_t)page << chip->page_shift);
3585 /* Increment page address and decrement length */
3586 len -= (1ULL << chip->phys_erase_shift);
3587 page += pages_per_block;
3589 /* Check, if we cross a chip boundary */
3590 if (len && !(page & chip->pagemask)) {
3592 chip->select_chip(mtd, -1);
3593 chip->select_chip(mtd, chipnr);
3596 instr->state = MTD_ERASE_DONE;
3600 ret = instr->state == MTD_ERASE_DONE ? 0 : -EIO;
3602 /* Deselect and wake up anyone waiting on the device */
3603 chip->select_chip(mtd, -1);
3604 nand_release_device(mtd);
3606 /* Do call back function */
3608 mtd_erase_callback(instr);
3610 /* Return more or less happy */
3615 * nand_sync - [MTD Interface] sync
3616 * @mtd: MTD device structure
3618 * Sync is actually a wait for chip ready function.
3620 static void nand_sync(struct mtd_info *mtd)
3622 pr_debug("%s: called\n", __func__);
3624 /* Grab the lock and see if the device is available */
3625 nand_get_device(mtd, FL_SYNCING);
3626 /* Release it and go back */
3627 nand_release_device(mtd);
3631 * nand_block_isbad - [MTD Interface] Check if block at offset is bad
3632 * @mtd: MTD device structure
3633 * @offs: offset relative to mtd start
3635 static int nand_block_isbad(struct mtd_info *mtd, loff_t offs)
3637 struct nand_chip *chip = mtd_to_nand(mtd);
3638 int chipnr = (int)(offs >> chip->chip_shift);
3641 /* Select the NAND device */
3642 nand_get_device(mtd, FL_READING);
3643 chip->select_chip(mtd, chipnr);
3645 ret = nand_block_checkbad(mtd, offs, 0);
3647 chip->select_chip(mtd, -1);
3648 nand_release_device(mtd);
3654 * nand_block_markbad - [MTD Interface] Mark block at the given offset as bad
3655 * @mtd: MTD device structure
3656 * @ofs: offset relative to mtd start
3658 static int nand_block_markbad(struct mtd_info *mtd, loff_t ofs)
3662 ret = nand_block_isbad(mtd, ofs);
3664 /* If it was bad already, return success and do nothing */
3670 return nand_block_markbad_lowlevel(mtd, ofs);
3674 * nand_onfi_set_features- [REPLACEABLE] set features for ONFI nand
3675 * @mtd: MTD device structure
3676 * @chip: nand chip info structure
3677 * @addr: feature address.
3678 * @subfeature_param: the subfeature parameters, a four bytes array.
3680 static int nand_onfi_set_features(struct mtd_info *mtd, struct nand_chip *chip,
3681 int addr, uint8_t *subfeature_param)
3683 #ifdef CONFIG_SYS_NAND_ONFI_DETECTION
3684 if (!chip->onfi_version ||
3685 !(le16_to_cpu(chip->onfi_params.opt_cmd)
3686 & ONFI_OPT_CMD_SET_GET_FEATURES))
3690 return nand_set_features_op(chip, addr, subfeature_param);
3694 * nand_onfi_get_features- [REPLACEABLE] get features for ONFI nand
3695 * @mtd: MTD device structure
3696 * @chip: nand chip info structure
3697 * @addr: feature address.
3698 * @subfeature_param: the subfeature parameters, a four bytes array.
3700 static int nand_onfi_get_features(struct mtd_info *mtd, struct nand_chip *chip,
3701 int addr, uint8_t *subfeature_param)
3703 #ifdef CONFIG_SYS_NAND_ONFI_DETECTION
3704 if (!chip->onfi_version ||
3705 !(le16_to_cpu(chip->onfi_params.opt_cmd)
3706 & ONFI_OPT_CMD_SET_GET_FEATURES))
3710 return nand_get_features_op(chip, addr, subfeature_param);
3713 /* Set default functions */
3714 static void nand_set_defaults(struct nand_chip *chip, int busw)
3716 /* check for proper chip_delay setup, set 20us if not */
3717 if (!chip->chip_delay)
3718 chip->chip_delay = 20;
3720 /* check, if a user supplied command function given */
3721 if (chip->cmdfunc == NULL)
3722 chip->cmdfunc = nand_command;
3724 /* check, if a user supplied wait function given */
3725 if (chip->waitfunc == NULL)
3726 chip->waitfunc = nand_wait;
3728 if (!chip->select_chip)
3729 chip->select_chip = nand_select_chip;
3731 /* set for ONFI nand */
3732 if (!chip->onfi_set_features)
3733 chip->onfi_set_features = nand_onfi_set_features;
3734 if (!chip->onfi_get_features)
3735 chip->onfi_get_features = nand_onfi_get_features;
3737 /* If called twice, pointers that depend on busw may need to be reset */
3738 if (!chip->read_byte || chip->read_byte == nand_read_byte)
3739 chip->read_byte = busw ? nand_read_byte16 : nand_read_byte;
3740 if (!chip->read_word)
3741 chip->read_word = nand_read_word;
3742 if (!chip->block_bad)
3743 chip->block_bad = nand_block_bad;
3744 if (!chip->block_markbad)
3745 chip->block_markbad = nand_default_block_markbad;
3746 if (!chip->write_buf || chip->write_buf == nand_write_buf)
3747 chip->write_buf = busw ? nand_write_buf16 : nand_write_buf;
3748 if (!chip->write_byte || chip->write_byte == nand_write_byte)
3749 chip->write_byte = busw ? nand_write_byte16 : nand_write_byte;
3750 if (!chip->read_buf || chip->read_buf == nand_read_buf)
3751 chip->read_buf = busw ? nand_read_buf16 : nand_read_buf;
3752 if (!chip->scan_bbt)
3753 chip->scan_bbt = nand_default_bbt;
3755 if (!chip->controller) {
3756 chip->controller = &chip->hwcontrol;
3757 spin_lock_init(&chip->controller->lock);
3758 init_waitqueue_head(&chip->controller->wq);
3761 if (!chip->buf_align)
3762 chip->buf_align = 1;
3765 /* Sanitize ONFI strings so we can safely print them */
3766 static void sanitize_string(char *s, size_t len)
3770 /* Null terminate */
3773 /* Remove non printable chars */
3774 for (i = 0; i < len - 1; i++) {
3775 if (s[i] < ' ' || s[i] > 127)
3779 /* Remove trailing spaces */
3783 static u16 onfi_crc16(u16 crc, u8 const *p, size_t len)
3788 for (i = 0; i < 8; i++)
3789 crc = (crc << 1) ^ ((crc & 0x8000) ? 0x8005 : 0);
3795 #ifdef CONFIG_SYS_NAND_ONFI_DETECTION
3796 /* Parse the Extended Parameter Page. */
3797 static int nand_flash_detect_ext_param_page(struct mtd_info *mtd,
3798 struct nand_chip *chip, struct nand_onfi_params *p)
3800 struct onfi_ext_param_page *ep;
3801 struct onfi_ext_section *s;
3802 struct onfi_ext_ecc_info *ecc;
3808 len = le16_to_cpu(p->ext_param_page_length) * 16;
3809 ep = kmalloc(len, GFP_KERNEL);
3813 /* Send our own NAND_CMD_PARAM. */
3814 ret = nand_read_param_page_op(chip, 0, NULL, 0);
3818 /* Use the Change Read Column command to skip the ONFI param pages. */
3819 ret = nand_change_read_column_op(chip,
3820 sizeof(*p) * p->num_of_param_pages,
3826 if ((onfi_crc16(ONFI_CRC_BASE, ((uint8_t *)ep) + 2, len - 2)
3827 != le16_to_cpu(ep->crc))) {
3828 pr_debug("fail in the CRC.\n");
3833 * Check the signature.
3834 * Do not strictly follow the ONFI spec, maybe changed in future.
3836 if (strncmp((char *)ep->sig, "EPPS", 4)) {
3837 pr_debug("The signature is invalid.\n");
3841 /* find the ECC section. */
3842 cursor = (uint8_t *)(ep + 1);
3843 for (i = 0; i < ONFI_EXT_SECTION_MAX; i++) {
3844 s = ep->sections + i;
3845 if (s->type == ONFI_SECTION_TYPE_2)
3847 cursor += s->length * 16;
3849 if (i == ONFI_EXT_SECTION_MAX) {
3850 pr_debug("We can not find the ECC section.\n");
3854 /* get the info we want. */
3855 ecc = (struct onfi_ext_ecc_info *)cursor;
3857 if (!ecc->codeword_size) {
3858 pr_debug("Invalid codeword size\n");
3862 chip->ecc_strength_ds = ecc->ecc_bits;
3863 chip->ecc_step_ds = 1 << ecc->codeword_size;
3871 static int nand_setup_read_retry_micron(struct mtd_info *mtd, int retry_mode)
3873 struct nand_chip *chip = mtd_to_nand(mtd);
3874 uint8_t feature[ONFI_SUBFEATURE_PARAM_LEN] = {retry_mode};
3876 return chip->onfi_set_features(mtd, chip, ONFI_FEATURE_ADDR_READ_RETRY,
3881 * Configure chip properties from Micron vendor-specific ONFI table
3883 static void nand_onfi_detect_micron(struct nand_chip *chip,
3884 struct nand_onfi_params *p)
3886 struct nand_onfi_vendor_micron *micron = (void *)p->vendor;
3888 if (le16_to_cpu(p->vendor_revision) < 1)
3891 chip->read_retries = micron->read_retry_options;
3892 chip->setup_read_retry = nand_setup_read_retry_micron;
3896 * Check if the NAND chip is ONFI compliant, returns 1 if it is, 0 otherwise.
3898 static int nand_flash_detect_onfi(struct mtd_info *mtd, struct nand_chip *chip,
3901 struct nand_onfi_params *p = &chip->onfi_params;
3905 /* Try ONFI for unknown chip or LP */
3906 ret = nand_readid_op(chip, 0x20, id, sizeof(id));
3907 if (ret || strncmp(id, "ONFI", 4))
3910 ret = nand_read_param_page_op(chip, 0, NULL, 0);
3914 for (i = 0; i < 3; i++) {
3915 ret = nand_read_data_op(chip, p, sizeof(*p), true);
3919 if (onfi_crc16(ONFI_CRC_BASE, (uint8_t *)p, 254) ==
3920 le16_to_cpu(p->crc)) {
3926 pr_err("Could not find valid ONFI parameter page; aborting\n");
3931 val = le16_to_cpu(p->revision);
3933 chip->onfi_version = 23;
3934 else if (val & (1 << 4))
3935 chip->onfi_version = 22;
3936 else if (val & (1 << 3))
3937 chip->onfi_version = 21;
3938 else if (val & (1 << 2))
3939 chip->onfi_version = 20;
3940 else if (val & (1 << 1))
3941 chip->onfi_version = 10;
3943 if (!chip->onfi_version) {
3944 pr_info("unsupported ONFI version: %d\n", val);
3948 sanitize_string(p->manufacturer, sizeof(p->manufacturer));
3949 sanitize_string(p->model, sizeof(p->model));
3951 mtd->name = p->model;
3953 mtd->writesize = le32_to_cpu(p->byte_per_page);
3956 * pages_per_block and blocks_per_lun may not be a power-of-2 size
3957 * (don't ask me who thought of this...). MTD assumes that these
3958 * dimensions will be power-of-2, so just truncate the remaining area.
3960 mtd->erasesize = 1 << (fls(le32_to_cpu(p->pages_per_block)) - 1);
3961 mtd->erasesize *= mtd->writesize;
3963 mtd->oobsize = le16_to_cpu(p->spare_bytes_per_page);
3965 /* See erasesize comment */
3966 chip->chipsize = 1 << (fls(le32_to_cpu(p->blocks_per_lun)) - 1);
3967 chip->chipsize *= (uint64_t)mtd->erasesize * p->lun_count;
3968 chip->bits_per_cell = p->bits_per_cell;
3970 if (onfi_feature(chip) & ONFI_FEATURE_16_BIT_BUS)
3971 *busw = NAND_BUSWIDTH_16;
3975 if (p->ecc_bits != 0xff) {
3976 chip->ecc_strength_ds = p->ecc_bits;
3977 chip->ecc_step_ds = 512;
3978 } else if (chip->onfi_version >= 21 &&
3979 (onfi_feature(chip) & ONFI_FEATURE_EXT_PARAM_PAGE)) {
3982 * The nand_flash_detect_ext_param_page() uses the
3983 * Change Read Column command which maybe not supported
3984 * by the chip->cmdfunc. So try to update the chip->cmdfunc
3985 * now. We do not replace user supplied command function.
3987 if (mtd->writesize > 512 && chip->cmdfunc == nand_command)
3988 chip->cmdfunc = nand_command_lp;
3990 /* The Extended Parameter Page is supported since ONFI 2.1. */
3991 if (nand_flash_detect_ext_param_page(mtd, chip, p))
3992 pr_warn("Failed to detect ONFI extended param page\n");
3994 pr_warn("Could not retrieve ONFI ECC requirements\n");
3997 if (p->jedec_id == NAND_MFR_MICRON)
3998 nand_onfi_detect_micron(chip, p);
4003 static int nand_flash_detect_onfi(struct mtd_info *mtd, struct nand_chip *chip,
4011 * Check if the NAND chip is JEDEC compliant, returns 1 if it is, 0 otherwise.
4013 static int nand_flash_detect_jedec(struct mtd_info *mtd, struct nand_chip *chip,
4016 struct nand_jedec_params *p = &chip->jedec_params;
4017 struct jedec_ecc_info *ecc;
4021 /* Try JEDEC for unknown chip or LP */
4022 ret = nand_readid_op(chip, 0x40, id, sizeof(id));
4023 if (ret || strncmp(id, "JEDEC", sizeof(id)))
4026 ret = nand_read_param_page_op(chip, 0x40, NULL, 0);
4030 for (i = 0; i < 3; i++) {
4031 ret = nand_read_data_op(chip, p, sizeof(*p), true);
4035 if (onfi_crc16(ONFI_CRC_BASE, (uint8_t *)p, 510) ==
4036 le16_to_cpu(p->crc))
4041 pr_err("Could not find valid JEDEC parameter page; aborting\n");
4046 val = le16_to_cpu(p->revision);
4048 chip->jedec_version = 10;
4049 else if (val & (1 << 1))
4050 chip->jedec_version = 1; /* vendor specific version */
4052 if (!chip->jedec_version) {
4053 pr_info("unsupported JEDEC version: %d\n", val);
4057 sanitize_string(p->manufacturer, sizeof(p->manufacturer));
4058 sanitize_string(p->model, sizeof(p->model));
4060 mtd->name = p->model;
4062 mtd->writesize = le32_to_cpu(p->byte_per_page);
4064 /* Please reference to the comment for nand_flash_detect_onfi. */
4065 mtd->erasesize = 1 << (fls(le32_to_cpu(p->pages_per_block)) - 1);
4066 mtd->erasesize *= mtd->writesize;
4068 mtd->oobsize = le16_to_cpu(p->spare_bytes_per_page);
4070 /* Please reference to the comment for nand_flash_detect_onfi. */
4071 chip->chipsize = 1 << (fls(le32_to_cpu(p->blocks_per_lun)) - 1);
4072 chip->chipsize *= (uint64_t)mtd->erasesize * p->lun_count;
4073 chip->bits_per_cell = p->bits_per_cell;
4075 if (jedec_feature(chip) & JEDEC_FEATURE_16_BIT_BUS)
4076 *busw = NAND_BUSWIDTH_16;
4081 ecc = &p->ecc_info[0];
4083 if (ecc->codeword_size >= 9) {
4084 chip->ecc_strength_ds = ecc->ecc_bits;
4085 chip->ecc_step_ds = 1 << ecc->codeword_size;
4087 pr_warn("Invalid codeword size\n");
4094 * nand_id_has_period - Check if an ID string has a given wraparound period
4095 * @id_data: the ID string
4096 * @arrlen: the length of the @id_data array
4097 * @period: the period of repitition
4099 * Check if an ID string is repeated within a given sequence of bytes at
4100 * specific repetition interval period (e.g., {0x20,0x01,0x7F,0x20} has a
4101 * period of 3). This is a helper function for nand_id_len(). Returns non-zero
4102 * if the repetition has a period of @period; otherwise, returns zero.
4104 static int nand_id_has_period(u8 *id_data, int arrlen, int period)
4107 for (i = 0; i < period; i++)
4108 for (j = i + period; j < arrlen; j += period)
4109 if (id_data[i] != id_data[j])
4115 * nand_id_len - Get the length of an ID string returned by CMD_READID
4116 * @id_data: the ID string
4117 * @arrlen: the length of the @id_data array
4119 * Returns the length of the ID string, according to known wraparound/trailing
4120 * zero patterns. If no pattern exists, returns the length of the array.
4122 static int nand_id_len(u8 *id_data, int arrlen)
4124 int last_nonzero, period;
4126 /* Find last non-zero byte */
4127 for (last_nonzero = arrlen - 1; last_nonzero >= 0; last_nonzero--)
4128 if (id_data[last_nonzero])
4132 if (last_nonzero < 0)
4135 /* Calculate wraparound period */
4136 for (period = 1; period < arrlen; period++)
4137 if (nand_id_has_period(id_data, arrlen, period))
4140 /* There's a repeated pattern */
4141 if (period < arrlen)
4144 /* There are trailing zeros */
4145 if (last_nonzero < arrlen - 1)
4146 return last_nonzero + 1;
4148 /* No pattern detected */
4152 /* Extract the bits of per cell from the 3rd byte of the extended ID */
4153 static int nand_get_bits_per_cell(u8 cellinfo)
4157 bits = cellinfo & NAND_CI_CELLTYPE_MSK;
4158 bits >>= NAND_CI_CELLTYPE_SHIFT;
4163 * Many new NAND share similar device ID codes, which represent the size of the
4164 * chip. The rest of the parameters must be decoded according to generic or
4165 * manufacturer-specific "extended ID" decoding patterns.
4167 static void nand_decode_ext_id(struct mtd_info *mtd, struct nand_chip *chip,
4168 u8 id_data[8], int *busw)
4171 /* The 3rd id byte holds MLC / multichip data */
4172 chip->bits_per_cell = nand_get_bits_per_cell(id_data[2]);
4173 /* The 4th id byte is the important one */
4176 id_len = nand_id_len(id_data, 8);
4179 * Field definitions are in the following datasheets:
4180 * Old style (4,5 byte ID): Samsung K9GAG08U0M (p.32)
4181 * New Samsung (6 byte ID): Samsung K9GAG08U0F (p.44)
4182 * Hynix MLC (6 byte ID): Hynix H27UBG8T2B (p.22)
4184 * Check for ID length, non-zero 6th byte, cell type, and Hynix/Samsung
4185 * ID to decide what to do.
4187 if (id_len == 6 && id_data[0] == NAND_MFR_SAMSUNG &&
4188 !nand_is_slc(chip) && id_data[5] != 0x00) {
4190 mtd->writesize = 2048 << (extid & 0x03);
4193 switch (((extid >> 2) & 0x04) | (extid & 0x03)) {
4213 default: /* Other cases are "reserved" (unknown) */
4214 mtd->oobsize = 1024;
4218 /* Calc blocksize */
4219 mtd->erasesize = (128 * 1024) <<
4220 (((extid >> 1) & 0x04) | (extid & 0x03));
4222 } else if (id_len == 6 && id_data[0] == NAND_MFR_HYNIX &&
4223 !nand_is_slc(chip)) {
4227 mtd->writesize = 2048 << (extid & 0x03);
4230 switch (((extid >> 2) & 0x04) | (extid & 0x03)) {
4254 /* Calc blocksize */
4255 tmp = ((extid >> 1) & 0x04) | (extid & 0x03);
4257 mtd->erasesize = (128 * 1024) << tmp;
4258 else if (tmp == 0x03)
4259 mtd->erasesize = 768 * 1024;
4261 mtd->erasesize = (64 * 1024) << tmp;
4265 mtd->writesize = 1024 << (extid & 0x03);
4268 mtd->oobsize = (8 << (extid & 0x01)) *
4269 (mtd->writesize >> 9);
4271 /* Calc blocksize. Blocksize is multiples of 64KiB */
4272 mtd->erasesize = (64 * 1024) << (extid & 0x03);
4274 /* Get buswidth information */
4275 *busw = (extid & 0x01) ? NAND_BUSWIDTH_16 : 0;
4278 * Toshiba 24nm raw SLC (i.e., not BENAND) have 32B OOB per
4279 * 512B page. For Toshiba SLC, we decode the 5th/6th byte as
4281 * - ID byte 6, bits[2:0]: 100b -> 43nm, 101b -> 32nm,
4283 * - ID byte 5, bit[7]: 1 -> BENAND, 0 -> raw SLC
4285 if (id_len >= 6 && id_data[0] == NAND_MFR_TOSHIBA &&
4286 nand_is_slc(chip) &&
4287 (id_data[5] & 0x7) == 0x6 /* 24nm */ &&
4288 !(id_data[4] & 0x80) /* !BENAND */) {
4289 mtd->oobsize = 32 * mtd->writesize >> 9;
4296 * Old devices have chip data hardcoded in the device ID table. nand_decode_id
4297 * decodes a matching ID table entry and assigns the MTD size parameters for
4300 static void nand_decode_id(struct mtd_info *mtd, struct nand_chip *chip,
4301 struct nand_flash_dev *type, u8 id_data[8],
4304 int maf_id = id_data[0];
4306 mtd->erasesize = type->erasesize;
4307 mtd->writesize = type->pagesize;
4308 mtd->oobsize = mtd->writesize / 32;
4309 *busw = type->options & NAND_BUSWIDTH_16;
4311 /* All legacy ID NAND are small-page, SLC */
4312 chip->bits_per_cell = 1;
4315 * Check for Spansion/AMD ID + repeating 5th, 6th byte since
4316 * some Spansion chips have erasesize that conflicts with size
4317 * listed in nand_ids table.
4318 * Data sheet (5 byte ID): Spansion S30ML-P ORNAND (p.39)
4320 if (maf_id == NAND_MFR_AMD && id_data[4] != 0x00 && id_data[5] == 0x00
4321 && id_data[6] == 0x00 && id_data[7] == 0x00
4322 && mtd->writesize == 512) {
4323 mtd->erasesize = 128 * 1024;
4324 mtd->erasesize <<= ((id_data[3] & 0x03) << 1);
4329 * Set the bad block marker/indicator (BBM/BBI) patterns according to some
4330 * heuristic patterns using various detected parameters (e.g., manufacturer,
4331 * page size, cell-type information).
4333 static void nand_decode_bbm_options(struct mtd_info *mtd,
4334 struct nand_chip *chip, u8 id_data[8])
4336 int maf_id = id_data[0];
4338 /* Set the bad block position */
4339 if (mtd->writesize > 512 || (chip->options & NAND_BUSWIDTH_16))
4340 chip->badblockpos = NAND_LARGE_BADBLOCK_POS;
4342 chip->badblockpos = NAND_SMALL_BADBLOCK_POS;
4345 * Bad block marker is stored in the last page of each block on Samsung
4346 * and Hynix MLC devices; stored in first two pages of each block on
4347 * Micron devices with 2KiB pages and on SLC Samsung, Hynix, Toshiba,
4348 * AMD/Spansion, and Macronix. All others scan only the first page.
4350 if (!nand_is_slc(chip) &&
4351 (maf_id == NAND_MFR_SAMSUNG ||
4352 maf_id == NAND_MFR_HYNIX))
4353 chip->bbt_options |= NAND_BBT_SCANLASTPAGE;
4354 else if ((nand_is_slc(chip) &&
4355 (maf_id == NAND_MFR_SAMSUNG ||
4356 maf_id == NAND_MFR_HYNIX ||
4357 maf_id == NAND_MFR_TOSHIBA ||
4358 maf_id == NAND_MFR_AMD ||
4359 maf_id == NAND_MFR_MACRONIX)) ||
4360 (mtd->writesize == 2048 &&
4361 maf_id == NAND_MFR_MICRON))
4362 chip->bbt_options |= NAND_BBT_SCAN2NDPAGE;
4365 static inline bool is_full_id_nand(struct nand_flash_dev *type)
4367 return type->id_len;
4370 static bool find_full_id_nand(struct mtd_info *mtd, struct nand_chip *chip,
4371 struct nand_flash_dev *type, u8 *id_data, int *busw)
4373 if (!strncmp((char *)type->id, (char *)id_data, type->id_len)) {
4374 mtd->writesize = type->pagesize;
4375 mtd->erasesize = type->erasesize;
4376 mtd->oobsize = type->oobsize;
4378 chip->bits_per_cell = nand_get_bits_per_cell(id_data[2]);
4379 chip->chipsize = (uint64_t)type->chipsize << 20;
4380 chip->options |= type->options;
4381 chip->ecc_strength_ds = NAND_ECC_STRENGTH(type);
4382 chip->ecc_step_ds = NAND_ECC_STEP(type);
4383 chip->onfi_timing_mode_default =
4384 type->onfi_timing_mode_default;
4386 *busw = type->options & NAND_BUSWIDTH_16;
4389 mtd->name = type->name;
4397 * Get the flash and manufacturer id and lookup if the type is supported.
4399 struct nand_flash_dev *nand_get_flash_type(struct mtd_info *mtd,
4400 struct nand_chip *chip,
4401 int *maf_id, int *dev_id,
4402 struct nand_flash_dev *type)
4409 * Reset the chip, required by some chips (e.g. Micron MT29FxGxxxxx)
4412 ret = nand_reset(chip, 0);
4414 return ERR_PTR(ret);
4416 /* Select the device */
4417 chip->select_chip(mtd, 0);
4419 /* Send the command for reading device ID */
4420 ret = nand_readid_op(chip, 0, id_data, 2);
4422 return ERR_PTR(ret);
4424 /* Read manufacturer and device IDs */
4425 *maf_id = id_data[0];
4426 *dev_id = id_data[1];
4429 * Try again to make sure, as some systems the bus-hold or other
4430 * interface concerns can cause random data which looks like a
4431 * possibly credible NAND flash to appear. If the two results do
4432 * not match, ignore the device completely.
4435 /* Read entire ID string */
4436 ret = nand_readid_op(chip, 0, id_data, 8);
4438 return ERR_PTR(ret);
4440 if (id_data[0] != *maf_id || id_data[1] != *dev_id) {
4441 pr_info("second ID read did not match %02x,%02x against %02x,%02x\n",
4442 *maf_id, *dev_id, id_data[0], id_data[1]);
4443 return ERR_PTR(-ENODEV);
4447 type = nand_flash_ids;
4449 for (; type->name != NULL; type++) {
4450 if (is_full_id_nand(type)) {
4451 if (find_full_id_nand(mtd, chip, type, id_data, &busw))
4453 } else if (*dev_id == type->dev_id) {
4458 chip->onfi_version = 0;
4459 if (!type->name || !type->pagesize) {
4460 /* Check if the chip is ONFI compliant */
4461 if (nand_flash_detect_onfi(mtd, chip, &busw))
4464 /* Check if the chip is JEDEC compliant */
4465 if (nand_flash_detect_jedec(mtd, chip, &busw))
4470 return ERR_PTR(-ENODEV);
4473 mtd->name = type->name;
4475 chip->chipsize = (uint64_t)type->chipsize << 20;
4477 if (!type->pagesize) {
4478 /* Decode parameters from extended ID */
4479 nand_decode_ext_id(mtd, chip, id_data, &busw);
4481 nand_decode_id(mtd, chip, type, id_data, &busw);
4483 /* Get chip options */
4484 chip->options |= type->options;
4487 * Check if chip is not a Samsung device. Do not clear the
4488 * options for chips which do not have an extended id.
4490 if (*maf_id != NAND_MFR_SAMSUNG && !type->pagesize)
4491 chip->options &= ~NAND_SAMSUNG_LP_OPTIONS;
4494 /* Try to identify manufacturer */
4495 for (maf_idx = 0; nand_manuf_ids[maf_idx].id != 0x0; maf_idx++) {
4496 if (nand_manuf_ids[maf_idx].id == *maf_id)
4500 if (chip->options & NAND_BUSWIDTH_AUTO) {
4501 WARN_ON(chip->options & NAND_BUSWIDTH_16);
4502 chip->options |= busw;
4503 nand_set_defaults(chip, busw);
4504 } else if (busw != (chip->options & NAND_BUSWIDTH_16)) {
4506 * Check, if buswidth is correct. Hardware drivers should set
4509 pr_info("device found, Manufacturer ID: 0x%02x, Chip ID: 0x%02x\n",
4511 pr_info("%s %s\n", nand_manuf_ids[maf_idx].name, mtd->name);
4512 pr_warn("bus width %d instead %d bit\n",
4513 (chip->options & NAND_BUSWIDTH_16) ? 16 : 8,
4515 return ERR_PTR(-EINVAL);
4518 nand_decode_bbm_options(mtd, chip, id_data);
4520 /* Calculate the address shift from the page size */
4521 chip->page_shift = ffs(mtd->writesize) - 1;
4522 /* Convert chipsize to number of pages per chip -1 */
4523 chip->pagemask = (chip->chipsize >> chip->page_shift) - 1;
4525 chip->bbt_erase_shift = chip->phys_erase_shift =
4526 ffs(mtd->erasesize) - 1;
4527 if (chip->chipsize & 0xffffffff)
4528 chip->chip_shift = ffs((unsigned)chip->chipsize) - 1;
4530 chip->chip_shift = ffs((unsigned)(chip->chipsize >> 32));
4531 chip->chip_shift += 32 - 1;
4534 if (chip->chip_shift - chip->page_shift > 16)
4535 chip->options |= NAND_ROW_ADDR_3;
4537 chip->badblockbits = 8;
4538 chip->erase = single_erase;
4540 /* Do not replace user supplied command function! */
4541 if (mtd->writesize > 512 && chip->cmdfunc == nand_command)
4542 chip->cmdfunc = nand_command_lp;
4544 pr_info("device found, Manufacturer ID: 0x%02x, Chip ID: 0x%02x\n",
4547 #ifdef CONFIG_SYS_NAND_ONFI_DETECTION
4548 if (chip->onfi_version)
4549 pr_info("%s %s\n", nand_manuf_ids[maf_idx].name,
4550 chip->onfi_params.model);
4551 else if (chip->jedec_version)
4552 pr_info("%s %s\n", nand_manuf_ids[maf_idx].name,
4553 chip->jedec_params.model);
4555 pr_info("%s %s\n", nand_manuf_ids[maf_idx].name,
4558 if (chip->jedec_version)
4559 pr_info("%s %s\n", nand_manuf_ids[maf_idx].name,
4560 chip->jedec_params.model);
4562 pr_info("%s %s\n", nand_manuf_ids[maf_idx].name,
4565 pr_info("%s %s\n", nand_manuf_ids[maf_idx].name,
4569 pr_info("%d MiB, %s, erase size: %d KiB, page size: %d, OOB size: %d\n",
4570 (int)(chip->chipsize >> 20), nand_is_slc(chip) ? "SLC" : "MLC",
4571 mtd->erasesize >> 10, mtd->writesize, mtd->oobsize);
4574 EXPORT_SYMBOL(nand_get_flash_type);
4576 #if CONFIG_IS_ENABLED(OF_CONTROL)
4577 DECLARE_GLOBAL_DATA_PTR;
4579 static int nand_dt_init(struct mtd_info *mtd, struct nand_chip *chip, int node)
4581 int ret, ecc_mode = -1, ecc_strength, ecc_step;
4582 const void *blob = gd->fdt_blob;
4585 ret = fdtdec_get_int(blob, node, "nand-bus-width", -1);
4587 chip->options |= NAND_BUSWIDTH_16;
4589 if (fdtdec_get_bool(blob, node, "nand-on-flash-bbt"))
4590 chip->bbt_options |= NAND_BBT_USE_FLASH;
4592 str = fdt_getprop(blob, node, "nand-ecc-mode", NULL);
4594 if (!strcmp(str, "none"))
4595 ecc_mode = NAND_ECC_NONE;
4596 else if (!strcmp(str, "soft"))
4597 ecc_mode = NAND_ECC_SOFT;
4598 else if (!strcmp(str, "hw"))
4599 ecc_mode = NAND_ECC_HW;
4600 else if (!strcmp(str, "hw_syndrome"))
4601 ecc_mode = NAND_ECC_HW_SYNDROME;
4602 else if (!strcmp(str, "hw_oob_first"))
4603 ecc_mode = NAND_ECC_HW_OOB_FIRST;
4604 else if (!strcmp(str, "soft_bch"))
4605 ecc_mode = NAND_ECC_SOFT_BCH;
4609 ecc_strength = fdtdec_get_int(blob, node, "nand-ecc-strength", -1);
4610 ecc_step = fdtdec_get_int(blob, node, "nand-ecc-step-size", -1);
4612 if ((ecc_step >= 0 && !(ecc_strength >= 0)) ||
4613 (!(ecc_step >= 0) && ecc_strength >= 0)) {
4614 pr_err("must set both strength and step size in DT\n");
4619 chip->ecc.mode = ecc_mode;
4621 if (ecc_strength >= 0)
4622 chip->ecc.strength = ecc_strength;
4625 chip->ecc.size = ecc_step;
4627 if (fdt_getprop(blob, node, "nand-ecc-maximize", NULL))
4628 chip->ecc.options |= NAND_ECC_MAXIMIZE;
4633 static int nand_dt_init(struct mtd_info *mtd, struct nand_chip *chip, int node)
4637 #endif /* CONFIG_IS_ENABLED(OF_CONTROL) */
4640 * nand_scan_ident - [NAND Interface] Scan for the NAND device
4641 * @mtd: MTD device structure
4642 * @maxchips: number of chips to scan for
4643 * @table: alternative NAND ID table
4645 * This is the first phase of the normal nand_scan() function. It reads the
4646 * flash ID and sets up MTD fields accordingly.
4649 int nand_scan_ident(struct mtd_info *mtd, int maxchips,
4650 struct nand_flash_dev *table)
4652 int i, nand_maf_id, nand_dev_id;
4653 struct nand_chip *chip = mtd_to_nand(mtd);
4654 struct nand_flash_dev *type;
4657 if (chip->flash_node) {
4658 ret = nand_dt_init(mtd, chip, chip->flash_node);
4663 /* Set the default functions */
4664 nand_set_defaults(chip, chip->options & NAND_BUSWIDTH_16);
4666 /* Read the flash type */
4667 type = nand_get_flash_type(mtd, chip, &nand_maf_id,
4668 &nand_dev_id, table);
4671 if (!(chip->options & NAND_SCAN_SILENT_NODEV))
4672 pr_warn("No NAND device found\n");
4673 chip->select_chip(mtd, -1);
4674 return PTR_ERR(type);
4677 /* Initialize the ->data_interface field. */
4678 ret = nand_init_data_interface(chip);
4683 * Setup the data interface correctly on the chip and controller side.
4684 * This explicit call to nand_setup_data_interface() is only required
4685 * for the first die, because nand_reset() has been called before
4686 * ->data_interface and ->default_onfi_timing_mode were set.
4687 * For the other dies, nand_reset() will automatically switch to the
4690 ret = nand_setup_data_interface(chip, 0);
4694 chip->select_chip(mtd, -1);
4696 /* Check for a chip array */
4697 for (i = 1; i < maxchips; i++) {
4700 /* See comment in nand_get_flash_type for reset */
4701 nand_reset(chip, i);
4703 chip->select_chip(mtd, i);
4704 /* Send the command for reading device ID */
4705 nand_readid_op(chip, 0, id, sizeof(id));
4707 /* Read manufacturer and device IDs */
4708 if (nand_maf_id != id[0] || nand_dev_id != id[1]) {
4709 chip->select_chip(mtd, -1);
4712 chip->select_chip(mtd, -1);
4717 pr_info("%d chips detected\n", i);
4720 /* Store the number of chips and calc total size for mtd */
4722 mtd->size = i * chip->chipsize;
4726 EXPORT_SYMBOL(nand_scan_ident);
4729 * nand_check_ecc_caps - check the sanity of preset ECC settings
4730 * @chip: nand chip info structure
4731 * @caps: ECC caps info structure
4732 * @oobavail: OOB size that the ECC engine can use
4734 * When ECC step size and strength are already set, check if they are supported
4735 * by the controller and the calculated ECC bytes fit within the chip's OOB.
4736 * On success, the calculated ECC bytes is set.
4738 int nand_check_ecc_caps(struct nand_chip *chip,
4739 const struct nand_ecc_caps *caps, int oobavail)
4741 struct mtd_info *mtd = nand_to_mtd(chip);
4742 const struct nand_ecc_step_info *stepinfo;
4743 int preset_step = chip->ecc.size;
4744 int preset_strength = chip->ecc.strength;
4745 int nsteps, ecc_bytes;
4748 if (WARN_ON(oobavail < 0))
4751 if (!preset_step || !preset_strength)
4754 nsteps = mtd->writesize / preset_step;
4756 for (i = 0; i < caps->nstepinfos; i++) {
4757 stepinfo = &caps->stepinfos[i];
4759 if (stepinfo->stepsize != preset_step)
4762 for (j = 0; j < stepinfo->nstrengths; j++) {
4763 if (stepinfo->strengths[j] != preset_strength)
4766 ecc_bytes = caps->calc_ecc_bytes(preset_step,
4768 if (WARN_ON_ONCE(ecc_bytes < 0))
4771 if (ecc_bytes * nsteps > oobavail) {
4772 pr_err("ECC (step, strength) = (%d, %d) does not fit in OOB",
4773 preset_step, preset_strength);
4777 chip->ecc.bytes = ecc_bytes;
4783 pr_err("ECC (step, strength) = (%d, %d) not supported on this controller",
4784 preset_step, preset_strength);
4788 EXPORT_SYMBOL_GPL(nand_check_ecc_caps);
4791 * nand_match_ecc_req - meet the chip's requirement with least ECC bytes
4792 * @chip: nand chip info structure
4793 * @caps: ECC engine caps info structure
4794 * @oobavail: OOB size that the ECC engine can use
4796 * If a chip's ECC requirement is provided, try to meet it with the least
4797 * number of ECC bytes (i.e. with the largest number of OOB-free bytes).
4798 * On success, the chosen ECC settings are set.
4800 int nand_match_ecc_req(struct nand_chip *chip,
4801 const struct nand_ecc_caps *caps, int oobavail)
4803 struct mtd_info *mtd = nand_to_mtd(chip);
4804 const struct nand_ecc_step_info *stepinfo;
4805 int req_step = chip->ecc_step_ds;
4806 int req_strength = chip->ecc_strength_ds;
4807 int req_corr, step_size, strength, nsteps, ecc_bytes, ecc_bytes_total;
4808 int best_step, best_strength, best_ecc_bytes;
4809 int best_ecc_bytes_total = INT_MAX;
4812 if (WARN_ON(oobavail < 0))
4815 /* No information provided by the NAND chip */
4816 if (!req_step || !req_strength)
4819 /* number of correctable bits the chip requires in a page */
4820 req_corr = mtd->writesize / req_step * req_strength;
4822 for (i = 0; i < caps->nstepinfos; i++) {
4823 stepinfo = &caps->stepinfos[i];
4824 step_size = stepinfo->stepsize;
4826 for (j = 0; j < stepinfo->nstrengths; j++) {
4827 strength = stepinfo->strengths[j];
4830 * If both step size and strength are smaller than the
4831 * chip's requirement, it is not easy to compare the
4832 * resulted reliability.
4834 if (step_size < req_step && strength < req_strength)
4837 if (mtd->writesize % step_size)
4840 nsteps = mtd->writesize / step_size;
4842 ecc_bytes = caps->calc_ecc_bytes(step_size, strength);
4843 if (WARN_ON_ONCE(ecc_bytes < 0))
4845 ecc_bytes_total = ecc_bytes * nsteps;
4847 if (ecc_bytes_total > oobavail ||
4848 strength * nsteps < req_corr)
4852 * We assume the best is to meet the chip's requrement
4853 * with the least number of ECC bytes.
4855 if (ecc_bytes_total < best_ecc_bytes_total) {
4856 best_ecc_bytes_total = ecc_bytes_total;
4857 best_step = step_size;
4858 best_strength = strength;
4859 best_ecc_bytes = ecc_bytes;
4864 if (best_ecc_bytes_total == INT_MAX)
4867 chip->ecc.size = best_step;
4868 chip->ecc.strength = best_strength;
4869 chip->ecc.bytes = best_ecc_bytes;
4873 EXPORT_SYMBOL_GPL(nand_match_ecc_req);
4876 * nand_maximize_ecc - choose the max ECC strength available
4877 * @chip: nand chip info structure
4878 * @caps: ECC engine caps info structure
4879 * @oobavail: OOB size that the ECC engine can use
4881 * Choose the max ECC strength that is supported on the controller, and can fit
4882 * within the chip's OOB. On success, the chosen ECC settings are set.
4884 int nand_maximize_ecc(struct nand_chip *chip,
4885 const struct nand_ecc_caps *caps, int oobavail)
4887 struct mtd_info *mtd = nand_to_mtd(chip);
4888 const struct nand_ecc_step_info *stepinfo;
4889 int step_size, strength, nsteps, ecc_bytes, corr;
4892 int best_strength, best_ecc_bytes;
4895 if (WARN_ON(oobavail < 0))
4898 for (i = 0; i < caps->nstepinfos; i++) {
4899 stepinfo = &caps->stepinfos[i];
4900 step_size = stepinfo->stepsize;
4902 /* If chip->ecc.size is already set, respect it */
4903 if (chip->ecc.size && step_size != chip->ecc.size)
4906 for (j = 0; j < stepinfo->nstrengths; j++) {
4907 strength = stepinfo->strengths[j];
4909 if (mtd->writesize % step_size)
4912 nsteps = mtd->writesize / step_size;
4914 ecc_bytes = caps->calc_ecc_bytes(step_size, strength);
4915 if (WARN_ON_ONCE(ecc_bytes < 0))
4918 if (ecc_bytes * nsteps > oobavail)
4921 corr = strength * nsteps;
4924 * If the number of correctable bits is the same,
4925 * bigger step_size has more reliability.
4927 if (corr > best_corr ||
4928 (corr == best_corr && step_size > best_step)) {
4930 best_step = step_size;
4931 best_strength = strength;
4932 best_ecc_bytes = ecc_bytes;
4940 chip->ecc.size = best_step;
4941 chip->ecc.strength = best_strength;
4942 chip->ecc.bytes = best_ecc_bytes;
4946 EXPORT_SYMBOL_GPL(nand_maximize_ecc);
4949 * Check if the chip configuration meet the datasheet requirements.
4951 * If our configuration corrects A bits per B bytes and the minimum
4952 * required correction level is X bits per Y bytes, then we must ensure
4953 * both of the following are true:
4955 * (1) A / B >= X / Y
4958 * Requirement (1) ensures we can correct for the required bitflip density.
4959 * Requirement (2) ensures we can correct even when all bitflips are clumped
4960 * in the same sector.
4962 static bool nand_ecc_strength_good(struct mtd_info *mtd)
4964 struct nand_chip *chip = mtd_to_nand(mtd);
4965 struct nand_ecc_ctrl *ecc = &chip->ecc;
4968 if (ecc->size == 0 || chip->ecc_step_ds == 0)
4969 /* Not enough information */
4973 * We get the number of corrected bits per page to compare
4974 * the correction density.
4976 corr = (mtd->writesize * ecc->strength) / ecc->size;
4977 ds_corr = (mtd->writesize * chip->ecc_strength_ds) / chip->ecc_step_ds;
4979 return corr >= ds_corr && ecc->strength >= chip->ecc_strength_ds;
4982 static bool invalid_ecc_page_accessors(struct nand_chip *chip)
4984 struct nand_ecc_ctrl *ecc = &chip->ecc;
4986 if (nand_standard_page_accessors(ecc))
4990 * NAND_ECC_CUSTOM_PAGE_ACCESS flag is set, make sure the NAND
4991 * controller driver implements all the page accessors because
4992 * default helpers are not suitable when the core does not
4993 * send the READ0/PAGEPROG commands.
4995 return (!ecc->read_page || !ecc->write_page ||
4996 !ecc->read_page_raw || !ecc->write_page_raw ||
4997 (NAND_HAS_SUBPAGE_READ(chip) && !ecc->read_subpage) ||
4998 (NAND_HAS_SUBPAGE_WRITE(chip) && !ecc->write_subpage &&
4999 ecc->hwctl && ecc->calculate));
5003 * nand_scan_tail - [NAND Interface] Scan for the NAND device
5004 * @mtd: MTD device structure
5006 * This is the second phase of the normal nand_scan() function. It fills out
5007 * all the uninitialized function pointers with the defaults and scans for a
5008 * bad block table if appropriate.
5010 int nand_scan_tail(struct mtd_info *mtd)
5013 struct nand_chip *chip = mtd_to_nand(mtd);
5014 struct nand_ecc_ctrl *ecc = &chip->ecc;
5015 struct nand_buffers *nbuf;
5017 /* New bad blocks should be marked in OOB, flash-based BBT, or both */
5018 BUG_ON((chip->bbt_options & NAND_BBT_NO_OOB_BBM) &&
5019 !(chip->bbt_options & NAND_BBT_USE_FLASH));
5021 if (invalid_ecc_page_accessors(chip)) {
5022 pr_err("Invalid ECC page accessors setup\n");
5026 if (!(chip->options & NAND_OWN_BUFFERS)) {
5027 nbuf = kzalloc(sizeof(struct nand_buffers), GFP_KERNEL);
5028 chip->buffers = nbuf;
5034 /* Set the internal oob buffer location, just after the page data */
5035 chip->oob_poi = chip->buffers->databuf + mtd->writesize;
5038 * If no default placement scheme is given, select an appropriate one.
5040 if (!ecc->layout && (ecc->mode != NAND_ECC_SOFT_BCH)) {
5041 switch (mtd->oobsize) {
5042 #ifndef CONFIG_SYS_NAND_DRIVER_ECC_LAYOUT
5044 ecc->layout = &nand_oob_8;
5047 ecc->layout = &nand_oob_16;
5050 ecc->layout = &nand_oob_64;
5053 ecc->layout = &nand_oob_128;
5057 pr_warn("No oob scheme defined for oobsize %d\n",
5063 if (!chip->write_page)
5064 chip->write_page = nand_write_page;
5067 * Check ECC mode, default to software if 3byte/512byte hardware ECC is
5068 * selected and we have 256 byte pagesize fallback to software ECC
5071 switch (ecc->mode) {
5072 case NAND_ECC_HW_OOB_FIRST:
5073 /* Similar to NAND_ECC_HW, but a separate read_page handle */
5074 if (!ecc->calculate || !ecc->correct || !ecc->hwctl) {
5075 pr_warn("No ECC functions supplied; hardware ECC not possible\n");
5078 if (!ecc->read_page)
5079 ecc->read_page = nand_read_page_hwecc_oob_first;
5082 /* Use standard hwecc read page function? */
5083 if (!ecc->read_page)
5084 ecc->read_page = nand_read_page_hwecc;
5085 if (!ecc->write_page)
5086 ecc->write_page = nand_write_page_hwecc;
5087 if (!ecc->read_page_raw)
5088 ecc->read_page_raw = nand_read_page_raw;
5089 if (!ecc->write_page_raw)
5090 ecc->write_page_raw = nand_write_page_raw;
5092 ecc->read_oob = nand_read_oob_std;
5093 if (!ecc->write_oob)
5094 ecc->write_oob = nand_write_oob_std;
5095 if (!ecc->read_subpage)
5096 ecc->read_subpage = nand_read_subpage;
5097 if (!ecc->write_subpage && ecc->hwctl && ecc->calculate)
5098 ecc->write_subpage = nand_write_subpage_hwecc;
5100 case NAND_ECC_HW_SYNDROME:
5101 if ((!ecc->calculate || !ecc->correct || !ecc->hwctl) &&
5103 ecc->read_page == nand_read_page_hwecc ||
5105 ecc->write_page == nand_write_page_hwecc)) {
5106 pr_warn("No ECC functions supplied; hardware ECC not possible\n");
5109 /* Use standard syndrome read/write page function? */
5110 if (!ecc->read_page)
5111 ecc->read_page = nand_read_page_syndrome;
5112 if (!ecc->write_page)
5113 ecc->write_page = nand_write_page_syndrome;
5114 if (!ecc->read_page_raw)
5115 ecc->read_page_raw = nand_read_page_raw_syndrome;
5116 if (!ecc->write_page_raw)
5117 ecc->write_page_raw = nand_write_page_raw_syndrome;
5119 ecc->read_oob = nand_read_oob_syndrome;
5120 if (!ecc->write_oob)
5121 ecc->write_oob = nand_write_oob_syndrome;
5123 if (mtd->writesize >= ecc->size) {
5124 if (!ecc->strength) {
5125 pr_warn("Driver must set ecc.strength when using hardware ECC\n");
5130 pr_warn("%d byte HW ECC not possible on %d byte page size, fallback to SW ECC\n",
5131 ecc->size, mtd->writesize);
5132 ecc->mode = NAND_ECC_SOFT;
5135 ecc->calculate = nand_calculate_ecc;
5136 ecc->correct = nand_correct_data;
5137 ecc->read_page = nand_read_page_swecc;
5138 ecc->read_subpage = nand_read_subpage;
5139 ecc->write_page = nand_write_page_swecc;
5140 ecc->read_page_raw = nand_read_page_raw;
5141 ecc->write_page_raw = nand_write_page_raw;
5142 ecc->read_oob = nand_read_oob_std;
5143 ecc->write_oob = nand_write_oob_std;
5150 case NAND_ECC_SOFT_BCH:
5151 if (!mtd_nand_has_bch()) {
5152 pr_warn("CONFIG_MTD_NAND_ECC_BCH not enabled\n");
5155 ecc->calculate = nand_bch_calculate_ecc;
5156 ecc->correct = nand_bch_correct_data;
5157 ecc->read_page = nand_read_page_swecc;
5158 ecc->read_subpage = nand_read_subpage;
5159 ecc->write_page = nand_write_page_swecc;
5160 ecc->read_page_raw = nand_read_page_raw;
5161 ecc->write_page_raw = nand_write_page_raw;
5162 ecc->read_oob = nand_read_oob_std;
5163 ecc->write_oob = nand_write_oob_std;
5165 * Board driver should supply ecc.size and ecc.strength values
5166 * to select how many bits are correctable. Otherwise, default
5167 * to 4 bits for large page devices.
5169 if (!ecc->size && (mtd->oobsize >= 64)) {
5174 /* See nand_bch_init() for details. */
5176 ecc->priv = nand_bch_init(mtd);
5178 pr_warn("BCH ECC initialization failed!\n");
5184 pr_warn("NAND_ECC_NONE selected by board driver. This is not recommended!\n");
5185 ecc->read_page = nand_read_page_raw;
5186 ecc->write_page = nand_write_page_raw;
5187 ecc->read_oob = nand_read_oob_std;
5188 ecc->read_page_raw = nand_read_page_raw;
5189 ecc->write_page_raw = nand_write_page_raw;
5190 ecc->write_oob = nand_write_oob_std;
5191 ecc->size = mtd->writesize;
5197 pr_warn("Invalid NAND_ECC_MODE %d\n", ecc->mode);
5201 /* For many systems, the standard OOB write also works for raw */
5202 if (!ecc->read_oob_raw)
5203 ecc->read_oob_raw = ecc->read_oob;
5204 if (!ecc->write_oob_raw)
5205 ecc->write_oob_raw = ecc->write_oob;
5208 * The number of bytes available for a client to place data into
5209 * the out of band area.
5213 for (i = 0; ecc->layout->oobfree[i].length; i++)
5214 mtd->oobavail += ecc->layout->oobfree[i].length;
5217 /* ECC sanity check: warn if it's too weak */
5218 if (!nand_ecc_strength_good(mtd))
5219 pr_warn("WARNING: %s: the ECC used on your system is too weak compared to the one required by the NAND chip\n",
5223 * Set the number of read / write steps for one page depending on ECC
5226 ecc->steps = mtd->writesize / ecc->size;
5227 if (ecc->steps * ecc->size != mtd->writesize) {
5228 pr_warn("Invalid ECC parameters\n");
5231 ecc->total = ecc->steps * ecc->bytes;
5233 /* Allow subpage writes up to ecc.steps. Not possible for MLC flash */
5234 if (!(chip->options & NAND_NO_SUBPAGE_WRITE) && nand_is_slc(chip)) {
5235 switch (ecc->steps) {
5237 mtd->subpage_sft = 1;
5242 mtd->subpage_sft = 2;
5246 chip->subpagesize = mtd->writesize >> mtd->subpage_sft;
5248 /* Initialize state */
5249 chip->state = FL_READY;
5251 /* Invalidate the pagebuffer reference */
5254 /* Large page NAND with SOFT_ECC should support subpage reads */
5255 switch (ecc->mode) {
5257 case NAND_ECC_SOFT_BCH:
5258 if (chip->page_shift > 9)
5259 chip->options |= NAND_SUBPAGE_READ;
5266 /* Fill in remaining MTD driver data */
5267 mtd->type = nand_is_slc(chip) ? MTD_NANDFLASH : MTD_MLCNANDFLASH;
5268 mtd->flags = (chip->options & NAND_ROM) ? MTD_CAP_ROM :
5270 mtd->_erase = nand_erase;
5271 mtd->_panic_write = panic_nand_write;
5272 mtd->_read_oob = nand_read_oob;
5273 mtd->_write_oob = nand_write_oob;
5274 mtd->_sync = nand_sync;
5276 mtd->_unlock = NULL;
5277 mtd->_block_isreserved = nand_block_isreserved;
5278 mtd->_block_isbad = nand_block_isbad;
5279 mtd->_block_markbad = nand_block_markbad;
5280 mtd->writebufsize = mtd->writesize;
5282 /* propagate ecc info to mtd_info */
5283 mtd->ecclayout = ecc->layout;
5284 mtd->ecc_strength = ecc->strength;
5285 mtd->ecc_step_size = ecc->size;
5287 * Initialize bitflip_threshold to its default prior scan_bbt() call.
5288 * scan_bbt() might invoke mtd_read(), thus bitflip_threshold must be
5291 if (!mtd->bitflip_threshold)
5292 mtd->bitflip_threshold = DIV_ROUND_UP(mtd->ecc_strength * 3, 4);
5296 EXPORT_SYMBOL(nand_scan_tail);
5299 * nand_scan - [NAND Interface] Scan for the NAND device
5300 * @mtd: MTD device structure
5301 * @maxchips: number of chips to scan for
5303 * This fills out all the uninitialized function pointers with the defaults.
5304 * The flash ID is read and the mtd/chip structures are filled with the
5305 * appropriate values.
5307 int nand_scan(struct mtd_info *mtd, int maxchips)
5311 ret = nand_scan_ident(mtd, maxchips, NULL);
5313 ret = nand_scan_tail(mtd);
5316 EXPORT_SYMBOL(nand_scan);
5318 MODULE_LICENSE("GPL");
5319 MODULE_AUTHOR("Steven J. Hill <sjhill@realitydiluted.com>");
5320 MODULE_AUTHOR("Thomas Gleixner <tglx@linutronix.de>");
5321 MODULE_DESCRIPTION("Generic NAND flash driver code");