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/nmi.h>
40 #include <linux/types.h>
41 #include <linux/mtd/mtd.h>
42 #include <linux/mtd/rawnand.h>
43 #include <linux/mtd/nand_ecc.h>
44 #include <linux/mtd/nand_bch.h>
45 #include <linux/interrupt.h>
46 #include <linux/bitops.h>
48 #include <linux/mtd/partitions.h>
51 static int nand_get_device(struct mtd_info *mtd, int new_state);
53 static int nand_do_write_oob(struct mtd_info *mtd, loff_t to,
54 struct mtd_oob_ops *ops);
56 /* Define default oob placement schemes for large and small page devices */
57 static int nand_ooblayout_ecc_sp(struct mtd_info *mtd, int section,
58 struct mtd_oob_region *oobregion)
60 struct nand_chip *chip = mtd_to_nand(mtd);
61 struct nand_ecc_ctrl *ecc = &chip->ecc;
67 oobregion->offset = 0;
68 if (mtd->oobsize == 16)
69 oobregion->length = 4;
71 oobregion->length = 3;
73 if (mtd->oobsize == 8)
76 oobregion->offset = 6;
77 oobregion->length = ecc->total - 4;
83 static int nand_ooblayout_free_sp(struct mtd_info *mtd, int section,
84 struct mtd_oob_region *oobregion)
89 if (mtd->oobsize == 16) {
93 oobregion->length = 8;
94 oobregion->offset = 8;
96 oobregion->length = 2;
98 oobregion->offset = 3;
100 oobregion->offset = 6;
106 const struct mtd_ooblayout_ops nand_ooblayout_sp_ops = {
107 .ecc = nand_ooblayout_ecc_sp,
108 .free = nand_ooblayout_free_sp,
110 EXPORT_SYMBOL_GPL(nand_ooblayout_sp_ops);
112 static int nand_ooblayout_ecc_lp(struct mtd_info *mtd, int section,
113 struct mtd_oob_region *oobregion)
115 struct nand_chip *chip = mtd_to_nand(mtd);
116 struct nand_ecc_ctrl *ecc = &chip->ecc;
118 if (section || !ecc->total)
121 oobregion->length = ecc->total;
122 oobregion->offset = mtd->oobsize - oobregion->length;
127 static int nand_ooblayout_free_lp(struct mtd_info *mtd, int section,
128 struct mtd_oob_region *oobregion)
130 struct nand_chip *chip = mtd_to_nand(mtd);
131 struct nand_ecc_ctrl *ecc = &chip->ecc;
136 oobregion->length = mtd->oobsize - ecc->total - 2;
137 oobregion->offset = 2;
142 const struct mtd_ooblayout_ops nand_ooblayout_lp_ops = {
143 .ecc = nand_ooblayout_ecc_lp,
144 .free = nand_ooblayout_free_lp,
146 EXPORT_SYMBOL_GPL(nand_ooblayout_lp_ops);
149 * Support the old "large page" layout used for 1-bit Hamming ECC where ECC
150 * are placed at a fixed offset.
152 static int nand_ooblayout_ecc_lp_hamming(struct mtd_info *mtd, int section,
153 struct mtd_oob_region *oobregion)
155 struct nand_chip *chip = mtd_to_nand(mtd);
156 struct nand_ecc_ctrl *ecc = &chip->ecc;
161 switch (mtd->oobsize) {
163 oobregion->offset = 40;
166 oobregion->offset = 80;
172 oobregion->length = ecc->total;
173 if (oobregion->offset + oobregion->length > mtd->oobsize)
179 static int nand_ooblayout_free_lp_hamming(struct mtd_info *mtd, int section,
180 struct mtd_oob_region *oobregion)
182 struct nand_chip *chip = mtd_to_nand(mtd);
183 struct nand_ecc_ctrl *ecc = &chip->ecc;
186 if (section < 0 || section > 1)
189 switch (mtd->oobsize) {
201 oobregion->offset = 2;
202 oobregion->length = ecc_offset - 2;
204 oobregion->offset = ecc_offset + ecc->total;
205 oobregion->length = mtd->oobsize - oobregion->offset;
211 static const struct mtd_ooblayout_ops nand_ooblayout_lp_hamming_ops = {
212 .ecc = nand_ooblayout_ecc_lp_hamming,
213 .free = nand_ooblayout_free_lp_hamming,
216 static int check_offs_len(struct mtd_info *mtd,
217 loff_t ofs, uint64_t len)
219 struct nand_chip *chip = mtd_to_nand(mtd);
222 /* Start address must align on block boundary */
223 if (ofs & ((1ULL << chip->phys_erase_shift) - 1)) {
224 pr_debug("%s: unaligned address\n", __func__);
228 /* Length must align on block boundary */
229 if (len & ((1ULL << chip->phys_erase_shift) - 1)) {
230 pr_debug("%s: length not block aligned\n", __func__);
238 * nand_release_device - [GENERIC] release chip
239 * @mtd: MTD device structure
241 * Release chip lock and wake up anyone waiting on the device.
243 static void nand_release_device(struct mtd_info *mtd)
245 struct nand_chip *chip = mtd_to_nand(mtd);
247 /* Release the controller and the chip */
248 spin_lock(&chip->controller->lock);
249 chip->controller->active = NULL;
250 chip->state = FL_READY;
251 wake_up(&chip->controller->wq);
252 spin_unlock(&chip->controller->lock);
256 * nand_read_byte - [DEFAULT] read one byte from the chip
257 * @mtd: MTD device structure
259 * Default read function for 8bit buswidth
261 static uint8_t nand_read_byte(struct mtd_info *mtd)
263 struct nand_chip *chip = mtd_to_nand(mtd);
264 return readb(chip->IO_ADDR_R);
268 * nand_read_byte16 - [DEFAULT] read one byte endianness aware from the chip
269 * @mtd: MTD device structure
271 * Default read function for 16bit buswidth with endianness conversion.
274 static uint8_t nand_read_byte16(struct mtd_info *mtd)
276 struct nand_chip *chip = mtd_to_nand(mtd);
277 return (uint8_t) cpu_to_le16(readw(chip->IO_ADDR_R));
281 * nand_read_word - [DEFAULT] read one word from the chip
282 * @mtd: MTD device structure
284 * Default read function for 16bit buswidth without endianness conversion.
286 static u16 nand_read_word(struct mtd_info *mtd)
288 struct nand_chip *chip = mtd_to_nand(mtd);
289 return readw(chip->IO_ADDR_R);
293 * nand_select_chip - [DEFAULT] control CE line
294 * @mtd: MTD device structure
295 * @chipnr: chipnumber to select, -1 for deselect
297 * Default select function for 1 chip devices.
299 static void nand_select_chip(struct mtd_info *mtd, int chipnr)
301 struct nand_chip *chip = mtd_to_nand(mtd);
305 chip->cmd_ctrl(mtd, NAND_CMD_NONE, 0 | NAND_CTRL_CHANGE);
316 * nand_write_byte - [DEFAULT] write single byte to chip
317 * @mtd: MTD device structure
318 * @byte: value to write
320 * Default function to write a byte to I/O[7:0]
322 static void nand_write_byte(struct mtd_info *mtd, uint8_t byte)
324 struct nand_chip *chip = mtd_to_nand(mtd);
326 chip->write_buf(mtd, &byte, 1);
330 * nand_write_byte16 - [DEFAULT] write single byte to a chip with width 16
331 * @mtd: MTD device structure
332 * @byte: value to write
334 * Default function to write a byte to I/O[7:0] on a 16-bit wide chip.
336 static void nand_write_byte16(struct mtd_info *mtd, uint8_t byte)
338 struct nand_chip *chip = mtd_to_nand(mtd);
339 uint16_t word = byte;
342 * It's not entirely clear what should happen to I/O[15:8] when writing
343 * a byte. The ONFi spec (Revision 3.1; 2012-09-19, Section 2.16) reads:
345 * When the host supports a 16-bit bus width, only data is
346 * transferred at the 16-bit width. All address and command line
347 * transfers shall use only the lower 8-bits of the data bus. During
348 * command transfers, the host may place any value on the upper
349 * 8-bits of the data bus. During address transfers, the host shall
350 * set the upper 8-bits of the data bus to 00h.
352 * One user of the write_byte callback is nand_onfi_set_features. The
353 * four parameters are specified to be written to I/O[7:0], but this is
354 * neither an address nor a command transfer. Let's assume a 0 on the
355 * upper I/O lines is OK.
357 chip->write_buf(mtd, (uint8_t *)&word, 2);
361 * nand_write_buf - [DEFAULT] write buffer to chip
362 * @mtd: MTD device structure
364 * @len: number of bytes to write
366 * Default write function for 8bit buswidth.
368 static void nand_write_buf(struct mtd_info *mtd, const uint8_t *buf, int len)
370 struct nand_chip *chip = mtd_to_nand(mtd);
372 iowrite8_rep(chip->IO_ADDR_W, buf, len);
376 * nand_read_buf - [DEFAULT] read chip data into buffer
377 * @mtd: MTD device structure
378 * @buf: buffer to store date
379 * @len: number of bytes to read
381 * Default read function for 8bit buswidth.
383 static void nand_read_buf(struct mtd_info *mtd, uint8_t *buf, int len)
385 struct nand_chip *chip = mtd_to_nand(mtd);
387 ioread8_rep(chip->IO_ADDR_R, buf, len);
391 * nand_write_buf16 - [DEFAULT] write buffer to chip
392 * @mtd: MTD device structure
394 * @len: number of bytes to write
396 * Default write function for 16bit buswidth.
398 static void nand_write_buf16(struct mtd_info *mtd, const uint8_t *buf, int len)
400 struct nand_chip *chip = mtd_to_nand(mtd);
401 u16 *p = (u16 *) buf;
403 iowrite16_rep(chip->IO_ADDR_W, p, len >> 1);
407 * nand_read_buf16 - [DEFAULT] read chip data into buffer
408 * @mtd: MTD device structure
409 * @buf: buffer to store date
410 * @len: number of bytes to read
412 * Default read function for 16bit buswidth.
414 static void nand_read_buf16(struct mtd_info *mtd, uint8_t *buf, int len)
416 struct nand_chip *chip = mtd_to_nand(mtd);
417 u16 *p = (u16 *) buf;
419 ioread16_rep(chip->IO_ADDR_R, p, len >> 1);
423 * nand_block_bad - [DEFAULT] Read bad block marker from the chip
424 * @mtd: MTD device structure
425 * @ofs: offset from device start
427 * Check, if the block is bad.
429 static int nand_block_bad(struct mtd_info *mtd, loff_t ofs)
431 int page, page_end, res;
432 struct nand_chip *chip = mtd_to_nand(mtd);
435 if (chip->bbt_options & NAND_BBT_SCANLASTPAGE)
436 ofs += mtd->erasesize - mtd->writesize;
438 page = (int)(ofs >> chip->page_shift) & chip->pagemask;
439 page_end = page + (chip->bbt_options & NAND_BBT_SCAN2NDPAGE ? 2 : 1);
441 for (; page < page_end; page++) {
442 res = chip->ecc.read_oob(mtd, chip, page);
446 bad = chip->oob_poi[chip->badblockpos];
448 if (likely(chip->badblockbits == 8))
451 res = hweight8(bad) < chip->badblockbits;
460 * nand_default_block_markbad - [DEFAULT] mark a block bad via bad block marker
461 * @mtd: MTD device structure
462 * @ofs: offset from device start
464 * This is the default implementation, which can be overridden by a hardware
465 * specific driver. It provides the details for writing a bad block marker to a
468 static int nand_default_block_markbad(struct mtd_info *mtd, loff_t ofs)
470 struct nand_chip *chip = mtd_to_nand(mtd);
471 struct mtd_oob_ops ops;
472 uint8_t buf[2] = { 0, 0 };
473 int ret = 0, res, i = 0;
475 memset(&ops, 0, sizeof(ops));
477 ops.ooboffs = chip->badblockpos;
478 if (chip->options & NAND_BUSWIDTH_16) {
479 ops.ooboffs &= ~0x01;
480 ops.len = ops.ooblen = 2;
482 ops.len = ops.ooblen = 1;
484 ops.mode = MTD_OPS_PLACE_OOB;
486 /* Write to first/last page(s) if necessary */
487 if (chip->bbt_options & NAND_BBT_SCANLASTPAGE)
488 ofs += mtd->erasesize - mtd->writesize;
490 res = nand_do_write_oob(mtd, ofs, &ops);
495 ofs += mtd->writesize;
496 } while ((chip->bbt_options & NAND_BBT_SCAN2NDPAGE) && i < 2);
502 * nand_block_markbad_lowlevel - mark a block bad
503 * @mtd: MTD device structure
504 * @ofs: offset from device start
506 * This function performs the generic NAND bad block marking steps (i.e., bad
507 * block table(s) and/or marker(s)). We only allow the hardware driver to
508 * specify how to write bad block markers to OOB (chip->block_markbad).
510 * We try operations in the following order:
512 * (1) erase the affected block, to allow OOB marker to be written cleanly
513 * (2) write bad block marker to OOB area of affected block (unless flag
514 * NAND_BBT_NO_OOB_BBM is present)
517 * Note that we retain the first error encountered in (2) or (3), finish the
518 * procedures, and dump the error in the end.
520 static int nand_block_markbad_lowlevel(struct mtd_info *mtd, loff_t ofs)
522 struct nand_chip *chip = mtd_to_nand(mtd);
525 if (!(chip->bbt_options & NAND_BBT_NO_OOB_BBM)) {
526 struct erase_info einfo;
528 /* Attempt erase before marking OOB */
529 memset(&einfo, 0, sizeof(einfo));
532 einfo.len = 1ULL << chip->phys_erase_shift;
533 nand_erase_nand(mtd, &einfo, 0);
535 /* Write bad block marker to OOB */
536 nand_get_device(mtd, FL_WRITING);
537 ret = chip->block_markbad(mtd, ofs);
538 nand_release_device(mtd);
541 /* Mark block bad in BBT */
543 res = nand_markbad_bbt(mtd, ofs);
549 mtd->ecc_stats.badblocks++;
555 * nand_check_wp - [GENERIC] check if the chip is write protected
556 * @mtd: MTD device structure
558 * Check, if the device is write protected. The function expects, that the
559 * device is already selected.
561 static int nand_check_wp(struct mtd_info *mtd)
563 struct nand_chip *chip = mtd_to_nand(mtd);
565 /* Broken xD cards report WP despite being writable */
566 if (chip->options & NAND_BROKEN_XD)
569 /* Check the WP bit */
570 chip->cmdfunc(mtd, NAND_CMD_STATUS, -1, -1);
571 return (chip->read_byte(mtd) & NAND_STATUS_WP) ? 0 : 1;
575 * nand_block_isreserved - [GENERIC] Check if a block is marked reserved.
576 * @mtd: MTD device structure
577 * @ofs: offset from device start
579 * Check if the block is marked as reserved.
581 static int nand_block_isreserved(struct mtd_info *mtd, loff_t ofs)
583 struct nand_chip *chip = mtd_to_nand(mtd);
587 /* Return info from the table */
588 return nand_isreserved_bbt(mtd, ofs);
592 * nand_block_checkbad - [GENERIC] Check if a block is marked bad
593 * @mtd: MTD device structure
594 * @ofs: offset from device start
595 * @allowbbt: 1, if its allowed to access the bbt area
597 * Check, if the block is bad. Either by reading the bad block table or
598 * calling of the scan function.
600 static int nand_block_checkbad(struct mtd_info *mtd, loff_t ofs, int allowbbt)
602 struct nand_chip *chip = mtd_to_nand(mtd);
605 return chip->block_bad(mtd, ofs);
607 /* Return info from the table */
608 return nand_isbad_bbt(mtd, ofs, allowbbt);
612 * panic_nand_wait_ready - [GENERIC] Wait for the ready pin after commands.
613 * @mtd: MTD device structure
616 * Helper function for nand_wait_ready used when needing to wait in interrupt
619 static void panic_nand_wait_ready(struct mtd_info *mtd, unsigned long timeo)
621 struct nand_chip *chip = mtd_to_nand(mtd);
624 /* Wait for the device to get ready */
625 for (i = 0; i < timeo; i++) {
626 if (chip->dev_ready(mtd))
628 touch_softlockup_watchdog();
634 * nand_wait_ready - [GENERIC] Wait for the ready pin after commands.
635 * @mtd: MTD device structure
637 * Wait for the ready pin after a command, and warn if a timeout occurs.
639 void nand_wait_ready(struct mtd_info *mtd)
641 struct nand_chip *chip = mtd_to_nand(mtd);
642 unsigned long timeo = 400;
644 if (in_interrupt() || oops_in_progress)
645 return panic_nand_wait_ready(mtd, timeo);
647 /* Wait until command is processed or timeout occurs */
648 timeo = jiffies + msecs_to_jiffies(timeo);
650 if (chip->dev_ready(mtd))
653 } while (time_before(jiffies, timeo));
655 if (!chip->dev_ready(mtd))
656 pr_warn_ratelimited("timeout while waiting for chip to become ready\n");
658 EXPORT_SYMBOL_GPL(nand_wait_ready);
661 * nand_wait_status_ready - [GENERIC] Wait for the ready status after commands.
662 * @mtd: MTD device structure
663 * @timeo: Timeout in ms
665 * Wait for status ready (i.e. command done) or timeout.
667 static void nand_wait_status_ready(struct mtd_info *mtd, unsigned long timeo)
669 register struct nand_chip *chip = mtd_to_nand(mtd);
671 timeo = jiffies + msecs_to_jiffies(timeo);
673 if ((chip->read_byte(mtd) & NAND_STATUS_READY))
675 touch_softlockup_watchdog();
676 } while (time_before(jiffies, timeo));
680 * nand_command - [DEFAULT] Send command to NAND device
681 * @mtd: MTD device structure
682 * @command: the command to be sent
683 * @column: the column address for this command, -1 if none
684 * @page_addr: the page address for this command, -1 if none
686 * Send command to NAND device. This function is used for small page devices
687 * (512 Bytes per page).
689 static void nand_command(struct mtd_info *mtd, unsigned int command,
690 int column, int page_addr)
692 register struct nand_chip *chip = mtd_to_nand(mtd);
693 int ctrl = NAND_CTRL_CLE | NAND_CTRL_CHANGE;
695 /* Write out the command to the device */
696 if (command == NAND_CMD_SEQIN) {
699 if (column >= mtd->writesize) {
701 column -= mtd->writesize;
702 readcmd = NAND_CMD_READOOB;
703 } else if (column < 256) {
704 /* First 256 bytes --> READ0 */
705 readcmd = NAND_CMD_READ0;
708 readcmd = NAND_CMD_READ1;
710 chip->cmd_ctrl(mtd, readcmd, ctrl);
711 ctrl &= ~NAND_CTRL_CHANGE;
713 chip->cmd_ctrl(mtd, command, ctrl);
715 /* Address cycle, when necessary */
716 ctrl = NAND_CTRL_ALE | NAND_CTRL_CHANGE;
717 /* Serially input address */
719 /* Adjust columns for 16 bit buswidth */
720 if (chip->options & NAND_BUSWIDTH_16 &&
721 !nand_opcode_8bits(command))
723 chip->cmd_ctrl(mtd, column, ctrl);
724 ctrl &= ~NAND_CTRL_CHANGE;
726 if (page_addr != -1) {
727 chip->cmd_ctrl(mtd, page_addr, ctrl);
728 ctrl &= ~NAND_CTRL_CHANGE;
729 chip->cmd_ctrl(mtd, page_addr >> 8, ctrl);
730 if (chip->options & NAND_ROW_ADDR_3)
731 chip->cmd_ctrl(mtd, page_addr >> 16, ctrl);
733 chip->cmd_ctrl(mtd, NAND_CMD_NONE, NAND_NCE | NAND_CTRL_CHANGE);
736 * Program and erase have their own busy handlers status and sequential
741 case NAND_CMD_PAGEPROG:
742 case NAND_CMD_ERASE1:
743 case NAND_CMD_ERASE2:
745 case NAND_CMD_STATUS:
746 case NAND_CMD_READID:
747 case NAND_CMD_SET_FEATURES:
753 udelay(chip->chip_delay);
754 chip->cmd_ctrl(mtd, NAND_CMD_STATUS,
755 NAND_CTRL_CLE | NAND_CTRL_CHANGE);
757 NAND_CMD_NONE, NAND_NCE | NAND_CTRL_CHANGE);
758 /* EZ-NAND can take upto 250ms as per ONFi v4.0 */
759 nand_wait_status_ready(mtd, 250);
762 /* This applies to read commands */
765 * READ0 is sometimes used to exit GET STATUS mode. When this
766 * is the case no address cycles are requested, and we can use
767 * this information to detect that we should not wait for the
768 * device to be ready.
770 if (column == -1 && page_addr == -1)
775 * If we don't have access to the busy pin, we apply the given
778 if (!chip->dev_ready) {
779 udelay(chip->chip_delay);
784 * Apply this short delay always to ensure that we do wait tWB in
785 * any case on any machine.
789 nand_wait_ready(mtd);
792 static void nand_ccs_delay(struct nand_chip *chip)
795 * The controller already takes care of waiting for tCCS when the RNDIN
796 * or RNDOUT command is sent, return directly.
798 if (!(chip->options & NAND_WAIT_TCCS))
802 * Wait tCCS_min if it is correctly defined, otherwise wait 500ns
803 * (which should be safe for all NANDs).
805 if (chip->data_interface && chip->data_interface->timings.sdr.tCCS_min)
806 ndelay(chip->data_interface->timings.sdr.tCCS_min / 1000);
812 * nand_command_lp - [DEFAULT] Send command to NAND large page device
813 * @mtd: MTD device structure
814 * @command: the command to be sent
815 * @column: the column address for this command, -1 if none
816 * @page_addr: the page address for this command, -1 if none
818 * Send command to NAND device. This is the version for the new large page
819 * devices. We don't have the separate regions as we have in the small page
820 * devices. We must emulate NAND_CMD_READOOB to keep the code compatible.
822 static void nand_command_lp(struct mtd_info *mtd, unsigned int command,
823 int column, int page_addr)
825 register struct nand_chip *chip = mtd_to_nand(mtd);
827 /* Emulate NAND_CMD_READOOB */
828 if (command == NAND_CMD_READOOB) {
829 column += mtd->writesize;
830 command = NAND_CMD_READ0;
833 /* Command latch cycle */
834 chip->cmd_ctrl(mtd, command, NAND_NCE | NAND_CLE | NAND_CTRL_CHANGE);
836 if (column != -1 || page_addr != -1) {
837 int ctrl = NAND_CTRL_CHANGE | NAND_NCE | NAND_ALE;
839 /* Serially input address */
841 /* Adjust columns for 16 bit buswidth */
842 if (chip->options & NAND_BUSWIDTH_16 &&
843 !nand_opcode_8bits(command))
845 chip->cmd_ctrl(mtd, column, ctrl);
846 ctrl &= ~NAND_CTRL_CHANGE;
848 /* Only output a single addr cycle for 8bits opcodes. */
849 if (!nand_opcode_8bits(command))
850 chip->cmd_ctrl(mtd, column >> 8, ctrl);
852 if (page_addr != -1) {
853 chip->cmd_ctrl(mtd, page_addr, ctrl);
854 chip->cmd_ctrl(mtd, page_addr >> 8,
855 NAND_NCE | NAND_ALE);
856 if (chip->options & NAND_ROW_ADDR_3)
857 chip->cmd_ctrl(mtd, page_addr >> 16,
858 NAND_NCE | NAND_ALE);
861 chip->cmd_ctrl(mtd, NAND_CMD_NONE, NAND_NCE | NAND_CTRL_CHANGE);
864 * Program and erase have their own busy handlers status, sequential
865 * in and status need no delay.
869 case NAND_CMD_CACHEDPROG:
870 case NAND_CMD_PAGEPROG:
871 case NAND_CMD_ERASE1:
872 case NAND_CMD_ERASE2:
874 case NAND_CMD_STATUS:
875 case NAND_CMD_READID:
876 case NAND_CMD_SET_FEATURES:
880 nand_ccs_delay(chip);
886 udelay(chip->chip_delay);
887 chip->cmd_ctrl(mtd, NAND_CMD_STATUS,
888 NAND_NCE | NAND_CLE | NAND_CTRL_CHANGE);
889 chip->cmd_ctrl(mtd, NAND_CMD_NONE,
890 NAND_NCE | NAND_CTRL_CHANGE);
891 /* EZ-NAND can take upto 250ms as per ONFi v4.0 */
892 nand_wait_status_ready(mtd, 250);
895 case NAND_CMD_RNDOUT:
896 /* No ready / busy check necessary */
897 chip->cmd_ctrl(mtd, NAND_CMD_RNDOUTSTART,
898 NAND_NCE | NAND_CLE | NAND_CTRL_CHANGE);
899 chip->cmd_ctrl(mtd, NAND_CMD_NONE,
900 NAND_NCE | NAND_CTRL_CHANGE);
902 nand_ccs_delay(chip);
907 * READ0 is sometimes used to exit GET STATUS mode. When this
908 * is the case no address cycles are requested, and we can use
909 * this information to detect that READSTART should not be
912 if (column == -1 && page_addr == -1)
915 chip->cmd_ctrl(mtd, NAND_CMD_READSTART,
916 NAND_NCE | NAND_CLE | NAND_CTRL_CHANGE);
917 chip->cmd_ctrl(mtd, NAND_CMD_NONE,
918 NAND_NCE | NAND_CTRL_CHANGE);
920 /* This applies to read commands */
923 * If we don't have access to the busy pin, we apply the given
926 if (!chip->dev_ready) {
927 udelay(chip->chip_delay);
933 * Apply this short delay always to ensure that we do wait tWB in
934 * any case on any machine.
938 nand_wait_ready(mtd);
942 * panic_nand_get_device - [GENERIC] Get chip for selected access
943 * @chip: the nand chip descriptor
944 * @mtd: MTD device structure
945 * @new_state: the state which is requested
947 * Used when in panic, no locks are taken.
949 static void panic_nand_get_device(struct nand_chip *chip,
950 struct mtd_info *mtd, int new_state)
952 /* Hardware controller shared among independent devices */
953 chip->controller->active = chip;
954 chip->state = new_state;
958 * nand_get_device - [GENERIC] Get chip for selected access
959 * @mtd: MTD device structure
960 * @new_state: the state which is requested
962 * Get the device and lock it for exclusive access
965 nand_get_device(struct mtd_info *mtd, int new_state)
967 struct nand_chip *chip = mtd_to_nand(mtd);
968 spinlock_t *lock = &chip->controller->lock;
969 wait_queue_head_t *wq = &chip->controller->wq;
970 DECLARE_WAITQUEUE(wait, current);
974 /* Hardware controller shared among independent devices */
975 if (!chip->controller->active)
976 chip->controller->active = chip;
978 if (chip->controller->active == chip && chip->state == FL_READY) {
979 chip->state = new_state;
983 if (new_state == FL_PM_SUSPENDED) {
984 if (chip->controller->active->state == FL_PM_SUSPENDED) {
985 chip->state = FL_PM_SUSPENDED;
990 set_current_state(TASK_UNINTERRUPTIBLE);
991 add_wait_queue(wq, &wait);
994 remove_wait_queue(wq, &wait);
999 * panic_nand_wait - [GENERIC] wait until the command is done
1000 * @mtd: MTD device structure
1001 * @chip: NAND chip structure
1004 * Wait for command done. This is a helper function for nand_wait used when
1005 * we are in interrupt context. May happen when in panic and trying to write
1006 * an oops through mtdoops.
1008 static void panic_nand_wait(struct mtd_info *mtd, struct nand_chip *chip,
1009 unsigned long timeo)
1012 for (i = 0; i < timeo; i++) {
1013 if (chip->dev_ready) {
1014 if (chip->dev_ready(mtd))
1017 if (chip->read_byte(mtd) & NAND_STATUS_READY)
1025 * nand_wait - [DEFAULT] wait until the command is done
1026 * @mtd: MTD device structure
1027 * @chip: NAND chip structure
1029 * Wait for command done. This applies to erase and program only.
1031 static int nand_wait(struct mtd_info *mtd, struct nand_chip *chip)
1035 unsigned long timeo = 400;
1038 * Apply this short delay always to ensure that we do wait tWB in any
1039 * case on any machine.
1043 chip->cmdfunc(mtd, NAND_CMD_STATUS, -1, -1);
1045 if (in_interrupt() || oops_in_progress)
1046 panic_nand_wait(mtd, chip, timeo);
1048 timeo = jiffies + msecs_to_jiffies(timeo);
1050 if (chip->dev_ready) {
1051 if (chip->dev_ready(mtd))
1054 if (chip->read_byte(mtd) & NAND_STATUS_READY)
1058 } while (time_before(jiffies, timeo));
1061 status = (int)chip->read_byte(mtd);
1062 /* This can happen if in case of timeout or buggy dev_ready */
1063 WARN_ON(!(status & NAND_STATUS_READY));
1068 * nand_reset_data_interface - Reset data interface and timings
1069 * @chip: The NAND chip
1070 * @chipnr: Internal die id
1072 * Reset the Data interface and timings to ONFI mode 0.
1074 * Returns 0 for success or negative error code otherwise.
1076 static int nand_reset_data_interface(struct nand_chip *chip, int chipnr)
1078 struct mtd_info *mtd = nand_to_mtd(chip);
1079 const struct nand_data_interface *conf;
1082 if (!chip->setup_data_interface)
1086 * The ONFI specification says:
1088 * To transition from NV-DDR or NV-DDR2 to the SDR data
1089 * interface, the host shall use the Reset (FFh) command
1090 * using SDR timing mode 0. A device in any timing mode is
1091 * required to recognize Reset (FFh) command issued in SDR
1095 * Configure the data interface in SDR mode and set the
1096 * timings to timing mode 0.
1099 conf = nand_get_default_data_interface();
1100 ret = chip->setup_data_interface(mtd, chipnr, conf);
1102 pr_err("Failed to configure data interface to SDR timing mode 0\n");
1108 * nand_setup_data_interface - Setup the best data interface and timings
1109 * @chip: The NAND chip
1110 * @chipnr: Internal die id
1112 * Find and configure the best data interface and NAND timings supported by
1113 * the chip and the driver.
1114 * First tries to retrieve supported timing modes from ONFI information,
1115 * and if the NAND chip does not support ONFI, relies on the
1116 * ->onfi_timing_mode_default specified in the nand_ids table.
1118 * Returns 0 for success or negative error code otherwise.
1120 static int nand_setup_data_interface(struct nand_chip *chip, int chipnr)
1122 struct mtd_info *mtd = nand_to_mtd(chip);
1125 if (!chip->setup_data_interface || !chip->data_interface)
1129 * Ensure the timing mode has been changed on the chip side
1130 * before changing timings on the controller side.
1132 if (chip->onfi_version &&
1133 (le16_to_cpu(chip->onfi_params.opt_cmd) &
1134 ONFI_OPT_CMD_SET_GET_FEATURES)) {
1135 u8 tmode_param[ONFI_SUBFEATURE_PARAM_LEN] = {
1136 chip->onfi_timing_mode_default,
1139 ret = chip->onfi_set_features(mtd, chip,
1140 ONFI_FEATURE_ADDR_TIMING_MODE,
1146 ret = chip->setup_data_interface(mtd, chipnr, chip->data_interface);
1152 * nand_init_data_interface - find the best data interface and timings
1153 * @chip: The NAND chip
1155 * Find the best data interface and NAND timings supported by the chip
1157 * First tries to retrieve supported timing modes from ONFI information,
1158 * and if the NAND chip does not support ONFI, relies on the
1159 * ->onfi_timing_mode_default specified in the nand_ids table. After this
1160 * function nand_chip->data_interface is initialized with the best timing mode
1163 * Returns 0 for success or negative error code otherwise.
1165 static int nand_init_data_interface(struct nand_chip *chip)
1167 struct mtd_info *mtd = nand_to_mtd(chip);
1168 int modes, mode, ret;
1170 if (!chip->setup_data_interface)
1174 * First try to identify the best timings from ONFI parameters and
1175 * if the NAND does not support ONFI, fallback to the default ONFI
1178 modes = onfi_get_async_timing_mode(chip);
1179 if (modes == ONFI_TIMING_MODE_UNKNOWN) {
1180 if (!chip->onfi_timing_mode_default)
1183 modes = GENMASK(chip->onfi_timing_mode_default, 0);
1186 chip->data_interface = kzalloc(sizeof(*chip->data_interface),
1188 if (!chip->data_interface)
1191 for (mode = fls(modes) - 1; mode >= 0; mode--) {
1192 ret = onfi_init_data_interface(chip, chip->data_interface,
1193 NAND_SDR_IFACE, mode);
1197 /* Pass -1 to only */
1198 ret = chip->setup_data_interface(mtd,
1199 NAND_DATA_IFACE_CHECK_ONLY,
1200 chip->data_interface);
1202 chip->onfi_timing_mode_default = mode;
1210 static void nand_release_data_interface(struct nand_chip *chip)
1212 kfree(chip->data_interface);
1216 * nand_reset - Reset and initialize a NAND device
1217 * @chip: The NAND chip
1218 * @chipnr: Internal die id
1220 * Returns 0 for success or negative error code otherwise
1222 int nand_reset(struct nand_chip *chip, int chipnr)
1224 struct mtd_info *mtd = nand_to_mtd(chip);
1227 ret = nand_reset_data_interface(chip, chipnr);
1232 * The CS line has to be released before we can apply the new NAND
1233 * interface settings, hence this weird ->select_chip() dance.
1235 chip->select_chip(mtd, chipnr);
1236 chip->cmdfunc(mtd, NAND_CMD_RESET, -1, -1);
1237 chip->select_chip(mtd, -1);
1239 chip->select_chip(mtd, chipnr);
1240 ret = nand_setup_data_interface(chip, chipnr);
1241 chip->select_chip(mtd, -1);
1247 EXPORT_SYMBOL_GPL(nand_reset);
1250 * nand_check_erased_buf - check if a buffer contains (almost) only 0xff data
1251 * @buf: buffer to test
1252 * @len: buffer length
1253 * @bitflips_threshold: maximum number of bitflips
1255 * Check if a buffer contains only 0xff, which means the underlying region
1256 * has been erased and is ready to be programmed.
1257 * The bitflips_threshold specify the maximum number of bitflips before
1258 * considering the region is not erased.
1259 * Note: The logic of this function has been extracted from the memweight
1260 * implementation, except that nand_check_erased_buf function exit before
1261 * testing the whole buffer if the number of bitflips exceed the
1262 * bitflips_threshold value.
1264 * Returns a positive number of bitflips less than or equal to
1265 * bitflips_threshold, or -ERROR_CODE for bitflips in excess of the
1268 static int nand_check_erased_buf(void *buf, int len, int bitflips_threshold)
1270 const unsigned char *bitmap = buf;
1274 for (; len && ((uintptr_t)bitmap) % sizeof(long);
1276 weight = hweight8(*bitmap);
1277 bitflips += BITS_PER_BYTE - weight;
1278 if (unlikely(bitflips > bitflips_threshold))
1282 for (; len >= sizeof(long);
1283 len -= sizeof(long), bitmap += sizeof(long)) {
1284 unsigned long d = *((unsigned long *)bitmap);
1287 weight = hweight_long(d);
1288 bitflips += BITS_PER_LONG - weight;
1289 if (unlikely(bitflips > bitflips_threshold))
1293 for (; len > 0; len--, bitmap++) {
1294 weight = hweight8(*bitmap);
1295 bitflips += BITS_PER_BYTE - weight;
1296 if (unlikely(bitflips > bitflips_threshold))
1304 * nand_check_erased_ecc_chunk - check if an ECC chunk contains (almost) only
1306 * @data: data buffer to test
1307 * @datalen: data length
1309 * @ecclen: ECC length
1310 * @extraoob: extra OOB buffer
1311 * @extraooblen: extra OOB length
1312 * @bitflips_threshold: maximum number of bitflips
1314 * Check if a data buffer and its associated ECC and OOB data contains only
1315 * 0xff pattern, which means the underlying region has been erased and is
1316 * ready to be programmed.
1317 * The bitflips_threshold specify the maximum number of bitflips before
1318 * considering the region as not erased.
1321 * 1/ ECC algorithms are working on pre-defined block sizes which are usually
1322 * different from the NAND page size. When fixing bitflips, ECC engines will
1323 * report the number of errors per chunk, and the NAND core infrastructure
1324 * expect you to return the maximum number of bitflips for the whole page.
1325 * This is why you should always use this function on a single chunk and
1326 * not on the whole page. After checking each chunk you should update your
1327 * max_bitflips value accordingly.
1328 * 2/ When checking for bitflips in erased pages you should not only check
1329 * the payload data but also their associated ECC data, because a user might
1330 * have programmed almost all bits to 1 but a few. In this case, we
1331 * shouldn't consider the chunk as erased, and checking ECC bytes prevent
1333 * 3/ The extraoob argument is optional, and should be used if some of your OOB
1334 * data are protected by the ECC engine.
1335 * It could also be used if you support subpages and want to attach some
1336 * extra OOB data to an ECC chunk.
1338 * Returns a positive number of bitflips less than or equal to
1339 * bitflips_threshold, or -ERROR_CODE for bitflips in excess of the
1340 * threshold. In case of success, the passed buffers are filled with 0xff.
1342 int nand_check_erased_ecc_chunk(void *data, int datalen,
1343 void *ecc, int ecclen,
1344 void *extraoob, int extraooblen,
1345 int bitflips_threshold)
1347 int data_bitflips = 0, ecc_bitflips = 0, extraoob_bitflips = 0;
1349 data_bitflips = nand_check_erased_buf(data, datalen,
1350 bitflips_threshold);
1351 if (data_bitflips < 0)
1352 return data_bitflips;
1354 bitflips_threshold -= data_bitflips;
1356 ecc_bitflips = nand_check_erased_buf(ecc, ecclen, bitflips_threshold);
1357 if (ecc_bitflips < 0)
1358 return ecc_bitflips;
1360 bitflips_threshold -= ecc_bitflips;
1362 extraoob_bitflips = nand_check_erased_buf(extraoob, extraooblen,
1363 bitflips_threshold);
1364 if (extraoob_bitflips < 0)
1365 return extraoob_bitflips;
1368 memset(data, 0xff, datalen);
1371 memset(ecc, 0xff, ecclen);
1373 if (extraoob_bitflips)
1374 memset(extraoob, 0xff, extraooblen);
1376 return data_bitflips + ecc_bitflips + extraoob_bitflips;
1378 EXPORT_SYMBOL(nand_check_erased_ecc_chunk);
1381 * nand_read_page_raw - [INTERN] read raw page data without ecc
1382 * @mtd: mtd info structure
1383 * @chip: nand chip info structure
1384 * @buf: buffer to store read data
1385 * @oob_required: caller requires OOB data read to chip->oob_poi
1386 * @page: page number to read
1388 * Not for syndrome calculating ECC controllers, which use a special oob layout.
1390 int nand_read_page_raw(struct mtd_info *mtd, struct nand_chip *chip,
1391 uint8_t *buf, int oob_required, int page)
1393 chip->read_buf(mtd, buf, mtd->writesize);
1395 chip->read_buf(mtd, chip->oob_poi, mtd->oobsize);
1398 EXPORT_SYMBOL(nand_read_page_raw);
1401 * nand_read_page_raw_syndrome - [INTERN] read raw page data without ecc
1402 * @mtd: mtd info structure
1403 * @chip: nand chip info structure
1404 * @buf: buffer to store read data
1405 * @oob_required: caller requires OOB data read to chip->oob_poi
1406 * @page: page number to read
1408 * We need a special oob layout and handling even when OOB isn't used.
1410 static int nand_read_page_raw_syndrome(struct mtd_info *mtd,
1411 struct nand_chip *chip, uint8_t *buf,
1412 int oob_required, int page)
1414 int eccsize = chip->ecc.size;
1415 int eccbytes = chip->ecc.bytes;
1416 uint8_t *oob = chip->oob_poi;
1419 for (steps = chip->ecc.steps; steps > 0; steps--) {
1420 chip->read_buf(mtd, buf, eccsize);
1423 if (chip->ecc.prepad) {
1424 chip->read_buf(mtd, oob, chip->ecc.prepad);
1425 oob += chip->ecc.prepad;
1428 chip->read_buf(mtd, oob, eccbytes);
1431 if (chip->ecc.postpad) {
1432 chip->read_buf(mtd, oob, chip->ecc.postpad);
1433 oob += chip->ecc.postpad;
1437 size = mtd->oobsize - (oob - chip->oob_poi);
1439 chip->read_buf(mtd, oob, size);
1445 * nand_read_page_swecc - [REPLACEABLE] software ECC based page read function
1446 * @mtd: mtd info structure
1447 * @chip: nand chip info structure
1448 * @buf: buffer to store read data
1449 * @oob_required: caller requires OOB data read to chip->oob_poi
1450 * @page: page number to read
1452 static int nand_read_page_swecc(struct mtd_info *mtd, struct nand_chip *chip,
1453 uint8_t *buf, int oob_required, int page)
1455 int i, eccsize = chip->ecc.size, ret;
1456 int eccbytes = chip->ecc.bytes;
1457 int eccsteps = chip->ecc.steps;
1459 uint8_t *ecc_calc = chip->buffers->ecccalc;
1460 uint8_t *ecc_code = chip->buffers->ecccode;
1461 unsigned int max_bitflips = 0;
1463 chip->ecc.read_page_raw(mtd, chip, buf, 1, page);
1465 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize)
1466 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
1468 ret = mtd_ooblayout_get_eccbytes(mtd, ecc_code, chip->oob_poi, 0,
1473 eccsteps = chip->ecc.steps;
1476 for (i = 0 ; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
1479 stat = chip->ecc.correct(mtd, p, &ecc_code[i], &ecc_calc[i]);
1481 mtd->ecc_stats.failed++;
1483 mtd->ecc_stats.corrected += stat;
1484 max_bitflips = max_t(unsigned int, max_bitflips, stat);
1487 return max_bitflips;
1491 * nand_read_subpage - [REPLACEABLE] ECC based sub-page read function
1492 * @mtd: mtd info structure
1493 * @chip: nand chip info structure
1494 * @data_offs: offset of requested data within the page
1495 * @readlen: data length
1496 * @bufpoi: buffer to store read data
1497 * @page: page number to read
1499 static int nand_read_subpage(struct mtd_info *mtd, struct nand_chip *chip,
1500 uint32_t data_offs, uint32_t readlen, uint8_t *bufpoi,
1503 int start_step, end_step, num_steps, ret;
1505 int data_col_addr, i, gaps = 0;
1506 int datafrag_len, eccfrag_len, aligned_len, aligned_pos;
1507 int busw = (chip->options & NAND_BUSWIDTH_16) ? 2 : 1;
1508 int index, section = 0;
1509 unsigned int max_bitflips = 0;
1510 struct mtd_oob_region oobregion = { };
1512 /* Column address within the page aligned to ECC size (256bytes) */
1513 start_step = data_offs / chip->ecc.size;
1514 end_step = (data_offs + readlen - 1) / chip->ecc.size;
1515 num_steps = end_step - start_step + 1;
1516 index = start_step * chip->ecc.bytes;
1518 /* Data size aligned to ECC ecc.size */
1519 datafrag_len = num_steps * chip->ecc.size;
1520 eccfrag_len = num_steps * chip->ecc.bytes;
1522 data_col_addr = start_step * chip->ecc.size;
1523 /* If we read not a page aligned data */
1524 if (data_col_addr != 0)
1525 chip->cmdfunc(mtd, NAND_CMD_RNDOUT, data_col_addr, -1);
1527 p = bufpoi + data_col_addr;
1528 chip->read_buf(mtd, p, datafrag_len);
1531 for (i = 0; i < eccfrag_len ; i += chip->ecc.bytes, p += chip->ecc.size)
1532 chip->ecc.calculate(mtd, p, &chip->buffers->ecccalc[i]);
1535 * The performance is faster if we position offsets according to
1536 * ecc.pos. Let's make sure that there are no gaps in ECC positions.
1538 ret = mtd_ooblayout_find_eccregion(mtd, index, §ion, &oobregion);
1542 if (oobregion.length < eccfrag_len)
1546 chip->cmdfunc(mtd, NAND_CMD_RNDOUT, mtd->writesize, -1);
1547 chip->read_buf(mtd, chip->oob_poi, mtd->oobsize);
1550 * Send the command to read the particular ECC bytes take care
1551 * about buswidth alignment in read_buf.
1553 aligned_pos = oobregion.offset & ~(busw - 1);
1554 aligned_len = eccfrag_len;
1555 if (oobregion.offset & (busw - 1))
1557 if ((oobregion.offset + (num_steps * chip->ecc.bytes)) &
1561 chip->cmdfunc(mtd, NAND_CMD_RNDOUT,
1562 mtd->writesize + aligned_pos, -1);
1563 chip->read_buf(mtd, &chip->oob_poi[aligned_pos], aligned_len);
1566 ret = mtd_ooblayout_get_eccbytes(mtd, chip->buffers->ecccode,
1567 chip->oob_poi, index, eccfrag_len);
1571 p = bufpoi + data_col_addr;
1572 for (i = 0; i < eccfrag_len ; i += chip->ecc.bytes, p += chip->ecc.size) {
1575 stat = chip->ecc.correct(mtd, p,
1576 &chip->buffers->ecccode[i], &chip->buffers->ecccalc[i]);
1577 if (stat == -EBADMSG &&
1578 (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
1579 /* check for empty pages with bitflips */
1580 stat = nand_check_erased_ecc_chunk(p, chip->ecc.size,
1581 &chip->buffers->ecccode[i],
1584 chip->ecc.strength);
1588 mtd->ecc_stats.failed++;
1590 mtd->ecc_stats.corrected += stat;
1591 max_bitflips = max_t(unsigned int, max_bitflips, stat);
1594 return max_bitflips;
1598 * nand_read_page_hwecc - [REPLACEABLE] hardware ECC based page read function
1599 * @mtd: mtd info structure
1600 * @chip: nand chip info structure
1601 * @buf: buffer to store read data
1602 * @oob_required: caller requires OOB data read to chip->oob_poi
1603 * @page: page number to read
1605 * Not for syndrome calculating ECC controllers which need a special oob layout.
1607 static int nand_read_page_hwecc(struct mtd_info *mtd, struct nand_chip *chip,
1608 uint8_t *buf, int oob_required, int page)
1610 int i, eccsize = chip->ecc.size, ret;
1611 int eccbytes = chip->ecc.bytes;
1612 int eccsteps = chip->ecc.steps;
1614 uint8_t *ecc_calc = chip->buffers->ecccalc;
1615 uint8_t *ecc_code = chip->buffers->ecccode;
1616 unsigned int max_bitflips = 0;
1618 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
1619 chip->ecc.hwctl(mtd, NAND_ECC_READ);
1620 chip->read_buf(mtd, p, eccsize);
1621 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
1623 chip->read_buf(mtd, chip->oob_poi, mtd->oobsize);
1625 ret = mtd_ooblayout_get_eccbytes(mtd, ecc_code, chip->oob_poi, 0,
1630 eccsteps = chip->ecc.steps;
1633 for (i = 0 ; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
1636 stat = chip->ecc.correct(mtd, p, &ecc_code[i], &ecc_calc[i]);
1637 if (stat == -EBADMSG &&
1638 (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
1639 /* check for empty pages with bitflips */
1640 stat = nand_check_erased_ecc_chunk(p, eccsize,
1641 &ecc_code[i], eccbytes,
1643 chip->ecc.strength);
1647 mtd->ecc_stats.failed++;
1649 mtd->ecc_stats.corrected += stat;
1650 max_bitflips = max_t(unsigned int, max_bitflips, stat);
1653 return max_bitflips;
1657 * nand_read_page_hwecc_oob_first - [REPLACEABLE] hw ecc, read oob first
1658 * @mtd: mtd info structure
1659 * @chip: nand chip info structure
1660 * @buf: buffer to store read data
1661 * @oob_required: caller requires OOB data read to chip->oob_poi
1662 * @page: page number to read
1664 * Hardware ECC for large page chips, require OOB to be read first. For this
1665 * ECC mode, the write_page method is re-used from ECC_HW. These methods
1666 * read/write ECC from the OOB area, unlike the ECC_HW_SYNDROME support with
1667 * multiple ECC steps, follows the "infix ECC" scheme and reads/writes ECC from
1668 * the data area, by overwriting the NAND manufacturer bad block markings.
1670 static int nand_read_page_hwecc_oob_first(struct mtd_info *mtd,
1671 struct nand_chip *chip, uint8_t *buf, int oob_required, int page)
1673 int i, eccsize = chip->ecc.size, ret;
1674 int eccbytes = chip->ecc.bytes;
1675 int eccsteps = chip->ecc.steps;
1677 uint8_t *ecc_code = chip->buffers->ecccode;
1678 uint8_t *ecc_calc = chip->buffers->ecccalc;
1679 unsigned int max_bitflips = 0;
1681 /* Read the OOB area first */
1682 chip->cmdfunc(mtd, NAND_CMD_READOOB, 0, page);
1683 chip->read_buf(mtd, chip->oob_poi, mtd->oobsize);
1684 chip->cmdfunc(mtd, NAND_CMD_READ0, 0, page);
1686 ret = mtd_ooblayout_get_eccbytes(mtd, ecc_code, chip->oob_poi, 0,
1691 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
1694 chip->ecc.hwctl(mtd, NAND_ECC_READ);
1695 chip->read_buf(mtd, p, eccsize);
1696 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
1698 stat = chip->ecc.correct(mtd, p, &ecc_code[i], NULL);
1699 if (stat == -EBADMSG &&
1700 (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
1701 /* check for empty pages with bitflips */
1702 stat = nand_check_erased_ecc_chunk(p, eccsize,
1703 &ecc_code[i], eccbytes,
1705 chip->ecc.strength);
1709 mtd->ecc_stats.failed++;
1711 mtd->ecc_stats.corrected += stat;
1712 max_bitflips = max_t(unsigned int, max_bitflips, stat);
1715 return max_bitflips;
1719 * nand_read_page_syndrome - [REPLACEABLE] hardware ECC syndrome based page read
1720 * @mtd: mtd info structure
1721 * @chip: nand chip info structure
1722 * @buf: buffer to store read data
1723 * @oob_required: caller requires OOB data read to chip->oob_poi
1724 * @page: page number to read
1726 * The hw generator calculates the error syndrome automatically. Therefore we
1727 * need a special oob layout and handling.
1729 static int nand_read_page_syndrome(struct mtd_info *mtd, struct nand_chip *chip,
1730 uint8_t *buf, int oob_required, int page)
1732 int i, eccsize = chip->ecc.size;
1733 int eccbytes = chip->ecc.bytes;
1734 int eccsteps = chip->ecc.steps;
1735 int eccpadbytes = eccbytes + chip->ecc.prepad + chip->ecc.postpad;
1737 uint8_t *oob = chip->oob_poi;
1738 unsigned int max_bitflips = 0;
1740 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
1743 chip->ecc.hwctl(mtd, NAND_ECC_READ);
1744 chip->read_buf(mtd, p, eccsize);
1746 if (chip->ecc.prepad) {
1747 chip->read_buf(mtd, oob, chip->ecc.prepad);
1748 oob += chip->ecc.prepad;
1751 chip->ecc.hwctl(mtd, NAND_ECC_READSYN);
1752 chip->read_buf(mtd, oob, eccbytes);
1753 stat = chip->ecc.correct(mtd, p, oob, NULL);
1757 if (chip->ecc.postpad) {
1758 chip->read_buf(mtd, oob, chip->ecc.postpad);
1759 oob += chip->ecc.postpad;
1762 if (stat == -EBADMSG &&
1763 (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
1764 /* check for empty pages with bitflips */
1765 stat = nand_check_erased_ecc_chunk(p, chip->ecc.size,
1769 chip->ecc.strength);
1773 mtd->ecc_stats.failed++;
1775 mtd->ecc_stats.corrected += stat;
1776 max_bitflips = max_t(unsigned int, max_bitflips, stat);
1780 /* Calculate remaining oob bytes */
1781 i = mtd->oobsize - (oob - chip->oob_poi);
1783 chip->read_buf(mtd, oob, i);
1785 return max_bitflips;
1789 * nand_transfer_oob - [INTERN] Transfer oob to client buffer
1790 * @mtd: mtd info structure
1791 * @oob: oob destination address
1792 * @ops: oob ops structure
1793 * @len: size of oob to transfer
1795 static uint8_t *nand_transfer_oob(struct mtd_info *mtd, uint8_t *oob,
1796 struct mtd_oob_ops *ops, size_t len)
1798 struct nand_chip *chip = mtd_to_nand(mtd);
1801 switch (ops->mode) {
1803 case MTD_OPS_PLACE_OOB:
1805 memcpy(oob, chip->oob_poi + ops->ooboffs, len);
1808 case MTD_OPS_AUTO_OOB:
1809 ret = mtd_ooblayout_get_databytes(mtd, oob, chip->oob_poi,
1821 * nand_setup_read_retry - [INTERN] Set the READ RETRY mode
1822 * @mtd: MTD device structure
1823 * @retry_mode: the retry mode to use
1825 * Some vendors supply a special command to shift the Vt threshold, to be used
1826 * when there are too many bitflips in a page (i.e., ECC error). After setting
1827 * a new threshold, the host should retry reading the page.
1829 static int nand_setup_read_retry(struct mtd_info *mtd, int retry_mode)
1831 struct nand_chip *chip = mtd_to_nand(mtd);
1833 pr_debug("setting READ RETRY mode %d\n", retry_mode);
1835 if (retry_mode >= chip->read_retries)
1838 if (!chip->setup_read_retry)
1841 return chip->setup_read_retry(mtd, retry_mode);
1845 * nand_do_read_ops - [INTERN] Read data with ECC
1846 * @mtd: MTD device structure
1847 * @from: offset to read from
1848 * @ops: oob ops structure
1850 * Internal function. Called with chip held.
1852 static int nand_do_read_ops(struct mtd_info *mtd, loff_t from,
1853 struct mtd_oob_ops *ops)
1855 int chipnr, page, realpage, col, bytes, aligned, oob_required;
1856 struct nand_chip *chip = mtd_to_nand(mtd);
1858 uint32_t readlen = ops->len;
1859 uint32_t oobreadlen = ops->ooblen;
1860 uint32_t max_oobsize = mtd_oobavail(mtd, ops);
1862 uint8_t *bufpoi, *oob, *buf;
1864 unsigned int max_bitflips = 0;
1866 bool ecc_fail = false;
1868 chipnr = (int)(from >> chip->chip_shift);
1869 chip->select_chip(mtd, chipnr);
1871 realpage = (int)(from >> chip->page_shift);
1872 page = realpage & chip->pagemask;
1874 col = (int)(from & (mtd->writesize - 1));
1878 oob_required = oob ? 1 : 0;
1881 unsigned int ecc_failures = mtd->ecc_stats.failed;
1883 bytes = min(mtd->writesize - col, readlen);
1884 aligned = (bytes == mtd->writesize);
1888 else if (chip->options & NAND_USE_BOUNCE_BUFFER)
1889 use_bufpoi = !virt_addr_valid(buf) ||
1890 !IS_ALIGNED((unsigned long)buf,
1895 /* Is the current page in the buffer? */
1896 if (realpage != chip->pagebuf || oob) {
1897 bufpoi = use_bufpoi ? chip->buffers->databuf : buf;
1899 if (use_bufpoi && aligned)
1900 pr_debug("%s: using read bounce buffer for buf@%p\n",
1904 if (nand_standard_page_accessors(&chip->ecc))
1905 chip->cmdfunc(mtd, NAND_CMD_READ0, 0x00, page);
1908 * Now read the page into the buffer. Absent an error,
1909 * the read methods return max bitflips per ecc step.
1911 if (unlikely(ops->mode == MTD_OPS_RAW))
1912 ret = chip->ecc.read_page_raw(mtd, chip, bufpoi,
1915 else if (!aligned && NAND_HAS_SUBPAGE_READ(chip) &&
1917 ret = chip->ecc.read_subpage(mtd, chip,
1921 ret = chip->ecc.read_page(mtd, chip, bufpoi,
1922 oob_required, page);
1925 /* Invalidate page cache */
1930 /* Transfer not aligned data */
1932 if (!NAND_HAS_SUBPAGE_READ(chip) && !oob &&
1933 !(mtd->ecc_stats.failed - ecc_failures) &&
1934 (ops->mode != MTD_OPS_RAW)) {
1935 chip->pagebuf = realpage;
1936 chip->pagebuf_bitflips = ret;
1938 /* Invalidate page cache */
1941 memcpy(buf, chip->buffers->databuf + col, bytes);
1944 if (unlikely(oob)) {
1945 int toread = min(oobreadlen, max_oobsize);
1948 oob = nand_transfer_oob(mtd,
1950 oobreadlen -= toread;
1954 if (chip->options & NAND_NEED_READRDY) {
1955 /* Apply delay or wait for ready/busy pin */
1956 if (!chip->dev_ready)
1957 udelay(chip->chip_delay);
1959 nand_wait_ready(mtd);
1962 if (mtd->ecc_stats.failed - ecc_failures) {
1963 if (retry_mode + 1 < chip->read_retries) {
1965 ret = nand_setup_read_retry(mtd,
1970 /* Reset failures; retry */
1971 mtd->ecc_stats.failed = ecc_failures;
1974 /* No more retry modes; real failure */
1980 max_bitflips = max_t(unsigned int, max_bitflips, ret);
1982 memcpy(buf, chip->buffers->databuf + col, bytes);
1984 max_bitflips = max_t(unsigned int, max_bitflips,
1985 chip->pagebuf_bitflips);
1990 /* Reset to retry mode 0 */
1992 ret = nand_setup_read_retry(mtd, 0);
2001 /* For subsequent reads align to page boundary */
2003 /* Increment page address */
2006 page = realpage & chip->pagemask;
2007 /* Check, if we cross a chip boundary */
2010 chip->select_chip(mtd, -1);
2011 chip->select_chip(mtd, chipnr);
2014 chip->select_chip(mtd, -1);
2016 ops->retlen = ops->len - (size_t) readlen;
2018 ops->oobretlen = ops->ooblen - oobreadlen;
2026 return max_bitflips;
2030 * nand_read - [MTD Interface] MTD compatibility function for nand_do_read_ecc
2031 * @mtd: MTD device structure
2032 * @from: offset to read from
2033 * @len: number of bytes to read
2034 * @retlen: pointer to variable to store the number of read bytes
2035 * @buf: the databuffer to put data
2037 * Get hold of the chip and call nand_do_read.
2039 static int nand_read(struct mtd_info *mtd, loff_t from, size_t len,
2040 size_t *retlen, uint8_t *buf)
2042 struct mtd_oob_ops ops;
2045 nand_get_device(mtd, FL_READING);
2046 memset(&ops, 0, sizeof(ops));
2049 ops.mode = MTD_OPS_PLACE_OOB;
2050 ret = nand_do_read_ops(mtd, from, &ops);
2051 *retlen = ops.retlen;
2052 nand_release_device(mtd);
2057 * nand_read_oob_std - [REPLACEABLE] the most common OOB data read function
2058 * @mtd: mtd info structure
2059 * @chip: nand chip info structure
2060 * @page: page number to read
2062 int nand_read_oob_std(struct mtd_info *mtd, struct nand_chip *chip, int page)
2064 chip->cmdfunc(mtd, NAND_CMD_READOOB, 0, page);
2065 chip->read_buf(mtd, chip->oob_poi, mtd->oobsize);
2068 EXPORT_SYMBOL(nand_read_oob_std);
2071 * nand_read_oob_syndrome - [REPLACEABLE] OOB data read function for HW ECC
2073 * @mtd: mtd info structure
2074 * @chip: nand chip info structure
2075 * @page: page number to read
2077 int nand_read_oob_syndrome(struct mtd_info *mtd, struct nand_chip *chip,
2080 int length = mtd->oobsize;
2081 int chunk = chip->ecc.bytes + chip->ecc.prepad + chip->ecc.postpad;
2082 int eccsize = chip->ecc.size;
2083 uint8_t *bufpoi = chip->oob_poi;
2084 int i, toread, sndrnd = 0, pos;
2086 chip->cmdfunc(mtd, NAND_CMD_READ0, chip->ecc.size, page);
2087 for (i = 0; i < chip->ecc.steps; i++) {
2089 pos = eccsize + i * (eccsize + chunk);
2090 if (mtd->writesize > 512)
2091 chip->cmdfunc(mtd, NAND_CMD_RNDOUT, pos, -1);
2093 chip->cmdfunc(mtd, NAND_CMD_READ0, pos, page);
2096 toread = min_t(int, length, chunk);
2097 chip->read_buf(mtd, bufpoi, toread);
2102 chip->read_buf(mtd, bufpoi, length);
2106 EXPORT_SYMBOL(nand_read_oob_syndrome);
2109 * nand_write_oob_std - [REPLACEABLE] the most common OOB data write function
2110 * @mtd: mtd info structure
2111 * @chip: nand chip info structure
2112 * @page: page number to write
2114 int nand_write_oob_std(struct mtd_info *mtd, struct nand_chip *chip, int page)
2117 const uint8_t *buf = chip->oob_poi;
2118 int length = mtd->oobsize;
2120 chip->cmdfunc(mtd, NAND_CMD_SEQIN, mtd->writesize, page);
2121 chip->write_buf(mtd, buf, length);
2122 /* Send command to program the OOB data */
2123 chip->cmdfunc(mtd, NAND_CMD_PAGEPROG, -1, -1);
2125 status = chip->waitfunc(mtd, chip);
2127 return status & NAND_STATUS_FAIL ? -EIO : 0;
2129 EXPORT_SYMBOL(nand_write_oob_std);
2132 * nand_write_oob_syndrome - [REPLACEABLE] OOB data write function for HW ECC
2133 * with syndrome - only for large page flash
2134 * @mtd: mtd info structure
2135 * @chip: nand chip info structure
2136 * @page: page number to write
2138 int nand_write_oob_syndrome(struct mtd_info *mtd, struct nand_chip *chip,
2141 int chunk = chip->ecc.bytes + chip->ecc.prepad + chip->ecc.postpad;
2142 int eccsize = chip->ecc.size, length = mtd->oobsize;
2143 int i, len, pos, status = 0, sndcmd = 0, steps = chip->ecc.steps;
2144 const uint8_t *bufpoi = chip->oob_poi;
2147 * data-ecc-data-ecc ... ecc-oob
2149 * data-pad-ecc-pad-data-pad .... ecc-pad-oob
2151 if (!chip->ecc.prepad && !chip->ecc.postpad) {
2152 pos = steps * (eccsize + chunk);
2157 chip->cmdfunc(mtd, NAND_CMD_SEQIN, pos, page);
2158 for (i = 0; i < steps; i++) {
2160 if (mtd->writesize <= 512) {
2161 uint32_t fill = 0xFFFFFFFF;
2165 int num = min_t(int, len, 4);
2166 chip->write_buf(mtd, (uint8_t *)&fill,
2171 pos = eccsize + i * (eccsize + chunk);
2172 chip->cmdfunc(mtd, NAND_CMD_RNDIN, pos, -1);
2176 len = min_t(int, length, chunk);
2177 chip->write_buf(mtd, bufpoi, len);
2182 chip->write_buf(mtd, bufpoi, length);
2184 chip->cmdfunc(mtd, NAND_CMD_PAGEPROG, -1, -1);
2185 status = chip->waitfunc(mtd, chip);
2187 return status & NAND_STATUS_FAIL ? -EIO : 0;
2189 EXPORT_SYMBOL(nand_write_oob_syndrome);
2192 * nand_do_read_oob - [INTERN] NAND read out-of-band
2193 * @mtd: MTD device structure
2194 * @from: offset to read from
2195 * @ops: oob operations description structure
2197 * NAND read out-of-band data from the spare area.
2199 static int nand_do_read_oob(struct mtd_info *mtd, loff_t from,
2200 struct mtd_oob_ops *ops)
2202 int page, realpage, chipnr;
2203 struct nand_chip *chip = mtd_to_nand(mtd);
2204 struct mtd_ecc_stats stats;
2205 int readlen = ops->ooblen;
2207 uint8_t *buf = ops->oobbuf;
2210 pr_debug("%s: from = 0x%08Lx, len = %i\n",
2211 __func__, (unsigned long long)from, readlen);
2213 stats = mtd->ecc_stats;
2215 len = mtd_oobavail(mtd, ops);
2217 if (unlikely(ops->ooboffs >= len)) {
2218 pr_debug("%s: attempt to start read outside oob\n",
2223 /* Do not allow reads past end of device */
2224 if (unlikely(from >= mtd->size ||
2225 ops->ooboffs + readlen > ((mtd->size >> chip->page_shift) -
2226 (from >> chip->page_shift)) * len)) {
2227 pr_debug("%s: attempt to read beyond end of device\n",
2232 chipnr = (int)(from >> chip->chip_shift);
2233 chip->select_chip(mtd, chipnr);
2235 /* Shift to get page */
2236 realpage = (int)(from >> chip->page_shift);
2237 page = realpage & chip->pagemask;
2240 if (ops->mode == MTD_OPS_RAW)
2241 ret = chip->ecc.read_oob_raw(mtd, chip, page);
2243 ret = chip->ecc.read_oob(mtd, chip, page);
2248 len = min(len, readlen);
2249 buf = nand_transfer_oob(mtd, buf, ops, len);
2251 if (chip->options & NAND_NEED_READRDY) {
2252 /* Apply delay or wait for ready/busy pin */
2253 if (!chip->dev_ready)
2254 udelay(chip->chip_delay);
2256 nand_wait_ready(mtd);
2263 /* Increment page address */
2266 page = realpage & chip->pagemask;
2267 /* Check, if we cross a chip boundary */
2270 chip->select_chip(mtd, -1);
2271 chip->select_chip(mtd, chipnr);
2274 chip->select_chip(mtd, -1);
2276 ops->oobretlen = ops->ooblen - readlen;
2281 if (mtd->ecc_stats.failed - stats.failed)
2284 return mtd->ecc_stats.corrected - stats.corrected ? -EUCLEAN : 0;
2288 * nand_read_oob - [MTD Interface] NAND read data and/or out-of-band
2289 * @mtd: MTD device structure
2290 * @from: offset to read from
2291 * @ops: oob operation description structure
2293 * NAND read data and/or out-of-band data.
2295 static int nand_read_oob(struct mtd_info *mtd, loff_t from,
2296 struct mtd_oob_ops *ops)
2302 /* Do not allow reads past end of device */
2303 if (ops->datbuf && (from + ops->len) > mtd->size) {
2304 pr_debug("%s: attempt to read beyond end of device\n",
2309 if (ops->mode != MTD_OPS_PLACE_OOB &&
2310 ops->mode != MTD_OPS_AUTO_OOB &&
2311 ops->mode != MTD_OPS_RAW)
2314 nand_get_device(mtd, FL_READING);
2317 ret = nand_do_read_oob(mtd, from, ops);
2319 ret = nand_do_read_ops(mtd, from, ops);
2321 nand_release_device(mtd);
2327 * nand_write_page_raw - [INTERN] raw page write function
2328 * @mtd: mtd info structure
2329 * @chip: nand chip info structure
2331 * @oob_required: must write chip->oob_poi to OOB
2332 * @page: page number to write
2334 * Not for syndrome calculating ECC controllers, which use a special oob layout.
2336 int nand_write_page_raw(struct mtd_info *mtd, struct nand_chip *chip,
2337 const uint8_t *buf, int oob_required, int page)
2339 chip->write_buf(mtd, buf, mtd->writesize);
2341 chip->write_buf(mtd, chip->oob_poi, mtd->oobsize);
2345 EXPORT_SYMBOL(nand_write_page_raw);
2348 * nand_write_page_raw_syndrome - [INTERN] raw page write function
2349 * @mtd: mtd info structure
2350 * @chip: nand chip info structure
2352 * @oob_required: must write chip->oob_poi to OOB
2353 * @page: page number to write
2355 * We need a special oob layout and handling even when ECC isn't checked.
2357 static int nand_write_page_raw_syndrome(struct mtd_info *mtd,
2358 struct nand_chip *chip,
2359 const uint8_t *buf, int oob_required,
2362 int eccsize = chip->ecc.size;
2363 int eccbytes = chip->ecc.bytes;
2364 uint8_t *oob = chip->oob_poi;
2367 for (steps = chip->ecc.steps; steps > 0; steps--) {
2368 chip->write_buf(mtd, buf, eccsize);
2371 if (chip->ecc.prepad) {
2372 chip->write_buf(mtd, oob, chip->ecc.prepad);
2373 oob += chip->ecc.prepad;
2376 chip->write_buf(mtd, oob, eccbytes);
2379 if (chip->ecc.postpad) {
2380 chip->write_buf(mtd, oob, chip->ecc.postpad);
2381 oob += chip->ecc.postpad;
2385 size = mtd->oobsize - (oob - chip->oob_poi);
2387 chip->write_buf(mtd, oob, size);
2392 * nand_write_page_swecc - [REPLACEABLE] software ECC based page write function
2393 * @mtd: mtd info structure
2394 * @chip: nand chip info structure
2396 * @oob_required: must write chip->oob_poi to OOB
2397 * @page: page number to write
2399 static int nand_write_page_swecc(struct mtd_info *mtd, struct nand_chip *chip,
2400 const uint8_t *buf, int oob_required,
2403 int i, eccsize = chip->ecc.size, ret;
2404 int eccbytes = chip->ecc.bytes;
2405 int eccsteps = chip->ecc.steps;
2406 uint8_t *ecc_calc = chip->buffers->ecccalc;
2407 const uint8_t *p = buf;
2409 /* Software ECC calculation */
2410 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize)
2411 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
2413 ret = mtd_ooblayout_set_eccbytes(mtd, ecc_calc, chip->oob_poi, 0,
2418 return chip->ecc.write_page_raw(mtd, chip, buf, 1, page);
2422 * nand_write_page_hwecc - [REPLACEABLE] hardware ECC based page write function
2423 * @mtd: mtd info structure
2424 * @chip: nand chip info structure
2426 * @oob_required: must write chip->oob_poi to OOB
2427 * @page: page number to write
2429 static int nand_write_page_hwecc(struct mtd_info *mtd, struct nand_chip *chip,
2430 const uint8_t *buf, int oob_required,
2433 int i, eccsize = chip->ecc.size, ret;
2434 int eccbytes = chip->ecc.bytes;
2435 int eccsteps = chip->ecc.steps;
2436 uint8_t *ecc_calc = chip->buffers->ecccalc;
2437 const uint8_t *p = buf;
2439 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
2440 chip->ecc.hwctl(mtd, NAND_ECC_WRITE);
2441 chip->write_buf(mtd, p, eccsize);
2442 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
2445 ret = mtd_ooblayout_set_eccbytes(mtd, ecc_calc, chip->oob_poi, 0,
2450 chip->write_buf(mtd, chip->oob_poi, mtd->oobsize);
2457 * nand_write_subpage_hwecc - [REPLACEABLE] hardware ECC based subpage write
2458 * @mtd: mtd info structure
2459 * @chip: nand chip info structure
2460 * @offset: column address of subpage within the page
2461 * @data_len: data length
2463 * @oob_required: must write chip->oob_poi to OOB
2464 * @page: page number to write
2466 static int nand_write_subpage_hwecc(struct mtd_info *mtd,
2467 struct nand_chip *chip, uint32_t offset,
2468 uint32_t data_len, const uint8_t *buf,
2469 int oob_required, int page)
2471 uint8_t *oob_buf = chip->oob_poi;
2472 uint8_t *ecc_calc = chip->buffers->ecccalc;
2473 int ecc_size = chip->ecc.size;
2474 int ecc_bytes = chip->ecc.bytes;
2475 int ecc_steps = chip->ecc.steps;
2476 uint32_t start_step = offset / ecc_size;
2477 uint32_t end_step = (offset + data_len - 1) / ecc_size;
2478 int oob_bytes = mtd->oobsize / ecc_steps;
2481 for (step = 0; step < ecc_steps; step++) {
2482 /* configure controller for WRITE access */
2483 chip->ecc.hwctl(mtd, NAND_ECC_WRITE);
2485 /* write data (untouched subpages already masked by 0xFF) */
2486 chip->write_buf(mtd, buf, ecc_size);
2488 /* mask ECC of un-touched subpages by padding 0xFF */
2489 if ((step < start_step) || (step > end_step))
2490 memset(ecc_calc, 0xff, ecc_bytes);
2492 chip->ecc.calculate(mtd, buf, ecc_calc);
2494 /* mask OOB of un-touched subpages by padding 0xFF */
2495 /* if oob_required, preserve OOB metadata of written subpage */
2496 if (!oob_required || (step < start_step) || (step > end_step))
2497 memset(oob_buf, 0xff, oob_bytes);
2500 ecc_calc += ecc_bytes;
2501 oob_buf += oob_bytes;
2504 /* copy calculated ECC for whole page to chip->buffer->oob */
2505 /* this include masked-value(0xFF) for unwritten subpages */
2506 ecc_calc = chip->buffers->ecccalc;
2507 ret = mtd_ooblayout_set_eccbytes(mtd, ecc_calc, chip->oob_poi, 0,
2512 /* write OOB buffer to NAND device */
2513 chip->write_buf(mtd, chip->oob_poi, mtd->oobsize);
2520 * nand_write_page_syndrome - [REPLACEABLE] hardware ECC syndrome based page write
2521 * @mtd: mtd info structure
2522 * @chip: nand chip info structure
2524 * @oob_required: must write chip->oob_poi to OOB
2525 * @page: page number to write
2527 * The hw generator calculates the error syndrome automatically. Therefore we
2528 * need a special oob layout and handling.
2530 static int nand_write_page_syndrome(struct mtd_info *mtd,
2531 struct nand_chip *chip,
2532 const uint8_t *buf, int oob_required,
2535 int i, eccsize = chip->ecc.size;
2536 int eccbytes = chip->ecc.bytes;
2537 int eccsteps = chip->ecc.steps;
2538 const uint8_t *p = buf;
2539 uint8_t *oob = chip->oob_poi;
2541 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
2543 chip->ecc.hwctl(mtd, NAND_ECC_WRITE);
2544 chip->write_buf(mtd, p, eccsize);
2546 if (chip->ecc.prepad) {
2547 chip->write_buf(mtd, oob, chip->ecc.prepad);
2548 oob += chip->ecc.prepad;
2551 chip->ecc.calculate(mtd, p, oob);
2552 chip->write_buf(mtd, oob, eccbytes);
2555 if (chip->ecc.postpad) {
2556 chip->write_buf(mtd, oob, chip->ecc.postpad);
2557 oob += chip->ecc.postpad;
2561 /* Calculate remaining oob bytes */
2562 i = mtd->oobsize - (oob - chip->oob_poi);
2564 chip->write_buf(mtd, oob, i);
2570 * nand_write_page - write one page
2571 * @mtd: MTD device structure
2572 * @chip: NAND chip descriptor
2573 * @offset: address offset within the page
2574 * @data_len: length of actual data to be written
2575 * @buf: the data to write
2576 * @oob_required: must write chip->oob_poi to OOB
2577 * @page: page number to write
2578 * @raw: use _raw version of write_page
2580 static int nand_write_page(struct mtd_info *mtd, struct nand_chip *chip,
2581 uint32_t offset, int data_len, const uint8_t *buf,
2582 int oob_required, int page, int raw)
2584 int status, subpage;
2586 if (!(chip->options & NAND_NO_SUBPAGE_WRITE) &&
2587 chip->ecc.write_subpage)
2588 subpage = offset || (data_len < mtd->writesize);
2592 if (nand_standard_page_accessors(&chip->ecc))
2593 chip->cmdfunc(mtd, NAND_CMD_SEQIN, 0x00, page);
2596 status = chip->ecc.write_page_raw(mtd, chip, buf,
2597 oob_required, page);
2599 status = chip->ecc.write_subpage(mtd, chip, offset, data_len,
2600 buf, oob_required, page);
2602 status = chip->ecc.write_page(mtd, chip, buf, oob_required,
2608 if (nand_standard_page_accessors(&chip->ecc)) {
2609 chip->cmdfunc(mtd, NAND_CMD_PAGEPROG, -1, -1);
2611 status = chip->waitfunc(mtd, chip);
2612 if (status & NAND_STATUS_FAIL)
2620 * nand_fill_oob - [INTERN] Transfer client buffer to oob
2621 * @mtd: MTD device structure
2622 * @oob: oob data buffer
2623 * @len: oob data write length
2624 * @ops: oob ops structure
2626 static uint8_t *nand_fill_oob(struct mtd_info *mtd, uint8_t *oob, size_t len,
2627 struct mtd_oob_ops *ops)
2629 struct nand_chip *chip = mtd_to_nand(mtd);
2633 * Initialise to all 0xFF, to avoid the possibility of left over OOB
2634 * data from a previous OOB read.
2636 memset(chip->oob_poi, 0xff, mtd->oobsize);
2638 switch (ops->mode) {
2640 case MTD_OPS_PLACE_OOB:
2642 memcpy(chip->oob_poi + ops->ooboffs, oob, len);
2645 case MTD_OPS_AUTO_OOB:
2646 ret = mtd_ooblayout_set_databytes(mtd, oob, chip->oob_poi,
2657 #define NOTALIGNED(x) ((x & (chip->subpagesize - 1)) != 0)
2660 * nand_do_write_ops - [INTERN] NAND write with ECC
2661 * @mtd: MTD device structure
2662 * @to: offset to write to
2663 * @ops: oob operations description structure
2665 * NAND write with ECC.
2667 static int nand_do_write_ops(struct mtd_info *mtd, loff_t to,
2668 struct mtd_oob_ops *ops)
2670 int chipnr, realpage, page, column;
2671 struct nand_chip *chip = mtd_to_nand(mtd);
2672 uint32_t writelen = ops->len;
2674 uint32_t oobwritelen = ops->ooblen;
2675 uint32_t oobmaxlen = mtd_oobavail(mtd, ops);
2677 uint8_t *oob = ops->oobbuf;
2678 uint8_t *buf = ops->datbuf;
2680 int oob_required = oob ? 1 : 0;
2686 /* Reject writes, which are not page aligned */
2687 if (NOTALIGNED(to) || NOTALIGNED(ops->len)) {
2688 pr_notice("%s: attempt to write non page aligned data\n",
2693 column = to & (mtd->writesize - 1);
2695 chipnr = (int)(to >> chip->chip_shift);
2696 chip->select_chip(mtd, chipnr);
2698 /* Check, if it is write protected */
2699 if (nand_check_wp(mtd)) {
2704 realpage = (int)(to >> chip->page_shift);
2705 page = realpage & chip->pagemask;
2707 /* Invalidate the page cache, when we write to the cached page */
2708 if (to <= ((loff_t)chip->pagebuf << chip->page_shift) &&
2709 ((loff_t)chip->pagebuf << chip->page_shift) < (to + ops->len))
2712 /* Don't allow multipage oob writes with offset */
2713 if (oob && ops->ooboffs && (ops->ooboffs + ops->ooblen > oobmaxlen)) {
2719 int bytes = mtd->writesize;
2720 uint8_t *wbuf = buf;
2722 int part_pagewr = (column || writelen < mtd->writesize);
2726 else if (chip->options & NAND_USE_BOUNCE_BUFFER)
2727 use_bufpoi = !virt_addr_valid(buf) ||
2728 !IS_ALIGNED((unsigned long)buf,
2733 /* Partial page write?, or need to use bounce buffer */
2735 pr_debug("%s: using write bounce buffer for buf@%p\n",
2738 bytes = min_t(int, bytes - column, writelen);
2740 memset(chip->buffers->databuf, 0xff, mtd->writesize);
2741 memcpy(&chip->buffers->databuf[column], buf, bytes);
2742 wbuf = chip->buffers->databuf;
2745 if (unlikely(oob)) {
2746 size_t len = min(oobwritelen, oobmaxlen);
2747 oob = nand_fill_oob(mtd, oob, len, ops);
2750 /* We still need to erase leftover OOB data */
2751 memset(chip->oob_poi, 0xff, mtd->oobsize);
2754 ret = nand_write_page(mtd, chip, column, bytes, wbuf,
2756 (ops->mode == MTD_OPS_RAW));
2768 page = realpage & chip->pagemask;
2769 /* Check, if we cross a chip boundary */
2772 chip->select_chip(mtd, -1);
2773 chip->select_chip(mtd, chipnr);
2777 ops->retlen = ops->len - writelen;
2779 ops->oobretlen = ops->ooblen;
2782 chip->select_chip(mtd, -1);
2787 * panic_nand_write - [MTD Interface] NAND write with ECC
2788 * @mtd: MTD device structure
2789 * @to: offset to write to
2790 * @len: number of bytes to write
2791 * @retlen: pointer to variable to store the number of written bytes
2792 * @buf: the data to write
2794 * NAND write with ECC. Used when performing writes in interrupt context, this
2795 * may for example be called by mtdoops when writing an oops while in panic.
2797 static int panic_nand_write(struct mtd_info *mtd, loff_t to, size_t len,
2798 size_t *retlen, const uint8_t *buf)
2800 struct nand_chip *chip = mtd_to_nand(mtd);
2801 int chipnr = (int)(to >> chip->chip_shift);
2802 struct mtd_oob_ops ops;
2805 /* Grab the device */
2806 panic_nand_get_device(chip, mtd, FL_WRITING);
2808 chip->select_chip(mtd, chipnr);
2810 /* Wait for the device to get ready */
2811 panic_nand_wait(mtd, chip, 400);
2813 memset(&ops, 0, sizeof(ops));
2815 ops.datbuf = (uint8_t *)buf;
2816 ops.mode = MTD_OPS_PLACE_OOB;
2818 ret = nand_do_write_ops(mtd, to, &ops);
2820 *retlen = ops.retlen;
2825 * nand_write - [MTD Interface] NAND write with ECC
2826 * @mtd: MTD device structure
2827 * @to: offset to write to
2828 * @len: number of bytes to write
2829 * @retlen: pointer to variable to store the number of written bytes
2830 * @buf: the data to write
2832 * NAND write with ECC.
2834 static int nand_write(struct mtd_info *mtd, loff_t to, size_t len,
2835 size_t *retlen, const uint8_t *buf)
2837 struct mtd_oob_ops ops;
2840 nand_get_device(mtd, FL_WRITING);
2841 memset(&ops, 0, sizeof(ops));
2843 ops.datbuf = (uint8_t *)buf;
2844 ops.mode = MTD_OPS_PLACE_OOB;
2845 ret = nand_do_write_ops(mtd, to, &ops);
2846 *retlen = ops.retlen;
2847 nand_release_device(mtd);
2852 * nand_do_write_oob - [MTD Interface] NAND write out-of-band
2853 * @mtd: MTD device structure
2854 * @to: offset to write to
2855 * @ops: oob operation description structure
2857 * NAND write out-of-band.
2859 static int nand_do_write_oob(struct mtd_info *mtd, loff_t to,
2860 struct mtd_oob_ops *ops)
2862 int chipnr, page, status, len;
2863 struct nand_chip *chip = mtd_to_nand(mtd);
2865 pr_debug("%s: to = 0x%08x, len = %i\n",
2866 __func__, (unsigned int)to, (int)ops->ooblen);
2868 len = mtd_oobavail(mtd, ops);
2870 /* Do not allow write past end of page */
2871 if ((ops->ooboffs + ops->ooblen) > len) {
2872 pr_debug("%s: attempt to write past end of page\n",
2877 if (unlikely(ops->ooboffs >= len)) {
2878 pr_debug("%s: attempt to start write outside oob\n",
2883 /* Do not allow write past end of device */
2884 if (unlikely(to >= mtd->size ||
2885 ops->ooboffs + ops->ooblen >
2886 ((mtd->size >> chip->page_shift) -
2887 (to >> chip->page_shift)) * len)) {
2888 pr_debug("%s: attempt to write beyond end of device\n",
2893 chipnr = (int)(to >> chip->chip_shift);
2896 * Reset the chip. Some chips (like the Toshiba TC5832DC found in one
2897 * of my DiskOnChip 2000 test units) will clear the whole data page too
2898 * if we don't do this. I have no clue why, but I seem to have 'fixed'
2899 * it in the doc2000 driver in August 1999. dwmw2.
2901 nand_reset(chip, chipnr);
2903 chip->select_chip(mtd, chipnr);
2905 /* Shift to get page */
2906 page = (int)(to >> chip->page_shift);
2908 /* Check, if it is write protected */
2909 if (nand_check_wp(mtd)) {
2910 chip->select_chip(mtd, -1);
2914 /* Invalidate the page cache, if we write to the cached page */
2915 if (page == chip->pagebuf)
2918 nand_fill_oob(mtd, ops->oobbuf, ops->ooblen, ops);
2920 if (ops->mode == MTD_OPS_RAW)
2921 status = chip->ecc.write_oob_raw(mtd, chip, page & chip->pagemask);
2923 status = chip->ecc.write_oob(mtd, chip, page & chip->pagemask);
2925 chip->select_chip(mtd, -1);
2930 ops->oobretlen = ops->ooblen;
2936 * nand_write_oob - [MTD Interface] NAND write data and/or out-of-band
2937 * @mtd: MTD device structure
2938 * @to: offset to write to
2939 * @ops: oob operation description structure
2941 static int nand_write_oob(struct mtd_info *mtd, loff_t to,
2942 struct mtd_oob_ops *ops)
2944 int ret = -ENOTSUPP;
2948 /* Do not allow writes past end of device */
2949 if (ops->datbuf && (to + ops->len) > mtd->size) {
2950 pr_debug("%s: attempt to write beyond end of device\n",
2955 nand_get_device(mtd, FL_WRITING);
2957 switch (ops->mode) {
2958 case MTD_OPS_PLACE_OOB:
2959 case MTD_OPS_AUTO_OOB:
2968 ret = nand_do_write_oob(mtd, to, ops);
2970 ret = nand_do_write_ops(mtd, to, ops);
2973 nand_release_device(mtd);
2978 * single_erase - [GENERIC] NAND standard block erase command function
2979 * @mtd: MTD device structure
2980 * @page: the page address of the block which will be erased
2982 * Standard erase command for NAND chips. Returns NAND status.
2984 static int single_erase(struct mtd_info *mtd, int page)
2986 struct nand_chip *chip = mtd_to_nand(mtd);
2987 /* Send commands to erase a block */
2988 chip->cmdfunc(mtd, NAND_CMD_ERASE1, -1, page);
2989 chip->cmdfunc(mtd, NAND_CMD_ERASE2, -1, -1);
2991 return chip->waitfunc(mtd, chip);
2995 * nand_erase - [MTD Interface] erase block(s)
2996 * @mtd: MTD device structure
2997 * @instr: erase instruction
2999 * Erase one ore more blocks.
3001 static int nand_erase(struct mtd_info *mtd, struct erase_info *instr)
3003 return nand_erase_nand(mtd, instr, 0);
3007 * nand_erase_nand - [INTERN] erase block(s)
3008 * @mtd: MTD device structure
3009 * @instr: erase instruction
3010 * @allowbbt: allow erasing the bbt area
3012 * Erase one ore more blocks.
3014 int nand_erase_nand(struct mtd_info *mtd, struct erase_info *instr,
3017 int page, status, pages_per_block, ret, chipnr;
3018 struct nand_chip *chip = mtd_to_nand(mtd);
3021 pr_debug("%s: start = 0x%012llx, len = %llu\n",
3022 __func__, (unsigned long long)instr->addr,
3023 (unsigned long long)instr->len);
3025 if (check_offs_len(mtd, instr->addr, instr->len))
3028 /* Grab the lock and see if the device is available */
3029 nand_get_device(mtd, FL_ERASING);
3031 /* Shift to get first page */
3032 page = (int)(instr->addr >> chip->page_shift);
3033 chipnr = (int)(instr->addr >> chip->chip_shift);
3035 /* Calculate pages in each block */
3036 pages_per_block = 1 << (chip->phys_erase_shift - chip->page_shift);
3038 /* Select the NAND device */
3039 chip->select_chip(mtd, chipnr);
3041 /* Check, if it is write protected */
3042 if (nand_check_wp(mtd)) {
3043 pr_debug("%s: device is write protected!\n",
3045 instr->state = MTD_ERASE_FAILED;
3049 /* Loop through the pages */
3052 instr->state = MTD_ERASING;
3055 /* Check if we have a bad block, we do not erase bad blocks! */
3056 if (nand_block_checkbad(mtd, ((loff_t) page) <<
3057 chip->page_shift, allowbbt)) {
3058 pr_warn("%s: attempt to erase a bad block at page 0x%08x\n",
3060 instr->state = MTD_ERASE_FAILED;
3065 * Invalidate the page cache, if we erase the block which
3066 * contains the current cached page.
3068 if (page <= chip->pagebuf && chip->pagebuf <
3069 (page + pages_per_block))
3072 status = chip->erase(mtd, page & chip->pagemask);
3074 /* See if block erase succeeded */
3075 if (status & NAND_STATUS_FAIL) {
3076 pr_debug("%s: failed erase, page 0x%08x\n",
3078 instr->state = MTD_ERASE_FAILED;
3080 ((loff_t)page << chip->page_shift);
3084 /* Increment page address and decrement length */
3085 len -= (1ULL << chip->phys_erase_shift);
3086 page += pages_per_block;
3088 /* Check, if we cross a chip boundary */
3089 if (len && !(page & chip->pagemask)) {
3091 chip->select_chip(mtd, -1);
3092 chip->select_chip(mtd, chipnr);
3095 instr->state = MTD_ERASE_DONE;
3099 ret = instr->state == MTD_ERASE_DONE ? 0 : -EIO;
3101 /* Deselect and wake up anyone waiting on the device */
3102 chip->select_chip(mtd, -1);
3103 nand_release_device(mtd);
3105 /* Do call back function */
3107 mtd_erase_callback(instr);
3109 /* Return more or less happy */
3114 * nand_sync - [MTD Interface] sync
3115 * @mtd: MTD device structure
3117 * Sync is actually a wait for chip ready function.
3119 static void nand_sync(struct mtd_info *mtd)
3121 pr_debug("%s: called\n", __func__);
3123 /* Grab the lock and see if the device is available */
3124 nand_get_device(mtd, FL_SYNCING);
3125 /* Release it and go back */
3126 nand_release_device(mtd);
3130 * nand_block_isbad - [MTD Interface] Check if block at offset is bad
3131 * @mtd: MTD device structure
3132 * @offs: offset relative to mtd start
3134 static int nand_block_isbad(struct mtd_info *mtd, loff_t offs)
3136 struct nand_chip *chip = mtd_to_nand(mtd);
3137 int chipnr = (int)(offs >> chip->chip_shift);
3140 /* Select the NAND device */
3141 nand_get_device(mtd, FL_READING);
3142 chip->select_chip(mtd, chipnr);
3144 ret = nand_block_checkbad(mtd, offs, 0);
3146 chip->select_chip(mtd, -1);
3147 nand_release_device(mtd);
3153 * nand_block_markbad - [MTD Interface] Mark block at the given offset as bad
3154 * @mtd: MTD device structure
3155 * @ofs: offset relative to mtd start
3157 static int nand_block_markbad(struct mtd_info *mtd, loff_t ofs)
3161 ret = nand_block_isbad(mtd, ofs);
3163 /* If it was bad already, return success and do nothing */
3169 return nand_block_markbad_lowlevel(mtd, ofs);
3173 * nand_max_bad_blocks - [MTD Interface] Max number of bad blocks for an mtd
3174 * @mtd: MTD device structure
3175 * @ofs: offset relative to mtd start
3176 * @len: length of mtd
3178 static int nand_max_bad_blocks(struct mtd_info *mtd, loff_t ofs, size_t len)
3180 struct nand_chip *chip = mtd_to_nand(mtd);
3181 u32 part_start_block;
3187 * max_bb_per_die and blocks_per_die used to determine
3188 * the maximum bad block count.
3190 if (!chip->max_bb_per_die || !chip->blocks_per_die)
3193 /* Get the start and end of the partition in erase blocks. */
3194 part_start_block = mtd_div_by_eb(ofs, mtd);
3195 part_end_block = mtd_div_by_eb(len, mtd) + part_start_block - 1;
3197 /* Get the start and end LUNs of the partition. */
3198 part_start_die = part_start_block / chip->blocks_per_die;
3199 part_end_die = part_end_block / chip->blocks_per_die;
3202 * Look up the bad blocks per unit and multiply by the number of units
3203 * that the partition spans.
3205 return chip->max_bb_per_die * (part_end_die - part_start_die + 1);
3209 * nand_onfi_set_features- [REPLACEABLE] set features for ONFI nand
3210 * @mtd: MTD device structure
3211 * @chip: nand chip info structure
3212 * @addr: feature address.
3213 * @subfeature_param: the subfeature parameters, a four bytes array.
3215 static int nand_onfi_set_features(struct mtd_info *mtd, struct nand_chip *chip,
3216 int addr, uint8_t *subfeature_param)
3221 if (!chip->onfi_version ||
3222 !(le16_to_cpu(chip->onfi_params.opt_cmd)
3223 & ONFI_OPT_CMD_SET_GET_FEATURES))
3226 chip->cmdfunc(mtd, NAND_CMD_SET_FEATURES, addr, -1);
3227 for (i = 0; i < ONFI_SUBFEATURE_PARAM_LEN; ++i)
3228 chip->write_byte(mtd, subfeature_param[i]);
3230 status = chip->waitfunc(mtd, chip);
3231 if (status & NAND_STATUS_FAIL)
3237 * nand_onfi_get_features- [REPLACEABLE] get features for ONFI nand
3238 * @mtd: MTD device structure
3239 * @chip: nand chip info structure
3240 * @addr: feature address.
3241 * @subfeature_param: the subfeature parameters, a four bytes array.
3243 static int nand_onfi_get_features(struct mtd_info *mtd, struct nand_chip *chip,
3244 int addr, uint8_t *subfeature_param)
3248 if (!chip->onfi_version ||
3249 !(le16_to_cpu(chip->onfi_params.opt_cmd)
3250 & ONFI_OPT_CMD_SET_GET_FEATURES))
3253 chip->cmdfunc(mtd, NAND_CMD_GET_FEATURES, addr, -1);
3254 for (i = 0; i < ONFI_SUBFEATURE_PARAM_LEN; ++i)
3255 *subfeature_param++ = chip->read_byte(mtd);
3260 * nand_onfi_get_set_features_notsupp - set/get features stub returning
3262 * @mtd: MTD device structure
3263 * @chip: nand chip info structure
3264 * @addr: feature address.
3265 * @subfeature_param: the subfeature parameters, a four bytes array.
3267 * Should be used by NAND controller drivers that do not support the SET/GET
3268 * FEATURES operations.
3270 int nand_onfi_get_set_features_notsupp(struct mtd_info *mtd,
3271 struct nand_chip *chip, int addr,
3272 u8 *subfeature_param)
3276 EXPORT_SYMBOL(nand_onfi_get_set_features_notsupp);
3279 * nand_suspend - [MTD Interface] Suspend the NAND flash
3280 * @mtd: MTD device structure
3282 static int nand_suspend(struct mtd_info *mtd)
3284 return nand_get_device(mtd, FL_PM_SUSPENDED);
3288 * nand_resume - [MTD Interface] Resume the NAND flash
3289 * @mtd: MTD device structure
3291 static void nand_resume(struct mtd_info *mtd)
3293 struct nand_chip *chip = mtd_to_nand(mtd);
3295 if (chip->state == FL_PM_SUSPENDED)
3296 nand_release_device(mtd);
3298 pr_err("%s called for a chip which is not in suspended state\n",
3303 * nand_shutdown - [MTD Interface] Finish the current NAND operation and
3304 * prevent further operations
3305 * @mtd: MTD device structure
3307 static void nand_shutdown(struct mtd_info *mtd)
3309 nand_get_device(mtd, FL_PM_SUSPENDED);
3312 /* Set default functions */
3313 static void nand_set_defaults(struct nand_chip *chip)
3315 unsigned int busw = chip->options & NAND_BUSWIDTH_16;
3317 /* check for proper chip_delay setup, set 20us if not */
3318 if (!chip->chip_delay)
3319 chip->chip_delay = 20;
3321 /* check, if a user supplied command function given */
3322 if (chip->cmdfunc == NULL)
3323 chip->cmdfunc = nand_command;
3325 /* check, if a user supplied wait function given */
3326 if (chip->waitfunc == NULL)
3327 chip->waitfunc = nand_wait;
3329 if (!chip->select_chip)
3330 chip->select_chip = nand_select_chip;
3332 /* set for ONFI nand */
3333 if (!chip->onfi_set_features)
3334 chip->onfi_set_features = nand_onfi_set_features;
3335 if (!chip->onfi_get_features)
3336 chip->onfi_get_features = nand_onfi_get_features;
3338 /* If called twice, pointers that depend on busw may need to be reset */
3339 if (!chip->read_byte || chip->read_byte == nand_read_byte)
3340 chip->read_byte = busw ? nand_read_byte16 : nand_read_byte;
3341 if (!chip->read_word)
3342 chip->read_word = nand_read_word;
3343 if (!chip->block_bad)
3344 chip->block_bad = nand_block_bad;
3345 if (!chip->block_markbad)
3346 chip->block_markbad = nand_default_block_markbad;
3347 if (!chip->write_buf || chip->write_buf == nand_write_buf)
3348 chip->write_buf = busw ? nand_write_buf16 : nand_write_buf;
3349 if (!chip->write_byte || chip->write_byte == nand_write_byte)
3350 chip->write_byte = busw ? nand_write_byte16 : nand_write_byte;
3351 if (!chip->read_buf || chip->read_buf == nand_read_buf)
3352 chip->read_buf = busw ? nand_read_buf16 : nand_read_buf;
3353 if (!chip->scan_bbt)
3354 chip->scan_bbt = nand_default_bbt;
3356 if (!chip->controller) {
3357 chip->controller = &chip->hwcontrol;
3358 nand_hw_control_init(chip->controller);
3361 if (!chip->buf_align)
3362 chip->buf_align = 1;
3365 /* Sanitize ONFI strings so we can safely print them */
3366 static void sanitize_string(uint8_t *s, size_t len)
3370 /* Null terminate */
3373 /* Remove non printable chars */
3374 for (i = 0; i < len - 1; i++) {
3375 if (s[i] < ' ' || s[i] > 127)
3379 /* Remove trailing spaces */
3383 static u16 onfi_crc16(u16 crc, u8 const *p, size_t len)
3388 for (i = 0; i < 8; i++)
3389 crc = (crc << 1) ^ ((crc & 0x8000) ? 0x8005 : 0);
3395 /* Parse the Extended Parameter Page. */
3396 static int nand_flash_detect_ext_param_page(struct nand_chip *chip,
3397 struct nand_onfi_params *p)
3399 struct mtd_info *mtd = nand_to_mtd(chip);
3400 struct onfi_ext_param_page *ep;
3401 struct onfi_ext_section *s;
3402 struct onfi_ext_ecc_info *ecc;
3408 len = le16_to_cpu(p->ext_param_page_length) * 16;
3409 ep = kmalloc(len, GFP_KERNEL);
3413 /* Send our own NAND_CMD_PARAM. */
3414 chip->cmdfunc(mtd, NAND_CMD_PARAM, 0, -1);
3416 /* Use the Change Read Column command to skip the ONFI param pages. */
3417 chip->cmdfunc(mtd, NAND_CMD_RNDOUT,
3418 sizeof(*p) * p->num_of_param_pages , -1);
3420 /* Read out the Extended Parameter Page. */
3421 chip->read_buf(mtd, (uint8_t *)ep, len);
3422 if ((onfi_crc16(ONFI_CRC_BASE, ((uint8_t *)ep) + 2, len - 2)
3423 != le16_to_cpu(ep->crc))) {
3424 pr_debug("fail in the CRC.\n");
3429 * Check the signature.
3430 * Do not strictly follow the ONFI spec, maybe changed in future.
3432 if (strncmp(ep->sig, "EPPS", 4)) {
3433 pr_debug("The signature is invalid.\n");
3437 /* find the ECC section. */
3438 cursor = (uint8_t *)(ep + 1);
3439 for (i = 0; i < ONFI_EXT_SECTION_MAX; i++) {
3440 s = ep->sections + i;
3441 if (s->type == ONFI_SECTION_TYPE_2)
3443 cursor += s->length * 16;
3445 if (i == ONFI_EXT_SECTION_MAX) {
3446 pr_debug("We can not find the ECC section.\n");
3450 /* get the info we want. */
3451 ecc = (struct onfi_ext_ecc_info *)cursor;
3453 if (!ecc->codeword_size) {
3454 pr_debug("Invalid codeword size\n");
3458 chip->ecc_strength_ds = ecc->ecc_bits;
3459 chip->ecc_step_ds = 1 << ecc->codeword_size;
3468 * Check if the NAND chip is ONFI compliant, returns 1 if it is, 0 otherwise.
3470 static int nand_flash_detect_onfi(struct nand_chip *chip)
3472 struct mtd_info *mtd = nand_to_mtd(chip);
3473 struct nand_onfi_params *p = &chip->onfi_params;
3477 /* Try ONFI for unknown chip or LP */
3478 chip->cmdfunc(mtd, NAND_CMD_READID, 0x20, -1);
3479 if (chip->read_byte(mtd) != 'O' || chip->read_byte(mtd) != 'N' ||
3480 chip->read_byte(mtd) != 'F' || chip->read_byte(mtd) != 'I')
3483 chip->cmdfunc(mtd, NAND_CMD_PARAM, 0, -1);
3484 for (i = 0; i < 3; i++) {
3485 for (j = 0; j < sizeof(*p); j++)
3486 ((uint8_t *)p)[j] = chip->read_byte(mtd);
3487 if (onfi_crc16(ONFI_CRC_BASE, (uint8_t *)p, 254) ==
3488 le16_to_cpu(p->crc)) {
3494 pr_err("Could not find valid ONFI parameter page; aborting\n");
3499 val = le16_to_cpu(p->revision);
3501 chip->onfi_version = 23;
3502 else if (val & (1 << 4))
3503 chip->onfi_version = 22;
3504 else if (val & (1 << 3))
3505 chip->onfi_version = 21;
3506 else if (val & (1 << 2))
3507 chip->onfi_version = 20;
3508 else if (val & (1 << 1))
3509 chip->onfi_version = 10;
3511 if (!chip->onfi_version) {
3512 pr_info("unsupported ONFI version: %d\n", val);
3516 sanitize_string(p->manufacturer, sizeof(p->manufacturer));
3517 sanitize_string(p->model, sizeof(p->model));
3519 mtd->name = p->model;
3521 mtd->writesize = le32_to_cpu(p->byte_per_page);
3524 * pages_per_block and blocks_per_lun may not be a power-of-2 size
3525 * (don't ask me who thought of this...). MTD assumes that these
3526 * dimensions will be power-of-2, so just truncate the remaining area.
3528 mtd->erasesize = 1 << (fls(le32_to_cpu(p->pages_per_block)) - 1);
3529 mtd->erasesize *= mtd->writesize;
3531 mtd->oobsize = le16_to_cpu(p->spare_bytes_per_page);
3533 /* See erasesize comment */
3534 chip->chipsize = 1 << (fls(le32_to_cpu(p->blocks_per_lun)) - 1);
3535 chip->chipsize *= (uint64_t)mtd->erasesize * p->lun_count;
3536 chip->bits_per_cell = p->bits_per_cell;
3538 chip->max_bb_per_die = le16_to_cpu(p->bb_per_lun);
3539 chip->blocks_per_die = le32_to_cpu(p->blocks_per_lun);
3541 if (onfi_feature(chip) & ONFI_FEATURE_16_BIT_BUS)
3542 chip->options |= NAND_BUSWIDTH_16;
3544 if (p->ecc_bits != 0xff) {
3545 chip->ecc_strength_ds = p->ecc_bits;
3546 chip->ecc_step_ds = 512;
3547 } else if (chip->onfi_version >= 21 &&
3548 (onfi_feature(chip) & ONFI_FEATURE_EXT_PARAM_PAGE)) {
3551 * The nand_flash_detect_ext_param_page() uses the
3552 * Change Read Column command which maybe not supported
3553 * by the chip->cmdfunc. So try to update the chip->cmdfunc
3554 * now. We do not replace user supplied command function.
3556 if (mtd->writesize > 512 && chip->cmdfunc == nand_command)
3557 chip->cmdfunc = nand_command_lp;
3559 /* The Extended Parameter Page is supported since ONFI 2.1. */
3560 if (nand_flash_detect_ext_param_page(chip, p))
3561 pr_warn("Failed to detect ONFI extended param page\n");
3563 pr_warn("Could not retrieve ONFI ECC requirements\n");
3570 * Check if the NAND chip is JEDEC compliant, returns 1 if it is, 0 otherwise.
3572 static int nand_flash_detect_jedec(struct nand_chip *chip)
3574 struct mtd_info *mtd = nand_to_mtd(chip);
3575 struct nand_jedec_params *p = &chip->jedec_params;
3576 struct jedec_ecc_info *ecc;
3580 /* Try JEDEC for unknown chip or LP */
3581 chip->cmdfunc(mtd, NAND_CMD_READID, 0x40, -1);
3582 if (chip->read_byte(mtd) != 'J' || chip->read_byte(mtd) != 'E' ||
3583 chip->read_byte(mtd) != 'D' || chip->read_byte(mtd) != 'E' ||
3584 chip->read_byte(mtd) != 'C')
3587 chip->cmdfunc(mtd, NAND_CMD_PARAM, 0x40, -1);
3588 for (i = 0; i < 3; i++) {
3589 for (j = 0; j < sizeof(*p); j++)
3590 ((uint8_t *)p)[j] = chip->read_byte(mtd);
3592 if (onfi_crc16(ONFI_CRC_BASE, (uint8_t *)p, 510) ==
3593 le16_to_cpu(p->crc))
3598 pr_err("Could not find valid JEDEC parameter page; aborting\n");
3603 val = le16_to_cpu(p->revision);
3605 chip->jedec_version = 10;
3606 else if (val & (1 << 1))
3607 chip->jedec_version = 1; /* vendor specific version */
3609 if (!chip->jedec_version) {
3610 pr_info("unsupported JEDEC version: %d\n", val);
3614 sanitize_string(p->manufacturer, sizeof(p->manufacturer));
3615 sanitize_string(p->model, sizeof(p->model));
3617 mtd->name = p->model;
3619 mtd->writesize = le32_to_cpu(p->byte_per_page);
3621 /* Please reference to the comment for nand_flash_detect_onfi. */
3622 mtd->erasesize = 1 << (fls(le32_to_cpu(p->pages_per_block)) - 1);
3623 mtd->erasesize *= mtd->writesize;
3625 mtd->oobsize = le16_to_cpu(p->spare_bytes_per_page);
3627 /* Please reference to the comment for nand_flash_detect_onfi. */
3628 chip->chipsize = 1 << (fls(le32_to_cpu(p->blocks_per_lun)) - 1);
3629 chip->chipsize *= (uint64_t)mtd->erasesize * p->lun_count;
3630 chip->bits_per_cell = p->bits_per_cell;
3632 if (jedec_feature(chip) & JEDEC_FEATURE_16_BIT_BUS)
3633 chip->options |= NAND_BUSWIDTH_16;
3636 ecc = &p->ecc_info[0];
3638 if (ecc->codeword_size >= 9) {
3639 chip->ecc_strength_ds = ecc->ecc_bits;
3640 chip->ecc_step_ds = 1 << ecc->codeword_size;
3642 pr_warn("Invalid codeword size\n");
3649 * nand_id_has_period - Check if an ID string has a given wraparound period
3650 * @id_data: the ID string
3651 * @arrlen: the length of the @id_data array
3652 * @period: the period of repitition
3654 * Check if an ID string is repeated within a given sequence of bytes at
3655 * specific repetition interval period (e.g., {0x20,0x01,0x7F,0x20} has a
3656 * period of 3). This is a helper function for nand_id_len(). Returns non-zero
3657 * if the repetition has a period of @period; otherwise, returns zero.
3659 static int nand_id_has_period(u8 *id_data, int arrlen, int period)
3662 for (i = 0; i < period; i++)
3663 for (j = i + period; j < arrlen; j += period)
3664 if (id_data[i] != id_data[j])
3670 * nand_id_len - Get the length of an ID string returned by CMD_READID
3671 * @id_data: the ID string
3672 * @arrlen: the length of the @id_data array
3674 * Returns the length of the ID string, according to known wraparound/trailing
3675 * zero patterns. If no pattern exists, returns the length of the array.
3677 static int nand_id_len(u8 *id_data, int arrlen)
3679 int last_nonzero, period;
3681 /* Find last non-zero byte */
3682 for (last_nonzero = arrlen - 1; last_nonzero >= 0; last_nonzero--)
3683 if (id_data[last_nonzero])
3687 if (last_nonzero < 0)
3690 /* Calculate wraparound period */
3691 for (period = 1; period < arrlen; period++)
3692 if (nand_id_has_period(id_data, arrlen, period))
3695 /* There's a repeated pattern */
3696 if (period < arrlen)
3699 /* There are trailing zeros */
3700 if (last_nonzero < arrlen - 1)
3701 return last_nonzero + 1;
3703 /* No pattern detected */
3707 /* Extract the bits of per cell from the 3rd byte of the extended ID */
3708 static int nand_get_bits_per_cell(u8 cellinfo)
3712 bits = cellinfo & NAND_CI_CELLTYPE_MSK;
3713 bits >>= NAND_CI_CELLTYPE_SHIFT;
3718 * Many new NAND share similar device ID codes, which represent the size of the
3719 * chip. The rest of the parameters must be decoded according to generic or
3720 * manufacturer-specific "extended ID" decoding patterns.
3722 void nand_decode_ext_id(struct nand_chip *chip)
3724 struct mtd_info *mtd = nand_to_mtd(chip);
3726 u8 *id_data = chip->id.data;
3727 /* The 3rd id byte holds MLC / multichip data */
3728 chip->bits_per_cell = nand_get_bits_per_cell(id_data[2]);
3729 /* The 4th id byte is the important one */
3733 mtd->writesize = 1024 << (extid & 0x03);
3736 mtd->oobsize = (8 << (extid & 0x01)) * (mtd->writesize >> 9);
3738 /* Calc blocksize. Blocksize is multiples of 64KiB */
3739 mtd->erasesize = (64 * 1024) << (extid & 0x03);
3741 /* Get buswidth information */
3743 chip->options |= NAND_BUSWIDTH_16;
3745 EXPORT_SYMBOL_GPL(nand_decode_ext_id);
3748 * Old devices have chip data hardcoded in the device ID table. nand_decode_id
3749 * decodes a matching ID table entry and assigns the MTD size parameters for
3752 static void nand_decode_id(struct nand_chip *chip, struct nand_flash_dev *type)
3754 struct mtd_info *mtd = nand_to_mtd(chip);
3756 mtd->erasesize = type->erasesize;
3757 mtd->writesize = type->pagesize;
3758 mtd->oobsize = mtd->writesize / 32;
3760 /* All legacy ID NAND are small-page, SLC */
3761 chip->bits_per_cell = 1;
3765 * Set the bad block marker/indicator (BBM/BBI) patterns according to some
3766 * heuristic patterns using various detected parameters (e.g., manufacturer,
3767 * page size, cell-type information).
3769 static void nand_decode_bbm_options(struct nand_chip *chip)
3771 struct mtd_info *mtd = nand_to_mtd(chip);
3773 /* Set the bad block position */
3774 if (mtd->writesize > 512 || (chip->options & NAND_BUSWIDTH_16))
3775 chip->badblockpos = NAND_LARGE_BADBLOCK_POS;
3777 chip->badblockpos = NAND_SMALL_BADBLOCK_POS;
3780 static inline bool is_full_id_nand(struct nand_flash_dev *type)
3782 return type->id_len;
3785 static bool find_full_id_nand(struct nand_chip *chip,
3786 struct nand_flash_dev *type)
3788 struct mtd_info *mtd = nand_to_mtd(chip);
3789 u8 *id_data = chip->id.data;
3791 if (!strncmp(type->id, id_data, type->id_len)) {
3792 mtd->writesize = type->pagesize;
3793 mtd->erasesize = type->erasesize;
3794 mtd->oobsize = type->oobsize;
3796 chip->bits_per_cell = nand_get_bits_per_cell(id_data[2]);
3797 chip->chipsize = (uint64_t)type->chipsize << 20;
3798 chip->options |= type->options;
3799 chip->ecc_strength_ds = NAND_ECC_STRENGTH(type);
3800 chip->ecc_step_ds = NAND_ECC_STEP(type);
3801 chip->onfi_timing_mode_default =
3802 type->onfi_timing_mode_default;
3805 mtd->name = type->name;
3813 * Manufacturer detection. Only used when the NAND is not ONFI or JEDEC
3814 * compliant and does not have a full-id or legacy-id entry in the nand_ids
3817 static void nand_manufacturer_detect(struct nand_chip *chip)
3820 * Try manufacturer detection if available and use
3821 * nand_decode_ext_id() otherwise.
3823 if (chip->manufacturer.desc && chip->manufacturer.desc->ops &&
3824 chip->manufacturer.desc->ops->detect) {
3825 /* The 3rd id byte holds MLC / multichip data */
3826 chip->bits_per_cell = nand_get_bits_per_cell(chip->id.data[2]);
3827 chip->manufacturer.desc->ops->detect(chip);
3829 nand_decode_ext_id(chip);
3834 * Manufacturer initialization. This function is called for all NANDs including
3835 * ONFI and JEDEC compliant ones.
3836 * Manufacturer drivers should put all their specific initialization code in
3837 * their ->init() hook.
3839 static int nand_manufacturer_init(struct nand_chip *chip)
3841 if (!chip->manufacturer.desc || !chip->manufacturer.desc->ops ||
3842 !chip->manufacturer.desc->ops->init)
3845 return chip->manufacturer.desc->ops->init(chip);
3849 * Manufacturer cleanup. This function is called for all NANDs including
3850 * ONFI and JEDEC compliant ones.
3851 * Manufacturer drivers should put all their specific cleanup code in their
3854 static void nand_manufacturer_cleanup(struct nand_chip *chip)
3856 /* Release manufacturer private data */
3857 if (chip->manufacturer.desc && chip->manufacturer.desc->ops &&
3858 chip->manufacturer.desc->ops->cleanup)
3859 chip->manufacturer.desc->ops->cleanup(chip);
3863 * Get the flash and manufacturer id and lookup if the type is supported.
3865 static int nand_detect(struct nand_chip *chip, struct nand_flash_dev *type)
3867 const struct nand_manufacturer *manufacturer;
3868 struct mtd_info *mtd = nand_to_mtd(chip);
3871 u8 *id_data = chip->id.data;
3875 * Reset the chip, required by some chips (e.g. Micron MT29FxGxxxxx)
3878 nand_reset(chip, 0);
3880 /* Select the device */
3881 chip->select_chip(mtd, 0);
3883 /* Send the command for reading device ID */
3884 chip->cmdfunc(mtd, NAND_CMD_READID, 0x00, -1);
3886 /* Read manufacturer and device IDs */
3887 maf_id = chip->read_byte(mtd);
3888 dev_id = chip->read_byte(mtd);
3891 * Try again to make sure, as some systems the bus-hold or other
3892 * interface concerns can cause random data which looks like a
3893 * possibly credible NAND flash to appear. If the two results do
3894 * not match, ignore the device completely.
3897 chip->cmdfunc(mtd, NAND_CMD_READID, 0x00, -1);
3899 /* Read entire ID string */
3900 for (i = 0; i < ARRAY_SIZE(chip->id.data); i++)
3901 id_data[i] = chip->read_byte(mtd);
3903 if (id_data[0] != maf_id || id_data[1] != dev_id) {
3904 pr_info("second ID read did not match %02x,%02x against %02x,%02x\n",
3905 maf_id, dev_id, id_data[0], id_data[1]);
3909 chip->id.len = nand_id_len(id_data, ARRAY_SIZE(chip->id.data));
3911 /* Try to identify manufacturer */
3912 manufacturer = nand_get_manufacturer(maf_id);
3913 chip->manufacturer.desc = manufacturer;
3916 type = nand_flash_ids;
3919 * Save the NAND_BUSWIDTH_16 flag before letting auto-detection logic
3921 * This is required to make sure initial NAND bus width set by the
3922 * NAND controller driver is coherent with the real NAND bus width
3923 * (extracted by auto-detection code).
3925 busw = chip->options & NAND_BUSWIDTH_16;
3928 * The flag is only set (never cleared), reset it to its default value
3929 * before starting auto-detection.
3931 chip->options &= ~NAND_BUSWIDTH_16;
3933 for (; type->name != NULL; type++) {
3934 if (is_full_id_nand(type)) {
3935 if (find_full_id_nand(chip, type))
3937 } else if (dev_id == type->dev_id) {
3942 chip->onfi_version = 0;
3943 if (!type->name || !type->pagesize) {
3944 /* Check if the chip is ONFI compliant */
3945 if (nand_flash_detect_onfi(chip))
3948 /* Check if the chip is JEDEC compliant */
3949 if (nand_flash_detect_jedec(chip))
3957 mtd->name = type->name;
3959 chip->chipsize = (uint64_t)type->chipsize << 20;
3961 if (!type->pagesize)
3962 nand_manufacturer_detect(chip);
3964 nand_decode_id(chip, type);
3966 /* Get chip options */
3967 chip->options |= type->options;
3971 if (chip->options & NAND_BUSWIDTH_AUTO) {
3972 WARN_ON(busw & NAND_BUSWIDTH_16);
3973 nand_set_defaults(chip);
3974 } else if (busw != (chip->options & NAND_BUSWIDTH_16)) {
3976 * Check, if buswidth is correct. Hardware drivers should set
3979 pr_info("device found, Manufacturer ID: 0x%02x, Chip ID: 0x%02x\n",
3981 pr_info("%s %s\n", nand_manufacturer_name(manufacturer),
3983 pr_warn("bus width %d instead of %d bits\n", busw ? 16 : 8,
3984 (chip->options & NAND_BUSWIDTH_16) ? 16 : 8);
3988 nand_decode_bbm_options(chip);
3990 /* Calculate the address shift from the page size */
3991 chip->page_shift = ffs(mtd->writesize) - 1;
3992 /* Convert chipsize to number of pages per chip -1 */
3993 chip->pagemask = (chip->chipsize >> chip->page_shift) - 1;
3995 chip->bbt_erase_shift = chip->phys_erase_shift =
3996 ffs(mtd->erasesize) - 1;
3997 if (chip->chipsize & 0xffffffff)
3998 chip->chip_shift = ffs((unsigned)chip->chipsize) - 1;
4000 chip->chip_shift = ffs((unsigned)(chip->chipsize >> 32));
4001 chip->chip_shift += 32 - 1;
4004 if (chip->chip_shift - chip->page_shift > 16)
4005 chip->options |= NAND_ROW_ADDR_3;
4007 chip->badblockbits = 8;
4008 chip->erase = single_erase;
4010 /* Do not replace user supplied command function! */
4011 if (mtd->writesize > 512 && chip->cmdfunc == nand_command)
4012 chip->cmdfunc = nand_command_lp;
4014 pr_info("device found, Manufacturer ID: 0x%02x, Chip ID: 0x%02x\n",
4017 if (chip->onfi_version)
4018 pr_info("%s %s\n", nand_manufacturer_name(manufacturer),
4019 chip->onfi_params.model);
4020 else if (chip->jedec_version)
4021 pr_info("%s %s\n", nand_manufacturer_name(manufacturer),
4022 chip->jedec_params.model);
4024 pr_info("%s %s\n", nand_manufacturer_name(manufacturer),
4027 pr_info("%d MiB, %s, erase size: %d KiB, page size: %d, OOB size: %d\n",
4028 (int)(chip->chipsize >> 20), nand_is_slc(chip) ? "SLC" : "MLC",
4029 mtd->erasesize >> 10, mtd->writesize, mtd->oobsize);
4033 static const char * const nand_ecc_modes[] = {
4034 [NAND_ECC_NONE] = "none",
4035 [NAND_ECC_SOFT] = "soft",
4036 [NAND_ECC_HW] = "hw",
4037 [NAND_ECC_HW_SYNDROME] = "hw_syndrome",
4038 [NAND_ECC_HW_OOB_FIRST] = "hw_oob_first",
4039 [NAND_ECC_ON_DIE] = "on-die",
4042 static int of_get_nand_ecc_mode(struct device_node *np)
4047 err = of_property_read_string(np, "nand-ecc-mode", &pm);
4051 for (i = 0; i < ARRAY_SIZE(nand_ecc_modes); i++)
4052 if (!strcasecmp(pm, nand_ecc_modes[i]))
4056 * For backward compatibility we support few obsoleted values that don't
4057 * have their mappings into nand_ecc_modes_t anymore (they were merged
4058 * with other enums).
4060 if (!strcasecmp(pm, "soft_bch"))
4061 return NAND_ECC_SOFT;
4066 static const char * const nand_ecc_algos[] = {
4067 [NAND_ECC_HAMMING] = "hamming",
4068 [NAND_ECC_BCH] = "bch",
4071 static int of_get_nand_ecc_algo(struct device_node *np)
4076 err = of_property_read_string(np, "nand-ecc-algo", &pm);
4078 for (i = NAND_ECC_HAMMING; i < ARRAY_SIZE(nand_ecc_algos); i++)
4079 if (!strcasecmp(pm, nand_ecc_algos[i]))
4085 * For backward compatibility we also read "nand-ecc-mode" checking
4086 * for some obsoleted values that were specifying ECC algorithm.
4088 err = of_property_read_string(np, "nand-ecc-mode", &pm);
4092 if (!strcasecmp(pm, "soft"))
4093 return NAND_ECC_HAMMING;
4094 else if (!strcasecmp(pm, "soft_bch"))
4095 return NAND_ECC_BCH;
4100 static int of_get_nand_ecc_step_size(struct device_node *np)
4105 ret = of_property_read_u32(np, "nand-ecc-step-size", &val);
4106 return ret ? ret : val;
4109 static int of_get_nand_ecc_strength(struct device_node *np)
4114 ret = of_property_read_u32(np, "nand-ecc-strength", &val);
4115 return ret ? ret : val;
4118 static int of_get_nand_bus_width(struct device_node *np)
4122 if (of_property_read_u32(np, "nand-bus-width", &val))
4134 static bool of_get_nand_on_flash_bbt(struct device_node *np)
4136 return of_property_read_bool(np, "nand-on-flash-bbt");
4139 static int nand_dt_init(struct nand_chip *chip)
4141 struct device_node *dn = nand_get_flash_node(chip);
4142 int ecc_mode, ecc_algo, ecc_strength, ecc_step;
4147 if (of_get_nand_bus_width(dn) == 16)
4148 chip->options |= NAND_BUSWIDTH_16;
4150 if (of_get_nand_on_flash_bbt(dn))
4151 chip->bbt_options |= NAND_BBT_USE_FLASH;
4153 ecc_mode = of_get_nand_ecc_mode(dn);
4154 ecc_algo = of_get_nand_ecc_algo(dn);
4155 ecc_strength = of_get_nand_ecc_strength(dn);
4156 ecc_step = of_get_nand_ecc_step_size(dn);
4159 chip->ecc.mode = ecc_mode;
4162 chip->ecc.algo = ecc_algo;
4164 if (ecc_strength >= 0)
4165 chip->ecc.strength = ecc_strength;
4168 chip->ecc.size = ecc_step;
4170 if (of_property_read_bool(dn, "nand-ecc-maximize"))
4171 chip->ecc.options |= NAND_ECC_MAXIMIZE;
4177 * nand_scan_ident - [NAND Interface] Scan for the NAND device
4178 * @mtd: MTD device structure
4179 * @maxchips: number of chips to scan for
4180 * @table: alternative NAND ID table
4182 * This is the first phase of the normal nand_scan() function. It reads the
4183 * flash ID and sets up MTD fields accordingly.
4186 int nand_scan_ident(struct mtd_info *mtd, int maxchips,
4187 struct nand_flash_dev *table)
4189 int i, nand_maf_id, nand_dev_id;
4190 struct nand_chip *chip = mtd_to_nand(mtd);
4193 ret = nand_dt_init(chip);
4197 if (!mtd->name && mtd->dev.parent)
4198 mtd->name = dev_name(mtd->dev.parent);
4200 if ((!chip->cmdfunc || !chip->select_chip) && !chip->cmd_ctrl) {
4202 * Default functions assigned for chip_select() and
4203 * cmdfunc() both expect cmd_ctrl() to be populated,
4204 * so we need to check that that's the case
4206 pr_err("chip.cmd_ctrl() callback is not provided");
4209 /* Set the default functions */
4210 nand_set_defaults(chip);
4212 /* Read the flash type */
4213 ret = nand_detect(chip, table);
4215 if (!(chip->options & NAND_SCAN_SILENT_NODEV))
4216 pr_warn("No NAND device found\n");
4217 chip->select_chip(mtd, -1);
4221 nand_maf_id = chip->id.data[0];
4222 nand_dev_id = chip->id.data[1];
4224 chip->select_chip(mtd, -1);
4226 /* Check for a chip array */
4227 for (i = 1; i < maxchips; i++) {
4228 /* See comment in nand_get_flash_type for reset */
4229 nand_reset(chip, i);
4231 chip->select_chip(mtd, i);
4232 /* Send the command for reading device ID */
4233 chip->cmdfunc(mtd, NAND_CMD_READID, 0x00, -1);
4234 /* Read manufacturer and device IDs */
4235 if (nand_maf_id != chip->read_byte(mtd) ||
4236 nand_dev_id != chip->read_byte(mtd)) {
4237 chip->select_chip(mtd, -1);
4240 chip->select_chip(mtd, -1);
4243 pr_info("%d chips detected\n", i);
4245 /* Store the number of chips and calc total size for mtd */
4247 mtd->size = i * chip->chipsize;
4251 EXPORT_SYMBOL(nand_scan_ident);
4253 static int nand_set_ecc_soft_ops(struct mtd_info *mtd)
4255 struct nand_chip *chip = mtd_to_nand(mtd);
4256 struct nand_ecc_ctrl *ecc = &chip->ecc;
4258 if (WARN_ON(ecc->mode != NAND_ECC_SOFT))
4261 switch (ecc->algo) {
4262 case NAND_ECC_HAMMING:
4263 ecc->calculate = nand_calculate_ecc;
4264 ecc->correct = nand_correct_data;
4265 ecc->read_page = nand_read_page_swecc;
4266 ecc->read_subpage = nand_read_subpage;
4267 ecc->write_page = nand_write_page_swecc;
4268 ecc->read_page_raw = nand_read_page_raw;
4269 ecc->write_page_raw = nand_write_page_raw;
4270 ecc->read_oob = nand_read_oob_std;
4271 ecc->write_oob = nand_write_oob_std;
4278 if (!mtd_nand_has_bch()) {
4279 WARN(1, "CONFIG_MTD_NAND_ECC_BCH not enabled\n");
4282 ecc->calculate = nand_bch_calculate_ecc;
4283 ecc->correct = nand_bch_correct_data;
4284 ecc->read_page = nand_read_page_swecc;
4285 ecc->read_subpage = nand_read_subpage;
4286 ecc->write_page = nand_write_page_swecc;
4287 ecc->read_page_raw = nand_read_page_raw;
4288 ecc->write_page_raw = nand_write_page_raw;
4289 ecc->read_oob = nand_read_oob_std;
4290 ecc->write_oob = nand_write_oob_std;
4293 * Board driver should supply ecc.size and ecc.strength
4294 * values to select how many bits are correctable.
4295 * Otherwise, default to 4 bits for large page devices.
4297 if (!ecc->size && (mtd->oobsize >= 64)) {
4303 * if no ecc placement scheme was provided pickup the default
4306 if (!mtd->ooblayout) {
4307 /* handle large page devices only */
4308 if (mtd->oobsize < 64) {
4309 WARN(1, "OOB layout is required when using software BCH on small pages\n");
4313 mtd_set_ooblayout(mtd, &nand_ooblayout_lp_ops);
4318 * We can only maximize ECC config when the default layout is
4319 * used, otherwise we don't know how many bytes can really be
4322 if (mtd->ooblayout == &nand_ooblayout_lp_ops &&
4323 ecc->options & NAND_ECC_MAXIMIZE) {
4326 /* Always prefer 1k blocks over 512bytes ones */
4328 steps = mtd->writesize / ecc->size;
4330 /* Reserve 2 bytes for the BBM */
4331 bytes = (mtd->oobsize - 2) / steps;
4332 ecc->strength = bytes * 8 / fls(8 * ecc->size);
4335 /* See nand_bch_init() for details. */
4337 ecc->priv = nand_bch_init(mtd);
4339 WARN(1, "BCH ECC initialization failed!\n");
4344 WARN(1, "Unsupported ECC algorithm!\n");
4350 * nand_check_ecc_caps - check the sanity of preset ECC settings
4351 * @chip: nand chip info structure
4352 * @caps: ECC caps info structure
4353 * @oobavail: OOB size that the ECC engine can use
4355 * When ECC step size and strength are already set, check if they are supported
4356 * by the controller and the calculated ECC bytes fit within the chip's OOB.
4357 * On success, the calculated ECC bytes is set.
4359 int nand_check_ecc_caps(struct nand_chip *chip,
4360 const struct nand_ecc_caps *caps, int oobavail)
4362 struct mtd_info *mtd = nand_to_mtd(chip);
4363 const struct nand_ecc_step_info *stepinfo;
4364 int preset_step = chip->ecc.size;
4365 int preset_strength = chip->ecc.strength;
4366 int nsteps, ecc_bytes;
4369 if (WARN_ON(oobavail < 0))
4372 if (!preset_step || !preset_strength)
4375 nsteps = mtd->writesize / preset_step;
4377 for (i = 0; i < caps->nstepinfos; i++) {
4378 stepinfo = &caps->stepinfos[i];
4380 if (stepinfo->stepsize != preset_step)
4383 for (j = 0; j < stepinfo->nstrengths; j++) {
4384 if (stepinfo->strengths[j] != preset_strength)
4387 ecc_bytes = caps->calc_ecc_bytes(preset_step,
4389 if (WARN_ON_ONCE(ecc_bytes < 0))
4392 if (ecc_bytes * nsteps > oobavail) {
4393 pr_err("ECC (step, strength) = (%d, %d) does not fit in OOB",
4394 preset_step, preset_strength);
4398 chip->ecc.bytes = ecc_bytes;
4404 pr_err("ECC (step, strength) = (%d, %d) not supported on this controller",
4405 preset_step, preset_strength);
4409 EXPORT_SYMBOL_GPL(nand_check_ecc_caps);
4412 * nand_match_ecc_req - meet the chip's requirement with least ECC bytes
4413 * @chip: nand chip info structure
4414 * @caps: ECC engine caps info structure
4415 * @oobavail: OOB size that the ECC engine can use
4417 * If a chip's ECC requirement is provided, try to meet it with the least
4418 * number of ECC bytes (i.e. with the largest number of OOB-free bytes).
4419 * On success, the chosen ECC settings are set.
4421 int nand_match_ecc_req(struct nand_chip *chip,
4422 const struct nand_ecc_caps *caps, int oobavail)
4424 struct mtd_info *mtd = nand_to_mtd(chip);
4425 const struct nand_ecc_step_info *stepinfo;
4426 int req_step = chip->ecc_step_ds;
4427 int req_strength = chip->ecc_strength_ds;
4428 int req_corr, step_size, strength, nsteps, ecc_bytes, ecc_bytes_total;
4429 int best_step, best_strength, best_ecc_bytes;
4430 int best_ecc_bytes_total = INT_MAX;
4433 if (WARN_ON(oobavail < 0))
4436 /* No information provided by the NAND chip */
4437 if (!req_step || !req_strength)
4440 /* number of correctable bits the chip requires in a page */
4441 req_corr = mtd->writesize / req_step * req_strength;
4443 for (i = 0; i < caps->nstepinfos; i++) {
4444 stepinfo = &caps->stepinfos[i];
4445 step_size = stepinfo->stepsize;
4447 for (j = 0; j < stepinfo->nstrengths; j++) {
4448 strength = stepinfo->strengths[j];
4451 * If both step size and strength are smaller than the
4452 * chip's requirement, it is not easy to compare the
4453 * resulted reliability.
4455 if (step_size < req_step && strength < req_strength)
4458 if (mtd->writesize % step_size)
4461 nsteps = mtd->writesize / step_size;
4463 ecc_bytes = caps->calc_ecc_bytes(step_size, strength);
4464 if (WARN_ON_ONCE(ecc_bytes < 0))
4466 ecc_bytes_total = ecc_bytes * nsteps;
4468 if (ecc_bytes_total > oobavail ||
4469 strength * nsteps < req_corr)
4473 * We assume the best is to meet the chip's requrement
4474 * with the least number of ECC bytes.
4476 if (ecc_bytes_total < best_ecc_bytes_total) {
4477 best_ecc_bytes_total = ecc_bytes_total;
4478 best_step = step_size;
4479 best_strength = strength;
4480 best_ecc_bytes = ecc_bytes;
4485 if (best_ecc_bytes_total == INT_MAX)
4488 chip->ecc.size = best_step;
4489 chip->ecc.strength = best_strength;
4490 chip->ecc.bytes = best_ecc_bytes;
4494 EXPORT_SYMBOL_GPL(nand_match_ecc_req);
4497 * nand_maximize_ecc - choose the max ECC strength available
4498 * @chip: nand chip info structure
4499 * @caps: ECC engine caps info structure
4500 * @oobavail: OOB size that the ECC engine can use
4502 * Choose the max ECC strength that is supported on the controller, and can fit
4503 * within the chip's OOB. On success, the chosen ECC settings are set.
4505 int nand_maximize_ecc(struct nand_chip *chip,
4506 const struct nand_ecc_caps *caps, int oobavail)
4508 struct mtd_info *mtd = nand_to_mtd(chip);
4509 const struct nand_ecc_step_info *stepinfo;
4510 int step_size, strength, nsteps, ecc_bytes, corr;
4513 int best_strength, best_ecc_bytes;
4516 if (WARN_ON(oobavail < 0))
4519 for (i = 0; i < caps->nstepinfos; i++) {
4520 stepinfo = &caps->stepinfos[i];
4521 step_size = stepinfo->stepsize;
4523 /* If chip->ecc.size is already set, respect it */
4524 if (chip->ecc.size && step_size != chip->ecc.size)
4527 for (j = 0; j < stepinfo->nstrengths; j++) {
4528 strength = stepinfo->strengths[j];
4530 if (mtd->writesize % step_size)
4533 nsteps = mtd->writesize / step_size;
4535 ecc_bytes = caps->calc_ecc_bytes(step_size, strength);
4536 if (WARN_ON_ONCE(ecc_bytes < 0))
4539 if (ecc_bytes * nsteps > oobavail)
4542 corr = strength * nsteps;
4545 * If the number of correctable bits is the same,
4546 * bigger step_size has more reliability.
4548 if (corr > best_corr ||
4549 (corr == best_corr && step_size > best_step)) {
4551 best_step = step_size;
4552 best_strength = strength;
4553 best_ecc_bytes = ecc_bytes;
4561 chip->ecc.size = best_step;
4562 chip->ecc.strength = best_strength;
4563 chip->ecc.bytes = best_ecc_bytes;
4567 EXPORT_SYMBOL_GPL(nand_maximize_ecc);
4570 * Check if the chip configuration meet the datasheet requirements.
4572 * If our configuration corrects A bits per B bytes and the minimum
4573 * required correction level is X bits per Y bytes, then we must ensure
4574 * both of the following are true:
4576 * (1) A / B >= X / Y
4579 * Requirement (1) ensures we can correct for the required bitflip density.
4580 * Requirement (2) ensures we can correct even when all bitflips are clumped
4581 * in the same sector.
4583 static bool nand_ecc_strength_good(struct mtd_info *mtd)
4585 struct nand_chip *chip = mtd_to_nand(mtd);
4586 struct nand_ecc_ctrl *ecc = &chip->ecc;
4589 if (ecc->size == 0 || chip->ecc_step_ds == 0)
4590 /* Not enough information */
4594 * We get the number of corrected bits per page to compare
4595 * the correction density.
4597 corr = (mtd->writesize * ecc->strength) / ecc->size;
4598 ds_corr = (mtd->writesize * chip->ecc_strength_ds) / chip->ecc_step_ds;
4600 return corr >= ds_corr && ecc->strength >= chip->ecc_strength_ds;
4603 static bool invalid_ecc_page_accessors(struct nand_chip *chip)
4605 struct nand_ecc_ctrl *ecc = &chip->ecc;
4607 if (nand_standard_page_accessors(ecc))
4611 * NAND_ECC_CUSTOM_PAGE_ACCESS flag is set, make sure the NAND
4612 * controller driver implements all the page accessors because
4613 * default helpers are not suitable when the core does not
4614 * send the READ0/PAGEPROG commands.
4616 return (!ecc->read_page || !ecc->write_page ||
4617 !ecc->read_page_raw || !ecc->write_page_raw ||
4618 (NAND_HAS_SUBPAGE_READ(chip) && !ecc->read_subpage) ||
4619 (NAND_HAS_SUBPAGE_WRITE(chip) && !ecc->write_subpage &&
4620 ecc->hwctl && ecc->calculate));
4624 * nand_scan_tail - [NAND Interface] Scan for the NAND device
4625 * @mtd: MTD device structure
4627 * This is the second phase of the normal nand_scan() function. It fills out
4628 * all the uninitialized function pointers with the defaults and scans for a
4629 * bad block table if appropriate.
4631 int nand_scan_tail(struct mtd_info *mtd)
4633 struct nand_chip *chip = mtd_to_nand(mtd);
4634 struct nand_ecc_ctrl *ecc = &chip->ecc;
4635 struct nand_buffers *nbuf = NULL;
4638 /* New bad blocks should be marked in OOB, flash-based BBT, or both */
4639 if (WARN_ON((chip->bbt_options & NAND_BBT_NO_OOB_BBM) &&
4640 !(chip->bbt_options & NAND_BBT_USE_FLASH))) {
4644 if (invalid_ecc_page_accessors(chip)) {
4645 pr_err("Invalid ECC page accessors setup\n");
4649 if (!(chip->options & NAND_OWN_BUFFERS)) {
4650 nbuf = kzalloc(sizeof(*nbuf), GFP_KERNEL);
4654 nbuf->ecccalc = kmalloc(mtd->oobsize, GFP_KERNEL);
4655 if (!nbuf->ecccalc) {
4660 nbuf->ecccode = kmalloc(mtd->oobsize, GFP_KERNEL);
4661 if (!nbuf->ecccode) {
4666 nbuf->databuf = kmalloc(mtd->writesize + mtd->oobsize,
4668 if (!nbuf->databuf) {
4673 chip->buffers = nbuf;
4674 } else if (!chip->buffers) {
4679 * FIXME: some NAND manufacturer drivers expect the first die to be
4680 * selected when manufacturer->init() is called. They should be fixed
4681 * to explictly select the relevant die when interacting with the NAND
4684 chip->select_chip(mtd, 0);
4685 ret = nand_manufacturer_init(chip);
4686 chip->select_chip(mtd, -1);
4690 /* Set the internal oob buffer location, just after the page data */
4691 chip->oob_poi = chip->buffers->databuf + mtd->writesize;
4694 * If no default placement scheme is given, select an appropriate one.
4696 if (!mtd->ooblayout &&
4697 !(ecc->mode == NAND_ECC_SOFT && ecc->algo == NAND_ECC_BCH)) {
4698 switch (mtd->oobsize) {
4701 mtd_set_ooblayout(mtd, &nand_ooblayout_sp_ops);
4705 mtd_set_ooblayout(mtd, &nand_ooblayout_lp_hamming_ops);
4709 * Expose the whole OOB area to users if ECC_NONE
4710 * is passed. We could do that for all kind of
4711 * ->oobsize, but we must keep the old large/small
4712 * page with ECC layout when ->oobsize <= 128 for
4713 * compatibility reasons.
4715 if (ecc->mode == NAND_ECC_NONE) {
4716 mtd_set_ooblayout(mtd,
4717 &nand_ooblayout_lp_ops);
4721 WARN(1, "No oob scheme defined for oobsize %d\n",
4724 goto err_nand_manuf_cleanup;
4729 * Check ECC mode, default to software if 3byte/512byte hardware ECC is
4730 * selected and we have 256 byte pagesize fallback to software ECC
4733 switch (ecc->mode) {
4734 case NAND_ECC_HW_OOB_FIRST:
4735 /* Similar to NAND_ECC_HW, but a separate read_page handle */
4736 if (!ecc->calculate || !ecc->correct || !ecc->hwctl) {
4737 WARN(1, "No ECC functions supplied; hardware ECC not possible\n");
4739 goto err_nand_manuf_cleanup;
4741 if (!ecc->read_page)
4742 ecc->read_page = nand_read_page_hwecc_oob_first;
4745 /* Use standard hwecc read page function? */
4746 if (!ecc->read_page)
4747 ecc->read_page = nand_read_page_hwecc;
4748 if (!ecc->write_page)
4749 ecc->write_page = nand_write_page_hwecc;
4750 if (!ecc->read_page_raw)
4751 ecc->read_page_raw = nand_read_page_raw;
4752 if (!ecc->write_page_raw)
4753 ecc->write_page_raw = nand_write_page_raw;
4755 ecc->read_oob = nand_read_oob_std;
4756 if (!ecc->write_oob)
4757 ecc->write_oob = nand_write_oob_std;
4758 if (!ecc->read_subpage)
4759 ecc->read_subpage = nand_read_subpage;
4760 if (!ecc->write_subpage && ecc->hwctl && ecc->calculate)
4761 ecc->write_subpage = nand_write_subpage_hwecc;
4763 case NAND_ECC_HW_SYNDROME:
4764 if ((!ecc->calculate || !ecc->correct || !ecc->hwctl) &&
4766 ecc->read_page == nand_read_page_hwecc ||
4768 ecc->write_page == nand_write_page_hwecc)) {
4769 WARN(1, "No ECC functions supplied; hardware ECC not possible\n");
4771 goto err_nand_manuf_cleanup;
4773 /* Use standard syndrome read/write page function? */
4774 if (!ecc->read_page)
4775 ecc->read_page = nand_read_page_syndrome;
4776 if (!ecc->write_page)
4777 ecc->write_page = nand_write_page_syndrome;
4778 if (!ecc->read_page_raw)
4779 ecc->read_page_raw = nand_read_page_raw_syndrome;
4780 if (!ecc->write_page_raw)
4781 ecc->write_page_raw = nand_write_page_raw_syndrome;
4783 ecc->read_oob = nand_read_oob_syndrome;
4784 if (!ecc->write_oob)
4785 ecc->write_oob = nand_write_oob_syndrome;
4787 if (mtd->writesize >= ecc->size) {
4788 if (!ecc->strength) {
4789 WARN(1, "Driver must set ecc.strength when using hardware ECC\n");
4791 goto err_nand_manuf_cleanup;
4795 pr_warn("%d byte HW ECC not possible on %d byte page size, fallback to SW ECC\n",
4796 ecc->size, mtd->writesize);
4797 ecc->mode = NAND_ECC_SOFT;
4798 ecc->algo = NAND_ECC_HAMMING;
4801 ret = nand_set_ecc_soft_ops(mtd);
4804 goto err_nand_manuf_cleanup;
4808 case NAND_ECC_ON_DIE:
4809 if (!ecc->read_page || !ecc->write_page) {
4810 WARN(1, "No ECC functions supplied; on-die ECC not possible\n");
4812 goto err_nand_manuf_cleanup;
4815 ecc->read_oob = nand_read_oob_std;
4816 if (!ecc->write_oob)
4817 ecc->write_oob = nand_write_oob_std;
4821 pr_warn("NAND_ECC_NONE selected by board driver. This is not recommended!\n");
4822 ecc->read_page = nand_read_page_raw;
4823 ecc->write_page = nand_write_page_raw;
4824 ecc->read_oob = nand_read_oob_std;
4825 ecc->read_page_raw = nand_read_page_raw;
4826 ecc->write_page_raw = nand_write_page_raw;
4827 ecc->write_oob = nand_write_oob_std;
4828 ecc->size = mtd->writesize;
4834 WARN(1, "Invalid NAND_ECC_MODE %d\n", ecc->mode);
4836 goto err_nand_manuf_cleanup;
4839 /* For many systems, the standard OOB write also works for raw */
4840 if (!ecc->read_oob_raw)
4841 ecc->read_oob_raw = ecc->read_oob;
4842 if (!ecc->write_oob_raw)
4843 ecc->write_oob_raw = ecc->write_oob;
4845 /* propagate ecc info to mtd_info */
4846 mtd->ecc_strength = ecc->strength;
4847 mtd->ecc_step_size = ecc->size;
4850 * Set the number of read / write steps for one page depending on ECC
4853 ecc->steps = mtd->writesize / ecc->size;
4854 if (ecc->steps * ecc->size != mtd->writesize) {
4855 WARN(1, "Invalid ECC parameters\n");
4857 goto err_nand_manuf_cleanup;
4859 ecc->total = ecc->steps * ecc->bytes;
4860 if (ecc->total > mtd->oobsize) {
4861 WARN(1, "Total number of ECC bytes exceeded oobsize\n");
4863 goto err_nand_manuf_cleanup;
4867 * The number of bytes available for a client to place data into
4868 * the out of band area.
4870 ret = mtd_ooblayout_count_freebytes(mtd);
4874 mtd->oobavail = ret;
4876 /* ECC sanity check: warn if it's too weak */
4877 if (!nand_ecc_strength_good(mtd))
4878 pr_warn("WARNING: %s: the ECC used on your system is too weak compared to the one required by the NAND chip\n",
4881 /* Allow subpage writes up to ecc.steps. Not possible for MLC flash */
4882 if (!(chip->options & NAND_NO_SUBPAGE_WRITE) && nand_is_slc(chip)) {
4883 switch (ecc->steps) {
4885 mtd->subpage_sft = 1;
4890 mtd->subpage_sft = 2;
4894 chip->subpagesize = mtd->writesize >> mtd->subpage_sft;
4896 /* Initialize state */
4897 chip->state = FL_READY;
4899 /* Invalidate the pagebuffer reference */
4902 /* Large page NAND with SOFT_ECC should support subpage reads */
4903 switch (ecc->mode) {
4905 if (chip->page_shift > 9)
4906 chip->options |= NAND_SUBPAGE_READ;
4913 /* Fill in remaining MTD driver data */
4914 mtd->type = nand_is_slc(chip) ? MTD_NANDFLASH : MTD_MLCNANDFLASH;
4915 mtd->flags = (chip->options & NAND_ROM) ? MTD_CAP_ROM :
4917 mtd->_erase = nand_erase;
4919 mtd->_unpoint = NULL;
4920 mtd->_read = nand_read;
4921 mtd->_write = nand_write;
4922 mtd->_panic_write = panic_nand_write;
4923 mtd->_read_oob = nand_read_oob;
4924 mtd->_write_oob = nand_write_oob;
4925 mtd->_sync = nand_sync;
4927 mtd->_unlock = NULL;
4928 mtd->_suspend = nand_suspend;
4929 mtd->_resume = nand_resume;
4930 mtd->_reboot = nand_shutdown;
4931 mtd->_block_isreserved = nand_block_isreserved;
4932 mtd->_block_isbad = nand_block_isbad;
4933 mtd->_block_markbad = nand_block_markbad;
4934 mtd->_max_bad_blocks = nand_max_bad_blocks;
4935 mtd->writebufsize = mtd->writesize;
4938 * Initialize bitflip_threshold to its default prior scan_bbt() call.
4939 * scan_bbt() might invoke mtd_read(), thus bitflip_threshold must be
4942 if (!mtd->bitflip_threshold)
4943 mtd->bitflip_threshold = DIV_ROUND_UP(mtd->ecc_strength * 3, 4);
4945 /* Initialize the ->data_interface field. */
4946 ret = nand_init_data_interface(chip);
4948 goto err_nand_manuf_cleanup;
4950 /* Enter fastest possible mode on all dies. */
4951 for (i = 0; i < chip->numchips; i++) {
4952 chip->select_chip(mtd, i);
4953 ret = nand_setup_data_interface(chip, i);
4954 chip->select_chip(mtd, -1);
4957 goto err_nand_data_iface_cleanup;
4960 /* Check, if we should skip the bad block table scan */
4961 if (chip->options & NAND_SKIP_BBTSCAN)
4964 /* Build bad block table */
4965 ret = chip->scan_bbt(mtd);
4967 goto err_nand_data_iface_cleanup;
4971 err_nand_data_iface_cleanup:
4972 nand_release_data_interface(chip);
4974 err_nand_manuf_cleanup:
4975 nand_manufacturer_cleanup(chip);
4979 kfree(nbuf->databuf);
4980 kfree(nbuf->ecccode);
4981 kfree(nbuf->ecccalc);
4987 EXPORT_SYMBOL(nand_scan_tail);
4990 * is_module_text_address() isn't exported, and it's mostly a pointless
4991 * test if this is a module _anyway_ -- they'd have to try _really_ hard
4992 * to call us from in-kernel code if the core NAND support is modular.
4995 #define caller_is_module() (1)
4997 #define caller_is_module() \
4998 is_module_text_address((unsigned long)__builtin_return_address(0))
5002 * nand_scan - [NAND Interface] Scan for the NAND device
5003 * @mtd: MTD device structure
5004 * @maxchips: number of chips to scan for
5006 * This fills out all the uninitialized function pointers with the defaults.
5007 * The flash ID is read and the mtd/chip structures are filled with the
5008 * appropriate values.
5010 int nand_scan(struct mtd_info *mtd, int maxchips)
5014 ret = nand_scan_ident(mtd, maxchips, NULL);
5016 ret = nand_scan_tail(mtd);
5019 EXPORT_SYMBOL(nand_scan);
5022 * nand_cleanup - [NAND Interface] Free resources held by the NAND device
5023 * @chip: NAND chip object
5025 void nand_cleanup(struct nand_chip *chip)
5027 if (chip->ecc.mode == NAND_ECC_SOFT &&
5028 chip->ecc.algo == NAND_ECC_BCH)
5029 nand_bch_free((struct nand_bch_control *)chip->ecc.priv);
5031 nand_release_data_interface(chip);
5033 /* Free bad block table memory */
5035 if (!(chip->options & NAND_OWN_BUFFERS) && chip->buffers) {
5036 kfree(chip->buffers->databuf);
5037 kfree(chip->buffers->ecccode);
5038 kfree(chip->buffers->ecccalc);
5039 kfree(chip->buffers);
5042 /* Free bad block descriptor memory */
5043 if (chip->badblock_pattern && chip->badblock_pattern->options
5044 & NAND_BBT_DYNAMICSTRUCT)
5045 kfree(chip->badblock_pattern);
5047 /* Free manufacturer priv data. */
5048 nand_manufacturer_cleanup(chip);
5050 EXPORT_SYMBOL_GPL(nand_cleanup);
5053 * nand_release - [NAND Interface] Unregister the MTD device and free resources
5054 * held by the NAND device
5055 * @mtd: MTD device structure
5057 void nand_release(struct mtd_info *mtd)
5059 mtd_device_unregister(mtd);
5060 nand_cleanup(mtd_to_nand(mtd));
5062 EXPORT_SYMBOL_GPL(nand_release);
5064 MODULE_LICENSE("GPL");
5065 MODULE_AUTHOR("Steven J. Hill <sjhill@realitydiluted.com>");
5066 MODULE_AUTHOR("Thomas Gleixner <tglx@linutronix.de>");
5067 MODULE_DESCRIPTION("Generic NAND flash driver code");