3 * This is the generic MTD driver for NAND flash devices. It should be
4 * capable of working with almost all NAND chips currently available.
6 * Additional technical information is available on
7 * http://www.linux-mtd.infradead.org/doc/nand.html
9 * Copyright (C) 2000 Steven J. Hill (sjhill@realitydiluted.com)
10 * 2002-2006 Thomas Gleixner (tglx@linutronix.de)
13 * David Woodhouse for adding multichip support
15 * Aleph One Ltd. and Toby Churchill Ltd. for supporting the
16 * rework for 2K page size chips
19 * Enable cached programming for 2k page size chips
20 * Check, if mtd->ecctype should be set to MTD_ECC_HW
21 * if we have HW ECC support.
22 * BBT table is not serialized, has to be fixed
24 * This program is free software; you can redistribute it and/or modify
25 * it under the terms of the GNU General Public License version 2 as
26 * published by the Free Software Foundation.
30 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
32 #include <linux/module.h>
33 #include <linux/delay.h>
34 #include <linux/errno.h>
35 #include <linux/err.h>
36 #include <linux/sched.h>
37 #include <linux/slab.h>
39 #include <linux/nmi.h>
40 #include <linux/types.h>
41 #include <linux/mtd/mtd.h>
42 #include <linux/mtd/rawnand.h>
43 #include <linux/mtd/nand_ecc.h>
44 #include <linux/mtd/nand_bch.h>
45 #include <linux/interrupt.h>
46 #include <linux/bitops.h>
48 #include <linux/mtd/partitions.h>
51 static int nand_get_device(struct mtd_info *mtd, int new_state);
53 static int nand_do_write_oob(struct mtd_info *mtd, loff_t to,
54 struct mtd_oob_ops *ops);
56 /* Define default oob placement schemes for large and small page devices */
57 static int nand_ooblayout_ecc_sp(struct mtd_info *mtd, int section,
58 struct mtd_oob_region *oobregion)
60 struct nand_chip *chip = mtd_to_nand(mtd);
61 struct nand_ecc_ctrl *ecc = &chip->ecc;
67 oobregion->offset = 0;
68 if (mtd->oobsize == 16)
69 oobregion->length = 4;
71 oobregion->length = 3;
73 if (mtd->oobsize == 8)
76 oobregion->offset = 6;
77 oobregion->length = ecc->total - 4;
83 static int nand_ooblayout_free_sp(struct mtd_info *mtd, int section,
84 struct mtd_oob_region *oobregion)
89 if (mtd->oobsize == 16) {
93 oobregion->length = 8;
94 oobregion->offset = 8;
96 oobregion->length = 2;
98 oobregion->offset = 3;
100 oobregion->offset = 6;
106 const struct mtd_ooblayout_ops nand_ooblayout_sp_ops = {
107 .ecc = nand_ooblayout_ecc_sp,
108 .free = nand_ooblayout_free_sp,
110 EXPORT_SYMBOL_GPL(nand_ooblayout_sp_ops);
112 static int nand_ooblayout_ecc_lp(struct mtd_info *mtd, int section,
113 struct mtd_oob_region *oobregion)
115 struct nand_chip *chip = mtd_to_nand(mtd);
116 struct nand_ecc_ctrl *ecc = &chip->ecc;
118 if (section || !ecc->total)
121 oobregion->length = ecc->total;
122 oobregion->offset = mtd->oobsize - oobregion->length;
127 static int nand_ooblayout_free_lp(struct mtd_info *mtd, int section,
128 struct mtd_oob_region *oobregion)
130 struct nand_chip *chip = mtd_to_nand(mtd);
131 struct nand_ecc_ctrl *ecc = &chip->ecc;
136 oobregion->length = mtd->oobsize - ecc->total - 2;
137 oobregion->offset = 2;
142 const struct mtd_ooblayout_ops nand_ooblayout_lp_ops = {
143 .ecc = nand_ooblayout_ecc_lp,
144 .free = nand_ooblayout_free_lp,
146 EXPORT_SYMBOL_GPL(nand_ooblayout_lp_ops);
149 * Support the old "large page" layout used for 1-bit Hamming ECC where ECC
150 * are placed at a fixed offset.
152 static int nand_ooblayout_ecc_lp_hamming(struct mtd_info *mtd, int section,
153 struct mtd_oob_region *oobregion)
155 struct nand_chip *chip = mtd_to_nand(mtd);
156 struct nand_ecc_ctrl *ecc = &chip->ecc;
161 switch (mtd->oobsize) {
163 oobregion->offset = 40;
166 oobregion->offset = 80;
172 oobregion->length = ecc->total;
173 if (oobregion->offset + oobregion->length > mtd->oobsize)
179 static int nand_ooblayout_free_lp_hamming(struct mtd_info *mtd, int section,
180 struct mtd_oob_region *oobregion)
182 struct nand_chip *chip = mtd_to_nand(mtd);
183 struct nand_ecc_ctrl *ecc = &chip->ecc;
186 if (section < 0 || section > 1)
189 switch (mtd->oobsize) {
201 oobregion->offset = 2;
202 oobregion->length = ecc_offset - 2;
204 oobregion->offset = ecc_offset + ecc->total;
205 oobregion->length = mtd->oobsize - oobregion->offset;
211 static const struct mtd_ooblayout_ops nand_ooblayout_lp_hamming_ops = {
212 .ecc = nand_ooblayout_ecc_lp_hamming,
213 .free = nand_ooblayout_free_lp_hamming,
216 static int check_offs_len(struct mtd_info *mtd,
217 loff_t ofs, uint64_t len)
219 struct nand_chip *chip = mtd_to_nand(mtd);
222 /* Start address must align on block boundary */
223 if (ofs & ((1ULL << chip->phys_erase_shift) - 1)) {
224 pr_debug("%s: unaligned address\n", __func__);
228 /* Length must align on block boundary */
229 if (len & ((1ULL << chip->phys_erase_shift) - 1)) {
230 pr_debug("%s: length not block aligned\n", __func__);
238 * nand_release_device - [GENERIC] release chip
239 * @mtd: MTD device structure
241 * Release chip lock and wake up anyone waiting on the device.
243 static void nand_release_device(struct mtd_info *mtd)
245 struct nand_chip *chip = mtd_to_nand(mtd);
247 /* Release the controller and the chip */
248 spin_lock(&chip->controller->lock);
249 chip->controller->active = NULL;
250 chip->state = FL_READY;
251 wake_up(&chip->controller->wq);
252 spin_unlock(&chip->controller->lock);
256 * nand_read_byte - [DEFAULT] read one byte from the chip
257 * @mtd: MTD device structure
259 * Default read function for 8bit buswidth
261 static uint8_t nand_read_byte(struct mtd_info *mtd)
263 struct nand_chip *chip = mtd_to_nand(mtd);
264 return readb(chip->IO_ADDR_R);
268 * nand_read_byte16 - [DEFAULT] read one byte endianness aware from the chip
269 * @mtd: MTD device structure
271 * Default read function for 16bit buswidth with endianness conversion.
274 static uint8_t nand_read_byte16(struct mtd_info *mtd)
276 struct nand_chip *chip = mtd_to_nand(mtd);
277 return (uint8_t) cpu_to_le16(readw(chip->IO_ADDR_R));
281 * nand_read_word - [DEFAULT] read one word from the chip
282 * @mtd: MTD device structure
284 * Default read function for 16bit buswidth without endianness conversion.
286 static u16 nand_read_word(struct mtd_info *mtd)
288 struct nand_chip *chip = mtd_to_nand(mtd);
289 return readw(chip->IO_ADDR_R);
293 * nand_select_chip - [DEFAULT] control CE line
294 * @mtd: MTD device structure
295 * @chipnr: chipnumber to select, -1 for deselect
297 * Default select function for 1 chip devices.
299 static void nand_select_chip(struct mtd_info *mtd, int chipnr)
301 struct nand_chip *chip = mtd_to_nand(mtd);
305 chip->cmd_ctrl(mtd, NAND_CMD_NONE, 0 | NAND_CTRL_CHANGE);
316 * nand_write_byte - [DEFAULT] write single byte to chip
317 * @mtd: MTD device structure
318 * @byte: value to write
320 * Default function to write a byte to I/O[7:0]
322 static void nand_write_byte(struct mtd_info *mtd, uint8_t byte)
324 struct nand_chip *chip = mtd_to_nand(mtd);
326 chip->write_buf(mtd, &byte, 1);
330 * nand_write_byte16 - [DEFAULT] write single byte to a chip with width 16
331 * @mtd: MTD device structure
332 * @byte: value to write
334 * Default function to write a byte to I/O[7:0] on a 16-bit wide chip.
336 static void nand_write_byte16(struct mtd_info *mtd, uint8_t byte)
338 struct nand_chip *chip = mtd_to_nand(mtd);
339 uint16_t word = byte;
342 * It's not entirely clear what should happen to I/O[15:8] when writing
343 * a byte. The ONFi spec (Revision 3.1; 2012-09-19, Section 2.16) reads:
345 * When the host supports a 16-bit bus width, only data is
346 * transferred at the 16-bit width. All address and command line
347 * transfers shall use only the lower 8-bits of the data bus. During
348 * command transfers, the host may place any value on the upper
349 * 8-bits of the data bus. During address transfers, the host shall
350 * set the upper 8-bits of the data bus to 00h.
352 * One user of the write_byte callback is nand_set_features. The
353 * four parameters are specified to be written to I/O[7:0], but this is
354 * neither an address nor a command transfer. Let's assume a 0 on the
355 * upper I/O lines is OK.
357 chip->write_buf(mtd, (uint8_t *)&word, 2);
361 * nand_write_buf - [DEFAULT] write buffer to chip
362 * @mtd: MTD device structure
364 * @len: number of bytes to write
366 * Default write function for 8bit buswidth.
368 static void nand_write_buf(struct mtd_info *mtd, const uint8_t *buf, int len)
370 struct nand_chip *chip = mtd_to_nand(mtd);
372 iowrite8_rep(chip->IO_ADDR_W, buf, len);
376 * nand_read_buf - [DEFAULT] read chip data into buffer
377 * @mtd: MTD device structure
378 * @buf: buffer to store date
379 * @len: number of bytes to read
381 * Default read function for 8bit buswidth.
383 static void nand_read_buf(struct mtd_info *mtd, uint8_t *buf, int len)
385 struct nand_chip *chip = mtd_to_nand(mtd);
387 ioread8_rep(chip->IO_ADDR_R, buf, len);
391 * nand_write_buf16 - [DEFAULT] write buffer to chip
392 * @mtd: MTD device structure
394 * @len: number of bytes to write
396 * Default write function for 16bit buswidth.
398 static void nand_write_buf16(struct mtd_info *mtd, const uint8_t *buf, int len)
400 struct nand_chip *chip = mtd_to_nand(mtd);
401 u16 *p = (u16 *) buf;
403 iowrite16_rep(chip->IO_ADDR_W, p, len >> 1);
407 * nand_read_buf16 - [DEFAULT] read chip data into buffer
408 * @mtd: MTD device structure
409 * @buf: buffer to store date
410 * @len: number of bytes to read
412 * Default read function for 16bit buswidth.
414 static void nand_read_buf16(struct mtd_info *mtd, uint8_t *buf, int len)
416 struct nand_chip *chip = mtd_to_nand(mtd);
417 u16 *p = (u16 *) buf;
419 ioread16_rep(chip->IO_ADDR_R, p, len >> 1);
423 * nand_block_bad - [DEFAULT] Read bad block marker from the chip
424 * @mtd: MTD device structure
425 * @ofs: offset from device start
427 * Check, if the block is bad.
429 static int nand_block_bad(struct mtd_info *mtd, loff_t ofs)
431 int page, page_end, res;
432 struct nand_chip *chip = mtd_to_nand(mtd);
435 if (chip->bbt_options & NAND_BBT_SCANLASTPAGE)
436 ofs += mtd->erasesize - mtd->writesize;
438 page = (int)(ofs >> chip->page_shift) & chip->pagemask;
439 page_end = page + (chip->bbt_options & NAND_BBT_SCAN2NDPAGE ? 2 : 1);
441 for (; page < page_end; page++) {
442 res = chip->ecc.read_oob(mtd, chip, page);
446 bad = chip->oob_poi[chip->badblockpos];
448 if (likely(chip->badblockbits == 8))
451 res = hweight8(bad) < chip->badblockbits;
460 * nand_default_block_markbad - [DEFAULT] mark a block bad via bad block marker
461 * @mtd: MTD device structure
462 * @ofs: offset from device start
464 * This is the default implementation, which can be overridden by a hardware
465 * specific driver. It provides the details for writing a bad block marker to a
468 static int nand_default_block_markbad(struct mtd_info *mtd, loff_t ofs)
470 struct nand_chip *chip = mtd_to_nand(mtd);
471 struct mtd_oob_ops ops;
472 uint8_t buf[2] = { 0, 0 };
473 int ret = 0, res, i = 0;
475 memset(&ops, 0, sizeof(ops));
477 ops.ooboffs = chip->badblockpos;
478 if (chip->options & NAND_BUSWIDTH_16) {
479 ops.ooboffs &= ~0x01;
480 ops.len = ops.ooblen = 2;
482 ops.len = ops.ooblen = 1;
484 ops.mode = MTD_OPS_PLACE_OOB;
486 /* Write to first/last page(s) if necessary */
487 if (chip->bbt_options & NAND_BBT_SCANLASTPAGE)
488 ofs += mtd->erasesize - mtd->writesize;
490 res = nand_do_write_oob(mtd, ofs, &ops);
495 ofs += mtd->writesize;
496 } while ((chip->bbt_options & NAND_BBT_SCAN2NDPAGE) && i < 2);
502 * nand_block_markbad_lowlevel - mark a block bad
503 * @mtd: MTD device structure
504 * @ofs: offset from device start
506 * This function performs the generic NAND bad block marking steps (i.e., bad
507 * block table(s) and/or marker(s)). We only allow the hardware driver to
508 * specify how to write bad block markers to OOB (chip->block_markbad).
510 * We try operations in the following order:
512 * (1) erase the affected block, to allow OOB marker to be written cleanly
513 * (2) write bad block marker to OOB area of affected block (unless flag
514 * NAND_BBT_NO_OOB_BBM is present)
517 * Note that we retain the first error encountered in (2) or (3), finish the
518 * procedures, and dump the error in the end.
520 static int nand_block_markbad_lowlevel(struct mtd_info *mtd, loff_t ofs)
522 struct nand_chip *chip = mtd_to_nand(mtd);
525 if (!(chip->bbt_options & NAND_BBT_NO_OOB_BBM)) {
526 struct erase_info einfo;
528 /* Attempt erase before marking OOB */
529 memset(&einfo, 0, sizeof(einfo));
531 einfo.len = 1ULL << chip->phys_erase_shift;
532 nand_erase_nand(mtd, &einfo, 0);
534 /* Write bad block marker to OOB */
535 nand_get_device(mtd, FL_WRITING);
536 ret = chip->block_markbad(mtd, ofs);
537 nand_release_device(mtd);
540 /* Mark block bad in BBT */
542 res = nand_markbad_bbt(mtd, ofs);
548 mtd->ecc_stats.badblocks++;
554 * nand_check_wp - [GENERIC] check if the chip is write protected
555 * @mtd: MTD device structure
557 * Check, if the device is write protected. The function expects, that the
558 * device is already selected.
560 static int nand_check_wp(struct mtd_info *mtd)
562 struct nand_chip *chip = mtd_to_nand(mtd);
566 /* Broken xD cards report WP despite being writable */
567 if (chip->options & NAND_BROKEN_XD)
570 /* Check the WP bit */
571 ret = nand_status_op(chip, &status);
575 return status & NAND_STATUS_WP ? 0 : 1;
579 * nand_block_isreserved - [GENERIC] Check if a block is marked reserved.
580 * @mtd: MTD device structure
581 * @ofs: offset from device start
583 * Check if the block is marked as reserved.
585 static int nand_block_isreserved(struct mtd_info *mtd, loff_t ofs)
587 struct nand_chip *chip = mtd_to_nand(mtd);
591 /* Return info from the table */
592 return nand_isreserved_bbt(mtd, ofs);
596 * nand_block_checkbad - [GENERIC] Check if a block is marked bad
597 * @mtd: MTD device structure
598 * @ofs: offset from device start
599 * @allowbbt: 1, if its allowed to access the bbt area
601 * Check, if the block is bad. Either by reading the bad block table or
602 * calling of the scan function.
604 static int nand_block_checkbad(struct mtd_info *mtd, loff_t ofs, int allowbbt)
606 struct nand_chip *chip = mtd_to_nand(mtd);
609 return chip->block_bad(mtd, ofs);
611 /* Return info from the table */
612 return nand_isbad_bbt(mtd, ofs, allowbbt);
616 * panic_nand_wait_ready - [GENERIC] Wait for the ready pin after commands.
617 * @mtd: MTD device structure
620 * Helper function for nand_wait_ready used when needing to wait in interrupt
623 static void panic_nand_wait_ready(struct mtd_info *mtd, unsigned long timeo)
625 struct nand_chip *chip = mtd_to_nand(mtd);
628 /* Wait for the device to get ready */
629 for (i = 0; i < timeo; i++) {
630 if (chip->dev_ready(mtd))
632 touch_softlockup_watchdog();
638 * nand_wait_ready - [GENERIC] Wait for the ready pin after commands.
639 * @mtd: MTD device structure
641 * Wait for the ready pin after a command, and warn if a timeout occurs.
643 void nand_wait_ready(struct mtd_info *mtd)
645 struct nand_chip *chip = mtd_to_nand(mtd);
646 unsigned long timeo = 400;
648 if (in_interrupt() || oops_in_progress)
649 return panic_nand_wait_ready(mtd, timeo);
651 /* Wait until command is processed or timeout occurs */
652 timeo = jiffies + msecs_to_jiffies(timeo);
654 if (chip->dev_ready(mtd))
657 } while (time_before(jiffies, timeo));
659 if (!chip->dev_ready(mtd))
660 pr_warn_ratelimited("timeout while waiting for chip to become ready\n");
662 EXPORT_SYMBOL_GPL(nand_wait_ready);
665 * nand_wait_status_ready - [GENERIC] Wait for the ready status after commands.
666 * @mtd: MTD device structure
667 * @timeo: Timeout in ms
669 * Wait for status ready (i.e. command done) or timeout.
671 static void nand_wait_status_ready(struct mtd_info *mtd, unsigned long timeo)
673 register struct nand_chip *chip = mtd_to_nand(mtd);
676 timeo = jiffies + msecs_to_jiffies(timeo);
680 ret = nand_read_data_op(chip, &status, sizeof(status), true);
684 if (status & NAND_STATUS_READY)
686 touch_softlockup_watchdog();
687 } while (time_before(jiffies, timeo));
691 * nand_soft_waitrdy - Poll STATUS reg until RDY bit is set to 1
692 * @chip: NAND chip structure
693 * @timeout_ms: Timeout in ms
695 * Poll the STATUS register using ->exec_op() until the RDY bit becomes 1.
696 * If that does not happen whitin the specified timeout, -ETIMEDOUT is
699 * This helper is intended to be used when the controller does not have access
700 * to the NAND R/B pin.
702 * Be aware that calling this helper from an ->exec_op() implementation means
703 * ->exec_op() must be re-entrant.
705 * Return 0 if the NAND chip is ready, a negative error otherwise.
707 int nand_soft_waitrdy(struct nand_chip *chip, unsigned long timeout_ms)
709 const struct nand_sdr_timings *timings;
716 /* Wait tWB before polling the STATUS reg. */
717 timings = nand_get_sdr_timings(&chip->data_interface);
718 ndelay(PSEC_TO_NSEC(timings->tWB_max));
720 ret = nand_status_op(chip, NULL);
724 timeout_ms = jiffies + msecs_to_jiffies(timeout_ms);
726 ret = nand_read_data_op(chip, &status, sizeof(status), true);
730 if (status & NAND_STATUS_READY)
734 * Typical lowest execution time for a tR on most NANDs is 10us,
735 * use this as polling delay before doing something smarter (ie.
736 * deriving a delay from the timeout value, timeout_ms/ratio).
739 } while (time_before(jiffies, timeout_ms));
742 * We have to exit READ_STATUS mode in order to read real data on the
743 * bus in case the WAITRDY instruction is preceding a DATA_IN
746 nand_exit_status_op(chip);
751 return status & NAND_STATUS_READY ? 0 : -ETIMEDOUT;
753 EXPORT_SYMBOL_GPL(nand_soft_waitrdy);
756 * nand_command - [DEFAULT] Send command to NAND device
757 * @mtd: MTD device structure
758 * @command: the command to be sent
759 * @column: the column address for this command, -1 if none
760 * @page_addr: the page address for this command, -1 if none
762 * Send command to NAND device. This function is used for small page devices
763 * (512 Bytes per page).
765 static void nand_command(struct mtd_info *mtd, unsigned int command,
766 int column, int page_addr)
768 register struct nand_chip *chip = mtd_to_nand(mtd);
769 int ctrl = NAND_CTRL_CLE | NAND_CTRL_CHANGE;
771 /* Write out the command to the device */
772 if (command == NAND_CMD_SEQIN) {
775 if (column >= mtd->writesize) {
777 column -= mtd->writesize;
778 readcmd = NAND_CMD_READOOB;
779 } else if (column < 256) {
780 /* First 256 bytes --> READ0 */
781 readcmd = NAND_CMD_READ0;
784 readcmd = NAND_CMD_READ1;
786 chip->cmd_ctrl(mtd, readcmd, ctrl);
787 ctrl &= ~NAND_CTRL_CHANGE;
789 if (command != NAND_CMD_NONE)
790 chip->cmd_ctrl(mtd, command, ctrl);
792 /* Address cycle, when necessary */
793 ctrl = NAND_CTRL_ALE | NAND_CTRL_CHANGE;
794 /* Serially input address */
796 /* Adjust columns for 16 bit buswidth */
797 if (chip->options & NAND_BUSWIDTH_16 &&
798 !nand_opcode_8bits(command))
800 chip->cmd_ctrl(mtd, column, ctrl);
801 ctrl &= ~NAND_CTRL_CHANGE;
803 if (page_addr != -1) {
804 chip->cmd_ctrl(mtd, page_addr, ctrl);
805 ctrl &= ~NAND_CTRL_CHANGE;
806 chip->cmd_ctrl(mtd, page_addr >> 8, ctrl);
807 if (chip->options & NAND_ROW_ADDR_3)
808 chip->cmd_ctrl(mtd, page_addr >> 16, ctrl);
810 chip->cmd_ctrl(mtd, NAND_CMD_NONE, NAND_NCE | NAND_CTRL_CHANGE);
813 * Program and erase have their own busy handlers status and sequential
819 case NAND_CMD_PAGEPROG:
820 case NAND_CMD_ERASE1:
821 case NAND_CMD_ERASE2:
823 case NAND_CMD_STATUS:
824 case NAND_CMD_READID:
825 case NAND_CMD_SET_FEATURES:
831 udelay(chip->chip_delay);
832 chip->cmd_ctrl(mtd, NAND_CMD_STATUS,
833 NAND_CTRL_CLE | NAND_CTRL_CHANGE);
835 NAND_CMD_NONE, NAND_NCE | NAND_CTRL_CHANGE);
836 /* EZ-NAND can take upto 250ms as per ONFi v4.0 */
837 nand_wait_status_ready(mtd, 250);
840 /* This applies to read commands */
843 * READ0 is sometimes used to exit GET STATUS mode. When this
844 * is the case no address cycles are requested, and we can use
845 * this information to detect that we should not wait for the
846 * device to be ready.
848 if (column == -1 && page_addr == -1)
853 * If we don't have access to the busy pin, we apply the given
856 if (!chip->dev_ready) {
857 udelay(chip->chip_delay);
862 * Apply this short delay always to ensure that we do wait tWB in
863 * any case on any machine.
867 nand_wait_ready(mtd);
870 static void nand_ccs_delay(struct nand_chip *chip)
873 * The controller already takes care of waiting for tCCS when the RNDIN
874 * or RNDOUT command is sent, return directly.
876 if (!(chip->options & NAND_WAIT_TCCS))
880 * Wait tCCS_min if it is correctly defined, otherwise wait 500ns
881 * (which should be safe for all NANDs).
883 if (chip->setup_data_interface)
884 ndelay(chip->data_interface.timings.sdr.tCCS_min / 1000);
890 * nand_command_lp - [DEFAULT] Send command to NAND large page device
891 * @mtd: MTD device structure
892 * @command: the command to be sent
893 * @column: the column address for this command, -1 if none
894 * @page_addr: the page address for this command, -1 if none
896 * Send command to NAND device. This is the version for the new large page
897 * devices. We don't have the separate regions as we have in the small page
898 * devices. We must emulate NAND_CMD_READOOB to keep the code compatible.
900 static void nand_command_lp(struct mtd_info *mtd, unsigned int command,
901 int column, int page_addr)
903 register struct nand_chip *chip = mtd_to_nand(mtd);
905 /* Emulate NAND_CMD_READOOB */
906 if (command == NAND_CMD_READOOB) {
907 column += mtd->writesize;
908 command = NAND_CMD_READ0;
911 /* Command latch cycle */
912 if (command != NAND_CMD_NONE)
913 chip->cmd_ctrl(mtd, command,
914 NAND_NCE | NAND_CLE | NAND_CTRL_CHANGE);
916 if (column != -1 || page_addr != -1) {
917 int ctrl = NAND_CTRL_CHANGE | NAND_NCE | NAND_ALE;
919 /* Serially input address */
921 /* Adjust columns for 16 bit buswidth */
922 if (chip->options & NAND_BUSWIDTH_16 &&
923 !nand_opcode_8bits(command))
925 chip->cmd_ctrl(mtd, column, ctrl);
926 ctrl &= ~NAND_CTRL_CHANGE;
928 /* Only output a single addr cycle for 8bits opcodes. */
929 if (!nand_opcode_8bits(command))
930 chip->cmd_ctrl(mtd, column >> 8, ctrl);
932 if (page_addr != -1) {
933 chip->cmd_ctrl(mtd, page_addr, ctrl);
934 chip->cmd_ctrl(mtd, page_addr >> 8,
935 NAND_NCE | NAND_ALE);
936 if (chip->options & NAND_ROW_ADDR_3)
937 chip->cmd_ctrl(mtd, page_addr >> 16,
938 NAND_NCE | NAND_ALE);
941 chip->cmd_ctrl(mtd, NAND_CMD_NONE, NAND_NCE | NAND_CTRL_CHANGE);
944 * Program and erase have their own busy handlers status, sequential
945 * in and status need no delay.
950 case NAND_CMD_CACHEDPROG:
951 case NAND_CMD_PAGEPROG:
952 case NAND_CMD_ERASE1:
953 case NAND_CMD_ERASE2:
955 case NAND_CMD_STATUS:
956 case NAND_CMD_READID:
957 case NAND_CMD_SET_FEATURES:
961 nand_ccs_delay(chip);
967 udelay(chip->chip_delay);
968 chip->cmd_ctrl(mtd, NAND_CMD_STATUS,
969 NAND_NCE | NAND_CLE | NAND_CTRL_CHANGE);
970 chip->cmd_ctrl(mtd, NAND_CMD_NONE,
971 NAND_NCE | NAND_CTRL_CHANGE);
972 /* EZ-NAND can take upto 250ms as per ONFi v4.0 */
973 nand_wait_status_ready(mtd, 250);
976 case NAND_CMD_RNDOUT:
977 /* No ready / busy check necessary */
978 chip->cmd_ctrl(mtd, NAND_CMD_RNDOUTSTART,
979 NAND_NCE | NAND_CLE | NAND_CTRL_CHANGE);
980 chip->cmd_ctrl(mtd, NAND_CMD_NONE,
981 NAND_NCE | NAND_CTRL_CHANGE);
983 nand_ccs_delay(chip);
988 * READ0 is sometimes used to exit GET STATUS mode. When this
989 * is the case no address cycles are requested, and we can use
990 * this information to detect that READSTART should not be
993 if (column == -1 && page_addr == -1)
996 chip->cmd_ctrl(mtd, NAND_CMD_READSTART,
997 NAND_NCE | NAND_CLE | NAND_CTRL_CHANGE);
998 chip->cmd_ctrl(mtd, NAND_CMD_NONE,
999 NAND_NCE | NAND_CTRL_CHANGE);
1001 /* This applies to read commands */
1004 * If we don't have access to the busy pin, we apply the given
1007 if (!chip->dev_ready) {
1008 udelay(chip->chip_delay);
1014 * Apply this short delay always to ensure that we do wait tWB in
1015 * any case on any machine.
1019 nand_wait_ready(mtd);
1023 * panic_nand_get_device - [GENERIC] Get chip for selected access
1024 * @chip: the nand chip descriptor
1025 * @mtd: MTD device structure
1026 * @new_state: the state which is requested
1028 * Used when in panic, no locks are taken.
1030 static void panic_nand_get_device(struct nand_chip *chip,
1031 struct mtd_info *mtd, int new_state)
1033 /* Hardware controller shared among independent devices */
1034 chip->controller->active = chip;
1035 chip->state = new_state;
1039 * nand_get_device - [GENERIC] Get chip for selected access
1040 * @mtd: MTD device structure
1041 * @new_state: the state which is requested
1043 * Get the device and lock it for exclusive access
1046 nand_get_device(struct mtd_info *mtd, int new_state)
1048 struct nand_chip *chip = mtd_to_nand(mtd);
1049 spinlock_t *lock = &chip->controller->lock;
1050 wait_queue_head_t *wq = &chip->controller->wq;
1051 DECLARE_WAITQUEUE(wait, current);
1055 /* Hardware controller shared among independent devices */
1056 if (!chip->controller->active)
1057 chip->controller->active = chip;
1059 if (chip->controller->active == chip && chip->state == FL_READY) {
1060 chip->state = new_state;
1064 if (new_state == FL_PM_SUSPENDED) {
1065 if (chip->controller->active->state == FL_PM_SUSPENDED) {
1066 chip->state = FL_PM_SUSPENDED;
1071 set_current_state(TASK_UNINTERRUPTIBLE);
1072 add_wait_queue(wq, &wait);
1075 remove_wait_queue(wq, &wait);
1080 * panic_nand_wait - [GENERIC] wait until the command is done
1081 * @mtd: MTD device structure
1082 * @chip: NAND chip structure
1085 * Wait for command done. This is a helper function for nand_wait used when
1086 * we are in interrupt context. May happen when in panic and trying to write
1087 * an oops through mtdoops.
1089 static void panic_nand_wait(struct mtd_info *mtd, struct nand_chip *chip,
1090 unsigned long timeo)
1093 for (i = 0; i < timeo; i++) {
1094 if (chip->dev_ready) {
1095 if (chip->dev_ready(mtd))
1101 ret = nand_read_data_op(chip, &status, sizeof(status),
1106 if (status & NAND_STATUS_READY)
1114 * nand_wait - [DEFAULT] wait until the command is done
1115 * @mtd: MTD device structure
1116 * @chip: NAND chip structure
1118 * Wait for command done. This applies to erase and program only.
1120 static int nand_wait(struct mtd_info *mtd, struct nand_chip *chip)
1123 unsigned long timeo = 400;
1128 * Apply this short delay always to ensure that we do wait tWB in any
1129 * case on any machine.
1133 ret = nand_status_op(chip, NULL);
1137 if (in_interrupt() || oops_in_progress)
1138 panic_nand_wait(mtd, chip, timeo);
1140 timeo = jiffies + msecs_to_jiffies(timeo);
1142 if (chip->dev_ready) {
1143 if (chip->dev_ready(mtd))
1146 ret = nand_read_data_op(chip, &status,
1147 sizeof(status), true);
1151 if (status & NAND_STATUS_READY)
1155 } while (time_before(jiffies, timeo));
1158 ret = nand_read_data_op(chip, &status, sizeof(status), true);
1162 /* This can happen if in case of timeout or buggy dev_ready */
1163 WARN_ON(!(status & NAND_STATUS_READY));
1167 static bool nand_supports_get_features(struct nand_chip *chip, int addr)
1169 return (chip->parameters.supports_set_get_features &&
1170 test_bit(addr, chip->parameters.get_feature_list));
1173 static bool nand_supports_set_features(struct nand_chip *chip, int addr)
1175 return (chip->parameters.supports_set_get_features &&
1176 test_bit(addr, chip->parameters.set_feature_list));
1180 * nand_get_features - wrapper to perform a GET_FEATURE
1181 * @chip: NAND chip info structure
1182 * @addr: feature address
1183 * @subfeature_param: the subfeature parameters, a four bytes array
1185 * Returns 0 for success, a negative error otherwise. Returns -ENOTSUPP if the
1186 * operation cannot be handled.
1188 int nand_get_features(struct nand_chip *chip, int addr,
1189 u8 *subfeature_param)
1191 struct mtd_info *mtd = nand_to_mtd(chip);
1193 if (!nand_supports_get_features(chip, addr))
1196 return chip->get_features(mtd, chip, addr, subfeature_param);
1198 EXPORT_SYMBOL_GPL(nand_get_features);
1201 * nand_set_features - wrapper to perform a SET_FEATURE
1202 * @chip: NAND chip info structure
1203 * @addr: feature address
1204 * @subfeature_param: the subfeature parameters, a four bytes array
1206 * Returns 0 for success, a negative error otherwise. Returns -ENOTSUPP if the
1207 * operation cannot be handled.
1209 int nand_set_features(struct nand_chip *chip, int addr,
1210 u8 *subfeature_param)
1212 struct mtd_info *mtd = nand_to_mtd(chip);
1214 if (!nand_supports_set_features(chip, addr))
1217 return chip->set_features(mtd, chip, addr, subfeature_param);
1219 EXPORT_SYMBOL_GPL(nand_set_features);
1222 * nand_reset_data_interface - Reset data interface and timings
1223 * @chip: The NAND chip
1224 * @chipnr: Internal die id
1226 * Reset the Data interface and timings to ONFI mode 0.
1228 * Returns 0 for success or negative error code otherwise.
1230 static int nand_reset_data_interface(struct nand_chip *chip, int chipnr)
1232 struct mtd_info *mtd = nand_to_mtd(chip);
1235 if (!chip->setup_data_interface)
1239 * The ONFI specification says:
1241 * To transition from NV-DDR or NV-DDR2 to the SDR data
1242 * interface, the host shall use the Reset (FFh) command
1243 * using SDR timing mode 0. A device in any timing mode is
1244 * required to recognize Reset (FFh) command issued in SDR
1248 * Configure the data interface in SDR mode and set the
1249 * timings to timing mode 0.
1252 onfi_fill_data_interface(chip, NAND_SDR_IFACE, 0);
1253 ret = chip->setup_data_interface(mtd, chipnr, &chip->data_interface);
1255 pr_err("Failed to configure data interface to SDR timing mode 0\n");
1261 * nand_setup_data_interface - Setup the best data interface and timings
1262 * @chip: The NAND chip
1263 * @chipnr: Internal die id
1265 * Find and configure the best data interface and NAND timings supported by
1266 * the chip and the driver.
1267 * First tries to retrieve supported timing modes from ONFI information,
1268 * and if the NAND chip does not support ONFI, relies on the
1269 * ->onfi_timing_mode_default specified in the nand_ids table.
1271 * Returns 0 for success or negative error code otherwise.
1273 static int nand_setup_data_interface(struct nand_chip *chip, int chipnr)
1275 struct mtd_info *mtd = nand_to_mtd(chip);
1276 u8 tmode_param[ONFI_SUBFEATURE_PARAM_LEN] = {
1277 chip->onfi_timing_mode_default,
1281 if (!chip->setup_data_interface)
1284 /* Change the mode on the chip side (if supported by the NAND chip) */
1285 if (nand_supports_set_features(chip, ONFI_FEATURE_ADDR_TIMING_MODE)) {
1286 chip->select_chip(mtd, chipnr);
1287 ret = nand_set_features(chip, ONFI_FEATURE_ADDR_TIMING_MODE,
1289 chip->select_chip(mtd, -1);
1294 /* Change the mode on the controller side */
1295 ret = chip->setup_data_interface(mtd, chipnr, &chip->data_interface);
1299 /* Check the mode has been accepted by the chip, if supported */
1300 if (!nand_supports_get_features(chip, ONFI_FEATURE_ADDR_TIMING_MODE))
1303 memset(tmode_param, 0, ONFI_SUBFEATURE_PARAM_LEN);
1304 chip->select_chip(mtd, chipnr);
1305 ret = nand_get_features(chip, ONFI_FEATURE_ADDR_TIMING_MODE,
1307 chip->select_chip(mtd, -1);
1309 goto err_reset_chip;
1311 if (tmode_param[0] != chip->onfi_timing_mode_default) {
1312 pr_warn("timing mode %d not acknowledged by the NAND chip\n",
1313 chip->onfi_timing_mode_default);
1314 goto err_reset_chip;
1321 * Fallback to mode 0 if the chip explicitly did not ack the chosen
1324 nand_reset_data_interface(chip, chipnr);
1325 chip->select_chip(mtd, chipnr);
1326 nand_reset_op(chip);
1327 chip->select_chip(mtd, -1);
1333 * nand_init_data_interface - find the best data interface and timings
1334 * @chip: The NAND chip
1336 * Find the best data interface and NAND timings supported by the chip
1338 * First tries to retrieve supported timing modes from ONFI information,
1339 * and if the NAND chip does not support ONFI, relies on the
1340 * ->onfi_timing_mode_default specified in the nand_ids table. After this
1341 * function nand_chip->data_interface is initialized with the best timing mode
1344 * Returns 0 for success or negative error code otherwise.
1346 static int nand_init_data_interface(struct nand_chip *chip)
1348 struct mtd_info *mtd = nand_to_mtd(chip);
1349 int modes, mode, ret;
1351 if (!chip->setup_data_interface)
1355 * First try to identify the best timings from ONFI parameters and
1356 * if the NAND does not support ONFI, fallback to the default ONFI
1359 modes = onfi_get_async_timing_mode(chip);
1360 if (modes == ONFI_TIMING_MODE_UNKNOWN) {
1361 if (!chip->onfi_timing_mode_default)
1364 modes = GENMASK(chip->onfi_timing_mode_default, 0);
1368 for (mode = fls(modes) - 1; mode >= 0; mode--) {
1369 ret = onfi_fill_data_interface(chip, NAND_SDR_IFACE, mode);
1374 * Pass NAND_DATA_IFACE_CHECK_ONLY to only check if the
1375 * controller supports the requested timings.
1377 ret = chip->setup_data_interface(mtd,
1378 NAND_DATA_IFACE_CHECK_ONLY,
1379 &chip->data_interface);
1381 chip->onfi_timing_mode_default = mode;
1390 * nand_fill_column_cycles - fill the column cycles of an address
1391 * @chip: The NAND chip
1392 * @addrs: Array of address cycles to fill
1393 * @offset_in_page: The offset in the page
1395 * Fills the first or the first two bytes of the @addrs field depending
1396 * on the NAND bus width and the page size.
1398 * Returns the number of cycles needed to encode the column, or a negative
1399 * error code in case one of the arguments is invalid.
1401 static int nand_fill_column_cycles(struct nand_chip *chip, u8 *addrs,
1402 unsigned int offset_in_page)
1404 struct mtd_info *mtd = nand_to_mtd(chip);
1406 /* Make sure the offset is less than the actual page size. */
1407 if (offset_in_page > mtd->writesize + mtd->oobsize)
1411 * On small page NANDs, there's a dedicated command to access the OOB
1412 * area, and the column address is relative to the start of the OOB
1413 * area, not the start of the page. Asjust the address accordingly.
1415 if (mtd->writesize <= 512 && offset_in_page >= mtd->writesize)
1416 offset_in_page -= mtd->writesize;
1419 * The offset in page is expressed in bytes, if the NAND bus is 16-bit
1420 * wide, then it must be divided by 2.
1422 if (chip->options & NAND_BUSWIDTH_16) {
1423 if (WARN_ON(offset_in_page % 2))
1426 offset_in_page /= 2;
1429 addrs[0] = offset_in_page;
1432 * Small page NANDs use 1 cycle for the columns, while large page NANDs
1435 if (mtd->writesize <= 512)
1438 addrs[1] = offset_in_page >> 8;
1443 static int nand_sp_exec_read_page_op(struct nand_chip *chip, unsigned int page,
1444 unsigned int offset_in_page, void *buf,
1447 struct mtd_info *mtd = nand_to_mtd(chip);
1448 const struct nand_sdr_timings *sdr =
1449 nand_get_sdr_timings(&chip->data_interface);
1451 struct nand_op_instr instrs[] = {
1452 NAND_OP_CMD(NAND_CMD_READ0, 0),
1453 NAND_OP_ADDR(3, addrs, PSEC_TO_NSEC(sdr->tWB_max)),
1454 NAND_OP_WAIT_RDY(PSEC_TO_MSEC(sdr->tR_max),
1455 PSEC_TO_NSEC(sdr->tRR_min)),
1456 NAND_OP_DATA_IN(len, buf, 0),
1458 struct nand_operation op = NAND_OPERATION(instrs);
1461 /* Drop the DATA_IN instruction if len is set to 0. */
1465 if (offset_in_page >= mtd->writesize)
1466 instrs[0].ctx.cmd.opcode = NAND_CMD_READOOB;
1467 else if (offset_in_page >= 256 &&
1468 !(chip->options & NAND_BUSWIDTH_16))
1469 instrs[0].ctx.cmd.opcode = NAND_CMD_READ1;
1471 ret = nand_fill_column_cycles(chip, addrs, offset_in_page);
1476 addrs[2] = page >> 8;
1478 if (chip->options & NAND_ROW_ADDR_3) {
1479 addrs[3] = page >> 16;
1480 instrs[1].ctx.addr.naddrs++;
1483 return nand_exec_op(chip, &op);
1486 static int nand_lp_exec_read_page_op(struct nand_chip *chip, unsigned int page,
1487 unsigned int offset_in_page, void *buf,
1490 const struct nand_sdr_timings *sdr =
1491 nand_get_sdr_timings(&chip->data_interface);
1493 struct nand_op_instr instrs[] = {
1494 NAND_OP_CMD(NAND_CMD_READ0, 0),
1495 NAND_OP_ADDR(4, addrs, 0),
1496 NAND_OP_CMD(NAND_CMD_READSTART, PSEC_TO_NSEC(sdr->tWB_max)),
1497 NAND_OP_WAIT_RDY(PSEC_TO_MSEC(sdr->tR_max),
1498 PSEC_TO_NSEC(sdr->tRR_min)),
1499 NAND_OP_DATA_IN(len, buf, 0),
1501 struct nand_operation op = NAND_OPERATION(instrs);
1504 /* Drop the DATA_IN instruction if len is set to 0. */
1508 ret = nand_fill_column_cycles(chip, addrs, offset_in_page);
1513 addrs[3] = page >> 8;
1515 if (chip->options & NAND_ROW_ADDR_3) {
1516 addrs[4] = page >> 16;
1517 instrs[1].ctx.addr.naddrs++;
1520 return nand_exec_op(chip, &op);
1524 * nand_read_page_op - Do a READ PAGE operation
1525 * @chip: The NAND chip
1526 * @page: page to read
1527 * @offset_in_page: offset within the page
1528 * @buf: buffer used to store the data
1529 * @len: length of the buffer
1531 * This function issues a READ PAGE operation.
1532 * This function does not select/unselect the CS line.
1534 * Returns 0 on success, a negative error code otherwise.
1536 int nand_read_page_op(struct nand_chip *chip, unsigned int page,
1537 unsigned int offset_in_page, void *buf, unsigned int len)
1539 struct mtd_info *mtd = nand_to_mtd(chip);
1544 if (offset_in_page + len > mtd->writesize + mtd->oobsize)
1547 if (chip->exec_op) {
1548 if (mtd->writesize > 512)
1549 return nand_lp_exec_read_page_op(chip, page,
1550 offset_in_page, buf,
1553 return nand_sp_exec_read_page_op(chip, page, offset_in_page,
1557 chip->cmdfunc(mtd, NAND_CMD_READ0, offset_in_page, page);
1559 chip->read_buf(mtd, buf, len);
1563 EXPORT_SYMBOL_GPL(nand_read_page_op);
1566 * nand_read_param_page_op - Do a READ PARAMETER PAGE operation
1567 * @chip: The NAND chip
1568 * @page: parameter page to read
1569 * @buf: buffer used to store the data
1570 * @len: length of the buffer
1572 * This function issues a READ PARAMETER PAGE operation.
1573 * This function does not select/unselect the CS line.
1575 * Returns 0 on success, a negative error code otherwise.
1577 static int nand_read_param_page_op(struct nand_chip *chip, u8 page, void *buf,
1580 struct mtd_info *mtd = nand_to_mtd(chip);
1587 if (chip->exec_op) {
1588 const struct nand_sdr_timings *sdr =
1589 nand_get_sdr_timings(&chip->data_interface);
1590 struct nand_op_instr instrs[] = {
1591 NAND_OP_CMD(NAND_CMD_PARAM, 0),
1592 NAND_OP_ADDR(1, &page, PSEC_TO_NSEC(sdr->tWB_max)),
1593 NAND_OP_WAIT_RDY(PSEC_TO_MSEC(sdr->tR_max),
1594 PSEC_TO_NSEC(sdr->tRR_min)),
1595 NAND_OP_8BIT_DATA_IN(len, buf, 0),
1597 struct nand_operation op = NAND_OPERATION(instrs);
1599 /* Drop the DATA_IN instruction if len is set to 0. */
1603 return nand_exec_op(chip, &op);
1606 chip->cmdfunc(mtd, NAND_CMD_PARAM, page, -1);
1607 for (i = 0; i < len; i++)
1608 p[i] = chip->read_byte(mtd);
1614 * nand_change_read_column_op - Do a CHANGE READ COLUMN operation
1615 * @chip: The NAND chip
1616 * @offset_in_page: offset within the page
1617 * @buf: buffer used to store the data
1618 * @len: length of the buffer
1619 * @force_8bit: force 8-bit bus access
1621 * This function issues a CHANGE READ COLUMN operation.
1622 * This function does not select/unselect the CS line.
1624 * Returns 0 on success, a negative error code otherwise.
1626 int nand_change_read_column_op(struct nand_chip *chip,
1627 unsigned int offset_in_page, void *buf,
1628 unsigned int len, bool force_8bit)
1630 struct mtd_info *mtd = nand_to_mtd(chip);
1635 if (offset_in_page + len > mtd->writesize + mtd->oobsize)
1638 /* Small page NANDs do not support column change. */
1639 if (mtd->writesize <= 512)
1642 if (chip->exec_op) {
1643 const struct nand_sdr_timings *sdr =
1644 nand_get_sdr_timings(&chip->data_interface);
1646 struct nand_op_instr instrs[] = {
1647 NAND_OP_CMD(NAND_CMD_RNDOUT, 0),
1648 NAND_OP_ADDR(2, addrs, 0),
1649 NAND_OP_CMD(NAND_CMD_RNDOUTSTART,
1650 PSEC_TO_NSEC(sdr->tCCS_min)),
1651 NAND_OP_DATA_IN(len, buf, 0),
1653 struct nand_operation op = NAND_OPERATION(instrs);
1656 ret = nand_fill_column_cycles(chip, addrs, offset_in_page);
1660 /* Drop the DATA_IN instruction if len is set to 0. */
1664 instrs[3].ctx.data.force_8bit = force_8bit;
1666 return nand_exec_op(chip, &op);
1669 chip->cmdfunc(mtd, NAND_CMD_RNDOUT, offset_in_page, -1);
1671 chip->read_buf(mtd, buf, len);
1675 EXPORT_SYMBOL_GPL(nand_change_read_column_op);
1678 * nand_read_oob_op - Do a READ OOB operation
1679 * @chip: The NAND chip
1680 * @page: page to read
1681 * @offset_in_oob: offset within the OOB area
1682 * @buf: buffer used to store the data
1683 * @len: length of the buffer
1685 * This function issues a READ OOB operation.
1686 * This function does not select/unselect the CS line.
1688 * Returns 0 on success, a negative error code otherwise.
1690 int nand_read_oob_op(struct nand_chip *chip, unsigned int page,
1691 unsigned int offset_in_oob, void *buf, unsigned int len)
1693 struct mtd_info *mtd = nand_to_mtd(chip);
1698 if (offset_in_oob + len > mtd->oobsize)
1702 return nand_read_page_op(chip, page,
1703 mtd->writesize + offset_in_oob,
1706 chip->cmdfunc(mtd, NAND_CMD_READOOB, offset_in_oob, page);
1708 chip->read_buf(mtd, buf, len);
1712 EXPORT_SYMBOL_GPL(nand_read_oob_op);
1714 static int nand_exec_prog_page_op(struct nand_chip *chip, unsigned int page,
1715 unsigned int offset_in_page, const void *buf,
1716 unsigned int len, bool prog)
1718 struct mtd_info *mtd = nand_to_mtd(chip);
1719 const struct nand_sdr_timings *sdr =
1720 nand_get_sdr_timings(&chip->data_interface);
1722 struct nand_op_instr instrs[] = {
1724 * The first instruction will be dropped if we're dealing
1725 * with a large page NAND and adjusted if we're dealing
1726 * with a small page NAND and the page offset is > 255.
1728 NAND_OP_CMD(NAND_CMD_READ0, 0),
1729 NAND_OP_CMD(NAND_CMD_SEQIN, 0),
1730 NAND_OP_ADDR(0, addrs, PSEC_TO_NSEC(sdr->tADL_min)),
1731 NAND_OP_DATA_OUT(len, buf, 0),
1732 NAND_OP_CMD(NAND_CMD_PAGEPROG, PSEC_TO_NSEC(sdr->tWB_max)),
1733 NAND_OP_WAIT_RDY(PSEC_TO_MSEC(sdr->tPROG_max), 0),
1735 struct nand_operation op = NAND_OPERATION(instrs);
1736 int naddrs = nand_fill_column_cycles(chip, addrs, offset_in_page);
1743 addrs[naddrs++] = page;
1744 addrs[naddrs++] = page >> 8;
1745 if (chip->options & NAND_ROW_ADDR_3)
1746 addrs[naddrs++] = page >> 16;
1748 instrs[2].ctx.addr.naddrs = naddrs;
1750 /* Drop the last two instructions if we're not programming the page. */
1753 /* Also drop the DATA_OUT instruction if empty. */
1758 if (mtd->writesize <= 512) {
1760 * Small pages need some more tweaking: we have to adjust the
1761 * first instruction depending on the page offset we're trying
1764 if (offset_in_page >= mtd->writesize)
1765 instrs[0].ctx.cmd.opcode = NAND_CMD_READOOB;
1766 else if (offset_in_page >= 256 &&
1767 !(chip->options & NAND_BUSWIDTH_16))
1768 instrs[0].ctx.cmd.opcode = NAND_CMD_READ1;
1771 * Drop the first command if we're dealing with a large page
1778 ret = nand_exec_op(chip, &op);
1782 ret = nand_status_op(chip, &status);
1790 * nand_prog_page_begin_op - starts a PROG PAGE operation
1791 * @chip: The NAND chip
1792 * @page: page to write
1793 * @offset_in_page: offset within the page
1794 * @buf: buffer containing the data to write to the page
1795 * @len: length of the buffer
1797 * This function issues the first half of a PROG PAGE operation.
1798 * This function does not select/unselect the CS line.
1800 * Returns 0 on success, a negative error code otherwise.
1802 int nand_prog_page_begin_op(struct nand_chip *chip, unsigned int page,
1803 unsigned int offset_in_page, const void *buf,
1806 struct mtd_info *mtd = nand_to_mtd(chip);
1811 if (offset_in_page + len > mtd->writesize + mtd->oobsize)
1815 return nand_exec_prog_page_op(chip, page, offset_in_page, buf,
1818 chip->cmdfunc(mtd, NAND_CMD_SEQIN, offset_in_page, page);
1821 chip->write_buf(mtd, buf, len);
1825 EXPORT_SYMBOL_GPL(nand_prog_page_begin_op);
1828 * nand_prog_page_end_op - ends a PROG PAGE operation
1829 * @chip: The NAND chip
1831 * This function issues the second half of a PROG PAGE operation.
1832 * This function does not select/unselect the CS line.
1834 * Returns 0 on success, a negative error code otherwise.
1836 int nand_prog_page_end_op(struct nand_chip *chip)
1838 struct mtd_info *mtd = nand_to_mtd(chip);
1842 if (chip->exec_op) {
1843 const struct nand_sdr_timings *sdr =
1844 nand_get_sdr_timings(&chip->data_interface);
1845 struct nand_op_instr instrs[] = {
1846 NAND_OP_CMD(NAND_CMD_PAGEPROG,
1847 PSEC_TO_NSEC(sdr->tWB_max)),
1848 NAND_OP_WAIT_RDY(PSEC_TO_MSEC(sdr->tPROG_max), 0),
1850 struct nand_operation op = NAND_OPERATION(instrs);
1852 ret = nand_exec_op(chip, &op);
1856 ret = nand_status_op(chip, &status);
1860 chip->cmdfunc(mtd, NAND_CMD_PAGEPROG, -1, -1);
1861 ret = chip->waitfunc(mtd, chip);
1868 if (status & NAND_STATUS_FAIL)
1873 EXPORT_SYMBOL_GPL(nand_prog_page_end_op);
1876 * nand_prog_page_op - Do a full PROG PAGE operation
1877 * @chip: The NAND chip
1878 * @page: page to write
1879 * @offset_in_page: offset within the page
1880 * @buf: buffer containing the data to write to the page
1881 * @len: length of the buffer
1883 * This function issues a full PROG PAGE operation.
1884 * This function does not select/unselect the CS line.
1886 * Returns 0 on success, a negative error code otherwise.
1888 int nand_prog_page_op(struct nand_chip *chip, unsigned int page,
1889 unsigned int offset_in_page, const void *buf,
1892 struct mtd_info *mtd = nand_to_mtd(chip);
1898 if (offset_in_page + len > mtd->writesize + mtd->oobsize)
1901 if (chip->exec_op) {
1902 status = nand_exec_prog_page_op(chip, page, offset_in_page, buf,
1905 chip->cmdfunc(mtd, NAND_CMD_SEQIN, offset_in_page, page);
1906 chip->write_buf(mtd, buf, len);
1907 chip->cmdfunc(mtd, NAND_CMD_PAGEPROG, -1, -1);
1908 status = chip->waitfunc(mtd, chip);
1911 if (status & NAND_STATUS_FAIL)
1916 EXPORT_SYMBOL_GPL(nand_prog_page_op);
1919 * nand_change_write_column_op - Do a CHANGE WRITE COLUMN operation
1920 * @chip: The NAND chip
1921 * @offset_in_page: offset within the page
1922 * @buf: buffer containing the data to send to the NAND
1923 * @len: length of the buffer
1924 * @force_8bit: force 8-bit bus access
1926 * This function issues a CHANGE WRITE COLUMN operation.
1927 * This function does not select/unselect the CS line.
1929 * Returns 0 on success, a negative error code otherwise.
1931 int nand_change_write_column_op(struct nand_chip *chip,
1932 unsigned int offset_in_page,
1933 const void *buf, unsigned int len,
1936 struct mtd_info *mtd = nand_to_mtd(chip);
1941 if (offset_in_page + len > mtd->writesize + mtd->oobsize)
1944 /* Small page NANDs do not support column change. */
1945 if (mtd->writesize <= 512)
1948 if (chip->exec_op) {
1949 const struct nand_sdr_timings *sdr =
1950 nand_get_sdr_timings(&chip->data_interface);
1952 struct nand_op_instr instrs[] = {
1953 NAND_OP_CMD(NAND_CMD_RNDIN, 0),
1954 NAND_OP_ADDR(2, addrs, PSEC_TO_NSEC(sdr->tCCS_min)),
1955 NAND_OP_DATA_OUT(len, buf, 0),
1957 struct nand_operation op = NAND_OPERATION(instrs);
1960 ret = nand_fill_column_cycles(chip, addrs, offset_in_page);
1964 instrs[2].ctx.data.force_8bit = force_8bit;
1966 /* Drop the DATA_OUT instruction if len is set to 0. */
1970 return nand_exec_op(chip, &op);
1973 chip->cmdfunc(mtd, NAND_CMD_RNDIN, offset_in_page, -1);
1975 chip->write_buf(mtd, buf, len);
1979 EXPORT_SYMBOL_GPL(nand_change_write_column_op);
1982 * nand_readid_op - Do a READID operation
1983 * @chip: The NAND chip
1984 * @addr: address cycle to pass after the READID command
1985 * @buf: buffer used to store the ID
1986 * @len: length of the buffer
1988 * This function sends a READID command and reads back the ID returned by the
1990 * This function does not select/unselect the CS line.
1992 * Returns 0 on success, a negative error code otherwise.
1994 int nand_readid_op(struct nand_chip *chip, u8 addr, void *buf,
1997 struct mtd_info *mtd = nand_to_mtd(chip);
2004 if (chip->exec_op) {
2005 const struct nand_sdr_timings *sdr =
2006 nand_get_sdr_timings(&chip->data_interface);
2007 struct nand_op_instr instrs[] = {
2008 NAND_OP_CMD(NAND_CMD_READID, 0),
2009 NAND_OP_ADDR(1, &addr, PSEC_TO_NSEC(sdr->tADL_min)),
2010 NAND_OP_8BIT_DATA_IN(len, buf, 0),
2012 struct nand_operation op = NAND_OPERATION(instrs);
2014 /* Drop the DATA_IN instruction if len is set to 0. */
2018 return nand_exec_op(chip, &op);
2021 chip->cmdfunc(mtd, NAND_CMD_READID, addr, -1);
2023 for (i = 0; i < len; i++)
2024 id[i] = chip->read_byte(mtd);
2028 EXPORT_SYMBOL_GPL(nand_readid_op);
2031 * nand_status_op - Do a STATUS operation
2032 * @chip: The NAND chip
2033 * @status: out variable to store the NAND status
2035 * This function sends a STATUS command and reads back the status returned by
2037 * This function does not select/unselect the CS line.
2039 * Returns 0 on success, a negative error code otherwise.
2041 int nand_status_op(struct nand_chip *chip, u8 *status)
2043 struct mtd_info *mtd = nand_to_mtd(chip);
2045 if (chip->exec_op) {
2046 const struct nand_sdr_timings *sdr =
2047 nand_get_sdr_timings(&chip->data_interface);
2048 struct nand_op_instr instrs[] = {
2049 NAND_OP_CMD(NAND_CMD_STATUS,
2050 PSEC_TO_NSEC(sdr->tADL_min)),
2051 NAND_OP_8BIT_DATA_IN(1, status, 0),
2053 struct nand_operation op = NAND_OPERATION(instrs);
2058 return nand_exec_op(chip, &op);
2061 chip->cmdfunc(mtd, NAND_CMD_STATUS, -1, -1);
2063 *status = chip->read_byte(mtd);
2067 EXPORT_SYMBOL_GPL(nand_status_op);
2070 * nand_exit_status_op - Exit a STATUS operation
2071 * @chip: The NAND chip
2073 * This function sends a READ0 command to cancel the effect of the STATUS
2074 * command to avoid reading only the status until a new read command is sent.
2076 * This function does not select/unselect the CS line.
2078 * Returns 0 on success, a negative error code otherwise.
2080 int nand_exit_status_op(struct nand_chip *chip)
2082 struct mtd_info *mtd = nand_to_mtd(chip);
2084 if (chip->exec_op) {
2085 struct nand_op_instr instrs[] = {
2086 NAND_OP_CMD(NAND_CMD_READ0, 0),
2088 struct nand_operation op = NAND_OPERATION(instrs);
2090 return nand_exec_op(chip, &op);
2093 chip->cmdfunc(mtd, NAND_CMD_READ0, -1, -1);
2097 EXPORT_SYMBOL_GPL(nand_exit_status_op);
2100 * nand_erase_op - Do an erase operation
2101 * @chip: The NAND chip
2102 * @eraseblock: block to erase
2104 * This function sends an ERASE command and waits for the NAND to be ready
2106 * This function does not select/unselect the CS line.
2108 * Returns 0 on success, a negative error code otherwise.
2110 int nand_erase_op(struct nand_chip *chip, unsigned int eraseblock)
2112 struct mtd_info *mtd = nand_to_mtd(chip);
2113 unsigned int page = eraseblock <<
2114 (chip->phys_erase_shift - chip->page_shift);
2118 if (chip->exec_op) {
2119 const struct nand_sdr_timings *sdr =
2120 nand_get_sdr_timings(&chip->data_interface);
2121 u8 addrs[3] = { page, page >> 8, page >> 16 };
2122 struct nand_op_instr instrs[] = {
2123 NAND_OP_CMD(NAND_CMD_ERASE1, 0),
2124 NAND_OP_ADDR(2, addrs, 0),
2125 NAND_OP_CMD(NAND_CMD_ERASE2,
2126 PSEC_TO_MSEC(sdr->tWB_max)),
2127 NAND_OP_WAIT_RDY(PSEC_TO_MSEC(sdr->tBERS_max), 0),
2129 struct nand_operation op = NAND_OPERATION(instrs);
2131 if (chip->options & NAND_ROW_ADDR_3)
2132 instrs[1].ctx.addr.naddrs++;
2134 ret = nand_exec_op(chip, &op);
2138 ret = nand_status_op(chip, &status);
2142 chip->cmdfunc(mtd, NAND_CMD_ERASE1, -1, page);
2143 chip->cmdfunc(mtd, NAND_CMD_ERASE2, -1, -1);
2145 ret = chip->waitfunc(mtd, chip);
2152 if (status & NAND_STATUS_FAIL)
2157 EXPORT_SYMBOL_GPL(nand_erase_op);
2160 * nand_set_features_op - Do a SET FEATURES operation
2161 * @chip: The NAND chip
2162 * @feature: feature id
2163 * @data: 4 bytes of data
2165 * This function sends a SET FEATURES command and waits for the NAND to be
2166 * ready before returning.
2167 * This function does not select/unselect the CS line.
2169 * Returns 0 on success, a negative error code otherwise.
2171 static int nand_set_features_op(struct nand_chip *chip, u8 feature,
2174 struct mtd_info *mtd = nand_to_mtd(chip);
2175 const u8 *params = data;
2178 if (chip->exec_op) {
2179 const struct nand_sdr_timings *sdr =
2180 nand_get_sdr_timings(&chip->data_interface);
2181 struct nand_op_instr instrs[] = {
2182 NAND_OP_CMD(NAND_CMD_SET_FEATURES, 0),
2183 NAND_OP_ADDR(1, &feature, PSEC_TO_NSEC(sdr->tADL_min)),
2184 NAND_OP_8BIT_DATA_OUT(ONFI_SUBFEATURE_PARAM_LEN, data,
2185 PSEC_TO_NSEC(sdr->tWB_max)),
2186 NAND_OP_WAIT_RDY(PSEC_TO_MSEC(sdr->tFEAT_max), 0),
2188 struct nand_operation op = NAND_OPERATION(instrs);
2190 return nand_exec_op(chip, &op);
2193 chip->cmdfunc(mtd, NAND_CMD_SET_FEATURES, feature, -1);
2194 for (i = 0; i < ONFI_SUBFEATURE_PARAM_LEN; ++i)
2195 chip->write_byte(mtd, params[i]);
2197 ret = chip->waitfunc(mtd, chip);
2201 if (ret & NAND_STATUS_FAIL)
2208 * nand_get_features_op - Do a GET FEATURES operation
2209 * @chip: The NAND chip
2210 * @feature: feature id
2211 * @data: 4 bytes of data
2213 * This function sends a GET FEATURES command and waits for the NAND to be
2214 * ready before returning.
2215 * This function does not select/unselect the CS line.
2217 * Returns 0 on success, a negative error code otherwise.
2219 static int nand_get_features_op(struct nand_chip *chip, u8 feature,
2222 struct mtd_info *mtd = nand_to_mtd(chip);
2226 if (chip->exec_op) {
2227 const struct nand_sdr_timings *sdr =
2228 nand_get_sdr_timings(&chip->data_interface);
2229 struct nand_op_instr instrs[] = {
2230 NAND_OP_CMD(NAND_CMD_GET_FEATURES, 0),
2231 NAND_OP_ADDR(1, &feature, PSEC_TO_NSEC(sdr->tWB_max)),
2232 NAND_OP_WAIT_RDY(PSEC_TO_MSEC(sdr->tFEAT_max),
2233 PSEC_TO_NSEC(sdr->tRR_min)),
2234 NAND_OP_8BIT_DATA_IN(ONFI_SUBFEATURE_PARAM_LEN,
2237 struct nand_operation op = NAND_OPERATION(instrs);
2239 return nand_exec_op(chip, &op);
2242 chip->cmdfunc(mtd, NAND_CMD_GET_FEATURES, feature, -1);
2243 for (i = 0; i < ONFI_SUBFEATURE_PARAM_LEN; ++i)
2244 params[i] = chip->read_byte(mtd);
2250 * nand_reset_op - Do a reset operation
2251 * @chip: The NAND chip
2253 * This function sends a RESET command and waits for the NAND to be ready
2255 * This function does not select/unselect the CS line.
2257 * Returns 0 on success, a negative error code otherwise.
2259 int nand_reset_op(struct nand_chip *chip)
2261 struct mtd_info *mtd = nand_to_mtd(chip);
2263 if (chip->exec_op) {
2264 const struct nand_sdr_timings *sdr =
2265 nand_get_sdr_timings(&chip->data_interface);
2266 struct nand_op_instr instrs[] = {
2267 NAND_OP_CMD(NAND_CMD_RESET, PSEC_TO_NSEC(sdr->tWB_max)),
2268 NAND_OP_WAIT_RDY(PSEC_TO_MSEC(sdr->tRST_max), 0),
2270 struct nand_operation op = NAND_OPERATION(instrs);
2272 return nand_exec_op(chip, &op);
2275 chip->cmdfunc(mtd, NAND_CMD_RESET, -1, -1);
2279 EXPORT_SYMBOL_GPL(nand_reset_op);
2282 * nand_read_data_op - Read data from the NAND
2283 * @chip: The NAND chip
2284 * @buf: buffer used to store the data
2285 * @len: length of the buffer
2286 * @force_8bit: force 8-bit bus access
2288 * This function does a raw data read on the bus. Usually used after launching
2289 * another NAND operation like nand_read_page_op().
2290 * This function does not select/unselect the CS line.
2292 * Returns 0 on success, a negative error code otherwise.
2294 int nand_read_data_op(struct nand_chip *chip, void *buf, unsigned int len,
2297 struct mtd_info *mtd = nand_to_mtd(chip);
2302 if (chip->exec_op) {
2303 struct nand_op_instr instrs[] = {
2304 NAND_OP_DATA_IN(len, buf, 0),
2306 struct nand_operation op = NAND_OPERATION(instrs);
2308 instrs[0].ctx.data.force_8bit = force_8bit;
2310 return nand_exec_op(chip, &op);
2317 for (i = 0; i < len; i++)
2318 p[i] = chip->read_byte(mtd);
2320 chip->read_buf(mtd, buf, len);
2325 EXPORT_SYMBOL_GPL(nand_read_data_op);
2328 * nand_write_data_op - Write data from the NAND
2329 * @chip: The NAND chip
2330 * @buf: buffer containing the data to send on the bus
2331 * @len: length of the buffer
2332 * @force_8bit: force 8-bit bus access
2334 * This function does a raw data write on the bus. Usually used after launching
2335 * another NAND operation like nand_write_page_begin_op().
2336 * This function does not select/unselect the CS line.
2338 * Returns 0 on success, a negative error code otherwise.
2340 int nand_write_data_op(struct nand_chip *chip, const void *buf,
2341 unsigned int len, bool force_8bit)
2343 struct mtd_info *mtd = nand_to_mtd(chip);
2348 if (chip->exec_op) {
2349 struct nand_op_instr instrs[] = {
2350 NAND_OP_DATA_OUT(len, buf, 0),
2352 struct nand_operation op = NAND_OPERATION(instrs);
2354 instrs[0].ctx.data.force_8bit = force_8bit;
2356 return nand_exec_op(chip, &op);
2363 for (i = 0; i < len; i++)
2364 chip->write_byte(mtd, p[i]);
2366 chip->write_buf(mtd, buf, len);
2371 EXPORT_SYMBOL_GPL(nand_write_data_op);
2374 * struct nand_op_parser_ctx - Context used by the parser
2375 * @instrs: array of all the instructions that must be addressed
2376 * @ninstrs: length of the @instrs array
2377 * @subop: Sub-operation to be passed to the NAND controller
2379 * This structure is used by the core to split NAND operations into
2380 * sub-operations that can be handled by the NAND controller.
2382 struct nand_op_parser_ctx {
2383 const struct nand_op_instr *instrs;
2384 unsigned int ninstrs;
2385 struct nand_subop subop;
2389 * nand_op_parser_must_split_instr - Checks if an instruction must be split
2390 * @pat: the parser pattern element that matches @instr
2391 * @instr: pointer to the instruction to check
2392 * @start_offset: this is an in/out parameter. If @instr has already been
2393 * split, then @start_offset is the offset from which to start
2394 * (either an address cycle or an offset in the data buffer).
2395 * Conversely, if the function returns true (ie. instr must be
2396 * split), this parameter is updated to point to the first
2397 * data/address cycle that has not been taken care of.
2399 * Some NAND controllers are limited and cannot send X address cycles with a
2400 * unique operation, or cannot read/write more than Y bytes at the same time.
2401 * In this case, split the instruction that does not fit in a single
2402 * controller-operation into two or more chunks.
2404 * Returns true if the instruction must be split, false otherwise.
2405 * The @start_offset parameter is also updated to the offset at which the next
2406 * bundle of instruction must start (if an address or a data instruction).
2409 nand_op_parser_must_split_instr(const struct nand_op_parser_pattern_elem *pat,
2410 const struct nand_op_instr *instr,
2411 unsigned int *start_offset)
2413 switch (pat->type) {
2414 case NAND_OP_ADDR_INSTR:
2415 if (!pat->ctx.addr.maxcycles)
2418 if (instr->ctx.addr.naddrs - *start_offset >
2419 pat->ctx.addr.maxcycles) {
2420 *start_offset += pat->ctx.addr.maxcycles;
2425 case NAND_OP_DATA_IN_INSTR:
2426 case NAND_OP_DATA_OUT_INSTR:
2427 if (!pat->ctx.data.maxlen)
2430 if (instr->ctx.data.len - *start_offset >
2431 pat->ctx.data.maxlen) {
2432 *start_offset += pat->ctx.data.maxlen;
2445 * nand_op_parser_match_pat - Checks if a pattern matches the instructions
2446 * remaining in the parser context
2447 * @pat: the pattern to test
2448 * @ctx: the parser context structure to match with the pattern @pat
2450 * Check if @pat matches the set or a sub-set of instructions remaining in @ctx.
2451 * Returns true if this is the case, false ortherwise. When true is returned,
2452 * @ctx->subop is updated with the set of instructions to be passed to the
2453 * controller driver.
2456 nand_op_parser_match_pat(const struct nand_op_parser_pattern *pat,
2457 struct nand_op_parser_ctx *ctx)
2459 unsigned int instr_offset = ctx->subop.first_instr_start_off;
2460 const struct nand_op_instr *end = ctx->instrs + ctx->ninstrs;
2461 const struct nand_op_instr *instr = ctx->subop.instrs;
2462 unsigned int i, ninstrs;
2464 for (i = 0, ninstrs = 0; i < pat->nelems && instr < end; i++) {
2466 * The pattern instruction does not match the operation
2467 * instruction. If the instruction is marked optional in the
2468 * pattern definition, we skip the pattern element and continue
2469 * to the next one. If the element is mandatory, there's no
2470 * match and we can return false directly.
2472 if (instr->type != pat->elems[i].type) {
2473 if (!pat->elems[i].optional)
2480 * Now check the pattern element constraints. If the pattern is
2481 * not able to handle the whole instruction in a single step,
2482 * we have to split it.
2483 * The last_instr_end_off value comes back updated to point to
2484 * the position where we have to split the instruction (the
2485 * start of the next subop chunk).
2487 if (nand_op_parser_must_split_instr(&pat->elems[i], instr,
2500 * This can happen if all instructions of a pattern are optional.
2501 * Still, if there's not at least one instruction handled by this
2502 * pattern, this is not a match, and we should try the next one (if
2509 * We had a match on the pattern head, but the pattern may be longer
2510 * than the instructions we're asked to execute. We need to make sure
2511 * there's no mandatory elements in the pattern tail.
2513 for (; i < pat->nelems; i++) {
2514 if (!pat->elems[i].optional)
2519 * We have a match: update the subop structure accordingly and return
2522 ctx->subop.ninstrs = ninstrs;
2523 ctx->subop.last_instr_end_off = instr_offset;
2528 #if IS_ENABLED(CONFIG_DYNAMIC_DEBUG) || defined(DEBUG)
2529 static void nand_op_parser_trace(const struct nand_op_parser_ctx *ctx)
2531 const struct nand_op_instr *instr;
2535 pr_debug("executing subop:\n");
2537 for (i = 0; i < ctx->ninstrs; i++) {
2538 instr = &ctx->instrs[i];
2540 if (instr == &ctx->subop.instrs[0])
2543 switch (instr->type) {
2544 case NAND_OP_CMD_INSTR:
2545 pr_debug("%sCMD [0x%02x]\n", prefix,
2546 instr->ctx.cmd.opcode);
2548 case NAND_OP_ADDR_INSTR:
2549 pr_debug("%sADDR [%d cyc: %*ph]\n", prefix,
2550 instr->ctx.addr.naddrs,
2551 instr->ctx.addr.naddrs < 64 ?
2552 instr->ctx.addr.naddrs : 64,
2553 instr->ctx.addr.addrs);
2555 case NAND_OP_DATA_IN_INSTR:
2556 pr_debug("%sDATA_IN [%d B%s]\n", prefix,
2557 instr->ctx.data.len,
2558 instr->ctx.data.force_8bit ?
2559 ", force 8-bit" : "");
2561 case NAND_OP_DATA_OUT_INSTR:
2562 pr_debug("%sDATA_OUT [%d B%s]\n", prefix,
2563 instr->ctx.data.len,
2564 instr->ctx.data.force_8bit ?
2565 ", force 8-bit" : "");
2567 case NAND_OP_WAITRDY_INSTR:
2568 pr_debug("%sWAITRDY [max %d ms]\n", prefix,
2569 instr->ctx.waitrdy.timeout_ms);
2573 if (instr == &ctx->subop.instrs[ctx->subop.ninstrs - 1])
2578 static void nand_op_parser_trace(const struct nand_op_parser_ctx *ctx)
2585 * nand_op_parser_exec_op - exec_op parser
2586 * @chip: the NAND chip
2587 * @parser: patterns description provided by the controller driver
2588 * @op: the NAND operation to address
2589 * @check_only: when true, the function only checks if @op can be handled but
2590 * does not execute the operation
2592 * Helper function designed to ease integration of NAND controller drivers that
2593 * only support a limited set of instruction sequences. The supported sequences
2594 * are described in @parser, and the framework takes care of splitting @op into
2595 * multiple sub-operations (if required) and pass them back to the ->exec()
2596 * callback of the matching pattern if @check_only is set to false.
2598 * NAND controller drivers should call this function from their own ->exec_op()
2601 * Returns 0 on success, a negative error code otherwise. A failure can be
2602 * caused by an unsupported operation (none of the supported patterns is able
2603 * to handle the requested operation), or an error returned by one of the
2604 * matching pattern->exec() hook.
2606 int nand_op_parser_exec_op(struct nand_chip *chip,
2607 const struct nand_op_parser *parser,
2608 const struct nand_operation *op, bool check_only)
2610 struct nand_op_parser_ctx ctx = {
2611 .subop.instrs = op->instrs,
2612 .instrs = op->instrs,
2613 .ninstrs = op->ninstrs,
2617 while (ctx.subop.instrs < op->instrs + op->ninstrs) {
2620 for (i = 0; i < parser->npatterns; i++) {
2621 const struct nand_op_parser_pattern *pattern;
2623 pattern = &parser->patterns[i];
2624 if (!nand_op_parser_match_pat(pattern, &ctx))
2627 nand_op_parser_trace(&ctx);
2632 ret = pattern->exec(chip, &ctx.subop);
2639 if (i == parser->npatterns) {
2640 pr_debug("->exec_op() parser: pattern not found!\n");
2645 * Update the context structure by pointing to the start of the
2648 ctx.subop.instrs = ctx.subop.instrs + ctx.subop.ninstrs;
2649 if (ctx.subop.last_instr_end_off)
2650 ctx.subop.instrs -= 1;
2652 ctx.subop.first_instr_start_off = ctx.subop.last_instr_end_off;
2657 EXPORT_SYMBOL_GPL(nand_op_parser_exec_op);
2659 static bool nand_instr_is_data(const struct nand_op_instr *instr)
2661 return instr && (instr->type == NAND_OP_DATA_IN_INSTR ||
2662 instr->type == NAND_OP_DATA_OUT_INSTR);
2665 static bool nand_subop_instr_is_valid(const struct nand_subop *subop,
2666 unsigned int instr_idx)
2668 return subop && instr_idx < subop->ninstrs;
2671 static int nand_subop_get_start_off(const struct nand_subop *subop,
2672 unsigned int instr_idx)
2677 return subop->first_instr_start_off;
2681 * nand_subop_get_addr_start_off - Get the start offset in an address array
2682 * @subop: The entire sub-operation
2683 * @instr_idx: Index of the instruction inside the sub-operation
2685 * During driver development, one could be tempted to directly use the
2686 * ->addr.addrs field of address instructions. This is wrong as address
2687 * instructions might be split.
2689 * Given an address instruction, returns the offset of the first cycle to issue.
2691 int nand_subop_get_addr_start_off(const struct nand_subop *subop,
2692 unsigned int instr_idx)
2694 if (!nand_subop_instr_is_valid(subop, instr_idx) ||
2695 subop->instrs[instr_idx].type != NAND_OP_ADDR_INSTR)
2698 return nand_subop_get_start_off(subop, instr_idx);
2700 EXPORT_SYMBOL_GPL(nand_subop_get_addr_start_off);
2703 * nand_subop_get_num_addr_cyc - Get the remaining address cycles to assert
2704 * @subop: The entire sub-operation
2705 * @instr_idx: Index of the instruction inside the sub-operation
2707 * During driver development, one could be tempted to directly use the
2708 * ->addr->naddrs field of a data instruction. This is wrong as instructions
2711 * Given an address instruction, returns the number of address cycle to issue.
2713 int nand_subop_get_num_addr_cyc(const struct nand_subop *subop,
2714 unsigned int instr_idx)
2716 int start_off, end_off;
2718 if (!nand_subop_instr_is_valid(subop, instr_idx) ||
2719 subop->instrs[instr_idx].type != NAND_OP_ADDR_INSTR)
2722 start_off = nand_subop_get_addr_start_off(subop, instr_idx);
2724 if (instr_idx == subop->ninstrs - 1 &&
2725 subop->last_instr_end_off)
2726 end_off = subop->last_instr_end_off;
2728 end_off = subop->instrs[instr_idx].ctx.addr.naddrs;
2730 return end_off - start_off;
2732 EXPORT_SYMBOL_GPL(nand_subop_get_num_addr_cyc);
2735 * nand_subop_get_data_start_off - Get the start offset in a data array
2736 * @subop: The entire sub-operation
2737 * @instr_idx: Index of the instruction inside the sub-operation
2739 * During driver development, one could be tempted to directly use the
2740 * ->data->buf.{in,out} field of data instructions. This is wrong as data
2741 * instructions might be split.
2743 * Given a data instruction, returns the offset to start from.
2745 int nand_subop_get_data_start_off(const struct nand_subop *subop,
2746 unsigned int instr_idx)
2748 if (!nand_subop_instr_is_valid(subop, instr_idx) ||
2749 !nand_instr_is_data(&subop->instrs[instr_idx]))
2752 return nand_subop_get_start_off(subop, instr_idx);
2754 EXPORT_SYMBOL_GPL(nand_subop_get_data_start_off);
2757 * nand_subop_get_data_len - Get the number of bytes to retrieve
2758 * @subop: The entire sub-operation
2759 * @instr_idx: Index of the instruction inside the sub-operation
2761 * During driver development, one could be tempted to directly use the
2762 * ->data->len field of a data instruction. This is wrong as data instructions
2765 * Returns the length of the chunk of data to send/receive.
2767 int nand_subop_get_data_len(const struct nand_subop *subop,
2768 unsigned int instr_idx)
2770 int start_off = 0, end_off;
2772 if (!nand_subop_instr_is_valid(subop, instr_idx) ||
2773 !nand_instr_is_data(&subop->instrs[instr_idx]))
2776 start_off = nand_subop_get_data_start_off(subop, instr_idx);
2778 if (instr_idx == subop->ninstrs - 1 &&
2779 subop->last_instr_end_off)
2780 end_off = subop->last_instr_end_off;
2782 end_off = subop->instrs[instr_idx].ctx.data.len;
2784 return end_off - start_off;
2786 EXPORT_SYMBOL_GPL(nand_subop_get_data_len);
2789 * nand_reset - Reset and initialize a NAND device
2790 * @chip: The NAND chip
2791 * @chipnr: Internal die id
2793 * Save the timings data structure, then apply SDR timings mode 0 (see
2794 * nand_reset_data_interface for details), do the reset operation, and
2795 * apply back the previous timings.
2797 * Returns 0 on success, a negative error code otherwise.
2799 int nand_reset(struct nand_chip *chip, int chipnr)
2801 struct mtd_info *mtd = nand_to_mtd(chip);
2802 struct nand_data_interface saved_data_intf = chip->data_interface;
2805 ret = nand_reset_data_interface(chip, chipnr);
2810 * The CS line has to be released before we can apply the new NAND
2811 * interface settings, hence this weird ->select_chip() dance.
2813 chip->select_chip(mtd, chipnr);
2814 ret = nand_reset_op(chip);
2815 chip->select_chip(mtd, -1);
2820 * A nand_reset_data_interface() put both the NAND chip and the NAND
2821 * controller in timings mode 0. If the default mode for this chip is
2822 * also 0, no need to proceed to the change again. Plus, at probe time,
2823 * nand_setup_data_interface() uses ->set/get_features() which would
2824 * fail anyway as the parameter page is not available yet.
2826 if (!chip->onfi_timing_mode_default)
2829 chip->data_interface = saved_data_intf;
2830 ret = nand_setup_data_interface(chip, chipnr);
2836 EXPORT_SYMBOL_GPL(nand_reset);
2839 * nand_check_erased_buf - check if a buffer contains (almost) only 0xff data
2840 * @buf: buffer to test
2841 * @len: buffer length
2842 * @bitflips_threshold: maximum number of bitflips
2844 * Check if a buffer contains only 0xff, which means the underlying region
2845 * has been erased and is ready to be programmed.
2846 * The bitflips_threshold specify the maximum number of bitflips before
2847 * considering the region is not erased.
2848 * Note: The logic of this function has been extracted from the memweight
2849 * implementation, except that nand_check_erased_buf function exit before
2850 * testing the whole buffer if the number of bitflips exceed the
2851 * bitflips_threshold value.
2853 * Returns a positive number of bitflips less than or equal to
2854 * bitflips_threshold, or -ERROR_CODE for bitflips in excess of the
2857 static int nand_check_erased_buf(void *buf, int len, int bitflips_threshold)
2859 const unsigned char *bitmap = buf;
2863 for (; len && ((uintptr_t)bitmap) % sizeof(long);
2865 weight = hweight8(*bitmap);
2866 bitflips += BITS_PER_BYTE - weight;
2867 if (unlikely(bitflips > bitflips_threshold))
2871 for (; len >= sizeof(long);
2872 len -= sizeof(long), bitmap += sizeof(long)) {
2873 unsigned long d = *((unsigned long *)bitmap);
2876 weight = hweight_long(d);
2877 bitflips += BITS_PER_LONG - weight;
2878 if (unlikely(bitflips > bitflips_threshold))
2882 for (; len > 0; len--, bitmap++) {
2883 weight = hweight8(*bitmap);
2884 bitflips += BITS_PER_BYTE - weight;
2885 if (unlikely(bitflips > bitflips_threshold))
2893 * nand_check_erased_ecc_chunk - check if an ECC chunk contains (almost) only
2895 * @data: data buffer to test
2896 * @datalen: data length
2898 * @ecclen: ECC length
2899 * @extraoob: extra OOB buffer
2900 * @extraooblen: extra OOB length
2901 * @bitflips_threshold: maximum number of bitflips
2903 * Check if a data buffer and its associated ECC and OOB data contains only
2904 * 0xff pattern, which means the underlying region has been erased and is
2905 * ready to be programmed.
2906 * The bitflips_threshold specify the maximum number of bitflips before
2907 * considering the region as not erased.
2910 * 1/ ECC algorithms are working on pre-defined block sizes which are usually
2911 * different from the NAND page size. When fixing bitflips, ECC engines will
2912 * report the number of errors per chunk, and the NAND core infrastructure
2913 * expect you to return the maximum number of bitflips for the whole page.
2914 * This is why you should always use this function on a single chunk and
2915 * not on the whole page. After checking each chunk you should update your
2916 * max_bitflips value accordingly.
2917 * 2/ When checking for bitflips in erased pages you should not only check
2918 * the payload data but also their associated ECC data, because a user might
2919 * have programmed almost all bits to 1 but a few. In this case, we
2920 * shouldn't consider the chunk as erased, and checking ECC bytes prevent
2922 * 3/ The extraoob argument is optional, and should be used if some of your OOB
2923 * data are protected by the ECC engine.
2924 * It could also be used if you support subpages and want to attach some
2925 * extra OOB data to an ECC chunk.
2927 * Returns a positive number of bitflips less than or equal to
2928 * bitflips_threshold, or -ERROR_CODE for bitflips in excess of the
2929 * threshold. In case of success, the passed buffers are filled with 0xff.
2931 int nand_check_erased_ecc_chunk(void *data, int datalen,
2932 void *ecc, int ecclen,
2933 void *extraoob, int extraooblen,
2934 int bitflips_threshold)
2936 int data_bitflips = 0, ecc_bitflips = 0, extraoob_bitflips = 0;
2938 data_bitflips = nand_check_erased_buf(data, datalen,
2939 bitflips_threshold);
2940 if (data_bitflips < 0)
2941 return data_bitflips;
2943 bitflips_threshold -= data_bitflips;
2945 ecc_bitflips = nand_check_erased_buf(ecc, ecclen, bitflips_threshold);
2946 if (ecc_bitflips < 0)
2947 return ecc_bitflips;
2949 bitflips_threshold -= ecc_bitflips;
2951 extraoob_bitflips = nand_check_erased_buf(extraoob, extraooblen,
2952 bitflips_threshold);
2953 if (extraoob_bitflips < 0)
2954 return extraoob_bitflips;
2957 memset(data, 0xff, datalen);
2960 memset(ecc, 0xff, ecclen);
2962 if (extraoob_bitflips)
2963 memset(extraoob, 0xff, extraooblen);
2965 return data_bitflips + ecc_bitflips + extraoob_bitflips;
2967 EXPORT_SYMBOL(nand_check_erased_ecc_chunk);
2970 * nand_read_page_raw - [INTERN] read raw page data without ecc
2971 * @mtd: mtd info structure
2972 * @chip: nand chip info structure
2973 * @buf: buffer to store read data
2974 * @oob_required: caller requires OOB data read to chip->oob_poi
2975 * @page: page number to read
2977 * Not for syndrome calculating ECC controllers, which use a special oob layout.
2979 int nand_read_page_raw(struct mtd_info *mtd, struct nand_chip *chip,
2980 uint8_t *buf, int oob_required, int page)
2984 ret = nand_read_page_op(chip, page, 0, buf, mtd->writesize);
2989 ret = nand_read_data_op(chip, chip->oob_poi, mtd->oobsize,
2997 EXPORT_SYMBOL(nand_read_page_raw);
3000 * nand_read_page_raw_syndrome - [INTERN] read raw page data without ecc
3001 * @mtd: mtd info structure
3002 * @chip: nand chip info structure
3003 * @buf: buffer to store read data
3004 * @oob_required: caller requires OOB data read to chip->oob_poi
3005 * @page: page number to read
3007 * We need a special oob layout and handling even when OOB isn't used.
3009 static int nand_read_page_raw_syndrome(struct mtd_info *mtd,
3010 struct nand_chip *chip, uint8_t *buf,
3011 int oob_required, int page)
3013 int eccsize = chip->ecc.size;
3014 int eccbytes = chip->ecc.bytes;
3015 uint8_t *oob = chip->oob_poi;
3016 int steps, size, ret;
3018 ret = nand_read_page_op(chip, page, 0, NULL, 0);
3022 for (steps = chip->ecc.steps; steps > 0; steps--) {
3023 ret = nand_read_data_op(chip, buf, eccsize, false);
3029 if (chip->ecc.prepad) {
3030 ret = nand_read_data_op(chip, oob, chip->ecc.prepad,
3035 oob += chip->ecc.prepad;
3038 ret = nand_read_data_op(chip, oob, eccbytes, false);
3044 if (chip->ecc.postpad) {
3045 ret = nand_read_data_op(chip, oob, chip->ecc.postpad,
3050 oob += chip->ecc.postpad;
3054 size = mtd->oobsize - (oob - chip->oob_poi);
3056 ret = nand_read_data_op(chip, oob, size, false);
3065 * nand_read_page_swecc - [REPLACEABLE] software ECC based page read function
3066 * @mtd: mtd info structure
3067 * @chip: nand chip info structure
3068 * @buf: buffer to store read data
3069 * @oob_required: caller requires OOB data read to chip->oob_poi
3070 * @page: page number to read
3072 static int nand_read_page_swecc(struct mtd_info *mtd, struct nand_chip *chip,
3073 uint8_t *buf, int oob_required, int page)
3075 int i, eccsize = chip->ecc.size, ret;
3076 int eccbytes = chip->ecc.bytes;
3077 int eccsteps = chip->ecc.steps;
3079 uint8_t *ecc_calc = chip->ecc.calc_buf;
3080 uint8_t *ecc_code = chip->ecc.code_buf;
3081 unsigned int max_bitflips = 0;
3083 chip->ecc.read_page_raw(mtd, chip, buf, 1, page);
3085 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize)
3086 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
3088 ret = mtd_ooblayout_get_eccbytes(mtd, ecc_code, chip->oob_poi, 0,
3093 eccsteps = chip->ecc.steps;
3096 for (i = 0 ; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
3099 stat = chip->ecc.correct(mtd, p, &ecc_code[i], &ecc_calc[i]);
3101 mtd->ecc_stats.failed++;
3103 mtd->ecc_stats.corrected += stat;
3104 max_bitflips = max_t(unsigned int, max_bitflips, stat);
3107 return max_bitflips;
3111 * nand_read_subpage - [REPLACEABLE] ECC based sub-page read function
3112 * @mtd: mtd info structure
3113 * @chip: nand chip info structure
3114 * @data_offs: offset of requested data within the page
3115 * @readlen: data length
3116 * @bufpoi: buffer to store read data
3117 * @page: page number to read
3119 static int nand_read_subpage(struct mtd_info *mtd, struct nand_chip *chip,
3120 uint32_t data_offs, uint32_t readlen, uint8_t *bufpoi,
3123 int start_step, end_step, num_steps, ret;
3125 int data_col_addr, i, gaps = 0;
3126 int datafrag_len, eccfrag_len, aligned_len, aligned_pos;
3127 int busw = (chip->options & NAND_BUSWIDTH_16) ? 2 : 1;
3128 int index, section = 0;
3129 unsigned int max_bitflips = 0;
3130 struct mtd_oob_region oobregion = { };
3132 /* Column address within the page aligned to ECC size (256bytes) */
3133 start_step = data_offs / chip->ecc.size;
3134 end_step = (data_offs + readlen - 1) / chip->ecc.size;
3135 num_steps = end_step - start_step + 1;
3136 index = start_step * chip->ecc.bytes;
3138 /* Data size aligned to ECC ecc.size */
3139 datafrag_len = num_steps * chip->ecc.size;
3140 eccfrag_len = num_steps * chip->ecc.bytes;
3142 data_col_addr = start_step * chip->ecc.size;
3143 /* If we read not a page aligned data */
3144 p = bufpoi + data_col_addr;
3145 ret = nand_read_page_op(chip, page, data_col_addr, p, datafrag_len);
3150 for (i = 0; i < eccfrag_len ; i += chip->ecc.bytes, p += chip->ecc.size)
3151 chip->ecc.calculate(mtd, p, &chip->ecc.calc_buf[i]);
3154 * The performance is faster if we position offsets according to
3155 * ecc.pos. Let's make sure that there are no gaps in ECC positions.
3157 ret = mtd_ooblayout_find_eccregion(mtd, index, §ion, &oobregion);
3161 if (oobregion.length < eccfrag_len)
3165 ret = nand_change_read_column_op(chip, mtd->writesize,
3166 chip->oob_poi, mtd->oobsize,
3172 * Send the command to read the particular ECC bytes take care
3173 * about buswidth alignment in read_buf.
3175 aligned_pos = oobregion.offset & ~(busw - 1);
3176 aligned_len = eccfrag_len;
3177 if (oobregion.offset & (busw - 1))
3179 if ((oobregion.offset + (num_steps * chip->ecc.bytes)) &
3183 ret = nand_change_read_column_op(chip,
3184 mtd->writesize + aligned_pos,
3185 &chip->oob_poi[aligned_pos],
3186 aligned_len, false);
3191 ret = mtd_ooblayout_get_eccbytes(mtd, chip->ecc.code_buf,
3192 chip->oob_poi, index, eccfrag_len);
3196 p = bufpoi + data_col_addr;
3197 for (i = 0; i < eccfrag_len ; i += chip->ecc.bytes, p += chip->ecc.size) {
3200 stat = chip->ecc.correct(mtd, p, &chip->ecc.code_buf[i],
3201 &chip->ecc.calc_buf[i]);
3202 if (stat == -EBADMSG &&
3203 (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
3204 /* check for empty pages with bitflips */
3205 stat = nand_check_erased_ecc_chunk(p, chip->ecc.size,
3206 &chip->ecc.code_buf[i],
3209 chip->ecc.strength);
3213 mtd->ecc_stats.failed++;
3215 mtd->ecc_stats.corrected += stat;
3216 max_bitflips = max_t(unsigned int, max_bitflips, stat);
3219 return max_bitflips;
3223 * nand_read_page_hwecc - [REPLACEABLE] hardware ECC based page read function
3224 * @mtd: mtd info structure
3225 * @chip: nand chip info structure
3226 * @buf: buffer to store read data
3227 * @oob_required: caller requires OOB data read to chip->oob_poi
3228 * @page: page number to read
3230 * Not for syndrome calculating ECC controllers which need a special oob layout.
3232 static int nand_read_page_hwecc(struct mtd_info *mtd, struct nand_chip *chip,
3233 uint8_t *buf, int oob_required, int page)
3235 int i, eccsize = chip->ecc.size, ret;
3236 int eccbytes = chip->ecc.bytes;
3237 int eccsteps = chip->ecc.steps;
3239 uint8_t *ecc_calc = chip->ecc.calc_buf;
3240 uint8_t *ecc_code = chip->ecc.code_buf;
3241 unsigned int max_bitflips = 0;
3243 ret = nand_read_page_op(chip, page, 0, NULL, 0);
3247 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
3248 chip->ecc.hwctl(mtd, NAND_ECC_READ);
3250 ret = nand_read_data_op(chip, p, eccsize, false);
3254 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
3257 ret = nand_read_data_op(chip, chip->oob_poi, mtd->oobsize, false);
3261 ret = mtd_ooblayout_get_eccbytes(mtd, ecc_code, chip->oob_poi, 0,
3266 eccsteps = chip->ecc.steps;
3269 for (i = 0 ; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
3272 stat = chip->ecc.correct(mtd, p, &ecc_code[i], &ecc_calc[i]);
3273 if (stat == -EBADMSG &&
3274 (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
3275 /* check for empty pages with bitflips */
3276 stat = nand_check_erased_ecc_chunk(p, eccsize,
3277 &ecc_code[i], eccbytes,
3279 chip->ecc.strength);
3283 mtd->ecc_stats.failed++;
3285 mtd->ecc_stats.corrected += stat;
3286 max_bitflips = max_t(unsigned int, max_bitflips, stat);
3289 return max_bitflips;
3293 * nand_read_page_hwecc_oob_first - [REPLACEABLE] hw ecc, read oob first
3294 * @mtd: mtd info structure
3295 * @chip: nand chip info structure
3296 * @buf: buffer to store read data
3297 * @oob_required: caller requires OOB data read to chip->oob_poi
3298 * @page: page number to read
3300 * Hardware ECC for large page chips, require OOB to be read first. For this
3301 * ECC mode, the write_page method is re-used from ECC_HW. These methods
3302 * read/write ECC from the OOB area, unlike the ECC_HW_SYNDROME support with
3303 * multiple ECC steps, follows the "infix ECC" scheme and reads/writes ECC from
3304 * the data area, by overwriting the NAND manufacturer bad block markings.
3306 static int nand_read_page_hwecc_oob_first(struct mtd_info *mtd,
3307 struct nand_chip *chip, uint8_t *buf, int oob_required, int page)
3309 int i, eccsize = chip->ecc.size, ret;
3310 int eccbytes = chip->ecc.bytes;
3311 int eccsteps = chip->ecc.steps;
3313 uint8_t *ecc_code = chip->ecc.code_buf;
3314 uint8_t *ecc_calc = chip->ecc.calc_buf;
3315 unsigned int max_bitflips = 0;
3317 /* Read the OOB area first */
3318 ret = nand_read_oob_op(chip, page, 0, chip->oob_poi, mtd->oobsize);
3322 ret = nand_read_page_op(chip, page, 0, NULL, 0);
3326 ret = mtd_ooblayout_get_eccbytes(mtd, ecc_code, chip->oob_poi, 0,
3331 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
3334 chip->ecc.hwctl(mtd, NAND_ECC_READ);
3336 ret = nand_read_data_op(chip, p, eccsize, false);
3340 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
3342 stat = chip->ecc.correct(mtd, p, &ecc_code[i], NULL);
3343 if (stat == -EBADMSG &&
3344 (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
3345 /* check for empty pages with bitflips */
3346 stat = nand_check_erased_ecc_chunk(p, eccsize,
3347 &ecc_code[i], eccbytes,
3349 chip->ecc.strength);
3353 mtd->ecc_stats.failed++;
3355 mtd->ecc_stats.corrected += stat;
3356 max_bitflips = max_t(unsigned int, max_bitflips, stat);
3359 return max_bitflips;
3363 * nand_read_page_syndrome - [REPLACEABLE] hardware ECC syndrome based page read
3364 * @mtd: mtd info structure
3365 * @chip: nand chip info structure
3366 * @buf: buffer to store read data
3367 * @oob_required: caller requires OOB data read to chip->oob_poi
3368 * @page: page number to read
3370 * The hw generator calculates the error syndrome automatically. Therefore we
3371 * need a special oob layout and handling.
3373 static int nand_read_page_syndrome(struct mtd_info *mtd, struct nand_chip *chip,
3374 uint8_t *buf, int oob_required, int page)
3376 int ret, i, eccsize = chip->ecc.size;
3377 int eccbytes = chip->ecc.bytes;
3378 int eccsteps = chip->ecc.steps;
3379 int eccpadbytes = eccbytes + chip->ecc.prepad + chip->ecc.postpad;
3381 uint8_t *oob = chip->oob_poi;
3382 unsigned int max_bitflips = 0;
3384 ret = nand_read_page_op(chip, page, 0, NULL, 0);
3388 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
3391 chip->ecc.hwctl(mtd, NAND_ECC_READ);
3393 ret = nand_read_data_op(chip, p, eccsize, false);
3397 if (chip->ecc.prepad) {
3398 ret = nand_read_data_op(chip, oob, chip->ecc.prepad,
3403 oob += chip->ecc.prepad;
3406 chip->ecc.hwctl(mtd, NAND_ECC_READSYN);
3408 ret = nand_read_data_op(chip, oob, eccbytes, false);
3412 stat = chip->ecc.correct(mtd, p, oob, NULL);
3416 if (chip->ecc.postpad) {
3417 ret = nand_read_data_op(chip, oob, chip->ecc.postpad,
3422 oob += chip->ecc.postpad;
3425 if (stat == -EBADMSG &&
3426 (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
3427 /* check for empty pages with bitflips */
3428 stat = nand_check_erased_ecc_chunk(p, chip->ecc.size,
3432 chip->ecc.strength);
3436 mtd->ecc_stats.failed++;
3438 mtd->ecc_stats.corrected += stat;
3439 max_bitflips = max_t(unsigned int, max_bitflips, stat);
3443 /* Calculate remaining oob bytes */
3444 i = mtd->oobsize - (oob - chip->oob_poi);
3446 ret = nand_read_data_op(chip, oob, i, false);
3451 return max_bitflips;
3455 * nand_transfer_oob - [INTERN] Transfer oob to client buffer
3456 * @mtd: mtd info structure
3457 * @oob: oob destination address
3458 * @ops: oob ops structure
3459 * @len: size of oob to transfer
3461 static uint8_t *nand_transfer_oob(struct mtd_info *mtd, uint8_t *oob,
3462 struct mtd_oob_ops *ops, size_t len)
3464 struct nand_chip *chip = mtd_to_nand(mtd);
3467 switch (ops->mode) {
3469 case MTD_OPS_PLACE_OOB:
3471 memcpy(oob, chip->oob_poi + ops->ooboffs, len);
3474 case MTD_OPS_AUTO_OOB:
3475 ret = mtd_ooblayout_get_databytes(mtd, oob, chip->oob_poi,
3487 * nand_setup_read_retry - [INTERN] Set the READ RETRY mode
3488 * @mtd: MTD device structure
3489 * @retry_mode: the retry mode to use
3491 * Some vendors supply a special command to shift the Vt threshold, to be used
3492 * when there are too many bitflips in a page (i.e., ECC error). After setting
3493 * a new threshold, the host should retry reading the page.
3495 static int nand_setup_read_retry(struct mtd_info *mtd, int retry_mode)
3497 struct nand_chip *chip = mtd_to_nand(mtd);
3499 pr_debug("setting READ RETRY mode %d\n", retry_mode);
3501 if (retry_mode >= chip->read_retries)
3504 if (!chip->setup_read_retry)
3507 return chip->setup_read_retry(mtd, retry_mode);
3511 * nand_do_read_ops - [INTERN] Read data with ECC
3512 * @mtd: MTD device structure
3513 * @from: offset to read from
3514 * @ops: oob ops structure
3516 * Internal function. Called with chip held.
3518 static int nand_do_read_ops(struct mtd_info *mtd, loff_t from,
3519 struct mtd_oob_ops *ops)
3521 int chipnr, page, realpage, col, bytes, aligned, oob_required;
3522 struct nand_chip *chip = mtd_to_nand(mtd);
3524 uint32_t readlen = ops->len;
3525 uint32_t oobreadlen = ops->ooblen;
3526 uint32_t max_oobsize = mtd_oobavail(mtd, ops);
3528 uint8_t *bufpoi, *oob, *buf;
3530 unsigned int max_bitflips = 0;
3532 bool ecc_fail = false;
3534 chipnr = (int)(from >> chip->chip_shift);
3535 chip->select_chip(mtd, chipnr);
3537 realpage = (int)(from >> chip->page_shift);
3538 page = realpage & chip->pagemask;
3540 col = (int)(from & (mtd->writesize - 1));
3544 oob_required = oob ? 1 : 0;
3547 unsigned int ecc_failures = mtd->ecc_stats.failed;
3549 bytes = min(mtd->writesize - col, readlen);
3550 aligned = (bytes == mtd->writesize);
3554 else if (chip->options & NAND_USE_BOUNCE_BUFFER)
3555 use_bufpoi = !virt_addr_valid(buf) ||
3556 !IS_ALIGNED((unsigned long)buf,
3561 /* Is the current page in the buffer? */
3562 if (realpage != chip->pagebuf || oob) {
3563 bufpoi = use_bufpoi ? chip->data_buf : buf;
3565 if (use_bufpoi && aligned)
3566 pr_debug("%s: using read bounce buffer for buf@%p\n",
3571 * Now read the page into the buffer. Absent an error,
3572 * the read methods return max bitflips per ecc step.
3574 if (unlikely(ops->mode == MTD_OPS_RAW))
3575 ret = chip->ecc.read_page_raw(mtd, chip, bufpoi,
3578 else if (!aligned && NAND_HAS_SUBPAGE_READ(chip) &&
3580 ret = chip->ecc.read_subpage(mtd, chip,
3584 ret = chip->ecc.read_page(mtd, chip, bufpoi,
3585 oob_required, page);
3588 /* Invalidate page cache */
3593 /* Transfer not aligned data */
3595 if (!NAND_HAS_SUBPAGE_READ(chip) && !oob &&
3596 !(mtd->ecc_stats.failed - ecc_failures) &&
3597 (ops->mode != MTD_OPS_RAW)) {
3598 chip->pagebuf = realpage;
3599 chip->pagebuf_bitflips = ret;
3601 /* Invalidate page cache */
3604 memcpy(buf, chip->data_buf + col, bytes);
3607 if (unlikely(oob)) {
3608 int toread = min(oobreadlen, max_oobsize);
3611 oob = nand_transfer_oob(mtd,
3613 oobreadlen -= toread;
3617 if (chip->options & NAND_NEED_READRDY) {
3618 /* Apply delay or wait for ready/busy pin */
3619 if (!chip->dev_ready)
3620 udelay(chip->chip_delay);
3622 nand_wait_ready(mtd);
3625 if (mtd->ecc_stats.failed - ecc_failures) {
3626 if (retry_mode + 1 < chip->read_retries) {
3628 ret = nand_setup_read_retry(mtd,
3633 /* Reset failures; retry */
3634 mtd->ecc_stats.failed = ecc_failures;
3637 /* No more retry modes; real failure */
3643 max_bitflips = max_t(unsigned int, max_bitflips, ret);
3645 memcpy(buf, chip->data_buf + col, bytes);
3647 max_bitflips = max_t(unsigned int, max_bitflips,
3648 chip->pagebuf_bitflips);
3653 /* Reset to retry mode 0 */
3655 ret = nand_setup_read_retry(mtd, 0);
3664 /* For subsequent reads align to page boundary */
3666 /* Increment page address */
3669 page = realpage & chip->pagemask;
3670 /* Check, if we cross a chip boundary */
3673 chip->select_chip(mtd, -1);
3674 chip->select_chip(mtd, chipnr);
3677 chip->select_chip(mtd, -1);
3679 ops->retlen = ops->len - (size_t) readlen;
3681 ops->oobretlen = ops->ooblen - oobreadlen;
3689 return max_bitflips;
3693 * nand_read_oob_std - [REPLACEABLE] the most common OOB data read function
3694 * @mtd: mtd info structure
3695 * @chip: nand chip info structure
3696 * @page: page number to read
3698 int nand_read_oob_std(struct mtd_info *mtd, struct nand_chip *chip, int page)
3700 return nand_read_oob_op(chip, page, 0, chip->oob_poi, mtd->oobsize);
3702 EXPORT_SYMBOL(nand_read_oob_std);
3705 * nand_read_oob_syndrome - [REPLACEABLE] OOB data read function for HW ECC
3707 * @mtd: mtd info structure
3708 * @chip: nand chip info structure
3709 * @page: page number to read
3711 int nand_read_oob_syndrome(struct mtd_info *mtd, struct nand_chip *chip,
3714 int length = mtd->oobsize;
3715 int chunk = chip->ecc.bytes + chip->ecc.prepad + chip->ecc.postpad;
3716 int eccsize = chip->ecc.size;
3717 uint8_t *bufpoi = chip->oob_poi;
3718 int i, toread, sndrnd = 0, pos, ret;
3720 ret = nand_read_page_op(chip, page, chip->ecc.size, NULL, 0);
3724 for (i = 0; i < chip->ecc.steps; i++) {
3728 pos = eccsize + i * (eccsize + chunk);
3729 if (mtd->writesize > 512)
3730 ret = nand_change_read_column_op(chip, pos,
3734 ret = nand_read_page_op(chip, page, pos, NULL,
3741 toread = min_t(int, length, chunk);
3743 ret = nand_read_data_op(chip, bufpoi, toread, false);
3751 ret = nand_read_data_op(chip, bufpoi, length, false);
3758 EXPORT_SYMBOL(nand_read_oob_syndrome);
3761 * nand_write_oob_std - [REPLACEABLE] the most common OOB data write function
3762 * @mtd: mtd info structure
3763 * @chip: nand chip info structure
3764 * @page: page number to write
3766 int nand_write_oob_std(struct mtd_info *mtd, struct nand_chip *chip, int page)
3768 return nand_prog_page_op(chip, page, mtd->writesize, chip->oob_poi,
3771 EXPORT_SYMBOL(nand_write_oob_std);
3774 * nand_write_oob_syndrome - [REPLACEABLE] OOB data write function for HW ECC
3775 * with syndrome - only for large page flash
3776 * @mtd: mtd info structure
3777 * @chip: nand chip info structure
3778 * @page: page number to write
3780 int nand_write_oob_syndrome(struct mtd_info *mtd, struct nand_chip *chip,
3783 int chunk = chip->ecc.bytes + chip->ecc.prepad + chip->ecc.postpad;
3784 int eccsize = chip->ecc.size, length = mtd->oobsize;
3785 int ret, i, len, pos, sndcmd = 0, steps = chip->ecc.steps;
3786 const uint8_t *bufpoi = chip->oob_poi;
3789 * data-ecc-data-ecc ... ecc-oob
3791 * data-pad-ecc-pad-data-pad .... ecc-pad-oob
3793 if (!chip->ecc.prepad && !chip->ecc.postpad) {
3794 pos = steps * (eccsize + chunk);
3799 ret = nand_prog_page_begin_op(chip, page, pos, NULL, 0);
3803 for (i = 0; i < steps; i++) {
3805 if (mtd->writesize <= 512) {
3806 uint32_t fill = 0xFFFFFFFF;
3810 int num = min_t(int, len, 4);
3812 ret = nand_write_data_op(chip, &fill,
3820 pos = eccsize + i * (eccsize + chunk);
3821 ret = nand_change_write_column_op(chip, pos,
3829 len = min_t(int, length, chunk);
3831 ret = nand_write_data_op(chip, bufpoi, len, false);
3839 ret = nand_write_data_op(chip, bufpoi, length, false);
3844 return nand_prog_page_end_op(chip);
3846 EXPORT_SYMBOL(nand_write_oob_syndrome);
3849 * nand_do_read_oob - [INTERN] NAND read out-of-band
3850 * @mtd: MTD device structure
3851 * @from: offset to read from
3852 * @ops: oob operations description structure
3854 * NAND read out-of-band data from the spare area.
3856 static int nand_do_read_oob(struct mtd_info *mtd, loff_t from,
3857 struct mtd_oob_ops *ops)
3859 unsigned int max_bitflips = 0;
3860 int page, realpage, chipnr;
3861 struct nand_chip *chip = mtd_to_nand(mtd);
3862 struct mtd_ecc_stats stats;
3863 int readlen = ops->ooblen;
3865 uint8_t *buf = ops->oobbuf;
3868 pr_debug("%s: from = 0x%08Lx, len = %i\n",
3869 __func__, (unsigned long long)from, readlen);
3871 stats = mtd->ecc_stats;
3873 len = mtd_oobavail(mtd, ops);
3875 chipnr = (int)(from >> chip->chip_shift);
3876 chip->select_chip(mtd, chipnr);
3878 /* Shift to get page */
3879 realpage = (int)(from >> chip->page_shift);
3880 page = realpage & chip->pagemask;
3883 if (ops->mode == MTD_OPS_RAW)
3884 ret = chip->ecc.read_oob_raw(mtd, chip, page);
3886 ret = chip->ecc.read_oob(mtd, chip, page);
3891 len = min(len, readlen);
3892 buf = nand_transfer_oob(mtd, buf, ops, len);
3894 if (chip->options & NAND_NEED_READRDY) {
3895 /* Apply delay or wait for ready/busy pin */
3896 if (!chip->dev_ready)
3897 udelay(chip->chip_delay);
3899 nand_wait_ready(mtd);
3902 max_bitflips = max_t(unsigned int, max_bitflips, ret);
3908 /* Increment page address */
3911 page = realpage & chip->pagemask;
3912 /* Check, if we cross a chip boundary */
3915 chip->select_chip(mtd, -1);
3916 chip->select_chip(mtd, chipnr);
3919 chip->select_chip(mtd, -1);
3921 ops->oobretlen = ops->ooblen - readlen;
3926 if (mtd->ecc_stats.failed - stats.failed)
3929 return max_bitflips;
3933 * nand_read_oob - [MTD Interface] NAND read data and/or out-of-band
3934 * @mtd: MTD device structure
3935 * @from: offset to read from
3936 * @ops: oob operation description structure
3938 * NAND read data and/or out-of-band data.
3940 static int nand_read_oob(struct mtd_info *mtd, loff_t from,
3941 struct mtd_oob_ops *ops)
3947 if (ops->mode != MTD_OPS_PLACE_OOB &&
3948 ops->mode != MTD_OPS_AUTO_OOB &&
3949 ops->mode != MTD_OPS_RAW)
3952 nand_get_device(mtd, FL_READING);
3955 ret = nand_do_read_oob(mtd, from, ops);
3957 ret = nand_do_read_ops(mtd, from, ops);
3959 nand_release_device(mtd);
3965 * nand_write_page_raw - [INTERN] raw page write function
3966 * @mtd: mtd info structure
3967 * @chip: nand chip info structure
3969 * @oob_required: must write chip->oob_poi to OOB
3970 * @page: page number to write
3972 * Not for syndrome calculating ECC controllers, which use a special oob layout.
3974 int nand_write_page_raw(struct mtd_info *mtd, struct nand_chip *chip,
3975 const uint8_t *buf, int oob_required, int page)
3979 ret = nand_prog_page_begin_op(chip, page, 0, buf, mtd->writesize);
3984 ret = nand_write_data_op(chip, chip->oob_poi, mtd->oobsize,
3990 return nand_prog_page_end_op(chip);
3992 EXPORT_SYMBOL(nand_write_page_raw);
3995 * nand_write_page_raw_syndrome - [INTERN] raw page write function
3996 * @mtd: mtd info structure
3997 * @chip: nand chip info structure
3999 * @oob_required: must write chip->oob_poi to OOB
4000 * @page: page number to write
4002 * We need a special oob layout and handling even when ECC isn't checked.
4004 static int nand_write_page_raw_syndrome(struct mtd_info *mtd,
4005 struct nand_chip *chip,
4006 const uint8_t *buf, int oob_required,
4009 int eccsize = chip->ecc.size;
4010 int eccbytes = chip->ecc.bytes;
4011 uint8_t *oob = chip->oob_poi;
4012 int steps, size, ret;
4014 ret = nand_prog_page_begin_op(chip, page, 0, NULL, 0);
4018 for (steps = chip->ecc.steps; steps > 0; steps--) {
4019 ret = nand_write_data_op(chip, buf, eccsize, false);
4025 if (chip->ecc.prepad) {
4026 ret = nand_write_data_op(chip, oob, chip->ecc.prepad,
4031 oob += chip->ecc.prepad;
4034 ret = nand_write_data_op(chip, oob, eccbytes, false);
4040 if (chip->ecc.postpad) {
4041 ret = nand_write_data_op(chip, oob, chip->ecc.postpad,
4046 oob += chip->ecc.postpad;
4050 size = mtd->oobsize - (oob - chip->oob_poi);
4052 ret = nand_write_data_op(chip, oob, size, false);
4057 return nand_prog_page_end_op(chip);
4060 * nand_write_page_swecc - [REPLACEABLE] software ECC based page write function
4061 * @mtd: mtd info structure
4062 * @chip: nand chip info structure
4064 * @oob_required: must write chip->oob_poi to OOB
4065 * @page: page number to write
4067 static int nand_write_page_swecc(struct mtd_info *mtd, struct nand_chip *chip,
4068 const uint8_t *buf, int oob_required,
4071 int i, eccsize = chip->ecc.size, ret;
4072 int eccbytes = chip->ecc.bytes;
4073 int eccsteps = chip->ecc.steps;
4074 uint8_t *ecc_calc = chip->ecc.calc_buf;
4075 const uint8_t *p = buf;
4077 /* Software ECC calculation */
4078 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize)
4079 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
4081 ret = mtd_ooblayout_set_eccbytes(mtd, ecc_calc, chip->oob_poi, 0,
4086 return chip->ecc.write_page_raw(mtd, chip, buf, 1, page);
4090 * nand_write_page_hwecc - [REPLACEABLE] hardware ECC based page write function
4091 * @mtd: mtd info structure
4092 * @chip: nand chip info structure
4094 * @oob_required: must write chip->oob_poi to OOB
4095 * @page: page number to write
4097 static int nand_write_page_hwecc(struct mtd_info *mtd, struct nand_chip *chip,
4098 const uint8_t *buf, int oob_required,
4101 int i, eccsize = chip->ecc.size, ret;
4102 int eccbytes = chip->ecc.bytes;
4103 int eccsteps = chip->ecc.steps;
4104 uint8_t *ecc_calc = chip->ecc.calc_buf;
4105 const uint8_t *p = buf;
4107 ret = nand_prog_page_begin_op(chip, page, 0, NULL, 0);
4111 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
4112 chip->ecc.hwctl(mtd, NAND_ECC_WRITE);
4114 ret = nand_write_data_op(chip, p, eccsize, false);
4118 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
4121 ret = mtd_ooblayout_set_eccbytes(mtd, ecc_calc, chip->oob_poi, 0,
4126 ret = nand_write_data_op(chip, chip->oob_poi, mtd->oobsize, false);
4130 return nand_prog_page_end_op(chip);
4135 * nand_write_subpage_hwecc - [REPLACEABLE] hardware ECC based subpage write
4136 * @mtd: mtd info structure
4137 * @chip: nand chip info structure
4138 * @offset: column address of subpage within the page
4139 * @data_len: data length
4141 * @oob_required: must write chip->oob_poi to OOB
4142 * @page: page number to write
4144 static int nand_write_subpage_hwecc(struct mtd_info *mtd,
4145 struct nand_chip *chip, uint32_t offset,
4146 uint32_t data_len, const uint8_t *buf,
4147 int oob_required, int page)
4149 uint8_t *oob_buf = chip->oob_poi;
4150 uint8_t *ecc_calc = chip->ecc.calc_buf;
4151 int ecc_size = chip->ecc.size;
4152 int ecc_bytes = chip->ecc.bytes;
4153 int ecc_steps = chip->ecc.steps;
4154 uint32_t start_step = offset / ecc_size;
4155 uint32_t end_step = (offset + data_len - 1) / ecc_size;
4156 int oob_bytes = mtd->oobsize / ecc_steps;
4159 ret = nand_prog_page_begin_op(chip, page, 0, NULL, 0);
4163 for (step = 0; step < ecc_steps; step++) {
4164 /* configure controller for WRITE access */
4165 chip->ecc.hwctl(mtd, NAND_ECC_WRITE);
4167 /* write data (untouched subpages already masked by 0xFF) */
4168 ret = nand_write_data_op(chip, buf, ecc_size, false);
4172 /* mask ECC of un-touched subpages by padding 0xFF */
4173 if ((step < start_step) || (step > end_step))
4174 memset(ecc_calc, 0xff, ecc_bytes);
4176 chip->ecc.calculate(mtd, buf, ecc_calc);
4178 /* mask OOB of un-touched subpages by padding 0xFF */
4179 /* if oob_required, preserve OOB metadata of written subpage */
4180 if (!oob_required || (step < start_step) || (step > end_step))
4181 memset(oob_buf, 0xff, oob_bytes);
4184 ecc_calc += ecc_bytes;
4185 oob_buf += oob_bytes;
4188 /* copy calculated ECC for whole page to chip->buffer->oob */
4189 /* this include masked-value(0xFF) for unwritten subpages */
4190 ecc_calc = chip->ecc.calc_buf;
4191 ret = mtd_ooblayout_set_eccbytes(mtd, ecc_calc, chip->oob_poi, 0,
4196 /* write OOB buffer to NAND device */
4197 ret = nand_write_data_op(chip, chip->oob_poi, mtd->oobsize, false);
4201 return nand_prog_page_end_op(chip);
4206 * nand_write_page_syndrome - [REPLACEABLE] hardware ECC syndrome based page write
4207 * @mtd: mtd info structure
4208 * @chip: nand chip info structure
4210 * @oob_required: must write chip->oob_poi to OOB
4211 * @page: page number to write
4213 * The hw generator calculates the error syndrome automatically. Therefore we
4214 * need a special oob layout and handling.
4216 static int nand_write_page_syndrome(struct mtd_info *mtd,
4217 struct nand_chip *chip,
4218 const uint8_t *buf, int oob_required,
4221 int i, eccsize = chip->ecc.size;
4222 int eccbytes = chip->ecc.bytes;
4223 int eccsteps = chip->ecc.steps;
4224 const uint8_t *p = buf;
4225 uint8_t *oob = chip->oob_poi;
4228 ret = nand_prog_page_begin_op(chip, page, 0, NULL, 0);
4232 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
4233 chip->ecc.hwctl(mtd, NAND_ECC_WRITE);
4235 ret = nand_write_data_op(chip, p, eccsize, false);
4239 if (chip->ecc.prepad) {
4240 ret = nand_write_data_op(chip, oob, chip->ecc.prepad,
4245 oob += chip->ecc.prepad;
4248 chip->ecc.calculate(mtd, p, oob);
4250 ret = nand_write_data_op(chip, oob, eccbytes, false);
4256 if (chip->ecc.postpad) {
4257 ret = nand_write_data_op(chip, oob, chip->ecc.postpad,
4262 oob += chip->ecc.postpad;
4266 /* Calculate remaining oob bytes */
4267 i = mtd->oobsize - (oob - chip->oob_poi);
4269 ret = nand_write_data_op(chip, oob, i, false);
4274 return nand_prog_page_end_op(chip);
4278 * nand_write_page - write one page
4279 * @mtd: MTD device structure
4280 * @chip: NAND chip descriptor
4281 * @offset: address offset within the page
4282 * @data_len: length of actual data to be written
4283 * @buf: the data to write
4284 * @oob_required: must write chip->oob_poi to OOB
4285 * @page: page number to write
4286 * @raw: use _raw version of write_page
4288 static int nand_write_page(struct mtd_info *mtd, struct nand_chip *chip,
4289 uint32_t offset, int data_len, const uint8_t *buf,
4290 int oob_required, int page, int raw)
4292 int status, subpage;
4294 if (!(chip->options & NAND_NO_SUBPAGE_WRITE) &&
4295 chip->ecc.write_subpage)
4296 subpage = offset || (data_len < mtd->writesize);
4301 status = chip->ecc.write_page_raw(mtd, chip, buf,
4302 oob_required, page);
4304 status = chip->ecc.write_subpage(mtd, chip, offset, data_len,
4305 buf, oob_required, page);
4307 status = chip->ecc.write_page(mtd, chip, buf, oob_required,
4317 * nand_fill_oob - [INTERN] Transfer client buffer to oob
4318 * @mtd: MTD device structure
4319 * @oob: oob data buffer
4320 * @len: oob data write length
4321 * @ops: oob ops structure
4323 static uint8_t *nand_fill_oob(struct mtd_info *mtd, uint8_t *oob, size_t len,
4324 struct mtd_oob_ops *ops)
4326 struct nand_chip *chip = mtd_to_nand(mtd);
4330 * Initialise to all 0xFF, to avoid the possibility of left over OOB
4331 * data from a previous OOB read.
4333 memset(chip->oob_poi, 0xff, mtd->oobsize);
4335 switch (ops->mode) {
4337 case MTD_OPS_PLACE_OOB:
4339 memcpy(chip->oob_poi + ops->ooboffs, oob, len);
4342 case MTD_OPS_AUTO_OOB:
4343 ret = mtd_ooblayout_set_databytes(mtd, oob, chip->oob_poi,
4354 #define NOTALIGNED(x) ((x & (chip->subpagesize - 1)) != 0)
4357 * nand_do_write_ops - [INTERN] NAND write with ECC
4358 * @mtd: MTD device structure
4359 * @to: offset to write to
4360 * @ops: oob operations description structure
4362 * NAND write with ECC.
4364 static int nand_do_write_ops(struct mtd_info *mtd, loff_t to,
4365 struct mtd_oob_ops *ops)
4367 int chipnr, realpage, page, column;
4368 struct nand_chip *chip = mtd_to_nand(mtd);
4369 uint32_t writelen = ops->len;
4371 uint32_t oobwritelen = ops->ooblen;
4372 uint32_t oobmaxlen = mtd_oobavail(mtd, ops);
4374 uint8_t *oob = ops->oobbuf;
4375 uint8_t *buf = ops->datbuf;
4377 int oob_required = oob ? 1 : 0;
4383 /* Reject writes, which are not page aligned */
4384 if (NOTALIGNED(to) || NOTALIGNED(ops->len)) {
4385 pr_notice("%s: attempt to write non page aligned data\n",
4390 column = to & (mtd->writesize - 1);
4392 chipnr = (int)(to >> chip->chip_shift);
4393 chip->select_chip(mtd, chipnr);
4395 /* Check, if it is write protected */
4396 if (nand_check_wp(mtd)) {
4401 realpage = (int)(to >> chip->page_shift);
4402 page = realpage & chip->pagemask;
4404 /* Invalidate the page cache, when we write to the cached page */
4405 if (to <= ((loff_t)chip->pagebuf << chip->page_shift) &&
4406 ((loff_t)chip->pagebuf << chip->page_shift) < (to + ops->len))
4409 /* Don't allow multipage oob writes with offset */
4410 if (oob && ops->ooboffs && (ops->ooboffs + ops->ooblen > oobmaxlen)) {
4416 int bytes = mtd->writesize;
4417 uint8_t *wbuf = buf;
4419 int part_pagewr = (column || writelen < mtd->writesize);
4423 else if (chip->options & NAND_USE_BOUNCE_BUFFER)
4424 use_bufpoi = !virt_addr_valid(buf) ||
4425 !IS_ALIGNED((unsigned long)buf,
4430 /* Partial page write?, or need to use bounce buffer */
4432 pr_debug("%s: using write bounce buffer for buf@%p\n",
4435 bytes = min_t(int, bytes - column, writelen);
4437 memset(chip->data_buf, 0xff, mtd->writesize);
4438 memcpy(&chip->data_buf[column], buf, bytes);
4439 wbuf = chip->data_buf;
4442 if (unlikely(oob)) {
4443 size_t len = min(oobwritelen, oobmaxlen);
4444 oob = nand_fill_oob(mtd, oob, len, ops);
4447 /* We still need to erase leftover OOB data */
4448 memset(chip->oob_poi, 0xff, mtd->oobsize);
4451 ret = nand_write_page(mtd, chip, column, bytes, wbuf,
4453 (ops->mode == MTD_OPS_RAW));
4465 page = realpage & chip->pagemask;
4466 /* Check, if we cross a chip boundary */
4469 chip->select_chip(mtd, -1);
4470 chip->select_chip(mtd, chipnr);
4474 ops->retlen = ops->len - writelen;
4476 ops->oobretlen = ops->ooblen;
4479 chip->select_chip(mtd, -1);
4484 * panic_nand_write - [MTD Interface] NAND write with ECC
4485 * @mtd: MTD device structure
4486 * @to: offset to write to
4487 * @len: number of bytes to write
4488 * @retlen: pointer to variable to store the number of written bytes
4489 * @buf: the data to write
4491 * NAND write with ECC. Used when performing writes in interrupt context, this
4492 * may for example be called by mtdoops when writing an oops while in panic.
4494 static int panic_nand_write(struct mtd_info *mtd, loff_t to, size_t len,
4495 size_t *retlen, const uint8_t *buf)
4497 struct nand_chip *chip = mtd_to_nand(mtd);
4498 int chipnr = (int)(to >> chip->chip_shift);
4499 struct mtd_oob_ops ops;
4502 /* Grab the device */
4503 panic_nand_get_device(chip, mtd, FL_WRITING);
4505 chip->select_chip(mtd, chipnr);
4507 /* Wait for the device to get ready */
4508 panic_nand_wait(mtd, chip, 400);
4510 memset(&ops, 0, sizeof(ops));
4512 ops.datbuf = (uint8_t *)buf;
4513 ops.mode = MTD_OPS_PLACE_OOB;
4515 ret = nand_do_write_ops(mtd, to, &ops);
4517 *retlen = ops.retlen;
4522 * nand_do_write_oob - [MTD Interface] NAND write out-of-band
4523 * @mtd: MTD device structure
4524 * @to: offset to write to
4525 * @ops: oob operation description structure
4527 * NAND write out-of-band.
4529 static int nand_do_write_oob(struct mtd_info *mtd, loff_t to,
4530 struct mtd_oob_ops *ops)
4532 int chipnr, page, status, len;
4533 struct nand_chip *chip = mtd_to_nand(mtd);
4535 pr_debug("%s: to = 0x%08x, len = %i\n",
4536 __func__, (unsigned int)to, (int)ops->ooblen);
4538 len = mtd_oobavail(mtd, ops);
4540 /* Do not allow write past end of page */
4541 if ((ops->ooboffs + ops->ooblen) > len) {
4542 pr_debug("%s: attempt to write past end of page\n",
4547 chipnr = (int)(to >> chip->chip_shift);
4550 * Reset the chip. Some chips (like the Toshiba TC5832DC found in one
4551 * of my DiskOnChip 2000 test units) will clear the whole data page too
4552 * if we don't do this. I have no clue why, but I seem to have 'fixed'
4553 * it in the doc2000 driver in August 1999. dwmw2.
4555 nand_reset(chip, chipnr);
4557 chip->select_chip(mtd, chipnr);
4559 /* Shift to get page */
4560 page = (int)(to >> chip->page_shift);
4562 /* Check, if it is write protected */
4563 if (nand_check_wp(mtd)) {
4564 chip->select_chip(mtd, -1);
4568 /* Invalidate the page cache, if we write to the cached page */
4569 if (page == chip->pagebuf)
4572 nand_fill_oob(mtd, ops->oobbuf, ops->ooblen, ops);
4574 if (ops->mode == MTD_OPS_RAW)
4575 status = chip->ecc.write_oob_raw(mtd, chip, page & chip->pagemask);
4577 status = chip->ecc.write_oob(mtd, chip, page & chip->pagemask);
4579 chip->select_chip(mtd, -1);
4584 ops->oobretlen = ops->ooblen;
4590 * nand_write_oob - [MTD Interface] NAND write data and/or out-of-band
4591 * @mtd: MTD device structure
4592 * @to: offset to write to
4593 * @ops: oob operation description structure
4595 static int nand_write_oob(struct mtd_info *mtd, loff_t to,
4596 struct mtd_oob_ops *ops)
4598 int ret = -ENOTSUPP;
4602 nand_get_device(mtd, FL_WRITING);
4604 switch (ops->mode) {
4605 case MTD_OPS_PLACE_OOB:
4606 case MTD_OPS_AUTO_OOB:
4615 ret = nand_do_write_oob(mtd, to, ops);
4617 ret = nand_do_write_ops(mtd, to, ops);
4620 nand_release_device(mtd);
4625 * single_erase - [GENERIC] NAND standard block erase command function
4626 * @mtd: MTD device structure
4627 * @page: the page address of the block which will be erased
4629 * Standard erase command for NAND chips. Returns NAND status.
4631 static int single_erase(struct mtd_info *mtd, int page)
4633 struct nand_chip *chip = mtd_to_nand(mtd);
4634 unsigned int eraseblock;
4636 /* Send commands to erase a block */
4637 eraseblock = page >> (chip->phys_erase_shift - chip->page_shift);
4639 return nand_erase_op(chip, eraseblock);
4643 * nand_erase - [MTD Interface] erase block(s)
4644 * @mtd: MTD device structure
4645 * @instr: erase instruction
4647 * Erase one ore more blocks.
4649 static int nand_erase(struct mtd_info *mtd, struct erase_info *instr)
4651 return nand_erase_nand(mtd, instr, 0);
4655 * nand_erase_nand - [INTERN] erase block(s)
4656 * @mtd: MTD device structure
4657 * @instr: erase instruction
4658 * @allowbbt: allow erasing the bbt area
4660 * Erase one ore more blocks.
4662 int nand_erase_nand(struct mtd_info *mtd, struct erase_info *instr,
4665 int page, status, pages_per_block, ret, chipnr;
4666 struct nand_chip *chip = mtd_to_nand(mtd);
4669 pr_debug("%s: start = 0x%012llx, len = %llu\n",
4670 __func__, (unsigned long long)instr->addr,
4671 (unsigned long long)instr->len);
4673 if (check_offs_len(mtd, instr->addr, instr->len))
4676 /* Grab the lock and see if the device is available */
4677 nand_get_device(mtd, FL_ERASING);
4679 /* Shift to get first page */
4680 page = (int)(instr->addr >> chip->page_shift);
4681 chipnr = (int)(instr->addr >> chip->chip_shift);
4683 /* Calculate pages in each block */
4684 pages_per_block = 1 << (chip->phys_erase_shift - chip->page_shift);
4686 /* Select the NAND device */
4687 chip->select_chip(mtd, chipnr);
4689 /* Check, if it is write protected */
4690 if (nand_check_wp(mtd)) {
4691 pr_debug("%s: device is write protected!\n",
4697 /* Loop through the pages */
4701 /* Check if we have a bad block, we do not erase bad blocks! */
4702 if (nand_block_checkbad(mtd, ((loff_t) page) <<
4703 chip->page_shift, allowbbt)) {
4704 pr_warn("%s: attempt to erase a bad block at page 0x%08x\n",
4711 * Invalidate the page cache, if we erase the block which
4712 * contains the current cached page.
4714 if (page <= chip->pagebuf && chip->pagebuf <
4715 (page + pages_per_block))
4718 status = chip->erase(mtd, page & chip->pagemask);
4720 /* See if block erase succeeded */
4722 pr_debug("%s: failed erase, page 0x%08x\n",
4726 ((loff_t)page << chip->page_shift);
4730 /* Increment page address and decrement length */
4731 len -= (1ULL << chip->phys_erase_shift);
4732 page += pages_per_block;
4734 /* Check, if we cross a chip boundary */
4735 if (len && !(page & chip->pagemask)) {
4737 chip->select_chip(mtd, -1);
4738 chip->select_chip(mtd, chipnr);
4745 /* Deselect and wake up anyone waiting on the device */
4746 chip->select_chip(mtd, -1);
4747 nand_release_device(mtd);
4749 /* Return more or less happy */
4754 * nand_sync - [MTD Interface] sync
4755 * @mtd: MTD device structure
4757 * Sync is actually a wait for chip ready function.
4759 static void nand_sync(struct mtd_info *mtd)
4761 pr_debug("%s: called\n", __func__);
4763 /* Grab the lock and see if the device is available */
4764 nand_get_device(mtd, FL_SYNCING);
4765 /* Release it and go back */
4766 nand_release_device(mtd);
4770 * nand_block_isbad - [MTD Interface] Check if block at offset is bad
4771 * @mtd: MTD device structure
4772 * @offs: offset relative to mtd start
4774 static int nand_block_isbad(struct mtd_info *mtd, loff_t offs)
4776 struct nand_chip *chip = mtd_to_nand(mtd);
4777 int chipnr = (int)(offs >> chip->chip_shift);
4780 /* Select the NAND device */
4781 nand_get_device(mtd, FL_READING);
4782 chip->select_chip(mtd, chipnr);
4784 ret = nand_block_checkbad(mtd, offs, 0);
4786 chip->select_chip(mtd, -1);
4787 nand_release_device(mtd);
4793 * nand_block_markbad - [MTD Interface] Mark block at the given offset as bad
4794 * @mtd: MTD device structure
4795 * @ofs: offset relative to mtd start
4797 static int nand_block_markbad(struct mtd_info *mtd, loff_t ofs)
4801 ret = nand_block_isbad(mtd, ofs);
4803 /* If it was bad already, return success and do nothing */
4809 return nand_block_markbad_lowlevel(mtd, ofs);
4813 * nand_max_bad_blocks - [MTD Interface] Max number of bad blocks for an mtd
4814 * @mtd: MTD device structure
4815 * @ofs: offset relative to mtd start
4816 * @len: length of mtd
4818 static int nand_max_bad_blocks(struct mtd_info *mtd, loff_t ofs, size_t len)
4820 struct nand_chip *chip = mtd_to_nand(mtd);
4821 u32 part_start_block;
4827 * max_bb_per_die and blocks_per_die used to determine
4828 * the maximum bad block count.
4830 if (!chip->max_bb_per_die || !chip->blocks_per_die)
4833 /* Get the start and end of the partition in erase blocks. */
4834 part_start_block = mtd_div_by_eb(ofs, mtd);
4835 part_end_block = mtd_div_by_eb(len, mtd) + part_start_block - 1;
4837 /* Get the start and end LUNs of the partition. */
4838 part_start_die = part_start_block / chip->blocks_per_die;
4839 part_end_die = part_end_block / chip->blocks_per_die;
4842 * Look up the bad blocks per unit and multiply by the number of units
4843 * that the partition spans.
4845 return chip->max_bb_per_die * (part_end_die - part_start_die + 1);
4849 * nand_default_set_features- [REPLACEABLE] set NAND chip features
4850 * @mtd: MTD device structure
4851 * @chip: nand chip info structure
4852 * @addr: feature address.
4853 * @subfeature_param: the subfeature parameters, a four bytes array.
4855 static int nand_default_set_features(struct mtd_info *mtd,
4856 struct nand_chip *chip, int addr,
4857 uint8_t *subfeature_param)
4859 return nand_set_features_op(chip, addr, subfeature_param);
4863 * nand_default_get_features- [REPLACEABLE] get NAND chip features
4864 * @mtd: MTD device structure
4865 * @chip: nand chip info structure
4866 * @addr: feature address.
4867 * @subfeature_param: the subfeature parameters, a four bytes array.
4869 static int nand_default_get_features(struct mtd_info *mtd,
4870 struct nand_chip *chip, int addr,
4871 uint8_t *subfeature_param)
4873 return nand_get_features_op(chip, addr, subfeature_param);
4877 * nand_get_set_features_notsupp - set/get features stub returning -ENOTSUPP
4878 * @mtd: MTD device structure
4879 * @chip: nand chip info structure
4880 * @addr: feature address.
4881 * @subfeature_param: the subfeature parameters, a four bytes array.
4883 * Should be used by NAND controller drivers that do not support the SET/GET
4884 * FEATURES operations.
4886 int nand_get_set_features_notsupp(struct mtd_info *mtd, struct nand_chip *chip,
4887 int addr, u8 *subfeature_param)
4891 EXPORT_SYMBOL(nand_get_set_features_notsupp);
4894 * nand_suspend - [MTD Interface] Suspend the NAND flash
4895 * @mtd: MTD device structure
4897 static int nand_suspend(struct mtd_info *mtd)
4899 return nand_get_device(mtd, FL_PM_SUSPENDED);
4903 * nand_resume - [MTD Interface] Resume the NAND flash
4904 * @mtd: MTD device structure
4906 static void nand_resume(struct mtd_info *mtd)
4908 struct nand_chip *chip = mtd_to_nand(mtd);
4910 if (chip->state == FL_PM_SUSPENDED)
4911 nand_release_device(mtd);
4913 pr_err("%s called for a chip which is not in suspended state\n",
4918 * nand_shutdown - [MTD Interface] Finish the current NAND operation and
4919 * prevent further operations
4920 * @mtd: MTD device structure
4922 static void nand_shutdown(struct mtd_info *mtd)
4924 nand_get_device(mtd, FL_PM_SUSPENDED);
4927 /* Set default functions */
4928 static void nand_set_defaults(struct nand_chip *chip)
4930 unsigned int busw = chip->options & NAND_BUSWIDTH_16;
4932 /* check for proper chip_delay setup, set 20us if not */
4933 if (!chip->chip_delay)
4934 chip->chip_delay = 20;
4936 /* check, if a user supplied command function given */
4937 if (!chip->cmdfunc && !chip->exec_op)
4938 chip->cmdfunc = nand_command;
4940 /* check, if a user supplied wait function given */
4941 if (chip->waitfunc == NULL)
4942 chip->waitfunc = nand_wait;
4944 if (!chip->select_chip)
4945 chip->select_chip = nand_select_chip;
4947 /* set for ONFI nand */
4948 if (!chip->set_features)
4949 chip->set_features = nand_default_set_features;
4950 if (!chip->get_features)
4951 chip->get_features = nand_default_get_features;
4953 /* If called twice, pointers that depend on busw may need to be reset */
4954 if (!chip->read_byte || chip->read_byte == nand_read_byte)
4955 chip->read_byte = busw ? nand_read_byte16 : nand_read_byte;
4956 if (!chip->read_word)
4957 chip->read_word = nand_read_word;
4958 if (!chip->block_bad)
4959 chip->block_bad = nand_block_bad;
4960 if (!chip->block_markbad)
4961 chip->block_markbad = nand_default_block_markbad;
4962 if (!chip->write_buf || chip->write_buf == nand_write_buf)
4963 chip->write_buf = busw ? nand_write_buf16 : nand_write_buf;
4964 if (!chip->write_byte || chip->write_byte == nand_write_byte)
4965 chip->write_byte = busw ? nand_write_byte16 : nand_write_byte;
4966 if (!chip->read_buf || chip->read_buf == nand_read_buf)
4967 chip->read_buf = busw ? nand_read_buf16 : nand_read_buf;
4968 if (!chip->scan_bbt)
4969 chip->scan_bbt = nand_default_bbt;
4971 if (!chip->controller) {
4972 chip->controller = &chip->hwcontrol;
4973 nand_hw_control_init(chip->controller);
4976 if (!chip->buf_align)
4977 chip->buf_align = 1;
4980 /* Sanitize ONFI strings so we can safely print them */
4981 static void sanitize_string(uint8_t *s, size_t len)
4985 /* Null terminate */
4988 /* Remove non printable chars */
4989 for (i = 0; i < len - 1; i++) {
4990 if (s[i] < ' ' || s[i] > 127)
4994 /* Remove trailing spaces */
4998 static u16 onfi_crc16(u16 crc, u8 const *p, size_t len)
5003 for (i = 0; i < 8; i++)
5004 crc = (crc << 1) ^ ((crc & 0x8000) ? 0x8005 : 0);
5010 /* Parse the Extended Parameter Page. */
5011 static int nand_flash_detect_ext_param_page(struct nand_chip *chip,
5012 struct nand_onfi_params *p)
5014 struct onfi_ext_param_page *ep;
5015 struct onfi_ext_section *s;
5016 struct onfi_ext_ecc_info *ecc;
5022 len = le16_to_cpu(p->ext_param_page_length) * 16;
5023 ep = kmalloc(len, GFP_KERNEL);
5027 /* Send our own NAND_CMD_PARAM. */
5028 ret = nand_read_param_page_op(chip, 0, NULL, 0);
5032 /* Use the Change Read Column command to skip the ONFI param pages. */
5033 ret = nand_change_read_column_op(chip,
5034 sizeof(*p) * p->num_of_param_pages,
5040 if ((onfi_crc16(ONFI_CRC_BASE, ((uint8_t *)ep) + 2, len - 2)
5041 != le16_to_cpu(ep->crc))) {
5042 pr_debug("fail in the CRC.\n");
5047 * Check the signature.
5048 * Do not strictly follow the ONFI spec, maybe changed in future.
5050 if (strncmp(ep->sig, "EPPS", 4)) {
5051 pr_debug("The signature is invalid.\n");
5055 /* find the ECC section. */
5056 cursor = (uint8_t *)(ep + 1);
5057 for (i = 0; i < ONFI_EXT_SECTION_MAX; i++) {
5058 s = ep->sections + i;
5059 if (s->type == ONFI_SECTION_TYPE_2)
5061 cursor += s->length * 16;
5063 if (i == ONFI_EXT_SECTION_MAX) {
5064 pr_debug("We can not find the ECC section.\n");
5068 /* get the info we want. */
5069 ecc = (struct onfi_ext_ecc_info *)cursor;
5071 if (!ecc->codeword_size) {
5072 pr_debug("Invalid codeword size\n");
5076 chip->ecc_strength_ds = ecc->ecc_bits;
5077 chip->ecc_step_ds = 1 << ecc->codeword_size;
5086 * Recover data with bit-wise majority
5088 static void nand_bit_wise_majority(const void **srcbufs,
5089 unsigned int nsrcbufs,
5091 unsigned int bufsize)
5095 for (i = 0; i < bufsize; i++) {
5098 for (j = 0; j < 8; j++) {
5099 unsigned int cnt = 0;
5101 for (k = 0; k < nsrcbufs; k++) {
5102 const u8 *srcbuf = srcbufs[k];
5104 if (srcbuf[i] & BIT(j))
5108 if (cnt > nsrcbufs / 2)
5112 ((u8 *)dstbuf)[i] = val;
5117 * Check if the NAND chip is ONFI compliant, returns 1 if it is, 0 otherwise.
5119 static int nand_flash_detect_onfi(struct nand_chip *chip)
5121 struct mtd_info *mtd = nand_to_mtd(chip);
5122 struct nand_onfi_params *p;
5126 /* Try ONFI for unknown chip or LP */
5127 ret = nand_readid_op(chip, 0x20, id, sizeof(id));
5128 if (ret || strncmp(id, "ONFI", 4))
5131 /* ONFI chip: allocate a buffer to hold its parameter page */
5132 p = kzalloc((sizeof(*p) * 3), GFP_KERNEL);
5136 ret = nand_read_param_page_op(chip, 0, NULL, 0);
5139 goto free_onfi_param_page;
5142 for (i = 0; i < 3; i++) {
5143 ret = nand_read_data_op(chip, &p[i], sizeof(*p), true);
5146 goto free_onfi_param_page;
5149 if (onfi_crc16(ONFI_CRC_BASE, (u8 *)&p[i], 254) ==
5150 le16_to_cpu(p->crc)) {
5152 memcpy(p, &p[i], sizeof(*p));
5158 const void *srcbufs[3] = {p, p + 1, p + 2};
5160 pr_warn("Could not find a valid ONFI parameter page, trying bit-wise majority to recover it\n");
5161 nand_bit_wise_majority(srcbufs, ARRAY_SIZE(srcbufs), p,
5164 if (onfi_crc16(ONFI_CRC_BASE, (u8 *)p, 254) !=
5165 le16_to_cpu(p->crc)) {
5166 pr_err("ONFI parameter recovery failed, aborting\n");
5167 goto free_onfi_param_page;
5172 val = le16_to_cpu(p->revision);
5174 chip->parameters.onfi.version = 23;
5175 else if (val & (1 << 4))
5176 chip->parameters.onfi.version = 22;
5177 else if (val & (1 << 3))
5178 chip->parameters.onfi.version = 21;
5179 else if (val & (1 << 2))
5180 chip->parameters.onfi.version = 20;
5181 else if (val & (1 << 1))
5182 chip->parameters.onfi.version = 10;
5184 if (!chip->parameters.onfi.version) {
5185 pr_info("unsupported ONFI version: %d\n", val);
5186 goto free_onfi_param_page;
5191 sanitize_string(p->manufacturer, sizeof(p->manufacturer));
5192 sanitize_string(p->model, sizeof(p->model));
5193 strncpy(chip->parameters.model, p->model,
5194 sizeof(chip->parameters.model) - 1);
5196 mtd->writesize = le32_to_cpu(p->byte_per_page);
5199 * pages_per_block and blocks_per_lun may not be a power-of-2 size
5200 * (don't ask me who thought of this...). MTD assumes that these
5201 * dimensions will be power-of-2, so just truncate the remaining area.
5203 mtd->erasesize = 1 << (fls(le32_to_cpu(p->pages_per_block)) - 1);
5204 mtd->erasesize *= mtd->writesize;
5206 mtd->oobsize = le16_to_cpu(p->spare_bytes_per_page);
5208 /* See erasesize comment */
5209 chip->chipsize = 1 << (fls(le32_to_cpu(p->blocks_per_lun)) - 1);
5210 chip->chipsize *= (uint64_t)mtd->erasesize * p->lun_count;
5211 chip->bits_per_cell = p->bits_per_cell;
5213 chip->max_bb_per_die = le16_to_cpu(p->bb_per_lun);
5214 chip->blocks_per_die = le32_to_cpu(p->blocks_per_lun);
5216 if (le16_to_cpu(p->features) & ONFI_FEATURE_16_BIT_BUS)
5217 chip->options |= NAND_BUSWIDTH_16;
5219 if (p->ecc_bits != 0xff) {
5220 chip->ecc_strength_ds = p->ecc_bits;
5221 chip->ecc_step_ds = 512;
5222 } else if (chip->parameters.onfi.version >= 21 &&
5223 (le16_to_cpu(p->features) & ONFI_FEATURE_EXT_PARAM_PAGE)) {
5226 * The nand_flash_detect_ext_param_page() uses the
5227 * Change Read Column command which maybe not supported
5228 * by the chip->cmdfunc. So try to update the chip->cmdfunc
5229 * now. We do not replace user supplied command function.
5231 if (mtd->writesize > 512 && chip->cmdfunc == nand_command)
5232 chip->cmdfunc = nand_command_lp;
5234 /* The Extended Parameter Page is supported since ONFI 2.1. */
5235 if (nand_flash_detect_ext_param_page(chip, p))
5236 pr_warn("Failed to detect ONFI extended param page\n");
5238 pr_warn("Could not retrieve ONFI ECC requirements\n");
5241 /* Save some parameters from the parameter page for future use */
5242 if (le16_to_cpu(p->opt_cmd) & ONFI_OPT_CMD_SET_GET_FEATURES) {
5243 chip->parameters.supports_set_get_features = true;
5244 bitmap_set(chip->parameters.get_feature_list,
5245 ONFI_FEATURE_ADDR_TIMING_MODE, 1);
5246 bitmap_set(chip->parameters.set_feature_list,
5247 ONFI_FEATURE_ADDR_TIMING_MODE, 1);
5249 chip->parameters.onfi.tPROG = le16_to_cpu(p->t_prog);
5250 chip->parameters.onfi.tBERS = le16_to_cpu(p->t_bers);
5251 chip->parameters.onfi.tR = le16_to_cpu(p->t_r);
5252 chip->parameters.onfi.tCCS = le16_to_cpu(p->t_ccs);
5253 chip->parameters.onfi.async_timing_mode =
5254 le16_to_cpu(p->async_timing_mode);
5255 chip->parameters.onfi.vendor_revision =
5256 le16_to_cpu(p->vendor_revision);
5257 memcpy(chip->parameters.onfi.vendor, p->vendor,
5260 free_onfi_param_page:
5266 * Check if the NAND chip is JEDEC compliant, returns 1 if it is, 0 otherwise.
5268 static int nand_flash_detect_jedec(struct nand_chip *chip)
5270 struct mtd_info *mtd = nand_to_mtd(chip);
5271 struct nand_jedec_params *p;
5272 struct jedec_ecc_info *ecc;
5273 int jedec_version = 0;
5277 /* Try JEDEC for unknown chip or LP */
5278 ret = nand_readid_op(chip, 0x40, id, sizeof(id));
5279 if (ret || strncmp(id, "JEDEC", sizeof(id)))
5282 /* JEDEC chip: allocate a buffer to hold its parameter page */
5283 p = kzalloc(sizeof(*p), GFP_KERNEL);
5287 ret = nand_read_param_page_op(chip, 0x40, NULL, 0);
5290 goto free_jedec_param_page;
5293 for (i = 0; i < 3; i++) {
5294 ret = nand_read_data_op(chip, p, sizeof(*p), true);
5297 goto free_jedec_param_page;
5300 if (onfi_crc16(ONFI_CRC_BASE, (uint8_t *)p, 510) ==
5301 le16_to_cpu(p->crc))
5306 pr_err("Could not find valid JEDEC parameter page; aborting\n");
5307 goto free_jedec_param_page;
5311 val = le16_to_cpu(p->revision);
5314 else if (val & (1 << 1))
5315 jedec_version = 1; /* vendor specific version */
5317 if (!jedec_version) {
5318 pr_info("unsupported JEDEC version: %d\n", val);
5319 goto free_jedec_param_page;
5322 sanitize_string(p->manufacturer, sizeof(p->manufacturer));
5323 sanitize_string(p->model, sizeof(p->model));
5324 strncpy(chip->parameters.model, p->model,
5325 sizeof(chip->parameters.model) - 1);
5327 mtd->writesize = le32_to_cpu(p->byte_per_page);
5329 /* Please reference to the comment for nand_flash_detect_onfi. */
5330 mtd->erasesize = 1 << (fls(le32_to_cpu(p->pages_per_block)) - 1);
5331 mtd->erasesize *= mtd->writesize;
5333 mtd->oobsize = le16_to_cpu(p->spare_bytes_per_page);
5335 /* Please reference to the comment for nand_flash_detect_onfi. */
5336 chip->chipsize = 1 << (fls(le32_to_cpu(p->blocks_per_lun)) - 1);
5337 chip->chipsize *= (uint64_t)mtd->erasesize * p->lun_count;
5338 chip->bits_per_cell = p->bits_per_cell;
5340 if (le16_to_cpu(p->features) & JEDEC_FEATURE_16_BIT_BUS)
5341 chip->options |= NAND_BUSWIDTH_16;
5344 ecc = &p->ecc_info[0];
5346 if (ecc->codeword_size >= 9) {
5347 chip->ecc_strength_ds = ecc->ecc_bits;
5348 chip->ecc_step_ds = 1 << ecc->codeword_size;
5350 pr_warn("Invalid codeword size\n");
5353 free_jedec_param_page:
5359 * nand_id_has_period - Check if an ID string has a given wraparound period
5360 * @id_data: the ID string
5361 * @arrlen: the length of the @id_data array
5362 * @period: the period of repitition
5364 * Check if an ID string is repeated within a given sequence of bytes at
5365 * specific repetition interval period (e.g., {0x20,0x01,0x7F,0x20} has a
5366 * period of 3). This is a helper function for nand_id_len(). Returns non-zero
5367 * if the repetition has a period of @period; otherwise, returns zero.
5369 static int nand_id_has_period(u8 *id_data, int arrlen, int period)
5372 for (i = 0; i < period; i++)
5373 for (j = i + period; j < arrlen; j += period)
5374 if (id_data[i] != id_data[j])
5380 * nand_id_len - Get the length of an ID string returned by CMD_READID
5381 * @id_data: the ID string
5382 * @arrlen: the length of the @id_data array
5384 * Returns the length of the ID string, according to known wraparound/trailing
5385 * zero patterns. If no pattern exists, returns the length of the array.
5387 static int nand_id_len(u8 *id_data, int arrlen)
5389 int last_nonzero, period;
5391 /* Find last non-zero byte */
5392 for (last_nonzero = arrlen - 1; last_nonzero >= 0; last_nonzero--)
5393 if (id_data[last_nonzero])
5397 if (last_nonzero < 0)
5400 /* Calculate wraparound period */
5401 for (period = 1; period < arrlen; period++)
5402 if (nand_id_has_period(id_data, arrlen, period))
5405 /* There's a repeated pattern */
5406 if (period < arrlen)
5409 /* There are trailing zeros */
5410 if (last_nonzero < arrlen - 1)
5411 return last_nonzero + 1;
5413 /* No pattern detected */
5417 /* Extract the bits of per cell from the 3rd byte of the extended ID */
5418 static int nand_get_bits_per_cell(u8 cellinfo)
5422 bits = cellinfo & NAND_CI_CELLTYPE_MSK;
5423 bits >>= NAND_CI_CELLTYPE_SHIFT;
5428 * Many new NAND share similar device ID codes, which represent the size of the
5429 * chip. The rest of the parameters must be decoded according to generic or
5430 * manufacturer-specific "extended ID" decoding patterns.
5432 void nand_decode_ext_id(struct nand_chip *chip)
5434 struct mtd_info *mtd = nand_to_mtd(chip);
5436 u8 *id_data = chip->id.data;
5437 /* The 3rd id byte holds MLC / multichip data */
5438 chip->bits_per_cell = nand_get_bits_per_cell(id_data[2]);
5439 /* The 4th id byte is the important one */
5443 mtd->writesize = 1024 << (extid & 0x03);
5446 mtd->oobsize = (8 << (extid & 0x01)) * (mtd->writesize >> 9);
5448 /* Calc blocksize. Blocksize is multiples of 64KiB */
5449 mtd->erasesize = (64 * 1024) << (extid & 0x03);
5451 /* Get buswidth information */
5453 chip->options |= NAND_BUSWIDTH_16;
5455 EXPORT_SYMBOL_GPL(nand_decode_ext_id);
5458 * Old devices have chip data hardcoded in the device ID table. nand_decode_id
5459 * decodes a matching ID table entry and assigns the MTD size parameters for
5462 static void nand_decode_id(struct nand_chip *chip, struct nand_flash_dev *type)
5464 struct mtd_info *mtd = nand_to_mtd(chip);
5466 mtd->erasesize = type->erasesize;
5467 mtd->writesize = type->pagesize;
5468 mtd->oobsize = mtd->writesize / 32;
5470 /* All legacy ID NAND are small-page, SLC */
5471 chip->bits_per_cell = 1;
5475 * Set the bad block marker/indicator (BBM/BBI) patterns according to some
5476 * heuristic patterns using various detected parameters (e.g., manufacturer,
5477 * page size, cell-type information).
5479 static void nand_decode_bbm_options(struct nand_chip *chip)
5481 struct mtd_info *mtd = nand_to_mtd(chip);
5483 /* Set the bad block position */
5484 if (mtd->writesize > 512 || (chip->options & NAND_BUSWIDTH_16))
5485 chip->badblockpos = NAND_LARGE_BADBLOCK_POS;
5487 chip->badblockpos = NAND_SMALL_BADBLOCK_POS;
5490 static inline bool is_full_id_nand(struct nand_flash_dev *type)
5492 return type->id_len;
5495 static bool find_full_id_nand(struct nand_chip *chip,
5496 struct nand_flash_dev *type)
5498 struct mtd_info *mtd = nand_to_mtd(chip);
5499 u8 *id_data = chip->id.data;
5501 if (!strncmp(type->id, id_data, type->id_len)) {
5502 mtd->writesize = type->pagesize;
5503 mtd->erasesize = type->erasesize;
5504 mtd->oobsize = type->oobsize;
5506 chip->bits_per_cell = nand_get_bits_per_cell(id_data[2]);
5507 chip->chipsize = (uint64_t)type->chipsize << 20;
5508 chip->options |= type->options;
5509 chip->ecc_strength_ds = NAND_ECC_STRENGTH(type);
5510 chip->ecc_step_ds = NAND_ECC_STEP(type);
5511 chip->onfi_timing_mode_default =
5512 type->onfi_timing_mode_default;
5514 strncpy(chip->parameters.model, type->name,
5515 sizeof(chip->parameters.model) - 1);
5523 * Manufacturer detection. Only used when the NAND is not ONFI or JEDEC
5524 * compliant and does not have a full-id or legacy-id entry in the nand_ids
5527 static void nand_manufacturer_detect(struct nand_chip *chip)
5530 * Try manufacturer detection if available and use
5531 * nand_decode_ext_id() otherwise.
5533 if (chip->manufacturer.desc && chip->manufacturer.desc->ops &&
5534 chip->manufacturer.desc->ops->detect) {
5535 /* The 3rd id byte holds MLC / multichip data */
5536 chip->bits_per_cell = nand_get_bits_per_cell(chip->id.data[2]);
5537 chip->manufacturer.desc->ops->detect(chip);
5539 nand_decode_ext_id(chip);
5544 * Manufacturer initialization. This function is called for all NANDs including
5545 * ONFI and JEDEC compliant ones.
5546 * Manufacturer drivers should put all their specific initialization code in
5547 * their ->init() hook.
5549 static int nand_manufacturer_init(struct nand_chip *chip)
5551 if (!chip->manufacturer.desc || !chip->manufacturer.desc->ops ||
5552 !chip->manufacturer.desc->ops->init)
5555 return chip->manufacturer.desc->ops->init(chip);
5559 * Manufacturer cleanup. This function is called for all NANDs including
5560 * ONFI and JEDEC compliant ones.
5561 * Manufacturer drivers should put all their specific cleanup code in their
5564 static void nand_manufacturer_cleanup(struct nand_chip *chip)
5566 /* Release manufacturer private data */
5567 if (chip->manufacturer.desc && chip->manufacturer.desc->ops &&
5568 chip->manufacturer.desc->ops->cleanup)
5569 chip->manufacturer.desc->ops->cleanup(chip);
5573 * Get the flash and manufacturer id and lookup if the type is supported.
5575 static int nand_detect(struct nand_chip *chip, struct nand_flash_dev *type)
5577 const struct nand_manufacturer *manufacturer;
5578 struct mtd_info *mtd = nand_to_mtd(chip);
5580 u8 *id_data = chip->id.data;
5584 * Reset the chip, required by some chips (e.g. Micron MT29FxGxxxxx)
5587 ret = nand_reset(chip, 0);
5591 /* Select the device */
5592 chip->select_chip(mtd, 0);
5594 /* Send the command for reading device ID */
5595 ret = nand_readid_op(chip, 0, id_data, 2);
5599 /* Read manufacturer and device IDs */
5600 maf_id = id_data[0];
5601 dev_id = id_data[1];
5604 * Try again to make sure, as some systems the bus-hold or other
5605 * interface concerns can cause random data which looks like a
5606 * possibly credible NAND flash to appear. If the two results do
5607 * not match, ignore the device completely.
5610 /* Read entire ID string */
5611 ret = nand_readid_op(chip, 0, id_data, sizeof(chip->id.data));
5615 if (id_data[0] != maf_id || id_data[1] != dev_id) {
5616 pr_info("second ID read did not match %02x,%02x against %02x,%02x\n",
5617 maf_id, dev_id, id_data[0], id_data[1]);
5621 chip->id.len = nand_id_len(id_data, ARRAY_SIZE(chip->id.data));
5623 /* Try to identify manufacturer */
5624 manufacturer = nand_get_manufacturer(maf_id);
5625 chip->manufacturer.desc = manufacturer;
5628 type = nand_flash_ids;
5631 * Save the NAND_BUSWIDTH_16 flag before letting auto-detection logic
5633 * This is required to make sure initial NAND bus width set by the
5634 * NAND controller driver is coherent with the real NAND bus width
5635 * (extracted by auto-detection code).
5637 busw = chip->options & NAND_BUSWIDTH_16;
5640 * The flag is only set (never cleared), reset it to its default value
5641 * before starting auto-detection.
5643 chip->options &= ~NAND_BUSWIDTH_16;
5645 for (; type->name != NULL; type++) {
5646 if (is_full_id_nand(type)) {
5647 if (find_full_id_nand(chip, type))
5649 } else if (dev_id == type->dev_id) {
5654 chip->parameters.onfi.version = 0;
5655 if (!type->name || !type->pagesize) {
5656 /* Check if the chip is ONFI compliant */
5657 ret = nand_flash_detect_onfi(chip);
5663 /* Check if the chip is JEDEC compliant */
5664 ret = nand_flash_detect_jedec(chip);
5674 strncpy(chip->parameters.model, type->name,
5675 sizeof(chip->parameters.model) - 1);
5677 chip->chipsize = (uint64_t)type->chipsize << 20;
5679 if (!type->pagesize)
5680 nand_manufacturer_detect(chip);
5682 nand_decode_id(chip, type);
5684 /* Get chip options */
5685 chip->options |= type->options;
5689 mtd->name = chip->parameters.model;
5691 if (chip->options & NAND_BUSWIDTH_AUTO) {
5692 WARN_ON(busw & NAND_BUSWIDTH_16);
5693 nand_set_defaults(chip);
5694 } else if (busw != (chip->options & NAND_BUSWIDTH_16)) {
5696 * Check, if buswidth is correct. Hardware drivers should set
5699 pr_info("device found, Manufacturer ID: 0x%02x, Chip ID: 0x%02x\n",
5701 pr_info("%s %s\n", nand_manufacturer_name(manufacturer),
5703 pr_warn("bus width %d instead of %d bits\n", busw ? 16 : 8,
5704 (chip->options & NAND_BUSWIDTH_16) ? 16 : 8);
5708 nand_decode_bbm_options(chip);
5710 /* Calculate the address shift from the page size */
5711 chip->page_shift = ffs(mtd->writesize) - 1;
5712 /* Convert chipsize to number of pages per chip -1 */
5713 chip->pagemask = (chip->chipsize >> chip->page_shift) - 1;
5715 chip->bbt_erase_shift = chip->phys_erase_shift =
5716 ffs(mtd->erasesize) - 1;
5717 if (chip->chipsize & 0xffffffff)
5718 chip->chip_shift = ffs((unsigned)chip->chipsize) - 1;
5720 chip->chip_shift = ffs((unsigned)(chip->chipsize >> 32));
5721 chip->chip_shift += 32 - 1;
5724 if (chip->chip_shift - chip->page_shift > 16)
5725 chip->options |= NAND_ROW_ADDR_3;
5727 chip->badblockbits = 8;
5728 chip->erase = single_erase;
5730 /* Do not replace user supplied command function! */
5731 if (mtd->writesize > 512 && chip->cmdfunc == nand_command)
5732 chip->cmdfunc = nand_command_lp;
5734 pr_info("device found, Manufacturer ID: 0x%02x, Chip ID: 0x%02x\n",
5736 pr_info("%s %s\n", nand_manufacturer_name(manufacturer),
5737 chip->parameters.model);
5738 pr_info("%d MiB, %s, erase size: %d KiB, page size: %d, OOB size: %d\n",
5739 (int)(chip->chipsize >> 20), nand_is_slc(chip) ? "SLC" : "MLC",
5740 mtd->erasesize >> 10, mtd->writesize, mtd->oobsize);
5744 static const char * const nand_ecc_modes[] = {
5745 [NAND_ECC_NONE] = "none",
5746 [NAND_ECC_SOFT] = "soft",
5747 [NAND_ECC_HW] = "hw",
5748 [NAND_ECC_HW_SYNDROME] = "hw_syndrome",
5749 [NAND_ECC_HW_OOB_FIRST] = "hw_oob_first",
5750 [NAND_ECC_ON_DIE] = "on-die",
5753 static int of_get_nand_ecc_mode(struct device_node *np)
5758 err = of_property_read_string(np, "nand-ecc-mode", &pm);
5762 for (i = 0; i < ARRAY_SIZE(nand_ecc_modes); i++)
5763 if (!strcasecmp(pm, nand_ecc_modes[i]))
5767 * For backward compatibility we support few obsoleted values that don't
5768 * have their mappings into nand_ecc_modes_t anymore (they were merged
5769 * with other enums).
5771 if (!strcasecmp(pm, "soft_bch"))
5772 return NAND_ECC_SOFT;
5777 static const char * const nand_ecc_algos[] = {
5778 [NAND_ECC_HAMMING] = "hamming",
5779 [NAND_ECC_BCH] = "bch",
5782 static int of_get_nand_ecc_algo(struct device_node *np)
5787 err = of_property_read_string(np, "nand-ecc-algo", &pm);
5789 for (i = NAND_ECC_HAMMING; i < ARRAY_SIZE(nand_ecc_algos); i++)
5790 if (!strcasecmp(pm, nand_ecc_algos[i]))
5796 * For backward compatibility we also read "nand-ecc-mode" checking
5797 * for some obsoleted values that were specifying ECC algorithm.
5799 err = of_property_read_string(np, "nand-ecc-mode", &pm);
5803 if (!strcasecmp(pm, "soft"))
5804 return NAND_ECC_HAMMING;
5805 else if (!strcasecmp(pm, "soft_bch"))
5806 return NAND_ECC_BCH;
5811 static int of_get_nand_ecc_step_size(struct device_node *np)
5816 ret = of_property_read_u32(np, "nand-ecc-step-size", &val);
5817 return ret ? ret : val;
5820 static int of_get_nand_ecc_strength(struct device_node *np)
5825 ret = of_property_read_u32(np, "nand-ecc-strength", &val);
5826 return ret ? ret : val;
5829 static int of_get_nand_bus_width(struct device_node *np)
5833 if (of_property_read_u32(np, "nand-bus-width", &val))
5845 static bool of_get_nand_on_flash_bbt(struct device_node *np)
5847 return of_property_read_bool(np, "nand-on-flash-bbt");
5850 static int nand_dt_init(struct nand_chip *chip)
5852 struct device_node *dn = nand_get_flash_node(chip);
5853 int ecc_mode, ecc_algo, ecc_strength, ecc_step;
5858 if (of_get_nand_bus_width(dn) == 16)
5859 chip->options |= NAND_BUSWIDTH_16;
5861 if (of_get_nand_on_flash_bbt(dn))
5862 chip->bbt_options |= NAND_BBT_USE_FLASH;
5864 ecc_mode = of_get_nand_ecc_mode(dn);
5865 ecc_algo = of_get_nand_ecc_algo(dn);
5866 ecc_strength = of_get_nand_ecc_strength(dn);
5867 ecc_step = of_get_nand_ecc_step_size(dn);
5870 chip->ecc.mode = ecc_mode;
5873 chip->ecc.algo = ecc_algo;
5875 if (ecc_strength >= 0)
5876 chip->ecc.strength = ecc_strength;
5879 chip->ecc.size = ecc_step;
5881 if (of_property_read_bool(dn, "nand-ecc-maximize"))
5882 chip->ecc.options |= NAND_ECC_MAXIMIZE;
5888 * nand_scan_ident - [NAND Interface] Scan for the NAND device
5889 * @mtd: MTD device structure
5890 * @maxchips: number of chips to scan for
5891 * @table: alternative NAND ID table
5893 * This is the first phase of the normal nand_scan() function. It reads the
5894 * flash ID and sets up MTD fields accordingly.
5897 int nand_scan_ident(struct mtd_info *mtd, int maxchips,
5898 struct nand_flash_dev *table)
5900 int i, nand_maf_id, nand_dev_id;
5901 struct nand_chip *chip = mtd_to_nand(mtd);
5904 /* Enforce the right timings for reset/detection */
5905 onfi_fill_data_interface(chip, NAND_SDR_IFACE, 0);
5907 ret = nand_dt_init(chip);
5911 if (!mtd->name && mtd->dev.parent)
5912 mtd->name = dev_name(mtd->dev.parent);
5915 * ->cmdfunc() is legacy and will only be used if ->exec_op() is not
5918 if (!chip->exec_op) {
5920 * Default functions assigned for ->cmdfunc() and
5921 * ->select_chip() both expect ->cmd_ctrl() to be populated.
5923 if ((!chip->cmdfunc || !chip->select_chip) && !chip->cmd_ctrl) {
5924 pr_err("->cmd_ctrl() should be provided\n");
5929 /* Set the default functions */
5930 nand_set_defaults(chip);
5932 /* Read the flash type */
5933 ret = nand_detect(chip, table);
5935 if (!(chip->options & NAND_SCAN_SILENT_NODEV))
5936 pr_warn("No NAND device found\n");
5937 chip->select_chip(mtd, -1);
5941 nand_maf_id = chip->id.data[0];
5942 nand_dev_id = chip->id.data[1];
5944 chip->select_chip(mtd, -1);
5946 /* Check for a chip array */
5947 for (i = 1; i < maxchips; i++) {
5950 /* See comment in nand_get_flash_type for reset */
5951 nand_reset(chip, i);
5953 chip->select_chip(mtd, i);
5954 /* Send the command for reading device ID */
5955 nand_readid_op(chip, 0, id, sizeof(id));
5956 /* Read manufacturer and device IDs */
5957 if (nand_maf_id != id[0] || nand_dev_id != id[1]) {
5958 chip->select_chip(mtd, -1);
5961 chip->select_chip(mtd, -1);
5964 pr_info("%d chips detected\n", i);
5966 /* Store the number of chips and calc total size for mtd */
5968 mtd->size = i * chip->chipsize;
5972 EXPORT_SYMBOL(nand_scan_ident);
5974 static int nand_set_ecc_soft_ops(struct mtd_info *mtd)
5976 struct nand_chip *chip = mtd_to_nand(mtd);
5977 struct nand_ecc_ctrl *ecc = &chip->ecc;
5979 if (WARN_ON(ecc->mode != NAND_ECC_SOFT))
5982 switch (ecc->algo) {
5983 case NAND_ECC_HAMMING:
5984 ecc->calculate = nand_calculate_ecc;
5985 ecc->correct = nand_correct_data;
5986 ecc->read_page = nand_read_page_swecc;
5987 ecc->read_subpage = nand_read_subpage;
5988 ecc->write_page = nand_write_page_swecc;
5989 ecc->read_page_raw = nand_read_page_raw;
5990 ecc->write_page_raw = nand_write_page_raw;
5991 ecc->read_oob = nand_read_oob_std;
5992 ecc->write_oob = nand_write_oob_std;
5999 if (!mtd_nand_has_bch()) {
6000 WARN(1, "CONFIG_MTD_NAND_ECC_BCH not enabled\n");
6003 ecc->calculate = nand_bch_calculate_ecc;
6004 ecc->correct = nand_bch_correct_data;
6005 ecc->read_page = nand_read_page_swecc;
6006 ecc->read_subpage = nand_read_subpage;
6007 ecc->write_page = nand_write_page_swecc;
6008 ecc->read_page_raw = nand_read_page_raw;
6009 ecc->write_page_raw = nand_write_page_raw;
6010 ecc->read_oob = nand_read_oob_std;
6011 ecc->write_oob = nand_write_oob_std;
6014 * Board driver should supply ecc.size and ecc.strength
6015 * values to select how many bits are correctable.
6016 * Otherwise, default to 4 bits for large page devices.
6018 if (!ecc->size && (mtd->oobsize >= 64)) {
6024 * if no ecc placement scheme was provided pickup the default
6027 if (!mtd->ooblayout) {
6028 /* handle large page devices only */
6029 if (mtd->oobsize < 64) {
6030 WARN(1, "OOB layout is required when using software BCH on small pages\n");
6034 mtd_set_ooblayout(mtd, &nand_ooblayout_lp_ops);
6039 * We can only maximize ECC config when the default layout is
6040 * used, otherwise we don't know how many bytes can really be
6043 if (mtd->ooblayout == &nand_ooblayout_lp_ops &&
6044 ecc->options & NAND_ECC_MAXIMIZE) {
6047 /* Always prefer 1k blocks over 512bytes ones */
6049 steps = mtd->writesize / ecc->size;
6051 /* Reserve 2 bytes for the BBM */
6052 bytes = (mtd->oobsize - 2) / steps;
6053 ecc->strength = bytes * 8 / fls(8 * ecc->size);
6056 /* See nand_bch_init() for details. */
6058 ecc->priv = nand_bch_init(mtd);
6060 WARN(1, "BCH ECC initialization failed!\n");
6065 WARN(1, "Unsupported ECC algorithm!\n");
6071 * nand_check_ecc_caps - check the sanity of preset ECC settings
6072 * @chip: nand chip info structure
6073 * @caps: ECC caps info structure
6074 * @oobavail: OOB size that the ECC engine can use
6076 * When ECC step size and strength are already set, check if they are supported
6077 * by the controller and the calculated ECC bytes fit within the chip's OOB.
6078 * On success, the calculated ECC bytes is set.
6080 int nand_check_ecc_caps(struct nand_chip *chip,
6081 const struct nand_ecc_caps *caps, int oobavail)
6083 struct mtd_info *mtd = nand_to_mtd(chip);
6084 const struct nand_ecc_step_info *stepinfo;
6085 int preset_step = chip->ecc.size;
6086 int preset_strength = chip->ecc.strength;
6087 int nsteps, ecc_bytes;
6090 if (WARN_ON(oobavail < 0))
6093 if (!preset_step || !preset_strength)
6096 nsteps = mtd->writesize / preset_step;
6098 for (i = 0; i < caps->nstepinfos; i++) {
6099 stepinfo = &caps->stepinfos[i];
6101 if (stepinfo->stepsize != preset_step)
6104 for (j = 0; j < stepinfo->nstrengths; j++) {
6105 if (stepinfo->strengths[j] != preset_strength)
6108 ecc_bytes = caps->calc_ecc_bytes(preset_step,
6110 if (WARN_ON_ONCE(ecc_bytes < 0))
6113 if (ecc_bytes * nsteps > oobavail) {
6114 pr_err("ECC (step, strength) = (%d, %d) does not fit in OOB",
6115 preset_step, preset_strength);
6119 chip->ecc.bytes = ecc_bytes;
6125 pr_err("ECC (step, strength) = (%d, %d) not supported on this controller",
6126 preset_step, preset_strength);
6130 EXPORT_SYMBOL_GPL(nand_check_ecc_caps);
6133 * nand_match_ecc_req - meet the chip's requirement with least ECC bytes
6134 * @chip: nand chip info structure
6135 * @caps: ECC engine caps info structure
6136 * @oobavail: OOB size that the ECC engine can use
6138 * If a chip's ECC requirement is provided, try to meet it with the least
6139 * number of ECC bytes (i.e. with the largest number of OOB-free bytes).
6140 * On success, the chosen ECC settings are set.
6142 int nand_match_ecc_req(struct nand_chip *chip,
6143 const struct nand_ecc_caps *caps, int oobavail)
6145 struct mtd_info *mtd = nand_to_mtd(chip);
6146 const struct nand_ecc_step_info *stepinfo;
6147 int req_step = chip->ecc_step_ds;
6148 int req_strength = chip->ecc_strength_ds;
6149 int req_corr, step_size, strength, nsteps, ecc_bytes, ecc_bytes_total;
6150 int best_step, best_strength, best_ecc_bytes;
6151 int best_ecc_bytes_total = INT_MAX;
6154 if (WARN_ON(oobavail < 0))
6157 /* No information provided by the NAND chip */
6158 if (!req_step || !req_strength)
6161 /* number of correctable bits the chip requires in a page */
6162 req_corr = mtd->writesize / req_step * req_strength;
6164 for (i = 0; i < caps->nstepinfos; i++) {
6165 stepinfo = &caps->stepinfos[i];
6166 step_size = stepinfo->stepsize;
6168 for (j = 0; j < stepinfo->nstrengths; j++) {
6169 strength = stepinfo->strengths[j];
6172 * If both step size and strength are smaller than the
6173 * chip's requirement, it is not easy to compare the
6174 * resulted reliability.
6176 if (step_size < req_step && strength < req_strength)
6179 if (mtd->writesize % step_size)
6182 nsteps = mtd->writesize / step_size;
6184 ecc_bytes = caps->calc_ecc_bytes(step_size, strength);
6185 if (WARN_ON_ONCE(ecc_bytes < 0))
6187 ecc_bytes_total = ecc_bytes * nsteps;
6189 if (ecc_bytes_total > oobavail ||
6190 strength * nsteps < req_corr)
6194 * We assume the best is to meet the chip's requrement
6195 * with the least number of ECC bytes.
6197 if (ecc_bytes_total < best_ecc_bytes_total) {
6198 best_ecc_bytes_total = ecc_bytes_total;
6199 best_step = step_size;
6200 best_strength = strength;
6201 best_ecc_bytes = ecc_bytes;
6206 if (best_ecc_bytes_total == INT_MAX)
6209 chip->ecc.size = best_step;
6210 chip->ecc.strength = best_strength;
6211 chip->ecc.bytes = best_ecc_bytes;
6215 EXPORT_SYMBOL_GPL(nand_match_ecc_req);
6218 * nand_maximize_ecc - choose the max ECC strength available
6219 * @chip: nand chip info structure
6220 * @caps: ECC engine caps info structure
6221 * @oobavail: OOB size that the ECC engine can use
6223 * Choose the max ECC strength that is supported on the controller, and can fit
6224 * within the chip's OOB. On success, the chosen ECC settings are set.
6226 int nand_maximize_ecc(struct nand_chip *chip,
6227 const struct nand_ecc_caps *caps, int oobavail)
6229 struct mtd_info *mtd = nand_to_mtd(chip);
6230 const struct nand_ecc_step_info *stepinfo;
6231 int step_size, strength, nsteps, ecc_bytes, corr;
6234 int best_strength, best_ecc_bytes;
6237 if (WARN_ON(oobavail < 0))
6240 for (i = 0; i < caps->nstepinfos; i++) {
6241 stepinfo = &caps->stepinfos[i];
6242 step_size = stepinfo->stepsize;
6244 /* If chip->ecc.size is already set, respect it */
6245 if (chip->ecc.size && step_size != chip->ecc.size)
6248 for (j = 0; j < stepinfo->nstrengths; j++) {
6249 strength = stepinfo->strengths[j];
6251 if (mtd->writesize % step_size)
6254 nsteps = mtd->writesize / step_size;
6256 ecc_bytes = caps->calc_ecc_bytes(step_size, strength);
6257 if (WARN_ON_ONCE(ecc_bytes < 0))
6260 if (ecc_bytes * nsteps > oobavail)
6263 corr = strength * nsteps;
6266 * If the number of correctable bits is the same,
6267 * bigger step_size has more reliability.
6269 if (corr > best_corr ||
6270 (corr == best_corr && step_size > best_step)) {
6272 best_step = step_size;
6273 best_strength = strength;
6274 best_ecc_bytes = ecc_bytes;
6282 chip->ecc.size = best_step;
6283 chip->ecc.strength = best_strength;
6284 chip->ecc.bytes = best_ecc_bytes;
6288 EXPORT_SYMBOL_GPL(nand_maximize_ecc);
6291 * Check if the chip configuration meet the datasheet requirements.
6293 * If our configuration corrects A bits per B bytes and the minimum
6294 * required correction level is X bits per Y bytes, then we must ensure
6295 * both of the following are true:
6297 * (1) A / B >= X / Y
6300 * Requirement (1) ensures we can correct for the required bitflip density.
6301 * Requirement (2) ensures we can correct even when all bitflips are clumped
6302 * in the same sector.
6304 static bool nand_ecc_strength_good(struct mtd_info *mtd)
6306 struct nand_chip *chip = mtd_to_nand(mtd);
6307 struct nand_ecc_ctrl *ecc = &chip->ecc;
6310 if (ecc->size == 0 || chip->ecc_step_ds == 0)
6311 /* Not enough information */
6315 * We get the number of corrected bits per page to compare
6316 * the correction density.
6318 corr = (mtd->writesize * ecc->strength) / ecc->size;
6319 ds_corr = (mtd->writesize * chip->ecc_strength_ds) / chip->ecc_step_ds;
6321 return corr >= ds_corr && ecc->strength >= chip->ecc_strength_ds;
6325 * nand_scan_tail - [NAND Interface] Scan for the NAND device
6326 * @mtd: MTD device structure
6328 * This is the second phase of the normal nand_scan() function. It fills out
6329 * all the uninitialized function pointers with the defaults and scans for a
6330 * bad block table if appropriate.
6332 int nand_scan_tail(struct mtd_info *mtd)
6334 struct nand_chip *chip = mtd_to_nand(mtd);
6335 struct nand_ecc_ctrl *ecc = &chip->ecc;
6338 /* New bad blocks should be marked in OOB, flash-based BBT, or both */
6339 if (WARN_ON((chip->bbt_options & NAND_BBT_NO_OOB_BBM) &&
6340 !(chip->bbt_options & NAND_BBT_USE_FLASH))) {
6344 chip->data_buf = kmalloc(mtd->writesize + mtd->oobsize, GFP_KERNEL);
6345 if (!chip->data_buf)
6349 * FIXME: some NAND manufacturer drivers expect the first die to be
6350 * selected when manufacturer->init() is called. They should be fixed
6351 * to explictly select the relevant die when interacting with the NAND
6354 chip->select_chip(mtd, 0);
6355 ret = nand_manufacturer_init(chip);
6356 chip->select_chip(mtd, -1);
6360 /* Set the internal oob buffer location, just after the page data */
6361 chip->oob_poi = chip->data_buf + mtd->writesize;
6364 * If no default placement scheme is given, select an appropriate one.
6366 if (!mtd->ooblayout &&
6367 !(ecc->mode == NAND_ECC_SOFT && ecc->algo == NAND_ECC_BCH)) {
6368 switch (mtd->oobsize) {
6371 mtd_set_ooblayout(mtd, &nand_ooblayout_sp_ops);
6375 mtd_set_ooblayout(mtd, &nand_ooblayout_lp_hamming_ops);
6379 * Expose the whole OOB area to users if ECC_NONE
6380 * is passed. We could do that for all kind of
6381 * ->oobsize, but we must keep the old large/small
6382 * page with ECC layout when ->oobsize <= 128 for
6383 * compatibility reasons.
6385 if (ecc->mode == NAND_ECC_NONE) {
6386 mtd_set_ooblayout(mtd,
6387 &nand_ooblayout_lp_ops);
6391 WARN(1, "No oob scheme defined for oobsize %d\n",
6394 goto err_nand_manuf_cleanup;
6399 * Check ECC mode, default to software if 3byte/512byte hardware ECC is
6400 * selected and we have 256 byte pagesize fallback to software ECC
6403 switch (ecc->mode) {
6404 case NAND_ECC_HW_OOB_FIRST:
6405 /* Similar to NAND_ECC_HW, but a separate read_page handle */
6406 if (!ecc->calculate || !ecc->correct || !ecc->hwctl) {
6407 WARN(1, "No ECC functions supplied; hardware ECC not possible\n");
6409 goto err_nand_manuf_cleanup;
6411 if (!ecc->read_page)
6412 ecc->read_page = nand_read_page_hwecc_oob_first;
6415 /* Use standard hwecc read page function? */
6416 if (!ecc->read_page)
6417 ecc->read_page = nand_read_page_hwecc;
6418 if (!ecc->write_page)
6419 ecc->write_page = nand_write_page_hwecc;
6420 if (!ecc->read_page_raw)
6421 ecc->read_page_raw = nand_read_page_raw;
6422 if (!ecc->write_page_raw)
6423 ecc->write_page_raw = nand_write_page_raw;
6425 ecc->read_oob = nand_read_oob_std;
6426 if (!ecc->write_oob)
6427 ecc->write_oob = nand_write_oob_std;
6428 if (!ecc->read_subpage)
6429 ecc->read_subpage = nand_read_subpage;
6430 if (!ecc->write_subpage && ecc->hwctl && ecc->calculate)
6431 ecc->write_subpage = nand_write_subpage_hwecc;
6433 case NAND_ECC_HW_SYNDROME:
6434 if ((!ecc->calculate || !ecc->correct || !ecc->hwctl) &&
6436 ecc->read_page == nand_read_page_hwecc ||
6438 ecc->write_page == nand_write_page_hwecc)) {
6439 WARN(1, "No ECC functions supplied; hardware ECC not possible\n");
6441 goto err_nand_manuf_cleanup;
6443 /* Use standard syndrome read/write page function? */
6444 if (!ecc->read_page)
6445 ecc->read_page = nand_read_page_syndrome;
6446 if (!ecc->write_page)
6447 ecc->write_page = nand_write_page_syndrome;
6448 if (!ecc->read_page_raw)
6449 ecc->read_page_raw = nand_read_page_raw_syndrome;
6450 if (!ecc->write_page_raw)
6451 ecc->write_page_raw = nand_write_page_raw_syndrome;
6453 ecc->read_oob = nand_read_oob_syndrome;
6454 if (!ecc->write_oob)
6455 ecc->write_oob = nand_write_oob_syndrome;
6457 if (mtd->writesize >= ecc->size) {
6458 if (!ecc->strength) {
6459 WARN(1, "Driver must set ecc.strength when using hardware ECC\n");
6461 goto err_nand_manuf_cleanup;
6465 pr_warn("%d byte HW ECC not possible on %d byte page size, fallback to SW ECC\n",
6466 ecc->size, mtd->writesize);
6467 ecc->mode = NAND_ECC_SOFT;
6468 ecc->algo = NAND_ECC_HAMMING;
6471 ret = nand_set_ecc_soft_ops(mtd);
6474 goto err_nand_manuf_cleanup;
6478 case NAND_ECC_ON_DIE:
6479 if (!ecc->read_page || !ecc->write_page) {
6480 WARN(1, "No ECC functions supplied; on-die ECC not possible\n");
6482 goto err_nand_manuf_cleanup;
6485 ecc->read_oob = nand_read_oob_std;
6486 if (!ecc->write_oob)
6487 ecc->write_oob = nand_write_oob_std;
6491 pr_warn("NAND_ECC_NONE selected by board driver. This is not recommended!\n");
6492 ecc->read_page = nand_read_page_raw;
6493 ecc->write_page = nand_write_page_raw;
6494 ecc->read_oob = nand_read_oob_std;
6495 ecc->read_page_raw = nand_read_page_raw;
6496 ecc->write_page_raw = nand_write_page_raw;
6497 ecc->write_oob = nand_write_oob_std;
6498 ecc->size = mtd->writesize;
6504 WARN(1, "Invalid NAND_ECC_MODE %d\n", ecc->mode);
6506 goto err_nand_manuf_cleanup;
6509 if (ecc->correct || ecc->calculate) {
6510 ecc->calc_buf = kmalloc(mtd->oobsize, GFP_KERNEL);
6511 ecc->code_buf = kmalloc(mtd->oobsize, GFP_KERNEL);
6512 if (!ecc->calc_buf || !ecc->code_buf) {
6514 goto err_nand_manuf_cleanup;
6518 /* For many systems, the standard OOB write also works for raw */
6519 if (!ecc->read_oob_raw)
6520 ecc->read_oob_raw = ecc->read_oob;
6521 if (!ecc->write_oob_raw)
6522 ecc->write_oob_raw = ecc->write_oob;
6524 /* propagate ecc info to mtd_info */
6525 mtd->ecc_strength = ecc->strength;
6526 mtd->ecc_step_size = ecc->size;
6529 * Set the number of read / write steps for one page depending on ECC
6532 ecc->steps = mtd->writesize / ecc->size;
6533 if (ecc->steps * ecc->size != mtd->writesize) {
6534 WARN(1, "Invalid ECC parameters\n");
6536 goto err_nand_manuf_cleanup;
6538 ecc->total = ecc->steps * ecc->bytes;
6539 if (ecc->total > mtd->oobsize) {
6540 WARN(1, "Total number of ECC bytes exceeded oobsize\n");
6542 goto err_nand_manuf_cleanup;
6546 * The number of bytes available for a client to place data into
6547 * the out of band area.
6549 ret = mtd_ooblayout_count_freebytes(mtd);
6553 mtd->oobavail = ret;
6555 /* ECC sanity check: warn if it's too weak */
6556 if (!nand_ecc_strength_good(mtd))
6557 pr_warn("WARNING: %s: the ECC used on your system is too weak compared to the one required by the NAND chip\n",
6560 /* Allow subpage writes up to ecc.steps. Not possible for MLC flash */
6561 if (!(chip->options & NAND_NO_SUBPAGE_WRITE) && nand_is_slc(chip)) {
6562 switch (ecc->steps) {
6564 mtd->subpage_sft = 1;
6569 mtd->subpage_sft = 2;
6573 chip->subpagesize = mtd->writesize >> mtd->subpage_sft;
6575 /* Initialize state */
6576 chip->state = FL_READY;
6578 /* Invalidate the pagebuffer reference */
6581 /* Large page NAND with SOFT_ECC should support subpage reads */
6582 switch (ecc->mode) {
6584 if (chip->page_shift > 9)
6585 chip->options |= NAND_SUBPAGE_READ;
6592 /* Fill in remaining MTD driver data */
6593 mtd->type = nand_is_slc(chip) ? MTD_NANDFLASH : MTD_MLCNANDFLASH;
6594 mtd->flags = (chip->options & NAND_ROM) ? MTD_CAP_ROM :
6596 mtd->_erase = nand_erase;
6598 mtd->_unpoint = NULL;
6599 mtd->_panic_write = panic_nand_write;
6600 mtd->_read_oob = nand_read_oob;
6601 mtd->_write_oob = nand_write_oob;
6602 mtd->_sync = nand_sync;
6604 mtd->_unlock = NULL;
6605 mtd->_suspend = nand_suspend;
6606 mtd->_resume = nand_resume;
6607 mtd->_reboot = nand_shutdown;
6608 mtd->_block_isreserved = nand_block_isreserved;
6609 mtd->_block_isbad = nand_block_isbad;
6610 mtd->_block_markbad = nand_block_markbad;
6611 mtd->_max_bad_blocks = nand_max_bad_blocks;
6612 mtd->writebufsize = mtd->writesize;
6615 * Initialize bitflip_threshold to its default prior scan_bbt() call.
6616 * scan_bbt() might invoke mtd_read(), thus bitflip_threshold must be
6619 if (!mtd->bitflip_threshold)
6620 mtd->bitflip_threshold = DIV_ROUND_UP(mtd->ecc_strength * 3, 4);
6622 /* Initialize the ->data_interface field. */
6623 ret = nand_init_data_interface(chip);
6625 goto err_nand_manuf_cleanup;
6627 /* Enter fastest possible mode on all dies. */
6628 for (i = 0; i < chip->numchips; i++) {
6629 ret = nand_setup_data_interface(chip, i);
6631 goto err_nand_manuf_cleanup;
6634 /* Check, if we should skip the bad block table scan */
6635 if (chip->options & NAND_SKIP_BBTSCAN)
6638 /* Build bad block table */
6639 ret = chip->scan_bbt(mtd);
6641 goto err_nand_manuf_cleanup;
6646 err_nand_manuf_cleanup:
6647 nand_manufacturer_cleanup(chip);
6650 kfree(chip->data_buf);
6651 kfree(ecc->code_buf);
6652 kfree(ecc->calc_buf);
6656 EXPORT_SYMBOL(nand_scan_tail);
6659 * is_module_text_address() isn't exported, and it's mostly a pointless
6660 * test if this is a module _anyway_ -- they'd have to try _really_ hard
6661 * to call us from in-kernel code if the core NAND support is modular.
6664 #define caller_is_module() (1)
6666 #define caller_is_module() \
6667 is_module_text_address((unsigned long)__builtin_return_address(0))
6671 * nand_scan_with_ids - [NAND Interface] Scan for the NAND device
6672 * @mtd: MTD device structure
6673 * @maxchips: number of chips to scan for
6674 * @ids: optional flash IDs table
6676 * This fills out all the uninitialized function pointers with the defaults.
6677 * The flash ID is read and the mtd/chip structures are filled with the
6678 * appropriate values.
6680 int nand_scan_with_ids(struct mtd_info *mtd, int maxchips,
6681 struct nand_flash_dev *ids)
6685 ret = nand_scan_ident(mtd, maxchips, ids);
6687 ret = nand_scan_tail(mtd);
6690 EXPORT_SYMBOL(nand_scan_with_ids);
6693 * nand_cleanup - [NAND Interface] Free resources held by the NAND device
6694 * @chip: NAND chip object
6696 void nand_cleanup(struct nand_chip *chip)
6698 if (chip->ecc.mode == NAND_ECC_SOFT &&
6699 chip->ecc.algo == NAND_ECC_BCH)
6700 nand_bch_free((struct nand_bch_control *)chip->ecc.priv);
6702 /* Free bad block table memory */
6704 kfree(chip->data_buf);
6705 kfree(chip->ecc.code_buf);
6706 kfree(chip->ecc.calc_buf);
6708 /* Free bad block descriptor memory */
6709 if (chip->badblock_pattern && chip->badblock_pattern->options
6710 & NAND_BBT_DYNAMICSTRUCT)
6711 kfree(chip->badblock_pattern);
6713 /* Free manufacturer priv data. */
6714 nand_manufacturer_cleanup(chip);
6716 EXPORT_SYMBOL_GPL(nand_cleanup);
6719 * nand_release - [NAND Interface] Unregister the MTD device and free resources
6720 * held by the NAND device
6721 * @mtd: MTD device structure
6723 void nand_release(struct mtd_info *mtd)
6725 mtd_device_unregister(mtd);
6726 nand_cleanup(mtd_to_nand(mtd));
6728 EXPORT_SYMBOL_GPL(nand_release);
6730 MODULE_LICENSE("GPL");
6731 MODULE_AUTHOR("Steven J. Hill <sjhill@realitydiluted.com>");
6732 MODULE_AUTHOR("Thomas Gleixner <tglx@linutronix.de>");
6733 MODULE_DESCRIPTION("Generic NAND flash driver code");