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);
567 /* Broken xD cards report WP despite being writable */
568 if (chip->options & NAND_BROKEN_XD)
571 /* Check the WP bit */
572 ret = nand_status_op(chip, &status);
576 return status & NAND_STATUS_WP ? 0 : 1;
580 * nand_block_isreserved - [GENERIC] Check if a block is marked reserved.
581 * @mtd: MTD device structure
582 * @ofs: offset from device start
584 * Check if the block is marked as reserved.
586 static int nand_block_isreserved(struct mtd_info *mtd, loff_t ofs)
588 struct nand_chip *chip = mtd_to_nand(mtd);
592 /* Return info from the table */
593 return nand_isreserved_bbt(mtd, ofs);
597 * nand_block_checkbad - [GENERIC] Check if a block is marked bad
598 * @mtd: MTD device structure
599 * @ofs: offset from device start
600 * @allowbbt: 1, if its allowed to access the bbt area
602 * Check, if the block is bad. Either by reading the bad block table or
603 * calling of the scan function.
605 static int nand_block_checkbad(struct mtd_info *mtd, loff_t ofs, int allowbbt)
607 struct nand_chip *chip = mtd_to_nand(mtd);
610 return chip->block_bad(mtd, ofs);
612 /* Return info from the table */
613 return nand_isbad_bbt(mtd, ofs, allowbbt);
617 * panic_nand_wait_ready - [GENERIC] Wait for the ready pin after commands.
618 * @mtd: MTD device structure
621 * Helper function for nand_wait_ready used when needing to wait in interrupt
624 static void panic_nand_wait_ready(struct mtd_info *mtd, unsigned long timeo)
626 struct nand_chip *chip = mtd_to_nand(mtd);
629 /* Wait for the device to get ready */
630 for (i = 0; i < timeo; i++) {
631 if (chip->dev_ready(mtd))
633 touch_softlockup_watchdog();
639 * nand_wait_ready - [GENERIC] Wait for the ready pin after commands.
640 * @mtd: MTD device structure
642 * Wait for the ready pin after a command, and warn if a timeout occurs.
644 void nand_wait_ready(struct mtd_info *mtd)
646 struct nand_chip *chip = mtd_to_nand(mtd);
647 unsigned long timeo = 400;
649 if (in_interrupt() || oops_in_progress)
650 return panic_nand_wait_ready(mtd, timeo);
652 /* Wait until command is processed or timeout occurs */
653 timeo = jiffies + msecs_to_jiffies(timeo);
655 if (chip->dev_ready(mtd))
658 } while (time_before(jiffies, timeo));
660 if (!chip->dev_ready(mtd))
661 pr_warn_ratelimited("timeout while waiting for chip to become ready\n");
663 EXPORT_SYMBOL_GPL(nand_wait_ready);
666 * nand_wait_status_ready - [GENERIC] Wait for the ready status after commands.
667 * @mtd: MTD device structure
668 * @timeo: Timeout in ms
670 * Wait for status ready (i.e. command done) or timeout.
672 static void nand_wait_status_ready(struct mtd_info *mtd, unsigned long timeo)
674 register struct nand_chip *chip = mtd_to_nand(mtd);
677 timeo = jiffies + msecs_to_jiffies(timeo);
681 ret = nand_read_data_op(chip, &status, sizeof(status), true);
685 if (status & NAND_STATUS_READY)
687 touch_softlockup_watchdog();
688 } while (time_before(jiffies, timeo));
692 * nand_command - [DEFAULT] Send command to NAND device
693 * @mtd: MTD device structure
694 * @command: the command to be sent
695 * @column: the column address for this command, -1 if none
696 * @page_addr: the page address for this command, -1 if none
698 * Send command to NAND device. This function is used for small page devices
699 * (512 Bytes per page).
701 static void nand_command(struct mtd_info *mtd, unsigned int command,
702 int column, int page_addr)
704 register struct nand_chip *chip = mtd_to_nand(mtd);
705 int ctrl = NAND_CTRL_CLE | NAND_CTRL_CHANGE;
707 /* Write out the command to the device */
708 if (command == NAND_CMD_SEQIN) {
711 if (column >= mtd->writesize) {
713 column -= mtd->writesize;
714 readcmd = NAND_CMD_READOOB;
715 } else if (column < 256) {
716 /* First 256 bytes --> READ0 */
717 readcmd = NAND_CMD_READ0;
720 readcmd = NAND_CMD_READ1;
722 chip->cmd_ctrl(mtd, readcmd, ctrl);
723 ctrl &= ~NAND_CTRL_CHANGE;
725 if (command != NAND_CMD_NONE)
726 chip->cmd_ctrl(mtd, command, ctrl);
728 /* Address cycle, when necessary */
729 ctrl = NAND_CTRL_ALE | NAND_CTRL_CHANGE;
730 /* Serially input address */
732 /* Adjust columns for 16 bit buswidth */
733 if (chip->options & NAND_BUSWIDTH_16 &&
734 !nand_opcode_8bits(command))
736 chip->cmd_ctrl(mtd, column, ctrl);
737 ctrl &= ~NAND_CTRL_CHANGE;
739 if (page_addr != -1) {
740 chip->cmd_ctrl(mtd, page_addr, ctrl);
741 ctrl &= ~NAND_CTRL_CHANGE;
742 chip->cmd_ctrl(mtd, page_addr >> 8, ctrl);
743 if (chip->options & NAND_ROW_ADDR_3)
744 chip->cmd_ctrl(mtd, page_addr >> 16, ctrl);
746 chip->cmd_ctrl(mtd, NAND_CMD_NONE, NAND_NCE | NAND_CTRL_CHANGE);
749 * Program and erase have their own busy handlers status and sequential
755 case NAND_CMD_PAGEPROG:
756 case NAND_CMD_ERASE1:
757 case NAND_CMD_ERASE2:
759 case NAND_CMD_STATUS:
760 case NAND_CMD_READID:
761 case NAND_CMD_SET_FEATURES:
767 udelay(chip->chip_delay);
768 chip->cmd_ctrl(mtd, NAND_CMD_STATUS,
769 NAND_CTRL_CLE | NAND_CTRL_CHANGE);
771 NAND_CMD_NONE, NAND_NCE | NAND_CTRL_CHANGE);
772 /* EZ-NAND can take upto 250ms as per ONFi v4.0 */
773 nand_wait_status_ready(mtd, 250);
776 /* This applies to read commands */
779 * READ0 is sometimes used to exit GET STATUS mode. When this
780 * is the case no address cycles are requested, and we can use
781 * this information to detect that we should not wait for the
782 * device to be ready.
784 if (column == -1 && page_addr == -1)
789 * If we don't have access to the busy pin, we apply the given
792 if (!chip->dev_ready) {
793 udelay(chip->chip_delay);
798 * Apply this short delay always to ensure that we do wait tWB in
799 * any case on any machine.
803 nand_wait_ready(mtd);
806 static void nand_ccs_delay(struct nand_chip *chip)
809 * The controller already takes care of waiting for tCCS when the RNDIN
810 * or RNDOUT command is sent, return directly.
812 if (!(chip->options & NAND_WAIT_TCCS))
816 * Wait tCCS_min if it is correctly defined, otherwise wait 500ns
817 * (which should be safe for all NANDs).
819 if (chip->data_interface && chip->data_interface->timings.sdr.tCCS_min)
820 ndelay(chip->data_interface->timings.sdr.tCCS_min / 1000);
826 * nand_command_lp - [DEFAULT] Send command to NAND large page device
827 * @mtd: MTD device structure
828 * @command: the command to be sent
829 * @column: the column address for this command, -1 if none
830 * @page_addr: the page address for this command, -1 if none
832 * Send command to NAND device. This is the version for the new large page
833 * devices. We don't have the separate regions as we have in the small page
834 * devices. We must emulate NAND_CMD_READOOB to keep the code compatible.
836 static void nand_command_lp(struct mtd_info *mtd, unsigned int command,
837 int column, int page_addr)
839 register struct nand_chip *chip = mtd_to_nand(mtd);
841 /* Emulate NAND_CMD_READOOB */
842 if (command == NAND_CMD_READOOB) {
843 column += mtd->writesize;
844 command = NAND_CMD_READ0;
847 /* Command latch cycle */
848 if (command != NAND_CMD_NONE)
849 chip->cmd_ctrl(mtd, command,
850 NAND_NCE | NAND_CLE | NAND_CTRL_CHANGE);
852 if (column != -1 || page_addr != -1) {
853 int ctrl = NAND_CTRL_CHANGE | NAND_NCE | NAND_ALE;
855 /* Serially input address */
857 /* Adjust columns for 16 bit buswidth */
858 if (chip->options & NAND_BUSWIDTH_16 &&
859 !nand_opcode_8bits(command))
861 chip->cmd_ctrl(mtd, column, ctrl);
862 ctrl &= ~NAND_CTRL_CHANGE;
864 /* Only output a single addr cycle for 8bits opcodes. */
865 if (!nand_opcode_8bits(command))
866 chip->cmd_ctrl(mtd, column >> 8, ctrl);
868 if (page_addr != -1) {
869 chip->cmd_ctrl(mtd, page_addr, ctrl);
870 chip->cmd_ctrl(mtd, page_addr >> 8,
871 NAND_NCE | NAND_ALE);
872 if (chip->options & NAND_ROW_ADDR_3)
873 chip->cmd_ctrl(mtd, page_addr >> 16,
874 NAND_NCE | NAND_ALE);
877 chip->cmd_ctrl(mtd, NAND_CMD_NONE, NAND_NCE | NAND_CTRL_CHANGE);
880 * Program and erase have their own busy handlers status, sequential
881 * in and status need no delay.
886 case NAND_CMD_CACHEDPROG:
887 case NAND_CMD_PAGEPROG:
888 case NAND_CMD_ERASE1:
889 case NAND_CMD_ERASE2:
891 case NAND_CMD_STATUS:
892 case NAND_CMD_READID:
893 case NAND_CMD_SET_FEATURES:
897 nand_ccs_delay(chip);
903 udelay(chip->chip_delay);
904 chip->cmd_ctrl(mtd, NAND_CMD_STATUS,
905 NAND_NCE | NAND_CLE | NAND_CTRL_CHANGE);
906 chip->cmd_ctrl(mtd, NAND_CMD_NONE,
907 NAND_NCE | NAND_CTRL_CHANGE);
908 /* EZ-NAND can take upto 250ms as per ONFi v4.0 */
909 nand_wait_status_ready(mtd, 250);
912 case NAND_CMD_RNDOUT:
913 /* No ready / busy check necessary */
914 chip->cmd_ctrl(mtd, NAND_CMD_RNDOUTSTART,
915 NAND_NCE | NAND_CLE | NAND_CTRL_CHANGE);
916 chip->cmd_ctrl(mtd, NAND_CMD_NONE,
917 NAND_NCE | NAND_CTRL_CHANGE);
919 nand_ccs_delay(chip);
924 * READ0 is sometimes used to exit GET STATUS mode. When this
925 * is the case no address cycles are requested, and we can use
926 * this information to detect that READSTART should not be
929 if (column == -1 && page_addr == -1)
932 chip->cmd_ctrl(mtd, NAND_CMD_READSTART,
933 NAND_NCE | NAND_CLE | NAND_CTRL_CHANGE);
934 chip->cmd_ctrl(mtd, NAND_CMD_NONE,
935 NAND_NCE | NAND_CTRL_CHANGE);
937 /* This applies to read commands */
940 * If we don't have access to the busy pin, we apply the given
943 if (!chip->dev_ready) {
944 udelay(chip->chip_delay);
950 * Apply this short delay always to ensure that we do wait tWB in
951 * any case on any machine.
955 nand_wait_ready(mtd);
959 * panic_nand_get_device - [GENERIC] Get chip for selected access
960 * @chip: the nand chip descriptor
961 * @mtd: MTD device structure
962 * @new_state: the state which is requested
964 * Used when in panic, no locks are taken.
966 static void panic_nand_get_device(struct nand_chip *chip,
967 struct mtd_info *mtd, int new_state)
969 /* Hardware controller shared among independent devices */
970 chip->controller->active = chip;
971 chip->state = new_state;
975 * nand_get_device - [GENERIC] Get chip for selected access
976 * @mtd: MTD device structure
977 * @new_state: the state which is requested
979 * Get the device and lock it for exclusive access
982 nand_get_device(struct mtd_info *mtd, int new_state)
984 struct nand_chip *chip = mtd_to_nand(mtd);
985 spinlock_t *lock = &chip->controller->lock;
986 wait_queue_head_t *wq = &chip->controller->wq;
987 DECLARE_WAITQUEUE(wait, current);
991 /* Hardware controller shared among independent devices */
992 if (!chip->controller->active)
993 chip->controller->active = chip;
995 if (chip->controller->active == chip && chip->state == FL_READY) {
996 chip->state = new_state;
1000 if (new_state == FL_PM_SUSPENDED) {
1001 if (chip->controller->active->state == FL_PM_SUSPENDED) {
1002 chip->state = FL_PM_SUSPENDED;
1007 set_current_state(TASK_UNINTERRUPTIBLE);
1008 add_wait_queue(wq, &wait);
1011 remove_wait_queue(wq, &wait);
1016 * panic_nand_wait - [GENERIC] wait until the command is done
1017 * @mtd: MTD device structure
1018 * @chip: NAND chip structure
1021 * Wait for command done. This is a helper function for nand_wait used when
1022 * we are in interrupt context. May happen when in panic and trying to write
1023 * an oops through mtdoops.
1025 static void panic_nand_wait(struct mtd_info *mtd, struct nand_chip *chip,
1026 unsigned long timeo)
1029 for (i = 0; i < timeo; i++) {
1030 if (chip->dev_ready) {
1031 if (chip->dev_ready(mtd))
1037 ret = nand_read_data_op(chip, &status, sizeof(status),
1042 if (status & NAND_STATUS_READY)
1050 * nand_wait - [DEFAULT] wait until the command is done
1051 * @mtd: MTD device structure
1052 * @chip: NAND chip structure
1054 * Wait for command done. This applies to erase and program only.
1056 static int nand_wait(struct mtd_info *mtd, struct nand_chip *chip)
1059 unsigned long timeo = 400;
1064 * Apply this short delay always to ensure that we do wait tWB in any
1065 * case on any machine.
1069 ret = nand_status_op(chip, NULL);
1073 if (in_interrupt() || oops_in_progress)
1074 panic_nand_wait(mtd, chip, timeo);
1076 timeo = jiffies + msecs_to_jiffies(timeo);
1078 if (chip->dev_ready) {
1079 if (chip->dev_ready(mtd))
1082 ret = nand_read_data_op(chip, &status,
1083 sizeof(status), true);
1087 if (status & NAND_STATUS_READY)
1091 } while (time_before(jiffies, timeo));
1094 ret = nand_read_data_op(chip, &status, sizeof(status), true);
1098 /* This can happen if in case of timeout or buggy dev_ready */
1099 WARN_ON(!(status & NAND_STATUS_READY));
1104 * nand_reset_data_interface - Reset data interface and timings
1105 * @chip: The NAND chip
1106 * @chipnr: Internal die id
1108 * Reset the Data interface and timings to ONFI mode 0.
1110 * Returns 0 for success or negative error code otherwise.
1112 static int nand_reset_data_interface(struct nand_chip *chip, int chipnr)
1114 struct mtd_info *mtd = nand_to_mtd(chip);
1115 const struct nand_data_interface *conf;
1118 if (!chip->setup_data_interface)
1122 * The ONFI specification says:
1124 * To transition from NV-DDR or NV-DDR2 to the SDR data
1125 * interface, the host shall use the Reset (FFh) command
1126 * using SDR timing mode 0. A device in any timing mode is
1127 * required to recognize Reset (FFh) command issued in SDR
1131 * Configure the data interface in SDR mode and set the
1132 * timings to timing mode 0.
1135 conf = nand_get_default_data_interface();
1136 ret = chip->setup_data_interface(mtd, chipnr, conf);
1138 pr_err("Failed to configure data interface to SDR timing mode 0\n");
1144 * nand_setup_data_interface - Setup the best data interface and timings
1145 * @chip: The NAND chip
1146 * @chipnr: Internal die id
1148 * Find and configure the best data interface and NAND timings supported by
1149 * the chip and the driver.
1150 * First tries to retrieve supported timing modes from ONFI information,
1151 * and if the NAND chip does not support ONFI, relies on the
1152 * ->onfi_timing_mode_default specified in the nand_ids table.
1154 * Returns 0 for success or negative error code otherwise.
1156 static int nand_setup_data_interface(struct nand_chip *chip, int chipnr)
1158 struct mtd_info *mtd = nand_to_mtd(chip);
1161 if (!chip->setup_data_interface || !chip->data_interface)
1165 * Ensure the timing mode has been changed on the chip side
1166 * before changing timings on the controller side.
1168 if (chip->onfi_version &&
1169 (le16_to_cpu(chip->onfi_params.opt_cmd) &
1170 ONFI_OPT_CMD_SET_GET_FEATURES)) {
1171 u8 tmode_param[ONFI_SUBFEATURE_PARAM_LEN] = {
1172 chip->onfi_timing_mode_default,
1175 ret = chip->onfi_set_features(mtd, chip,
1176 ONFI_FEATURE_ADDR_TIMING_MODE,
1182 ret = chip->setup_data_interface(mtd, chipnr, chip->data_interface);
1188 * nand_init_data_interface - find the best data interface and timings
1189 * @chip: The NAND chip
1191 * Find the best data interface and NAND timings supported by the chip
1193 * First tries to retrieve supported timing modes from ONFI information,
1194 * and if the NAND chip does not support ONFI, relies on the
1195 * ->onfi_timing_mode_default specified in the nand_ids table. After this
1196 * function nand_chip->data_interface is initialized with the best timing mode
1199 * Returns 0 for success or negative error code otherwise.
1201 static int nand_init_data_interface(struct nand_chip *chip)
1203 struct mtd_info *mtd = nand_to_mtd(chip);
1204 int modes, mode, ret;
1206 if (!chip->setup_data_interface)
1210 * First try to identify the best timings from ONFI parameters and
1211 * if the NAND does not support ONFI, fallback to the default ONFI
1214 modes = onfi_get_async_timing_mode(chip);
1215 if (modes == ONFI_TIMING_MODE_UNKNOWN) {
1216 if (!chip->onfi_timing_mode_default)
1219 modes = GENMASK(chip->onfi_timing_mode_default, 0);
1222 chip->data_interface = kzalloc(sizeof(*chip->data_interface),
1224 if (!chip->data_interface)
1227 for (mode = fls(modes) - 1; mode >= 0; mode--) {
1228 ret = onfi_init_data_interface(chip, chip->data_interface,
1229 NAND_SDR_IFACE, mode);
1233 /* Pass -1 to only */
1234 ret = chip->setup_data_interface(mtd,
1235 NAND_DATA_IFACE_CHECK_ONLY,
1236 chip->data_interface);
1238 chip->onfi_timing_mode_default = mode;
1246 static void nand_release_data_interface(struct nand_chip *chip)
1248 kfree(chip->data_interface);
1252 * nand_read_page_op - Do a READ PAGE operation
1253 * @chip: The NAND chip
1254 * @page: page to read
1255 * @offset_in_page: offset within the page
1256 * @buf: buffer used to store the data
1257 * @len: length of the buffer
1259 * This function issues a READ PAGE operation.
1260 * This function does not select/unselect the CS line.
1262 * Returns 0 on success, a negative error code otherwise.
1264 int nand_read_page_op(struct nand_chip *chip, unsigned int page,
1265 unsigned int offset_in_page, void *buf, unsigned int len)
1267 struct mtd_info *mtd = nand_to_mtd(chip);
1272 if (offset_in_page + len > mtd->writesize + mtd->oobsize)
1275 chip->cmdfunc(mtd, NAND_CMD_READ0, offset_in_page, page);
1277 chip->read_buf(mtd, buf, len);
1281 EXPORT_SYMBOL_GPL(nand_read_page_op);
1284 * nand_read_param_page_op - Do a READ PARAMETER PAGE operation
1285 * @chip: The NAND chip
1286 * @page: parameter page to read
1287 * @buf: buffer used to store the data
1288 * @len: length of the buffer
1290 * This function issues a READ PARAMETER PAGE operation.
1291 * This function does not select/unselect the CS line.
1293 * Returns 0 on success, a negative error code otherwise.
1295 static int nand_read_param_page_op(struct nand_chip *chip, u8 page, void *buf,
1298 struct mtd_info *mtd = nand_to_mtd(chip);
1305 chip->cmdfunc(mtd, NAND_CMD_PARAM, page, -1);
1306 for (i = 0; i < len; i++)
1307 p[i] = chip->read_byte(mtd);
1313 * nand_change_read_column_op - Do a CHANGE READ COLUMN operation
1314 * @chip: The NAND chip
1315 * @offset_in_page: offset within the page
1316 * @buf: buffer used to store the data
1317 * @len: length of the buffer
1318 * @force_8bit: force 8-bit bus access
1320 * This function issues a CHANGE READ COLUMN operation.
1321 * This function does not select/unselect the CS line.
1323 * Returns 0 on success, a negative error code otherwise.
1325 int nand_change_read_column_op(struct nand_chip *chip,
1326 unsigned int offset_in_page, void *buf,
1327 unsigned int len, bool force_8bit)
1329 struct mtd_info *mtd = nand_to_mtd(chip);
1334 if (offset_in_page + len > mtd->writesize + mtd->oobsize)
1337 chip->cmdfunc(mtd, NAND_CMD_RNDOUT, offset_in_page, -1);
1339 chip->read_buf(mtd, buf, len);
1343 EXPORT_SYMBOL_GPL(nand_change_read_column_op);
1346 * nand_read_oob_op - Do a READ OOB operation
1347 * @chip: The NAND chip
1348 * @page: page to read
1349 * @offset_in_oob: offset within the OOB area
1350 * @buf: buffer used to store the data
1351 * @len: length of the buffer
1353 * This function issues a READ OOB operation.
1354 * This function does not select/unselect the CS line.
1356 * Returns 0 on success, a negative error code otherwise.
1358 int nand_read_oob_op(struct nand_chip *chip, unsigned int page,
1359 unsigned int offset_in_oob, void *buf, unsigned int len)
1361 struct mtd_info *mtd = nand_to_mtd(chip);
1366 if (offset_in_oob + len > mtd->oobsize)
1369 chip->cmdfunc(mtd, NAND_CMD_READOOB, offset_in_oob, page);
1371 chip->read_buf(mtd, buf, len);
1375 EXPORT_SYMBOL_GPL(nand_read_oob_op);
1378 * nand_prog_page_begin_op - starts a PROG PAGE operation
1379 * @chip: The NAND chip
1380 * @page: page to write
1381 * @offset_in_page: offset within the page
1382 * @buf: buffer containing the data to write to the page
1383 * @len: length of the buffer
1385 * This function issues the first half of a PROG PAGE operation.
1386 * This function does not select/unselect the CS line.
1388 * Returns 0 on success, a negative error code otherwise.
1390 int nand_prog_page_begin_op(struct nand_chip *chip, unsigned int page,
1391 unsigned int offset_in_page, const void *buf,
1394 struct mtd_info *mtd = nand_to_mtd(chip);
1399 if (offset_in_page + len > mtd->writesize + mtd->oobsize)
1402 chip->cmdfunc(mtd, NAND_CMD_SEQIN, offset_in_page, page);
1405 chip->write_buf(mtd, buf, len);
1409 EXPORT_SYMBOL_GPL(nand_prog_page_begin_op);
1412 * nand_prog_page_end_op - ends a PROG PAGE operation
1413 * @chip: The NAND chip
1415 * This function issues the second half of a PROG PAGE operation.
1416 * This function does not select/unselect the CS line.
1418 * Returns 0 on success, a negative error code otherwise.
1420 int nand_prog_page_end_op(struct nand_chip *chip)
1422 struct mtd_info *mtd = nand_to_mtd(chip);
1425 chip->cmdfunc(mtd, NAND_CMD_PAGEPROG, -1, -1);
1427 status = chip->waitfunc(mtd, chip);
1428 if (status & NAND_STATUS_FAIL)
1433 EXPORT_SYMBOL_GPL(nand_prog_page_end_op);
1436 * nand_prog_page_op - Do a full PROG PAGE operation
1437 * @chip: The NAND chip
1438 * @page: page to write
1439 * @offset_in_page: offset within the page
1440 * @buf: buffer containing the data to write to the page
1441 * @len: length of the buffer
1443 * This function issues a full PROG PAGE operation.
1444 * This function does not select/unselect the CS line.
1446 * Returns 0 on success, a negative error code otherwise.
1448 int nand_prog_page_op(struct nand_chip *chip, unsigned int page,
1449 unsigned int offset_in_page, const void *buf,
1452 struct mtd_info *mtd = nand_to_mtd(chip);
1458 if (offset_in_page + len > mtd->writesize + mtd->oobsize)
1461 chip->cmdfunc(mtd, NAND_CMD_SEQIN, offset_in_page, page);
1462 chip->write_buf(mtd, buf, len);
1463 chip->cmdfunc(mtd, NAND_CMD_PAGEPROG, -1, -1);
1465 status = chip->waitfunc(mtd, chip);
1466 if (status & NAND_STATUS_FAIL)
1471 EXPORT_SYMBOL_GPL(nand_prog_page_op);
1474 * nand_change_write_column_op - Do a CHANGE WRITE COLUMN operation
1475 * @chip: The NAND chip
1476 * @offset_in_page: offset within the page
1477 * @buf: buffer containing the data to send to the NAND
1478 * @len: length of the buffer
1479 * @force_8bit: force 8-bit bus access
1481 * This function issues a CHANGE WRITE COLUMN operation.
1482 * This function does not select/unselect the CS line.
1484 * Returns 0 on success, a negative error code otherwise.
1486 int nand_change_write_column_op(struct nand_chip *chip,
1487 unsigned int offset_in_page,
1488 const void *buf, unsigned int len,
1491 struct mtd_info *mtd = nand_to_mtd(chip);
1496 if (offset_in_page + len > mtd->writesize + mtd->oobsize)
1499 chip->cmdfunc(mtd, NAND_CMD_RNDIN, offset_in_page, -1);
1501 chip->write_buf(mtd, buf, len);
1505 EXPORT_SYMBOL_GPL(nand_change_write_column_op);
1508 * nand_readid_op - Do a READID operation
1509 * @chip: The NAND chip
1510 * @addr: address cycle to pass after the READID command
1511 * @buf: buffer used to store the ID
1512 * @len: length of the buffer
1514 * This function sends a READID command and reads back the ID returned by the
1516 * This function does not select/unselect the CS line.
1518 * Returns 0 on success, a negative error code otherwise.
1520 int nand_readid_op(struct nand_chip *chip, u8 addr, void *buf,
1523 struct mtd_info *mtd = nand_to_mtd(chip);
1530 chip->cmdfunc(mtd, NAND_CMD_READID, addr, -1);
1532 for (i = 0; i < len; i++)
1533 id[i] = chip->read_byte(mtd);
1537 EXPORT_SYMBOL_GPL(nand_readid_op);
1540 * nand_status_op - Do a STATUS operation
1541 * @chip: The NAND chip
1542 * @status: out variable to store the NAND status
1544 * This function sends a STATUS command and reads back the status returned by
1546 * This function does not select/unselect the CS line.
1548 * Returns 0 on success, a negative error code otherwise.
1550 int nand_status_op(struct nand_chip *chip, u8 *status)
1552 struct mtd_info *mtd = nand_to_mtd(chip);
1554 chip->cmdfunc(mtd, NAND_CMD_STATUS, -1, -1);
1556 *status = chip->read_byte(mtd);
1560 EXPORT_SYMBOL_GPL(nand_status_op);
1563 * nand_exit_status_op - Exit a STATUS operation
1564 * @chip: The NAND chip
1566 * This function sends a READ0 command to cancel the effect of the STATUS
1567 * command to avoid reading only the status until a new read command is sent.
1569 * This function does not select/unselect the CS line.
1571 * Returns 0 on success, a negative error code otherwise.
1573 int nand_exit_status_op(struct nand_chip *chip)
1575 struct mtd_info *mtd = nand_to_mtd(chip);
1577 chip->cmdfunc(mtd, NAND_CMD_READ0, -1, -1);
1581 EXPORT_SYMBOL_GPL(nand_exit_status_op);
1584 * nand_erase_op - Do an erase operation
1585 * @chip: The NAND chip
1586 * @eraseblock: block to erase
1588 * This function sends an ERASE command and waits for the NAND to be ready
1590 * This function does not select/unselect the CS line.
1592 * Returns 0 on success, a negative error code otherwise.
1594 int nand_erase_op(struct nand_chip *chip, unsigned int eraseblock)
1596 struct mtd_info *mtd = nand_to_mtd(chip);
1597 unsigned int page = eraseblock <<
1598 (chip->phys_erase_shift - chip->page_shift);
1601 chip->cmdfunc(mtd, NAND_CMD_ERASE1, -1, page);
1602 chip->cmdfunc(mtd, NAND_CMD_ERASE2, -1, -1);
1604 status = chip->waitfunc(mtd, chip);
1608 if (status & NAND_STATUS_FAIL)
1613 EXPORT_SYMBOL_GPL(nand_erase_op);
1616 * nand_set_features_op - Do a SET FEATURES operation
1617 * @chip: The NAND chip
1618 * @feature: feature id
1619 * @data: 4 bytes of data
1621 * This function sends a SET FEATURES command and waits for the NAND to be
1622 * ready before returning.
1623 * This function does not select/unselect the CS line.
1625 * Returns 0 on success, a negative error code otherwise.
1627 static int nand_set_features_op(struct nand_chip *chip, u8 feature,
1630 struct mtd_info *mtd = nand_to_mtd(chip);
1631 const u8 *params = data;
1634 chip->cmdfunc(mtd, NAND_CMD_SET_FEATURES, feature, -1);
1635 for (i = 0; i < ONFI_SUBFEATURE_PARAM_LEN; ++i)
1636 chip->write_byte(mtd, params[i]);
1638 status = chip->waitfunc(mtd, chip);
1639 if (status & NAND_STATUS_FAIL)
1646 * nand_get_features_op - Do a GET FEATURES operation
1647 * @chip: The NAND chip
1648 * @feature: feature id
1649 * @data: 4 bytes of data
1651 * This function sends a GET FEATURES command and waits for the NAND to be
1652 * ready before returning.
1653 * This function does not select/unselect the CS line.
1655 * Returns 0 on success, a negative error code otherwise.
1657 static int nand_get_features_op(struct nand_chip *chip, u8 feature,
1660 struct mtd_info *mtd = nand_to_mtd(chip);
1664 chip->cmdfunc(mtd, NAND_CMD_GET_FEATURES, feature, -1);
1665 for (i = 0; i < ONFI_SUBFEATURE_PARAM_LEN; ++i)
1666 params[i] = chip->read_byte(mtd);
1672 * nand_reset_op - Do a reset operation
1673 * @chip: The NAND chip
1675 * This function sends a RESET command and waits for the NAND to be ready
1677 * This function does not select/unselect the CS line.
1679 * Returns 0 on success, a negative error code otherwise.
1681 int nand_reset_op(struct nand_chip *chip)
1683 struct mtd_info *mtd = nand_to_mtd(chip);
1685 chip->cmdfunc(mtd, NAND_CMD_RESET, -1, -1);
1689 EXPORT_SYMBOL_GPL(nand_reset_op);
1692 * nand_read_data_op - Read data from the NAND
1693 * @chip: The NAND chip
1694 * @buf: buffer used to store the data
1695 * @len: length of the buffer
1696 * @force_8bit: force 8-bit bus access
1698 * This function does a raw data read on the bus. Usually used after launching
1699 * another NAND operation like nand_read_page_op().
1700 * This function does not select/unselect the CS line.
1702 * Returns 0 on success, a negative error code otherwise.
1704 int nand_read_data_op(struct nand_chip *chip, void *buf, unsigned int len,
1707 struct mtd_info *mtd = nand_to_mtd(chip);
1716 for (i = 0; i < len; i++)
1717 p[i] = chip->read_byte(mtd);
1719 chip->read_buf(mtd, buf, len);
1724 EXPORT_SYMBOL_GPL(nand_read_data_op);
1727 * nand_write_data_op - Write data from the NAND
1728 * @chip: The NAND chip
1729 * @buf: buffer containing the data to send on the bus
1730 * @len: length of the buffer
1731 * @force_8bit: force 8-bit bus access
1733 * This function does a raw data write on the bus. Usually used after launching
1734 * another NAND operation like nand_write_page_begin_op().
1735 * This function does not select/unselect the CS line.
1737 * Returns 0 on success, a negative error code otherwise.
1739 int nand_write_data_op(struct nand_chip *chip, const void *buf,
1740 unsigned int len, bool force_8bit)
1742 struct mtd_info *mtd = nand_to_mtd(chip);
1751 for (i = 0; i < len; i++)
1752 chip->write_byte(mtd, p[i]);
1754 chip->write_buf(mtd, buf, len);
1759 EXPORT_SYMBOL_GPL(nand_write_data_op);
1762 * nand_reset - Reset and initialize a NAND device
1763 * @chip: The NAND chip
1764 * @chipnr: Internal die id
1766 * Returns 0 for success or negative error code otherwise
1768 int nand_reset(struct nand_chip *chip, int chipnr)
1770 struct mtd_info *mtd = nand_to_mtd(chip);
1773 ret = nand_reset_data_interface(chip, chipnr);
1778 * The CS line has to be released before we can apply the new NAND
1779 * interface settings, hence this weird ->select_chip() dance.
1781 chip->select_chip(mtd, chipnr);
1782 ret = nand_reset_op(chip);
1783 chip->select_chip(mtd, -1);
1787 chip->select_chip(mtd, chipnr);
1788 ret = nand_setup_data_interface(chip, chipnr);
1789 chip->select_chip(mtd, -1);
1795 EXPORT_SYMBOL_GPL(nand_reset);
1798 * nand_check_erased_buf - check if a buffer contains (almost) only 0xff data
1799 * @buf: buffer to test
1800 * @len: buffer length
1801 * @bitflips_threshold: maximum number of bitflips
1803 * Check if a buffer contains only 0xff, which means the underlying region
1804 * has been erased and is ready to be programmed.
1805 * The bitflips_threshold specify the maximum number of bitflips before
1806 * considering the region is not erased.
1807 * Note: The logic of this function has been extracted from the memweight
1808 * implementation, except that nand_check_erased_buf function exit before
1809 * testing the whole buffer if the number of bitflips exceed the
1810 * bitflips_threshold value.
1812 * Returns a positive number of bitflips less than or equal to
1813 * bitflips_threshold, or -ERROR_CODE for bitflips in excess of the
1816 static int nand_check_erased_buf(void *buf, int len, int bitflips_threshold)
1818 const unsigned char *bitmap = buf;
1822 for (; len && ((uintptr_t)bitmap) % sizeof(long);
1824 weight = hweight8(*bitmap);
1825 bitflips += BITS_PER_BYTE - weight;
1826 if (unlikely(bitflips > bitflips_threshold))
1830 for (; len >= sizeof(long);
1831 len -= sizeof(long), bitmap += sizeof(long)) {
1832 unsigned long d = *((unsigned long *)bitmap);
1835 weight = hweight_long(d);
1836 bitflips += BITS_PER_LONG - weight;
1837 if (unlikely(bitflips > bitflips_threshold))
1841 for (; len > 0; len--, bitmap++) {
1842 weight = hweight8(*bitmap);
1843 bitflips += BITS_PER_BYTE - weight;
1844 if (unlikely(bitflips > bitflips_threshold))
1852 * nand_check_erased_ecc_chunk - check if an ECC chunk contains (almost) only
1854 * @data: data buffer to test
1855 * @datalen: data length
1857 * @ecclen: ECC length
1858 * @extraoob: extra OOB buffer
1859 * @extraooblen: extra OOB length
1860 * @bitflips_threshold: maximum number of bitflips
1862 * Check if a data buffer and its associated ECC and OOB data contains only
1863 * 0xff pattern, which means the underlying region has been erased and is
1864 * ready to be programmed.
1865 * The bitflips_threshold specify the maximum number of bitflips before
1866 * considering the region as not erased.
1869 * 1/ ECC algorithms are working on pre-defined block sizes which are usually
1870 * different from the NAND page size. When fixing bitflips, ECC engines will
1871 * report the number of errors per chunk, and the NAND core infrastructure
1872 * expect you to return the maximum number of bitflips for the whole page.
1873 * This is why you should always use this function on a single chunk and
1874 * not on the whole page. After checking each chunk you should update your
1875 * max_bitflips value accordingly.
1876 * 2/ When checking for bitflips in erased pages you should not only check
1877 * the payload data but also their associated ECC data, because a user might
1878 * have programmed almost all bits to 1 but a few. In this case, we
1879 * shouldn't consider the chunk as erased, and checking ECC bytes prevent
1881 * 3/ The extraoob argument is optional, and should be used if some of your OOB
1882 * data are protected by the ECC engine.
1883 * It could also be used if you support subpages and want to attach some
1884 * extra OOB data to an ECC chunk.
1886 * Returns a positive number of bitflips less than or equal to
1887 * bitflips_threshold, or -ERROR_CODE for bitflips in excess of the
1888 * threshold. In case of success, the passed buffers are filled with 0xff.
1890 int nand_check_erased_ecc_chunk(void *data, int datalen,
1891 void *ecc, int ecclen,
1892 void *extraoob, int extraooblen,
1893 int bitflips_threshold)
1895 int data_bitflips = 0, ecc_bitflips = 0, extraoob_bitflips = 0;
1897 data_bitflips = nand_check_erased_buf(data, datalen,
1898 bitflips_threshold);
1899 if (data_bitflips < 0)
1900 return data_bitflips;
1902 bitflips_threshold -= data_bitflips;
1904 ecc_bitflips = nand_check_erased_buf(ecc, ecclen, bitflips_threshold);
1905 if (ecc_bitflips < 0)
1906 return ecc_bitflips;
1908 bitflips_threshold -= ecc_bitflips;
1910 extraoob_bitflips = nand_check_erased_buf(extraoob, extraooblen,
1911 bitflips_threshold);
1912 if (extraoob_bitflips < 0)
1913 return extraoob_bitflips;
1916 memset(data, 0xff, datalen);
1919 memset(ecc, 0xff, ecclen);
1921 if (extraoob_bitflips)
1922 memset(extraoob, 0xff, extraooblen);
1924 return data_bitflips + ecc_bitflips + extraoob_bitflips;
1926 EXPORT_SYMBOL(nand_check_erased_ecc_chunk);
1929 * nand_read_page_raw - [INTERN] read raw page data without ecc
1930 * @mtd: mtd info structure
1931 * @chip: nand chip info structure
1932 * @buf: buffer to store read data
1933 * @oob_required: caller requires OOB data read to chip->oob_poi
1934 * @page: page number to read
1936 * Not for syndrome calculating ECC controllers, which use a special oob layout.
1938 int nand_read_page_raw(struct mtd_info *mtd, struct nand_chip *chip,
1939 uint8_t *buf, int oob_required, int page)
1943 ret = nand_read_data_op(chip, buf, mtd->writesize, false);
1948 ret = nand_read_data_op(chip, chip->oob_poi, mtd->oobsize,
1956 EXPORT_SYMBOL(nand_read_page_raw);
1959 * nand_read_page_raw_syndrome - [INTERN] read raw page data without ecc
1960 * @mtd: mtd info structure
1961 * @chip: nand chip info structure
1962 * @buf: buffer to store read data
1963 * @oob_required: caller requires OOB data read to chip->oob_poi
1964 * @page: page number to read
1966 * We need a special oob layout and handling even when OOB isn't used.
1968 static int nand_read_page_raw_syndrome(struct mtd_info *mtd,
1969 struct nand_chip *chip, uint8_t *buf,
1970 int oob_required, int page)
1972 int eccsize = chip->ecc.size;
1973 int eccbytes = chip->ecc.bytes;
1974 uint8_t *oob = chip->oob_poi;
1975 int steps, size, ret;
1977 for (steps = chip->ecc.steps; steps > 0; steps--) {
1978 ret = nand_read_data_op(chip, buf, eccsize, false);
1984 if (chip->ecc.prepad) {
1985 ret = nand_read_data_op(chip, oob, chip->ecc.prepad,
1990 oob += chip->ecc.prepad;
1993 ret = nand_read_data_op(chip, oob, eccbytes, false);
1999 if (chip->ecc.postpad) {
2000 ret = nand_read_data_op(chip, oob, chip->ecc.postpad,
2005 oob += chip->ecc.postpad;
2009 size = mtd->oobsize - (oob - chip->oob_poi);
2011 ret = nand_read_data_op(chip, oob, size, false);
2020 * nand_read_page_swecc - [REPLACEABLE] software ECC based page read function
2021 * @mtd: mtd info structure
2022 * @chip: nand chip info structure
2023 * @buf: buffer to store read data
2024 * @oob_required: caller requires OOB data read to chip->oob_poi
2025 * @page: page number to read
2027 static int nand_read_page_swecc(struct mtd_info *mtd, struct nand_chip *chip,
2028 uint8_t *buf, int oob_required, int page)
2030 int i, eccsize = chip->ecc.size, ret;
2031 int eccbytes = chip->ecc.bytes;
2032 int eccsteps = chip->ecc.steps;
2034 uint8_t *ecc_calc = chip->buffers->ecccalc;
2035 uint8_t *ecc_code = chip->buffers->ecccode;
2036 unsigned int max_bitflips = 0;
2038 chip->ecc.read_page_raw(mtd, chip, buf, 1, page);
2040 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize)
2041 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
2043 ret = mtd_ooblayout_get_eccbytes(mtd, ecc_code, chip->oob_poi, 0,
2048 eccsteps = chip->ecc.steps;
2051 for (i = 0 ; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
2054 stat = chip->ecc.correct(mtd, p, &ecc_code[i], &ecc_calc[i]);
2056 mtd->ecc_stats.failed++;
2058 mtd->ecc_stats.corrected += stat;
2059 max_bitflips = max_t(unsigned int, max_bitflips, stat);
2062 return max_bitflips;
2066 * nand_read_subpage - [REPLACEABLE] ECC based sub-page read function
2067 * @mtd: mtd info structure
2068 * @chip: nand chip info structure
2069 * @data_offs: offset of requested data within the page
2070 * @readlen: data length
2071 * @bufpoi: buffer to store read data
2072 * @page: page number to read
2074 static int nand_read_subpage(struct mtd_info *mtd, struct nand_chip *chip,
2075 uint32_t data_offs, uint32_t readlen, uint8_t *bufpoi,
2078 int start_step, end_step, num_steps, ret;
2080 int data_col_addr, i, gaps = 0;
2081 int datafrag_len, eccfrag_len, aligned_len, aligned_pos;
2082 int busw = (chip->options & NAND_BUSWIDTH_16) ? 2 : 1;
2083 int index, section = 0;
2084 unsigned int max_bitflips = 0;
2085 struct mtd_oob_region oobregion = { };
2087 /* Column address within the page aligned to ECC size (256bytes) */
2088 start_step = data_offs / chip->ecc.size;
2089 end_step = (data_offs + readlen - 1) / chip->ecc.size;
2090 num_steps = end_step - start_step + 1;
2091 index = start_step * chip->ecc.bytes;
2093 /* Data size aligned to ECC ecc.size */
2094 datafrag_len = num_steps * chip->ecc.size;
2095 eccfrag_len = num_steps * chip->ecc.bytes;
2097 data_col_addr = start_step * chip->ecc.size;
2098 /* If we read not a page aligned data */
2099 if (data_col_addr != 0)
2100 chip->cmdfunc(mtd, NAND_CMD_RNDOUT, data_col_addr, -1);
2102 p = bufpoi + data_col_addr;
2103 ret = nand_read_data_op(chip, p, datafrag_len, false);
2108 for (i = 0; i < eccfrag_len ; i += chip->ecc.bytes, p += chip->ecc.size)
2109 chip->ecc.calculate(mtd, p, &chip->buffers->ecccalc[i]);
2112 * The performance is faster if we position offsets according to
2113 * ecc.pos. Let's make sure that there are no gaps in ECC positions.
2115 ret = mtd_ooblayout_find_eccregion(mtd, index, §ion, &oobregion);
2119 if (oobregion.length < eccfrag_len)
2123 ret = nand_change_read_column_op(chip, mtd->writesize,
2124 chip->oob_poi, mtd->oobsize,
2130 * Send the command to read the particular ECC bytes take care
2131 * about buswidth alignment in read_buf.
2133 aligned_pos = oobregion.offset & ~(busw - 1);
2134 aligned_len = eccfrag_len;
2135 if (oobregion.offset & (busw - 1))
2137 if ((oobregion.offset + (num_steps * chip->ecc.bytes)) &
2141 ret = nand_change_read_column_op(chip,
2142 mtd->writesize + aligned_pos,
2143 &chip->oob_poi[aligned_pos],
2144 aligned_len, false);
2149 ret = mtd_ooblayout_get_eccbytes(mtd, chip->buffers->ecccode,
2150 chip->oob_poi, index, eccfrag_len);
2154 p = bufpoi + data_col_addr;
2155 for (i = 0; i < eccfrag_len ; i += chip->ecc.bytes, p += chip->ecc.size) {
2158 stat = chip->ecc.correct(mtd, p,
2159 &chip->buffers->ecccode[i], &chip->buffers->ecccalc[i]);
2160 if (stat == -EBADMSG &&
2161 (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
2162 /* check for empty pages with bitflips */
2163 stat = nand_check_erased_ecc_chunk(p, chip->ecc.size,
2164 &chip->buffers->ecccode[i],
2167 chip->ecc.strength);
2171 mtd->ecc_stats.failed++;
2173 mtd->ecc_stats.corrected += stat;
2174 max_bitflips = max_t(unsigned int, max_bitflips, stat);
2177 return max_bitflips;
2181 * nand_read_page_hwecc - [REPLACEABLE] hardware ECC based page read function
2182 * @mtd: mtd info structure
2183 * @chip: nand chip info structure
2184 * @buf: buffer to store read data
2185 * @oob_required: caller requires OOB data read to chip->oob_poi
2186 * @page: page number to read
2188 * Not for syndrome calculating ECC controllers which need a special oob layout.
2190 static int nand_read_page_hwecc(struct mtd_info *mtd, struct nand_chip *chip,
2191 uint8_t *buf, int oob_required, int page)
2193 int i, eccsize = chip->ecc.size, ret;
2194 int eccbytes = chip->ecc.bytes;
2195 int eccsteps = chip->ecc.steps;
2197 uint8_t *ecc_calc = chip->buffers->ecccalc;
2198 uint8_t *ecc_code = chip->buffers->ecccode;
2199 unsigned int max_bitflips = 0;
2201 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
2202 chip->ecc.hwctl(mtd, NAND_ECC_READ);
2204 ret = nand_read_data_op(chip, p, eccsize, false);
2208 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
2211 ret = nand_read_data_op(chip, chip->oob_poi, mtd->oobsize, false);
2215 ret = mtd_ooblayout_get_eccbytes(mtd, ecc_code, chip->oob_poi, 0,
2220 eccsteps = chip->ecc.steps;
2223 for (i = 0 ; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
2226 stat = chip->ecc.correct(mtd, p, &ecc_code[i], &ecc_calc[i]);
2227 if (stat == -EBADMSG &&
2228 (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
2229 /* check for empty pages with bitflips */
2230 stat = nand_check_erased_ecc_chunk(p, eccsize,
2231 &ecc_code[i], eccbytes,
2233 chip->ecc.strength);
2237 mtd->ecc_stats.failed++;
2239 mtd->ecc_stats.corrected += stat;
2240 max_bitflips = max_t(unsigned int, max_bitflips, stat);
2243 return max_bitflips;
2247 * nand_read_page_hwecc_oob_first - [REPLACEABLE] hw ecc, read oob first
2248 * @mtd: mtd info structure
2249 * @chip: nand chip info structure
2250 * @buf: buffer to store read data
2251 * @oob_required: caller requires OOB data read to chip->oob_poi
2252 * @page: page number to read
2254 * Hardware ECC for large page chips, require OOB to be read first. For this
2255 * ECC mode, the write_page method is re-used from ECC_HW. These methods
2256 * read/write ECC from the OOB area, unlike the ECC_HW_SYNDROME support with
2257 * multiple ECC steps, follows the "infix ECC" scheme and reads/writes ECC from
2258 * the data area, by overwriting the NAND manufacturer bad block markings.
2260 static int nand_read_page_hwecc_oob_first(struct mtd_info *mtd,
2261 struct nand_chip *chip, uint8_t *buf, int oob_required, int page)
2263 int i, eccsize = chip->ecc.size, ret;
2264 int eccbytes = chip->ecc.bytes;
2265 int eccsteps = chip->ecc.steps;
2267 uint8_t *ecc_code = chip->buffers->ecccode;
2268 uint8_t *ecc_calc = chip->buffers->ecccalc;
2269 unsigned int max_bitflips = 0;
2271 /* Read the OOB area first */
2272 ret = nand_read_oob_op(chip, page, 0, chip->oob_poi, mtd->oobsize);
2276 ret = nand_read_page_op(chip, page, 0, NULL, 0);
2280 ret = mtd_ooblayout_get_eccbytes(mtd, ecc_code, chip->oob_poi, 0,
2285 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
2288 chip->ecc.hwctl(mtd, NAND_ECC_READ);
2290 ret = nand_read_data_op(chip, p, eccsize, false);
2294 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
2296 stat = chip->ecc.correct(mtd, p, &ecc_code[i], NULL);
2297 if (stat == -EBADMSG &&
2298 (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
2299 /* check for empty pages with bitflips */
2300 stat = nand_check_erased_ecc_chunk(p, eccsize,
2301 &ecc_code[i], eccbytes,
2303 chip->ecc.strength);
2307 mtd->ecc_stats.failed++;
2309 mtd->ecc_stats.corrected += stat;
2310 max_bitflips = max_t(unsigned int, max_bitflips, stat);
2313 return max_bitflips;
2317 * nand_read_page_syndrome - [REPLACEABLE] hardware ECC syndrome based page read
2318 * @mtd: mtd info structure
2319 * @chip: nand chip info structure
2320 * @buf: buffer to store read data
2321 * @oob_required: caller requires OOB data read to chip->oob_poi
2322 * @page: page number to read
2324 * The hw generator calculates the error syndrome automatically. Therefore we
2325 * need a special oob layout and handling.
2327 static int nand_read_page_syndrome(struct mtd_info *mtd, struct nand_chip *chip,
2328 uint8_t *buf, int oob_required, int page)
2330 int ret, i, eccsize = chip->ecc.size;
2331 int eccbytes = chip->ecc.bytes;
2332 int eccsteps = chip->ecc.steps;
2333 int eccpadbytes = eccbytes + chip->ecc.prepad + chip->ecc.postpad;
2335 uint8_t *oob = chip->oob_poi;
2336 unsigned int max_bitflips = 0;
2338 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
2341 chip->ecc.hwctl(mtd, NAND_ECC_READ);
2343 ret = nand_read_data_op(chip, p, eccsize, false);
2347 if (chip->ecc.prepad) {
2348 ret = nand_read_data_op(chip, oob, chip->ecc.prepad,
2353 oob += chip->ecc.prepad;
2356 chip->ecc.hwctl(mtd, NAND_ECC_READSYN);
2358 ret = nand_read_data_op(chip, oob, eccbytes, false);
2362 stat = chip->ecc.correct(mtd, p, oob, NULL);
2366 if (chip->ecc.postpad) {
2367 ret = nand_read_data_op(chip, oob, chip->ecc.postpad,
2372 oob += chip->ecc.postpad;
2375 if (stat == -EBADMSG &&
2376 (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
2377 /* check for empty pages with bitflips */
2378 stat = nand_check_erased_ecc_chunk(p, chip->ecc.size,
2382 chip->ecc.strength);
2386 mtd->ecc_stats.failed++;
2388 mtd->ecc_stats.corrected += stat;
2389 max_bitflips = max_t(unsigned int, max_bitflips, stat);
2393 /* Calculate remaining oob bytes */
2394 i = mtd->oobsize - (oob - chip->oob_poi);
2396 ret = nand_read_data_op(chip, oob, i, false);
2401 return max_bitflips;
2405 * nand_transfer_oob - [INTERN] Transfer oob to client buffer
2406 * @mtd: mtd info structure
2407 * @oob: oob destination address
2408 * @ops: oob ops structure
2409 * @len: size of oob to transfer
2411 static uint8_t *nand_transfer_oob(struct mtd_info *mtd, uint8_t *oob,
2412 struct mtd_oob_ops *ops, size_t len)
2414 struct nand_chip *chip = mtd_to_nand(mtd);
2417 switch (ops->mode) {
2419 case MTD_OPS_PLACE_OOB:
2421 memcpy(oob, chip->oob_poi + ops->ooboffs, len);
2424 case MTD_OPS_AUTO_OOB:
2425 ret = mtd_ooblayout_get_databytes(mtd, oob, chip->oob_poi,
2437 * nand_setup_read_retry - [INTERN] Set the READ RETRY mode
2438 * @mtd: MTD device structure
2439 * @retry_mode: the retry mode to use
2441 * Some vendors supply a special command to shift the Vt threshold, to be used
2442 * when there are too many bitflips in a page (i.e., ECC error). After setting
2443 * a new threshold, the host should retry reading the page.
2445 static int nand_setup_read_retry(struct mtd_info *mtd, int retry_mode)
2447 struct nand_chip *chip = mtd_to_nand(mtd);
2449 pr_debug("setting READ RETRY mode %d\n", retry_mode);
2451 if (retry_mode >= chip->read_retries)
2454 if (!chip->setup_read_retry)
2457 return chip->setup_read_retry(mtd, retry_mode);
2461 * nand_do_read_ops - [INTERN] Read data with ECC
2462 * @mtd: MTD device structure
2463 * @from: offset to read from
2464 * @ops: oob ops structure
2466 * Internal function. Called with chip held.
2468 static int nand_do_read_ops(struct mtd_info *mtd, loff_t from,
2469 struct mtd_oob_ops *ops)
2471 int chipnr, page, realpage, col, bytes, aligned, oob_required;
2472 struct nand_chip *chip = mtd_to_nand(mtd);
2474 uint32_t readlen = ops->len;
2475 uint32_t oobreadlen = ops->ooblen;
2476 uint32_t max_oobsize = mtd_oobavail(mtd, ops);
2478 uint8_t *bufpoi, *oob, *buf;
2480 unsigned int max_bitflips = 0;
2482 bool ecc_fail = false;
2484 chipnr = (int)(from >> chip->chip_shift);
2485 chip->select_chip(mtd, chipnr);
2487 realpage = (int)(from >> chip->page_shift);
2488 page = realpage & chip->pagemask;
2490 col = (int)(from & (mtd->writesize - 1));
2494 oob_required = oob ? 1 : 0;
2497 unsigned int ecc_failures = mtd->ecc_stats.failed;
2499 bytes = min(mtd->writesize - col, readlen);
2500 aligned = (bytes == mtd->writesize);
2504 else if (chip->options & NAND_USE_BOUNCE_BUFFER)
2505 use_bufpoi = !virt_addr_valid(buf) ||
2506 !IS_ALIGNED((unsigned long)buf,
2511 /* Is the current page in the buffer? */
2512 if (realpage != chip->pagebuf || oob) {
2513 bufpoi = use_bufpoi ? chip->buffers->databuf : buf;
2515 if (use_bufpoi && aligned)
2516 pr_debug("%s: using read bounce buffer for buf@%p\n",
2520 if (nand_standard_page_accessors(&chip->ecc)) {
2521 ret = nand_read_page_op(chip, page, 0, NULL, 0);
2527 * Now read the page into the buffer. Absent an error,
2528 * the read methods return max bitflips per ecc step.
2530 if (unlikely(ops->mode == MTD_OPS_RAW))
2531 ret = chip->ecc.read_page_raw(mtd, chip, bufpoi,
2534 else if (!aligned && NAND_HAS_SUBPAGE_READ(chip) &&
2536 ret = chip->ecc.read_subpage(mtd, chip,
2540 ret = chip->ecc.read_page(mtd, chip, bufpoi,
2541 oob_required, page);
2544 /* Invalidate page cache */
2549 /* Transfer not aligned data */
2551 if (!NAND_HAS_SUBPAGE_READ(chip) && !oob &&
2552 !(mtd->ecc_stats.failed - ecc_failures) &&
2553 (ops->mode != MTD_OPS_RAW)) {
2554 chip->pagebuf = realpage;
2555 chip->pagebuf_bitflips = ret;
2557 /* Invalidate page cache */
2560 memcpy(buf, chip->buffers->databuf + col, bytes);
2563 if (unlikely(oob)) {
2564 int toread = min(oobreadlen, max_oobsize);
2567 oob = nand_transfer_oob(mtd,
2569 oobreadlen -= toread;
2573 if (chip->options & NAND_NEED_READRDY) {
2574 /* Apply delay or wait for ready/busy pin */
2575 if (!chip->dev_ready)
2576 udelay(chip->chip_delay);
2578 nand_wait_ready(mtd);
2581 if (mtd->ecc_stats.failed - ecc_failures) {
2582 if (retry_mode + 1 < chip->read_retries) {
2584 ret = nand_setup_read_retry(mtd,
2589 /* Reset failures; retry */
2590 mtd->ecc_stats.failed = ecc_failures;
2593 /* No more retry modes; real failure */
2599 max_bitflips = max_t(unsigned int, max_bitflips, ret);
2601 memcpy(buf, chip->buffers->databuf + col, bytes);
2603 max_bitflips = max_t(unsigned int, max_bitflips,
2604 chip->pagebuf_bitflips);
2609 /* Reset to retry mode 0 */
2611 ret = nand_setup_read_retry(mtd, 0);
2620 /* For subsequent reads align to page boundary */
2622 /* Increment page address */
2625 page = realpage & chip->pagemask;
2626 /* Check, if we cross a chip boundary */
2629 chip->select_chip(mtd, -1);
2630 chip->select_chip(mtd, chipnr);
2633 chip->select_chip(mtd, -1);
2635 ops->retlen = ops->len - (size_t) readlen;
2637 ops->oobretlen = ops->ooblen - oobreadlen;
2645 return max_bitflips;
2649 * nand_read - [MTD Interface] MTD compatibility function for nand_do_read_ecc
2650 * @mtd: MTD device structure
2651 * @from: offset to read from
2652 * @len: number of bytes to read
2653 * @retlen: pointer to variable to store the number of read bytes
2654 * @buf: the databuffer to put data
2656 * Get hold of the chip and call nand_do_read.
2658 static int nand_read(struct mtd_info *mtd, loff_t from, size_t len,
2659 size_t *retlen, uint8_t *buf)
2661 struct mtd_oob_ops ops;
2664 nand_get_device(mtd, FL_READING);
2665 memset(&ops, 0, sizeof(ops));
2668 ops.mode = MTD_OPS_PLACE_OOB;
2669 ret = nand_do_read_ops(mtd, from, &ops);
2670 *retlen = ops.retlen;
2671 nand_release_device(mtd);
2676 * nand_read_oob_std - [REPLACEABLE] the most common OOB data read function
2677 * @mtd: mtd info structure
2678 * @chip: nand chip info structure
2679 * @page: page number to read
2681 int nand_read_oob_std(struct mtd_info *mtd, struct nand_chip *chip, int page)
2683 return nand_read_oob_op(chip, page, 0, chip->oob_poi, mtd->oobsize);
2685 EXPORT_SYMBOL(nand_read_oob_std);
2688 * nand_read_oob_syndrome - [REPLACEABLE] OOB data read function for HW ECC
2690 * @mtd: mtd info structure
2691 * @chip: nand chip info structure
2692 * @page: page number to read
2694 int nand_read_oob_syndrome(struct mtd_info *mtd, struct nand_chip *chip,
2697 int length = mtd->oobsize;
2698 int chunk = chip->ecc.bytes + chip->ecc.prepad + chip->ecc.postpad;
2699 int eccsize = chip->ecc.size;
2700 uint8_t *bufpoi = chip->oob_poi;
2701 int i, toread, sndrnd = 0, pos, ret;
2703 ret = nand_read_page_op(chip, page, chip->ecc.size, NULL, 0);
2707 for (i = 0; i < chip->ecc.steps; i++) {
2711 pos = eccsize + i * (eccsize + chunk);
2712 if (mtd->writesize > 512)
2713 ret = nand_change_read_column_op(chip, pos,
2717 ret = nand_read_page_op(chip, page, pos, NULL,
2724 toread = min_t(int, length, chunk);
2726 ret = nand_read_data_op(chip, bufpoi, toread, false);
2734 ret = nand_read_data_op(chip, bufpoi, length, false);
2741 EXPORT_SYMBOL(nand_read_oob_syndrome);
2744 * nand_write_oob_std - [REPLACEABLE] the most common OOB data write function
2745 * @mtd: mtd info structure
2746 * @chip: nand chip info structure
2747 * @page: page number to write
2749 int nand_write_oob_std(struct mtd_info *mtd, struct nand_chip *chip, int page)
2751 return nand_prog_page_op(chip, page, mtd->writesize, chip->oob_poi,
2754 EXPORT_SYMBOL(nand_write_oob_std);
2757 * nand_write_oob_syndrome - [REPLACEABLE] OOB data write function for HW ECC
2758 * with syndrome - only for large page flash
2759 * @mtd: mtd info structure
2760 * @chip: nand chip info structure
2761 * @page: page number to write
2763 int nand_write_oob_syndrome(struct mtd_info *mtd, struct nand_chip *chip,
2766 int chunk = chip->ecc.bytes + chip->ecc.prepad + chip->ecc.postpad;
2767 int eccsize = chip->ecc.size, length = mtd->oobsize;
2768 int ret, i, len, pos, sndcmd = 0, steps = chip->ecc.steps;
2769 const uint8_t *bufpoi = chip->oob_poi;
2772 * data-ecc-data-ecc ... ecc-oob
2774 * data-pad-ecc-pad-data-pad .... ecc-pad-oob
2776 if (!chip->ecc.prepad && !chip->ecc.postpad) {
2777 pos = steps * (eccsize + chunk);
2782 ret = nand_prog_page_begin_op(chip, page, pos, NULL, 0);
2786 for (i = 0; i < steps; i++) {
2788 if (mtd->writesize <= 512) {
2789 uint32_t fill = 0xFFFFFFFF;
2793 int num = min_t(int, len, 4);
2795 ret = nand_write_data_op(chip, &fill,
2803 pos = eccsize + i * (eccsize + chunk);
2804 ret = nand_change_write_column_op(chip, pos,
2812 len = min_t(int, length, chunk);
2814 ret = nand_write_data_op(chip, bufpoi, len, false);
2822 ret = nand_write_data_op(chip, bufpoi, length, false);
2827 return nand_prog_page_end_op(chip);
2829 EXPORT_SYMBOL(nand_write_oob_syndrome);
2832 * nand_do_read_oob - [INTERN] NAND read out-of-band
2833 * @mtd: MTD device structure
2834 * @from: offset to read from
2835 * @ops: oob operations description structure
2837 * NAND read out-of-band data from the spare area.
2839 static int nand_do_read_oob(struct mtd_info *mtd, loff_t from,
2840 struct mtd_oob_ops *ops)
2842 int page, realpage, chipnr;
2843 struct nand_chip *chip = mtd_to_nand(mtd);
2844 struct mtd_ecc_stats stats;
2845 int readlen = ops->ooblen;
2847 uint8_t *buf = ops->oobbuf;
2850 pr_debug("%s: from = 0x%08Lx, len = %i\n",
2851 __func__, (unsigned long long)from, readlen);
2853 stats = mtd->ecc_stats;
2855 len = mtd_oobavail(mtd, ops);
2857 if (unlikely(ops->ooboffs >= len)) {
2858 pr_debug("%s: attempt to start read outside oob\n",
2863 /* Do not allow reads past end of device */
2864 if (unlikely(from >= mtd->size ||
2865 ops->ooboffs + readlen > ((mtd->size >> chip->page_shift) -
2866 (from >> chip->page_shift)) * len)) {
2867 pr_debug("%s: attempt to read beyond end of device\n",
2872 chipnr = (int)(from >> chip->chip_shift);
2873 chip->select_chip(mtd, chipnr);
2875 /* Shift to get page */
2876 realpage = (int)(from >> chip->page_shift);
2877 page = realpage & chip->pagemask;
2880 if (ops->mode == MTD_OPS_RAW)
2881 ret = chip->ecc.read_oob_raw(mtd, chip, page);
2883 ret = chip->ecc.read_oob(mtd, chip, page);
2888 len = min(len, readlen);
2889 buf = nand_transfer_oob(mtd, buf, ops, len);
2891 if (chip->options & NAND_NEED_READRDY) {
2892 /* Apply delay or wait for ready/busy pin */
2893 if (!chip->dev_ready)
2894 udelay(chip->chip_delay);
2896 nand_wait_ready(mtd);
2903 /* Increment page address */
2906 page = realpage & chip->pagemask;
2907 /* Check, if we cross a chip boundary */
2910 chip->select_chip(mtd, -1);
2911 chip->select_chip(mtd, chipnr);
2914 chip->select_chip(mtd, -1);
2916 ops->oobretlen = ops->ooblen - readlen;
2921 if (mtd->ecc_stats.failed - stats.failed)
2924 return mtd->ecc_stats.corrected - stats.corrected ? -EUCLEAN : 0;
2928 * nand_read_oob - [MTD Interface] NAND read data and/or out-of-band
2929 * @mtd: MTD device structure
2930 * @from: offset to read from
2931 * @ops: oob operation description structure
2933 * NAND read data and/or out-of-band data.
2935 static int nand_read_oob(struct mtd_info *mtd, loff_t from,
2936 struct mtd_oob_ops *ops)
2942 /* Do not allow reads past end of device */
2943 if (ops->datbuf && (from + ops->len) > mtd->size) {
2944 pr_debug("%s: attempt to read beyond end of device\n",
2949 if (ops->mode != MTD_OPS_PLACE_OOB &&
2950 ops->mode != MTD_OPS_AUTO_OOB &&
2951 ops->mode != MTD_OPS_RAW)
2954 nand_get_device(mtd, FL_READING);
2957 ret = nand_do_read_oob(mtd, from, ops);
2959 ret = nand_do_read_ops(mtd, from, ops);
2961 nand_release_device(mtd);
2967 * nand_write_page_raw - [INTERN] raw page write function
2968 * @mtd: mtd info structure
2969 * @chip: nand chip info structure
2971 * @oob_required: must write chip->oob_poi to OOB
2972 * @page: page number to write
2974 * Not for syndrome calculating ECC controllers, which use a special oob layout.
2976 int nand_write_page_raw(struct mtd_info *mtd, struct nand_chip *chip,
2977 const uint8_t *buf, int oob_required, int page)
2981 ret = nand_write_data_op(chip, buf, mtd->writesize, false);
2986 ret = nand_write_data_op(chip, chip->oob_poi, mtd->oobsize,
2994 EXPORT_SYMBOL(nand_write_page_raw);
2997 * nand_write_page_raw_syndrome - [INTERN] raw page write function
2998 * @mtd: mtd info structure
2999 * @chip: nand chip info structure
3001 * @oob_required: must write chip->oob_poi to OOB
3002 * @page: page number to write
3004 * We need a special oob layout and handling even when ECC isn't checked.
3006 static int nand_write_page_raw_syndrome(struct mtd_info *mtd,
3007 struct nand_chip *chip,
3008 const uint8_t *buf, int oob_required,
3011 int eccsize = chip->ecc.size;
3012 int eccbytes = chip->ecc.bytes;
3013 uint8_t *oob = chip->oob_poi;
3014 int steps, size, ret;
3016 for (steps = chip->ecc.steps; steps > 0; steps--) {
3017 ret = nand_write_data_op(chip, buf, eccsize, false);
3023 if (chip->ecc.prepad) {
3024 ret = nand_write_data_op(chip, oob, chip->ecc.prepad,
3029 oob += chip->ecc.prepad;
3032 ret = nand_write_data_op(chip, oob, eccbytes, false);
3038 if (chip->ecc.postpad) {
3039 ret = nand_write_data_op(chip, oob, chip->ecc.postpad,
3044 oob += chip->ecc.postpad;
3048 size = mtd->oobsize - (oob - chip->oob_poi);
3050 ret = nand_write_data_op(chip, oob, size, false);
3058 * nand_write_page_swecc - [REPLACEABLE] software ECC based page write function
3059 * @mtd: mtd info structure
3060 * @chip: nand chip info structure
3062 * @oob_required: must write chip->oob_poi to OOB
3063 * @page: page number to write
3065 static int nand_write_page_swecc(struct mtd_info *mtd, struct nand_chip *chip,
3066 const uint8_t *buf, int oob_required,
3069 int i, eccsize = chip->ecc.size, ret;
3070 int eccbytes = chip->ecc.bytes;
3071 int eccsteps = chip->ecc.steps;
3072 uint8_t *ecc_calc = chip->buffers->ecccalc;
3073 const uint8_t *p = buf;
3075 /* Software ECC calculation */
3076 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize)
3077 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
3079 ret = mtd_ooblayout_set_eccbytes(mtd, ecc_calc, chip->oob_poi, 0,
3084 return chip->ecc.write_page_raw(mtd, chip, buf, 1, page);
3088 * nand_write_page_hwecc - [REPLACEABLE] hardware ECC based page write function
3089 * @mtd: mtd info structure
3090 * @chip: nand chip info structure
3092 * @oob_required: must write chip->oob_poi to OOB
3093 * @page: page number to write
3095 static int nand_write_page_hwecc(struct mtd_info *mtd, struct nand_chip *chip,
3096 const uint8_t *buf, int oob_required,
3099 int i, eccsize = chip->ecc.size, ret;
3100 int eccbytes = chip->ecc.bytes;
3101 int eccsteps = chip->ecc.steps;
3102 uint8_t *ecc_calc = chip->buffers->ecccalc;
3103 const uint8_t *p = buf;
3105 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
3106 chip->ecc.hwctl(mtd, NAND_ECC_WRITE);
3108 ret = nand_write_data_op(chip, p, eccsize, false);
3112 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
3115 ret = mtd_ooblayout_set_eccbytes(mtd, ecc_calc, chip->oob_poi, 0,
3120 ret = nand_write_data_op(chip, chip->oob_poi, mtd->oobsize, false);
3129 * nand_write_subpage_hwecc - [REPLACEABLE] hardware ECC based subpage write
3130 * @mtd: mtd info structure
3131 * @chip: nand chip info structure
3132 * @offset: column address of subpage within the page
3133 * @data_len: data length
3135 * @oob_required: must write chip->oob_poi to OOB
3136 * @page: page number to write
3138 static int nand_write_subpage_hwecc(struct mtd_info *mtd,
3139 struct nand_chip *chip, uint32_t offset,
3140 uint32_t data_len, const uint8_t *buf,
3141 int oob_required, int page)
3143 uint8_t *oob_buf = chip->oob_poi;
3144 uint8_t *ecc_calc = chip->buffers->ecccalc;
3145 int ecc_size = chip->ecc.size;
3146 int ecc_bytes = chip->ecc.bytes;
3147 int ecc_steps = chip->ecc.steps;
3148 uint32_t start_step = offset / ecc_size;
3149 uint32_t end_step = (offset + data_len - 1) / ecc_size;
3150 int oob_bytes = mtd->oobsize / ecc_steps;
3153 for (step = 0; step < ecc_steps; step++) {
3154 /* configure controller for WRITE access */
3155 chip->ecc.hwctl(mtd, NAND_ECC_WRITE);
3157 /* write data (untouched subpages already masked by 0xFF) */
3158 ret = nand_write_data_op(chip, buf, ecc_size, false);
3162 /* mask ECC of un-touched subpages by padding 0xFF */
3163 if ((step < start_step) || (step > end_step))
3164 memset(ecc_calc, 0xff, ecc_bytes);
3166 chip->ecc.calculate(mtd, buf, ecc_calc);
3168 /* mask OOB of un-touched subpages by padding 0xFF */
3169 /* if oob_required, preserve OOB metadata of written subpage */
3170 if (!oob_required || (step < start_step) || (step > end_step))
3171 memset(oob_buf, 0xff, oob_bytes);
3174 ecc_calc += ecc_bytes;
3175 oob_buf += oob_bytes;
3178 /* copy calculated ECC for whole page to chip->buffer->oob */
3179 /* this include masked-value(0xFF) for unwritten subpages */
3180 ecc_calc = chip->buffers->ecccalc;
3181 ret = mtd_ooblayout_set_eccbytes(mtd, ecc_calc, chip->oob_poi, 0,
3186 /* write OOB buffer to NAND device */
3187 ret = nand_write_data_op(chip, chip->oob_poi, mtd->oobsize, false);
3196 * nand_write_page_syndrome - [REPLACEABLE] hardware ECC syndrome based page write
3197 * @mtd: mtd info structure
3198 * @chip: nand chip info structure
3200 * @oob_required: must write chip->oob_poi to OOB
3201 * @page: page number to write
3203 * The hw generator calculates the error syndrome automatically. Therefore we
3204 * need a special oob layout and handling.
3206 static int nand_write_page_syndrome(struct mtd_info *mtd,
3207 struct nand_chip *chip,
3208 const uint8_t *buf, int oob_required,
3211 int i, eccsize = chip->ecc.size;
3212 int eccbytes = chip->ecc.bytes;
3213 int eccsteps = chip->ecc.steps;
3214 const uint8_t *p = buf;
3215 uint8_t *oob = chip->oob_poi;
3218 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
3219 chip->ecc.hwctl(mtd, NAND_ECC_WRITE);
3221 ret = nand_write_data_op(chip, p, eccsize, false);
3225 if (chip->ecc.prepad) {
3226 ret = nand_write_data_op(chip, oob, chip->ecc.prepad,
3231 oob += chip->ecc.prepad;
3234 chip->ecc.calculate(mtd, p, oob);
3236 ret = nand_write_data_op(chip, oob, eccbytes, false);
3242 if (chip->ecc.postpad) {
3243 ret = nand_write_data_op(chip, oob, chip->ecc.postpad,
3248 oob += chip->ecc.postpad;
3252 /* Calculate remaining oob bytes */
3253 i = mtd->oobsize - (oob - chip->oob_poi);
3255 ret = nand_write_data_op(chip, oob, i, false);
3264 * nand_write_page - write one page
3265 * @mtd: MTD device structure
3266 * @chip: NAND chip descriptor
3267 * @offset: address offset within the page
3268 * @data_len: length of actual data to be written
3269 * @buf: the data to write
3270 * @oob_required: must write chip->oob_poi to OOB
3271 * @page: page number to write
3272 * @raw: use _raw version of write_page
3274 static int nand_write_page(struct mtd_info *mtd, struct nand_chip *chip,
3275 uint32_t offset, int data_len, const uint8_t *buf,
3276 int oob_required, int page, int raw)
3278 int status, subpage;
3280 if (!(chip->options & NAND_NO_SUBPAGE_WRITE) &&
3281 chip->ecc.write_subpage)
3282 subpage = offset || (data_len < mtd->writesize);
3286 if (nand_standard_page_accessors(&chip->ecc)) {
3287 status = nand_prog_page_begin_op(chip, page, 0, NULL, 0);
3293 status = chip->ecc.write_page_raw(mtd, chip, buf,
3294 oob_required, page);
3296 status = chip->ecc.write_subpage(mtd, chip, offset, data_len,
3297 buf, oob_required, page);
3299 status = chip->ecc.write_page(mtd, chip, buf, oob_required,
3305 if (nand_standard_page_accessors(&chip->ecc))
3306 return nand_prog_page_end_op(chip);
3312 * nand_fill_oob - [INTERN] Transfer client buffer to oob
3313 * @mtd: MTD device structure
3314 * @oob: oob data buffer
3315 * @len: oob data write length
3316 * @ops: oob ops structure
3318 static uint8_t *nand_fill_oob(struct mtd_info *mtd, uint8_t *oob, size_t len,
3319 struct mtd_oob_ops *ops)
3321 struct nand_chip *chip = mtd_to_nand(mtd);
3325 * Initialise to all 0xFF, to avoid the possibility of left over OOB
3326 * data from a previous OOB read.
3328 memset(chip->oob_poi, 0xff, mtd->oobsize);
3330 switch (ops->mode) {
3332 case MTD_OPS_PLACE_OOB:
3334 memcpy(chip->oob_poi + ops->ooboffs, oob, len);
3337 case MTD_OPS_AUTO_OOB:
3338 ret = mtd_ooblayout_set_databytes(mtd, oob, chip->oob_poi,
3349 #define NOTALIGNED(x) ((x & (chip->subpagesize - 1)) != 0)
3352 * nand_do_write_ops - [INTERN] NAND write with ECC
3353 * @mtd: MTD device structure
3354 * @to: offset to write to
3355 * @ops: oob operations description structure
3357 * NAND write with ECC.
3359 static int nand_do_write_ops(struct mtd_info *mtd, loff_t to,
3360 struct mtd_oob_ops *ops)
3362 int chipnr, realpage, page, column;
3363 struct nand_chip *chip = mtd_to_nand(mtd);
3364 uint32_t writelen = ops->len;
3366 uint32_t oobwritelen = ops->ooblen;
3367 uint32_t oobmaxlen = mtd_oobavail(mtd, ops);
3369 uint8_t *oob = ops->oobbuf;
3370 uint8_t *buf = ops->datbuf;
3372 int oob_required = oob ? 1 : 0;
3378 /* Reject writes, which are not page aligned */
3379 if (NOTALIGNED(to) || NOTALIGNED(ops->len)) {
3380 pr_notice("%s: attempt to write non page aligned data\n",
3385 column = to & (mtd->writesize - 1);
3387 chipnr = (int)(to >> chip->chip_shift);
3388 chip->select_chip(mtd, chipnr);
3390 /* Check, if it is write protected */
3391 if (nand_check_wp(mtd)) {
3396 realpage = (int)(to >> chip->page_shift);
3397 page = realpage & chip->pagemask;
3399 /* Invalidate the page cache, when we write to the cached page */
3400 if (to <= ((loff_t)chip->pagebuf << chip->page_shift) &&
3401 ((loff_t)chip->pagebuf << chip->page_shift) < (to + ops->len))
3404 /* Don't allow multipage oob writes with offset */
3405 if (oob && ops->ooboffs && (ops->ooboffs + ops->ooblen > oobmaxlen)) {
3411 int bytes = mtd->writesize;
3412 uint8_t *wbuf = buf;
3414 int part_pagewr = (column || writelen < mtd->writesize);
3418 else if (chip->options & NAND_USE_BOUNCE_BUFFER)
3419 use_bufpoi = !virt_addr_valid(buf) ||
3420 !IS_ALIGNED((unsigned long)buf,
3425 /* Partial page write?, or need to use bounce buffer */
3427 pr_debug("%s: using write bounce buffer for buf@%p\n",
3430 bytes = min_t(int, bytes - column, writelen);
3432 memset(chip->buffers->databuf, 0xff, mtd->writesize);
3433 memcpy(&chip->buffers->databuf[column], buf, bytes);
3434 wbuf = chip->buffers->databuf;
3437 if (unlikely(oob)) {
3438 size_t len = min(oobwritelen, oobmaxlen);
3439 oob = nand_fill_oob(mtd, oob, len, ops);
3442 /* We still need to erase leftover OOB data */
3443 memset(chip->oob_poi, 0xff, mtd->oobsize);
3446 ret = nand_write_page(mtd, chip, column, bytes, wbuf,
3448 (ops->mode == MTD_OPS_RAW));
3460 page = realpage & chip->pagemask;
3461 /* Check, if we cross a chip boundary */
3464 chip->select_chip(mtd, -1);
3465 chip->select_chip(mtd, chipnr);
3469 ops->retlen = ops->len - writelen;
3471 ops->oobretlen = ops->ooblen;
3474 chip->select_chip(mtd, -1);
3479 * panic_nand_write - [MTD Interface] NAND write with ECC
3480 * @mtd: MTD device structure
3481 * @to: offset to write to
3482 * @len: number of bytes to write
3483 * @retlen: pointer to variable to store the number of written bytes
3484 * @buf: the data to write
3486 * NAND write with ECC. Used when performing writes in interrupt context, this
3487 * may for example be called by mtdoops when writing an oops while in panic.
3489 static int panic_nand_write(struct mtd_info *mtd, loff_t to, size_t len,
3490 size_t *retlen, const uint8_t *buf)
3492 struct nand_chip *chip = mtd_to_nand(mtd);
3493 int chipnr = (int)(to >> chip->chip_shift);
3494 struct mtd_oob_ops ops;
3497 /* Grab the device */
3498 panic_nand_get_device(chip, mtd, FL_WRITING);
3500 chip->select_chip(mtd, chipnr);
3502 /* Wait for the device to get ready */
3503 panic_nand_wait(mtd, chip, 400);
3505 memset(&ops, 0, sizeof(ops));
3507 ops.datbuf = (uint8_t *)buf;
3508 ops.mode = MTD_OPS_PLACE_OOB;
3510 ret = nand_do_write_ops(mtd, to, &ops);
3512 *retlen = ops.retlen;
3517 * nand_write - [MTD Interface] NAND write with ECC
3518 * @mtd: MTD device structure
3519 * @to: offset to write to
3520 * @len: number of bytes to write
3521 * @retlen: pointer to variable to store the number of written bytes
3522 * @buf: the data to write
3524 * NAND write with ECC.
3526 static int nand_write(struct mtd_info *mtd, loff_t to, size_t len,
3527 size_t *retlen, const uint8_t *buf)
3529 struct mtd_oob_ops ops;
3532 nand_get_device(mtd, FL_WRITING);
3533 memset(&ops, 0, sizeof(ops));
3535 ops.datbuf = (uint8_t *)buf;
3536 ops.mode = MTD_OPS_PLACE_OOB;
3537 ret = nand_do_write_ops(mtd, to, &ops);
3538 *retlen = ops.retlen;
3539 nand_release_device(mtd);
3544 * nand_do_write_oob - [MTD Interface] NAND write out-of-band
3545 * @mtd: MTD device structure
3546 * @to: offset to write to
3547 * @ops: oob operation description structure
3549 * NAND write out-of-band.
3551 static int nand_do_write_oob(struct mtd_info *mtd, loff_t to,
3552 struct mtd_oob_ops *ops)
3554 int chipnr, page, status, len;
3555 struct nand_chip *chip = mtd_to_nand(mtd);
3557 pr_debug("%s: to = 0x%08x, len = %i\n",
3558 __func__, (unsigned int)to, (int)ops->ooblen);
3560 len = mtd_oobavail(mtd, ops);
3562 /* Do not allow write past end of page */
3563 if ((ops->ooboffs + ops->ooblen) > len) {
3564 pr_debug("%s: attempt to write past end of page\n",
3569 if (unlikely(ops->ooboffs >= len)) {
3570 pr_debug("%s: attempt to start write outside oob\n",
3575 /* Do not allow write past end of device */
3576 if (unlikely(to >= mtd->size ||
3577 ops->ooboffs + ops->ooblen >
3578 ((mtd->size >> chip->page_shift) -
3579 (to >> chip->page_shift)) * len)) {
3580 pr_debug("%s: attempt to write beyond end of device\n",
3585 chipnr = (int)(to >> chip->chip_shift);
3588 * Reset the chip. Some chips (like the Toshiba TC5832DC found in one
3589 * of my DiskOnChip 2000 test units) will clear the whole data page too
3590 * if we don't do this. I have no clue why, but I seem to have 'fixed'
3591 * it in the doc2000 driver in August 1999. dwmw2.
3593 nand_reset(chip, chipnr);
3595 chip->select_chip(mtd, chipnr);
3597 /* Shift to get page */
3598 page = (int)(to >> chip->page_shift);
3600 /* Check, if it is write protected */
3601 if (nand_check_wp(mtd)) {
3602 chip->select_chip(mtd, -1);
3606 /* Invalidate the page cache, if we write to the cached page */
3607 if (page == chip->pagebuf)
3610 nand_fill_oob(mtd, ops->oobbuf, ops->ooblen, ops);
3612 if (ops->mode == MTD_OPS_RAW)
3613 status = chip->ecc.write_oob_raw(mtd, chip, page & chip->pagemask);
3615 status = chip->ecc.write_oob(mtd, chip, page & chip->pagemask);
3617 chip->select_chip(mtd, -1);
3622 ops->oobretlen = ops->ooblen;
3628 * nand_write_oob - [MTD Interface] NAND write data and/or out-of-band
3629 * @mtd: MTD device structure
3630 * @to: offset to write to
3631 * @ops: oob operation description structure
3633 static int nand_write_oob(struct mtd_info *mtd, loff_t to,
3634 struct mtd_oob_ops *ops)
3636 int ret = -ENOTSUPP;
3640 /* Do not allow writes past end of device */
3641 if (ops->datbuf && (to + ops->len) > mtd->size) {
3642 pr_debug("%s: attempt to write beyond end of device\n",
3647 nand_get_device(mtd, FL_WRITING);
3649 switch (ops->mode) {
3650 case MTD_OPS_PLACE_OOB:
3651 case MTD_OPS_AUTO_OOB:
3660 ret = nand_do_write_oob(mtd, to, ops);
3662 ret = nand_do_write_ops(mtd, to, ops);
3665 nand_release_device(mtd);
3670 * single_erase - [GENERIC] NAND standard block erase command function
3671 * @mtd: MTD device structure
3672 * @page: the page address of the block which will be erased
3674 * Standard erase command for NAND chips. Returns NAND status.
3676 static int single_erase(struct mtd_info *mtd, int page)
3678 struct nand_chip *chip = mtd_to_nand(mtd);
3679 unsigned int eraseblock;
3681 /* Send commands to erase a block */
3682 eraseblock = page >> (chip->phys_erase_shift - chip->page_shift);
3684 return nand_erase_op(chip, eraseblock);
3688 * nand_erase - [MTD Interface] erase block(s)
3689 * @mtd: MTD device structure
3690 * @instr: erase instruction
3692 * Erase one ore more blocks.
3694 static int nand_erase(struct mtd_info *mtd, struct erase_info *instr)
3696 return nand_erase_nand(mtd, instr, 0);
3700 * nand_erase_nand - [INTERN] erase block(s)
3701 * @mtd: MTD device structure
3702 * @instr: erase instruction
3703 * @allowbbt: allow erasing the bbt area
3705 * Erase one ore more blocks.
3707 int nand_erase_nand(struct mtd_info *mtd, struct erase_info *instr,
3710 int page, status, pages_per_block, ret, chipnr;
3711 struct nand_chip *chip = mtd_to_nand(mtd);
3714 pr_debug("%s: start = 0x%012llx, len = %llu\n",
3715 __func__, (unsigned long long)instr->addr,
3716 (unsigned long long)instr->len);
3718 if (check_offs_len(mtd, instr->addr, instr->len))
3721 /* Grab the lock and see if the device is available */
3722 nand_get_device(mtd, FL_ERASING);
3724 /* Shift to get first page */
3725 page = (int)(instr->addr >> chip->page_shift);
3726 chipnr = (int)(instr->addr >> chip->chip_shift);
3728 /* Calculate pages in each block */
3729 pages_per_block = 1 << (chip->phys_erase_shift - chip->page_shift);
3731 /* Select the NAND device */
3732 chip->select_chip(mtd, chipnr);
3734 /* Check, if it is write protected */
3735 if (nand_check_wp(mtd)) {
3736 pr_debug("%s: device is write protected!\n",
3738 instr->state = MTD_ERASE_FAILED;
3742 /* Loop through the pages */
3745 instr->state = MTD_ERASING;
3748 /* Check if we have a bad block, we do not erase bad blocks! */
3749 if (nand_block_checkbad(mtd, ((loff_t) page) <<
3750 chip->page_shift, allowbbt)) {
3751 pr_warn("%s: attempt to erase a bad block at page 0x%08x\n",
3753 instr->state = MTD_ERASE_FAILED;
3758 * Invalidate the page cache, if we erase the block which
3759 * contains the current cached page.
3761 if (page <= chip->pagebuf && chip->pagebuf <
3762 (page + pages_per_block))
3765 status = chip->erase(mtd, page & chip->pagemask);
3767 /* See if block erase succeeded */
3769 pr_debug("%s: failed erase, page 0x%08x\n",
3771 instr->state = MTD_ERASE_FAILED;
3773 ((loff_t)page << chip->page_shift);
3777 /* Increment page address and decrement length */
3778 len -= (1ULL << chip->phys_erase_shift);
3779 page += pages_per_block;
3781 /* Check, if we cross a chip boundary */
3782 if (len && !(page & chip->pagemask)) {
3784 chip->select_chip(mtd, -1);
3785 chip->select_chip(mtd, chipnr);
3788 instr->state = MTD_ERASE_DONE;
3792 ret = instr->state == MTD_ERASE_DONE ? 0 : -EIO;
3794 /* Deselect and wake up anyone waiting on the device */
3795 chip->select_chip(mtd, -1);
3796 nand_release_device(mtd);
3798 /* Do call back function */
3800 mtd_erase_callback(instr);
3802 /* Return more or less happy */
3807 * nand_sync - [MTD Interface] sync
3808 * @mtd: MTD device structure
3810 * Sync is actually a wait for chip ready function.
3812 static void nand_sync(struct mtd_info *mtd)
3814 pr_debug("%s: called\n", __func__);
3816 /* Grab the lock and see if the device is available */
3817 nand_get_device(mtd, FL_SYNCING);
3818 /* Release it and go back */
3819 nand_release_device(mtd);
3823 * nand_block_isbad - [MTD Interface] Check if block at offset is bad
3824 * @mtd: MTD device structure
3825 * @offs: offset relative to mtd start
3827 static int nand_block_isbad(struct mtd_info *mtd, loff_t offs)
3829 struct nand_chip *chip = mtd_to_nand(mtd);
3830 int chipnr = (int)(offs >> chip->chip_shift);
3833 /* Select the NAND device */
3834 nand_get_device(mtd, FL_READING);
3835 chip->select_chip(mtd, chipnr);
3837 ret = nand_block_checkbad(mtd, offs, 0);
3839 chip->select_chip(mtd, -1);
3840 nand_release_device(mtd);
3846 * nand_block_markbad - [MTD Interface] Mark block at the given offset as bad
3847 * @mtd: MTD device structure
3848 * @ofs: offset relative to mtd start
3850 static int nand_block_markbad(struct mtd_info *mtd, loff_t ofs)
3854 ret = nand_block_isbad(mtd, ofs);
3856 /* If it was bad already, return success and do nothing */
3862 return nand_block_markbad_lowlevel(mtd, ofs);
3866 * nand_max_bad_blocks - [MTD Interface] Max number of bad blocks for an mtd
3867 * @mtd: MTD device structure
3868 * @ofs: offset relative to mtd start
3869 * @len: length of mtd
3871 static int nand_max_bad_blocks(struct mtd_info *mtd, loff_t ofs, size_t len)
3873 struct nand_chip *chip = mtd_to_nand(mtd);
3874 u32 part_start_block;
3880 * max_bb_per_die and blocks_per_die used to determine
3881 * the maximum bad block count.
3883 if (!chip->max_bb_per_die || !chip->blocks_per_die)
3886 /* Get the start and end of the partition in erase blocks. */
3887 part_start_block = mtd_div_by_eb(ofs, mtd);
3888 part_end_block = mtd_div_by_eb(len, mtd) + part_start_block - 1;
3890 /* Get the start and end LUNs of the partition. */
3891 part_start_die = part_start_block / chip->blocks_per_die;
3892 part_end_die = part_end_block / chip->blocks_per_die;
3895 * Look up the bad blocks per unit and multiply by the number of units
3896 * that the partition spans.
3898 return chip->max_bb_per_die * (part_end_die - part_start_die + 1);
3902 * nand_onfi_set_features- [REPLACEABLE] set features for ONFI nand
3903 * @mtd: MTD device structure
3904 * @chip: nand chip info structure
3905 * @addr: feature address.
3906 * @subfeature_param: the subfeature parameters, a four bytes array.
3908 static int nand_onfi_set_features(struct mtd_info *mtd, struct nand_chip *chip,
3909 int addr, uint8_t *subfeature_param)
3911 if (!chip->onfi_version ||
3912 !(le16_to_cpu(chip->onfi_params.opt_cmd)
3913 & ONFI_OPT_CMD_SET_GET_FEATURES))
3916 return nand_set_features_op(chip, addr, subfeature_param);
3920 * nand_onfi_get_features- [REPLACEABLE] get features for ONFI nand
3921 * @mtd: MTD device structure
3922 * @chip: nand chip info structure
3923 * @addr: feature address.
3924 * @subfeature_param: the subfeature parameters, a four bytes array.
3926 static int nand_onfi_get_features(struct mtd_info *mtd, struct nand_chip *chip,
3927 int addr, uint8_t *subfeature_param)
3929 if (!chip->onfi_version ||
3930 !(le16_to_cpu(chip->onfi_params.opt_cmd)
3931 & ONFI_OPT_CMD_SET_GET_FEATURES))
3934 return nand_get_features_op(chip, addr, subfeature_param);
3938 * nand_onfi_get_set_features_notsupp - set/get features stub returning
3940 * @mtd: MTD device structure
3941 * @chip: nand chip info structure
3942 * @addr: feature address.
3943 * @subfeature_param: the subfeature parameters, a four bytes array.
3945 * Should be used by NAND controller drivers that do not support the SET/GET
3946 * FEATURES operations.
3948 int nand_onfi_get_set_features_notsupp(struct mtd_info *mtd,
3949 struct nand_chip *chip, int addr,
3950 u8 *subfeature_param)
3954 EXPORT_SYMBOL(nand_onfi_get_set_features_notsupp);
3957 * nand_suspend - [MTD Interface] Suspend the NAND flash
3958 * @mtd: MTD device structure
3960 static int nand_suspend(struct mtd_info *mtd)
3962 return nand_get_device(mtd, FL_PM_SUSPENDED);
3966 * nand_resume - [MTD Interface] Resume the NAND flash
3967 * @mtd: MTD device structure
3969 static void nand_resume(struct mtd_info *mtd)
3971 struct nand_chip *chip = mtd_to_nand(mtd);
3973 if (chip->state == FL_PM_SUSPENDED)
3974 nand_release_device(mtd);
3976 pr_err("%s called for a chip which is not in suspended state\n",
3981 * nand_shutdown - [MTD Interface] Finish the current NAND operation and
3982 * prevent further operations
3983 * @mtd: MTD device structure
3985 static void nand_shutdown(struct mtd_info *mtd)
3987 nand_get_device(mtd, FL_PM_SUSPENDED);
3990 /* Set default functions */
3991 static void nand_set_defaults(struct nand_chip *chip)
3993 unsigned int busw = chip->options & NAND_BUSWIDTH_16;
3995 /* check for proper chip_delay setup, set 20us if not */
3996 if (!chip->chip_delay)
3997 chip->chip_delay = 20;
3999 /* check, if a user supplied command function given */
4000 if (chip->cmdfunc == NULL)
4001 chip->cmdfunc = nand_command;
4003 /* check, if a user supplied wait function given */
4004 if (chip->waitfunc == NULL)
4005 chip->waitfunc = nand_wait;
4007 if (!chip->select_chip)
4008 chip->select_chip = nand_select_chip;
4010 /* set for ONFI nand */
4011 if (!chip->onfi_set_features)
4012 chip->onfi_set_features = nand_onfi_set_features;
4013 if (!chip->onfi_get_features)
4014 chip->onfi_get_features = nand_onfi_get_features;
4016 /* If called twice, pointers that depend on busw may need to be reset */
4017 if (!chip->read_byte || chip->read_byte == nand_read_byte)
4018 chip->read_byte = busw ? nand_read_byte16 : nand_read_byte;
4019 if (!chip->read_word)
4020 chip->read_word = nand_read_word;
4021 if (!chip->block_bad)
4022 chip->block_bad = nand_block_bad;
4023 if (!chip->block_markbad)
4024 chip->block_markbad = nand_default_block_markbad;
4025 if (!chip->write_buf || chip->write_buf == nand_write_buf)
4026 chip->write_buf = busw ? nand_write_buf16 : nand_write_buf;
4027 if (!chip->write_byte || chip->write_byte == nand_write_byte)
4028 chip->write_byte = busw ? nand_write_byte16 : nand_write_byte;
4029 if (!chip->read_buf || chip->read_buf == nand_read_buf)
4030 chip->read_buf = busw ? nand_read_buf16 : nand_read_buf;
4031 if (!chip->scan_bbt)
4032 chip->scan_bbt = nand_default_bbt;
4034 if (!chip->controller) {
4035 chip->controller = &chip->hwcontrol;
4036 nand_hw_control_init(chip->controller);
4039 if (!chip->buf_align)
4040 chip->buf_align = 1;
4043 /* Sanitize ONFI strings so we can safely print them */
4044 static void sanitize_string(uint8_t *s, size_t len)
4048 /* Null terminate */
4051 /* Remove non printable chars */
4052 for (i = 0; i < len - 1; i++) {
4053 if (s[i] < ' ' || s[i] > 127)
4057 /* Remove trailing spaces */
4061 static u16 onfi_crc16(u16 crc, u8 const *p, size_t len)
4066 for (i = 0; i < 8; i++)
4067 crc = (crc << 1) ^ ((crc & 0x8000) ? 0x8005 : 0);
4073 /* Parse the Extended Parameter Page. */
4074 static int nand_flash_detect_ext_param_page(struct nand_chip *chip,
4075 struct nand_onfi_params *p)
4077 struct onfi_ext_param_page *ep;
4078 struct onfi_ext_section *s;
4079 struct onfi_ext_ecc_info *ecc;
4085 len = le16_to_cpu(p->ext_param_page_length) * 16;
4086 ep = kmalloc(len, GFP_KERNEL);
4090 /* Send our own NAND_CMD_PARAM. */
4091 ret = nand_read_param_page_op(chip, 0, NULL, 0);
4095 /* Use the Change Read Column command to skip the ONFI param pages. */
4096 ret = nand_change_read_column_op(chip,
4097 sizeof(*p) * p->num_of_param_pages,
4103 if ((onfi_crc16(ONFI_CRC_BASE, ((uint8_t *)ep) + 2, len - 2)
4104 != le16_to_cpu(ep->crc))) {
4105 pr_debug("fail in the CRC.\n");
4110 * Check the signature.
4111 * Do not strictly follow the ONFI spec, maybe changed in future.
4113 if (strncmp(ep->sig, "EPPS", 4)) {
4114 pr_debug("The signature is invalid.\n");
4118 /* find the ECC section. */
4119 cursor = (uint8_t *)(ep + 1);
4120 for (i = 0; i < ONFI_EXT_SECTION_MAX; i++) {
4121 s = ep->sections + i;
4122 if (s->type == ONFI_SECTION_TYPE_2)
4124 cursor += s->length * 16;
4126 if (i == ONFI_EXT_SECTION_MAX) {
4127 pr_debug("We can not find the ECC section.\n");
4131 /* get the info we want. */
4132 ecc = (struct onfi_ext_ecc_info *)cursor;
4134 if (!ecc->codeword_size) {
4135 pr_debug("Invalid codeword size\n");
4139 chip->ecc_strength_ds = ecc->ecc_bits;
4140 chip->ecc_step_ds = 1 << ecc->codeword_size;
4149 * Check if the NAND chip is ONFI compliant, returns 1 if it is, 0 otherwise.
4151 static int nand_flash_detect_onfi(struct nand_chip *chip)
4153 struct mtd_info *mtd = nand_to_mtd(chip);
4154 struct nand_onfi_params *p = &chip->onfi_params;
4158 /* Try ONFI for unknown chip or LP */
4159 ret = nand_readid_op(chip, 0x20, id, sizeof(id));
4160 if (ret || strncmp(id, "ONFI", 4))
4163 ret = nand_read_param_page_op(chip, 0, NULL, 0);
4167 for (i = 0; i < 3; i++) {
4168 ret = nand_read_data_op(chip, p, sizeof(*p), true);
4172 if (onfi_crc16(ONFI_CRC_BASE, (uint8_t *)p, 254) ==
4173 le16_to_cpu(p->crc)) {
4179 pr_err("Could not find valid ONFI parameter page; aborting\n");
4184 val = le16_to_cpu(p->revision);
4186 chip->onfi_version = 23;
4187 else if (val & (1 << 4))
4188 chip->onfi_version = 22;
4189 else if (val & (1 << 3))
4190 chip->onfi_version = 21;
4191 else if (val & (1 << 2))
4192 chip->onfi_version = 20;
4193 else if (val & (1 << 1))
4194 chip->onfi_version = 10;
4196 if (!chip->onfi_version) {
4197 pr_info("unsupported ONFI version: %d\n", val);
4201 sanitize_string(p->manufacturer, sizeof(p->manufacturer));
4202 sanitize_string(p->model, sizeof(p->model));
4204 mtd->name = p->model;
4206 mtd->writesize = le32_to_cpu(p->byte_per_page);
4209 * pages_per_block and blocks_per_lun may not be a power-of-2 size
4210 * (don't ask me who thought of this...). MTD assumes that these
4211 * dimensions will be power-of-2, so just truncate the remaining area.
4213 mtd->erasesize = 1 << (fls(le32_to_cpu(p->pages_per_block)) - 1);
4214 mtd->erasesize *= mtd->writesize;
4216 mtd->oobsize = le16_to_cpu(p->spare_bytes_per_page);
4218 /* See erasesize comment */
4219 chip->chipsize = 1 << (fls(le32_to_cpu(p->blocks_per_lun)) - 1);
4220 chip->chipsize *= (uint64_t)mtd->erasesize * p->lun_count;
4221 chip->bits_per_cell = p->bits_per_cell;
4223 chip->max_bb_per_die = le16_to_cpu(p->bb_per_lun);
4224 chip->blocks_per_die = le32_to_cpu(p->blocks_per_lun);
4226 if (onfi_feature(chip) & ONFI_FEATURE_16_BIT_BUS)
4227 chip->options |= NAND_BUSWIDTH_16;
4229 if (p->ecc_bits != 0xff) {
4230 chip->ecc_strength_ds = p->ecc_bits;
4231 chip->ecc_step_ds = 512;
4232 } else if (chip->onfi_version >= 21 &&
4233 (onfi_feature(chip) & ONFI_FEATURE_EXT_PARAM_PAGE)) {
4236 * The nand_flash_detect_ext_param_page() uses the
4237 * Change Read Column command which maybe not supported
4238 * by the chip->cmdfunc. So try to update the chip->cmdfunc
4239 * now. We do not replace user supplied command function.
4241 if (mtd->writesize > 512 && chip->cmdfunc == nand_command)
4242 chip->cmdfunc = nand_command_lp;
4244 /* The Extended Parameter Page is supported since ONFI 2.1. */
4245 if (nand_flash_detect_ext_param_page(chip, p))
4246 pr_warn("Failed to detect ONFI extended param page\n");
4248 pr_warn("Could not retrieve ONFI ECC requirements\n");
4255 * Check if the NAND chip is JEDEC compliant, returns 1 if it is, 0 otherwise.
4257 static int nand_flash_detect_jedec(struct nand_chip *chip)
4259 struct mtd_info *mtd = nand_to_mtd(chip);
4260 struct nand_jedec_params *p = &chip->jedec_params;
4261 struct jedec_ecc_info *ecc;
4265 /* Try JEDEC for unknown chip or LP */
4266 ret = nand_readid_op(chip, 0x40, id, sizeof(id));
4267 if (ret || strncmp(id, "JEDEC", sizeof(id)))
4270 ret = nand_read_param_page_op(chip, 0x40, NULL, 0);
4274 for (i = 0; i < 3; i++) {
4275 ret = nand_read_data_op(chip, p, sizeof(*p), true);
4279 if (onfi_crc16(ONFI_CRC_BASE, (uint8_t *)p, 510) ==
4280 le16_to_cpu(p->crc))
4285 pr_err("Could not find valid JEDEC parameter page; aborting\n");
4290 val = le16_to_cpu(p->revision);
4292 chip->jedec_version = 10;
4293 else if (val & (1 << 1))
4294 chip->jedec_version = 1; /* vendor specific version */
4296 if (!chip->jedec_version) {
4297 pr_info("unsupported JEDEC version: %d\n", val);
4301 sanitize_string(p->manufacturer, sizeof(p->manufacturer));
4302 sanitize_string(p->model, sizeof(p->model));
4304 mtd->name = p->model;
4306 mtd->writesize = le32_to_cpu(p->byte_per_page);
4308 /* Please reference to the comment for nand_flash_detect_onfi. */
4309 mtd->erasesize = 1 << (fls(le32_to_cpu(p->pages_per_block)) - 1);
4310 mtd->erasesize *= mtd->writesize;
4312 mtd->oobsize = le16_to_cpu(p->spare_bytes_per_page);
4314 /* Please reference to the comment for nand_flash_detect_onfi. */
4315 chip->chipsize = 1 << (fls(le32_to_cpu(p->blocks_per_lun)) - 1);
4316 chip->chipsize *= (uint64_t)mtd->erasesize * p->lun_count;
4317 chip->bits_per_cell = p->bits_per_cell;
4319 if (jedec_feature(chip) & JEDEC_FEATURE_16_BIT_BUS)
4320 chip->options |= NAND_BUSWIDTH_16;
4323 ecc = &p->ecc_info[0];
4325 if (ecc->codeword_size >= 9) {
4326 chip->ecc_strength_ds = ecc->ecc_bits;
4327 chip->ecc_step_ds = 1 << ecc->codeword_size;
4329 pr_warn("Invalid codeword size\n");
4336 * nand_id_has_period - Check if an ID string has a given wraparound period
4337 * @id_data: the ID string
4338 * @arrlen: the length of the @id_data array
4339 * @period: the period of repitition
4341 * Check if an ID string is repeated within a given sequence of bytes at
4342 * specific repetition interval period (e.g., {0x20,0x01,0x7F,0x20} has a
4343 * period of 3). This is a helper function for nand_id_len(). Returns non-zero
4344 * if the repetition has a period of @period; otherwise, returns zero.
4346 static int nand_id_has_period(u8 *id_data, int arrlen, int period)
4349 for (i = 0; i < period; i++)
4350 for (j = i + period; j < arrlen; j += period)
4351 if (id_data[i] != id_data[j])
4357 * nand_id_len - Get the length of an ID string returned by CMD_READID
4358 * @id_data: the ID string
4359 * @arrlen: the length of the @id_data array
4361 * Returns the length of the ID string, according to known wraparound/trailing
4362 * zero patterns. If no pattern exists, returns the length of the array.
4364 static int nand_id_len(u8 *id_data, int arrlen)
4366 int last_nonzero, period;
4368 /* Find last non-zero byte */
4369 for (last_nonzero = arrlen - 1; last_nonzero >= 0; last_nonzero--)
4370 if (id_data[last_nonzero])
4374 if (last_nonzero < 0)
4377 /* Calculate wraparound period */
4378 for (period = 1; period < arrlen; period++)
4379 if (nand_id_has_period(id_data, arrlen, period))
4382 /* There's a repeated pattern */
4383 if (period < arrlen)
4386 /* There are trailing zeros */
4387 if (last_nonzero < arrlen - 1)
4388 return last_nonzero + 1;
4390 /* No pattern detected */
4394 /* Extract the bits of per cell from the 3rd byte of the extended ID */
4395 static int nand_get_bits_per_cell(u8 cellinfo)
4399 bits = cellinfo & NAND_CI_CELLTYPE_MSK;
4400 bits >>= NAND_CI_CELLTYPE_SHIFT;
4405 * Many new NAND share similar device ID codes, which represent the size of the
4406 * chip. The rest of the parameters must be decoded according to generic or
4407 * manufacturer-specific "extended ID" decoding patterns.
4409 void nand_decode_ext_id(struct nand_chip *chip)
4411 struct mtd_info *mtd = nand_to_mtd(chip);
4413 u8 *id_data = chip->id.data;
4414 /* The 3rd id byte holds MLC / multichip data */
4415 chip->bits_per_cell = nand_get_bits_per_cell(id_data[2]);
4416 /* The 4th id byte is the important one */
4420 mtd->writesize = 1024 << (extid & 0x03);
4423 mtd->oobsize = (8 << (extid & 0x01)) * (mtd->writesize >> 9);
4425 /* Calc blocksize. Blocksize is multiples of 64KiB */
4426 mtd->erasesize = (64 * 1024) << (extid & 0x03);
4428 /* Get buswidth information */
4430 chip->options |= NAND_BUSWIDTH_16;
4432 EXPORT_SYMBOL_GPL(nand_decode_ext_id);
4435 * Old devices have chip data hardcoded in the device ID table. nand_decode_id
4436 * decodes a matching ID table entry and assigns the MTD size parameters for
4439 static void nand_decode_id(struct nand_chip *chip, struct nand_flash_dev *type)
4441 struct mtd_info *mtd = nand_to_mtd(chip);
4443 mtd->erasesize = type->erasesize;
4444 mtd->writesize = type->pagesize;
4445 mtd->oobsize = mtd->writesize / 32;
4447 /* All legacy ID NAND are small-page, SLC */
4448 chip->bits_per_cell = 1;
4452 * Set the bad block marker/indicator (BBM/BBI) patterns according to some
4453 * heuristic patterns using various detected parameters (e.g., manufacturer,
4454 * page size, cell-type information).
4456 static void nand_decode_bbm_options(struct nand_chip *chip)
4458 struct mtd_info *mtd = nand_to_mtd(chip);
4460 /* Set the bad block position */
4461 if (mtd->writesize > 512 || (chip->options & NAND_BUSWIDTH_16))
4462 chip->badblockpos = NAND_LARGE_BADBLOCK_POS;
4464 chip->badblockpos = NAND_SMALL_BADBLOCK_POS;
4467 static inline bool is_full_id_nand(struct nand_flash_dev *type)
4469 return type->id_len;
4472 static bool find_full_id_nand(struct nand_chip *chip,
4473 struct nand_flash_dev *type)
4475 struct mtd_info *mtd = nand_to_mtd(chip);
4476 u8 *id_data = chip->id.data;
4478 if (!strncmp(type->id, id_data, type->id_len)) {
4479 mtd->writesize = type->pagesize;
4480 mtd->erasesize = type->erasesize;
4481 mtd->oobsize = type->oobsize;
4483 chip->bits_per_cell = nand_get_bits_per_cell(id_data[2]);
4484 chip->chipsize = (uint64_t)type->chipsize << 20;
4485 chip->options |= type->options;
4486 chip->ecc_strength_ds = NAND_ECC_STRENGTH(type);
4487 chip->ecc_step_ds = NAND_ECC_STEP(type);
4488 chip->onfi_timing_mode_default =
4489 type->onfi_timing_mode_default;
4492 mtd->name = type->name;
4500 * Manufacturer detection. Only used when the NAND is not ONFI or JEDEC
4501 * compliant and does not have a full-id or legacy-id entry in the nand_ids
4504 static void nand_manufacturer_detect(struct nand_chip *chip)
4507 * Try manufacturer detection if available and use
4508 * nand_decode_ext_id() otherwise.
4510 if (chip->manufacturer.desc && chip->manufacturer.desc->ops &&
4511 chip->manufacturer.desc->ops->detect) {
4512 /* The 3rd id byte holds MLC / multichip data */
4513 chip->bits_per_cell = nand_get_bits_per_cell(chip->id.data[2]);
4514 chip->manufacturer.desc->ops->detect(chip);
4516 nand_decode_ext_id(chip);
4521 * Manufacturer initialization. This function is called for all NANDs including
4522 * ONFI and JEDEC compliant ones.
4523 * Manufacturer drivers should put all their specific initialization code in
4524 * their ->init() hook.
4526 static int nand_manufacturer_init(struct nand_chip *chip)
4528 if (!chip->manufacturer.desc || !chip->manufacturer.desc->ops ||
4529 !chip->manufacturer.desc->ops->init)
4532 return chip->manufacturer.desc->ops->init(chip);
4536 * Manufacturer cleanup. This function is called for all NANDs including
4537 * ONFI and JEDEC compliant ones.
4538 * Manufacturer drivers should put all their specific cleanup code in their
4541 static void nand_manufacturer_cleanup(struct nand_chip *chip)
4543 /* Release manufacturer private data */
4544 if (chip->manufacturer.desc && chip->manufacturer.desc->ops &&
4545 chip->manufacturer.desc->ops->cleanup)
4546 chip->manufacturer.desc->ops->cleanup(chip);
4550 * Get the flash and manufacturer id and lookup if the type is supported.
4552 static int nand_detect(struct nand_chip *chip, struct nand_flash_dev *type)
4554 const struct nand_manufacturer *manufacturer;
4555 struct mtd_info *mtd = nand_to_mtd(chip);
4557 u8 *id_data = chip->id.data;
4561 * Reset the chip, required by some chips (e.g. Micron MT29FxGxxxxx)
4564 ret = nand_reset(chip, 0);
4568 /* Select the device */
4569 chip->select_chip(mtd, 0);
4571 /* Send the command for reading device ID */
4572 ret = nand_readid_op(chip, 0, id_data, 2);
4576 /* Read manufacturer and device IDs */
4577 maf_id = id_data[0];
4578 dev_id = id_data[1];
4581 * Try again to make sure, as some systems the bus-hold or other
4582 * interface concerns can cause random data which looks like a
4583 * possibly credible NAND flash to appear. If the two results do
4584 * not match, ignore the device completely.
4587 /* Read entire ID string */
4588 ret = nand_readid_op(chip, 0, id_data, sizeof(chip->id.data));
4592 if (id_data[0] != maf_id || id_data[1] != dev_id) {
4593 pr_info("second ID read did not match %02x,%02x against %02x,%02x\n",
4594 maf_id, dev_id, id_data[0], id_data[1]);
4598 chip->id.len = nand_id_len(id_data, ARRAY_SIZE(chip->id.data));
4600 /* Try to identify manufacturer */
4601 manufacturer = nand_get_manufacturer(maf_id);
4602 chip->manufacturer.desc = manufacturer;
4605 type = nand_flash_ids;
4608 * Save the NAND_BUSWIDTH_16 flag before letting auto-detection logic
4610 * This is required to make sure initial NAND bus width set by the
4611 * NAND controller driver is coherent with the real NAND bus width
4612 * (extracted by auto-detection code).
4614 busw = chip->options & NAND_BUSWIDTH_16;
4617 * The flag is only set (never cleared), reset it to its default value
4618 * before starting auto-detection.
4620 chip->options &= ~NAND_BUSWIDTH_16;
4622 for (; type->name != NULL; type++) {
4623 if (is_full_id_nand(type)) {
4624 if (find_full_id_nand(chip, type))
4626 } else if (dev_id == type->dev_id) {
4631 chip->onfi_version = 0;
4632 if (!type->name || !type->pagesize) {
4633 /* Check if the chip is ONFI compliant */
4634 if (nand_flash_detect_onfi(chip))
4637 /* Check if the chip is JEDEC compliant */
4638 if (nand_flash_detect_jedec(chip))
4646 mtd->name = type->name;
4648 chip->chipsize = (uint64_t)type->chipsize << 20;
4650 if (!type->pagesize)
4651 nand_manufacturer_detect(chip);
4653 nand_decode_id(chip, type);
4655 /* Get chip options */
4656 chip->options |= type->options;
4660 if (chip->options & NAND_BUSWIDTH_AUTO) {
4661 WARN_ON(busw & NAND_BUSWIDTH_16);
4662 nand_set_defaults(chip);
4663 } else if (busw != (chip->options & NAND_BUSWIDTH_16)) {
4665 * Check, if buswidth is correct. Hardware drivers should set
4668 pr_info("device found, Manufacturer ID: 0x%02x, Chip ID: 0x%02x\n",
4670 pr_info("%s %s\n", nand_manufacturer_name(manufacturer),
4672 pr_warn("bus width %d instead of %d bits\n", busw ? 16 : 8,
4673 (chip->options & NAND_BUSWIDTH_16) ? 16 : 8);
4677 nand_decode_bbm_options(chip);
4679 /* Calculate the address shift from the page size */
4680 chip->page_shift = ffs(mtd->writesize) - 1;
4681 /* Convert chipsize to number of pages per chip -1 */
4682 chip->pagemask = (chip->chipsize >> chip->page_shift) - 1;
4684 chip->bbt_erase_shift = chip->phys_erase_shift =
4685 ffs(mtd->erasesize) - 1;
4686 if (chip->chipsize & 0xffffffff)
4687 chip->chip_shift = ffs((unsigned)chip->chipsize) - 1;
4689 chip->chip_shift = ffs((unsigned)(chip->chipsize >> 32));
4690 chip->chip_shift += 32 - 1;
4693 if (chip->chip_shift - chip->page_shift > 16)
4694 chip->options |= NAND_ROW_ADDR_3;
4696 chip->badblockbits = 8;
4697 chip->erase = single_erase;
4699 /* Do not replace user supplied command function! */
4700 if (mtd->writesize > 512 && chip->cmdfunc == nand_command)
4701 chip->cmdfunc = nand_command_lp;
4703 pr_info("device found, Manufacturer ID: 0x%02x, Chip ID: 0x%02x\n",
4706 if (chip->onfi_version)
4707 pr_info("%s %s\n", nand_manufacturer_name(manufacturer),
4708 chip->onfi_params.model);
4709 else if (chip->jedec_version)
4710 pr_info("%s %s\n", nand_manufacturer_name(manufacturer),
4711 chip->jedec_params.model);
4713 pr_info("%s %s\n", nand_manufacturer_name(manufacturer),
4716 pr_info("%d MiB, %s, erase size: %d KiB, page size: %d, OOB size: %d\n",
4717 (int)(chip->chipsize >> 20), nand_is_slc(chip) ? "SLC" : "MLC",
4718 mtd->erasesize >> 10, mtd->writesize, mtd->oobsize);
4722 static const char * const nand_ecc_modes[] = {
4723 [NAND_ECC_NONE] = "none",
4724 [NAND_ECC_SOFT] = "soft",
4725 [NAND_ECC_HW] = "hw",
4726 [NAND_ECC_HW_SYNDROME] = "hw_syndrome",
4727 [NAND_ECC_HW_OOB_FIRST] = "hw_oob_first",
4728 [NAND_ECC_ON_DIE] = "on-die",
4731 static int of_get_nand_ecc_mode(struct device_node *np)
4736 err = of_property_read_string(np, "nand-ecc-mode", &pm);
4740 for (i = 0; i < ARRAY_SIZE(nand_ecc_modes); i++)
4741 if (!strcasecmp(pm, nand_ecc_modes[i]))
4745 * For backward compatibility we support few obsoleted values that don't
4746 * have their mappings into nand_ecc_modes_t anymore (they were merged
4747 * with other enums).
4749 if (!strcasecmp(pm, "soft_bch"))
4750 return NAND_ECC_SOFT;
4755 static const char * const nand_ecc_algos[] = {
4756 [NAND_ECC_HAMMING] = "hamming",
4757 [NAND_ECC_BCH] = "bch",
4760 static int of_get_nand_ecc_algo(struct device_node *np)
4765 err = of_property_read_string(np, "nand-ecc-algo", &pm);
4767 for (i = NAND_ECC_HAMMING; i < ARRAY_SIZE(nand_ecc_algos); i++)
4768 if (!strcasecmp(pm, nand_ecc_algos[i]))
4774 * For backward compatibility we also read "nand-ecc-mode" checking
4775 * for some obsoleted values that were specifying ECC algorithm.
4777 err = of_property_read_string(np, "nand-ecc-mode", &pm);
4781 if (!strcasecmp(pm, "soft"))
4782 return NAND_ECC_HAMMING;
4783 else if (!strcasecmp(pm, "soft_bch"))
4784 return NAND_ECC_BCH;
4789 static int of_get_nand_ecc_step_size(struct device_node *np)
4794 ret = of_property_read_u32(np, "nand-ecc-step-size", &val);
4795 return ret ? ret : val;
4798 static int of_get_nand_ecc_strength(struct device_node *np)
4803 ret = of_property_read_u32(np, "nand-ecc-strength", &val);
4804 return ret ? ret : val;
4807 static int of_get_nand_bus_width(struct device_node *np)
4811 if (of_property_read_u32(np, "nand-bus-width", &val))
4823 static bool of_get_nand_on_flash_bbt(struct device_node *np)
4825 return of_property_read_bool(np, "nand-on-flash-bbt");
4828 static int nand_dt_init(struct nand_chip *chip)
4830 struct device_node *dn = nand_get_flash_node(chip);
4831 int ecc_mode, ecc_algo, ecc_strength, ecc_step;
4836 if (of_get_nand_bus_width(dn) == 16)
4837 chip->options |= NAND_BUSWIDTH_16;
4839 if (of_get_nand_on_flash_bbt(dn))
4840 chip->bbt_options |= NAND_BBT_USE_FLASH;
4842 ecc_mode = of_get_nand_ecc_mode(dn);
4843 ecc_algo = of_get_nand_ecc_algo(dn);
4844 ecc_strength = of_get_nand_ecc_strength(dn);
4845 ecc_step = of_get_nand_ecc_step_size(dn);
4848 chip->ecc.mode = ecc_mode;
4851 chip->ecc.algo = ecc_algo;
4853 if (ecc_strength >= 0)
4854 chip->ecc.strength = ecc_strength;
4857 chip->ecc.size = ecc_step;
4859 if (of_property_read_bool(dn, "nand-ecc-maximize"))
4860 chip->ecc.options |= NAND_ECC_MAXIMIZE;
4866 * nand_scan_ident - [NAND Interface] Scan for the NAND device
4867 * @mtd: MTD device structure
4868 * @maxchips: number of chips to scan for
4869 * @table: alternative NAND ID table
4871 * This is the first phase of the normal nand_scan() function. It reads the
4872 * flash ID and sets up MTD fields accordingly.
4875 int nand_scan_ident(struct mtd_info *mtd, int maxchips,
4876 struct nand_flash_dev *table)
4878 int i, nand_maf_id, nand_dev_id;
4879 struct nand_chip *chip = mtd_to_nand(mtd);
4882 ret = nand_dt_init(chip);
4886 if (!mtd->name && mtd->dev.parent)
4887 mtd->name = dev_name(mtd->dev.parent);
4889 if ((!chip->cmdfunc || !chip->select_chip) && !chip->cmd_ctrl) {
4891 * Default functions assigned for chip_select() and
4892 * cmdfunc() both expect cmd_ctrl() to be populated,
4893 * so we need to check that that's the case
4895 pr_err("chip.cmd_ctrl() callback is not provided");
4898 /* Set the default functions */
4899 nand_set_defaults(chip);
4901 /* Read the flash type */
4902 ret = nand_detect(chip, table);
4904 if (!(chip->options & NAND_SCAN_SILENT_NODEV))
4905 pr_warn("No NAND device found\n");
4906 chip->select_chip(mtd, -1);
4910 nand_maf_id = chip->id.data[0];
4911 nand_dev_id = chip->id.data[1];
4913 chip->select_chip(mtd, -1);
4915 /* Check for a chip array */
4916 for (i = 1; i < maxchips; i++) {
4919 /* See comment in nand_get_flash_type for reset */
4920 nand_reset(chip, i);
4922 chip->select_chip(mtd, i);
4923 /* Send the command for reading device ID */
4924 nand_readid_op(chip, 0, id, sizeof(id));
4925 /* Read manufacturer and device IDs */
4926 if (nand_maf_id != id[0] || nand_dev_id != id[1]) {
4927 chip->select_chip(mtd, -1);
4930 chip->select_chip(mtd, -1);
4933 pr_info("%d chips detected\n", i);
4935 /* Store the number of chips and calc total size for mtd */
4937 mtd->size = i * chip->chipsize;
4941 EXPORT_SYMBOL(nand_scan_ident);
4943 static int nand_set_ecc_soft_ops(struct mtd_info *mtd)
4945 struct nand_chip *chip = mtd_to_nand(mtd);
4946 struct nand_ecc_ctrl *ecc = &chip->ecc;
4948 if (WARN_ON(ecc->mode != NAND_ECC_SOFT))
4951 switch (ecc->algo) {
4952 case NAND_ECC_HAMMING:
4953 ecc->calculate = nand_calculate_ecc;
4954 ecc->correct = nand_correct_data;
4955 ecc->read_page = nand_read_page_swecc;
4956 ecc->read_subpage = nand_read_subpage;
4957 ecc->write_page = nand_write_page_swecc;
4958 ecc->read_page_raw = nand_read_page_raw;
4959 ecc->write_page_raw = nand_write_page_raw;
4960 ecc->read_oob = nand_read_oob_std;
4961 ecc->write_oob = nand_write_oob_std;
4968 if (!mtd_nand_has_bch()) {
4969 WARN(1, "CONFIG_MTD_NAND_ECC_BCH not enabled\n");
4972 ecc->calculate = nand_bch_calculate_ecc;
4973 ecc->correct = nand_bch_correct_data;
4974 ecc->read_page = nand_read_page_swecc;
4975 ecc->read_subpage = nand_read_subpage;
4976 ecc->write_page = nand_write_page_swecc;
4977 ecc->read_page_raw = nand_read_page_raw;
4978 ecc->write_page_raw = nand_write_page_raw;
4979 ecc->read_oob = nand_read_oob_std;
4980 ecc->write_oob = nand_write_oob_std;
4983 * Board driver should supply ecc.size and ecc.strength
4984 * values to select how many bits are correctable.
4985 * Otherwise, default to 4 bits for large page devices.
4987 if (!ecc->size && (mtd->oobsize >= 64)) {
4993 * if no ecc placement scheme was provided pickup the default
4996 if (!mtd->ooblayout) {
4997 /* handle large page devices only */
4998 if (mtd->oobsize < 64) {
4999 WARN(1, "OOB layout is required when using software BCH on small pages\n");
5003 mtd_set_ooblayout(mtd, &nand_ooblayout_lp_ops);
5008 * We can only maximize ECC config when the default layout is
5009 * used, otherwise we don't know how many bytes can really be
5012 if (mtd->ooblayout == &nand_ooblayout_lp_ops &&
5013 ecc->options & NAND_ECC_MAXIMIZE) {
5016 /* Always prefer 1k blocks over 512bytes ones */
5018 steps = mtd->writesize / ecc->size;
5020 /* Reserve 2 bytes for the BBM */
5021 bytes = (mtd->oobsize - 2) / steps;
5022 ecc->strength = bytes * 8 / fls(8 * ecc->size);
5025 /* See nand_bch_init() for details. */
5027 ecc->priv = nand_bch_init(mtd);
5029 WARN(1, "BCH ECC initialization failed!\n");
5034 WARN(1, "Unsupported ECC algorithm!\n");
5040 * nand_check_ecc_caps - check the sanity of preset ECC settings
5041 * @chip: nand chip info structure
5042 * @caps: ECC caps info structure
5043 * @oobavail: OOB size that the ECC engine can use
5045 * When ECC step size and strength are already set, check if they are supported
5046 * by the controller and the calculated ECC bytes fit within the chip's OOB.
5047 * On success, the calculated ECC bytes is set.
5049 int nand_check_ecc_caps(struct nand_chip *chip,
5050 const struct nand_ecc_caps *caps, int oobavail)
5052 struct mtd_info *mtd = nand_to_mtd(chip);
5053 const struct nand_ecc_step_info *stepinfo;
5054 int preset_step = chip->ecc.size;
5055 int preset_strength = chip->ecc.strength;
5056 int nsteps, ecc_bytes;
5059 if (WARN_ON(oobavail < 0))
5062 if (!preset_step || !preset_strength)
5065 nsteps = mtd->writesize / preset_step;
5067 for (i = 0; i < caps->nstepinfos; i++) {
5068 stepinfo = &caps->stepinfos[i];
5070 if (stepinfo->stepsize != preset_step)
5073 for (j = 0; j < stepinfo->nstrengths; j++) {
5074 if (stepinfo->strengths[j] != preset_strength)
5077 ecc_bytes = caps->calc_ecc_bytes(preset_step,
5079 if (WARN_ON_ONCE(ecc_bytes < 0))
5082 if (ecc_bytes * nsteps > oobavail) {
5083 pr_err("ECC (step, strength) = (%d, %d) does not fit in OOB",
5084 preset_step, preset_strength);
5088 chip->ecc.bytes = ecc_bytes;
5094 pr_err("ECC (step, strength) = (%d, %d) not supported on this controller",
5095 preset_step, preset_strength);
5099 EXPORT_SYMBOL_GPL(nand_check_ecc_caps);
5102 * nand_match_ecc_req - meet the chip's requirement with least ECC bytes
5103 * @chip: nand chip info structure
5104 * @caps: ECC engine caps info structure
5105 * @oobavail: OOB size that the ECC engine can use
5107 * If a chip's ECC requirement is provided, try to meet it with the least
5108 * number of ECC bytes (i.e. with the largest number of OOB-free bytes).
5109 * On success, the chosen ECC settings are set.
5111 int nand_match_ecc_req(struct nand_chip *chip,
5112 const struct nand_ecc_caps *caps, int oobavail)
5114 struct mtd_info *mtd = nand_to_mtd(chip);
5115 const struct nand_ecc_step_info *stepinfo;
5116 int req_step = chip->ecc_step_ds;
5117 int req_strength = chip->ecc_strength_ds;
5118 int req_corr, step_size, strength, nsteps, ecc_bytes, ecc_bytes_total;
5119 int best_step, best_strength, best_ecc_bytes;
5120 int best_ecc_bytes_total = INT_MAX;
5123 if (WARN_ON(oobavail < 0))
5126 /* No information provided by the NAND chip */
5127 if (!req_step || !req_strength)
5130 /* number of correctable bits the chip requires in a page */
5131 req_corr = mtd->writesize / req_step * req_strength;
5133 for (i = 0; i < caps->nstepinfos; i++) {
5134 stepinfo = &caps->stepinfos[i];
5135 step_size = stepinfo->stepsize;
5137 for (j = 0; j < stepinfo->nstrengths; j++) {
5138 strength = stepinfo->strengths[j];
5141 * If both step size and strength are smaller than the
5142 * chip's requirement, it is not easy to compare the
5143 * resulted reliability.
5145 if (step_size < req_step && strength < req_strength)
5148 if (mtd->writesize % step_size)
5151 nsteps = mtd->writesize / step_size;
5153 ecc_bytes = caps->calc_ecc_bytes(step_size, strength);
5154 if (WARN_ON_ONCE(ecc_bytes < 0))
5156 ecc_bytes_total = ecc_bytes * nsteps;
5158 if (ecc_bytes_total > oobavail ||
5159 strength * nsteps < req_corr)
5163 * We assume the best is to meet the chip's requrement
5164 * with the least number of ECC bytes.
5166 if (ecc_bytes_total < best_ecc_bytes_total) {
5167 best_ecc_bytes_total = ecc_bytes_total;
5168 best_step = step_size;
5169 best_strength = strength;
5170 best_ecc_bytes = ecc_bytes;
5175 if (best_ecc_bytes_total == INT_MAX)
5178 chip->ecc.size = best_step;
5179 chip->ecc.strength = best_strength;
5180 chip->ecc.bytes = best_ecc_bytes;
5184 EXPORT_SYMBOL_GPL(nand_match_ecc_req);
5187 * nand_maximize_ecc - choose the max ECC strength available
5188 * @chip: nand chip info structure
5189 * @caps: ECC engine caps info structure
5190 * @oobavail: OOB size that the ECC engine can use
5192 * Choose the max ECC strength that is supported on the controller, and can fit
5193 * within the chip's OOB. On success, the chosen ECC settings are set.
5195 int nand_maximize_ecc(struct nand_chip *chip,
5196 const struct nand_ecc_caps *caps, int oobavail)
5198 struct mtd_info *mtd = nand_to_mtd(chip);
5199 const struct nand_ecc_step_info *stepinfo;
5200 int step_size, strength, nsteps, ecc_bytes, corr;
5203 int best_strength, best_ecc_bytes;
5206 if (WARN_ON(oobavail < 0))
5209 for (i = 0; i < caps->nstepinfos; i++) {
5210 stepinfo = &caps->stepinfos[i];
5211 step_size = stepinfo->stepsize;
5213 /* If chip->ecc.size is already set, respect it */
5214 if (chip->ecc.size && step_size != chip->ecc.size)
5217 for (j = 0; j < stepinfo->nstrengths; j++) {
5218 strength = stepinfo->strengths[j];
5220 if (mtd->writesize % step_size)
5223 nsteps = mtd->writesize / step_size;
5225 ecc_bytes = caps->calc_ecc_bytes(step_size, strength);
5226 if (WARN_ON_ONCE(ecc_bytes < 0))
5229 if (ecc_bytes * nsteps > oobavail)
5232 corr = strength * nsteps;
5235 * If the number of correctable bits is the same,
5236 * bigger step_size has more reliability.
5238 if (corr > best_corr ||
5239 (corr == best_corr && step_size > best_step)) {
5241 best_step = step_size;
5242 best_strength = strength;
5243 best_ecc_bytes = ecc_bytes;
5251 chip->ecc.size = best_step;
5252 chip->ecc.strength = best_strength;
5253 chip->ecc.bytes = best_ecc_bytes;
5257 EXPORT_SYMBOL_GPL(nand_maximize_ecc);
5260 * Check if the chip configuration meet the datasheet requirements.
5262 * If our configuration corrects A bits per B bytes and the minimum
5263 * required correction level is X bits per Y bytes, then we must ensure
5264 * both of the following are true:
5266 * (1) A / B >= X / Y
5269 * Requirement (1) ensures we can correct for the required bitflip density.
5270 * Requirement (2) ensures we can correct even when all bitflips are clumped
5271 * in the same sector.
5273 static bool nand_ecc_strength_good(struct mtd_info *mtd)
5275 struct nand_chip *chip = mtd_to_nand(mtd);
5276 struct nand_ecc_ctrl *ecc = &chip->ecc;
5279 if (ecc->size == 0 || chip->ecc_step_ds == 0)
5280 /* Not enough information */
5284 * We get the number of corrected bits per page to compare
5285 * the correction density.
5287 corr = (mtd->writesize * ecc->strength) / ecc->size;
5288 ds_corr = (mtd->writesize * chip->ecc_strength_ds) / chip->ecc_step_ds;
5290 return corr >= ds_corr && ecc->strength >= chip->ecc_strength_ds;
5293 static bool invalid_ecc_page_accessors(struct nand_chip *chip)
5295 struct nand_ecc_ctrl *ecc = &chip->ecc;
5297 if (nand_standard_page_accessors(ecc))
5301 * NAND_ECC_CUSTOM_PAGE_ACCESS flag is set, make sure the NAND
5302 * controller driver implements all the page accessors because
5303 * default helpers are not suitable when the core does not
5304 * send the READ0/PAGEPROG commands.
5306 return (!ecc->read_page || !ecc->write_page ||
5307 !ecc->read_page_raw || !ecc->write_page_raw ||
5308 (NAND_HAS_SUBPAGE_READ(chip) && !ecc->read_subpage) ||
5309 (NAND_HAS_SUBPAGE_WRITE(chip) && !ecc->write_subpage &&
5310 ecc->hwctl && ecc->calculate));
5314 * nand_scan_tail - [NAND Interface] Scan for the NAND device
5315 * @mtd: MTD device structure
5317 * This is the second phase of the normal nand_scan() function. It fills out
5318 * all the uninitialized function pointers with the defaults and scans for a
5319 * bad block table if appropriate.
5321 int nand_scan_tail(struct mtd_info *mtd)
5323 struct nand_chip *chip = mtd_to_nand(mtd);
5324 struct nand_ecc_ctrl *ecc = &chip->ecc;
5325 struct nand_buffers *nbuf = NULL;
5328 /* New bad blocks should be marked in OOB, flash-based BBT, or both */
5329 if (WARN_ON((chip->bbt_options & NAND_BBT_NO_OOB_BBM) &&
5330 !(chip->bbt_options & NAND_BBT_USE_FLASH))) {
5334 if (invalid_ecc_page_accessors(chip)) {
5335 pr_err("Invalid ECC page accessors setup\n");
5339 if (!(chip->options & NAND_OWN_BUFFERS)) {
5340 nbuf = kzalloc(sizeof(*nbuf), GFP_KERNEL);
5344 nbuf->ecccalc = kmalloc(mtd->oobsize, GFP_KERNEL);
5345 if (!nbuf->ecccalc) {
5350 nbuf->ecccode = kmalloc(mtd->oobsize, GFP_KERNEL);
5351 if (!nbuf->ecccode) {
5356 nbuf->databuf = kmalloc(mtd->writesize + mtd->oobsize,
5358 if (!nbuf->databuf) {
5363 chip->buffers = nbuf;
5364 } else if (!chip->buffers) {
5369 * FIXME: some NAND manufacturer drivers expect the first die to be
5370 * selected when manufacturer->init() is called. They should be fixed
5371 * to explictly select the relevant die when interacting with the NAND
5374 chip->select_chip(mtd, 0);
5375 ret = nand_manufacturer_init(chip);
5376 chip->select_chip(mtd, -1);
5380 /* Set the internal oob buffer location, just after the page data */
5381 chip->oob_poi = chip->buffers->databuf + mtd->writesize;
5384 * If no default placement scheme is given, select an appropriate one.
5386 if (!mtd->ooblayout &&
5387 !(ecc->mode == NAND_ECC_SOFT && ecc->algo == NAND_ECC_BCH)) {
5388 switch (mtd->oobsize) {
5391 mtd_set_ooblayout(mtd, &nand_ooblayout_sp_ops);
5395 mtd_set_ooblayout(mtd, &nand_ooblayout_lp_hamming_ops);
5399 * Expose the whole OOB area to users if ECC_NONE
5400 * is passed. We could do that for all kind of
5401 * ->oobsize, but we must keep the old large/small
5402 * page with ECC layout when ->oobsize <= 128 for
5403 * compatibility reasons.
5405 if (ecc->mode == NAND_ECC_NONE) {
5406 mtd_set_ooblayout(mtd,
5407 &nand_ooblayout_lp_ops);
5411 WARN(1, "No oob scheme defined for oobsize %d\n",
5414 goto err_nand_manuf_cleanup;
5419 * Check ECC mode, default to software if 3byte/512byte hardware ECC is
5420 * selected and we have 256 byte pagesize fallback to software ECC
5423 switch (ecc->mode) {
5424 case NAND_ECC_HW_OOB_FIRST:
5425 /* Similar to NAND_ECC_HW, but a separate read_page handle */
5426 if (!ecc->calculate || !ecc->correct || !ecc->hwctl) {
5427 WARN(1, "No ECC functions supplied; hardware ECC not possible\n");
5429 goto err_nand_manuf_cleanup;
5431 if (!ecc->read_page)
5432 ecc->read_page = nand_read_page_hwecc_oob_first;
5435 /* Use standard hwecc read page function? */
5436 if (!ecc->read_page)
5437 ecc->read_page = nand_read_page_hwecc;
5438 if (!ecc->write_page)
5439 ecc->write_page = nand_write_page_hwecc;
5440 if (!ecc->read_page_raw)
5441 ecc->read_page_raw = nand_read_page_raw;
5442 if (!ecc->write_page_raw)
5443 ecc->write_page_raw = nand_write_page_raw;
5445 ecc->read_oob = nand_read_oob_std;
5446 if (!ecc->write_oob)
5447 ecc->write_oob = nand_write_oob_std;
5448 if (!ecc->read_subpage)
5449 ecc->read_subpage = nand_read_subpage;
5450 if (!ecc->write_subpage && ecc->hwctl && ecc->calculate)
5451 ecc->write_subpage = nand_write_subpage_hwecc;
5453 case NAND_ECC_HW_SYNDROME:
5454 if ((!ecc->calculate || !ecc->correct || !ecc->hwctl) &&
5456 ecc->read_page == nand_read_page_hwecc ||
5458 ecc->write_page == nand_write_page_hwecc)) {
5459 WARN(1, "No ECC functions supplied; hardware ECC not possible\n");
5461 goto err_nand_manuf_cleanup;
5463 /* Use standard syndrome read/write page function? */
5464 if (!ecc->read_page)
5465 ecc->read_page = nand_read_page_syndrome;
5466 if (!ecc->write_page)
5467 ecc->write_page = nand_write_page_syndrome;
5468 if (!ecc->read_page_raw)
5469 ecc->read_page_raw = nand_read_page_raw_syndrome;
5470 if (!ecc->write_page_raw)
5471 ecc->write_page_raw = nand_write_page_raw_syndrome;
5473 ecc->read_oob = nand_read_oob_syndrome;
5474 if (!ecc->write_oob)
5475 ecc->write_oob = nand_write_oob_syndrome;
5477 if (mtd->writesize >= ecc->size) {
5478 if (!ecc->strength) {
5479 WARN(1, "Driver must set ecc.strength when using hardware ECC\n");
5481 goto err_nand_manuf_cleanup;
5485 pr_warn("%d byte HW ECC not possible on %d byte page size, fallback to SW ECC\n",
5486 ecc->size, mtd->writesize);
5487 ecc->mode = NAND_ECC_SOFT;
5488 ecc->algo = NAND_ECC_HAMMING;
5491 ret = nand_set_ecc_soft_ops(mtd);
5494 goto err_nand_manuf_cleanup;
5498 case NAND_ECC_ON_DIE:
5499 if (!ecc->read_page || !ecc->write_page) {
5500 WARN(1, "No ECC functions supplied; on-die ECC not possible\n");
5502 goto err_nand_manuf_cleanup;
5505 ecc->read_oob = nand_read_oob_std;
5506 if (!ecc->write_oob)
5507 ecc->write_oob = nand_write_oob_std;
5511 pr_warn("NAND_ECC_NONE selected by board driver. This is not recommended!\n");
5512 ecc->read_page = nand_read_page_raw;
5513 ecc->write_page = nand_write_page_raw;
5514 ecc->read_oob = nand_read_oob_std;
5515 ecc->read_page_raw = nand_read_page_raw;
5516 ecc->write_page_raw = nand_write_page_raw;
5517 ecc->write_oob = nand_write_oob_std;
5518 ecc->size = mtd->writesize;
5524 WARN(1, "Invalid NAND_ECC_MODE %d\n", ecc->mode);
5526 goto err_nand_manuf_cleanup;
5529 /* For many systems, the standard OOB write also works for raw */
5530 if (!ecc->read_oob_raw)
5531 ecc->read_oob_raw = ecc->read_oob;
5532 if (!ecc->write_oob_raw)
5533 ecc->write_oob_raw = ecc->write_oob;
5535 /* propagate ecc info to mtd_info */
5536 mtd->ecc_strength = ecc->strength;
5537 mtd->ecc_step_size = ecc->size;
5540 * Set the number of read / write steps for one page depending on ECC
5543 ecc->steps = mtd->writesize / ecc->size;
5544 if (ecc->steps * ecc->size != mtd->writesize) {
5545 WARN(1, "Invalid ECC parameters\n");
5547 goto err_nand_manuf_cleanup;
5549 ecc->total = ecc->steps * ecc->bytes;
5550 if (ecc->total > mtd->oobsize) {
5551 WARN(1, "Total number of ECC bytes exceeded oobsize\n");
5553 goto err_nand_manuf_cleanup;
5557 * The number of bytes available for a client to place data into
5558 * the out of band area.
5560 ret = mtd_ooblayout_count_freebytes(mtd);
5564 mtd->oobavail = ret;
5566 /* ECC sanity check: warn if it's too weak */
5567 if (!nand_ecc_strength_good(mtd))
5568 pr_warn("WARNING: %s: the ECC used on your system is too weak compared to the one required by the NAND chip\n",
5571 /* Allow subpage writes up to ecc.steps. Not possible for MLC flash */
5572 if (!(chip->options & NAND_NO_SUBPAGE_WRITE) && nand_is_slc(chip)) {
5573 switch (ecc->steps) {
5575 mtd->subpage_sft = 1;
5580 mtd->subpage_sft = 2;
5584 chip->subpagesize = mtd->writesize >> mtd->subpage_sft;
5586 /* Initialize state */
5587 chip->state = FL_READY;
5589 /* Invalidate the pagebuffer reference */
5592 /* Large page NAND with SOFT_ECC should support subpage reads */
5593 switch (ecc->mode) {
5595 if (chip->page_shift > 9)
5596 chip->options |= NAND_SUBPAGE_READ;
5603 /* Fill in remaining MTD driver data */
5604 mtd->type = nand_is_slc(chip) ? MTD_NANDFLASH : MTD_MLCNANDFLASH;
5605 mtd->flags = (chip->options & NAND_ROM) ? MTD_CAP_ROM :
5607 mtd->_erase = nand_erase;
5609 mtd->_unpoint = NULL;
5610 mtd->_read = nand_read;
5611 mtd->_write = nand_write;
5612 mtd->_panic_write = panic_nand_write;
5613 mtd->_read_oob = nand_read_oob;
5614 mtd->_write_oob = nand_write_oob;
5615 mtd->_sync = nand_sync;
5617 mtd->_unlock = NULL;
5618 mtd->_suspend = nand_suspend;
5619 mtd->_resume = nand_resume;
5620 mtd->_reboot = nand_shutdown;
5621 mtd->_block_isreserved = nand_block_isreserved;
5622 mtd->_block_isbad = nand_block_isbad;
5623 mtd->_block_markbad = nand_block_markbad;
5624 mtd->_max_bad_blocks = nand_max_bad_blocks;
5625 mtd->writebufsize = mtd->writesize;
5628 * Initialize bitflip_threshold to its default prior scan_bbt() call.
5629 * scan_bbt() might invoke mtd_read(), thus bitflip_threshold must be
5632 if (!mtd->bitflip_threshold)
5633 mtd->bitflip_threshold = DIV_ROUND_UP(mtd->ecc_strength * 3, 4);
5635 /* Initialize the ->data_interface field. */
5636 ret = nand_init_data_interface(chip);
5638 goto err_nand_manuf_cleanup;
5640 /* Enter fastest possible mode on all dies. */
5641 for (i = 0; i < chip->numchips; i++) {
5642 chip->select_chip(mtd, i);
5643 ret = nand_setup_data_interface(chip, i);
5644 chip->select_chip(mtd, -1);
5647 goto err_nand_data_iface_cleanup;
5650 /* Check, if we should skip the bad block table scan */
5651 if (chip->options & NAND_SKIP_BBTSCAN)
5654 /* Build bad block table */
5655 ret = chip->scan_bbt(mtd);
5657 goto err_nand_data_iface_cleanup;
5661 err_nand_data_iface_cleanup:
5662 nand_release_data_interface(chip);
5664 err_nand_manuf_cleanup:
5665 nand_manufacturer_cleanup(chip);
5669 kfree(nbuf->databuf);
5670 kfree(nbuf->ecccode);
5671 kfree(nbuf->ecccalc);
5677 EXPORT_SYMBOL(nand_scan_tail);
5680 * is_module_text_address() isn't exported, and it's mostly a pointless
5681 * test if this is a module _anyway_ -- they'd have to try _really_ hard
5682 * to call us from in-kernel code if the core NAND support is modular.
5685 #define caller_is_module() (1)
5687 #define caller_is_module() \
5688 is_module_text_address((unsigned long)__builtin_return_address(0))
5692 * nand_scan - [NAND Interface] Scan for the NAND device
5693 * @mtd: MTD device structure
5694 * @maxchips: number of chips to scan for
5696 * This fills out all the uninitialized function pointers with the defaults.
5697 * The flash ID is read and the mtd/chip structures are filled with the
5698 * appropriate values.
5700 int nand_scan(struct mtd_info *mtd, int maxchips)
5704 ret = nand_scan_ident(mtd, maxchips, NULL);
5706 ret = nand_scan_tail(mtd);
5709 EXPORT_SYMBOL(nand_scan);
5712 * nand_cleanup - [NAND Interface] Free resources held by the NAND device
5713 * @chip: NAND chip object
5715 void nand_cleanup(struct nand_chip *chip)
5717 if (chip->ecc.mode == NAND_ECC_SOFT &&
5718 chip->ecc.algo == NAND_ECC_BCH)
5719 nand_bch_free((struct nand_bch_control *)chip->ecc.priv);
5721 nand_release_data_interface(chip);
5723 /* Free bad block table memory */
5725 if (!(chip->options & NAND_OWN_BUFFERS) && chip->buffers) {
5726 kfree(chip->buffers->databuf);
5727 kfree(chip->buffers->ecccode);
5728 kfree(chip->buffers->ecccalc);
5729 kfree(chip->buffers);
5732 /* Free bad block descriptor memory */
5733 if (chip->badblock_pattern && chip->badblock_pattern->options
5734 & NAND_BBT_DYNAMICSTRUCT)
5735 kfree(chip->badblock_pattern);
5737 /* Free manufacturer priv data. */
5738 nand_manufacturer_cleanup(chip);
5740 EXPORT_SYMBOL_GPL(nand_cleanup);
5743 * nand_release - [NAND Interface] Unregister the MTD device and free resources
5744 * held by the NAND device
5745 * @mtd: MTD device structure
5747 void nand_release(struct mtd_info *mtd)
5749 mtd_device_unregister(mtd);
5750 nand_cleanup(mtd_to_nand(mtd));
5752 EXPORT_SYMBOL_GPL(nand_release);
5754 MODULE_LICENSE("GPL");
5755 MODULE_AUTHOR("Steven J. Hill <sjhill@realitydiluted.com>");
5756 MODULE_AUTHOR("Thomas Gleixner <tglx@linutronix.de>");
5757 MODULE_DESCRIPTION("Generic NAND flash driver code");