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, res = 0, i = 0;
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;
367 if (chip->options & NAND_BUSWIDTH_16) {
368 chip->cmdfunc(mtd, NAND_CMD_READOOB,
369 chip->badblockpos & 0xFE, page);
370 bad = cpu_to_le16(chip->read_word(mtd));
371 if (chip->badblockpos & 0x1)
376 chip->cmdfunc(mtd, NAND_CMD_READOOB, chip->badblockpos,
378 bad = chip->read_byte(mtd);
381 if (likely(chip->badblockbits == 8))
384 res = hweight8(bad) < chip->badblockbits;
385 ofs += mtd->writesize;
386 page = (int)(ofs >> chip->page_shift) & chip->pagemask;
388 } while (!res && i < 2 && (chip->bbt_options & NAND_BBT_SCAN2NDPAGE));
394 * nand_default_block_markbad - [DEFAULT] mark a block bad via bad block marker
395 * @mtd: MTD device structure
396 * @ofs: offset from device start
398 * This is the default implementation, which can be overridden by a hardware
399 * specific driver. It provides the details for writing a bad block marker to a
402 static int nand_default_block_markbad(struct mtd_info *mtd, loff_t ofs)
404 struct nand_chip *chip = mtd_to_nand(mtd);
405 struct mtd_oob_ops ops;
406 uint8_t buf[2] = { 0, 0 };
407 int ret = 0, res, i = 0;
409 memset(&ops, 0, sizeof(ops));
411 ops.ooboffs = chip->badblockpos;
412 if (chip->options & NAND_BUSWIDTH_16) {
413 ops.ooboffs &= ~0x01;
414 ops.len = ops.ooblen = 2;
416 ops.len = ops.ooblen = 1;
418 ops.mode = MTD_OPS_PLACE_OOB;
420 /* Write to first/last page(s) if necessary */
421 if (chip->bbt_options & NAND_BBT_SCANLASTPAGE)
422 ofs += mtd->erasesize - mtd->writesize;
424 res = nand_do_write_oob(mtd, ofs, &ops);
429 ofs += mtd->writesize;
430 } while ((chip->bbt_options & NAND_BBT_SCAN2NDPAGE) && i < 2);
436 * nand_block_markbad_lowlevel - mark a block bad
437 * @mtd: MTD device structure
438 * @ofs: offset from device start
440 * This function performs the generic NAND bad block marking steps (i.e., bad
441 * block table(s) and/or marker(s)). We only allow the hardware driver to
442 * specify how to write bad block markers to OOB (chip->block_markbad).
444 * We try operations in the following order:
445 * (1) erase the affected block, to allow OOB marker to be written cleanly
446 * (2) write bad block marker to OOB area of affected block (unless flag
447 * NAND_BBT_NO_OOB_BBM is present)
449 * Note that we retain the first error encountered in (2) or (3), finish the
450 * procedures, and dump the error in the end.
452 static int nand_block_markbad_lowlevel(struct mtd_info *mtd, loff_t ofs)
454 struct nand_chip *chip = mtd_to_nand(mtd);
457 if (!(chip->bbt_options & NAND_BBT_NO_OOB_BBM)) {
458 struct erase_info einfo;
460 /* Attempt erase before marking OOB */
461 memset(&einfo, 0, sizeof(einfo));
464 einfo.len = 1ULL << chip->phys_erase_shift;
465 nand_erase_nand(mtd, &einfo, 0);
467 /* Write bad block marker to OOB */
468 nand_get_device(mtd, FL_WRITING);
469 ret = chip->block_markbad(mtd, ofs);
470 nand_release_device(mtd);
473 /* Mark block bad in BBT */
475 res = nand_markbad_bbt(mtd, ofs);
481 mtd->ecc_stats.badblocks++;
487 * nand_check_wp - [GENERIC] check if the chip is write protected
488 * @mtd: MTD device structure
490 * Check, if the device is write protected. The function expects, that the
491 * device is already selected.
493 static int nand_check_wp(struct mtd_info *mtd)
495 struct nand_chip *chip = mtd_to_nand(mtd);
497 /* Broken xD cards report WP despite being writable */
498 if (chip->options & NAND_BROKEN_XD)
501 /* Check the WP bit */
502 chip->cmdfunc(mtd, NAND_CMD_STATUS, -1, -1);
503 return (chip->read_byte(mtd) & NAND_STATUS_WP) ? 0 : 1;
507 * nand_block_isreserved - [GENERIC] Check if a block is marked reserved.
508 * @mtd: MTD device structure
509 * @ofs: offset from device start
511 * Check if the block is marked as reserved.
513 static int nand_block_isreserved(struct mtd_info *mtd, loff_t ofs)
515 struct nand_chip *chip = mtd_to_nand(mtd);
519 /* Return info from the table */
520 return nand_isreserved_bbt(mtd, ofs);
524 * nand_block_checkbad - [GENERIC] Check if a block is marked bad
525 * @mtd: MTD device structure
526 * @ofs: offset from device start
527 * @allowbbt: 1, if its allowed to access the bbt area
529 * Check, if the block is bad. Either by reading the bad block table or
530 * calling of the scan function.
532 static int nand_block_checkbad(struct mtd_info *mtd, loff_t ofs, int allowbbt)
534 struct nand_chip *chip = mtd_to_nand(mtd);
537 return chip->block_bad(mtd, ofs);
539 /* Return info from the table */
540 return nand_isbad_bbt(mtd, ofs, allowbbt);
544 * panic_nand_wait_ready - [GENERIC] Wait for the ready pin after commands.
545 * @mtd: MTD device structure
548 * Helper function for nand_wait_ready used when needing to wait in interrupt
551 static void panic_nand_wait_ready(struct mtd_info *mtd, unsigned long timeo)
553 struct nand_chip *chip = mtd_to_nand(mtd);
556 /* Wait for the device to get ready */
557 for (i = 0; i < timeo; i++) {
558 if (chip->dev_ready(mtd))
560 touch_softlockup_watchdog();
566 * nand_wait_ready - [GENERIC] Wait for the ready pin after commands.
567 * @mtd: MTD device structure
569 * Wait for the ready pin after a command, and warn if a timeout occurs.
571 void nand_wait_ready(struct mtd_info *mtd)
573 struct nand_chip *chip = mtd_to_nand(mtd);
574 unsigned long timeo = 400;
576 if (in_interrupt() || oops_in_progress)
577 return panic_nand_wait_ready(mtd, timeo);
579 /* Wait until command is processed or timeout occurs */
580 timeo = jiffies + msecs_to_jiffies(timeo);
582 if (chip->dev_ready(mtd))
585 } while (time_before(jiffies, timeo));
587 if (!chip->dev_ready(mtd))
588 pr_warn_ratelimited("timeout while waiting for chip to become ready\n");
590 EXPORT_SYMBOL_GPL(nand_wait_ready);
593 * nand_wait_status_ready - [GENERIC] Wait for the ready status after commands.
594 * @mtd: MTD device structure
595 * @timeo: Timeout in ms
597 * Wait for status ready (i.e. command done) or timeout.
599 static void nand_wait_status_ready(struct mtd_info *mtd, unsigned long timeo)
601 register struct nand_chip *chip = mtd_to_nand(mtd);
603 timeo = jiffies + msecs_to_jiffies(timeo);
605 if ((chip->read_byte(mtd) & NAND_STATUS_READY))
607 touch_softlockup_watchdog();
608 } while (time_before(jiffies, timeo));
612 * nand_command - [DEFAULT] Send command to NAND device
613 * @mtd: MTD device structure
614 * @command: the command to be sent
615 * @column: the column address for this command, -1 if none
616 * @page_addr: the page address for this command, -1 if none
618 * Send command to NAND device. This function is used for small page devices
619 * (512 Bytes per page).
621 static void nand_command(struct mtd_info *mtd, unsigned int command,
622 int column, int page_addr)
624 register struct nand_chip *chip = mtd_to_nand(mtd);
625 int ctrl = NAND_CTRL_CLE | NAND_CTRL_CHANGE;
627 /* Write out the command to the device */
628 if (command == NAND_CMD_SEQIN) {
631 if (column >= mtd->writesize) {
633 column -= mtd->writesize;
634 readcmd = NAND_CMD_READOOB;
635 } else if (column < 256) {
636 /* First 256 bytes --> READ0 */
637 readcmd = NAND_CMD_READ0;
640 readcmd = NAND_CMD_READ1;
642 chip->cmd_ctrl(mtd, readcmd, ctrl);
643 ctrl &= ~NAND_CTRL_CHANGE;
645 chip->cmd_ctrl(mtd, command, ctrl);
647 /* Address cycle, when necessary */
648 ctrl = NAND_CTRL_ALE | NAND_CTRL_CHANGE;
649 /* Serially input address */
651 /* Adjust columns for 16 bit buswidth */
652 if (chip->options & NAND_BUSWIDTH_16 &&
653 !nand_opcode_8bits(command))
655 chip->cmd_ctrl(mtd, column, ctrl);
656 ctrl &= ~NAND_CTRL_CHANGE;
658 if (page_addr != -1) {
659 chip->cmd_ctrl(mtd, page_addr, ctrl);
660 ctrl &= ~NAND_CTRL_CHANGE;
661 chip->cmd_ctrl(mtd, page_addr >> 8, ctrl);
662 /* One more address cycle for devices > 32MiB */
663 if (chip->chipsize > (32 << 20))
664 chip->cmd_ctrl(mtd, page_addr >> 16, ctrl);
666 chip->cmd_ctrl(mtd, NAND_CMD_NONE, NAND_NCE | NAND_CTRL_CHANGE);
669 * Program and erase have their own busy handlers status and sequential
674 case NAND_CMD_PAGEPROG:
675 case NAND_CMD_ERASE1:
676 case NAND_CMD_ERASE2:
678 case NAND_CMD_STATUS:
684 udelay(chip->chip_delay);
685 chip->cmd_ctrl(mtd, NAND_CMD_STATUS,
686 NAND_CTRL_CLE | NAND_CTRL_CHANGE);
688 NAND_CMD_NONE, NAND_NCE | NAND_CTRL_CHANGE);
689 /* EZ-NAND can take upto 250ms as per ONFi v4.0 */
690 nand_wait_status_ready(mtd, 250);
693 /* This applies to read commands */
696 * If we don't have access to the busy pin, we apply the given
699 if (!chip->dev_ready) {
700 udelay(chip->chip_delay);
705 * Apply this short delay always to ensure that we do wait tWB in
706 * any case on any machine.
710 nand_wait_ready(mtd);
713 static void nand_ccs_delay(struct nand_chip *chip)
716 * The controller already takes care of waiting for tCCS when the RNDIN
717 * or RNDOUT command is sent, return directly.
719 if (!(chip->options & NAND_WAIT_TCCS))
723 * Wait tCCS_min if it is correctly defined, otherwise wait 500ns
724 * (which should be safe for all NANDs).
726 if (chip->data_interface && chip->data_interface->timings.sdr.tCCS_min)
727 ndelay(chip->data_interface->timings.sdr.tCCS_min / 1000);
733 * nand_command_lp - [DEFAULT] Send command to NAND large page device
734 * @mtd: MTD device structure
735 * @command: the command to be sent
736 * @column: the column address for this command, -1 if none
737 * @page_addr: the page address for this command, -1 if none
739 * Send command to NAND device. This is the version for the new large page
740 * devices. We don't have the separate regions as we have in the small page
741 * devices. We must emulate NAND_CMD_READOOB to keep the code compatible.
743 static void nand_command_lp(struct mtd_info *mtd, unsigned int command,
744 int column, int page_addr)
746 register struct nand_chip *chip = mtd_to_nand(mtd);
748 /* Emulate NAND_CMD_READOOB */
749 if (command == NAND_CMD_READOOB) {
750 column += mtd->writesize;
751 command = NAND_CMD_READ0;
754 /* Command latch cycle */
755 chip->cmd_ctrl(mtd, command, NAND_NCE | NAND_CLE | NAND_CTRL_CHANGE);
757 if (column != -1 || page_addr != -1) {
758 int ctrl = NAND_CTRL_CHANGE | NAND_NCE | NAND_ALE;
760 /* Serially input address */
762 /* Adjust columns for 16 bit buswidth */
763 if (chip->options & NAND_BUSWIDTH_16 &&
764 !nand_opcode_8bits(command))
766 chip->cmd_ctrl(mtd, column, ctrl);
767 ctrl &= ~NAND_CTRL_CHANGE;
769 /* Only output a single addr cycle for 8bits opcodes. */
770 if (!nand_opcode_8bits(command))
771 chip->cmd_ctrl(mtd, column >> 8, ctrl);
773 if (page_addr != -1) {
774 chip->cmd_ctrl(mtd, page_addr, ctrl);
775 chip->cmd_ctrl(mtd, page_addr >> 8,
776 NAND_NCE | NAND_ALE);
777 /* One more address cycle for devices > 128MiB */
778 if (chip->chipsize > (128 << 20))
779 chip->cmd_ctrl(mtd, page_addr >> 16,
780 NAND_NCE | NAND_ALE);
783 chip->cmd_ctrl(mtd, NAND_CMD_NONE, NAND_NCE | NAND_CTRL_CHANGE);
786 * Program and erase have their own busy handlers status, sequential
787 * in and status need no delay.
791 case NAND_CMD_CACHEDPROG:
792 case NAND_CMD_PAGEPROG:
793 case NAND_CMD_ERASE1:
794 case NAND_CMD_ERASE2:
796 case NAND_CMD_STATUS:
800 nand_ccs_delay(chip);
806 udelay(chip->chip_delay);
807 chip->cmd_ctrl(mtd, NAND_CMD_STATUS,
808 NAND_NCE | NAND_CLE | NAND_CTRL_CHANGE);
809 chip->cmd_ctrl(mtd, NAND_CMD_NONE,
810 NAND_NCE | NAND_CTRL_CHANGE);
811 /* EZ-NAND can take upto 250ms as per ONFi v4.0 */
812 nand_wait_status_ready(mtd, 250);
815 case NAND_CMD_RNDOUT:
816 /* No ready / busy check necessary */
817 chip->cmd_ctrl(mtd, NAND_CMD_RNDOUTSTART,
818 NAND_NCE | NAND_CLE | NAND_CTRL_CHANGE);
819 chip->cmd_ctrl(mtd, NAND_CMD_NONE,
820 NAND_NCE | NAND_CTRL_CHANGE);
822 nand_ccs_delay(chip);
826 chip->cmd_ctrl(mtd, NAND_CMD_READSTART,
827 NAND_NCE | NAND_CLE | NAND_CTRL_CHANGE);
828 chip->cmd_ctrl(mtd, NAND_CMD_NONE,
829 NAND_NCE | NAND_CTRL_CHANGE);
831 /* This applies to read commands */
834 * If we don't have access to the busy pin, we apply the given
837 if (!chip->dev_ready) {
838 udelay(chip->chip_delay);
844 * Apply this short delay always to ensure that we do wait tWB in
845 * any case on any machine.
849 nand_wait_ready(mtd);
853 * panic_nand_get_device - [GENERIC] Get chip for selected access
854 * @chip: the nand chip descriptor
855 * @mtd: MTD device structure
856 * @new_state: the state which is requested
858 * Used when in panic, no locks are taken.
860 static void panic_nand_get_device(struct nand_chip *chip,
861 struct mtd_info *mtd, int new_state)
863 /* Hardware controller shared among independent devices */
864 chip->controller->active = chip;
865 chip->state = new_state;
869 * nand_get_device - [GENERIC] Get chip for selected access
870 * @mtd: MTD device structure
871 * @new_state: the state which is requested
873 * Get the device and lock it for exclusive access
876 nand_get_device(struct mtd_info *mtd, int new_state)
878 struct nand_chip *chip = mtd_to_nand(mtd);
879 spinlock_t *lock = &chip->controller->lock;
880 wait_queue_head_t *wq = &chip->controller->wq;
881 DECLARE_WAITQUEUE(wait, current);
885 /* Hardware controller shared among independent devices */
886 if (!chip->controller->active)
887 chip->controller->active = chip;
889 if (chip->controller->active == chip && chip->state == FL_READY) {
890 chip->state = new_state;
894 if (new_state == FL_PM_SUSPENDED) {
895 if (chip->controller->active->state == FL_PM_SUSPENDED) {
896 chip->state = FL_PM_SUSPENDED;
901 set_current_state(TASK_UNINTERRUPTIBLE);
902 add_wait_queue(wq, &wait);
905 remove_wait_queue(wq, &wait);
910 * panic_nand_wait - [GENERIC] wait until the command is done
911 * @mtd: MTD device structure
912 * @chip: NAND chip structure
915 * Wait for command done. This is a helper function for nand_wait used when
916 * we are in interrupt context. May happen when in panic and trying to write
917 * an oops through mtdoops.
919 static void panic_nand_wait(struct mtd_info *mtd, struct nand_chip *chip,
923 for (i = 0; i < timeo; i++) {
924 if (chip->dev_ready) {
925 if (chip->dev_ready(mtd))
928 if (chip->read_byte(mtd) & NAND_STATUS_READY)
936 * nand_wait - [DEFAULT] wait until the command is done
937 * @mtd: MTD device structure
938 * @chip: NAND chip structure
940 * Wait for command done. This applies to erase and program only.
942 static int nand_wait(struct mtd_info *mtd, struct nand_chip *chip)
946 unsigned long timeo = 400;
949 * Apply this short delay always to ensure that we do wait tWB in any
950 * case on any machine.
954 chip->cmdfunc(mtd, NAND_CMD_STATUS, -1, -1);
956 if (in_interrupt() || oops_in_progress)
957 panic_nand_wait(mtd, chip, timeo);
959 timeo = jiffies + msecs_to_jiffies(timeo);
961 if (chip->dev_ready) {
962 if (chip->dev_ready(mtd))
965 if (chip->read_byte(mtd) & NAND_STATUS_READY)
969 } while (time_before(jiffies, timeo));
972 status = (int)chip->read_byte(mtd);
973 /* This can happen if in case of timeout or buggy dev_ready */
974 WARN_ON(!(status & NAND_STATUS_READY));
979 * nand_reset_data_interface - Reset data interface and timings
980 * @chip: The NAND chip
982 * Reset the Data interface and timings to ONFI mode 0.
984 * Returns 0 for success or negative error code otherwise.
986 static int nand_reset_data_interface(struct nand_chip *chip)
988 struct mtd_info *mtd = nand_to_mtd(chip);
989 const struct nand_data_interface *conf;
992 if (!chip->setup_data_interface)
996 * The ONFI specification says:
998 * To transition from NV-DDR or NV-DDR2 to the SDR data
999 * interface, the host shall use the Reset (FFh) command
1000 * using SDR timing mode 0. A device in any timing mode is
1001 * required to recognize Reset (FFh) command issued in SDR
1005 * Configure the data interface in SDR mode and set the
1006 * timings to timing mode 0.
1009 conf = nand_get_default_data_interface();
1010 ret = chip->setup_data_interface(mtd, conf, false);
1012 pr_err("Failed to configure data interface to SDR timing mode 0\n");
1018 * nand_setup_data_interface - Setup the best data interface and timings
1019 * @chip: The NAND chip
1021 * Find and configure the best data interface and NAND timings supported by
1022 * the chip and the driver.
1023 * First tries to retrieve supported timing modes from ONFI information,
1024 * and if the NAND chip does not support ONFI, relies on the
1025 * ->onfi_timing_mode_default specified in the nand_ids table.
1027 * Returns 0 for success or negative error code otherwise.
1029 static int nand_setup_data_interface(struct nand_chip *chip)
1031 struct mtd_info *mtd = nand_to_mtd(chip);
1034 if (!chip->setup_data_interface || !chip->data_interface)
1038 * Ensure the timing mode has been changed on the chip side
1039 * before changing timings on the controller side.
1041 if (chip->onfi_version) {
1042 u8 tmode_param[ONFI_SUBFEATURE_PARAM_LEN] = {
1043 chip->onfi_timing_mode_default,
1046 ret = chip->onfi_set_features(mtd, chip,
1047 ONFI_FEATURE_ADDR_TIMING_MODE,
1053 ret = chip->setup_data_interface(mtd, chip->data_interface, false);
1059 * nand_init_data_interface - find the best data interface and timings
1060 * @chip: The NAND chip
1062 * Find the best data interface and NAND timings supported by the chip
1064 * First tries to retrieve supported timing modes from ONFI information,
1065 * and if the NAND chip does not support ONFI, relies on the
1066 * ->onfi_timing_mode_default specified in the nand_ids table. After this
1067 * function nand_chip->data_interface is initialized with the best timing mode
1070 * Returns 0 for success or negative error code otherwise.
1072 static int nand_init_data_interface(struct nand_chip *chip)
1074 struct mtd_info *mtd = nand_to_mtd(chip);
1075 int modes, mode, ret;
1077 if (!chip->setup_data_interface)
1081 * First try to identify the best timings from ONFI parameters and
1082 * if the NAND does not support ONFI, fallback to the default ONFI
1085 modes = onfi_get_async_timing_mode(chip);
1086 if (modes == ONFI_TIMING_MODE_UNKNOWN) {
1087 if (!chip->onfi_timing_mode_default)
1090 modes = GENMASK(chip->onfi_timing_mode_default, 0);
1093 chip->data_interface = kzalloc(sizeof(*chip->data_interface),
1095 if (!chip->data_interface)
1098 for (mode = fls(modes) - 1; mode >= 0; mode--) {
1099 ret = onfi_init_data_interface(chip, chip->data_interface,
1100 NAND_SDR_IFACE, mode);
1104 ret = chip->setup_data_interface(mtd, chip->data_interface,
1107 chip->onfi_timing_mode_default = mode;
1115 static void nand_release_data_interface(struct nand_chip *chip)
1117 kfree(chip->data_interface);
1121 * nand_reset - Reset and initialize a NAND device
1122 * @chip: The NAND chip
1123 * @chipnr: Internal die id
1125 * Returns 0 for success or negative error code otherwise
1127 int nand_reset(struct nand_chip *chip, int chipnr)
1129 struct mtd_info *mtd = nand_to_mtd(chip);
1132 ret = nand_reset_data_interface(chip);
1137 * The CS line has to be released before we can apply the new NAND
1138 * interface settings, hence this weird ->select_chip() dance.
1140 chip->select_chip(mtd, chipnr);
1141 chip->cmdfunc(mtd, NAND_CMD_RESET, -1, -1);
1142 chip->select_chip(mtd, -1);
1144 chip->select_chip(mtd, chipnr);
1145 ret = nand_setup_data_interface(chip);
1146 chip->select_chip(mtd, -1);
1154 * __nand_unlock - [REPLACEABLE] unlocks specified locked blocks
1156 * @ofs: offset to start unlock from
1157 * @len: length to unlock
1158 * @invert: when = 0, unlock the range of blocks within the lower and
1159 * upper boundary address
1160 * when = 1, unlock the range of blocks outside the boundaries
1161 * of the lower and upper boundary address
1163 * Returs unlock status.
1165 static int __nand_unlock(struct mtd_info *mtd, loff_t ofs,
1166 uint64_t len, int invert)
1170 struct nand_chip *chip = mtd_to_nand(mtd);
1172 /* Submit address of first page to unlock */
1173 page = ofs >> chip->page_shift;
1174 chip->cmdfunc(mtd, NAND_CMD_UNLOCK1, -1, page & chip->pagemask);
1176 /* Submit address of last page to unlock */
1177 page = (ofs + len) >> chip->page_shift;
1178 chip->cmdfunc(mtd, NAND_CMD_UNLOCK2, -1,
1179 (page | invert) & chip->pagemask);
1181 /* Call wait ready function */
1182 status = chip->waitfunc(mtd, chip);
1183 /* See if device thinks it succeeded */
1184 if (status & NAND_STATUS_FAIL) {
1185 pr_debug("%s: error status = 0x%08x\n",
1194 * nand_unlock - [REPLACEABLE] unlocks specified locked blocks
1196 * @ofs: offset to start unlock from
1197 * @len: length to unlock
1199 * Returns unlock status.
1201 int nand_unlock(struct mtd_info *mtd, loff_t ofs, uint64_t len)
1205 struct nand_chip *chip = mtd_to_nand(mtd);
1207 pr_debug("%s: start = 0x%012llx, len = %llu\n",
1208 __func__, (unsigned long long)ofs, len);
1210 if (check_offs_len(mtd, ofs, len))
1213 /* Align to last block address if size addresses end of the device */
1214 if (ofs + len == mtd->size)
1215 len -= mtd->erasesize;
1217 nand_get_device(mtd, FL_UNLOCKING);
1219 /* Shift to get chip number */
1220 chipnr = ofs >> chip->chip_shift;
1224 * If we want to check the WP through READ STATUS and check the bit 7
1225 * we must reset the chip
1226 * some operation can also clear the bit 7 of status register
1227 * eg. erase/program a locked block
1229 nand_reset(chip, chipnr);
1231 chip->select_chip(mtd, chipnr);
1233 /* Check, if it is write protected */
1234 if (nand_check_wp(mtd)) {
1235 pr_debug("%s: device is write protected!\n",
1241 ret = __nand_unlock(mtd, ofs, len, 0);
1244 chip->select_chip(mtd, -1);
1245 nand_release_device(mtd);
1249 EXPORT_SYMBOL(nand_unlock);
1252 * nand_lock - [REPLACEABLE] locks all blocks present in the device
1254 * @ofs: offset to start unlock from
1255 * @len: length to unlock
1257 * This feature is not supported in many NAND parts. 'Micron' NAND parts do
1258 * have this feature, but it allows only to lock all blocks, not for specified
1259 * range for block. Implementing 'lock' feature by making use of 'unlock', for
1262 * Returns lock status.
1264 int nand_lock(struct mtd_info *mtd, loff_t ofs, uint64_t len)
1267 int chipnr, status, page;
1268 struct nand_chip *chip = mtd_to_nand(mtd);
1270 pr_debug("%s: start = 0x%012llx, len = %llu\n",
1271 __func__, (unsigned long long)ofs, len);
1273 if (check_offs_len(mtd, ofs, len))
1276 nand_get_device(mtd, FL_LOCKING);
1278 /* Shift to get chip number */
1279 chipnr = ofs >> chip->chip_shift;
1283 * If we want to check the WP through READ STATUS and check the bit 7
1284 * we must reset the chip
1285 * some operation can also clear the bit 7 of status register
1286 * eg. erase/program a locked block
1288 nand_reset(chip, chipnr);
1290 chip->select_chip(mtd, chipnr);
1292 /* Check, if it is write protected */
1293 if (nand_check_wp(mtd)) {
1294 pr_debug("%s: device is write protected!\n",
1296 status = MTD_ERASE_FAILED;
1301 /* Submit address of first page to lock */
1302 page = ofs >> chip->page_shift;
1303 chip->cmdfunc(mtd, NAND_CMD_LOCK, -1, page & chip->pagemask);
1305 /* Call wait ready function */
1306 status = chip->waitfunc(mtd, chip);
1307 /* See if device thinks it succeeded */
1308 if (status & NAND_STATUS_FAIL) {
1309 pr_debug("%s: error status = 0x%08x\n",
1315 ret = __nand_unlock(mtd, ofs, len, 0x1);
1318 chip->select_chip(mtd, -1);
1319 nand_release_device(mtd);
1323 EXPORT_SYMBOL(nand_lock);
1326 * nand_check_erased_buf - check if a buffer contains (almost) only 0xff data
1327 * @buf: buffer to test
1328 * @len: buffer length
1329 * @bitflips_threshold: maximum number of bitflips
1331 * Check if a buffer contains only 0xff, which means the underlying region
1332 * has been erased and is ready to be programmed.
1333 * The bitflips_threshold specify the maximum number of bitflips before
1334 * considering the region is not erased.
1335 * Note: The logic of this function has been extracted from the memweight
1336 * implementation, except that nand_check_erased_buf function exit before
1337 * testing the whole buffer if the number of bitflips exceed the
1338 * bitflips_threshold value.
1340 * Returns a positive number of bitflips less than or equal to
1341 * bitflips_threshold, or -ERROR_CODE for bitflips in excess of the
1344 static int nand_check_erased_buf(void *buf, int len, int bitflips_threshold)
1346 const unsigned char *bitmap = buf;
1350 for (; len && ((uintptr_t)bitmap) % sizeof(long);
1352 weight = hweight8(*bitmap);
1353 bitflips += BITS_PER_BYTE - weight;
1354 if (unlikely(bitflips > bitflips_threshold))
1358 for (; len >= sizeof(long);
1359 len -= sizeof(long), bitmap += sizeof(long)) {
1360 weight = hweight_long(*((unsigned long *)bitmap));
1361 bitflips += BITS_PER_LONG - weight;
1362 if (unlikely(bitflips > bitflips_threshold))
1366 for (; len > 0; len--, bitmap++) {
1367 weight = hweight8(*bitmap);
1368 bitflips += BITS_PER_BYTE - weight;
1369 if (unlikely(bitflips > bitflips_threshold))
1377 * nand_check_erased_ecc_chunk - check if an ECC chunk contains (almost) only
1379 * @data: data buffer to test
1380 * @datalen: data length
1382 * @ecclen: ECC length
1383 * @extraoob: extra OOB buffer
1384 * @extraooblen: extra OOB length
1385 * @bitflips_threshold: maximum number of bitflips
1387 * Check if a data buffer and its associated ECC and OOB data contains only
1388 * 0xff pattern, which means the underlying region has been erased and is
1389 * ready to be programmed.
1390 * The bitflips_threshold specify the maximum number of bitflips before
1391 * considering the region as not erased.
1394 * 1/ ECC algorithms are working on pre-defined block sizes which are usually
1395 * different from the NAND page size. When fixing bitflips, ECC engines will
1396 * report the number of errors per chunk, and the NAND core infrastructure
1397 * expect you to return the maximum number of bitflips for the whole page.
1398 * This is why you should always use this function on a single chunk and
1399 * not on the whole page. After checking each chunk you should update your
1400 * max_bitflips value accordingly.
1401 * 2/ When checking for bitflips in erased pages you should not only check
1402 * the payload data but also their associated ECC data, because a user might
1403 * have programmed almost all bits to 1 but a few. In this case, we
1404 * shouldn't consider the chunk as erased, and checking ECC bytes prevent
1406 * 3/ The extraoob argument is optional, and should be used if some of your OOB
1407 * data are protected by the ECC engine.
1408 * It could also be used if you support subpages and want to attach some
1409 * extra OOB data to an ECC chunk.
1411 * Returns a positive number of bitflips less than or equal to
1412 * bitflips_threshold, or -ERROR_CODE for bitflips in excess of the
1413 * threshold. In case of success, the passed buffers are filled with 0xff.
1415 int nand_check_erased_ecc_chunk(void *data, int datalen,
1416 void *ecc, int ecclen,
1417 void *extraoob, int extraooblen,
1418 int bitflips_threshold)
1420 int data_bitflips = 0, ecc_bitflips = 0, extraoob_bitflips = 0;
1422 data_bitflips = nand_check_erased_buf(data, datalen,
1423 bitflips_threshold);
1424 if (data_bitflips < 0)
1425 return data_bitflips;
1427 bitflips_threshold -= data_bitflips;
1429 ecc_bitflips = nand_check_erased_buf(ecc, ecclen, bitflips_threshold);
1430 if (ecc_bitflips < 0)
1431 return ecc_bitflips;
1433 bitflips_threshold -= ecc_bitflips;
1435 extraoob_bitflips = nand_check_erased_buf(extraoob, extraooblen,
1436 bitflips_threshold);
1437 if (extraoob_bitflips < 0)
1438 return extraoob_bitflips;
1441 memset(data, 0xff, datalen);
1444 memset(ecc, 0xff, ecclen);
1446 if (extraoob_bitflips)
1447 memset(extraoob, 0xff, extraooblen);
1449 return data_bitflips + ecc_bitflips + extraoob_bitflips;
1451 EXPORT_SYMBOL(nand_check_erased_ecc_chunk);
1454 * nand_read_page_raw - [INTERN] read raw page data without ecc
1455 * @mtd: mtd info structure
1456 * @chip: nand chip info structure
1457 * @buf: buffer to store read data
1458 * @oob_required: caller requires OOB data read to chip->oob_poi
1459 * @page: page number to read
1461 * Not for syndrome calculating ECC controllers, which use a special oob layout.
1463 static int nand_read_page_raw(struct mtd_info *mtd, struct nand_chip *chip,
1464 uint8_t *buf, int oob_required, int page)
1466 chip->read_buf(mtd, buf, mtd->writesize);
1468 chip->read_buf(mtd, chip->oob_poi, mtd->oobsize);
1473 * nand_read_page_raw_syndrome - [INTERN] read raw page data without ecc
1474 * @mtd: mtd info structure
1475 * @chip: nand chip info structure
1476 * @buf: buffer to store read data
1477 * @oob_required: caller requires OOB data read to chip->oob_poi
1478 * @page: page number to read
1480 * We need a special oob layout and handling even when OOB isn't used.
1482 static int nand_read_page_raw_syndrome(struct mtd_info *mtd,
1483 struct nand_chip *chip, uint8_t *buf,
1484 int oob_required, int page)
1486 int eccsize = chip->ecc.size;
1487 int eccbytes = chip->ecc.bytes;
1488 uint8_t *oob = chip->oob_poi;
1491 for (steps = chip->ecc.steps; steps > 0; steps--) {
1492 chip->read_buf(mtd, buf, eccsize);
1495 if (chip->ecc.prepad) {
1496 chip->read_buf(mtd, oob, chip->ecc.prepad);
1497 oob += chip->ecc.prepad;
1500 chip->read_buf(mtd, oob, eccbytes);
1503 if (chip->ecc.postpad) {
1504 chip->read_buf(mtd, oob, chip->ecc.postpad);
1505 oob += chip->ecc.postpad;
1509 size = mtd->oobsize - (oob - chip->oob_poi);
1511 chip->read_buf(mtd, oob, size);
1517 * nand_read_page_swecc - [REPLACEABLE] software ECC based page read function
1518 * @mtd: mtd info structure
1519 * @chip: nand chip info structure
1520 * @buf: buffer to store read data
1521 * @oob_required: caller requires OOB data read to chip->oob_poi
1522 * @page: page number to read
1524 static int nand_read_page_swecc(struct mtd_info *mtd, struct nand_chip *chip,
1525 uint8_t *buf, int oob_required, int page)
1527 int i, eccsize = chip->ecc.size, ret;
1528 int eccbytes = chip->ecc.bytes;
1529 int eccsteps = chip->ecc.steps;
1531 uint8_t *ecc_calc = chip->buffers->ecccalc;
1532 uint8_t *ecc_code = chip->buffers->ecccode;
1533 unsigned int max_bitflips = 0;
1535 chip->ecc.read_page_raw(mtd, chip, buf, 1, page);
1537 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize)
1538 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
1540 ret = mtd_ooblayout_get_eccbytes(mtd, ecc_code, chip->oob_poi, 0,
1545 eccsteps = chip->ecc.steps;
1548 for (i = 0 ; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
1551 stat = chip->ecc.correct(mtd, p, &ecc_code[i], &ecc_calc[i]);
1553 mtd->ecc_stats.failed++;
1555 mtd->ecc_stats.corrected += stat;
1556 max_bitflips = max_t(unsigned int, max_bitflips, stat);
1559 return max_bitflips;
1563 * nand_read_subpage - [REPLACEABLE] ECC based sub-page read function
1564 * @mtd: mtd info structure
1565 * @chip: nand chip info structure
1566 * @data_offs: offset of requested data within the page
1567 * @readlen: data length
1568 * @bufpoi: buffer to store read data
1569 * @page: page number to read
1571 static int nand_read_subpage(struct mtd_info *mtd, struct nand_chip *chip,
1572 uint32_t data_offs, uint32_t readlen, uint8_t *bufpoi,
1575 int start_step, end_step, num_steps, ret;
1577 int data_col_addr, i, gaps = 0;
1578 int datafrag_len, eccfrag_len, aligned_len, aligned_pos;
1579 int busw = (chip->options & NAND_BUSWIDTH_16) ? 2 : 1;
1580 int index, section = 0;
1581 unsigned int max_bitflips = 0;
1582 struct mtd_oob_region oobregion = { };
1584 /* Column address within the page aligned to ECC size (256bytes) */
1585 start_step = data_offs / chip->ecc.size;
1586 end_step = (data_offs + readlen - 1) / chip->ecc.size;
1587 num_steps = end_step - start_step + 1;
1588 index = start_step * chip->ecc.bytes;
1590 /* Data size aligned to ECC ecc.size */
1591 datafrag_len = num_steps * chip->ecc.size;
1592 eccfrag_len = num_steps * chip->ecc.bytes;
1594 data_col_addr = start_step * chip->ecc.size;
1595 /* If we read not a page aligned data */
1596 if (data_col_addr != 0)
1597 chip->cmdfunc(mtd, NAND_CMD_RNDOUT, data_col_addr, -1);
1599 p = bufpoi + data_col_addr;
1600 chip->read_buf(mtd, p, datafrag_len);
1603 for (i = 0; i < eccfrag_len ; i += chip->ecc.bytes, p += chip->ecc.size)
1604 chip->ecc.calculate(mtd, p, &chip->buffers->ecccalc[i]);
1607 * The performance is faster if we position offsets according to
1608 * ecc.pos. Let's make sure that there are no gaps in ECC positions.
1610 ret = mtd_ooblayout_find_eccregion(mtd, index, §ion, &oobregion);
1614 if (oobregion.length < eccfrag_len)
1618 chip->cmdfunc(mtd, NAND_CMD_RNDOUT, mtd->writesize, -1);
1619 chip->read_buf(mtd, chip->oob_poi, mtd->oobsize);
1622 * Send the command to read the particular ECC bytes take care
1623 * about buswidth alignment in read_buf.
1625 aligned_pos = oobregion.offset & ~(busw - 1);
1626 aligned_len = eccfrag_len;
1627 if (oobregion.offset & (busw - 1))
1629 if ((oobregion.offset + (num_steps * chip->ecc.bytes)) &
1633 chip->cmdfunc(mtd, NAND_CMD_RNDOUT,
1634 mtd->writesize + aligned_pos, -1);
1635 chip->read_buf(mtd, &chip->oob_poi[aligned_pos], aligned_len);
1638 ret = mtd_ooblayout_get_eccbytes(mtd, chip->buffers->ecccode,
1639 chip->oob_poi, index, eccfrag_len);
1643 p = bufpoi + data_col_addr;
1644 for (i = 0; i < eccfrag_len ; i += chip->ecc.bytes, p += chip->ecc.size) {
1647 stat = chip->ecc.correct(mtd, p,
1648 &chip->buffers->ecccode[i], &chip->buffers->ecccalc[i]);
1649 if (stat == -EBADMSG &&
1650 (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
1651 /* check for empty pages with bitflips */
1652 stat = nand_check_erased_ecc_chunk(p, chip->ecc.size,
1653 &chip->buffers->ecccode[i],
1656 chip->ecc.strength);
1660 mtd->ecc_stats.failed++;
1662 mtd->ecc_stats.corrected += stat;
1663 max_bitflips = max_t(unsigned int, max_bitflips, stat);
1666 return max_bitflips;
1670 * nand_read_page_hwecc - [REPLACEABLE] hardware ECC based page read function
1671 * @mtd: mtd info structure
1672 * @chip: nand chip info structure
1673 * @buf: buffer to store read data
1674 * @oob_required: caller requires OOB data read to chip->oob_poi
1675 * @page: page number to read
1677 * Not for syndrome calculating ECC controllers which need a special oob layout.
1679 static int nand_read_page_hwecc(struct mtd_info *mtd, struct nand_chip *chip,
1680 uint8_t *buf, int oob_required, int page)
1682 int i, eccsize = chip->ecc.size, ret;
1683 int eccbytes = chip->ecc.bytes;
1684 int eccsteps = chip->ecc.steps;
1686 uint8_t *ecc_calc = chip->buffers->ecccalc;
1687 uint8_t *ecc_code = chip->buffers->ecccode;
1688 unsigned int max_bitflips = 0;
1690 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
1691 chip->ecc.hwctl(mtd, NAND_ECC_READ);
1692 chip->read_buf(mtd, p, eccsize);
1693 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
1695 chip->read_buf(mtd, chip->oob_poi, mtd->oobsize);
1697 ret = mtd_ooblayout_get_eccbytes(mtd, ecc_code, chip->oob_poi, 0,
1702 eccsteps = chip->ecc.steps;
1705 for (i = 0 ; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
1708 stat = chip->ecc.correct(mtd, p, &ecc_code[i], &ecc_calc[i]);
1709 if (stat == -EBADMSG &&
1710 (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
1711 /* check for empty pages with bitflips */
1712 stat = nand_check_erased_ecc_chunk(p, eccsize,
1713 &ecc_code[i], eccbytes,
1715 chip->ecc.strength);
1719 mtd->ecc_stats.failed++;
1721 mtd->ecc_stats.corrected += stat;
1722 max_bitflips = max_t(unsigned int, max_bitflips, stat);
1725 return max_bitflips;
1729 * nand_read_page_hwecc_oob_first - [REPLACEABLE] hw ecc, read oob first
1730 * @mtd: mtd info structure
1731 * @chip: nand chip info structure
1732 * @buf: buffer to store read data
1733 * @oob_required: caller requires OOB data read to chip->oob_poi
1734 * @page: page number to read
1736 * Hardware ECC for large page chips, require OOB to be read first. For this
1737 * ECC mode, the write_page method is re-used from ECC_HW. These methods
1738 * read/write ECC from the OOB area, unlike the ECC_HW_SYNDROME support with
1739 * multiple ECC steps, follows the "infix ECC" scheme and reads/writes ECC from
1740 * the data area, by overwriting the NAND manufacturer bad block markings.
1742 static int nand_read_page_hwecc_oob_first(struct mtd_info *mtd,
1743 struct nand_chip *chip, uint8_t *buf, int oob_required, int page)
1745 int i, eccsize = chip->ecc.size, ret;
1746 int eccbytes = chip->ecc.bytes;
1747 int eccsteps = chip->ecc.steps;
1749 uint8_t *ecc_code = chip->buffers->ecccode;
1750 uint8_t *ecc_calc = chip->buffers->ecccalc;
1751 unsigned int max_bitflips = 0;
1753 /* Read the OOB area first */
1754 chip->cmdfunc(mtd, NAND_CMD_READOOB, 0, page);
1755 chip->read_buf(mtd, chip->oob_poi, mtd->oobsize);
1756 chip->cmdfunc(mtd, NAND_CMD_READ0, 0, page);
1758 ret = mtd_ooblayout_get_eccbytes(mtd, ecc_code, chip->oob_poi, 0,
1763 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
1766 chip->ecc.hwctl(mtd, NAND_ECC_READ);
1767 chip->read_buf(mtd, p, eccsize);
1768 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
1770 stat = chip->ecc.correct(mtd, p, &ecc_code[i], NULL);
1771 if (stat == -EBADMSG &&
1772 (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
1773 /* check for empty pages with bitflips */
1774 stat = nand_check_erased_ecc_chunk(p, eccsize,
1775 &ecc_code[i], eccbytes,
1777 chip->ecc.strength);
1781 mtd->ecc_stats.failed++;
1783 mtd->ecc_stats.corrected += stat;
1784 max_bitflips = max_t(unsigned int, max_bitflips, stat);
1787 return max_bitflips;
1791 * nand_read_page_syndrome - [REPLACEABLE] hardware ECC syndrome based page read
1792 * @mtd: mtd info structure
1793 * @chip: nand chip info structure
1794 * @buf: buffer to store read data
1795 * @oob_required: caller requires OOB data read to chip->oob_poi
1796 * @page: page number to read
1798 * The hw generator calculates the error syndrome automatically. Therefore we
1799 * need a special oob layout and handling.
1801 static int nand_read_page_syndrome(struct mtd_info *mtd, struct nand_chip *chip,
1802 uint8_t *buf, int oob_required, int page)
1804 int i, eccsize = chip->ecc.size;
1805 int eccbytes = chip->ecc.bytes;
1806 int eccsteps = chip->ecc.steps;
1807 int eccpadbytes = eccbytes + chip->ecc.prepad + chip->ecc.postpad;
1809 uint8_t *oob = chip->oob_poi;
1810 unsigned int max_bitflips = 0;
1812 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
1815 chip->ecc.hwctl(mtd, NAND_ECC_READ);
1816 chip->read_buf(mtd, p, eccsize);
1818 if (chip->ecc.prepad) {
1819 chip->read_buf(mtd, oob, chip->ecc.prepad);
1820 oob += chip->ecc.prepad;
1823 chip->ecc.hwctl(mtd, NAND_ECC_READSYN);
1824 chip->read_buf(mtd, oob, eccbytes);
1825 stat = chip->ecc.correct(mtd, p, oob, NULL);
1829 if (chip->ecc.postpad) {
1830 chip->read_buf(mtd, oob, chip->ecc.postpad);
1831 oob += chip->ecc.postpad;
1834 if (stat == -EBADMSG &&
1835 (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
1836 /* check for empty pages with bitflips */
1837 stat = nand_check_erased_ecc_chunk(p, chip->ecc.size,
1841 chip->ecc.strength);
1845 mtd->ecc_stats.failed++;
1847 mtd->ecc_stats.corrected += stat;
1848 max_bitflips = max_t(unsigned int, max_bitflips, stat);
1852 /* Calculate remaining oob bytes */
1853 i = mtd->oobsize - (oob - chip->oob_poi);
1855 chip->read_buf(mtd, oob, i);
1857 return max_bitflips;
1861 * nand_transfer_oob - [INTERN] Transfer oob to client buffer
1862 * @mtd: mtd info structure
1863 * @oob: oob destination address
1864 * @ops: oob ops structure
1865 * @len: size of oob to transfer
1867 static uint8_t *nand_transfer_oob(struct mtd_info *mtd, uint8_t *oob,
1868 struct mtd_oob_ops *ops, size_t len)
1870 struct nand_chip *chip = mtd_to_nand(mtd);
1873 switch (ops->mode) {
1875 case MTD_OPS_PLACE_OOB:
1877 memcpy(oob, chip->oob_poi + ops->ooboffs, len);
1880 case MTD_OPS_AUTO_OOB:
1881 ret = mtd_ooblayout_get_databytes(mtd, oob, chip->oob_poi,
1893 * nand_setup_read_retry - [INTERN] Set the READ RETRY mode
1894 * @mtd: MTD device structure
1895 * @retry_mode: the retry mode to use
1897 * Some vendors supply a special command to shift the Vt threshold, to be used
1898 * when there are too many bitflips in a page (i.e., ECC error). After setting
1899 * a new threshold, the host should retry reading the page.
1901 static int nand_setup_read_retry(struct mtd_info *mtd, int retry_mode)
1903 struct nand_chip *chip = mtd_to_nand(mtd);
1905 pr_debug("setting READ RETRY mode %d\n", retry_mode);
1907 if (retry_mode >= chip->read_retries)
1910 if (!chip->setup_read_retry)
1913 return chip->setup_read_retry(mtd, retry_mode);
1917 * nand_do_read_ops - [INTERN] Read data with ECC
1918 * @mtd: MTD device structure
1919 * @from: offset to read from
1920 * @ops: oob ops structure
1922 * Internal function. Called with chip held.
1924 static int nand_do_read_ops(struct mtd_info *mtd, loff_t from,
1925 struct mtd_oob_ops *ops)
1927 int chipnr, page, realpage, col, bytes, aligned, oob_required;
1928 struct nand_chip *chip = mtd_to_nand(mtd);
1930 uint32_t readlen = ops->len;
1931 uint32_t oobreadlen = ops->ooblen;
1932 uint32_t max_oobsize = mtd_oobavail(mtd, ops);
1934 uint8_t *bufpoi, *oob, *buf;
1936 unsigned int max_bitflips = 0;
1938 bool ecc_fail = false;
1940 chipnr = (int)(from >> chip->chip_shift);
1941 chip->select_chip(mtd, chipnr);
1943 realpage = (int)(from >> chip->page_shift);
1944 page = realpage & chip->pagemask;
1946 col = (int)(from & (mtd->writesize - 1));
1950 oob_required = oob ? 1 : 0;
1953 unsigned int ecc_failures = mtd->ecc_stats.failed;
1955 bytes = min(mtd->writesize - col, readlen);
1956 aligned = (bytes == mtd->writesize);
1960 else if (chip->options & NAND_USE_BOUNCE_BUFFER)
1961 use_bufpoi = !virt_addr_valid(buf);
1965 /* Is the current page in the buffer? */
1966 if (realpage != chip->pagebuf || oob) {
1967 bufpoi = use_bufpoi ? chip->buffers->databuf : buf;
1969 if (use_bufpoi && aligned)
1970 pr_debug("%s: using read bounce buffer for buf@%p\n",
1974 if (nand_standard_page_accessors(&chip->ecc))
1975 chip->cmdfunc(mtd, NAND_CMD_READ0, 0x00, page);
1978 * Now read the page into the buffer. Absent an error,
1979 * the read methods return max bitflips per ecc step.
1981 if (unlikely(ops->mode == MTD_OPS_RAW))
1982 ret = chip->ecc.read_page_raw(mtd, chip, bufpoi,
1985 else if (!aligned && NAND_HAS_SUBPAGE_READ(chip) &&
1987 ret = chip->ecc.read_subpage(mtd, chip,
1991 ret = chip->ecc.read_page(mtd, chip, bufpoi,
1992 oob_required, page);
1995 /* Invalidate page cache */
2000 max_bitflips = max_t(unsigned int, max_bitflips, ret);
2002 /* Transfer not aligned data */
2004 if (!NAND_HAS_SUBPAGE_READ(chip) && !oob &&
2005 !(mtd->ecc_stats.failed - ecc_failures) &&
2006 (ops->mode != MTD_OPS_RAW)) {
2007 chip->pagebuf = realpage;
2008 chip->pagebuf_bitflips = ret;
2010 /* Invalidate page cache */
2013 memcpy(buf, chip->buffers->databuf + col, bytes);
2016 if (unlikely(oob)) {
2017 int toread = min(oobreadlen, max_oobsize);
2020 oob = nand_transfer_oob(mtd,
2022 oobreadlen -= toread;
2026 if (chip->options & NAND_NEED_READRDY) {
2027 /* Apply delay or wait for ready/busy pin */
2028 if (!chip->dev_ready)
2029 udelay(chip->chip_delay);
2031 nand_wait_ready(mtd);
2034 if (mtd->ecc_stats.failed - ecc_failures) {
2035 if (retry_mode + 1 < chip->read_retries) {
2037 ret = nand_setup_read_retry(mtd,
2042 /* Reset failures; retry */
2043 mtd->ecc_stats.failed = ecc_failures;
2046 /* No more retry modes; real failure */
2053 memcpy(buf, chip->buffers->databuf + col, bytes);
2055 max_bitflips = max_t(unsigned int, max_bitflips,
2056 chip->pagebuf_bitflips);
2061 /* Reset to retry mode 0 */
2063 ret = nand_setup_read_retry(mtd, 0);
2072 /* For subsequent reads align to page boundary */
2074 /* Increment page address */
2077 page = realpage & chip->pagemask;
2078 /* Check, if we cross a chip boundary */
2081 chip->select_chip(mtd, -1);
2082 chip->select_chip(mtd, chipnr);
2085 chip->select_chip(mtd, -1);
2087 ops->retlen = ops->len - (size_t) readlen;
2089 ops->oobretlen = ops->ooblen - oobreadlen;
2097 return max_bitflips;
2101 * nand_read - [MTD Interface] MTD compatibility function for nand_do_read_ecc
2102 * @mtd: MTD device structure
2103 * @from: offset to read from
2104 * @len: number of bytes to read
2105 * @retlen: pointer to variable to store the number of read bytes
2106 * @buf: the databuffer to put data
2108 * Get hold of the chip and call nand_do_read.
2110 static int nand_read(struct mtd_info *mtd, loff_t from, size_t len,
2111 size_t *retlen, uint8_t *buf)
2113 struct mtd_oob_ops ops;
2116 nand_get_device(mtd, FL_READING);
2117 memset(&ops, 0, sizeof(ops));
2120 ops.mode = MTD_OPS_PLACE_OOB;
2121 ret = nand_do_read_ops(mtd, from, &ops);
2122 *retlen = ops.retlen;
2123 nand_release_device(mtd);
2128 * nand_read_oob_std - [REPLACEABLE] the most common OOB data read function
2129 * @mtd: mtd info structure
2130 * @chip: nand chip info structure
2131 * @page: page number to read
2133 int nand_read_oob_std(struct mtd_info *mtd, struct nand_chip *chip, int page)
2135 chip->cmdfunc(mtd, NAND_CMD_READOOB, 0, page);
2136 chip->read_buf(mtd, chip->oob_poi, mtd->oobsize);
2139 EXPORT_SYMBOL(nand_read_oob_std);
2142 * nand_read_oob_syndrome - [REPLACEABLE] OOB data read function for HW ECC
2144 * @mtd: mtd info structure
2145 * @chip: nand chip info structure
2146 * @page: page number to read
2148 int nand_read_oob_syndrome(struct mtd_info *mtd, struct nand_chip *chip,
2151 int length = mtd->oobsize;
2152 int chunk = chip->ecc.bytes + chip->ecc.prepad + chip->ecc.postpad;
2153 int eccsize = chip->ecc.size;
2154 uint8_t *bufpoi = chip->oob_poi;
2155 int i, toread, sndrnd = 0, pos;
2157 chip->cmdfunc(mtd, NAND_CMD_READ0, chip->ecc.size, page);
2158 for (i = 0; i < chip->ecc.steps; i++) {
2160 pos = eccsize + i * (eccsize + chunk);
2161 if (mtd->writesize > 512)
2162 chip->cmdfunc(mtd, NAND_CMD_RNDOUT, pos, -1);
2164 chip->cmdfunc(mtd, NAND_CMD_READ0, pos, page);
2167 toread = min_t(int, length, chunk);
2168 chip->read_buf(mtd, bufpoi, toread);
2173 chip->read_buf(mtd, bufpoi, length);
2177 EXPORT_SYMBOL(nand_read_oob_syndrome);
2180 * nand_write_oob_std - [REPLACEABLE] the most common OOB data write function
2181 * @mtd: mtd info structure
2182 * @chip: nand chip info structure
2183 * @page: page number to write
2185 int nand_write_oob_std(struct mtd_info *mtd, struct nand_chip *chip, int page)
2188 const uint8_t *buf = chip->oob_poi;
2189 int length = mtd->oobsize;
2191 chip->cmdfunc(mtd, NAND_CMD_SEQIN, mtd->writesize, page);
2192 chip->write_buf(mtd, buf, length);
2193 /* Send command to program the OOB data */
2194 chip->cmdfunc(mtd, NAND_CMD_PAGEPROG, -1, -1);
2196 status = chip->waitfunc(mtd, chip);
2198 return status & NAND_STATUS_FAIL ? -EIO : 0;
2200 EXPORT_SYMBOL(nand_write_oob_std);
2203 * nand_write_oob_syndrome - [REPLACEABLE] OOB data write function for HW ECC
2204 * with syndrome - only for large page flash
2205 * @mtd: mtd info structure
2206 * @chip: nand chip info structure
2207 * @page: page number to write
2209 int nand_write_oob_syndrome(struct mtd_info *mtd, struct nand_chip *chip,
2212 int chunk = chip->ecc.bytes + chip->ecc.prepad + chip->ecc.postpad;
2213 int eccsize = chip->ecc.size, length = mtd->oobsize;
2214 int i, len, pos, status = 0, sndcmd = 0, steps = chip->ecc.steps;
2215 const uint8_t *bufpoi = chip->oob_poi;
2218 * data-ecc-data-ecc ... ecc-oob
2220 * data-pad-ecc-pad-data-pad .... ecc-pad-oob
2222 if (!chip->ecc.prepad && !chip->ecc.postpad) {
2223 pos = steps * (eccsize + chunk);
2228 chip->cmdfunc(mtd, NAND_CMD_SEQIN, pos, page);
2229 for (i = 0; i < steps; i++) {
2231 if (mtd->writesize <= 512) {
2232 uint32_t fill = 0xFFFFFFFF;
2236 int num = min_t(int, len, 4);
2237 chip->write_buf(mtd, (uint8_t *)&fill,
2242 pos = eccsize + i * (eccsize + chunk);
2243 chip->cmdfunc(mtd, NAND_CMD_RNDIN, pos, -1);
2247 len = min_t(int, length, chunk);
2248 chip->write_buf(mtd, bufpoi, len);
2253 chip->write_buf(mtd, bufpoi, length);
2255 chip->cmdfunc(mtd, NAND_CMD_PAGEPROG, -1, -1);
2256 status = chip->waitfunc(mtd, chip);
2258 return status & NAND_STATUS_FAIL ? -EIO : 0;
2260 EXPORT_SYMBOL(nand_write_oob_syndrome);
2263 * nand_do_read_oob - [INTERN] NAND read out-of-band
2264 * @mtd: MTD device structure
2265 * @from: offset to read from
2266 * @ops: oob operations description structure
2268 * NAND read out-of-band data from the spare area.
2270 static int nand_do_read_oob(struct mtd_info *mtd, loff_t from,
2271 struct mtd_oob_ops *ops)
2273 int page, realpage, chipnr;
2274 struct nand_chip *chip = mtd_to_nand(mtd);
2275 struct mtd_ecc_stats stats;
2276 int readlen = ops->ooblen;
2278 uint8_t *buf = ops->oobbuf;
2281 pr_debug("%s: from = 0x%08Lx, len = %i\n",
2282 __func__, (unsigned long long)from, readlen);
2284 stats = mtd->ecc_stats;
2286 len = mtd_oobavail(mtd, ops);
2288 if (unlikely(ops->ooboffs >= len)) {
2289 pr_debug("%s: attempt to start read outside oob\n",
2294 /* Do not allow reads past end of device */
2295 if (unlikely(from >= mtd->size ||
2296 ops->ooboffs + readlen > ((mtd->size >> chip->page_shift) -
2297 (from >> chip->page_shift)) * len)) {
2298 pr_debug("%s: attempt to read beyond end of device\n",
2303 chipnr = (int)(from >> chip->chip_shift);
2304 chip->select_chip(mtd, chipnr);
2306 /* Shift to get page */
2307 realpage = (int)(from >> chip->page_shift);
2308 page = realpage & chip->pagemask;
2311 if (ops->mode == MTD_OPS_RAW)
2312 ret = chip->ecc.read_oob_raw(mtd, chip, page);
2314 ret = chip->ecc.read_oob(mtd, chip, page);
2319 len = min(len, readlen);
2320 buf = nand_transfer_oob(mtd, buf, ops, len);
2322 if (chip->options & NAND_NEED_READRDY) {
2323 /* Apply delay or wait for ready/busy pin */
2324 if (!chip->dev_ready)
2325 udelay(chip->chip_delay);
2327 nand_wait_ready(mtd);
2334 /* Increment page address */
2337 page = realpage & chip->pagemask;
2338 /* Check, if we cross a chip boundary */
2341 chip->select_chip(mtd, -1);
2342 chip->select_chip(mtd, chipnr);
2345 chip->select_chip(mtd, -1);
2347 ops->oobretlen = ops->ooblen - readlen;
2352 if (mtd->ecc_stats.failed - stats.failed)
2355 return mtd->ecc_stats.corrected - stats.corrected ? -EUCLEAN : 0;
2359 * nand_read_oob - [MTD Interface] NAND read data and/or out-of-band
2360 * @mtd: MTD device structure
2361 * @from: offset to read from
2362 * @ops: oob operation description structure
2364 * NAND read data and/or out-of-band data.
2366 static int nand_read_oob(struct mtd_info *mtd, loff_t from,
2367 struct mtd_oob_ops *ops)
2373 /* Do not allow reads past end of device */
2374 if (ops->datbuf && (from + ops->len) > mtd->size) {
2375 pr_debug("%s: attempt to read beyond end of device\n",
2380 if (ops->mode != MTD_OPS_PLACE_OOB &&
2381 ops->mode != MTD_OPS_AUTO_OOB &&
2382 ops->mode != MTD_OPS_RAW)
2385 nand_get_device(mtd, FL_READING);
2388 ret = nand_do_read_oob(mtd, from, ops);
2390 ret = nand_do_read_ops(mtd, from, ops);
2392 nand_release_device(mtd);
2398 * nand_write_page_raw - [INTERN] raw page write function
2399 * @mtd: mtd info structure
2400 * @chip: nand chip info structure
2402 * @oob_required: must write chip->oob_poi to OOB
2403 * @page: page number to write
2405 * Not for syndrome calculating ECC controllers, which use a special oob layout.
2407 static int nand_write_page_raw(struct mtd_info *mtd, struct nand_chip *chip,
2408 const uint8_t *buf, int oob_required, int page)
2410 chip->write_buf(mtd, buf, mtd->writesize);
2412 chip->write_buf(mtd, chip->oob_poi, mtd->oobsize);
2418 * nand_write_page_raw_syndrome - [INTERN] raw page write function
2419 * @mtd: mtd info structure
2420 * @chip: nand chip info structure
2422 * @oob_required: must write chip->oob_poi to OOB
2423 * @page: page number to write
2425 * We need a special oob layout and handling even when ECC isn't checked.
2427 static int nand_write_page_raw_syndrome(struct mtd_info *mtd,
2428 struct nand_chip *chip,
2429 const uint8_t *buf, int oob_required,
2432 int eccsize = chip->ecc.size;
2433 int eccbytes = chip->ecc.bytes;
2434 uint8_t *oob = chip->oob_poi;
2437 for (steps = chip->ecc.steps; steps > 0; steps--) {
2438 chip->write_buf(mtd, buf, eccsize);
2441 if (chip->ecc.prepad) {
2442 chip->write_buf(mtd, oob, chip->ecc.prepad);
2443 oob += chip->ecc.prepad;
2446 chip->write_buf(mtd, oob, eccbytes);
2449 if (chip->ecc.postpad) {
2450 chip->write_buf(mtd, oob, chip->ecc.postpad);
2451 oob += chip->ecc.postpad;
2455 size = mtd->oobsize - (oob - chip->oob_poi);
2457 chip->write_buf(mtd, oob, size);
2462 * nand_write_page_swecc - [REPLACEABLE] software ECC based page write function
2463 * @mtd: mtd info structure
2464 * @chip: nand chip info structure
2466 * @oob_required: must write chip->oob_poi to OOB
2467 * @page: page number to write
2469 static int nand_write_page_swecc(struct mtd_info *mtd, struct nand_chip *chip,
2470 const uint8_t *buf, int oob_required,
2473 int i, eccsize = chip->ecc.size, ret;
2474 int eccbytes = chip->ecc.bytes;
2475 int eccsteps = chip->ecc.steps;
2476 uint8_t *ecc_calc = chip->buffers->ecccalc;
2477 const uint8_t *p = buf;
2479 /* Software ECC calculation */
2480 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize)
2481 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
2483 ret = mtd_ooblayout_set_eccbytes(mtd, ecc_calc, chip->oob_poi, 0,
2488 return chip->ecc.write_page_raw(mtd, chip, buf, 1, page);
2492 * nand_write_page_hwecc - [REPLACEABLE] hardware ECC based page write function
2493 * @mtd: mtd info structure
2494 * @chip: nand chip info structure
2496 * @oob_required: must write chip->oob_poi to OOB
2497 * @page: page number to write
2499 static int nand_write_page_hwecc(struct mtd_info *mtd, struct nand_chip *chip,
2500 const uint8_t *buf, int oob_required,
2503 int i, eccsize = chip->ecc.size, ret;
2504 int eccbytes = chip->ecc.bytes;
2505 int eccsteps = chip->ecc.steps;
2506 uint8_t *ecc_calc = chip->buffers->ecccalc;
2507 const uint8_t *p = buf;
2509 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
2510 chip->ecc.hwctl(mtd, NAND_ECC_WRITE);
2511 chip->write_buf(mtd, p, eccsize);
2512 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
2515 ret = mtd_ooblayout_set_eccbytes(mtd, ecc_calc, chip->oob_poi, 0,
2520 chip->write_buf(mtd, chip->oob_poi, mtd->oobsize);
2527 * nand_write_subpage_hwecc - [REPLACEABLE] hardware ECC based subpage write
2528 * @mtd: mtd info structure
2529 * @chip: nand chip info structure
2530 * @offset: column address of subpage within the page
2531 * @data_len: data length
2533 * @oob_required: must write chip->oob_poi to OOB
2534 * @page: page number to write
2536 static int nand_write_subpage_hwecc(struct mtd_info *mtd,
2537 struct nand_chip *chip, uint32_t offset,
2538 uint32_t data_len, const uint8_t *buf,
2539 int oob_required, int page)
2541 uint8_t *oob_buf = chip->oob_poi;
2542 uint8_t *ecc_calc = chip->buffers->ecccalc;
2543 int ecc_size = chip->ecc.size;
2544 int ecc_bytes = chip->ecc.bytes;
2545 int ecc_steps = chip->ecc.steps;
2546 uint32_t start_step = offset / ecc_size;
2547 uint32_t end_step = (offset + data_len - 1) / ecc_size;
2548 int oob_bytes = mtd->oobsize / ecc_steps;
2551 for (step = 0; step < ecc_steps; step++) {
2552 /* configure controller for WRITE access */
2553 chip->ecc.hwctl(mtd, NAND_ECC_WRITE);
2555 /* write data (untouched subpages already masked by 0xFF) */
2556 chip->write_buf(mtd, buf, ecc_size);
2558 /* mask ECC of un-touched subpages by padding 0xFF */
2559 if ((step < start_step) || (step > end_step))
2560 memset(ecc_calc, 0xff, ecc_bytes);
2562 chip->ecc.calculate(mtd, buf, ecc_calc);
2564 /* mask OOB of un-touched subpages by padding 0xFF */
2565 /* if oob_required, preserve OOB metadata of written subpage */
2566 if (!oob_required || (step < start_step) || (step > end_step))
2567 memset(oob_buf, 0xff, oob_bytes);
2570 ecc_calc += ecc_bytes;
2571 oob_buf += oob_bytes;
2574 /* copy calculated ECC for whole page to chip->buffer->oob */
2575 /* this include masked-value(0xFF) for unwritten subpages */
2576 ecc_calc = chip->buffers->ecccalc;
2577 ret = mtd_ooblayout_set_eccbytes(mtd, ecc_calc, chip->oob_poi, 0,
2582 /* write OOB buffer to NAND device */
2583 chip->write_buf(mtd, chip->oob_poi, mtd->oobsize);
2590 * nand_write_page_syndrome - [REPLACEABLE] hardware ECC syndrome based page write
2591 * @mtd: mtd info structure
2592 * @chip: nand chip info structure
2594 * @oob_required: must write chip->oob_poi to OOB
2595 * @page: page number to write
2597 * The hw generator calculates the error syndrome automatically. Therefore we
2598 * need a special oob layout and handling.
2600 static int nand_write_page_syndrome(struct mtd_info *mtd,
2601 struct nand_chip *chip,
2602 const uint8_t *buf, int oob_required,
2605 int i, eccsize = chip->ecc.size;
2606 int eccbytes = chip->ecc.bytes;
2607 int eccsteps = chip->ecc.steps;
2608 const uint8_t *p = buf;
2609 uint8_t *oob = chip->oob_poi;
2611 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
2613 chip->ecc.hwctl(mtd, NAND_ECC_WRITE);
2614 chip->write_buf(mtd, p, eccsize);
2616 if (chip->ecc.prepad) {
2617 chip->write_buf(mtd, oob, chip->ecc.prepad);
2618 oob += chip->ecc.prepad;
2621 chip->ecc.calculate(mtd, p, oob);
2622 chip->write_buf(mtd, oob, eccbytes);
2625 if (chip->ecc.postpad) {
2626 chip->write_buf(mtd, oob, chip->ecc.postpad);
2627 oob += chip->ecc.postpad;
2631 /* Calculate remaining oob bytes */
2632 i = mtd->oobsize - (oob - chip->oob_poi);
2634 chip->write_buf(mtd, oob, i);
2640 * nand_write_page - [REPLACEABLE] write one page
2641 * @mtd: MTD device structure
2642 * @chip: NAND chip descriptor
2643 * @offset: address offset within the page
2644 * @data_len: length of actual data to be written
2645 * @buf: the data to write
2646 * @oob_required: must write chip->oob_poi to OOB
2647 * @page: page number to write
2648 * @cached: cached programming
2649 * @raw: use _raw version of write_page
2651 static int nand_write_page(struct mtd_info *mtd, struct nand_chip *chip,
2652 uint32_t offset, int data_len, const uint8_t *buf,
2653 int oob_required, int page, int cached, int raw)
2655 int status, subpage;
2657 if (!(chip->options & NAND_NO_SUBPAGE_WRITE) &&
2658 chip->ecc.write_subpage)
2659 subpage = offset || (data_len < mtd->writesize);
2663 if (nand_standard_page_accessors(&chip->ecc))
2664 chip->cmdfunc(mtd, NAND_CMD_SEQIN, 0x00, page);
2667 status = chip->ecc.write_page_raw(mtd, chip, buf,
2668 oob_required, page);
2670 status = chip->ecc.write_subpage(mtd, chip, offset, data_len,
2671 buf, oob_required, page);
2673 status = chip->ecc.write_page(mtd, chip, buf, oob_required,
2680 * Cached progamming disabled for now. Not sure if it's worth the
2681 * trouble. The speed gain is not very impressive. (2.3->2.6Mib/s).
2685 if (!cached || !NAND_HAS_CACHEPROG(chip)) {
2687 if (nand_standard_page_accessors(&chip->ecc))
2688 chip->cmdfunc(mtd, NAND_CMD_PAGEPROG, -1, -1);
2689 status = chip->waitfunc(mtd, chip);
2691 * See if operation failed and additional status checks are
2694 if ((status & NAND_STATUS_FAIL) && (chip->errstat))
2695 status = chip->errstat(mtd, chip, FL_WRITING, status,
2698 if (status & NAND_STATUS_FAIL)
2701 chip->cmdfunc(mtd, NAND_CMD_CACHEDPROG, -1, -1);
2702 status = chip->waitfunc(mtd, chip);
2709 * nand_fill_oob - [INTERN] Transfer client buffer to oob
2710 * @mtd: MTD device structure
2711 * @oob: oob data buffer
2712 * @len: oob data write length
2713 * @ops: oob ops structure
2715 static uint8_t *nand_fill_oob(struct mtd_info *mtd, uint8_t *oob, size_t len,
2716 struct mtd_oob_ops *ops)
2718 struct nand_chip *chip = mtd_to_nand(mtd);
2722 * Initialise to all 0xFF, to avoid the possibility of left over OOB
2723 * data from a previous OOB read.
2725 memset(chip->oob_poi, 0xff, mtd->oobsize);
2727 switch (ops->mode) {
2729 case MTD_OPS_PLACE_OOB:
2731 memcpy(chip->oob_poi + ops->ooboffs, oob, len);
2734 case MTD_OPS_AUTO_OOB:
2735 ret = mtd_ooblayout_set_databytes(mtd, oob, chip->oob_poi,
2746 #define NOTALIGNED(x) ((x & (chip->subpagesize - 1)) != 0)
2749 * nand_do_write_ops - [INTERN] NAND write with ECC
2750 * @mtd: MTD device structure
2751 * @to: offset to write to
2752 * @ops: oob operations description structure
2754 * NAND write with ECC.
2756 static int nand_do_write_ops(struct mtd_info *mtd, loff_t to,
2757 struct mtd_oob_ops *ops)
2759 int chipnr, realpage, page, blockmask, column;
2760 struct nand_chip *chip = mtd_to_nand(mtd);
2761 uint32_t writelen = ops->len;
2763 uint32_t oobwritelen = ops->ooblen;
2764 uint32_t oobmaxlen = mtd_oobavail(mtd, ops);
2766 uint8_t *oob = ops->oobbuf;
2767 uint8_t *buf = ops->datbuf;
2769 int oob_required = oob ? 1 : 0;
2775 /* Reject writes, which are not page aligned */
2776 if (NOTALIGNED(to) || NOTALIGNED(ops->len)) {
2777 pr_notice("%s: attempt to write non page aligned data\n",
2782 column = to & (mtd->writesize - 1);
2784 chipnr = (int)(to >> chip->chip_shift);
2785 chip->select_chip(mtd, chipnr);
2787 /* Check, if it is write protected */
2788 if (nand_check_wp(mtd)) {
2793 realpage = (int)(to >> chip->page_shift);
2794 page = realpage & chip->pagemask;
2795 blockmask = (1 << (chip->phys_erase_shift - chip->page_shift)) - 1;
2797 /* Invalidate the page cache, when we write to the cached page */
2798 if (to <= ((loff_t)chip->pagebuf << chip->page_shift) &&
2799 ((loff_t)chip->pagebuf << chip->page_shift) < (to + ops->len))
2802 /* Don't allow multipage oob writes with offset */
2803 if (oob && ops->ooboffs && (ops->ooboffs + ops->ooblen > oobmaxlen)) {
2809 int bytes = mtd->writesize;
2810 int cached = writelen > bytes && page != blockmask;
2811 uint8_t *wbuf = buf;
2813 int part_pagewr = (column || writelen < mtd->writesize);
2817 else if (chip->options & NAND_USE_BOUNCE_BUFFER)
2818 use_bufpoi = !virt_addr_valid(buf);
2822 /* Partial page write?, or need to use bounce buffer */
2824 pr_debug("%s: using write bounce buffer for buf@%p\n",
2828 bytes = min_t(int, bytes - column, writelen);
2830 memset(chip->buffers->databuf, 0xff, mtd->writesize);
2831 memcpy(&chip->buffers->databuf[column], buf, bytes);
2832 wbuf = chip->buffers->databuf;
2835 if (unlikely(oob)) {
2836 size_t len = min(oobwritelen, oobmaxlen);
2837 oob = nand_fill_oob(mtd, oob, len, ops);
2840 /* We still need to erase leftover OOB data */
2841 memset(chip->oob_poi, 0xff, mtd->oobsize);
2843 ret = chip->write_page(mtd, chip, column, bytes, wbuf,
2844 oob_required, page, cached,
2845 (ops->mode == MTD_OPS_RAW));
2857 page = realpage & chip->pagemask;
2858 /* Check, if we cross a chip boundary */
2861 chip->select_chip(mtd, -1);
2862 chip->select_chip(mtd, chipnr);
2866 ops->retlen = ops->len - writelen;
2868 ops->oobretlen = ops->ooblen;
2871 chip->select_chip(mtd, -1);
2876 * panic_nand_write - [MTD Interface] NAND write with ECC
2877 * @mtd: MTD device structure
2878 * @to: offset to write to
2879 * @len: number of bytes to write
2880 * @retlen: pointer to variable to store the number of written bytes
2881 * @buf: the data to write
2883 * NAND write with ECC. Used when performing writes in interrupt context, this
2884 * may for example be called by mtdoops when writing an oops while in panic.
2886 static int panic_nand_write(struct mtd_info *mtd, loff_t to, size_t len,
2887 size_t *retlen, const uint8_t *buf)
2889 struct nand_chip *chip = mtd_to_nand(mtd);
2890 struct mtd_oob_ops ops;
2893 /* Wait for the device to get ready */
2894 panic_nand_wait(mtd, chip, 400);
2896 /* Grab the device */
2897 panic_nand_get_device(chip, mtd, FL_WRITING);
2899 memset(&ops, 0, sizeof(ops));
2901 ops.datbuf = (uint8_t *)buf;
2902 ops.mode = MTD_OPS_PLACE_OOB;
2904 ret = nand_do_write_ops(mtd, to, &ops);
2906 *retlen = ops.retlen;
2911 * nand_write - [MTD Interface] NAND write with ECC
2912 * @mtd: MTD device structure
2913 * @to: offset to write to
2914 * @len: number of bytes to write
2915 * @retlen: pointer to variable to store the number of written bytes
2916 * @buf: the data to write
2918 * NAND write with ECC.
2920 static int nand_write(struct mtd_info *mtd, loff_t to, size_t len,
2921 size_t *retlen, const uint8_t *buf)
2923 struct mtd_oob_ops ops;
2926 nand_get_device(mtd, FL_WRITING);
2927 memset(&ops, 0, sizeof(ops));
2929 ops.datbuf = (uint8_t *)buf;
2930 ops.mode = MTD_OPS_PLACE_OOB;
2931 ret = nand_do_write_ops(mtd, to, &ops);
2932 *retlen = ops.retlen;
2933 nand_release_device(mtd);
2938 * nand_do_write_oob - [MTD Interface] NAND write out-of-band
2939 * @mtd: MTD device structure
2940 * @to: offset to write to
2941 * @ops: oob operation description structure
2943 * NAND write out-of-band.
2945 static int nand_do_write_oob(struct mtd_info *mtd, loff_t to,
2946 struct mtd_oob_ops *ops)
2948 int chipnr, page, status, len;
2949 struct nand_chip *chip = mtd_to_nand(mtd);
2951 pr_debug("%s: to = 0x%08x, len = %i\n",
2952 __func__, (unsigned int)to, (int)ops->ooblen);
2954 len = mtd_oobavail(mtd, ops);
2956 /* Do not allow write past end of page */
2957 if ((ops->ooboffs + ops->ooblen) > len) {
2958 pr_debug("%s: attempt to write past end of page\n",
2963 if (unlikely(ops->ooboffs >= len)) {
2964 pr_debug("%s: attempt to start write outside oob\n",
2969 /* Do not allow write past end of device */
2970 if (unlikely(to >= mtd->size ||
2971 ops->ooboffs + ops->ooblen >
2972 ((mtd->size >> chip->page_shift) -
2973 (to >> chip->page_shift)) * len)) {
2974 pr_debug("%s: attempt to write beyond end of device\n",
2979 chipnr = (int)(to >> chip->chip_shift);
2982 * Reset the chip. Some chips (like the Toshiba TC5832DC found in one
2983 * of my DiskOnChip 2000 test units) will clear the whole data page too
2984 * if we don't do this. I have no clue why, but I seem to have 'fixed'
2985 * it in the doc2000 driver in August 1999. dwmw2.
2987 nand_reset(chip, chipnr);
2989 chip->select_chip(mtd, chipnr);
2991 /* Shift to get page */
2992 page = (int)(to >> chip->page_shift);
2994 /* Check, if it is write protected */
2995 if (nand_check_wp(mtd)) {
2996 chip->select_chip(mtd, -1);
3000 /* Invalidate the page cache, if we write to the cached page */
3001 if (page == chip->pagebuf)
3004 nand_fill_oob(mtd, ops->oobbuf, ops->ooblen, ops);
3006 if (ops->mode == MTD_OPS_RAW)
3007 status = chip->ecc.write_oob_raw(mtd, chip, page & chip->pagemask);
3009 status = chip->ecc.write_oob(mtd, chip, page & chip->pagemask);
3011 chip->select_chip(mtd, -1);
3016 ops->oobretlen = ops->ooblen;
3022 * nand_write_oob - [MTD Interface] NAND write data and/or out-of-band
3023 * @mtd: MTD device structure
3024 * @to: offset to write to
3025 * @ops: oob operation description structure
3027 static int nand_write_oob(struct mtd_info *mtd, loff_t to,
3028 struct mtd_oob_ops *ops)
3030 int ret = -ENOTSUPP;
3034 /* Do not allow writes past end of device */
3035 if (ops->datbuf && (to + ops->len) > mtd->size) {
3036 pr_debug("%s: attempt to write beyond end of device\n",
3041 nand_get_device(mtd, FL_WRITING);
3043 switch (ops->mode) {
3044 case MTD_OPS_PLACE_OOB:
3045 case MTD_OPS_AUTO_OOB:
3054 ret = nand_do_write_oob(mtd, to, ops);
3056 ret = nand_do_write_ops(mtd, to, ops);
3059 nand_release_device(mtd);
3064 * single_erase - [GENERIC] NAND standard block erase command function
3065 * @mtd: MTD device structure
3066 * @page: the page address of the block which will be erased
3068 * Standard erase command for NAND chips. Returns NAND status.
3070 static int single_erase(struct mtd_info *mtd, int page)
3072 struct nand_chip *chip = mtd_to_nand(mtd);
3073 /* Send commands to erase a block */
3074 chip->cmdfunc(mtd, NAND_CMD_ERASE1, -1, page);
3075 chip->cmdfunc(mtd, NAND_CMD_ERASE2, -1, -1);
3077 return chip->waitfunc(mtd, chip);
3081 * nand_erase - [MTD Interface] erase block(s)
3082 * @mtd: MTD device structure
3083 * @instr: erase instruction
3085 * Erase one ore more blocks.
3087 static int nand_erase(struct mtd_info *mtd, struct erase_info *instr)
3089 return nand_erase_nand(mtd, instr, 0);
3093 * nand_erase_nand - [INTERN] erase block(s)
3094 * @mtd: MTD device structure
3095 * @instr: erase instruction
3096 * @allowbbt: allow erasing the bbt area
3098 * Erase one ore more blocks.
3100 int nand_erase_nand(struct mtd_info *mtd, struct erase_info *instr,
3103 int page, status, pages_per_block, ret, chipnr;
3104 struct nand_chip *chip = mtd_to_nand(mtd);
3107 pr_debug("%s: start = 0x%012llx, len = %llu\n",
3108 __func__, (unsigned long long)instr->addr,
3109 (unsigned long long)instr->len);
3111 if (check_offs_len(mtd, instr->addr, instr->len))
3114 /* Grab the lock and see if the device is available */
3115 nand_get_device(mtd, FL_ERASING);
3117 /* Shift to get first page */
3118 page = (int)(instr->addr >> chip->page_shift);
3119 chipnr = (int)(instr->addr >> chip->chip_shift);
3121 /* Calculate pages in each block */
3122 pages_per_block = 1 << (chip->phys_erase_shift - chip->page_shift);
3124 /* Select the NAND device */
3125 chip->select_chip(mtd, chipnr);
3127 /* Check, if it is write protected */
3128 if (nand_check_wp(mtd)) {
3129 pr_debug("%s: device is write protected!\n",
3131 instr->state = MTD_ERASE_FAILED;
3135 /* Loop through the pages */
3138 instr->state = MTD_ERASING;
3141 /* Check if we have a bad block, we do not erase bad blocks! */
3142 if (nand_block_checkbad(mtd, ((loff_t) page) <<
3143 chip->page_shift, allowbbt)) {
3144 pr_warn("%s: attempt to erase a bad block at page 0x%08x\n",
3146 instr->state = MTD_ERASE_FAILED;
3151 * Invalidate the page cache, if we erase the block which
3152 * contains the current cached page.
3154 if (page <= chip->pagebuf && chip->pagebuf <
3155 (page + pages_per_block))
3158 status = chip->erase(mtd, page & chip->pagemask);
3161 * See if operation failed and additional status checks are
3164 if ((status & NAND_STATUS_FAIL) && (chip->errstat))
3165 status = chip->errstat(mtd, chip, FL_ERASING,
3168 /* See if block erase succeeded */
3169 if (status & NAND_STATUS_FAIL) {
3170 pr_debug("%s: failed erase, page 0x%08x\n",
3172 instr->state = MTD_ERASE_FAILED;
3174 ((loff_t)page << chip->page_shift);
3178 /* Increment page address and decrement length */
3179 len -= (1ULL << chip->phys_erase_shift);
3180 page += pages_per_block;
3182 /* Check, if we cross a chip boundary */
3183 if (len && !(page & chip->pagemask)) {
3185 chip->select_chip(mtd, -1);
3186 chip->select_chip(mtd, chipnr);
3189 instr->state = MTD_ERASE_DONE;
3193 ret = instr->state == MTD_ERASE_DONE ? 0 : -EIO;
3195 /* Deselect and wake up anyone waiting on the device */
3196 chip->select_chip(mtd, -1);
3197 nand_release_device(mtd);
3199 /* Do call back function */
3201 mtd_erase_callback(instr);
3203 /* Return more or less happy */
3208 * nand_sync - [MTD Interface] sync
3209 * @mtd: MTD device structure
3211 * Sync is actually a wait for chip ready function.
3213 static void nand_sync(struct mtd_info *mtd)
3215 pr_debug("%s: called\n", __func__);
3217 /* Grab the lock and see if the device is available */
3218 nand_get_device(mtd, FL_SYNCING);
3219 /* Release it and go back */
3220 nand_release_device(mtd);
3224 * nand_block_isbad - [MTD Interface] Check if block at offset is bad
3225 * @mtd: MTD device structure
3226 * @offs: offset relative to mtd start
3228 static int nand_block_isbad(struct mtd_info *mtd, loff_t offs)
3230 struct nand_chip *chip = mtd_to_nand(mtd);
3231 int chipnr = (int)(offs >> chip->chip_shift);
3234 /* Select the NAND device */
3235 nand_get_device(mtd, FL_READING);
3236 chip->select_chip(mtd, chipnr);
3238 ret = nand_block_checkbad(mtd, offs, 0);
3240 chip->select_chip(mtd, -1);
3241 nand_release_device(mtd);
3247 * nand_block_markbad - [MTD Interface] Mark block at the given offset as bad
3248 * @mtd: MTD device structure
3249 * @ofs: offset relative to mtd start
3251 static int nand_block_markbad(struct mtd_info *mtd, loff_t ofs)
3255 ret = nand_block_isbad(mtd, ofs);
3257 /* If it was bad already, return success and do nothing */
3263 return nand_block_markbad_lowlevel(mtd, ofs);
3267 * nand_max_bad_blocks - [MTD Interface] Max number of bad blocks for an mtd
3268 * @mtd: MTD device structure
3269 * @ofs: offset relative to mtd start
3270 * @len: length of mtd
3272 static int nand_max_bad_blocks(struct mtd_info *mtd, loff_t ofs, size_t len)
3274 struct nand_chip *chip = mtd_to_nand(mtd);
3275 u32 part_start_block;
3281 * max_bb_per_die and blocks_per_die used to determine
3282 * the maximum bad block count.
3284 if (!chip->max_bb_per_die || !chip->blocks_per_die)
3287 /* Get the start and end of the partition in erase blocks. */
3288 part_start_block = mtd_div_by_eb(ofs, mtd);
3289 part_end_block = mtd_div_by_eb(len, mtd) + part_start_block - 1;
3291 /* Get the start and end LUNs of the partition. */
3292 part_start_die = part_start_block / chip->blocks_per_die;
3293 part_end_die = part_end_block / chip->blocks_per_die;
3296 * Look up the bad blocks per unit and multiply by the number of units
3297 * that the partition spans.
3299 return chip->max_bb_per_die * (part_end_die - part_start_die + 1);
3303 * nand_onfi_set_features- [REPLACEABLE] set features for ONFI nand
3304 * @mtd: MTD device structure
3305 * @chip: nand chip info structure
3306 * @addr: feature address.
3307 * @subfeature_param: the subfeature parameters, a four bytes array.
3309 static int nand_onfi_set_features(struct mtd_info *mtd, struct nand_chip *chip,
3310 int addr, uint8_t *subfeature_param)
3315 if (!chip->onfi_version ||
3316 !(le16_to_cpu(chip->onfi_params.opt_cmd)
3317 & ONFI_OPT_CMD_SET_GET_FEATURES))
3320 chip->cmdfunc(mtd, NAND_CMD_SET_FEATURES, addr, -1);
3321 for (i = 0; i < ONFI_SUBFEATURE_PARAM_LEN; ++i)
3322 chip->write_byte(mtd, subfeature_param[i]);
3324 status = chip->waitfunc(mtd, chip);
3325 if (status & NAND_STATUS_FAIL)
3331 * nand_onfi_get_features- [REPLACEABLE] get features for ONFI nand
3332 * @mtd: MTD device structure
3333 * @chip: nand chip info structure
3334 * @addr: feature address.
3335 * @subfeature_param: the subfeature parameters, a four bytes array.
3337 static int nand_onfi_get_features(struct mtd_info *mtd, struct nand_chip *chip,
3338 int addr, uint8_t *subfeature_param)
3342 if (!chip->onfi_version ||
3343 !(le16_to_cpu(chip->onfi_params.opt_cmd)
3344 & ONFI_OPT_CMD_SET_GET_FEATURES))
3347 chip->cmdfunc(mtd, NAND_CMD_GET_FEATURES, addr, -1);
3348 for (i = 0; i < ONFI_SUBFEATURE_PARAM_LEN; ++i)
3349 *subfeature_param++ = chip->read_byte(mtd);
3354 * nand_suspend - [MTD Interface] Suspend the NAND flash
3355 * @mtd: MTD device structure
3357 static int nand_suspend(struct mtd_info *mtd)
3359 return nand_get_device(mtd, FL_PM_SUSPENDED);
3363 * nand_resume - [MTD Interface] Resume the NAND flash
3364 * @mtd: MTD device structure
3366 static void nand_resume(struct mtd_info *mtd)
3368 struct nand_chip *chip = mtd_to_nand(mtd);
3370 if (chip->state == FL_PM_SUSPENDED)
3371 nand_release_device(mtd);
3373 pr_err("%s called for a chip which is not in suspended state\n",
3378 * nand_shutdown - [MTD Interface] Finish the current NAND operation and
3379 * prevent further operations
3380 * @mtd: MTD device structure
3382 static void nand_shutdown(struct mtd_info *mtd)
3384 nand_get_device(mtd, FL_PM_SUSPENDED);
3387 /* Set default functions */
3388 static void nand_set_defaults(struct nand_chip *chip)
3390 unsigned int busw = chip->options & NAND_BUSWIDTH_16;
3392 /* check for proper chip_delay setup, set 20us if not */
3393 if (!chip->chip_delay)
3394 chip->chip_delay = 20;
3396 /* check, if a user supplied command function given */
3397 if (chip->cmdfunc == NULL)
3398 chip->cmdfunc = nand_command;
3400 /* check, if a user supplied wait function given */
3401 if (chip->waitfunc == NULL)
3402 chip->waitfunc = nand_wait;
3404 if (!chip->select_chip)
3405 chip->select_chip = nand_select_chip;
3407 /* set for ONFI nand */
3408 if (!chip->onfi_set_features)
3409 chip->onfi_set_features = nand_onfi_set_features;
3410 if (!chip->onfi_get_features)
3411 chip->onfi_get_features = nand_onfi_get_features;
3413 /* If called twice, pointers that depend on busw may need to be reset */
3414 if (!chip->read_byte || chip->read_byte == nand_read_byte)
3415 chip->read_byte = busw ? nand_read_byte16 : nand_read_byte;
3416 if (!chip->read_word)
3417 chip->read_word = nand_read_word;
3418 if (!chip->block_bad)
3419 chip->block_bad = nand_block_bad;
3420 if (!chip->block_markbad)
3421 chip->block_markbad = nand_default_block_markbad;
3422 if (!chip->write_buf || chip->write_buf == nand_write_buf)
3423 chip->write_buf = busw ? nand_write_buf16 : nand_write_buf;
3424 if (!chip->write_byte || chip->write_byte == nand_write_byte)
3425 chip->write_byte = busw ? nand_write_byte16 : nand_write_byte;
3426 if (!chip->read_buf || chip->read_buf == nand_read_buf)
3427 chip->read_buf = busw ? nand_read_buf16 : nand_read_buf;
3428 if (!chip->scan_bbt)
3429 chip->scan_bbt = nand_default_bbt;
3431 if (!chip->controller) {
3432 chip->controller = &chip->hwcontrol;
3433 nand_hw_control_init(chip->controller);
3438 /* Sanitize ONFI strings so we can safely print them */
3439 static void sanitize_string(uint8_t *s, size_t len)
3443 /* Null terminate */
3446 /* Remove non printable chars */
3447 for (i = 0; i < len - 1; i++) {
3448 if (s[i] < ' ' || s[i] > 127)
3452 /* Remove trailing spaces */
3456 static u16 onfi_crc16(u16 crc, u8 const *p, size_t len)
3461 for (i = 0; i < 8; i++)
3462 crc = (crc << 1) ^ ((crc & 0x8000) ? 0x8005 : 0);
3468 /* Parse the Extended Parameter Page. */
3469 static int nand_flash_detect_ext_param_page(struct nand_chip *chip,
3470 struct nand_onfi_params *p)
3472 struct mtd_info *mtd = nand_to_mtd(chip);
3473 struct onfi_ext_param_page *ep;
3474 struct onfi_ext_section *s;
3475 struct onfi_ext_ecc_info *ecc;
3481 len = le16_to_cpu(p->ext_param_page_length) * 16;
3482 ep = kmalloc(len, GFP_KERNEL);
3486 /* Send our own NAND_CMD_PARAM. */
3487 chip->cmdfunc(mtd, NAND_CMD_PARAM, 0, -1);
3489 /* Use the Change Read Column command to skip the ONFI param pages. */
3490 chip->cmdfunc(mtd, NAND_CMD_RNDOUT,
3491 sizeof(*p) * p->num_of_param_pages , -1);
3493 /* Read out the Extended Parameter Page. */
3494 chip->read_buf(mtd, (uint8_t *)ep, len);
3495 if ((onfi_crc16(ONFI_CRC_BASE, ((uint8_t *)ep) + 2, len - 2)
3496 != le16_to_cpu(ep->crc))) {
3497 pr_debug("fail in the CRC.\n");
3502 * Check the signature.
3503 * Do not strictly follow the ONFI spec, maybe changed in future.
3505 if (strncmp(ep->sig, "EPPS", 4)) {
3506 pr_debug("The signature is invalid.\n");
3510 /* find the ECC section. */
3511 cursor = (uint8_t *)(ep + 1);
3512 for (i = 0; i < ONFI_EXT_SECTION_MAX; i++) {
3513 s = ep->sections + i;
3514 if (s->type == ONFI_SECTION_TYPE_2)
3516 cursor += s->length * 16;
3518 if (i == ONFI_EXT_SECTION_MAX) {
3519 pr_debug("We can not find the ECC section.\n");
3523 /* get the info we want. */
3524 ecc = (struct onfi_ext_ecc_info *)cursor;
3526 if (!ecc->codeword_size) {
3527 pr_debug("Invalid codeword size\n");
3531 chip->ecc_strength_ds = ecc->ecc_bits;
3532 chip->ecc_step_ds = 1 << ecc->codeword_size;
3541 * Check if the NAND chip is ONFI compliant, returns 1 if it is, 0 otherwise.
3543 static int nand_flash_detect_onfi(struct nand_chip *chip)
3545 struct mtd_info *mtd = nand_to_mtd(chip);
3546 struct nand_onfi_params *p = &chip->onfi_params;
3550 /* Try ONFI for unknown chip or LP */
3551 chip->cmdfunc(mtd, NAND_CMD_READID, 0x20, -1);
3552 if (chip->read_byte(mtd) != 'O' || chip->read_byte(mtd) != 'N' ||
3553 chip->read_byte(mtd) != 'F' || chip->read_byte(mtd) != 'I')
3556 chip->cmdfunc(mtd, NAND_CMD_PARAM, 0, -1);
3557 for (i = 0; i < 3; i++) {
3558 for (j = 0; j < sizeof(*p); j++)
3559 ((uint8_t *)p)[j] = chip->read_byte(mtd);
3560 if (onfi_crc16(ONFI_CRC_BASE, (uint8_t *)p, 254) ==
3561 le16_to_cpu(p->crc)) {
3567 pr_err("Could not find valid ONFI parameter page; aborting\n");
3572 val = le16_to_cpu(p->revision);
3574 chip->onfi_version = 23;
3575 else if (val & (1 << 4))
3576 chip->onfi_version = 22;
3577 else if (val & (1 << 3))
3578 chip->onfi_version = 21;
3579 else if (val & (1 << 2))
3580 chip->onfi_version = 20;
3581 else if (val & (1 << 1))
3582 chip->onfi_version = 10;
3584 if (!chip->onfi_version) {
3585 pr_info("unsupported ONFI version: %d\n", val);
3589 sanitize_string(p->manufacturer, sizeof(p->manufacturer));
3590 sanitize_string(p->model, sizeof(p->model));
3592 mtd->name = p->model;
3594 mtd->writesize = le32_to_cpu(p->byte_per_page);
3597 * pages_per_block and blocks_per_lun may not be a power-of-2 size
3598 * (don't ask me who thought of this...). MTD assumes that these
3599 * dimensions will be power-of-2, so just truncate the remaining area.
3601 mtd->erasesize = 1 << (fls(le32_to_cpu(p->pages_per_block)) - 1);
3602 mtd->erasesize *= mtd->writesize;
3604 mtd->oobsize = le16_to_cpu(p->spare_bytes_per_page);
3606 /* See erasesize comment */
3607 chip->chipsize = 1 << (fls(le32_to_cpu(p->blocks_per_lun)) - 1);
3608 chip->chipsize *= (uint64_t)mtd->erasesize * p->lun_count;
3609 chip->bits_per_cell = p->bits_per_cell;
3611 chip->max_bb_per_die = le16_to_cpu(p->bb_per_lun);
3612 chip->blocks_per_die = le32_to_cpu(p->blocks_per_lun);
3614 if (onfi_feature(chip) & ONFI_FEATURE_16_BIT_BUS)
3615 chip->options |= NAND_BUSWIDTH_16;
3617 if (p->ecc_bits != 0xff) {
3618 chip->ecc_strength_ds = p->ecc_bits;
3619 chip->ecc_step_ds = 512;
3620 } else if (chip->onfi_version >= 21 &&
3621 (onfi_feature(chip) & ONFI_FEATURE_EXT_PARAM_PAGE)) {
3624 * The nand_flash_detect_ext_param_page() uses the
3625 * Change Read Column command which maybe not supported
3626 * by the chip->cmdfunc. So try to update the chip->cmdfunc
3627 * now. We do not replace user supplied command function.
3629 if (mtd->writesize > 512 && chip->cmdfunc == nand_command)
3630 chip->cmdfunc = nand_command_lp;
3632 /* The Extended Parameter Page is supported since ONFI 2.1. */
3633 if (nand_flash_detect_ext_param_page(chip, p))
3634 pr_warn("Failed to detect ONFI extended param page\n");
3636 pr_warn("Could not retrieve ONFI ECC requirements\n");
3643 * Check if the NAND chip is JEDEC compliant, returns 1 if it is, 0 otherwise.
3645 static int nand_flash_detect_jedec(struct nand_chip *chip)
3647 struct mtd_info *mtd = nand_to_mtd(chip);
3648 struct nand_jedec_params *p = &chip->jedec_params;
3649 struct jedec_ecc_info *ecc;
3653 /* Try JEDEC for unknown chip or LP */
3654 chip->cmdfunc(mtd, NAND_CMD_READID, 0x40, -1);
3655 if (chip->read_byte(mtd) != 'J' || chip->read_byte(mtd) != 'E' ||
3656 chip->read_byte(mtd) != 'D' || chip->read_byte(mtd) != 'E' ||
3657 chip->read_byte(mtd) != 'C')
3660 chip->cmdfunc(mtd, NAND_CMD_PARAM, 0x40, -1);
3661 for (i = 0; i < 3; i++) {
3662 for (j = 0; j < sizeof(*p); j++)
3663 ((uint8_t *)p)[j] = chip->read_byte(mtd);
3665 if (onfi_crc16(ONFI_CRC_BASE, (uint8_t *)p, 510) ==
3666 le16_to_cpu(p->crc))
3671 pr_err("Could not find valid JEDEC parameter page; aborting\n");
3676 val = le16_to_cpu(p->revision);
3678 chip->jedec_version = 10;
3679 else if (val & (1 << 1))
3680 chip->jedec_version = 1; /* vendor specific version */
3682 if (!chip->jedec_version) {
3683 pr_info("unsupported JEDEC version: %d\n", val);
3687 sanitize_string(p->manufacturer, sizeof(p->manufacturer));
3688 sanitize_string(p->model, sizeof(p->model));
3690 mtd->name = p->model;
3692 mtd->writesize = le32_to_cpu(p->byte_per_page);
3694 /* Please reference to the comment for nand_flash_detect_onfi. */
3695 mtd->erasesize = 1 << (fls(le32_to_cpu(p->pages_per_block)) - 1);
3696 mtd->erasesize *= mtd->writesize;
3698 mtd->oobsize = le16_to_cpu(p->spare_bytes_per_page);
3700 /* Please reference to the comment for nand_flash_detect_onfi. */
3701 chip->chipsize = 1 << (fls(le32_to_cpu(p->blocks_per_lun)) - 1);
3702 chip->chipsize *= (uint64_t)mtd->erasesize * p->lun_count;
3703 chip->bits_per_cell = p->bits_per_cell;
3705 if (jedec_feature(chip) & JEDEC_FEATURE_16_BIT_BUS)
3706 chip->options |= NAND_BUSWIDTH_16;
3709 ecc = &p->ecc_info[0];
3711 if (ecc->codeword_size >= 9) {
3712 chip->ecc_strength_ds = ecc->ecc_bits;
3713 chip->ecc_step_ds = 1 << ecc->codeword_size;
3715 pr_warn("Invalid codeword size\n");
3722 * nand_id_has_period - Check if an ID string has a given wraparound period
3723 * @id_data: the ID string
3724 * @arrlen: the length of the @id_data array
3725 * @period: the period of repitition
3727 * Check if an ID string is repeated within a given sequence of bytes at
3728 * specific repetition interval period (e.g., {0x20,0x01,0x7F,0x20} has a
3729 * period of 3). This is a helper function for nand_id_len(). Returns non-zero
3730 * if the repetition has a period of @period; otherwise, returns zero.
3732 static int nand_id_has_period(u8 *id_data, int arrlen, int period)
3735 for (i = 0; i < period; i++)
3736 for (j = i + period; j < arrlen; j += period)
3737 if (id_data[i] != id_data[j])
3743 * nand_id_len - Get the length of an ID string returned by CMD_READID
3744 * @id_data: the ID string
3745 * @arrlen: the length of the @id_data array
3747 * Returns the length of the ID string, according to known wraparound/trailing
3748 * zero patterns. If no pattern exists, returns the length of the array.
3750 static int nand_id_len(u8 *id_data, int arrlen)
3752 int last_nonzero, period;
3754 /* Find last non-zero byte */
3755 for (last_nonzero = arrlen - 1; last_nonzero >= 0; last_nonzero--)
3756 if (id_data[last_nonzero])
3760 if (last_nonzero < 0)
3763 /* Calculate wraparound period */
3764 for (period = 1; period < arrlen; period++)
3765 if (nand_id_has_period(id_data, arrlen, period))
3768 /* There's a repeated pattern */
3769 if (period < arrlen)
3772 /* There are trailing zeros */
3773 if (last_nonzero < arrlen - 1)
3774 return last_nonzero + 1;
3776 /* No pattern detected */
3780 /* Extract the bits of per cell from the 3rd byte of the extended ID */
3781 static int nand_get_bits_per_cell(u8 cellinfo)
3785 bits = cellinfo & NAND_CI_CELLTYPE_MSK;
3786 bits >>= NAND_CI_CELLTYPE_SHIFT;
3791 * Many new NAND share similar device ID codes, which represent the size of the
3792 * chip. The rest of the parameters must be decoded according to generic or
3793 * manufacturer-specific "extended ID" decoding patterns.
3795 void nand_decode_ext_id(struct nand_chip *chip)
3797 struct mtd_info *mtd = nand_to_mtd(chip);
3799 u8 *id_data = chip->id.data;
3800 /* The 3rd id byte holds MLC / multichip data */
3801 chip->bits_per_cell = nand_get_bits_per_cell(id_data[2]);
3802 /* The 4th id byte is the important one */
3806 mtd->writesize = 1024 << (extid & 0x03);
3809 mtd->oobsize = (8 << (extid & 0x01)) * (mtd->writesize >> 9);
3811 /* Calc blocksize. Blocksize is multiples of 64KiB */
3812 mtd->erasesize = (64 * 1024) << (extid & 0x03);
3814 /* Get buswidth information */
3816 chip->options |= NAND_BUSWIDTH_16;
3818 EXPORT_SYMBOL_GPL(nand_decode_ext_id);
3821 * Old devices have chip data hardcoded in the device ID table. nand_decode_id
3822 * decodes a matching ID table entry and assigns the MTD size parameters for
3825 static void nand_decode_id(struct nand_chip *chip, struct nand_flash_dev *type)
3827 struct mtd_info *mtd = nand_to_mtd(chip);
3829 mtd->erasesize = type->erasesize;
3830 mtd->writesize = type->pagesize;
3831 mtd->oobsize = mtd->writesize / 32;
3833 /* All legacy ID NAND are small-page, SLC */
3834 chip->bits_per_cell = 1;
3838 * Set the bad block marker/indicator (BBM/BBI) patterns according to some
3839 * heuristic patterns using various detected parameters (e.g., manufacturer,
3840 * page size, cell-type information).
3842 static void nand_decode_bbm_options(struct nand_chip *chip)
3844 struct mtd_info *mtd = nand_to_mtd(chip);
3846 /* Set the bad block position */
3847 if (mtd->writesize > 512 || (chip->options & NAND_BUSWIDTH_16))
3848 chip->badblockpos = NAND_LARGE_BADBLOCK_POS;
3850 chip->badblockpos = NAND_SMALL_BADBLOCK_POS;
3853 static inline bool is_full_id_nand(struct nand_flash_dev *type)
3855 return type->id_len;
3858 static bool find_full_id_nand(struct nand_chip *chip,
3859 struct nand_flash_dev *type)
3861 struct mtd_info *mtd = nand_to_mtd(chip);
3862 u8 *id_data = chip->id.data;
3864 if (!strncmp(type->id, id_data, type->id_len)) {
3865 mtd->writesize = type->pagesize;
3866 mtd->erasesize = type->erasesize;
3867 mtd->oobsize = type->oobsize;
3869 chip->bits_per_cell = nand_get_bits_per_cell(id_data[2]);
3870 chip->chipsize = (uint64_t)type->chipsize << 20;
3871 chip->options |= type->options;
3872 chip->ecc_strength_ds = NAND_ECC_STRENGTH(type);
3873 chip->ecc_step_ds = NAND_ECC_STEP(type);
3874 chip->onfi_timing_mode_default =
3875 type->onfi_timing_mode_default;
3878 mtd->name = type->name;
3886 * Manufacturer detection. Only used when the NAND is not ONFI or JEDEC
3887 * compliant and does not have a full-id or legacy-id entry in the nand_ids
3890 static void nand_manufacturer_detect(struct nand_chip *chip)
3893 * Try manufacturer detection if available and use
3894 * nand_decode_ext_id() otherwise.
3896 if (chip->manufacturer.desc && chip->manufacturer.desc->ops &&
3897 chip->manufacturer.desc->ops->detect)
3898 chip->manufacturer.desc->ops->detect(chip);
3900 nand_decode_ext_id(chip);
3904 * Manufacturer initialization. This function is called for all NANDs including
3905 * ONFI and JEDEC compliant ones.
3906 * Manufacturer drivers should put all their specific initialization code in
3907 * their ->init() hook.
3909 static int nand_manufacturer_init(struct nand_chip *chip)
3911 if (!chip->manufacturer.desc || !chip->manufacturer.desc->ops ||
3912 !chip->manufacturer.desc->ops->init)
3915 return chip->manufacturer.desc->ops->init(chip);
3919 * Manufacturer cleanup. This function is called for all NANDs including
3920 * ONFI and JEDEC compliant ones.
3921 * Manufacturer drivers should put all their specific cleanup code in their
3924 static void nand_manufacturer_cleanup(struct nand_chip *chip)
3926 /* Release manufacturer private data */
3927 if (chip->manufacturer.desc && chip->manufacturer.desc->ops &&
3928 chip->manufacturer.desc->ops->cleanup)
3929 chip->manufacturer.desc->ops->cleanup(chip);
3933 * Get the flash and manufacturer id and lookup if the type is supported.
3935 static int nand_detect(struct nand_chip *chip, struct nand_flash_dev *type)
3937 const struct nand_manufacturer *manufacturer;
3938 struct mtd_info *mtd = nand_to_mtd(chip);
3941 u8 *id_data = chip->id.data;
3945 * Reset the chip, required by some chips (e.g. Micron MT29FxGxxxxx)
3948 nand_reset(chip, 0);
3950 /* Select the device */
3951 chip->select_chip(mtd, 0);
3953 /* Send the command for reading device ID */
3954 chip->cmdfunc(mtd, NAND_CMD_READID, 0x00, -1);
3956 /* Read manufacturer and device IDs */
3957 maf_id = chip->read_byte(mtd);
3958 dev_id = chip->read_byte(mtd);
3961 * Try again to make sure, as some systems the bus-hold or other
3962 * interface concerns can cause random data which looks like a
3963 * possibly credible NAND flash to appear. If the two results do
3964 * not match, ignore the device completely.
3967 chip->cmdfunc(mtd, NAND_CMD_READID, 0x00, -1);
3969 /* Read entire ID string */
3970 for (i = 0; i < 8; i++)
3971 id_data[i] = chip->read_byte(mtd);
3973 if (id_data[0] != maf_id || id_data[1] != dev_id) {
3974 pr_info("second ID read did not match %02x,%02x against %02x,%02x\n",
3975 maf_id, dev_id, id_data[0], id_data[1]);
3979 chip->id.len = nand_id_len(id_data, 8);
3981 /* Try to identify manufacturer */
3982 manufacturer = nand_get_manufacturer(maf_id);
3983 chip->manufacturer.desc = manufacturer;
3986 type = nand_flash_ids;
3989 * Save the NAND_BUSWIDTH_16 flag before letting auto-detection logic
3991 * This is required to make sure initial NAND bus width set by the
3992 * NAND controller driver is coherent with the real NAND bus width
3993 * (extracted by auto-detection code).
3995 busw = chip->options & NAND_BUSWIDTH_16;
3998 * The flag is only set (never cleared), reset it to its default value
3999 * before starting auto-detection.
4001 chip->options &= ~NAND_BUSWIDTH_16;
4003 for (; type->name != NULL; type++) {
4004 if (is_full_id_nand(type)) {
4005 if (find_full_id_nand(chip, type))
4007 } else if (dev_id == type->dev_id) {
4012 chip->onfi_version = 0;
4013 if (!type->name || !type->pagesize) {
4014 /* Check if the chip is ONFI compliant */
4015 if (nand_flash_detect_onfi(chip))
4018 /* Check if the chip is JEDEC compliant */
4019 if (nand_flash_detect_jedec(chip))
4027 mtd->name = type->name;
4029 chip->chipsize = (uint64_t)type->chipsize << 20;
4031 if (!type->pagesize)
4032 nand_manufacturer_detect(chip);
4034 nand_decode_id(chip, type);
4036 /* Get chip options */
4037 chip->options |= type->options;
4041 if (chip->options & NAND_BUSWIDTH_AUTO) {
4042 WARN_ON(busw & NAND_BUSWIDTH_16);
4043 nand_set_defaults(chip);
4044 } else if (busw != (chip->options & NAND_BUSWIDTH_16)) {
4046 * Check, if buswidth is correct. Hardware drivers should set
4049 pr_info("device found, Manufacturer ID: 0x%02x, Chip ID: 0x%02x\n",
4051 pr_info("%s %s\n", nand_manufacturer_name(manufacturer),
4053 pr_warn("bus width %d instead of %d bits\n", busw ? 16 : 8,
4054 (chip->options & NAND_BUSWIDTH_16) ? 16 : 8);
4058 nand_decode_bbm_options(chip);
4060 /* Calculate the address shift from the page size */
4061 chip->page_shift = ffs(mtd->writesize) - 1;
4062 /* Convert chipsize to number of pages per chip -1 */
4063 chip->pagemask = (chip->chipsize >> chip->page_shift) - 1;
4065 chip->bbt_erase_shift = chip->phys_erase_shift =
4066 ffs(mtd->erasesize) - 1;
4067 if (chip->chipsize & 0xffffffff)
4068 chip->chip_shift = ffs((unsigned)chip->chipsize) - 1;
4070 chip->chip_shift = ffs((unsigned)(chip->chipsize >> 32));
4071 chip->chip_shift += 32 - 1;
4074 chip->badblockbits = 8;
4075 chip->erase = single_erase;
4077 /* Do not replace user supplied command function! */
4078 if (mtd->writesize > 512 && chip->cmdfunc == nand_command)
4079 chip->cmdfunc = nand_command_lp;
4081 ret = nand_manufacturer_init(chip);
4085 pr_info("device found, Manufacturer ID: 0x%02x, Chip ID: 0x%02x\n",
4088 if (chip->onfi_version)
4089 pr_info("%s %s\n", nand_manufacturer_name(manufacturer),
4090 chip->onfi_params.model);
4091 else if (chip->jedec_version)
4092 pr_info("%s %s\n", nand_manufacturer_name(manufacturer),
4093 chip->jedec_params.model);
4095 pr_info("%s %s\n", nand_manufacturer_name(manufacturer),
4098 pr_info("%d MiB, %s, erase size: %d KiB, page size: %d, OOB size: %d\n",
4099 (int)(chip->chipsize >> 20), nand_is_slc(chip) ? "SLC" : "MLC",
4100 mtd->erasesize >> 10, mtd->writesize, mtd->oobsize);
4104 static const char * const nand_ecc_modes[] = {
4105 [NAND_ECC_NONE] = "none",
4106 [NAND_ECC_SOFT] = "soft",
4107 [NAND_ECC_HW] = "hw",
4108 [NAND_ECC_HW_SYNDROME] = "hw_syndrome",
4109 [NAND_ECC_HW_OOB_FIRST] = "hw_oob_first",
4112 static int of_get_nand_ecc_mode(struct device_node *np)
4117 err = of_property_read_string(np, "nand-ecc-mode", &pm);
4121 for (i = 0; i < ARRAY_SIZE(nand_ecc_modes); i++)
4122 if (!strcasecmp(pm, nand_ecc_modes[i]))
4126 * For backward compatibility we support few obsoleted values that don't
4127 * have their mappings into nand_ecc_modes_t anymore (they were merged
4128 * with other enums).
4130 if (!strcasecmp(pm, "soft_bch"))
4131 return NAND_ECC_SOFT;
4136 static const char * const nand_ecc_algos[] = {
4137 [NAND_ECC_HAMMING] = "hamming",
4138 [NAND_ECC_BCH] = "bch",
4141 static int of_get_nand_ecc_algo(struct device_node *np)
4146 err = of_property_read_string(np, "nand-ecc-algo", &pm);
4148 for (i = NAND_ECC_HAMMING; i < ARRAY_SIZE(nand_ecc_algos); i++)
4149 if (!strcasecmp(pm, nand_ecc_algos[i]))
4155 * For backward compatibility we also read "nand-ecc-mode" checking
4156 * for some obsoleted values that were specifying ECC algorithm.
4158 err = of_property_read_string(np, "nand-ecc-mode", &pm);
4162 if (!strcasecmp(pm, "soft"))
4163 return NAND_ECC_HAMMING;
4164 else if (!strcasecmp(pm, "soft_bch"))
4165 return NAND_ECC_BCH;
4170 static int of_get_nand_ecc_step_size(struct device_node *np)
4175 ret = of_property_read_u32(np, "nand-ecc-step-size", &val);
4176 return ret ? ret : val;
4179 static int of_get_nand_ecc_strength(struct device_node *np)
4184 ret = of_property_read_u32(np, "nand-ecc-strength", &val);
4185 return ret ? ret : val;
4188 static int of_get_nand_bus_width(struct device_node *np)
4192 if (of_property_read_u32(np, "nand-bus-width", &val))
4204 static bool of_get_nand_on_flash_bbt(struct device_node *np)
4206 return of_property_read_bool(np, "nand-on-flash-bbt");
4209 static int nand_dt_init(struct nand_chip *chip)
4211 struct device_node *dn = nand_get_flash_node(chip);
4212 int ecc_mode, ecc_algo, ecc_strength, ecc_step;
4217 if (of_get_nand_bus_width(dn) == 16)
4218 chip->options |= NAND_BUSWIDTH_16;
4220 if (of_get_nand_on_flash_bbt(dn))
4221 chip->bbt_options |= NAND_BBT_USE_FLASH;
4223 ecc_mode = of_get_nand_ecc_mode(dn);
4224 ecc_algo = of_get_nand_ecc_algo(dn);
4225 ecc_strength = of_get_nand_ecc_strength(dn);
4226 ecc_step = of_get_nand_ecc_step_size(dn);
4228 if ((ecc_step >= 0 && !(ecc_strength >= 0)) ||
4229 (!(ecc_step >= 0) && ecc_strength >= 0)) {
4230 pr_err("must set both strength and step size in DT\n");
4235 chip->ecc.mode = ecc_mode;
4238 chip->ecc.algo = ecc_algo;
4240 if (ecc_strength >= 0)
4241 chip->ecc.strength = ecc_strength;
4244 chip->ecc.size = ecc_step;
4246 if (of_property_read_bool(dn, "nand-ecc-maximize"))
4247 chip->ecc.options |= NAND_ECC_MAXIMIZE;
4253 * nand_scan_ident - [NAND Interface] Scan for the NAND device
4254 * @mtd: MTD device structure
4255 * @maxchips: number of chips to scan for
4256 * @table: alternative NAND ID table
4258 * This is the first phase of the normal nand_scan() function. It reads the
4259 * flash ID and sets up MTD fields accordingly.
4262 int nand_scan_ident(struct mtd_info *mtd, int maxchips,
4263 struct nand_flash_dev *table)
4265 int i, nand_maf_id, nand_dev_id;
4266 struct nand_chip *chip = mtd_to_nand(mtd);
4269 ret = nand_dt_init(chip);
4273 if (!mtd->name && mtd->dev.parent)
4274 mtd->name = dev_name(mtd->dev.parent);
4276 if ((!chip->cmdfunc || !chip->select_chip) && !chip->cmd_ctrl) {
4278 * Default functions assigned for chip_select() and
4279 * cmdfunc() both expect cmd_ctrl() to be populated,
4280 * so we need to check that that's the case
4282 pr_err("chip.cmd_ctrl() callback is not provided");
4285 /* Set the default functions */
4286 nand_set_defaults(chip);
4288 /* Read the flash type */
4289 ret = nand_detect(chip, table);
4291 if (!(chip->options & NAND_SCAN_SILENT_NODEV))
4292 pr_warn("No NAND device found\n");
4293 chip->select_chip(mtd, -1);
4297 /* Initialize the ->data_interface field. */
4298 ret = nand_init_data_interface(chip);
4303 * Setup the data interface correctly on the chip and controller side.
4304 * This explicit call to nand_setup_data_interface() is only required
4305 * for the first die, because nand_reset() has been called before
4306 * ->data_interface and ->default_onfi_timing_mode were set.
4307 * For the other dies, nand_reset() will automatically switch to the
4310 ret = nand_setup_data_interface(chip);
4314 nand_maf_id = chip->id.data[0];
4315 nand_dev_id = chip->id.data[1];
4317 chip->select_chip(mtd, -1);
4319 /* Check for a chip array */
4320 for (i = 1; i < maxchips; i++) {
4321 /* See comment in nand_get_flash_type for reset */
4322 nand_reset(chip, i);
4324 chip->select_chip(mtd, i);
4325 /* Send the command for reading device ID */
4326 chip->cmdfunc(mtd, NAND_CMD_READID, 0x00, -1);
4327 /* Read manufacturer and device IDs */
4328 if (nand_maf_id != chip->read_byte(mtd) ||
4329 nand_dev_id != chip->read_byte(mtd)) {
4330 chip->select_chip(mtd, -1);
4333 chip->select_chip(mtd, -1);
4336 pr_info("%d chips detected\n", i);
4338 /* Store the number of chips and calc total size for mtd */
4340 mtd->size = i * chip->chipsize;
4344 EXPORT_SYMBOL(nand_scan_ident);
4346 static int nand_set_ecc_soft_ops(struct mtd_info *mtd)
4348 struct nand_chip *chip = mtd_to_nand(mtd);
4349 struct nand_ecc_ctrl *ecc = &chip->ecc;
4351 if (WARN_ON(ecc->mode != NAND_ECC_SOFT))
4354 switch (ecc->algo) {
4355 case NAND_ECC_HAMMING:
4356 ecc->calculate = nand_calculate_ecc;
4357 ecc->correct = nand_correct_data;
4358 ecc->read_page = nand_read_page_swecc;
4359 ecc->read_subpage = nand_read_subpage;
4360 ecc->write_page = nand_write_page_swecc;
4361 ecc->read_page_raw = nand_read_page_raw;
4362 ecc->write_page_raw = nand_write_page_raw;
4363 ecc->read_oob = nand_read_oob_std;
4364 ecc->write_oob = nand_write_oob_std;
4371 if (!mtd_nand_has_bch()) {
4372 WARN(1, "CONFIG_MTD_NAND_ECC_BCH not enabled\n");
4375 ecc->calculate = nand_bch_calculate_ecc;
4376 ecc->correct = nand_bch_correct_data;
4377 ecc->read_page = nand_read_page_swecc;
4378 ecc->read_subpage = nand_read_subpage;
4379 ecc->write_page = nand_write_page_swecc;
4380 ecc->read_page_raw = nand_read_page_raw;
4381 ecc->write_page_raw = nand_write_page_raw;
4382 ecc->read_oob = nand_read_oob_std;
4383 ecc->write_oob = nand_write_oob_std;
4386 * Board driver should supply ecc.size and ecc.strength
4387 * values to select how many bits are correctable.
4388 * Otherwise, default to 4 bits for large page devices.
4390 if (!ecc->size && (mtd->oobsize >= 64)) {
4396 * if no ecc placement scheme was provided pickup the default
4399 if (!mtd->ooblayout) {
4400 /* handle large page devices only */
4401 if (mtd->oobsize < 64) {
4402 WARN(1, "OOB layout is required when using software BCH on small pages\n");
4406 mtd_set_ooblayout(mtd, &nand_ooblayout_lp_ops);
4411 * We can only maximize ECC config when the default layout is
4412 * used, otherwise we don't know how many bytes can really be
4415 if (mtd->ooblayout == &nand_ooblayout_lp_ops &&
4416 ecc->options & NAND_ECC_MAXIMIZE) {
4419 /* Always prefer 1k blocks over 512bytes ones */
4421 steps = mtd->writesize / ecc->size;
4423 /* Reserve 2 bytes for the BBM */
4424 bytes = (mtd->oobsize - 2) / steps;
4425 ecc->strength = bytes * 8 / fls(8 * ecc->size);
4428 /* See nand_bch_init() for details. */
4430 ecc->priv = nand_bch_init(mtd);
4432 WARN(1, "BCH ECC initialization failed!\n");
4437 WARN(1, "Unsupported ECC algorithm!\n");
4443 * Check if the chip configuration meet the datasheet requirements.
4445 * If our configuration corrects A bits per B bytes and the minimum
4446 * required correction level is X bits per Y bytes, then we must ensure
4447 * both of the following are true:
4449 * (1) A / B >= X / Y
4452 * Requirement (1) ensures we can correct for the required bitflip density.
4453 * Requirement (2) ensures we can correct even when all bitflips are clumped
4454 * in the same sector.
4456 static bool nand_ecc_strength_good(struct mtd_info *mtd)
4458 struct nand_chip *chip = mtd_to_nand(mtd);
4459 struct nand_ecc_ctrl *ecc = &chip->ecc;
4462 if (ecc->size == 0 || chip->ecc_step_ds == 0)
4463 /* Not enough information */
4467 * We get the number of corrected bits per page to compare
4468 * the correction density.
4470 corr = (mtd->writesize * ecc->strength) / ecc->size;
4471 ds_corr = (mtd->writesize * chip->ecc_strength_ds) / chip->ecc_step_ds;
4473 return corr >= ds_corr && ecc->strength >= chip->ecc_strength_ds;
4476 static bool invalid_ecc_page_accessors(struct nand_chip *chip)
4478 struct nand_ecc_ctrl *ecc = &chip->ecc;
4480 if (nand_standard_page_accessors(ecc))
4484 * NAND_ECC_CUSTOM_PAGE_ACCESS flag is set, make sure the NAND
4485 * controller driver implements all the page accessors because
4486 * default helpers are not suitable when the core does not
4487 * send the READ0/PAGEPROG commands.
4489 return (!ecc->read_page || !ecc->write_page ||
4490 !ecc->read_page_raw || !ecc->write_page_raw ||
4491 (NAND_HAS_SUBPAGE_READ(chip) && !ecc->read_subpage) ||
4492 (NAND_HAS_SUBPAGE_WRITE(chip) && !ecc->write_subpage &&
4493 ecc->hwctl && ecc->calculate));
4497 * nand_scan_tail - [NAND Interface] Scan for the NAND device
4498 * @mtd: MTD device structure
4500 * This is the second phase of the normal nand_scan() function. It fills out
4501 * all the uninitialized function pointers with the defaults and scans for a
4502 * bad block table if appropriate.
4504 int nand_scan_tail(struct mtd_info *mtd)
4506 struct nand_chip *chip = mtd_to_nand(mtd);
4507 struct nand_ecc_ctrl *ecc = &chip->ecc;
4508 struct nand_buffers *nbuf;
4511 /* New bad blocks should be marked in OOB, flash-based BBT, or both */
4512 if (WARN_ON((chip->bbt_options & NAND_BBT_NO_OOB_BBM) &&
4513 !(chip->bbt_options & NAND_BBT_USE_FLASH)))
4516 if (invalid_ecc_page_accessors(chip)) {
4517 pr_err("Invalid ECC page accessors setup\n");
4521 if (!(chip->options & NAND_OWN_BUFFERS)) {
4522 nbuf = kzalloc(sizeof(*nbuf) + mtd->writesize
4523 + mtd->oobsize * 3, GFP_KERNEL);
4526 nbuf->ecccalc = (uint8_t *)(nbuf + 1);
4527 nbuf->ecccode = nbuf->ecccalc + mtd->oobsize;
4528 nbuf->databuf = nbuf->ecccode + mtd->oobsize;
4530 chip->buffers = nbuf;
4536 /* Set the internal oob buffer location, just after the page data */
4537 chip->oob_poi = chip->buffers->databuf + mtd->writesize;
4540 * If no default placement scheme is given, select an appropriate one.
4542 if (!mtd->ooblayout &&
4543 !(ecc->mode == NAND_ECC_SOFT && ecc->algo == NAND_ECC_BCH)) {
4544 switch (mtd->oobsize) {
4547 mtd_set_ooblayout(mtd, &nand_ooblayout_sp_ops);
4551 mtd_set_ooblayout(mtd, &nand_ooblayout_lp_ops);
4554 WARN(1, "No oob scheme defined for oobsize %d\n",
4561 if (!chip->write_page)
4562 chip->write_page = nand_write_page;
4565 * Check ECC mode, default to software if 3byte/512byte hardware ECC is
4566 * selected and we have 256 byte pagesize fallback to software ECC
4569 switch (ecc->mode) {
4570 case NAND_ECC_HW_OOB_FIRST:
4571 /* Similar to NAND_ECC_HW, but a separate read_page handle */
4572 if (!ecc->calculate || !ecc->correct || !ecc->hwctl) {
4573 WARN(1, "No ECC functions supplied; hardware ECC not possible\n");
4577 if (!ecc->read_page)
4578 ecc->read_page = nand_read_page_hwecc_oob_first;
4581 /* Use standard hwecc read page function? */
4582 if (!ecc->read_page)
4583 ecc->read_page = nand_read_page_hwecc;
4584 if (!ecc->write_page)
4585 ecc->write_page = nand_write_page_hwecc;
4586 if (!ecc->read_page_raw)
4587 ecc->read_page_raw = nand_read_page_raw;
4588 if (!ecc->write_page_raw)
4589 ecc->write_page_raw = nand_write_page_raw;
4591 ecc->read_oob = nand_read_oob_std;
4592 if (!ecc->write_oob)
4593 ecc->write_oob = nand_write_oob_std;
4594 if (!ecc->read_subpage)
4595 ecc->read_subpage = nand_read_subpage;
4596 if (!ecc->write_subpage && ecc->hwctl && ecc->calculate)
4597 ecc->write_subpage = nand_write_subpage_hwecc;
4599 case NAND_ECC_HW_SYNDROME:
4600 if ((!ecc->calculate || !ecc->correct || !ecc->hwctl) &&
4602 ecc->read_page == nand_read_page_hwecc ||
4604 ecc->write_page == nand_write_page_hwecc)) {
4605 WARN(1, "No ECC functions supplied; hardware ECC not possible\n");
4609 /* Use standard syndrome read/write page function? */
4610 if (!ecc->read_page)
4611 ecc->read_page = nand_read_page_syndrome;
4612 if (!ecc->write_page)
4613 ecc->write_page = nand_write_page_syndrome;
4614 if (!ecc->read_page_raw)
4615 ecc->read_page_raw = nand_read_page_raw_syndrome;
4616 if (!ecc->write_page_raw)
4617 ecc->write_page_raw = nand_write_page_raw_syndrome;
4619 ecc->read_oob = nand_read_oob_syndrome;
4620 if (!ecc->write_oob)
4621 ecc->write_oob = nand_write_oob_syndrome;
4623 if (mtd->writesize >= ecc->size) {
4624 if (!ecc->strength) {
4625 WARN(1, "Driver must set ecc.strength when using hardware ECC\n");
4631 pr_warn("%d byte HW ECC not possible on %d byte page size, fallback to SW ECC\n",
4632 ecc->size, mtd->writesize);
4633 ecc->mode = NAND_ECC_SOFT;
4634 ecc->algo = NAND_ECC_HAMMING;
4637 ret = nand_set_ecc_soft_ops(mtd);
4645 pr_warn("NAND_ECC_NONE selected by board driver. This is not recommended!\n");
4646 ecc->read_page = nand_read_page_raw;
4647 ecc->write_page = nand_write_page_raw;
4648 ecc->read_oob = nand_read_oob_std;
4649 ecc->read_page_raw = nand_read_page_raw;
4650 ecc->write_page_raw = nand_write_page_raw;
4651 ecc->write_oob = nand_write_oob_std;
4652 ecc->size = mtd->writesize;
4658 WARN(1, "Invalid NAND_ECC_MODE %d\n", ecc->mode);
4663 /* For many systems, the standard OOB write also works for raw */
4664 if (!ecc->read_oob_raw)
4665 ecc->read_oob_raw = ecc->read_oob;
4666 if (!ecc->write_oob_raw)
4667 ecc->write_oob_raw = ecc->write_oob;
4669 /* propagate ecc info to mtd_info */
4670 mtd->ecc_strength = ecc->strength;
4671 mtd->ecc_step_size = ecc->size;
4674 * Set the number of read / write steps for one page depending on ECC
4677 ecc->steps = mtd->writesize / ecc->size;
4678 if (ecc->steps * ecc->size != mtd->writesize) {
4679 WARN(1, "Invalid ECC parameters\n");
4683 ecc->total = ecc->steps * ecc->bytes;
4686 * The number of bytes available for a client to place data into
4687 * the out of band area.
4689 ret = mtd_ooblayout_count_freebytes(mtd);
4693 mtd->oobavail = ret;
4695 /* ECC sanity check: warn if it's too weak */
4696 if (!nand_ecc_strength_good(mtd))
4697 pr_warn("WARNING: %s: the ECC used on your system is too weak compared to the one required by the NAND chip\n",
4700 /* Allow subpage writes up to ecc.steps. Not possible for MLC flash */
4701 if (!(chip->options & NAND_NO_SUBPAGE_WRITE) && nand_is_slc(chip)) {
4702 switch (ecc->steps) {
4704 mtd->subpage_sft = 1;
4709 mtd->subpage_sft = 2;
4713 chip->subpagesize = mtd->writesize >> mtd->subpage_sft;
4715 /* Initialize state */
4716 chip->state = FL_READY;
4718 /* Invalidate the pagebuffer reference */
4721 /* Large page NAND with SOFT_ECC should support subpage reads */
4722 switch (ecc->mode) {
4724 if (chip->page_shift > 9)
4725 chip->options |= NAND_SUBPAGE_READ;
4732 /* Fill in remaining MTD driver data */
4733 mtd->type = nand_is_slc(chip) ? MTD_NANDFLASH : MTD_MLCNANDFLASH;
4734 mtd->flags = (chip->options & NAND_ROM) ? MTD_CAP_ROM :
4736 mtd->_erase = nand_erase;
4738 mtd->_unpoint = NULL;
4739 mtd->_read = nand_read;
4740 mtd->_write = nand_write;
4741 mtd->_panic_write = panic_nand_write;
4742 mtd->_read_oob = nand_read_oob;
4743 mtd->_write_oob = nand_write_oob;
4744 mtd->_sync = nand_sync;
4746 mtd->_unlock = NULL;
4747 mtd->_suspend = nand_suspend;
4748 mtd->_resume = nand_resume;
4749 mtd->_reboot = nand_shutdown;
4750 mtd->_block_isreserved = nand_block_isreserved;
4751 mtd->_block_isbad = nand_block_isbad;
4752 mtd->_block_markbad = nand_block_markbad;
4753 mtd->_max_bad_blocks = nand_max_bad_blocks;
4754 mtd->writebufsize = mtd->writesize;
4757 * Initialize bitflip_threshold to its default prior scan_bbt() call.
4758 * scan_bbt() might invoke mtd_read(), thus bitflip_threshold must be
4761 if (!mtd->bitflip_threshold)
4762 mtd->bitflip_threshold = DIV_ROUND_UP(mtd->ecc_strength * 3, 4);
4764 /* Check, if we should skip the bad block table scan */
4765 if (chip->options & NAND_SKIP_BBTSCAN)
4768 /* Build bad block table */
4769 return chip->scan_bbt(mtd);
4771 if (!(chip->options & NAND_OWN_BUFFERS))
4772 kfree(chip->buffers);
4775 EXPORT_SYMBOL(nand_scan_tail);
4778 * is_module_text_address() isn't exported, and it's mostly a pointless
4779 * test if this is a module _anyway_ -- they'd have to try _really_ hard
4780 * to call us from in-kernel code if the core NAND support is modular.
4783 #define caller_is_module() (1)
4785 #define caller_is_module() \
4786 is_module_text_address((unsigned long)__builtin_return_address(0))
4790 * nand_scan - [NAND Interface] Scan for the NAND device
4791 * @mtd: MTD device structure
4792 * @maxchips: number of chips to scan for
4794 * This fills out all the uninitialized function pointers with the defaults.
4795 * The flash ID is read and the mtd/chip structures are filled with the
4796 * appropriate values.
4798 int nand_scan(struct mtd_info *mtd, int maxchips)
4802 ret = nand_scan_ident(mtd, maxchips, NULL);
4804 ret = nand_scan_tail(mtd);
4807 EXPORT_SYMBOL(nand_scan);
4810 * nand_cleanup - [NAND Interface] Free resources held by the NAND device
4811 * @chip: NAND chip object
4813 void nand_cleanup(struct nand_chip *chip)
4815 if (chip->ecc.mode == NAND_ECC_SOFT &&
4816 chip->ecc.algo == NAND_ECC_BCH)
4817 nand_bch_free((struct nand_bch_control *)chip->ecc.priv);
4819 nand_release_data_interface(chip);
4821 /* Free bad block table memory */
4823 if (!(chip->options & NAND_OWN_BUFFERS))
4824 kfree(chip->buffers);
4826 /* Free bad block descriptor memory */
4827 if (chip->badblock_pattern && chip->badblock_pattern->options
4828 & NAND_BBT_DYNAMICSTRUCT)
4829 kfree(chip->badblock_pattern);
4831 /* Free manufacturer priv data. */
4832 nand_manufacturer_cleanup(chip);
4834 EXPORT_SYMBOL_GPL(nand_cleanup);
4837 * nand_release - [NAND Interface] Unregister the MTD device and free resources
4838 * held by the NAND device
4839 * @mtd: MTD device structure
4841 void nand_release(struct mtd_info *mtd)
4843 mtd_device_unregister(mtd);
4844 nand_cleanup(mtd_to_nand(mtd));
4846 EXPORT_SYMBOL_GPL(nand_release);
4848 MODULE_LICENSE("GPL");
4849 MODULE_AUTHOR("Steven J. Hill <sjhill@realitydiluted.com>");
4850 MODULE_AUTHOR("Thomas Gleixner <tglx@linutronix.de>");
4851 MODULE_DESCRIPTION("Generic NAND flash driver code");