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/nand.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 oobregion->length = 4;
70 oobregion->offset = 6;
71 oobregion->length = ecc->total - 4;
77 static int nand_ooblayout_free_sp(struct mtd_info *mtd, int section,
78 struct mtd_oob_region *oobregion)
83 if (mtd->oobsize == 16) {
87 oobregion->length = 8;
88 oobregion->offset = 8;
90 oobregion->length = 2;
92 oobregion->offset = 3;
94 oobregion->offset = 6;
100 const struct mtd_ooblayout_ops nand_ooblayout_sp_ops = {
101 .ecc = nand_ooblayout_ecc_sp,
102 .free = nand_ooblayout_free_sp,
104 EXPORT_SYMBOL_GPL(nand_ooblayout_sp_ops);
106 static int nand_ooblayout_ecc_lp(struct mtd_info *mtd, int section,
107 struct mtd_oob_region *oobregion)
109 struct nand_chip *chip = mtd_to_nand(mtd);
110 struct nand_ecc_ctrl *ecc = &chip->ecc;
115 oobregion->length = ecc->total;
116 oobregion->offset = mtd->oobsize - oobregion->length;
121 static int nand_ooblayout_free_lp(struct mtd_info *mtd, int section,
122 struct mtd_oob_region *oobregion)
124 struct nand_chip *chip = mtd_to_nand(mtd);
125 struct nand_ecc_ctrl *ecc = &chip->ecc;
130 oobregion->length = mtd->oobsize - ecc->total - 2;
131 oobregion->offset = 2;
136 const struct mtd_ooblayout_ops nand_ooblayout_lp_ops = {
137 .ecc = nand_ooblayout_ecc_lp,
138 .free = nand_ooblayout_free_lp,
140 EXPORT_SYMBOL_GPL(nand_ooblayout_lp_ops);
142 static int check_offs_len(struct mtd_info *mtd,
143 loff_t ofs, uint64_t len)
145 struct nand_chip *chip = mtd_to_nand(mtd);
148 /* Start address must align on block boundary */
149 if (ofs & ((1ULL << chip->phys_erase_shift) - 1)) {
150 pr_debug("%s: unaligned address\n", __func__);
154 /* Length must align on block boundary */
155 if (len & ((1ULL << chip->phys_erase_shift) - 1)) {
156 pr_debug("%s: length not block aligned\n", __func__);
164 * nand_release_device - [GENERIC] release chip
165 * @mtd: MTD device structure
167 * Release chip lock and wake up anyone waiting on the device.
169 static void nand_release_device(struct mtd_info *mtd)
171 struct nand_chip *chip = mtd_to_nand(mtd);
173 /* Release the controller and the chip */
174 spin_lock(&chip->controller->lock);
175 chip->controller->active = NULL;
176 chip->state = FL_READY;
177 wake_up(&chip->controller->wq);
178 spin_unlock(&chip->controller->lock);
182 * nand_read_byte - [DEFAULT] read one byte from the chip
183 * @mtd: MTD device structure
185 * Default read function for 8bit buswidth
187 static uint8_t nand_read_byte(struct mtd_info *mtd)
189 struct nand_chip *chip = mtd_to_nand(mtd);
190 return readb(chip->IO_ADDR_R);
194 * nand_read_byte16 - [DEFAULT] read one byte endianness aware from the chip
195 * @mtd: MTD device structure
197 * Default read function for 16bit buswidth with endianness conversion.
200 static uint8_t nand_read_byte16(struct mtd_info *mtd)
202 struct nand_chip *chip = mtd_to_nand(mtd);
203 return (uint8_t) cpu_to_le16(readw(chip->IO_ADDR_R));
207 * nand_read_word - [DEFAULT] read one word from the chip
208 * @mtd: MTD device structure
210 * Default read function for 16bit buswidth without endianness conversion.
212 static u16 nand_read_word(struct mtd_info *mtd)
214 struct nand_chip *chip = mtd_to_nand(mtd);
215 return readw(chip->IO_ADDR_R);
219 * nand_select_chip - [DEFAULT] control CE line
220 * @mtd: MTD device structure
221 * @chipnr: chipnumber to select, -1 for deselect
223 * Default select function for 1 chip devices.
225 static void nand_select_chip(struct mtd_info *mtd, int chipnr)
227 struct nand_chip *chip = mtd_to_nand(mtd);
231 chip->cmd_ctrl(mtd, NAND_CMD_NONE, 0 | NAND_CTRL_CHANGE);
242 * nand_write_byte - [DEFAULT] write single byte to chip
243 * @mtd: MTD device structure
244 * @byte: value to write
246 * Default function to write a byte to I/O[7:0]
248 static void nand_write_byte(struct mtd_info *mtd, uint8_t byte)
250 struct nand_chip *chip = mtd_to_nand(mtd);
252 chip->write_buf(mtd, &byte, 1);
256 * nand_write_byte16 - [DEFAULT] write single byte to a chip with width 16
257 * @mtd: MTD device structure
258 * @byte: value to write
260 * Default function to write a byte to I/O[7:0] on a 16-bit wide chip.
262 static void nand_write_byte16(struct mtd_info *mtd, uint8_t byte)
264 struct nand_chip *chip = mtd_to_nand(mtd);
265 uint16_t word = byte;
268 * It's not entirely clear what should happen to I/O[15:8] when writing
269 * a byte. The ONFi spec (Revision 3.1; 2012-09-19, Section 2.16) reads:
271 * When the host supports a 16-bit bus width, only data is
272 * transferred at the 16-bit width. All address and command line
273 * transfers shall use only the lower 8-bits of the data bus. During
274 * command transfers, the host may place any value on the upper
275 * 8-bits of the data bus. During address transfers, the host shall
276 * set the upper 8-bits of the data bus to 00h.
278 * One user of the write_byte callback is nand_onfi_set_features. The
279 * four parameters are specified to be written to I/O[7:0], but this is
280 * neither an address nor a command transfer. Let's assume a 0 on the
281 * upper I/O lines is OK.
283 chip->write_buf(mtd, (uint8_t *)&word, 2);
287 * nand_write_buf - [DEFAULT] write buffer to chip
288 * @mtd: MTD device structure
290 * @len: number of bytes to write
292 * Default write function for 8bit buswidth.
294 static void nand_write_buf(struct mtd_info *mtd, const uint8_t *buf, int len)
296 struct nand_chip *chip = mtd_to_nand(mtd);
298 iowrite8_rep(chip->IO_ADDR_W, buf, len);
302 * nand_read_buf - [DEFAULT] read chip data into buffer
303 * @mtd: MTD device structure
304 * @buf: buffer to store date
305 * @len: number of bytes to read
307 * Default read function for 8bit buswidth.
309 static void nand_read_buf(struct mtd_info *mtd, uint8_t *buf, int len)
311 struct nand_chip *chip = mtd_to_nand(mtd);
313 ioread8_rep(chip->IO_ADDR_R, buf, len);
317 * nand_write_buf16 - [DEFAULT] write buffer to chip
318 * @mtd: MTD device structure
320 * @len: number of bytes to write
322 * Default write function for 16bit buswidth.
324 static void nand_write_buf16(struct mtd_info *mtd, const uint8_t *buf, int len)
326 struct nand_chip *chip = mtd_to_nand(mtd);
327 u16 *p = (u16 *) buf;
329 iowrite16_rep(chip->IO_ADDR_W, p, len >> 1);
333 * nand_read_buf16 - [DEFAULT] read chip data into buffer
334 * @mtd: MTD device structure
335 * @buf: buffer to store date
336 * @len: number of bytes to read
338 * Default read function for 16bit buswidth.
340 static void nand_read_buf16(struct mtd_info *mtd, uint8_t *buf, int len)
342 struct nand_chip *chip = mtd_to_nand(mtd);
343 u16 *p = (u16 *) buf;
345 ioread16_rep(chip->IO_ADDR_R, p, len >> 1);
349 * nand_block_bad - [DEFAULT] Read bad block marker from the chip
350 * @mtd: MTD device structure
351 * @ofs: offset from device start
353 * Check, if the block is bad.
355 static int nand_block_bad(struct mtd_info *mtd, loff_t ofs)
357 int page, page_end, res;
358 struct nand_chip *chip = mtd_to_nand(mtd);
361 if (chip->bbt_options & NAND_BBT_SCANLASTPAGE)
362 ofs += mtd->erasesize - mtd->writesize;
364 page = (int)(ofs >> chip->page_shift) & chip->pagemask;
365 page_end = page + (chip->bbt_options & NAND_BBT_SCAN2NDPAGE ? 2 : 1);
367 for (; page < page_end; page++) {
368 res = chip->ecc.read_oob(mtd, chip, page);
372 bad = chip->oob_poi[chip->badblockpos];
374 if (likely(chip->badblockbits == 8))
377 res = hweight8(bad) < chip->badblockbits;
386 * nand_default_block_markbad - [DEFAULT] mark a block bad via bad block marker
387 * @mtd: MTD device structure
388 * @ofs: offset from device start
390 * This is the default implementation, which can be overridden by a hardware
391 * specific driver. It provides the details for writing a bad block marker to a
394 static int nand_default_block_markbad(struct mtd_info *mtd, loff_t ofs)
396 struct nand_chip *chip = mtd_to_nand(mtd);
397 struct mtd_oob_ops ops;
398 uint8_t buf[2] = { 0, 0 };
399 int ret = 0, res, i = 0;
401 memset(&ops, 0, sizeof(ops));
403 ops.ooboffs = chip->badblockpos;
404 if (chip->options & NAND_BUSWIDTH_16) {
405 ops.ooboffs &= ~0x01;
406 ops.len = ops.ooblen = 2;
408 ops.len = ops.ooblen = 1;
410 ops.mode = MTD_OPS_PLACE_OOB;
412 /* Write to first/last page(s) if necessary */
413 if (chip->bbt_options & NAND_BBT_SCANLASTPAGE)
414 ofs += mtd->erasesize - mtd->writesize;
416 res = nand_do_write_oob(mtd, ofs, &ops);
421 ofs += mtd->writesize;
422 } while ((chip->bbt_options & NAND_BBT_SCAN2NDPAGE) && i < 2);
428 * nand_block_markbad_lowlevel - mark a block bad
429 * @mtd: MTD device structure
430 * @ofs: offset from device start
432 * This function performs the generic NAND bad block marking steps (i.e., bad
433 * block table(s) and/or marker(s)). We only allow the hardware driver to
434 * specify how to write bad block markers to OOB (chip->block_markbad).
436 * We try operations in the following order:
437 * (1) erase the affected block, to allow OOB marker to be written cleanly
438 * (2) write bad block marker to OOB area of affected block (unless flag
439 * NAND_BBT_NO_OOB_BBM is present)
441 * Note that we retain the first error encountered in (2) or (3), finish the
442 * procedures, and dump the error in the end.
444 static int nand_block_markbad_lowlevel(struct mtd_info *mtd, loff_t ofs)
446 struct nand_chip *chip = mtd_to_nand(mtd);
449 if (!(chip->bbt_options & NAND_BBT_NO_OOB_BBM)) {
450 struct erase_info einfo;
452 /* Attempt erase before marking OOB */
453 memset(&einfo, 0, sizeof(einfo));
456 einfo.len = 1ULL << chip->phys_erase_shift;
457 nand_erase_nand(mtd, &einfo, 0);
459 /* Write bad block marker to OOB */
460 nand_get_device(mtd, FL_WRITING);
461 ret = chip->block_markbad(mtd, ofs);
462 nand_release_device(mtd);
465 /* Mark block bad in BBT */
467 res = nand_markbad_bbt(mtd, ofs);
473 mtd->ecc_stats.badblocks++;
479 * nand_check_wp - [GENERIC] check if the chip is write protected
480 * @mtd: MTD device structure
482 * Check, if the device is write protected. The function expects, that the
483 * device is already selected.
485 static int nand_check_wp(struct mtd_info *mtd)
487 struct nand_chip *chip = mtd_to_nand(mtd);
489 /* Broken xD cards report WP despite being writable */
490 if (chip->options & NAND_BROKEN_XD)
493 /* Check the WP bit */
494 chip->cmdfunc(mtd, NAND_CMD_STATUS, -1, -1);
495 return (chip->read_byte(mtd) & NAND_STATUS_WP) ? 0 : 1;
499 * nand_block_isreserved - [GENERIC] Check if a block is marked reserved.
500 * @mtd: MTD device structure
501 * @ofs: offset from device start
503 * Check if the block is marked as reserved.
505 static int nand_block_isreserved(struct mtd_info *mtd, loff_t ofs)
507 struct nand_chip *chip = mtd_to_nand(mtd);
511 /* Return info from the table */
512 return nand_isreserved_bbt(mtd, ofs);
516 * nand_block_checkbad - [GENERIC] Check if a block is marked bad
517 * @mtd: MTD device structure
518 * @ofs: offset from device start
519 * @allowbbt: 1, if its allowed to access the bbt area
521 * Check, if the block is bad. Either by reading the bad block table or
522 * calling of the scan function.
524 static int nand_block_checkbad(struct mtd_info *mtd, loff_t ofs, int allowbbt)
526 struct nand_chip *chip = mtd_to_nand(mtd);
529 return chip->block_bad(mtd, ofs);
531 /* Return info from the table */
532 return nand_isbad_bbt(mtd, ofs, allowbbt);
536 * panic_nand_wait_ready - [GENERIC] Wait for the ready pin after commands.
537 * @mtd: MTD device structure
540 * Helper function for nand_wait_ready used when needing to wait in interrupt
543 static void panic_nand_wait_ready(struct mtd_info *mtd, unsigned long timeo)
545 struct nand_chip *chip = mtd_to_nand(mtd);
548 /* Wait for the device to get ready */
549 for (i = 0; i < timeo; i++) {
550 if (chip->dev_ready(mtd))
552 touch_softlockup_watchdog();
558 * nand_wait_ready - [GENERIC] Wait for the ready pin after commands.
559 * @mtd: MTD device structure
561 * Wait for the ready pin after a command, and warn if a timeout occurs.
563 void nand_wait_ready(struct mtd_info *mtd)
565 struct nand_chip *chip = mtd_to_nand(mtd);
566 unsigned long timeo = 400;
568 if (in_interrupt() || oops_in_progress)
569 return panic_nand_wait_ready(mtd, timeo);
571 /* Wait until command is processed or timeout occurs */
572 timeo = jiffies + msecs_to_jiffies(timeo);
574 if (chip->dev_ready(mtd))
577 } while (time_before(jiffies, timeo));
579 if (!chip->dev_ready(mtd))
580 pr_warn_ratelimited("timeout while waiting for chip to become ready\n");
582 EXPORT_SYMBOL_GPL(nand_wait_ready);
585 * nand_wait_status_ready - [GENERIC] Wait for the ready status after commands.
586 * @mtd: MTD device structure
587 * @timeo: Timeout in ms
589 * Wait for status ready (i.e. command done) or timeout.
591 static void nand_wait_status_ready(struct mtd_info *mtd, unsigned long timeo)
593 register struct nand_chip *chip = mtd_to_nand(mtd);
595 timeo = jiffies + msecs_to_jiffies(timeo);
597 if ((chip->read_byte(mtd) & NAND_STATUS_READY))
599 touch_softlockup_watchdog();
600 } while (time_before(jiffies, timeo));
604 * nand_command - [DEFAULT] Send command to NAND device
605 * @mtd: MTD device structure
606 * @command: the command to be sent
607 * @column: the column address for this command, -1 if none
608 * @page_addr: the page address for this command, -1 if none
610 * Send command to NAND device. This function is used for small page devices
611 * (512 Bytes per page).
613 static void nand_command(struct mtd_info *mtd, unsigned int command,
614 int column, int page_addr)
616 register struct nand_chip *chip = mtd_to_nand(mtd);
617 int ctrl = NAND_CTRL_CLE | NAND_CTRL_CHANGE;
619 /* Write out the command to the device */
620 if (command == NAND_CMD_SEQIN) {
623 if (column >= mtd->writesize) {
625 column -= mtd->writesize;
626 readcmd = NAND_CMD_READOOB;
627 } else if (column < 256) {
628 /* First 256 bytes --> READ0 */
629 readcmd = NAND_CMD_READ0;
632 readcmd = NAND_CMD_READ1;
634 chip->cmd_ctrl(mtd, readcmd, ctrl);
635 ctrl &= ~NAND_CTRL_CHANGE;
637 chip->cmd_ctrl(mtd, command, ctrl);
639 /* Address cycle, when necessary */
640 ctrl = NAND_CTRL_ALE | NAND_CTRL_CHANGE;
641 /* Serially input address */
643 /* Adjust columns for 16 bit buswidth */
644 if (chip->options & NAND_BUSWIDTH_16 &&
645 !nand_opcode_8bits(command))
647 chip->cmd_ctrl(mtd, column, ctrl);
648 ctrl &= ~NAND_CTRL_CHANGE;
650 if (page_addr != -1) {
651 chip->cmd_ctrl(mtd, page_addr, ctrl);
652 ctrl &= ~NAND_CTRL_CHANGE;
653 chip->cmd_ctrl(mtd, page_addr >> 8, ctrl);
654 /* One more address cycle for devices > 32MiB */
655 if (chip->chipsize > (32 << 20))
656 chip->cmd_ctrl(mtd, page_addr >> 16, ctrl);
658 chip->cmd_ctrl(mtd, NAND_CMD_NONE, NAND_NCE | NAND_CTRL_CHANGE);
661 * Program and erase have their own busy handlers status and sequential
666 case NAND_CMD_PAGEPROG:
667 case NAND_CMD_ERASE1:
668 case NAND_CMD_ERASE2:
670 case NAND_CMD_STATUS:
671 case NAND_CMD_READID:
677 udelay(chip->chip_delay);
678 chip->cmd_ctrl(mtd, NAND_CMD_STATUS,
679 NAND_CTRL_CLE | NAND_CTRL_CHANGE);
681 NAND_CMD_NONE, NAND_NCE | NAND_CTRL_CHANGE);
682 /* EZ-NAND can take upto 250ms as per ONFi v4.0 */
683 nand_wait_status_ready(mtd, 250);
686 /* This applies to read commands */
689 * If we don't have access to the busy pin, we apply the given
692 if (!chip->dev_ready) {
693 udelay(chip->chip_delay);
698 * Apply this short delay always to ensure that we do wait tWB in
699 * any case on any machine.
703 nand_wait_ready(mtd);
706 static void nand_ccs_delay(struct nand_chip *chip)
709 * The controller already takes care of waiting for tCCS when the RNDIN
710 * or RNDOUT command is sent, return directly.
712 if (!(chip->options & NAND_WAIT_TCCS))
716 * Wait tCCS_min if it is correctly defined, otherwise wait 500ns
717 * (which should be safe for all NANDs).
719 if (chip->data_interface && chip->data_interface->timings.sdr.tCCS_min)
720 ndelay(chip->data_interface->timings.sdr.tCCS_min / 1000);
726 * nand_command_lp - [DEFAULT] Send command to NAND large page device
727 * @mtd: MTD device structure
728 * @command: the command to be sent
729 * @column: the column address for this command, -1 if none
730 * @page_addr: the page address for this command, -1 if none
732 * Send command to NAND device. This is the version for the new large page
733 * devices. We don't have the separate regions as we have in the small page
734 * devices. We must emulate NAND_CMD_READOOB to keep the code compatible.
736 static void nand_command_lp(struct mtd_info *mtd, unsigned int command,
737 int column, int page_addr)
739 register struct nand_chip *chip = mtd_to_nand(mtd);
741 /* Emulate NAND_CMD_READOOB */
742 if (command == NAND_CMD_READOOB) {
743 column += mtd->writesize;
744 command = NAND_CMD_READ0;
747 /* Command latch cycle */
748 chip->cmd_ctrl(mtd, command, NAND_NCE | NAND_CLE | NAND_CTRL_CHANGE);
750 if (column != -1 || page_addr != -1) {
751 int ctrl = NAND_CTRL_CHANGE | NAND_NCE | NAND_ALE;
753 /* Serially input address */
755 /* Adjust columns for 16 bit buswidth */
756 if (chip->options & NAND_BUSWIDTH_16 &&
757 !nand_opcode_8bits(command))
759 chip->cmd_ctrl(mtd, column, ctrl);
760 ctrl &= ~NAND_CTRL_CHANGE;
762 /* Only output a single addr cycle for 8bits opcodes. */
763 if (!nand_opcode_8bits(command))
764 chip->cmd_ctrl(mtd, column >> 8, ctrl);
766 if (page_addr != -1) {
767 chip->cmd_ctrl(mtd, page_addr, ctrl);
768 chip->cmd_ctrl(mtd, page_addr >> 8,
769 NAND_NCE | NAND_ALE);
770 /* One more address cycle for devices > 128MiB */
771 if (chip->chipsize > (128 << 20))
772 chip->cmd_ctrl(mtd, page_addr >> 16,
773 NAND_NCE | NAND_ALE);
776 chip->cmd_ctrl(mtd, NAND_CMD_NONE, NAND_NCE | NAND_CTRL_CHANGE);
779 * Program and erase have their own busy handlers status, sequential
780 * in and status need no delay.
784 case NAND_CMD_CACHEDPROG:
785 case NAND_CMD_PAGEPROG:
786 case NAND_CMD_ERASE1:
787 case NAND_CMD_ERASE2:
789 case NAND_CMD_STATUS:
790 case NAND_CMD_READID:
794 nand_ccs_delay(chip);
800 udelay(chip->chip_delay);
801 chip->cmd_ctrl(mtd, NAND_CMD_STATUS,
802 NAND_NCE | NAND_CLE | NAND_CTRL_CHANGE);
803 chip->cmd_ctrl(mtd, NAND_CMD_NONE,
804 NAND_NCE | NAND_CTRL_CHANGE);
805 /* EZ-NAND can take upto 250ms as per ONFi v4.0 */
806 nand_wait_status_ready(mtd, 250);
809 case NAND_CMD_RNDOUT:
810 /* No ready / busy check necessary */
811 chip->cmd_ctrl(mtd, NAND_CMD_RNDOUTSTART,
812 NAND_NCE | NAND_CLE | NAND_CTRL_CHANGE);
813 chip->cmd_ctrl(mtd, NAND_CMD_NONE,
814 NAND_NCE | NAND_CTRL_CHANGE);
816 nand_ccs_delay(chip);
820 chip->cmd_ctrl(mtd, NAND_CMD_READSTART,
821 NAND_NCE | NAND_CLE | NAND_CTRL_CHANGE);
822 chip->cmd_ctrl(mtd, NAND_CMD_NONE,
823 NAND_NCE | NAND_CTRL_CHANGE);
825 /* This applies to read commands */
828 * If we don't have access to the busy pin, we apply the given
831 if (!chip->dev_ready) {
832 udelay(chip->chip_delay);
838 * Apply this short delay always to ensure that we do wait tWB in
839 * any case on any machine.
843 nand_wait_ready(mtd);
847 * panic_nand_get_device - [GENERIC] Get chip for selected access
848 * @chip: the nand chip descriptor
849 * @mtd: MTD device structure
850 * @new_state: the state which is requested
852 * Used when in panic, no locks are taken.
854 static void panic_nand_get_device(struct nand_chip *chip,
855 struct mtd_info *mtd, int new_state)
857 /* Hardware controller shared among independent devices */
858 chip->controller->active = chip;
859 chip->state = new_state;
863 * nand_get_device - [GENERIC] Get chip for selected access
864 * @mtd: MTD device structure
865 * @new_state: the state which is requested
867 * Get the device and lock it for exclusive access
870 nand_get_device(struct mtd_info *mtd, int new_state)
872 struct nand_chip *chip = mtd_to_nand(mtd);
873 spinlock_t *lock = &chip->controller->lock;
874 wait_queue_head_t *wq = &chip->controller->wq;
875 DECLARE_WAITQUEUE(wait, current);
879 /* Hardware controller shared among independent devices */
880 if (!chip->controller->active)
881 chip->controller->active = chip;
883 if (chip->controller->active == chip && chip->state == FL_READY) {
884 chip->state = new_state;
888 if (new_state == FL_PM_SUSPENDED) {
889 if (chip->controller->active->state == FL_PM_SUSPENDED) {
890 chip->state = FL_PM_SUSPENDED;
895 set_current_state(TASK_UNINTERRUPTIBLE);
896 add_wait_queue(wq, &wait);
899 remove_wait_queue(wq, &wait);
904 * panic_nand_wait - [GENERIC] wait until the command is done
905 * @mtd: MTD device structure
906 * @chip: NAND chip structure
909 * Wait for command done. This is a helper function for nand_wait used when
910 * we are in interrupt context. May happen when in panic and trying to write
911 * an oops through mtdoops.
913 static void panic_nand_wait(struct mtd_info *mtd, struct nand_chip *chip,
917 for (i = 0; i < timeo; i++) {
918 if (chip->dev_ready) {
919 if (chip->dev_ready(mtd))
922 if (chip->read_byte(mtd) & NAND_STATUS_READY)
930 * nand_wait - [DEFAULT] wait until the command is done
931 * @mtd: MTD device structure
932 * @chip: NAND chip structure
934 * Wait for command done. This applies to erase and program only.
936 static int nand_wait(struct mtd_info *mtd, struct nand_chip *chip)
940 unsigned long timeo = 400;
943 * Apply this short delay always to ensure that we do wait tWB in any
944 * case on any machine.
948 chip->cmdfunc(mtd, NAND_CMD_STATUS, -1, -1);
950 if (in_interrupt() || oops_in_progress)
951 panic_nand_wait(mtd, chip, timeo);
953 timeo = jiffies + msecs_to_jiffies(timeo);
955 if (chip->dev_ready) {
956 if (chip->dev_ready(mtd))
959 if (chip->read_byte(mtd) & NAND_STATUS_READY)
963 } while (time_before(jiffies, timeo));
966 status = (int)chip->read_byte(mtd);
967 /* This can happen if in case of timeout or buggy dev_ready */
968 WARN_ON(!(status & NAND_STATUS_READY));
973 * nand_reset_data_interface - Reset data interface and timings
974 * @chip: The NAND chip
976 * Reset the Data interface and timings to ONFI mode 0.
978 * Returns 0 for success or negative error code otherwise.
980 static int nand_reset_data_interface(struct nand_chip *chip)
982 struct mtd_info *mtd = nand_to_mtd(chip);
983 const struct nand_data_interface *conf;
986 if (!chip->setup_data_interface)
990 * The ONFI specification says:
992 * To transition from NV-DDR or NV-DDR2 to the SDR data
993 * interface, the host shall use the Reset (FFh) command
994 * using SDR timing mode 0. A device in any timing mode is
995 * required to recognize Reset (FFh) command issued in SDR
999 * Configure the data interface in SDR mode and set the
1000 * timings to timing mode 0.
1003 conf = nand_get_default_data_interface();
1004 ret = chip->setup_data_interface(mtd, conf, false);
1006 pr_err("Failed to configure data interface to SDR timing mode 0\n");
1012 * nand_setup_data_interface - Setup the best data interface and timings
1013 * @chip: The NAND chip
1015 * Find and configure the best data interface and NAND timings supported by
1016 * the chip and the driver.
1017 * First tries to retrieve supported timing modes from ONFI information,
1018 * and if the NAND chip does not support ONFI, relies on the
1019 * ->onfi_timing_mode_default specified in the nand_ids table.
1021 * Returns 0 for success or negative error code otherwise.
1023 static int nand_setup_data_interface(struct nand_chip *chip)
1025 struct mtd_info *mtd = nand_to_mtd(chip);
1028 if (!chip->setup_data_interface || !chip->data_interface)
1032 * Ensure the timing mode has been changed on the chip side
1033 * before changing timings on the controller side.
1035 if (chip->onfi_version) {
1036 u8 tmode_param[ONFI_SUBFEATURE_PARAM_LEN] = {
1037 chip->onfi_timing_mode_default,
1040 ret = chip->onfi_set_features(mtd, chip,
1041 ONFI_FEATURE_ADDR_TIMING_MODE,
1047 ret = chip->setup_data_interface(mtd, chip->data_interface, false);
1053 * nand_init_data_interface - find the best data interface and timings
1054 * @chip: The NAND chip
1056 * Find the best data interface and NAND timings supported by the chip
1058 * First tries to retrieve supported timing modes from ONFI information,
1059 * and if the NAND chip does not support ONFI, relies on the
1060 * ->onfi_timing_mode_default specified in the nand_ids table. After this
1061 * function nand_chip->data_interface is initialized with the best timing mode
1064 * Returns 0 for success or negative error code otherwise.
1066 static int nand_init_data_interface(struct nand_chip *chip)
1068 struct mtd_info *mtd = nand_to_mtd(chip);
1069 int modes, mode, ret;
1071 if (!chip->setup_data_interface)
1075 * First try to identify the best timings from ONFI parameters and
1076 * if the NAND does not support ONFI, fallback to the default ONFI
1079 modes = onfi_get_async_timing_mode(chip);
1080 if (modes == ONFI_TIMING_MODE_UNKNOWN) {
1081 if (!chip->onfi_timing_mode_default)
1084 modes = GENMASK(chip->onfi_timing_mode_default, 0);
1087 chip->data_interface = kzalloc(sizeof(*chip->data_interface),
1089 if (!chip->data_interface)
1092 for (mode = fls(modes) - 1; mode >= 0; mode--) {
1093 ret = onfi_init_data_interface(chip, chip->data_interface,
1094 NAND_SDR_IFACE, mode);
1098 ret = chip->setup_data_interface(mtd, chip->data_interface,
1101 chip->onfi_timing_mode_default = mode;
1109 static void nand_release_data_interface(struct nand_chip *chip)
1111 kfree(chip->data_interface);
1115 * nand_reset - Reset and initialize a NAND device
1116 * @chip: The NAND chip
1117 * @chipnr: Internal die id
1119 * Returns 0 for success or negative error code otherwise
1121 int nand_reset(struct nand_chip *chip, int chipnr)
1123 struct mtd_info *mtd = nand_to_mtd(chip);
1126 ret = nand_reset_data_interface(chip);
1131 * The CS line has to be released before we can apply the new NAND
1132 * interface settings, hence this weird ->select_chip() dance.
1134 chip->select_chip(mtd, chipnr);
1135 chip->cmdfunc(mtd, NAND_CMD_RESET, -1, -1);
1136 chip->select_chip(mtd, -1);
1138 chip->select_chip(mtd, chipnr);
1139 ret = nand_setup_data_interface(chip);
1140 chip->select_chip(mtd, -1);
1148 * __nand_unlock - [REPLACEABLE] unlocks specified locked blocks
1150 * @ofs: offset to start unlock from
1151 * @len: length to unlock
1152 * @invert: when = 0, unlock the range of blocks within the lower and
1153 * upper boundary address
1154 * when = 1, unlock the range of blocks outside the boundaries
1155 * of the lower and upper boundary address
1157 * Returs unlock status.
1159 static int __nand_unlock(struct mtd_info *mtd, loff_t ofs,
1160 uint64_t len, int invert)
1164 struct nand_chip *chip = mtd_to_nand(mtd);
1166 /* Submit address of first page to unlock */
1167 page = ofs >> chip->page_shift;
1168 chip->cmdfunc(mtd, NAND_CMD_UNLOCK1, -1, page & chip->pagemask);
1170 /* Submit address of last page to unlock */
1171 page = (ofs + len) >> chip->page_shift;
1172 chip->cmdfunc(mtd, NAND_CMD_UNLOCK2, -1,
1173 (page | invert) & chip->pagemask);
1175 /* Call wait ready function */
1176 status = chip->waitfunc(mtd, chip);
1177 /* See if device thinks it succeeded */
1178 if (status & NAND_STATUS_FAIL) {
1179 pr_debug("%s: error status = 0x%08x\n",
1188 * nand_unlock - [REPLACEABLE] unlocks specified locked blocks
1190 * @ofs: offset to start unlock from
1191 * @len: length to unlock
1193 * Returns unlock status.
1195 int nand_unlock(struct mtd_info *mtd, loff_t ofs, uint64_t len)
1199 struct nand_chip *chip = mtd_to_nand(mtd);
1201 pr_debug("%s: start = 0x%012llx, len = %llu\n",
1202 __func__, (unsigned long long)ofs, len);
1204 if (check_offs_len(mtd, ofs, len))
1207 /* Align to last block address if size addresses end of the device */
1208 if (ofs + len == mtd->size)
1209 len -= mtd->erasesize;
1211 nand_get_device(mtd, FL_UNLOCKING);
1213 /* Shift to get chip number */
1214 chipnr = ofs >> chip->chip_shift;
1218 * If we want to check the WP through READ STATUS and check the bit 7
1219 * we must reset the chip
1220 * some operation can also clear the bit 7 of status register
1221 * eg. erase/program a locked block
1223 nand_reset(chip, chipnr);
1225 chip->select_chip(mtd, chipnr);
1227 /* Check, if it is write protected */
1228 if (nand_check_wp(mtd)) {
1229 pr_debug("%s: device is write protected!\n",
1235 ret = __nand_unlock(mtd, ofs, len, 0);
1238 chip->select_chip(mtd, -1);
1239 nand_release_device(mtd);
1243 EXPORT_SYMBOL(nand_unlock);
1246 * nand_lock - [REPLACEABLE] locks all blocks present in the device
1248 * @ofs: offset to start unlock from
1249 * @len: length to unlock
1251 * This feature is not supported in many NAND parts. 'Micron' NAND parts do
1252 * have this feature, but it allows only to lock all blocks, not for specified
1253 * range for block. Implementing 'lock' feature by making use of 'unlock', for
1256 * Returns lock status.
1258 int nand_lock(struct mtd_info *mtd, loff_t ofs, uint64_t len)
1261 int chipnr, status, page;
1262 struct nand_chip *chip = mtd_to_nand(mtd);
1264 pr_debug("%s: start = 0x%012llx, len = %llu\n",
1265 __func__, (unsigned long long)ofs, len);
1267 if (check_offs_len(mtd, ofs, len))
1270 nand_get_device(mtd, FL_LOCKING);
1272 /* Shift to get chip number */
1273 chipnr = ofs >> chip->chip_shift;
1277 * If we want to check the WP through READ STATUS and check the bit 7
1278 * we must reset the chip
1279 * some operation can also clear the bit 7 of status register
1280 * eg. erase/program a locked block
1282 nand_reset(chip, chipnr);
1284 chip->select_chip(mtd, chipnr);
1286 /* Check, if it is write protected */
1287 if (nand_check_wp(mtd)) {
1288 pr_debug("%s: device is write protected!\n",
1290 status = MTD_ERASE_FAILED;
1295 /* Submit address of first page to lock */
1296 page = ofs >> chip->page_shift;
1297 chip->cmdfunc(mtd, NAND_CMD_LOCK, -1, page & chip->pagemask);
1299 /* Call wait ready function */
1300 status = chip->waitfunc(mtd, chip);
1301 /* See if device thinks it succeeded */
1302 if (status & NAND_STATUS_FAIL) {
1303 pr_debug("%s: error status = 0x%08x\n",
1309 ret = __nand_unlock(mtd, ofs, len, 0x1);
1312 chip->select_chip(mtd, -1);
1313 nand_release_device(mtd);
1317 EXPORT_SYMBOL(nand_lock);
1320 * nand_check_erased_buf - check if a buffer contains (almost) only 0xff data
1321 * @buf: buffer to test
1322 * @len: buffer length
1323 * @bitflips_threshold: maximum number of bitflips
1325 * Check if a buffer contains only 0xff, which means the underlying region
1326 * has been erased and is ready to be programmed.
1327 * The bitflips_threshold specify the maximum number of bitflips before
1328 * considering the region is not erased.
1329 * Note: The logic of this function has been extracted from the memweight
1330 * implementation, except that nand_check_erased_buf function exit before
1331 * testing the whole buffer if the number of bitflips exceed the
1332 * bitflips_threshold value.
1334 * Returns a positive number of bitflips less than or equal to
1335 * bitflips_threshold, or -ERROR_CODE for bitflips in excess of the
1338 static int nand_check_erased_buf(void *buf, int len, int bitflips_threshold)
1340 const unsigned char *bitmap = buf;
1344 for (; len && ((uintptr_t)bitmap) % sizeof(long);
1346 weight = hweight8(*bitmap);
1347 bitflips += BITS_PER_BYTE - weight;
1348 if (unlikely(bitflips > bitflips_threshold))
1352 for (; len >= sizeof(long);
1353 len -= sizeof(long), bitmap += sizeof(long)) {
1354 weight = hweight_long(*((unsigned long *)bitmap));
1355 bitflips += BITS_PER_LONG - weight;
1356 if (unlikely(bitflips > bitflips_threshold))
1360 for (; len > 0; len--, bitmap++) {
1361 weight = hweight8(*bitmap);
1362 bitflips += BITS_PER_BYTE - weight;
1363 if (unlikely(bitflips > bitflips_threshold))
1371 * nand_check_erased_ecc_chunk - check if an ECC chunk contains (almost) only
1373 * @data: data buffer to test
1374 * @datalen: data length
1376 * @ecclen: ECC length
1377 * @extraoob: extra OOB buffer
1378 * @extraooblen: extra OOB length
1379 * @bitflips_threshold: maximum number of bitflips
1381 * Check if a data buffer and its associated ECC and OOB data contains only
1382 * 0xff pattern, which means the underlying region has been erased and is
1383 * ready to be programmed.
1384 * The bitflips_threshold specify the maximum number of bitflips before
1385 * considering the region as not erased.
1388 * 1/ ECC algorithms are working on pre-defined block sizes which are usually
1389 * different from the NAND page size. When fixing bitflips, ECC engines will
1390 * report the number of errors per chunk, and the NAND core infrastructure
1391 * expect you to return the maximum number of bitflips for the whole page.
1392 * This is why you should always use this function on a single chunk and
1393 * not on the whole page. After checking each chunk you should update your
1394 * max_bitflips value accordingly.
1395 * 2/ When checking for bitflips in erased pages you should not only check
1396 * the payload data but also their associated ECC data, because a user might
1397 * have programmed almost all bits to 1 but a few. In this case, we
1398 * shouldn't consider the chunk as erased, and checking ECC bytes prevent
1400 * 3/ The extraoob argument is optional, and should be used if some of your OOB
1401 * data are protected by the ECC engine.
1402 * It could also be used if you support subpages and want to attach some
1403 * extra OOB data to an ECC chunk.
1405 * Returns a positive number of bitflips less than or equal to
1406 * bitflips_threshold, or -ERROR_CODE for bitflips in excess of the
1407 * threshold. In case of success, the passed buffers are filled with 0xff.
1409 int nand_check_erased_ecc_chunk(void *data, int datalen,
1410 void *ecc, int ecclen,
1411 void *extraoob, int extraooblen,
1412 int bitflips_threshold)
1414 int data_bitflips = 0, ecc_bitflips = 0, extraoob_bitflips = 0;
1416 data_bitflips = nand_check_erased_buf(data, datalen,
1417 bitflips_threshold);
1418 if (data_bitflips < 0)
1419 return data_bitflips;
1421 bitflips_threshold -= data_bitflips;
1423 ecc_bitflips = nand_check_erased_buf(ecc, ecclen, bitflips_threshold);
1424 if (ecc_bitflips < 0)
1425 return ecc_bitflips;
1427 bitflips_threshold -= ecc_bitflips;
1429 extraoob_bitflips = nand_check_erased_buf(extraoob, extraooblen,
1430 bitflips_threshold);
1431 if (extraoob_bitflips < 0)
1432 return extraoob_bitflips;
1435 memset(data, 0xff, datalen);
1438 memset(ecc, 0xff, ecclen);
1440 if (extraoob_bitflips)
1441 memset(extraoob, 0xff, extraooblen);
1443 return data_bitflips + ecc_bitflips + extraoob_bitflips;
1445 EXPORT_SYMBOL(nand_check_erased_ecc_chunk);
1448 * nand_read_page_raw - [INTERN] read raw page data without ecc
1449 * @mtd: mtd info structure
1450 * @chip: nand chip info structure
1451 * @buf: buffer to store read data
1452 * @oob_required: caller requires OOB data read to chip->oob_poi
1453 * @page: page number to read
1455 * Not for syndrome calculating ECC controllers, which use a special oob layout.
1457 static int nand_read_page_raw(struct mtd_info *mtd, struct nand_chip *chip,
1458 uint8_t *buf, int oob_required, int page)
1460 chip->read_buf(mtd, buf, mtd->writesize);
1462 chip->read_buf(mtd, chip->oob_poi, mtd->oobsize);
1467 * nand_read_page_raw_syndrome - [INTERN] read raw page data without ecc
1468 * @mtd: mtd info structure
1469 * @chip: nand chip info structure
1470 * @buf: buffer to store read data
1471 * @oob_required: caller requires OOB data read to chip->oob_poi
1472 * @page: page number to read
1474 * We need a special oob layout and handling even when OOB isn't used.
1476 static int nand_read_page_raw_syndrome(struct mtd_info *mtd,
1477 struct nand_chip *chip, uint8_t *buf,
1478 int oob_required, int page)
1480 int eccsize = chip->ecc.size;
1481 int eccbytes = chip->ecc.bytes;
1482 uint8_t *oob = chip->oob_poi;
1485 for (steps = chip->ecc.steps; steps > 0; steps--) {
1486 chip->read_buf(mtd, buf, eccsize);
1489 if (chip->ecc.prepad) {
1490 chip->read_buf(mtd, oob, chip->ecc.prepad);
1491 oob += chip->ecc.prepad;
1494 chip->read_buf(mtd, oob, eccbytes);
1497 if (chip->ecc.postpad) {
1498 chip->read_buf(mtd, oob, chip->ecc.postpad);
1499 oob += chip->ecc.postpad;
1503 size = mtd->oobsize - (oob - chip->oob_poi);
1505 chip->read_buf(mtd, oob, size);
1511 * nand_read_page_swecc - [REPLACEABLE] software ECC based page read function
1512 * @mtd: mtd info structure
1513 * @chip: nand chip info structure
1514 * @buf: buffer to store read data
1515 * @oob_required: caller requires OOB data read to chip->oob_poi
1516 * @page: page number to read
1518 static int nand_read_page_swecc(struct mtd_info *mtd, struct nand_chip *chip,
1519 uint8_t *buf, int oob_required, int page)
1521 int i, eccsize = chip->ecc.size, ret;
1522 int eccbytes = chip->ecc.bytes;
1523 int eccsteps = chip->ecc.steps;
1525 uint8_t *ecc_calc = chip->buffers->ecccalc;
1526 uint8_t *ecc_code = chip->buffers->ecccode;
1527 unsigned int max_bitflips = 0;
1529 chip->ecc.read_page_raw(mtd, chip, buf, 1, page);
1531 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize)
1532 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
1534 ret = mtd_ooblayout_get_eccbytes(mtd, ecc_code, chip->oob_poi, 0,
1539 eccsteps = chip->ecc.steps;
1542 for (i = 0 ; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
1545 stat = chip->ecc.correct(mtd, p, &ecc_code[i], &ecc_calc[i]);
1547 mtd->ecc_stats.failed++;
1549 mtd->ecc_stats.corrected += stat;
1550 max_bitflips = max_t(unsigned int, max_bitflips, stat);
1553 return max_bitflips;
1557 * nand_read_subpage - [REPLACEABLE] ECC based sub-page read function
1558 * @mtd: mtd info structure
1559 * @chip: nand chip info structure
1560 * @data_offs: offset of requested data within the page
1561 * @readlen: data length
1562 * @bufpoi: buffer to store read data
1563 * @page: page number to read
1565 static int nand_read_subpage(struct mtd_info *mtd, struct nand_chip *chip,
1566 uint32_t data_offs, uint32_t readlen, uint8_t *bufpoi,
1569 int start_step, end_step, num_steps, ret;
1571 int data_col_addr, i, gaps = 0;
1572 int datafrag_len, eccfrag_len, aligned_len, aligned_pos;
1573 int busw = (chip->options & NAND_BUSWIDTH_16) ? 2 : 1;
1574 int index, section = 0;
1575 unsigned int max_bitflips = 0;
1576 struct mtd_oob_region oobregion = { };
1578 /* Column address within the page aligned to ECC size (256bytes) */
1579 start_step = data_offs / chip->ecc.size;
1580 end_step = (data_offs + readlen - 1) / chip->ecc.size;
1581 num_steps = end_step - start_step + 1;
1582 index = start_step * chip->ecc.bytes;
1584 /* Data size aligned to ECC ecc.size */
1585 datafrag_len = num_steps * chip->ecc.size;
1586 eccfrag_len = num_steps * chip->ecc.bytes;
1588 data_col_addr = start_step * chip->ecc.size;
1589 /* If we read not a page aligned data */
1590 if (data_col_addr != 0)
1591 chip->cmdfunc(mtd, NAND_CMD_RNDOUT, data_col_addr, -1);
1593 p = bufpoi + data_col_addr;
1594 chip->read_buf(mtd, p, datafrag_len);
1597 for (i = 0; i < eccfrag_len ; i += chip->ecc.bytes, p += chip->ecc.size)
1598 chip->ecc.calculate(mtd, p, &chip->buffers->ecccalc[i]);
1601 * The performance is faster if we position offsets according to
1602 * ecc.pos. Let's make sure that there are no gaps in ECC positions.
1604 ret = mtd_ooblayout_find_eccregion(mtd, index, §ion, &oobregion);
1608 if (oobregion.length < eccfrag_len)
1612 chip->cmdfunc(mtd, NAND_CMD_RNDOUT, mtd->writesize, -1);
1613 chip->read_buf(mtd, chip->oob_poi, mtd->oobsize);
1616 * Send the command to read the particular ECC bytes take care
1617 * about buswidth alignment in read_buf.
1619 aligned_pos = oobregion.offset & ~(busw - 1);
1620 aligned_len = eccfrag_len;
1621 if (oobregion.offset & (busw - 1))
1623 if ((oobregion.offset + (num_steps * chip->ecc.bytes)) &
1627 chip->cmdfunc(mtd, NAND_CMD_RNDOUT,
1628 mtd->writesize + aligned_pos, -1);
1629 chip->read_buf(mtd, &chip->oob_poi[aligned_pos], aligned_len);
1632 ret = mtd_ooblayout_get_eccbytes(mtd, chip->buffers->ecccode,
1633 chip->oob_poi, index, eccfrag_len);
1637 p = bufpoi + data_col_addr;
1638 for (i = 0; i < eccfrag_len ; i += chip->ecc.bytes, p += chip->ecc.size) {
1641 stat = chip->ecc.correct(mtd, p,
1642 &chip->buffers->ecccode[i], &chip->buffers->ecccalc[i]);
1643 if (stat == -EBADMSG &&
1644 (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
1645 /* check for empty pages with bitflips */
1646 stat = nand_check_erased_ecc_chunk(p, chip->ecc.size,
1647 &chip->buffers->ecccode[i],
1650 chip->ecc.strength);
1654 mtd->ecc_stats.failed++;
1656 mtd->ecc_stats.corrected += stat;
1657 max_bitflips = max_t(unsigned int, max_bitflips, stat);
1660 return max_bitflips;
1664 * nand_read_page_hwecc - [REPLACEABLE] hardware ECC based page read function
1665 * @mtd: mtd info structure
1666 * @chip: nand chip info structure
1667 * @buf: buffer to store read data
1668 * @oob_required: caller requires OOB data read to chip->oob_poi
1669 * @page: page number to read
1671 * Not for syndrome calculating ECC controllers which need a special oob layout.
1673 static int nand_read_page_hwecc(struct mtd_info *mtd, struct nand_chip *chip,
1674 uint8_t *buf, int oob_required, int page)
1676 int i, eccsize = chip->ecc.size, ret;
1677 int eccbytes = chip->ecc.bytes;
1678 int eccsteps = chip->ecc.steps;
1680 uint8_t *ecc_calc = chip->buffers->ecccalc;
1681 uint8_t *ecc_code = chip->buffers->ecccode;
1682 unsigned int max_bitflips = 0;
1684 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
1685 chip->ecc.hwctl(mtd, NAND_ECC_READ);
1686 chip->read_buf(mtd, p, eccsize);
1687 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
1689 chip->read_buf(mtd, chip->oob_poi, mtd->oobsize);
1691 ret = mtd_ooblayout_get_eccbytes(mtd, ecc_code, chip->oob_poi, 0,
1696 eccsteps = chip->ecc.steps;
1699 for (i = 0 ; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
1702 stat = chip->ecc.correct(mtd, p, &ecc_code[i], &ecc_calc[i]);
1703 if (stat == -EBADMSG &&
1704 (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
1705 /* check for empty pages with bitflips */
1706 stat = nand_check_erased_ecc_chunk(p, eccsize,
1707 &ecc_code[i], eccbytes,
1709 chip->ecc.strength);
1713 mtd->ecc_stats.failed++;
1715 mtd->ecc_stats.corrected += stat;
1716 max_bitflips = max_t(unsigned int, max_bitflips, stat);
1719 return max_bitflips;
1723 * nand_read_page_hwecc_oob_first - [REPLACEABLE] hw ecc, read oob first
1724 * @mtd: mtd info structure
1725 * @chip: nand chip info structure
1726 * @buf: buffer to store read data
1727 * @oob_required: caller requires OOB data read to chip->oob_poi
1728 * @page: page number to read
1730 * Hardware ECC for large page chips, require OOB to be read first. For this
1731 * ECC mode, the write_page method is re-used from ECC_HW. These methods
1732 * read/write ECC from the OOB area, unlike the ECC_HW_SYNDROME support with
1733 * multiple ECC steps, follows the "infix ECC" scheme and reads/writes ECC from
1734 * the data area, by overwriting the NAND manufacturer bad block markings.
1736 static int nand_read_page_hwecc_oob_first(struct mtd_info *mtd,
1737 struct nand_chip *chip, uint8_t *buf, int oob_required, int page)
1739 int i, eccsize = chip->ecc.size, ret;
1740 int eccbytes = chip->ecc.bytes;
1741 int eccsteps = chip->ecc.steps;
1743 uint8_t *ecc_code = chip->buffers->ecccode;
1744 uint8_t *ecc_calc = chip->buffers->ecccalc;
1745 unsigned int max_bitflips = 0;
1747 /* Read the OOB area first */
1748 chip->cmdfunc(mtd, NAND_CMD_READOOB, 0, page);
1749 chip->read_buf(mtd, chip->oob_poi, mtd->oobsize);
1750 chip->cmdfunc(mtd, NAND_CMD_READ0, 0, page);
1752 ret = mtd_ooblayout_get_eccbytes(mtd, ecc_code, chip->oob_poi, 0,
1757 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
1760 chip->ecc.hwctl(mtd, NAND_ECC_READ);
1761 chip->read_buf(mtd, p, eccsize);
1762 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
1764 stat = chip->ecc.correct(mtd, p, &ecc_code[i], NULL);
1765 if (stat == -EBADMSG &&
1766 (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
1767 /* check for empty pages with bitflips */
1768 stat = nand_check_erased_ecc_chunk(p, eccsize,
1769 &ecc_code[i], eccbytes,
1771 chip->ecc.strength);
1775 mtd->ecc_stats.failed++;
1777 mtd->ecc_stats.corrected += stat;
1778 max_bitflips = max_t(unsigned int, max_bitflips, stat);
1781 return max_bitflips;
1785 * nand_read_page_syndrome - [REPLACEABLE] hardware ECC syndrome based page read
1786 * @mtd: mtd info structure
1787 * @chip: nand chip info structure
1788 * @buf: buffer to store read data
1789 * @oob_required: caller requires OOB data read to chip->oob_poi
1790 * @page: page number to read
1792 * The hw generator calculates the error syndrome automatically. Therefore we
1793 * need a special oob layout and handling.
1795 static int nand_read_page_syndrome(struct mtd_info *mtd, struct nand_chip *chip,
1796 uint8_t *buf, int oob_required, int page)
1798 int i, eccsize = chip->ecc.size;
1799 int eccbytes = chip->ecc.bytes;
1800 int eccsteps = chip->ecc.steps;
1801 int eccpadbytes = eccbytes + chip->ecc.prepad + chip->ecc.postpad;
1803 uint8_t *oob = chip->oob_poi;
1804 unsigned int max_bitflips = 0;
1806 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
1809 chip->ecc.hwctl(mtd, NAND_ECC_READ);
1810 chip->read_buf(mtd, p, eccsize);
1812 if (chip->ecc.prepad) {
1813 chip->read_buf(mtd, oob, chip->ecc.prepad);
1814 oob += chip->ecc.prepad;
1817 chip->ecc.hwctl(mtd, NAND_ECC_READSYN);
1818 chip->read_buf(mtd, oob, eccbytes);
1819 stat = chip->ecc.correct(mtd, p, oob, NULL);
1823 if (chip->ecc.postpad) {
1824 chip->read_buf(mtd, oob, chip->ecc.postpad);
1825 oob += chip->ecc.postpad;
1828 if (stat == -EBADMSG &&
1829 (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
1830 /* check for empty pages with bitflips */
1831 stat = nand_check_erased_ecc_chunk(p, chip->ecc.size,
1835 chip->ecc.strength);
1839 mtd->ecc_stats.failed++;
1841 mtd->ecc_stats.corrected += stat;
1842 max_bitflips = max_t(unsigned int, max_bitflips, stat);
1846 /* Calculate remaining oob bytes */
1847 i = mtd->oobsize - (oob - chip->oob_poi);
1849 chip->read_buf(mtd, oob, i);
1851 return max_bitflips;
1855 * nand_transfer_oob - [INTERN] Transfer oob to client buffer
1856 * @mtd: mtd info structure
1857 * @oob: oob destination address
1858 * @ops: oob ops structure
1859 * @len: size of oob to transfer
1861 static uint8_t *nand_transfer_oob(struct mtd_info *mtd, uint8_t *oob,
1862 struct mtd_oob_ops *ops, size_t len)
1864 struct nand_chip *chip = mtd_to_nand(mtd);
1867 switch (ops->mode) {
1869 case MTD_OPS_PLACE_OOB:
1871 memcpy(oob, chip->oob_poi + ops->ooboffs, len);
1874 case MTD_OPS_AUTO_OOB:
1875 ret = mtd_ooblayout_get_databytes(mtd, oob, chip->oob_poi,
1887 * nand_setup_read_retry - [INTERN] Set the READ RETRY mode
1888 * @mtd: MTD device structure
1889 * @retry_mode: the retry mode to use
1891 * Some vendors supply a special command to shift the Vt threshold, to be used
1892 * when there are too many bitflips in a page (i.e., ECC error). After setting
1893 * a new threshold, the host should retry reading the page.
1895 static int nand_setup_read_retry(struct mtd_info *mtd, int retry_mode)
1897 struct nand_chip *chip = mtd_to_nand(mtd);
1899 pr_debug("setting READ RETRY mode %d\n", retry_mode);
1901 if (retry_mode >= chip->read_retries)
1904 if (!chip->setup_read_retry)
1907 return chip->setup_read_retry(mtd, retry_mode);
1911 * nand_do_read_ops - [INTERN] Read data with ECC
1912 * @mtd: MTD device structure
1913 * @from: offset to read from
1914 * @ops: oob ops structure
1916 * Internal function. Called with chip held.
1918 static int nand_do_read_ops(struct mtd_info *mtd, loff_t from,
1919 struct mtd_oob_ops *ops)
1921 int chipnr, page, realpage, col, bytes, aligned, oob_required;
1922 struct nand_chip *chip = mtd_to_nand(mtd);
1924 uint32_t readlen = ops->len;
1925 uint32_t oobreadlen = ops->ooblen;
1926 uint32_t max_oobsize = mtd_oobavail(mtd, ops);
1928 uint8_t *bufpoi, *oob, *buf;
1930 unsigned int max_bitflips = 0;
1932 bool ecc_fail = false;
1934 chipnr = (int)(from >> chip->chip_shift);
1935 chip->select_chip(mtd, chipnr);
1937 realpage = (int)(from >> chip->page_shift);
1938 page = realpage & chip->pagemask;
1940 col = (int)(from & (mtd->writesize - 1));
1944 oob_required = oob ? 1 : 0;
1947 unsigned int ecc_failures = mtd->ecc_stats.failed;
1949 bytes = min(mtd->writesize - col, readlen);
1950 aligned = (bytes == mtd->writesize);
1954 else if (chip->options & NAND_USE_BOUNCE_BUFFER)
1955 use_bufpoi = !virt_addr_valid(buf);
1959 /* Is the current page in the buffer? */
1960 if (realpage != chip->pagebuf || oob) {
1961 bufpoi = use_bufpoi ? chip->buffers->databuf : buf;
1963 if (use_bufpoi && aligned)
1964 pr_debug("%s: using read bounce buffer for buf@%p\n",
1968 if (nand_standard_page_accessors(&chip->ecc))
1969 chip->cmdfunc(mtd, NAND_CMD_READ0, 0x00, page);
1972 * Now read the page into the buffer. Absent an error,
1973 * the read methods return max bitflips per ecc step.
1975 if (unlikely(ops->mode == MTD_OPS_RAW))
1976 ret = chip->ecc.read_page_raw(mtd, chip, bufpoi,
1979 else if (!aligned && NAND_HAS_SUBPAGE_READ(chip) &&
1981 ret = chip->ecc.read_subpage(mtd, chip,
1985 ret = chip->ecc.read_page(mtd, chip, bufpoi,
1986 oob_required, page);
1989 /* Invalidate page cache */
1994 max_bitflips = max_t(unsigned int, max_bitflips, ret);
1996 /* Transfer not aligned data */
1998 if (!NAND_HAS_SUBPAGE_READ(chip) && !oob &&
1999 !(mtd->ecc_stats.failed - ecc_failures) &&
2000 (ops->mode != MTD_OPS_RAW)) {
2001 chip->pagebuf = realpage;
2002 chip->pagebuf_bitflips = ret;
2004 /* Invalidate page cache */
2007 memcpy(buf, chip->buffers->databuf + col, bytes);
2010 if (unlikely(oob)) {
2011 int toread = min(oobreadlen, max_oobsize);
2014 oob = nand_transfer_oob(mtd,
2016 oobreadlen -= toread;
2020 if (chip->options & NAND_NEED_READRDY) {
2021 /* Apply delay or wait for ready/busy pin */
2022 if (!chip->dev_ready)
2023 udelay(chip->chip_delay);
2025 nand_wait_ready(mtd);
2028 if (mtd->ecc_stats.failed - ecc_failures) {
2029 if (retry_mode + 1 < chip->read_retries) {
2031 ret = nand_setup_read_retry(mtd,
2036 /* Reset failures; retry */
2037 mtd->ecc_stats.failed = ecc_failures;
2040 /* No more retry modes; real failure */
2047 memcpy(buf, chip->buffers->databuf + col, bytes);
2049 max_bitflips = max_t(unsigned int, max_bitflips,
2050 chip->pagebuf_bitflips);
2055 /* Reset to retry mode 0 */
2057 ret = nand_setup_read_retry(mtd, 0);
2066 /* For subsequent reads align to page boundary */
2068 /* Increment page address */
2071 page = realpage & chip->pagemask;
2072 /* Check, if we cross a chip boundary */
2075 chip->select_chip(mtd, -1);
2076 chip->select_chip(mtd, chipnr);
2079 chip->select_chip(mtd, -1);
2081 ops->retlen = ops->len - (size_t) readlen;
2083 ops->oobretlen = ops->ooblen - oobreadlen;
2091 return max_bitflips;
2095 * nand_read - [MTD Interface] MTD compatibility function for nand_do_read_ecc
2096 * @mtd: MTD device structure
2097 * @from: offset to read from
2098 * @len: number of bytes to read
2099 * @retlen: pointer to variable to store the number of read bytes
2100 * @buf: the databuffer to put data
2102 * Get hold of the chip and call nand_do_read.
2104 static int nand_read(struct mtd_info *mtd, loff_t from, size_t len,
2105 size_t *retlen, uint8_t *buf)
2107 struct mtd_oob_ops ops;
2110 nand_get_device(mtd, FL_READING);
2111 memset(&ops, 0, sizeof(ops));
2114 ops.mode = MTD_OPS_PLACE_OOB;
2115 ret = nand_do_read_ops(mtd, from, &ops);
2116 *retlen = ops.retlen;
2117 nand_release_device(mtd);
2122 * nand_read_oob_std - [REPLACEABLE] the most common OOB data read function
2123 * @mtd: mtd info structure
2124 * @chip: nand chip info structure
2125 * @page: page number to read
2127 int nand_read_oob_std(struct mtd_info *mtd, struct nand_chip *chip, int page)
2129 chip->cmdfunc(mtd, NAND_CMD_READOOB, 0, page);
2130 chip->read_buf(mtd, chip->oob_poi, mtd->oobsize);
2133 EXPORT_SYMBOL(nand_read_oob_std);
2136 * nand_read_oob_syndrome - [REPLACEABLE] OOB data read function for HW ECC
2138 * @mtd: mtd info structure
2139 * @chip: nand chip info structure
2140 * @page: page number to read
2142 int nand_read_oob_syndrome(struct mtd_info *mtd, struct nand_chip *chip,
2145 int length = mtd->oobsize;
2146 int chunk = chip->ecc.bytes + chip->ecc.prepad + chip->ecc.postpad;
2147 int eccsize = chip->ecc.size;
2148 uint8_t *bufpoi = chip->oob_poi;
2149 int i, toread, sndrnd = 0, pos;
2151 chip->cmdfunc(mtd, NAND_CMD_READ0, chip->ecc.size, page);
2152 for (i = 0; i < chip->ecc.steps; i++) {
2154 pos = eccsize + i * (eccsize + chunk);
2155 if (mtd->writesize > 512)
2156 chip->cmdfunc(mtd, NAND_CMD_RNDOUT, pos, -1);
2158 chip->cmdfunc(mtd, NAND_CMD_READ0, pos, page);
2161 toread = min_t(int, length, chunk);
2162 chip->read_buf(mtd, bufpoi, toread);
2167 chip->read_buf(mtd, bufpoi, length);
2171 EXPORT_SYMBOL(nand_read_oob_syndrome);
2174 * nand_write_oob_std - [REPLACEABLE] the most common OOB data write function
2175 * @mtd: mtd info structure
2176 * @chip: nand chip info structure
2177 * @page: page number to write
2179 int nand_write_oob_std(struct mtd_info *mtd, struct nand_chip *chip, int page)
2182 const uint8_t *buf = chip->oob_poi;
2183 int length = mtd->oobsize;
2185 chip->cmdfunc(mtd, NAND_CMD_SEQIN, mtd->writesize, page);
2186 chip->write_buf(mtd, buf, length);
2187 /* Send command to program the OOB data */
2188 chip->cmdfunc(mtd, NAND_CMD_PAGEPROG, -1, -1);
2190 status = chip->waitfunc(mtd, chip);
2192 return status & NAND_STATUS_FAIL ? -EIO : 0;
2194 EXPORT_SYMBOL(nand_write_oob_std);
2197 * nand_write_oob_syndrome - [REPLACEABLE] OOB data write function for HW ECC
2198 * with syndrome - only for large page flash
2199 * @mtd: mtd info structure
2200 * @chip: nand chip info structure
2201 * @page: page number to write
2203 int nand_write_oob_syndrome(struct mtd_info *mtd, struct nand_chip *chip,
2206 int chunk = chip->ecc.bytes + chip->ecc.prepad + chip->ecc.postpad;
2207 int eccsize = chip->ecc.size, length = mtd->oobsize;
2208 int i, len, pos, status = 0, sndcmd = 0, steps = chip->ecc.steps;
2209 const uint8_t *bufpoi = chip->oob_poi;
2212 * data-ecc-data-ecc ... ecc-oob
2214 * data-pad-ecc-pad-data-pad .... ecc-pad-oob
2216 if (!chip->ecc.prepad && !chip->ecc.postpad) {
2217 pos = steps * (eccsize + chunk);
2222 chip->cmdfunc(mtd, NAND_CMD_SEQIN, pos, page);
2223 for (i = 0; i < steps; i++) {
2225 if (mtd->writesize <= 512) {
2226 uint32_t fill = 0xFFFFFFFF;
2230 int num = min_t(int, len, 4);
2231 chip->write_buf(mtd, (uint8_t *)&fill,
2236 pos = eccsize + i * (eccsize + chunk);
2237 chip->cmdfunc(mtd, NAND_CMD_RNDIN, pos, -1);
2241 len = min_t(int, length, chunk);
2242 chip->write_buf(mtd, bufpoi, len);
2247 chip->write_buf(mtd, bufpoi, length);
2249 chip->cmdfunc(mtd, NAND_CMD_PAGEPROG, -1, -1);
2250 status = chip->waitfunc(mtd, chip);
2252 return status & NAND_STATUS_FAIL ? -EIO : 0;
2254 EXPORT_SYMBOL(nand_write_oob_syndrome);
2257 * nand_do_read_oob - [INTERN] NAND read out-of-band
2258 * @mtd: MTD device structure
2259 * @from: offset to read from
2260 * @ops: oob operations description structure
2262 * NAND read out-of-band data from the spare area.
2264 static int nand_do_read_oob(struct mtd_info *mtd, loff_t from,
2265 struct mtd_oob_ops *ops)
2267 int page, realpage, chipnr;
2268 struct nand_chip *chip = mtd_to_nand(mtd);
2269 struct mtd_ecc_stats stats;
2270 int readlen = ops->ooblen;
2272 uint8_t *buf = ops->oobbuf;
2275 pr_debug("%s: from = 0x%08Lx, len = %i\n",
2276 __func__, (unsigned long long)from, readlen);
2278 stats = mtd->ecc_stats;
2280 len = mtd_oobavail(mtd, ops);
2282 if (unlikely(ops->ooboffs >= len)) {
2283 pr_debug("%s: attempt to start read outside oob\n",
2288 /* Do not allow reads past end of device */
2289 if (unlikely(from >= mtd->size ||
2290 ops->ooboffs + readlen > ((mtd->size >> chip->page_shift) -
2291 (from >> chip->page_shift)) * len)) {
2292 pr_debug("%s: attempt to read beyond end of device\n",
2297 chipnr = (int)(from >> chip->chip_shift);
2298 chip->select_chip(mtd, chipnr);
2300 /* Shift to get page */
2301 realpage = (int)(from >> chip->page_shift);
2302 page = realpage & chip->pagemask;
2305 if (ops->mode == MTD_OPS_RAW)
2306 ret = chip->ecc.read_oob_raw(mtd, chip, page);
2308 ret = chip->ecc.read_oob(mtd, chip, page);
2313 len = min(len, readlen);
2314 buf = nand_transfer_oob(mtd, buf, ops, len);
2316 if (chip->options & NAND_NEED_READRDY) {
2317 /* Apply delay or wait for ready/busy pin */
2318 if (!chip->dev_ready)
2319 udelay(chip->chip_delay);
2321 nand_wait_ready(mtd);
2328 /* Increment page address */
2331 page = realpage & chip->pagemask;
2332 /* Check, if we cross a chip boundary */
2335 chip->select_chip(mtd, -1);
2336 chip->select_chip(mtd, chipnr);
2339 chip->select_chip(mtd, -1);
2341 ops->oobretlen = ops->ooblen - readlen;
2346 if (mtd->ecc_stats.failed - stats.failed)
2349 return mtd->ecc_stats.corrected - stats.corrected ? -EUCLEAN : 0;
2353 * nand_read_oob - [MTD Interface] NAND read data and/or out-of-band
2354 * @mtd: MTD device structure
2355 * @from: offset to read from
2356 * @ops: oob operation description structure
2358 * NAND read data and/or out-of-band data.
2360 static int nand_read_oob(struct mtd_info *mtd, loff_t from,
2361 struct mtd_oob_ops *ops)
2367 /* Do not allow reads past end of device */
2368 if (ops->datbuf && (from + ops->len) > mtd->size) {
2369 pr_debug("%s: attempt to read beyond end of device\n",
2374 if (ops->mode != MTD_OPS_PLACE_OOB &&
2375 ops->mode != MTD_OPS_AUTO_OOB &&
2376 ops->mode != MTD_OPS_RAW)
2379 nand_get_device(mtd, FL_READING);
2382 ret = nand_do_read_oob(mtd, from, ops);
2384 ret = nand_do_read_ops(mtd, from, ops);
2386 nand_release_device(mtd);
2392 * nand_write_page_raw - [INTERN] raw page write function
2393 * @mtd: mtd info structure
2394 * @chip: nand chip info structure
2396 * @oob_required: must write chip->oob_poi to OOB
2397 * @page: page number to write
2399 * Not for syndrome calculating ECC controllers, which use a special oob layout.
2401 static int nand_write_page_raw(struct mtd_info *mtd, struct nand_chip *chip,
2402 const uint8_t *buf, int oob_required, int page)
2404 chip->write_buf(mtd, buf, mtd->writesize);
2406 chip->write_buf(mtd, chip->oob_poi, mtd->oobsize);
2412 * nand_write_page_raw_syndrome - [INTERN] raw page write function
2413 * @mtd: mtd info structure
2414 * @chip: nand chip info structure
2416 * @oob_required: must write chip->oob_poi to OOB
2417 * @page: page number to write
2419 * We need a special oob layout and handling even when ECC isn't checked.
2421 static int nand_write_page_raw_syndrome(struct mtd_info *mtd,
2422 struct nand_chip *chip,
2423 const uint8_t *buf, int oob_required,
2426 int eccsize = chip->ecc.size;
2427 int eccbytes = chip->ecc.bytes;
2428 uint8_t *oob = chip->oob_poi;
2431 for (steps = chip->ecc.steps; steps > 0; steps--) {
2432 chip->write_buf(mtd, buf, eccsize);
2435 if (chip->ecc.prepad) {
2436 chip->write_buf(mtd, oob, chip->ecc.prepad);
2437 oob += chip->ecc.prepad;
2440 chip->write_buf(mtd, oob, eccbytes);
2443 if (chip->ecc.postpad) {
2444 chip->write_buf(mtd, oob, chip->ecc.postpad);
2445 oob += chip->ecc.postpad;
2449 size = mtd->oobsize - (oob - chip->oob_poi);
2451 chip->write_buf(mtd, oob, size);
2456 * nand_write_page_swecc - [REPLACEABLE] software ECC based page write function
2457 * @mtd: mtd info structure
2458 * @chip: nand chip info structure
2460 * @oob_required: must write chip->oob_poi to OOB
2461 * @page: page number to write
2463 static int nand_write_page_swecc(struct mtd_info *mtd, struct nand_chip *chip,
2464 const uint8_t *buf, int oob_required,
2467 int i, eccsize = chip->ecc.size, ret;
2468 int eccbytes = chip->ecc.bytes;
2469 int eccsteps = chip->ecc.steps;
2470 uint8_t *ecc_calc = chip->buffers->ecccalc;
2471 const uint8_t *p = buf;
2473 /* Software ECC calculation */
2474 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize)
2475 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
2477 ret = mtd_ooblayout_set_eccbytes(mtd, ecc_calc, chip->oob_poi, 0,
2482 return chip->ecc.write_page_raw(mtd, chip, buf, 1, page);
2486 * nand_write_page_hwecc - [REPLACEABLE] hardware ECC based page write function
2487 * @mtd: mtd info structure
2488 * @chip: nand chip info structure
2490 * @oob_required: must write chip->oob_poi to OOB
2491 * @page: page number to write
2493 static int nand_write_page_hwecc(struct mtd_info *mtd, struct nand_chip *chip,
2494 const uint8_t *buf, int oob_required,
2497 int i, eccsize = chip->ecc.size, ret;
2498 int eccbytes = chip->ecc.bytes;
2499 int eccsteps = chip->ecc.steps;
2500 uint8_t *ecc_calc = chip->buffers->ecccalc;
2501 const uint8_t *p = buf;
2503 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
2504 chip->ecc.hwctl(mtd, NAND_ECC_WRITE);
2505 chip->write_buf(mtd, p, eccsize);
2506 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
2509 ret = mtd_ooblayout_set_eccbytes(mtd, ecc_calc, chip->oob_poi, 0,
2514 chip->write_buf(mtd, chip->oob_poi, mtd->oobsize);
2521 * nand_write_subpage_hwecc - [REPLACEABLE] hardware ECC based subpage write
2522 * @mtd: mtd info structure
2523 * @chip: nand chip info structure
2524 * @offset: column address of subpage within the page
2525 * @data_len: data length
2527 * @oob_required: must write chip->oob_poi to OOB
2528 * @page: page number to write
2530 static int nand_write_subpage_hwecc(struct mtd_info *mtd,
2531 struct nand_chip *chip, uint32_t offset,
2532 uint32_t data_len, const uint8_t *buf,
2533 int oob_required, int page)
2535 uint8_t *oob_buf = chip->oob_poi;
2536 uint8_t *ecc_calc = chip->buffers->ecccalc;
2537 int ecc_size = chip->ecc.size;
2538 int ecc_bytes = chip->ecc.bytes;
2539 int ecc_steps = chip->ecc.steps;
2540 uint32_t start_step = offset / ecc_size;
2541 uint32_t end_step = (offset + data_len - 1) / ecc_size;
2542 int oob_bytes = mtd->oobsize / ecc_steps;
2545 for (step = 0; step < ecc_steps; step++) {
2546 /* configure controller for WRITE access */
2547 chip->ecc.hwctl(mtd, NAND_ECC_WRITE);
2549 /* write data (untouched subpages already masked by 0xFF) */
2550 chip->write_buf(mtd, buf, ecc_size);
2552 /* mask ECC of un-touched subpages by padding 0xFF */
2553 if ((step < start_step) || (step > end_step))
2554 memset(ecc_calc, 0xff, ecc_bytes);
2556 chip->ecc.calculate(mtd, buf, ecc_calc);
2558 /* mask OOB of un-touched subpages by padding 0xFF */
2559 /* if oob_required, preserve OOB metadata of written subpage */
2560 if (!oob_required || (step < start_step) || (step > end_step))
2561 memset(oob_buf, 0xff, oob_bytes);
2564 ecc_calc += ecc_bytes;
2565 oob_buf += oob_bytes;
2568 /* copy calculated ECC for whole page to chip->buffer->oob */
2569 /* this include masked-value(0xFF) for unwritten subpages */
2570 ecc_calc = chip->buffers->ecccalc;
2571 ret = mtd_ooblayout_set_eccbytes(mtd, ecc_calc, chip->oob_poi, 0,
2576 /* write OOB buffer to NAND device */
2577 chip->write_buf(mtd, chip->oob_poi, mtd->oobsize);
2584 * nand_write_page_syndrome - [REPLACEABLE] hardware ECC syndrome based page write
2585 * @mtd: mtd info structure
2586 * @chip: nand chip info structure
2588 * @oob_required: must write chip->oob_poi to OOB
2589 * @page: page number to write
2591 * The hw generator calculates the error syndrome automatically. Therefore we
2592 * need a special oob layout and handling.
2594 static int nand_write_page_syndrome(struct mtd_info *mtd,
2595 struct nand_chip *chip,
2596 const uint8_t *buf, int oob_required,
2599 int i, eccsize = chip->ecc.size;
2600 int eccbytes = chip->ecc.bytes;
2601 int eccsteps = chip->ecc.steps;
2602 const uint8_t *p = buf;
2603 uint8_t *oob = chip->oob_poi;
2605 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
2607 chip->ecc.hwctl(mtd, NAND_ECC_WRITE);
2608 chip->write_buf(mtd, p, eccsize);
2610 if (chip->ecc.prepad) {
2611 chip->write_buf(mtd, oob, chip->ecc.prepad);
2612 oob += chip->ecc.prepad;
2615 chip->ecc.calculate(mtd, p, oob);
2616 chip->write_buf(mtd, oob, eccbytes);
2619 if (chip->ecc.postpad) {
2620 chip->write_buf(mtd, oob, chip->ecc.postpad);
2621 oob += chip->ecc.postpad;
2625 /* Calculate remaining oob bytes */
2626 i = mtd->oobsize - (oob - chip->oob_poi);
2628 chip->write_buf(mtd, oob, i);
2634 * nand_write_page - [REPLACEABLE] write one page
2635 * @mtd: MTD device structure
2636 * @chip: NAND chip descriptor
2637 * @offset: address offset within the page
2638 * @data_len: length of actual data to be written
2639 * @buf: the data to write
2640 * @oob_required: must write chip->oob_poi to OOB
2641 * @page: page number to write
2642 * @cached: cached programming
2643 * @raw: use _raw version of write_page
2645 static int nand_write_page(struct mtd_info *mtd, struct nand_chip *chip,
2646 uint32_t offset, int data_len, const uint8_t *buf,
2647 int oob_required, int page, int cached, int raw)
2649 int status, subpage;
2651 if (!(chip->options & NAND_NO_SUBPAGE_WRITE) &&
2652 chip->ecc.write_subpage)
2653 subpage = offset || (data_len < mtd->writesize);
2657 if (nand_standard_page_accessors(&chip->ecc))
2658 chip->cmdfunc(mtd, NAND_CMD_SEQIN, 0x00, page);
2661 status = chip->ecc.write_page_raw(mtd, chip, buf,
2662 oob_required, page);
2664 status = chip->ecc.write_subpage(mtd, chip, offset, data_len,
2665 buf, oob_required, page);
2667 status = chip->ecc.write_page(mtd, chip, buf, oob_required,
2674 * Cached progamming disabled for now. Not sure if it's worth the
2675 * trouble. The speed gain is not very impressive. (2.3->2.6Mib/s).
2679 if (!cached || !NAND_HAS_CACHEPROG(chip)) {
2681 if (nand_standard_page_accessors(&chip->ecc))
2682 chip->cmdfunc(mtd, NAND_CMD_PAGEPROG, -1, -1);
2683 status = chip->waitfunc(mtd, chip);
2685 * See if operation failed and additional status checks are
2688 if ((status & NAND_STATUS_FAIL) && (chip->errstat))
2689 status = chip->errstat(mtd, chip, FL_WRITING, status,
2692 if (status & NAND_STATUS_FAIL)
2695 chip->cmdfunc(mtd, NAND_CMD_CACHEDPROG, -1, -1);
2696 status = chip->waitfunc(mtd, chip);
2703 * nand_fill_oob - [INTERN] Transfer client buffer to oob
2704 * @mtd: MTD device structure
2705 * @oob: oob data buffer
2706 * @len: oob data write length
2707 * @ops: oob ops structure
2709 static uint8_t *nand_fill_oob(struct mtd_info *mtd, uint8_t *oob, size_t len,
2710 struct mtd_oob_ops *ops)
2712 struct nand_chip *chip = mtd_to_nand(mtd);
2716 * Initialise to all 0xFF, to avoid the possibility of left over OOB
2717 * data from a previous OOB read.
2719 memset(chip->oob_poi, 0xff, mtd->oobsize);
2721 switch (ops->mode) {
2723 case MTD_OPS_PLACE_OOB:
2725 memcpy(chip->oob_poi + ops->ooboffs, oob, len);
2728 case MTD_OPS_AUTO_OOB:
2729 ret = mtd_ooblayout_set_databytes(mtd, oob, chip->oob_poi,
2740 #define NOTALIGNED(x) ((x & (chip->subpagesize - 1)) != 0)
2743 * nand_do_write_ops - [INTERN] NAND write with ECC
2744 * @mtd: MTD device structure
2745 * @to: offset to write to
2746 * @ops: oob operations description structure
2748 * NAND write with ECC.
2750 static int nand_do_write_ops(struct mtd_info *mtd, loff_t to,
2751 struct mtd_oob_ops *ops)
2753 int chipnr, realpage, page, blockmask, column;
2754 struct nand_chip *chip = mtd_to_nand(mtd);
2755 uint32_t writelen = ops->len;
2757 uint32_t oobwritelen = ops->ooblen;
2758 uint32_t oobmaxlen = mtd_oobavail(mtd, ops);
2760 uint8_t *oob = ops->oobbuf;
2761 uint8_t *buf = ops->datbuf;
2763 int oob_required = oob ? 1 : 0;
2769 /* Reject writes, which are not page aligned */
2770 if (NOTALIGNED(to) || NOTALIGNED(ops->len)) {
2771 pr_notice("%s: attempt to write non page aligned data\n",
2776 column = to & (mtd->writesize - 1);
2778 chipnr = (int)(to >> chip->chip_shift);
2779 chip->select_chip(mtd, chipnr);
2781 /* Check, if it is write protected */
2782 if (nand_check_wp(mtd)) {
2787 realpage = (int)(to >> chip->page_shift);
2788 page = realpage & chip->pagemask;
2789 blockmask = (1 << (chip->phys_erase_shift - chip->page_shift)) - 1;
2791 /* Invalidate the page cache, when we write to the cached page */
2792 if (to <= ((loff_t)chip->pagebuf << chip->page_shift) &&
2793 ((loff_t)chip->pagebuf << chip->page_shift) < (to + ops->len))
2796 /* Don't allow multipage oob writes with offset */
2797 if (oob && ops->ooboffs && (ops->ooboffs + ops->ooblen > oobmaxlen)) {
2803 int bytes = mtd->writesize;
2804 int cached = writelen > bytes && page != blockmask;
2805 uint8_t *wbuf = buf;
2807 int part_pagewr = (column || writelen < mtd->writesize);
2811 else if (chip->options & NAND_USE_BOUNCE_BUFFER)
2812 use_bufpoi = !virt_addr_valid(buf);
2816 /* Partial page write?, or need to use bounce buffer */
2818 pr_debug("%s: using write bounce buffer for buf@%p\n",
2822 bytes = min_t(int, bytes - column, writelen);
2824 memset(chip->buffers->databuf, 0xff, mtd->writesize);
2825 memcpy(&chip->buffers->databuf[column], buf, bytes);
2826 wbuf = chip->buffers->databuf;
2829 if (unlikely(oob)) {
2830 size_t len = min(oobwritelen, oobmaxlen);
2831 oob = nand_fill_oob(mtd, oob, len, ops);
2834 /* We still need to erase leftover OOB data */
2835 memset(chip->oob_poi, 0xff, mtd->oobsize);
2837 ret = chip->write_page(mtd, chip, column, bytes, wbuf,
2838 oob_required, page, cached,
2839 (ops->mode == MTD_OPS_RAW));
2851 page = realpage & chip->pagemask;
2852 /* Check, if we cross a chip boundary */
2855 chip->select_chip(mtd, -1);
2856 chip->select_chip(mtd, chipnr);
2860 ops->retlen = ops->len - writelen;
2862 ops->oobretlen = ops->ooblen;
2865 chip->select_chip(mtd, -1);
2870 * panic_nand_write - [MTD Interface] NAND write with ECC
2871 * @mtd: MTD device structure
2872 * @to: offset to write to
2873 * @len: number of bytes to write
2874 * @retlen: pointer to variable to store the number of written bytes
2875 * @buf: the data to write
2877 * NAND write with ECC. Used when performing writes in interrupt context, this
2878 * may for example be called by mtdoops when writing an oops while in panic.
2880 static int panic_nand_write(struct mtd_info *mtd, loff_t to, size_t len,
2881 size_t *retlen, const uint8_t *buf)
2883 struct nand_chip *chip = mtd_to_nand(mtd);
2884 struct mtd_oob_ops ops;
2887 /* Wait for the device to get ready */
2888 panic_nand_wait(mtd, chip, 400);
2890 /* Grab the device */
2891 panic_nand_get_device(chip, mtd, FL_WRITING);
2893 memset(&ops, 0, sizeof(ops));
2895 ops.datbuf = (uint8_t *)buf;
2896 ops.mode = MTD_OPS_PLACE_OOB;
2898 ret = nand_do_write_ops(mtd, to, &ops);
2900 *retlen = ops.retlen;
2905 * nand_write - [MTD Interface] NAND write with ECC
2906 * @mtd: MTD device structure
2907 * @to: offset to write to
2908 * @len: number of bytes to write
2909 * @retlen: pointer to variable to store the number of written bytes
2910 * @buf: the data to write
2912 * NAND write with ECC.
2914 static int nand_write(struct mtd_info *mtd, loff_t to, size_t len,
2915 size_t *retlen, const uint8_t *buf)
2917 struct mtd_oob_ops ops;
2920 nand_get_device(mtd, FL_WRITING);
2921 memset(&ops, 0, sizeof(ops));
2923 ops.datbuf = (uint8_t *)buf;
2924 ops.mode = MTD_OPS_PLACE_OOB;
2925 ret = nand_do_write_ops(mtd, to, &ops);
2926 *retlen = ops.retlen;
2927 nand_release_device(mtd);
2932 * nand_do_write_oob - [MTD Interface] NAND write out-of-band
2933 * @mtd: MTD device structure
2934 * @to: offset to write to
2935 * @ops: oob operation description structure
2937 * NAND write out-of-band.
2939 static int nand_do_write_oob(struct mtd_info *mtd, loff_t to,
2940 struct mtd_oob_ops *ops)
2942 int chipnr, page, status, len;
2943 struct nand_chip *chip = mtd_to_nand(mtd);
2945 pr_debug("%s: to = 0x%08x, len = %i\n",
2946 __func__, (unsigned int)to, (int)ops->ooblen);
2948 len = mtd_oobavail(mtd, ops);
2950 /* Do not allow write past end of page */
2951 if ((ops->ooboffs + ops->ooblen) > len) {
2952 pr_debug("%s: attempt to write past end of page\n",
2957 if (unlikely(ops->ooboffs >= len)) {
2958 pr_debug("%s: attempt to start write outside oob\n",
2963 /* Do not allow write past end of device */
2964 if (unlikely(to >= mtd->size ||
2965 ops->ooboffs + ops->ooblen >
2966 ((mtd->size >> chip->page_shift) -
2967 (to >> chip->page_shift)) * len)) {
2968 pr_debug("%s: attempt to write beyond end of device\n",
2973 chipnr = (int)(to >> chip->chip_shift);
2976 * Reset the chip. Some chips (like the Toshiba TC5832DC found in one
2977 * of my DiskOnChip 2000 test units) will clear the whole data page too
2978 * if we don't do this. I have no clue why, but I seem to have 'fixed'
2979 * it in the doc2000 driver in August 1999. dwmw2.
2981 nand_reset(chip, chipnr);
2983 chip->select_chip(mtd, chipnr);
2985 /* Shift to get page */
2986 page = (int)(to >> chip->page_shift);
2988 /* Check, if it is write protected */
2989 if (nand_check_wp(mtd)) {
2990 chip->select_chip(mtd, -1);
2994 /* Invalidate the page cache, if we write to the cached page */
2995 if (page == chip->pagebuf)
2998 nand_fill_oob(mtd, ops->oobbuf, ops->ooblen, ops);
3000 if (ops->mode == MTD_OPS_RAW)
3001 status = chip->ecc.write_oob_raw(mtd, chip, page & chip->pagemask);
3003 status = chip->ecc.write_oob(mtd, chip, page & chip->pagemask);
3005 chip->select_chip(mtd, -1);
3010 ops->oobretlen = ops->ooblen;
3016 * nand_write_oob - [MTD Interface] NAND write data and/or out-of-band
3017 * @mtd: MTD device structure
3018 * @to: offset to write to
3019 * @ops: oob operation description structure
3021 static int nand_write_oob(struct mtd_info *mtd, loff_t to,
3022 struct mtd_oob_ops *ops)
3024 int ret = -ENOTSUPP;
3028 /* Do not allow writes past end of device */
3029 if (ops->datbuf && (to + ops->len) > mtd->size) {
3030 pr_debug("%s: attempt to write beyond end of device\n",
3035 nand_get_device(mtd, FL_WRITING);
3037 switch (ops->mode) {
3038 case MTD_OPS_PLACE_OOB:
3039 case MTD_OPS_AUTO_OOB:
3048 ret = nand_do_write_oob(mtd, to, ops);
3050 ret = nand_do_write_ops(mtd, to, ops);
3053 nand_release_device(mtd);
3058 * single_erase - [GENERIC] NAND standard block erase command function
3059 * @mtd: MTD device structure
3060 * @page: the page address of the block which will be erased
3062 * Standard erase command for NAND chips. Returns NAND status.
3064 static int single_erase(struct mtd_info *mtd, int page)
3066 struct nand_chip *chip = mtd_to_nand(mtd);
3067 /* Send commands to erase a block */
3068 chip->cmdfunc(mtd, NAND_CMD_ERASE1, -1, page);
3069 chip->cmdfunc(mtd, NAND_CMD_ERASE2, -1, -1);
3071 return chip->waitfunc(mtd, chip);
3075 * nand_erase - [MTD Interface] erase block(s)
3076 * @mtd: MTD device structure
3077 * @instr: erase instruction
3079 * Erase one ore more blocks.
3081 static int nand_erase(struct mtd_info *mtd, struct erase_info *instr)
3083 return nand_erase_nand(mtd, instr, 0);
3087 * nand_erase_nand - [INTERN] erase block(s)
3088 * @mtd: MTD device structure
3089 * @instr: erase instruction
3090 * @allowbbt: allow erasing the bbt area
3092 * Erase one ore more blocks.
3094 int nand_erase_nand(struct mtd_info *mtd, struct erase_info *instr,
3097 int page, status, pages_per_block, ret, chipnr;
3098 struct nand_chip *chip = mtd_to_nand(mtd);
3101 pr_debug("%s: start = 0x%012llx, len = %llu\n",
3102 __func__, (unsigned long long)instr->addr,
3103 (unsigned long long)instr->len);
3105 if (check_offs_len(mtd, instr->addr, instr->len))
3108 /* Grab the lock and see if the device is available */
3109 nand_get_device(mtd, FL_ERASING);
3111 /* Shift to get first page */
3112 page = (int)(instr->addr >> chip->page_shift);
3113 chipnr = (int)(instr->addr >> chip->chip_shift);
3115 /* Calculate pages in each block */
3116 pages_per_block = 1 << (chip->phys_erase_shift - chip->page_shift);
3118 /* Select the NAND device */
3119 chip->select_chip(mtd, chipnr);
3121 /* Check, if it is write protected */
3122 if (nand_check_wp(mtd)) {
3123 pr_debug("%s: device is write protected!\n",
3125 instr->state = MTD_ERASE_FAILED;
3129 /* Loop through the pages */
3132 instr->state = MTD_ERASING;
3135 /* Check if we have a bad block, we do not erase bad blocks! */
3136 if (nand_block_checkbad(mtd, ((loff_t) page) <<
3137 chip->page_shift, allowbbt)) {
3138 pr_warn("%s: attempt to erase a bad block at page 0x%08x\n",
3140 instr->state = MTD_ERASE_FAILED;
3145 * Invalidate the page cache, if we erase the block which
3146 * contains the current cached page.
3148 if (page <= chip->pagebuf && chip->pagebuf <
3149 (page + pages_per_block))
3152 status = chip->erase(mtd, page & chip->pagemask);
3155 * See if operation failed and additional status checks are
3158 if ((status & NAND_STATUS_FAIL) && (chip->errstat))
3159 status = chip->errstat(mtd, chip, FL_ERASING,
3162 /* See if block erase succeeded */
3163 if (status & NAND_STATUS_FAIL) {
3164 pr_debug("%s: failed erase, page 0x%08x\n",
3166 instr->state = MTD_ERASE_FAILED;
3168 ((loff_t)page << chip->page_shift);
3172 /* Increment page address and decrement length */
3173 len -= (1ULL << chip->phys_erase_shift);
3174 page += pages_per_block;
3176 /* Check, if we cross a chip boundary */
3177 if (len && !(page & chip->pagemask)) {
3179 chip->select_chip(mtd, -1);
3180 chip->select_chip(mtd, chipnr);
3183 instr->state = MTD_ERASE_DONE;
3187 ret = instr->state == MTD_ERASE_DONE ? 0 : -EIO;
3189 /* Deselect and wake up anyone waiting on the device */
3190 chip->select_chip(mtd, -1);
3191 nand_release_device(mtd);
3193 /* Do call back function */
3195 mtd_erase_callback(instr);
3197 /* Return more or less happy */
3202 * nand_sync - [MTD Interface] sync
3203 * @mtd: MTD device structure
3205 * Sync is actually a wait for chip ready function.
3207 static void nand_sync(struct mtd_info *mtd)
3209 pr_debug("%s: called\n", __func__);
3211 /* Grab the lock and see if the device is available */
3212 nand_get_device(mtd, FL_SYNCING);
3213 /* Release it and go back */
3214 nand_release_device(mtd);
3218 * nand_block_isbad - [MTD Interface] Check if block at offset is bad
3219 * @mtd: MTD device structure
3220 * @offs: offset relative to mtd start
3222 static int nand_block_isbad(struct mtd_info *mtd, loff_t offs)
3224 struct nand_chip *chip = mtd_to_nand(mtd);
3225 int chipnr = (int)(offs >> chip->chip_shift);
3228 /* Select the NAND device */
3229 nand_get_device(mtd, FL_READING);
3230 chip->select_chip(mtd, chipnr);
3232 ret = nand_block_checkbad(mtd, offs, 0);
3234 chip->select_chip(mtd, -1);
3235 nand_release_device(mtd);
3241 * nand_block_markbad - [MTD Interface] Mark block at the given offset as bad
3242 * @mtd: MTD device structure
3243 * @ofs: offset relative to mtd start
3245 static int nand_block_markbad(struct mtd_info *mtd, loff_t ofs)
3249 ret = nand_block_isbad(mtd, ofs);
3251 /* If it was bad already, return success and do nothing */
3257 return nand_block_markbad_lowlevel(mtd, ofs);
3261 * nand_max_bad_blocks - [MTD Interface] Max number of bad blocks for an mtd
3262 * @mtd: MTD device structure
3263 * @ofs: offset relative to mtd start
3264 * @len: length of mtd
3266 static int nand_max_bad_blocks(struct mtd_info *mtd, loff_t ofs, size_t len)
3268 struct nand_chip *chip = mtd_to_nand(mtd);
3269 u32 part_start_block;
3275 * max_bb_per_die and blocks_per_die used to determine
3276 * the maximum bad block count.
3278 if (!chip->max_bb_per_die || !chip->blocks_per_die)
3281 /* Get the start and end of the partition in erase blocks. */
3282 part_start_block = mtd_div_by_eb(ofs, mtd);
3283 part_end_block = mtd_div_by_eb(len, mtd) + part_start_block - 1;
3285 /* Get the start and end LUNs of the partition. */
3286 part_start_die = part_start_block / chip->blocks_per_die;
3287 part_end_die = part_end_block / chip->blocks_per_die;
3290 * Look up the bad blocks per unit and multiply by the number of units
3291 * that the partition spans.
3293 return chip->max_bb_per_die * (part_end_die - part_start_die + 1);
3297 * nand_onfi_set_features- [REPLACEABLE] set features for ONFI nand
3298 * @mtd: MTD device structure
3299 * @chip: nand chip info structure
3300 * @addr: feature address.
3301 * @subfeature_param: the subfeature parameters, a four bytes array.
3303 static int nand_onfi_set_features(struct mtd_info *mtd, struct nand_chip *chip,
3304 int addr, uint8_t *subfeature_param)
3309 if (!chip->onfi_version ||
3310 !(le16_to_cpu(chip->onfi_params.opt_cmd)
3311 & ONFI_OPT_CMD_SET_GET_FEATURES))
3314 chip->cmdfunc(mtd, NAND_CMD_SET_FEATURES, addr, -1);
3315 for (i = 0; i < ONFI_SUBFEATURE_PARAM_LEN; ++i)
3316 chip->write_byte(mtd, subfeature_param[i]);
3318 status = chip->waitfunc(mtd, chip);
3319 if (status & NAND_STATUS_FAIL)
3325 * nand_onfi_get_features- [REPLACEABLE] get features for ONFI nand
3326 * @mtd: MTD device structure
3327 * @chip: nand chip info structure
3328 * @addr: feature address.
3329 * @subfeature_param: the subfeature parameters, a four bytes array.
3331 static int nand_onfi_get_features(struct mtd_info *mtd, struct nand_chip *chip,
3332 int addr, uint8_t *subfeature_param)
3336 if (!chip->onfi_version ||
3337 !(le16_to_cpu(chip->onfi_params.opt_cmd)
3338 & ONFI_OPT_CMD_SET_GET_FEATURES))
3341 chip->cmdfunc(mtd, NAND_CMD_GET_FEATURES, addr, -1);
3342 for (i = 0; i < ONFI_SUBFEATURE_PARAM_LEN; ++i)
3343 *subfeature_param++ = chip->read_byte(mtd);
3348 * nand_suspend - [MTD Interface] Suspend the NAND flash
3349 * @mtd: MTD device structure
3351 static int nand_suspend(struct mtd_info *mtd)
3353 return nand_get_device(mtd, FL_PM_SUSPENDED);
3357 * nand_resume - [MTD Interface] Resume the NAND flash
3358 * @mtd: MTD device structure
3360 static void nand_resume(struct mtd_info *mtd)
3362 struct nand_chip *chip = mtd_to_nand(mtd);
3364 if (chip->state == FL_PM_SUSPENDED)
3365 nand_release_device(mtd);
3367 pr_err("%s called for a chip which is not in suspended state\n",
3372 * nand_shutdown - [MTD Interface] Finish the current NAND operation and
3373 * prevent further operations
3374 * @mtd: MTD device structure
3376 static void nand_shutdown(struct mtd_info *mtd)
3378 nand_get_device(mtd, FL_PM_SUSPENDED);
3381 /* Set default functions */
3382 static void nand_set_defaults(struct nand_chip *chip)
3384 unsigned int busw = chip->options & NAND_BUSWIDTH_16;
3386 /* check for proper chip_delay setup, set 20us if not */
3387 if (!chip->chip_delay)
3388 chip->chip_delay = 20;
3390 /* check, if a user supplied command function given */
3391 if (chip->cmdfunc == NULL)
3392 chip->cmdfunc = nand_command;
3394 /* check, if a user supplied wait function given */
3395 if (chip->waitfunc == NULL)
3396 chip->waitfunc = nand_wait;
3398 if (!chip->select_chip)
3399 chip->select_chip = nand_select_chip;
3401 /* set for ONFI nand */
3402 if (!chip->onfi_set_features)
3403 chip->onfi_set_features = nand_onfi_set_features;
3404 if (!chip->onfi_get_features)
3405 chip->onfi_get_features = nand_onfi_get_features;
3407 /* If called twice, pointers that depend on busw may need to be reset */
3408 if (!chip->read_byte || chip->read_byte == nand_read_byte)
3409 chip->read_byte = busw ? nand_read_byte16 : nand_read_byte;
3410 if (!chip->read_word)
3411 chip->read_word = nand_read_word;
3412 if (!chip->block_bad)
3413 chip->block_bad = nand_block_bad;
3414 if (!chip->block_markbad)
3415 chip->block_markbad = nand_default_block_markbad;
3416 if (!chip->write_buf || chip->write_buf == nand_write_buf)
3417 chip->write_buf = busw ? nand_write_buf16 : nand_write_buf;
3418 if (!chip->write_byte || chip->write_byte == nand_write_byte)
3419 chip->write_byte = busw ? nand_write_byte16 : nand_write_byte;
3420 if (!chip->read_buf || chip->read_buf == nand_read_buf)
3421 chip->read_buf = busw ? nand_read_buf16 : nand_read_buf;
3422 if (!chip->scan_bbt)
3423 chip->scan_bbt = nand_default_bbt;
3425 if (!chip->controller) {
3426 chip->controller = &chip->hwcontrol;
3427 nand_hw_control_init(chip->controller);
3432 /* Sanitize ONFI strings so we can safely print them */
3433 static void sanitize_string(uint8_t *s, size_t len)
3437 /* Null terminate */
3440 /* Remove non printable chars */
3441 for (i = 0; i < len - 1; i++) {
3442 if (s[i] < ' ' || s[i] > 127)
3446 /* Remove trailing spaces */
3450 static u16 onfi_crc16(u16 crc, u8 const *p, size_t len)
3455 for (i = 0; i < 8; i++)
3456 crc = (crc << 1) ^ ((crc & 0x8000) ? 0x8005 : 0);
3462 /* Parse the Extended Parameter Page. */
3463 static int nand_flash_detect_ext_param_page(struct nand_chip *chip,
3464 struct nand_onfi_params *p)
3466 struct mtd_info *mtd = nand_to_mtd(chip);
3467 struct onfi_ext_param_page *ep;
3468 struct onfi_ext_section *s;
3469 struct onfi_ext_ecc_info *ecc;
3475 len = le16_to_cpu(p->ext_param_page_length) * 16;
3476 ep = kmalloc(len, GFP_KERNEL);
3480 /* Send our own NAND_CMD_PARAM. */
3481 chip->cmdfunc(mtd, NAND_CMD_PARAM, 0, -1);
3483 /* Use the Change Read Column command to skip the ONFI param pages. */
3484 chip->cmdfunc(mtd, NAND_CMD_RNDOUT,
3485 sizeof(*p) * p->num_of_param_pages , -1);
3487 /* Read out the Extended Parameter Page. */
3488 chip->read_buf(mtd, (uint8_t *)ep, len);
3489 if ((onfi_crc16(ONFI_CRC_BASE, ((uint8_t *)ep) + 2, len - 2)
3490 != le16_to_cpu(ep->crc))) {
3491 pr_debug("fail in the CRC.\n");
3496 * Check the signature.
3497 * Do not strictly follow the ONFI spec, maybe changed in future.
3499 if (strncmp(ep->sig, "EPPS", 4)) {
3500 pr_debug("The signature is invalid.\n");
3504 /* find the ECC section. */
3505 cursor = (uint8_t *)(ep + 1);
3506 for (i = 0; i < ONFI_EXT_SECTION_MAX; i++) {
3507 s = ep->sections + i;
3508 if (s->type == ONFI_SECTION_TYPE_2)
3510 cursor += s->length * 16;
3512 if (i == ONFI_EXT_SECTION_MAX) {
3513 pr_debug("We can not find the ECC section.\n");
3517 /* get the info we want. */
3518 ecc = (struct onfi_ext_ecc_info *)cursor;
3520 if (!ecc->codeword_size) {
3521 pr_debug("Invalid codeword size\n");
3525 chip->ecc_strength_ds = ecc->ecc_bits;
3526 chip->ecc_step_ds = 1 << ecc->codeword_size;
3535 * Check if the NAND chip is ONFI compliant, returns 1 if it is, 0 otherwise.
3537 static int nand_flash_detect_onfi(struct nand_chip *chip)
3539 struct mtd_info *mtd = nand_to_mtd(chip);
3540 struct nand_onfi_params *p = &chip->onfi_params;
3544 /* Try ONFI for unknown chip or LP */
3545 chip->cmdfunc(mtd, NAND_CMD_READID, 0x20, -1);
3546 if (chip->read_byte(mtd) != 'O' || chip->read_byte(mtd) != 'N' ||
3547 chip->read_byte(mtd) != 'F' || chip->read_byte(mtd) != 'I')
3550 chip->cmdfunc(mtd, NAND_CMD_PARAM, 0, -1);
3551 for (i = 0; i < 3; i++) {
3552 for (j = 0; j < sizeof(*p); j++)
3553 ((uint8_t *)p)[j] = chip->read_byte(mtd);
3554 if (onfi_crc16(ONFI_CRC_BASE, (uint8_t *)p, 254) ==
3555 le16_to_cpu(p->crc)) {
3561 pr_err("Could not find valid ONFI parameter page; aborting\n");
3566 val = le16_to_cpu(p->revision);
3568 chip->onfi_version = 23;
3569 else if (val & (1 << 4))
3570 chip->onfi_version = 22;
3571 else if (val & (1 << 3))
3572 chip->onfi_version = 21;
3573 else if (val & (1 << 2))
3574 chip->onfi_version = 20;
3575 else if (val & (1 << 1))
3576 chip->onfi_version = 10;
3578 if (!chip->onfi_version) {
3579 pr_info("unsupported ONFI version: %d\n", val);
3583 sanitize_string(p->manufacturer, sizeof(p->manufacturer));
3584 sanitize_string(p->model, sizeof(p->model));
3586 mtd->name = p->model;
3588 mtd->writesize = le32_to_cpu(p->byte_per_page);
3591 * pages_per_block and blocks_per_lun may not be a power-of-2 size
3592 * (don't ask me who thought of this...). MTD assumes that these
3593 * dimensions will be power-of-2, so just truncate the remaining area.
3595 mtd->erasesize = 1 << (fls(le32_to_cpu(p->pages_per_block)) - 1);
3596 mtd->erasesize *= mtd->writesize;
3598 mtd->oobsize = le16_to_cpu(p->spare_bytes_per_page);
3600 /* See erasesize comment */
3601 chip->chipsize = 1 << (fls(le32_to_cpu(p->blocks_per_lun)) - 1);
3602 chip->chipsize *= (uint64_t)mtd->erasesize * p->lun_count;
3603 chip->bits_per_cell = p->bits_per_cell;
3605 chip->max_bb_per_die = le16_to_cpu(p->bb_per_lun);
3606 chip->blocks_per_die = le32_to_cpu(p->blocks_per_lun);
3608 if (onfi_feature(chip) & ONFI_FEATURE_16_BIT_BUS)
3609 chip->options |= NAND_BUSWIDTH_16;
3611 if (p->ecc_bits != 0xff) {
3612 chip->ecc_strength_ds = p->ecc_bits;
3613 chip->ecc_step_ds = 512;
3614 } else if (chip->onfi_version >= 21 &&
3615 (onfi_feature(chip) & ONFI_FEATURE_EXT_PARAM_PAGE)) {
3618 * The nand_flash_detect_ext_param_page() uses the
3619 * Change Read Column command which maybe not supported
3620 * by the chip->cmdfunc. So try to update the chip->cmdfunc
3621 * now. We do not replace user supplied command function.
3623 if (mtd->writesize > 512 && chip->cmdfunc == nand_command)
3624 chip->cmdfunc = nand_command_lp;
3626 /* The Extended Parameter Page is supported since ONFI 2.1. */
3627 if (nand_flash_detect_ext_param_page(chip, p))
3628 pr_warn("Failed to detect ONFI extended param page\n");
3630 pr_warn("Could not retrieve ONFI ECC requirements\n");
3637 * Check if the NAND chip is JEDEC compliant, returns 1 if it is, 0 otherwise.
3639 static int nand_flash_detect_jedec(struct nand_chip *chip)
3641 struct mtd_info *mtd = nand_to_mtd(chip);
3642 struct nand_jedec_params *p = &chip->jedec_params;
3643 struct jedec_ecc_info *ecc;
3647 /* Try JEDEC for unknown chip or LP */
3648 chip->cmdfunc(mtd, NAND_CMD_READID, 0x40, -1);
3649 if (chip->read_byte(mtd) != 'J' || chip->read_byte(mtd) != 'E' ||
3650 chip->read_byte(mtd) != 'D' || chip->read_byte(mtd) != 'E' ||
3651 chip->read_byte(mtd) != 'C')
3654 chip->cmdfunc(mtd, NAND_CMD_PARAM, 0x40, -1);
3655 for (i = 0; i < 3; i++) {
3656 for (j = 0; j < sizeof(*p); j++)
3657 ((uint8_t *)p)[j] = chip->read_byte(mtd);
3659 if (onfi_crc16(ONFI_CRC_BASE, (uint8_t *)p, 510) ==
3660 le16_to_cpu(p->crc))
3665 pr_err("Could not find valid JEDEC parameter page; aborting\n");
3670 val = le16_to_cpu(p->revision);
3672 chip->jedec_version = 10;
3673 else if (val & (1 << 1))
3674 chip->jedec_version = 1; /* vendor specific version */
3676 if (!chip->jedec_version) {
3677 pr_info("unsupported JEDEC version: %d\n", val);
3681 sanitize_string(p->manufacturer, sizeof(p->manufacturer));
3682 sanitize_string(p->model, sizeof(p->model));
3684 mtd->name = p->model;
3686 mtd->writesize = le32_to_cpu(p->byte_per_page);
3688 /* Please reference to the comment for nand_flash_detect_onfi. */
3689 mtd->erasesize = 1 << (fls(le32_to_cpu(p->pages_per_block)) - 1);
3690 mtd->erasesize *= mtd->writesize;
3692 mtd->oobsize = le16_to_cpu(p->spare_bytes_per_page);
3694 /* Please reference to the comment for nand_flash_detect_onfi. */
3695 chip->chipsize = 1 << (fls(le32_to_cpu(p->blocks_per_lun)) - 1);
3696 chip->chipsize *= (uint64_t)mtd->erasesize * p->lun_count;
3697 chip->bits_per_cell = p->bits_per_cell;
3699 if (jedec_feature(chip) & JEDEC_FEATURE_16_BIT_BUS)
3700 chip->options |= NAND_BUSWIDTH_16;
3703 ecc = &p->ecc_info[0];
3705 if (ecc->codeword_size >= 9) {
3706 chip->ecc_strength_ds = ecc->ecc_bits;
3707 chip->ecc_step_ds = 1 << ecc->codeword_size;
3709 pr_warn("Invalid codeword size\n");
3716 * nand_id_has_period - Check if an ID string has a given wraparound period
3717 * @id_data: the ID string
3718 * @arrlen: the length of the @id_data array
3719 * @period: the period of repitition
3721 * Check if an ID string is repeated within a given sequence of bytes at
3722 * specific repetition interval period (e.g., {0x20,0x01,0x7F,0x20} has a
3723 * period of 3). This is a helper function for nand_id_len(). Returns non-zero
3724 * if the repetition has a period of @period; otherwise, returns zero.
3726 static int nand_id_has_period(u8 *id_data, int arrlen, int period)
3729 for (i = 0; i < period; i++)
3730 for (j = i + period; j < arrlen; j += period)
3731 if (id_data[i] != id_data[j])
3737 * nand_id_len - Get the length of an ID string returned by CMD_READID
3738 * @id_data: the ID string
3739 * @arrlen: the length of the @id_data array
3741 * Returns the length of the ID string, according to known wraparound/trailing
3742 * zero patterns. If no pattern exists, returns the length of the array.
3744 static int nand_id_len(u8 *id_data, int arrlen)
3746 int last_nonzero, period;
3748 /* Find last non-zero byte */
3749 for (last_nonzero = arrlen - 1; last_nonzero >= 0; last_nonzero--)
3750 if (id_data[last_nonzero])
3754 if (last_nonzero < 0)
3757 /* Calculate wraparound period */
3758 for (period = 1; period < arrlen; period++)
3759 if (nand_id_has_period(id_data, arrlen, period))
3762 /* There's a repeated pattern */
3763 if (period < arrlen)
3766 /* There are trailing zeros */
3767 if (last_nonzero < arrlen - 1)
3768 return last_nonzero + 1;
3770 /* No pattern detected */
3774 /* Extract the bits of per cell from the 3rd byte of the extended ID */
3775 static int nand_get_bits_per_cell(u8 cellinfo)
3779 bits = cellinfo & NAND_CI_CELLTYPE_MSK;
3780 bits >>= NAND_CI_CELLTYPE_SHIFT;
3785 * Many new NAND share similar device ID codes, which represent the size of the
3786 * chip. The rest of the parameters must be decoded according to generic or
3787 * manufacturer-specific "extended ID" decoding patterns.
3789 void nand_decode_ext_id(struct nand_chip *chip)
3791 struct mtd_info *mtd = nand_to_mtd(chip);
3793 u8 *id_data = chip->id.data;
3794 /* The 3rd id byte holds MLC / multichip data */
3795 chip->bits_per_cell = nand_get_bits_per_cell(id_data[2]);
3796 /* The 4th id byte is the important one */
3800 mtd->writesize = 1024 << (extid & 0x03);
3803 mtd->oobsize = (8 << (extid & 0x01)) * (mtd->writesize >> 9);
3805 /* Calc blocksize. Blocksize is multiples of 64KiB */
3806 mtd->erasesize = (64 * 1024) << (extid & 0x03);
3808 /* Get buswidth information */
3810 chip->options |= NAND_BUSWIDTH_16;
3812 EXPORT_SYMBOL_GPL(nand_decode_ext_id);
3815 * Old devices have chip data hardcoded in the device ID table. nand_decode_id
3816 * decodes a matching ID table entry and assigns the MTD size parameters for
3819 static void nand_decode_id(struct nand_chip *chip, struct nand_flash_dev *type)
3821 struct mtd_info *mtd = nand_to_mtd(chip);
3823 mtd->erasesize = type->erasesize;
3824 mtd->writesize = type->pagesize;
3825 mtd->oobsize = mtd->writesize / 32;
3827 /* All legacy ID NAND are small-page, SLC */
3828 chip->bits_per_cell = 1;
3832 * Set the bad block marker/indicator (BBM/BBI) patterns according to some
3833 * heuristic patterns using various detected parameters (e.g., manufacturer,
3834 * page size, cell-type information).
3836 static void nand_decode_bbm_options(struct nand_chip *chip)
3838 struct mtd_info *mtd = nand_to_mtd(chip);
3840 /* Set the bad block position */
3841 if (mtd->writesize > 512 || (chip->options & NAND_BUSWIDTH_16))
3842 chip->badblockpos = NAND_LARGE_BADBLOCK_POS;
3844 chip->badblockpos = NAND_SMALL_BADBLOCK_POS;
3847 static inline bool is_full_id_nand(struct nand_flash_dev *type)
3849 return type->id_len;
3852 static bool find_full_id_nand(struct nand_chip *chip,
3853 struct nand_flash_dev *type)
3855 struct mtd_info *mtd = nand_to_mtd(chip);
3856 u8 *id_data = chip->id.data;
3858 if (!strncmp(type->id, id_data, type->id_len)) {
3859 mtd->writesize = type->pagesize;
3860 mtd->erasesize = type->erasesize;
3861 mtd->oobsize = type->oobsize;
3863 chip->bits_per_cell = nand_get_bits_per_cell(id_data[2]);
3864 chip->chipsize = (uint64_t)type->chipsize << 20;
3865 chip->options |= type->options;
3866 chip->ecc_strength_ds = NAND_ECC_STRENGTH(type);
3867 chip->ecc_step_ds = NAND_ECC_STEP(type);
3868 chip->onfi_timing_mode_default =
3869 type->onfi_timing_mode_default;
3872 mtd->name = type->name;
3880 * Manufacturer detection. Only used when the NAND is not ONFI or JEDEC
3881 * compliant and does not have a full-id or legacy-id entry in the nand_ids
3884 static void nand_manufacturer_detect(struct nand_chip *chip)
3887 * Try manufacturer detection if available and use
3888 * nand_decode_ext_id() otherwise.
3890 if (chip->manufacturer.desc && chip->manufacturer.desc->ops &&
3891 chip->manufacturer.desc->ops->detect)
3892 chip->manufacturer.desc->ops->detect(chip);
3894 nand_decode_ext_id(chip);
3898 * Manufacturer initialization. This function is called for all NANDs including
3899 * ONFI and JEDEC compliant ones.
3900 * Manufacturer drivers should put all their specific initialization code in
3901 * their ->init() hook.
3903 static int nand_manufacturer_init(struct nand_chip *chip)
3905 if (!chip->manufacturer.desc || !chip->manufacturer.desc->ops ||
3906 !chip->manufacturer.desc->ops->init)
3909 return chip->manufacturer.desc->ops->init(chip);
3913 * Manufacturer cleanup. This function is called for all NANDs including
3914 * ONFI and JEDEC compliant ones.
3915 * Manufacturer drivers should put all their specific cleanup code in their
3918 static void nand_manufacturer_cleanup(struct nand_chip *chip)
3920 /* Release manufacturer private data */
3921 if (chip->manufacturer.desc && chip->manufacturer.desc->ops &&
3922 chip->manufacturer.desc->ops->cleanup)
3923 chip->manufacturer.desc->ops->cleanup(chip);
3927 * Get the flash and manufacturer id and lookup if the type is supported.
3929 static int nand_detect(struct nand_chip *chip, struct nand_flash_dev *type)
3931 const struct nand_manufacturer *manufacturer;
3932 struct mtd_info *mtd = nand_to_mtd(chip);
3935 u8 *id_data = chip->id.data;
3939 * Reset the chip, required by some chips (e.g. Micron MT29FxGxxxxx)
3942 nand_reset(chip, 0);
3944 /* Select the device */
3945 chip->select_chip(mtd, 0);
3947 /* Send the command for reading device ID */
3948 chip->cmdfunc(mtd, NAND_CMD_READID, 0x00, -1);
3950 /* Read manufacturer and device IDs */
3951 maf_id = chip->read_byte(mtd);
3952 dev_id = chip->read_byte(mtd);
3955 * Try again to make sure, as some systems the bus-hold or other
3956 * interface concerns can cause random data which looks like a
3957 * possibly credible NAND flash to appear. If the two results do
3958 * not match, ignore the device completely.
3961 chip->cmdfunc(mtd, NAND_CMD_READID, 0x00, -1);
3963 /* Read entire ID string */
3964 for (i = 0; i < 8; i++)
3965 id_data[i] = chip->read_byte(mtd);
3967 if (id_data[0] != maf_id || id_data[1] != dev_id) {
3968 pr_info("second ID read did not match %02x,%02x against %02x,%02x\n",
3969 maf_id, dev_id, id_data[0], id_data[1]);
3973 chip->id.len = nand_id_len(id_data, 8);
3975 /* Try to identify manufacturer */
3976 manufacturer = nand_get_manufacturer(maf_id);
3977 chip->manufacturer.desc = manufacturer;
3980 type = nand_flash_ids;
3983 * Save the NAND_BUSWIDTH_16 flag before letting auto-detection logic
3985 * This is required to make sure initial NAND bus width set by the
3986 * NAND controller driver is coherent with the real NAND bus width
3987 * (extracted by auto-detection code).
3989 busw = chip->options & NAND_BUSWIDTH_16;
3992 * The flag is only set (never cleared), reset it to its default value
3993 * before starting auto-detection.
3995 chip->options &= ~NAND_BUSWIDTH_16;
3997 for (; type->name != NULL; type++) {
3998 if (is_full_id_nand(type)) {
3999 if (find_full_id_nand(chip, type))
4001 } else if (dev_id == type->dev_id) {
4006 chip->onfi_version = 0;
4007 if (!type->name || !type->pagesize) {
4008 /* Check if the chip is ONFI compliant */
4009 if (nand_flash_detect_onfi(chip))
4012 /* Check if the chip is JEDEC compliant */
4013 if (nand_flash_detect_jedec(chip))
4021 mtd->name = type->name;
4023 chip->chipsize = (uint64_t)type->chipsize << 20;
4025 if (!type->pagesize)
4026 nand_manufacturer_detect(chip);
4028 nand_decode_id(chip, type);
4030 /* Get chip options */
4031 chip->options |= type->options;
4035 if (chip->options & NAND_BUSWIDTH_AUTO) {
4036 WARN_ON(busw & NAND_BUSWIDTH_16);
4037 nand_set_defaults(chip);
4038 } else if (busw != (chip->options & NAND_BUSWIDTH_16)) {
4040 * Check, if buswidth is correct. Hardware drivers should set
4043 pr_info("device found, Manufacturer ID: 0x%02x, Chip ID: 0x%02x\n",
4045 pr_info("%s %s\n", nand_manufacturer_name(manufacturer),
4047 pr_warn("bus width %d instead of %d bits\n", busw ? 16 : 8,
4048 (chip->options & NAND_BUSWIDTH_16) ? 16 : 8);
4052 nand_decode_bbm_options(chip);
4054 /* Calculate the address shift from the page size */
4055 chip->page_shift = ffs(mtd->writesize) - 1;
4056 /* Convert chipsize to number of pages per chip -1 */
4057 chip->pagemask = (chip->chipsize >> chip->page_shift) - 1;
4059 chip->bbt_erase_shift = chip->phys_erase_shift =
4060 ffs(mtd->erasesize) - 1;
4061 if (chip->chipsize & 0xffffffff)
4062 chip->chip_shift = ffs((unsigned)chip->chipsize) - 1;
4064 chip->chip_shift = ffs((unsigned)(chip->chipsize >> 32));
4065 chip->chip_shift += 32 - 1;
4068 chip->badblockbits = 8;
4069 chip->erase = single_erase;
4071 /* Do not replace user supplied command function! */
4072 if (mtd->writesize > 512 && chip->cmdfunc == nand_command)
4073 chip->cmdfunc = nand_command_lp;
4075 ret = nand_manufacturer_init(chip);
4079 pr_info("device found, Manufacturer ID: 0x%02x, Chip ID: 0x%02x\n",
4082 if (chip->onfi_version)
4083 pr_info("%s %s\n", nand_manufacturer_name(manufacturer),
4084 chip->onfi_params.model);
4085 else if (chip->jedec_version)
4086 pr_info("%s %s\n", nand_manufacturer_name(manufacturer),
4087 chip->jedec_params.model);
4089 pr_info("%s %s\n", nand_manufacturer_name(manufacturer),
4092 pr_info("%d MiB, %s, erase size: %d KiB, page size: %d, OOB size: %d\n",
4093 (int)(chip->chipsize >> 20), nand_is_slc(chip) ? "SLC" : "MLC",
4094 mtd->erasesize >> 10, mtd->writesize, mtd->oobsize);
4098 static const char * const nand_ecc_modes[] = {
4099 [NAND_ECC_NONE] = "none",
4100 [NAND_ECC_SOFT] = "soft",
4101 [NAND_ECC_HW] = "hw",
4102 [NAND_ECC_HW_SYNDROME] = "hw_syndrome",
4103 [NAND_ECC_HW_OOB_FIRST] = "hw_oob_first",
4106 static int of_get_nand_ecc_mode(struct device_node *np)
4111 err = of_property_read_string(np, "nand-ecc-mode", &pm);
4115 for (i = 0; i < ARRAY_SIZE(nand_ecc_modes); i++)
4116 if (!strcasecmp(pm, nand_ecc_modes[i]))
4120 * For backward compatibility we support few obsoleted values that don't
4121 * have their mappings into nand_ecc_modes_t anymore (they were merged
4122 * with other enums).
4124 if (!strcasecmp(pm, "soft_bch"))
4125 return NAND_ECC_SOFT;
4130 static const char * const nand_ecc_algos[] = {
4131 [NAND_ECC_HAMMING] = "hamming",
4132 [NAND_ECC_BCH] = "bch",
4135 static int of_get_nand_ecc_algo(struct device_node *np)
4140 err = of_property_read_string(np, "nand-ecc-algo", &pm);
4142 for (i = NAND_ECC_HAMMING; i < ARRAY_SIZE(nand_ecc_algos); i++)
4143 if (!strcasecmp(pm, nand_ecc_algos[i]))
4149 * For backward compatibility we also read "nand-ecc-mode" checking
4150 * for some obsoleted values that were specifying ECC algorithm.
4152 err = of_property_read_string(np, "nand-ecc-mode", &pm);
4156 if (!strcasecmp(pm, "soft"))
4157 return NAND_ECC_HAMMING;
4158 else if (!strcasecmp(pm, "soft_bch"))
4159 return NAND_ECC_BCH;
4164 static int of_get_nand_ecc_step_size(struct device_node *np)
4169 ret = of_property_read_u32(np, "nand-ecc-step-size", &val);
4170 return ret ? ret : val;
4173 static int of_get_nand_ecc_strength(struct device_node *np)
4178 ret = of_property_read_u32(np, "nand-ecc-strength", &val);
4179 return ret ? ret : val;
4182 static int of_get_nand_bus_width(struct device_node *np)
4186 if (of_property_read_u32(np, "nand-bus-width", &val))
4198 static bool of_get_nand_on_flash_bbt(struct device_node *np)
4200 return of_property_read_bool(np, "nand-on-flash-bbt");
4203 static int nand_dt_init(struct nand_chip *chip)
4205 struct device_node *dn = nand_get_flash_node(chip);
4206 int ecc_mode, ecc_algo, ecc_strength, ecc_step;
4211 if (of_get_nand_bus_width(dn) == 16)
4212 chip->options |= NAND_BUSWIDTH_16;
4214 if (of_get_nand_on_flash_bbt(dn))
4215 chip->bbt_options |= NAND_BBT_USE_FLASH;
4217 ecc_mode = of_get_nand_ecc_mode(dn);
4218 ecc_algo = of_get_nand_ecc_algo(dn);
4219 ecc_strength = of_get_nand_ecc_strength(dn);
4220 ecc_step = of_get_nand_ecc_step_size(dn);
4223 chip->ecc.mode = ecc_mode;
4226 chip->ecc.algo = ecc_algo;
4228 if (ecc_strength >= 0)
4229 chip->ecc.strength = ecc_strength;
4232 chip->ecc.size = ecc_step;
4234 if (of_property_read_bool(dn, "nand-ecc-maximize"))
4235 chip->ecc.options |= NAND_ECC_MAXIMIZE;
4241 * nand_scan_ident - [NAND Interface] Scan for the NAND device
4242 * @mtd: MTD device structure
4243 * @maxchips: number of chips to scan for
4244 * @table: alternative NAND ID table
4246 * This is the first phase of the normal nand_scan() function. It reads the
4247 * flash ID and sets up MTD fields accordingly.
4250 int nand_scan_ident(struct mtd_info *mtd, int maxchips,
4251 struct nand_flash_dev *table)
4253 int i, nand_maf_id, nand_dev_id;
4254 struct nand_chip *chip = mtd_to_nand(mtd);
4257 ret = nand_dt_init(chip);
4261 if (!mtd->name && mtd->dev.parent)
4262 mtd->name = dev_name(mtd->dev.parent);
4264 if ((!chip->cmdfunc || !chip->select_chip) && !chip->cmd_ctrl) {
4266 * Default functions assigned for chip_select() and
4267 * cmdfunc() both expect cmd_ctrl() to be populated,
4268 * so we need to check that that's the case
4270 pr_err("chip.cmd_ctrl() callback is not provided");
4273 /* Set the default functions */
4274 nand_set_defaults(chip);
4276 /* Read the flash type */
4277 ret = nand_detect(chip, table);
4279 if (!(chip->options & NAND_SCAN_SILENT_NODEV))
4280 pr_warn("No NAND device found\n");
4281 chip->select_chip(mtd, -1);
4285 /* Initialize the ->data_interface field. */
4286 ret = nand_init_data_interface(chip);
4291 * Setup the data interface correctly on the chip and controller side.
4292 * This explicit call to nand_setup_data_interface() is only required
4293 * for the first die, because nand_reset() has been called before
4294 * ->data_interface and ->default_onfi_timing_mode were set.
4295 * For the other dies, nand_reset() will automatically switch to the
4298 ret = nand_setup_data_interface(chip);
4302 nand_maf_id = chip->id.data[0];
4303 nand_dev_id = chip->id.data[1];
4305 chip->select_chip(mtd, -1);
4307 /* Check for a chip array */
4308 for (i = 1; i < maxchips; i++) {
4309 /* See comment in nand_get_flash_type for reset */
4310 nand_reset(chip, i);
4312 chip->select_chip(mtd, i);
4313 /* Send the command for reading device ID */
4314 chip->cmdfunc(mtd, NAND_CMD_READID, 0x00, -1);
4315 /* Read manufacturer and device IDs */
4316 if (nand_maf_id != chip->read_byte(mtd) ||
4317 nand_dev_id != chip->read_byte(mtd)) {
4318 chip->select_chip(mtd, -1);
4321 chip->select_chip(mtd, -1);
4324 pr_info("%d chips detected\n", i);
4326 /* Store the number of chips and calc total size for mtd */
4328 mtd->size = i * chip->chipsize;
4332 EXPORT_SYMBOL(nand_scan_ident);
4334 static int nand_set_ecc_soft_ops(struct mtd_info *mtd)
4336 struct nand_chip *chip = mtd_to_nand(mtd);
4337 struct nand_ecc_ctrl *ecc = &chip->ecc;
4339 if (WARN_ON(ecc->mode != NAND_ECC_SOFT))
4342 switch (ecc->algo) {
4343 case NAND_ECC_HAMMING:
4344 ecc->calculate = nand_calculate_ecc;
4345 ecc->correct = nand_correct_data;
4346 ecc->read_page = nand_read_page_swecc;
4347 ecc->read_subpage = nand_read_subpage;
4348 ecc->write_page = nand_write_page_swecc;
4349 ecc->read_page_raw = nand_read_page_raw;
4350 ecc->write_page_raw = nand_write_page_raw;
4351 ecc->read_oob = nand_read_oob_std;
4352 ecc->write_oob = nand_write_oob_std;
4359 if (!mtd_nand_has_bch()) {
4360 WARN(1, "CONFIG_MTD_NAND_ECC_BCH not enabled\n");
4363 ecc->calculate = nand_bch_calculate_ecc;
4364 ecc->correct = nand_bch_correct_data;
4365 ecc->read_page = nand_read_page_swecc;
4366 ecc->read_subpage = nand_read_subpage;
4367 ecc->write_page = nand_write_page_swecc;
4368 ecc->read_page_raw = nand_read_page_raw;
4369 ecc->write_page_raw = nand_write_page_raw;
4370 ecc->read_oob = nand_read_oob_std;
4371 ecc->write_oob = nand_write_oob_std;
4374 * Board driver should supply ecc.size and ecc.strength
4375 * values to select how many bits are correctable.
4376 * Otherwise, default to 4 bits for large page devices.
4378 if (!ecc->size && (mtd->oobsize >= 64)) {
4384 * if no ecc placement scheme was provided pickup the default
4387 if (!mtd->ooblayout) {
4388 /* handle large page devices only */
4389 if (mtd->oobsize < 64) {
4390 WARN(1, "OOB layout is required when using software BCH on small pages\n");
4394 mtd_set_ooblayout(mtd, &nand_ooblayout_lp_ops);
4399 * We can only maximize ECC config when the default layout is
4400 * used, otherwise we don't know how many bytes can really be
4403 if (mtd->ooblayout == &nand_ooblayout_lp_ops &&
4404 ecc->options & NAND_ECC_MAXIMIZE) {
4407 /* Always prefer 1k blocks over 512bytes ones */
4409 steps = mtd->writesize / ecc->size;
4411 /* Reserve 2 bytes for the BBM */
4412 bytes = (mtd->oobsize - 2) / steps;
4413 ecc->strength = bytes * 8 / fls(8 * ecc->size);
4416 /* See nand_bch_init() for details. */
4418 ecc->priv = nand_bch_init(mtd);
4420 WARN(1, "BCH ECC initialization failed!\n");
4425 WARN(1, "Unsupported ECC algorithm!\n");
4431 * Check if the chip configuration meet the datasheet requirements.
4433 * If our configuration corrects A bits per B bytes and the minimum
4434 * required correction level is X bits per Y bytes, then we must ensure
4435 * both of the following are true:
4437 * (1) A / B >= X / Y
4440 * Requirement (1) ensures we can correct for the required bitflip density.
4441 * Requirement (2) ensures we can correct even when all bitflips are clumped
4442 * in the same sector.
4444 static bool nand_ecc_strength_good(struct mtd_info *mtd)
4446 struct nand_chip *chip = mtd_to_nand(mtd);
4447 struct nand_ecc_ctrl *ecc = &chip->ecc;
4450 if (ecc->size == 0 || chip->ecc_step_ds == 0)
4451 /* Not enough information */
4455 * We get the number of corrected bits per page to compare
4456 * the correction density.
4458 corr = (mtd->writesize * ecc->strength) / ecc->size;
4459 ds_corr = (mtd->writesize * chip->ecc_strength_ds) / chip->ecc_step_ds;
4461 return corr >= ds_corr && ecc->strength >= chip->ecc_strength_ds;
4464 static bool invalid_ecc_page_accessors(struct nand_chip *chip)
4466 struct nand_ecc_ctrl *ecc = &chip->ecc;
4468 if (nand_standard_page_accessors(ecc))
4472 * NAND_ECC_CUSTOM_PAGE_ACCESS flag is set, make sure the NAND
4473 * controller driver implements all the page accessors because
4474 * default helpers are not suitable when the core does not
4475 * send the READ0/PAGEPROG commands.
4477 return (!ecc->read_page || !ecc->write_page ||
4478 !ecc->read_page_raw || !ecc->write_page_raw ||
4479 (NAND_HAS_SUBPAGE_READ(chip) && !ecc->read_subpage) ||
4480 (NAND_HAS_SUBPAGE_WRITE(chip) && !ecc->write_subpage &&
4481 ecc->hwctl && ecc->calculate));
4485 * nand_scan_tail - [NAND Interface] Scan for the NAND device
4486 * @mtd: MTD device structure
4488 * This is the second phase of the normal nand_scan() function. It fills out
4489 * all the uninitialized function pointers with the defaults and scans for a
4490 * bad block table if appropriate.
4492 int nand_scan_tail(struct mtd_info *mtd)
4494 struct nand_chip *chip = mtd_to_nand(mtd);
4495 struct nand_ecc_ctrl *ecc = &chip->ecc;
4496 struct nand_buffers *nbuf;
4499 /* New bad blocks should be marked in OOB, flash-based BBT, or both */
4500 if (WARN_ON((chip->bbt_options & NAND_BBT_NO_OOB_BBM) &&
4501 !(chip->bbt_options & NAND_BBT_USE_FLASH)))
4504 if (invalid_ecc_page_accessors(chip)) {
4505 pr_err("Invalid ECC page accessors setup\n");
4509 if (!(chip->options & NAND_OWN_BUFFERS)) {
4510 nbuf = kzalloc(sizeof(*nbuf) + mtd->writesize
4511 + mtd->oobsize * 3, GFP_KERNEL);
4514 nbuf->ecccalc = (uint8_t *)(nbuf + 1);
4515 nbuf->ecccode = nbuf->ecccalc + mtd->oobsize;
4516 nbuf->databuf = nbuf->ecccode + mtd->oobsize;
4518 chip->buffers = nbuf;
4524 /* Set the internal oob buffer location, just after the page data */
4525 chip->oob_poi = chip->buffers->databuf + mtd->writesize;
4528 * If no default placement scheme is given, select an appropriate one.
4530 if (!mtd->ooblayout &&
4531 !(ecc->mode == NAND_ECC_SOFT && ecc->algo == NAND_ECC_BCH)) {
4532 switch (mtd->oobsize) {
4535 mtd_set_ooblayout(mtd, &nand_ooblayout_sp_ops);
4539 mtd_set_ooblayout(mtd, &nand_ooblayout_lp_ops);
4542 WARN(1, "No oob scheme defined for oobsize %d\n",
4549 if (!chip->write_page)
4550 chip->write_page = nand_write_page;
4553 * Check ECC mode, default to software if 3byte/512byte hardware ECC is
4554 * selected and we have 256 byte pagesize fallback to software ECC
4557 switch (ecc->mode) {
4558 case NAND_ECC_HW_OOB_FIRST:
4559 /* Similar to NAND_ECC_HW, but a separate read_page handle */
4560 if (!ecc->calculate || !ecc->correct || !ecc->hwctl) {
4561 WARN(1, "No ECC functions supplied; hardware ECC not possible\n");
4565 if (!ecc->read_page)
4566 ecc->read_page = nand_read_page_hwecc_oob_first;
4569 /* Use standard hwecc read page function? */
4570 if (!ecc->read_page)
4571 ecc->read_page = nand_read_page_hwecc;
4572 if (!ecc->write_page)
4573 ecc->write_page = nand_write_page_hwecc;
4574 if (!ecc->read_page_raw)
4575 ecc->read_page_raw = nand_read_page_raw;
4576 if (!ecc->write_page_raw)
4577 ecc->write_page_raw = nand_write_page_raw;
4579 ecc->read_oob = nand_read_oob_std;
4580 if (!ecc->write_oob)
4581 ecc->write_oob = nand_write_oob_std;
4582 if (!ecc->read_subpage)
4583 ecc->read_subpage = nand_read_subpage;
4584 if (!ecc->write_subpage && ecc->hwctl && ecc->calculate)
4585 ecc->write_subpage = nand_write_subpage_hwecc;
4587 case NAND_ECC_HW_SYNDROME:
4588 if ((!ecc->calculate || !ecc->correct || !ecc->hwctl) &&
4590 ecc->read_page == nand_read_page_hwecc ||
4592 ecc->write_page == nand_write_page_hwecc)) {
4593 WARN(1, "No ECC functions supplied; hardware ECC not possible\n");
4597 /* Use standard syndrome read/write page function? */
4598 if (!ecc->read_page)
4599 ecc->read_page = nand_read_page_syndrome;
4600 if (!ecc->write_page)
4601 ecc->write_page = nand_write_page_syndrome;
4602 if (!ecc->read_page_raw)
4603 ecc->read_page_raw = nand_read_page_raw_syndrome;
4604 if (!ecc->write_page_raw)
4605 ecc->write_page_raw = nand_write_page_raw_syndrome;
4607 ecc->read_oob = nand_read_oob_syndrome;
4608 if (!ecc->write_oob)
4609 ecc->write_oob = nand_write_oob_syndrome;
4611 if (mtd->writesize >= ecc->size) {
4612 if (!ecc->strength) {
4613 WARN(1, "Driver must set ecc.strength when using hardware ECC\n");
4619 pr_warn("%d byte HW ECC not possible on %d byte page size, fallback to SW ECC\n",
4620 ecc->size, mtd->writesize);
4621 ecc->mode = NAND_ECC_SOFT;
4622 ecc->algo = NAND_ECC_HAMMING;
4625 ret = nand_set_ecc_soft_ops(mtd);
4633 pr_warn("NAND_ECC_NONE selected by board driver. This is not recommended!\n");
4634 ecc->read_page = nand_read_page_raw;
4635 ecc->write_page = nand_write_page_raw;
4636 ecc->read_oob = nand_read_oob_std;
4637 ecc->read_page_raw = nand_read_page_raw;
4638 ecc->write_page_raw = nand_write_page_raw;
4639 ecc->write_oob = nand_write_oob_std;
4640 ecc->size = mtd->writesize;
4646 WARN(1, "Invalid NAND_ECC_MODE %d\n", ecc->mode);
4651 /* For many systems, the standard OOB write also works for raw */
4652 if (!ecc->read_oob_raw)
4653 ecc->read_oob_raw = ecc->read_oob;
4654 if (!ecc->write_oob_raw)
4655 ecc->write_oob_raw = ecc->write_oob;
4657 /* propagate ecc info to mtd_info */
4658 mtd->ecc_strength = ecc->strength;
4659 mtd->ecc_step_size = ecc->size;
4662 * Set the number of read / write steps for one page depending on ECC
4665 ecc->steps = mtd->writesize / ecc->size;
4666 if (ecc->steps * ecc->size != mtd->writesize) {
4667 WARN(1, "Invalid ECC parameters\n");
4671 ecc->total = ecc->steps * ecc->bytes;
4674 * The number of bytes available for a client to place data into
4675 * the out of band area.
4677 ret = mtd_ooblayout_count_freebytes(mtd);
4681 mtd->oobavail = ret;
4683 /* ECC sanity check: warn if it's too weak */
4684 if (!nand_ecc_strength_good(mtd))
4685 pr_warn("WARNING: %s: the ECC used on your system is too weak compared to the one required by the NAND chip\n",
4688 /* Allow subpage writes up to ecc.steps. Not possible for MLC flash */
4689 if (!(chip->options & NAND_NO_SUBPAGE_WRITE) && nand_is_slc(chip)) {
4690 switch (ecc->steps) {
4692 mtd->subpage_sft = 1;
4697 mtd->subpage_sft = 2;
4701 chip->subpagesize = mtd->writesize >> mtd->subpage_sft;
4703 /* Initialize state */
4704 chip->state = FL_READY;
4706 /* Invalidate the pagebuffer reference */
4709 /* Large page NAND with SOFT_ECC should support subpage reads */
4710 switch (ecc->mode) {
4712 if (chip->page_shift > 9)
4713 chip->options |= NAND_SUBPAGE_READ;
4720 /* Fill in remaining MTD driver data */
4721 mtd->type = nand_is_slc(chip) ? MTD_NANDFLASH : MTD_MLCNANDFLASH;
4722 mtd->flags = (chip->options & NAND_ROM) ? MTD_CAP_ROM :
4724 mtd->_erase = nand_erase;
4726 mtd->_unpoint = NULL;
4727 mtd->_read = nand_read;
4728 mtd->_write = nand_write;
4729 mtd->_panic_write = panic_nand_write;
4730 mtd->_read_oob = nand_read_oob;
4731 mtd->_write_oob = nand_write_oob;
4732 mtd->_sync = nand_sync;
4734 mtd->_unlock = NULL;
4735 mtd->_suspend = nand_suspend;
4736 mtd->_resume = nand_resume;
4737 mtd->_reboot = nand_shutdown;
4738 mtd->_block_isreserved = nand_block_isreserved;
4739 mtd->_block_isbad = nand_block_isbad;
4740 mtd->_block_markbad = nand_block_markbad;
4741 mtd->_max_bad_blocks = nand_max_bad_blocks;
4742 mtd->writebufsize = mtd->writesize;
4745 * Initialize bitflip_threshold to its default prior scan_bbt() call.
4746 * scan_bbt() might invoke mtd_read(), thus bitflip_threshold must be
4749 if (!mtd->bitflip_threshold)
4750 mtd->bitflip_threshold = DIV_ROUND_UP(mtd->ecc_strength * 3, 4);
4752 /* Check, if we should skip the bad block table scan */
4753 if (chip->options & NAND_SKIP_BBTSCAN)
4756 /* Build bad block table */
4757 return chip->scan_bbt(mtd);
4759 if (!(chip->options & NAND_OWN_BUFFERS))
4760 kfree(chip->buffers);
4763 EXPORT_SYMBOL(nand_scan_tail);
4766 * is_module_text_address() isn't exported, and it's mostly a pointless
4767 * test if this is a module _anyway_ -- they'd have to try _really_ hard
4768 * to call us from in-kernel code if the core NAND support is modular.
4771 #define caller_is_module() (1)
4773 #define caller_is_module() \
4774 is_module_text_address((unsigned long)__builtin_return_address(0))
4778 * nand_scan - [NAND Interface] Scan for the NAND device
4779 * @mtd: MTD device structure
4780 * @maxchips: number of chips to scan for
4782 * This fills out all the uninitialized function pointers with the defaults.
4783 * The flash ID is read and the mtd/chip structures are filled with the
4784 * appropriate values.
4786 int nand_scan(struct mtd_info *mtd, int maxchips)
4790 ret = nand_scan_ident(mtd, maxchips, NULL);
4792 ret = nand_scan_tail(mtd);
4795 EXPORT_SYMBOL(nand_scan);
4798 * nand_cleanup - [NAND Interface] Free resources held by the NAND device
4799 * @chip: NAND chip object
4801 void nand_cleanup(struct nand_chip *chip)
4803 if (chip->ecc.mode == NAND_ECC_SOFT &&
4804 chip->ecc.algo == NAND_ECC_BCH)
4805 nand_bch_free((struct nand_bch_control *)chip->ecc.priv);
4807 nand_release_data_interface(chip);
4809 /* Free bad block table memory */
4811 if (!(chip->options & NAND_OWN_BUFFERS))
4812 kfree(chip->buffers);
4814 /* Free bad block descriptor memory */
4815 if (chip->badblock_pattern && chip->badblock_pattern->options
4816 & NAND_BBT_DYNAMICSTRUCT)
4817 kfree(chip->badblock_pattern);
4819 /* Free manufacturer priv data. */
4820 nand_manufacturer_cleanup(chip);
4822 EXPORT_SYMBOL_GPL(nand_cleanup);
4825 * nand_release - [NAND Interface] Unregister the MTD device and free resources
4826 * held by the NAND device
4827 * @mtd: MTD device structure
4829 void nand_release(struct mtd_info *mtd)
4831 mtd_device_unregister(mtd);
4832 nand_cleanup(mtd_to_nand(mtd));
4834 EXPORT_SYMBOL_GPL(nand_release);
4836 MODULE_LICENSE("GPL");
4837 MODULE_AUTHOR("Steven J. Hill <sjhill@realitydiluted.com>");
4838 MODULE_AUTHOR("Thomas Gleixner <tglx@linutronix.de>");
4839 MODULE_DESCRIPTION("Generic NAND flash driver code");