3 * This is the generic MTD driver for NAND flash devices. It should be
4 * capable of working with almost all NAND chips currently available.
6 * Additional technical information is available on
7 * http://www.linux-mtd.infradead.org/doc/nand.html
9 * Copyright (C) 2000 Steven J. Hill (sjhill@realitydiluted.com)
10 * 2002-2006 Thomas Gleixner (tglx@linutronix.de)
13 * David Woodhouse for adding multichip support
15 * Aleph One Ltd. and Toby Churchill Ltd. for supporting the
16 * rework for 2K page size chips
19 * Enable cached programming for 2k page size chips
20 * Check, if mtd->ecctype should be set to MTD_ECC_HW
21 * if we have HW ECC support.
22 * BBT table is not serialized, has to be fixed
24 * This program is free software; you can redistribute it and/or modify
25 * it under the terms of the GNU General Public License version 2 as
26 * published by the Free Software Foundation.
30 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
32 #if CONFIG_IS_ENABLED(OF_CONTROL)
37 #include <linux/err.h>
38 #include <linux/compat.h>
39 #include <linux/mtd/mtd.h>
40 #include <linux/mtd/rawnand.h>
41 #include <linux/mtd/nand_ecc.h>
42 #include <linux/mtd/nand_bch.h>
43 #ifdef CONFIG_MTD_PARTITIONS
44 #include <linux/mtd/partitions.h>
47 #include <linux/errno.h>
49 /* Define default oob placement schemes for large and small page devices */
50 #ifdef CONFIG_SYS_NAND_DRIVER_ECC_LAYOUT
51 static struct nand_ecclayout nand_oob_8 = {
61 static struct nand_ecclayout nand_oob_16 = {
63 .eccpos = {0, 1, 2, 3, 6, 7},
69 static struct nand_ecclayout nand_oob_64 = {
72 40, 41, 42, 43, 44, 45, 46, 47,
73 48, 49, 50, 51, 52, 53, 54, 55,
74 56, 57, 58, 59, 60, 61, 62, 63},
80 static struct nand_ecclayout nand_oob_128 = {
83 80, 81, 82, 83, 84, 85, 86, 87,
84 88, 89, 90, 91, 92, 93, 94, 95,
85 96, 97, 98, 99, 100, 101, 102, 103,
86 104, 105, 106, 107, 108, 109, 110, 111,
87 112, 113, 114, 115, 116, 117, 118, 119,
88 120, 121, 122, 123, 124, 125, 126, 127},
95 static int nand_get_device(struct mtd_info *mtd, int new_state);
97 static int nand_do_write_oob(struct mtd_info *mtd, loff_t to,
98 struct mtd_oob_ops *ops);
101 * For devices which display every fart in the system on a separate LED. Is
102 * compiled away when LED support is disabled.
104 DEFINE_LED_TRIGGER(nand_led_trigger);
106 static int check_offs_len(struct mtd_info *mtd,
107 loff_t ofs, uint64_t len)
109 struct nand_chip *chip = mtd_to_nand(mtd);
112 /* Start address must align on block boundary */
113 if (ofs & ((1ULL << chip->phys_erase_shift) - 1)) {
114 pr_debug("%s: unaligned address\n", __func__);
118 /* Length must align on block boundary */
119 if (len & ((1ULL << chip->phys_erase_shift) - 1)) {
120 pr_debug("%s: length not block aligned\n", __func__);
128 * nand_release_device - [GENERIC] release chip
129 * @mtd: MTD device structure
131 * Release chip lock and wake up anyone waiting on the device.
133 static void nand_release_device(struct mtd_info *mtd)
135 struct nand_chip *chip = mtd_to_nand(mtd);
137 /* De-select the NAND device */
138 chip->select_chip(mtd, -1);
142 * nand_read_byte - [DEFAULT] read one byte from the chip
143 * @mtd: MTD device structure
145 * Default read function for 8bit buswidth
147 uint8_t nand_read_byte(struct mtd_info *mtd)
149 struct nand_chip *chip = mtd_to_nand(mtd);
150 return readb(chip->IO_ADDR_R);
154 * nand_read_byte16 - [DEFAULT] read one byte endianness aware from the chip
155 * @mtd: MTD device structure
157 * Default read function for 16bit buswidth with endianness conversion.
160 static uint8_t nand_read_byte16(struct mtd_info *mtd)
162 struct nand_chip *chip = mtd_to_nand(mtd);
163 return (uint8_t) cpu_to_le16(readw(chip->IO_ADDR_R));
167 * nand_read_word - [DEFAULT] read one word from the chip
168 * @mtd: MTD device structure
170 * Default read function for 16bit buswidth without endianness conversion.
172 static u16 nand_read_word(struct mtd_info *mtd)
174 struct nand_chip *chip = mtd_to_nand(mtd);
175 return readw(chip->IO_ADDR_R);
179 * nand_select_chip - [DEFAULT] control CE line
180 * @mtd: MTD device structure
181 * @chipnr: chipnumber to select, -1 for deselect
183 * Default select function for 1 chip devices.
185 static void nand_select_chip(struct mtd_info *mtd, int chipnr)
187 struct nand_chip *chip = mtd_to_nand(mtd);
191 chip->cmd_ctrl(mtd, NAND_CMD_NONE, 0 | NAND_CTRL_CHANGE);
202 * nand_write_byte - [DEFAULT] write single byte to chip
203 * @mtd: MTD device structure
204 * @byte: value to write
206 * Default function to write a byte to I/O[7:0]
208 static void nand_write_byte(struct mtd_info *mtd, uint8_t byte)
210 struct nand_chip *chip = mtd_to_nand(mtd);
212 chip->write_buf(mtd, &byte, 1);
216 * nand_write_byte16 - [DEFAULT] write single byte to a chip with width 16
217 * @mtd: MTD device structure
218 * @byte: value to write
220 * Default function to write a byte to I/O[7:0] on a 16-bit wide chip.
222 static void nand_write_byte16(struct mtd_info *mtd, uint8_t byte)
224 struct nand_chip *chip = mtd_to_nand(mtd);
225 uint16_t word = byte;
228 * It's not entirely clear what should happen to I/O[15:8] when writing
229 * a byte. The ONFi spec (Revision 3.1; 2012-09-19, Section 2.16) reads:
231 * When the host supports a 16-bit bus width, only data is
232 * transferred at the 16-bit width. All address and command line
233 * transfers shall use only the lower 8-bits of the data bus. During
234 * command transfers, the host may place any value on the upper
235 * 8-bits of the data bus. During address transfers, the host shall
236 * set the upper 8-bits of the data bus to 00h.
238 * One user of the write_byte callback is nand_onfi_set_features. The
239 * four parameters are specified to be written to I/O[7:0], but this is
240 * neither an address nor a command transfer. Let's assume a 0 on the
241 * upper I/O lines is OK.
243 chip->write_buf(mtd, (uint8_t *)&word, 2);
246 static void iowrite8_rep(void *addr, const uint8_t *buf, int len)
250 for (i = 0; i < len; i++)
251 writeb(buf[i], addr);
253 static void ioread8_rep(void *addr, uint8_t *buf, int len)
257 for (i = 0; i < len; i++)
258 buf[i] = readb(addr);
261 static void ioread16_rep(void *addr, void *buf, int len)
264 u16 *p = (u16 *) buf;
266 for (i = 0; i < len; i++)
270 static void iowrite16_rep(void *addr, void *buf, int len)
273 u16 *p = (u16 *) buf;
275 for (i = 0; i < len; i++)
280 * nand_write_buf - [DEFAULT] write buffer to chip
281 * @mtd: MTD device structure
283 * @len: number of bytes to write
285 * Default write function for 8bit buswidth.
287 void nand_write_buf(struct mtd_info *mtd, const uint8_t *buf, int len)
289 struct nand_chip *chip = mtd_to_nand(mtd);
291 iowrite8_rep(chip->IO_ADDR_W, buf, len);
295 * nand_read_buf - [DEFAULT] read chip data into buffer
296 * @mtd: MTD device structure
297 * @buf: buffer to store date
298 * @len: number of bytes to read
300 * Default read function for 8bit buswidth.
302 void nand_read_buf(struct mtd_info *mtd, uint8_t *buf, int len)
304 struct nand_chip *chip = mtd_to_nand(mtd);
306 ioread8_rep(chip->IO_ADDR_R, buf, len);
310 * nand_write_buf16 - [DEFAULT] write buffer to chip
311 * @mtd: MTD device structure
313 * @len: number of bytes to write
315 * Default write function for 16bit buswidth.
317 void nand_write_buf16(struct mtd_info *mtd, const uint8_t *buf, int len)
319 struct nand_chip *chip = mtd_to_nand(mtd);
320 u16 *p = (u16 *) buf;
322 iowrite16_rep(chip->IO_ADDR_W, p, len >> 1);
326 * nand_read_buf16 - [DEFAULT] read chip data into buffer
327 * @mtd: MTD device structure
328 * @buf: buffer to store date
329 * @len: number of bytes to read
331 * Default read function for 16bit buswidth.
333 void nand_read_buf16(struct mtd_info *mtd, uint8_t *buf, int len)
335 struct nand_chip *chip = mtd_to_nand(mtd);
336 u16 *p = (u16 *) buf;
338 ioread16_rep(chip->IO_ADDR_R, p, len >> 1);
342 * nand_block_bad - [DEFAULT] Read bad block marker from the chip
343 * @mtd: MTD device structure
344 * @ofs: offset from device start
346 * Check, if the block is bad.
348 static int nand_block_bad(struct mtd_info *mtd, loff_t ofs)
350 int page, res = 0, i = 0;
351 struct nand_chip *chip = mtd_to_nand(mtd);
354 if (chip->bbt_options & NAND_BBT_SCANLASTPAGE)
355 ofs += mtd->erasesize - mtd->writesize;
357 page = (int)(ofs >> chip->page_shift) & chip->pagemask;
360 if (chip->options & NAND_BUSWIDTH_16) {
361 chip->cmdfunc(mtd, NAND_CMD_READOOB,
362 chip->badblockpos & 0xFE, page);
363 bad = cpu_to_le16(chip->read_word(mtd));
364 if (chip->badblockpos & 0x1)
369 chip->cmdfunc(mtd, NAND_CMD_READOOB, chip->badblockpos,
371 bad = chip->read_byte(mtd);
374 if (likely(chip->badblockbits == 8))
377 res = hweight8(bad) < chip->badblockbits;
378 ofs += mtd->writesize;
379 page = (int)(ofs >> chip->page_shift) & chip->pagemask;
381 } while (!res && i < 2 && (chip->bbt_options & NAND_BBT_SCAN2NDPAGE));
387 * nand_default_block_markbad - [DEFAULT] mark a block bad via bad block marker
388 * @mtd: MTD device structure
389 * @ofs: offset from device start
391 * This is the default implementation, which can be overridden by a hardware
392 * specific driver. It provides the details for writing a bad block marker to a
395 static int nand_default_block_markbad(struct mtd_info *mtd, loff_t ofs)
397 struct nand_chip *chip = mtd_to_nand(mtd);
398 struct mtd_oob_ops ops;
399 uint8_t buf[2] = { 0, 0 };
400 int ret = 0, res, i = 0;
402 memset(&ops, 0, sizeof(ops));
404 ops.ooboffs = chip->badblockpos;
405 if (chip->options & NAND_BUSWIDTH_16) {
406 ops.ooboffs &= ~0x01;
407 ops.len = ops.ooblen = 2;
409 ops.len = ops.ooblen = 1;
411 ops.mode = MTD_OPS_PLACE_OOB;
413 /* Write to first/last page(s) if necessary */
414 if (chip->bbt_options & NAND_BBT_SCANLASTPAGE)
415 ofs += mtd->erasesize - mtd->writesize;
417 res = nand_do_write_oob(mtd, ofs, &ops);
422 ofs += mtd->writesize;
423 } while ((chip->bbt_options & NAND_BBT_SCAN2NDPAGE) && i < 2);
429 * nand_block_markbad_lowlevel - mark a block bad
430 * @mtd: MTD device structure
431 * @ofs: offset from device start
433 * This function performs the generic NAND bad block marking steps (i.e., bad
434 * block table(s) and/or marker(s)). We only allow the hardware driver to
435 * specify how to write bad block markers to OOB (chip->block_markbad).
437 * We try operations in the following order:
438 * (1) erase the affected block, to allow OOB marker to be written cleanly
439 * (2) write bad block marker to OOB area of affected block (unless flag
440 * NAND_BBT_NO_OOB_BBM is present)
442 * Note that we retain the first error encountered in (2) or (3), finish the
443 * procedures, and dump the error in the end.
445 static int nand_block_markbad_lowlevel(struct mtd_info *mtd, loff_t ofs)
447 struct nand_chip *chip = mtd_to_nand(mtd);
450 if (!(chip->bbt_options & NAND_BBT_NO_OOB_BBM)) {
451 struct erase_info einfo;
453 /* Attempt erase before marking OOB */
454 memset(&einfo, 0, sizeof(einfo));
457 einfo.len = 1ULL << chip->phys_erase_shift;
458 nand_erase_nand(mtd, &einfo, 0);
460 /* Write bad block marker to OOB */
461 nand_get_device(mtd, FL_WRITING);
462 ret = chip->block_markbad(mtd, ofs);
463 nand_release_device(mtd);
466 /* Mark block bad in BBT */
468 res = nand_markbad_bbt(mtd, ofs);
474 mtd->ecc_stats.badblocks++;
480 * nand_check_wp - [GENERIC] check if the chip is write protected
481 * @mtd: MTD device structure
483 * Check, if the device is write protected. The function expects, that the
484 * device is already selected.
486 static int nand_check_wp(struct mtd_info *mtd)
488 struct nand_chip *chip = mtd_to_nand(mtd);
490 /* Broken xD cards report WP despite being writable */
491 if (chip->options & NAND_BROKEN_XD)
494 /* Check the WP bit */
495 chip->cmdfunc(mtd, NAND_CMD_STATUS, -1, -1);
496 return (chip->read_byte(mtd) & NAND_STATUS_WP) ? 0 : 1;
500 * nand_block_isreserved - [GENERIC] Check if a block is marked reserved.
501 * @mtd: MTD device structure
502 * @ofs: offset from device start
504 * Check if the block is marked as reserved.
506 static int nand_block_isreserved(struct mtd_info *mtd, loff_t ofs)
508 struct nand_chip *chip = mtd_to_nand(mtd);
512 /* Return info from the table */
513 return nand_isreserved_bbt(mtd, ofs);
517 * nand_block_checkbad - [GENERIC] Check if a block is marked bad
518 * @mtd: MTD device structure
519 * @ofs: offset from device start
520 * @allowbbt: 1, if its allowed to access the bbt area
522 * Check, if the block is bad. Either by reading the bad block table or
523 * calling of the scan function.
525 static int nand_block_checkbad(struct mtd_info *mtd, loff_t ofs, int allowbbt)
527 struct nand_chip *chip = mtd_to_nand(mtd);
529 if (!(chip->options & NAND_SKIP_BBTSCAN) &&
530 !(chip->options & NAND_BBT_SCANNED)) {
531 chip->options |= NAND_BBT_SCANNED;
536 return chip->block_bad(mtd, ofs);
538 /* Return info from the table */
539 return nand_isbad_bbt(mtd, ofs, allowbbt);
543 * nand_wait_ready - [GENERIC] Wait for the ready pin after commands.
544 * @mtd: MTD device structure
546 * Wait for the ready pin after a command, and warn if a timeout occurs.
548 void nand_wait_ready(struct mtd_info *mtd)
550 struct nand_chip *chip = mtd_to_nand(mtd);
551 u32 timeo = (CONFIG_SYS_HZ * 400) / 1000;
554 time_start = get_timer(0);
555 /* Wait until command is processed or timeout occurs */
556 while (get_timer(time_start) < timeo) {
558 if (chip->dev_ready(mtd))
562 if (!chip->dev_ready(mtd))
563 pr_warn("timeout while waiting for chip to become ready\n");
565 EXPORT_SYMBOL_GPL(nand_wait_ready);
568 * nand_wait_status_ready - [GENERIC] Wait for the ready status after commands.
569 * @mtd: MTD device structure
570 * @timeo: Timeout in ms
572 * Wait for status ready (i.e. command done) or timeout.
574 static void nand_wait_status_ready(struct mtd_info *mtd, unsigned long timeo)
576 register struct nand_chip *chip = mtd_to_nand(mtd);
579 timeo = (CONFIG_SYS_HZ * timeo) / 1000;
580 time_start = get_timer(0);
581 while (get_timer(time_start) < timeo) {
582 if ((chip->read_byte(mtd) & NAND_STATUS_READY))
589 * nand_command - [DEFAULT] Send command to NAND device
590 * @mtd: MTD device structure
591 * @command: the command to be sent
592 * @column: the column address for this command, -1 if none
593 * @page_addr: the page address for this command, -1 if none
595 * Send command to NAND device. This function is used for small page devices
596 * (512 Bytes per page).
598 static void nand_command(struct mtd_info *mtd, unsigned int command,
599 int column, int page_addr)
601 register struct nand_chip *chip = mtd_to_nand(mtd);
602 int ctrl = NAND_CTRL_CLE | NAND_CTRL_CHANGE;
604 /* Write out the command to the device */
605 if (command == NAND_CMD_SEQIN) {
608 if (column >= mtd->writesize) {
610 column -= mtd->writesize;
611 readcmd = NAND_CMD_READOOB;
612 } else if (column < 256) {
613 /* First 256 bytes --> READ0 */
614 readcmd = NAND_CMD_READ0;
617 readcmd = NAND_CMD_READ1;
619 chip->cmd_ctrl(mtd, readcmd, ctrl);
620 ctrl &= ~NAND_CTRL_CHANGE;
622 chip->cmd_ctrl(mtd, command, ctrl);
624 /* Address cycle, when necessary */
625 ctrl = NAND_CTRL_ALE | NAND_CTRL_CHANGE;
626 /* Serially input address */
628 /* Adjust columns for 16 bit buswidth */
629 if (chip->options & NAND_BUSWIDTH_16 &&
630 !nand_opcode_8bits(command))
632 chip->cmd_ctrl(mtd, column, ctrl);
633 ctrl &= ~NAND_CTRL_CHANGE;
635 if (page_addr != -1) {
636 chip->cmd_ctrl(mtd, page_addr, ctrl);
637 ctrl &= ~NAND_CTRL_CHANGE;
638 chip->cmd_ctrl(mtd, page_addr >> 8, ctrl);
639 if (chip->options & NAND_ROW_ADDR_3)
640 chip->cmd_ctrl(mtd, page_addr >> 16, ctrl);
642 chip->cmd_ctrl(mtd, NAND_CMD_NONE, NAND_NCE | NAND_CTRL_CHANGE);
645 * Program and erase have their own busy handlers status and sequential
650 case NAND_CMD_PAGEPROG:
651 case NAND_CMD_ERASE1:
652 case NAND_CMD_ERASE2:
654 case NAND_CMD_STATUS:
655 case NAND_CMD_READID:
656 case NAND_CMD_SET_FEATURES:
662 udelay(chip->chip_delay);
663 chip->cmd_ctrl(mtd, NAND_CMD_STATUS,
664 NAND_CTRL_CLE | NAND_CTRL_CHANGE);
666 NAND_CMD_NONE, NAND_NCE | NAND_CTRL_CHANGE);
667 /* EZ-NAND can take upto 250ms as per ONFi v4.0 */
668 nand_wait_status_ready(mtd, 250);
671 /* This applies to read commands */
674 * If we don't have access to the busy pin, we apply the given
677 if (!chip->dev_ready) {
678 udelay(chip->chip_delay);
683 * Apply this short delay always to ensure that we do wait tWB in
684 * any case on any machine.
688 nand_wait_ready(mtd);
692 * nand_command_lp - [DEFAULT] Send command to NAND large page device
693 * @mtd: MTD device structure
694 * @command: the command to be sent
695 * @column: the column address for this command, -1 if none
696 * @page_addr: the page address for this command, -1 if none
698 * Send command to NAND device. This is the version for the new large page
699 * devices. We don't have the separate regions as we have in the small page
700 * devices. We must emulate NAND_CMD_READOOB to keep the code compatible.
702 static void nand_command_lp(struct mtd_info *mtd, unsigned int command,
703 int column, int page_addr)
705 register struct nand_chip *chip = mtd_to_nand(mtd);
707 /* Emulate NAND_CMD_READOOB */
708 if (command == NAND_CMD_READOOB) {
709 column += mtd->writesize;
710 command = NAND_CMD_READ0;
713 /* Command latch cycle */
714 chip->cmd_ctrl(mtd, command, NAND_NCE | NAND_CLE | NAND_CTRL_CHANGE);
716 if (column != -1 || page_addr != -1) {
717 int ctrl = NAND_CTRL_CHANGE | NAND_NCE | NAND_ALE;
719 /* Serially input address */
721 /* Adjust columns for 16 bit buswidth */
722 if (chip->options & NAND_BUSWIDTH_16 &&
723 !nand_opcode_8bits(command))
725 chip->cmd_ctrl(mtd, column, ctrl);
726 ctrl &= ~NAND_CTRL_CHANGE;
727 chip->cmd_ctrl(mtd, column >> 8, ctrl);
729 if (page_addr != -1) {
730 chip->cmd_ctrl(mtd, page_addr, ctrl);
731 chip->cmd_ctrl(mtd, page_addr >> 8,
732 NAND_NCE | NAND_ALE);
733 if (chip->options & NAND_ROW_ADDR_3)
734 chip->cmd_ctrl(mtd, page_addr >> 16,
735 NAND_NCE | NAND_ALE);
738 chip->cmd_ctrl(mtd, NAND_CMD_NONE, NAND_NCE | NAND_CTRL_CHANGE);
741 * Program and erase have their own busy handlers status, sequential
742 * in and status need no delay.
746 case NAND_CMD_CACHEDPROG:
747 case NAND_CMD_PAGEPROG:
748 case NAND_CMD_ERASE1:
749 case NAND_CMD_ERASE2:
752 case NAND_CMD_STATUS:
753 case NAND_CMD_READID:
754 case NAND_CMD_SET_FEATURES:
760 udelay(chip->chip_delay);
761 chip->cmd_ctrl(mtd, NAND_CMD_STATUS,
762 NAND_NCE | NAND_CLE | NAND_CTRL_CHANGE);
763 chip->cmd_ctrl(mtd, NAND_CMD_NONE,
764 NAND_NCE | NAND_CTRL_CHANGE);
765 /* EZ-NAND can take upto 250ms as per ONFi v4.0 */
766 nand_wait_status_ready(mtd, 250);
769 case NAND_CMD_RNDOUT:
770 /* No ready / busy check necessary */
771 chip->cmd_ctrl(mtd, NAND_CMD_RNDOUTSTART,
772 NAND_NCE | NAND_CLE | NAND_CTRL_CHANGE);
773 chip->cmd_ctrl(mtd, NAND_CMD_NONE,
774 NAND_NCE | NAND_CTRL_CHANGE);
778 chip->cmd_ctrl(mtd, NAND_CMD_READSTART,
779 NAND_NCE | NAND_CLE | NAND_CTRL_CHANGE);
780 chip->cmd_ctrl(mtd, NAND_CMD_NONE,
781 NAND_NCE | NAND_CTRL_CHANGE);
783 /* This applies to read commands */
786 * If we don't have access to the busy pin, we apply the given
789 if (!chip->dev_ready) {
790 udelay(chip->chip_delay);
796 * Apply this short delay always to ensure that we do wait tWB in
797 * any case on any machine.
801 nand_wait_ready(mtd);
805 * panic_nand_get_device - [GENERIC] Get chip for selected access
806 * @chip: the nand chip descriptor
807 * @mtd: MTD device structure
808 * @new_state: the state which is requested
810 * Used when in panic, no locks are taken.
812 static void panic_nand_get_device(struct nand_chip *chip,
813 struct mtd_info *mtd, int new_state)
815 /* Hardware controller shared among independent devices */
816 chip->controller->active = chip;
817 chip->state = new_state;
821 * nand_get_device - [GENERIC] Get chip for selected access
822 * @mtd: MTD device structure
823 * @new_state: the state which is requested
825 * Get the device and lock it for exclusive access
828 nand_get_device(struct mtd_info *mtd, int new_state)
830 struct nand_chip *chip = mtd_to_nand(mtd);
831 chip->state = new_state;
836 * panic_nand_wait - [GENERIC] wait until the command is done
837 * @mtd: MTD device structure
838 * @chip: NAND chip structure
841 * Wait for command done. This is a helper function for nand_wait used when
842 * we are in interrupt context. May happen when in panic and trying to write
843 * an oops through mtdoops.
845 static void panic_nand_wait(struct mtd_info *mtd, struct nand_chip *chip,
849 for (i = 0; i < timeo; i++) {
850 if (chip->dev_ready) {
851 if (chip->dev_ready(mtd))
854 if (chip->read_byte(mtd) & NAND_STATUS_READY)
862 * nand_wait - [DEFAULT] wait until the command is done
863 * @mtd: MTD device structure
864 * @chip: NAND chip structure
866 * Wait for command done. This applies to erase and program only.
868 static int nand_wait(struct mtd_info *mtd, struct nand_chip *chip)
871 unsigned long timeo = 400;
873 led_trigger_event(nand_led_trigger, LED_FULL);
876 * Apply this short delay always to ensure that we do wait tWB in any
877 * case on any machine.
881 chip->cmdfunc(mtd, NAND_CMD_STATUS, -1, -1);
883 u32 timer = (CONFIG_SYS_HZ * timeo) / 1000;
886 time_start = get_timer(0);
887 while (get_timer(time_start) < timer) {
888 if (chip->dev_ready) {
889 if (chip->dev_ready(mtd))
892 if (chip->read_byte(mtd) & NAND_STATUS_READY)
896 led_trigger_event(nand_led_trigger, LED_OFF);
898 status = (int)chip->read_byte(mtd);
899 /* This can happen if in case of timeout or buggy dev_ready */
900 WARN_ON(!(status & NAND_STATUS_READY));
905 * nand_reset_data_interface - Reset data interface and timings
906 * @chip: The NAND chip
907 * @chipnr: Internal die id
909 * Reset the Data interface and timings to ONFI mode 0.
911 * Returns 0 for success or negative error code otherwise.
913 static int nand_reset_data_interface(struct nand_chip *chip, int chipnr)
915 struct mtd_info *mtd = nand_to_mtd(chip);
916 const struct nand_data_interface *conf;
919 if (!chip->setup_data_interface)
923 * The ONFI specification says:
925 * To transition from NV-DDR or NV-DDR2 to the SDR data
926 * interface, the host shall use the Reset (FFh) command
927 * using SDR timing mode 0. A device in any timing mode is
928 * required to recognize Reset (FFh) command issued in SDR
932 * Configure the data interface in SDR mode and set the
933 * timings to timing mode 0.
936 conf = nand_get_default_data_interface();
937 ret = chip->setup_data_interface(mtd, chipnr, conf);
939 pr_err("Failed to configure data interface to SDR timing mode 0\n");
945 * nand_setup_data_interface - Setup the best data interface and timings
946 * @chip: The NAND chip
947 * @chipnr: Internal die id
949 * Find and configure the best data interface and NAND timings supported by
950 * the chip and the driver.
951 * First tries to retrieve supported timing modes from ONFI information,
952 * and if the NAND chip does not support ONFI, relies on the
953 * ->onfi_timing_mode_default specified in the nand_ids table.
955 * Returns 0 for success or negative error code otherwise.
957 static int nand_setup_data_interface(struct nand_chip *chip, int chipnr)
959 struct mtd_info *mtd = nand_to_mtd(chip);
962 if (!chip->setup_data_interface || !chip->data_interface)
966 * Ensure the timing mode has been changed on the chip side
967 * before changing timings on the controller side.
969 if (chip->onfi_version) {
970 u8 tmode_param[ONFI_SUBFEATURE_PARAM_LEN] = {
971 chip->onfi_timing_mode_default,
974 ret = chip->onfi_set_features(mtd, chip,
975 ONFI_FEATURE_ADDR_TIMING_MODE,
981 ret = chip->setup_data_interface(mtd, chipnr, chip->data_interface);
987 * nand_init_data_interface - find the best data interface and timings
988 * @chip: The NAND chip
990 * Find the best data interface and NAND timings supported by the chip
992 * First tries to retrieve supported timing modes from ONFI information,
993 * and if the NAND chip does not support ONFI, relies on the
994 * ->onfi_timing_mode_default specified in the nand_ids table. After this
995 * function nand_chip->data_interface is initialized with the best timing mode
998 * Returns 0 for success or negative error code otherwise.
1000 static int nand_init_data_interface(struct nand_chip *chip)
1002 struct mtd_info *mtd = nand_to_mtd(chip);
1003 int modes, mode, ret;
1005 if (!chip->setup_data_interface)
1009 * First try to identify the best timings from ONFI parameters and
1010 * if the NAND does not support ONFI, fallback to the default ONFI
1013 modes = onfi_get_async_timing_mode(chip);
1014 if (modes == ONFI_TIMING_MODE_UNKNOWN) {
1015 if (!chip->onfi_timing_mode_default)
1018 modes = GENMASK(chip->onfi_timing_mode_default, 0);
1021 chip->data_interface = kzalloc(sizeof(*chip->data_interface),
1023 if (!chip->data_interface)
1026 for (mode = fls(modes) - 1; mode >= 0; mode--) {
1027 ret = onfi_init_data_interface(chip, chip->data_interface,
1028 NAND_SDR_IFACE, mode);
1032 /* Pass -1 to only */
1033 ret = chip->setup_data_interface(mtd,
1034 NAND_DATA_IFACE_CHECK_ONLY,
1035 chip->data_interface);
1037 chip->onfi_timing_mode_default = mode;
1045 static void __maybe_unused nand_release_data_interface(struct nand_chip *chip)
1047 kfree(chip->data_interface);
1051 * nand_reset - Reset and initialize a NAND device
1052 * @chip: The NAND chip
1053 * @chipnr: Internal die id
1055 * Returns 0 for success or negative error code otherwise
1057 int nand_reset(struct nand_chip *chip, int chipnr)
1059 struct mtd_info *mtd = nand_to_mtd(chip);
1062 ret = nand_reset_data_interface(chip, chipnr);
1067 * The CS line has to be released before we can apply the new NAND
1068 * interface settings, hence this weird ->select_chip() dance.
1070 chip->select_chip(mtd, chipnr);
1071 chip->cmdfunc(mtd, NAND_CMD_RESET, -1, -1);
1072 chip->select_chip(mtd, -1);
1074 chip->select_chip(mtd, chipnr);
1075 ret = nand_setup_data_interface(chip, chipnr);
1076 chip->select_chip(mtd, -1);
1084 * nand_check_erased_buf - check if a buffer contains (almost) only 0xff data
1085 * @buf: buffer to test
1086 * @len: buffer length
1087 * @bitflips_threshold: maximum number of bitflips
1089 * Check if a buffer contains only 0xff, which means the underlying region
1090 * has been erased and is ready to be programmed.
1091 * The bitflips_threshold specify the maximum number of bitflips before
1092 * considering the region is not erased.
1093 * Note: The logic of this function has been extracted from the memweight
1094 * implementation, except that nand_check_erased_buf function exit before
1095 * testing the whole buffer if the number of bitflips exceed the
1096 * bitflips_threshold value.
1098 * Returns a positive number of bitflips less than or equal to
1099 * bitflips_threshold, or -ERROR_CODE for bitflips in excess of the
1102 static int nand_check_erased_buf(void *buf, int len, int bitflips_threshold)
1104 const unsigned char *bitmap = buf;
1108 for (; len && ((uintptr_t)bitmap) % sizeof(long);
1110 weight = hweight8(*bitmap);
1111 bitflips += BITS_PER_BYTE - weight;
1112 if (unlikely(bitflips > bitflips_threshold))
1116 for (; len >= 4; len -= 4, bitmap += 4) {
1117 weight = hweight32(*((u32 *)bitmap));
1118 bitflips += 32 - weight;
1119 if (unlikely(bitflips > bitflips_threshold))
1123 for (; len > 0; len--, bitmap++) {
1124 weight = hweight8(*bitmap);
1125 bitflips += BITS_PER_BYTE - weight;
1126 if (unlikely(bitflips > bitflips_threshold))
1134 * nand_check_erased_ecc_chunk - check if an ECC chunk contains (almost) only
1136 * @data: data buffer to test
1137 * @datalen: data length
1139 * @ecclen: ECC length
1140 * @extraoob: extra OOB buffer
1141 * @extraooblen: extra OOB length
1142 * @bitflips_threshold: maximum number of bitflips
1144 * Check if a data buffer and its associated ECC and OOB data contains only
1145 * 0xff pattern, which means the underlying region has been erased and is
1146 * ready to be programmed.
1147 * The bitflips_threshold specify the maximum number of bitflips before
1148 * considering the region as not erased.
1151 * 1/ ECC algorithms are working on pre-defined block sizes which are usually
1152 * different from the NAND page size. When fixing bitflips, ECC engines will
1153 * report the number of errors per chunk, and the NAND core infrastructure
1154 * expect you to return the maximum number of bitflips for the whole page.
1155 * This is why you should always use this function on a single chunk and
1156 * not on the whole page. After checking each chunk you should update your
1157 * max_bitflips value accordingly.
1158 * 2/ When checking for bitflips in erased pages you should not only check
1159 * the payload data but also their associated ECC data, because a user might
1160 * have programmed almost all bits to 1 but a few. In this case, we
1161 * shouldn't consider the chunk as erased, and checking ECC bytes prevent
1163 * 3/ The extraoob argument is optional, and should be used if some of your OOB
1164 * data are protected by the ECC engine.
1165 * It could also be used if you support subpages and want to attach some
1166 * extra OOB data to an ECC chunk.
1168 * Returns a positive number of bitflips less than or equal to
1169 * bitflips_threshold, or -ERROR_CODE for bitflips in excess of the
1170 * threshold. In case of success, the passed buffers are filled with 0xff.
1172 int nand_check_erased_ecc_chunk(void *data, int datalen,
1173 void *ecc, int ecclen,
1174 void *extraoob, int extraooblen,
1175 int bitflips_threshold)
1177 int data_bitflips = 0, ecc_bitflips = 0, extraoob_bitflips = 0;
1179 data_bitflips = nand_check_erased_buf(data, datalen,
1180 bitflips_threshold);
1181 if (data_bitflips < 0)
1182 return data_bitflips;
1184 bitflips_threshold -= data_bitflips;
1186 ecc_bitflips = nand_check_erased_buf(ecc, ecclen, bitflips_threshold);
1187 if (ecc_bitflips < 0)
1188 return ecc_bitflips;
1190 bitflips_threshold -= ecc_bitflips;
1192 extraoob_bitflips = nand_check_erased_buf(extraoob, extraooblen,
1193 bitflips_threshold);
1194 if (extraoob_bitflips < 0)
1195 return extraoob_bitflips;
1198 memset(data, 0xff, datalen);
1201 memset(ecc, 0xff, ecclen);
1203 if (extraoob_bitflips)
1204 memset(extraoob, 0xff, extraooblen);
1206 return data_bitflips + ecc_bitflips + extraoob_bitflips;
1208 EXPORT_SYMBOL(nand_check_erased_ecc_chunk);
1211 * nand_read_page_raw - [INTERN] read raw page data without ecc
1212 * @mtd: mtd info structure
1213 * @chip: nand chip info structure
1214 * @buf: buffer to store read data
1215 * @oob_required: caller requires OOB data read to chip->oob_poi
1216 * @page: page number to read
1218 * Not for syndrome calculating ECC controllers, which use a special oob layout.
1220 static int nand_read_page_raw(struct mtd_info *mtd, struct nand_chip *chip,
1221 uint8_t *buf, int oob_required, int page)
1223 chip->read_buf(mtd, buf, mtd->writesize);
1225 chip->read_buf(mtd, chip->oob_poi, mtd->oobsize);
1230 * nand_read_page_raw_syndrome - [INTERN] read raw page data without ecc
1231 * @mtd: mtd info structure
1232 * @chip: nand chip info structure
1233 * @buf: buffer to store read data
1234 * @oob_required: caller requires OOB data read to chip->oob_poi
1235 * @page: page number to read
1237 * We need a special oob layout and handling even when OOB isn't used.
1239 static int nand_read_page_raw_syndrome(struct mtd_info *mtd,
1240 struct nand_chip *chip, uint8_t *buf,
1241 int oob_required, int page)
1243 int eccsize = chip->ecc.size;
1244 int eccbytes = chip->ecc.bytes;
1245 uint8_t *oob = chip->oob_poi;
1248 for (steps = chip->ecc.steps; steps > 0; steps--) {
1249 chip->read_buf(mtd, buf, eccsize);
1252 if (chip->ecc.prepad) {
1253 chip->read_buf(mtd, oob, chip->ecc.prepad);
1254 oob += chip->ecc.prepad;
1257 chip->read_buf(mtd, oob, eccbytes);
1260 if (chip->ecc.postpad) {
1261 chip->read_buf(mtd, oob, chip->ecc.postpad);
1262 oob += chip->ecc.postpad;
1266 size = mtd->oobsize - (oob - chip->oob_poi);
1268 chip->read_buf(mtd, oob, size);
1274 * nand_read_page_swecc - [REPLACEABLE] software ECC based page read function
1275 * @mtd: mtd info structure
1276 * @chip: nand chip info structure
1277 * @buf: buffer to store read data
1278 * @oob_required: caller requires OOB data read to chip->oob_poi
1279 * @page: page number to read
1281 static int nand_read_page_swecc(struct mtd_info *mtd, struct nand_chip *chip,
1282 uint8_t *buf, int oob_required, int page)
1284 int i, eccsize = chip->ecc.size;
1285 int eccbytes = chip->ecc.bytes;
1286 int eccsteps = chip->ecc.steps;
1288 uint8_t *ecc_calc = chip->buffers->ecccalc;
1289 uint8_t *ecc_code = chip->buffers->ecccode;
1290 uint32_t *eccpos = chip->ecc.layout->eccpos;
1291 unsigned int max_bitflips = 0;
1293 chip->ecc.read_page_raw(mtd, chip, buf, 1, page);
1295 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize)
1296 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
1298 for (i = 0; i < chip->ecc.total; i++)
1299 ecc_code[i] = chip->oob_poi[eccpos[i]];
1301 eccsteps = chip->ecc.steps;
1304 for (i = 0 ; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
1307 stat = chip->ecc.correct(mtd, p, &ecc_code[i], &ecc_calc[i]);
1309 mtd->ecc_stats.failed++;
1311 mtd->ecc_stats.corrected += stat;
1312 max_bitflips = max_t(unsigned int, max_bitflips, stat);
1315 return max_bitflips;
1319 * nand_read_subpage - [REPLACEABLE] ECC based sub-page read function
1320 * @mtd: mtd info structure
1321 * @chip: nand chip info structure
1322 * @data_offs: offset of requested data within the page
1323 * @readlen: data length
1324 * @bufpoi: buffer to store read data
1325 * @page: page number to read
1327 static int nand_read_subpage(struct mtd_info *mtd, struct nand_chip *chip,
1328 uint32_t data_offs, uint32_t readlen, uint8_t *bufpoi,
1331 int start_step, end_step, num_steps;
1332 uint32_t *eccpos = chip->ecc.layout->eccpos;
1334 int data_col_addr, i, gaps = 0;
1335 int datafrag_len, eccfrag_len, aligned_len, aligned_pos;
1336 int busw = (chip->options & NAND_BUSWIDTH_16) ? 2 : 1;
1338 unsigned int max_bitflips = 0;
1340 /* Column address within the page aligned to ECC size (256bytes) */
1341 start_step = data_offs / chip->ecc.size;
1342 end_step = (data_offs + readlen - 1) / chip->ecc.size;
1343 num_steps = end_step - start_step + 1;
1344 index = start_step * chip->ecc.bytes;
1346 /* Data size aligned to ECC ecc.size */
1347 datafrag_len = num_steps * chip->ecc.size;
1348 eccfrag_len = num_steps * chip->ecc.bytes;
1350 data_col_addr = start_step * chip->ecc.size;
1351 /* If we read not a page aligned data */
1352 if (data_col_addr != 0)
1353 chip->cmdfunc(mtd, NAND_CMD_RNDOUT, data_col_addr, -1);
1355 p = bufpoi + data_col_addr;
1356 chip->read_buf(mtd, p, datafrag_len);
1359 for (i = 0; i < eccfrag_len ; i += chip->ecc.bytes, p += chip->ecc.size)
1360 chip->ecc.calculate(mtd, p, &chip->buffers->ecccalc[i]);
1363 * The performance is faster if we position offsets according to
1364 * ecc.pos. Let's make sure that there are no gaps in ECC positions.
1366 for (i = 0; i < eccfrag_len - 1; i++) {
1367 if (eccpos[i + index] + 1 != eccpos[i + index + 1]) {
1373 chip->cmdfunc(mtd, NAND_CMD_RNDOUT, mtd->writesize, -1);
1374 chip->read_buf(mtd, chip->oob_poi, mtd->oobsize);
1377 * Send the command to read the particular ECC bytes take care
1378 * about buswidth alignment in read_buf.
1380 aligned_pos = eccpos[index] & ~(busw - 1);
1381 aligned_len = eccfrag_len;
1382 if (eccpos[index] & (busw - 1))
1384 if (eccpos[index + (num_steps * chip->ecc.bytes)] & (busw - 1))
1387 chip->cmdfunc(mtd, NAND_CMD_RNDOUT,
1388 mtd->writesize + aligned_pos, -1);
1389 chip->read_buf(mtd, &chip->oob_poi[aligned_pos], aligned_len);
1392 for (i = 0; i < eccfrag_len; i++)
1393 chip->buffers->ecccode[i] = chip->oob_poi[eccpos[i + index]];
1395 p = bufpoi + data_col_addr;
1396 for (i = 0; i < eccfrag_len ; i += chip->ecc.bytes, p += chip->ecc.size) {
1399 stat = chip->ecc.correct(mtd, p,
1400 &chip->buffers->ecccode[i], &chip->buffers->ecccalc[i]);
1401 if (stat == -EBADMSG &&
1402 (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
1403 /* check for empty pages with bitflips */
1404 stat = nand_check_erased_ecc_chunk(p, chip->ecc.size,
1405 &chip->buffers->ecccode[i],
1408 chip->ecc.strength);
1412 mtd->ecc_stats.failed++;
1414 mtd->ecc_stats.corrected += stat;
1415 max_bitflips = max_t(unsigned int, max_bitflips, stat);
1418 return max_bitflips;
1422 * nand_read_page_hwecc - [REPLACEABLE] hardware ECC based page read function
1423 * @mtd: mtd info structure
1424 * @chip: nand chip info structure
1425 * @buf: buffer to store read data
1426 * @oob_required: caller requires OOB data read to chip->oob_poi
1427 * @page: page number to read
1429 * Not for syndrome calculating ECC controllers which need a special oob layout.
1431 static int nand_read_page_hwecc(struct mtd_info *mtd, struct nand_chip *chip,
1432 uint8_t *buf, int oob_required, int page)
1434 int i, eccsize = chip->ecc.size;
1435 int eccbytes = chip->ecc.bytes;
1436 int eccsteps = chip->ecc.steps;
1438 uint8_t *ecc_calc = chip->buffers->ecccalc;
1439 uint8_t *ecc_code = chip->buffers->ecccode;
1440 uint32_t *eccpos = chip->ecc.layout->eccpos;
1441 unsigned int max_bitflips = 0;
1443 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
1444 chip->ecc.hwctl(mtd, NAND_ECC_READ);
1445 chip->read_buf(mtd, p, eccsize);
1446 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
1448 chip->read_buf(mtd, chip->oob_poi, mtd->oobsize);
1450 for (i = 0; i < chip->ecc.total; i++)
1451 ecc_code[i] = chip->oob_poi[eccpos[i]];
1453 eccsteps = chip->ecc.steps;
1456 for (i = 0 ; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
1459 stat = chip->ecc.correct(mtd, p, &ecc_code[i], &ecc_calc[i]);
1460 if (stat == -EBADMSG &&
1461 (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
1462 /* check for empty pages with bitflips */
1463 stat = nand_check_erased_ecc_chunk(p, eccsize,
1464 &ecc_code[i], eccbytes,
1466 chip->ecc.strength);
1470 mtd->ecc_stats.failed++;
1472 mtd->ecc_stats.corrected += stat;
1473 max_bitflips = max_t(unsigned int, max_bitflips, stat);
1476 return max_bitflips;
1480 * nand_read_page_hwecc_oob_first - [REPLACEABLE] hw ecc, read oob first
1481 * @mtd: mtd info structure
1482 * @chip: nand chip info structure
1483 * @buf: buffer to store read data
1484 * @oob_required: caller requires OOB data read to chip->oob_poi
1485 * @page: page number to read
1487 * Hardware ECC for large page chips, require OOB to be read first. For this
1488 * ECC mode, the write_page method is re-used from ECC_HW. These methods
1489 * read/write ECC from the OOB area, unlike the ECC_HW_SYNDROME support with
1490 * multiple ECC steps, follows the "infix ECC" scheme and reads/writes ECC from
1491 * the data area, by overwriting the NAND manufacturer bad block markings.
1493 static int nand_read_page_hwecc_oob_first(struct mtd_info *mtd,
1494 struct nand_chip *chip, uint8_t *buf, int oob_required, int page)
1496 int i, eccsize = chip->ecc.size;
1497 int eccbytes = chip->ecc.bytes;
1498 int eccsteps = chip->ecc.steps;
1500 uint8_t *ecc_code = chip->buffers->ecccode;
1501 uint32_t *eccpos = chip->ecc.layout->eccpos;
1502 uint8_t *ecc_calc = chip->buffers->ecccalc;
1503 unsigned int max_bitflips = 0;
1505 /* Read the OOB area first */
1506 chip->cmdfunc(mtd, NAND_CMD_READOOB, 0, page);
1507 chip->read_buf(mtd, chip->oob_poi, mtd->oobsize);
1508 chip->cmdfunc(mtd, NAND_CMD_READ0, 0, page);
1510 for (i = 0; i < chip->ecc.total; i++)
1511 ecc_code[i] = chip->oob_poi[eccpos[i]];
1513 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
1516 chip->ecc.hwctl(mtd, NAND_ECC_READ);
1517 chip->read_buf(mtd, p, eccsize);
1518 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
1520 stat = chip->ecc.correct(mtd, p, &ecc_code[i], NULL);
1521 if (stat == -EBADMSG &&
1522 (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
1523 /* check for empty pages with bitflips */
1524 stat = nand_check_erased_ecc_chunk(p, eccsize,
1525 &ecc_code[i], eccbytes,
1527 chip->ecc.strength);
1531 mtd->ecc_stats.failed++;
1533 mtd->ecc_stats.corrected += stat;
1534 max_bitflips = max_t(unsigned int, max_bitflips, stat);
1537 return max_bitflips;
1541 * nand_read_page_syndrome - [REPLACEABLE] hardware ECC syndrome based page read
1542 * @mtd: mtd info structure
1543 * @chip: nand chip info structure
1544 * @buf: buffer to store read data
1545 * @oob_required: caller requires OOB data read to chip->oob_poi
1546 * @page: page number to read
1548 * The hw generator calculates the error syndrome automatically. Therefore we
1549 * need a special oob layout and handling.
1551 static int nand_read_page_syndrome(struct mtd_info *mtd, struct nand_chip *chip,
1552 uint8_t *buf, int oob_required, int page)
1554 int i, eccsize = chip->ecc.size;
1555 int eccbytes = chip->ecc.bytes;
1556 int eccsteps = chip->ecc.steps;
1557 int eccpadbytes = eccbytes + chip->ecc.prepad + chip->ecc.postpad;
1559 uint8_t *oob = chip->oob_poi;
1560 unsigned int max_bitflips = 0;
1562 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
1565 chip->ecc.hwctl(mtd, NAND_ECC_READ);
1566 chip->read_buf(mtd, p, eccsize);
1568 if (chip->ecc.prepad) {
1569 chip->read_buf(mtd, oob, chip->ecc.prepad);
1570 oob += chip->ecc.prepad;
1573 chip->ecc.hwctl(mtd, NAND_ECC_READSYN);
1574 chip->read_buf(mtd, oob, eccbytes);
1575 stat = chip->ecc.correct(mtd, p, oob, NULL);
1579 if (chip->ecc.postpad) {
1580 chip->read_buf(mtd, oob, chip->ecc.postpad);
1581 oob += chip->ecc.postpad;
1584 if (stat == -EBADMSG &&
1585 (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
1586 /* check for empty pages with bitflips */
1587 stat = nand_check_erased_ecc_chunk(p, chip->ecc.size,
1591 chip->ecc.strength);
1595 mtd->ecc_stats.failed++;
1597 mtd->ecc_stats.corrected += stat;
1598 max_bitflips = max_t(unsigned int, max_bitflips, stat);
1602 /* Calculate remaining oob bytes */
1603 i = mtd->oobsize - (oob - chip->oob_poi);
1605 chip->read_buf(mtd, oob, i);
1607 return max_bitflips;
1611 * nand_transfer_oob - [INTERN] Transfer oob to client buffer
1612 * @chip: nand chip structure
1613 * @oob: oob destination address
1614 * @ops: oob ops structure
1615 * @len: size of oob to transfer
1617 static uint8_t *nand_transfer_oob(struct nand_chip *chip, uint8_t *oob,
1618 struct mtd_oob_ops *ops, size_t len)
1620 switch (ops->mode) {
1622 case MTD_OPS_PLACE_OOB:
1624 memcpy(oob, chip->oob_poi + ops->ooboffs, len);
1627 case MTD_OPS_AUTO_OOB: {
1628 struct nand_oobfree *free = chip->ecc.layout->oobfree;
1629 uint32_t boffs = 0, roffs = ops->ooboffs;
1632 for (; free->length && len; free++, len -= bytes) {
1633 /* Read request not from offset 0? */
1634 if (unlikely(roffs)) {
1635 if (roffs >= free->length) {
1636 roffs -= free->length;
1639 boffs = free->offset + roffs;
1640 bytes = min_t(size_t, len,
1641 (free->length - roffs));
1644 bytes = min_t(size_t, len, free->length);
1645 boffs = free->offset;
1647 memcpy(oob, chip->oob_poi + boffs, bytes);
1659 * nand_setup_read_retry - [INTERN] Set the READ RETRY mode
1660 * @mtd: MTD device structure
1661 * @retry_mode: the retry mode to use
1663 * Some vendors supply a special command to shift the Vt threshold, to be used
1664 * when there are too many bitflips in a page (i.e., ECC error). After setting
1665 * a new threshold, the host should retry reading the page.
1667 static int nand_setup_read_retry(struct mtd_info *mtd, int retry_mode)
1669 struct nand_chip *chip = mtd_to_nand(mtd);
1671 pr_debug("setting READ RETRY mode %d\n", retry_mode);
1673 if (retry_mode >= chip->read_retries)
1676 if (!chip->setup_read_retry)
1679 return chip->setup_read_retry(mtd, retry_mode);
1683 * nand_do_read_ops - [INTERN] Read data with ECC
1684 * @mtd: MTD device structure
1685 * @from: offset to read from
1686 * @ops: oob ops structure
1688 * Internal function. Called with chip held.
1690 static int nand_do_read_ops(struct mtd_info *mtd, loff_t from,
1691 struct mtd_oob_ops *ops)
1693 int chipnr, page, realpage, col, bytes, aligned, oob_required;
1694 struct nand_chip *chip = mtd_to_nand(mtd);
1696 uint32_t readlen = ops->len;
1697 uint32_t oobreadlen = ops->ooblen;
1698 uint32_t max_oobsize = mtd_oobavail(mtd, ops);
1700 uint8_t *bufpoi, *oob, *buf;
1702 unsigned int max_bitflips = 0;
1704 bool ecc_fail = false;
1706 chipnr = (int)(from >> chip->chip_shift);
1707 chip->select_chip(mtd, chipnr);
1709 realpage = (int)(from >> chip->page_shift);
1710 page = realpage & chip->pagemask;
1712 col = (int)(from & (mtd->writesize - 1));
1716 oob_required = oob ? 1 : 0;
1719 unsigned int ecc_failures = mtd->ecc_stats.failed;
1722 bytes = min(mtd->writesize - col, readlen);
1723 aligned = (bytes == mtd->writesize);
1727 else if (chip->options & NAND_USE_BOUNCE_BUFFER)
1728 use_bufpoi = !IS_ALIGNED((unsigned long)buf,
1733 /* Is the current page in the buffer? */
1734 if (realpage != chip->pagebuf || oob) {
1735 bufpoi = use_bufpoi ? chip->buffers->databuf : buf;
1737 if (use_bufpoi && aligned)
1738 pr_debug("%s: using read bounce buffer for buf@%p\n",
1742 if (nand_standard_page_accessors(&chip->ecc))
1743 chip->cmdfunc(mtd, NAND_CMD_READ0, 0x00, page);
1746 * Now read the page into the buffer. Absent an error,
1747 * the read methods return max bitflips per ecc step.
1749 if (unlikely(ops->mode == MTD_OPS_RAW))
1750 ret = chip->ecc.read_page_raw(mtd, chip, bufpoi,
1753 else if (!aligned && NAND_HAS_SUBPAGE_READ(chip) &&
1755 ret = chip->ecc.read_subpage(mtd, chip,
1759 ret = chip->ecc.read_page(mtd, chip, bufpoi,
1760 oob_required, page);
1763 /* Invalidate page cache */
1768 max_bitflips = max_t(unsigned int, max_bitflips, ret);
1770 /* Transfer not aligned data */
1772 if (!NAND_HAS_SUBPAGE_READ(chip) && !oob &&
1773 !(mtd->ecc_stats.failed - ecc_failures) &&
1774 (ops->mode != MTD_OPS_RAW)) {
1775 chip->pagebuf = realpage;
1776 chip->pagebuf_bitflips = ret;
1778 /* Invalidate page cache */
1781 memcpy(buf, chip->buffers->databuf + col, bytes);
1784 if (unlikely(oob)) {
1785 int toread = min(oobreadlen, max_oobsize);
1788 oob = nand_transfer_oob(chip,
1790 oobreadlen -= toread;
1794 if (chip->options & NAND_NEED_READRDY) {
1795 /* Apply delay or wait for ready/busy pin */
1796 if (!chip->dev_ready)
1797 udelay(chip->chip_delay);
1799 nand_wait_ready(mtd);
1802 if (mtd->ecc_stats.failed - ecc_failures) {
1803 if (retry_mode + 1 < chip->read_retries) {
1805 ret = nand_setup_read_retry(mtd,
1810 /* Reset failures; retry */
1811 mtd->ecc_stats.failed = ecc_failures;
1814 /* No more retry modes; real failure */
1821 memcpy(buf, chip->buffers->databuf + col, bytes);
1823 max_bitflips = max_t(unsigned int, max_bitflips,
1824 chip->pagebuf_bitflips);
1829 /* Reset to retry mode 0 */
1831 ret = nand_setup_read_retry(mtd, 0);
1840 /* For subsequent reads align to page boundary */
1842 /* Increment page address */
1845 page = realpage & chip->pagemask;
1846 /* Check, if we cross a chip boundary */
1849 chip->select_chip(mtd, -1);
1850 chip->select_chip(mtd, chipnr);
1853 chip->select_chip(mtd, -1);
1855 ops->retlen = ops->len - (size_t) readlen;
1857 ops->oobretlen = ops->ooblen - oobreadlen;
1865 return max_bitflips;
1869 * nand_read_oob_std - [REPLACEABLE] the most common OOB data read function
1870 * @mtd: mtd info structure
1871 * @chip: nand chip info structure
1872 * @page: page number to read
1874 static int nand_read_oob_std(struct mtd_info *mtd, struct nand_chip *chip,
1877 chip->cmdfunc(mtd, NAND_CMD_READOOB, 0, page);
1878 chip->read_buf(mtd, chip->oob_poi, mtd->oobsize);
1883 * nand_read_oob_syndrome - [REPLACEABLE] OOB data read function for HW ECC
1885 * @mtd: mtd info structure
1886 * @chip: nand chip info structure
1887 * @page: page number to read
1889 static int nand_read_oob_syndrome(struct mtd_info *mtd, struct nand_chip *chip,
1892 int length = mtd->oobsize;
1893 int chunk = chip->ecc.bytes + chip->ecc.prepad + chip->ecc.postpad;
1894 int eccsize = chip->ecc.size;
1895 uint8_t *bufpoi = chip->oob_poi;
1896 int i, toread, sndrnd = 0, pos;
1898 chip->cmdfunc(mtd, NAND_CMD_READ0, chip->ecc.size, page);
1899 for (i = 0; i < chip->ecc.steps; i++) {
1901 pos = eccsize + i * (eccsize + chunk);
1902 if (mtd->writesize > 512)
1903 chip->cmdfunc(mtd, NAND_CMD_RNDOUT, pos, -1);
1905 chip->cmdfunc(mtd, NAND_CMD_READ0, pos, page);
1908 toread = min_t(int, length, chunk);
1909 chip->read_buf(mtd, bufpoi, toread);
1914 chip->read_buf(mtd, bufpoi, length);
1920 * nand_write_oob_std - [REPLACEABLE] the most common OOB data write function
1921 * @mtd: mtd info structure
1922 * @chip: nand chip info structure
1923 * @page: page number to write
1925 static int nand_write_oob_std(struct mtd_info *mtd, struct nand_chip *chip,
1929 const uint8_t *buf = chip->oob_poi;
1930 int length = mtd->oobsize;
1932 chip->cmdfunc(mtd, NAND_CMD_SEQIN, mtd->writesize, page);
1933 chip->write_buf(mtd, buf, length);
1934 /* Send command to program the OOB data */
1935 chip->cmdfunc(mtd, NAND_CMD_PAGEPROG, -1, -1);
1937 status = chip->waitfunc(mtd, chip);
1939 return status & NAND_STATUS_FAIL ? -EIO : 0;
1943 * nand_write_oob_syndrome - [REPLACEABLE] OOB data write function for HW ECC
1944 * with syndrome - only for large page flash
1945 * @mtd: mtd info structure
1946 * @chip: nand chip info structure
1947 * @page: page number to write
1949 static int nand_write_oob_syndrome(struct mtd_info *mtd,
1950 struct nand_chip *chip, int page)
1952 int chunk = chip->ecc.bytes + chip->ecc.prepad + chip->ecc.postpad;
1953 int eccsize = chip->ecc.size, length = mtd->oobsize;
1954 int i, len, pos, status = 0, sndcmd = 0, steps = chip->ecc.steps;
1955 const uint8_t *bufpoi = chip->oob_poi;
1958 * data-ecc-data-ecc ... ecc-oob
1960 * data-pad-ecc-pad-data-pad .... ecc-pad-oob
1962 if (!chip->ecc.prepad && !chip->ecc.postpad) {
1963 pos = steps * (eccsize + chunk);
1968 chip->cmdfunc(mtd, NAND_CMD_SEQIN, pos, page);
1969 for (i = 0; i < steps; i++) {
1971 if (mtd->writesize <= 512) {
1972 uint32_t fill = 0xFFFFFFFF;
1976 int num = min_t(int, len, 4);
1977 chip->write_buf(mtd, (uint8_t *)&fill,
1982 pos = eccsize + i * (eccsize + chunk);
1983 chip->cmdfunc(mtd, NAND_CMD_RNDIN, pos, -1);
1987 len = min_t(int, length, chunk);
1988 chip->write_buf(mtd, bufpoi, len);
1993 chip->write_buf(mtd, bufpoi, length);
1995 chip->cmdfunc(mtd, NAND_CMD_PAGEPROG, -1, -1);
1996 status = chip->waitfunc(mtd, chip);
1998 return status & NAND_STATUS_FAIL ? -EIO : 0;
2002 * nand_do_read_oob - [INTERN] NAND read out-of-band
2003 * @mtd: MTD device structure
2004 * @from: offset to read from
2005 * @ops: oob operations description structure
2007 * NAND read out-of-band data from the spare area.
2009 static int nand_do_read_oob(struct mtd_info *mtd, loff_t from,
2010 struct mtd_oob_ops *ops)
2012 int page, realpage, chipnr;
2013 struct nand_chip *chip = mtd_to_nand(mtd);
2014 struct mtd_ecc_stats stats;
2015 int readlen = ops->ooblen;
2017 uint8_t *buf = ops->oobbuf;
2020 pr_debug("%s: from = 0x%08Lx, len = %i\n",
2021 __func__, (unsigned long long)from, readlen);
2023 stats = mtd->ecc_stats;
2025 len = mtd_oobavail(mtd, ops);
2027 if (unlikely(ops->ooboffs >= len)) {
2028 pr_debug("%s: attempt to start read outside oob\n",
2033 /* Do not allow reads past end of device */
2034 if (unlikely(from >= mtd->size ||
2035 ops->ooboffs + readlen > ((mtd->size >> chip->page_shift) -
2036 (from >> chip->page_shift)) * len)) {
2037 pr_debug("%s: attempt to read beyond end of device\n",
2042 chipnr = (int)(from >> chip->chip_shift);
2043 chip->select_chip(mtd, chipnr);
2045 /* Shift to get page */
2046 realpage = (int)(from >> chip->page_shift);
2047 page = realpage & chip->pagemask;
2052 if (ops->mode == MTD_OPS_RAW)
2053 ret = chip->ecc.read_oob_raw(mtd, chip, page);
2055 ret = chip->ecc.read_oob(mtd, chip, page);
2060 len = min(len, readlen);
2061 buf = nand_transfer_oob(chip, buf, ops, len);
2063 if (chip->options & NAND_NEED_READRDY) {
2064 /* Apply delay or wait for ready/busy pin */
2065 if (!chip->dev_ready)
2066 udelay(chip->chip_delay);
2068 nand_wait_ready(mtd);
2075 /* Increment page address */
2078 page = realpage & chip->pagemask;
2079 /* Check, if we cross a chip boundary */
2082 chip->select_chip(mtd, -1);
2083 chip->select_chip(mtd, chipnr);
2086 chip->select_chip(mtd, -1);
2088 ops->oobretlen = ops->ooblen - readlen;
2093 if (mtd->ecc_stats.failed - stats.failed)
2096 return mtd->ecc_stats.corrected - stats.corrected ? -EUCLEAN : 0;
2100 * nand_read_oob - [MTD Interface] NAND read data and/or out-of-band
2101 * @mtd: MTD device structure
2102 * @from: offset to read from
2103 * @ops: oob operation description structure
2105 * NAND read data and/or out-of-band data.
2107 static int nand_read_oob(struct mtd_info *mtd, loff_t from,
2108 struct mtd_oob_ops *ops)
2110 int ret = -ENOTSUPP;
2114 /* Do not allow reads past end of device */
2115 if (ops->datbuf && (from + ops->len) > mtd->size) {
2116 pr_debug("%s: attempt to read beyond end of device\n",
2121 nand_get_device(mtd, FL_READING);
2123 switch (ops->mode) {
2124 case MTD_OPS_PLACE_OOB:
2125 case MTD_OPS_AUTO_OOB:
2134 ret = nand_do_read_oob(mtd, from, ops);
2136 ret = nand_do_read_ops(mtd, from, ops);
2139 nand_release_device(mtd);
2145 * nand_write_page_raw - [INTERN] raw page write function
2146 * @mtd: mtd info structure
2147 * @chip: nand chip info structure
2149 * @oob_required: must write chip->oob_poi to OOB
2150 * @page: page number to write
2152 * Not for syndrome calculating ECC controllers, which use a special oob layout.
2154 static int nand_write_page_raw(struct mtd_info *mtd, struct nand_chip *chip,
2155 const uint8_t *buf, int oob_required, int page)
2157 chip->write_buf(mtd, buf, mtd->writesize);
2159 chip->write_buf(mtd, chip->oob_poi, mtd->oobsize);
2165 * nand_write_page_raw_syndrome - [INTERN] raw page write function
2166 * @mtd: mtd info structure
2167 * @chip: nand chip info structure
2169 * @oob_required: must write chip->oob_poi to OOB
2170 * @page: page number to write
2172 * We need a special oob layout and handling even when ECC isn't checked.
2174 static int nand_write_page_raw_syndrome(struct mtd_info *mtd,
2175 struct nand_chip *chip,
2176 const uint8_t *buf, int oob_required,
2179 int eccsize = chip->ecc.size;
2180 int eccbytes = chip->ecc.bytes;
2181 uint8_t *oob = chip->oob_poi;
2184 for (steps = chip->ecc.steps; steps > 0; steps--) {
2185 chip->write_buf(mtd, buf, eccsize);
2188 if (chip->ecc.prepad) {
2189 chip->write_buf(mtd, oob, chip->ecc.prepad);
2190 oob += chip->ecc.prepad;
2193 chip->write_buf(mtd, oob, eccbytes);
2196 if (chip->ecc.postpad) {
2197 chip->write_buf(mtd, oob, chip->ecc.postpad);
2198 oob += chip->ecc.postpad;
2202 size = mtd->oobsize - (oob - chip->oob_poi);
2204 chip->write_buf(mtd, oob, size);
2209 * nand_write_page_swecc - [REPLACEABLE] software ECC based page write function
2210 * @mtd: mtd info structure
2211 * @chip: nand chip info structure
2213 * @oob_required: must write chip->oob_poi to OOB
2214 * @page: page number to write
2216 static int nand_write_page_swecc(struct mtd_info *mtd, struct nand_chip *chip,
2217 const uint8_t *buf, int oob_required,
2220 int i, eccsize = chip->ecc.size;
2221 int eccbytes = chip->ecc.bytes;
2222 int eccsteps = chip->ecc.steps;
2223 uint8_t *ecc_calc = chip->buffers->ecccalc;
2224 const uint8_t *p = buf;
2225 uint32_t *eccpos = chip->ecc.layout->eccpos;
2227 /* Software ECC calculation */
2228 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize)
2229 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
2231 for (i = 0; i < chip->ecc.total; i++)
2232 chip->oob_poi[eccpos[i]] = ecc_calc[i];
2234 return chip->ecc.write_page_raw(mtd, chip, buf, 1, page);
2238 * nand_write_page_hwecc - [REPLACEABLE] hardware ECC based page write function
2239 * @mtd: mtd info structure
2240 * @chip: nand chip info structure
2242 * @oob_required: must write chip->oob_poi to OOB
2243 * @page: page number to write
2245 static int nand_write_page_hwecc(struct mtd_info *mtd, struct nand_chip *chip,
2246 const uint8_t *buf, int oob_required,
2249 int i, eccsize = chip->ecc.size;
2250 int eccbytes = chip->ecc.bytes;
2251 int eccsteps = chip->ecc.steps;
2252 uint8_t *ecc_calc = chip->buffers->ecccalc;
2253 const uint8_t *p = buf;
2254 uint32_t *eccpos = chip->ecc.layout->eccpos;
2256 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
2257 chip->ecc.hwctl(mtd, NAND_ECC_WRITE);
2258 chip->write_buf(mtd, p, eccsize);
2259 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
2262 for (i = 0; i < chip->ecc.total; i++)
2263 chip->oob_poi[eccpos[i]] = ecc_calc[i];
2265 chip->write_buf(mtd, chip->oob_poi, mtd->oobsize);
2272 * nand_write_subpage_hwecc - [REPLACEABLE] hardware ECC based subpage write
2273 * @mtd: mtd info structure
2274 * @chip: nand chip info structure
2275 * @offset: column address of subpage within the page
2276 * @data_len: data length
2278 * @oob_required: must write chip->oob_poi to OOB
2279 * @page: page number to write
2281 static int nand_write_subpage_hwecc(struct mtd_info *mtd,
2282 struct nand_chip *chip, uint32_t offset,
2283 uint32_t data_len, const uint8_t *buf,
2284 int oob_required, int page)
2286 uint8_t *oob_buf = chip->oob_poi;
2287 uint8_t *ecc_calc = chip->buffers->ecccalc;
2288 int ecc_size = chip->ecc.size;
2289 int ecc_bytes = chip->ecc.bytes;
2290 int ecc_steps = chip->ecc.steps;
2291 uint32_t *eccpos = chip->ecc.layout->eccpos;
2292 uint32_t start_step = offset / ecc_size;
2293 uint32_t end_step = (offset + data_len - 1) / ecc_size;
2294 int oob_bytes = mtd->oobsize / ecc_steps;
2297 for (step = 0; step < ecc_steps; step++) {
2298 /* configure controller for WRITE access */
2299 chip->ecc.hwctl(mtd, NAND_ECC_WRITE);
2301 /* write data (untouched subpages already masked by 0xFF) */
2302 chip->write_buf(mtd, buf, ecc_size);
2304 /* mask ECC of un-touched subpages by padding 0xFF */
2305 if ((step < start_step) || (step > end_step))
2306 memset(ecc_calc, 0xff, ecc_bytes);
2308 chip->ecc.calculate(mtd, buf, ecc_calc);
2310 /* mask OOB of un-touched subpages by padding 0xFF */
2311 /* if oob_required, preserve OOB metadata of written subpage */
2312 if (!oob_required || (step < start_step) || (step > end_step))
2313 memset(oob_buf, 0xff, oob_bytes);
2316 ecc_calc += ecc_bytes;
2317 oob_buf += oob_bytes;
2320 /* copy calculated ECC for whole page to chip->buffer->oob */
2321 /* this include masked-value(0xFF) for unwritten subpages */
2322 ecc_calc = chip->buffers->ecccalc;
2323 for (i = 0; i < chip->ecc.total; i++)
2324 chip->oob_poi[eccpos[i]] = ecc_calc[i];
2326 /* write OOB buffer to NAND device */
2327 chip->write_buf(mtd, chip->oob_poi, mtd->oobsize);
2334 * nand_write_page_syndrome - [REPLACEABLE] hardware ECC syndrome based page write
2335 * @mtd: mtd info structure
2336 * @chip: nand chip info structure
2338 * @oob_required: must write chip->oob_poi to OOB
2339 * @page: page number to write
2341 * The hw generator calculates the error syndrome automatically. Therefore we
2342 * need a special oob layout and handling.
2344 static int nand_write_page_syndrome(struct mtd_info *mtd,
2345 struct nand_chip *chip,
2346 const uint8_t *buf, int oob_required,
2349 int i, eccsize = chip->ecc.size;
2350 int eccbytes = chip->ecc.bytes;
2351 int eccsteps = chip->ecc.steps;
2352 const uint8_t *p = buf;
2353 uint8_t *oob = chip->oob_poi;
2355 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
2357 chip->ecc.hwctl(mtd, NAND_ECC_WRITE);
2358 chip->write_buf(mtd, p, eccsize);
2360 if (chip->ecc.prepad) {
2361 chip->write_buf(mtd, oob, chip->ecc.prepad);
2362 oob += chip->ecc.prepad;
2365 chip->ecc.calculate(mtd, p, oob);
2366 chip->write_buf(mtd, oob, eccbytes);
2369 if (chip->ecc.postpad) {
2370 chip->write_buf(mtd, oob, chip->ecc.postpad);
2371 oob += chip->ecc.postpad;
2375 /* Calculate remaining oob bytes */
2376 i = mtd->oobsize - (oob - chip->oob_poi);
2378 chip->write_buf(mtd, oob, i);
2384 * nand_write_page - [REPLACEABLE] write one page
2385 * @mtd: MTD device structure
2386 * @chip: NAND chip descriptor
2387 * @offset: address offset within the page
2388 * @data_len: length of actual data to be written
2389 * @buf: the data to write
2390 * @oob_required: must write chip->oob_poi to OOB
2391 * @page: page number to write
2392 * @raw: use _raw version of write_page
2394 static int nand_write_page(struct mtd_info *mtd, struct nand_chip *chip,
2395 uint32_t offset, int data_len, const uint8_t *buf,
2396 int oob_required, int page, int raw)
2398 int status, subpage;
2400 if (!(chip->options & NAND_NO_SUBPAGE_WRITE) &&
2401 chip->ecc.write_subpage)
2402 subpage = offset || (data_len < mtd->writesize);
2406 if (nand_standard_page_accessors(&chip->ecc))
2407 chip->cmdfunc(mtd, NAND_CMD_SEQIN, 0x00, page);
2410 status = chip->ecc.write_page_raw(mtd, chip, buf,
2411 oob_required, page);
2413 status = chip->ecc.write_subpage(mtd, chip, offset, data_len,
2414 buf, oob_required, page);
2416 status = chip->ecc.write_page(mtd, chip, buf, oob_required,
2422 if (nand_standard_page_accessors(&chip->ecc)) {
2423 chip->cmdfunc(mtd, NAND_CMD_PAGEPROG, -1, -1);
2425 status = chip->waitfunc(mtd, chip);
2426 if (status & NAND_STATUS_FAIL)
2434 * nand_fill_oob - [INTERN] Transfer client buffer to oob
2435 * @mtd: MTD device structure
2436 * @oob: oob data buffer
2437 * @len: oob data write length
2438 * @ops: oob ops structure
2440 static uint8_t *nand_fill_oob(struct mtd_info *mtd, uint8_t *oob, size_t len,
2441 struct mtd_oob_ops *ops)
2443 struct nand_chip *chip = mtd_to_nand(mtd);
2446 * Initialise to all 0xFF, to avoid the possibility of left over OOB
2447 * data from a previous OOB read.
2449 memset(chip->oob_poi, 0xff, mtd->oobsize);
2451 switch (ops->mode) {
2453 case MTD_OPS_PLACE_OOB:
2455 memcpy(chip->oob_poi + ops->ooboffs, oob, len);
2458 case MTD_OPS_AUTO_OOB: {
2459 struct nand_oobfree *free = chip->ecc.layout->oobfree;
2460 uint32_t boffs = 0, woffs = ops->ooboffs;
2463 for (; free->length && len; free++, len -= bytes) {
2464 /* Write request not from offset 0? */
2465 if (unlikely(woffs)) {
2466 if (woffs >= free->length) {
2467 woffs -= free->length;
2470 boffs = free->offset + woffs;
2471 bytes = min_t(size_t, len,
2472 (free->length - woffs));
2475 bytes = min_t(size_t, len, free->length);
2476 boffs = free->offset;
2478 memcpy(chip->oob_poi + boffs, oob, bytes);
2489 #define NOTALIGNED(x) ((x & (chip->subpagesize - 1)) != 0)
2492 * nand_do_write_ops - [INTERN] NAND write with ECC
2493 * @mtd: MTD device structure
2494 * @to: offset to write to
2495 * @ops: oob operations description structure
2497 * NAND write with ECC.
2499 static int nand_do_write_ops(struct mtd_info *mtd, loff_t to,
2500 struct mtd_oob_ops *ops)
2502 int chipnr, realpage, page, column;
2503 struct nand_chip *chip = mtd_to_nand(mtd);
2504 uint32_t writelen = ops->len;
2506 uint32_t oobwritelen = ops->ooblen;
2507 uint32_t oobmaxlen = mtd_oobavail(mtd, ops);
2509 uint8_t *oob = ops->oobbuf;
2510 uint8_t *buf = ops->datbuf;
2512 int oob_required = oob ? 1 : 0;
2518 /* Reject writes, which are not page aligned */
2519 if (NOTALIGNED(to)) {
2520 pr_notice("%s: attempt to write non page aligned data\n",
2525 column = to & (mtd->writesize - 1);
2527 chipnr = (int)(to >> chip->chip_shift);
2528 chip->select_chip(mtd, chipnr);
2530 /* Check, if it is write protected */
2531 if (nand_check_wp(mtd)) {
2536 realpage = (int)(to >> chip->page_shift);
2537 page = realpage & chip->pagemask;
2539 /* Invalidate the page cache, when we write to the cached page */
2540 if (to <= ((loff_t)chip->pagebuf << chip->page_shift) &&
2541 ((loff_t)chip->pagebuf << chip->page_shift) < (to + ops->len))
2544 /* Don't allow multipage oob writes with offset */
2545 if (oob && ops->ooboffs && (ops->ooboffs + ops->ooblen > oobmaxlen)) {
2551 int bytes = mtd->writesize;
2552 uint8_t *wbuf = buf;
2554 int part_pagewr = (column || writelen < mtd->writesize);
2558 else if (chip->options & NAND_USE_BOUNCE_BUFFER)
2559 use_bufpoi = !IS_ALIGNED((unsigned long)buf,
2565 /* Partial page write?, or need to use bounce buffer */
2567 pr_debug("%s: using write bounce buffer for buf@%p\n",
2570 bytes = min_t(int, bytes - column, writelen);
2572 memset(chip->buffers->databuf, 0xff, mtd->writesize);
2573 memcpy(&chip->buffers->databuf[column], buf, bytes);
2574 wbuf = chip->buffers->databuf;
2577 if (unlikely(oob)) {
2578 size_t len = min(oobwritelen, oobmaxlen);
2579 oob = nand_fill_oob(mtd, oob, len, ops);
2582 /* We still need to erase leftover OOB data */
2583 memset(chip->oob_poi, 0xff, mtd->oobsize);
2585 ret = chip->write_page(mtd, chip, column, bytes, wbuf,
2587 (ops->mode == MTD_OPS_RAW));
2599 page = realpage & chip->pagemask;
2600 /* Check, if we cross a chip boundary */
2603 chip->select_chip(mtd, -1);
2604 chip->select_chip(mtd, chipnr);
2608 ops->retlen = ops->len - writelen;
2610 ops->oobretlen = ops->ooblen;
2613 chip->select_chip(mtd, -1);
2618 * panic_nand_write - [MTD Interface] NAND write with ECC
2619 * @mtd: MTD device structure
2620 * @to: offset to write to
2621 * @len: number of bytes to write
2622 * @retlen: pointer to variable to store the number of written bytes
2623 * @buf: the data to write
2625 * NAND write with ECC. Used when performing writes in interrupt context, this
2626 * may for example be called by mtdoops when writing an oops while in panic.
2628 static int panic_nand_write(struct mtd_info *mtd, loff_t to, size_t len,
2629 size_t *retlen, const uint8_t *buf)
2631 struct nand_chip *chip = mtd_to_nand(mtd);
2632 struct mtd_oob_ops ops;
2635 /* Wait for the device to get ready */
2636 panic_nand_wait(mtd, chip, 400);
2638 /* Grab the device */
2639 panic_nand_get_device(chip, mtd, FL_WRITING);
2641 memset(&ops, 0, sizeof(ops));
2643 ops.datbuf = (uint8_t *)buf;
2644 ops.mode = MTD_OPS_PLACE_OOB;
2646 ret = nand_do_write_ops(mtd, to, &ops);
2648 *retlen = ops.retlen;
2653 * nand_do_write_oob - [MTD Interface] NAND write out-of-band
2654 * @mtd: MTD device structure
2655 * @to: offset to write to
2656 * @ops: oob operation description structure
2658 * NAND write out-of-band.
2660 static int nand_do_write_oob(struct mtd_info *mtd, loff_t to,
2661 struct mtd_oob_ops *ops)
2663 int chipnr, page, status, len;
2664 struct nand_chip *chip = mtd_to_nand(mtd);
2666 pr_debug("%s: to = 0x%08x, len = %i\n",
2667 __func__, (unsigned int)to, (int)ops->ooblen);
2669 len = mtd_oobavail(mtd, ops);
2671 /* Do not allow write past end of page */
2672 if ((ops->ooboffs + ops->ooblen) > len) {
2673 pr_debug("%s: attempt to write past end of page\n",
2678 if (unlikely(ops->ooboffs >= len)) {
2679 pr_debug("%s: attempt to start write outside oob\n",
2684 /* Do not allow write past end of device */
2685 if (unlikely(to >= mtd->size ||
2686 ops->ooboffs + ops->ooblen >
2687 ((mtd->size >> chip->page_shift) -
2688 (to >> chip->page_shift)) * len)) {
2689 pr_debug("%s: attempt to write beyond end of device\n",
2694 chipnr = (int)(to >> chip->chip_shift);
2697 * Reset the chip. Some chips (like the Toshiba TC5832DC found in one
2698 * of my DiskOnChip 2000 test units) will clear the whole data page too
2699 * if we don't do this. I have no clue why, but I seem to have 'fixed'
2700 * it in the doc2000 driver in August 1999. dwmw2.
2702 nand_reset(chip, chipnr);
2704 chip->select_chip(mtd, chipnr);
2706 /* Shift to get page */
2707 page = (int)(to >> chip->page_shift);
2709 /* Check, if it is write protected */
2710 if (nand_check_wp(mtd)) {
2711 chip->select_chip(mtd, -1);
2715 /* Invalidate the page cache, if we write to the cached page */
2716 if (page == chip->pagebuf)
2719 nand_fill_oob(mtd, ops->oobbuf, ops->ooblen, ops);
2721 if (ops->mode == MTD_OPS_RAW)
2722 status = chip->ecc.write_oob_raw(mtd, chip, page & chip->pagemask);
2724 status = chip->ecc.write_oob(mtd, chip, page & chip->pagemask);
2726 chip->select_chip(mtd, -1);
2731 ops->oobretlen = ops->ooblen;
2737 * nand_write_oob - [MTD Interface] NAND write data and/or out-of-band
2738 * @mtd: MTD device structure
2739 * @to: offset to write to
2740 * @ops: oob operation description structure
2742 static int nand_write_oob(struct mtd_info *mtd, loff_t to,
2743 struct mtd_oob_ops *ops)
2745 int ret = -ENOTSUPP;
2749 /* Do not allow writes past end of device */
2750 if (ops->datbuf && (to + ops->len) > mtd->size) {
2751 pr_debug("%s: attempt to write beyond end of device\n",
2756 nand_get_device(mtd, FL_WRITING);
2758 switch (ops->mode) {
2759 case MTD_OPS_PLACE_OOB:
2760 case MTD_OPS_AUTO_OOB:
2769 ret = nand_do_write_oob(mtd, to, ops);
2771 ret = nand_do_write_ops(mtd, to, ops);
2774 nand_release_device(mtd);
2779 * single_erase - [GENERIC] NAND standard block erase command function
2780 * @mtd: MTD device structure
2781 * @page: the page address of the block which will be erased
2783 * Standard erase command for NAND chips. Returns NAND status.
2785 static int single_erase(struct mtd_info *mtd, int page)
2787 struct nand_chip *chip = mtd_to_nand(mtd);
2788 /* Send commands to erase a block */
2789 chip->cmdfunc(mtd, NAND_CMD_ERASE1, -1, page);
2790 chip->cmdfunc(mtd, NAND_CMD_ERASE2, -1, -1);
2792 return chip->waitfunc(mtd, chip);
2796 * nand_erase - [MTD Interface] erase block(s)
2797 * @mtd: MTD device structure
2798 * @instr: erase instruction
2800 * Erase one ore more blocks.
2802 static int nand_erase(struct mtd_info *mtd, struct erase_info *instr)
2804 return nand_erase_nand(mtd, instr, 0);
2808 * nand_erase_nand - [INTERN] erase block(s)
2809 * @mtd: MTD device structure
2810 * @instr: erase instruction
2811 * @allowbbt: allow erasing the bbt area
2813 * Erase one ore more blocks.
2815 int nand_erase_nand(struct mtd_info *mtd, struct erase_info *instr,
2818 int page, status, pages_per_block, ret, chipnr;
2819 struct nand_chip *chip = mtd_to_nand(mtd);
2822 pr_debug("%s: start = 0x%012llx, len = %llu\n",
2823 __func__, (unsigned long long)instr->addr,
2824 (unsigned long long)instr->len);
2826 if (check_offs_len(mtd, instr->addr, instr->len))
2829 /* Grab the lock and see if the device is available */
2830 nand_get_device(mtd, FL_ERASING);
2832 /* Shift to get first page */
2833 page = (int)(instr->addr >> chip->page_shift);
2834 chipnr = (int)(instr->addr >> chip->chip_shift);
2836 /* Calculate pages in each block */
2837 pages_per_block = 1 << (chip->phys_erase_shift - chip->page_shift);
2839 /* Select the NAND device */
2840 chip->select_chip(mtd, chipnr);
2842 /* Check, if it is write protected */
2843 if (nand_check_wp(mtd)) {
2844 pr_debug("%s: device is write protected!\n",
2846 instr->state = MTD_ERASE_FAILED;
2850 /* Loop through the pages */
2853 instr->state = MTD_ERASING;
2858 /* Check if we have a bad block, we do not erase bad blocks! */
2859 if (!instr->scrub && nand_block_checkbad(mtd, ((loff_t) page) <<
2860 chip->page_shift, allowbbt)) {
2861 pr_warn("%s: attempt to erase a bad block at page 0x%08x\n",
2863 instr->state = MTD_ERASE_FAILED;
2868 * Invalidate the page cache, if we erase the block which
2869 * contains the current cached page.
2871 if (page <= chip->pagebuf && chip->pagebuf <
2872 (page + pages_per_block))
2875 status = chip->erase(mtd, page & chip->pagemask);
2877 /* See if block erase succeeded */
2878 if (status & NAND_STATUS_FAIL) {
2879 pr_debug("%s: failed erase, page 0x%08x\n",
2881 instr->state = MTD_ERASE_FAILED;
2883 ((loff_t)page << chip->page_shift);
2887 /* Increment page address and decrement length */
2888 len -= (1ULL << chip->phys_erase_shift);
2889 page += pages_per_block;
2891 /* Check, if we cross a chip boundary */
2892 if (len && !(page & chip->pagemask)) {
2894 chip->select_chip(mtd, -1);
2895 chip->select_chip(mtd, chipnr);
2898 instr->state = MTD_ERASE_DONE;
2902 ret = instr->state == MTD_ERASE_DONE ? 0 : -EIO;
2904 /* Deselect and wake up anyone waiting on the device */
2905 chip->select_chip(mtd, -1);
2906 nand_release_device(mtd);
2908 /* Do call back function */
2910 mtd_erase_callback(instr);
2912 /* Return more or less happy */
2917 * nand_sync - [MTD Interface] sync
2918 * @mtd: MTD device structure
2920 * Sync is actually a wait for chip ready function.
2922 static void nand_sync(struct mtd_info *mtd)
2924 pr_debug("%s: called\n", __func__);
2926 /* Grab the lock and see if the device is available */
2927 nand_get_device(mtd, FL_SYNCING);
2928 /* Release it and go back */
2929 nand_release_device(mtd);
2933 * nand_block_isbad - [MTD Interface] Check if block at offset is bad
2934 * @mtd: MTD device structure
2935 * @offs: offset relative to mtd start
2937 static int nand_block_isbad(struct mtd_info *mtd, loff_t offs)
2939 struct nand_chip *chip = mtd_to_nand(mtd);
2940 int chipnr = (int)(offs >> chip->chip_shift);
2943 /* Select the NAND device */
2944 nand_get_device(mtd, FL_READING);
2945 chip->select_chip(mtd, chipnr);
2947 ret = nand_block_checkbad(mtd, offs, 0);
2949 chip->select_chip(mtd, -1);
2950 nand_release_device(mtd);
2956 * nand_block_markbad - [MTD Interface] Mark block at the given offset as bad
2957 * @mtd: MTD device structure
2958 * @ofs: offset relative to mtd start
2960 static int nand_block_markbad(struct mtd_info *mtd, loff_t ofs)
2964 ret = nand_block_isbad(mtd, ofs);
2966 /* If it was bad already, return success and do nothing */
2972 return nand_block_markbad_lowlevel(mtd, ofs);
2976 * nand_onfi_set_features- [REPLACEABLE] set features for ONFI nand
2977 * @mtd: MTD device structure
2978 * @chip: nand chip info structure
2979 * @addr: feature address.
2980 * @subfeature_param: the subfeature parameters, a four bytes array.
2982 static int nand_onfi_set_features(struct mtd_info *mtd, struct nand_chip *chip,
2983 int addr, uint8_t *subfeature_param)
2988 #ifdef CONFIG_SYS_NAND_ONFI_DETECTION
2989 if (!chip->onfi_version ||
2990 !(le16_to_cpu(chip->onfi_params.opt_cmd)
2991 & ONFI_OPT_CMD_SET_GET_FEATURES))
2995 chip->cmdfunc(mtd, NAND_CMD_SET_FEATURES, addr, -1);
2996 for (i = 0; i < ONFI_SUBFEATURE_PARAM_LEN; ++i)
2997 chip->write_byte(mtd, subfeature_param[i]);
2999 status = chip->waitfunc(mtd, chip);
3000 if (status & NAND_STATUS_FAIL)
3006 * nand_onfi_get_features- [REPLACEABLE] get features for ONFI nand
3007 * @mtd: MTD device structure
3008 * @chip: nand chip info structure
3009 * @addr: feature address.
3010 * @subfeature_param: the subfeature parameters, a four bytes array.
3012 static int nand_onfi_get_features(struct mtd_info *mtd, struct nand_chip *chip,
3013 int addr, uint8_t *subfeature_param)
3017 #ifdef CONFIG_SYS_NAND_ONFI_DETECTION
3018 if (!chip->onfi_version ||
3019 !(le16_to_cpu(chip->onfi_params.opt_cmd)
3020 & ONFI_OPT_CMD_SET_GET_FEATURES))
3024 chip->cmdfunc(mtd, NAND_CMD_GET_FEATURES, addr, -1);
3025 for (i = 0; i < ONFI_SUBFEATURE_PARAM_LEN; ++i)
3026 *subfeature_param++ = chip->read_byte(mtd);
3030 /* Set default functions */
3031 static void nand_set_defaults(struct nand_chip *chip, int busw)
3033 /* check for proper chip_delay setup, set 20us if not */
3034 if (!chip->chip_delay)
3035 chip->chip_delay = 20;
3037 /* check, if a user supplied command function given */
3038 if (chip->cmdfunc == NULL)
3039 chip->cmdfunc = nand_command;
3041 /* check, if a user supplied wait function given */
3042 if (chip->waitfunc == NULL)
3043 chip->waitfunc = nand_wait;
3045 if (!chip->select_chip)
3046 chip->select_chip = nand_select_chip;
3048 /* set for ONFI nand */
3049 if (!chip->onfi_set_features)
3050 chip->onfi_set_features = nand_onfi_set_features;
3051 if (!chip->onfi_get_features)
3052 chip->onfi_get_features = nand_onfi_get_features;
3054 /* If called twice, pointers that depend on busw may need to be reset */
3055 if (!chip->read_byte || chip->read_byte == nand_read_byte)
3056 chip->read_byte = busw ? nand_read_byte16 : nand_read_byte;
3057 if (!chip->read_word)
3058 chip->read_word = nand_read_word;
3059 if (!chip->block_bad)
3060 chip->block_bad = nand_block_bad;
3061 if (!chip->block_markbad)
3062 chip->block_markbad = nand_default_block_markbad;
3063 if (!chip->write_buf || chip->write_buf == nand_write_buf)
3064 chip->write_buf = busw ? nand_write_buf16 : nand_write_buf;
3065 if (!chip->write_byte || chip->write_byte == nand_write_byte)
3066 chip->write_byte = busw ? nand_write_byte16 : nand_write_byte;
3067 if (!chip->read_buf || chip->read_buf == nand_read_buf)
3068 chip->read_buf = busw ? nand_read_buf16 : nand_read_buf;
3069 if (!chip->scan_bbt)
3070 chip->scan_bbt = nand_default_bbt;
3072 if (!chip->controller) {
3073 chip->controller = &chip->hwcontrol;
3074 spin_lock_init(&chip->controller->lock);
3075 init_waitqueue_head(&chip->controller->wq);
3078 if (!chip->buf_align)
3079 chip->buf_align = 1;
3082 /* Sanitize ONFI strings so we can safely print them */
3083 static void sanitize_string(char *s, size_t len)
3087 /* Null terminate */
3090 /* Remove non printable chars */
3091 for (i = 0; i < len - 1; i++) {
3092 if (s[i] < ' ' || s[i] > 127)
3096 /* Remove trailing spaces */
3100 static u16 onfi_crc16(u16 crc, u8 const *p, size_t len)
3105 for (i = 0; i < 8; i++)
3106 crc = (crc << 1) ^ ((crc & 0x8000) ? 0x8005 : 0);
3112 #ifdef CONFIG_SYS_NAND_ONFI_DETECTION
3113 /* Parse the Extended Parameter Page. */
3114 static int nand_flash_detect_ext_param_page(struct mtd_info *mtd,
3115 struct nand_chip *chip, struct nand_onfi_params *p)
3117 struct onfi_ext_param_page *ep;
3118 struct onfi_ext_section *s;
3119 struct onfi_ext_ecc_info *ecc;
3125 len = le16_to_cpu(p->ext_param_page_length) * 16;
3126 ep = kmalloc(len, GFP_KERNEL);
3130 /* Send our own NAND_CMD_PARAM. */
3131 chip->cmdfunc(mtd, NAND_CMD_PARAM, 0, -1);
3133 /* Use the Change Read Column command to skip the ONFI param pages. */
3134 chip->cmdfunc(mtd, NAND_CMD_RNDOUT,
3135 sizeof(*p) * p->num_of_param_pages , -1);
3137 /* Read out the Extended Parameter Page. */
3138 chip->read_buf(mtd, (uint8_t *)ep, len);
3139 if ((onfi_crc16(ONFI_CRC_BASE, ((uint8_t *)ep) + 2, len - 2)
3140 != le16_to_cpu(ep->crc))) {
3141 pr_debug("fail in the CRC.\n");
3146 * Check the signature.
3147 * Do not strictly follow the ONFI spec, maybe changed in future.
3149 if (strncmp((char *)ep->sig, "EPPS", 4)) {
3150 pr_debug("The signature is invalid.\n");
3154 /* find the ECC section. */
3155 cursor = (uint8_t *)(ep + 1);
3156 for (i = 0; i < ONFI_EXT_SECTION_MAX; i++) {
3157 s = ep->sections + i;
3158 if (s->type == ONFI_SECTION_TYPE_2)
3160 cursor += s->length * 16;
3162 if (i == ONFI_EXT_SECTION_MAX) {
3163 pr_debug("We can not find the ECC section.\n");
3167 /* get the info we want. */
3168 ecc = (struct onfi_ext_ecc_info *)cursor;
3170 if (!ecc->codeword_size) {
3171 pr_debug("Invalid codeword size\n");
3175 chip->ecc_strength_ds = ecc->ecc_bits;
3176 chip->ecc_step_ds = 1 << ecc->codeword_size;
3184 static int nand_setup_read_retry_micron(struct mtd_info *mtd, int retry_mode)
3186 struct nand_chip *chip = mtd_to_nand(mtd);
3187 uint8_t feature[ONFI_SUBFEATURE_PARAM_LEN] = {retry_mode};
3189 return chip->onfi_set_features(mtd, chip, ONFI_FEATURE_ADDR_READ_RETRY,
3194 * Configure chip properties from Micron vendor-specific ONFI table
3196 static void nand_onfi_detect_micron(struct nand_chip *chip,
3197 struct nand_onfi_params *p)
3199 struct nand_onfi_vendor_micron *micron = (void *)p->vendor;
3201 if (le16_to_cpu(p->vendor_revision) < 1)
3204 chip->read_retries = micron->read_retry_options;
3205 chip->setup_read_retry = nand_setup_read_retry_micron;
3209 * Check if the NAND chip is ONFI compliant, returns 1 if it is, 0 otherwise.
3211 static int nand_flash_detect_onfi(struct mtd_info *mtd, struct nand_chip *chip,
3214 struct nand_onfi_params *p = &chip->onfi_params;
3218 /* Try ONFI for unknown chip or LP */
3219 chip->cmdfunc(mtd, NAND_CMD_READID, 0x20, -1);
3220 if (chip->read_byte(mtd) != 'O' || chip->read_byte(mtd) != 'N' ||
3221 chip->read_byte(mtd) != 'F' || chip->read_byte(mtd) != 'I')
3224 chip->cmdfunc(mtd, NAND_CMD_PARAM, 0, -1);
3225 for (i = 0; i < 3; i++) {
3226 for (j = 0; j < sizeof(*p); j++)
3227 ((uint8_t *)p)[j] = chip->read_byte(mtd);
3228 if (onfi_crc16(ONFI_CRC_BASE, (uint8_t *)p, 254) ==
3229 le16_to_cpu(p->crc)) {
3235 pr_err("Could not find valid ONFI parameter page; aborting\n");
3240 val = le16_to_cpu(p->revision);
3242 chip->onfi_version = 23;
3243 else if (val & (1 << 4))
3244 chip->onfi_version = 22;
3245 else if (val & (1 << 3))
3246 chip->onfi_version = 21;
3247 else if (val & (1 << 2))
3248 chip->onfi_version = 20;
3249 else if (val & (1 << 1))
3250 chip->onfi_version = 10;
3252 if (!chip->onfi_version) {
3253 pr_info("unsupported ONFI version: %d\n", val);
3257 sanitize_string(p->manufacturer, sizeof(p->manufacturer));
3258 sanitize_string(p->model, sizeof(p->model));
3260 mtd->name = p->model;
3262 mtd->writesize = le32_to_cpu(p->byte_per_page);
3265 * pages_per_block and blocks_per_lun may not be a power-of-2 size
3266 * (don't ask me who thought of this...). MTD assumes that these
3267 * dimensions will be power-of-2, so just truncate the remaining area.
3269 mtd->erasesize = 1 << (fls(le32_to_cpu(p->pages_per_block)) - 1);
3270 mtd->erasesize *= mtd->writesize;
3272 mtd->oobsize = le16_to_cpu(p->spare_bytes_per_page);
3274 /* See erasesize comment */
3275 chip->chipsize = 1 << (fls(le32_to_cpu(p->blocks_per_lun)) - 1);
3276 chip->chipsize *= (uint64_t)mtd->erasesize * p->lun_count;
3277 chip->bits_per_cell = p->bits_per_cell;
3279 if (onfi_feature(chip) & ONFI_FEATURE_16_BIT_BUS)
3280 *busw = NAND_BUSWIDTH_16;
3284 if (p->ecc_bits != 0xff) {
3285 chip->ecc_strength_ds = p->ecc_bits;
3286 chip->ecc_step_ds = 512;
3287 } else if (chip->onfi_version >= 21 &&
3288 (onfi_feature(chip) & ONFI_FEATURE_EXT_PARAM_PAGE)) {
3291 * The nand_flash_detect_ext_param_page() uses the
3292 * Change Read Column command which maybe not supported
3293 * by the chip->cmdfunc. So try to update the chip->cmdfunc
3294 * now. We do not replace user supplied command function.
3296 if (mtd->writesize > 512 && chip->cmdfunc == nand_command)
3297 chip->cmdfunc = nand_command_lp;
3299 /* The Extended Parameter Page is supported since ONFI 2.1. */
3300 if (nand_flash_detect_ext_param_page(mtd, chip, p))
3301 pr_warn("Failed to detect ONFI extended param page\n");
3303 pr_warn("Could not retrieve ONFI ECC requirements\n");
3306 if (p->jedec_id == NAND_MFR_MICRON)
3307 nand_onfi_detect_micron(chip, p);
3312 static int nand_flash_detect_onfi(struct mtd_info *mtd, struct nand_chip *chip,
3320 * Check if the NAND chip is JEDEC compliant, returns 1 if it is, 0 otherwise.
3322 static int nand_flash_detect_jedec(struct mtd_info *mtd, struct nand_chip *chip,
3325 struct nand_jedec_params *p = &chip->jedec_params;
3326 struct jedec_ecc_info *ecc;
3330 /* Try JEDEC for unknown chip or LP */
3331 chip->cmdfunc(mtd, NAND_CMD_READID, 0x40, -1);
3332 if (chip->read_byte(mtd) != 'J' || chip->read_byte(mtd) != 'E' ||
3333 chip->read_byte(mtd) != 'D' || chip->read_byte(mtd) != 'E' ||
3334 chip->read_byte(mtd) != 'C')
3337 chip->cmdfunc(mtd, NAND_CMD_PARAM, 0x40, -1);
3338 for (i = 0; i < 3; i++) {
3339 for (j = 0; j < sizeof(*p); j++)
3340 ((uint8_t *)p)[j] = chip->read_byte(mtd);
3342 if (onfi_crc16(ONFI_CRC_BASE, (uint8_t *)p, 510) ==
3343 le16_to_cpu(p->crc))
3348 pr_err("Could not find valid JEDEC parameter page; aborting\n");
3353 val = le16_to_cpu(p->revision);
3355 chip->jedec_version = 10;
3356 else if (val & (1 << 1))
3357 chip->jedec_version = 1; /* vendor specific version */
3359 if (!chip->jedec_version) {
3360 pr_info("unsupported JEDEC version: %d\n", val);
3364 sanitize_string(p->manufacturer, sizeof(p->manufacturer));
3365 sanitize_string(p->model, sizeof(p->model));
3367 mtd->name = p->model;
3369 mtd->writesize = le32_to_cpu(p->byte_per_page);
3371 /* Please reference to the comment for nand_flash_detect_onfi. */
3372 mtd->erasesize = 1 << (fls(le32_to_cpu(p->pages_per_block)) - 1);
3373 mtd->erasesize *= mtd->writesize;
3375 mtd->oobsize = le16_to_cpu(p->spare_bytes_per_page);
3377 /* Please reference to the comment for nand_flash_detect_onfi. */
3378 chip->chipsize = 1 << (fls(le32_to_cpu(p->blocks_per_lun)) - 1);
3379 chip->chipsize *= (uint64_t)mtd->erasesize * p->lun_count;
3380 chip->bits_per_cell = p->bits_per_cell;
3382 if (jedec_feature(chip) & JEDEC_FEATURE_16_BIT_BUS)
3383 *busw = NAND_BUSWIDTH_16;
3388 ecc = &p->ecc_info[0];
3390 if (ecc->codeword_size >= 9) {
3391 chip->ecc_strength_ds = ecc->ecc_bits;
3392 chip->ecc_step_ds = 1 << ecc->codeword_size;
3394 pr_warn("Invalid codeword size\n");
3401 * nand_id_has_period - Check if an ID string has a given wraparound period
3402 * @id_data: the ID string
3403 * @arrlen: the length of the @id_data array
3404 * @period: the period of repitition
3406 * Check if an ID string is repeated within a given sequence of bytes at
3407 * specific repetition interval period (e.g., {0x20,0x01,0x7F,0x20} has a
3408 * period of 3). This is a helper function for nand_id_len(). Returns non-zero
3409 * if the repetition has a period of @period; otherwise, returns zero.
3411 static int nand_id_has_period(u8 *id_data, int arrlen, int period)
3414 for (i = 0; i < period; i++)
3415 for (j = i + period; j < arrlen; j += period)
3416 if (id_data[i] != id_data[j])
3422 * nand_id_len - Get the length of an ID string returned by CMD_READID
3423 * @id_data: the ID string
3424 * @arrlen: the length of the @id_data array
3426 * Returns the length of the ID string, according to known wraparound/trailing
3427 * zero patterns. If no pattern exists, returns the length of the array.
3429 static int nand_id_len(u8 *id_data, int arrlen)
3431 int last_nonzero, period;
3433 /* Find last non-zero byte */
3434 for (last_nonzero = arrlen - 1; last_nonzero >= 0; last_nonzero--)
3435 if (id_data[last_nonzero])
3439 if (last_nonzero < 0)
3442 /* Calculate wraparound period */
3443 for (period = 1; period < arrlen; period++)
3444 if (nand_id_has_period(id_data, arrlen, period))
3447 /* There's a repeated pattern */
3448 if (period < arrlen)
3451 /* There are trailing zeros */
3452 if (last_nonzero < arrlen - 1)
3453 return last_nonzero + 1;
3455 /* No pattern detected */
3459 /* Extract the bits of per cell from the 3rd byte of the extended ID */
3460 static int nand_get_bits_per_cell(u8 cellinfo)
3464 bits = cellinfo & NAND_CI_CELLTYPE_MSK;
3465 bits >>= NAND_CI_CELLTYPE_SHIFT;
3470 * Many new NAND share similar device ID codes, which represent the size of the
3471 * chip. The rest of the parameters must be decoded according to generic or
3472 * manufacturer-specific "extended ID" decoding patterns.
3474 static void nand_decode_ext_id(struct mtd_info *mtd, struct nand_chip *chip,
3475 u8 id_data[8], int *busw)
3478 /* The 3rd id byte holds MLC / multichip data */
3479 chip->bits_per_cell = nand_get_bits_per_cell(id_data[2]);
3480 /* The 4th id byte is the important one */
3483 id_len = nand_id_len(id_data, 8);
3486 * Field definitions are in the following datasheets:
3487 * Old style (4,5 byte ID): Samsung K9GAG08U0M (p.32)
3488 * New Samsung (6 byte ID): Samsung K9GAG08U0F (p.44)
3489 * Hynix MLC (6 byte ID): Hynix H27UBG8T2B (p.22)
3491 * Check for ID length, non-zero 6th byte, cell type, and Hynix/Samsung
3492 * ID to decide what to do.
3494 if (id_len == 6 && id_data[0] == NAND_MFR_SAMSUNG &&
3495 !nand_is_slc(chip) && id_data[5] != 0x00) {
3497 mtd->writesize = 2048 << (extid & 0x03);
3500 switch (((extid >> 2) & 0x04) | (extid & 0x03)) {
3520 default: /* Other cases are "reserved" (unknown) */
3521 mtd->oobsize = 1024;
3525 /* Calc blocksize */
3526 mtd->erasesize = (128 * 1024) <<
3527 (((extid >> 1) & 0x04) | (extid & 0x03));
3529 } else if (id_len == 6 && id_data[0] == NAND_MFR_HYNIX &&
3530 !nand_is_slc(chip)) {
3534 mtd->writesize = 2048 << (extid & 0x03);
3537 switch (((extid >> 2) & 0x04) | (extid & 0x03)) {
3561 /* Calc blocksize */
3562 tmp = ((extid >> 1) & 0x04) | (extid & 0x03);
3564 mtd->erasesize = (128 * 1024) << tmp;
3565 else if (tmp == 0x03)
3566 mtd->erasesize = 768 * 1024;
3568 mtd->erasesize = (64 * 1024) << tmp;
3572 mtd->writesize = 1024 << (extid & 0x03);
3575 mtd->oobsize = (8 << (extid & 0x01)) *
3576 (mtd->writesize >> 9);
3578 /* Calc blocksize. Blocksize is multiples of 64KiB */
3579 mtd->erasesize = (64 * 1024) << (extid & 0x03);
3581 /* Get buswidth information */
3582 *busw = (extid & 0x01) ? NAND_BUSWIDTH_16 : 0;
3585 * Toshiba 24nm raw SLC (i.e., not BENAND) have 32B OOB per
3586 * 512B page. For Toshiba SLC, we decode the 5th/6th byte as
3588 * - ID byte 6, bits[2:0]: 100b -> 43nm, 101b -> 32nm,
3590 * - ID byte 5, bit[7]: 1 -> BENAND, 0 -> raw SLC
3592 if (id_len >= 6 && id_data[0] == NAND_MFR_TOSHIBA &&
3593 nand_is_slc(chip) &&
3594 (id_data[5] & 0x7) == 0x6 /* 24nm */ &&
3595 !(id_data[4] & 0x80) /* !BENAND */) {
3596 mtd->oobsize = 32 * mtd->writesize >> 9;
3603 * Old devices have chip data hardcoded in the device ID table. nand_decode_id
3604 * decodes a matching ID table entry and assigns the MTD size parameters for
3607 static void nand_decode_id(struct mtd_info *mtd, struct nand_chip *chip,
3608 struct nand_flash_dev *type, u8 id_data[8],
3611 int maf_id = id_data[0];
3613 mtd->erasesize = type->erasesize;
3614 mtd->writesize = type->pagesize;
3615 mtd->oobsize = mtd->writesize / 32;
3616 *busw = type->options & NAND_BUSWIDTH_16;
3618 /* All legacy ID NAND are small-page, SLC */
3619 chip->bits_per_cell = 1;
3622 * Check for Spansion/AMD ID + repeating 5th, 6th byte since
3623 * some Spansion chips have erasesize that conflicts with size
3624 * listed in nand_ids table.
3625 * Data sheet (5 byte ID): Spansion S30ML-P ORNAND (p.39)
3627 if (maf_id == NAND_MFR_AMD && id_data[4] != 0x00 && id_data[5] == 0x00
3628 && id_data[6] == 0x00 && id_data[7] == 0x00
3629 && mtd->writesize == 512) {
3630 mtd->erasesize = 128 * 1024;
3631 mtd->erasesize <<= ((id_data[3] & 0x03) << 1);
3636 * Set the bad block marker/indicator (BBM/BBI) patterns according to some
3637 * heuristic patterns using various detected parameters (e.g., manufacturer,
3638 * page size, cell-type information).
3640 static void nand_decode_bbm_options(struct mtd_info *mtd,
3641 struct nand_chip *chip, u8 id_data[8])
3643 int maf_id = id_data[0];
3645 /* Set the bad block position */
3646 if (mtd->writesize > 512 || (chip->options & NAND_BUSWIDTH_16))
3647 chip->badblockpos = NAND_LARGE_BADBLOCK_POS;
3649 chip->badblockpos = NAND_SMALL_BADBLOCK_POS;
3652 * Bad block marker is stored in the last page of each block on Samsung
3653 * and Hynix MLC devices; stored in first two pages of each block on
3654 * Micron devices with 2KiB pages and on SLC Samsung, Hynix, Toshiba,
3655 * AMD/Spansion, and Macronix. All others scan only the first page.
3657 if (!nand_is_slc(chip) &&
3658 (maf_id == NAND_MFR_SAMSUNG ||
3659 maf_id == NAND_MFR_HYNIX))
3660 chip->bbt_options |= NAND_BBT_SCANLASTPAGE;
3661 else if ((nand_is_slc(chip) &&
3662 (maf_id == NAND_MFR_SAMSUNG ||
3663 maf_id == NAND_MFR_HYNIX ||
3664 maf_id == NAND_MFR_TOSHIBA ||
3665 maf_id == NAND_MFR_AMD ||
3666 maf_id == NAND_MFR_MACRONIX)) ||
3667 (mtd->writesize == 2048 &&
3668 maf_id == NAND_MFR_MICRON))
3669 chip->bbt_options |= NAND_BBT_SCAN2NDPAGE;
3672 static inline bool is_full_id_nand(struct nand_flash_dev *type)
3674 return type->id_len;
3677 static bool find_full_id_nand(struct mtd_info *mtd, struct nand_chip *chip,
3678 struct nand_flash_dev *type, u8 *id_data, int *busw)
3680 if (!strncmp((char *)type->id, (char *)id_data, type->id_len)) {
3681 mtd->writesize = type->pagesize;
3682 mtd->erasesize = type->erasesize;
3683 mtd->oobsize = type->oobsize;
3685 chip->bits_per_cell = nand_get_bits_per_cell(id_data[2]);
3686 chip->chipsize = (uint64_t)type->chipsize << 20;
3687 chip->options |= type->options;
3688 chip->ecc_strength_ds = NAND_ECC_STRENGTH(type);
3689 chip->ecc_step_ds = NAND_ECC_STEP(type);
3690 chip->onfi_timing_mode_default =
3691 type->onfi_timing_mode_default;
3693 *busw = type->options & NAND_BUSWIDTH_16;
3696 mtd->name = type->name;
3704 * Get the flash and manufacturer id and lookup if the type is supported.
3706 struct nand_flash_dev *nand_get_flash_type(struct mtd_info *mtd,
3707 struct nand_chip *chip,
3708 int *maf_id, int *dev_id,
3709 struct nand_flash_dev *type)
3716 * Reset the chip, required by some chips (e.g. Micron MT29FxGxxxxx)
3719 nand_reset(chip, 0);
3721 /* Select the device */
3722 chip->select_chip(mtd, 0);
3724 /* Send the command for reading device ID */
3725 chip->cmdfunc(mtd, NAND_CMD_READID, 0x00, -1);
3727 /* Read manufacturer and device IDs */
3728 *maf_id = chip->read_byte(mtd);
3729 *dev_id = chip->read_byte(mtd);
3732 * Try again to make sure, as some systems the bus-hold or other
3733 * interface concerns can cause random data which looks like a
3734 * possibly credible NAND flash to appear. If the two results do
3735 * not match, ignore the device completely.
3738 chip->cmdfunc(mtd, NAND_CMD_READID, 0x00, -1);
3740 /* Read entire ID string */
3741 for (i = 0; i < 8; i++)
3742 id_data[i] = chip->read_byte(mtd);
3744 if (id_data[0] != *maf_id || id_data[1] != *dev_id) {
3745 pr_info("second ID read did not match %02x,%02x against %02x,%02x\n",
3746 *maf_id, *dev_id, id_data[0], id_data[1]);
3747 return ERR_PTR(-ENODEV);
3751 type = nand_flash_ids;
3753 for (; type->name != NULL; type++) {
3754 if (is_full_id_nand(type)) {
3755 if (find_full_id_nand(mtd, chip, type, id_data, &busw))
3757 } else if (*dev_id == type->dev_id) {
3762 chip->onfi_version = 0;
3763 if (!type->name || !type->pagesize) {
3764 /* Check if the chip is ONFI compliant */
3765 if (nand_flash_detect_onfi(mtd, chip, &busw))
3768 /* Check if the chip is JEDEC compliant */
3769 if (nand_flash_detect_jedec(mtd, chip, &busw))
3774 return ERR_PTR(-ENODEV);
3777 mtd->name = type->name;
3779 chip->chipsize = (uint64_t)type->chipsize << 20;
3781 if (!type->pagesize) {
3782 /* Decode parameters from extended ID */
3783 nand_decode_ext_id(mtd, chip, id_data, &busw);
3785 nand_decode_id(mtd, chip, type, id_data, &busw);
3787 /* Get chip options */
3788 chip->options |= type->options;
3791 * Check if chip is not a Samsung device. Do not clear the
3792 * options for chips which do not have an extended id.
3794 if (*maf_id != NAND_MFR_SAMSUNG && !type->pagesize)
3795 chip->options &= ~NAND_SAMSUNG_LP_OPTIONS;
3798 /* Try to identify manufacturer */
3799 for (maf_idx = 0; nand_manuf_ids[maf_idx].id != 0x0; maf_idx++) {
3800 if (nand_manuf_ids[maf_idx].id == *maf_id)
3804 if (chip->options & NAND_BUSWIDTH_AUTO) {
3805 WARN_ON(chip->options & NAND_BUSWIDTH_16);
3806 chip->options |= busw;
3807 nand_set_defaults(chip, busw);
3808 } else if (busw != (chip->options & NAND_BUSWIDTH_16)) {
3810 * Check, if buswidth is correct. Hardware drivers should set
3813 pr_info("device found, Manufacturer ID: 0x%02x, Chip ID: 0x%02x\n",
3815 pr_info("%s %s\n", nand_manuf_ids[maf_idx].name, mtd->name);
3816 pr_warn("bus width %d instead %d bit\n",
3817 (chip->options & NAND_BUSWIDTH_16) ? 16 : 8,
3819 return ERR_PTR(-EINVAL);
3822 nand_decode_bbm_options(mtd, chip, id_data);
3824 /* Calculate the address shift from the page size */
3825 chip->page_shift = ffs(mtd->writesize) - 1;
3826 /* Convert chipsize to number of pages per chip -1 */
3827 chip->pagemask = (chip->chipsize >> chip->page_shift) - 1;
3829 chip->bbt_erase_shift = chip->phys_erase_shift =
3830 ffs(mtd->erasesize) - 1;
3831 if (chip->chipsize & 0xffffffff)
3832 chip->chip_shift = ffs((unsigned)chip->chipsize) - 1;
3834 chip->chip_shift = ffs((unsigned)(chip->chipsize >> 32));
3835 chip->chip_shift += 32 - 1;
3838 if (chip->chip_shift - chip->page_shift > 16)
3839 chip->options |= NAND_ROW_ADDR_3;
3841 chip->badblockbits = 8;
3842 chip->erase = single_erase;
3844 /* Do not replace user supplied command function! */
3845 if (mtd->writesize > 512 && chip->cmdfunc == nand_command)
3846 chip->cmdfunc = nand_command_lp;
3848 pr_info("device found, Manufacturer ID: 0x%02x, Chip ID: 0x%02x\n",
3851 #ifdef CONFIG_SYS_NAND_ONFI_DETECTION
3852 if (chip->onfi_version)
3853 pr_info("%s %s\n", nand_manuf_ids[maf_idx].name,
3854 chip->onfi_params.model);
3855 else if (chip->jedec_version)
3856 pr_info("%s %s\n", nand_manuf_ids[maf_idx].name,
3857 chip->jedec_params.model);
3859 pr_info("%s %s\n", nand_manuf_ids[maf_idx].name,
3862 if (chip->jedec_version)
3863 pr_info("%s %s\n", nand_manuf_ids[maf_idx].name,
3864 chip->jedec_params.model);
3866 pr_info("%s %s\n", nand_manuf_ids[maf_idx].name,
3869 pr_info("%s %s\n", nand_manuf_ids[maf_idx].name,
3873 pr_info("%d MiB, %s, erase size: %d KiB, page size: %d, OOB size: %d\n",
3874 (int)(chip->chipsize >> 20), nand_is_slc(chip) ? "SLC" : "MLC",
3875 mtd->erasesize >> 10, mtd->writesize, mtd->oobsize);
3878 EXPORT_SYMBOL(nand_get_flash_type);
3880 #if CONFIG_IS_ENABLED(OF_CONTROL)
3881 DECLARE_GLOBAL_DATA_PTR;
3883 static int nand_dt_init(struct mtd_info *mtd, struct nand_chip *chip, int node)
3885 int ret, ecc_mode = -1, ecc_strength, ecc_step;
3886 const void *blob = gd->fdt_blob;
3889 ret = fdtdec_get_int(blob, node, "nand-bus-width", -1);
3891 chip->options |= NAND_BUSWIDTH_16;
3893 if (fdtdec_get_bool(blob, node, "nand-on-flash-bbt"))
3894 chip->bbt_options |= NAND_BBT_USE_FLASH;
3896 str = fdt_getprop(blob, node, "nand-ecc-mode", NULL);
3898 if (!strcmp(str, "none"))
3899 ecc_mode = NAND_ECC_NONE;
3900 else if (!strcmp(str, "soft"))
3901 ecc_mode = NAND_ECC_SOFT;
3902 else if (!strcmp(str, "hw"))
3903 ecc_mode = NAND_ECC_HW;
3904 else if (!strcmp(str, "hw_syndrome"))
3905 ecc_mode = NAND_ECC_HW_SYNDROME;
3906 else if (!strcmp(str, "hw_oob_first"))
3907 ecc_mode = NAND_ECC_HW_OOB_FIRST;
3908 else if (!strcmp(str, "soft_bch"))
3909 ecc_mode = NAND_ECC_SOFT_BCH;
3913 ecc_strength = fdtdec_get_int(blob, node, "nand-ecc-strength", -1);
3914 ecc_step = fdtdec_get_int(blob, node, "nand-ecc-step-size", -1);
3916 if ((ecc_step >= 0 && !(ecc_strength >= 0)) ||
3917 (!(ecc_step >= 0) && ecc_strength >= 0)) {
3918 pr_err("must set both strength and step size in DT\n");
3923 chip->ecc.mode = ecc_mode;
3925 if (ecc_strength >= 0)
3926 chip->ecc.strength = ecc_strength;
3929 chip->ecc.size = ecc_step;
3931 if (fdt_getprop(blob, node, "nand-ecc-maximize", NULL))
3932 chip->ecc.options |= NAND_ECC_MAXIMIZE;
3937 static int nand_dt_init(struct mtd_info *mtd, struct nand_chip *chip, int node)
3941 #endif /* CONFIG_IS_ENABLED(OF_CONTROL) */
3944 * nand_scan_ident - [NAND Interface] Scan for the NAND device
3945 * @mtd: MTD device structure
3946 * @maxchips: number of chips to scan for
3947 * @table: alternative NAND ID table
3949 * This is the first phase of the normal nand_scan() function. It reads the
3950 * flash ID and sets up MTD fields accordingly.
3953 int nand_scan_ident(struct mtd_info *mtd, int maxchips,
3954 struct nand_flash_dev *table)
3956 int i, nand_maf_id, nand_dev_id;
3957 struct nand_chip *chip = mtd_to_nand(mtd);
3958 struct nand_flash_dev *type;
3961 if (chip->flash_node) {
3962 ret = nand_dt_init(mtd, chip, chip->flash_node);
3967 /* Set the default functions */
3968 nand_set_defaults(chip, chip->options & NAND_BUSWIDTH_16);
3970 /* Read the flash type */
3971 type = nand_get_flash_type(mtd, chip, &nand_maf_id,
3972 &nand_dev_id, table);
3975 if (!(chip->options & NAND_SCAN_SILENT_NODEV))
3976 pr_warn("No NAND device found\n");
3977 chip->select_chip(mtd, -1);
3978 return PTR_ERR(type);
3981 /* Initialize the ->data_interface field. */
3982 ret = nand_init_data_interface(chip);
3987 * Setup the data interface correctly on the chip and controller side.
3988 * This explicit call to nand_setup_data_interface() is only required
3989 * for the first die, because nand_reset() has been called before
3990 * ->data_interface and ->default_onfi_timing_mode were set.
3991 * For the other dies, nand_reset() will automatically switch to the
3994 ret = nand_setup_data_interface(chip, 0);
3998 chip->select_chip(mtd, -1);
4000 /* Check for a chip array */
4001 for (i = 1; i < maxchips; i++) {
4002 /* See comment in nand_get_flash_type for reset */
4003 nand_reset(chip, i);
4005 chip->select_chip(mtd, i);
4006 /* Send the command for reading device ID */
4007 chip->cmdfunc(mtd, NAND_CMD_READID, 0x00, -1);
4008 /* Read manufacturer and device IDs */
4009 if (nand_maf_id != chip->read_byte(mtd) ||
4010 nand_dev_id != chip->read_byte(mtd)) {
4011 chip->select_chip(mtd, -1);
4014 chip->select_chip(mtd, -1);
4019 pr_info("%d chips detected\n", i);
4022 /* Store the number of chips and calc total size for mtd */
4024 mtd->size = i * chip->chipsize;
4028 EXPORT_SYMBOL(nand_scan_ident);
4031 * nand_check_ecc_caps - check the sanity of preset ECC settings
4032 * @chip: nand chip info structure
4033 * @caps: ECC caps info structure
4034 * @oobavail: OOB size that the ECC engine can use
4036 * When ECC step size and strength are already set, check if they are supported
4037 * by the controller and the calculated ECC bytes fit within the chip's OOB.
4038 * On success, the calculated ECC bytes is set.
4040 int nand_check_ecc_caps(struct nand_chip *chip,
4041 const struct nand_ecc_caps *caps, int oobavail)
4043 struct mtd_info *mtd = nand_to_mtd(chip);
4044 const struct nand_ecc_step_info *stepinfo;
4045 int preset_step = chip->ecc.size;
4046 int preset_strength = chip->ecc.strength;
4047 int nsteps, ecc_bytes;
4050 if (WARN_ON(oobavail < 0))
4053 if (!preset_step || !preset_strength)
4056 nsteps = mtd->writesize / preset_step;
4058 for (i = 0; i < caps->nstepinfos; i++) {
4059 stepinfo = &caps->stepinfos[i];
4061 if (stepinfo->stepsize != preset_step)
4064 for (j = 0; j < stepinfo->nstrengths; j++) {
4065 if (stepinfo->strengths[j] != preset_strength)
4068 ecc_bytes = caps->calc_ecc_bytes(preset_step,
4070 if (WARN_ON_ONCE(ecc_bytes < 0))
4073 if (ecc_bytes * nsteps > oobavail) {
4074 pr_err("ECC (step, strength) = (%d, %d) does not fit in OOB",
4075 preset_step, preset_strength);
4079 chip->ecc.bytes = ecc_bytes;
4085 pr_err("ECC (step, strength) = (%d, %d) not supported on this controller",
4086 preset_step, preset_strength);
4090 EXPORT_SYMBOL_GPL(nand_check_ecc_caps);
4093 * nand_match_ecc_req - meet the chip's requirement with least ECC bytes
4094 * @chip: nand chip info structure
4095 * @caps: ECC engine caps info structure
4096 * @oobavail: OOB size that the ECC engine can use
4098 * If a chip's ECC requirement is provided, try to meet it with the least
4099 * number of ECC bytes (i.e. with the largest number of OOB-free bytes).
4100 * On success, the chosen ECC settings are set.
4102 int nand_match_ecc_req(struct nand_chip *chip,
4103 const struct nand_ecc_caps *caps, int oobavail)
4105 struct mtd_info *mtd = nand_to_mtd(chip);
4106 const struct nand_ecc_step_info *stepinfo;
4107 int req_step = chip->ecc_step_ds;
4108 int req_strength = chip->ecc_strength_ds;
4109 int req_corr, step_size, strength, nsteps, ecc_bytes, ecc_bytes_total;
4110 int best_step, best_strength, best_ecc_bytes;
4111 int best_ecc_bytes_total = INT_MAX;
4114 if (WARN_ON(oobavail < 0))
4117 /* No information provided by the NAND chip */
4118 if (!req_step || !req_strength)
4121 /* number of correctable bits the chip requires in a page */
4122 req_corr = mtd->writesize / req_step * req_strength;
4124 for (i = 0; i < caps->nstepinfos; i++) {
4125 stepinfo = &caps->stepinfos[i];
4126 step_size = stepinfo->stepsize;
4128 for (j = 0; j < stepinfo->nstrengths; j++) {
4129 strength = stepinfo->strengths[j];
4132 * If both step size and strength are smaller than the
4133 * chip's requirement, it is not easy to compare the
4134 * resulted reliability.
4136 if (step_size < req_step && strength < req_strength)
4139 if (mtd->writesize % step_size)
4142 nsteps = mtd->writesize / step_size;
4144 ecc_bytes = caps->calc_ecc_bytes(step_size, strength);
4145 if (WARN_ON_ONCE(ecc_bytes < 0))
4147 ecc_bytes_total = ecc_bytes * nsteps;
4149 if (ecc_bytes_total > oobavail ||
4150 strength * nsteps < req_corr)
4154 * We assume the best is to meet the chip's requrement
4155 * with the least number of ECC bytes.
4157 if (ecc_bytes_total < best_ecc_bytes_total) {
4158 best_ecc_bytes_total = ecc_bytes_total;
4159 best_step = step_size;
4160 best_strength = strength;
4161 best_ecc_bytes = ecc_bytes;
4166 if (best_ecc_bytes_total == INT_MAX)
4169 chip->ecc.size = best_step;
4170 chip->ecc.strength = best_strength;
4171 chip->ecc.bytes = best_ecc_bytes;
4175 EXPORT_SYMBOL_GPL(nand_match_ecc_req);
4178 * nand_maximize_ecc - choose the max ECC strength available
4179 * @chip: nand chip info structure
4180 * @caps: ECC engine caps info structure
4181 * @oobavail: OOB size that the ECC engine can use
4183 * Choose the max ECC strength that is supported on the controller, and can fit
4184 * within the chip's OOB. On success, the chosen ECC settings are set.
4186 int nand_maximize_ecc(struct nand_chip *chip,
4187 const struct nand_ecc_caps *caps, int oobavail)
4189 struct mtd_info *mtd = nand_to_mtd(chip);
4190 const struct nand_ecc_step_info *stepinfo;
4191 int step_size, strength, nsteps, ecc_bytes, corr;
4194 int best_strength, best_ecc_bytes;
4197 if (WARN_ON(oobavail < 0))
4200 for (i = 0; i < caps->nstepinfos; i++) {
4201 stepinfo = &caps->stepinfos[i];
4202 step_size = stepinfo->stepsize;
4204 /* If chip->ecc.size is already set, respect it */
4205 if (chip->ecc.size && step_size != chip->ecc.size)
4208 for (j = 0; j < stepinfo->nstrengths; j++) {
4209 strength = stepinfo->strengths[j];
4211 if (mtd->writesize % step_size)
4214 nsteps = mtd->writesize / step_size;
4216 ecc_bytes = caps->calc_ecc_bytes(step_size, strength);
4217 if (WARN_ON_ONCE(ecc_bytes < 0))
4220 if (ecc_bytes * nsteps > oobavail)
4223 corr = strength * nsteps;
4226 * If the number of correctable bits is the same,
4227 * bigger step_size has more reliability.
4229 if (corr > best_corr ||
4230 (corr == best_corr && step_size > best_step)) {
4232 best_step = step_size;
4233 best_strength = strength;
4234 best_ecc_bytes = ecc_bytes;
4242 chip->ecc.size = best_step;
4243 chip->ecc.strength = best_strength;
4244 chip->ecc.bytes = best_ecc_bytes;
4248 EXPORT_SYMBOL_GPL(nand_maximize_ecc);
4251 * Check if the chip configuration meet the datasheet requirements.
4253 * If our configuration corrects A bits per B bytes and the minimum
4254 * required correction level is X bits per Y bytes, then we must ensure
4255 * both of the following are true:
4257 * (1) A / B >= X / Y
4260 * Requirement (1) ensures we can correct for the required bitflip density.
4261 * Requirement (2) ensures we can correct even when all bitflips are clumped
4262 * in the same sector.
4264 static bool nand_ecc_strength_good(struct mtd_info *mtd)
4266 struct nand_chip *chip = mtd_to_nand(mtd);
4267 struct nand_ecc_ctrl *ecc = &chip->ecc;
4270 if (ecc->size == 0 || chip->ecc_step_ds == 0)
4271 /* Not enough information */
4275 * We get the number of corrected bits per page to compare
4276 * the correction density.
4278 corr = (mtd->writesize * ecc->strength) / ecc->size;
4279 ds_corr = (mtd->writesize * chip->ecc_strength_ds) / chip->ecc_step_ds;
4281 return corr >= ds_corr && ecc->strength >= chip->ecc_strength_ds;
4284 static bool invalid_ecc_page_accessors(struct nand_chip *chip)
4286 struct nand_ecc_ctrl *ecc = &chip->ecc;
4288 if (nand_standard_page_accessors(ecc))
4292 * NAND_ECC_CUSTOM_PAGE_ACCESS flag is set, make sure the NAND
4293 * controller driver implements all the page accessors because
4294 * default helpers are not suitable when the core does not
4295 * send the READ0/PAGEPROG commands.
4297 return (!ecc->read_page || !ecc->write_page ||
4298 !ecc->read_page_raw || !ecc->write_page_raw ||
4299 (NAND_HAS_SUBPAGE_READ(chip) && !ecc->read_subpage) ||
4300 (NAND_HAS_SUBPAGE_WRITE(chip) && !ecc->write_subpage &&
4301 ecc->hwctl && ecc->calculate));
4305 * nand_scan_tail - [NAND Interface] Scan for the NAND device
4306 * @mtd: MTD device structure
4308 * This is the second phase of the normal nand_scan() function. It fills out
4309 * all the uninitialized function pointers with the defaults and scans for a
4310 * bad block table if appropriate.
4312 int nand_scan_tail(struct mtd_info *mtd)
4315 struct nand_chip *chip = mtd_to_nand(mtd);
4316 struct nand_ecc_ctrl *ecc = &chip->ecc;
4317 struct nand_buffers *nbuf;
4319 /* New bad blocks should be marked in OOB, flash-based BBT, or both */
4320 BUG_ON((chip->bbt_options & NAND_BBT_NO_OOB_BBM) &&
4321 !(chip->bbt_options & NAND_BBT_USE_FLASH));
4323 if (invalid_ecc_page_accessors(chip)) {
4324 pr_err("Invalid ECC page accessors setup\n");
4328 if (!(chip->options & NAND_OWN_BUFFERS)) {
4329 nbuf = kzalloc(sizeof(struct nand_buffers), GFP_KERNEL);
4330 chip->buffers = nbuf;
4336 /* Set the internal oob buffer location, just after the page data */
4337 chip->oob_poi = chip->buffers->databuf + mtd->writesize;
4340 * If no default placement scheme is given, select an appropriate one.
4342 if (!ecc->layout && (ecc->mode != NAND_ECC_SOFT_BCH)) {
4343 switch (mtd->oobsize) {
4344 #ifdef CONFIG_SYS_NAND_DRIVER_ECC_LAYOUT
4346 ecc->layout = &nand_oob_8;
4349 ecc->layout = &nand_oob_16;
4352 ecc->layout = &nand_oob_64;
4355 ecc->layout = &nand_oob_128;
4359 pr_warn("No oob scheme defined for oobsize %d\n",
4365 if (!chip->write_page)
4366 chip->write_page = nand_write_page;
4369 * Check ECC mode, default to software if 3byte/512byte hardware ECC is
4370 * selected and we have 256 byte pagesize fallback to software ECC
4373 switch (ecc->mode) {
4374 case NAND_ECC_HW_OOB_FIRST:
4375 /* Similar to NAND_ECC_HW, but a separate read_page handle */
4376 if (!ecc->calculate || !ecc->correct || !ecc->hwctl) {
4377 pr_warn("No ECC functions supplied; hardware ECC not possible\n");
4380 if (!ecc->read_page)
4381 ecc->read_page = nand_read_page_hwecc_oob_first;
4384 /* Use standard hwecc read page function? */
4385 if (!ecc->read_page)
4386 ecc->read_page = nand_read_page_hwecc;
4387 if (!ecc->write_page)
4388 ecc->write_page = nand_write_page_hwecc;
4389 if (!ecc->read_page_raw)
4390 ecc->read_page_raw = nand_read_page_raw;
4391 if (!ecc->write_page_raw)
4392 ecc->write_page_raw = nand_write_page_raw;
4394 ecc->read_oob = nand_read_oob_std;
4395 if (!ecc->write_oob)
4396 ecc->write_oob = nand_write_oob_std;
4397 if (!ecc->read_subpage)
4398 ecc->read_subpage = nand_read_subpage;
4399 if (!ecc->write_subpage && ecc->hwctl && ecc->calculate)
4400 ecc->write_subpage = nand_write_subpage_hwecc;
4402 case NAND_ECC_HW_SYNDROME:
4403 if ((!ecc->calculate || !ecc->correct || !ecc->hwctl) &&
4405 ecc->read_page == nand_read_page_hwecc ||
4407 ecc->write_page == nand_write_page_hwecc)) {
4408 pr_warn("No ECC functions supplied; hardware ECC not possible\n");
4411 /* Use standard syndrome read/write page function? */
4412 if (!ecc->read_page)
4413 ecc->read_page = nand_read_page_syndrome;
4414 if (!ecc->write_page)
4415 ecc->write_page = nand_write_page_syndrome;
4416 if (!ecc->read_page_raw)
4417 ecc->read_page_raw = nand_read_page_raw_syndrome;
4418 if (!ecc->write_page_raw)
4419 ecc->write_page_raw = nand_write_page_raw_syndrome;
4421 ecc->read_oob = nand_read_oob_syndrome;
4422 if (!ecc->write_oob)
4423 ecc->write_oob = nand_write_oob_syndrome;
4425 if (mtd->writesize >= ecc->size) {
4426 if (!ecc->strength) {
4427 pr_warn("Driver must set ecc.strength when using hardware ECC\n");
4432 pr_warn("%d byte HW ECC not possible on %d byte page size, fallback to SW ECC\n",
4433 ecc->size, mtd->writesize);
4434 ecc->mode = NAND_ECC_SOFT;
4437 ecc->calculate = nand_calculate_ecc;
4438 ecc->correct = nand_correct_data;
4439 ecc->read_page = nand_read_page_swecc;
4440 ecc->read_subpage = nand_read_subpage;
4441 ecc->write_page = nand_write_page_swecc;
4442 ecc->read_page_raw = nand_read_page_raw;
4443 ecc->write_page_raw = nand_write_page_raw;
4444 ecc->read_oob = nand_read_oob_std;
4445 ecc->write_oob = nand_write_oob_std;
4452 case NAND_ECC_SOFT_BCH:
4453 if (!mtd_nand_has_bch()) {
4454 pr_warn("CONFIG_MTD_NAND_ECC_BCH not enabled\n");
4457 ecc->calculate = nand_bch_calculate_ecc;
4458 ecc->correct = nand_bch_correct_data;
4459 ecc->read_page = nand_read_page_swecc;
4460 ecc->read_subpage = nand_read_subpage;
4461 ecc->write_page = nand_write_page_swecc;
4462 ecc->read_page_raw = nand_read_page_raw;
4463 ecc->write_page_raw = nand_write_page_raw;
4464 ecc->read_oob = nand_read_oob_std;
4465 ecc->write_oob = nand_write_oob_std;
4467 * Board driver should supply ecc.size and ecc.strength values
4468 * to select how many bits are correctable. Otherwise, default
4469 * to 4 bits for large page devices.
4471 if (!ecc->size && (mtd->oobsize >= 64)) {
4476 /* See nand_bch_init() for details. */
4478 ecc->priv = nand_bch_init(mtd);
4480 pr_warn("BCH ECC initialization failed!\n");
4486 pr_warn("NAND_ECC_NONE selected by board driver. This is not recommended!\n");
4487 ecc->read_page = nand_read_page_raw;
4488 ecc->write_page = nand_write_page_raw;
4489 ecc->read_oob = nand_read_oob_std;
4490 ecc->read_page_raw = nand_read_page_raw;
4491 ecc->write_page_raw = nand_write_page_raw;
4492 ecc->write_oob = nand_write_oob_std;
4493 ecc->size = mtd->writesize;
4499 pr_warn("Invalid NAND_ECC_MODE %d\n", ecc->mode);
4503 /* For many systems, the standard OOB write also works for raw */
4504 if (!ecc->read_oob_raw)
4505 ecc->read_oob_raw = ecc->read_oob;
4506 if (!ecc->write_oob_raw)
4507 ecc->write_oob_raw = ecc->write_oob;
4510 * The number of bytes available for a client to place data into
4511 * the out of band area.
4515 for (i = 0; ecc->layout->oobfree[i].length; i++)
4516 mtd->oobavail += ecc->layout->oobfree[i].length;
4519 /* ECC sanity check: warn if it's too weak */
4520 if (!nand_ecc_strength_good(mtd))
4521 pr_warn("WARNING: %s: the ECC used on your system is too weak compared to the one required by the NAND chip\n",
4525 * Set the number of read / write steps for one page depending on ECC
4528 ecc->steps = mtd->writesize / ecc->size;
4529 if (ecc->steps * ecc->size != mtd->writesize) {
4530 pr_warn("Invalid ECC parameters\n");
4533 ecc->total = ecc->steps * ecc->bytes;
4535 /* Allow subpage writes up to ecc.steps. Not possible for MLC flash */
4536 if (!(chip->options & NAND_NO_SUBPAGE_WRITE) && nand_is_slc(chip)) {
4537 switch (ecc->steps) {
4539 mtd->subpage_sft = 1;
4544 mtd->subpage_sft = 2;
4548 chip->subpagesize = mtd->writesize >> mtd->subpage_sft;
4550 /* Initialize state */
4551 chip->state = FL_READY;
4553 /* Invalidate the pagebuffer reference */
4556 /* Large page NAND with SOFT_ECC should support subpage reads */
4557 switch (ecc->mode) {
4559 case NAND_ECC_SOFT_BCH:
4560 if (chip->page_shift > 9)
4561 chip->options |= NAND_SUBPAGE_READ;
4568 /* Fill in remaining MTD driver data */
4569 mtd->type = nand_is_slc(chip) ? MTD_NANDFLASH : MTD_MLCNANDFLASH;
4570 mtd->flags = (chip->options & NAND_ROM) ? MTD_CAP_ROM :
4572 mtd->_erase = nand_erase;
4573 mtd->_panic_write = panic_nand_write;
4574 mtd->_read_oob = nand_read_oob;
4575 mtd->_write_oob = nand_write_oob;
4576 mtd->_sync = nand_sync;
4578 mtd->_unlock = NULL;
4579 mtd->_block_isreserved = nand_block_isreserved;
4580 mtd->_block_isbad = nand_block_isbad;
4581 mtd->_block_markbad = nand_block_markbad;
4582 mtd->writebufsize = mtd->writesize;
4584 /* propagate ecc info to mtd_info */
4585 mtd->ecclayout = ecc->layout;
4586 mtd->ecc_strength = ecc->strength;
4587 mtd->ecc_step_size = ecc->size;
4589 * Initialize bitflip_threshold to its default prior scan_bbt() call.
4590 * scan_bbt() might invoke mtd_read(), thus bitflip_threshold must be
4593 if (!mtd->bitflip_threshold)
4594 mtd->bitflip_threshold = DIV_ROUND_UP(mtd->ecc_strength * 3, 4);
4598 EXPORT_SYMBOL(nand_scan_tail);
4601 * nand_scan - [NAND Interface] Scan for the NAND device
4602 * @mtd: MTD device structure
4603 * @maxchips: number of chips to scan for
4605 * This fills out all the uninitialized function pointers with the defaults.
4606 * The flash ID is read and the mtd/chip structures are filled with the
4607 * appropriate values.
4609 int nand_scan(struct mtd_info *mtd, int maxchips)
4613 ret = nand_scan_ident(mtd, maxchips, NULL);
4615 ret = nand_scan_tail(mtd);
4618 EXPORT_SYMBOL(nand_scan);
4620 MODULE_LICENSE("GPL");
4621 MODULE_AUTHOR("Steven J. Hill <sjhill@realitydiluted.com>");
4622 MODULE_AUTHOR("Thomas Gleixner <tglx@linutronix.de>");
4623 MODULE_DESCRIPTION("Generic NAND flash driver code");