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:
672 case NAND_CMD_SET_FEATURES:
678 udelay(chip->chip_delay);
679 chip->cmd_ctrl(mtd, NAND_CMD_STATUS,
680 NAND_CTRL_CLE | NAND_CTRL_CHANGE);
682 NAND_CMD_NONE, NAND_NCE | NAND_CTRL_CHANGE);
683 /* EZ-NAND can take upto 250ms as per ONFi v4.0 */
684 nand_wait_status_ready(mtd, 250);
687 /* This applies to read commands */
690 * If we don't have access to the busy pin, we apply the given
693 if (!chip->dev_ready) {
694 udelay(chip->chip_delay);
699 * Apply this short delay always to ensure that we do wait tWB in
700 * any case on any machine.
704 nand_wait_ready(mtd);
707 static void nand_ccs_delay(struct nand_chip *chip)
710 * The controller already takes care of waiting for tCCS when the RNDIN
711 * or RNDOUT command is sent, return directly.
713 if (!(chip->options & NAND_WAIT_TCCS))
717 * Wait tCCS_min if it is correctly defined, otherwise wait 500ns
718 * (which should be safe for all NANDs).
720 if (chip->data_interface && chip->data_interface->timings.sdr.tCCS_min)
721 ndelay(chip->data_interface->timings.sdr.tCCS_min / 1000);
727 * nand_command_lp - [DEFAULT] Send command to NAND large page device
728 * @mtd: MTD device structure
729 * @command: the command to be sent
730 * @column: the column address for this command, -1 if none
731 * @page_addr: the page address for this command, -1 if none
733 * Send command to NAND device. This is the version for the new large page
734 * devices. We don't have the separate regions as we have in the small page
735 * devices. We must emulate NAND_CMD_READOOB to keep the code compatible.
737 static void nand_command_lp(struct mtd_info *mtd, unsigned int command,
738 int column, int page_addr)
740 register struct nand_chip *chip = mtd_to_nand(mtd);
742 /* Emulate NAND_CMD_READOOB */
743 if (command == NAND_CMD_READOOB) {
744 column += mtd->writesize;
745 command = NAND_CMD_READ0;
748 /* Command latch cycle */
749 chip->cmd_ctrl(mtd, command, NAND_NCE | NAND_CLE | NAND_CTRL_CHANGE);
751 if (column != -1 || page_addr != -1) {
752 int ctrl = NAND_CTRL_CHANGE | NAND_NCE | NAND_ALE;
754 /* Serially input address */
756 /* Adjust columns for 16 bit buswidth */
757 if (chip->options & NAND_BUSWIDTH_16 &&
758 !nand_opcode_8bits(command))
760 chip->cmd_ctrl(mtd, column, ctrl);
761 ctrl &= ~NAND_CTRL_CHANGE;
763 /* Only output a single addr cycle for 8bits opcodes. */
764 if (!nand_opcode_8bits(command))
765 chip->cmd_ctrl(mtd, column >> 8, ctrl);
767 if (page_addr != -1) {
768 chip->cmd_ctrl(mtd, page_addr, ctrl);
769 chip->cmd_ctrl(mtd, page_addr >> 8,
770 NAND_NCE | NAND_ALE);
771 /* One more address cycle for devices > 128MiB */
772 if (chip->chipsize > (128 << 20))
773 chip->cmd_ctrl(mtd, page_addr >> 16,
774 NAND_NCE | NAND_ALE);
777 chip->cmd_ctrl(mtd, NAND_CMD_NONE, NAND_NCE | NAND_CTRL_CHANGE);
780 * Program and erase have their own busy handlers status, sequential
781 * in and status need no delay.
785 case NAND_CMD_CACHEDPROG:
786 case NAND_CMD_PAGEPROG:
787 case NAND_CMD_ERASE1:
788 case NAND_CMD_ERASE2:
790 case NAND_CMD_STATUS:
791 case NAND_CMD_READID:
792 case NAND_CMD_SET_FEATURES:
796 nand_ccs_delay(chip);
802 udelay(chip->chip_delay);
803 chip->cmd_ctrl(mtd, NAND_CMD_STATUS,
804 NAND_NCE | NAND_CLE | NAND_CTRL_CHANGE);
805 chip->cmd_ctrl(mtd, NAND_CMD_NONE,
806 NAND_NCE | NAND_CTRL_CHANGE);
807 /* EZ-NAND can take upto 250ms as per ONFi v4.0 */
808 nand_wait_status_ready(mtd, 250);
811 case NAND_CMD_RNDOUT:
812 /* No ready / busy check necessary */
813 chip->cmd_ctrl(mtd, NAND_CMD_RNDOUTSTART,
814 NAND_NCE | NAND_CLE | NAND_CTRL_CHANGE);
815 chip->cmd_ctrl(mtd, NAND_CMD_NONE,
816 NAND_NCE | NAND_CTRL_CHANGE);
818 nand_ccs_delay(chip);
822 chip->cmd_ctrl(mtd, NAND_CMD_READSTART,
823 NAND_NCE | NAND_CLE | NAND_CTRL_CHANGE);
824 chip->cmd_ctrl(mtd, NAND_CMD_NONE,
825 NAND_NCE | NAND_CTRL_CHANGE);
827 /* This applies to read commands */
830 * If we don't have access to the busy pin, we apply the given
833 if (!chip->dev_ready) {
834 udelay(chip->chip_delay);
840 * Apply this short delay always to ensure that we do wait tWB in
841 * any case on any machine.
845 nand_wait_ready(mtd);
849 * panic_nand_get_device - [GENERIC] Get chip for selected access
850 * @chip: the nand chip descriptor
851 * @mtd: MTD device structure
852 * @new_state: the state which is requested
854 * Used when in panic, no locks are taken.
856 static void panic_nand_get_device(struct nand_chip *chip,
857 struct mtd_info *mtd, int new_state)
859 /* Hardware controller shared among independent devices */
860 chip->controller->active = chip;
861 chip->state = new_state;
865 * nand_get_device - [GENERIC] Get chip for selected access
866 * @mtd: MTD device structure
867 * @new_state: the state which is requested
869 * Get the device and lock it for exclusive access
872 nand_get_device(struct mtd_info *mtd, int new_state)
874 struct nand_chip *chip = mtd_to_nand(mtd);
875 spinlock_t *lock = &chip->controller->lock;
876 wait_queue_head_t *wq = &chip->controller->wq;
877 DECLARE_WAITQUEUE(wait, current);
881 /* Hardware controller shared among independent devices */
882 if (!chip->controller->active)
883 chip->controller->active = chip;
885 if (chip->controller->active == chip && chip->state == FL_READY) {
886 chip->state = new_state;
890 if (new_state == FL_PM_SUSPENDED) {
891 if (chip->controller->active->state == FL_PM_SUSPENDED) {
892 chip->state = FL_PM_SUSPENDED;
897 set_current_state(TASK_UNINTERRUPTIBLE);
898 add_wait_queue(wq, &wait);
901 remove_wait_queue(wq, &wait);
906 * panic_nand_wait - [GENERIC] wait until the command is done
907 * @mtd: MTD device structure
908 * @chip: NAND chip structure
911 * Wait for command done. This is a helper function for nand_wait used when
912 * we are in interrupt context. May happen when in panic and trying to write
913 * an oops through mtdoops.
915 static void panic_nand_wait(struct mtd_info *mtd, struct nand_chip *chip,
919 for (i = 0; i < timeo; i++) {
920 if (chip->dev_ready) {
921 if (chip->dev_ready(mtd))
924 if (chip->read_byte(mtd) & NAND_STATUS_READY)
932 * nand_wait - [DEFAULT] wait until the command is done
933 * @mtd: MTD device structure
934 * @chip: NAND chip structure
936 * Wait for command done. This applies to erase and program only.
938 static int nand_wait(struct mtd_info *mtd, struct nand_chip *chip)
942 unsigned long timeo = 400;
945 * Apply this short delay always to ensure that we do wait tWB in any
946 * case on any machine.
950 chip->cmdfunc(mtd, NAND_CMD_STATUS, -1, -1);
952 if (in_interrupt() || oops_in_progress)
953 panic_nand_wait(mtd, chip, timeo);
955 timeo = jiffies + msecs_to_jiffies(timeo);
957 if (chip->dev_ready) {
958 if (chip->dev_ready(mtd))
961 if (chip->read_byte(mtd) & NAND_STATUS_READY)
965 } while (time_before(jiffies, timeo));
968 status = (int)chip->read_byte(mtd);
969 /* This can happen if in case of timeout or buggy dev_ready */
970 WARN_ON(!(status & NAND_STATUS_READY));
975 * nand_reset_data_interface - Reset data interface and timings
976 * @chip: The NAND chip
978 * Reset the Data interface and timings to ONFI mode 0.
980 * Returns 0 for success or negative error code otherwise.
982 static int nand_reset_data_interface(struct nand_chip *chip)
984 struct mtd_info *mtd = nand_to_mtd(chip);
985 const struct nand_data_interface *conf;
988 if (!chip->setup_data_interface)
992 * The ONFI specification says:
994 * To transition from NV-DDR or NV-DDR2 to the SDR data
995 * interface, the host shall use the Reset (FFh) command
996 * using SDR timing mode 0. A device in any timing mode is
997 * required to recognize Reset (FFh) command issued in SDR
1001 * Configure the data interface in SDR mode and set the
1002 * timings to timing mode 0.
1005 conf = nand_get_default_data_interface();
1006 ret = chip->setup_data_interface(mtd, conf, false);
1008 pr_err("Failed to configure data interface to SDR timing mode 0\n");
1014 * nand_setup_data_interface - Setup the best data interface and timings
1015 * @chip: The NAND chip
1017 * Find and configure the best data interface and NAND timings supported by
1018 * the chip and the driver.
1019 * First tries to retrieve supported timing modes from ONFI information,
1020 * and if the NAND chip does not support ONFI, relies on the
1021 * ->onfi_timing_mode_default specified in the nand_ids table.
1023 * Returns 0 for success or negative error code otherwise.
1025 static int nand_setup_data_interface(struct nand_chip *chip)
1027 struct mtd_info *mtd = nand_to_mtd(chip);
1030 if (!chip->setup_data_interface || !chip->data_interface)
1034 * Ensure the timing mode has been changed on the chip side
1035 * before changing timings on the controller side.
1037 if (chip->onfi_version) {
1038 u8 tmode_param[ONFI_SUBFEATURE_PARAM_LEN] = {
1039 chip->onfi_timing_mode_default,
1042 ret = chip->onfi_set_features(mtd, chip,
1043 ONFI_FEATURE_ADDR_TIMING_MODE,
1049 ret = chip->setup_data_interface(mtd, chip->data_interface, false);
1055 * nand_init_data_interface - find the best data interface and timings
1056 * @chip: The NAND chip
1058 * Find the best data interface and NAND timings supported by the chip
1060 * First tries to retrieve supported timing modes from ONFI information,
1061 * and if the NAND chip does not support ONFI, relies on the
1062 * ->onfi_timing_mode_default specified in the nand_ids table. After this
1063 * function nand_chip->data_interface is initialized with the best timing mode
1066 * Returns 0 for success or negative error code otherwise.
1068 static int nand_init_data_interface(struct nand_chip *chip)
1070 struct mtd_info *mtd = nand_to_mtd(chip);
1071 int modes, mode, ret;
1073 if (!chip->setup_data_interface)
1077 * First try to identify the best timings from ONFI parameters and
1078 * if the NAND does not support ONFI, fallback to the default ONFI
1081 modes = onfi_get_async_timing_mode(chip);
1082 if (modes == ONFI_TIMING_MODE_UNKNOWN) {
1083 if (!chip->onfi_timing_mode_default)
1086 modes = GENMASK(chip->onfi_timing_mode_default, 0);
1089 chip->data_interface = kzalloc(sizeof(*chip->data_interface),
1091 if (!chip->data_interface)
1094 for (mode = fls(modes) - 1; mode >= 0; mode--) {
1095 ret = onfi_init_data_interface(chip, chip->data_interface,
1096 NAND_SDR_IFACE, mode);
1100 ret = chip->setup_data_interface(mtd, chip->data_interface,
1103 chip->onfi_timing_mode_default = mode;
1111 static void nand_release_data_interface(struct nand_chip *chip)
1113 kfree(chip->data_interface);
1117 * nand_reset - Reset and initialize a NAND device
1118 * @chip: The NAND chip
1119 * @chipnr: Internal die id
1121 * Returns 0 for success or negative error code otherwise
1123 int nand_reset(struct nand_chip *chip, int chipnr)
1125 struct mtd_info *mtd = nand_to_mtd(chip);
1128 ret = nand_reset_data_interface(chip);
1133 * The CS line has to be released before we can apply the new NAND
1134 * interface settings, hence this weird ->select_chip() dance.
1136 chip->select_chip(mtd, chipnr);
1137 chip->cmdfunc(mtd, NAND_CMD_RESET, -1, -1);
1138 chip->select_chip(mtd, -1);
1140 chip->select_chip(mtd, chipnr);
1141 ret = nand_setup_data_interface(chip);
1142 chip->select_chip(mtd, -1);
1150 * __nand_unlock - [REPLACEABLE] unlocks specified locked blocks
1152 * @ofs: offset to start unlock from
1153 * @len: length to unlock
1154 * @invert: when = 0, unlock the range of blocks within the lower and
1155 * upper boundary address
1156 * when = 1, unlock the range of blocks outside the boundaries
1157 * of the lower and upper boundary address
1159 * Returs unlock status.
1161 static int __nand_unlock(struct mtd_info *mtd, loff_t ofs,
1162 uint64_t len, int invert)
1166 struct nand_chip *chip = mtd_to_nand(mtd);
1168 /* Submit address of first page to unlock */
1169 page = ofs >> chip->page_shift;
1170 chip->cmdfunc(mtd, NAND_CMD_UNLOCK1, -1, page & chip->pagemask);
1172 /* Submit address of last page to unlock */
1173 page = (ofs + len) >> chip->page_shift;
1174 chip->cmdfunc(mtd, NAND_CMD_UNLOCK2, -1,
1175 (page | invert) & chip->pagemask);
1177 /* Call wait ready function */
1178 status = chip->waitfunc(mtd, chip);
1179 /* See if device thinks it succeeded */
1180 if (status & NAND_STATUS_FAIL) {
1181 pr_debug("%s: error status = 0x%08x\n",
1190 * nand_unlock - [REPLACEABLE] unlocks specified locked blocks
1192 * @ofs: offset to start unlock from
1193 * @len: length to unlock
1195 * Returns unlock status.
1197 int nand_unlock(struct mtd_info *mtd, loff_t ofs, uint64_t len)
1201 struct nand_chip *chip = mtd_to_nand(mtd);
1203 pr_debug("%s: start = 0x%012llx, len = %llu\n",
1204 __func__, (unsigned long long)ofs, len);
1206 if (check_offs_len(mtd, ofs, len))
1209 /* Align to last block address if size addresses end of the device */
1210 if (ofs + len == mtd->size)
1211 len -= mtd->erasesize;
1213 nand_get_device(mtd, FL_UNLOCKING);
1215 /* Shift to get chip number */
1216 chipnr = ofs >> chip->chip_shift;
1220 * If we want to check the WP through READ STATUS and check the bit 7
1221 * we must reset the chip
1222 * some operation can also clear the bit 7 of status register
1223 * eg. erase/program a locked block
1225 nand_reset(chip, chipnr);
1227 chip->select_chip(mtd, chipnr);
1229 /* Check, if it is write protected */
1230 if (nand_check_wp(mtd)) {
1231 pr_debug("%s: device is write protected!\n",
1237 ret = __nand_unlock(mtd, ofs, len, 0);
1240 chip->select_chip(mtd, -1);
1241 nand_release_device(mtd);
1245 EXPORT_SYMBOL(nand_unlock);
1248 * nand_lock - [REPLACEABLE] locks all blocks present in the device
1250 * @ofs: offset to start unlock from
1251 * @len: length to unlock
1253 * This feature is not supported in many NAND parts. 'Micron' NAND parts do
1254 * have this feature, but it allows only to lock all blocks, not for specified
1255 * range for block. Implementing 'lock' feature by making use of 'unlock', for
1258 * Returns lock status.
1260 int nand_lock(struct mtd_info *mtd, loff_t ofs, uint64_t len)
1263 int chipnr, status, page;
1264 struct nand_chip *chip = mtd_to_nand(mtd);
1266 pr_debug("%s: start = 0x%012llx, len = %llu\n",
1267 __func__, (unsigned long long)ofs, len);
1269 if (check_offs_len(mtd, ofs, len))
1272 nand_get_device(mtd, FL_LOCKING);
1274 /* Shift to get chip number */
1275 chipnr = ofs >> chip->chip_shift;
1279 * If we want to check the WP through READ STATUS and check the bit 7
1280 * we must reset the chip
1281 * some operation can also clear the bit 7 of status register
1282 * eg. erase/program a locked block
1284 nand_reset(chip, chipnr);
1286 chip->select_chip(mtd, chipnr);
1288 /* Check, if it is write protected */
1289 if (nand_check_wp(mtd)) {
1290 pr_debug("%s: device is write protected!\n",
1292 status = MTD_ERASE_FAILED;
1297 /* Submit address of first page to lock */
1298 page = ofs >> chip->page_shift;
1299 chip->cmdfunc(mtd, NAND_CMD_LOCK, -1, page & chip->pagemask);
1301 /* Call wait ready function */
1302 status = chip->waitfunc(mtd, chip);
1303 /* See if device thinks it succeeded */
1304 if (status & NAND_STATUS_FAIL) {
1305 pr_debug("%s: error status = 0x%08x\n",
1311 ret = __nand_unlock(mtd, ofs, len, 0x1);
1314 chip->select_chip(mtd, -1);
1315 nand_release_device(mtd);
1319 EXPORT_SYMBOL(nand_lock);
1322 * nand_check_erased_buf - check if a buffer contains (almost) only 0xff data
1323 * @buf: buffer to test
1324 * @len: buffer length
1325 * @bitflips_threshold: maximum number of bitflips
1327 * Check if a buffer contains only 0xff, which means the underlying region
1328 * has been erased and is ready to be programmed.
1329 * The bitflips_threshold specify the maximum number of bitflips before
1330 * considering the region is not erased.
1331 * Note: The logic of this function has been extracted from the memweight
1332 * implementation, except that nand_check_erased_buf function exit before
1333 * testing the whole buffer if the number of bitflips exceed the
1334 * bitflips_threshold value.
1336 * Returns a positive number of bitflips less than or equal to
1337 * bitflips_threshold, or -ERROR_CODE for bitflips in excess of the
1340 static int nand_check_erased_buf(void *buf, int len, int bitflips_threshold)
1342 const unsigned char *bitmap = buf;
1346 for (; len && ((uintptr_t)bitmap) % sizeof(long);
1348 weight = hweight8(*bitmap);
1349 bitflips += BITS_PER_BYTE - weight;
1350 if (unlikely(bitflips > bitflips_threshold))
1354 for (; len >= sizeof(long);
1355 len -= sizeof(long), bitmap += sizeof(long)) {
1356 weight = hweight_long(*((unsigned long *)bitmap));
1357 bitflips += BITS_PER_LONG - weight;
1358 if (unlikely(bitflips > bitflips_threshold))
1362 for (; len > 0; len--, bitmap++) {
1363 weight = hweight8(*bitmap);
1364 bitflips += BITS_PER_BYTE - weight;
1365 if (unlikely(bitflips > bitflips_threshold))
1373 * nand_check_erased_ecc_chunk - check if an ECC chunk contains (almost) only
1375 * @data: data buffer to test
1376 * @datalen: data length
1378 * @ecclen: ECC length
1379 * @extraoob: extra OOB buffer
1380 * @extraooblen: extra OOB length
1381 * @bitflips_threshold: maximum number of bitflips
1383 * Check if a data buffer and its associated ECC and OOB data contains only
1384 * 0xff pattern, which means the underlying region has been erased and is
1385 * ready to be programmed.
1386 * The bitflips_threshold specify the maximum number of bitflips before
1387 * considering the region as not erased.
1390 * 1/ ECC algorithms are working on pre-defined block sizes which are usually
1391 * different from the NAND page size. When fixing bitflips, ECC engines will
1392 * report the number of errors per chunk, and the NAND core infrastructure
1393 * expect you to return the maximum number of bitflips for the whole page.
1394 * This is why you should always use this function on a single chunk and
1395 * not on the whole page. After checking each chunk you should update your
1396 * max_bitflips value accordingly.
1397 * 2/ When checking for bitflips in erased pages you should not only check
1398 * the payload data but also their associated ECC data, because a user might
1399 * have programmed almost all bits to 1 but a few. In this case, we
1400 * shouldn't consider the chunk as erased, and checking ECC bytes prevent
1402 * 3/ The extraoob argument is optional, and should be used if some of your OOB
1403 * data are protected by the ECC engine.
1404 * It could also be used if you support subpages and want to attach some
1405 * extra OOB data to an ECC chunk.
1407 * Returns a positive number of bitflips less than or equal to
1408 * bitflips_threshold, or -ERROR_CODE for bitflips in excess of the
1409 * threshold. In case of success, the passed buffers are filled with 0xff.
1411 int nand_check_erased_ecc_chunk(void *data, int datalen,
1412 void *ecc, int ecclen,
1413 void *extraoob, int extraooblen,
1414 int bitflips_threshold)
1416 int data_bitflips = 0, ecc_bitflips = 0, extraoob_bitflips = 0;
1418 data_bitflips = nand_check_erased_buf(data, datalen,
1419 bitflips_threshold);
1420 if (data_bitflips < 0)
1421 return data_bitflips;
1423 bitflips_threshold -= data_bitflips;
1425 ecc_bitflips = nand_check_erased_buf(ecc, ecclen, bitflips_threshold);
1426 if (ecc_bitflips < 0)
1427 return ecc_bitflips;
1429 bitflips_threshold -= ecc_bitflips;
1431 extraoob_bitflips = nand_check_erased_buf(extraoob, extraooblen,
1432 bitflips_threshold);
1433 if (extraoob_bitflips < 0)
1434 return extraoob_bitflips;
1437 memset(data, 0xff, datalen);
1440 memset(ecc, 0xff, ecclen);
1442 if (extraoob_bitflips)
1443 memset(extraoob, 0xff, extraooblen);
1445 return data_bitflips + ecc_bitflips + extraoob_bitflips;
1447 EXPORT_SYMBOL(nand_check_erased_ecc_chunk);
1450 * nand_read_page_raw - [INTERN] read raw page data without ecc
1451 * @mtd: mtd info structure
1452 * @chip: nand chip info structure
1453 * @buf: buffer to store read data
1454 * @oob_required: caller requires OOB data read to chip->oob_poi
1455 * @page: page number to read
1457 * Not for syndrome calculating ECC controllers, which use a special oob layout.
1459 static int nand_read_page_raw(struct mtd_info *mtd, struct nand_chip *chip,
1460 uint8_t *buf, int oob_required, int page)
1462 chip->read_buf(mtd, buf, mtd->writesize);
1464 chip->read_buf(mtd, chip->oob_poi, mtd->oobsize);
1469 * nand_read_page_raw_syndrome - [INTERN] read raw page data without ecc
1470 * @mtd: mtd info structure
1471 * @chip: nand chip info structure
1472 * @buf: buffer to store read data
1473 * @oob_required: caller requires OOB data read to chip->oob_poi
1474 * @page: page number to read
1476 * We need a special oob layout and handling even when OOB isn't used.
1478 static int nand_read_page_raw_syndrome(struct mtd_info *mtd,
1479 struct nand_chip *chip, uint8_t *buf,
1480 int oob_required, int page)
1482 int eccsize = chip->ecc.size;
1483 int eccbytes = chip->ecc.bytes;
1484 uint8_t *oob = chip->oob_poi;
1487 for (steps = chip->ecc.steps; steps > 0; steps--) {
1488 chip->read_buf(mtd, buf, eccsize);
1491 if (chip->ecc.prepad) {
1492 chip->read_buf(mtd, oob, chip->ecc.prepad);
1493 oob += chip->ecc.prepad;
1496 chip->read_buf(mtd, oob, eccbytes);
1499 if (chip->ecc.postpad) {
1500 chip->read_buf(mtd, oob, chip->ecc.postpad);
1501 oob += chip->ecc.postpad;
1505 size = mtd->oobsize - (oob - chip->oob_poi);
1507 chip->read_buf(mtd, oob, size);
1513 * nand_read_page_swecc - [REPLACEABLE] software ECC based page read function
1514 * @mtd: mtd info structure
1515 * @chip: nand chip info structure
1516 * @buf: buffer to store read data
1517 * @oob_required: caller requires OOB data read to chip->oob_poi
1518 * @page: page number to read
1520 static int nand_read_page_swecc(struct mtd_info *mtd, struct nand_chip *chip,
1521 uint8_t *buf, int oob_required, int page)
1523 int i, eccsize = chip->ecc.size, ret;
1524 int eccbytes = chip->ecc.bytes;
1525 int eccsteps = chip->ecc.steps;
1527 uint8_t *ecc_calc = chip->buffers->ecccalc;
1528 uint8_t *ecc_code = chip->buffers->ecccode;
1529 unsigned int max_bitflips = 0;
1531 chip->ecc.read_page_raw(mtd, chip, buf, 1, page);
1533 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize)
1534 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
1536 ret = mtd_ooblayout_get_eccbytes(mtd, ecc_code, chip->oob_poi, 0,
1541 eccsteps = chip->ecc.steps;
1544 for (i = 0 ; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
1547 stat = chip->ecc.correct(mtd, p, &ecc_code[i], &ecc_calc[i]);
1549 mtd->ecc_stats.failed++;
1551 mtd->ecc_stats.corrected += stat;
1552 max_bitflips = max_t(unsigned int, max_bitflips, stat);
1555 return max_bitflips;
1559 * nand_read_subpage - [REPLACEABLE] ECC based sub-page read function
1560 * @mtd: mtd info structure
1561 * @chip: nand chip info structure
1562 * @data_offs: offset of requested data within the page
1563 * @readlen: data length
1564 * @bufpoi: buffer to store read data
1565 * @page: page number to read
1567 static int nand_read_subpage(struct mtd_info *mtd, struct nand_chip *chip,
1568 uint32_t data_offs, uint32_t readlen, uint8_t *bufpoi,
1571 int start_step, end_step, num_steps, ret;
1573 int data_col_addr, i, gaps = 0;
1574 int datafrag_len, eccfrag_len, aligned_len, aligned_pos;
1575 int busw = (chip->options & NAND_BUSWIDTH_16) ? 2 : 1;
1576 int index, section = 0;
1577 unsigned int max_bitflips = 0;
1578 struct mtd_oob_region oobregion = { };
1580 /* Column address within the page aligned to ECC size (256bytes) */
1581 start_step = data_offs / chip->ecc.size;
1582 end_step = (data_offs + readlen - 1) / chip->ecc.size;
1583 num_steps = end_step - start_step + 1;
1584 index = start_step * chip->ecc.bytes;
1586 /* Data size aligned to ECC ecc.size */
1587 datafrag_len = num_steps * chip->ecc.size;
1588 eccfrag_len = num_steps * chip->ecc.bytes;
1590 data_col_addr = start_step * chip->ecc.size;
1591 /* If we read not a page aligned data */
1592 if (data_col_addr != 0)
1593 chip->cmdfunc(mtd, NAND_CMD_RNDOUT, data_col_addr, -1);
1595 p = bufpoi + data_col_addr;
1596 chip->read_buf(mtd, p, datafrag_len);
1599 for (i = 0; i < eccfrag_len ; i += chip->ecc.bytes, p += chip->ecc.size)
1600 chip->ecc.calculate(mtd, p, &chip->buffers->ecccalc[i]);
1603 * The performance is faster if we position offsets according to
1604 * ecc.pos. Let's make sure that there are no gaps in ECC positions.
1606 ret = mtd_ooblayout_find_eccregion(mtd, index, §ion, &oobregion);
1610 if (oobregion.length < eccfrag_len)
1614 chip->cmdfunc(mtd, NAND_CMD_RNDOUT, mtd->writesize, -1);
1615 chip->read_buf(mtd, chip->oob_poi, mtd->oobsize);
1618 * Send the command to read the particular ECC bytes take care
1619 * about buswidth alignment in read_buf.
1621 aligned_pos = oobregion.offset & ~(busw - 1);
1622 aligned_len = eccfrag_len;
1623 if (oobregion.offset & (busw - 1))
1625 if ((oobregion.offset + (num_steps * chip->ecc.bytes)) &
1629 chip->cmdfunc(mtd, NAND_CMD_RNDOUT,
1630 mtd->writesize + aligned_pos, -1);
1631 chip->read_buf(mtd, &chip->oob_poi[aligned_pos], aligned_len);
1634 ret = mtd_ooblayout_get_eccbytes(mtd, chip->buffers->ecccode,
1635 chip->oob_poi, index, eccfrag_len);
1639 p = bufpoi + data_col_addr;
1640 for (i = 0; i < eccfrag_len ; i += chip->ecc.bytes, p += chip->ecc.size) {
1643 stat = chip->ecc.correct(mtd, p,
1644 &chip->buffers->ecccode[i], &chip->buffers->ecccalc[i]);
1645 if (stat == -EBADMSG &&
1646 (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
1647 /* check for empty pages with bitflips */
1648 stat = nand_check_erased_ecc_chunk(p, chip->ecc.size,
1649 &chip->buffers->ecccode[i],
1652 chip->ecc.strength);
1656 mtd->ecc_stats.failed++;
1658 mtd->ecc_stats.corrected += stat;
1659 max_bitflips = max_t(unsigned int, max_bitflips, stat);
1662 return max_bitflips;
1666 * nand_read_page_hwecc - [REPLACEABLE] hardware ECC based page read function
1667 * @mtd: mtd info structure
1668 * @chip: nand chip info structure
1669 * @buf: buffer to store read data
1670 * @oob_required: caller requires OOB data read to chip->oob_poi
1671 * @page: page number to read
1673 * Not for syndrome calculating ECC controllers which need a special oob layout.
1675 static int nand_read_page_hwecc(struct mtd_info *mtd, struct nand_chip *chip,
1676 uint8_t *buf, int oob_required, int page)
1678 int i, eccsize = chip->ecc.size, ret;
1679 int eccbytes = chip->ecc.bytes;
1680 int eccsteps = chip->ecc.steps;
1682 uint8_t *ecc_calc = chip->buffers->ecccalc;
1683 uint8_t *ecc_code = chip->buffers->ecccode;
1684 unsigned int max_bitflips = 0;
1686 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
1687 chip->ecc.hwctl(mtd, NAND_ECC_READ);
1688 chip->read_buf(mtd, p, eccsize);
1689 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
1691 chip->read_buf(mtd, chip->oob_poi, mtd->oobsize);
1693 ret = mtd_ooblayout_get_eccbytes(mtd, ecc_code, chip->oob_poi, 0,
1698 eccsteps = chip->ecc.steps;
1701 for (i = 0 ; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
1704 stat = chip->ecc.correct(mtd, p, &ecc_code[i], &ecc_calc[i]);
1705 if (stat == -EBADMSG &&
1706 (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
1707 /* check for empty pages with bitflips */
1708 stat = nand_check_erased_ecc_chunk(p, eccsize,
1709 &ecc_code[i], eccbytes,
1711 chip->ecc.strength);
1715 mtd->ecc_stats.failed++;
1717 mtd->ecc_stats.corrected += stat;
1718 max_bitflips = max_t(unsigned int, max_bitflips, stat);
1721 return max_bitflips;
1725 * nand_read_page_hwecc_oob_first - [REPLACEABLE] hw ecc, read oob first
1726 * @mtd: mtd info structure
1727 * @chip: nand chip info structure
1728 * @buf: buffer to store read data
1729 * @oob_required: caller requires OOB data read to chip->oob_poi
1730 * @page: page number to read
1732 * Hardware ECC for large page chips, require OOB to be read first. For this
1733 * ECC mode, the write_page method is re-used from ECC_HW. These methods
1734 * read/write ECC from the OOB area, unlike the ECC_HW_SYNDROME support with
1735 * multiple ECC steps, follows the "infix ECC" scheme and reads/writes ECC from
1736 * the data area, by overwriting the NAND manufacturer bad block markings.
1738 static int nand_read_page_hwecc_oob_first(struct mtd_info *mtd,
1739 struct nand_chip *chip, uint8_t *buf, int oob_required, int page)
1741 int i, eccsize = chip->ecc.size, ret;
1742 int eccbytes = chip->ecc.bytes;
1743 int eccsteps = chip->ecc.steps;
1745 uint8_t *ecc_code = chip->buffers->ecccode;
1746 uint8_t *ecc_calc = chip->buffers->ecccalc;
1747 unsigned int max_bitflips = 0;
1749 /* Read the OOB area first */
1750 chip->cmdfunc(mtd, NAND_CMD_READOOB, 0, page);
1751 chip->read_buf(mtd, chip->oob_poi, mtd->oobsize);
1752 chip->cmdfunc(mtd, NAND_CMD_READ0, 0, page);
1754 ret = mtd_ooblayout_get_eccbytes(mtd, ecc_code, chip->oob_poi, 0,
1759 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
1762 chip->ecc.hwctl(mtd, NAND_ECC_READ);
1763 chip->read_buf(mtd, p, eccsize);
1764 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
1766 stat = chip->ecc.correct(mtd, p, &ecc_code[i], NULL);
1767 if (stat == -EBADMSG &&
1768 (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
1769 /* check for empty pages with bitflips */
1770 stat = nand_check_erased_ecc_chunk(p, eccsize,
1771 &ecc_code[i], eccbytes,
1773 chip->ecc.strength);
1777 mtd->ecc_stats.failed++;
1779 mtd->ecc_stats.corrected += stat;
1780 max_bitflips = max_t(unsigned int, max_bitflips, stat);
1783 return max_bitflips;
1787 * nand_read_page_syndrome - [REPLACEABLE] hardware ECC syndrome based page read
1788 * @mtd: mtd info structure
1789 * @chip: nand chip info structure
1790 * @buf: buffer to store read data
1791 * @oob_required: caller requires OOB data read to chip->oob_poi
1792 * @page: page number to read
1794 * The hw generator calculates the error syndrome automatically. Therefore we
1795 * need a special oob layout and handling.
1797 static int nand_read_page_syndrome(struct mtd_info *mtd, struct nand_chip *chip,
1798 uint8_t *buf, int oob_required, int page)
1800 int i, eccsize = chip->ecc.size;
1801 int eccbytes = chip->ecc.bytes;
1802 int eccsteps = chip->ecc.steps;
1803 int eccpadbytes = eccbytes + chip->ecc.prepad + chip->ecc.postpad;
1805 uint8_t *oob = chip->oob_poi;
1806 unsigned int max_bitflips = 0;
1808 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
1811 chip->ecc.hwctl(mtd, NAND_ECC_READ);
1812 chip->read_buf(mtd, p, eccsize);
1814 if (chip->ecc.prepad) {
1815 chip->read_buf(mtd, oob, chip->ecc.prepad);
1816 oob += chip->ecc.prepad;
1819 chip->ecc.hwctl(mtd, NAND_ECC_READSYN);
1820 chip->read_buf(mtd, oob, eccbytes);
1821 stat = chip->ecc.correct(mtd, p, oob, NULL);
1825 if (chip->ecc.postpad) {
1826 chip->read_buf(mtd, oob, chip->ecc.postpad);
1827 oob += chip->ecc.postpad;
1830 if (stat == -EBADMSG &&
1831 (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
1832 /* check for empty pages with bitflips */
1833 stat = nand_check_erased_ecc_chunk(p, chip->ecc.size,
1837 chip->ecc.strength);
1841 mtd->ecc_stats.failed++;
1843 mtd->ecc_stats.corrected += stat;
1844 max_bitflips = max_t(unsigned int, max_bitflips, stat);
1848 /* Calculate remaining oob bytes */
1849 i = mtd->oobsize - (oob - chip->oob_poi);
1851 chip->read_buf(mtd, oob, i);
1853 return max_bitflips;
1857 * nand_transfer_oob - [INTERN] Transfer oob to client buffer
1858 * @mtd: mtd info structure
1859 * @oob: oob destination address
1860 * @ops: oob ops structure
1861 * @len: size of oob to transfer
1863 static uint8_t *nand_transfer_oob(struct mtd_info *mtd, uint8_t *oob,
1864 struct mtd_oob_ops *ops, size_t len)
1866 struct nand_chip *chip = mtd_to_nand(mtd);
1869 switch (ops->mode) {
1871 case MTD_OPS_PLACE_OOB:
1873 memcpy(oob, chip->oob_poi + ops->ooboffs, len);
1876 case MTD_OPS_AUTO_OOB:
1877 ret = mtd_ooblayout_get_databytes(mtd, oob, chip->oob_poi,
1889 * nand_setup_read_retry - [INTERN] Set the READ RETRY mode
1890 * @mtd: MTD device structure
1891 * @retry_mode: the retry mode to use
1893 * Some vendors supply a special command to shift the Vt threshold, to be used
1894 * when there are too many bitflips in a page (i.e., ECC error). After setting
1895 * a new threshold, the host should retry reading the page.
1897 static int nand_setup_read_retry(struct mtd_info *mtd, int retry_mode)
1899 struct nand_chip *chip = mtd_to_nand(mtd);
1901 pr_debug("setting READ RETRY mode %d\n", retry_mode);
1903 if (retry_mode >= chip->read_retries)
1906 if (!chip->setup_read_retry)
1909 return chip->setup_read_retry(mtd, retry_mode);
1913 * nand_do_read_ops - [INTERN] Read data with ECC
1914 * @mtd: MTD device structure
1915 * @from: offset to read from
1916 * @ops: oob ops structure
1918 * Internal function. Called with chip held.
1920 static int nand_do_read_ops(struct mtd_info *mtd, loff_t from,
1921 struct mtd_oob_ops *ops)
1923 int chipnr, page, realpage, col, bytes, aligned, oob_required;
1924 struct nand_chip *chip = mtd_to_nand(mtd);
1926 uint32_t readlen = ops->len;
1927 uint32_t oobreadlen = ops->ooblen;
1928 uint32_t max_oobsize = mtd_oobavail(mtd, ops);
1930 uint8_t *bufpoi, *oob, *buf;
1932 unsigned int max_bitflips = 0;
1934 bool ecc_fail = false;
1936 chipnr = (int)(from >> chip->chip_shift);
1937 chip->select_chip(mtd, chipnr);
1939 realpage = (int)(from >> chip->page_shift);
1940 page = realpage & chip->pagemask;
1942 col = (int)(from & (mtd->writesize - 1));
1946 oob_required = oob ? 1 : 0;
1949 unsigned int ecc_failures = mtd->ecc_stats.failed;
1951 bytes = min(mtd->writesize - col, readlen);
1952 aligned = (bytes == mtd->writesize);
1956 else if (chip->options & NAND_USE_BOUNCE_BUFFER)
1957 use_bufpoi = !virt_addr_valid(buf);
1961 /* Is the current page in the buffer? */
1962 if (realpage != chip->pagebuf || oob) {
1963 bufpoi = use_bufpoi ? chip->buffers->databuf : buf;
1965 if (use_bufpoi && aligned)
1966 pr_debug("%s: using read bounce buffer for buf@%p\n",
1970 if (nand_standard_page_accessors(&chip->ecc))
1971 chip->cmdfunc(mtd, NAND_CMD_READ0, 0x00, page);
1974 * Now read the page into the buffer. Absent an error,
1975 * the read methods return max bitflips per ecc step.
1977 if (unlikely(ops->mode == MTD_OPS_RAW))
1978 ret = chip->ecc.read_page_raw(mtd, chip, bufpoi,
1981 else if (!aligned && NAND_HAS_SUBPAGE_READ(chip) &&
1983 ret = chip->ecc.read_subpage(mtd, chip,
1987 ret = chip->ecc.read_page(mtd, chip, bufpoi,
1988 oob_required, page);
1991 /* Invalidate page cache */
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 */
2046 max_bitflips = max_t(unsigned int, max_bitflips, ret);
2048 memcpy(buf, chip->buffers->databuf + col, bytes);
2050 max_bitflips = max_t(unsigned int, max_bitflips,
2051 chip->pagebuf_bitflips);
2056 /* Reset to retry mode 0 */
2058 ret = nand_setup_read_retry(mtd, 0);
2067 /* For subsequent reads align to page boundary */
2069 /* Increment page address */
2072 page = realpage & chip->pagemask;
2073 /* Check, if we cross a chip boundary */
2076 chip->select_chip(mtd, -1);
2077 chip->select_chip(mtd, chipnr);
2080 chip->select_chip(mtd, -1);
2082 ops->retlen = ops->len - (size_t) readlen;
2084 ops->oobretlen = ops->ooblen - oobreadlen;
2092 return max_bitflips;
2096 * nand_read - [MTD Interface] MTD compatibility function for nand_do_read_ecc
2097 * @mtd: MTD device structure
2098 * @from: offset to read from
2099 * @len: number of bytes to read
2100 * @retlen: pointer to variable to store the number of read bytes
2101 * @buf: the databuffer to put data
2103 * Get hold of the chip and call nand_do_read.
2105 static int nand_read(struct mtd_info *mtd, loff_t from, size_t len,
2106 size_t *retlen, uint8_t *buf)
2108 struct mtd_oob_ops ops;
2111 nand_get_device(mtd, FL_READING);
2112 memset(&ops, 0, sizeof(ops));
2115 ops.mode = MTD_OPS_PLACE_OOB;
2116 ret = nand_do_read_ops(mtd, from, &ops);
2117 *retlen = ops.retlen;
2118 nand_release_device(mtd);
2123 * nand_read_oob_std - [REPLACEABLE] the most common OOB data read function
2124 * @mtd: mtd info structure
2125 * @chip: nand chip info structure
2126 * @page: page number to read
2128 int nand_read_oob_std(struct mtd_info *mtd, struct nand_chip *chip, int page)
2130 chip->cmdfunc(mtd, NAND_CMD_READOOB, 0, page);
2131 chip->read_buf(mtd, chip->oob_poi, mtd->oobsize);
2134 EXPORT_SYMBOL(nand_read_oob_std);
2137 * nand_read_oob_syndrome - [REPLACEABLE] OOB data read function for HW ECC
2139 * @mtd: mtd info structure
2140 * @chip: nand chip info structure
2141 * @page: page number to read
2143 int nand_read_oob_syndrome(struct mtd_info *mtd, struct nand_chip *chip,
2146 int length = mtd->oobsize;
2147 int chunk = chip->ecc.bytes + chip->ecc.prepad + chip->ecc.postpad;
2148 int eccsize = chip->ecc.size;
2149 uint8_t *bufpoi = chip->oob_poi;
2150 int i, toread, sndrnd = 0, pos;
2152 chip->cmdfunc(mtd, NAND_CMD_READ0, chip->ecc.size, page);
2153 for (i = 0; i < chip->ecc.steps; i++) {
2155 pos = eccsize + i * (eccsize + chunk);
2156 if (mtd->writesize > 512)
2157 chip->cmdfunc(mtd, NAND_CMD_RNDOUT, pos, -1);
2159 chip->cmdfunc(mtd, NAND_CMD_READ0, pos, page);
2162 toread = min_t(int, length, chunk);
2163 chip->read_buf(mtd, bufpoi, toread);
2168 chip->read_buf(mtd, bufpoi, length);
2172 EXPORT_SYMBOL(nand_read_oob_syndrome);
2175 * nand_write_oob_std - [REPLACEABLE] the most common OOB data write function
2176 * @mtd: mtd info structure
2177 * @chip: nand chip info structure
2178 * @page: page number to write
2180 int nand_write_oob_std(struct mtd_info *mtd, struct nand_chip *chip, int page)
2183 const uint8_t *buf = chip->oob_poi;
2184 int length = mtd->oobsize;
2186 chip->cmdfunc(mtd, NAND_CMD_SEQIN, mtd->writesize, page);
2187 chip->write_buf(mtd, buf, length);
2188 /* Send command to program the OOB data */
2189 chip->cmdfunc(mtd, NAND_CMD_PAGEPROG, -1, -1);
2191 status = chip->waitfunc(mtd, chip);
2193 return status & NAND_STATUS_FAIL ? -EIO : 0;
2195 EXPORT_SYMBOL(nand_write_oob_std);
2198 * nand_write_oob_syndrome - [REPLACEABLE] OOB data write function for HW ECC
2199 * with syndrome - only for large page flash
2200 * @mtd: mtd info structure
2201 * @chip: nand chip info structure
2202 * @page: page number to write
2204 int nand_write_oob_syndrome(struct mtd_info *mtd, struct nand_chip *chip,
2207 int chunk = chip->ecc.bytes + chip->ecc.prepad + chip->ecc.postpad;
2208 int eccsize = chip->ecc.size, length = mtd->oobsize;
2209 int i, len, pos, status = 0, sndcmd = 0, steps = chip->ecc.steps;
2210 const uint8_t *bufpoi = chip->oob_poi;
2213 * data-ecc-data-ecc ... ecc-oob
2215 * data-pad-ecc-pad-data-pad .... ecc-pad-oob
2217 if (!chip->ecc.prepad && !chip->ecc.postpad) {
2218 pos = steps * (eccsize + chunk);
2223 chip->cmdfunc(mtd, NAND_CMD_SEQIN, pos, page);
2224 for (i = 0; i < steps; i++) {
2226 if (mtd->writesize <= 512) {
2227 uint32_t fill = 0xFFFFFFFF;
2231 int num = min_t(int, len, 4);
2232 chip->write_buf(mtd, (uint8_t *)&fill,
2237 pos = eccsize + i * (eccsize + chunk);
2238 chip->cmdfunc(mtd, NAND_CMD_RNDIN, pos, -1);
2242 len = min_t(int, length, chunk);
2243 chip->write_buf(mtd, bufpoi, len);
2248 chip->write_buf(mtd, bufpoi, length);
2250 chip->cmdfunc(mtd, NAND_CMD_PAGEPROG, -1, -1);
2251 status = chip->waitfunc(mtd, chip);
2253 return status & NAND_STATUS_FAIL ? -EIO : 0;
2255 EXPORT_SYMBOL(nand_write_oob_syndrome);
2258 * nand_do_read_oob - [INTERN] NAND read out-of-band
2259 * @mtd: MTD device structure
2260 * @from: offset to read from
2261 * @ops: oob operations description structure
2263 * NAND read out-of-band data from the spare area.
2265 static int nand_do_read_oob(struct mtd_info *mtd, loff_t from,
2266 struct mtd_oob_ops *ops)
2268 int page, realpage, chipnr;
2269 struct nand_chip *chip = mtd_to_nand(mtd);
2270 struct mtd_ecc_stats stats;
2271 int readlen = ops->ooblen;
2273 uint8_t *buf = ops->oobbuf;
2276 pr_debug("%s: from = 0x%08Lx, len = %i\n",
2277 __func__, (unsigned long long)from, readlen);
2279 stats = mtd->ecc_stats;
2281 len = mtd_oobavail(mtd, ops);
2283 if (unlikely(ops->ooboffs >= len)) {
2284 pr_debug("%s: attempt to start read outside oob\n",
2289 /* Do not allow reads past end of device */
2290 if (unlikely(from >= mtd->size ||
2291 ops->ooboffs + readlen > ((mtd->size >> chip->page_shift) -
2292 (from >> chip->page_shift)) * len)) {
2293 pr_debug("%s: attempt to read beyond end of device\n",
2298 chipnr = (int)(from >> chip->chip_shift);
2299 chip->select_chip(mtd, chipnr);
2301 /* Shift to get page */
2302 realpage = (int)(from >> chip->page_shift);
2303 page = realpage & chip->pagemask;
2306 if (ops->mode == MTD_OPS_RAW)
2307 ret = chip->ecc.read_oob_raw(mtd, chip, page);
2309 ret = chip->ecc.read_oob(mtd, chip, page);
2314 len = min(len, readlen);
2315 buf = nand_transfer_oob(mtd, buf, ops, len);
2317 if (chip->options & NAND_NEED_READRDY) {
2318 /* Apply delay or wait for ready/busy pin */
2319 if (!chip->dev_ready)
2320 udelay(chip->chip_delay);
2322 nand_wait_ready(mtd);
2329 /* Increment page address */
2332 page = realpage & chip->pagemask;
2333 /* Check, if we cross a chip boundary */
2336 chip->select_chip(mtd, -1);
2337 chip->select_chip(mtd, chipnr);
2340 chip->select_chip(mtd, -1);
2342 ops->oobretlen = ops->ooblen - readlen;
2347 if (mtd->ecc_stats.failed - stats.failed)
2350 return mtd->ecc_stats.corrected - stats.corrected ? -EUCLEAN : 0;
2354 * nand_read_oob - [MTD Interface] NAND read data and/or out-of-band
2355 * @mtd: MTD device structure
2356 * @from: offset to read from
2357 * @ops: oob operation description structure
2359 * NAND read data and/or out-of-band data.
2361 static int nand_read_oob(struct mtd_info *mtd, loff_t from,
2362 struct mtd_oob_ops *ops)
2368 /* Do not allow reads past end of device */
2369 if (ops->datbuf && (from + ops->len) > mtd->size) {
2370 pr_debug("%s: attempt to read beyond end of device\n",
2375 if (ops->mode != MTD_OPS_PLACE_OOB &&
2376 ops->mode != MTD_OPS_AUTO_OOB &&
2377 ops->mode != MTD_OPS_RAW)
2380 nand_get_device(mtd, FL_READING);
2383 ret = nand_do_read_oob(mtd, from, ops);
2385 ret = nand_do_read_ops(mtd, from, ops);
2387 nand_release_device(mtd);
2393 * nand_write_page_raw - [INTERN] raw page write function
2394 * @mtd: mtd info structure
2395 * @chip: nand chip info structure
2397 * @oob_required: must write chip->oob_poi to OOB
2398 * @page: page number to write
2400 * Not for syndrome calculating ECC controllers, which use a special oob layout.
2402 static int nand_write_page_raw(struct mtd_info *mtd, struct nand_chip *chip,
2403 const uint8_t *buf, int oob_required, int page)
2405 chip->write_buf(mtd, buf, mtd->writesize);
2407 chip->write_buf(mtd, chip->oob_poi, mtd->oobsize);
2413 * nand_write_page_raw_syndrome - [INTERN] raw page write function
2414 * @mtd: mtd info structure
2415 * @chip: nand chip info structure
2417 * @oob_required: must write chip->oob_poi to OOB
2418 * @page: page number to write
2420 * We need a special oob layout and handling even when ECC isn't checked.
2422 static int nand_write_page_raw_syndrome(struct mtd_info *mtd,
2423 struct nand_chip *chip,
2424 const uint8_t *buf, int oob_required,
2427 int eccsize = chip->ecc.size;
2428 int eccbytes = chip->ecc.bytes;
2429 uint8_t *oob = chip->oob_poi;
2432 for (steps = chip->ecc.steps; steps > 0; steps--) {
2433 chip->write_buf(mtd, buf, eccsize);
2436 if (chip->ecc.prepad) {
2437 chip->write_buf(mtd, oob, chip->ecc.prepad);
2438 oob += chip->ecc.prepad;
2441 chip->write_buf(mtd, oob, eccbytes);
2444 if (chip->ecc.postpad) {
2445 chip->write_buf(mtd, oob, chip->ecc.postpad);
2446 oob += chip->ecc.postpad;
2450 size = mtd->oobsize - (oob - chip->oob_poi);
2452 chip->write_buf(mtd, oob, size);
2457 * nand_write_page_swecc - [REPLACEABLE] software ECC based page write function
2458 * @mtd: mtd info structure
2459 * @chip: nand chip info structure
2461 * @oob_required: must write chip->oob_poi to OOB
2462 * @page: page number to write
2464 static int nand_write_page_swecc(struct mtd_info *mtd, struct nand_chip *chip,
2465 const uint8_t *buf, int oob_required,
2468 int i, eccsize = chip->ecc.size, ret;
2469 int eccbytes = chip->ecc.bytes;
2470 int eccsteps = chip->ecc.steps;
2471 uint8_t *ecc_calc = chip->buffers->ecccalc;
2472 const uint8_t *p = buf;
2474 /* Software ECC calculation */
2475 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize)
2476 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
2478 ret = mtd_ooblayout_set_eccbytes(mtd, ecc_calc, chip->oob_poi, 0,
2483 return chip->ecc.write_page_raw(mtd, chip, buf, 1, page);
2487 * nand_write_page_hwecc - [REPLACEABLE] hardware ECC based page write function
2488 * @mtd: mtd info structure
2489 * @chip: nand chip info structure
2491 * @oob_required: must write chip->oob_poi to OOB
2492 * @page: page number to write
2494 static int nand_write_page_hwecc(struct mtd_info *mtd, struct nand_chip *chip,
2495 const uint8_t *buf, int oob_required,
2498 int i, eccsize = chip->ecc.size, ret;
2499 int eccbytes = chip->ecc.bytes;
2500 int eccsteps = chip->ecc.steps;
2501 uint8_t *ecc_calc = chip->buffers->ecccalc;
2502 const uint8_t *p = buf;
2504 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
2505 chip->ecc.hwctl(mtd, NAND_ECC_WRITE);
2506 chip->write_buf(mtd, p, eccsize);
2507 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
2510 ret = mtd_ooblayout_set_eccbytes(mtd, ecc_calc, chip->oob_poi, 0,
2515 chip->write_buf(mtd, chip->oob_poi, mtd->oobsize);
2522 * nand_write_subpage_hwecc - [REPLACEABLE] hardware ECC based subpage write
2523 * @mtd: mtd info structure
2524 * @chip: nand chip info structure
2525 * @offset: column address of subpage within the page
2526 * @data_len: data length
2528 * @oob_required: must write chip->oob_poi to OOB
2529 * @page: page number to write
2531 static int nand_write_subpage_hwecc(struct mtd_info *mtd,
2532 struct nand_chip *chip, uint32_t offset,
2533 uint32_t data_len, const uint8_t *buf,
2534 int oob_required, int page)
2536 uint8_t *oob_buf = chip->oob_poi;
2537 uint8_t *ecc_calc = chip->buffers->ecccalc;
2538 int ecc_size = chip->ecc.size;
2539 int ecc_bytes = chip->ecc.bytes;
2540 int ecc_steps = chip->ecc.steps;
2541 uint32_t start_step = offset / ecc_size;
2542 uint32_t end_step = (offset + data_len - 1) / ecc_size;
2543 int oob_bytes = mtd->oobsize / ecc_steps;
2546 for (step = 0; step < ecc_steps; step++) {
2547 /* configure controller for WRITE access */
2548 chip->ecc.hwctl(mtd, NAND_ECC_WRITE);
2550 /* write data (untouched subpages already masked by 0xFF) */
2551 chip->write_buf(mtd, buf, ecc_size);
2553 /* mask ECC of un-touched subpages by padding 0xFF */
2554 if ((step < start_step) || (step > end_step))
2555 memset(ecc_calc, 0xff, ecc_bytes);
2557 chip->ecc.calculate(mtd, buf, ecc_calc);
2559 /* mask OOB of un-touched subpages by padding 0xFF */
2560 /* if oob_required, preserve OOB metadata of written subpage */
2561 if (!oob_required || (step < start_step) || (step > end_step))
2562 memset(oob_buf, 0xff, oob_bytes);
2565 ecc_calc += ecc_bytes;
2566 oob_buf += oob_bytes;
2569 /* copy calculated ECC for whole page to chip->buffer->oob */
2570 /* this include masked-value(0xFF) for unwritten subpages */
2571 ecc_calc = chip->buffers->ecccalc;
2572 ret = mtd_ooblayout_set_eccbytes(mtd, ecc_calc, chip->oob_poi, 0,
2577 /* write OOB buffer to NAND device */
2578 chip->write_buf(mtd, chip->oob_poi, mtd->oobsize);
2585 * nand_write_page_syndrome - [REPLACEABLE] hardware ECC syndrome based page write
2586 * @mtd: mtd info structure
2587 * @chip: nand chip info structure
2589 * @oob_required: must write chip->oob_poi to OOB
2590 * @page: page number to write
2592 * The hw generator calculates the error syndrome automatically. Therefore we
2593 * need a special oob layout and handling.
2595 static int nand_write_page_syndrome(struct mtd_info *mtd,
2596 struct nand_chip *chip,
2597 const uint8_t *buf, int oob_required,
2600 int i, eccsize = chip->ecc.size;
2601 int eccbytes = chip->ecc.bytes;
2602 int eccsteps = chip->ecc.steps;
2603 const uint8_t *p = buf;
2604 uint8_t *oob = chip->oob_poi;
2606 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
2608 chip->ecc.hwctl(mtd, NAND_ECC_WRITE);
2609 chip->write_buf(mtd, p, eccsize);
2611 if (chip->ecc.prepad) {
2612 chip->write_buf(mtd, oob, chip->ecc.prepad);
2613 oob += chip->ecc.prepad;
2616 chip->ecc.calculate(mtd, p, oob);
2617 chip->write_buf(mtd, oob, eccbytes);
2620 if (chip->ecc.postpad) {
2621 chip->write_buf(mtd, oob, chip->ecc.postpad);
2622 oob += chip->ecc.postpad;
2626 /* Calculate remaining oob bytes */
2627 i = mtd->oobsize - (oob - chip->oob_poi);
2629 chip->write_buf(mtd, oob, i);
2635 * nand_write_page - write one page
2636 * @mtd: MTD device structure
2637 * @chip: NAND chip descriptor
2638 * @offset: address offset within the page
2639 * @data_len: length of actual data to be written
2640 * @buf: the data to write
2641 * @oob_required: must write chip->oob_poi to OOB
2642 * @page: page number to write
2643 * @cached: cached programming
2644 * @raw: use _raw version of write_page
2646 static int nand_write_page(struct mtd_info *mtd, struct nand_chip *chip,
2647 uint32_t offset, int data_len, const uint8_t *buf,
2648 int oob_required, int page, int cached, int raw)
2650 int status, subpage;
2652 if (!(chip->options & NAND_NO_SUBPAGE_WRITE) &&
2653 chip->ecc.write_subpage)
2654 subpage = offset || (data_len < mtd->writesize);
2658 if (nand_standard_page_accessors(&chip->ecc))
2659 chip->cmdfunc(mtd, NAND_CMD_SEQIN, 0x00, page);
2662 status = chip->ecc.write_page_raw(mtd, chip, buf,
2663 oob_required, page);
2665 status = chip->ecc.write_subpage(mtd, chip, offset, data_len,
2666 buf, oob_required, page);
2668 status = chip->ecc.write_page(mtd, chip, buf, oob_required,
2675 * Cached progamming disabled for now. Not sure if it's worth the
2676 * trouble. The speed gain is not very impressive. (2.3->2.6Mib/s).
2680 if (!cached || !NAND_HAS_CACHEPROG(chip)) {
2682 if (nand_standard_page_accessors(&chip->ecc))
2683 chip->cmdfunc(mtd, NAND_CMD_PAGEPROG, -1, -1);
2684 status = chip->waitfunc(mtd, chip);
2686 * See if operation failed and additional status checks are
2689 if ((status & NAND_STATUS_FAIL) && (chip->errstat))
2690 status = chip->errstat(mtd, chip, FL_WRITING, status,
2693 if (status & NAND_STATUS_FAIL)
2696 chip->cmdfunc(mtd, NAND_CMD_CACHEDPROG, -1, -1);
2697 status = chip->waitfunc(mtd, chip);
2704 * nand_fill_oob - [INTERN] Transfer client buffer to oob
2705 * @mtd: MTD device structure
2706 * @oob: oob data buffer
2707 * @len: oob data write length
2708 * @ops: oob ops structure
2710 static uint8_t *nand_fill_oob(struct mtd_info *mtd, uint8_t *oob, size_t len,
2711 struct mtd_oob_ops *ops)
2713 struct nand_chip *chip = mtd_to_nand(mtd);
2717 * Initialise to all 0xFF, to avoid the possibility of left over OOB
2718 * data from a previous OOB read.
2720 memset(chip->oob_poi, 0xff, mtd->oobsize);
2722 switch (ops->mode) {
2724 case MTD_OPS_PLACE_OOB:
2726 memcpy(chip->oob_poi + ops->ooboffs, oob, len);
2729 case MTD_OPS_AUTO_OOB:
2730 ret = mtd_ooblayout_set_databytes(mtd, oob, chip->oob_poi,
2741 #define NOTALIGNED(x) ((x & (chip->subpagesize - 1)) != 0)
2744 * nand_do_write_ops - [INTERN] NAND write with ECC
2745 * @mtd: MTD device structure
2746 * @to: offset to write to
2747 * @ops: oob operations description structure
2749 * NAND write with ECC.
2751 static int nand_do_write_ops(struct mtd_info *mtd, loff_t to,
2752 struct mtd_oob_ops *ops)
2754 int chipnr, realpage, page, blockmask, column;
2755 struct nand_chip *chip = mtd_to_nand(mtd);
2756 uint32_t writelen = ops->len;
2758 uint32_t oobwritelen = ops->ooblen;
2759 uint32_t oobmaxlen = mtd_oobavail(mtd, ops);
2761 uint8_t *oob = ops->oobbuf;
2762 uint8_t *buf = ops->datbuf;
2764 int oob_required = oob ? 1 : 0;
2770 /* Reject writes, which are not page aligned */
2771 if (NOTALIGNED(to) || NOTALIGNED(ops->len)) {
2772 pr_notice("%s: attempt to write non page aligned data\n",
2777 column = to & (mtd->writesize - 1);
2779 chipnr = (int)(to >> chip->chip_shift);
2780 chip->select_chip(mtd, chipnr);
2782 /* Check, if it is write protected */
2783 if (nand_check_wp(mtd)) {
2788 realpage = (int)(to >> chip->page_shift);
2789 page = realpage & chip->pagemask;
2790 blockmask = (1 << (chip->phys_erase_shift - chip->page_shift)) - 1;
2792 /* Invalidate the page cache, when we write to the cached page */
2793 if (to <= ((loff_t)chip->pagebuf << chip->page_shift) &&
2794 ((loff_t)chip->pagebuf << chip->page_shift) < (to + ops->len))
2797 /* Don't allow multipage oob writes with offset */
2798 if (oob && ops->ooboffs && (ops->ooboffs + ops->ooblen > oobmaxlen)) {
2804 int bytes = mtd->writesize;
2805 int cached = writelen > bytes && page != blockmask;
2806 uint8_t *wbuf = buf;
2808 int part_pagewr = (column || writelen < mtd->writesize);
2812 else if (chip->options & NAND_USE_BOUNCE_BUFFER)
2813 use_bufpoi = !virt_addr_valid(buf);
2817 /* Partial page write?, or need to use bounce buffer */
2819 pr_debug("%s: using write bounce buffer for buf@%p\n",
2823 bytes = min_t(int, bytes - column, writelen);
2825 memset(chip->buffers->databuf, 0xff, mtd->writesize);
2826 memcpy(&chip->buffers->databuf[column], buf, bytes);
2827 wbuf = chip->buffers->databuf;
2830 if (unlikely(oob)) {
2831 size_t len = min(oobwritelen, oobmaxlen);
2832 oob = nand_fill_oob(mtd, oob, len, ops);
2835 /* We still need to erase leftover OOB data */
2836 memset(chip->oob_poi, 0xff, mtd->oobsize);
2839 ret = nand_write_page(mtd, chip, column, bytes, wbuf,
2840 oob_required, page, cached,
2841 (ops->mode == MTD_OPS_RAW));
2853 page = realpage & chip->pagemask;
2854 /* Check, if we cross a chip boundary */
2857 chip->select_chip(mtd, -1);
2858 chip->select_chip(mtd, chipnr);
2862 ops->retlen = ops->len - writelen;
2864 ops->oobretlen = ops->ooblen;
2867 chip->select_chip(mtd, -1);
2872 * panic_nand_write - [MTD Interface] NAND write with ECC
2873 * @mtd: MTD device structure
2874 * @to: offset to write to
2875 * @len: number of bytes to write
2876 * @retlen: pointer to variable to store the number of written bytes
2877 * @buf: the data to write
2879 * NAND write with ECC. Used when performing writes in interrupt context, this
2880 * may for example be called by mtdoops when writing an oops while in panic.
2882 static int panic_nand_write(struct mtd_info *mtd, loff_t to, size_t len,
2883 size_t *retlen, const uint8_t *buf)
2885 struct nand_chip *chip = mtd_to_nand(mtd);
2886 struct mtd_oob_ops ops;
2889 /* Wait for the device to get ready */
2890 panic_nand_wait(mtd, chip, 400);
2892 /* Grab the device */
2893 panic_nand_get_device(chip, mtd, FL_WRITING);
2895 memset(&ops, 0, sizeof(ops));
2897 ops.datbuf = (uint8_t *)buf;
2898 ops.mode = MTD_OPS_PLACE_OOB;
2900 ret = nand_do_write_ops(mtd, to, &ops);
2902 *retlen = ops.retlen;
2907 * nand_write - [MTD Interface] NAND write with ECC
2908 * @mtd: MTD device structure
2909 * @to: offset to write to
2910 * @len: number of bytes to write
2911 * @retlen: pointer to variable to store the number of written bytes
2912 * @buf: the data to write
2914 * NAND write with ECC.
2916 static int nand_write(struct mtd_info *mtd, loff_t to, size_t len,
2917 size_t *retlen, const uint8_t *buf)
2919 struct mtd_oob_ops ops;
2922 nand_get_device(mtd, FL_WRITING);
2923 memset(&ops, 0, sizeof(ops));
2925 ops.datbuf = (uint8_t *)buf;
2926 ops.mode = MTD_OPS_PLACE_OOB;
2927 ret = nand_do_write_ops(mtd, to, &ops);
2928 *retlen = ops.retlen;
2929 nand_release_device(mtd);
2934 * nand_do_write_oob - [MTD Interface] NAND write out-of-band
2935 * @mtd: MTD device structure
2936 * @to: offset to write to
2937 * @ops: oob operation description structure
2939 * NAND write out-of-band.
2941 static int nand_do_write_oob(struct mtd_info *mtd, loff_t to,
2942 struct mtd_oob_ops *ops)
2944 int chipnr, page, status, len;
2945 struct nand_chip *chip = mtd_to_nand(mtd);
2947 pr_debug("%s: to = 0x%08x, len = %i\n",
2948 __func__, (unsigned int)to, (int)ops->ooblen);
2950 len = mtd_oobavail(mtd, ops);
2952 /* Do not allow write past end of page */
2953 if ((ops->ooboffs + ops->ooblen) > len) {
2954 pr_debug("%s: attempt to write past end of page\n",
2959 if (unlikely(ops->ooboffs >= len)) {
2960 pr_debug("%s: attempt to start write outside oob\n",
2965 /* Do not allow write past end of device */
2966 if (unlikely(to >= mtd->size ||
2967 ops->ooboffs + ops->ooblen >
2968 ((mtd->size >> chip->page_shift) -
2969 (to >> chip->page_shift)) * len)) {
2970 pr_debug("%s: attempt to write beyond end of device\n",
2975 chipnr = (int)(to >> chip->chip_shift);
2978 * Reset the chip. Some chips (like the Toshiba TC5832DC found in one
2979 * of my DiskOnChip 2000 test units) will clear the whole data page too
2980 * if we don't do this. I have no clue why, but I seem to have 'fixed'
2981 * it in the doc2000 driver in August 1999. dwmw2.
2983 nand_reset(chip, chipnr);
2985 chip->select_chip(mtd, chipnr);
2987 /* Shift to get page */
2988 page = (int)(to >> chip->page_shift);
2990 /* Check, if it is write protected */
2991 if (nand_check_wp(mtd)) {
2992 chip->select_chip(mtd, -1);
2996 /* Invalidate the page cache, if we write to the cached page */
2997 if (page == chip->pagebuf)
3000 nand_fill_oob(mtd, ops->oobbuf, ops->ooblen, ops);
3002 if (ops->mode == MTD_OPS_RAW)
3003 status = chip->ecc.write_oob_raw(mtd, chip, page & chip->pagemask);
3005 status = chip->ecc.write_oob(mtd, chip, page & chip->pagemask);
3007 chip->select_chip(mtd, -1);
3012 ops->oobretlen = ops->ooblen;
3018 * nand_write_oob - [MTD Interface] NAND write data and/or out-of-band
3019 * @mtd: MTD device structure
3020 * @to: offset to write to
3021 * @ops: oob operation description structure
3023 static int nand_write_oob(struct mtd_info *mtd, loff_t to,
3024 struct mtd_oob_ops *ops)
3026 int ret = -ENOTSUPP;
3030 /* Do not allow writes past end of device */
3031 if (ops->datbuf && (to + ops->len) > mtd->size) {
3032 pr_debug("%s: attempt to write beyond end of device\n",
3037 nand_get_device(mtd, FL_WRITING);
3039 switch (ops->mode) {
3040 case MTD_OPS_PLACE_OOB:
3041 case MTD_OPS_AUTO_OOB:
3050 ret = nand_do_write_oob(mtd, to, ops);
3052 ret = nand_do_write_ops(mtd, to, ops);
3055 nand_release_device(mtd);
3060 * single_erase - [GENERIC] NAND standard block erase command function
3061 * @mtd: MTD device structure
3062 * @page: the page address of the block which will be erased
3064 * Standard erase command for NAND chips. Returns NAND status.
3066 static int single_erase(struct mtd_info *mtd, int page)
3068 struct nand_chip *chip = mtd_to_nand(mtd);
3069 /* Send commands to erase a block */
3070 chip->cmdfunc(mtd, NAND_CMD_ERASE1, -1, page);
3071 chip->cmdfunc(mtd, NAND_CMD_ERASE2, -1, -1);
3073 return chip->waitfunc(mtd, chip);
3077 * nand_erase - [MTD Interface] erase block(s)
3078 * @mtd: MTD device structure
3079 * @instr: erase instruction
3081 * Erase one ore more blocks.
3083 static int nand_erase(struct mtd_info *mtd, struct erase_info *instr)
3085 return nand_erase_nand(mtd, instr, 0);
3089 * nand_erase_nand - [INTERN] erase block(s)
3090 * @mtd: MTD device structure
3091 * @instr: erase instruction
3092 * @allowbbt: allow erasing the bbt area
3094 * Erase one ore more blocks.
3096 int nand_erase_nand(struct mtd_info *mtd, struct erase_info *instr,
3099 int page, status, pages_per_block, ret, chipnr;
3100 struct nand_chip *chip = mtd_to_nand(mtd);
3103 pr_debug("%s: start = 0x%012llx, len = %llu\n",
3104 __func__, (unsigned long long)instr->addr,
3105 (unsigned long long)instr->len);
3107 if (check_offs_len(mtd, instr->addr, instr->len))
3110 /* Grab the lock and see if the device is available */
3111 nand_get_device(mtd, FL_ERASING);
3113 /* Shift to get first page */
3114 page = (int)(instr->addr >> chip->page_shift);
3115 chipnr = (int)(instr->addr >> chip->chip_shift);
3117 /* Calculate pages in each block */
3118 pages_per_block = 1 << (chip->phys_erase_shift - chip->page_shift);
3120 /* Select the NAND device */
3121 chip->select_chip(mtd, chipnr);
3123 /* Check, if it is write protected */
3124 if (nand_check_wp(mtd)) {
3125 pr_debug("%s: device is write protected!\n",
3127 instr->state = MTD_ERASE_FAILED;
3131 /* Loop through the pages */
3134 instr->state = MTD_ERASING;
3137 /* Check if we have a bad block, we do not erase bad blocks! */
3138 if (nand_block_checkbad(mtd, ((loff_t) page) <<
3139 chip->page_shift, allowbbt)) {
3140 pr_warn("%s: attempt to erase a bad block at page 0x%08x\n",
3142 instr->state = MTD_ERASE_FAILED;
3147 * Invalidate the page cache, if we erase the block which
3148 * contains the current cached page.
3150 if (page <= chip->pagebuf && chip->pagebuf <
3151 (page + pages_per_block))
3154 status = chip->erase(mtd, page & chip->pagemask);
3157 * See if operation failed and additional status checks are
3160 if ((status & NAND_STATUS_FAIL) && (chip->errstat))
3161 status = chip->errstat(mtd, chip, FL_ERASING,
3164 /* See if block erase succeeded */
3165 if (status & NAND_STATUS_FAIL) {
3166 pr_debug("%s: failed erase, page 0x%08x\n",
3168 instr->state = MTD_ERASE_FAILED;
3170 ((loff_t)page << chip->page_shift);
3174 /* Increment page address and decrement length */
3175 len -= (1ULL << chip->phys_erase_shift);
3176 page += pages_per_block;
3178 /* Check, if we cross a chip boundary */
3179 if (len && !(page & chip->pagemask)) {
3181 chip->select_chip(mtd, -1);
3182 chip->select_chip(mtd, chipnr);
3185 instr->state = MTD_ERASE_DONE;
3189 ret = instr->state == MTD_ERASE_DONE ? 0 : -EIO;
3191 /* Deselect and wake up anyone waiting on the device */
3192 chip->select_chip(mtd, -1);
3193 nand_release_device(mtd);
3195 /* Do call back function */
3197 mtd_erase_callback(instr);
3199 /* Return more or less happy */
3204 * nand_sync - [MTD Interface] sync
3205 * @mtd: MTD device structure
3207 * Sync is actually a wait for chip ready function.
3209 static void nand_sync(struct mtd_info *mtd)
3211 pr_debug("%s: called\n", __func__);
3213 /* Grab the lock and see if the device is available */
3214 nand_get_device(mtd, FL_SYNCING);
3215 /* Release it and go back */
3216 nand_release_device(mtd);
3220 * nand_block_isbad - [MTD Interface] Check if block at offset is bad
3221 * @mtd: MTD device structure
3222 * @offs: offset relative to mtd start
3224 static int nand_block_isbad(struct mtd_info *mtd, loff_t offs)
3226 struct nand_chip *chip = mtd_to_nand(mtd);
3227 int chipnr = (int)(offs >> chip->chip_shift);
3230 /* Select the NAND device */
3231 nand_get_device(mtd, FL_READING);
3232 chip->select_chip(mtd, chipnr);
3234 ret = nand_block_checkbad(mtd, offs, 0);
3236 chip->select_chip(mtd, -1);
3237 nand_release_device(mtd);
3243 * nand_block_markbad - [MTD Interface] Mark block at the given offset as bad
3244 * @mtd: MTD device structure
3245 * @ofs: offset relative to mtd start
3247 static int nand_block_markbad(struct mtd_info *mtd, loff_t ofs)
3251 ret = nand_block_isbad(mtd, ofs);
3253 /* If it was bad already, return success and do nothing */
3259 return nand_block_markbad_lowlevel(mtd, ofs);
3263 * nand_max_bad_blocks - [MTD Interface] Max number of bad blocks for an mtd
3264 * @mtd: MTD device structure
3265 * @ofs: offset relative to mtd start
3266 * @len: length of mtd
3268 static int nand_max_bad_blocks(struct mtd_info *mtd, loff_t ofs, size_t len)
3270 struct nand_chip *chip = mtd_to_nand(mtd);
3271 u32 part_start_block;
3277 * max_bb_per_die and blocks_per_die used to determine
3278 * the maximum bad block count.
3280 if (!chip->max_bb_per_die || !chip->blocks_per_die)
3283 /* Get the start and end of the partition in erase blocks. */
3284 part_start_block = mtd_div_by_eb(ofs, mtd);
3285 part_end_block = mtd_div_by_eb(len, mtd) + part_start_block - 1;
3287 /* Get the start and end LUNs of the partition. */
3288 part_start_die = part_start_block / chip->blocks_per_die;
3289 part_end_die = part_end_block / chip->blocks_per_die;
3292 * Look up the bad blocks per unit and multiply by the number of units
3293 * that the partition spans.
3295 return chip->max_bb_per_die * (part_end_die - part_start_die + 1);
3299 * nand_onfi_set_features- [REPLACEABLE] set features for ONFI nand
3300 * @mtd: MTD device structure
3301 * @chip: nand chip info structure
3302 * @addr: feature address.
3303 * @subfeature_param: the subfeature parameters, a four bytes array.
3305 static int nand_onfi_set_features(struct mtd_info *mtd, struct nand_chip *chip,
3306 int addr, uint8_t *subfeature_param)
3311 if (!chip->onfi_version ||
3312 !(le16_to_cpu(chip->onfi_params.opt_cmd)
3313 & ONFI_OPT_CMD_SET_GET_FEATURES))
3316 chip->cmdfunc(mtd, NAND_CMD_SET_FEATURES, addr, -1);
3317 for (i = 0; i < ONFI_SUBFEATURE_PARAM_LEN; ++i)
3318 chip->write_byte(mtd, subfeature_param[i]);
3320 status = chip->waitfunc(mtd, chip);
3321 if (status & NAND_STATUS_FAIL)
3327 * nand_onfi_get_features- [REPLACEABLE] get features for ONFI nand
3328 * @mtd: MTD device structure
3329 * @chip: nand chip info structure
3330 * @addr: feature address.
3331 * @subfeature_param: the subfeature parameters, a four bytes array.
3333 static int nand_onfi_get_features(struct mtd_info *mtd, struct nand_chip *chip,
3334 int addr, uint8_t *subfeature_param)
3338 if (!chip->onfi_version ||
3339 !(le16_to_cpu(chip->onfi_params.opt_cmd)
3340 & ONFI_OPT_CMD_SET_GET_FEATURES))
3343 chip->cmdfunc(mtd, NAND_CMD_GET_FEATURES, addr, -1);
3344 for (i = 0; i < ONFI_SUBFEATURE_PARAM_LEN; ++i)
3345 *subfeature_param++ = chip->read_byte(mtd);
3350 * nand_suspend - [MTD Interface] Suspend the NAND flash
3351 * @mtd: MTD device structure
3353 static int nand_suspend(struct mtd_info *mtd)
3355 return nand_get_device(mtd, FL_PM_SUSPENDED);
3359 * nand_resume - [MTD Interface] Resume the NAND flash
3360 * @mtd: MTD device structure
3362 static void nand_resume(struct mtd_info *mtd)
3364 struct nand_chip *chip = mtd_to_nand(mtd);
3366 if (chip->state == FL_PM_SUSPENDED)
3367 nand_release_device(mtd);
3369 pr_err("%s called for a chip which is not in suspended state\n",
3374 * nand_shutdown - [MTD Interface] Finish the current NAND operation and
3375 * prevent further operations
3376 * @mtd: MTD device structure
3378 static void nand_shutdown(struct mtd_info *mtd)
3380 nand_get_device(mtd, FL_PM_SUSPENDED);
3383 /* Set default functions */
3384 static void nand_set_defaults(struct nand_chip *chip)
3386 unsigned int busw = chip->options & NAND_BUSWIDTH_16;
3388 /* check for proper chip_delay setup, set 20us if not */
3389 if (!chip->chip_delay)
3390 chip->chip_delay = 20;
3392 /* check, if a user supplied command function given */
3393 if (chip->cmdfunc == NULL)
3394 chip->cmdfunc = nand_command;
3396 /* check, if a user supplied wait function given */
3397 if (chip->waitfunc == NULL)
3398 chip->waitfunc = nand_wait;
3400 if (!chip->select_chip)
3401 chip->select_chip = nand_select_chip;
3403 /* set for ONFI nand */
3404 if (!chip->onfi_set_features)
3405 chip->onfi_set_features = nand_onfi_set_features;
3406 if (!chip->onfi_get_features)
3407 chip->onfi_get_features = nand_onfi_get_features;
3409 /* If called twice, pointers that depend on busw may need to be reset */
3410 if (!chip->read_byte || chip->read_byte == nand_read_byte)
3411 chip->read_byte = busw ? nand_read_byte16 : nand_read_byte;
3412 if (!chip->read_word)
3413 chip->read_word = nand_read_word;
3414 if (!chip->block_bad)
3415 chip->block_bad = nand_block_bad;
3416 if (!chip->block_markbad)
3417 chip->block_markbad = nand_default_block_markbad;
3418 if (!chip->write_buf || chip->write_buf == nand_write_buf)
3419 chip->write_buf = busw ? nand_write_buf16 : nand_write_buf;
3420 if (!chip->write_byte || chip->write_byte == nand_write_byte)
3421 chip->write_byte = busw ? nand_write_byte16 : nand_write_byte;
3422 if (!chip->read_buf || chip->read_buf == nand_read_buf)
3423 chip->read_buf = busw ? nand_read_buf16 : nand_read_buf;
3424 if (!chip->scan_bbt)
3425 chip->scan_bbt = nand_default_bbt;
3427 if (!chip->controller) {
3428 chip->controller = &chip->hwcontrol;
3429 nand_hw_control_init(chip->controller);
3434 /* Sanitize ONFI strings so we can safely print them */
3435 static void sanitize_string(uint8_t *s, size_t len)
3439 /* Null terminate */
3442 /* Remove non printable chars */
3443 for (i = 0; i < len - 1; i++) {
3444 if (s[i] < ' ' || s[i] > 127)
3448 /* Remove trailing spaces */
3452 static u16 onfi_crc16(u16 crc, u8 const *p, size_t len)
3457 for (i = 0; i < 8; i++)
3458 crc = (crc << 1) ^ ((crc & 0x8000) ? 0x8005 : 0);
3464 /* Parse the Extended Parameter Page. */
3465 static int nand_flash_detect_ext_param_page(struct nand_chip *chip,
3466 struct nand_onfi_params *p)
3468 struct mtd_info *mtd = nand_to_mtd(chip);
3469 struct onfi_ext_param_page *ep;
3470 struct onfi_ext_section *s;
3471 struct onfi_ext_ecc_info *ecc;
3477 len = le16_to_cpu(p->ext_param_page_length) * 16;
3478 ep = kmalloc(len, GFP_KERNEL);
3482 /* Send our own NAND_CMD_PARAM. */
3483 chip->cmdfunc(mtd, NAND_CMD_PARAM, 0, -1);
3485 /* Use the Change Read Column command to skip the ONFI param pages. */
3486 chip->cmdfunc(mtd, NAND_CMD_RNDOUT,
3487 sizeof(*p) * p->num_of_param_pages , -1);
3489 /* Read out the Extended Parameter Page. */
3490 chip->read_buf(mtd, (uint8_t *)ep, len);
3491 if ((onfi_crc16(ONFI_CRC_BASE, ((uint8_t *)ep) + 2, len - 2)
3492 != le16_to_cpu(ep->crc))) {
3493 pr_debug("fail in the CRC.\n");
3498 * Check the signature.
3499 * Do not strictly follow the ONFI spec, maybe changed in future.
3501 if (strncmp(ep->sig, "EPPS", 4)) {
3502 pr_debug("The signature is invalid.\n");
3506 /* find the ECC section. */
3507 cursor = (uint8_t *)(ep + 1);
3508 for (i = 0; i < ONFI_EXT_SECTION_MAX; i++) {
3509 s = ep->sections + i;
3510 if (s->type == ONFI_SECTION_TYPE_2)
3512 cursor += s->length * 16;
3514 if (i == ONFI_EXT_SECTION_MAX) {
3515 pr_debug("We can not find the ECC section.\n");
3519 /* get the info we want. */
3520 ecc = (struct onfi_ext_ecc_info *)cursor;
3522 if (!ecc->codeword_size) {
3523 pr_debug("Invalid codeword size\n");
3527 chip->ecc_strength_ds = ecc->ecc_bits;
3528 chip->ecc_step_ds = 1 << ecc->codeword_size;
3537 * Check if the NAND chip is ONFI compliant, returns 1 if it is, 0 otherwise.
3539 static int nand_flash_detect_onfi(struct nand_chip *chip)
3541 struct mtd_info *mtd = nand_to_mtd(chip);
3542 struct nand_onfi_params *p = &chip->onfi_params;
3546 /* Try ONFI for unknown chip or LP */
3547 chip->cmdfunc(mtd, NAND_CMD_READID, 0x20, -1);
3548 if (chip->read_byte(mtd) != 'O' || chip->read_byte(mtd) != 'N' ||
3549 chip->read_byte(mtd) != 'F' || chip->read_byte(mtd) != 'I')
3552 chip->cmdfunc(mtd, NAND_CMD_PARAM, 0, -1);
3553 for (i = 0; i < 3; i++) {
3554 for (j = 0; j < sizeof(*p); j++)
3555 ((uint8_t *)p)[j] = chip->read_byte(mtd);
3556 if (onfi_crc16(ONFI_CRC_BASE, (uint8_t *)p, 254) ==
3557 le16_to_cpu(p->crc)) {
3563 pr_err("Could not find valid ONFI parameter page; aborting\n");
3568 val = le16_to_cpu(p->revision);
3570 chip->onfi_version = 23;
3571 else if (val & (1 << 4))
3572 chip->onfi_version = 22;
3573 else if (val & (1 << 3))
3574 chip->onfi_version = 21;
3575 else if (val & (1 << 2))
3576 chip->onfi_version = 20;
3577 else if (val & (1 << 1))
3578 chip->onfi_version = 10;
3580 if (!chip->onfi_version) {
3581 pr_info("unsupported ONFI version: %d\n", val);
3585 sanitize_string(p->manufacturer, sizeof(p->manufacturer));
3586 sanitize_string(p->model, sizeof(p->model));
3588 mtd->name = p->model;
3590 mtd->writesize = le32_to_cpu(p->byte_per_page);
3593 * pages_per_block and blocks_per_lun may not be a power-of-2 size
3594 * (don't ask me who thought of this...). MTD assumes that these
3595 * dimensions will be power-of-2, so just truncate the remaining area.
3597 mtd->erasesize = 1 << (fls(le32_to_cpu(p->pages_per_block)) - 1);
3598 mtd->erasesize *= mtd->writesize;
3600 mtd->oobsize = le16_to_cpu(p->spare_bytes_per_page);
3602 /* See erasesize comment */
3603 chip->chipsize = 1 << (fls(le32_to_cpu(p->blocks_per_lun)) - 1);
3604 chip->chipsize *= (uint64_t)mtd->erasesize * p->lun_count;
3605 chip->bits_per_cell = p->bits_per_cell;
3607 chip->max_bb_per_die = le16_to_cpu(p->bb_per_lun);
3608 chip->blocks_per_die = le32_to_cpu(p->blocks_per_lun);
3610 if (onfi_feature(chip) & ONFI_FEATURE_16_BIT_BUS)
3611 chip->options |= NAND_BUSWIDTH_16;
3613 if (p->ecc_bits != 0xff) {
3614 chip->ecc_strength_ds = p->ecc_bits;
3615 chip->ecc_step_ds = 512;
3616 } else if (chip->onfi_version >= 21 &&
3617 (onfi_feature(chip) & ONFI_FEATURE_EXT_PARAM_PAGE)) {
3620 * The nand_flash_detect_ext_param_page() uses the
3621 * Change Read Column command which maybe not supported
3622 * by the chip->cmdfunc. So try to update the chip->cmdfunc
3623 * now. We do not replace user supplied command function.
3625 if (mtd->writesize > 512 && chip->cmdfunc == nand_command)
3626 chip->cmdfunc = nand_command_lp;
3628 /* The Extended Parameter Page is supported since ONFI 2.1. */
3629 if (nand_flash_detect_ext_param_page(chip, p))
3630 pr_warn("Failed to detect ONFI extended param page\n");
3632 pr_warn("Could not retrieve ONFI ECC requirements\n");
3639 * Check if the NAND chip is JEDEC compliant, returns 1 if it is, 0 otherwise.
3641 static int nand_flash_detect_jedec(struct nand_chip *chip)
3643 struct mtd_info *mtd = nand_to_mtd(chip);
3644 struct nand_jedec_params *p = &chip->jedec_params;
3645 struct jedec_ecc_info *ecc;
3649 /* Try JEDEC for unknown chip or LP */
3650 chip->cmdfunc(mtd, NAND_CMD_READID, 0x40, -1);
3651 if (chip->read_byte(mtd) != 'J' || chip->read_byte(mtd) != 'E' ||
3652 chip->read_byte(mtd) != 'D' || chip->read_byte(mtd) != 'E' ||
3653 chip->read_byte(mtd) != 'C')
3656 chip->cmdfunc(mtd, NAND_CMD_PARAM, 0x40, -1);
3657 for (i = 0; i < 3; i++) {
3658 for (j = 0; j < sizeof(*p); j++)
3659 ((uint8_t *)p)[j] = chip->read_byte(mtd);
3661 if (onfi_crc16(ONFI_CRC_BASE, (uint8_t *)p, 510) ==
3662 le16_to_cpu(p->crc))
3667 pr_err("Could not find valid JEDEC parameter page; aborting\n");
3672 val = le16_to_cpu(p->revision);
3674 chip->jedec_version = 10;
3675 else if (val & (1 << 1))
3676 chip->jedec_version = 1; /* vendor specific version */
3678 if (!chip->jedec_version) {
3679 pr_info("unsupported JEDEC version: %d\n", val);
3683 sanitize_string(p->manufacturer, sizeof(p->manufacturer));
3684 sanitize_string(p->model, sizeof(p->model));
3686 mtd->name = p->model;
3688 mtd->writesize = le32_to_cpu(p->byte_per_page);
3690 /* Please reference to the comment for nand_flash_detect_onfi. */
3691 mtd->erasesize = 1 << (fls(le32_to_cpu(p->pages_per_block)) - 1);
3692 mtd->erasesize *= mtd->writesize;
3694 mtd->oobsize = le16_to_cpu(p->spare_bytes_per_page);
3696 /* Please reference to the comment for nand_flash_detect_onfi. */
3697 chip->chipsize = 1 << (fls(le32_to_cpu(p->blocks_per_lun)) - 1);
3698 chip->chipsize *= (uint64_t)mtd->erasesize * p->lun_count;
3699 chip->bits_per_cell = p->bits_per_cell;
3701 if (jedec_feature(chip) & JEDEC_FEATURE_16_BIT_BUS)
3702 chip->options |= NAND_BUSWIDTH_16;
3705 ecc = &p->ecc_info[0];
3707 if (ecc->codeword_size >= 9) {
3708 chip->ecc_strength_ds = ecc->ecc_bits;
3709 chip->ecc_step_ds = 1 << ecc->codeword_size;
3711 pr_warn("Invalid codeword size\n");
3718 * nand_id_has_period - Check if an ID string has a given wraparound period
3719 * @id_data: the ID string
3720 * @arrlen: the length of the @id_data array
3721 * @period: the period of repitition
3723 * Check if an ID string is repeated within a given sequence of bytes at
3724 * specific repetition interval period (e.g., {0x20,0x01,0x7F,0x20} has a
3725 * period of 3). This is a helper function for nand_id_len(). Returns non-zero
3726 * if the repetition has a period of @period; otherwise, returns zero.
3728 static int nand_id_has_period(u8 *id_data, int arrlen, int period)
3731 for (i = 0; i < period; i++)
3732 for (j = i + period; j < arrlen; j += period)
3733 if (id_data[i] != id_data[j])
3739 * nand_id_len - Get the length of an ID string returned by CMD_READID
3740 * @id_data: the ID string
3741 * @arrlen: the length of the @id_data array
3743 * Returns the length of the ID string, according to known wraparound/trailing
3744 * zero patterns. If no pattern exists, returns the length of the array.
3746 static int nand_id_len(u8 *id_data, int arrlen)
3748 int last_nonzero, period;
3750 /* Find last non-zero byte */
3751 for (last_nonzero = arrlen - 1; last_nonzero >= 0; last_nonzero--)
3752 if (id_data[last_nonzero])
3756 if (last_nonzero < 0)
3759 /* Calculate wraparound period */
3760 for (period = 1; period < arrlen; period++)
3761 if (nand_id_has_period(id_data, arrlen, period))
3764 /* There's a repeated pattern */
3765 if (period < arrlen)
3768 /* There are trailing zeros */
3769 if (last_nonzero < arrlen - 1)
3770 return last_nonzero + 1;
3772 /* No pattern detected */
3776 /* Extract the bits of per cell from the 3rd byte of the extended ID */
3777 static int nand_get_bits_per_cell(u8 cellinfo)
3781 bits = cellinfo & NAND_CI_CELLTYPE_MSK;
3782 bits >>= NAND_CI_CELLTYPE_SHIFT;
3787 * Many new NAND share similar device ID codes, which represent the size of the
3788 * chip. The rest of the parameters must be decoded according to generic or
3789 * manufacturer-specific "extended ID" decoding patterns.
3791 void nand_decode_ext_id(struct nand_chip *chip)
3793 struct mtd_info *mtd = nand_to_mtd(chip);
3795 u8 *id_data = chip->id.data;
3796 /* The 3rd id byte holds MLC / multichip data */
3797 chip->bits_per_cell = nand_get_bits_per_cell(id_data[2]);
3798 /* The 4th id byte is the important one */
3802 mtd->writesize = 1024 << (extid & 0x03);
3805 mtd->oobsize = (8 << (extid & 0x01)) * (mtd->writesize >> 9);
3807 /* Calc blocksize. Blocksize is multiples of 64KiB */
3808 mtd->erasesize = (64 * 1024) << (extid & 0x03);
3810 /* Get buswidth information */
3812 chip->options |= NAND_BUSWIDTH_16;
3814 EXPORT_SYMBOL_GPL(nand_decode_ext_id);
3817 * Old devices have chip data hardcoded in the device ID table. nand_decode_id
3818 * decodes a matching ID table entry and assigns the MTD size parameters for
3821 static void nand_decode_id(struct nand_chip *chip, struct nand_flash_dev *type)
3823 struct mtd_info *mtd = nand_to_mtd(chip);
3825 mtd->erasesize = type->erasesize;
3826 mtd->writesize = type->pagesize;
3827 mtd->oobsize = mtd->writesize / 32;
3829 /* All legacy ID NAND are small-page, SLC */
3830 chip->bits_per_cell = 1;
3834 * Set the bad block marker/indicator (BBM/BBI) patterns according to some
3835 * heuristic patterns using various detected parameters (e.g., manufacturer,
3836 * page size, cell-type information).
3838 static void nand_decode_bbm_options(struct nand_chip *chip)
3840 struct mtd_info *mtd = nand_to_mtd(chip);
3842 /* Set the bad block position */
3843 if (mtd->writesize > 512 || (chip->options & NAND_BUSWIDTH_16))
3844 chip->badblockpos = NAND_LARGE_BADBLOCK_POS;
3846 chip->badblockpos = NAND_SMALL_BADBLOCK_POS;
3849 static inline bool is_full_id_nand(struct nand_flash_dev *type)
3851 return type->id_len;
3854 static bool find_full_id_nand(struct nand_chip *chip,
3855 struct nand_flash_dev *type)
3857 struct mtd_info *mtd = nand_to_mtd(chip);
3858 u8 *id_data = chip->id.data;
3860 if (!strncmp(type->id, id_data, type->id_len)) {
3861 mtd->writesize = type->pagesize;
3862 mtd->erasesize = type->erasesize;
3863 mtd->oobsize = type->oobsize;
3865 chip->bits_per_cell = nand_get_bits_per_cell(id_data[2]);
3866 chip->chipsize = (uint64_t)type->chipsize << 20;
3867 chip->options |= type->options;
3868 chip->ecc_strength_ds = NAND_ECC_STRENGTH(type);
3869 chip->ecc_step_ds = NAND_ECC_STEP(type);
3870 chip->onfi_timing_mode_default =
3871 type->onfi_timing_mode_default;
3874 mtd->name = type->name;
3882 * Manufacturer detection. Only used when the NAND is not ONFI or JEDEC
3883 * compliant and does not have a full-id or legacy-id entry in the nand_ids
3886 static void nand_manufacturer_detect(struct nand_chip *chip)
3889 * Try manufacturer detection if available and use
3890 * nand_decode_ext_id() otherwise.
3892 if (chip->manufacturer.desc && chip->manufacturer.desc->ops &&
3893 chip->manufacturer.desc->ops->detect)
3894 chip->manufacturer.desc->ops->detect(chip);
3896 nand_decode_ext_id(chip);
3900 * Manufacturer initialization. This function is called for all NANDs including
3901 * ONFI and JEDEC compliant ones.
3902 * Manufacturer drivers should put all their specific initialization code in
3903 * their ->init() hook.
3905 static int nand_manufacturer_init(struct nand_chip *chip)
3907 if (!chip->manufacturer.desc || !chip->manufacturer.desc->ops ||
3908 !chip->manufacturer.desc->ops->init)
3911 return chip->manufacturer.desc->ops->init(chip);
3915 * Manufacturer cleanup. This function is called for all NANDs including
3916 * ONFI and JEDEC compliant ones.
3917 * Manufacturer drivers should put all their specific cleanup code in their
3920 static void nand_manufacturer_cleanup(struct nand_chip *chip)
3922 /* Release manufacturer private data */
3923 if (chip->manufacturer.desc && chip->manufacturer.desc->ops &&
3924 chip->manufacturer.desc->ops->cleanup)
3925 chip->manufacturer.desc->ops->cleanup(chip);
3929 * Get the flash and manufacturer id and lookup if the type is supported.
3931 static int nand_detect(struct nand_chip *chip, struct nand_flash_dev *type)
3933 const struct nand_manufacturer *manufacturer;
3934 struct mtd_info *mtd = nand_to_mtd(chip);
3937 u8 *id_data = chip->id.data;
3941 * Reset the chip, required by some chips (e.g. Micron MT29FxGxxxxx)
3944 nand_reset(chip, 0);
3946 /* Select the device */
3947 chip->select_chip(mtd, 0);
3949 /* Send the command for reading device ID */
3950 chip->cmdfunc(mtd, NAND_CMD_READID, 0x00, -1);
3952 /* Read manufacturer and device IDs */
3953 maf_id = chip->read_byte(mtd);
3954 dev_id = chip->read_byte(mtd);
3957 * Try again to make sure, as some systems the bus-hold or other
3958 * interface concerns can cause random data which looks like a
3959 * possibly credible NAND flash to appear. If the two results do
3960 * not match, ignore the device completely.
3963 chip->cmdfunc(mtd, NAND_CMD_READID, 0x00, -1);
3965 /* Read entire ID string */
3966 for (i = 0; i < 8; i++)
3967 id_data[i] = chip->read_byte(mtd);
3969 if (id_data[0] != maf_id || id_data[1] != dev_id) {
3970 pr_info("second ID read did not match %02x,%02x against %02x,%02x\n",
3971 maf_id, dev_id, id_data[0], id_data[1]);
3975 chip->id.len = nand_id_len(id_data, 8);
3977 /* Try to identify manufacturer */
3978 manufacturer = nand_get_manufacturer(maf_id);
3979 chip->manufacturer.desc = manufacturer;
3982 type = nand_flash_ids;
3985 * Save the NAND_BUSWIDTH_16 flag before letting auto-detection logic
3987 * This is required to make sure initial NAND bus width set by the
3988 * NAND controller driver is coherent with the real NAND bus width
3989 * (extracted by auto-detection code).
3991 busw = chip->options & NAND_BUSWIDTH_16;
3994 * The flag is only set (never cleared), reset it to its default value
3995 * before starting auto-detection.
3997 chip->options &= ~NAND_BUSWIDTH_16;
3999 for (; type->name != NULL; type++) {
4000 if (is_full_id_nand(type)) {
4001 if (find_full_id_nand(chip, type))
4003 } else if (dev_id == type->dev_id) {
4008 chip->onfi_version = 0;
4009 if (!type->name || !type->pagesize) {
4010 /* Check if the chip is ONFI compliant */
4011 if (nand_flash_detect_onfi(chip))
4014 /* Check if the chip is JEDEC compliant */
4015 if (nand_flash_detect_jedec(chip))
4023 mtd->name = type->name;
4025 chip->chipsize = (uint64_t)type->chipsize << 20;
4027 if (!type->pagesize)
4028 nand_manufacturer_detect(chip);
4030 nand_decode_id(chip, type);
4032 /* Get chip options */
4033 chip->options |= type->options;
4037 if (chip->options & NAND_BUSWIDTH_AUTO) {
4038 WARN_ON(busw & NAND_BUSWIDTH_16);
4039 nand_set_defaults(chip);
4040 } else if (busw != (chip->options & NAND_BUSWIDTH_16)) {
4042 * Check, if buswidth is correct. Hardware drivers should set
4045 pr_info("device found, Manufacturer ID: 0x%02x, Chip ID: 0x%02x\n",
4047 pr_info("%s %s\n", nand_manufacturer_name(manufacturer),
4049 pr_warn("bus width %d instead of %d bits\n", busw ? 16 : 8,
4050 (chip->options & NAND_BUSWIDTH_16) ? 16 : 8);
4054 nand_decode_bbm_options(chip);
4056 /* Calculate the address shift from the page size */
4057 chip->page_shift = ffs(mtd->writesize) - 1;
4058 /* Convert chipsize to number of pages per chip -1 */
4059 chip->pagemask = (chip->chipsize >> chip->page_shift) - 1;
4061 chip->bbt_erase_shift = chip->phys_erase_shift =
4062 ffs(mtd->erasesize) - 1;
4063 if (chip->chipsize & 0xffffffff)
4064 chip->chip_shift = ffs((unsigned)chip->chipsize) - 1;
4066 chip->chip_shift = ffs((unsigned)(chip->chipsize >> 32));
4067 chip->chip_shift += 32 - 1;
4070 chip->badblockbits = 8;
4071 chip->erase = single_erase;
4073 /* Do not replace user supplied command function! */
4074 if (mtd->writesize > 512 && chip->cmdfunc == nand_command)
4075 chip->cmdfunc = nand_command_lp;
4077 ret = nand_manufacturer_init(chip);
4081 pr_info("device found, Manufacturer ID: 0x%02x, Chip ID: 0x%02x\n",
4084 if (chip->onfi_version)
4085 pr_info("%s %s\n", nand_manufacturer_name(manufacturer),
4086 chip->onfi_params.model);
4087 else if (chip->jedec_version)
4088 pr_info("%s %s\n", nand_manufacturer_name(manufacturer),
4089 chip->jedec_params.model);
4091 pr_info("%s %s\n", nand_manufacturer_name(manufacturer),
4094 pr_info("%d MiB, %s, erase size: %d KiB, page size: %d, OOB size: %d\n",
4095 (int)(chip->chipsize >> 20), nand_is_slc(chip) ? "SLC" : "MLC",
4096 mtd->erasesize >> 10, mtd->writesize, mtd->oobsize);
4100 static const char * const nand_ecc_modes[] = {
4101 [NAND_ECC_NONE] = "none",
4102 [NAND_ECC_SOFT] = "soft",
4103 [NAND_ECC_HW] = "hw",
4104 [NAND_ECC_HW_SYNDROME] = "hw_syndrome",
4105 [NAND_ECC_HW_OOB_FIRST] = "hw_oob_first",
4108 static int of_get_nand_ecc_mode(struct device_node *np)
4113 err = of_property_read_string(np, "nand-ecc-mode", &pm);
4117 for (i = 0; i < ARRAY_SIZE(nand_ecc_modes); i++)
4118 if (!strcasecmp(pm, nand_ecc_modes[i]))
4122 * For backward compatibility we support few obsoleted values that don't
4123 * have their mappings into nand_ecc_modes_t anymore (they were merged
4124 * with other enums).
4126 if (!strcasecmp(pm, "soft_bch"))
4127 return NAND_ECC_SOFT;
4132 static const char * const nand_ecc_algos[] = {
4133 [NAND_ECC_HAMMING] = "hamming",
4134 [NAND_ECC_BCH] = "bch",
4137 static int of_get_nand_ecc_algo(struct device_node *np)
4142 err = of_property_read_string(np, "nand-ecc-algo", &pm);
4144 for (i = NAND_ECC_HAMMING; i < ARRAY_SIZE(nand_ecc_algos); i++)
4145 if (!strcasecmp(pm, nand_ecc_algos[i]))
4151 * For backward compatibility we also read "nand-ecc-mode" checking
4152 * for some obsoleted values that were specifying ECC algorithm.
4154 err = of_property_read_string(np, "nand-ecc-mode", &pm);
4158 if (!strcasecmp(pm, "soft"))
4159 return NAND_ECC_HAMMING;
4160 else if (!strcasecmp(pm, "soft_bch"))
4161 return NAND_ECC_BCH;
4166 static int of_get_nand_ecc_step_size(struct device_node *np)
4171 ret = of_property_read_u32(np, "nand-ecc-step-size", &val);
4172 return ret ? ret : val;
4175 static int of_get_nand_ecc_strength(struct device_node *np)
4180 ret = of_property_read_u32(np, "nand-ecc-strength", &val);
4181 return ret ? ret : val;
4184 static int of_get_nand_bus_width(struct device_node *np)
4188 if (of_property_read_u32(np, "nand-bus-width", &val))
4200 static bool of_get_nand_on_flash_bbt(struct device_node *np)
4202 return of_property_read_bool(np, "nand-on-flash-bbt");
4205 static int nand_dt_init(struct nand_chip *chip)
4207 struct device_node *dn = nand_get_flash_node(chip);
4208 int ecc_mode, ecc_algo, ecc_strength, ecc_step;
4213 if (of_get_nand_bus_width(dn) == 16)
4214 chip->options |= NAND_BUSWIDTH_16;
4216 if (of_get_nand_on_flash_bbt(dn))
4217 chip->bbt_options |= NAND_BBT_USE_FLASH;
4219 ecc_mode = of_get_nand_ecc_mode(dn);
4220 ecc_algo = of_get_nand_ecc_algo(dn);
4221 ecc_strength = of_get_nand_ecc_strength(dn);
4222 ecc_step = of_get_nand_ecc_step_size(dn);
4225 chip->ecc.mode = ecc_mode;
4228 chip->ecc.algo = ecc_algo;
4230 if (ecc_strength >= 0)
4231 chip->ecc.strength = ecc_strength;
4234 chip->ecc.size = ecc_step;
4236 if (of_property_read_bool(dn, "nand-ecc-maximize"))
4237 chip->ecc.options |= NAND_ECC_MAXIMIZE;
4243 * nand_scan_ident - [NAND Interface] Scan for the NAND device
4244 * @mtd: MTD device structure
4245 * @maxchips: number of chips to scan for
4246 * @table: alternative NAND ID table
4248 * This is the first phase of the normal nand_scan() function. It reads the
4249 * flash ID and sets up MTD fields accordingly.
4252 int nand_scan_ident(struct mtd_info *mtd, int maxchips,
4253 struct nand_flash_dev *table)
4255 int i, nand_maf_id, nand_dev_id;
4256 struct nand_chip *chip = mtd_to_nand(mtd);
4259 ret = nand_dt_init(chip);
4263 if (!mtd->name && mtd->dev.parent)
4264 mtd->name = dev_name(mtd->dev.parent);
4266 if ((!chip->cmdfunc || !chip->select_chip) && !chip->cmd_ctrl) {
4268 * Default functions assigned for chip_select() and
4269 * cmdfunc() both expect cmd_ctrl() to be populated,
4270 * so we need to check that that's the case
4272 pr_err("chip.cmd_ctrl() callback is not provided");
4275 /* Set the default functions */
4276 nand_set_defaults(chip);
4278 /* Read the flash type */
4279 ret = nand_detect(chip, table);
4281 if (!(chip->options & NAND_SCAN_SILENT_NODEV))
4282 pr_warn("No NAND device found\n");
4283 chip->select_chip(mtd, -1);
4287 /* Initialize the ->data_interface field. */
4288 ret = nand_init_data_interface(chip);
4293 * Setup the data interface correctly on the chip and controller side.
4294 * This explicit call to nand_setup_data_interface() is only required
4295 * for the first die, because nand_reset() has been called before
4296 * ->data_interface and ->default_onfi_timing_mode were set.
4297 * For the other dies, nand_reset() will automatically switch to the
4300 ret = nand_setup_data_interface(chip);
4304 nand_maf_id = chip->id.data[0];
4305 nand_dev_id = chip->id.data[1];
4307 chip->select_chip(mtd, -1);
4309 /* Check for a chip array */
4310 for (i = 1; i < maxchips; i++) {
4311 /* See comment in nand_get_flash_type for reset */
4312 nand_reset(chip, i);
4314 chip->select_chip(mtd, i);
4315 /* Send the command for reading device ID */
4316 chip->cmdfunc(mtd, NAND_CMD_READID, 0x00, -1);
4317 /* Read manufacturer and device IDs */
4318 if (nand_maf_id != chip->read_byte(mtd) ||
4319 nand_dev_id != chip->read_byte(mtd)) {
4320 chip->select_chip(mtd, -1);
4323 chip->select_chip(mtd, -1);
4326 pr_info("%d chips detected\n", i);
4328 /* Store the number of chips and calc total size for mtd */
4330 mtd->size = i * chip->chipsize;
4334 EXPORT_SYMBOL(nand_scan_ident);
4336 static int nand_set_ecc_soft_ops(struct mtd_info *mtd)
4338 struct nand_chip *chip = mtd_to_nand(mtd);
4339 struct nand_ecc_ctrl *ecc = &chip->ecc;
4341 if (WARN_ON(ecc->mode != NAND_ECC_SOFT))
4344 switch (ecc->algo) {
4345 case NAND_ECC_HAMMING:
4346 ecc->calculate = nand_calculate_ecc;
4347 ecc->correct = nand_correct_data;
4348 ecc->read_page = nand_read_page_swecc;
4349 ecc->read_subpage = nand_read_subpage;
4350 ecc->write_page = nand_write_page_swecc;
4351 ecc->read_page_raw = nand_read_page_raw;
4352 ecc->write_page_raw = nand_write_page_raw;
4353 ecc->read_oob = nand_read_oob_std;
4354 ecc->write_oob = nand_write_oob_std;
4361 if (!mtd_nand_has_bch()) {
4362 WARN(1, "CONFIG_MTD_NAND_ECC_BCH not enabled\n");
4365 ecc->calculate = nand_bch_calculate_ecc;
4366 ecc->correct = nand_bch_correct_data;
4367 ecc->read_page = nand_read_page_swecc;
4368 ecc->read_subpage = nand_read_subpage;
4369 ecc->write_page = nand_write_page_swecc;
4370 ecc->read_page_raw = nand_read_page_raw;
4371 ecc->write_page_raw = nand_write_page_raw;
4372 ecc->read_oob = nand_read_oob_std;
4373 ecc->write_oob = nand_write_oob_std;
4376 * Board driver should supply ecc.size and ecc.strength
4377 * values to select how many bits are correctable.
4378 * Otherwise, default to 4 bits for large page devices.
4380 if (!ecc->size && (mtd->oobsize >= 64)) {
4386 * if no ecc placement scheme was provided pickup the default
4389 if (!mtd->ooblayout) {
4390 /* handle large page devices only */
4391 if (mtd->oobsize < 64) {
4392 WARN(1, "OOB layout is required when using software BCH on small pages\n");
4396 mtd_set_ooblayout(mtd, &nand_ooblayout_lp_ops);
4401 * We can only maximize ECC config when the default layout is
4402 * used, otherwise we don't know how many bytes can really be
4405 if (mtd->ooblayout == &nand_ooblayout_lp_ops &&
4406 ecc->options & NAND_ECC_MAXIMIZE) {
4409 /* Always prefer 1k blocks over 512bytes ones */
4411 steps = mtd->writesize / ecc->size;
4413 /* Reserve 2 bytes for the BBM */
4414 bytes = (mtd->oobsize - 2) / steps;
4415 ecc->strength = bytes * 8 / fls(8 * ecc->size);
4418 /* See nand_bch_init() for details. */
4420 ecc->priv = nand_bch_init(mtd);
4422 WARN(1, "BCH ECC initialization failed!\n");
4427 WARN(1, "Unsupported ECC algorithm!\n");
4433 * Check if the chip configuration meet the datasheet requirements.
4435 * If our configuration corrects A bits per B bytes and the minimum
4436 * required correction level is X bits per Y bytes, then we must ensure
4437 * both of the following are true:
4439 * (1) A / B >= X / Y
4442 * Requirement (1) ensures we can correct for the required bitflip density.
4443 * Requirement (2) ensures we can correct even when all bitflips are clumped
4444 * in the same sector.
4446 static bool nand_ecc_strength_good(struct mtd_info *mtd)
4448 struct nand_chip *chip = mtd_to_nand(mtd);
4449 struct nand_ecc_ctrl *ecc = &chip->ecc;
4452 if (ecc->size == 0 || chip->ecc_step_ds == 0)
4453 /* Not enough information */
4457 * We get the number of corrected bits per page to compare
4458 * the correction density.
4460 corr = (mtd->writesize * ecc->strength) / ecc->size;
4461 ds_corr = (mtd->writesize * chip->ecc_strength_ds) / chip->ecc_step_ds;
4463 return corr >= ds_corr && ecc->strength >= chip->ecc_strength_ds;
4466 static bool invalid_ecc_page_accessors(struct nand_chip *chip)
4468 struct nand_ecc_ctrl *ecc = &chip->ecc;
4470 if (nand_standard_page_accessors(ecc))
4474 * NAND_ECC_CUSTOM_PAGE_ACCESS flag is set, make sure the NAND
4475 * controller driver implements all the page accessors because
4476 * default helpers are not suitable when the core does not
4477 * send the READ0/PAGEPROG commands.
4479 return (!ecc->read_page || !ecc->write_page ||
4480 !ecc->read_page_raw || !ecc->write_page_raw ||
4481 (NAND_HAS_SUBPAGE_READ(chip) && !ecc->read_subpage) ||
4482 (NAND_HAS_SUBPAGE_WRITE(chip) && !ecc->write_subpage &&
4483 ecc->hwctl && ecc->calculate));
4487 * nand_scan_tail - [NAND Interface] Scan for the NAND device
4488 * @mtd: MTD device structure
4490 * This is the second phase of the normal nand_scan() function. It fills out
4491 * all the uninitialized function pointers with the defaults and scans for a
4492 * bad block table if appropriate.
4494 int nand_scan_tail(struct mtd_info *mtd)
4496 struct nand_chip *chip = mtd_to_nand(mtd);
4497 struct nand_ecc_ctrl *ecc = &chip->ecc;
4498 struct nand_buffers *nbuf;
4501 /* New bad blocks should be marked in OOB, flash-based BBT, or both */
4502 if (WARN_ON((chip->bbt_options & NAND_BBT_NO_OOB_BBM) &&
4503 !(chip->bbt_options & NAND_BBT_USE_FLASH)))
4506 if (invalid_ecc_page_accessors(chip)) {
4507 pr_err("Invalid ECC page accessors setup\n");
4511 if (!(chip->options & NAND_OWN_BUFFERS)) {
4512 nbuf = kzalloc(sizeof(*nbuf) + mtd->writesize
4513 + mtd->oobsize * 3, GFP_KERNEL);
4516 nbuf->ecccalc = (uint8_t *)(nbuf + 1);
4517 nbuf->ecccode = nbuf->ecccalc + mtd->oobsize;
4518 nbuf->databuf = nbuf->ecccode + mtd->oobsize;
4520 chip->buffers = nbuf;
4526 /* Set the internal oob buffer location, just after the page data */
4527 chip->oob_poi = chip->buffers->databuf + mtd->writesize;
4530 * If no default placement scheme is given, select an appropriate one.
4532 if (!mtd->ooblayout &&
4533 !(ecc->mode == NAND_ECC_SOFT && ecc->algo == NAND_ECC_BCH)) {
4534 switch (mtd->oobsize) {
4537 mtd_set_ooblayout(mtd, &nand_ooblayout_sp_ops);
4541 mtd_set_ooblayout(mtd, &nand_ooblayout_lp_ops);
4544 WARN(1, "No oob scheme defined for oobsize %d\n",
4552 * Check ECC mode, default to software if 3byte/512byte hardware ECC is
4553 * selected and we have 256 byte pagesize fallback to software ECC
4556 switch (ecc->mode) {
4557 case NAND_ECC_HW_OOB_FIRST:
4558 /* Similar to NAND_ECC_HW, but a separate read_page handle */
4559 if (!ecc->calculate || !ecc->correct || !ecc->hwctl) {
4560 WARN(1, "No ECC functions supplied; hardware ECC not possible\n");
4564 if (!ecc->read_page)
4565 ecc->read_page = nand_read_page_hwecc_oob_first;
4568 /* Use standard hwecc read page function? */
4569 if (!ecc->read_page)
4570 ecc->read_page = nand_read_page_hwecc;
4571 if (!ecc->write_page)
4572 ecc->write_page = nand_write_page_hwecc;
4573 if (!ecc->read_page_raw)
4574 ecc->read_page_raw = nand_read_page_raw;
4575 if (!ecc->write_page_raw)
4576 ecc->write_page_raw = nand_write_page_raw;
4578 ecc->read_oob = nand_read_oob_std;
4579 if (!ecc->write_oob)
4580 ecc->write_oob = nand_write_oob_std;
4581 if (!ecc->read_subpage)
4582 ecc->read_subpage = nand_read_subpage;
4583 if (!ecc->write_subpage && ecc->hwctl && ecc->calculate)
4584 ecc->write_subpage = nand_write_subpage_hwecc;
4586 case NAND_ECC_HW_SYNDROME:
4587 if ((!ecc->calculate || !ecc->correct || !ecc->hwctl) &&
4589 ecc->read_page == nand_read_page_hwecc ||
4591 ecc->write_page == nand_write_page_hwecc)) {
4592 WARN(1, "No ECC functions supplied; hardware ECC not possible\n");
4596 /* Use standard syndrome read/write page function? */
4597 if (!ecc->read_page)
4598 ecc->read_page = nand_read_page_syndrome;
4599 if (!ecc->write_page)
4600 ecc->write_page = nand_write_page_syndrome;
4601 if (!ecc->read_page_raw)
4602 ecc->read_page_raw = nand_read_page_raw_syndrome;
4603 if (!ecc->write_page_raw)
4604 ecc->write_page_raw = nand_write_page_raw_syndrome;
4606 ecc->read_oob = nand_read_oob_syndrome;
4607 if (!ecc->write_oob)
4608 ecc->write_oob = nand_write_oob_syndrome;
4610 if (mtd->writesize >= ecc->size) {
4611 if (!ecc->strength) {
4612 WARN(1, "Driver must set ecc.strength when using hardware ECC\n");
4618 pr_warn("%d byte HW ECC not possible on %d byte page size, fallback to SW ECC\n",
4619 ecc->size, mtd->writesize);
4620 ecc->mode = NAND_ECC_SOFT;
4621 ecc->algo = NAND_ECC_HAMMING;
4624 ret = nand_set_ecc_soft_ops(mtd);
4632 pr_warn("NAND_ECC_NONE selected by board driver. This is not recommended!\n");
4633 ecc->read_page = nand_read_page_raw;
4634 ecc->write_page = nand_write_page_raw;
4635 ecc->read_oob = nand_read_oob_std;
4636 ecc->read_page_raw = nand_read_page_raw;
4637 ecc->write_page_raw = nand_write_page_raw;
4638 ecc->write_oob = nand_write_oob_std;
4639 ecc->size = mtd->writesize;
4645 WARN(1, "Invalid NAND_ECC_MODE %d\n", ecc->mode);
4650 /* For many systems, the standard OOB write also works for raw */
4651 if (!ecc->read_oob_raw)
4652 ecc->read_oob_raw = ecc->read_oob;
4653 if (!ecc->write_oob_raw)
4654 ecc->write_oob_raw = ecc->write_oob;
4656 /* propagate ecc info to mtd_info */
4657 mtd->ecc_strength = ecc->strength;
4658 mtd->ecc_step_size = ecc->size;
4661 * Set the number of read / write steps for one page depending on ECC
4664 ecc->steps = mtd->writesize / ecc->size;
4665 if (ecc->steps * ecc->size != mtd->writesize) {
4666 WARN(1, "Invalid ECC parameters\n");
4670 ecc->total = ecc->steps * ecc->bytes;
4673 * The number of bytes available for a client to place data into
4674 * the out of band area.
4676 ret = mtd_ooblayout_count_freebytes(mtd);
4680 mtd->oobavail = ret;
4682 /* ECC sanity check: warn if it's too weak */
4683 if (!nand_ecc_strength_good(mtd))
4684 pr_warn("WARNING: %s: the ECC used on your system is too weak compared to the one required by the NAND chip\n",
4687 /* Allow subpage writes up to ecc.steps. Not possible for MLC flash */
4688 if (!(chip->options & NAND_NO_SUBPAGE_WRITE) && nand_is_slc(chip)) {
4689 switch (ecc->steps) {
4691 mtd->subpage_sft = 1;
4696 mtd->subpage_sft = 2;
4700 chip->subpagesize = mtd->writesize >> mtd->subpage_sft;
4702 /* Initialize state */
4703 chip->state = FL_READY;
4705 /* Invalidate the pagebuffer reference */
4708 /* Large page NAND with SOFT_ECC should support subpage reads */
4709 switch (ecc->mode) {
4711 if (chip->page_shift > 9)
4712 chip->options |= NAND_SUBPAGE_READ;
4719 /* Fill in remaining MTD driver data */
4720 mtd->type = nand_is_slc(chip) ? MTD_NANDFLASH : MTD_MLCNANDFLASH;
4721 mtd->flags = (chip->options & NAND_ROM) ? MTD_CAP_ROM :
4723 mtd->_erase = nand_erase;
4725 mtd->_unpoint = NULL;
4726 mtd->_read = nand_read;
4727 mtd->_write = nand_write;
4728 mtd->_panic_write = panic_nand_write;
4729 mtd->_read_oob = nand_read_oob;
4730 mtd->_write_oob = nand_write_oob;
4731 mtd->_sync = nand_sync;
4733 mtd->_unlock = NULL;
4734 mtd->_suspend = nand_suspend;
4735 mtd->_resume = nand_resume;
4736 mtd->_reboot = nand_shutdown;
4737 mtd->_block_isreserved = nand_block_isreserved;
4738 mtd->_block_isbad = nand_block_isbad;
4739 mtd->_block_markbad = nand_block_markbad;
4740 mtd->_max_bad_blocks = nand_max_bad_blocks;
4741 mtd->writebufsize = mtd->writesize;
4744 * Initialize bitflip_threshold to its default prior scan_bbt() call.
4745 * scan_bbt() might invoke mtd_read(), thus bitflip_threshold must be
4748 if (!mtd->bitflip_threshold)
4749 mtd->bitflip_threshold = DIV_ROUND_UP(mtd->ecc_strength * 3, 4);
4751 /* Check, if we should skip the bad block table scan */
4752 if (chip->options & NAND_SKIP_BBTSCAN)
4755 /* Build bad block table */
4756 return chip->scan_bbt(mtd);
4758 if (!(chip->options & NAND_OWN_BUFFERS))
4759 kfree(chip->buffers);
4762 EXPORT_SYMBOL(nand_scan_tail);
4765 * is_module_text_address() isn't exported, and it's mostly a pointless
4766 * test if this is a module _anyway_ -- they'd have to try _really_ hard
4767 * to call us from in-kernel code if the core NAND support is modular.
4770 #define caller_is_module() (1)
4772 #define caller_is_module() \
4773 is_module_text_address((unsigned long)__builtin_return_address(0))
4777 * nand_scan - [NAND Interface] Scan for the NAND device
4778 * @mtd: MTD device structure
4779 * @maxchips: number of chips to scan for
4781 * This fills out all the uninitialized function pointers with the defaults.
4782 * The flash ID is read and the mtd/chip structures are filled with the
4783 * appropriate values.
4785 int nand_scan(struct mtd_info *mtd, int maxchips)
4789 ret = nand_scan_ident(mtd, maxchips, NULL);
4791 ret = nand_scan_tail(mtd);
4794 EXPORT_SYMBOL(nand_scan);
4797 * nand_cleanup - [NAND Interface] Free resources held by the NAND device
4798 * @chip: NAND chip object
4800 void nand_cleanup(struct nand_chip *chip)
4802 if (chip->ecc.mode == NAND_ECC_SOFT &&
4803 chip->ecc.algo == NAND_ECC_BCH)
4804 nand_bch_free((struct nand_bch_control *)chip->ecc.priv);
4806 nand_release_data_interface(chip);
4808 /* Free bad block table memory */
4810 if (!(chip->options & NAND_OWN_BUFFERS))
4811 kfree(chip->buffers);
4813 /* Free bad block descriptor memory */
4814 if (chip->badblock_pattern && chip->badblock_pattern->options
4815 & NAND_BBT_DYNAMICSTRUCT)
4816 kfree(chip->badblock_pattern);
4818 /* Free manufacturer priv data. */
4819 nand_manufacturer_cleanup(chip);
4821 EXPORT_SYMBOL_GPL(nand_cleanup);
4824 * nand_release - [NAND Interface] Unregister the MTD device and free resources
4825 * held by the NAND device
4826 * @mtd: MTD device structure
4828 void nand_release(struct mtd_info *mtd)
4830 mtd_device_unregister(mtd);
4831 nand_cleanup(mtd_to_nand(mtd));
4833 EXPORT_SYMBOL_GPL(nand_release);
4835 MODULE_LICENSE("GPL");
4836 MODULE_AUTHOR("Steven J. Hill <sjhill@realitydiluted.com>");
4837 MODULE_AUTHOR("Thomas Gleixner <tglx@linutronix.de>");
4838 MODULE_DESCRIPTION("Generic NAND flash driver code");