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
35 #include <dm/devres.h>
36 #include <linux/bitops.h>
37 #include <linux/bug.h>
38 #include <linux/delay.h>
39 #include <linux/err.h>
40 #include <linux/compat.h>
41 #include <linux/mtd/mtd.h>
42 #include <linux/mtd/rawnand.h>
43 #include <linux/mtd/nand_ecc.h>
44 #include <linux/mtd/nand_bch.h>
45 #ifdef CONFIG_MTD_PARTITIONS
46 #include <linux/mtd/partitions.h>
49 #include <linux/errno.h>
51 /* Define default oob placement schemes for large and small page devices */
52 #ifndef CONFIG_SYS_NAND_DRIVER_ECC_LAYOUT
53 static struct nand_ecclayout nand_oob_8 = {
63 static struct nand_ecclayout nand_oob_16 = {
65 .eccpos = {0, 1, 2, 3, 6, 7},
71 static struct nand_ecclayout nand_oob_64 = {
74 40, 41, 42, 43, 44, 45, 46, 47,
75 48, 49, 50, 51, 52, 53, 54, 55,
76 56, 57, 58, 59, 60, 61, 62, 63},
82 static struct nand_ecclayout nand_oob_128 = {
85 80, 81, 82, 83, 84, 85, 86, 87,
86 88, 89, 90, 91, 92, 93, 94, 95,
87 96, 97, 98, 99, 100, 101, 102, 103,
88 104, 105, 106, 107, 108, 109, 110, 111,
89 112, 113, 114, 115, 116, 117, 118, 119,
90 120, 121, 122, 123, 124, 125, 126, 127},
97 static int nand_get_device(struct mtd_info *mtd, int new_state);
99 static int nand_do_write_oob(struct mtd_info *mtd, loff_t to,
100 struct mtd_oob_ops *ops);
103 * For devices which display every fart in the system on a separate LED. Is
104 * compiled away when LED support is disabled.
106 DEFINE_LED_TRIGGER(nand_led_trigger);
108 static int check_offs_len(struct mtd_info *mtd,
109 loff_t ofs, uint64_t len)
111 struct nand_chip *chip = mtd_to_nand(mtd);
114 /* Start address must align on block boundary */
115 if (ofs & ((1ULL << chip->phys_erase_shift) - 1)) {
116 pr_debug("%s: unaligned address\n", __func__);
120 /* Length must align on block boundary */
121 if (len & ((1ULL << chip->phys_erase_shift) - 1)) {
122 pr_debug("%s: length not block aligned\n", __func__);
130 * nand_release_device - [GENERIC] release chip
131 * @mtd: MTD device structure
133 * Release chip lock and wake up anyone waiting on the device.
135 static void nand_release_device(struct mtd_info *mtd)
137 struct nand_chip *chip = mtd_to_nand(mtd);
139 /* De-select the NAND device */
140 chip->select_chip(mtd, -1);
144 * nand_read_byte - [DEFAULT] read one byte from the chip
145 * @mtd: MTD device structure
147 * Default read function for 8bit buswidth
149 uint8_t nand_read_byte(struct mtd_info *mtd)
151 struct nand_chip *chip = mtd_to_nand(mtd);
152 return readb(chip->IO_ADDR_R);
156 * nand_read_byte16 - [DEFAULT] read one byte endianness aware from the chip
157 * @mtd: MTD device structure
159 * Default read function for 16bit buswidth with endianness conversion.
162 static uint8_t nand_read_byte16(struct mtd_info *mtd)
164 struct nand_chip *chip = mtd_to_nand(mtd);
165 return (uint8_t) cpu_to_le16(readw(chip->IO_ADDR_R));
169 * nand_read_word - [DEFAULT] read one word from the chip
170 * @mtd: MTD device structure
172 * Default read function for 16bit buswidth without endianness conversion.
174 static u16 nand_read_word(struct mtd_info *mtd)
176 struct nand_chip *chip = mtd_to_nand(mtd);
177 return readw(chip->IO_ADDR_R);
181 * nand_select_chip - [DEFAULT] control CE line
182 * @mtd: MTD device structure
183 * @chipnr: chipnumber to select, -1 for deselect
185 * Default select function for 1 chip devices.
187 static void nand_select_chip(struct mtd_info *mtd, int chipnr)
189 struct nand_chip *chip = mtd_to_nand(mtd);
193 chip->cmd_ctrl(mtd, NAND_CMD_NONE, 0 | NAND_CTRL_CHANGE);
204 * nand_write_byte - [DEFAULT] write single byte to chip
205 * @mtd: MTD device structure
206 * @byte: value to write
208 * Default function to write a byte to I/O[7:0]
210 static void nand_write_byte(struct mtd_info *mtd, uint8_t byte)
212 struct nand_chip *chip = mtd_to_nand(mtd);
214 chip->write_buf(mtd, &byte, 1);
218 * nand_write_byte16 - [DEFAULT] write single byte to a chip with width 16
219 * @mtd: MTD device structure
220 * @byte: value to write
222 * Default function to write a byte to I/O[7:0] on a 16-bit wide chip.
224 static void nand_write_byte16(struct mtd_info *mtd, uint8_t byte)
226 struct nand_chip *chip = mtd_to_nand(mtd);
227 uint16_t word = byte;
230 * It's not entirely clear what should happen to I/O[15:8] when writing
231 * a byte. The ONFi spec (Revision 3.1; 2012-09-19, Section 2.16) reads:
233 * When the host supports a 16-bit bus width, only data is
234 * transferred at the 16-bit width. All address and command line
235 * transfers shall use only the lower 8-bits of the data bus. During
236 * command transfers, the host may place any value on the upper
237 * 8-bits of the data bus. During address transfers, the host shall
238 * set the upper 8-bits of the data bus to 00h.
240 * One user of the write_byte callback is nand_onfi_set_features. The
241 * four parameters are specified to be written to I/O[7:0], but this is
242 * neither an address nor a command transfer. Let's assume a 0 on the
243 * upper I/O lines is OK.
245 chip->write_buf(mtd, (uint8_t *)&word, 2);
248 static void iowrite8_rep(void *addr, const uint8_t *buf, int len)
252 for (i = 0; i < len; i++)
253 writeb(buf[i], addr);
255 static void ioread8_rep(void *addr, uint8_t *buf, int len)
259 for (i = 0; i < len; i++)
260 buf[i] = readb(addr);
263 static void ioread16_rep(void *addr, void *buf, int len)
266 u16 *p = (u16 *) buf;
268 for (i = 0; i < len; i++)
272 static void iowrite16_rep(void *addr, void *buf, int len)
275 u16 *p = (u16 *) buf;
277 for (i = 0; i < len; i++)
282 * nand_write_buf - [DEFAULT] write buffer to chip
283 * @mtd: MTD device structure
285 * @len: number of bytes to write
287 * Default write function for 8bit buswidth.
289 void nand_write_buf(struct mtd_info *mtd, const uint8_t *buf, int len)
291 struct nand_chip *chip = mtd_to_nand(mtd);
293 iowrite8_rep(chip->IO_ADDR_W, buf, len);
297 * nand_read_buf - [DEFAULT] read chip data into buffer
298 * @mtd: MTD device structure
299 * @buf: buffer to store date
300 * @len: number of bytes to read
302 * Default read function for 8bit buswidth.
304 void nand_read_buf(struct mtd_info *mtd, uint8_t *buf, int len)
306 struct nand_chip *chip = mtd_to_nand(mtd);
308 ioread8_rep(chip->IO_ADDR_R, buf, len);
312 * nand_write_buf16 - [DEFAULT] write buffer to chip
313 * @mtd: MTD device structure
315 * @len: number of bytes to write
317 * Default write function for 16bit buswidth.
319 void nand_write_buf16(struct mtd_info *mtd, const uint8_t *buf, int len)
321 struct nand_chip *chip = mtd_to_nand(mtd);
322 u16 *p = (u16 *) buf;
324 iowrite16_rep(chip->IO_ADDR_W, p, len >> 1);
328 * nand_read_buf16 - [DEFAULT] read chip data into buffer
329 * @mtd: MTD device structure
330 * @buf: buffer to store date
331 * @len: number of bytes to read
333 * Default read function for 16bit buswidth.
335 void nand_read_buf16(struct mtd_info *mtd, uint8_t *buf, int len)
337 struct nand_chip *chip = mtd_to_nand(mtd);
338 u16 *p = (u16 *) buf;
340 ioread16_rep(chip->IO_ADDR_R, p, len >> 1);
344 * nand_block_bad - [DEFAULT] Read bad block marker from the chip
345 * @mtd: MTD device structure
346 * @ofs: offset from device start
348 * Check, if the block is bad.
350 static int nand_block_bad(struct mtd_info *mtd, loff_t ofs)
352 int page, res = 0, i = 0;
353 struct nand_chip *chip = mtd_to_nand(mtd);
356 if (chip->bbt_options & NAND_BBT_SCANLASTPAGE)
357 ofs += mtd->erasesize - mtd->writesize;
359 page = (int)(ofs >> chip->page_shift) & chip->pagemask;
362 if (chip->options & NAND_BUSWIDTH_16) {
363 chip->cmdfunc(mtd, NAND_CMD_READOOB,
364 chip->badblockpos & 0xFE, page);
365 bad = cpu_to_le16(chip->read_word(mtd));
366 if (chip->badblockpos & 0x1)
371 chip->cmdfunc(mtd, NAND_CMD_READOOB, chip->badblockpos,
373 bad = chip->read_byte(mtd);
376 if (likely(chip->badblockbits == 8))
379 res = hweight8(bad) < chip->badblockbits;
380 ofs += mtd->writesize;
381 page = (int)(ofs >> chip->page_shift) & chip->pagemask;
383 } while (!res && i < 2 && (chip->bbt_options & NAND_BBT_SCAN2NDPAGE));
389 * nand_default_block_markbad - [DEFAULT] mark a block bad via bad block marker
390 * @mtd: MTD device structure
391 * @ofs: offset from device start
393 * This is the default implementation, which can be overridden by a hardware
394 * specific driver. It provides the details for writing a bad block marker to a
397 static int nand_default_block_markbad(struct mtd_info *mtd, loff_t ofs)
399 struct nand_chip *chip = mtd_to_nand(mtd);
400 struct mtd_oob_ops ops;
401 uint8_t buf[2] = { 0, 0 };
402 int ret = 0, res, i = 0;
404 memset(&ops, 0, sizeof(ops));
406 ops.ooboffs = chip->badblockpos;
407 if (chip->options & NAND_BUSWIDTH_16) {
408 ops.ooboffs &= ~0x01;
409 ops.len = ops.ooblen = 2;
411 ops.len = ops.ooblen = 1;
413 ops.mode = MTD_OPS_PLACE_OOB;
415 /* Write to first/last page(s) if necessary */
416 if (chip->bbt_options & NAND_BBT_SCANLASTPAGE)
417 ofs += mtd->erasesize - mtd->writesize;
419 res = nand_do_write_oob(mtd, ofs, &ops);
424 ofs += mtd->writesize;
425 } while ((chip->bbt_options & NAND_BBT_SCAN2NDPAGE) && i < 2);
431 * nand_block_markbad_lowlevel - mark a block bad
432 * @mtd: MTD device structure
433 * @ofs: offset from device start
435 * This function performs the generic NAND bad block marking steps (i.e., bad
436 * block table(s) and/or marker(s)). We only allow the hardware driver to
437 * specify how to write bad block markers to OOB (chip->block_markbad).
439 * We try operations in the following order:
440 * (1) erase the affected block, to allow OOB marker to be written cleanly
441 * (2) write bad block marker to OOB area of affected block (unless flag
442 * NAND_BBT_NO_OOB_BBM is present)
444 * Note that we retain the first error encountered in (2) or (3), finish the
445 * procedures, and dump the error in the end.
447 static int nand_block_markbad_lowlevel(struct mtd_info *mtd, loff_t ofs)
449 struct nand_chip *chip = mtd_to_nand(mtd);
452 if (!(chip->bbt_options & NAND_BBT_NO_OOB_BBM)) {
453 struct erase_info einfo;
455 /* Attempt erase before marking OOB */
456 memset(&einfo, 0, sizeof(einfo));
459 einfo.len = 1ULL << chip->phys_erase_shift;
460 nand_erase_nand(mtd, &einfo, 0);
462 /* Write bad block marker to OOB */
463 nand_get_device(mtd, FL_WRITING);
464 ret = chip->block_markbad(mtd, ofs);
465 nand_release_device(mtd);
468 /* Mark block bad in BBT */
470 res = nand_markbad_bbt(mtd, ofs);
476 mtd->ecc_stats.badblocks++;
482 * nand_check_wp - [GENERIC] check if the chip is write protected
483 * @mtd: MTD device structure
485 * Check, if the device is write protected. The function expects, that the
486 * device is already selected.
488 static int nand_check_wp(struct mtd_info *mtd)
490 struct nand_chip *chip = mtd_to_nand(mtd);
494 /* Broken xD cards report WP despite being writable */
495 if (chip->options & NAND_BROKEN_XD)
498 /* Check the WP bit */
499 ret = nand_status_op(chip, &status);
503 return status & NAND_STATUS_WP ? 0 : 1;
507 * nand_block_isreserved - [GENERIC] Check if a block is marked reserved.
508 * @mtd: MTD device structure
509 * @ofs: offset from device start
511 * Check if the block is marked as reserved.
513 static int nand_block_isreserved(struct mtd_info *mtd, loff_t ofs)
515 struct nand_chip *chip = mtd_to_nand(mtd);
519 /* Return info from the table */
520 return nand_isreserved_bbt(mtd, ofs);
524 * nand_block_checkbad - [GENERIC] Check if a block is marked bad
525 * @mtd: MTD device structure
526 * @ofs: offset from device start
527 * @allowbbt: 1, if its allowed to access the bbt area
529 * Check, if the block is bad. Either by reading the bad block table or
530 * calling of the scan function.
532 static int nand_block_checkbad(struct mtd_info *mtd, loff_t ofs, int allowbbt)
534 struct nand_chip *chip = mtd_to_nand(mtd);
536 if (!(chip->options & NAND_SKIP_BBTSCAN) &&
537 !(chip->options & NAND_BBT_SCANNED)) {
538 chip->options |= NAND_BBT_SCANNED;
543 return chip->block_bad(mtd, ofs);
545 /* Return info from the table */
546 return nand_isbad_bbt(mtd, ofs, allowbbt);
550 * nand_wait_ready - [GENERIC] Wait for the ready pin after commands.
551 * @mtd: MTD device structure
553 * Wait for the ready pin after a command, and warn if a timeout occurs.
555 void nand_wait_ready(struct mtd_info *mtd)
557 struct nand_chip *chip = mtd_to_nand(mtd);
558 u32 timeo = (CONFIG_SYS_HZ * 400) / 1000;
561 time_start = get_timer(0);
562 /* Wait until command is processed or timeout occurs */
563 while (get_timer(time_start) < timeo) {
565 if (chip->dev_ready(mtd))
569 if (!chip->dev_ready(mtd))
570 pr_warn("timeout while waiting for chip to become ready\n");
572 EXPORT_SYMBOL_GPL(nand_wait_ready);
575 * nand_wait_status_ready - [GENERIC] Wait for the ready status after commands.
576 * @mtd: MTD device structure
577 * @timeo: Timeout in ms
579 * Wait for status ready (i.e. command done) or timeout.
581 static void nand_wait_status_ready(struct mtd_info *mtd, unsigned long timeo)
583 register struct nand_chip *chip = mtd_to_nand(mtd);
587 timeo = (CONFIG_SYS_HZ * timeo) / 1000;
588 time_start = get_timer(0);
589 while (get_timer(time_start) < timeo) {
592 ret = nand_read_data_op(chip, &status, sizeof(status), true);
596 if (status & NAND_STATUS_READY)
603 * nand_command - [DEFAULT] Send command to NAND device
604 * @mtd: MTD device structure
605 * @command: the command to be sent
606 * @column: the column address for this command, -1 if none
607 * @page_addr: the page address for this command, -1 if none
609 * Send command to NAND device. This function is used for small page devices
610 * (512 Bytes per page).
612 static void nand_command(struct mtd_info *mtd, unsigned int command,
613 int column, int page_addr)
615 register struct nand_chip *chip = mtd_to_nand(mtd);
616 int ctrl = NAND_CTRL_CLE | NAND_CTRL_CHANGE;
618 /* Write out the command to the device */
619 if (command == NAND_CMD_SEQIN) {
622 if (column >= mtd->writesize) {
624 column -= mtd->writesize;
625 readcmd = NAND_CMD_READOOB;
626 } else if (column < 256) {
627 /* First 256 bytes --> READ0 */
628 readcmd = NAND_CMD_READ0;
631 readcmd = NAND_CMD_READ1;
633 chip->cmd_ctrl(mtd, readcmd, ctrl);
634 ctrl &= ~NAND_CTRL_CHANGE;
636 chip->cmd_ctrl(mtd, command, ctrl);
638 /* Address cycle, when necessary */
639 ctrl = NAND_CTRL_ALE | NAND_CTRL_CHANGE;
640 /* Serially input address */
642 /* Adjust columns for 16 bit buswidth */
643 if (chip->options & NAND_BUSWIDTH_16 &&
644 !nand_opcode_8bits(command))
646 chip->cmd_ctrl(mtd, column, ctrl);
647 ctrl &= ~NAND_CTRL_CHANGE;
649 if (page_addr != -1) {
650 chip->cmd_ctrl(mtd, page_addr, ctrl);
651 ctrl &= ~NAND_CTRL_CHANGE;
652 chip->cmd_ctrl(mtd, page_addr >> 8, ctrl);
653 if (chip->options & NAND_ROW_ADDR_3)
654 chip->cmd_ctrl(mtd, page_addr >> 16, ctrl);
656 chip->cmd_ctrl(mtd, NAND_CMD_NONE, NAND_NCE | NAND_CTRL_CHANGE);
659 * Program and erase have their own busy handlers status and sequential
664 case NAND_CMD_PAGEPROG:
665 case NAND_CMD_ERASE1:
666 case NAND_CMD_ERASE2:
668 case NAND_CMD_STATUS:
669 case NAND_CMD_READID:
670 case NAND_CMD_SET_FEATURES:
676 udelay(chip->chip_delay);
677 chip->cmd_ctrl(mtd, NAND_CMD_STATUS,
678 NAND_CTRL_CLE | NAND_CTRL_CHANGE);
680 NAND_CMD_NONE, NAND_NCE | NAND_CTRL_CHANGE);
681 /* EZ-NAND can take upto 250ms as per ONFi v4.0 */
682 nand_wait_status_ready(mtd, 250);
685 /* This applies to read commands */
688 * If we don't have access to the busy pin, we apply the given
691 if (!chip->dev_ready) {
692 udelay(chip->chip_delay);
697 * Apply this short delay always to ensure that we do wait tWB in
698 * any case on any machine.
702 nand_wait_ready(mtd);
706 * nand_command_lp - [DEFAULT] Send command to NAND large page device
707 * @mtd: MTD device structure
708 * @command: the command to be sent
709 * @column: the column address for this command, -1 if none
710 * @page_addr: the page address for this command, -1 if none
712 * Send command to NAND device. This is the version for the new large page
713 * devices. We don't have the separate regions as we have in the small page
714 * devices. We must emulate NAND_CMD_READOOB to keep the code compatible.
716 static void nand_command_lp(struct mtd_info *mtd, unsigned int command,
717 int column, int page_addr)
719 register struct nand_chip *chip = mtd_to_nand(mtd);
721 /* Emulate NAND_CMD_READOOB */
722 if (command == NAND_CMD_READOOB) {
723 column += mtd->writesize;
724 command = NAND_CMD_READ0;
727 /* Command latch cycle */
728 chip->cmd_ctrl(mtd, command, NAND_NCE | NAND_CLE | NAND_CTRL_CHANGE);
730 if (column != -1 || page_addr != -1) {
731 int ctrl = NAND_CTRL_CHANGE | NAND_NCE | NAND_ALE;
733 /* Serially input address */
735 /* Adjust columns for 16 bit buswidth */
736 if (chip->options & NAND_BUSWIDTH_16 &&
737 !nand_opcode_8bits(command))
739 chip->cmd_ctrl(mtd, column, ctrl);
740 ctrl &= ~NAND_CTRL_CHANGE;
741 chip->cmd_ctrl(mtd, column >> 8, ctrl);
743 if (page_addr != -1) {
744 chip->cmd_ctrl(mtd, page_addr, ctrl);
745 chip->cmd_ctrl(mtd, page_addr >> 8,
746 NAND_NCE | NAND_ALE);
747 if (chip->options & NAND_ROW_ADDR_3)
748 chip->cmd_ctrl(mtd, page_addr >> 16,
749 NAND_NCE | NAND_ALE);
752 chip->cmd_ctrl(mtd, NAND_CMD_NONE, NAND_NCE | NAND_CTRL_CHANGE);
755 * Program and erase have their own busy handlers status, sequential
756 * in and status need no delay.
760 case NAND_CMD_CACHEDPROG:
761 case NAND_CMD_PAGEPROG:
762 case NAND_CMD_ERASE1:
763 case NAND_CMD_ERASE2:
766 case NAND_CMD_STATUS:
767 case NAND_CMD_READID:
768 case NAND_CMD_SET_FEATURES:
774 udelay(chip->chip_delay);
775 chip->cmd_ctrl(mtd, NAND_CMD_STATUS,
776 NAND_NCE | NAND_CLE | NAND_CTRL_CHANGE);
777 chip->cmd_ctrl(mtd, NAND_CMD_NONE,
778 NAND_NCE | NAND_CTRL_CHANGE);
779 /* EZ-NAND can take upto 250ms as per ONFi v4.0 */
780 nand_wait_status_ready(mtd, 250);
783 case NAND_CMD_RNDOUT:
784 /* No ready / busy check necessary */
785 chip->cmd_ctrl(mtd, NAND_CMD_RNDOUTSTART,
786 NAND_NCE | NAND_CLE | NAND_CTRL_CHANGE);
787 chip->cmd_ctrl(mtd, NAND_CMD_NONE,
788 NAND_NCE | NAND_CTRL_CHANGE);
792 chip->cmd_ctrl(mtd, NAND_CMD_READSTART,
793 NAND_NCE | NAND_CLE | NAND_CTRL_CHANGE);
794 chip->cmd_ctrl(mtd, NAND_CMD_NONE,
795 NAND_NCE | NAND_CTRL_CHANGE);
797 /* This applies to read commands */
800 * If we don't have access to the busy pin, we apply the given
803 if (!chip->dev_ready) {
804 udelay(chip->chip_delay);
810 * Apply this short delay always to ensure that we do wait tWB in
811 * any case on any machine.
815 nand_wait_ready(mtd);
819 * panic_nand_get_device - [GENERIC] Get chip for selected access
820 * @chip: the nand chip descriptor
821 * @mtd: MTD device structure
822 * @new_state: the state which is requested
824 * Used when in panic, no locks are taken.
826 static void panic_nand_get_device(struct nand_chip *chip,
827 struct mtd_info *mtd, int new_state)
829 /* Hardware controller shared among independent devices */
830 chip->controller->active = chip;
831 chip->state = new_state;
835 * nand_get_device - [GENERIC] Get chip for selected access
836 * @mtd: MTD device structure
837 * @new_state: the state which is requested
839 * Get the device and lock it for exclusive access
842 nand_get_device(struct mtd_info *mtd, int new_state)
844 struct nand_chip *chip = mtd_to_nand(mtd);
845 chip->state = new_state;
850 * panic_nand_wait - [GENERIC] wait until the command is done
851 * @mtd: MTD device structure
852 * @chip: NAND chip structure
855 * Wait for command done. This is a helper function for nand_wait used when
856 * we are in interrupt context. May happen when in panic and trying to write
857 * an oops through mtdoops.
859 static void panic_nand_wait(struct mtd_info *mtd, struct nand_chip *chip,
863 for (i = 0; i < timeo; i++) {
864 if (chip->dev_ready) {
865 if (chip->dev_ready(mtd))
871 ret = nand_read_data_op(chip, &status, sizeof(status),
876 if (status & NAND_STATUS_READY)
884 * nand_wait - [DEFAULT] wait until the command is done
885 * @mtd: MTD device structure
886 * @chip: NAND chip structure
888 * Wait for command done. This applies to erase and program only.
890 static int nand_wait(struct mtd_info *mtd, struct nand_chip *chip)
892 unsigned long timeo = 400;
896 led_trigger_event(nand_led_trigger, LED_FULL);
899 * Apply this short delay always to ensure that we do wait tWB in any
900 * case on any machine.
904 ret = nand_status_op(chip, NULL);
908 u32 timer = (CONFIG_SYS_HZ * timeo) / 1000;
911 time_start = get_timer(0);
912 while (get_timer(time_start) < timer) {
913 if (chip->dev_ready) {
914 if (chip->dev_ready(mtd))
917 ret = nand_read_data_op(chip, &status,
918 sizeof(status), true);
922 if (status & NAND_STATUS_READY)
926 led_trigger_event(nand_led_trigger, LED_OFF);
928 ret = nand_read_data_op(chip, &status, sizeof(status), true);
932 /* This can happen if in case of timeout or buggy dev_ready */
933 WARN_ON(!(status & NAND_STATUS_READY));
938 * nand_reset_data_interface - Reset data interface and timings
939 * @chip: The NAND chip
940 * @chipnr: Internal die id
942 * Reset the Data interface and timings to ONFI mode 0.
944 * Returns 0 for success or negative error code otherwise.
946 static int nand_reset_data_interface(struct nand_chip *chip, int chipnr)
948 struct mtd_info *mtd = nand_to_mtd(chip);
949 const struct nand_data_interface *conf;
952 if (!chip->setup_data_interface)
956 * The ONFI specification says:
958 * To transition from NV-DDR or NV-DDR2 to the SDR data
959 * interface, the host shall use the Reset (FFh) command
960 * using SDR timing mode 0. A device in any timing mode is
961 * required to recognize Reset (FFh) command issued in SDR
965 * Configure the data interface in SDR mode and set the
966 * timings to timing mode 0.
969 conf = nand_get_default_data_interface();
970 ret = chip->setup_data_interface(mtd, chipnr, conf);
972 pr_err("Failed to configure data interface to SDR timing mode 0\n");
978 * nand_setup_data_interface - Setup the best data interface and timings
979 * @chip: The NAND chip
980 * @chipnr: Internal die id
982 * Find and configure the best data interface and NAND timings supported by
983 * the chip and the driver.
984 * First tries to retrieve supported timing modes from ONFI information,
985 * and if the NAND chip does not support ONFI, relies on the
986 * ->onfi_timing_mode_default specified in the nand_ids table.
988 * Returns 0 for success or negative error code otherwise.
990 static int nand_setup_data_interface(struct nand_chip *chip, int chipnr)
992 struct mtd_info *mtd = nand_to_mtd(chip);
995 if (!chip->setup_data_interface || !chip->data_interface)
999 * Ensure the timing mode has been changed on the chip side
1000 * before changing timings on the controller side.
1002 if (chip->onfi_version) {
1003 u8 tmode_param[ONFI_SUBFEATURE_PARAM_LEN] = {
1004 chip->onfi_timing_mode_default,
1007 ret = chip->onfi_set_features(mtd, chip,
1008 ONFI_FEATURE_ADDR_TIMING_MODE,
1014 ret = chip->setup_data_interface(mtd, chipnr, chip->data_interface);
1020 * nand_init_data_interface - find the best data interface and timings
1021 * @chip: The NAND chip
1023 * Find the best data interface and NAND timings supported by the chip
1025 * First tries to retrieve supported timing modes from ONFI information,
1026 * and if the NAND chip does not support ONFI, relies on the
1027 * ->onfi_timing_mode_default specified in the nand_ids table. After this
1028 * function nand_chip->data_interface is initialized with the best timing mode
1031 * Returns 0 for success or negative error code otherwise.
1033 static int nand_init_data_interface(struct nand_chip *chip)
1035 struct mtd_info *mtd = nand_to_mtd(chip);
1036 int modes, mode, ret;
1038 if (!chip->setup_data_interface)
1042 * First try to identify the best timings from ONFI parameters and
1043 * if the NAND does not support ONFI, fallback to the default ONFI
1046 modes = onfi_get_async_timing_mode(chip);
1047 if (modes == ONFI_TIMING_MODE_UNKNOWN) {
1048 if (!chip->onfi_timing_mode_default)
1051 modes = GENMASK(chip->onfi_timing_mode_default, 0);
1054 chip->data_interface = kzalloc(sizeof(*chip->data_interface),
1056 if (!chip->data_interface)
1059 for (mode = fls(modes) - 1; mode >= 0; mode--) {
1060 ret = onfi_init_data_interface(chip, chip->data_interface,
1061 NAND_SDR_IFACE, mode);
1065 /* Pass -1 to only */
1066 ret = chip->setup_data_interface(mtd,
1067 NAND_DATA_IFACE_CHECK_ONLY,
1068 chip->data_interface);
1070 chip->onfi_timing_mode_default = mode;
1078 static void __maybe_unused nand_release_data_interface(struct nand_chip *chip)
1080 kfree(chip->data_interface);
1084 * nand_read_page_op - Do a READ PAGE operation
1085 * @chip: The NAND chip
1086 * @page: page to read
1087 * @offset_in_page: offset within the page
1088 * @buf: buffer used to store the data
1089 * @len: length of the buffer
1091 * This function issues a READ PAGE operation.
1092 * This function does not select/unselect the CS line.
1094 * Returns 0 on success, a negative error code otherwise.
1096 int nand_read_page_op(struct nand_chip *chip, unsigned int page,
1097 unsigned int offset_in_page, void *buf, unsigned int len)
1099 struct mtd_info *mtd = nand_to_mtd(chip);
1104 if (offset_in_page + len > mtd->writesize + mtd->oobsize)
1107 chip->cmdfunc(mtd, NAND_CMD_READ0, offset_in_page, page);
1109 chip->read_buf(mtd, buf, len);
1113 EXPORT_SYMBOL_GPL(nand_read_page_op);
1116 * nand_read_param_page_op - Do a READ PARAMETER PAGE operation
1117 * @chip: The NAND chip
1118 * @page: parameter page to read
1119 * @buf: buffer used to store the data
1120 * @len: length of the buffer
1122 * This function issues a READ PARAMETER PAGE operation.
1123 * This function does not select/unselect the CS line.
1125 * Returns 0 on success, a negative error code otherwise.
1127 static int nand_read_param_page_op(struct nand_chip *chip, u8 page, void *buf,
1130 struct mtd_info *mtd = nand_to_mtd(chip);
1137 chip->cmdfunc(mtd, NAND_CMD_PARAM, page, -1);
1138 for (i = 0; i < len; i++)
1139 p[i] = chip->read_byte(mtd);
1145 * nand_change_read_column_op - Do a CHANGE READ COLUMN operation
1146 * @chip: The NAND chip
1147 * @offset_in_page: offset within the page
1148 * @buf: buffer used to store the data
1149 * @len: length of the buffer
1150 * @force_8bit: force 8-bit bus access
1152 * This function issues a CHANGE READ COLUMN operation.
1153 * This function does not select/unselect the CS line.
1155 * Returns 0 on success, a negative error code otherwise.
1157 int nand_change_read_column_op(struct nand_chip *chip,
1158 unsigned int offset_in_page, void *buf,
1159 unsigned int len, bool force_8bit)
1161 struct mtd_info *mtd = nand_to_mtd(chip);
1166 if (offset_in_page + len > mtd->writesize + mtd->oobsize)
1169 chip->cmdfunc(mtd, NAND_CMD_RNDOUT, offset_in_page, -1);
1171 chip->read_buf(mtd, buf, len);
1175 EXPORT_SYMBOL_GPL(nand_change_read_column_op);
1178 * nand_read_oob_op - Do a READ OOB operation
1179 * @chip: The NAND chip
1180 * @page: page to read
1181 * @offset_in_oob: offset within the OOB area
1182 * @buf: buffer used to store the data
1183 * @len: length of the buffer
1185 * This function issues a READ OOB operation.
1186 * This function does not select/unselect the CS line.
1188 * Returns 0 on success, a negative error code otherwise.
1190 int nand_read_oob_op(struct nand_chip *chip, unsigned int page,
1191 unsigned int offset_in_oob, void *buf, unsigned int len)
1193 struct mtd_info *mtd = nand_to_mtd(chip);
1198 if (offset_in_oob + len > mtd->oobsize)
1201 chip->cmdfunc(mtd, NAND_CMD_READOOB, offset_in_oob, page);
1203 chip->read_buf(mtd, buf, len);
1207 EXPORT_SYMBOL_GPL(nand_read_oob_op);
1210 * nand_prog_page_begin_op - starts a PROG PAGE operation
1211 * @chip: The NAND chip
1212 * @page: page to write
1213 * @offset_in_page: offset within the page
1214 * @buf: buffer containing the data to write to the page
1215 * @len: length of the buffer
1217 * This function issues the first half of a PROG PAGE operation.
1218 * This function does not select/unselect the CS line.
1220 * Returns 0 on success, a negative error code otherwise.
1222 int nand_prog_page_begin_op(struct nand_chip *chip, unsigned int page,
1223 unsigned int offset_in_page, const void *buf,
1226 struct mtd_info *mtd = nand_to_mtd(chip);
1231 if (offset_in_page + len > mtd->writesize + mtd->oobsize)
1234 chip->cmdfunc(mtd, NAND_CMD_SEQIN, offset_in_page, page);
1237 chip->write_buf(mtd, buf, len);
1241 EXPORT_SYMBOL_GPL(nand_prog_page_begin_op);
1244 * nand_prog_page_end_op - ends a PROG PAGE operation
1245 * @chip: The NAND chip
1247 * This function issues the second half of a PROG PAGE operation.
1248 * This function does not select/unselect the CS line.
1250 * Returns 0 on success, a negative error code otherwise.
1252 int nand_prog_page_end_op(struct nand_chip *chip)
1254 struct mtd_info *mtd = nand_to_mtd(chip);
1257 chip->cmdfunc(mtd, NAND_CMD_PAGEPROG, -1, -1);
1259 status = chip->waitfunc(mtd, chip);
1260 if (status & NAND_STATUS_FAIL)
1265 EXPORT_SYMBOL_GPL(nand_prog_page_end_op);
1268 * nand_prog_page_op - Do a full PROG PAGE operation
1269 * @chip: The NAND chip
1270 * @page: page to write
1271 * @offset_in_page: offset within the page
1272 * @buf: buffer containing the data to write to the page
1273 * @len: length of the buffer
1275 * This function issues a full PROG PAGE operation.
1276 * This function does not select/unselect the CS line.
1278 * Returns 0 on success, a negative error code otherwise.
1280 int nand_prog_page_op(struct nand_chip *chip, unsigned int page,
1281 unsigned int offset_in_page, const void *buf,
1284 struct mtd_info *mtd = nand_to_mtd(chip);
1290 if (offset_in_page + len > mtd->writesize + mtd->oobsize)
1293 chip->cmdfunc(mtd, NAND_CMD_SEQIN, offset_in_page, page);
1294 chip->write_buf(mtd, buf, len);
1295 chip->cmdfunc(mtd, NAND_CMD_PAGEPROG, -1, -1);
1297 status = chip->waitfunc(mtd, chip);
1298 if (status & NAND_STATUS_FAIL)
1303 EXPORT_SYMBOL_GPL(nand_prog_page_op);
1306 * nand_change_write_column_op - Do a CHANGE WRITE COLUMN operation
1307 * @chip: The NAND chip
1308 * @offset_in_page: offset within the page
1309 * @buf: buffer containing the data to send to the NAND
1310 * @len: length of the buffer
1311 * @force_8bit: force 8-bit bus access
1313 * This function issues a CHANGE WRITE COLUMN operation.
1314 * This function does not select/unselect the CS line.
1316 * Returns 0 on success, a negative error code otherwise.
1318 int nand_change_write_column_op(struct nand_chip *chip,
1319 unsigned int offset_in_page,
1320 const void *buf, unsigned int len,
1323 struct mtd_info *mtd = nand_to_mtd(chip);
1328 if (offset_in_page + len > mtd->writesize + mtd->oobsize)
1331 chip->cmdfunc(mtd, NAND_CMD_RNDIN, offset_in_page, -1);
1333 chip->write_buf(mtd, buf, len);
1337 EXPORT_SYMBOL_GPL(nand_change_write_column_op);
1340 * nand_readid_op - Do a READID operation
1341 * @chip: The NAND chip
1342 * @addr: address cycle to pass after the READID command
1343 * @buf: buffer used to store the ID
1344 * @len: length of the buffer
1346 * This function sends a READID command and reads back the ID returned by the
1348 * This function does not select/unselect the CS line.
1350 * Returns 0 on success, a negative error code otherwise.
1352 int nand_readid_op(struct nand_chip *chip, u8 addr, void *buf,
1355 struct mtd_info *mtd = nand_to_mtd(chip);
1362 chip->cmdfunc(mtd, NAND_CMD_READID, addr, -1);
1364 for (i = 0; i < len; i++)
1365 id[i] = chip->read_byte(mtd);
1369 EXPORT_SYMBOL_GPL(nand_readid_op);
1372 * nand_status_op - Do a STATUS operation
1373 * @chip: The NAND chip
1374 * @status: out variable to store the NAND status
1376 * This function sends a STATUS command and reads back the status returned by
1378 * This function does not select/unselect the CS line.
1380 * Returns 0 on success, a negative error code otherwise.
1382 int nand_status_op(struct nand_chip *chip, u8 *status)
1384 struct mtd_info *mtd = nand_to_mtd(chip);
1386 chip->cmdfunc(mtd, NAND_CMD_STATUS, -1, -1);
1388 *status = chip->read_byte(mtd);
1392 EXPORT_SYMBOL_GPL(nand_status_op);
1395 * nand_exit_status_op - Exit a STATUS operation
1396 * @chip: The NAND chip
1398 * This function sends a READ0 command to cancel the effect of the STATUS
1399 * command to avoid reading only the status until a new read command is sent.
1401 * This function does not select/unselect the CS line.
1403 * Returns 0 on success, a negative error code otherwise.
1405 int nand_exit_status_op(struct nand_chip *chip)
1407 struct mtd_info *mtd = nand_to_mtd(chip);
1409 chip->cmdfunc(mtd, NAND_CMD_READ0, -1, -1);
1413 EXPORT_SYMBOL_GPL(nand_exit_status_op);
1416 * nand_erase_op - Do an erase operation
1417 * @chip: The NAND chip
1418 * @eraseblock: block to erase
1420 * This function sends an ERASE command and waits for the NAND to be ready
1422 * This function does not select/unselect the CS line.
1424 * Returns 0 on success, a negative error code otherwise.
1426 int nand_erase_op(struct nand_chip *chip, unsigned int eraseblock)
1428 struct mtd_info *mtd = nand_to_mtd(chip);
1429 unsigned int page = eraseblock <<
1430 (chip->phys_erase_shift - chip->page_shift);
1433 chip->cmdfunc(mtd, NAND_CMD_ERASE1, -1, page);
1434 chip->cmdfunc(mtd, NAND_CMD_ERASE2, -1, -1);
1436 status = chip->waitfunc(mtd, chip);
1440 if (status & NAND_STATUS_FAIL)
1445 EXPORT_SYMBOL_GPL(nand_erase_op);
1448 * nand_set_features_op - Do a SET FEATURES operation
1449 * @chip: The NAND chip
1450 * @feature: feature id
1451 * @data: 4 bytes of data
1453 * This function sends a SET FEATURES command and waits for the NAND to be
1454 * ready before returning.
1455 * This function does not select/unselect the CS line.
1457 * Returns 0 on success, a negative error code otherwise.
1459 static int nand_set_features_op(struct nand_chip *chip, u8 feature,
1462 struct mtd_info *mtd = nand_to_mtd(chip);
1463 const u8 *params = data;
1466 chip->cmdfunc(mtd, NAND_CMD_SET_FEATURES, feature, -1);
1467 for (i = 0; i < ONFI_SUBFEATURE_PARAM_LEN; ++i)
1468 chip->write_byte(mtd, params[i]);
1470 status = chip->waitfunc(mtd, chip);
1471 if (status & NAND_STATUS_FAIL)
1478 * nand_get_features_op - Do a GET FEATURES operation
1479 * @chip: The NAND chip
1480 * @feature: feature id
1481 * @data: 4 bytes of data
1483 * This function sends a GET FEATURES command and waits for the NAND to be
1484 * ready before returning.
1485 * This function does not select/unselect the CS line.
1487 * Returns 0 on success, a negative error code otherwise.
1489 static int nand_get_features_op(struct nand_chip *chip, u8 feature,
1492 struct mtd_info *mtd = nand_to_mtd(chip);
1496 chip->cmdfunc(mtd, NAND_CMD_GET_FEATURES, feature, -1);
1497 for (i = 0; i < ONFI_SUBFEATURE_PARAM_LEN; ++i)
1498 params[i] = chip->read_byte(mtd);
1504 * nand_reset_op - Do a reset operation
1505 * @chip: The NAND chip
1507 * This function sends a RESET command and waits for the NAND to be ready
1509 * This function does not select/unselect the CS line.
1511 * Returns 0 on success, a negative error code otherwise.
1513 int nand_reset_op(struct nand_chip *chip)
1515 struct mtd_info *mtd = nand_to_mtd(chip);
1517 chip->cmdfunc(mtd, NAND_CMD_RESET, -1, -1);
1521 EXPORT_SYMBOL_GPL(nand_reset_op);
1524 * nand_read_data_op - Read data from the NAND
1525 * @chip: The NAND chip
1526 * @buf: buffer used to store the data
1527 * @len: length of the buffer
1528 * @force_8bit: force 8-bit bus access
1530 * This function does a raw data read on the bus. Usually used after launching
1531 * another NAND operation like nand_read_page_op().
1532 * This function does not select/unselect the CS line.
1534 * Returns 0 on success, a negative error code otherwise.
1536 int nand_read_data_op(struct nand_chip *chip, void *buf, unsigned int len,
1539 struct mtd_info *mtd = nand_to_mtd(chip);
1548 for (i = 0; i < len; i++)
1549 p[i] = chip->read_byte(mtd);
1551 chip->read_buf(mtd, buf, len);
1556 EXPORT_SYMBOL_GPL(nand_read_data_op);
1559 * nand_write_data_op - Write data from the NAND
1560 * @chip: The NAND chip
1561 * @buf: buffer containing the data to send on the bus
1562 * @len: length of the buffer
1563 * @force_8bit: force 8-bit bus access
1565 * This function does a raw data write on the bus. Usually used after launching
1566 * another NAND operation like nand_write_page_begin_op().
1567 * This function does not select/unselect the CS line.
1569 * Returns 0 on success, a negative error code otherwise.
1571 int nand_write_data_op(struct nand_chip *chip, const void *buf,
1572 unsigned int len, bool force_8bit)
1574 struct mtd_info *mtd = nand_to_mtd(chip);
1583 for (i = 0; i < len; i++)
1584 chip->write_byte(mtd, p[i]);
1586 chip->write_buf(mtd, buf, len);
1591 EXPORT_SYMBOL_GPL(nand_write_data_op);
1594 * nand_reset - Reset and initialize a NAND device
1595 * @chip: The NAND chip
1596 * @chipnr: Internal die id
1598 * Returns 0 for success or negative error code otherwise
1600 int nand_reset(struct nand_chip *chip, int chipnr)
1602 struct mtd_info *mtd = nand_to_mtd(chip);
1605 ret = nand_reset_data_interface(chip, chipnr);
1610 * The CS line has to be released before we can apply the new NAND
1611 * interface settings, hence this weird ->select_chip() dance.
1613 chip->select_chip(mtd, chipnr);
1614 ret = nand_reset_op(chip);
1615 chip->select_chip(mtd, -1);
1619 chip->select_chip(mtd, chipnr);
1620 ret = nand_setup_data_interface(chip, chipnr);
1621 chip->select_chip(mtd, -1);
1629 * nand_check_erased_buf - check if a buffer contains (almost) only 0xff data
1630 * @buf: buffer to test
1631 * @len: buffer length
1632 * @bitflips_threshold: maximum number of bitflips
1634 * Check if a buffer contains only 0xff, which means the underlying region
1635 * has been erased and is ready to be programmed.
1636 * The bitflips_threshold specify the maximum number of bitflips before
1637 * considering the region is not erased.
1638 * Note: The logic of this function has been extracted from the memweight
1639 * implementation, except that nand_check_erased_buf function exit before
1640 * testing the whole buffer if the number of bitflips exceed the
1641 * bitflips_threshold value.
1643 * Returns a positive number of bitflips less than or equal to
1644 * bitflips_threshold, or -ERROR_CODE for bitflips in excess of the
1647 static int nand_check_erased_buf(void *buf, int len, int bitflips_threshold)
1649 const unsigned char *bitmap = buf;
1653 for (; len && ((uintptr_t)bitmap) % sizeof(long);
1655 weight = hweight8(*bitmap);
1656 bitflips += BITS_PER_BYTE - weight;
1657 if (unlikely(bitflips > bitflips_threshold))
1661 for (; len >= 4; len -= 4, bitmap += 4) {
1662 weight = hweight32(*((u32 *)bitmap));
1663 bitflips += 32 - weight;
1664 if (unlikely(bitflips > bitflips_threshold))
1668 for (; len > 0; len--, bitmap++) {
1669 weight = hweight8(*bitmap);
1670 bitflips += BITS_PER_BYTE - weight;
1671 if (unlikely(bitflips > bitflips_threshold))
1679 * nand_check_erased_ecc_chunk - check if an ECC chunk contains (almost) only
1681 * @data: data buffer to test
1682 * @datalen: data length
1684 * @ecclen: ECC length
1685 * @extraoob: extra OOB buffer
1686 * @extraooblen: extra OOB length
1687 * @bitflips_threshold: maximum number of bitflips
1689 * Check if a data buffer and its associated ECC and OOB data contains only
1690 * 0xff pattern, which means the underlying region has been erased and is
1691 * ready to be programmed.
1692 * The bitflips_threshold specify the maximum number of bitflips before
1693 * considering the region as not erased.
1696 * 1/ ECC algorithms are working on pre-defined block sizes which are usually
1697 * different from the NAND page size. When fixing bitflips, ECC engines will
1698 * report the number of errors per chunk, and the NAND core infrastructure
1699 * expect you to return the maximum number of bitflips for the whole page.
1700 * This is why you should always use this function on a single chunk and
1701 * not on the whole page. After checking each chunk you should update your
1702 * max_bitflips value accordingly.
1703 * 2/ When checking for bitflips in erased pages you should not only check
1704 * the payload data but also their associated ECC data, because a user might
1705 * have programmed almost all bits to 1 but a few. In this case, we
1706 * shouldn't consider the chunk as erased, and checking ECC bytes prevent
1708 * 3/ The extraoob argument is optional, and should be used if some of your OOB
1709 * data are protected by the ECC engine.
1710 * It could also be used if you support subpages and want to attach some
1711 * extra OOB data to an ECC chunk.
1713 * Returns a positive number of bitflips less than or equal to
1714 * bitflips_threshold, or -ERROR_CODE for bitflips in excess of the
1715 * threshold. In case of success, the passed buffers are filled with 0xff.
1717 int nand_check_erased_ecc_chunk(void *data, int datalen,
1718 void *ecc, int ecclen,
1719 void *extraoob, int extraooblen,
1720 int bitflips_threshold)
1722 int data_bitflips = 0, ecc_bitflips = 0, extraoob_bitflips = 0;
1724 data_bitflips = nand_check_erased_buf(data, datalen,
1725 bitflips_threshold);
1726 if (data_bitflips < 0)
1727 return data_bitflips;
1729 bitflips_threshold -= data_bitflips;
1731 ecc_bitflips = nand_check_erased_buf(ecc, ecclen, bitflips_threshold);
1732 if (ecc_bitflips < 0)
1733 return ecc_bitflips;
1735 bitflips_threshold -= ecc_bitflips;
1737 extraoob_bitflips = nand_check_erased_buf(extraoob, extraooblen,
1738 bitflips_threshold);
1739 if (extraoob_bitflips < 0)
1740 return extraoob_bitflips;
1743 memset(data, 0xff, datalen);
1746 memset(ecc, 0xff, ecclen);
1748 if (extraoob_bitflips)
1749 memset(extraoob, 0xff, extraooblen);
1751 return data_bitflips + ecc_bitflips + extraoob_bitflips;
1753 EXPORT_SYMBOL(nand_check_erased_ecc_chunk);
1756 * nand_read_page_raw - [INTERN] read raw page data without ecc
1757 * @mtd: mtd info structure
1758 * @chip: nand chip info structure
1759 * @buf: buffer to store read data
1760 * @oob_required: caller requires OOB data read to chip->oob_poi
1761 * @page: page number to read
1763 * Not for syndrome calculating ECC controllers, which use a special oob layout.
1765 static int nand_read_page_raw(struct mtd_info *mtd, struct nand_chip *chip,
1766 uint8_t *buf, int oob_required, int page)
1770 ret = nand_read_data_op(chip, buf, mtd->writesize, false);
1775 ret = nand_read_data_op(chip, chip->oob_poi, mtd->oobsize,
1785 * nand_read_page_raw_syndrome - [INTERN] read raw page data without ecc
1786 * @mtd: mtd info structure
1787 * @chip: nand chip info structure
1788 * @buf: buffer to store read data
1789 * @oob_required: caller requires OOB data read to chip->oob_poi
1790 * @page: page number to read
1792 * We need a special oob layout and handling even when OOB isn't used.
1794 static int nand_read_page_raw_syndrome(struct mtd_info *mtd,
1795 struct nand_chip *chip, uint8_t *buf,
1796 int oob_required, int page)
1798 int eccsize = chip->ecc.size;
1799 int eccbytes = chip->ecc.bytes;
1800 uint8_t *oob = chip->oob_poi;
1801 int steps, size, ret;
1803 for (steps = chip->ecc.steps; steps > 0; steps--) {
1804 ret = nand_read_data_op(chip, buf, eccsize, false);
1810 if (chip->ecc.prepad) {
1811 ret = nand_read_data_op(chip, oob, chip->ecc.prepad,
1816 oob += chip->ecc.prepad;
1819 ret = nand_read_data_op(chip, oob, eccbytes, false);
1825 if (chip->ecc.postpad) {
1826 ret = nand_read_data_op(chip, oob, chip->ecc.postpad,
1831 oob += chip->ecc.postpad;
1835 size = mtd->oobsize - (oob - chip->oob_poi);
1837 ret = nand_read_data_op(chip, oob, size, false);
1846 * nand_read_page_swecc - [REPLACEABLE] software ECC based page read function
1847 * @mtd: mtd info structure
1848 * @chip: nand chip info structure
1849 * @buf: buffer to store read data
1850 * @oob_required: caller requires OOB data read to chip->oob_poi
1851 * @page: page number to read
1853 static int nand_read_page_swecc(struct mtd_info *mtd, struct nand_chip *chip,
1854 uint8_t *buf, int oob_required, int page)
1856 int i, eccsize = chip->ecc.size;
1857 int eccbytes = chip->ecc.bytes;
1858 int eccsteps = chip->ecc.steps;
1860 uint8_t *ecc_calc = chip->buffers->ecccalc;
1861 uint8_t *ecc_code = chip->buffers->ecccode;
1862 uint32_t *eccpos = chip->ecc.layout->eccpos;
1863 unsigned int max_bitflips = 0;
1865 chip->ecc.read_page_raw(mtd, chip, buf, 1, page);
1867 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize)
1868 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
1870 for (i = 0; i < chip->ecc.total; i++)
1871 ecc_code[i] = chip->oob_poi[eccpos[i]];
1873 eccsteps = chip->ecc.steps;
1876 for (i = 0 ; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
1879 stat = chip->ecc.correct(mtd, p, &ecc_code[i], &ecc_calc[i]);
1881 mtd->ecc_stats.failed++;
1883 mtd->ecc_stats.corrected += stat;
1884 max_bitflips = max_t(unsigned int, max_bitflips, stat);
1887 return max_bitflips;
1891 * nand_read_subpage - [REPLACEABLE] ECC based sub-page read function
1892 * @mtd: mtd info structure
1893 * @chip: nand chip info structure
1894 * @data_offs: offset of requested data within the page
1895 * @readlen: data length
1896 * @bufpoi: buffer to store read data
1897 * @page: page number to read
1899 static int nand_read_subpage(struct mtd_info *mtd, struct nand_chip *chip,
1900 uint32_t data_offs, uint32_t readlen, uint8_t *bufpoi,
1903 int start_step, end_step, num_steps;
1904 uint32_t *eccpos = chip->ecc.layout->eccpos;
1906 int data_col_addr, i, gaps = 0;
1907 int datafrag_len, eccfrag_len, aligned_len, aligned_pos;
1908 int busw = (chip->options & NAND_BUSWIDTH_16) ? 2 : 1;
1910 unsigned int max_bitflips = 0;
1913 /* Column address within the page aligned to ECC size (256bytes) */
1914 start_step = data_offs / chip->ecc.size;
1915 end_step = (data_offs + readlen - 1) / chip->ecc.size;
1916 num_steps = end_step - start_step + 1;
1917 index = start_step * chip->ecc.bytes;
1919 /* Data size aligned to ECC ecc.size */
1920 datafrag_len = num_steps * chip->ecc.size;
1921 eccfrag_len = num_steps * chip->ecc.bytes;
1923 data_col_addr = start_step * chip->ecc.size;
1924 /* If we read not a page aligned data */
1925 if (data_col_addr != 0)
1926 chip->cmdfunc(mtd, NAND_CMD_RNDOUT, data_col_addr, -1);
1928 p = bufpoi + data_col_addr;
1929 ret = nand_read_data_op(chip, p, datafrag_len, false);
1934 for (i = 0; i < eccfrag_len ; i += chip->ecc.bytes, p += chip->ecc.size)
1935 chip->ecc.calculate(mtd, p, &chip->buffers->ecccalc[i]);
1938 * The performance is faster if we position offsets according to
1939 * ecc.pos. Let's make sure that there are no gaps in ECC positions.
1941 for (i = 0; i < eccfrag_len - 1; i++) {
1942 if (eccpos[i + index] + 1 != eccpos[i + index + 1]) {
1948 ret = nand_change_read_column_op(chip, mtd->writesize,
1949 chip->oob_poi, mtd->oobsize,
1955 * Send the command to read the particular ECC bytes take care
1956 * about buswidth alignment in read_buf.
1958 aligned_pos = eccpos[index] & ~(busw - 1);
1959 aligned_len = eccfrag_len;
1960 if (eccpos[index] & (busw - 1))
1962 if (eccpos[index + (num_steps * chip->ecc.bytes)] & (busw - 1))
1965 ret = nand_change_read_column_op(chip,
1966 mtd->writesize + aligned_pos,
1967 &chip->oob_poi[aligned_pos],
1968 aligned_len, false);
1973 for (i = 0; i < eccfrag_len; i++)
1974 chip->buffers->ecccode[i] = chip->oob_poi[eccpos[i + index]];
1976 p = bufpoi + data_col_addr;
1977 for (i = 0; i < eccfrag_len ; i += chip->ecc.bytes, p += chip->ecc.size) {
1980 stat = chip->ecc.correct(mtd, p,
1981 &chip->buffers->ecccode[i], &chip->buffers->ecccalc[i]);
1982 if (stat == -EBADMSG &&
1983 (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
1984 /* check for empty pages with bitflips */
1985 stat = nand_check_erased_ecc_chunk(p, chip->ecc.size,
1986 &chip->buffers->ecccode[i],
1989 chip->ecc.strength);
1993 mtd->ecc_stats.failed++;
1995 mtd->ecc_stats.corrected += stat;
1996 max_bitflips = max_t(unsigned int, max_bitflips, stat);
1999 return max_bitflips;
2003 * nand_read_page_hwecc - [REPLACEABLE] hardware ECC based page read function
2004 * @mtd: mtd info structure
2005 * @chip: nand chip info structure
2006 * @buf: buffer to store read data
2007 * @oob_required: caller requires OOB data read to chip->oob_poi
2008 * @page: page number to read
2010 * Not for syndrome calculating ECC controllers which need a special oob layout.
2012 static int nand_read_page_hwecc(struct mtd_info *mtd, struct nand_chip *chip,
2013 uint8_t *buf, int oob_required, int page)
2015 int i, eccsize = chip->ecc.size;
2016 int eccbytes = chip->ecc.bytes;
2017 int eccsteps = chip->ecc.steps;
2019 uint8_t *ecc_calc = chip->buffers->ecccalc;
2020 uint8_t *ecc_code = chip->buffers->ecccode;
2021 uint32_t *eccpos = chip->ecc.layout->eccpos;
2022 unsigned int max_bitflips = 0;
2025 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
2026 chip->ecc.hwctl(mtd, NAND_ECC_READ);
2028 ret = nand_read_data_op(chip, p, eccsize, false);
2032 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
2035 ret = nand_read_data_op(chip, chip->oob_poi, mtd->oobsize, false);
2039 for (i = 0; i < chip->ecc.total; i++)
2040 ecc_code[i] = chip->oob_poi[eccpos[i]];
2042 eccsteps = chip->ecc.steps;
2045 for (i = 0 ; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
2048 stat = chip->ecc.correct(mtd, p, &ecc_code[i], &ecc_calc[i]);
2049 if (stat == -EBADMSG &&
2050 (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
2051 /* check for empty pages with bitflips */
2052 stat = nand_check_erased_ecc_chunk(p, eccsize,
2053 &ecc_code[i], eccbytes,
2055 chip->ecc.strength);
2059 mtd->ecc_stats.failed++;
2061 mtd->ecc_stats.corrected += stat;
2062 max_bitflips = max_t(unsigned int, max_bitflips, stat);
2065 return max_bitflips;
2069 * nand_read_page_hwecc_oob_first - [REPLACEABLE] hw ecc, read oob first
2070 * @mtd: mtd info structure
2071 * @chip: nand chip info structure
2072 * @buf: buffer to store read data
2073 * @oob_required: caller requires OOB data read to chip->oob_poi
2074 * @page: page number to read
2076 * Hardware ECC for large page chips, require OOB to be read first. For this
2077 * ECC mode, the write_page method is re-used from ECC_HW. These methods
2078 * read/write ECC from the OOB area, unlike the ECC_HW_SYNDROME support with
2079 * multiple ECC steps, follows the "infix ECC" scheme and reads/writes ECC from
2080 * the data area, by overwriting the NAND manufacturer bad block markings.
2082 static int nand_read_page_hwecc_oob_first(struct mtd_info *mtd,
2083 struct nand_chip *chip, uint8_t *buf, int oob_required, int page)
2085 int i, eccsize = chip->ecc.size;
2086 int eccbytes = chip->ecc.bytes;
2087 int eccsteps = chip->ecc.steps;
2089 uint8_t *ecc_code = chip->buffers->ecccode;
2090 uint32_t *eccpos = chip->ecc.layout->eccpos;
2091 uint8_t *ecc_calc = chip->buffers->ecccalc;
2092 unsigned int max_bitflips = 0;
2095 /* Read the OOB area first */
2096 ret = nand_read_oob_op(chip, page, 0, chip->oob_poi, mtd->oobsize);
2100 ret = nand_read_page_op(chip, page, 0, NULL, 0);
2104 for (i = 0; i < chip->ecc.total; i++)
2105 ecc_code[i] = chip->oob_poi[eccpos[i]];
2107 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
2110 chip->ecc.hwctl(mtd, NAND_ECC_READ);
2112 ret = nand_read_data_op(chip, p, eccsize, false);
2116 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
2118 stat = chip->ecc.correct(mtd, p, &ecc_code[i], NULL);
2119 if (stat == -EBADMSG &&
2120 (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
2121 /* check for empty pages with bitflips */
2122 stat = nand_check_erased_ecc_chunk(p, eccsize,
2123 &ecc_code[i], eccbytes,
2125 chip->ecc.strength);
2129 mtd->ecc_stats.failed++;
2131 mtd->ecc_stats.corrected += stat;
2132 max_bitflips = max_t(unsigned int, max_bitflips, stat);
2135 return max_bitflips;
2139 * nand_read_page_syndrome - [REPLACEABLE] hardware ECC syndrome based page read
2140 * @mtd: mtd info structure
2141 * @chip: nand chip info structure
2142 * @buf: buffer to store read data
2143 * @oob_required: caller requires OOB data read to chip->oob_poi
2144 * @page: page number to read
2146 * The hw generator calculates the error syndrome automatically. Therefore we
2147 * need a special oob layout and handling.
2149 static int nand_read_page_syndrome(struct mtd_info *mtd, struct nand_chip *chip,
2150 uint8_t *buf, int oob_required, int page)
2152 int ret, i, eccsize = chip->ecc.size;
2153 int eccbytes = chip->ecc.bytes;
2154 int eccsteps = chip->ecc.steps;
2155 int eccpadbytes = eccbytes + chip->ecc.prepad + chip->ecc.postpad;
2157 uint8_t *oob = chip->oob_poi;
2158 unsigned int max_bitflips = 0;
2160 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
2163 chip->ecc.hwctl(mtd, NAND_ECC_READ);
2165 ret = nand_read_data_op(chip, p, eccsize, false);
2169 if (chip->ecc.prepad) {
2170 ret = nand_read_data_op(chip, oob, chip->ecc.prepad,
2175 oob += chip->ecc.prepad;
2178 chip->ecc.hwctl(mtd, NAND_ECC_READSYN);
2180 ret = nand_read_data_op(chip, oob, eccbytes, false);
2184 stat = chip->ecc.correct(mtd, p, oob, NULL);
2188 if (chip->ecc.postpad) {
2189 ret = nand_read_data_op(chip, oob, chip->ecc.postpad,
2194 oob += chip->ecc.postpad;
2197 if (stat == -EBADMSG &&
2198 (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
2199 /* check for empty pages with bitflips */
2200 stat = nand_check_erased_ecc_chunk(p, chip->ecc.size,
2204 chip->ecc.strength);
2208 mtd->ecc_stats.failed++;
2210 mtd->ecc_stats.corrected += stat;
2211 max_bitflips = max_t(unsigned int, max_bitflips, stat);
2215 /* Calculate remaining oob bytes */
2216 i = mtd->oobsize - (oob - chip->oob_poi);
2218 ret = nand_read_data_op(chip, oob, i, false);
2223 return max_bitflips;
2227 * nand_transfer_oob - [INTERN] Transfer oob to client buffer
2228 * @chip: nand chip structure
2229 * @oob: oob destination address
2230 * @ops: oob ops structure
2231 * @len: size of oob to transfer
2233 static uint8_t *nand_transfer_oob(struct nand_chip *chip, uint8_t *oob,
2234 struct mtd_oob_ops *ops, size_t len)
2236 switch (ops->mode) {
2238 case MTD_OPS_PLACE_OOB:
2240 memcpy(oob, chip->oob_poi + ops->ooboffs, len);
2243 case MTD_OPS_AUTO_OOB: {
2244 struct nand_oobfree *free = chip->ecc.layout->oobfree;
2245 uint32_t boffs = 0, roffs = ops->ooboffs;
2248 for (; free->length && len; free++, len -= bytes) {
2249 /* Read request not from offset 0? */
2250 if (unlikely(roffs)) {
2251 if (roffs >= free->length) {
2252 roffs -= free->length;
2255 boffs = free->offset + roffs;
2256 bytes = min_t(size_t, len,
2257 (free->length - roffs));
2260 bytes = min_t(size_t, len, free->length);
2261 boffs = free->offset;
2263 memcpy(oob, chip->oob_poi + boffs, bytes);
2275 * nand_setup_read_retry - [INTERN] Set the READ RETRY mode
2276 * @mtd: MTD device structure
2277 * @retry_mode: the retry mode to use
2279 * Some vendors supply a special command to shift the Vt threshold, to be used
2280 * when there are too many bitflips in a page (i.e., ECC error). After setting
2281 * a new threshold, the host should retry reading the page.
2283 static int nand_setup_read_retry(struct mtd_info *mtd, int retry_mode)
2285 struct nand_chip *chip = mtd_to_nand(mtd);
2287 pr_debug("setting READ RETRY mode %d\n", retry_mode);
2289 if (retry_mode >= chip->read_retries)
2292 if (!chip->setup_read_retry)
2295 return chip->setup_read_retry(mtd, retry_mode);
2299 * nand_do_read_ops - [INTERN] Read data with ECC
2300 * @mtd: MTD device structure
2301 * @from: offset to read from
2302 * @ops: oob ops structure
2304 * Internal function. Called with chip held.
2306 static int nand_do_read_ops(struct mtd_info *mtd, loff_t from,
2307 struct mtd_oob_ops *ops)
2309 int chipnr, page, realpage, col, bytes, aligned, oob_required;
2310 struct nand_chip *chip = mtd_to_nand(mtd);
2312 uint32_t readlen = ops->len;
2313 uint32_t oobreadlen = ops->ooblen;
2314 uint32_t max_oobsize = mtd_oobavail(mtd, ops);
2316 uint8_t *bufpoi, *oob, *buf;
2318 unsigned int max_bitflips = 0;
2320 bool ecc_fail = false;
2322 chipnr = (int)(from >> chip->chip_shift);
2323 chip->select_chip(mtd, chipnr);
2325 realpage = (int)(from >> chip->page_shift);
2326 page = realpage & chip->pagemask;
2328 col = (int)(from & (mtd->writesize - 1));
2332 oob_required = oob ? 1 : 0;
2335 unsigned int ecc_failures = mtd->ecc_stats.failed;
2338 bytes = min(mtd->writesize - col, readlen);
2339 aligned = (bytes == mtd->writesize);
2343 else if (chip->options & NAND_USE_BOUNCE_BUFFER)
2344 use_bufpoi = !IS_ALIGNED((unsigned long)buf,
2349 /* Is the current page in the buffer? */
2350 if (realpage != chip->pagebuf || oob) {
2351 bufpoi = use_bufpoi ? chip->buffers->databuf : buf;
2353 if (use_bufpoi && aligned)
2354 pr_debug("%s: using read bounce buffer for buf@%p\n",
2358 if (nand_standard_page_accessors(&chip->ecc)) {
2359 ret = nand_read_page_op(chip, page, 0, NULL, 0);
2365 * Now read the page into the buffer. Absent an error,
2366 * the read methods return max bitflips per ecc step.
2368 if (unlikely(ops->mode == MTD_OPS_RAW))
2369 ret = chip->ecc.read_page_raw(mtd, chip, bufpoi,
2372 else if (!aligned && NAND_HAS_SUBPAGE_READ(chip) &&
2374 ret = chip->ecc.read_subpage(mtd, chip,
2378 ret = chip->ecc.read_page(mtd, chip, bufpoi,
2379 oob_required, page);
2382 /* Invalidate page cache */
2387 max_bitflips = max_t(unsigned int, max_bitflips, ret);
2389 /* Transfer not aligned data */
2391 if (!NAND_HAS_SUBPAGE_READ(chip) && !oob &&
2392 !(mtd->ecc_stats.failed - ecc_failures) &&
2393 (ops->mode != MTD_OPS_RAW)) {
2394 chip->pagebuf = realpage;
2395 chip->pagebuf_bitflips = ret;
2397 /* Invalidate page cache */
2400 memcpy(buf, chip->buffers->databuf + col, bytes);
2403 if (unlikely(oob)) {
2404 int toread = min(oobreadlen, max_oobsize);
2407 oob = nand_transfer_oob(chip,
2409 oobreadlen -= toread;
2413 if (chip->options & NAND_NEED_READRDY) {
2414 /* Apply delay or wait for ready/busy pin */
2415 if (!chip->dev_ready)
2416 udelay(chip->chip_delay);
2418 nand_wait_ready(mtd);
2421 if (mtd->ecc_stats.failed - ecc_failures) {
2422 if (retry_mode + 1 < chip->read_retries) {
2424 ret = nand_setup_read_retry(mtd,
2429 /* Reset failures; retry */
2430 mtd->ecc_stats.failed = ecc_failures;
2433 /* No more retry modes; real failure */
2440 memcpy(buf, chip->buffers->databuf + col, bytes);
2442 max_bitflips = max_t(unsigned int, max_bitflips,
2443 chip->pagebuf_bitflips);
2448 /* Reset to retry mode 0 */
2450 ret = nand_setup_read_retry(mtd, 0);
2459 /* For subsequent reads align to page boundary */
2461 /* Increment page address */
2464 page = realpage & chip->pagemask;
2465 /* Check, if we cross a chip boundary */
2468 chip->select_chip(mtd, -1);
2469 chip->select_chip(mtd, chipnr);
2472 chip->select_chip(mtd, -1);
2474 ops->retlen = ops->len - (size_t) readlen;
2476 ops->oobretlen = ops->ooblen - oobreadlen;
2484 return max_bitflips;
2488 * nand_read_oob_std - [REPLACEABLE] the most common OOB data read function
2489 * @mtd: mtd info structure
2490 * @chip: nand chip info structure
2491 * @page: page number to read
2493 static int nand_read_oob_std(struct mtd_info *mtd, struct nand_chip *chip,
2496 return nand_read_oob_op(chip, page, 0, chip->oob_poi, mtd->oobsize);
2500 * nand_read_oob_syndrome - [REPLACEABLE] OOB data read function for HW ECC
2502 * @mtd: mtd info structure
2503 * @chip: nand chip info structure
2504 * @page: page number to read
2506 static int nand_read_oob_syndrome(struct mtd_info *mtd, struct nand_chip *chip,
2509 int length = mtd->oobsize;
2510 int chunk = chip->ecc.bytes + chip->ecc.prepad + chip->ecc.postpad;
2511 int eccsize = chip->ecc.size;
2512 uint8_t *bufpoi = chip->oob_poi;
2513 int i, toread, sndrnd = 0, pos, ret;
2515 ret = nand_read_page_op(chip, page, chip->ecc.size, NULL, 0);
2519 for (i = 0; i < chip->ecc.steps; i++) {
2523 pos = eccsize + i * (eccsize + chunk);
2524 if (mtd->writesize > 512)
2525 ret = nand_change_read_column_op(chip, pos,
2529 ret = nand_read_page_op(chip, page, pos, NULL,
2536 toread = min_t(int, length, chunk);
2538 ret = nand_read_data_op(chip, bufpoi, toread, false);
2546 ret = nand_read_data_op(chip, bufpoi, length, false);
2555 * nand_write_oob_std - [REPLACEABLE] the most common OOB data write function
2556 * @mtd: mtd info structure
2557 * @chip: nand chip info structure
2558 * @page: page number to write
2560 static int nand_write_oob_std(struct mtd_info *mtd, struct nand_chip *chip,
2563 return nand_prog_page_op(chip, page, mtd->writesize, chip->oob_poi,
2568 * nand_write_oob_syndrome - [REPLACEABLE] OOB data write function for HW ECC
2569 * with syndrome - only for large page flash
2570 * @mtd: mtd info structure
2571 * @chip: nand chip info structure
2572 * @page: page number to write
2574 static int nand_write_oob_syndrome(struct mtd_info *mtd,
2575 struct nand_chip *chip, int page)
2577 int chunk = chip->ecc.bytes + chip->ecc.prepad + chip->ecc.postpad;
2578 int eccsize = chip->ecc.size, length = mtd->oobsize;
2579 int ret, i, len, pos, sndcmd = 0, steps = chip->ecc.steps;
2580 const uint8_t *bufpoi = chip->oob_poi;
2583 * data-ecc-data-ecc ... ecc-oob
2585 * data-pad-ecc-pad-data-pad .... ecc-pad-oob
2587 if (!chip->ecc.prepad && !chip->ecc.postpad) {
2588 pos = steps * (eccsize + chunk);
2593 ret = nand_prog_page_begin_op(chip, page, pos, NULL, 0);
2597 for (i = 0; i < steps; i++) {
2599 if (mtd->writesize <= 512) {
2600 uint32_t fill = 0xFFFFFFFF;
2604 int num = min_t(int, len, 4);
2606 ret = nand_write_data_op(chip, &fill,
2614 pos = eccsize + i * (eccsize + chunk);
2615 ret = nand_change_write_column_op(chip, pos,
2623 len = min_t(int, length, chunk);
2625 ret = nand_write_data_op(chip, bufpoi, len, false);
2633 ret = nand_write_data_op(chip, bufpoi, length, false);
2638 return nand_prog_page_end_op(chip);
2642 * nand_do_read_oob - [INTERN] NAND read out-of-band
2643 * @mtd: MTD device structure
2644 * @from: offset to read from
2645 * @ops: oob operations description structure
2647 * NAND read out-of-band data from the spare area.
2649 static int nand_do_read_oob(struct mtd_info *mtd, loff_t from,
2650 struct mtd_oob_ops *ops)
2652 int page, realpage, chipnr;
2653 struct nand_chip *chip = mtd_to_nand(mtd);
2654 struct mtd_ecc_stats stats;
2655 int readlen = ops->ooblen;
2657 uint8_t *buf = ops->oobbuf;
2660 pr_debug("%s: from = 0x%08Lx, len = %i\n",
2661 __func__, (unsigned long long)from, readlen);
2663 stats = mtd->ecc_stats;
2665 len = mtd_oobavail(mtd, ops);
2667 if (unlikely(ops->ooboffs >= len)) {
2668 pr_debug("%s: attempt to start read outside oob\n",
2673 /* Do not allow reads past end of device */
2674 if (unlikely(from >= mtd->size ||
2675 ops->ooboffs + readlen > ((mtd->size >> chip->page_shift) -
2676 (from >> chip->page_shift)) * len)) {
2677 pr_debug("%s: attempt to read beyond end of device\n",
2682 chipnr = (int)(from >> chip->chip_shift);
2683 chip->select_chip(mtd, chipnr);
2685 /* Shift to get page */
2686 realpage = (int)(from >> chip->page_shift);
2687 page = realpage & chip->pagemask;
2692 if (ops->mode == MTD_OPS_RAW)
2693 ret = chip->ecc.read_oob_raw(mtd, chip, page);
2695 ret = chip->ecc.read_oob(mtd, chip, page);
2700 len = min(len, readlen);
2701 buf = nand_transfer_oob(chip, buf, ops, len);
2703 if (chip->options & NAND_NEED_READRDY) {
2704 /* Apply delay or wait for ready/busy pin */
2705 if (!chip->dev_ready)
2706 udelay(chip->chip_delay);
2708 nand_wait_ready(mtd);
2715 /* Increment page address */
2718 page = realpage & chip->pagemask;
2719 /* Check, if we cross a chip boundary */
2722 chip->select_chip(mtd, -1);
2723 chip->select_chip(mtd, chipnr);
2726 chip->select_chip(mtd, -1);
2728 ops->oobretlen = ops->ooblen - readlen;
2733 if (mtd->ecc_stats.failed - stats.failed)
2736 return mtd->ecc_stats.corrected - stats.corrected ? -EUCLEAN : 0;
2740 * nand_read_oob - [MTD Interface] NAND read data and/or out-of-band
2741 * @mtd: MTD device structure
2742 * @from: offset to read from
2743 * @ops: oob operation description structure
2745 * NAND read data and/or out-of-band data.
2747 static int nand_read_oob(struct mtd_info *mtd, loff_t from,
2748 struct mtd_oob_ops *ops)
2750 int ret = -ENOTSUPP;
2754 /* Do not allow reads past end of device */
2755 if (ops->datbuf && (from + ops->len) > mtd->size) {
2756 pr_debug("%s: attempt to read beyond end of device\n",
2761 nand_get_device(mtd, FL_READING);
2763 switch (ops->mode) {
2764 case MTD_OPS_PLACE_OOB:
2765 case MTD_OPS_AUTO_OOB:
2774 ret = nand_do_read_oob(mtd, from, ops);
2776 ret = nand_do_read_ops(mtd, from, ops);
2779 nand_release_device(mtd);
2785 * nand_write_page_raw - [INTERN] raw page write function
2786 * @mtd: mtd info structure
2787 * @chip: nand chip info structure
2789 * @oob_required: must write chip->oob_poi to OOB
2790 * @page: page number to write
2792 * Not for syndrome calculating ECC controllers, which use a special oob layout.
2794 static int nand_write_page_raw(struct mtd_info *mtd, struct nand_chip *chip,
2795 const uint8_t *buf, int oob_required, int page)
2799 ret = nand_write_data_op(chip, buf, mtd->writesize, false);
2804 ret = nand_write_data_op(chip, chip->oob_poi, mtd->oobsize,
2814 * nand_write_page_raw_syndrome - [INTERN] raw page write function
2815 * @mtd: mtd info structure
2816 * @chip: nand chip info structure
2818 * @oob_required: must write chip->oob_poi to OOB
2819 * @page: page number to write
2821 * We need a special oob layout and handling even when ECC isn't checked.
2823 static int nand_write_page_raw_syndrome(struct mtd_info *mtd,
2824 struct nand_chip *chip,
2825 const uint8_t *buf, int oob_required,
2828 int eccsize = chip->ecc.size;
2829 int eccbytes = chip->ecc.bytes;
2830 uint8_t *oob = chip->oob_poi;
2831 int steps, size, ret;
2833 for (steps = chip->ecc.steps; steps > 0; steps--) {
2834 ret = nand_write_data_op(chip, buf, eccsize, false);
2840 if (chip->ecc.prepad) {
2841 ret = nand_write_data_op(chip, oob, chip->ecc.prepad,
2846 oob += chip->ecc.prepad;
2849 ret = nand_write_data_op(chip, oob, eccbytes, false);
2855 if (chip->ecc.postpad) {
2856 ret = nand_write_data_op(chip, oob, chip->ecc.postpad,
2861 oob += chip->ecc.postpad;
2865 size = mtd->oobsize - (oob - chip->oob_poi);
2867 ret = nand_write_data_op(chip, oob, size, false);
2875 * nand_write_page_swecc - [REPLACEABLE] software ECC based page write function
2876 * @mtd: mtd info structure
2877 * @chip: nand chip info structure
2879 * @oob_required: must write chip->oob_poi to OOB
2880 * @page: page number to write
2882 static int nand_write_page_swecc(struct mtd_info *mtd, struct nand_chip *chip,
2883 const uint8_t *buf, int oob_required,
2886 int i, eccsize = chip->ecc.size;
2887 int eccbytes = chip->ecc.bytes;
2888 int eccsteps = chip->ecc.steps;
2889 uint8_t *ecc_calc = chip->buffers->ecccalc;
2890 const uint8_t *p = buf;
2891 uint32_t *eccpos = chip->ecc.layout->eccpos;
2893 /* Software ECC calculation */
2894 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize)
2895 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
2897 for (i = 0; i < chip->ecc.total; i++)
2898 chip->oob_poi[eccpos[i]] = ecc_calc[i];
2900 return chip->ecc.write_page_raw(mtd, chip, buf, 1, page);
2904 * nand_write_page_hwecc - [REPLACEABLE] hardware ECC based page write function
2905 * @mtd: mtd info structure
2906 * @chip: nand chip info structure
2908 * @oob_required: must write chip->oob_poi to OOB
2909 * @page: page number to write
2911 static int nand_write_page_hwecc(struct mtd_info *mtd, struct nand_chip *chip,
2912 const uint8_t *buf, int oob_required,
2915 int i, eccsize = chip->ecc.size;
2916 int eccbytes = chip->ecc.bytes;
2917 int eccsteps = chip->ecc.steps;
2918 uint8_t *ecc_calc = chip->buffers->ecccalc;
2919 const uint8_t *p = buf;
2920 uint32_t *eccpos = chip->ecc.layout->eccpos;
2923 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
2924 chip->ecc.hwctl(mtd, NAND_ECC_WRITE);
2926 ret = nand_write_data_op(chip, p, eccsize, false);
2930 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
2933 for (i = 0; i < chip->ecc.total; i++)
2934 chip->oob_poi[eccpos[i]] = ecc_calc[i];
2936 ret = nand_write_data_op(chip, chip->oob_poi, mtd->oobsize, false);
2945 * nand_write_subpage_hwecc - [REPLACEABLE] hardware ECC based subpage write
2946 * @mtd: mtd info structure
2947 * @chip: nand chip info structure
2948 * @offset: column address of subpage within the page
2949 * @data_len: data length
2951 * @oob_required: must write chip->oob_poi to OOB
2952 * @page: page number to write
2954 static int nand_write_subpage_hwecc(struct mtd_info *mtd,
2955 struct nand_chip *chip, uint32_t offset,
2956 uint32_t data_len, const uint8_t *buf,
2957 int oob_required, int page)
2959 uint8_t *oob_buf = chip->oob_poi;
2960 uint8_t *ecc_calc = chip->buffers->ecccalc;
2961 int ecc_size = chip->ecc.size;
2962 int ecc_bytes = chip->ecc.bytes;
2963 int ecc_steps = chip->ecc.steps;
2964 uint32_t *eccpos = chip->ecc.layout->eccpos;
2965 uint32_t start_step = offset / ecc_size;
2966 uint32_t end_step = (offset + data_len - 1) / ecc_size;
2967 int oob_bytes = mtd->oobsize / ecc_steps;
2971 for (step = 0; step < ecc_steps; step++) {
2972 /* configure controller for WRITE access */
2973 chip->ecc.hwctl(mtd, NAND_ECC_WRITE);
2975 /* write data (untouched subpages already masked by 0xFF) */
2976 ret = nand_write_data_op(chip, buf, ecc_size, false);
2980 /* mask ECC of un-touched subpages by padding 0xFF */
2981 if ((step < start_step) || (step > end_step))
2982 memset(ecc_calc, 0xff, ecc_bytes);
2984 chip->ecc.calculate(mtd, buf, ecc_calc);
2986 /* mask OOB of un-touched subpages by padding 0xFF */
2987 /* if oob_required, preserve OOB metadata of written subpage */
2988 if (!oob_required || (step < start_step) || (step > end_step))
2989 memset(oob_buf, 0xff, oob_bytes);
2992 ecc_calc += ecc_bytes;
2993 oob_buf += oob_bytes;
2996 /* copy calculated ECC for whole page to chip->buffer->oob */
2997 /* this include masked-value(0xFF) for unwritten subpages */
2998 ecc_calc = chip->buffers->ecccalc;
2999 for (i = 0; i < chip->ecc.total; i++)
3000 chip->oob_poi[eccpos[i]] = ecc_calc[i];
3002 /* write OOB buffer to NAND device */
3003 ret = nand_write_data_op(chip, chip->oob_poi, mtd->oobsize, false);
3012 * nand_write_page_syndrome - [REPLACEABLE] hardware ECC syndrome based page write
3013 * @mtd: mtd info structure
3014 * @chip: nand chip info structure
3016 * @oob_required: must write chip->oob_poi to OOB
3017 * @page: page number to write
3019 * The hw generator calculates the error syndrome automatically. Therefore we
3020 * need a special oob layout and handling.
3022 static int nand_write_page_syndrome(struct mtd_info *mtd,
3023 struct nand_chip *chip,
3024 const uint8_t *buf, int oob_required,
3027 int i, eccsize = chip->ecc.size;
3028 int eccbytes = chip->ecc.bytes;
3029 int eccsteps = chip->ecc.steps;
3030 const uint8_t *p = buf;
3031 uint8_t *oob = chip->oob_poi;
3034 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
3035 chip->ecc.hwctl(mtd, NAND_ECC_WRITE);
3037 ret = nand_write_data_op(chip, p, eccsize, false);
3041 if (chip->ecc.prepad) {
3042 ret = nand_write_data_op(chip, oob, chip->ecc.prepad,
3047 oob += chip->ecc.prepad;
3050 chip->ecc.calculate(mtd, p, oob);
3052 ret = nand_write_data_op(chip, oob, eccbytes, false);
3058 if (chip->ecc.postpad) {
3059 ret = nand_write_data_op(chip, oob, chip->ecc.postpad,
3064 oob += chip->ecc.postpad;
3068 /* Calculate remaining oob bytes */
3069 i = mtd->oobsize - (oob - chip->oob_poi);
3071 ret = nand_write_data_op(chip, oob, i, false);
3080 * nand_write_page - [REPLACEABLE] write one page
3081 * @mtd: MTD device structure
3082 * @chip: NAND chip descriptor
3083 * @offset: address offset within the page
3084 * @data_len: length of actual data to be written
3085 * @buf: the data to write
3086 * @oob_required: must write chip->oob_poi to OOB
3087 * @page: page number to write
3088 * @raw: use _raw version of write_page
3090 static int nand_write_page(struct mtd_info *mtd, struct nand_chip *chip,
3091 uint32_t offset, int data_len, const uint8_t *buf,
3092 int oob_required, int page, int raw)
3094 int status, subpage;
3096 if (!(chip->options & NAND_NO_SUBPAGE_WRITE) &&
3097 chip->ecc.write_subpage)
3098 subpage = offset || (data_len < mtd->writesize);
3102 if (nand_standard_page_accessors(&chip->ecc)) {
3103 status = nand_prog_page_begin_op(chip, page, 0, NULL, 0);
3109 status = chip->ecc.write_page_raw(mtd, chip, buf,
3110 oob_required, page);
3112 status = chip->ecc.write_subpage(mtd, chip, offset, data_len,
3113 buf, oob_required, page);
3115 status = chip->ecc.write_page(mtd, chip, buf, oob_required,
3121 if (nand_standard_page_accessors(&chip->ecc))
3122 return nand_prog_page_end_op(chip);
3128 * nand_fill_oob - [INTERN] Transfer client buffer to oob
3129 * @mtd: MTD device structure
3130 * @oob: oob data buffer
3131 * @len: oob data write length
3132 * @ops: oob ops structure
3134 static uint8_t *nand_fill_oob(struct mtd_info *mtd, uint8_t *oob, size_t len,
3135 struct mtd_oob_ops *ops)
3137 struct nand_chip *chip = mtd_to_nand(mtd);
3140 * Initialise to all 0xFF, to avoid the possibility of left over OOB
3141 * data from a previous OOB read.
3143 memset(chip->oob_poi, 0xff, mtd->oobsize);
3145 switch (ops->mode) {
3147 case MTD_OPS_PLACE_OOB:
3149 memcpy(chip->oob_poi + ops->ooboffs, oob, len);
3152 case MTD_OPS_AUTO_OOB: {
3153 struct nand_oobfree *free = chip->ecc.layout->oobfree;
3154 uint32_t boffs = 0, woffs = ops->ooboffs;
3157 for (; free->length && len; free++, len -= bytes) {
3158 /* Write request not from offset 0? */
3159 if (unlikely(woffs)) {
3160 if (woffs >= free->length) {
3161 woffs -= free->length;
3164 boffs = free->offset + woffs;
3165 bytes = min_t(size_t, len,
3166 (free->length - woffs));
3169 bytes = min_t(size_t, len, free->length);
3170 boffs = free->offset;
3172 memcpy(chip->oob_poi + boffs, oob, bytes);
3183 #define NOTALIGNED(x) ((x & (chip->subpagesize - 1)) != 0)
3186 * nand_do_write_ops - [INTERN] NAND write with ECC
3187 * @mtd: MTD device structure
3188 * @to: offset to write to
3189 * @ops: oob operations description structure
3191 * NAND write with ECC.
3193 static int nand_do_write_ops(struct mtd_info *mtd, loff_t to,
3194 struct mtd_oob_ops *ops)
3196 int chipnr, realpage, page, column;
3197 struct nand_chip *chip = mtd_to_nand(mtd);
3198 uint32_t writelen = ops->len;
3200 uint32_t oobwritelen = ops->ooblen;
3201 uint32_t oobmaxlen = mtd_oobavail(mtd, ops);
3203 uint8_t *oob = ops->oobbuf;
3204 uint8_t *buf = ops->datbuf;
3206 int oob_required = oob ? 1 : 0;
3212 /* Reject writes, which are not page aligned */
3213 if (NOTALIGNED(to)) {
3214 pr_notice("%s: attempt to write non page aligned data\n",
3219 column = to & (mtd->writesize - 1);
3221 chipnr = (int)(to >> chip->chip_shift);
3222 chip->select_chip(mtd, chipnr);
3224 /* Check, if it is write protected */
3225 if (nand_check_wp(mtd)) {
3230 realpage = (int)(to >> chip->page_shift);
3231 page = realpage & chip->pagemask;
3233 /* Invalidate the page cache, when we write to the cached page */
3234 if (to <= ((loff_t)chip->pagebuf << chip->page_shift) &&
3235 ((loff_t)chip->pagebuf << chip->page_shift) < (to + ops->len))
3238 /* Don't allow multipage oob writes with offset */
3239 if (oob && ops->ooboffs && (ops->ooboffs + ops->ooblen > oobmaxlen)) {
3245 int bytes = mtd->writesize;
3246 uint8_t *wbuf = buf;
3248 int part_pagewr = (column || writelen < mtd->writesize);
3252 else if (chip->options & NAND_USE_BOUNCE_BUFFER)
3253 use_bufpoi = !IS_ALIGNED((unsigned long)buf,
3259 /* Partial page write?, or need to use bounce buffer */
3261 pr_debug("%s: using write bounce buffer for buf@%p\n",
3264 bytes = min_t(int, bytes - column, writelen);
3266 memset(chip->buffers->databuf, 0xff, mtd->writesize);
3267 memcpy(&chip->buffers->databuf[column], buf, bytes);
3268 wbuf = chip->buffers->databuf;
3271 if (unlikely(oob)) {
3272 size_t len = min(oobwritelen, oobmaxlen);
3273 oob = nand_fill_oob(mtd, oob, len, ops);
3276 /* We still need to erase leftover OOB data */
3277 memset(chip->oob_poi, 0xff, mtd->oobsize);
3279 ret = chip->write_page(mtd, chip, column, bytes, wbuf,
3281 (ops->mode == MTD_OPS_RAW));
3293 page = realpage & chip->pagemask;
3294 /* Check, if we cross a chip boundary */
3297 chip->select_chip(mtd, -1);
3298 chip->select_chip(mtd, chipnr);
3302 ops->retlen = ops->len - writelen;
3304 ops->oobretlen = ops->ooblen;
3307 chip->select_chip(mtd, -1);
3312 * panic_nand_write - [MTD Interface] NAND write with ECC
3313 * @mtd: MTD device structure
3314 * @to: offset to write to
3315 * @len: number of bytes to write
3316 * @retlen: pointer to variable to store the number of written bytes
3317 * @buf: the data to write
3319 * NAND write with ECC. Used when performing writes in interrupt context, this
3320 * may for example be called by mtdoops when writing an oops while in panic.
3322 static int panic_nand_write(struct mtd_info *mtd, loff_t to, size_t len,
3323 size_t *retlen, const uint8_t *buf)
3325 struct nand_chip *chip = mtd_to_nand(mtd);
3326 struct mtd_oob_ops ops;
3329 /* Wait for the device to get ready */
3330 panic_nand_wait(mtd, chip, 400);
3332 /* Grab the device */
3333 panic_nand_get_device(chip, mtd, FL_WRITING);
3335 memset(&ops, 0, sizeof(ops));
3337 ops.datbuf = (uint8_t *)buf;
3338 ops.mode = MTD_OPS_PLACE_OOB;
3340 ret = nand_do_write_ops(mtd, to, &ops);
3342 *retlen = ops.retlen;
3347 * nand_do_write_oob - [MTD Interface] NAND write out-of-band
3348 * @mtd: MTD device structure
3349 * @to: offset to write to
3350 * @ops: oob operation description structure
3352 * NAND write out-of-band.
3354 static int nand_do_write_oob(struct mtd_info *mtd, loff_t to,
3355 struct mtd_oob_ops *ops)
3357 int chipnr, page, status, len;
3358 struct nand_chip *chip = mtd_to_nand(mtd);
3360 pr_debug("%s: to = 0x%08x, len = %i\n",
3361 __func__, (unsigned int)to, (int)ops->ooblen);
3363 len = mtd_oobavail(mtd, ops);
3365 /* Do not allow write past end of page */
3366 if ((ops->ooboffs + ops->ooblen) > len) {
3367 pr_debug("%s: attempt to write past end of page\n",
3372 if (unlikely(ops->ooboffs >= len)) {
3373 pr_debug("%s: attempt to start write outside oob\n",
3378 /* Do not allow write past end of device */
3379 if (unlikely(to >= mtd->size ||
3380 ops->ooboffs + ops->ooblen >
3381 ((mtd->size >> chip->page_shift) -
3382 (to >> chip->page_shift)) * len)) {
3383 pr_debug("%s: attempt to write beyond end of device\n",
3388 chipnr = (int)(to >> chip->chip_shift);
3391 * Reset the chip. Some chips (like the Toshiba TC5832DC found in one
3392 * of my DiskOnChip 2000 test units) will clear the whole data page too
3393 * if we don't do this. I have no clue why, but I seem to have 'fixed'
3394 * it in the doc2000 driver in August 1999. dwmw2.
3396 nand_reset(chip, chipnr);
3398 chip->select_chip(mtd, chipnr);
3400 /* Shift to get page */
3401 page = (int)(to >> chip->page_shift);
3403 /* Check, if it is write protected */
3404 if (nand_check_wp(mtd)) {
3405 chip->select_chip(mtd, -1);
3409 /* Invalidate the page cache, if we write to the cached page */
3410 if (page == chip->pagebuf)
3413 nand_fill_oob(mtd, ops->oobbuf, ops->ooblen, ops);
3415 if (ops->mode == MTD_OPS_RAW)
3416 status = chip->ecc.write_oob_raw(mtd, chip, page & chip->pagemask);
3418 status = chip->ecc.write_oob(mtd, chip, page & chip->pagemask);
3420 chip->select_chip(mtd, -1);
3425 ops->oobretlen = ops->ooblen;
3431 * nand_write_oob - [MTD Interface] NAND write data and/or out-of-band
3432 * @mtd: MTD device structure
3433 * @to: offset to write to
3434 * @ops: oob operation description structure
3436 static int nand_write_oob(struct mtd_info *mtd, loff_t to,
3437 struct mtd_oob_ops *ops)
3439 int ret = -ENOTSUPP;
3443 /* Do not allow writes past end of device */
3444 if (ops->datbuf && (to + ops->len) > mtd->size) {
3445 pr_debug("%s: attempt to write beyond end of device\n",
3450 nand_get_device(mtd, FL_WRITING);
3452 switch (ops->mode) {
3453 case MTD_OPS_PLACE_OOB:
3454 case MTD_OPS_AUTO_OOB:
3463 ret = nand_do_write_oob(mtd, to, ops);
3465 ret = nand_do_write_ops(mtd, to, ops);
3468 nand_release_device(mtd);
3473 * single_erase - [GENERIC] NAND standard block erase command function
3474 * @mtd: MTD device structure
3475 * @page: the page address of the block which will be erased
3477 * Standard erase command for NAND chips. Returns NAND status.
3479 static int single_erase(struct mtd_info *mtd, int page)
3481 struct nand_chip *chip = mtd_to_nand(mtd);
3482 unsigned int eraseblock;
3484 /* Send commands to erase a block */
3485 eraseblock = page >> (chip->phys_erase_shift - chip->page_shift);
3487 return nand_erase_op(chip, eraseblock);
3491 * nand_erase - [MTD Interface] erase block(s)
3492 * @mtd: MTD device structure
3493 * @instr: erase instruction
3495 * Erase one ore more blocks.
3497 static int nand_erase(struct mtd_info *mtd, struct erase_info *instr)
3499 return nand_erase_nand(mtd, instr, 0);
3503 * nand_erase_nand - [INTERN] erase block(s)
3504 * @mtd: MTD device structure
3505 * @instr: erase instruction
3506 * @allowbbt: allow erasing the bbt area
3508 * Erase one ore more blocks.
3510 int nand_erase_nand(struct mtd_info *mtd, struct erase_info *instr,
3513 int page, status, pages_per_block, ret, chipnr;
3514 struct nand_chip *chip = mtd_to_nand(mtd);
3517 pr_debug("%s: start = 0x%012llx, len = %llu\n",
3518 __func__, (unsigned long long)instr->addr,
3519 (unsigned long long)instr->len);
3521 if (check_offs_len(mtd, instr->addr, instr->len))
3524 /* Grab the lock and see if the device is available */
3525 nand_get_device(mtd, FL_ERASING);
3527 /* Shift to get first page */
3528 page = (int)(instr->addr >> chip->page_shift);
3529 chipnr = (int)(instr->addr >> chip->chip_shift);
3531 /* Calculate pages in each block */
3532 pages_per_block = 1 << (chip->phys_erase_shift - chip->page_shift);
3534 /* Select the NAND device */
3535 chip->select_chip(mtd, chipnr);
3537 /* Check, if it is write protected */
3538 if (nand_check_wp(mtd)) {
3539 pr_debug("%s: device is write protected!\n",
3541 instr->state = MTD_ERASE_FAILED;
3545 /* Loop through the pages */
3548 instr->state = MTD_ERASING;
3553 /* Check if we have a bad block, we do not erase bad blocks! */
3554 if (!instr->scrub && nand_block_checkbad(mtd, ((loff_t) page) <<
3555 chip->page_shift, allowbbt)) {
3556 pr_warn("%s: attempt to erase a bad block at page 0x%08x\n",
3558 instr->state = MTD_ERASE_FAILED;
3560 ((loff_t)page << chip->page_shift);
3565 * Invalidate the page cache, if we erase the block which
3566 * contains the current cached page.
3568 if (page <= chip->pagebuf && chip->pagebuf <
3569 (page + pages_per_block))
3572 status = chip->erase(mtd, page & chip->pagemask);
3574 /* See if block erase succeeded */
3575 if (status & NAND_STATUS_FAIL) {
3576 pr_debug("%s: failed erase, page 0x%08x\n",
3578 instr->state = MTD_ERASE_FAILED;
3580 ((loff_t)page << chip->page_shift);
3584 /* Increment page address and decrement length */
3585 len -= (1ULL << chip->phys_erase_shift);
3586 page += pages_per_block;
3588 /* Check, if we cross a chip boundary */
3589 if (len && !(page & chip->pagemask)) {
3591 chip->select_chip(mtd, -1);
3592 chip->select_chip(mtd, chipnr);
3595 instr->state = MTD_ERASE_DONE;
3599 ret = instr->state == MTD_ERASE_DONE ? 0 : -EIO;
3601 /* Deselect and wake up anyone waiting on the device */
3602 chip->select_chip(mtd, -1);
3603 nand_release_device(mtd);
3605 /* Do call back function */
3607 mtd_erase_callback(instr);
3609 /* Return more or less happy */
3614 * nand_sync - [MTD Interface] sync
3615 * @mtd: MTD device structure
3617 * Sync is actually a wait for chip ready function.
3619 static void nand_sync(struct mtd_info *mtd)
3621 pr_debug("%s: called\n", __func__);
3623 /* Grab the lock and see if the device is available */
3624 nand_get_device(mtd, FL_SYNCING);
3625 /* Release it and go back */
3626 nand_release_device(mtd);
3630 * nand_block_isbad - [MTD Interface] Check if block at offset is bad
3631 * @mtd: MTD device structure
3632 * @offs: offset relative to mtd start
3634 static int nand_block_isbad(struct mtd_info *mtd, loff_t offs)
3636 struct nand_chip *chip = mtd_to_nand(mtd);
3637 int chipnr = (int)(offs >> chip->chip_shift);
3640 /* Select the NAND device */
3641 nand_get_device(mtd, FL_READING);
3642 chip->select_chip(mtd, chipnr);
3644 ret = nand_block_checkbad(mtd, offs, 0);
3646 chip->select_chip(mtd, -1);
3647 nand_release_device(mtd);
3653 * nand_block_markbad - [MTD Interface] Mark block at the given offset as bad
3654 * @mtd: MTD device structure
3655 * @ofs: offset relative to mtd start
3657 static int nand_block_markbad(struct mtd_info *mtd, loff_t ofs)
3661 ret = nand_block_isbad(mtd, ofs);
3663 /* If it was bad already, return success and do nothing */
3669 return nand_block_markbad_lowlevel(mtd, ofs);
3673 * nand_onfi_set_features- [REPLACEABLE] set features for ONFI nand
3674 * @mtd: MTD device structure
3675 * @chip: nand chip info structure
3676 * @addr: feature address.
3677 * @subfeature_param: the subfeature parameters, a four bytes array.
3679 static int nand_onfi_set_features(struct mtd_info *mtd, struct nand_chip *chip,
3680 int addr, uint8_t *subfeature_param)
3682 #ifdef CONFIG_SYS_NAND_ONFI_DETECTION
3683 if (!chip->onfi_version ||
3684 !(le16_to_cpu(chip->onfi_params.opt_cmd)
3685 & ONFI_OPT_CMD_SET_GET_FEATURES))
3689 return nand_set_features_op(chip, addr, subfeature_param);
3693 * nand_onfi_get_features- [REPLACEABLE] get features for ONFI nand
3694 * @mtd: MTD device structure
3695 * @chip: nand chip info structure
3696 * @addr: feature address.
3697 * @subfeature_param: the subfeature parameters, a four bytes array.
3699 static int nand_onfi_get_features(struct mtd_info *mtd, struct nand_chip *chip,
3700 int addr, uint8_t *subfeature_param)
3702 #ifdef CONFIG_SYS_NAND_ONFI_DETECTION
3703 if (!chip->onfi_version ||
3704 !(le16_to_cpu(chip->onfi_params.opt_cmd)
3705 & ONFI_OPT_CMD_SET_GET_FEATURES))
3709 return nand_get_features_op(chip, addr, subfeature_param);
3712 /* Set default functions */
3713 static void nand_set_defaults(struct nand_chip *chip, int busw)
3715 /* check for proper chip_delay setup, set 20us if not */
3716 if (!chip->chip_delay)
3717 chip->chip_delay = 20;
3719 /* check, if a user supplied command function given */
3720 if (chip->cmdfunc == NULL)
3721 chip->cmdfunc = nand_command;
3723 /* check, if a user supplied wait function given */
3724 if (chip->waitfunc == NULL)
3725 chip->waitfunc = nand_wait;
3727 if (!chip->select_chip)
3728 chip->select_chip = nand_select_chip;
3730 /* set for ONFI nand */
3731 if (!chip->onfi_set_features)
3732 chip->onfi_set_features = nand_onfi_set_features;
3733 if (!chip->onfi_get_features)
3734 chip->onfi_get_features = nand_onfi_get_features;
3736 /* If called twice, pointers that depend on busw may need to be reset */
3737 if (!chip->read_byte || chip->read_byte == nand_read_byte)
3738 chip->read_byte = busw ? nand_read_byte16 : nand_read_byte;
3739 if (!chip->read_word)
3740 chip->read_word = nand_read_word;
3741 if (!chip->block_bad)
3742 chip->block_bad = nand_block_bad;
3743 if (!chip->block_markbad)
3744 chip->block_markbad = nand_default_block_markbad;
3745 if (!chip->write_buf || chip->write_buf == nand_write_buf)
3746 chip->write_buf = busw ? nand_write_buf16 : nand_write_buf;
3747 if (!chip->write_byte || chip->write_byte == nand_write_byte)
3748 chip->write_byte = busw ? nand_write_byte16 : nand_write_byte;
3749 if (!chip->read_buf || chip->read_buf == nand_read_buf)
3750 chip->read_buf = busw ? nand_read_buf16 : nand_read_buf;
3751 if (!chip->scan_bbt)
3752 chip->scan_bbt = nand_default_bbt;
3754 if (!chip->controller) {
3755 chip->controller = &chip->hwcontrol;
3756 spin_lock_init(&chip->controller->lock);
3757 init_waitqueue_head(&chip->controller->wq);
3760 if (!chip->buf_align)
3761 chip->buf_align = 1;
3764 /* Sanitize ONFI strings so we can safely print them */
3765 static void sanitize_string(char *s, size_t len)
3769 /* Null terminate */
3772 /* Remove non printable chars */
3773 for (i = 0; i < len - 1; i++) {
3774 if (s[i] < ' ' || s[i] > 127)
3778 /* Remove trailing spaces */
3782 static u16 onfi_crc16(u16 crc, u8 const *p, size_t len)
3787 for (i = 0; i < 8; i++)
3788 crc = (crc << 1) ^ ((crc & 0x8000) ? 0x8005 : 0);
3794 #ifdef CONFIG_SYS_NAND_ONFI_DETECTION
3795 /* Parse the Extended Parameter Page. */
3796 static int nand_flash_detect_ext_param_page(struct mtd_info *mtd,
3797 struct nand_chip *chip, struct nand_onfi_params *p)
3799 struct onfi_ext_param_page *ep;
3800 struct onfi_ext_section *s;
3801 struct onfi_ext_ecc_info *ecc;
3807 len = le16_to_cpu(p->ext_param_page_length) * 16;
3808 ep = kmalloc(len, GFP_KERNEL);
3812 /* Send our own NAND_CMD_PARAM. */
3813 ret = nand_read_param_page_op(chip, 0, NULL, 0);
3817 /* Use the Change Read Column command to skip the ONFI param pages. */
3818 ret = nand_change_read_column_op(chip,
3819 sizeof(*p) * p->num_of_param_pages,
3825 if ((onfi_crc16(ONFI_CRC_BASE, ((uint8_t *)ep) + 2, len - 2)
3826 != le16_to_cpu(ep->crc))) {
3827 pr_debug("fail in the CRC.\n");
3832 * Check the signature.
3833 * Do not strictly follow the ONFI spec, maybe changed in future.
3835 if (strncmp((char *)ep->sig, "EPPS", 4)) {
3836 pr_debug("The signature is invalid.\n");
3840 /* find the ECC section. */
3841 cursor = (uint8_t *)(ep + 1);
3842 for (i = 0; i < ONFI_EXT_SECTION_MAX; i++) {
3843 s = ep->sections + i;
3844 if (s->type == ONFI_SECTION_TYPE_2)
3846 cursor += s->length * 16;
3848 if (i == ONFI_EXT_SECTION_MAX) {
3849 pr_debug("We can not find the ECC section.\n");
3853 /* get the info we want. */
3854 ecc = (struct onfi_ext_ecc_info *)cursor;
3856 if (!ecc->codeword_size) {
3857 pr_debug("Invalid codeword size\n");
3861 chip->ecc_strength_ds = ecc->ecc_bits;
3862 chip->ecc_step_ds = 1 << ecc->codeword_size;
3870 static int nand_setup_read_retry_micron(struct mtd_info *mtd, int retry_mode)
3872 struct nand_chip *chip = mtd_to_nand(mtd);
3873 uint8_t feature[ONFI_SUBFEATURE_PARAM_LEN] = {retry_mode};
3875 return chip->onfi_set_features(mtd, chip, ONFI_FEATURE_ADDR_READ_RETRY,
3880 * Configure chip properties from Micron vendor-specific ONFI table
3882 static void nand_onfi_detect_micron(struct nand_chip *chip,
3883 struct nand_onfi_params *p)
3885 struct nand_onfi_vendor_micron *micron = (void *)p->vendor;
3887 if (le16_to_cpu(p->vendor_revision) < 1)
3890 chip->read_retries = micron->read_retry_options;
3891 chip->setup_read_retry = nand_setup_read_retry_micron;
3895 * Check if the NAND chip is ONFI compliant, returns 1 if it is, 0 otherwise.
3897 static int nand_flash_detect_onfi(struct mtd_info *mtd, struct nand_chip *chip,
3900 struct nand_onfi_params *p = &chip->onfi_params;
3904 /* Try ONFI for unknown chip or LP */
3905 ret = nand_readid_op(chip, 0x20, id, sizeof(id));
3906 if (ret || strncmp(id, "ONFI", 4))
3909 ret = nand_read_param_page_op(chip, 0, NULL, 0);
3913 for (i = 0; i < 3; i++) {
3914 ret = nand_read_data_op(chip, p, sizeof(*p), true);
3918 if (onfi_crc16(ONFI_CRC_BASE, (uint8_t *)p, 254) ==
3919 le16_to_cpu(p->crc)) {
3925 pr_err("Could not find valid ONFI parameter page; aborting\n");
3930 val = le16_to_cpu(p->revision);
3932 chip->onfi_version = 23;
3933 else if (val & (1 << 4))
3934 chip->onfi_version = 22;
3935 else if (val & (1 << 3))
3936 chip->onfi_version = 21;
3937 else if (val & (1 << 2))
3938 chip->onfi_version = 20;
3939 else if (val & (1 << 1))
3940 chip->onfi_version = 10;
3942 if (!chip->onfi_version) {
3943 pr_info("unsupported ONFI version: %d\n", val);
3947 sanitize_string(p->manufacturer, sizeof(p->manufacturer));
3948 sanitize_string(p->model, sizeof(p->model));
3950 mtd->name = p->model;
3952 mtd->writesize = le32_to_cpu(p->byte_per_page);
3955 * pages_per_block and blocks_per_lun may not be a power-of-2 size
3956 * (don't ask me who thought of this...). MTD assumes that these
3957 * dimensions will be power-of-2, so just truncate the remaining area.
3959 mtd->erasesize = 1 << (fls(le32_to_cpu(p->pages_per_block)) - 1);
3960 mtd->erasesize *= mtd->writesize;
3962 mtd->oobsize = le16_to_cpu(p->spare_bytes_per_page);
3964 /* See erasesize comment */
3965 chip->chipsize = 1 << (fls(le32_to_cpu(p->blocks_per_lun)) - 1);
3966 chip->chipsize *= (uint64_t)mtd->erasesize * p->lun_count;
3967 chip->bits_per_cell = p->bits_per_cell;
3969 if (onfi_feature(chip) & ONFI_FEATURE_16_BIT_BUS)
3970 *busw = NAND_BUSWIDTH_16;
3974 if (p->ecc_bits != 0xff) {
3975 chip->ecc_strength_ds = p->ecc_bits;
3976 chip->ecc_step_ds = 512;
3977 } else if (chip->onfi_version >= 21 &&
3978 (onfi_feature(chip) & ONFI_FEATURE_EXT_PARAM_PAGE)) {
3981 * The nand_flash_detect_ext_param_page() uses the
3982 * Change Read Column command which maybe not supported
3983 * by the chip->cmdfunc. So try to update the chip->cmdfunc
3984 * now. We do not replace user supplied command function.
3986 if (mtd->writesize > 512 && chip->cmdfunc == nand_command)
3987 chip->cmdfunc = nand_command_lp;
3989 /* The Extended Parameter Page is supported since ONFI 2.1. */
3990 if (nand_flash_detect_ext_param_page(mtd, chip, p))
3991 pr_warn("Failed to detect ONFI extended param page\n");
3993 pr_warn("Could not retrieve ONFI ECC requirements\n");
3996 if (p->jedec_id == NAND_MFR_MICRON)
3997 nand_onfi_detect_micron(chip, p);
4002 static int nand_flash_detect_onfi(struct mtd_info *mtd, struct nand_chip *chip,
4010 * Check if the NAND chip is JEDEC compliant, returns 1 if it is, 0 otherwise.
4012 static int nand_flash_detect_jedec(struct mtd_info *mtd, struct nand_chip *chip,
4015 struct nand_jedec_params *p = &chip->jedec_params;
4016 struct jedec_ecc_info *ecc;
4020 /* Try JEDEC for unknown chip or LP */
4021 ret = nand_readid_op(chip, 0x40, id, sizeof(id));
4022 if (ret || strncmp(id, "JEDEC", sizeof(id)))
4025 ret = nand_read_param_page_op(chip, 0x40, NULL, 0);
4029 for (i = 0; i < 3; i++) {
4030 ret = nand_read_data_op(chip, p, sizeof(*p), true);
4034 if (onfi_crc16(ONFI_CRC_BASE, (uint8_t *)p, 510) ==
4035 le16_to_cpu(p->crc))
4040 pr_err("Could not find valid JEDEC parameter page; aborting\n");
4045 val = le16_to_cpu(p->revision);
4047 chip->jedec_version = 10;
4048 else if (val & (1 << 1))
4049 chip->jedec_version = 1; /* vendor specific version */
4051 if (!chip->jedec_version) {
4052 pr_info("unsupported JEDEC version: %d\n", val);
4056 sanitize_string(p->manufacturer, sizeof(p->manufacturer));
4057 sanitize_string(p->model, sizeof(p->model));
4059 mtd->name = p->model;
4061 mtd->writesize = le32_to_cpu(p->byte_per_page);
4063 /* Please reference to the comment for nand_flash_detect_onfi. */
4064 mtd->erasesize = 1 << (fls(le32_to_cpu(p->pages_per_block)) - 1);
4065 mtd->erasesize *= mtd->writesize;
4067 mtd->oobsize = le16_to_cpu(p->spare_bytes_per_page);
4069 /* Please reference to the comment for nand_flash_detect_onfi. */
4070 chip->chipsize = 1 << (fls(le32_to_cpu(p->blocks_per_lun)) - 1);
4071 chip->chipsize *= (uint64_t)mtd->erasesize * p->lun_count;
4072 chip->bits_per_cell = p->bits_per_cell;
4074 if (jedec_feature(chip) & JEDEC_FEATURE_16_BIT_BUS)
4075 *busw = NAND_BUSWIDTH_16;
4080 ecc = &p->ecc_info[0];
4082 if (ecc->codeword_size >= 9) {
4083 chip->ecc_strength_ds = ecc->ecc_bits;
4084 chip->ecc_step_ds = 1 << ecc->codeword_size;
4086 pr_warn("Invalid codeword size\n");
4093 * nand_id_has_period - Check if an ID string has a given wraparound period
4094 * @id_data: the ID string
4095 * @arrlen: the length of the @id_data array
4096 * @period: the period of repitition
4098 * Check if an ID string is repeated within a given sequence of bytes at
4099 * specific repetition interval period (e.g., {0x20,0x01,0x7F,0x20} has a
4100 * period of 3). This is a helper function for nand_id_len(). Returns non-zero
4101 * if the repetition has a period of @period; otherwise, returns zero.
4103 static int nand_id_has_period(u8 *id_data, int arrlen, int period)
4106 for (i = 0; i < period; i++)
4107 for (j = i + period; j < arrlen; j += period)
4108 if (id_data[i] != id_data[j])
4114 * nand_id_len - Get the length of an ID string returned by CMD_READID
4115 * @id_data: the ID string
4116 * @arrlen: the length of the @id_data array
4118 * Returns the length of the ID string, according to known wraparound/trailing
4119 * zero patterns. If no pattern exists, returns the length of the array.
4121 static int nand_id_len(u8 *id_data, int arrlen)
4123 int last_nonzero, period;
4125 /* Find last non-zero byte */
4126 for (last_nonzero = arrlen - 1; last_nonzero >= 0; last_nonzero--)
4127 if (id_data[last_nonzero])
4131 if (last_nonzero < 0)
4134 /* Calculate wraparound period */
4135 for (period = 1; period < arrlen; period++)
4136 if (nand_id_has_period(id_data, arrlen, period))
4139 /* There's a repeated pattern */
4140 if (period < arrlen)
4143 /* There are trailing zeros */
4144 if (last_nonzero < arrlen - 1)
4145 return last_nonzero + 1;
4147 /* No pattern detected */
4151 /* Extract the bits of per cell from the 3rd byte of the extended ID */
4152 static int nand_get_bits_per_cell(u8 cellinfo)
4156 bits = cellinfo & NAND_CI_CELLTYPE_MSK;
4157 bits >>= NAND_CI_CELLTYPE_SHIFT;
4162 * Many new NAND share similar device ID codes, which represent the size of the
4163 * chip. The rest of the parameters must be decoded according to generic or
4164 * manufacturer-specific "extended ID" decoding patterns.
4166 static void nand_decode_ext_id(struct mtd_info *mtd, struct nand_chip *chip,
4167 u8 id_data[8], int *busw)
4170 /* The 3rd id byte holds MLC / multichip data */
4171 chip->bits_per_cell = nand_get_bits_per_cell(id_data[2]);
4172 /* The 4th id byte is the important one */
4175 id_len = nand_id_len(id_data, 8);
4178 * Field definitions are in the following datasheets:
4179 * Old style (4,5 byte ID): Samsung K9GAG08U0M (p.32)
4180 * New Samsung (6 byte ID): Samsung K9GAG08U0F (p.44)
4181 * Hynix MLC (6 byte ID): Hynix H27UBG8T2B (p.22)
4183 * Check for ID length, non-zero 6th byte, cell type, and Hynix/Samsung
4184 * ID to decide what to do.
4186 if (id_len == 6 && id_data[0] == NAND_MFR_SAMSUNG &&
4187 !nand_is_slc(chip) && id_data[5] != 0x00) {
4189 mtd->writesize = 2048 << (extid & 0x03);
4192 switch (((extid >> 2) & 0x04) | (extid & 0x03)) {
4212 default: /* Other cases are "reserved" (unknown) */
4213 mtd->oobsize = 1024;
4217 /* Calc blocksize */
4218 mtd->erasesize = (128 * 1024) <<
4219 (((extid >> 1) & 0x04) | (extid & 0x03));
4221 } else if (id_len == 6 && id_data[0] == NAND_MFR_HYNIX &&
4222 !nand_is_slc(chip)) {
4226 mtd->writesize = 2048 << (extid & 0x03);
4229 switch (((extid >> 2) & 0x04) | (extid & 0x03)) {
4253 /* Calc blocksize */
4254 tmp = ((extid >> 1) & 0x04) | (extid & 0x03);
4256 mtd->erasesize = (128 * 1024) << tmp;
4257 else if (tmp == 0x03)
4258 mtd->erasesize = 768 * 1024;
4260 mtd->erasesize = (64 * 1024) << tmp;
4264 mtd->writesize = 1024 << (extid & 0x03);
4267 mtd->oobsize = (8 << (extid & 0x01)) *
4268 (mtd->writesize >> 9);
4270 /* Calc blocksize. Blocksize is multiples of 64KiB */
4271 mtd->erasesize = (64 * 1024) << (extid & 0x03);
4273 /* Get buswidth information */
4274 *busw = (extid & 0x01) ? NAND_BUSWIDTH_16 : 0;
4277 * Toshiba 24nm raw SLC (i.e., not BENAND) have 32B OOB per
4278 * 512B page. For Toshiba SLC, we decode the 5th/6th byte as
4280 * - ID byte 6, bits[2:0]: 100b -> 43nm, 101b -> 32nm,
4282 * - ID byte 5, bit[7]: 1 -> BENAND, 0 -> raw SLC
4284 if (id_len >= 6 && id_data[0] == NAND_MFR_TOSHIBA &&
4285 nand_is_slc(chip) &&
4286 (id_data[5] & 0x7) == 0x6 /* 24nm */ &&
4287 !(id_data[4] & 0x80) /* !BENAND */) {
4288 mtd->oobsize = 32 * mtd->writesize >> 9;
4295 * Old devices have chip data hardcoded in the device ID table. nand_decode_id
4296 * decodes a matching ID table entry and assigns the MTD size parameters for
4299 static void nand_decode_id(struct mtd_info *mtd, struct nand_chip *chip,
4300 struct nand_flash_dev *type, u8 id_data[8],
4303 int maf_id = id_data[0];
4305 mtd->erasesize = type->erasesize;
4306 mtd->writesize = type->pagesize;
4307 mtd->oobsize = mtd->writesize / 32;
4308 *busw = type->options & NAND_BUSWIDTH_16;
4310 /* All legacy ID NAND are small-page, SLC */
4311 chip->bits_per_cell = 1;
4314 * Check for Spansion/AMD ID + repeating 5th, 6th byte since
4315 * some Spansion chips have erasesize that conflicts with size
4316 * listed in nand_ids table.
4317 * Data sheet (5 byte ID): Spansion S30ML-P ORNAND (p.39)
4319 if (maf_id == NAND_MFR_AMD && id_data[4] != 0x00 && id_data[5] == 0x00
4320 && id_data[6] == 0x00 && id_data[7] == 0x00
4321 && mtd->writesize == 512) {
4322 mtd->erasesize = 128 * 1024;
4323 mtd->erasesize <<= ((id_data[3] & 0x03) << 1);
4328 * Set the bad block marker/indicator (BBM/BBI) patterns according to some
4329 * heuristic patterns using various detected parameters (e.g., manufacturer,
4330 * page size, cell-type information).
4332 static void nand_decode_bbm_options(struct mtd_info *mtd,
4333 struct nand_chip *chip, u8 id_data[8])
4335 int maf_id = id_data[0];
4337 /* Set the bad block position */
4338 if (mtd->writesize > 512 || (chip->options & NAND_BUSWIDTH_16))
4339 chip->badblockpos = NAND_LARGE_BADBLOCK_POS;
4341 chip->badblockpos = NAND_SMALL_BADBLOCK_POS;
4344 * Bad block marker is stored in the last page of each block on Samsung
4345 * and Hynix MLC devices; stored in first two pages of each block on
4346 * Micron devices with 2KiB pages and on SLC Samsung, Hynix, Toshiba,
4347 * AMD/Spansion, and Macronix. All others scan only the first page.
4349 if (!nand_is_slc(chip) &&
4350 (maf_id == NAND_MFR_SAMSUNG ||
4351 maf_id == NAND_MFR_HYNIX))
4352 chip->bbt_options |= NAND_BBT_SCANLASTPAGE;
4353 else if ((nand_is_slc(chip) &&
4354 (maf_id == NAND_MFR_SAMSUNG ||
4355 maf_id == NAND_MFR_HYNIX ||
4356 maf_id == NAND_MFR_TOSHIBA ||
4357 maf_id == NAND_MFR_AMD ||
4358 maf_id == NAND_MFR_MACRONIX)) ||
4359 (mtd->writesize == 2048 &&
4360 maf_id == NAND_MFR_MICRON))
4361 chip->bbt_options |= NAND_BBT_SCAN2NDPAGE;
4364 static inline bool is_full_id_nand(struct nand_flash_dev *type)
4366 return type->id_len;
4369 static bool find_full_id_nand(struct mtd_info *mtd, struct nand_chip *chip,
4370 struct nand_flash_dev *type, u8 *id_data, int *busw)
4372 if (!strncmp((char *)type->id, (char *)id_data, type->id_len)) {
4373 mtd->writesize = type->pagesize;
4374 mtd->erasesize = type->erasesize;
4375 mtd->oobsize = type->oobsize;
4377 chip->bits_per_cell = nand_get_bits_per_cell(id_data[2]);
4378 chip->chipsize = (uint64_t)type->chipsize << 20;
4379 chip->options |= type->options;
4380 chip->ecc_strength_ds = NAND_ECC_STRENGTH(type);
4381 chip->ecc_step_ds = NAND_ECC_STEP(type);
4382 chip->onfi_timing_mode_default =
4383 type->onfi_timing_mode_default;
4385 *busw = type->options & NAND_BUSWIDTH_16;
4388 mtd->name = type->name;
4396 * Get the flash and manufacturer id and lookup if the type is supported.
4398 struct nand_flash_dev *nand_get_flash_type(struct mtd_info *mtd,
4399 struct nand_chip *chip,
4400 int *maf_id, int *dev_id,
4401 struct nand_flash_dev *type)
4408 * Reset the chip, required by some chips (e.g. Micron MT29FxGxxxxx)
4411 ret = nand_reset(chip, 0);
4413 return ERR_PTR(ret);
4415 /* Select the device */
4416 chip->select_chip(mtd, 0);
4418 /* Send the command for reading device ID */
4419 ret = nand_readid_op(chip, 0, id_data, 2);
4421 return ERR_PTR(ret);
4423 /* Read manufacturer and device IDs */
4424 *maf_id = id_data[0];
4425 *dev_id = id_data[1];
4428 * Try again to make sure, as some systems the bus-hold or other
4429 * interface concerns can cause random data which looks like a
4430 * possibly credible NAND flash to appear. If the two results do
4431 * not match, ignore the device completely.
4434 /* Read entire ID string */
4435 ret = nand_readid_op(chip, 0, id_data, 8);
4437 return ERR_PTR(ret);
4439 if (id_data[0] != *maf_id || id_data[1] != *dev_id) {
4440 pr_info("second ID read did not match %02x,%02x against %02x,%02x\n",
4441 *maf_id, *dev_id, id_data[0], id_data[1]);
4442 return ERR_PTR(-ENODEV);
4446 type = nand_flash_ids;
4448 for (; type->name != NULL; type++) {
4449 if (is_full_id_nand(type)) {
4450 if (find_full_id_nand(mtd, chip, type, id_data, &busw))
4452 } else if (*dev_id == type->dev_id) {
4457 chip->onfi_version = 0;
4458 if (!type->name || !type->pagesize) {
4459 /* Check if the chip is ONFI compliant */
4460 if (nand_flash_detect_onfi(mtd, chip, &busw))
4463 /* Check if the chip is JEDEC compliant */
4464 if (nand_flash_detect_jedec(mtd, chip, &busw))
4469 return ERR_PTR(-ENODEV);
4472 mtd->name = type->name;
4474 chip->chipsize = (uint64_t)type->chipsize << 20;
4476 if (!type->pagesize) {
4477 /* Decode parameters from extended ID */
4478 nand_decode_ext_id(mtd, chip, id_data, &busw);
4480 nand_decode_id(mtd, chip, type, id_data, &busw);
4482 /* Get chip options */
4483 chip->options |= type->options;
4486 * Check if chip is not a Samsung device. Do not clear the
4487 * options for chips which do not have an extended id.
4489 if (*maf_id != NAND_MFR_SAMSUNG && !type->pagesize)
4490 chip->options &= ~NAND_SAMSUNG_LP_OPTIONS;
4493 /* Try to identify manufacturer */
4494 for (maf_idx = 0; nand_manuf_ids[maf_idx].id != 0x0; maf_idx++) {
4495 if (nand_manuf_ids[maf_idx].id == *maf_id)
4499 if (chip->options & NAND_BUSWIDTH_AUTO) {
4500 WARN_ON(chip->options & NAND_BUSWIDTH_16);
4501 chip->options |= busw;
4502 nand_set_defaults(chip, busw);
4503 } else if (busw != (chip->options & NAND_BUSWIDTH_16)) {
4505 * Check, if buswidth is correct. Hardware drivers should set
4508 pr_info("device found, Manufacturer ID: 0x%02x, Chip ID: 0x%02x\n",
4510 pr_info("%s %s\n", nand_manuf_ids[maf_idx].name, mtd->name);
4511 pr_warn("bus width %d instead %d bit\n",
4512 (chip->options & NAND_BUSWIDTH_16) ? 16 : 8,
4514 return ERR_PTR(-EINVAL);
4517 nand_decode_bbm_options(mtd, chip, id_data);
4519 /* Calculate the address shift from the page size */
4520 chip->page_shift = ffs(mtd->writesize) - 1;
4521 /* Convert chipsize to number of pages per chip -1 */
4522 chip->pagemask = (chip->chipsize >> chip->page_shift) - 1;
4524 chip->bbt_erase_shift = chip->phys_erase_shift =
4525 ffs(mtd->erasesize) - 1;
4526 if (chip->chipsize & 0xffffffff)
4527 chip->chip_shift = ffs((unsigned)chip->chipsize) - 1;
4529 chip->chip_shift = ffs((unsigned)(chip->chipsize >> 32));
4530 chip->chip_shift += 32 - 1;
4533 if (chip->chip_shift - chip->page_shift > 16)
4534 chip->options |= NAND_ROW_ADDR_3;
4536 chip->badblockbits = 8;
4537 chip->erase = single_erase;
4539 /* Do not replace user supplied command function! */
4540 if (mtd->writesize > 512 && chip->cmdfunc == nand_command)
4541 chip->cmdfunc = nand_command_lp;
4543 pr_info("device found, Manufacturer ID: 0x%02x, Chip ID: 0x%02x\n",
4546 #ifdef CONFIG_SYS_NAND_ONFI_DETECTION
4547 if (chip->onfi_version)
4548 pr_info("%s %s\n", nand_manuf_ids[maf_idx].name,
4549 chip->onfi_params.model);
4550 else if (chip->jedec_version)
4551 pr_info("%s %s\n", nand_manuf_ids[maf_idx].name,
4552 chip->jedec_params.model);
4554 pr_info("%s %s\n", nand_manuf_ids[maf_idx].name,
4557 if (chip->jedec_version)
4558 pr_info("%s %s\n", nand_manuf_ids[maf_idx].name,
4559 chip->jedec_params.model);
4561 pr_info("%s %s\n", nand_manuf_ids[maf_idx].name,
4564 pr_info("%s %s\n", nand_manuf_ids[maf_idx].name,
4568 pr_info("%d MiB, %s, erase size: %d KiB, page size: %d, OOB size: %d\n",
4569 (int)(chip->chipsize >> 20), nand_is_slc(chip) ? "SLC" : "MLC",
4570 mtd->erasesize >> 10, mtd->writesize, mtd->oobsize);
4573 EXPORT_SYMBOL(nand_get_flash_type);
4575 #if CONFIG_IS_ENABLED(OF_CONTROL)
4577 static int nand_dt_init(struct mtd_info *mtd, struct nand_chip *chip, ofnode node)
4579 int ret, ecc_mode = -1, ecc_strength, ecc_step;
4582 ret = ofnode_read_s32_default(node, "nand-bus-width", -1);
4584 chip->options |= NAND_BUSWIDTH_16;
4586 if (ofnode_read_bool(node, "nand-on-flash-bbt"))
4587 chip->bbt_options |= NAND_BBT_USE_FLASH;
4589 str = ofnode_read_string(node, "nand-ecc-mode");
4591 if (!strcmp(str, "none"))
4592 ecc_mode = NAND_ECC_NONE;
4593 else if (!strcmp(str, "soft"))
4594 ecc_mode = NAND_ECC_SOFT;
4595 else if (!strcmp(str, "hw"))
4596 ecc_mode = NAND_ECC_HW;
4597 else if (!strcmp(str, "hw_syndrome"))
4598 ecc_mode = NAND_ECC_HW_SYNDROME;
4599 else if (!strcmp(str, "hw_oob_first"))
4600 ecc_mode = NAND_ECC_HW_OOB_FIRST;
4601 else if (!strcmp(str, "soft_bch"))
4602 ecc_mode = NAND_ECC_SOFT_BCH;
4605 ecc_strength = ofnode_read_s32_default(node,
4606 "nand-ecc-strength", -1);
4607 ecc_step = ofnode_read_s32_default(node,
4608 "nand-ecc-step-size", -1);
4610 if ((ecc_step >= 0 && !(ecc_strength >= 0)) ||
4611 (!(ecc_step >= 0) && ecc_strength >= 0)) {
4612 pr_err("must set both strength and step size in DT\n");
4617 chip->ecc.mode = ecc_mode;
4619 if (ecc_strength >= 0)
4620 chip->ecc.strength = ecc_strength;
4623 chip->ecc.size = ecc_step;
4625 if (ofnode_read_bool(node, "nand-ecc-maximize"))
4626 chip->ecc.options |= NAND_ECC_MAXIMIZE;
4631 static int nand_dt_init(struct mtd_info *mtd, struct nand_chip *chip, ofnode node)
4635 #endif /* CONFIG_IS_ENABLED(OF_CONTROL) */
4638 * nand_scan_ident - [NAND Interface] Scan for the NAND device
4639 * @mtd: MTD device structure
4640 * @maxchips: number of chips to scan for
4641 * @table: alternative NAND ID table
4643 * This is the first phase of the normal nand_scan() function. It reads the
4644 * flash ID and sets up MTD fields accordingly.
4647 int nand_scan_ident(struct mtd_info *mtd, int maxchips,
4648 struct nand_flash_dev *table)
4650 int i, nand_maf_id, nand_dev_id;
4651 struct nand_chip *chip = mtd_to_nand(mtd);
4652 struct nand_flash_dev *type;
4655 if (ofnode_valid(chip->flash_node)) {
4656 ret = nand_dt_init(mtd, chip, chip->flash_node);
4661 /* Set the default functions */
4662 nand_set_defaults(chip, chip->options & NAND_BUSWIDTH_16);
4664 /* Read the flash type */
4665 type = nand_get_flash_type(mtd, chip, &nand_maf_id,
4666 &nand_dev_id, table);
4669 if (!(chip->options & NAND_SCAN_SILENT_NODEV))
4670 pr_warn("No NAND device found\n");
4671 chip->select_chip(mtd, -1);
4672 return PTR_ERR(type);
4675 /* Initialize the ->data_interface field. */
4676 ret = nand_init_data_interface(chip);
4681 * Setup the data interface correctly on the chip and controller side.
4682 * This explicit call to nand_setup_data_interface() is only required
4683 * for the first die, because nand_reset() has been called before
4684 * ->data_interface and ->default_onfi_timing_mode were set.
4685 * For the other dies, nand_reset() will automatically switch to the
4688 ret = nand_setup_data_interface(chip, 0);
4692 chip->select_chip(mtd, -1);
4694 /* Check for a chip array */
4695 for (i = 1; i < maxchips; i++) {
4698 /* See comment in nand_get_flash_type for reset */
4699 nand_reset(chip, i);
4701 chip->select_chip(mtd, i);
4702 /* Send the command for reading device ID */
4703 nand_readid_op(chip, 0, id, sizeof(id));
4705 /* Read manufacturer and device IDs */
4706 if (nand_maf_id != id[0] || nand_dev_id != id[1]) {
4707 chip->select_chip(mtd, -1);
4710 chip->select_chip(mtd, -1);
4715 pr_info("%d chips detected\n", i);
4718 /* Store the number of chips and calc total size for mtd */
4720 mtd->size = i * chip->chipsize;
4724 EXPORT_SYMBOL(nand_scan_ident);
4727 * nand_check_ecc_caps - check the sanity of preset ECC settings
4728 * @chip: nand chip info structure
4729 * @caps: ECC caps info structure
4730 * @oobavail: OOB size that the ECC engine can use
4732 * When ECC step size and strength are already set, check if they are supported
4733 * by the controller and the calculated ECC bytes fit within the chip's OOB.
4734 * On success, the calculated ECC bytes is set.
4736 int nand_check_ecc_caps(struct nand_chip *chip,
4737 const struct nand_ecc_caps *caps, int oobavail)
4739 struct mtd_info *mtd = nand_to_mtd(chip);
4740 const struct nand_ecc_step_info *stepinfo;
4741 int preset_step = chip->ecc.size;
4742 int preset_strength = chip->ecc.strength;
4743 int nsteps, ecc_bytes;
4746 if (WARN_ON(oobavail < 0))
4749 if (!preset_step || !preset_strength)
4752 nsteps = mtd->writesize / preset_step;
4754 for (i = 0; i < caps->nstepinfos; i++) {
4755 stepinfo = &caps->stepinfos[i];
4757 if (stepinfo->stepsize != preset_step)
4760 for (j = 0; j < stepinfo->nstrengths; j++) {
4761 if (stepinfo->strengths[j] != preset_strength)
4764 ecc_bytes = caps->calc_ecc_bytes(preset_step,
4766 if (WARN_ON_ONCE(ecc_bytes < 0))
4769 if (ecc_bytes * nsteps > oobavail) {
4770 pr_err("ECC (step, strength) = (%d, %d) does not fit in OOB",
4771 preset_step, preset_strength);
4775 chip->ecc.bytes = ecc_bytes;
4781 pr_err("ECC (step, strength) = (%d, %d) not supported on this controller",
4782 preset_step, preset_strength);
4786 EXPORT_SYMBOL_GPL(nand_check_ecc_caps);
4789 * nand_match_ecc_req - meet the chip's requirement with least ECC bytes
4790 * @chip: nand chip info structure
4791 * @caps: ECC engine caps info structure
4792 * @oobavail: OOB size that the ECC engine can use
4794 * If a chip's ECC requirement is provided, try to meet it with the least
4795 * number of ECC bytes (i.e. with the largest number of OOB-free bytes).
4796 * On success, the chosen ECC settings are set.
4798 int nand_match_ecc_req(struct nand_chip *chip,
4799 const struct nand_ecc_caps *caps, int oobavail)
4801 struct mtd_info *mtd = nand_to_mtd(chip);
4802 const struct nand_ecc_step_info *stepinfo;
4803 int req_step = chip->ecc_step_ds;
4804 int req_strength = chip->ecc_strength_ds;
4805 int req_corr, step_size, strength, nsteps, ecc_bytes, ecc_bytes_total;
4806 int best_step, best_strength, best_ecc_bytes;
4807 int best_ecc_bytes_total = INT_MAX;
4810 if (WARN_ON(oobavail < 0))
4813 /* No information provided by the NAND chip */
4814 if (!req_step || !req_strength)
4817 /* number of correctable bits the chip requires in a page */
4818 req_corr = mtd->writesize / req_step * req_strength;
4820 for (i = 0; i < caps->nstepinfos; i++) {
4821 stepinfo = &caps->stepinfos[i];
4822 step_size = stepinfo->stepsize;
4824 for (j = 0; j < stepinfo->nstrengths; j++) {
4825 strength = stepinfo->strengths[j];
4828 * If both step size and strength are smaller than the
4829 * chip's requirement, it is not easy to compare the
4830 * resulted reliability.
4832 if (step_size < req_step && strength < req_strength)
4835 if (mtd->writesize % step_size)
4838 nsteps = mtd->writesize / step_size;
4840 ecc_bytes = caps->calc_ecc_bytes(step_size, strength);
4841 if (WARN_ON_ONCE(ecc_bytes < 0))
4843 ecc_bytes_total = ecc_bytes * nsteps;
4845 if (ecc_bytes_total > oobavail ||
4846 strength * nsteps < req_corr)
4850 * We assume the best is to meet the chip's requrement
4851 * with the least number of ECC bytes.
4853 if (ecc_bytes_total < best_ecc_bytes_total) {
4854 best_ecc_bytes_total = ecc_bytes_total;
4855 best_step = step_size;
4856 best_strength = strength;
4857 best_ecc_bytes = ecc_bytes;
4862 if (best_ecc_bytes_total == INT_MAX)
4865 chip->ecc.size = best_step;
4866 chip->ecc.strength = best_strength;
4867 chip->ecc.bytes = best_ecc_bytes;
4871 EXPORT_SYMBOL_GPL(nand_match_ecc_req);
4874 * nand_maximize_ecc - choose the max ECC strength available
4875 * @chip: nand chip info structure
4876 * @caps: ECC engine caps info structure
4877 * @oobavail: OOB size that the ECC engine can use
4879 * Choose the max ECC strength that is supported on the controller, and can fit
4880 * within the chip's OOB. On success, the chosen ECC settings are set.
4882 int nand_maximize_ecc(struct nand_chip *chip,
4883 const struct nand_ecc_caps *caps, int oobavail)
4885 struct mtd_info *mtd = nand_to_mtd(chip);
4886 const struct nand_ecc_step_info *stepinfo;
4887 int step_size, strength, nsteps, ecc_bytes, corr;
4890 int best_strength, best_ecc_bytes;
4893 if (WARN_ON(oobavail < 0))
4896 for (i = 0; i < caps->nstepinfos; i++) {
4897 stepinfo = &caps->stepinfos[i];
4898 step_size = stepinfo->stepsize;
4900 /* If chip->ecc.size is already set, respect it */
4901 if (chip->ecc.size && step_size != chip->ecc.size)
4904 for (j = 0; j < stepinfo->nstrengths; j++) {
4905 strength = stepinfo->strengths[j];
4907 if (mtd->writesize % step_size)
4910 nsteps = mtd->writesize / step_size;
4912 ecc_bytes = caps->calc_ecc_bytes(step_size, strength);
4913 if (WARN_ON_ONCE(ecc_bytes < 0))
4916 if (ecc_bytes * nsteps > oobavail)
4919 corr = strength * nsteps;
4922 * If the number of correctable bits is the same,
4923 * bigger step_size has more reliability.
4925 if (corr > best_corr ||
4926 (corr == best_corr && step_size > best_step)) {
4928 best_step = step_size;
4929 best_strength = strength;
4930 best_ecc_bytes = ecc_bytes;
4938 chip->ecc.size = best_step;
4939 chip->ecc.strength = best_strength;
4940 chip->ecc.bytes = best_ecc_bytes;
4944 EXPORT_SYMBOL_GPL(nand_maximize_ecc);
4947 * Check if the chip configuration meet the datasheet requirements.
4949 * If our configuration corrects A bits per B bytes and the minimum
4950 * required correction level is X bits per Y bytes, then we must ensure
4951 * both of the following are true:
4953 * (1) A / B >= X / Y
4956 * Requirement (1) ensures we can correct for the required bitflip density.
4957 * Requirement (2) ensures we can correct even when all bitflips are clumped
4958 * in the same sector.
4960 static bool nand_ecc_strength_good(struct mtd_info *mtd)
4962 struct nand_chip *chip = mtd_to_nand(mtd);
4963 struct nand_ecc_ctrl *ecc = &chip->ecc;
4966 if (ecc->size == 0 || chip->ecc_step_ds == 0)
4967 /* Not enough information */
4971 * We get the number of corrected bits per page to compare
4972 * the correction density.
4974 corr = (mtd->writesize * ecc->strength) / ecc->size;
4975 ds_corr = (mtd->writesize * chip->ecc_strength_ds) / chip->ecc_step_ds;
4977 return corr >= ds_corr && ecc->strength >= chip->ecc_strength_ds;
4980 static bool invalid_ecc_page_accessors(struct nand_chip *chip)
4982 struct nand_ecc_ctrl *ecc = &chip->ecc;
4984 if (nand_standard_page_accessors(ecc))
4988 * NAND_ECC_CUSTOM_PAGE_ACCESS flag is set, make sure the NAND
4989 * controller driver implements all the page accessors because
4990 * default helpers are not suitable when the core does not
4991 * send the READ0/PAGEPROG commands.
4993 return (!ecc->read_page || !ecc->write_page ||
4994 !ecc->read_page_raw || !ecc->write_page_raw ||
4995 (NAND_HAS_SUBPAGE_READ(chip) && !ecc->read_subpage) ||
4996 (NAND_HAS_SUBPAGE_WRITE(chip) && !ecc->write_subpage &&
4997 ecc->hwctl && ecc->calculate));
5001 * nand_scan_tail - [NAND Interface] Scan for the NAND device
5002 * @mtd: MTD device structure
5004 * This is the second phase of the normal nand_scan() function. It fills out
5005 * all the uninitialized function pointers with the defaults and scans for a
5006 * bad block table if appropriate.
5008 int nand_scan_tail(struct mtd_info *mtd)
5011 struct nand_chip *chip = mtd_to_nand(mtd);
5012 struct nand_ecc_ctrl *ecc = &chip->ecc;
5013 struct nand_buffers *nbuf;
5015 /* New bad blocks should be marked in OOB, flash-based BBT, or both */
5016 BUG_ON((chip->bbt_options & NAND_BBT_NO_OOB_BBM) &&
5017 !(chip->bbt_options & NAND_BBT_USE_FLASH));
5019 if (invalid_ecc_page_accessors(chip)) {
5020 pr_err("Invalid ECC page accessors setup\n");
5024 if (!(chip->options & NAND_OWN_BUFFERS)) {
5025 nbuf = kzalloc(sizeof(struct nand_buffers), GFP_KERNEL);
5026 chip->buffers = nbuf;
5032 /* Set the internal oob buffer location, just after the page data */
5033 chip->oob_poi = chip->buffers->databuf + mtd->writesize;
5036 * If no default placement scheme is given, select an appropriate one.
5038 if (!ecc->layout && (ecc->mode != NAND_ECC_SOFT_BCH)) {
5039 switch (mtd->oobsize) {
5040 #ifndef CONFIG_SYS_NAND_DRIVER_ECC_LAYOUT
5042 ecc->layout = &nand_oob_8;
5045 ecc->layout = &nand_oob_16;
5048 ecc->layout = &nand_oob_64;
5051 ecc->layout = &nand_oob_128;
5055 pr_warn("No oob scheme defined for oobsize %d\n",
5061 if (!chip->write_page)
5062 chip->write_page = nand_write_page;
5065 * Check ECC mode, default to software if 3byte/512byte hardware ECC is
5066 * selected and we have 256 byte pagesize fallback to software ECC
5069 switch (ecc->mode) {
5070 case NAND_ECC_HW_OOB_FIRST:
5071 /* Similar to NAND_ECC_HW, but a separate read_page handle */
5072 if (!ecc->calculate || !ecc->correct || !ecc->hwctl) {
5073 pr_warn("No ECC functions supplied; hardware ECC not possible\n");
5076 if (!ecc->read_page)
5077 ecc->read_page = nand_read_page_hwecc_oob_first;
5080 /* Use standard hwecc read page function? */
5081 if (!ecc->read_page)
5082 ecc->read_page = nand_read_page_hwecc;
5083 if (!ecc->write_page)
5084 ecc->write_page = nand_write_page_hwecc;
5085 if (!ecc->read_page_raw)
5086 ecc->read_page_raw = nand_read_page_raw;
5087 if (!ecc->write_page_raw)
5088 ecc->write_page_raw = nand_write_page_raw;
5090 ecc->read_oob = nand_read_oob_std;
5091 if (!ecc->write_oob)
5092 ecc->write_oob = nand_write_oob_std;
5093 if (!ecc->read_subpage)
5094 ecc->read_subpage = nand_read_subpage;
5095 if (!ecc->write_subpage && ecc->hwctl && ecc->calculate)
5096 ecc->write_subpage = nand_write_subpage_hwecc;
5098 case NAND_ECC_HW_SYNDROME:
5099 if ((!ecc->calculate || !ecc->correct || !ecc->hwctl) &&
5101 ecc->read_page == nand_read_page_hwecc ||
5103 ecc->write_page == nand_write_page_hwecc)) {
5104 pr_warn("No ECC functions supplied; hardware ECC not possible\n");
5107 /* Use standard syndrome read/write page function? */
5108 if (!ecc->read_page)
5109 ecc->read_page = nand_read_page_syndrome;
5110 if (!ecc->write_page)
5111 ecc->write_page = nand_write_page_syndrome;
5112 if (!ecc->read_page_raw)
5113 ecc->read_page_raw = nand_read_page_raw_syndrome;
5114 if (!ecc->write_page_raw)
5115 ecc->write_page_raw = nand_write_page_raw_syndrome;
5117 ecc->read_oob = nand_read_oob_syndrome;
5118 if (!ecc->write_oob)
5119 ecc->write_oob = nand_write_oob_syndrome;
5121 if (mtd->writesize >= ecc->size) {
5122 if (!ecc->strength) {
5123 pr_warn("Driver must set ecc.strength when using hardware ECC\n");
5128 pr_warn("%d byte HW ECC not possible on %d byte page size, fallback to SW ECC\n",
5129 ecc->size, mtd->writesize);
5130 ecc->mode = NAND_ECC_SOFT;
5133 ecc->calculate = nand_calculate_ecc;
5134 ecc->correct = nand_correct_data;
5135 ecc->read_page = nand_read_page_swecc;
5136 ecc->read_subpage = nand_read_subpage;
5137 ecc->write_page = nand_write_page_swecc;
5138 ecc->read_page_raw = nand_read_page_raw;
5139 ecc->write_page_raw = nand_write_page_raw;
5140 ecc->read_oob = nand_read_oob_std;
5141 ecc->write_oob = nand_write_oob_std;
5148 case NAND_ECC_SOFT_BCH:
5149 if (!mtd_nand_has_bch()) {
5150 pr_warn("CONFIG_MTD_NAND_ECC_BCH not enabled\n");
5153 ecc->calculate = nand_bch_calculate_ecc;
5154 ecc->correct = nand_bch_correct_data;
5155 ecc->read_page = nand_read_page_swecc;
5156 ecc->read_subpage = nand_read_subpage;
5157 ecc->write_page = nand_write_page_swecc;
5158 ecc->read_page_raw = nand_read_page_raw;
5159 ecc->write_page_raw = nand_write_page_raw;
5160 ecc->read_oob = nand_read_oob_std;
5161 ecc->write_oob = nand_write_oob_std;
5163 * Board driver should supply ecc.size and ecc.strength values
5164 * to select how many bits are correctable. Otherwise, default
5165 * to 4 bits for large page devices.
5167 if (!ecc->size && (mtd->oobsize >= 64)) {
5172 /* See nand_bch_init() for details. */
5174 ecc->priv = nand_bch_init(mtd);
5176 pr_warn("BCH ECC initialization failed!\n");
5182 pr_warn("NAND_ECC_NONE selected by board driver. This is not recommended!\n");
5183 ecc->read_page = nand_read_page_raw;
5184 ecc->write_page = nand_write_page_raw;
5185 ecc->read_oob = nand_read_oob_std;
5186 ecc->read_page_raw = nand_read_page_raw;
5187 ecc->write_page_raw = nand_write_page_raw;
5188 ecc->write_oob = nand_write_oob_std;
5189 ecc->size = mtd->writesize;
5195 pr_warn("Invalid NAND_ECC_MODE %d\n", ecc->mode);
5199 /* For many systems, the standard OOB write also works for raw */
5200 if (!ecc->read_oob_raw)
5201 ecc->read_oob_raw = ecc->read_oob;
5202 if (!ecc->write_oob_raw)
5203 ecc->write_oob_raw = ecc->write_oob;
5206 * The number of bytes available for a client to place data into
5207 * the out of band area.
5211 for (i = 0; ecc->layout->oobfree[i].length; i++)
5212 mtd->oobavail += ecc->layout->oobfree[i].length;
5215 /* ECC sanity check: warn if it's too weak */
5216 if (!nand_ecc_strength_good(mtd))
5217 pr_warn("WARNING: %s: the ECC used on your system is too weak compared to the one required by the NAND chip\n",
5221 * Set the number of read / write steps for one page depending on ECC
5224 ecc->steps = mtd->writesize / ecc->size;
5225 if (ecc->steps * ecc->size != mtd->writesize) {
5226 pr_warn("Invalid ECC parameters\n");
5229 ecc->total = ecc->steps * ecc->bytes;
5231 /* Allow subpage writes up to ecc.steps. Not possible for MLC flash */
5232 if (!(chip->options & NAND_NO_SUBPAGE_WRITE) && nand_is_slc(chip)) {
5233 switch (ecc->steps) {
5235 mtd->subpage_sft = 1;
5240 mtd->subpage_sft = 2;
5244 chip->subpagesize = mtd->writesize >> mtd->subpage_sft;
5246 /* Initialize state */
5247 chip->state = FL_READY;
5249 /* Invalidate the pagebuffer reference */
5252 /* Large page NAND with SOFT_ECC should support subpage reads */
5253 switch (ecc->mode) {
5255 case NAND_ECC_SOFT_BCH:
5256 if (chip->page_shift > 9)
5257 chip->options |= NAND_SUBPAGE_READ;
5264 /* Fill in remaining MTD driver data */
5265 mtd->type = nand_is_slc(chip) ? MTD_NANDFLASH : MTD_MLCNANDFLASH;
5266 mtd->flags = (chip->options & NAND_ROM) ? MTD_CAP_ROM :
5268 mtd->_erase = nand_erase;
5269 mtd->_panic_write = panic_nand_write;
5270 mtd->_read_oob = nand_read_oob;
5271 mtd->_write_oob = nand_write_oob;
5272 mtd->_sync = nand_sync;
5274 mtd->_unlock = NULL;
5275 mtd->_block_isreserved = nand_block_isreserved;
5276 mtd->_block_isbad = nand_block_isbad;
5277 mtd->_block_markbad = nand_block_markbad;
5278 mtd->writebufsize = mtd->writesize;
5280 /* propagate ecc info to mtd_info */
5281 mtd->ecclayout = ecc->layout;
5282 mtd->ecc_strength = ecc->strength;
5283 mtd->ecc_step_size = ecc->size;
5285 * Initialize bitflip_threshold to its default prior scan_bbt() call.
5286 * scan_bbt() might invoke mtd_read(), thus bitflip_threshold must be
5289 if (!mtd->bitflip_threshold)
5290 mtd->bitflip_threshold = DIV_ROUND_UP(mtd->ecc_strength * 3, 4);
5294 EXPORT_SYMBOL(nand_scan_tail);
5297 * nand_scan - [NAND Interface] Scan for the NAND device
5298 * @mtd: MTD device structure
5299 * @maxchips: number of chips to scan for
5301 * This fills out all the uninitialized function pointers with the defaults.
5302 * The flash ID is read and the mtd/chip structures are filled with the
5303 * appropriate values.
5305 int nand_scan(struct mtd_info *mtd, int maxchips)
5309 ret = nand_scan_ident(mtd, maxchips, NULL);
5311 ret = nand_scan_tail(mtd);
5314 EXPORT_SYMBOL(nand_scan);
5316 MODULE_LICENSE("GPL");
5317 MODULE_AUTHOR("Steven J. Hill <sjhill@realitydiluted.com>");
5318 MODULE_AUTHOR("Thomas Gleixner <tglx@linutronix.de>");
5319 MODULE_DESCRIPTION("Generic NAND flash driver code");