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 #include <linux/module.h>
33 #include <linux/delay.h>
34 #include <linux/errno.h>
35 #include <linux/err.h>
36 #include <linux/sched.h>
37 #include <linux/slab.h>
39 #include <linux/types.h>
40 #include <linux/mtd/mtd.h>
41 #include <linux/mtd/nand.h>
42 #include <linux/mtd/nand_ecc.h>
43 #include <linux/mtd/nand_bch.h>
44 #include <linux/interrupt.h>
45 #include <linux/bitops.h>
47 #include <linux/mtd/partitions.h>
50 static int nand_get_device(struct mtd_info *mtd, int new_state);
52 static int nand_do_write_oob(struct mtd_info *mtd, loff_t to,
53 struct mtd_oob_ops *ops);
55 /* Define default oob placement schemes for large and small page devices */
56 static int nand_ooblayout_ecc_sp(struct mtd_info *mtd, int section,
57 struct mtd_oob_region *oobregion)
59 struct nand_chip *chip = mtd_to_nand(mtd);
60 struct nand_ecc_ctrl *ecc = &chip->ecc;
66 oobregion->offset = 0;
67 oobregion->length = 4;
69 oobregion->offset = 6;
70 oobregion->length = ecc->total - 4;
76 static int nand_ooblayout_free_sp(struct mtd_info *mtd, int section,
77 struct mtd_oob_region *oobregion)
82 if (mtd->oobsize == 16) {
86 oobregion->length = 8;
87 oobregion->offset = 8;
89 oobregion->length = 2;
91 oobregion->offset = 3;
93 oobregion->offset = 6;
99 const struct mtd_ooblayout_ops nand_ooblayout_sp_ops = {
100 .ecc = nand_ooblayout_ecc_sp,
101 .free = nand_ooblayout_free_sp,
103 EXPORT_SYMBOL_GPL(nand_ooblayout_sp_ops);
105 static int nand_ooblayout_ecc_lp(struct mtd_info *mtd, int section,
106 struct mtd_oob_region *oobregion)
108 struct nand_chip *chip = mtd_to_nand(mtd);
109 struct nand_ecc_ctrl *ecc = &chip->ecc;
114 oobregion->length = ecc->total;
115 oobregion->offset = mtd->oobsize - oobregion->length;
120 static int nand_ooblayout_free_lp(struct mtd_info *mtd, int section,
121 struct mtd_oob_region *oobregion)
123 struct nand_chip *chip = mtd_to_nand(mtd);
124 struct nand_ecc_ctrl *ecc = &chip->ecc;
129 oobregion->length = mtd->oobsize - ecc->total - 2;
130 oobregion->offset = 2;
135 const struct mtd_ooblayout_ops nand_ooblayout_lp_ops = {
136 .ecc = nand_ooblayout_ecc_lp,
137 .free = nand_ooblayout_free_lp,
139 EXPORT_SYMBOL_GPL(nand_ooblayout_lp_ops);
141 static int check_offs_len(struct mtd_info *mtd,
142 loff_t ofs, uint64_t len)
144 struct nand_chip *chip = mtd_to_nand(mtd);
147 /* Start address must align on block boundary */
148 if (ofs & ((1ULL << chip->phys_erase_shift) - 1)) {
149 pr_debug("%s: unaligned address\n", __func__);
153 /* Length must align on block boundary */
154 if (len & ((1ULL << chip->phys_erase_shift) - 1)) {
155 pr_debug("%s: length not block aligned\n", __func__);
163 * nand_release_device - [GENERIC] release chip
164 * @mtd: MTD device structure
166 * Release chip lock and wake up anyone waiting on the device.
168 static void nand_release_device(struct mtd_info *mtd)
170 struct nand_chip *chip = mtd_to_nand(mtd);
172 /* Release the controller and the chip */
173 spin_lock(&chip->controller->lock);
174 chip->controller->active = NULL;
175 chip->state = FL_READY;
176 wake_up(&chip->controller->wq);
177 spin_unlock(&chip->controller->lock);
181 * nand_read_byte - [DEFAULT] read one byte from the chip
182 * @mtd: MTD device structure
184 * Default read function for 8bit buswidth
186 static uint8_t nand_read_byte(struct mtd_info *mtd)
188 struct nand_chip *chip = mtd_to_nand(mtd);
189 return readb(chip->IO_ADDR_R);
193 * nand_read_byte16 - [DEFAULT] read one byte endianness aware from the chip
194 * @mtd: MTD device structure
196 * Default read function for 16bit buswidth with endianness conversion.
199 static uint8_t nand_read_byte16(struct mtd_info *mtd)
201 struct nand_chip *chip = mtd_to_nand(mtd);
202 return (uint8_t) cpu_to_le16(readw(chip->IO_ADDR_R));
206 * nand_read_word - [DEFAULT] read one word from the chip
207 * @mtd: MTD device structure
209 * Default read function for 16bit buswidth without endianness conversion.
211 static u16 nand_read_word(struct mtd_info *mtd)
213 struct nand_chip *chip = mtd_to_nand(mtd);
214 return readw(chip->IO_ADDR_R);
218 * nand_select_chip - [DEFAULT] control CE line
219 * @mtd: MTD device structure
220 * @chipnr: chipnumber to select, -1 for deselect
222 * Default select function for 1 chip devices.
224 static void nand_select_chip(struct mtd_info *mtd, int chipnr)
226 struct nand_chip *chip = mtd_to_nand(mtd);
230 chip->cmd_ctrl(mtd, NAND_CMD_NONE, 0 | NAND_CTRL_CHANGE);
241 * nand_write_byte - [DEFAULT] write single byte to chip
242 * @mtd: MTD device structure
243 * @byte: value to write
245 * Default function to write a byte to I/O[7:0]
247 static void nand_write_byte(struct mtd_info *mtd, uint8_t byte)
249 struct nand_chip *chip = mtd_to_nand(mtd);
251 chip->write_buf(mtd, &byte, 1);
255 * nand_write_byte16 - [DEFAULT] write single byte to a chip with width 16
256 * @mtd: MTD device structure
257 * @byte: value to write
259 * Default function to write a byte to I/O[7:0] on a 16-bit wide chip.
261 static void nand_write_byte16(struct mtd_info *mtd, uint8_t byte)
263 struct nand_chip *chip = mtd_to_nand(mtd);
264 uint16_t word = byte;
267 * It's not entirely clear what should happen to I/O[15:8] when writing
268 * a byte. The ONFi spec (Revision 3.1; 2012-09-19, Section 2.16) reads:
270 * When the host supports a 16-bit bus width, only data is
271 * transferred at the 16-bit width. All address and command line
272 * transfers shall use only the lower 8-bits of the data bus. During
273 * command transfers, the host may place any value on the upper
274 * 8-bits of the data bus. During address transfers, the host shall
275 * set the upper 8-bits of the data bus to 00h.
277 * One user of the write_byte callback is nand_onfi_set_features. The
278 * four parameters are specified to be written to I/O[7:0], but this is
279 * neither an address nor a command transfer. Let's assume a 0 on the
280 * upper I/O lines is OK.
282 chip->write_buf(mtd, (uint8_t *)&word, 2);
286 * nand_write_buf - [DEFAULT] write buffer to chip
287 * @mtd: MTD device structure
289 * @len: number of bytes to write
291 * Default write function for 8bit buswidth.
293 static void nand_write_buf(struct mtd_info *mtd, const uint8_t *buf, int len)
295 struct nand_chip *chip = mtd_to_nand(mtd);
297 iowrite8_rep(chip->IO_ADDR_W, buf, len);
301 * nand_read_buf - [DEFAULT] read chip data into buffer
302 * @mtd: MTD device structure
303 * @buf: buffer to store date
304 * @len: number of bytes to read
306 * Default read function for 8bit buswidth.
308 static void nand_read_buf(struct mtd_info *mtd, uint8_t *buf, int len)
310 struct nand_chip *chip = mtd_to_nand(mtd);
312 ioread8_rep(chip->IO_ADDR_R, buf, len);
316 * nand_write_buf16 - [DEFAULT] write buffer to chip
317 * @mtd: MTD device structure
319 * @len: number of bytes to write
321 * Default write function for 16bit buswidth.
323 static void nand_write_buf16(struct mtd_info *mtd, const uint8_t *buf, int len)
325 struct nand_chip *chip = mtd_to_nand(mtd);
326 u16 *p = (u16 *) buf;
328 iowrite16_rep(chip->IO_ADDR_W, p, len >> 1);
332 * nand_read_buf16 - [DEFAULT] read chip data into buffer
333 * @mtd: MTD device structure
334 * @buf: buffer to store date
335 * @len: number of bytes to read
337 * Default read function for 16bit buswidth.
339 static void nand_read_buf16(struct mtd_info *mtd, uint8_t *buf, int len)
341 struct nand_chip *chip = mtd_to_nand(mtd);
342 u16 *p = (u16 *) buf;
344 ioread16_rep(chip->IO_ADDR_R, p, len >> 1);
348 * nand_block_bad - [DEFAULT] Read bad block marker from the chip
349 * @mtd: MTD device structure
350 * @ofs: offset from device start
352 * Check, if the block is bad.
354 static int nand_block_bad(struct mtd_info *mtd, loff_t ofs)
356 int page, res = 0, i = 0;
357 struct nand_chip *chip = mtd_to_nand(mtd);
360 if (chip->bbt_options & NAND_BBT_SCANLASTPAGE)
361 ofs += mtd->erasesize - mtd->writesize;
363 page = (int)(ofs >> chip->page_shift) & chip->pagemask;
366 if (chip->options & NAND_BUSWIDTH_16) {
367 chip->cmdfunc(mtd, NAND_CMD_READOOB,
368 chip->badblockpos & 0xFE, page);
369 bad = cpu_to_le16(chip->read_word(mtd));
370 if (chip->badblockpos & 0x1)
375 chip->cmdfunc(mtd, NAND_CMD_READOOB, chip->badblockpos,
377 bad = chip->read_byte(mtd);
380 if (likely(chip->badblockbits == 8))
383 res = hweight8(bad) < chip->badblockbits;
384 ofs += mtd->writesize;
385 page = (int)(ofs >> chip->page_shift) & chip->pagemask;
387 } while (!res && i < 2 && (chip->bbt_options & NAND_BBT_SCAN2NDPAGE));
393 * nand_default_block_markbad - [DEFAULT] mark a block bad via bad block marker
394 * @mtd: MTD device structure
395 * @ofs: offset from device start
397 * This is the default implementation, which can be overridden by a hardware
398 * specific driver. It provides the details for writing a bad block marker to a
401 static int nand_default_block_markbad(struct mtd_info *mtd, loff_t ofs)
403 struct nand_chip *chip = mtd_to_nand(mtd);
404 struct mtd_oob_ops ops;
405 uint8_t buf[2] = { 0, 0 };
406 int ret = 0, res, i = 0;
408 memset(&ops, 0, sizeof(ops));
410 ops.ooboffs = chip->badblockpos;
411 if (chip->options & NAND_BUSWIDTH_16) {
412 ops.ooboffs &= ~0x01;
413 ops.len = ops.ooblen = 2;
415 ops.len = ops.ooblen = 1;
417 ops.mode = MTD_OPS_PLACE_OOB;
419 /* Write to first/last page(s) if necessary */
420 if (chip->bbt_options & NAND_BBT_SCANLASTPAGE)
421 ofs += mtd->erasesize - mtd->writesize;
423 res = nand_do_write_oob(mtd, ofs, &ops);
428 ofs += mtd->writesize;
429 } while ((chip->bbt_options & NAND_BBT_SCAN2NDPAGE) && i < 2);
435 * nand_block_markbad_lowlevel - mark a block bad
436 * @mtd: MTD device structure
437 * @ofs: offset from device start
439 * This function performs the generic NAND bad block marking steps (i.e., bad
440 * block table(s) and/or marker(s)). We only allow the hardware driver to
441 * specify how to write bad block markers to OOB (chip->block_markbad).
443 * We try operations in the following order:
444 * (1) erase the affected block, to allow OOB marker to be written cleanly
445 * (2) write bad block marker to OOB area of affected block (unless flag
446 * NAND_BBT_NO_OOB_BBM is present)
448 * Note that we retain the first error encountered in (2) or (3), finish the
449 * procedures, and dump the error in the end.
451 static int nand_block_markbad_lowlevel(struct mtd_info *mtd, loff_t ofs)
453 struct nand_chip *chip = mtd_to_nand(mtd);
456 if (!(chip->bbt_options & NAND_BBT_NO_OOB_BBM)) {
457 struct erase_info einfo;
459 /* Attempt erase before marking OOB */
460 memset(&einfo, 0, sizeof(einfo));
463 einfo.len = 1ULL << chip->phys_erase_shift;
464 nand_erase_nand(mtd, &einfo, 0);
466 /* Write bad block marker to OOB */
467 nand_get_device(mtd, FL_WRITING);
468 ret = chip->block_markbad(mtd, ofs);
469 nand_release_device(mtd);
472 /* Mark block bad in BBT */
474 res = nand_markbad_bbt(mtd, ofs);
480 mtd->ecc_stats.badblocks++;
486 * nand_check_wp - [GENERIC] check if the chip is write protected
487 * @mtd: MTD device structure
489 * Check, if the device is write protected. The function expects, that the
490 * device is already selected.
492 static int nand_check_wp(struct mtd_info *mtd)
494 struct nand_chip *chip = mtd_to_nand(mtd);
496 /* Broken xD cards report WP despite being writable */
497 if (chip->options & NAND_BROKEN_XD)
500 /* Check the WP bit */
501 chip->cmdfunc(mtd, NAND_CMD_STATUS, -1, -1);
502 return (chip->read_byte(mtd) & NAND_STATUS_WP) ? 0 : 1;
506 * nand_block_isreserved - [GENERIC] Check if a block is marked reserved.
507 * @mtd: MTD device structure
508 * @ofs: offset from device start
510 * Check if the block is marked as reserved.
512 static int nand_block_isreserved(struct mtd_info *mtd, loff_t ofs)
514 struct nand_chip *chip = mtd_to_nand(mtd);
518 /* Return info from the table */
519 return nand_isreserved_bbt(mtd, ofs);
523 * nand_block_checkbad - [GENERIC] Check if a block is marked bad
524 * @mtd: MTD device structure
525 * @ofs: offset from device start
526 * @allowbbt: 1, if its allowed to access the bbt area
528 * Check, if the block is bad. Either by reading the bad block table or
529 * calling of the scan function.
531 static int nand_block_checkbad(struct mtd_info *mtd, loff_t ofs, int allowbbt)
533 struct nand_chip *chip = mtd_to_nand(mtd);
536 return chip->block_bad(mtd, ofs);
538 /* Return info from the table */
539 return nand_isbad_bbt(mtd, ofs, allowbbt);
543 * panic_nand_wait_ready - [GENERIC] Wait for the ready pin after commands.
544 * @mtd: MTD device structure
547 * Helper function for nand_wait_ready used when needing to wait in interrupt
550 static void panic_nand_wait_ready(struct mtd_info *mtd, unsigned long timeo)
552 struct nand_chip *chip = mtd_to_nand(mtd);
555 /* Wait for the device to get ready */
556 for (i = 0; i < timeo; i++) {
557 if (chip->dev_ready(mtd))
559 touch_softlockup_watchdog();
565 * nand_wait_ready - [GENERIC] Wait for the ready pin after commands.
566 * @mtd: MTD device structure
568 * Wait for the ready pin after a command, and warn if a timeout occurs.
570 void nand_wait_ready(struct mtd_info *mtd)
572 struct nand_chip *chip = mtd_to_nand(mtd);
573 unsigned long timeo = 400;
575 if (in_interrupt() || oops_in_progress)
576 return panic_nand_wait_ready(mtd, timeo);
578 /* Wait until command is processed or timeout occurs */
579 timeo = jiffies + msecs_to_jiffies(timeo);
581 if (chip->dev_ready(mtd))
584 } while (time_before(jiffies, timeo));
586 if (!chip->dev_ready(mtd))
587 pr_warn_ratelimited("timeout while waiting for chip to become ready\n");
589 EXPORT_SYMBOL_GPL(nand_wait_ready);
592 * nand_wait_status_ready - [GENERIC] Wait for the ready status after commands.
593 * @mtd: MTD device structure
594 * @timeo: Timeout in ms
596 * Wait for status ready (i.e. command done) or timeout.
598 static void nand_wait_status_ready(struct mtd_info *mtd, unsigned long timeo)
600 register struct nand_chip *chip = mtd_to_nand(mtd);
602 timeo = jiffies + msecs_to_jiffies(timeo);
604 if ((chip->read_byte(mtd) & NAND_STATUS_READY))
606 touch_softlockup_watchdog();
607 } while (time_before(jiffies, timeo));
611 * nand_command - [DEFAULT] Send command to NAND device
612 * @mtd: MTD device structure
613 * @command: the command to be sent
614 * @column: the column address for this command, -1 if none
615 * @page_addr: the page address for this command, -1 if none
617 * Send command to NAND device. This function is used for small page devices
618 * (512 Bytes per page).
620 static void nand_command(struct mtd_info *mtd, unsigned int command,
621 int column, int page_addr)
623 register struct nand_chip *chip = mtd_to_nand(mtd);
624 int ctrl = NAND_CTRL_CLE | NAND_CTRL_CHANGE;
626 /* Write out the command to the device */
627 if (command == NAND_CMD_SEQIN) {
630 if (column >= mtd->writesize) {
632 column -= mtd->writesize;
633 readcmd = NAND_CMD_READOOB;
634 } else if (column < 256) {
635 /* First 256 bytes --> READ0 */
636 readcmd = NAND_CMD_READ0;
639 readcmd = NAND_CMD_READ1;
641 chip->cmd_ctrl(mtd, readcmd, ctrl);
642 ctrl &= ~NAND_CTRL_CHANGE;
644 chip->cmd_ctrl(mtd, command, ctrl);
646 /* Address cycle, when necessary */
647 ctrl = NAND_CTRL_ALE | NAND_CTRL_CHANGE;
648 /* Serially input address */
650 /* Adjust columns for 16 bit buswidth */
651 if (chip->options & NAND_BUSWIDTH_16 &&
652 !nand_opcode_8bits(command))
654 chip->cmd_ctrl(mtd, column, ctrl);
655 ctrl &= ~NAND_CTRL_CHANGE;
657 if (page_addr != -1) {
658 chip->cmd_ctrl(mtd, page_addr, ctrl);
659 ctrl &= ~NAND_CTRL_CHANGE;
660 chip->cmd_ctrl(mtd, page_addr >> 8, ctrl);
661 /* One more address cycle for devices > 32MiB */
662 if (chip->chipsize > (32 << 20))
663 chip->cmd_ctrl(mtd, page_addr >> 16, ctrl);
665 chip->cmd_ctrl(mtd, NAND_CMD_NONE, NAND_NCE | NAND_CTRL_CHANGE);
668 * Program and erase have their own busy handlers status and sequential
673 case NAND_CMD_PAGEPROG:
674 case NAND_CMD_ERASE1:
675 case NAND_CMD_ERASE2:
677 case NAND_CMD_STATUS:
683 udelay(chip->chip_delay);
684 chip->cmd_ctrl(mtd, NAND_CMD_STATUS,
685 NAND_CTRL_CLE | NAND_CTRL_CHANGE);
687 NAND_CMD_NONE, NAND_NCE | NAND_CTRL_CHANGE);
688 /* EZ-NAND can take upto 250ms as per ONFi v4.0 */
689 nand_wait_status_ready(mtd, 250);
692 /* This applies to read commands */
695 * If we don't have access to the busy pin, we apply the given
698 if (!chip->dev_ready) {
699 udelay(chip->chip_delay);
704 * Apply this short delay always to ensure that we do wait tWB in
705 * any case on any machine.
709 nand_wait_ready(mtd);
713 * nand_command_lp - [DEFAULT] Send command to NAND large page device
714 * @mtd: MTD device structure
715 * @command: the command to be sent
716 * @column: the column address for this command, -1 if none
717 * @page_addr: the page address for this command, -1 if none
719 * Send command to NAND device. This is the version for the new large page
720 * devices. We don't have the separate regions as we have in the small page
721 * devices. We must emulate NAND_CMD_READOOB to keep the code compatible.
723 static void nand_command_lp(struct mtd_info *mtd, unsigned int command,
724 int column, int page_addr)
726 register struct nand_chip *chip = mtd_to_nand(mtd);
728 /* Emulate NAND_CMD_READOOB */
729 if (command == NAND_CMD_READOOB) {
730 column += mtd->writesize;
731 command = NAND_CMD_READ0;
734 /* Command latch cycle */
735 chip->cmd_ctrl(mtd, command, NAND_NCE | NAND_CLE | NAND_CTRL_CHANGE);
737 if (column != -1 || page_addr != -1) {
738 int ctrl = NAND_CTRL_CHANGE | NAND_NCE | NAND_ALE;
740 /* Serially input address */
742 /* Adjust columns for 16 bit buswidth */
743 if (chip->options & NAND_BUSWIDTH_16 &&
744 !nand_opcode_8bits(command))
746 chip->cmd_ctrl(mtd, column, ctrl);
747 ctrl &= ~NAND_CTRL_CHANGE;
748 chip->cmd_ctrl(mtd, column >> 8, ctrl);
750 if (page_addr != -1) {
751 chip->cmd_ctrl(mtd, page_addr, ctrl);
752 chip->cmd_ctrl(mtd, page_addr >> 8,
753 NAND_NCE | NAND_ALE);
754 /* One more address cycle for devices > 128MiB */
755 if (chip->chipsize > (128 << 20))
756 chip->cmd_ctrl(mtd, page_addr >> 16,
757 NAND_NCE | NAND_ALE);
760 chip->cmd_ctrl(mtd, NAND_CMD_NONE, NAND_NCE | NAND_CTRL_CHANGE);
763 * Program and erase have their own busy handlers status, sequential
764 * in and status need no delay.
768 case NAND_CMD_CACHEDPROG:
769 case NAND_CMD_PAGEPROG:
770 case NAND_CMD_ERASE1:
771 case NAND_CMD_ERASE2:
774 case NAND_CMD_STATUS:
780 udelay(chip->chip_delay);
781 chip->cmd_ctrl(mtd, NAND_CMD_STATUS,
782 NAND_NCE | NAND_CLE | NAND_CTRL_CHANGE);
783 chip->cmd_ctrl(mtd, NAND_CMD_NONE,
784 NAND_NCE | NAND_CTRL_CHANGE);
785 /* EZ-NAND can take upto 250ms as per ONFi v4.0 */
786 nand_wait_status_ready(mtd, 250);
789 case NAND_CMD_RNDOUT:
790 /* No ready / busy check necessary */
791 chip->cmd_ctrl(mtd, NAND_CMD_RNDOUTSTART,
792 NAND_NCE | NAND_CLE | NAND_CTRL_CHANGE);
793 chip->cmd_ctrl(mtd, NAND_CMD_NONE,
794 NAND_NCE | NAND_CTRL_CHANGE);
798 chip->cmd_ctrl(mtd, NAND_CMD_READSTART,
799 NAND_NCE | NAND_CLE | NAND_CTRL_CHANGE);
800 chip->cmd_ctrl(mtd, NAND_CMD_NONE,
801 NAND_NCE | NAND_CTRL_CHANGE);
803 /* This applies to read commands */
806 * If we don't have access to the busy pin, we apply the given
809 if (!chip->dev_ready) {
810 udelay(chip->chip_delay);
816 * Apply this short delay always to ensure that we do wait tWB in
817 * any case on any machine.
821 nand_wait_ready(mtd);
825 * panic_nand_get_device - [GENERIC] Get chip for selected access
826 * @chip: the nand chip descriptor
827 * @mtd: MTD device structure
828 * @new_state: the state which is requested
830 * Used when in panic, no locks are taken.
832 static void panic_nand_get_device(struct nand_chip *chip,
833 struct mtd_info *mtd, int new_state)
835 /* Hardware controller shared among independent devices */
836 chip->controller->active = chip;
837 chip->state = new_state;
841 * nand_get_device - [GENERIC] Get chip for selected access
842 * @mtd: MTD device structure
843 * @new_state: the state which is requested
845 * Get the device and lock it for exclusive access
848 nand_get_device(struct mtd_info *mtd, int new_state)
850 struct nand_chip *chip = mtd_to_nand(mtd);
851 spinlock_t *lock = &chip->controller->lock;
852 wait_queue_head_t *wq = &chip->controller->wq;
853 DECLARE_WAITQUEUE(wait, current);
857 /* Hardware controller shared among independent devices */
858 if (!chip->controller->active)
859 chip->controller->active = chip;
861 if (chip->controller->active == chip && chip->state == FL_READY) {
862 chip->state = new_state;
866 if (new_state == FL_PM_SUSPENDED) {
867 if (chip->controller->active->state == FL_PM_SUSPENDED) {
868 chip->state = FL_PM_SUSPENDED;
873 set_current_state(TASK_UNINTERRUPTIBLE);
874 add_wait_queue(wq, &wait);
877 remove_wait_queue(wq, &wait);
882 * panic_nand_wait - [GENERIC] wait until the command is done
883 * @mtd: MTD device structure
884 * @chip: NAND chip structure
887 * Wait for command done. This is a helper function for nand_wait used when
888 * we are in interrupt context. May happen when in panic and trying to write
889 * an oops through mtdoops.
891 static void panic_nand_wait(struct mtd_info *mtd, struct nand_chip *chip,
895 for (i = 0; i < timeo; i++) {
896 if (chip->dev_ready) {
897 if (chip->dev_ready(mtd))
900 if (chip->read_byte(mtd) & NAND_STATUS_READY)
908 * nand_wait - [DEFAULT] wait until the command is done
909 * @mtd: MTD device structure
910 * @chip: NAND chip structure
912 * Wait for command done. This applies to erase and program only.
914 static int nand_wait(struct mtd_info *mtd, struct nand_chip *chip)
918 unsigned long timeo = 400;
921 * Apply this short delay always to ensure that we do wait tWB in any
922 * case on any machine.
926 chip->cmdfunc(mtd, NAND_CMD_STATUS, -1, -1);
928 if (in_interrupt() || oops_in_progress)
929 panic_nand_wait(mtd, chip, timeo);
931 timeo = jiffies + msecs_to_jiffies(timeo);
933 if (chip->dev_ready) {
934 if (chip->dev_ready(mtd))
937 if (chip->read_byte(mtd) & NAND_STATUS_READY)
941 } while (time_before(jiffies, timeo));
944 status = (int)chip->read_byte(mtd);
945 /* This can happen if in case of timeout or buggy dev_ready */
946 WARN_ON(!(status & NAND_STATUS_READY));
951 * nand_reset_data_interface - Reset data interface and timings
952 * @chip: The NAND chip
954 * Reset the Data interface and timings to ONFI mode 0.
956 * Returns 0 for success or negative error code otherwise.
958 static int nand_reset_data_interface(struct nand_chip *chip)
960 struct mtd_info *mtd = nand_to_mtd(chip);
961 const struct nand_data_interface *conf;
964 if (!chip->setup_data_interface)
968 * The ONFI specification says:
970 * To transition from NV-DDR or NV-DDR2 to the SDR data
971 * interface, the host shall use the Reset (FFh) command
972 * using SDR timing mode 0. A device in any timing mode is
973 * required to recognize Reset (FFh) command issued in SDR
977 * Configure the data interface in SDR mode and set the
978 * timings to timing mode 0.
981 conf = nand_get_default_data_interface();
982 ret = chip->setup_data_interface(mtd, conf, false);
984 pr_err("Failed to configure data interface to SDR timing mode 0\n");
990 * nand_setup_data_interface - Setup the best data interface and timings
991 * @chip: The NAND chip
993 * Find and configure the best data interface and NAND timings supported by
994 * the chip and the driver.
995 * First tries to retrieve supported timing modes from ONFI information,
996 * and if the NAND chip does not support ONFI, relies on the
997 * ->onfi_timing_mode_default specified in the nand_ids table.
999 * Returns 0 for success or negative error code otherwise.
1001 static int nand_setup_data_interface(struct nand_chip *chip)
1003 struct mtd_info *mtd = nand_to_mtd(chip);
1006 if (!chip->setup_data_interface || !chip->data_interface)
1010 * Ensure the timing mode has been changed on the chip side
1011 * before changing timings on the controller side.
1013 if (chip->onfi_version) {
1014 u8 tmode_param[ONFI_SUBFEATURE_PARAM_LEN] = {
1015 chip->onfi_timing_mode_default,
1018 ret = chip->onfi_set_features(mtd, chip,
1019 ONFI_FEATURE_ADDR_TIMING_MODE,
1025 ret = chip->setup_data_interface(mtd, chip->data_interface, false);
1031 * nand_init_data_interface - find the best data interface and timings
1032 * @chip: The NAND chip
1034 * Find the best data interface and NAND timings supported by the chip
1036 * First tries to retrieve supported timing modes from ONFI information,
1037 * and if the NAND chip does not support ONFI, relies on the
1038 * ->onfi_timing_mode_default specified in the nand_ids table. After this
1039 * function nand_chip->data_interface is initialized with the best timing mode
1042 * Returns 0 for success or negative error code otherwise.
1044 static int nand_init_data_interface(struct nand_chip *chip)
1046 struct mtd_info *mtd = nand_to_mtd(chip);
1047 int modes, mode, ret;
1049 if (!chip->setup_data_interface)
1053 * First try to identify the best timings from ONFI parameters and
1054 * if the NAND does not support ONFI, fallback to the default ONFI
1057 modes = onfi_get_async_timing_mode(chip);
1058 if (modes == ONFI_TIMING_MODE_UNKNOWN) {
1059 if (!chip->onfi_timing_mode_default)
1062 modes = GENMASK(chip->onfi_timing_mode_default, 0);
1065 chip->data_interface = kzalloc(sizeof(*chip->data_interface),
1067 if (!chip->data_interface)
1070 for (mode = fls(modes) - 1; mode >= 0; mode--) {
1071 ret = onfi_init_data_interface(chip, chip->data_interface,
1072 NAND_SDR_IFACE, mode);
1076 ret = chip->setup_data_interface(mtd, chip->data_interface,
1079 chip->onfi_timing_mode_default = mode;
1087 static void nand_release_data_interface(struct nand_chip *chip)
1089 kfree(chip->data_interface);
1093 * nand_reset - Reset and initialize a NAND device
1094 * @chip: The NAND chip
1096 * Returns 0 for success or negative error code otherwise
1098 int nand_reset(struct nand_chip *chip)
1100 struct mtd_info *mtd = nand_to_mtd(chip);
1103 ret = nand_reset_data_interface(chip);
1107 chip->cmdfunc(mtd, NAND_CMD_RESET, -1, -1);
1109 ret = nand_setup_data_interface(chip);
1117 * __nand_unlock - [REPLACEABLE] unlocks specified locked blocks
1119 * @ofs: offset to start unlock from
1120 * @len: length to unlock
1121 * @invert: when = 0, unlock the range of blocks within the lower and
1122 * upper boundary address
1123 * when = 1, unlock the range of blocks outside the boundaries
1124 * of the lower and upper boundary address
1126 * Returs unlock status.
1128 static int __nand_unlock(struct mtd_info *mtd, loff_t ofs,
1129 uint64_t len, int invert)
1133 struct nand_chip *chip = mtd_to_nand(mtd);
1135 /* Submit address of first page to unlock */
1136 page = ofs >> chip->page_shift;
1137 chip->cmdfunc(mtd, NAND_CMD_UNLOCK1, -1, page & chip->pagemask);
1139 /* Submit address of last page to unlock */
1140 page = (ofs + len) >> chip->page_shift;
1141 chip->cmdfunc(mtd, NAND_CMD_UNLOCK2, -1,
1142 (page | invert) & chip->pagemask);
1144 /* Call wait ready function */
1145 status = chip->waitfunc(mtd, chip);
1146 /* See if device thinks it succeeded */
1147 if (status & NAND_STATUS_FAIL) {
1148 pr_debug("%s: error status = 0x%08x\n",
1157 * nand_unlock - [REPLACEABLE] unlocks specified locked blocks
1159 * @ofs: offset to start unlock from
1160 * @len: length to unlock
1162 * Returns unlock status.
1164 int nand_unlock(struct mtd_info *mtd, loff_t ofs, uint64_t len)
1168 struct nand_chip *chip = mtd_to_nand(mtd);
1170 pr_debug("%s: start = 0x%012llx, len = %llu\n",
1171 __func__, (unsigned long long)ofs, len);
1173 if (check_offs_len(mtd, ofs, len))
1176 /* Align to last block address if size addresses end of the device */
1177 if (ofs + len == mtd->size)
1178 len -= mtd->erasesize;
1180 nand_get_device(mtd, FL_UNLOCKING);
1182 /* Shift to get chip number */
1183 chipnr = ofs >> chip->chip_shift;
1185 chip->select_chip(mtd, chipnr);
1189 * If we want to check the WP through READ STATUS and check the bit 7
1190 * we must reset the chip
1191 * some operation can also clear the bit 7 of status register
1192 * eg. erase/program a locked block
1196 /* Check, if it is write protected */
1197 if (nand_check_wp(mtd)) {
1198 pr_debug("%s: device is write protected!\n",
1204 ret = __nand_unlock(mtd, ofs, len, 0);
1207 chip->select_chip(mtd, -1);
1208 nand_release_device(mtd);
1212 EXPORT_SYMBOL(nand_unlock);
1215 * nand_lock - [REPLACEABLE] locks all blocks present in the device
1217 * @ofs: offset to start unlock from
1218 * @len: length to unlock
1220 * This feature is not supported in many NAND parts. 'Micron' NAND parts do
1221 * have this feature, but it allows only to lock all blocks, not for specified
1222 * range for block. Implementing 'lock' feature by making use of 'unlock', for
1225 * Returns lock status.
1227 int nand_lock(struct mtd_info *mtd, loff_t ofs, uint64_t len)
1230 int chipnr, status, page;
1231 struct nand_chip *chip = mtd_to_nand(mtd);
1233 pr_debug("%s: start = 0x%012llx, len = %llu\n",
1234 __func__, (unsigned long long)ofs, len);
1236 if (check_offs_len(mtd, ofs, len))
1239 nand_get_device(mtd, FL_LOCKING);
1241 /* Shift to get chip number */
1242 chipnr = ofs >> chip->chip_shift;
1244 chip->select_chip(mtd, chipnr);
1248 * If we want to check the WP through READ STATUS and check the bit 7
1249 * we must reset the chip
1250 * some operation can also clear the bit 7 of status register
1251 * eg. erase/program a locked block
1255 /* Check, if it is write protected */
1256 if (nand_check_wp(mtd)) {
1257 pr_debug("%s: device is write protected!\n",
1259 status = MTD_ERASE_FAILED;
1264 /* Submit address of first page to lock */
1265 page = ofs >> chip->page_shift;
1266 chip->cmdfunc(mtd, NAND_CMD_LOCK, -1, page & chip->pagemask);
1268 /* Call wait ready function */
1269 status = chip->waitfunc(mtd, chip);
1270 /* See if device thinks it succeeded */
1271 if (status & NAND_STATUS_FAIL) {
1272 pr_debug("%s: error status = 0x%08x\n",
1278 ret = __nand_unlock(mtd, ofs, len, 0x1);
1281 chip->select_chip(mtd, -1);
1282 nand_release_device(mtd);
1286 EXPORT_SYMBOL(nand_lock);
1289 * nand_check_erased_buf - check if a buffer contains (almost) only 0xff data
1290 * @buf: buffer to test
1291 * @len: buffer length
1292 * @bitflips_threshold: maximum number of bitflips
1294 * Check if a buffer contains only 0xff, which means the underlying region
1295 * has been erased and is ready to be programmed.
1296 * The bitflips_threshold specify the maximum number of bitflips before
1297 * considering the region is not erased.
1298 * Note: The logic of this function has been extracted from the memweight
1299 * implementation, except that nand_check_erased_buf function exit before
1300 * testing the whole buffer if the number of bitflips exceed the
1301 * bitflips_threshold value.
1303 * Returns a positive number of bitflips less than or equal to
1304 * bitflips_threshold, or -ERROR_CODE for bitflips in excess of the
1307 static int nand_check_erased_buf(void *buf, int len, int bitflips_threshold)
1309 const unsigned char *bitmap = buf;
1313 for (; len && ((uintptr_t)bitmap) % sizeof(long);
1315 weight = hweight8(*bitmap);
1316 bitflips += BITS_PER_BYTE - weight;
1317 if (unlikely(bitflips > bitflips_threshold))
1321 for (; len >= sizeof(long);
1322 len -= sizeof(long), bitmap += sizeof(long)) {
1323 weight = hweight_long(*((unsigned long *)bitmap));
1324 bitflips += BITS_PER_LONG - weight;
1325 if (unlikely(bitflips > bitflips_threshold))
1329 for (; len > 0; len--, bitmap++) {
1330 weight = hweight8(*bitmap);
1331 bitflips += BITS_PER_BYTE - weight;
1332 if (unlikely(bitflips > bitflips_threshold))
1340 * nand_check_erased_ecc_chunk - check if an ECC chunk contains (almost) only
1342 * @data: data buffer to test
1343 * @datalen: data length
1345 * @ecclen: ECC length
1346 * @extraoob: extra OOB buffer
1347 * @extraooblen: extra OOB length
1348 * @bitflips_threshold: maximum number of bitflips
1350 * Check if a data buffer and its associated ECC and OOB data contains only
1351 * 0xff pattern, which means the underlying region has been erased and is
1352 * ready to be programmed.
1353 * The bitflips_threshold specify the maximum number of bitflips before
1354 * considering the region as not erased.
1357 * 1/ ECC algorithms are working on pre-defined block sizes which are usually
1358 * different from the NAND page size. When fixing bitflips, ECC engines will
1359 * report the number of errors per chunk, and the NAND core infrastructure
1360 * expect you to return the maximum number of bitflips for the whole page.
1361 * This is why you should always use this function on a single chunk and
1362 * not on the whole page. After checking each chunk you should update your
1363 * max_bitflips value accordingly.
1364 * 2/ When checking for bitflips in erased pages you should not only check
1365 * the payload data but also their associated ECC data, because a user might
1366 * have programmed almost all bits to 1 but a few. In this case, we
1367 * shouldn't consider the chunk as erased, and checking ECC bytes prevent
1369 * 3/ The extraoob argument is optional, and should be used if some of your OOB
1370 * data are protected by the ECC engine.
1371 * It could also be used if you support subpages and want to attach some
1372 * extra OOB data to an ECC chunk.
1374 * Returns a positive number of bitflips less than or equal to
1375 * bitflips_threshold, or -ERROR_CODE for bitflips in excess of the
1376 * threshold. In case of success, the passed buffers are filled with 0xff.
1378 int nand_check_erased_ecc_chunk(void *data, int datalen,
1379 void *ecc, int ecclen,
1380 void *extraoob, int extraooblen,
1381 int bitflips_threshold)
1383 int data_bitflips = 0, ecc_bitflips = 0, extraoob_bitflips = 0;
1385 data_bitflips = nand_check_erased_buf(data, datalen,
1386 bitflips_threshold);
1387 if (data_bitflips < 0)
1388 return data_bitflips;
1390 bitflips_threshold -= data_bitflips;
1392 ecc_bitflips = nand_check_erased_buf(ecc, ecclen, bitflips_threshold);
1393 if (ecc_bitflips < 0)
1394 return ecc_bitflips;
1396 bitflips_threshold -= ecc_bitflips;
1398 extraoob_bitflips = nand_check_erased_buf(extraoob, extraooblen,
1399 bitflips_threshold);
1400 if (extraoob_bitflips < 0)
1401 return extraoob_bitflips;
1404 memset(data, 0xff, datalen);
1407 memset(ecc, 0xff, ecclen);
1409 if (extraoob_bitflips)
1410 memset(extraoob, 0xff, extraooblen);
1412 return data_bitflips + ecc_bitflips + extraoob_bitflips;
1414 EXPORT_SYMBOL(nand_check_erased_ecc_chunk);
1417 * nand_read_page_raw - [INTERN] read raw page data without ecc
1418 * @mtd: mtd info structure
1419 * @chip: nand chip info structure
1420 * @buf: buffer to store read data
1421 * @oob_required: caller requires OOB data read to chip->oob_poi
1422 * @page: page number to read
1424 * Not for syndrome calculating ECC controllers, which use a special oob layout.
1426 static int nand_read_page_raw(struct mtd_info *mtd, struct nand_chip *chip,
1427 uint8_t *buf, int oob_required, int page)
1429 chip->read_buf(mtd, buf, mtd->writesize);
1431 chip->read_buf(mtd, chip->oob_poi, mtd->oobsize);
1436 * nand_read_page_raw_syndrome - [INTERN] read raw page data without ecc
1437 * @mtd: mtd info structure
1438 * @chip: nand chip info structure
1439 * @buf: buffer to store read data
1440 * @oob_required: caller requires OOB data read to chip->oob_poi
1441 * @page: page number to read
1443 * We need a special oob layout and handling even when OOB isn't used.
1445 static int nand_read_page_raw_syndrome(struct mtd_info *mtd,
1446 struct nand_chip *chip, uint8_t *buf,
1447 int oob_required, int page)
1449 int eccsize = chip->ecc.size;
1450 int eccbytes = chip->ecc.bytes;
1451 uint8_t *oob = chip->oob_poi;
1454 for (steps = chip->ecc.steps; steps > 0; steps--) {
1455 chip->read_buf(mtd, buf, eccsize);
1458 if (chip->ecc.prepad) {
1459 chip->read_buf(mtd, oob, chip->ecc.prepad);
1460 oob += chip->ecc.prepad;
1463 chip->read_buf(mtd, oob, eccbytes);
1466 if (chip->ecc.postpad) {
1467 chip->read_buf(mtd, oob, chip->ecc.postpad);
1468 oob += chip->ecc.postpad;
1472 size = mtd->oobsize - (oob - chip->oob_poi);
1474 chip->read_buf(mtd, oob, size);
1480 * nand_read_page_swecc - [REPLACEABLE] software ECC based page read function
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 static int nand_read_page_swecc(struct mtd_info *mtd, struct nand_chip *chip,
1488 uint8_t *buf, int oob_required, int page)
1490 int i, eccsize = chip->ecc.size, ret;
1491 int eccbytes = chip->ecc.bytes;
1492 int eccsteps = chip->ecc.steps;
1494 uint8_t *ecc_calc = chip->buffers->ecccalc;
1495 uint8_t *ecc_code = chip->buffers->ecccode;
1496 unsigned int max_bitflips = 0;
1498 chip->ecc.read_page_raw(mtd, chip, buf, 1, page);
1500 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize)
1501 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
1503 ret = mtd_ooblayout_get_eccbytes(mtd, ecc_code, chip->oob_poi, 0,
1508 eccsteps = chip->ecc.steps;
1511 for (i = 0 ; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
1514 stat = chip->ecc.correct(mtd, p, &ecc_code[i], &ecc_calc[i]);
1516 mtd->ecc_stats.failed++;
1518 mtd->ecc_stats.corrected += stat;
1519 max_bitflips = max_t(unsigned int, max_bitflips, stat);
1522 return max_bitflips;
1526 * nand_read_subpage - [REPLACEABLE] ECC based sub-page read function
1527 * @mtd: mtd info structure
1528 * @chip: nand chip info structure
1529 * @data_offs: offset of requested data within the page
1530 * @readlen: data length
1531 * @bufpoi: buffer to store read data
1532 * @page: page number to read
1534 static int nand_read_subpage(struct mtd_info *mtd, struct nand_chip *chip,
1535 uint32_t data_offs, uint32_t readlen, uint8_t *bufpoi,
1538 int start_step, end_step, num_steps, ret;
1540 int data_col_addr, i, gaps = 0;
1541 int datafrag_len, eccfrag_len, aligned_len, aligned_pos;
1542 int busw = (chip->options & NAND_BUSWIDTH_16) ? 2 : 1;
1543 int index, section = 0;
1544 unsigned int max_bitflips = 0;
1545 struct mtd_oob_region oobregion = { };
1547 /* Column address within the page aligned to ECC size (256bytes) */
1548 start_step = data_offs / chip->ecc.size;
1549 end_step = (data_offs + readlen - 1) / chip->ecc.size;
1550 num_steps = end_step - start_step + 1;
1551 index = start_step * chip->ecc.bytes;
1553 /* Data size aligned to ECC ecc.size */
1554 datafrag_len = num_steps * chip->ecc.size;
1555 eccfrag_len = num_steps * chip->ecc.bytes;
1557 data_col_addr = start_step * chip->ecc.size;
1558 /* If we read not a page aligned data */
1559 if (data_col_addr != 0)
1560 chip->cmdfunc(mtd, NAND_CMD_RNDOUT, data_col_addr, -1);
1562 p = bufpoi + data_col_addr;
1563 chip->read_buf(mtd, p, datafrag_len);
1566 for (i = 0; i < eccfrag_len ; i += chip->ecc.bytes, p += chip->ecc.size)
1567 chip->ecc.calculate(mtd, p, &chip->buffers->ecccalc[i]);
1570 * The performance is faster if we position offsets according to
1571 * ecc.pos. Let's make sure that there are no gaps in ECC positions.
1573 ret = mtd_ooblayout_find_eccregion(mtd, index, §ion, &oobregion);
1577 if (oobregion.length < eccfrag_len)
1581 chip->cmdfunc(mtd, NAND_CMD_RNDOUT, mtd->writesize, -1);
1582 chip->read_buf(mtd, chip->oob_poi, mtd->oobsize);
1585 * Send the command to read the particular ECC bytes take care
1586 * about buswidth alignment in read_buf.
1588 aligned_pos = oobregion.offset & ~(busw - 1);
1589 aligned_len = eccfrag_len;
1590 if (oobregion.offset & (busw - 1))
1592 if ((oobregion.offset + (num_steps * chip->ecc.bytes)) &
1596 chip->cmdfunc(mtd, NAND_CMD_RNDOUT,
1597 mtd->writesize + aligned_pos, -1);
1598 chip->read_buf(mtd, &chip->oob_poi[aligned_pos], aligned_len);
1601 ret = mtd_ooblayout_get_eccbytes(mtd, chip->buffers->ecccode,
1602 chip->oob_poi, index, eccfrag_len);
1606 p = bufpoi + data_col_addr;
1607 for (i = 0; i < eccfrag_len ; i += chip->ecc.bytes, p += chip->ecc.size) {
1610 stat = chip->ecc.correct(mtd, p,
1611 &chip->buffers->ecccode[i], &chip->buffers->ecccalc[i]);
1612 if (stat == -EBADMSG &&
1613 (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
1614 /* check for empty pages with bitflips */
1615 stat = nand_check_erased_ecc_chunk(p, chip->ecc.size,
1616 &chip->buffers->ecccode[i],
1619 chip->ecc.strength);
1623 mtd->ecc_stats.failed++;
1625 mtd->ecc_stats.corrected += stat;
1626 max_bitflips = max_t(unsigned int, max_bitflips, stat);
1629 return max_bitflips;
1633 * nand_read_page_hwecc - [REPLACEABLE] hardware ECC based page read function
1634 * @mtd: mtd info structure
1635 * @chip: nand chip info structure
1636 * @buf: buffer to store read data
1637 * @oob_required: caller requires OOB data read to chip->oob_poi
1638 * @page: page number to read
1640 * Not for syndrome calculating ECC controllers which need a special oob layout.
1642 static int nand_read_page_hwecc(struct mtd_info *mtd, struct nand_chip *chip,
1643 uint8_t *buf, int oob_required, int page)
1645 int i, eccsize = chip->ecc.size, ret;
1646 int eccbytes = chip->ecc.bytes;
1647 int eccsteps = chip->ecc.steps;
1649 uint8_t *ecc_calc = chip->buffers->ecccalc;
1650 uint8_t *ecc_code = chip->buffers->ecccode;
1651 unsigned int max_bitflips = 0;
1653 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
1654 chip->ecc.hwctl(mtd, NAND_ECC_READ);
1655 chip->read_buf(mtd, p, eccsize);
1656 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
1658 chip->read_buf(mtd, chip->oob_poi, mtd->oobsize);
1660 ret = mtd_ooblayout_get_eccbytes(mtd, ecc_code, chip->oob_poi, 0,
1665 eccsteps = chip->ecc.steps;
1668 for (i = 0 ; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
1671 stat = chip->ecc.correct(mtd, p, &ecc_code[i], &ecc_calc[i]);
1672 if (stat == -EBADMSG &&
1673 (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
1674 /* check for empty pages with bitflips */
1675 stat = nand_check_erased_ecc_chunk(p, eccsize,
1676 &ecc_code[i], eccbytes,
1678 chip->ecc.strength);
1682 mtd->ecc_stats.failed++;
1684 mtd->ecc_stats.corrected += stat;
1685 max_bitflips = max_t(unsigned int, max_bitflips, stat);
1688 return max_bitflips;
1692 * nand_read_page_hwecc_oob_first - [REPLACEABLE] hw ecc, read oob first
1693 * @mtd: mtd info structure
1694 * @chip: nand chip info structure
1695 * @buf: buffer to store read data
1696 * @oob_required: caller requires OOB data read to chip->oob_poi
1697 * @page: page number to read
1699 * Hardware ECC for large page chips, require OOB to be read first. For this
1700 * ECC mode, the write_page method is re-used from ECC_HW. These methods
1701 * read/write ECC from the OOB area, unlike the ECC_HW_SYNDROME support with
1702 * multiple ECC steps, follows the "infix ECC" scheme and reads/writes ECC from
1703 * the data area, by overwriting the NAND manufacturer bad block markings.
1705 static int nand_read_page_hwecc_oob_first(struct mtd_info *mtd,
1706 struct nand_chip *chip, uint8_t *buf, int oob_required, int page)
1708 int i, eccsize = chip->ecc.size, ret;
1709 int eccbytes = chip->ecc.bytes;
1710 int eccsteps = chip->ecc.steps;
1712 uint8_t *ecc_code = chip->buffers->ecccode;
1713 uint8_t *ecc_calc = chip->buffers->ecccalc;
1714 unsigned int max_bitflips = 0;
1716 /* Read the OOB area first */
1717 chip->cmdfunc(mtd, NAND_CMD_READOOB, 0, page);
1718 chip->read_buf(mtd, chip->oob_poi, mtd->oobsize);
1719 chip->cmdfunc(mtd, NAND_CMD_READ0, 0, page);
1721 ret = mtd_ooblayout_get_eccbytes(mtd, ecc_code, chip->oob_poi, 0,
1726 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
1729 chip->ecc.hwctl(mtd, NAND_ECC_READ);
1730 chip->read_buf(mtd, p, eccsize);
1731 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
1733 stat = chip->ecc.correct(mtd, p, &ecc_code[i], NULL);
1734 if (stat == -EBADMSG &&
1735 (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
1736 /* check for empty pages with bitflips */
1737 stat = nand_check_erased_ecc_chunk(p, eccsize,
1738 &ecc_code[i], eccbytes,
1740 chip->ecc.strength);
1744 mtd->ecc_stats.failed++;
1746 mtd->ecc_stats.corrected += stat;
1747 max_bitflips = max_t(unsigned int, max_bitflips, stat);
1750 return max_bitflips;
1754 * nand_read_page_syndrome - [REPLACEABLE] hardware ECC syndrome based page read
1755 * @mtd: mtd info structure
1756 * @chip: nand chip info structure
1757 * @buf: buffer to store read data
1758 * @oob_required: caller requires OOB data read to chip->oob_poi
1759 * @page: page number to read
1761 * The hw generator calculates the error syndrome automatically. Therefore we
1762 * need a special oob layout and handling.
1764 static int nand_read_page_syndrome(struct mtd_info *mtd, struct nand_chip *chip,
1765 uint8_t *buf, int oob_required, int page)
1767 int i, eccsize = chip->ecc.size;
1768 int eccbytes = chip->ecc.bytes;
1769 int eccsteps = chip->ecc.steps;
1770 int eccpadbytes = eccbytes + chip->ecc.prepad + chip->ecc.postpad;
1772 uint8_t *oob = chip->oob_poi;
1773 unsigned int max_bitflips = 0;
1775 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
1778 chip->ecc.hwctl(mtd, NAND_ECC_READ);
1779 chip->read_buf(mtd, p, eccsize);
1781 if (chip->ecc.prepad) {
1782 chip->read_buf(mtd, oob, chip->ecc.prepad);
1783 oob += chip->ecc.prepad;
1786 chip->ecc.hwctl(mtd, NAND_ECC_READSYN);
1787 chip->read_buf(mtd, oob, eccbytes);
1788 stat = chip->ecc.correct(mtd, p, oob, NULL);
1792 if (chip->ecc.postpad) {
1793 chip->read_buf(mtd, oob, chip->ecc.postpad);
1794 oob += chip->ecc.postpad;
1797 if (stat == -EBADMSG &&
1798 (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
1799 /* check for empty pages with bitflips */
1800 stat = nand_check_erased_ecc_chunk(p, chip->ecc.size,
1804 chip->ecc.strength);
1808 mtd->ecc_stats.failed++;
1810 mtd->ecc_stats.corrected += stat;
1811 max_bitflips = max_t(unsigned int, max_bitflips, stat);
1815 /* Calculate remaining oob bytes */
1816 i = mtd->oobsize - (oob - chip->oob_poi);
1818 chip->read_buf(mtd, oob, i);
1820 return max_bitflips;
1824 * nand_transfer_oob - [INTERN] Transfer oob to client buffer
1825 * @mtd: mtd info structure
1826 * @oob: oob destination address
1827 * @ops: oob ops structure
1828 * @len: size of oob to transfer
1830 static uint8_t *nand_transfer_oob(struct mtd_info *mtd, uint8_t *oob,
1831 struct mtd_oob_ops *ops, size_t len)
1833 struct nand_chip *chip = mtd_to_nand(mtd);
1836 switch (ops->mode) {
1838 case MTD_OPS_PLACE_OOB:
1840 memcpy(oob, chip->oob_poi + ops->ooboffs, len);
1843 case MTD_OPS_AUTO_OOB:
1844 ret = mtd_ooblayout_get_databytes(mtd, oob, chip->oob_poi,
1856 * nand_setup_read_retry - [INTERN] Set the READ RETRY mode
1857 * @mtd: MTD device structure
1858 * @retry_mode: the retry mode to use
1860 * Some vendors supply a special command to shift the Vt threshold, to be used
1861 * when there are too many bitflips in a page (i.e., ECC error). After setting
1862 * a new threshold, the host should retry reading the page.
1864 static int nand_setup_read_retry(struct mtd_info *mtd, int retry_mode)
1866 struct nand_chip *chip = mtd_to_nand(mtd);
1868 pr_debug("setting READ RETRY mode %d\n", retry_mode);
1870 if (retry_mode >= chip->read_retries)
1873 if (!chip->setup_read_retry)
1876 return chip->setup_read_retry(mtd, retry_mode);
1880 * nand_do_read_ops - [INTERN] Read data with ECC
1881 * @mtd: MTD device structure
1882 * @from: offset to read from
1883 * @ops: oob ops structure
1885 * Internal function. Called with chip held.
1887 static int nand_do_read_ops(struct mtd_info *mtd, loff_t from,
1888 struct mtd_oob_ops *ops)
1890 int chipnr, page, realpage, col, bytes, aligned, oob_required;
1891 struct nand_chip *chip = mtd_to_nand(mtd);
1893 uint32_t readlen = ops->len;
1894 uint32_t oobreadlen = ops->ooblen;
1895 uint32_t max_oobsize = mtd_oobavail(mtd, ops);
1897 uint8_t *bufpoi, *oob, *buf;
1899 unsigned int max_bitflips = 0;
1901 bool ecc_fail = false;
1903 chipnr = (int)(from >> chip->chip_shift);
1904 chip->select_chip(mtd, chipnr);
1906 realpage = (int)(from >> chip->page_shift);
1907 page = realpage & chip->pagemask;
1909 col = (int)(from & (mtd->writesize - 1));
1913 oob_required = oob ? 1 : 0;
1916 unsigned int ecc_failures = mtd->ecc_stats.failed;
1918 bytes = min(mtd->writesize - col, readlen);
1919 aligned = (bytes == mtd->writesize);
1923 else if (chip->options & NAND_USE_BOUNCE_BUFFER)
1924 use_bufpoi = !virt_addr_valid(buf);
1928 /* Is the current page in the buffer? */
1929 if (realpage != chip->pagebuf || oob) {
1930 bufpoi = use_bufpoi ? chip->buffers->databuf : buf;
1932 if (use_bufpoi && aligned)
1933 pr_debug("%s: using read bounce buffer for buf@%p\n",
1937 chip->cmdfunc(mtd, NAND_CMD_READ0, 0x00, page);
1940 * Now read the page into the buffer. Absent an error,
1941 * the read methods return max bitflips per ecc step.
1943 if (unlikely(ops->mode == MTD_OPS_RAW))
1944 ret = chip->ecc.read_page_raw(mtd, chip, bufpoi,
1947 else if (!aligned && NAND_HAS_SUBPAGE_READ(chip) &&
1949 ret = chip->ecc.read_subpage(mtd, chip,
1953 ret = chip->ecc.read_page(mtd, chip, bufpoi,
1954 oob_required, page);
1957 /* Invalidate page cache */
1962 max_bitflips = max_t(unsigned int, max_bitflips, ret);
1964 /* Transfer not aligned data */
1966 if (!NAND_HAS_SUBPAGE_READ(chip) && !oob &&
1967 !(mtd->ecc_stats.failed - ecc_failures) &&
1968 (ops->mode != MTD_OPS_RAW)) {
1969 chip->pagebuf = realpage;
1970 chip->pagebuf_bitflips = ret;
1972 /* Invalidate page cache */
1975 memcpy(buf, chip->buffers->databuf + col, bytes);
1978 if (unlikely(oob)) {
1979 int toread = min(oobreadlen, max_oobsize);
1982 oob = nand_transfer_oob(mtd,
1984 oobreadlen -= toread;
1988 if (chip->options & NAND_NEED_READRDY) {
1989 /* Apply delay or wait for ready/busy pin */
1990 if (!chip->dev_ready)
1991 udelay(chip->chip_delay);
1993 nand_wait_ready(mtd);
1996 if (mtd->ecc_stats.failed - ecc_failures) {
1997 if (retry_mode + 1 < chip->read_retries) {
1999 ret = nand_setup_read_retry(mtd,
2004 /* Reset failures; retry */
2005 mtd->ecc_stats.failed = ecc_failures;
2008 /* No more retry modes; real failure */
2015 memcpy(buf, chip->buffers->databuf + col, bytes);
2017 max_bitflips = max_t(unsigned int, max_bitflips,
2018 chip->pagebuf_bitflips);
2023 /* Reset to retry mode 0 */
2025 ret = nand_setup_read_retry(mtd, 0);
2034 /* For subsequent reads align to page boundary */
2036 /* Increment page address */
2039 page = realpage & chip->pagemask;
2040 /* Check, if we cross a chip boundary */
2043 chip->select_chip(mtd, -1);
2044 chip->select_chip(mtd, chipnr);
2047 chip->select_chip(mtd, -1);
2049 ops->retlen = ops->len - (size_t) readlen;
2051 ops->oobretlen = ops->ooblen - oobreadlen;
2059 return max_bitflips;
2063 * nand_read - [MTD Interface] MTD compatibility function for nand_do_read_ecc
2064 * @mtd: MTD device structure
2065 * @from: offset to read from
2066 * @len: number of bytes to read
2067 * @retlen: pointer to variable to store the number of read bytes
2068 * @buf: the databuffer to put data
2070 * Get hold of the chip and call nand_do_read.
2072 static int nand_read(struct mtd_info *mtd, loff_t from, size_t len,
2073 size_t *retlen, uint8_t *buf)
2075 struct mtd_oob_ops ops;
2078 nand_get_device(mtd, FL_READING);
2079 memset(&ops, 0, sizeof(ops));
2082 ops.mode = MTD_OPS_PLACE_OOB;
2083 ret = nand_do_read_ops(mtd, from, &ops);
2084 *retlen = ops.retlen;
2085 nand_release_device(mtd);
2090 * nand_read_oob_std - [REPLACEABLE] the most common OOB data read function
2091 * @mtd: mtd info structure
2092 * @chip: nand chip info structure
2093 * @page: page number to read
2095 int nand_read_oob_std(struct mtd_info *mtd, struct nand_chip *chip, int page)
2097 chip->cmdfunc(mtd, NAND_CMD_READOOB, 0, page);
2098 chip->read_buf(mtd, chip->oob_poi, mtd->oobsize);
2101 EXPORT_SYMBOL(nand_read_oob_std);
2104 * nand_read_oob_syndrome - [REPLACEABLE] OOB data read function for HW ECC
2106 * @mtd: mtd info structure
2107 * @chip: nand chip info structure
2108 * @page: page number to read
2110 int nand_read_oob_syndrome(struct mtd_info *mtd, struct nand_chip *chip,
2113 int length = mtd->oobsize;
2114 int chunk = chip->ecc.bytes + chip->ecc.prepad + chip->ecc.postpad;
2115 int eccsize = chip->ecc.size;
2116 uint8_t *bufpoi = chip->oob_poi;
2117 int i, toread, sndrnd = 0, pos;
2119 chip->cmdfunc(mtd, NAND_CMD_READ0, chip->ecc.size, page);
2120 for (i = 0; i < chip->ecc.steps; i++) {
2122 pos = eccsize + i * (eccsize + chunk);
2123 if (mtd->writesize > 512)
2124 chip->cmdfunc(mtd, NAND_CMD_RNDOUT, pos, -1);
2126 chip->cmdfunc(mtd, NAND_CMD_READ0, pos, page);
2129 toread = min_t(int, length, chunk);
2130 chip->read_buf(mtd, bufpoi, toread);
2135 chip->read_buf(mtd, bufpoi, length);
2139 EXPORT_SYMBOL(nand_read_oob_syndrome);
2142 * nand_write_oob_std - [REPLACEABLE] the most common OOB data write function
2143 * @mtd: mtd info structure
2144 * @chip: nand chip info structure
2145 * @page: page number to write
2147 int nand_write_oob_std(struct mtd_info *mtd, struct nand_chip *chip, int page)
2150 const uint8_t *buf = chip->oob_poi;
2151 int length = mtd->oobsize;
2153 chip->cmdfunc(mtd, NAND_CMD_SEQIN, mtd->writesize, page);
2154 chip->write_buf(mtd, buf, length);
2155 /* Send command to program the OOB data */
2156 chip->cmdfunc(mtd, NAND_CMD_PAGEPROG, -1, -1);
2158 status = chip->waitfunc(mtd, chip);
2160 return status & NAND_STATUS_FAIL ? -EIO : 0;
2162 EXPORT_SYMBOL(nand_write_oob_std);
2165 * nand_write_oob_syndrome - [REPLACEABLE] OOB data write function for HW ECC
2166 * with syndrome - only for large page flash
2167 * @mtd: mtd info structure
2168 * @chip: nand chip info structure
2169 * @page: page number to write
2171 int nand_write_oob_syndrome(struct mtd_info *mtd, struct nand_chip *chip,
2174 int chunk = chip->ecc.bytes + chip->ecc.prepad + chip->ecc.postpad;
2175 int eccsize = chip->ecc.size, length = mtd->oobsize;
2176 int i, len, pos, status = 0, sndcmd = 0, steps = chip->ecc.steps;
2177 const uint8_t *bufpoi = chip->oob_poi;
2180 * data-ecc-data-ecc ... ecc-oob
2182 * data-pad-ecc-pad-data-pad .... ecc-pad-oob
2184 if (!chip->ecc.prepad && !chip->ecc.postpad) {
2185 pos = steps * (eccsize + chunk);
2190 chip->cmdfunc(mtd, NAND_CMD_SEQIN, pos, page);
2191 for (i = 0; i < steps; i++) {
2193 if (mtd->writesize <= 512) {
2194 uint32_t fill = 0xFFFFFFFF;
2198 int num = min_t(int, len, 4);
2199 chip->write_buf(mtd, (uint8_t *)&fill,
2204 pos = eccsize + i * (eccsize + chunk);
2205 chip->cmdfunc(mtd, NAND_CMD_RNDIN, pos, -1);
2209 len = min_t(int, length, chunk);
2210 chip->write_buf(mtd, bufpoi, len);
2215 chip->write_buf(mtd, bufpoi, length);
2217 chip->cmdfunc(mtd, NAND_CMD_PAGEPROG, -1, -1);
2218 status = chip->waitfunc(mtd, chip);
2220 return status & NAND_STATUS_FAIL ? -EIO : 0;
2222 EXPORT_SYMBOL(nand_write_oob_syndrome);
2225 * nand_do_read_oob - [INTERN] NAND read out-of-band
2226 * @mtd: MTD device structure
2227 * @from: offset to read from
2228 * @ops: oob operations description structure
2230 * NAND read out-of-band data from the spare area.
2232 static int nand_do_read_oob(struct mtd_info *mtd, loff_t from,
2233 struct mtd_oob_ops *ops)
2235 int page, realpage, chipnr;
2236 struct nand_chip *chip = mtd_to_nand(mtd);
2237 struct mtd_ecc_stats stats;
2238 int readlen = ops->ooblen;
2240 uint8_t *buf = ops->oobbuf;
2243 pr_debug("%s: from = 0x%08Lx, len = %i\n",
2244 __func__, (unsigned long long)from, readlen);
2246 stats = mtd->ecc_stats;
2248 len = mtd_oobavail(mtd, ops);
2250 if (unlikely(ops->ooboffs >= len)) {
2251 pr_debug("%s: attempt to start read outside oob\n",
2256 /* Do not allow reads past end of device */
2257 if (unlikely(from >= mtd->size ||
2258 ops->ooboffs + readlen > ((mtd->size >> chip->page_shift) -
2259 (from >> chip->page_shift)) * len)) {
2260 pr_debug("%s: attempt to read beyond end of device\n",
2265 chipnr = (int)(from >> chip->chip_shift);
2266 chip->select_chip(mtd, chipnr);
2268 /* Shift to get page */
2269 realpage = (int)(from >> chip->page_shift);
2270 page = realpage & chip->pagemask;
2273 if (ops->mode == MTD_OPS_RAW)
2274 ret = chip->ecc.read_oob_raw(mtd, chip, page);
2276 ret = chip->ecc.read_oob(mtd, chip, page);
2281 len = min(len, readlen);
2282 buf = nand_transfer_oob(mtd, buf, ops, len);
2284 if (chip->options & NAND_NEED_READRDY) {
2285 /* Apply delay or wait for ready/busy pin */
2286 if (!chip->dev_ready)
2287 udelay(chip->chip_delay);
2289 nand_wait_ready(mtd);
2296 /* Increment page address */
2299 page = realpage & chip->pagemask;
2300 /* Check, if we cross a chip boundary */
2303 chip->select_chip(mtd, -1);
2304 chip->select_chip(mtd, chipnr);
2307 chip->select_chip(mtd, -1);
2309 ops->oobretlen = ops->ooblen - readlen;
2314 if (mtd->ecc_stats.failed - stats.failed)
2317 return mtd->ecc_stats.corrected - stats.corrected ? -EUCLEAN : 0;
2321 * nand_read_oob - [MTD Interface] NAND read data and/or out-of-band
2322 * @mtd: MTD device structure
2323 * @from: offset to read from
2324 * @ops: oob operation description structure
2326 * NAND read data and/or out-of-band data.
2328 static int nand_read_oob(struct mtd_info *mtd, loff_t from,
2329 struct mtd_oob_ops *ops)
2335 /* Do not allow reads past end of device */
2336 if (ops->datbuf && (from + ops->len) > mtd->size) {
2337 pr_debug("%s: attempt to read beyond end of device\n",
2342 if (ops->mode != MTD_OPS_PLACE_OOB &&
2343 ops->mode != MTD_OPS_AUTO_OOB &&
2344 ops->mode != MTD_OPS_RAW)
2347 nand_get_device(mtd, FL_READING);
2350 ret = nand_do_read_oob(mtd, from, ops);
2352 ret = nand_do_read_ops(mtd, from, ops);
2354 nand_release_device(mtd);
2360 * nand_write_page_raw - [INTERN] raw page write function
2361 * @mtd: mtd info structure
2362 * @chip: nand chip info structure
2364 * @oob_required: must write chip->oob_poi to OOB
2365 * @page: page number to write
2367 * Not for syndrome calculating ECC controllers, which use a special oob layout.
2369 static int nand_write_page_raw(struct mtd_info *mtd, struct nand_chip *chip,
2370 const uint8_t *buf, int oob_required, int page)
2372 chip->write_buf(mtd, buf, mtd->writesize);
2374 chip->write_buf(mtd, chip->oob_poi, mtd->oobsize);
2380 * nand_write_page_raw_syndrome - [INTERN] raw page write function
2381 * @mtd: mtd info structure
2382 * @chip: nand chip info structure
2384 * @oob_required: must write chip->oob_poi to OOB
2385 * @page: page number to write
2387 * We need a special oob layout and handling even when ECC isn't checked.
2389 static int nand_write_page_raw_syndrome(struct mtd_info *mtd,
2390 struct nand_chip *chip,
2391 const uint8_t *buf, int oob_required,
2394 int eccsize = chip->ecc.size;
2395 int eccbytes = chip->ecc.bytes;
2396 uint8_t *oob = chip->oob_poi;
2399 for (steps = chip->ecc.steps; steps > 0; steps--) {
2400 chip->write_buf(mtd, buf, eccsize);
2403 if (chip->ecc.prepad) {
2404 chip->write_buf(mtd, oob, chip->ecc.prepad);
2405 oob += chip->ecc.prepad;
2408 chip->write_buf(mtd, oob, eccbytes);
2411 if (chip->ecc.postpad) {
2412 chip->write_buf(mtd, oob, chip->ecc.postpad);
2413 oob += chip->ecc.postpad;
2417 size = mtd->oobsize - (oob - chip->oob_poi);
2419 chip->write_buf(mtd, oob, size);
2424 * nand_write_page_swecc - [REPLACEABLE] software ECC based page write function
2425 * @mtd: mtd info structure
2426 * @chip: nand chip info structure
2428 * @oob_required: must write chip->oob_poi to OOB
2429 * @page: page number to write
2431 static int nand_write_page_swecc(struct mtd_info *mtd, struct nand_chip *chip,
2432 const uint8_t *buf, int oob_required,
2435 int i, eccsize = chip->ecc.size, ret;
2436 int eccbytes = chip->ecc.bytes;
2437 int eccsteps = chip->ecc.steps;
2438 uint8_t *ecc_calc = chip->buffers->ecccalc;
2439 const uint8_t *p = buf;
2441 /* Software ECC calculation */
2442 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize)
2443 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
2445 ret = mtd_ooblayout_set_eccbytes(mtd, ecc_calc, chip->oob_poi, 0,
2450 return chip->ecc.write_page_raw(mtd, chip, buf, 1, page);
2454 * nand_write_page_hwecc - [REPLACEABLE] hardware ECC based page write function
2455 * @mtd: mtd info structure
2456 * @chip: nand chip info structure
2458 * @oob_required: must write chip->oob_poi to OOB
2459 * @page: page number to write
2461 static int nand_write_page_hwecc(struct mtd_info *mtd, struct nand_chip *chip,
2462 const uint8_t *buf, int oob_required,
2465 int i, eccsize = chip->ecc.size, ret;
2466 int eccbytes = chip->ecc.bytes;
2467 int eccsteps = chip->ecc.steps;
2468 uint8_t *ecc_calc = chip->buffers->ecccalc;
2469 const uint8_t *p = buf;
2471 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
2472 chip->ecc.hwctl(mtd, NAND_ECC_WRITE);
2473 chip->write_buf(mtd, p, eccsize);
2474 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
2477 ret = mtd_ooblayout_set_eccbytes(mtd, ecc_calc, chip->oob_poi, 0,
2482 chip->write_buf(mtd, chip->oob_poi, mtd->oobsize);
2489 * nand_write_subpage_hwecc - [REPLACEABLE] hardware ECC based subpage write
2490 * @mtd: mtd info structure
2491 * @chip: nand chip info structure
2492 * @offset: column address of subpage within the page
2493 * @data_len: data length
2495 * @oob_required: must write chip->oob_poi to OOB
2496 * @page: page number to write
2498 static int nand_write_subpage_hwecc(struct mtd_info *mtd,
2499 struct nand_chip *chip, uint32_t offset,
2500 uint32_t data_len, const uint8_t *buf,
2501 int oob_required, int page)
2503 uint8_t *oob_buf = chip->oob_poi;
2504 uint8_t *ecc_calc = chip->buffers->ecccalc;
2505 int ecc_size = chip->ecc.size;
2506 int ecc_bytes = chip->ecc.bytes;
2507 int ecc_steps = chip->ecc.steps;
2508 uint32_t start_step = offset / ecc_size;
2509 uint32_t end_step = (offset + data_len - 1) / ecc_size;
2510 int oob_bytes = mtd->oobsize / ecc_steps;
2513 for (step = 0; step < ecc_steps; step++) {
2514 /* configure controller for WRITE access */
2515 chip->ecc.hwctl(mtd, NAND_ECC_WRITE);
2517 /* write data (untouched subpages already masked by 0xFF) */
2518 chip->write_buf(mtd, buf, ecc_size);
2520 /* mask ECC of un-touched subpages by padding 0xFF */
2521 if ((step < start_step) || (step > end_step))
2522 memset(ecc_calc, 0xff, ecc_bytes);
2524 chip->ecc.calculate(mtd, buf, ecc_calc);
2526 /* mask OOB of un-touched subpages by padding 0xFF */
2527 /* if oob_required, preserve OOB metadata of written subpage */
2528 if (!oob_required || (step < start_step) || (step > end_step))
2529 memset(oob_buf, 0xff, oob_bytes);
2532 ecc_calc += ecc_bytes;
2533 oob_buf += oob_bytes;
2536 /* copy calculated ECC for whole page to chip->buffer->oob */
2537 /* this include masked-value(0xFF) for unwritten subpages */
2538 ecc_calc = chip->buffers->ecccalc;
2539 ret = mtd_ooblayout_set_eccbytes(mtd, ecc_calc, chip->oob_poi, 0,
2544 /* write OOB buffer to NAND device */
2545 chip->write_buf(mtd, chip->oob_poi, mtd->oobsize);
2552 * nand_write_page_syndrome - [REPLACEABLE] hardware ECC syndrome based page write
2553 * @mtd: mtd info structure
2554 * @chip: nand chip info structure
2556 * @oob_required: must write chip->oob_poi to OOB
2557 * @page: page number to write
2559 * The hw generator calculates the error syndrome automatically. Therefore we
2560 * need a special oob layout and handling.
2562 static int nand_write_page_syndrome(struct mtd_info *mtd,
2563 struct nand_chip *chip,
2564 const uint8_t *buf, int oob_required,
2567 int i, eccsize = chip->ecc.size;
2568 int eccbytes = chip->ecc.bytes;
2569 int eccsteps = chip->ecc.steps;
2570 const uint8_t *p = buf;
2571 uint8_t *oob = chip->oob_poi;
2573 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
2575 chip->ecc.hwctl(mtd, NAND_ECC_WRITE);
2576 chip->write_buf(mtd, p, eccsize);
2578 if (chip->ecc.prepad) {
2579 chip->write_buf(mtd, oob, chip->ecc.prepad);
2580 oob += chip->ecc.prepad;
2583 chip->ecc.calculate(mtd, p, oob);
2584 chip->write_buf(mtd, oob, eccbytes);
2587 if (chip->ecc.postpad) {
2588 chip->write_buf(mtd, oob, chip->ecc.postpad);
2589 oob += chip->ecc.postpad;
2593 /* Calculate remaining oob bytes */
2594 i = mtd->oobsize - (oob - chip->oob_poi);
2596 chip->write_buf(mtd, oob, i);
2602 * nand_write_page - [REPLACEABLE] write one page
2603 * @mtd: MTD device structure
2604 * @chip: NAND chip descriptor
2605 * @offset: address offset within the page
2606 * @data_len: length of actual data to be written
2607 * @buf: the data to write
2608 * @oob_required: must write chip->oob_poi to OOB
2609 * @page: page number to write
2610 * @cached: cached programming
2611 * @raw: use _raw version of write_page
2613 static int nand_write_page(struct mtd_info *mtd, struct nand_chip *chip,
2614 uint32_t offset, int data_len, const uint8_t *buf,
2615 int oob_required, int page, int cached, int raw)
2617 int status, subpage;
2619 if (!(chip->options & NAND_NO_SUBPAGE_WRITE) &&
2620 chip->ecc.write_subpage)
2621 subpage = offset || (data_len < mtd->writesize);
2625 chip->cmdfunc(mtd, NAND_CMD_SEQIN, 0x00, page);
2628 status = chip->ecc.write_page_raw(mtd, chip, buf,
2629 oob_required, page);
2631 status = chip->ecc.write_subpage(mtd, chip, offset, data_len,
2632 buf, oob_required, page);
2634 status = chip->ecc.write_page(mtd, chip, buf, oob_required,
2641 * Cached progamming disabled for now. Not sure if it's worth the
2642 * trouble. The speed gain is not very impressive. (2.3->2.6Mib/s).
2646 if (!cached || !NAND_HAS_CACHEPROG(chip)) {
2648 chip->cmdfunc(mtd, NAND_CMD_PAGEPROG, -1, -1);
2649 status = chip->waitfunc(mtd, chip);
2651 * See if operation failed and additional status checks are
2654 if ((status & NAND_STATUS_FAIL) && (chip->errstat))
2655 status = chip->errstat(mtd, chip, FL_WRITING, status,
2658 if (status & NAND_STATUS_FAIL)
2661 chip->cmdfunc(mtd, NAND_CMD_CACHEDPROG, -1, -1);
2662 status = chip->waitfunc(mtd, chip);
2669 * nand_fill_oob - [INTERN] Transfer client buffer to oob
2670 * @mtd: MTD device structure
2671 * @oob: oob data buffer
2672 * @len: oob data write length
2673 * @ops: oob ops structure
2675 static uint8_t *nand_fill_oob(struct mtd_info *mtd, uint8_t *oob, size_t len,
2676 struct mtd_oob_ops *ops)
2678 struct nand_chip *chip = mtd_to_nand(mtd);
2682 * Initialise to all 0xFF, to avoid the possibility of left over OOB
2683 * data from a previous OOB read.
2685 memset(chip->oob_poi, 0xff, mtd->oobsize);
2687 switch (ops->mode) {
2689 case MTD_OPS_PLACE_OOB:
2691 memcpy(chip->oob_poi + ops->ooboffs, oob, len);
2694 case MTD_OPS_AUTO_OOB:
2695 ret = mtd_ooblayout_set_databytes(mtd, oob, chip->oob_poi,
2706 #define NOTALIGNED(x) ((x & (chip->subpagesize - 1)) != 0)
2709 * nand_do_write_ops - [INTERN] NAND write with ECC
2710 * @mtd: MTD device structure
2711 * @to: offset to write to
2712 * @ops: oob operations description structure
2714 * NAND write with ECC.
2716 static int nand_do_write_ops(struct mtd_info *mtd, loff_t to,
2717 struct mtd_oob_ops *ops)
2719 int chipnr, realpage, page, blockmask, column;
2720 struct nand_chip *chip = mtd_to_nand(mtd);
2721 uint32_t writelen = ops->len;
2723 uint32_t oobwritelen = ops->ooblen;
2724 uint32_t oobmaxlen = mtd_oobavail(mtd, ops);
2726 uint8_t *oob = ops->oobbuf;
2727 uint8_t *buf = ops->datbuf;
2729 int oob_required = oob ? 1 : 0;
2735 /* Reject writes, which are not page aligned */
2736 if (NOTALIGNED(to) || NOTALIGNED(ops->len)) {
2737 pr_notice("%s: attempt to write non page aligned data\n",
2742 column = to & (mtd->writesize - 1);
2744 chipnr = (int)(to >> chip->chip_shift);
2745 chip->select_chip(mtd, chipnr);
2747 /* Check, if it is write protected */
2748 if (nand_check_wp(mtd)) {
2753 realpage = (int)(to >> chip->page_shift);
2754 page = realpage & chip->pagemask;
2755 blockmask = (1 << (chip->phys_erase_shift - chip->page_shift)) - 1;
2757 /* Invalidate the page cache, when we write to the cached page */
2758 if (to <= ((loff_t)chip->pagebuf << chip->page_shift) &&
2759 ((loff_t)chip->pagebuf << chip->page_shift) < (to + ops->len))
2762 /* Don't allow multipage oob writes with offset */
2763 if (oob && ops->ooboffs && (ops->ooboffs + ops->ooblen > oobmaxlen)) {
2769 int bytes = mtd->writesize;
2770 int cached = writelen > bytes && page != blockmask;
2771 uint8_t *wbuf = buf;
2773 int part_pagewr = (column || writelen < mtd->writesize);
2777 else if (chip->options & NAND_USE_BOUNCE_BUFFER)
2778 use_bufpoi = !virt_addr_valid(buf);
2782 /* Partial page write?, or need to use bounce buffer */
2784 pr_debug("%s: using write bounce buffer for buf@%p\n",
2788 bytes = min_t(int, bytes - column, writelen);
2790 memset(chip->buffers->databuf, 0xff, mtd->writesize);
2791 memcpy(&chip->buffers->databuf[column], buf, bytes);
2792 wbuf = chip->buffers->databuf;
2795 if (unlikely(oob)) {
2796 size_t len = min(oobwritelen, oobmaxlen);
2797 oob = nand_fill_oob(mtd, oob, len, ops);
2800 /* We still need to erase leftover OOB data */
2801 memset(chip->oob_poi, 0xff, mtd->oobsize);
2803 ret = chip->write_page(mtd, chip, column, bytes, wbuf,
2804 oob_required, page, cached,
2805 (ops->mode == MTD_OPS_RAW));
2817 page = realpage & chip->pagemask;
2818 /* Check, if we cross a chip boundary */
2821 chip->select_chip(mtd, -1);
2822 chip->select_chip(mtd, chipnr);
2826 ops->retlen = ops->len - writelen;
2828 ops->oobretlen = ops->ooblen;
2831 chip->select_chip(mtd, -1);
2836 * panic_nand_write - [MTD Interface] NAND write with ECC
2837 * @mtd: MTD device structure
2838 * @to: offset to write to
2839 * @len: number of bytes to write
2840 * @retlen: pointer to variable to store the number of written bytes
2841 * @buf: the data to write
2843 * NAND write with ECC. Used when performing writes in interrupt context, this
2844 * may for example be called by mtdoops when writing an oops while in panic.
2846 static int panic_nand_write(struct mtd_info *mtd, loff_t to, size_t len,
2847 size_t *retlen, const uint8_t *buf)
2849 struct nand_chip *chip = mtd_to_nand(mtd);
2850 struct mtd_oob_ops ops;
2853 /* Wait for the device to get ready */
2854 panic_nand_wait(mtd, chip, 400);
2856 /* Grab the device */
2857 panic_nand_get_device(chip, mtd, FL_WRITING);
2859 memset(&ops, 0, sizeof(ops));
2861 ops.datbuf = (uint8_t *)buf;
2862 ops.mode = MTD_OPS_PLACE_OOB;
2864 ret = nand_do_write_ops(mtd, to, &ops);
2866 *retlen = ops.retlen;
2871 * nand_write - [MTD Interface] NAND write with ECC
2872 * @mtd: MTD device structure
2873 * @to: offset to write to
2874 * @len: number of bytes to write
2875 * @retlen: pointer to variable to store the number of written bytes
2876 * @buf: the data to write
2878 * NAND write with ECC.
2880 static int nand_write(struct mtd_info *mtd, loff_t to, size_t len,
2881 size_t *retlen, const uint8_t *buf)
2883 struct mtd_oob_ops ops;
2886 nand_get_device(mtd, FL_WRITING);
2887 memset(&ops, 0, sizeof(ops));
2889 ops.datbuf = (uint8_t *)buf;
2890 ops.mode = MTD_OPS_PLACE_OOB;
2891 ret = nand_do_write_ops(mtd, to, &ops);
2892 *retlen = ops.retlen;
2893 nand_release_device(mtd);
2898 * nand_do_write_oob - [MTD Interface] NAND write out-of-band
2899 * @mtd: MTD device structure
2900 * @to: offset to write to
2901 * @ops: oob operation description structure
2903 * NAND write out-of-band.
2905 static int nand_do_write_oob(struct mtd_info *mtd, loff_t to,
2906 struct mtd_oob_ops *ops)
2908 int chipnr, page, status, len;
2909 struct nand_chip *chip = mtd_to_nand(mtd);
2911 pr_debug("%s: to = 0x%08x, len = %i\n",
2912 __func__, (unsigned int)to, (int)ops->ooblen);
2914 len = mtd_oobavail(mtd, ops);
2916 /* Do not allow write past end of page */
2917 if ((ops->ooboffs + ops->ooblen) > len) {
2918 pr_debug("%s: attempt to write past end of page\n",
2923 if (unlikely(ops->ooboffs >= len)) {
2924 pr_debug("%s: attempt to start write outside oob\n",
2929 /* Do not allow write past end of device */
2930 if (unlikely(to >= mtd->size ||
2931 ops->ooboffs + ops->ooblen >
2932 ((mtd->size >> chip->page_shift) -
2933 (to >> chip->page_shift)) * len)) {
2934 pr_debug("%s: attempt to write beyond end of device\n",
2939 chipnr = (int)(to >> chip->chip_shift);
2940 chip->select_chip(mtd, chipnr);
2942 /* Shift to get page */
2943 page = (int)(to >> chip->page_shift);
2946 * Reset the chip. Some chips (like the Toshiba TC5832DC found in one
2947 * of my DiskOnChip 2000 test units) will clear the whole data page too
2948 * if we don't do this. I have no clue why, but I seem to have 'fixed'
2949 * it in the doc2000 driver in August 1999. dwmw2.
2953 /* Check, if it is write protected */
2954 if (nand_check_wp(mtd)) {
2955 chip->select_chip(mtd, -1);
2959 /* Invalidate the page cache, if we write to the cached page */
2960 if (page == chip->pagebuf)
2963 nand_fill_oob(mtd, ops->oobbuf, ops->ooblen, ops);
2965 if (ops->mode == MTD_OPS_RAW)
2966 status = chip->ecc.write_oob_raw(mtd, chip, page & chip->pagemask);
2968 status = chip->ecc.write_oob(mtd, chip, page & chip->pagemask);
2970 chip->select_chip(mtd, -1);
2975 ops->oobretlen = ops->ooblen;
2981 * nand_write_oob - [MTD Interface] NAND write data and/or out-of-band
2982 * @mtd: MTD device structure
2983 * @to: offset to write to
2984 * @ops: oob operation description structure
2986 static int nand_write_oob(struct mtd_info *mtd, loff_t to,
2987 struct mtd_oob_ops *ops)
2989 int ret = -ENOTSUPP;
2993 /* Do not allow writes past end of device */
2994 if (ops->datbuf && (to + ops->len) > mtd->size) {
2995 pr_debug("%s: attempt to write beyond end of device\n",
3000 nand_get_device(mtd, FL_WRITING);
3002 switch (ops->mode) {
3003 case MTD_OPS_PLACE_OOB:
3004 case MTD_OPS_AUTO_OOB:
3013 ret = nand_do_write_oob(mtd, to, ops);
3015 ret = nand_do_write_ops(mtd, to, ops);
3018 nand_release_device(mtd);
3023 * single_erase - [GENERIC] NAND standard block erase command function
3024 * @mtd: MTD device structure
3025 * @page: the page address of the block which will be erased
3027 * Standard erase command for NAND chips. Returns NAND status.
3029 static int single_erase(struct mtd_info *mtd, int page)
3031 struct nand_chip *chip = mtd_to_nand(mtd);
3032 /* Send commands to erase a block */
3033 chip->cmdfunc(mtd, NAND_CMD_ERASE1, -1, page);
3034 chip->cmdfunc(mtd, NAND_CMD_ERASE2, -1, -1);
3036 return chip->waitfunc(mtd, chip);
3040 * nand_erase - [MTD Interface] erase block(s)
3041 * @mtd: MTD device structure
3042 * @instr: erase instruction
3044 * Erase one ore more blocks.
3046 static int nand_erase(struct mtd_info *mtd, struct erase_info *instr)
3048 return nand_erase_nand(mtd, instr, 0);
3052 * nand_erase_nand - [INTERN] erase block(s)
3053 * @mtd: MTD device structure
3054 * @instr: erase instruction
3055 * @allowbbt: allow erasing the bbt area
3057 * Erase one ore more blocks.
3059 int nand_erase_nand(struct mtd_info *mtd, struct erase_info *instr,
3062 int page, status, pages_per_block, ret, chipnr;
3063 struct nand_chip *chip = mtd_to_nand(mtd);
3066 pr_debug("%s: start = 0x%012llx, len = %llu\n",
3067 __func__, (unsigned long long)instr->addr,
3068 (unsigned long long)instr->len);
3070 if (check_offs_len(mtd, instr->addr, instr->len))
3073 /* Grab the lock and see if the device is available */
3074 nand_get_device(mtd, FL_ERASING);
3076 /* Shift to get first page */
3077 page = (int)(instr->addr >> chip->page_shift);
3078 chipnr = (int)(instr->addr >> chip->chip_shift);
3080 /* Calculate pages in each block */
3081 pages_per_block = 1 << (chip->phys_erase_shift - chip->page_shift);
3083 /* Select the NAND device */
3084 chip->select_chip(mtd, chipnr);
3086 /* Check, if it is write protected */
3087 if (nand_check_wp(mtd)) {
3088 pr_debug("%s: device is write protected!\n",
3090 instr->state = MTD_ERASE_FAILED;
3094 /* Loop through the pages */
3097 instr->state = MTD_ERASING;
3100 /* Check if we have a bad block, we do not erase bad blocks! */
3101 if (nand_block_checkbad(mtd, ((loff_t) page) <<
3102 chip->page_shift, allowbbt)) {
3103 pr_warn("%s: attempt to erase a bad block at page 0x%08x\n",
3105 instr->state = MTD_ERASE_FAILED;
3110 * Invalidate the page cache, if we erase the block which
3111 * contains the current cached page.
3113 if (page <= chip->pagebuf && chip->pagebuf <
3114 (page + pages_per_block))
3117 status = chip->erase(mtd, page & chip->pagemask);
3120 * See if operation failed and additional status checks are
3123 if ((status & NAND_STATUS_FAIL) && (chip->errstat))
3124 status = chip->errstat(mtd, chip, FL_ERASING,
3127 /* See if block erase succeeded */
3128 if (status & NAND_STATUS_FAIL) {
3129 pr_debug("%s: failed erase, page 0x%08x\n",
3131 instr->state = MTD_ERASE_FAILED;
3133 ((loff_t)page << chip->page_shift);
3137 /* Increment page address and decrement length */
3138 len -= (1ULL << chip->phys_erase_shift);
3139 page += pages_per_block;
3141 /* Check, if we cross a chip boundary */
3142 if (len && !(page & chip->pagemask)) {
3144 chip->select_chip(mtd, -1);
3145 chip->select_chip(mtd, chipnr);
3148 instr->state = MTD_ERASE_DONE;
3152 ret = instr->state == MTD_ERASE_DONE ? 0 : -EIO;
3154 /* Deselect and wake up anyone waiting on the device */
3155 chip->select_chip(mtd, -1);
3156 nand_release_device(mtd);
3158 /* Do call back function */
3160 mtd_erase_callback(instr);
3162 /* Return more or less happy */
3167 * nand_sync - [MTD Interface] sync
3168 * @mtd: MTD device structure
3170 * Sync is actually a wait for chip ready function.
3172 static void nand_sync(struct mtd_info *mtd)
3174 pr_debug("%s: called\n", __func__);
3176 /* Grab the lock and see if the device is available */
3177 nand_get_device(mtd, FL_SYNCING);
3178 /* Release it and go back */
3179 nand_release_device(mtd);
3183 * nand_block_isbad - [MTD Interface] Check if block at offset is bad
3184 * @mtd: MTD device structure
3185 * @offs: offset relative to mtd start
3187 static int nand_block_isbad(struct mtd_info *mtd, loff_t offs)
3189 struct nand_chip *chip = mtd_to_nand(mtd);
3190 int chipnr = (int)(offs >> chip->chip_shift);
3193 /* Select the NAND device */
3194 nand_get_device(mtd, FL_READING);
3195 chip->select_chip(mtd, chipnr);
3197 ret = nand_block_checkbad(mtd, offs, 0);
3199 chip->select_chip(mtd, -1);
3200 nand_release_device(mtd);
3206 * nand_block_markbad - [MTD Interface] Mark block at the given offset as bad
3207 * @mtd: MTD device structure
3208 * @ofs: offset relative to mtd start
3210 static int nand_block_markbad(struct mtd_info *mtd, loff_t ofs)
3214 ret = nand_block_isbad(mtd, ofs);
3216 /* If it was bad already, return success and do nothing */
3222 return nand_block_markbad_lowlevel(mtd, ofs);
3226 * nand_onfi_set_features- [REPLACEABLE] set features for ONFI nand
3227 * @mtd: MTD device structure
3228 * @chip: nand chip info structure
3229 * @addr: feature address.
3230 * @subfeature_param: the subfeature parameters, a four bytes array.
3232 static int nand_onfi_set_features(struct mtd_info *mtd, struct nand_chip *chip,
3233 int addr, uint8_t *subfeature_param)
3238 if (!chip->onfi_version ||
3239 !(le16_to_cpu(chip->onfi_params.opt_cmd)
3240 & ONFI_OPT_CMD_SET_GET_FEATURES))
3243 chip->cmdfunc(mtd, NAND_CMD_SET_FEATURES, addr, -1);
3244 for (i = 0; i < ONFI_SUBFEATURE_PARAM_LEN; ++i)
3245 chip->write_byte(mtd, subfeature_param[i]);
3247 status = chip->waitfunc(mtd, chip);
3248 if (status & NAND_STATUS_FAIL)
3254 * nand_onfi_get_features- [REPLACEABLE] get features for ONFI nand
3255 * @mtd: MTD device structure
3256 * @chip: nand chip info structure
3257 * @addr: feature address.
3258 * @subfeature_param: the subfeature parameters, a four bytes array.
3260 static int nand_onfi_get_features(struct mtd_info *mtd, struct nand_chip *chip,
3261 int addr, uint8_t *subfeature_param)
3265 if (!chip->onfi_version ||
3266 !(le16_to_cpu(chip->onfi_params.opt_cmd)
3267 & ONFI_OPT_CMD_SET_GET_FEATURES))
3270 chip->cmdfunc(mtd, NAND_CMD_GET_FEATURES, addr, -1);
3271 for (i = 0; i < ONFI_SUBFEATURE_PARAM_LEN; ++i)
3272 *subfeature_param++ = chip->read_byte(mtd);
3277 * nand_suspend - [MTD Interface] Suspend the NAND flash
3278 * @mtd: MTD device structure
3280 static int nand_suspend(struct mtd_info *mtd)
3282 return nand_get_device(mtd, FL_PM_SUSPENDED);
3286 * nand_resume - [MTD Interface] Resume the NAND flash
3287 * @mtd: MTD device structure
3289 static void nand_resume(struct mtd_info *mtd)
3291 struct nand_chip *chip = mtd_to_nand(mtd);
3293 if (chip->state == FL_PM_SUSPENDED)
3294 nand_release_device(mtd);
3296 pr_err("%s called for a chip which is not in suspended state\n",
3301 * nand_shutdown - [MTD Interface] Finish the current NAND operation and
3302 * prevent further operations
3303 * @mtd: MTD device structure
3305 static void nand_shutdown(struct mtd_info *mtd)
3307 nand_get_device(mtd, FL_PM_SUSPENDED);
3310 /* Set default functions */
3311 static void nand_set_defaults(struct nand_chip *chip, int busw)
3313 /* check for proper chip_delay setup, set 20us if not */
3314 if (!chip->chip_delay)
3315 chip->chip_delay = 20;
3317 /* check, if a user supplied command function given */
3318 if (chip->cmdfunc == NULL)
3319 chip->cmdfunc = nand_command;
3321 /* check, if a user supplied wait function given */
3322 if (chip->waitfunc == NULL)
3323 chip->waitfunc = nand_wait;
3325 if (!chip->select_chip)
3326 chip->select_chip = nand_select_chip;
3328 /* set for ONFI nand */
3329 if (!chip->onfi_set_features)
3330 chip->onfi_set_features = nand_onfi_set_features;
3331 if (!chip->onfi_get_features)
3332 chip->onfi_get_features = nand_onfi_get_features;
3334 /* If called twice, pointers that depend on busw may need to be reset */
3335 if (!chip->read_byte || chip->read_byte == nand_read_byte)
3336 chip->read_byte = busw ? nand_read_byte16 : nand_read_byte;
3337 if (!chip->read_word)
3338 chip->read_word = nand_read_word;
3339 if (!chip->block_bad)
3340 chip->block_bad = nand_block_bad;
3341 if (!chip->block_markbad)
3342 chip->block_markbad = nand_default_block_markbad;
3343 if (!chip->write_buf || chip->write_buf == nand_write_buf)
3344 chip->write_buf = busw ? nand_write_buf16 : nand_write_buf;
3345 if (!chip->write_byte || chip->write_byte == nand_write_byte)
3346 chip->write_byte = busw ? nand_write_byte16 : nand_write_byte;
3347 if (!chip->read_buf || chip->read_buf == nand_read_buf)
3348 chip->read_buf = busw ? nand_read_buf16 : nand_read_buf;
3349 if (!chip->scan_bbt)
3350 chip->scan_bbt = nand_default_bbt;
3352 if (!chip->controller) {
3353 chip->controller = &chip->hwcontrol;
3354 nand_hw_control_init(chip->controller);
3359 /* Sanitize ONFI strings so we can safely print them */
3360 static void sanitize_string(uint8_t *s, size_t len)
3364 /* Null terminate */
3367 /* Remove non printable chars */
3368 for (i = 0; i < len - 1; i++) {
3369 if (s[i] < ' ' || s[i] > 127)
3373 /* Remove trailing spaces */
3377 static u16 onfi_crc16(u16 crc, u8 const *p, size_t len)
3382 for (i = 0; i < 8; i++)
3383 crc = (crc << 1) ^ ((crc & 0x8000) ? 0x8005 : 0);
3389 /* Parse the Extended Parameter Page. */
3390 static int nand_flash_detect_ext_param_page(struct mtd_info *mtd,
3391 struct nand_chip *chip, struct nand_onfi_params *p)
3393 struct onfi_ext_param_page *ep;
3394 struct onfi_ext_section *s;
3395 struct onfi_ext_ecc_info *ecc;
3401 len = le16_to_cpu(p->ext_param_page_length) * 16;
3402 ep = kmalloc(len, GFP_KERNEL);
3406 /* Send our own NAND_CMD_PARAM. */
3407 chip->cmdfunc(mtd, NAND_CMD_PARAM, 0, -1);
3409 /* Use the Change Read Column command to skip the ONFI param pages. */
3410 chip->cmdfunc(mtd, NAND_CMD_RNDOUT,
3411 sizeof(*p) * p->num_of_param_pages , -1);
3413 /* Read out the Extended Parameter Page. */
3414 chip->read_buf(mtd, (uint8_t *)ep, len);
3415 if ((onfi_crc16(ONFI_CRC_BASE, ((uint8_t *)ep) + 2, len - 2)
3416 != le16_to_cpu(ep->crc))) {
3417 pr_debug("fail in the CRC.\n");
3422 * Check the signature.
3423 * Do not strictly follow the ONFI spec, maybe changed in future.
3425 if (strncmp(ep->sig, "EPPS", 4)) {
3426 pr_debug("The signature is invalid.\n");
3430 /* find the ECC section. */
3431 cursor = (uint8_t *)(ep + 1);
3432 for (i = 0; i < ONFI_EXT_SECTION_MAX; i++) {
3433 s = ep->sections + i;
3434 if (s->type == ONFI_SECTION_TYPE_2)
3436 cursor += s->length * 16;
3438 if (i == ONFI_EXT_SECTION_MAX) {
3439 pr_debug("We can not find the ECC section.\n");
3443 /* get the info we want. */
3444 ecc = (struct onfi_ext_ecc_info *)cursor;
3446 if (!ecc->codeword_size) {
3447 pr_debug("Invalid codeword size\n");
3451 chip->ecc_strength_ds = ecc->ecc_bits;
3452 chip->ecc_step_ds = 1 << ecc->codeword_size;
3460 static int nand_setup_read_retry_micron(struct mtd_info *mtd, int retry_mode)
3462 struct nand_chip *chip = mtd_to_nand(mtd);
3463 uint8_t feature[ONFI_SUBFEATURE_PARAM_LEN] = {retry_mode};
3465 return chip->onfi_set_features(mtd, chip, ONFI_FEATURE_ADDR_READ_RETRY,
3470 * Configure chip properties from Micron vendor-specific ONFI table
3472 static void nand_onfi_detect_micron(struct nand_chip *chip,
3473 struct nand_onfi_params *p)
3475 struct nand_onfi_vendor_micron *micron = (void *)p->vendor;
3477 if (le16_to_cpu(p->vendor_revision) < 1)
3480 chip->read_retries = micron->read_retry_options;
3481 chip->setup_read_retry = nand_setup_read_retry_micron;
3485 * Check if the NAND chip is ONFI compliant, returns 1 if it is, 0 otherwise.
3487 static int nand_flash_detect_onfi(struct mtd_info *mtd, struct nand_chip *chip,
3490 struct nand_onfi_params *p = &chip->onfi_params;
3494 /* Try ONFI for unknown chip or LP */
3495 chip->cmdfunc(mtd, NAND_CMD_READID, 0x20, -1);
3496 if (chip->read_byte(mtd) != 'O' || chip->read_byte(mtd) != 'N' ||
3497 chip->read_byte(mtd) != 'F' || chip->read_byte(mtd) != 'I')
3500 chip->cmdfunc(mtd, NAND_CMD_PARAM, 0, -1);
3501 for (i = 0; i < 3; i++) {
3502 for (j = 0; j < sizeof(*p); j++)
3503 ((uint8_t *)p)[j] = chip->read_byte(mtd);
3504 if (onfi_crc16(ONFI_CRC_BASE, (uint8_t *)p, 254) ==
3505 le16_to_cpu(p->crc)) {
3511 pr_err("Could not find valid ONFI parameter page; aborting\n");
3516 val = le16_to_cpu(p->revision);
3518 chip->onfi_version = 23;
3519 else if (val & (1 << 4))
3520 chip->onfi_version = 22;
3521 else if (val & (1 << 3))
3522 chip->onfi_version = 21;
3523 else if (val & (1 << 2))
3524 chip->onfi_version = 20;
3525 else if (val & (1 << 1))
3526 chip->onfi_version = 10;
3528 if (!chip->onfi_version) {
3529 pr_info("unsupported ONFI version: %d\n", val);
3533 sanitize_string(p->manufacturer, sizeof(p->manufacturer));
3534 sanitize_string(p->model, sizeof(p->model));
3536 mtd->name = p->model;
3538 mtd->writesize = le32_to_cpu(p->byte_per_page);
3541 * pages_per_block and blocks_per_lun may not be a power-of-2 size
3542 * (don't ask me who thought of this...). MTD assumes that these
3543 * dimensions will be power-of-2, so just truncate the remaining area.
3545 mtd->erasesize = 1 << (fls(le32_to_cpu(p->pages_per_block)) - 1);
3546 mtd->erasesize *= mtd->writesize;
3548 mtd->oobsize = le16_to_cpu(p->spare_bytes_per_page);
3550 /* See erasesize comment */
3551 chip->chipsize = 1 << (fls(le32_to_cpu(p->blocks_per_lun)) - 1);
3552 chip->chipsize *= (uint64_t)mtd->erasesize * p->lun_count;
3553 chip->bits_per_cell = p->bits_per_cell;
3555 if (onfi_feature(chip) & ONFI_FEATURE_16_BIT_BUS)
3556 *busw = NAND_BUSWIDTH_16;
3560 if (p->ecc_bits != 0xff) {
3561 chip->ecc_strength_ds = p->ecc_bits;
3562 chip->ecc_step_ds = 512;
3563 } else if (chip->onfi_version >= 21 &&
3564 (onfi_feature(chip) & ONFI_FEATURE_EXT_PARAM_PAGE)) {
3567 * The nand_flash_detect_ext_param_page() uses the
3568 * Change Read Column command which maybe not supported
3569 * by the chip->cmdfunc. So try to update the chip->cmdfunc
3570 * now. We do not replace user supplied command function.
3572 if (mtd->writesize > 512 && chip->cmdfunc == nand_command)
3573 chip->cmdfunc = nand_command_lp;
3575 /* The Extended Parameter Page is supported since ONFI 2.1. */
3576 if (nand_flash_detect_ext_param_page(mtd, chip, p))
3577 pr_warn("Failed to detect ONFI extended param page\n");
3579 pr_warn("Could not retrieve ONFI ECC requirements\n");
3582 if (p->jedec_id == NAND_MFR_MICRON)
3583 nand_onfi_detect_micron(chip, p);
3589 * Check if the NAND chip is JEDEC compliant, returns 1 if it is, 0 otherwise.
3591 static int nand_flash_detect_jedec(struct mtd_info *mtd, struct nand_chip *chip,
3594 struct nand_jedec_params *p = &chip->jedec_params;
3595 struct jedec_ecc_info *ecc;
3599 /* Try JEDEC for unknown chip or LP */
3600 chip->cmdfunc(mtd, NAND_CMD_READID, 0x40, -1);
3601 if (chip->read_byte(mtd) != 'J' || chip->read_byte(mtd) != 'E' ||
3602 chip->read_byte(mtd) != 'D' || chip->read_byte(mtd) != 'E' ||
3603 chip->read_byte(mtd) != 'C')
3606 chip->cmdfunc(mtd, NAND_CMD_PARAM, 0x40, -1);
3607 for (i = 0; i < 3; i++) {
3608 for (j = 0; j < sizeof(*p); j++)
3609 ((uint8_t *)p)[j] = chip->read_byte(mtd);
3611 if (onfi_crc16(ONFI_CRC_BASE, (uint8_t *)p, 510) ==
3612 le16_to_cpu(p->crc))
3617 pr_err("Could not find valid JEDEC parameter page; aborting\n");
3622 val = le16_to_cpu(p->revision);
3624 chip->jedec_version = 10;
3625 else if (val & (1 << 1))
3626 chip->jedec_version = 1; /* vendor specific version */
3628 if (!chip->jedec_version) {
3629 pr_info("unsupported JEDEC version: %d\n", val);
3633 sanitize_string(p->manufacturer, sizeof(p->manufacturer));
3634 sanitize_string(p->model, sizeof(p->model));
3636 mtd->name = p->model;
3638 mtd->writesize = le32_to_cpu(p->byte_per_page);
3640 /* Please reference to the comment for nand_flash_detect_onfi. */
3641 mtd->erasesize = 1 << (fls(le32_to_cpu(p->pages_per_block)) - 1);
3642 mtd->erasesize *= mtd->writesize;
3644 mtd->oobsize = le16_to_cpu(p->spare_bytes_per_page);
3646 /* Please reference to the comment for nand_flash_detect_onfi. */
3647 chip->chipsize = 1 << (fls(le32_to_cpu(p->blocks_per_lun)) - 1);
3648 chip->chipsize *= (uint64_t)mtd->erasesize * p->lun_count;
3649 chip->bits_per_cell = p->bits_per_cell;
3651 if (jedec_feature(chip) & JEDEC_FEATURE_16_BIT_BUS)
3652 *busw = NAND_BUSWIDTH_16;
3657 ecc = &p->ecc_info[0];
3659 if (ecc->codeword_size >= 9) {
3660 chip->ecc_strength_ds = ecc->ecc_bits;
3661 chip->ecc_step_ds = 1 << ecc->codeword_size;
3663 pr_warn("Invalid codeword size\n");
3670 * nand_id_has_period - Check if an ID string has a given wraparound period
3671 * @id_data: the ID string
3672 * @arrlen: the length of the @id_data array
3673 * @period: the period of repitition
3675 * Check if an ID string is repeated within a given sequence of bytes at
3676 * specific repetition interval period (e.g., {0x20,0x01,0x7F,0x20} has a
3677 * period of 3). This is a helper function for nand_id_len(). Returns non-zero
3678 * if the repetition has a period of @period; otherwise, returns zero.
3680 static int nand_id_has_period(u8 *id_data, int arrlen, int period)
3683 for (i = 0; i < period; i++)
3684 for (j = i + period; j < arrlen; j += period)
3685 if (id_data[i] != id_data[j])
3691 * nand_id_len - Get the length of an ID string returned by CMD_READID
3692 * @id_data: the ID string
3693 * @arrlen: the length of the @id_data array
3695 * Returns the length of the ID string, according to known wraparound/trailing
3696 * zero patterns. If no pattern exists, returns the length of the array.
3698 static int nand_id_len(u8 *id_data, int arrlen)
3700 int last_nonzero, period;
3702 /* Find last non-zero byte */
3703 for (last_nonzero = arrlen - 1; last_nonzero >= 0; last_nonzero--)
3704 if (id_data[last_nonzero])
3708 if (last_nonzero < 0)
3711 /* Calculate wraparound period */
3712 for (period = 1; period < arrlen; period++)
3713 if (nand_id_has_period(id_data, arrlen, period))
3716 /* There's a repeated pattern */
3717 if (period < arrlen)
3720 /* There are trailing zeros */
3721 if (last_nonzero < arrlen - 1)
3722 return last_nonzero + 1;
3724 /* No pattern detected */
3728 /* Extract the bits of per cell from the 3rd byte of the extended ID */
3729 static int nand_get_bits_per_cell(u8 cellinfo)
3733 bits = cellinfo & NAND_CI_CELLTYPE_MSK;
3734 bits >>= NAND_CI_CELLTYPE_SHIFT;
3739 * Many new NAND share similar device ID codes, which represent the size of the
3740 * chip. The rest of the parameters must be decoded according to generic or
3741 * manufacturer-specific "extended ID" decoding patterns.
3743 static void nand_decode_ext_id(struct mtd_info *mtd, struct nand_chip *chip,
3744 u8 id_data[8], int *busw)
3747 /* The 3rd id byte holds MLC / multichip data */
3748 chip->bits_per_cell = nand_get_bits_per_cell(id_data[2]);
3749 /* The 4th id byte is the important one */
3752 id_len = nand_id_len(id_data, 8);
3755 * Field definitions are in the following datasheets:
3756 * Old style (4,5 byte ID): Samsung K9GAG08U0M (p.32)
3757 * New Samsung (6 byte ID): Samsung K9GAG08U0F (p.44)
3758 * Hynix MLC (6 byte ID): Hynix H27UBG8T2B (p.22)
3760 * Check for ID length, non-zero 6th byte, cell type, and Hynix/Samsung
3761 * ID to decide what to do.
3763 if (id_len == 6 && id_data[0] == NAND_MFR_SAMSUNG &&
3764 !nand_is_slc(chip) && id_data[5] != 0x00) {
3766 mtd->writesize = 2048 << (extid & 0x03);
3769 switch (((extid >> 2) & 0x04) | (extid & 0x03)) {
3789 default: /* Other cases are "reserved" (unknown) */
3790 mtd->oobsize = 1024;
3794 /* Calc blocksize */
3795 mtd->erasesize = (128 * 1024) <<
3796 (((extid >> 1) & 0x04) | (extid & 0x03));
3798 } else if (id_len == 6 && id_data[0] == NAND_MFR_HYNIX &&
3799 !nand_is_slc(chip)) {
3803 mtd->writesize = 2048 << (extid & 0x03);
3806 switch (((extid >> 2) & 0x04) | (extid & 0x03)) {
3830 /* Calc blocksize */
3831 tmp = ((extid >> 1) & 0x04) | (extid & 0x03);
3833 mtd->erasesize = (128 * 1024) << tmp;
3834 else if (tmp == 0x03)
3835 mtd->erasesize = 768 * 1024;
3837 mtd->erasesize = (64 * 1024) << tmp;
3841 mtd->writesize = 1024 << (extid & 0x03);
3844 mtd->oobsize = (8 << (extid & 0x01)) *
3845 (mtd->writesize >> 9);
3847 /* Calc blocksize. Blocksize is multiples of 64KiB */
3848 mtd->erasesize = (64 * 1024) << (extid & 0x03);
3850 /* Get buswidth information */
3851 *busw = (extid & 0x01) ? NAND_BUSWIDTH_16 : 0;
3854 * Toshiba 24nm raw SLC (i.e., not BENAND) have 32B OOB per
3855 * 512B page. For Toshiba SLC, we decode the 5th/6th byte as
3857 * - ID byte 6, bits[2:0]: 100b -> 43nm, 101b -> 32nm,
3859 * - ID byte 5, bit[7]: 1 -> BENAND, 0 -> raw SLC
3861 if (id_len >= 6 && id_data[0] == NAND_MFR_TOSHIBA &&
3862 nand_is_slc(chip) &&
3863 (id_data[5] & 0x7) == 0x6 /* 24nm */ &&
3864 !(id_data[4] & 0x80) /* !BENAND */) {
3865 mtd->oobsize = 32 * mtd->writesize >> 9;
3872 * Old devices have chip data hardcoded in the device ID table. nand_decode_id
3873 * decodes a matching ID table entry and assigns the MTD size parameters for
3876 static void nand_decode_id(struct mtd_info *mtd, struct nand_chip *chip,
3877 struct nand_flash_dev *type, u8 id_data[8],
3880 int maf_id = id_data[0];
3882 mtd->erasesize = type->erasesize;
3883 mtd->writesize = type->pagesize;
3884 mtd->oobsize = mtd->writesize / 32;
3885 *busw = type->options & NAND_BUSWIDTH_16;
3887 /* All legacy ID NAND are small-page, SLC */
3888 chip->bits_per_cell = 1;
3891 * Check for Spansion/AMD ID + repeating 5th, 6th byte since
3892 * some Spansion chips have erasesize that conflicts with size
3893 * listed in nand_ids table.
3894 * Data sheet (5 byte ID): Spansion S30ML-P ORNAND (p.39)
3896 if (maf_id == NAND_MFR_AMD && id_data[4] != 0x00 && id_data[5] == 0x00
3897 && id_data[6] == 0x00 && id_data[7] == 0x00
3898 && mtd->writesize == 512) {
3899 mtd->erasesize = 128 * 1024;
3900 mtd->erasesize <<= ((id_data[3] & 0x03) << 1);
3905 * Set the bad block marker/indicator (BBM/BBI) patterns according to some
3906 * heuristic patterns using various detected parameters (e.g., manufacturer,
3907 * page size, cell-type information).
3909 static void nand_decode_bbm_options(struct mtd_info *mtd,
3910 struct nand_chip *chip, u8 id_data[8])
3912 int maf_id = id_data[0];
3914 /* Set the bad block position */
3915 if (mtd->writesize > 512 || (chip->options & NAND_BUSWIDTH_16))
3916 chip->badblockpos = NAND_LARGE_BADBLOCK_POS;
3918 chip->badblockpos = NAND_SMALL_BADBLOCK_POS;
3921 * Bad block marker is stored in the last page of each block on Samsung
3922 * and Hynix MLC devices; stored in first two pages of each block on
3923 * Micron devices with 2KiB pages and on SLC Samsung, Hynix, Toshiba,
3924 * AMD/Spansion, and Macronix. All others scan only the first page.
3926 if (!nand_is_slc(chip) &&
3927 (maf_id == NAND_MFR_SAMSUNG ||
3928 maf_id == NAND_MFR_HYNIX))
3929 chip->bbt_options |= NAND_BBT_SCANLASTPAGE;
3930 else if ((nand_is_slc(chip) &&
3931 (maf_id == NAND_MFR_SAMSUNG ||
3932 maf_id == NAND_MFR_HYNIX ||
3933 maf_id == NAND_MFR_TOSHIBA ||
3934 maf_id == NAND_MFR_AMD ||
3935 maf_id == NAND_MFR_MACRONIX)) ||
3936 (mtd->writesize == 2048 &&
3937 maf_id == NAND_MFR_MICRON))
3938 chip->bbt_options |= NAND_BBT_SCAN2NDPAGE;
3941 static inline bool is_full_id_nand(struct nand_flash_dev *type)
3943 return type->id_len;
3946 static bool find_full_id_nand(struct mtd_info *mtd, struct nand_chip *chip,
3947 struct nand_flash_dev *type, u8 *id_data, int *busw)
3949 if (!strncmp(type->id, id_data, type->id_len)) {
3950 mtd->writesize = type->pagesize;
3951 mtd->erasesize = type->erasesize;
3952 mtd->oobsize = type->oobsize;
3954 chip->bits_per_cell = nand_get_bits_per_cell(id_data[2]);
3955 chip->chipsize = (uint64_t)type->chipsize << 20;
3956 chip->options |= type->options;
3957 chip->ecc_strength_ds = NAND_ECC_STRENGTH(type);
3958 chip->ecc_step_ds = NAND_ECC_STEP(type);
3959 chip->onfi_timing_mode_default =
3960 type->onfi_timing_mode_default;
3962 *busw = type->options & NAND_BUSWIDTH_16;
3965 mtd->name = type->name;
3973 * Get the flash and manufacturer id and lookup if the type is supported.
3975 static struct nand_flash_dev *nand_get_flash_type(struct mtd_info *mtd,
3976 struct nand_chip *chip,
3977 int *maf_id, int *dev_id,
3978 struct nand_flash_dev *type)
3984 /* Select the device */
3985 chip->select_chip(mtd, 0);
3988 * Reset the chip, required by some chips (e.g. Micron MT29FxGxxxxx)
3993 /* Send the command for reading device ID */
3994 chip->cmdfunc(mtd, NAND_CMD_READID, 0x00, -1);
3996 /* Read manufacturer and device IDs */
3997 *maf_id = chip->read_byte(mtd);
3998 *dev_id = chip->read_byte(mtd);
4001 * Try again to make sure, as some systems the bus-hold or other
4002 * interface concerns can cause random data which looks like a
4003 * possibly credible NAND flash to appear. If the two results do
4004 * not match, ignore the device completely.
4007 chip->cmdfunc(mtd, NAND_CMD_READID, 0x00, -1);
4009 /* Read entire ID string */
4010 for (i = 0; i < 8; i++)
4011 id_data[i] = chip->read_byte(mtd);
4013 if (id_data[0] != *maf_id || id_data[1] != *dev_id) {
4014 pr_info("second ID read did not match %02x,%02x against %02x,%02x\n",
4015 *maf_id, *dev_id, id_data[0], id_data[1]);
4016 return ERR_PTR(-ENODEV);
4020 type = nand_flash_ids;
4022 for (; type->name != NULL; type++) {
4023 if (is_full_id_nand(type)) {
4024 if (find_full_id_nand(mtd, chip, type, id_data, &busw))
4026 } else if (*dev_id == type->dev_id) {
4031 chip->onfi_version = 0;
4032 if (!type->name || !type->pagesize) {
4033 /* Check if the chip is ONFI compliant */
4034 if (nand_flash_detect_onfi(mtd, chip, &busw))
4037 /* Check if the chip is JEDEC compliant */
4038 if (nand_flash_detect_jedec(mtd, chip, &busw))
4043 return ERR_PTR(-ENODEV);
4046 mtd->name = type->name;
4048 chip->chipsize = (uint64_t)type->chipsize << 20;
4050 if (!type->pagesize) {
4051 /* Decode parameters from extended ID */
4052 nand_decode_ext_id(mtd, chip, id_data, &busw);
4054 nand_decode_id(mtd, chip, type, id_data, &busw);
4056 /* Get chip options */
4057 chip->options |= type->options;
4060 * Check if chip is not a Samsung device. Do not clear the
4061 * options for chips which do not have an extended id.
4063 if (*maf_id != NAND_MFR_SAMSUNG && !type->pagesize)
4064 chip->options &= ~NAND_SAMSUNG_LP_OPTIONS;
4067 /* Try to identify manufacturer */
4068 for (maf_idx = 0; nand_manuf_ids[maf_idx].id != 0x0; maf_idx++) {
4069 if (nand_manuf_ids[maf_idx].id == *maf_id)
4073 if (chip->options & NAND_BUSWIDTH_AUTO) {
4074 WARN_ON(chip->options & NAND_BUSWIDTH_16);
4075 chip->options |= busw;
4076 nand_set_defaults(chip, busw);
4077 } else if (busw != (chip->options & NAND_BUSWIDTH_16)) {
4079 * Check, if buswidth is correct. Hardware drivers should set
4082 pr_info("device found, Manufacturer ID: 0x%02x, Chip ID: 0x%02x\n",
4084 pr_info("%s %s\n", nand_manuf_ids[maf_idx].name, mtd->name);
4085 pr_warn("bus width %d instead %d bit\n",
4086 (chip->options & NAND_BUSWIDTH_16) ? 16 : 8,
4088 return ERR_PTR(-EINVAL);
4091 nand_decode_bbm_options(mtd, chip, id_data);
4093 /* Calculate the address shift from the page size */
4094 chip->page_shift = ffs(mtd->writesize) - 1;
4095 /* Convert chipsize to number of pages per chip -1 */
4096 chip->pagemask = (chip->chipsize >> chip->page_shift) - 1;
4098 chip->bbt_erase_shift = chip->phys_erase_shift =
4099 ffs(mtd->erasesize) - 1;
4100 if (chip->chipsize & 0xffffffff)
4101 chip->chip_shift = ffs((unsigned)chip->chipsize) - 1;
4103 chip->chip_shift = ffs((unsigned)(chip->chipsize >> 32));
4104 chip->chip_shift += 32 - 1;
4107 chip->badblockbits = 8;
4108 chip->erase = single_erase;
4110 /* Do not replace user supplied command function! */
4111 if (mtd->writesize > 512 && chip->cmdfunc == nand_command)
4112 chip->cmdfunc = nand_command_lp;
4114 pr_info("device found, Manufacturer ID: 0x%02x, Chip ID: 0x%02x\n",
4117 if (chip->onfi_version)
4118 pr_info("%s %s\n", nand_manuf_ids[maf_idx].name,
4119 chip->onfi_params.model);
4120 else if (chip->jedec_version)
4121 pr_info("%s %s\n", nand_manuf_ids[maf_idx].name,
4122 chip->jedec_params.model);
4124 pr_info("%s %s\n", nand_manuf_ids[maf_idx].name,
4127 pr_info("%d MiB, %s, erase size: %d KiB, page size: %d, OOB size: %d\n",
4128 (int)(chip->chipsize >> 20), nand_is_slc(chip) ? "SLC" : "MLC",
4129 mtd->erasesize >> 10, mtd->writesize, mtd->oobsize);
4133 static const char * const nand_ecc_modes[] = {
4134 [NAND_ECC_NONE] = "none",
4135 [NAND_ECC_SOFT] = "soft",
4136 [NAND_ECC_HW] = "hw",
4137 [NAND_ECC_HW_SYNDROME] = "hw_syndrome",
4138 [NAND_ECC_HW_OOB_FIRST] = "hw_oob_first",
4141 static int of_get_nand_ecc_mode(struct device_node *np)
4146 err = of_property_read_string(np, "nand-ecc-mode", &pm);
4150 for (i = 0; i < ARRAY_SIZE(nand_ecc_modes); i++)
4151 if (!strcasecmp(pm, nand_ecc_modes[i]))
4155 * For backward compatibility we support few obsoleted values that don't
4156 * have their mappings into nand_ecc_modes_t anymore (they were merged
4157 * with other enums).
4159 if (!strcasecmp(pm, "soft_bch"))
4160 return NAND_ECC_SOFT;
4165 static const char * const nand_ecc_algos[] = {
4166 [NAND_ECC_HAMMING] = "hamming",
4167 [NAND_ECC_BCH] = "bch",
4170 static int of_get_nand_ecc_algo(struct device_node *np)
4175 err = of_property_read_string(np, "nand-ecc-algo", &pm);
4177 for (i = NAND_ECC_HAMMING; i < ARRAY_SIZE(nand_ecc_algos); i++)
4178 if (!strcasecmp(pm, nand_ecc_algos[i]))
4184 * For backward compatibility we also read "nand-ecc-mode" checking
4185 * for some obsoleted values that were specifying ECC algorithm.
4187 err = of_property_read_string(np, "nand-ecc-mode", &pm);
4191 if (!strcasecmp(pm, "soft"))
4192 return NAND_ECC_HAMMING;
4193 else if (!strcasecmp(pm, "soft_bch"))
4194 return NAND_ECC_BCH;
4199 static int of_get_nand_ecc_step_size(struct device_node *np)
4204 ret = of_property_read_u32(np, "nand-ecc-step-size", &val);
4205 return ret ? ret : val;
4208 static int of_get_nand_ecc_strength(struct device_node *np)
4213 ret = of_property_read_u32(np, "nand-ecc-strength", &val);
4214 return ret ? ret : val;
4217 static int of_get_nand_bus_width(struct device_node *np)
4221 if (of_property_read_u32(np, "nand-bus-width", &val))
4233 static bool of_get_nand_on_flash_bbt(struct device_node *np)
4235 return of_property_read_bool(np, "nand-on-flash-bbt");
4238 static int nand_dt_init(struct nand_chip *chip)
4240 struct device_node *dn = nand_get_flash_node(chip);
4241 int ecc_mode, ecc_algo, ecc_strength, ecc_step;
4246 if (of_get_nand_bus_width(dn) == 16)
4247 chip->options |= NAND_BUSWIDTH_16;
4249 if (of_get_nand_on_flash_bbt(dn))
4250 chip->bbt_options |= NAND_BBT_USE_FLASH;
4252 ecc_mode = of_get_nand_ecc_mode(dn);
4253 ecc_algo = of_get_nand_ecc_algo(dn);
4254 ecc_strength = of_get_nand_ecc_strength(dn);
4255 ecc_step = of_get_nand_ecc_step_size(dn);
4257 if ((ecc_step >= 0 && !(ecc_strength >= 0)) ||
4258 (!(ecc_step >= 0) && ecc_strength >= 0)) {
4259 pr_err("must set both strength and step size in DT\n");
4264 chip->ecc.mode = ecc_mode;
4267 chip->ecc.algo = ecc_algo;
4269 if (ecc_strength >= 0)
4270 chip->ecc.strength = ecc_strength;
4273 chip->ecc.size = ecc_step;
4279 * nand_scan_ident - [NAND Interface] Scan for the NAND device
4280 * @mtd: MTD device structure
4281 * @maxchips: number of chips to scan for
4282 * @table: alternative NAND ID table
4284 * This is the first phase of the normal nand_scan() function. It reads the
4285 * flash ID and sets up MTD fields accordingly.
4288 int nand_scan_ident(struct mtd_info *mtd, int maxchips,
4289 struct nand_flash_dev *table)
4291 int i, nand_maf_id, nand_dev_id;
4292 struct nand_chip *chip = mtd_to_nand(mtd);
4293 struct nand_flash_dev *type;
4296 ret = nand_dt_init(chip);
4300 if (!mtd->name && mtd->dev.parent)
4301 mtd->name = dev_name(mtd->dev.parent);
4303 if ((!chip->cmdfunc || !chip->select_chip) && !chip->cmd_ctrl) {
4305 * Default functions assigned for chip_select() and
4306 * cmdfunc() both expect cmd_ctrl() to be populated,
4307 * so we need to check that that's the case
4309 pr_err("chip.cmd_ctrl() callback is not provided");
4312 /* Set the default functions */
4313 nand_set_defaults(chip, chip->options & NAND_BUSWIDTH_16);
4315 /* Read the flash type */
4316 type = nand_get_flash_type(mtd, chip, &nand_maf_id,
4317 &nand_dev_id, table);
4320 if (!(chip->options & NAND_SCAN_SILENT_NODEV))
4321 pr_warn("No NAND device found\n");
4322 chip->select_chip(mtd, -1);
4323 return PTR_ERR(type);
4326 ret = nand_init_data_interface(chip);
4330 chip->select_chip(mtd, -1);
4332 /* Check for a chip array */
4333 for (i = 1; i < maxchips; i++) {
4334 chip->select_chip(mtd, i);
4335 /* See comment in nand_get_flash_type for reset */
4337 /* Send the command for reading device ID */
4338 chip->cmdfunc(mtd, NAND_CMD_READID, 0x00, -1);
4339 /* Read manufacturer and device IDs */
4340 if (nand_maf_id != chip->read_byte(mtd) ||
4341 nand_dev_id != chip->read_byte(mtd)) {
4342 chip->select_chip(mtd, -1);
4345 chip->select_chip(mtd, -1);
4348 pr_info("%d chips detected\n", i);
4350 /* Store the number of chips and calc total size for mtd */
4352 mtd->size = i * chip->chipsize;
4356 EXPORT_SYMBOL(nand_scan_ident);
4358 static int nand_set_ecc_soft_ops(struct mtd_info *mtd)
4360 struct nand_chip *chip = mtd_to_nand(mtd);
4361 struct nand_ecc_ctrl *ecc = &chip->ecc;
4363 if (WARN_ON(ecc->mode != NAND_ECC_SOFT))
4366 switch (ecc->algo) {
4367 case NAND_ECC_HAMMING:
4368 ecc->calculate = nand_calculate_ecc;
4369 ecc->correct = nand_correct_data;
4370 ecc->read_page = nand_read_page_swecc;
4371 ecc->read_subpage = nand_read_subpage;
4372 ecc->write_page = nand_write_page_swecc;
4373 ecc->read_page_raw = nand_read_page_raw;
4374 ecc->write_page_raw = nand_write_page_raw;
4375 ecc->read_oob = nand_read_oob_std;
4376 ecc->write_oob = nand_write_oob_std;
4383 if (!mtd_nand_has_bch()) {
4384 WARN(1, "CONFIG_MTD_NAND_ECC_BCH not enabled\n");
4387 ecc->calculate = nand_bch_calculate_ecc;
4388 ecc->correct = nand_bch_correct_data;
4389 ecc->read_page = nand_read_page_swecc;
4390 ecc->read_subpage = nand_read_subpage;
4391 ecc->write_page = nand_write_page_swecc;
4392 ecc->read_page_raw = nand_read_page_raw;
4393 ecc->write_page_raw = nand_write_page_raw;
4394 ecc->read_oob = nand_read_oob_std;
4395 ecc->write_oob = nand_write_oob_std;
4397 * Board driver should supply ecc.size and ecc.strength
4398 * values to select how many bits are correctable.
4399 * Otherwise, default to 4 bits for large page devices.
4401 if (!ecc->size && (mtd->oobsize >= 64)) {
4407 * if no ecc placement scheme was provided pickup the default
4410 if (!mtd->ooblayout) {
4411 /* handle large page devices only */
4412 if (mtd->oobsize < 64) {
4413 WARN(1, "OOB layout is required when using software BCH on small pages\n");
4417 mtd_set_ooblayout(mtd, &nand_ooblayout_lp_ops);
4420 /* See nand_bch_init() for details. */
4422 ecc->priv = nand_bch_init(mtd);
4424 WARN(1, "BCH ECC initialization failed!\n");
4429 WARN(1, "Unsupported ECC algorithm!\n");
4435 * Check if the chip configuration meet the datasheet requirements.
4437 * If our configuration corrects A bits per B bytes and the minimum
4438 * required correction level is X bits per Y bytes, then we must ensure
4439 * both of the following are true:
4441 * (1) A / B >= X / Y
4444 * Requirement (1) ensures we can correct for the required bitflip density.
4445 * Requirement (2) ensures we can correct even when all bitflips are clumped
4446 * in the same sector.
4448 static bool nand_ecc_strength_good(struct mtd_info *mtd)
4450 struct nand_chip *chip = mtd_to_nand(mtd);
4451 struct nand_ecc_ctrl *ecc = &chip->ecc;
4454 if (ecc->size == 0 || chip->ecc_step_ds == 0)
4455 /* Not enough information */
4459 * We get the number of corrected bits per page to compare
4460 * the correction density.
4462 corr = (mtd->writesize * ecc->strength) / ecc->size;
4463 ds_corr = (mtd->writesize * chip->ecc_strength_ds) / chip->ecc_step_ds;
4465 return corr >= ds_corr && ecc->strength >= chip->ecc_strength_ds;
4469 * nand_scan_tail - [NAND Interface] Scan for the NAND device
4470 * @mtd: MTD device structure
4472 * This is the second phase of the normal nand_scan() function. It fills out
4473 * all the uninitialized function pointers with the defaults and scans for a
4474 * bad block table if appropriate.
4476 int nand_scan_tail(struct mtd_info *mtd)
4478 struct nand_chip *chip = mtd_to_nand(mtd);
4479 struct nand_ecc_ctrl *ecc = &chip->ecc;
4480 struct nand_buffers *nbuf;
4483 /* New bad blocks should be marked in OOB, flash-based BBT, or both */
4484 if (WARN_ON((chip->bbt_options & NAND_BBT_NO_OOB_BBM) &&
4485 !(chip->bbt_options & NAND_BBT_USE_FLASH)))
4488 if (!(chip->options & NAND_OWN_BUFFERS)) {
4489 nbuf = kzalloc(sizeof(*nbuf) + mtd->writesize
4490 + mtd->oobsize * 3, GFP_KERNEL);
4493 nbuf->ecccalc = (uint8_t *)(nbuf + 1);
4494 nbuf->ecccode = nbuf->ecccalc + mtd->oobsize;
4495 nbuf->databuf = nbuf->ecccode + mtd->oobsize;
4497 chip->buffers = nbuf;
4503 /* Set the internal oob buffer location, just after the page data */
4504 chip->oob_poi = chip->buffers->databuf + mtd->writesize;
4507 * If no default placement scheme is given, select an appropriate one.
4509 if (!mtd->ooblayout &&
4510 !(ecc->mode == NAND_ECC_SOFT && ecc->algo == NAND_ECC_BCH)) {
4511 switch (mtd->oobsize) {
4514 mtd_set_ooblayout(mtd, &nand_ooblayout_sp_ops);
4518 mtd_set_ooblayout(mtd, &nand_ooblayout_lp_ops);
4521 WARN(1, "No oob scheme defined for oobsize %d\n",
4528 if (!chip->write_page)
4529 chip->write_page = nand_write_page;
4532 * Check ECC mode, default to software if 3byte/512byte hardware ECC is
4533 * selected and we have 256 byte pagesize fallback to software ECC
4536 switch (ecc->mode) {
4537 case NAND_ECC_HW_OOB_FIRST:
4538 /* Similar to NAND_ECC_HW, but a separate read_page handle */
4539 if (!ecc->calculate || !ecc->correct || !ecc->hwctl) {
4540 WARN(1, "No ECC functions supplied; hardware ECC not possible\n");
4544 if (!ecc->read_page)
4545 ecc->read_page = nand_read_page_hwecc_oob_first;
4548 /* Use standard hwecc read page function? */
4549 if (!ecc->read_page)
4550 ecc->read_page = nand_read_page_hwecc;
4551 if (!ecc->write_page)
4552 ecc->write_page = nand_write_page_hwecc;
4553 if (!ecc->read_page_raw)
4554 ecc->read_page_raw = nand_read_page_raw;
4555 if (!ecc->write_page_raw)
4556 ecc->write_page_raw = nand_write_page_raw;
4558 ecc->read_oob = nand_read_oob_std;
4559 if (!ecc->write_oob)
4560 ecc->write_oob = nand_write_oob_std;
4561 if (!ecc->read_subpage)
4562 ecc->read_subpage = nand_read_subpage;
4563 if (!ecc->write_subpage && ecc->hwctl && ecc->calculate)
4564 ecc->write_subpage = nand_write_subpage_hwecc;
4566 case NAND_ECC_HW_SYNDROME:
4567 if ((!ecc->calculate || !ecc->correct || !ecc->hwctl) &&
4569 ecc->read_page == nand_read_page_hwecc ||
4571 ecc->write_page == nand_write_page_hwecc)) {
4572 WARN(1, "No ECC functions supplied; hardware ECC not possible\n");
4576 /* Use standard syndrome read/write page function? */
4577 if (!ecc->read_page)
4578 ecc->read_page = nand_read_page_syndrome;
4579 if (!ecc->write_page)
4580 ecc->write_page = nand_write_page_syndrome;
4581 if (!ecc->read_page_raw)
4582 ecc->read_page_raw = nand_read_page_raw_syndrome;
4583 if (!ecc->write_page_raw)
4584 ecc->write_page_raw = nand_write_page_raw_syndrome;
4586 ecc->read_oob = nand_read_oob_syndrome;
4587 if (!ecc->write_oob)
4588 ecc->write_oob = nand_write_oob_syndrome;
4590 if (mtd->writesize >= ecc->size) {
4591 if (!ecc->strength) {
4592 WARN(1, "Driver must set ecc.strength when using hardware ECC\n");
4598 pr_warn("%d byte HW ECC not possible on %d byte page size, fallback to SW ECC\n",
4599 ecc->size, mtd->writesize);
4600 ecc->mode = NAND_ECC_SOFT;
4601 ecc->algo = NAND_ECC_HAMMING;
4604 ret = nand_set_ecc_soft_ops(mtd);
4612 pr_warn("NAND_ECC_NONE selected by board driver. This is not recommended!\n");
4613 ecc->read_page = nand_read_page_raw;
4614 ecc->write_page = nand_write_page_raw;
4615 ecc->read_oob = nand_read_oob_std;
4616 ecc->read_page_raw = nand_read_page_raw;
4617 ecc->write_page_raw = nand_write_page_raw;
4618 ecc->write_oob = nand_write_oob_std;
4619 ecc->size = mtd->writesize;
4625 WARN(1, "Invalid NAND_ECC_MODE %d\n", ecc->mode);
4630 /* For many systems, the standard OOB write also works for raw */
4631 if (!ecc->read_oob_raw)
4632 ecc->read_oob_raw = ecc->read_oob;
4633 if (!ecc->write_oob_raw)
4634 ecc->write_oob_raw = ecc->write_oob;
4636 /* propagate ecc info to mtd_info */
4637 mtd->ecc_strength = ecc->strength;
4638 mtd->ecc_step_size = ecc->size;
4641 * Set the number of read / write steps for one page depending on ECC
4644 ecc->steps = mtd->writesize / ecc->size;
4645 if (ecc->steps * ecc->size != mtd->writesize) {
4646 WARN(1, "Invalid ECC parameters\n");
4650 ecc->total = ecc->steps * ecc->bytes;
4653 * The number of bytes available for a client to place data into
4654 * the out of band area.
4656 ret = mtd_ooblayout_count_freebytes(mtd);
4660 mtd->oobavail = ret;
4662 /* ECC sanity check: warn if it's too weak */
4663 if (!nand_ecc_strength_good(mtd))
4664 pr_warn("WARNING: %s: the ECC used on your system is too weak compared to the one required by the NAND chip\n",
4667 /* Allow subpage writes up to ecc.steps. Not possible for MLC flash */
4668 if (!(chip->options & NAND_NO_SUBPAGE_WRITE) && nand_is_slc(chip)) {
4669 switch (ecc->steps) {
4671 mtd->subpage_sft = 1;
4676 mtd->subpage_sft = 2;
4680 chip->subpagesize = mtd->writesize >> mtd->subpage_sft;
4682 /* Initialize state */
4683 chip->state = FL_READY;
4685 /* Invalidate the pagebuffer reference */
4688 /* Large page NAND with SOFT_ECC should support subpage reads */
4689 switch (ecc->mode) {
4691 if (chip->page_shift > 9)
4692 chip->options |= NAND_SUBPAGE_READ;
4699 /* Fill in remaining MTD driver data */
4700 mtd->type = nand_is_slc(chip) ? MTD_NANDFLASH : MTD_MLCNANDFLASH;
4701 mtd->flags = (chip->options & NAND_ROM) ? MTD_CAP_ROM :
4703 mtd->_erase = nand_erase;
4705 mtd->_unpoint = NULL;
4706 mtd->_read = nand_read;
4707 mtd->_write = nand_write;
4708 mtd->_panic_write = panic_nand_write;
4709 mtd->_read_oob = nand_read_oob;
4710 mtd->_write_oob = nand_write_oob;
4711 mtd->_sync = nand_sync;
4713 mtd->_unlock = NULL;
4714 mtd->_suspend = nand_suspend;
4715 mtd->_resume = nand_resume;
4716 mtd->_reboot = nand_shutdown;
4717 mtd->_block_isreserved = nand_block_isreserved;
4718 mtd->_block_isbad = nand_block_isbad;
4719 mtd->_block_markbad = nand_block_markbad;
4720 mtd->writebufsize = mtd->writesize;
4723 * Initialize bitflip_threshold to its default prior scan_bbt() call.
4724 * scan_bbt() might invoke mtd_read(), thus bitflip_threshold must be
4727 if (!mtd->bitflip_threshold)
4728 mtd->bitflip_threshold = DIV_ROUND_UP(mtd->ecc_strength * 3, 4);
4730 /* Check, if we should skip the bad block table scan */
4731 if (chip->options & NAND_SKIP_BBTSCAN)
4734 /* Build bad block table */
4735 return chip->scan_bbt(mtd);
4737 if (!(chip->options & NAND_OWN_BUFFERS))
4738 kfree(chip->buffers);
4741 EXPORT_SYMBOL(nand_scan_tail);
4744 * is_module_text_address() isn't exported, and it's mostly a pointless
4745 * test if this is a module _anyway_ -- they'd have to try _really_ hard
4746 * to call us from in-kernel code if the core NAND support is modular.
4749 #define caller_is_module() (1)
4751 #define caller_is_module() \
4752 is_module_text_address((unsigned long)__builtin_return_address(0))
4756 * nand_scan - [NAND Interface] Scan for the NAND device
4757 * @mtd: MTD device structure
4758 * @maxchips: number of chips to scan for
4760 * This fills out all the uninitialized function pointers with the defaults.
4761 * The flash ID is read and the mtd/chip structures are filled with the
4762 * appropriate values.
4764 int nand_scan(struct mtd_info *mtd, int maxchips)
4768 ret = nand_scan_ident(mtd, maxchips, NULL);
4770 ret = nand_scan_tail(mtd);
4773 EXPORT_SYMBOL(nand_scan);
4776 * nand_release - [NAND Interface] Free resources held by the NAND device
4777 * @mtd: MTD device structure
4779 void nand_release(struct mtd_info *mtd)
4781 struct nand_chip *chip = mtd_to_nand(mtd);
4783 if (chip->ecc.mode == NAND_ECC_SOFT &&
4784 chip->ecc.algo == NAND_ECC_BCH)
4785 nand_bch_free((struct nand_bch_control *)chip->ecc.priv);
4787 mtd_device_unregister(mtd);
4789 nand_release_data_interface(chip);
4791 /* Free bad block table memory */
4793 if (!(chip->options & NAND_OWN_BUFFERS))
4794 kfree(chip->buffers);
4796 /* Free bad block descriptor memory */
4797 if (chip->badblock_pattern && chip->badblock_pattern->options
4798 & NAND_BBT_DYNAMICSTRUCT)
4799 kfree(chip->badblock_pattern);
4801 EXPORT_SYMBOL_GPL(nand_release);
4803 MODULE_LICENSE("GPL");
4804 MODULE_AUTHOR("Steven J. Hill <sjhill@realitydiluted.com>");
4805 MODULE_AUTHOR("Thomas Gleixner <tglx@linutronix.de>");
4806 MODULE_DESCRIPTION("Generic NAND flash driver code");