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/types.h>
40 #include <linux/mtd/mtd.h>
41 #include <linux/mtd/nand.h>
42 #include <linux/mtd/nand_ecc.h>
43 #include <linux/mtd/nand_bch.h>
44 #include <linux/interrupt.h>
45 #include <linux/bitops.h>
46 #include <linux/leds.h>
48 #include <linux/mtd/partitions.h>
49 #include <linux/of_mtd.h>
51 /* Define default oob placement schemes for large and small page devices */
52 static struct nand_ecclayout nand_oob_8 = {
62 static struct nand_ecclayout nand_oob_16 = {
64 .eccpos = {0, 1, 2, 3, 6, 7},
70 static struct nand_ecclayout nand_oob_64 = {
73 40, 41, 42, 43, 44, 45, 46, 47,
74 48, 49, 50, 51, 52, 53, 54, 55,
75 56, 57, 58, 59, 60, 61, 62, 63},
81 static struct nand_ecclayout nand_oob_128 = {
84 80, 81, 82, 83, 84, 85, 86, 87,
85 88, 89, 90, 91, 92, 93, 94, 95,
86 96, 97, 98, 99, 100, 101, 102, 103,
87 104, 105, 106, 107, 108, 109, 110, 111,
88 112, 113, 114, 115, 116, 117, 118, 119,
89 120, 121, 122, 123, 124, 125, 126, 127},
95 static int nand_get_device(struct mtd_info *mtd, int new_state);
97 static int nand_do_write_oob(struct mtd_info *mtd, loff_t to,
98 struct mtd_oob_ops *ops);
101 * For devices which display every fart in the system on a separate LED. Is
102 * compiled away when LED support is disabled.
104 DEFINE_LED_TRIGGER(nand_led_trigger);
106 static int check_offs_len(struct mtd_info *mtd,
107 loff_t ofs, uint64_t len)
109 struct nand_chip *chip = mtd_to_nand(mtd);
112 /* Start address must align on block boundary */
113 if (ofs & ((1ULL << chip->phys_erase_shift) - 1)) {
114 pr_debug("%s: unaligned address\n", __func__);
118 /* Length must align on block boundary */
119 if (len & ((1ULL << chip->phys_erase_shift) - 1)) {
120 pr_debug("%s: length not block aligned\n", __func__);
128 * nand_release_device - [GENERIC] release chip
129 * @mtd: MTD device structure
131 * Release chip lock and wake up anyone waiting on the device.
133 static void nand_release_device(struct mtd_info *mtd)
135 struct nand_chip *chip = mtd_to_nand(mtd);
137 /* Release the controller and the chip */
138 spin_lock(&chip->controller->lock);
139 chip->controller->active = NULL;
140 chip->state = FL_READY;
141 wake_up(&chip->controller->wq);
142 spin_unlock(&chip->controller->lock);
146 * nand_read_byte - [DEFAULT] read one byte from the chip
147 * @mtd: MTD device structure
149 * Default read function for 8bit buswidth
151 static uint8_t nand_read_byte(struct mtd_info *mtd)
153 struct nand_chip *chip = mtd_to_nand(mtd);
154 return readb(chip->IO_ADDR_R);
158 * nand_read_byte16 - [DEFAULT] read one byte endianness aware from the chip
159 * @mtd: MTD device structure
161 * Default read function for 16bit buswidth with endianness conversion.
164 static uint8_t nand_read_byte16(struct mtd_info *mtd)
166 struct nand_chip *chip = mtd_to_nand(mtd);
167 return (uint8_t) cpu_to_le16(readw(chip->IO_ADDR_R));
171 * nand_read_word - [DEFAULT] read one word from the chip
172 * @mtd: MTD device structure
174 * Default read function for 16bit buswidth without endianness conversion.
176 static u16 nand_read_word(struct mtd_info *mtd)
178 struct nand_chip *chip = mtd_to_nand(mtd);
179 return readw(chip->IO_ADDR_R);
183 * nand_select_chip - [DEFAULT] control CE line
184 * @mtd: MTD device structure
185 * @chipnr: chipnumber to select, -1 for deselect
187 * Default select function for 1 chip devices.
189 static void nand_select_chip(struct mtd_info *mtd, int chipnr)
191 struct nand_chip *chip = mtd_to_nand(mtd);
195 chip->cmd_ctrl(mtd, NAND_CMD_NONE, 0 | NAND_CTRL_CHANGE);
206 * nand_write_byte - [DEFAULT] write single byte to chip
207 * @mtd: MTD device structure
208 * @byte: value to write
210 * Default function to write a byte to I/O[7:0]
212 static void nand_write_byte(struct mtd_info *mtd, uint8_t byte)
214 struct nand_chip *chip = mtd_to_nand(mtd);
216 chip->write_buf(mtd, &byte, 1);
220 * nand_write_byte16 - [DEFAULT] write single byte to a chip with width 16
221 * @mtd: MTD device structure
222 * @byte: value to write
224 * Default function to write a byte to I/O[7:0] on a 16-bit wide chip.
226 static void nand_write_byte16(struct mtd_info *mtd, uint8_t byte)
228 struct nand_chip *chip = mtd_to_nand(mtd);
229 uint16_t word = byte;
232 * It's not entirely clear what should happen to I/O[15:8] when writing
233 * a byte. The ONFi spec (Revision 3.1; 2012-09-19, Section 2.16) reads:
235 * When the host supports a 16-bit bus width, only data is
236 * transferred at the 16-bit width. All address and command line
237 * transfers shall use only the lower 8-bits of the data bus. During
238 * command transfers, the host may place any value on the upper
239 * 8-bits of the data bus. During address transfers, the host shall
240 * set the upper 8-bits of the data bus to 00h.
242 * One user of the write_byte callback is nand_onfi_set_features. The
243 * four parameters are specified to be written to I/O[7:0], but this is
244 * neither an address nor a command transfer. Let's assume a 0 on the
245 * upper I/O lines is OK.
247 chip->write_buf(mtd, (uint8_t *)&word, 2);
251 * nand_write_buf - [DEFAULT] write buffer to chip
252 * @mtd: MTD device structure
254 * @len: number of bytes to write
256 * Default write function for 8bit buswidth.
258 static void nand_write_buf(struct mtd_info *mtd, const uint8_t *buf, int len)
260 struct nand_chip *chip = mtd_to_nand(mtd);
262 iowrite8_rep(chip->IO_ADDR_W, buf, len);
266 * nand_read_buf - [DEFAULT] read chip data into buffer
267 * @mtd: MTD device structure
268 * @buf: buffer to store date
269 * @len: number of bytes to read
271 * Default read function for 8bit buswidth.
273 static void nand_read_buf(struct mtd_info *mtd, uint8_t *buf, int len)
275 struct nand_chip *chip = mtd_to_nand(mtd);
277 ioread8_rep(chip->IO_ADDR_R, buf, len);
281 * nand_write_buf16 - [DEFAULT] write buffer to chip
282 * @mtd: MTD device structure
284 * @len: number of bytes to write
286 * Default write function for 16bit buswidth.
288 static void nand_write_buf16(struct mtd_info *mtd, const uint8_t *buf, int len)
290 struct nand_chip *chip = mtd_to_nand(mtd);
291 u16 *p = (u16 *) buf;
293 iowrite16_rep(chip->IO_ADDR_W, p, len >> 1);
297 * nand_read_buf16 - [DEFAULT] read chip data into buffer
298 * @mtd: MTD device structure
299 * @buf: buffer to store date
300 * @len: number of bytes to read
302 * Default read function for 16bit buswidth.
304 static void nand_read_buf16(struct mtd_info *mtd, uint8_t *buf, int len)
306 struct nand_chip *chip = mtd_to_nand(mtd);
307 u16 *p = (u16 *) buf;
309 ioread16_rep(chip->IO_ADDR_R, p, len >> 1);
313 * nand_block_bad - [DEFAULT] Read bad block marker from the chip
314 * @mtd: MTD device structure
315 * @ofs: offset from device start
316 * @getchip: 0, if the chip is already selected
318 * Check, if the block is bad.
320 static int nand_block_bad(struct mtd_info *mtd, loff_t ofs)
322 int page, res = 0, i = 0;
323 struct nand_chip *chip = mtd_to_nand(mtd);
326 if (chip->bbt_options & NAND_BBT_SCANLASTPAGE)
327 ofs += mtd->erasesize - mtd->writesize;
329 page = (int)(ofs >> chip->page_shift) & chip->pagemask;
332 if (chip->options & NAND_BUSWIDTH_16) {
333 chip->cmdfunc(mtd, NAND_CMD_READOOB,
334 chip->badblockpos & 0xFE, page);
335 bad = cpu_to_le16(chip->read_word(mtd));
336 if (chip->badblockpos & 0x1)
341 chip->cmdfunc(mtd, NAND_CMD_READOOB, chip->badblockpos,
343 bad = chip->read_byte(mtd);
346 if (likely(chip->badblockbits == 8))
349 res = hweight8(bad) < chip->badblockbits;
350 ofs += mtd->writesize;
351 page = (int)(ofs >> chip->page_shift) & chip->pagemask;
353 } while (!res && i < 2 && (chip->bbt_options & NAND_BBT_SCAN2NDPAGE));
359 * nand_default_block_markbad - [DEFAULT] mark a block bad via bad block marker
360 * @mtd: MTD device structure
361 * @ofs: offset from device start
363 * This is the default implementation, which can be overridden by a hardware
364 * specific driver. It provides the details for writing a bad block marker to a
367 static int nand_default_block_markbad(struct mtd_info *mtd, loff_t ofs)
369 struct nand_chip *chip = mtd_to_nand(mtd);
370 struct mtd_oob_ops ops;
371 uint8_t buf[2] = { 0, 0 };
372 int ret = 0, res, i = 0;
374 memset(&ops, 0, sizeof(ops));
376 ops.ooboffs = chip->badblockpos;
377 if (chip->options & NAND_BUSWIDTH_16) {
378 ops.ooboffs &= ~0x01;
379 ops.len = ops.ooblen = 2;
381 ops.len = ops.ooblen = 1;
383 ops.mode = MTD_OPS_PLACE_OOB;
385 /* Write to first/last page(s) if necessary */
386 if (chip->bbt_options & NAND_BBT_SCANLASTPAGE)
387 ofs += mtd->erasesize - mtd->writesize;
389 res = nand_do_write_oob(mtd, ofs, &ops);
394 ofs += mtd->writesize;
395 } while ((chip->bbt_options & NAND_BBT_SCAN2NDPAGE) && i < 2);
401 * nand_block_markbad_lowlevel - mark a block bad
402 * @mtd: MTD device structure
403 * @ofs: offset from device start
405 * This function performs the generic NAND bad block marking steps (i.e., bad
406 * block table(s) and/or marker(s)). We only allow the hardware driver to
407 * specify how to write bad block markers to OOB (chip->block_markbad).
409 * We try operations in the following order:
410 * (1) erase the affected block, to allow OOB marker to be written cleanly
411 * (2) write bad block marker to OOB area of affected block (unless flag
412 * NAND_BBT_NO_OOB_BBM is present)
414 * Note that we retain the first error encountered in (2) or (3), finish the
415 * procedures, and dump the error in the end.
417 static int nand_block_markbad_lowlevel(struct mtd_info *mtd, loff_t ofs)
419 struct nand_chip *chip = mtd_to_nand(mtd);
422 if (!(chip->bbt_options & NAND_BBT_NO_OOB_BBM)) {
423 struct erase_info einfo;
425 /* Attempt erase before marking OOB */
426 memset(&einfo, 0, sizeof(einfo));
429 einfo.len = 1ULL << chip->phys_erase_shift;
430 nand_erase_nand(mtd, &einfo, 0);
432 /* Write bad block marker to OOB */
433 nand_get_device(mtd, FL_WRITING);
434 ret = chip->block_markbad(mtd, ofs);
435 nand_release_device(mtd);
438 /* Mark block bad in BBT */
440 res = nand_markbad_bbt(mtd, ofs);
446 mtd->ecc_stats.badblocks++;
452 * nand_check_wp - [GENERIC] check if the chip is write protected
453 * @mtd: MTD device structure
455 * Check, if the device is write protected. The function expects, that the
456 * device is already selected.
458 static int nand_check_wp(struct mtd_info *mtd)
460 struct nand_chip *chip = mtd_to_nand(mtd);
462 /* Broken xD cards report WP despite being writable */
463 if (chip->options & NAND_BROKEN_XD)
466 /* Check the WP bit */
467 chip->cmdfunc(mtd, NAND_CMD_STATUS, -1, -1);
468 return (chip->read_byte(mtd) & NAND_STATUS_WP) ? 0 : 1;
472 * nand_block_isreserved - [GENERIC] Check if a block is marked reserved.
473 * @mtd: MTD device structure
474 * @ofs: offset from device start
476 * Check if the block is marked as reserved.
478 static int nand_block_isreserved(struct mtd_info *mtd, loff_t ofs)
480 struct nand_chip *chip = mtd_to_nand(mtd);
484 /* Return info from the table */
485 return nand_isreserved_bbt(mtd, ofs);
489 * nand_block_checkbad - [GENERIC] Check if a block is marked bad
490 * @mtd: MTD device structure
491 * @ofs: offset from device start
492 * @allowbbt: 1, if its allowed to access the bbt area
494 * Check, if the block is bad. Either by reading the bad block table or
495 * calling of the scan function.
497 static int nand_block_checkbad(struct mtd_info *mtd, loff_t ofs, int allowbbt)
499 struct nand_chip *chip = mtd_to_nand(mtd);
502 return chip->block_bad(mtd, ofs);
504 /* Return info from the table */
505 return nand_isbad_bbt(mtd, ofs, allowbbt);
509 * panic_nand_wait_ready - [GENERIC] Wait for the ready pin after commands.
510 * @mtd: MTD device structure
513 * Helper function for nand_wait_ready used when needing to wait in interrupt
516 static void panic_nand_wait_ready(struct mtd_info *mtd, unsigned long timeo)
518 struct nand_chip *chip = mtd_to_nand(mtd);
521 /* Wait for the device to get ready */
522 for (i = 0; i < timeo; i++) {
523 if (chip->dev_ready(mtd))
525 touch_softlockup_watchdog();
531 * nand_wait_ready - [GENERIC] Wait for the ready pin after commands.
532 * @mtd: MTD device structure
534 * Wait for the ready pin after a command, and warn if a timeout occurs.
536 void nand_wait_ready(struct mtd_info *mtd)
538 struct nand_chip *chip = mtd_to_nand(mtd);
539 unsigned long timeo = 400;
541 if (in_interrupt() || oops_in_progress)
542 return panic_nand_wait_ready(mtd, timeo);
544 led_trigger_event(nand_led_trigger, LED_FULL);
545 /* Wait until command is processed or timeout occurs */
546 timeo = jiffies + msecs_to_jiffies(timeo);
548 if (chip->dev_ready(mtd))
551 } while (time_before(jiffies, timeo));
553 if (!chip->dev_ready(mtd))
554 pr_warn_ratelimited("timeout while waiting for chip to become ready\n");
556 led_trigger_event(nand_led_trigger, LED_OFF);
558 EXPORT_SYMBOL_GPL(nand_wait_ready);
561 * nand_wait_status_ready - [GENERIC] Wait for the ready status after commands.
562 * @mtd: MTD device structure
563 * @timeo: Timeout in ms
565 * Wait for status ready (i.e. command done) or timeout.
567 static void nand_wait_status_ready(struct mtd_info *mtd, unsigned long timeo)
569 register struct nand_chip *chip = mtd_to_nand(mtd);
571 timeo = jiffies + msecs_to_jiffies(timeo);
573 if ((chip->read_byte(mtd) & NAND_STATUS_READY))
575 touch_softlockup_watchdog();
576 } while (time_before(jiffies, timeo));
580 * nand_command - [DEFAULT] Send command to NAND device
581 * @mtd: MTD device structure
582 * @command: the command to be sent
583 * @column: the column address for this command, -1 if none
584 * @page_addr: the page address for this command, -1 if none
586 * Send command to NAND device. This function is used for small page devices
587 * (512 Bytes per page).
589 static void nand_command(struct mtd_info *mtd, unsigned int command,
590 int column, int page_addr)
592 register struct nand_chip *chip = mtd_to_nand(mtd);
593 int ctrl = NAND_CTRL_CLE | NAND_CTRL_CHANGE;
595 /* Write out the command to the device */
596 if (command == NAND_CMD_SEQIN) {
599 if (column >= mtd->writesize) {
601 column -= mtd->writesize;
602 readcmd = NAND_CMD_READOOB;
603 } else if (column < 256) {
604 /* First 256 bytes --> READ0 */
605 readcmd = NAND_CMD_READ0;
608 readcmd = NAND_CMD_READ1;
610 chip->cmd_ctrl(mtd, readcmd, ctrl);
611 ctrl &= ~NAND_CTRL_CHANGE;
613 chip->cmd_ctrl(mtd, command, ctrl);
615 /* Address cycle, when necessary */
616 ctrl = NAND_CTRL_ALE | NAND_CTRL_CHANGE;
617 /* Serially input address */
619 /* Adjust columns for 16 bit buswidth */
620 if (chip->options & NAND_BUSWIDTH_16 &&
621 !nand_opcode_8bits(command))
623 chip->cmd_ctrl(mtd, column, ctrl);
624 ctrl &= ~NAND_CTRL_CHANGE;
626 if (page_addr != -1) {
627 chip->cmd_ctrl(mtd, page_addr, ctrl);
628 ctrl &= ~NAND_CTRL_CHANGE;
629 chip->cmd_ctrl(mtd, page_addr >> 8, ctrl);
630 /* One more address cycle for devices > 32MiB */
631 if (chip->chipsize > (32 << 20))
632 chip->cmd_ctrl(mtd, page_addr >> 16, ctrl);
634 chip->cmd_ctrl(mtd, NAND_CMD_NONE, NAND_NCE | NAND_CTRL_CHANGE);
637 * Program and erase have their own busy handlers status and sequential
642 case NAND_CMD_PAGEPROG:
643 case NAND_CMD_ERASE1:
644 case NAND_CMD_ERASE2:
646 case NAND_CMD_STATUS:
652 udelay(chip->chip_delay);
653 chip->cmd_ctrl(mtd, NAND_CMD_STATUS,
654 NAND_CTRL_CLE | NAND_CTRL_CHANGE);
656 NAND_CMD_NONE, NAND_NCE | NAND_CTRL_CHANGE);
657 /* EZ-NAND can take upto 250ms as per ONFi v4.0 */
658 nand_wait_status_ready(mtd, 250);
661 /* This applies to read commands */
664 * If we don't have access to the busy pin, we apply the given
667 if (!chip->dev_ready) {
668 udelay(chip->chip_delay);
673 * Apply this short delay always to ensure that we do wait tWB in
674 * any case on any machine.
678 nand_wait_ready(mtd);
682 * nand_command_lp - [DEFAULT] Send command to NAND large page device
683 * @mtd: MTD device structure
684 * @command: the command to be sent
685 * @column: the column address for this command, -1 if none
686 * @page_addr: the page address for this command, -1 if none
688 * Send command to NAND device. This is the version for the new large page
689 * devices. We don't have the separate regions as we have in the small page
690 * devices. We must emulate NAND_CMD_READOOB to keep the code compatible.
692 static void nand_command_lp(struct mtd_info *mtd, unsigned int command,
693 int column, int page_addr)
695 register struct nand_chip *chip = mtd_to_nand(mtd);
697 /* Emulate NAND_CMD_READOOB */
698 if (command == NAND_CMD_READOOB) {
699 column += mtd->writesize;
700 command = NAND_CMD_READ0;
703 /* Command latch cycle */
704 chip->cmd_ctrl(mtd, command, NAND_NCE | NAND_CLE | NAND_CTRL_CHANGE);
706 if (column != -1 || page_addr != -1) {
707 int ctrl = NAND_CTRL_CHANGE | NAND_NCE | NAND_ALE;
709 /* Serially input address */
711 /* Adjust columns for 16 bit buswidth */
712 if (chip->options & NAND_BUSWIDTH_16 &&
713 !nand_opcode_8bits(command))
715 chip->cmd_ctrl(mtd, column, ctrl);
716 ctrl &= ~NAND_CTRL_CHANGE;
717 chip->cmd_ctrl(mtd, column >> 8, ctrl);
719 if (page_addr != -1) {
720 chip->cmd_ctrl(mtd, page_addr, ctrl);
721 chip->cmd_ctrl(mtd, page_addr >> 8,
722 NAND_NCE | NAND_ALE);
723 /* One more address cycle for devices > 128MiB */
724 if (chip->chipsize > (128 << 20))
725 chip->cmd_ctrl(mtd, page_addr >> 16,
726 NAND_NCE | NAND_ALE);
729 chip->cmd_ctrl(mtd, NAND_CMD_NONE, NAND_NCE | NAND_CTRL_CHANGE);
732 * Program and erase have their own busy handlers status, sequential
733 * in and status need no delay.
737 case NAND_CMD_CACHEDPROG:
738 case NAND_CMD_PAGEPROG:
739 case NAND_CMD_ERASE1:
740 case NAND_CMD_ERASE2:
743 case NAND_CMD_STATUS:
749 udelay(chip->chip_delay);
750 chip->cmd_ctrl(mtd, NAND_CMD_STATUS,
751 NAND_NCE | NAND_CLE | NAND_CTRL_CHANGE);
752 chip->cmd_ctrl(mtd, NAND_CMD_NONE,
753 NAND_NCE | NAND_CTRL_CHANGE);
754 /* EZ-NAND can take upto 250ms as per ONFi v4.0 */
755 nand_wait_status_ready(mtd, 250);
758 case NAND_CMD_RNDOUT:
759 /* No ready / busy check necessary */
760 chip->cmd_ctrl(mtd, NAND_CMD_RNDOUTSTART,
761 NAND_NCE | NAND_CLE | NAND_CTRL_CHANGE);
762 chip->cmd_ctrl(mtd, NAND_CMD_NONE,
763 NAND_NCE | NAND_CTRL_CHANGE);
767 chip->cmd_ctrl(mtd, NAND_CMD_READSTART,
768 NAND_NCE | NAND_CLE | NAND_CTRL_CHANGE);
769 chip->cmd_ctrl(mtd, NAND_CMD_NONE,
770 NAND_NCE | NAND_CTRL_CHANGE);
772 /* This applies to read commands */
775 * If we don't have access to the busy pin, we apply the given
778 if (!chip->dev_ready) {
779 udelay(chip->chip_delay);
785 * Apply this short delay always to ensure that we do wait tWB in
786 * any case on any machine.
790 nand_wait_ready(mtd);
794 * panic_nand_get_device - [GENERIC] Get chip for selected access
795 * @chip: the nand chip descriptor
796 * @mtd: MTD device structure
797 * @new_state: the state which is requested
799 * Used when in panic, no locks are taken.
801 static void panic_nand_get_device(struct nand_chip *chip,
802 struct mtd_info *mtd, int new_state)
804 /* Hardware controller shared among independent devices */
805 chip->controller->active = chip;
806 chip->state = new_state;
810 * nand_get_device - [GENERIC] Get chip for selected access
811 * @mtd: MTD device structure
812 * @new_state: the state which is requested
814 * Get the device and lock it for exclusive access
817 nand_get_device(struct mtd_info *mtd, int new_state)
819 struct nand_chip *chip = mtd_to_nand(mtd);
820 spinlock_t *lock = &chip->controller->lock;
821 wait_queue_head_t *wq = &chip->controller->wq;
822 DECLARE_WAITQUEUE(wait, current);
826 /* Hardware controller shared among independent devices */
827 if (!chip->controller->active)
828 chip->controller->active = chip;
830 if (chip->controller->active == chip && chip->state == FL_READY) {
831 chip->state = new_state;
835 if (new_state == FL_PM_SUSPENDED) {
836 if (chip->controller->active->state == FL_PM_SUSPENDED) {
837 chip->state = FL_PM_SUSPENDED;
842 set_current_state(TASK_UNINTERRUPTIBLE);
843 add_wait_queue(wq, &wait);
846 remove_wait_queue(wq, &wait);
851 * panic_nand_wait - [GENERIC] wait until the command is done
852 * @mtd: MTD device structure
853 * @chip: NAND chip structure
856 * Wait for command done. This is a helper function for nand_wait used when
857 * we are in interrupt context. May happen when in panic and trying to write
858 * an oops through mtdoops.
860 static void panic_nand_wait(struct mtd_info *mtd, struct nand_chip *chip,
864 for (i = 0; i < timeo; i++) {
865 if (chip->dev_ready) {
866 if (chip->dev_ready(mtd))
869 if (chip->read_byte(mtd) & NAND_STATUS_READY)
877 * nand_wait - [DEFAULT] wait until the command is done
878 * @mtd: MTD device structure
879 * @chip: NAND chip structure
881 * Wait for command done. This applies to erase and program only.
883 static int nand_wait(struct mtd_info *mtd, struct nand_chip *chip)
887 unsigned long timeo = 400;
889 led_trigger_event(nand_led_trigger, LED_FULL);
892 * Apply this short delay always to ensure that we do wait tWB in any
893 * case on any machine.
897 chip->cmdfunc(mtd, NAND_CMD_STATUS, -1, -1);
899 if (in_interrupt() || oops_in_progress)
900 panic_nand_wait(mtd, chip, timeo);
902 timeo = jiffies + msecs_to_jiffies(timeo);
904 if (chip->dev_ready) {
905 if (chip->dev_ready(mtd))
908 if (chip->read_byte(mtd) & NAND_STATUS_READY)
912 } while (time_before(jiffies, timeo));
914 led_trigger_event(nand_led_trigger, LED_OFF);
916 status = (int)chip->read_byte(mtd);
917 /* This can happen if in case of timeout or buggy dev_ready */
918 WARN_ON(!(status & NAND_STATUS_READY));
923 * __nand_unlock - [REPLACEABLE] unlocks specified locked blocks
925 * @ofs: offset to start unlock from
926 * @len: length to unlock
927 * @invert: when = 0, unlock the range of blocks within the lower and
928 * upper boundary address
929 * when = 1, unlock the range of blocks outside the boundaries
930 * of the lower and upper boundary address
932 * Returs unlock status.
934 static int __nand_unlock(struct mtd_info *mtd, loff_t ofs,
935 uint64_t len, int invert)
939 struct nand_chip *chip = mtd_to_nand(mtd);
941 /* Submit address of first page to unlock */
942 page = ofs >> chip->page_shift;
943 chip->cmdfunc(mtd, NAND_CMD_UNLOCK1, -1, page & chip->pagemask);
945 /* Submit address of last page to unlock */
946 page = (ofs + len) >> chip->page_shift;
947 chip->cmdfunc(mtd, NAND_CMD_UNLOCK2, -1,
948 (page | invert) & chip->pagemask);
950 /* Call wait ready function */
951 status = chip->waitfunc(mtd, chip);
952 /* See if device thinks it succeeded */
953 if (status & NAND_STATUS_FAIL) {
954 pr_debug("%s: error status = 0x%08x\n",
963 * nand_unlock - [REPLACEABLE] unlocks specified locked blocks
965 * @ofs: offset to start unlock from
966 * @len: length to unlock
968 * Returns unlock status.
970 int nand_unlock(struct mtd_info *mtd, loff_t ofs, uint64_t len)
974 struct nand_chip *chip = mtd_to_nand(mtd);
976 pr_debug("%s: start = 0x%012llx, len = %llu\n",
977 __func__, (unsigned long long)ofs, len);
979 if (check_offs_len(mtd, ofs, len))
982 /* Align to last block address if size addresses end of the device */
983 if (ofs + len == mtd->size)
984 len -= mtd->erasesize;
986 nand_get_device(mtd, FL_UNLOCKING);
988 /* Shift to get chip number */
989 chipnr = ofs >> chip->chip_shift;
991 chip->select_chip(mtd, chipnr);
995 * If we want to check the WP through READ STATUS and check the bit 7
996 * we must reset the chip
997 * some operation can also clear the bit 7 of status register
998 * eg. erase/program a locked block
1000 chip->cmdfunc(mtd, NAND_CMD_RESET, -1, -1);
1002 /* Check, if it is write protected */
1003 if (nand_check_wp(mtd)) {
1004 pr_debug("%s: device is write protected!\n",
1010 ret = __nand_unlock(mtd, ofs, len, 0);
1013 chip->select_chip(mtd, -1);
1014 nand_release_device(mtd);
1018 EXPORT_SYMBOL(nand_unlock);
1021 * nand_lock - [REPLACEABLE] locks all blocks present in the device
1023 * @ofs: offset to start unlock from
1024 * @len: length to unlock
1026 * This feature is not supported in many NAND parts. 'Micron' NAND parts do
1027 * have this feature, but it allows only to lock all blocks, not for specified
1028 * range for block. Implementing 'lock' feature by making use of 'unlock', for
1031 * Returns lock status.
1033 int nand_lock(struct mtd_info *mtd, loff_t ofs, uint64_t len)
1036 int chipnr, status, page;
1037 struct nand_chip *chip = mtd_to_nand(mtd);
1039 pr_debug("%s: start = 0x%012llx, len = %llu\n",
1040 __func__, (unsigned long long)ofs, len);
1042 if (check_offs_len(mtd, ofs, len))
1045 nand_get_device(mtd, FL_LOCKING);
1047 /* Shift to get chip number */
1048 chipnr = ofs >> chip->chip_shift;
1050 chip->select_chip(mtd, chipnr);
1054 * If we want to check the WP through READ STATUS and check the bit 7
1055 * we must reset the chip
1056 * some operation can also clear the bit 7 of status register
1057 * eg. erase/program a locked block
1059 chip->cmdfunc(mtd, NAND_CMD_RESET, -1, -1);
1061 /* Check, if it is write protected */
1062 if (nand_check_wp(mtd)) {
1063 pr_debug("%s: device is write protected!\n",
1065 status = MTD_ERASE_FAILED;
1070 /* Submit address of first page to lock */
1071 page = ofs >> chip->page_shift;
1072 chip->cmdfunc(mtd, NAND_CMD_LOCK, -1, page & chip->pagemask);
1074 /* Call wait ready function */
1075 status = chip->waitfunc(mtd, chip);
1076 /* See if device thinks it succeeded */
1077 if (status & NAND_STATUS_FAIL) {
1078 pr_debug("%s: error status = 0x%08x\n",
1084 ret = __nand_unlock(mtd, ofs, len, 0x1);
1087 chip->select_chip(mtd, -1);
1088 nand_release_device(mtd);
1092 EXPORT_SYMBOL(nand_lock);
1095 * nand_check_erased_buf - check if a buffer contains (almost) only 0xff data
1096 * @buf: buffer to test
1097 * @len: buffer length
1098 * @bitflips_threshold: maximum number of bitflips
1100 * Check if a buffer contains only 0xff, which means the underlying region
1101 * has been erased and is ready to be programmed.
1102 * The bitflips_threshold specify the maximum number of bitflips before
1103 * considering the region is not erased.
1104 * Note: The logic of this function has been extracted from the memweight
1105 * implementation, except that nand_check_erased_buf function exit before
1106 * testing the whole buffer if the number of bitflips exceed the
1107 * bitflips_threshold value.
1109 * Returns a positive number of bitflips less than or equal to
1110 * bitflips_threshold, or -ERROR_CODE for bitflips in excess of the
1113 static int nand_check_erased_buf(void *buf, int len, int bitflips_threshold)
1115 const unsigned char *bitmap = buf;
1119 for (; len && ((uintptr_t)bitmap) % sizeof(long);
1121 weight = hweight8(*bitmap);
1122 bitflips += BITS_PER_BYTE - weight;
1123 if (unlikely(bitflips > bitflips_threshold))
1127 for (; len >= sizeof(long);
1128 len -= sizeof(long), bitmap += sizeof(long)) {
1129 weight = hweight_long(*((unsigned long *)bitmap));
1130 bitflips += BITS_PER_LONG - weight;
1131 if (unlikely(bitflips > bitflips_threshold))
1135 for (; len > 0; len--, bitmap++) {
1136 weight = hweight8(*bitmap);
1137 bitflips += BITS_PER_BYTE - weight;
1138 if (unlikely(bitflips > bitflips_threshold))
1146 * nand_check_erased_ecc_chunk - check if an ECC chunk contains (almost) only
1148 * @data: data buffer to test
1149 * @datalen: data length
1151 * @ecclen: ECC length
1152 * @extraoob: extra OOB buffer
1153 * @extraooblen: extra OOB length
1154 * @bitflips_threshold: maximum number of bitflips
1156 * Check if a data buffer and its associated ECC and OOB data contains only
1157 * 0xff pattern, which means the underlying region has been erased and is
1158 * ready to be programmed.
1159 * The bitflips_threshold specify the maximum number of bitflips before
1160 * considering the region as not erased.
1163 * 1/ ECC algorithms are working on pre-defined block sizes which are usually
1164 * different from the NAND page size. When fixing bitflips, ECC engines will
1165 * report the number of errors per chunk, and the NAND core infrastructure
1166 * expect you to return the maximum number of bitflips for the whole page.
1167 * This is why you should always use this function on a single chunk and
1168 * not on the whole page. After checking each chunk you should update your
1169 * max_bitflips value accordingly.
1170 * 2/ When checking for bitflips in erased pages you should not only check
1171 * the payload data but also their associated ECC data, because a user might
1172 * have programmed almost all bits to 1 but a few. In this case, we
1173 * shouldn't consider the chunk as erased, and checking ECC bytes prevent
1175 * 3/ The extraoob argument is optional, and should be used if some of your OOB
1176 * data are protected by the ECC engine.
1177 * It could also be used if you support subpages and want to attach some
1178 * extra OOB data to an ECC chunk.
1180 * Returns a positive number of bitflips less than or equal to
1181 * bitflips_threshold, or -ERROR_CODE for bitflips in excess of the
1182 * threshold. In case of success, the passed buffers are filled with 0xff.
1184 int nand_check_erased_ecc_chunk(void *data, int datalen,
1185 void *ecc, int ecclen,
1186 void *extraoob, int extraooblen,
1187 int bitflips_threshold)
1189 int data_bitflips = 0, ecc_bitflips = 0, extraoob_bitflips = 0;
1191 data_bitflips = nand_check_erased_buf(data, datalen,
1192 bitflips_threshold);
1193 if (data_bitflips < 0)
1194 return data_bitflips;
1196 bitflips_threshold -= data_bitflips;
1198 ecc_bitflips = nand_check_erased_buf(ecc, ecclen, bitflips_threshold);
1199 if (ecc_bitflips < 0)
1200 return ecc_bitflips;
1202 bitflips_threshold -= ecc_bitflips;
1204 extraoob_bitflips = nand_check_erased_buf(extraoob, extraooblen,
1205 bitflips_threshold);
1206 if (extraoob_bitflips < 0)
1207 return extraoob_bitflips;
1210 memset(data, 0xff, datalen);
1213 memset(ecc, 0xff, ecclen);
1215 if (extraoob_bitflips)
1216 memset(extraoob, 0xff, extraooblen);
1218 return data_bitflips + ecc_bitflips + extraoob_bitflips;
1220 EXPORT_SYMBOL(nand_check_erased_ecc_chunk);
1223 * nand_read_page_raw - [INTERN] read raw page data without ecc
1224 * @mtd: mtd info structure
1225 * @chip: nand chip info structure
1226 * @buf: buffer to store read data
1227 * @oob_required: caller requires OOB data read to chip->oob_poi
1228 * @page: page number to read
1230 * Not for syndrome calculating ECC controllers, which use a special oob layout.
1232 static int nand_read_page_raw(struct mtd_info *mtd, struct nand_chip *chip,
1233 uint8_t *buf, int oob_required, int page)
1235 chip->read_buf(mtd, buf, mtd->writesize);
1237 chip->read_buf(mtd, chip->oob_poi, mtd->oobsize);
1242 * nand_read_page_raw_syndrome - [INTERN] read raw page data without ecc
1243 * @mtd: mtd info structure
1244 * @chip: nand chip info structure
1245 * @buf: buffer to store read data
1246 * @oob_required: caller requires OOB data read to chip->oob_poi
1247 * @page: page number to read
1249 * We need a special oob layout and handling even when OOB isn't used.
1251 static int nand_read_page_raw_syndrome(struct mtd_info *mtd,
1252 struct nand_chip *chip, uint8_t *buf,
1253 int oob_required, int page)
1255 int eccsize = chip->ecc.size;
1256 int eccbytes = chip->ecc.bytes;
1257 uint8_t *oob = chip->oob_poi;
1260 for (steps = chip->ecc.steps; steps > 0; steps--) {
1261 chip->read_buf(mtd, buf, eccsize);
1264 if (chip->ecc.prepad) {
1265 chip->read_buf(mtd, oob, chip->ecc.prepad);
1266 oob += chip->ecc.prepad;
1269 chip->read_buf(mtd, oob, eccbytes);
1272 if (chip->ecc.postpad) {
1273 chip->read_buf(mtd, oob, chip->ecc.postpad);
1274 oob += chip->ecc.postpad;
1278 size = mtd->oobsize - (oob - chip->oob_poi);
1280 chip->read_buf(mtd, oob, size);
1286 * nand_read_page_swecc - [REPLACEABLE] software ECC based page read function
1287 * @mtd: mtd info structure
1288 * @chip: nand chip info structure
1289 * @buf: buffer to store read data
1290 * @oob_required: caller requires OOB data read to chip->oob_poi
1291 * @page: page number to read
1293 static int nand_read_page_swecc(struct mtd_info *mtd, struct nand_chip *chip,
1294 uint8_t *buf, int oob_required, int page)
1296 int i, eccsize = chip->ecc.size;
1297 int eccbytes = chip->ecc.bytes;
1298 int eccsteps = chip->ecc.steps;
1300 uint8_t *ecc_calc = chip->buffers->ecccalc;
1301 uint8_t *ecc_code = chip->buffers->ecccode;
1302 uint32_t *eccpos = chip->ecc.layout->eccpos;
1303 unsigned int max_bitflips = 0;
1305 chip->ecc.read_page_raw(mtd, chip, buf, 1, page);
1307 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize)
1308 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
1310 for (i = 0; i < chip->ecc.total; i++)
1311 ecc_code[i] = chip->oob_poi[eccpos[i]];
1313 eccsteps = chip->ecc.steps;
1316 for (i = 0 ; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
1319 stat = chip->ecc.correct(mtd, p, &ecc_code[i], &ecc_calc[i]);
1321 mtd->ecc_stats.failed++;
1323 mtd->ecc_stats.corrected += stat;
1324 max_bitflips = max_t(unsigned int, max_bitflips, stat);
1327 return max_bitflips;
1331 * nand_read_subpage - [REPLACEABLE] ECC based sub-page read function
1332 * @mtd: mtd info structure
1333 * @chip: nand chip info structure
1334 * @data_offs: offset of requested data within the page
1335 * @readlen: data length
1336 * @bufpoi: buffer to store read data
1337 * @page: page number to read
1339 static int nand_read_subpage(struct mtd_info *mtd, struct nand_chip *chip,
1340 uint32_t data_offs, uint32_t readlen, uint8_t *bufpoi,
1343 int start_step, end_step, num_steps;
1344 uint32_t *eccpos = chip->ecc.layout->eccpos;
1346 int data_col_addr, i, gaps = 0;
1347 int datafrag_len, eccfrag_len, aligned_len, aligned_pos;
1348 int busw = (chip->options & NAND_BUSWIDTH_16) ? 2 : 1;
1350 unsigned int max_bitflips = 0;
1352 /* Column address within the page aligned to ECC size (256bytes) */
1353 start_step = data_offs / chip->ecc.size;
1354 end_step = (data_offs + readlen - 1) / chip->ecc.size;
1355 num_steps = end_step - start_step + 1;
1356 index = start_step * chip->ecc.bytes;
1358 /* Data size aligned to ECC ecc.size */
1359 datafrag_len = num_steps * chip->ecc.size;
1360 eccfrag_len = num_steps * chip->ecc.bytes;
1362 data_col_addr = start_step * chip->ecc.size;
1363 /* If we read not a page aligned data */
1364 if (data_col_addr != 0)
1365 chip->cmdfunc(mtd, NAND_CMD_RNDOUT, data_col_addr, -1);
1367 p = bufpoi + data_col_addr;
1368 chip->read_buf(mtd, p, datafrag_len);
1371 for (i = 0; i < eccfrag_len ; i += chip->ecc.bytes, p += chip->ecc.size)
1372 chip->ecc.calculate(mtd, p, &chip->buffers->ecccalc[i]);
1375 * The performance is faster if we position offsets according to
1376 * ecc.pos. Let's make sure that there are no gaps in ECC positions.
1378 for (i = 0; i < eccfrag_len - 1; i++) {
1379 if (eccpos[i + index] + 1 != eccpos[i + index + 1]) {
1385 chip->cmdfunc(mtd, NAND_CMD_RNDOUT, mtd->writesize, -1);
1386 chip->read_buf(mtd, chip->oob_poi, mtd->oobsize);
1389 * Send the command to read the particular ECC bytes take care
1390 * about buswidth alignment in read_buf.
1392 aligned_pos = eccpos[index] & ~(busw - 1);
1393 aligned_len = eccfrag_len;
1394 if (eccpos[index] & (busw - 1))
1396 if (eccpos[index + (num_steps * chip->ecc.bytes)] & (busw - 1))
1399 chip->cmdfunc(mtd, NAND_CMD_RNDOUT,
1400 mtd->writesize + aligned_pos, -1);
1401 chip->read_buf(mtd, &chip->oob_poi[aligned_pos], aligned_len);
1404 for (i = 0; i < eccfrag_len; i++)
1405 chip->buffers->ecccode[i] = chip->oob_poi[eccpos[i + index]];
1407 p = bufpoi + data_col_addr;
1408 for (i = 0; i < eccfrag_len ; i += chip->ecc.bytes, p += chip->ecc.size) {
1411 stat = chip->ecc.correct(mtd, p,
1412 &chip->buffers->ecccode[i], &chip->buffers->ecccalc[i]);
1413 if (stat == -EBADMSG &&
1414 (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
1415 /* check for empty pages with bitflips */
1416 stat = nand_check_erased_ecc_chunk(p, chip->ecc.size,
1417 &chip->buffers->ecccode[i],
1420 chip->ecc.strength);
1424 mtd->ecc_stats.failed++;
1426 mtd->ecc_stats.corrected += stat;
1427 max_bitflips = max_t(unsigned int, max_bitflips, stat);
1430 return max_bitflips;
1434 * nand_read_page_hwecc - [REPLACEABLE] hardware ECC based page read function
1435 * @mtd: mtd info structure
1436 * @chip: nand chip info structure
1437 * @buf: buffer to store read data
1438 * @oob_required: caller requires OOB data read to chip->oob_poi
1439 * @page: page number to read
1441 * Not for syndrome calculating ECC controllers which need a special oob layout.
1443 static int nand_read_page_hwecc(struct mtd_info *mtd, struct nand_chip *chip,
1444 uint8_t *buf, int oob_required, int page)
1446 int i, eccsize = chip->ecc.size;
1447 int eccbytes = chip->ecc.bytes;
1448 int eccsteps = chip->ecc.steps;
1450 uint8_t *ecc_calc = chip->buffers->ecccalc;
1451 uint8_t *ecc_code = chip->buffers->ecccode;
1452 uint32_t *eccpos = chip->ecc.layout->eccpos;
1453 unsigned int max_bitflips = 0;
1455 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
1456 chip->ecc.hwctl(mtd, NAND_ECC_READ);
1457 chip->read_buf(mtd, p, eccsize);
1458 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
1460 chip->read_buf(mtd, chip->oob_poi, mtd->oobsize);
1462 for (i = 0; i < chip->ecc.total; i++)
1463 ecc_code[i] = chip->oob_poi[eccpos[i]];
1465 eccsteps = chip->ecc.steps;
1468 for (i = 0 ; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
1471 stat = chip->ecc.correct(mtd, p, &ecc_code[i], &ecc_calc[i]);
1472 if (stat == -EBADMSG &&
1473 (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
1474 /* check for empty pages with bitflips */
1475 stat = nand_check_erased_ecc_chunk(p, eccsize,
1476 &ecc_code[i], eccbytes,
1478 chip->ecc.strength);
1482 mtd->ecc_stats.failed++;
1484 mtd->ecc_stats.corrected += stat;
1485 max_bitflips = max_t(unsigned int, max_bitflips, stat);
1488 return max_bitflips;
1492 * nand_read_page_hwecc_oob_first - [REPLACEABLE] hw ecc, read oob first
1493 * @mtd: mtd info structure
1494 * @chip: nand chip info structure
1495 * @buf: buffer to store read data
1496 * @oob_required: caller requires OOB data read to chip->oob_poi
1497 * @page: page number to read
1499 * Hardware ECC for large page chips, require OOB to be read first. For this
1500 * ECC mode, the write_page method is re-used from ECC_HW. These methods
1501 * read/write ECC from the OOB area, unlike the ECC_HW_SYNDROME support with
1502 * multiple ECC steps, follows the "infix ECC" scheme and reads/writes ECC from
1503 * the data area, by overwriting the NAND manufacturer bad block markings.
1505 static int nand_read_page_hwecc_oob_first(struct mtd_info *mtd,
1506 struct nand_chip *chip, uint8_t *buf, int oob_required, int page)
1508 int i, eccsize = chip->ecc.size;
1509 int eccbytes = chip->ecc.bytes;
1510 int eccsteps = chip->ecc.steps;
1512 uint8_t *ecc_code = chip->buffers->ecccode;
1513 uint32_t *eccpos = chip->ecc.layout->eccpos;
1514 uint8_t *ecc_calc = chip->buffers->ecccalc;
1515 unsigned int max_bitflips = 0;
1517 /* Read the OOB area first */
1518 chip->cmdfunc(mtd, NAND_CMD_READOOB, 0, page);
1519 chip->read_buf(mtd, chip->oob_poi, mtd->oobsize);
1520 chip->cmdfunc(mtd, NAND_CMD_READ0, 0, page);
1522 for (i = 0; i < chip->ecc.total; i++)
1523 ecc_code[i] = chip->oob_poi[eccpos[i]];
1525 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
1528 chip->ecc.hwctl(mtd, NAND_ECC_READ);
1529 chip->read_buf(mtd, p, eccsize);
1530 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
1532 stat = chip->ecc.correct(mtd, p, &ecc_code[i], NULL);
1533 if (stat == -EBADMSG &&
1534 (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
1535 /* check for empty pages with bitflips */
1536 stat = nand_check_erased_ecc_chunk(p, eccsize,
1537 &ecc_code[i], eccbytes,
1539 chip->ecc.strength);
1543 mtd->ecc_stats.failed++;
1545 mtd->ecc_stats.corrected += stat;
1546 max_bitflips = max_t(unsigned int, max_bitflips, stat);
1549 return max_bitflips;
1553 * nand_read_page_syndrome - [REPLACEABLE] hardware ECC syndrome based page read
1554 * @mtd: mtd info structure
1555 * @chip: nand chip info structure
1556 * @buf: buffer to store read data
1557 * @oob_required: caller requires OOB data read to chip->oob_poi
1558 * @page: page number to read
1560 * The hw generator calculates the error syndrome automatically. Therefore we
1561 * need a special oob layout and handling.
1563 static int nand_read_page_syndrome(struct mtd_info *mtd, struct nand_chip *chip,
1564 uint8_t *buf, int oob_required, int page)
1566 int i, eccsize = chip->ecc.size;
1567 int eccbytes = chip->ecc.bytes;
1568 int eccsteps = chip->ecc.steps;
1569 int eccpadbytes = eccbytes + chip->ecc.prepad + chip->ecc.postpad;
1571 uint8_t *oob = chip->oob_poi;
1572 unsigned int max_bitflips = 0;
1574 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
1577 chip->ecc.hwctl(mtd, NAND_ECC_READ);
1578 chip->read_buf(mtd, p, eccsize);
1580 if (chip->ecc.prepad) {
1581 chip->read_buf(mtd, oob, chip->ecc.prepad);
1582 oob += chip->ecc.prepad;
1585 chip->ecc.hwctl(mtd, NAND_ECC_READSYN);
1586 chip->read_buf(mtd, oob, eccbytes);
1587 stat = chip->ecc.correct(mtd, p, oob, NULL);
1591 if (chip->ecc.postpad) {
1592 chip->read_buf(mtd, oob, chip->ecc.postpad);
1593 oob += chip->ecc.postpad;
1596 if (stat == -EBADMSG &&
1597 (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
1598 /* check for empty pages with bitflips */
1599 stat = nand_check_erased_ecc_chunk(p, chip->ecc.size,
1603 chip->ecc.strength);
1607 mtd->ecc_stats.failed++;
1609 mtd->ecc_stats.corrected += stat;
1610 max_bitflips = max_t(unsigned int, max_bitflips, stat);
1614 /* Calculate remaining oob bytes */
1615 i = mtd->oobsize - (oob - chip->oob_poi);
1617 chip->read_buf(mtd, oob, i);
1619 return max_bitflips;
1623 * nand_transfer_oob - [INTERN] Transfer oob to client buffer
1624 * @chip: nand chip structure
1625 * @oob: oob destination address
1626 * @ops: oob ops structure
1627 * @len: size of oob to transfer
1629 static uint8_t *nand_transfer_oob(struct nand_chip *chip, uint8_t *oob,
1630 struct mtd_oob_ops *ops, size_t len)
1632 switch (ops->mode) {
1634 case MTD_OPS_PLACE_OOB:
1636 memcpy(oob, chip->oob_poi + ops->ooboffs, len);
1639 case MTD_OPS_AUTO_OOB: {
1640 struct nand_oobfree *free = chip->ecc.layout->oobfree;
1641 uint32_t boffs = 0, roffs = ops->ooboffs;
1644 for (; free->length && len; free++, len -= bytes) {
1645 /* Read request not from offset 0? */
1646 if (unlikely(roffs)) {
1647 if (roffs >= free->length) {
1648 roffs -= free->length;
1651 boffs = free->offset + roffs;
1652 bytes = min_t(size_t, len,
1653 (free->length - roffs));
1656 bytes = min_t(size_t, len, free->length);
1657 boffs = free->offset;
1659 memcpy(oob, chip->oob_poi + boffs, bytes);
1671 * nand_setup_read_retry - [INTERN] Set the READ RETRY mode
1672 * @mtd: MTD device structure
1673 * @retry_mode: the retry mode to use
1675 * Some vendors supply a special command to shift the Vt threshold, to be used
1676 * when there are too many bitflips in a page (i.e., ECC error). After setting
1677 * a new threshold, the host should retry reading the page.
1679 static int nand_setup_read_retry(struct mtd_info *mtd, int retry_mode)
1681 struct nand_chip *chip = mtd_to_nand(mtd);
1683 pr_debug("setting READ RETRY mode %d\n", retry_mode);
1685 if (retry_mode >= chip->read_retries)
1688 if (!chip->setup_read_retry)
1691 return chip->setup_read_retry(mtd, retry_mode);
1695 * nand_do_read_ops - [INTERN] Read data with ECC
1696 * @mtd: MTD device structure
1697 * @from: offset to read from
1698 * @ops: oob ops structure
1700 * Internal function. Called with chip held.
1702 static int nand_do_read_ops(struct mtd_info *mtd, loff_t from,
1703 struct mtd_oob_ops *ops)
1705 int chipnr, page, realpage, col, bytes, aligned, oob_required;
1706 struct nand_chip *chip = mtd_to_nand(mtd);
1708 uint32_t readlen = ops->len;
1709 uint32_t oobreadlen = ops->ooblen;
1710 uint32_t max_oobsize = mtd_oobavail(mtd, ops);
1712 uint8_t *bufpoi, *oob, *buf;
1714 unsigned int max_bitflips = 0;
1716 bool ecc_fail = false;
1718 chipnr = (int)(from >> chip->chip_shift);
1719 chip->select_chip(mtd, chipnr);
1721 realpage = (int)(from >> chip->page_shift);
1722 page = realpage & chip->pagemask;
1724 col = (int)(from & (mtd->writesize - 1));
1728 oob_required = oob ? 1 : 0;
1731 unsigned int ecc_failures = mtd->ecc_stats.failed;
1733 bytes = min(mtd->writesize - col, readlen);
1734 aligned = (bytes == mtd->writesize);
1738 else if (chip->options & NAND_USE_BOUNCE_BUFFER)
1739 use_bufpoi = !virt_addr_valid(buf);
1743 /* Is the current page in the buffer? */
1744 if (realpage != chip->pagebuf || oob) {
1745 bufpoi = use_bufpoi ? chip->buffers->databuf : buf;
1747 if (use_bufpoi && aligned)
1748 pr_debug("%s: using read bounce buffer for buf@%p\n",
1752 chip->cmdfunc(mtd, NAND_CMD_READ0, 0x00, page);
1755 * Now read the page into the buffer. Absent an error,
1756 * the read methods return max bitflips per ecc step.
1758 if (unlikely(ops->mode == MTD_OPS_RAW))
1759 ret = chip->ecc.read_page_raw(mtd, chip, bufpoi,
1762 else if (!aligned && NAND_HAS_SUBPAGE_READ(chip) &&
1764 ret = chip->ecc.read_subpage(mtd, chip,
1768 ret = chip->ecc.read_page(mtd, chip, bufpoi,
1769 oob_required, page);
1772 /* Invalidate page cache */
1777 max_bitflips = max_t(unsigned int, max_bitflips, ret);
1779 /* Transfer not aligned data */
1781 if (!NAND_HAS_SUBPAGE_READ(chip) && !oob &&
1782 !(mtd->ecc_stats.failed - ecc_failures) &&
1783 (ops->mode != MTD_OPS_RAW)) {
1784 chip->pagebuf = realpage;
1785 chip->pagebuf_bitflips = ret;
1787 /* Invalidate page cache */
1790 memcpy(buf, chip->buffers->databuf + col, bytes);
1793 if (unlikely(oob)) {
1794 int toread = min(oobreadlen, max_oobsize);
1797 oob = nand_transfer_oob(chip,
1799 oobreadlen -= toread;
1803 if (chip->options & NAND_NEED_READRDY) {
1804 /* Apply delay or wait for ready/busy pin */
1805 if (!chip->dev_ready)
1806 udelay(chip->chip_delay);
1808 nand_wait_ready(mtd);
1811 if (mtd->ecc_stats.failed - ecc_failures) {
1812 if (retry_mode + 1 < chip->read_retries) {
1814 ret = nand_setup_read_retry(mtd,
1819 /* Reset failures; retry */
1820 mtd->ecc_stats.failed = ecc_failures;
1823 /* No more retry modes; real failure */
1830 memcpy(buf, chip->buffers->databuf + col, bytes);
1832 max_bitflips = max_t(unsigned int, max_bitflips,
1833 chip->pagebuf_bitflips);
1838 /* Reset to retry mode 0 */
1840 ret = nand_setup_read_retry(mtd, 0);
1849 /* For subsequent reads align to page boundary */
1851 /* Increment page address */
1854 page = realpage & chip->pagemask;
1855 /* Check, if we cross a chip boundary */
1858 chip->select_chip(mtd, -1);
1859 chip->select_chip(mtd, chipnr);
1862 chip->select_chip(mtd, -1);
1864 ops->retlen = ops->len - (size_t) readlen;
1866 ops->oobretlen = ops->ooblen - oobreadlen;
1874 return max_bitflips;
1878 * nand_read - [MTD Interface] MTD compatibility function for nand_do_read_ecc
1879 * @mtd: MTD device structure
1880 * @from: offset to read from
1881 * @len: number of bytes to read
1882 * @retlen: pointer to variable to store the number of read bytes
1883 * @buf: the databuffer to put data
1885 * Get hold of the chip and call nand_do_read.
1887 static int nand_read(struct mtd_info *mtd, loff_t from, size_t len,
1888 size_t *retlen, uint8_t *buf)
1890 struct mtd_oob_ops ops;
1893 nand_get_device(mtd, FL_READING);
1894 memset(&ops, 0, sizeof(ops));
1897 ops.mode = MTD_OPS_PLACE_OOB;
1898 ret = nand_do_read_ops(mtd, from, &ops);
1899 *retlen = ops.retlen;
1900 nand_release_device(mtd);
1905 * nand_read_oob_std - [REPLACEABLE] the most common OOB data read function
1906 * @mtd: mtd info structure
1907 * @chip: nand chip info structure
1908 * @page: page number to read
1910 static int nand_read_oob_std(struct mtd_info *mtd, struct nand_chip *chip,
1913 chip->cmdfunc(mtd, NAND_CMD_READOOB, 0, page);
1914 chip->read_buf(mtd, chip->oob_poi, mtd->oobsize);
1919 * nand_read_oob_syndrome - [REPLACEABLE] OOB data read function for HW ECC
1921 * @mtd: mtd info structure
1922 * @chip: nand chip info structure
1923 * @page: page number to read
1925 static int nand_read_oob_syndrome(struct mtd_info *mtd, struct nand_chip *chip,
1928 int length = mtd->oobsize;
1929 int chunk = chip->ecc.bytes + chip->ecc.prepad + chip->ecc.postpad;
1930 int eccsize = chip->ecc.size;
1931 uint8_t *bufpoi = chip->oob_poi;
1932 int i, toread, sndrnd = 0, pos;
1934 chip->cmdfunc(mtd, NAND_CMD_READ0, chip->ecc.size, page);
1935 for (i = 0; i < chip->ecc.steps; i++) {
1937 pos = eccsize + i * (eccsize + chunk);
1938 if (mtd->writesize > 512)
1939 chip->cmdfunc(mtd, NAND_CMD_RNDOUT, pos, -1);
1941 chip->cmdfunc(mtd, NAND_CMD_READ0, pos, page);
1944 toread = min_t(int, length, chunk);
1945 chip->read_buf(mtd, bufpoi, toread);
1950 chip->read_buf(mtd, bufpoi, length);
1956 * nand_write_oob_std - [REPLACEABLE] the most common OOB data write function
1957 * @mtd: mtd info structure
1958 * @chip: nand chip info structure
1959 * @page: page number to write
1961 static int nand_write_oob_std(struct mtd_info *mtd, struct nand_chip *chip,
1965 const uint8_t *buf = chip->oob_poi;
1966 int length = mtd->oobsize;
1968 chip->cmdfunc(mtd, NAND_CMD_SEQIN, mtd->writesize, page);
1969 chip->write_buf(mtd, buf, length);
1970 /* Send command to program the OOB data */
1971 chip->cmdfunc(mtd, NAND_CMD_PAGEPROG, -1, -1);
1973 status = chip->waitfunc(mtd, chip);
1975 return status & NAND_STATUS_FAIL ? -EIO : 0;
1979 * nand_write_oob_syndrome - [REPLACEABLE] OOB data write function for HW ECC
1980 * with syndrome - only for large page flash
1981 * @mtd: mtd info structure
1982 * @chip: nand chip info structure
1983 * @page: page number to write
1985 static int nand_write_oob_syndrome(struct mtd_info *mtd,
1986 struct nand_chip *chip, int page)
1988 int chunk = chip->ecc.bytes + chip->ecc.prepad + chip->ecc.postpad;
1989 int eccsize = chip->ecc.size, length = mtd->oobsize;
1990 int i, len, pos, status = 0, sndcmd = 0, steps = chip->ecc.steps;
1991 const uint8_t *bufpoi = chip->oob_poi;
1994 * data-ecc-data-ecc ... ecc-oob
1996 * data-pad-ecc-pad-data-pad .... ecc-pad-oob
1998 if (!chip->ecc.prepad && !chip->ecc.postpad) {
1999 pos = steps * (eccsize + chunk);
2004 chip->cmdfunc(mtd, NAND_CMD_SEQIN, pos, page);
2005 for (i = 0; i < steps; i++) {
2007 if (mtd->writesize <= 512) {
2008 uint32_t fill = 0xFFFFFFFF;
2012 int num = min_t(int, len, 4);
2013 chip->write_buf(mtd, (uint8_t *)&fill,
2018 pos = eccsize + i * (eccsize + chunk);
2019 chip->cmdfunc(mtd, NAND_CMD_RNDIN, pos, -1);
2023 len = min_t(int, length, chunk);
2024 chip->write_buf(mtd, bufpoi, len);
2029 chip->write_buf(mtd, bufpoi, length);
2031 chip->cmdfunc(mtd, NAND_CMD_PAGEPROG, -1, -1);
2032 status = chip->waitfunc(mtd, chip);
2034 return status & NAND_STATUS_FAIL ? -EIO : 0;
2038 * nand_do_read_oob - [INTERN] NAND read out-of-band
2039 * @mtd: MTD device structure
2040 * @from: offset to read from
2041 * @ops: oob operations description structure
2043 * NAND read out-of-band data from the spare area.
2045 static int nand_do_read_oob(struct mtd_info *mtd, loff_t from,
2046 struct mtd_oob_ops *ops)
2048 int page, realpage, chipnr;
2049 struct nand_chip *chip = mtd_to_nand(mtd);
2050 struct mtd_ecc_stats stats;
2051 int readlen = ops->ooblen;
2053 uint8_t *buf = ops->oobbuf;
2056 pr_debug("%s: from = 0x%08Lx, len = %i\n",
2057 __func__, (unsigned long long)from, readlen);
2059 stats = mtd->ecc_stats;
2061 len = mtd_oobavail(mtd, ops);
2063 if (unlikely(ops->ooboffs >= len)) {
2064 pr_debug("%s: attempt to start read outside oob\n",
2069 /* Do not allow reads past end of device */
2070 if (unlikely(from >= mtd->size ||
2071 ops->ooboffs + readlen > ((mtd->size >> chip->page_shift) -
2072 (from >> chip->page_shift)) * len)) {
2073 pr_debug("%s: attempt to read beyond end of device\n",
2078 chipnr = (int)(from >> chip->chip_shift);
2079 chip->select_chip(mtd, chipnr);
2081 /* Shift to get page */
2082 realpage = (int)(from >> chip->page_shift);
2083 page = realpage & chip->pagemask;
2086 if (ops->mode == MTD_OPS_RAW)
2087 ret = chip->ecc.read_oob_raw(mtd, chip, page);
2089 ret = chip->ecc.read_oob(mtd, chip, page);
2094 len = min(len, readlen);
2095 buf = nand_transfer_oob(chip, buf, ops, len);
2097 if (chip->options & NAND_NEED_READRDY) {
2098 /* Apply delay or wait for ready/busy pin */
2099 if (!chip->dev_ready)
2100 udelay(chip->chip_delay);
2102 nand_wait_ready(mtd);
2109 /* Increment page address */
2112 page = realpage & chip->pagemask;
2113 /* Check, if we cross a chip boundary */
2116 chip->select_chip(mtd, -1);
2117 chip->select_chip(mtd, chipnr);
2120 chip->select_chip(mtd, -1);
2122 ops->oobretlen = ops->ooblen - readlen;
2127 if (mtd->ecc_stats.failed - stats.failed)
2130 return mtd->ecc_stats.corrected - stats.corrected ? -EUCLEAN : 0;
2134 * nand_read_oob - [MTD Interface] NAND read data and/or out-of-band
2135 * @mtd: MTD device structure
2136 * @from: offset to read from
2137 * @ops: oob operation description structure
2139 * NAND read data and/or out-of-band data.
2141 static int nand_read_oob(struct mtd_info *mtd, loff_t from,
2142 struct mtd_oob_ops *ops)
2144 int ret = -ENOTSUPP;
2148 /* Do not allow reads past end of device */
2149 if (ops->datbuf && (from + ops->len) > mtd->size) {
2150 pr_debug("%s: attempt to read beyond end of device\n",
2155 nand_get_device(mtd, FL_READING);
2157 switch (ops->mode) {
2158 case MTD_OPS_PLACE_OOB:
2159 case MTD_OPS_AUTO_OOB:
2168 ret = nand_do_read_oob(mtd, from, ops);
2170 ret = nand_do_read_ops(mtd, from, ops);
2173 nand_release_device(mtd);
2179 * nand_write_page_raw - [INTERN] raw page write function
2180 * @mtd: mtd info structure
2181 * @chip: nand chip info structure
2183 * @oob_required: must write chip->oob_poi to OOB
2184 * @page: page number to write
2186 * Not for syndrome calculating ECC controllers, which use a special oob layout.
2188 static int nand_write_page_raw(struct mtd_info *mtd, struct nand_chip *chip,
2189 const uint8_t *buf, int oob_required, int page)
2191 chip->write_buf(mtd, buf, mtd->writesize);
2193 chip->write_buf(mtd, chip->oob_poi, mtd->oobsize);
2199 * nand_write_page_raw_syndrome - [INTERN] raw page write function
2200 * @mtd: mtd info structure
2201 * @chip: nand chip info structure
2203 * @oob_required: must write chip->oob_poi to OOB
2204 * @page: page number to write
2206 * We need a special oob layout and handling even when ECC isn't checked.
2208 static int nand_write_page_raw_syndrome(struct mtd_info *mtd,
2209 struct nand_chip *chip,
2210 const uint8_t *buf, int oob_required,
2213 int eccsize = chip->ecc.size;
2214 int eccbytes = chip->ecc.bytes;
2215 uint8_t *oob = chip->oob_poi;
2218 for (steps = chip->ecc.steps; steps > 0; steps--) {
2219 chip->write_buf(mtd, buf, eccsize);
2222 if (chip->ecc.prepad) {
2223 chip->write_buf(mtd, oob, chip->ecc.prepad);
2224 oob += chip->ecc.prepad;
2227 chip->write_buf(mtd, oob, eccbytes);
2230 if (chip->ecc.postpad) {
2231 chip->write_buf(mtd, oob, chip->ecc.postpad);
2232 oob += chip->ecc.postpad;
2236 size = mtd->oobsize - (oob - chip->oob_poi);
2238 chip->write_buf(mtd, oob, size);
2243 * nand_write_page_swecc - [REPLACEABLE] software ECC based page write function
2244 * @mtd: mtd info structure
2245 * @chip: nand chip info structure
2247 * @oob_required: must write chip->oob_poi to OOB
2248 * @page: page number to write
2250 static int nand_write_page_swecc(struct mtd_info *mtd, struct nand_chip *chip,
2251 const uint8_t *buf, int oob_required,
2254 int i, eccsize = chip->ecc.size;
2255 int eccbytes = chip->ecc.bytes;
2256 int eccsteps = chip->ecc.steps;
2257 uint8_t *ecc_calc = chip->buffers->ecccalc;
2258 const uint8_t *p = buf;
2259 uint32_t *eccpos = chip->ecc.layout->eccpos;
2261 /* Software ECC calculation */
2262 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize)
2263 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
2265 for (i = 0; i < chip->ecc.total; i++)
2266 chip->oob_poi[eccpos[i]] = ecc_calc[i];
2268 return chip->ecc.write_page_raw(mtd, chip, buf, 1, page);
2272 * nand_write_page_hwecc - [REPLACEABLE] hardware ECC based page write function
2273 * @mtd: mtd info structure
2274 * @chip: nand chip info structure
2276 * @oob_required: must write chip->oob_poi to OOB
2277 * @page: page number to write
2279 static int nand_write_page_hwecc(struct mtd_info *mtd, struct nand_chip *chip,
2280 const uint8_t *buf, int oob_required,
2283 int i, eccsize = chip->ecc.size;
2284 int eccbytes = chip->ecc.bytes;
2285 int eccsteps = chip->ecc.steps;
2286 uint8_t *ecc_calc = chip->buffers->ecccalc;
2287 const uint8_t *p = buf;
2288 uint32_t *eccpos = chip->ecc.layout->eccpos;
2290 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
2291 chip->ecc.hwctl(mtd, NAND_ECC_WRITE);
2292 chip->write_buf(mtd, p, eccsize);
2293 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
2296 for (i = 0; i < chip->ecc.total; i++)
2297 chip->oob_poi[eccpos[i]] = ecc_calc[i];
2299 chip->write_buf(mtd, chip->oob_poi, mtd->oobsize);
2306 * nand_write_subpage_hwecc - [REPLACEABLE] hardware ECC based subpage write
2307 * @mtd: mtd info structure
2308 * @chip: nand chip info structure
2309 * @offset: column address of subpage within the page
2310 * @data_len: data length
2312 * @oob_required: must write chip->oob_poi to OOB
2313 * @page: page number to write
2315 static int nand_write_subpage_hwecc(struct mtd_info *mtd,
2316 struct nand_chip *chip, uint32_t offset,
2317 uint32_t data_len, const uint8_t *buf,
2318 int oob_required, int page)
2320 uint8_t *oob_buf = chip->oob_poi;
2321 uint8_t *ecc_calc = chip->buffers->ecccalc;
2322 int ecc_size = chip->ecc.size;
2323 int ecc_bytes = chip->ecc.bytes;
2324 int ecc_steps = chip->ecc.steps;
2325 uint32_t *eccpos = chip->ecc.layout->eccpos;
2326 uint32_t start_step = offset / ecc_size;
2327 uint32_t end_step = (offset + data_len - 1) / ecc_size;
2328 int oob_bytes = mtd->oobsize / ecc_steps;
2331 for (step = 0; step < ecc_steps; step++) {
2332 /* configure controller for WRITE access */
2333 chip->ecc.hwctl(mtd, NAND_ECC_WRITE);
2335 /* write data (untouched subpages already masked by 0xFF) */
2336 chip->write_buf(mtd, buf, ecc_size);
2338 /* mask ECC of un-touched subpages by padding 0xFF */
2339 if ((step < start_step) || (step > end_step))
2340 memset(ecc_calc, 0xff, ecc_bytes);
2342 chip->ecc.calculate(mtd, buf, ecc_calc);
2344 /* mask OOB of un-touched subpages by padding 0xFF */
2345 /* if oob_required, preserve OOB metadata of written subpage */
2346 if (!oob_required || (step < start_step) || (step > end_step))
2347 memset(oob_buf, 0xff, oob_bytes);
2350 ecc_calc += ecc_bytes;
2351 oob_buf += oob_bytes;
2354 /* copy calculated ECC for whole page to chip->buffer->oob */
2355 /* this include masked-value(0xFF) for unwritten subpages */
2356 ecc_calc = chip->buffers->ecccalc;
2357 for (i = 0; i < chip->ecc.total; i++)
2358 chip->oob_poi[eccpos[i]] = ecc_calc[i];
2360 /* write OOB buffer to NAND device */
2361 chip->write_buf(mtd, chip->oob_poi, mtd->oobsize);
2368 * nand_write_page_syndrome - [REPLACEABLE] hardware ECC syndrome based page write
2369 * @mtd: mtd info structure
2370 * @chip: nand chip info structure
2372 * @oob_required: must write chip->oob_poi to OOB
2373 * @page: page number to write
2375 * The hw generator calculates the error syndrome automatically. Therefore we
2376 * need a special oob layout and handling.
2378 static int nand_write_page_syndrome(struct mtd_info *mtd,
2379 struct nand_chip *chip,
2380 const uint8_t *buf, int oob_required,
2383 int i, eccsize = chip->ecc.size;
2384 int eccbytes = chip->ecc.bytes;
2385 int eccsteps = chip->ecc.steps;
2386 const uint8_t *p = buf;
2387 uint8_t *oob = chip->oob_poi;
2389 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
2391 chip->ecc.hwctl(mtd, NAND_ECC_WRITE);
2392 chip->write_buf(mtd, p, eccsize);
2394 if (chip->ecc.prepad) {
2395 chip->write_buf(mtd, oob, chip->ecc.prepad);
2396 oob += chip->ecc.prepad;
2399 chip->ecc.calculate(mtd, p, oob);
2400 chip->write_buf(mtd, oob, eccbytes);
2403 if (chip->ecc.postpad) {
2404 chip->write_buf(mtd, oob, chip->ecc.postpad);
2405 oob += chip->ecc.postpad;
2409 /* Calculate remaining oob bytes */
2410 i = mtd->oobsize - (oob - chip->oob_poi);
2412 chip->write_buf(mtd, oob, i);
2418 * nand_write_page - [REPLACEABLE] write one page
2419 * @mtd: MTD device structure
2420 * @chip: NAND chip descriptor
2421 * @offset: address offset within the page
2422 * @data_len: length of actual data to be written
2423 * @buf: the data to write
2424 * @oob_required: must write chip->oob_poi to OOB
2425 * @page: page number to write
2426 * @cached: cached programming
2427 * @raw: use _raw version of write_page
2429 static int nand_write_page(struct mtd_info *mtd, struct nand_chip *chip,
2430 uint32_t offset, int data_len, const uint8_t *buf,
2431 int oob_required, int page, int cached, int raw)
2433 int status, subpage;
2435 if (!(chip->options & NAND_NO_SUBPAGE_WRITE) &&
2436 chip->ecc.write_subpage)
2437 subpage = offset || (data_len < mtd->writesize);
2441 chip->cmdfunc(mtd, NAND_CMD_SEQIN, 0x00, page);
2444 status = chip->ecc.write_page_raw(mtd, chip, buf,
2445 oob_required, page);
2447 status = chip->ecc.write_subpage(mtd, chip, offset, data_len,
2448 buf, oob_required, page);
2450 status = chip->ecc.write_page(mtd, chip, buf, oob_required,
2457 * Cached progamming disabled for now. Not sure if it's worth the
2458 * trouble. The speed gain is not very impressive. (2.3->2.6Mib/s).
2462 if (!cached || !NAND_HAS_CACHEPROG(chip)) {
2464 chip->cmdfunc(mtd, NAND_CMD_PAGEPROG, -1, -1);
2465 status = chip->waitfunc(mtd, chip);
2467 * See if operation failed and additional status checks are
2470 if ((status & NAND_STATUS_FAIL) && (chip->errstat))
2471 status = chip->errstat(mtd, chip, FL_WRITING, status,
2474 if (status & NAND_STATUS_FAIL)
2477 chip->cmdfunc(mtd, NAND_CMD_CACHEDPROG, -1, -1);
2478 status = chip->waitfunc(mtd, chip);
2485 * nand_fill_oob - [INTERN] Transfer client buffer to oob
2486 * @mtd: MTD device structure
2487 * @oob: oob data buffer
2488 * @len: oob data write length
2489 * @ops: oob ops structure
2491 static uint8_t *nand_fill_oob(struct mtd_info *mtd, uint8_t *oob, size_t len,
2492 struct mtd_oob_ops *ops)
2494 struct nand_chip *chip = mtd_to_nand(mtd);
2497 * Initialise to all 0xFF, to avoid the possibility of left over OOB
2498 * data from a previous OOB read.
2500 memset(chip->oob_poi, 0xff, mtd->oobsize);
2502 switch (ops->mode) {
2504 case MTD_OPS_PLACE_OOB:
2506 memcpy(chip->oob_poi + ops->ooboffs, oob, len);
2509 case MTD_OPS_AUTO_OOB: {
2510 struct nand_oobfree *free = chip->ecc.layout->oobfree;
2511 uint32_t boffs = 0, woffs = ops->ooboffs;
2514 for (; free->length && len; free++, len -= bytes) {
2515 /* Write request not from offset 0? */
2516 if (unlikely(woffs)) {
2517 if (woffs >= free->length) {
2518 woffs -= free->length;
2521 boffs = free->offset + woffs;
2522 bytes = min_t(size_t, len,
2523 (free->length - woffs));
2526 bytes = min_t(size_t, len, free->length);
2527 boffs = free->offset;
2529 memcpy(chip->oob_poi + boffs, oob, bytes);
2540 #define NOTALIGNED(x) ((x & (chip->subpagesize - 1)) != 0)
2543 * nand_do_write_ops - [INTERN] NAND write with ECC
2544 * @mtd: MTD device structure
2545 * @to: offset to write to
2546 * @ops: oob operations description structure
2548 * NAND write with ECC.
2550 static int nand_do_write_ops(struct mtd_info *mtd, loff_t to,
2551 struct mtd_oob_ops *ops)
2553 int chipnr, realpage, page, blockmask, column;
2554 struct nand_chip *chip = mtd_to_nand(mtd);
2555 uint32_t writelen = ops->len;
2557 uint32_t oobwritelen = ops->ooblen;
2558 uint32_t oobmaxlen = mtd_oobavail(mtd, ops);
2560 uint8_t *oob = ops->oobbuf;
2561 uint8_t *buf = ops->datbuf;
2563 int oob_required = oob ? 1 : 0;
2569 /* Reject writes, which are not page aligned */
2570 if (NOTALIGNED(to) || NOTALIGNED(ops->len)) {
2571 pr_notice("%s: attempt to write non page aligned data\n",
2576 column = to & (mtd->writesize - 1);
2578 chipnr = (int)(to >> chip->chip_shift);
2579 chip->select_chip(mtd, chipnr);
2581 /* Check, if it is write protected */
2582 if (nand_check_wp(mtd)) {
2587 realpage = (int)(to >> chip->page_shift);
2588 page = realpage & chip->pagemask;
2589 blockmask = (1 << (chip->phys_erase_shift - chip->page_shift)) - 1;
2591 /* Invalidate the page cache, when we write to the cached page */
2592 if (to <= ((loff_t)chip->pagebuf << chip->page_shift) &&
2593 ((loff_t)chip->pagebuf << chip->page_shift) < (to + ops->len))
2596 /* Don't allow multipage oob writes with offset */
2597 if (oob && ops->ooboffs && (ops->ooboffs + ops->ooblen > oobmaxlen)) {
2603 int bytes = mtd->writesize;
2604 int cached = writelen > bytes && page != blockmask;
2605 uint8_t *wbuf = buf;
2607 int part_pagewr = (column || writelen < (mtd->writesize - 1));
2611 else if (chip->options & NAND_USE_BOUNCE_BUFFER)
2612 use_bufpoi = !virt_addr_valid(buf);
2616 /* Partial page write?, or need to use bounce buffer */
2618 pr_debug("%s: using write bounce buffer for buf@%p\n",
2622 bytes = min_t(int, bytes - column, writelen);
2624 memset(chip->buffers->databuf, 0xff, mtd->writesize);
2625 memcpy(&chip->buffers->databuf[column], buf, bytes);
2626 wbuf = chip->buffers->databuf;
2629 if (unlikely(oob)) {
2630 size_t len = min(oobwritelen, oobmaxlen);
2631 oob = nand_fill_oob(mtd, oob, len, ops);
2634 /* We still need to erase leftover OOB data */
2635 memset(chip->oob_poi, 0xff, mtd->oobsize);
2637 ret = chip->write_page(mtd, chip, column, bytes, wbuf,
2638 oob_required, page, cached,
2639 (ops->mode == MTD_OPS_RAW));
2651 page = realpage & chip->pagemask;
2652 /* Check, if we cross a chip boundary */
2655 chip->select_chip(mtd, -1);
2656 chip->select_chip(mtd, chipnr);
2660 ops->retlen = ops->len - writelen;
2662 ops->oobretlen = ops->ooblen;
2665 chip->select_chip(mtd, -1);
2670 * panic_nand_write - [MTD Interface] NAND write with ECC
2671 * @mtd: MTD device structure
2672 * @to: offset to write to
2673 * @len: number of bytes to write
2674 * @retlen: pointer to variable to store the number of written bytes
2675 * @buf: the data to write
2677 * NAND write with ECC. Used when performing writes in interrupt context, this
2678 * may for example be called by mtdoops when writing an oops while in panic.
2680 static int panic_nand_write(struct mtd_info *mtd, loff_t to, size_t len,
2681 size_t *retlen, const uint8_t *buf)
2683 struct nand_chip *chip = mtd_to_nand(mtd);
2684 struct mtd_oob_ops ops;
2687 /* Wait for the device to get ready */
2688 panic_nand_wait(mtd, chip, 400);
2690 /* Grab the device */
2691 panic_nand_get_device(chip, mtd, FL_WRITING);
2693 memset(&ops, 0, sizeof(ops));
2695 ops.datbuf = (uint8_t *)buf;
2696 ops.mode = MTD_OPS_PLACE_OOB;
2698 ret = nand_do_write_ops(mtd, to, &ops);
2700 *retlen = ops.retlen;
2705 * nand_write - [MTD Interface] NAND write with ECC
2706 * @mtd: MTD device structure
2707 * @to: offset to write to
2708 * @len: number of bytes to write
2709 * @retlen: pointer to variable to store the number of written bytes
2710 * @buf: the data to write
2712 * NAND write with ECC.
2714 static int nand_write(struct mtd_info *mtd, loff_t to, size_t len,
2715 size_t *retlen, const uint8_t *buf)
2717 struct mtd_oob_ops ops;
2720 nand_get_device(mtd, FL_WRITING);
2721 memset(&ops, 0, sizeof(ops));
2723 ops.datbuf = (uint8_t *)buf;
2724 ops.mode = MTD_OPS_PLACE_OOB;
2725 ret = nand_do_write_ops(mtd, to, &ops);
2726 *retlen = ops.retlen;
2727 nand_release_device(mtd);
2732 * nand_do_write_oob - [MTD Interface] NAND write out-of-band
2733 * @mtd: MTD device structure
2734 * @to: offset to write to
2735 * @ops: oob operation description structure
2737 * NAND write out-of-band.
2739 static int nand_do_write_oob(struct mtd_info *mtd, loff_t to,
2740 struct mtd_oob_ops *ops)
2742 int chipnr, page, status, len;
2743 struct nand_chip *chip = mtd_to_nand(mtd);
2745 pr_debug("%s: to = 0x%08x, len = %i\n",
2746 __func__, (unsigned int)to, (int)ops->ooblen);
2748 len = mtd_oobavail(mtd, ops);
2750 /* Do not allow write past end of page */
2751 if ((ops->ooboffs + ops->ooblen) > len) {
2752 pr_debug("%s: attempt to write past end of page\n",
2757 if (unlikely(ops->ooboffs >= len)) {
2758 pr_debug("%s: attempt to start write outside oob\n",
2763 /* Do not allow write past end of device */
2764 if (unlikely(to >= mtd->size ||
2765 ops->ooboffs + ops->ooblen >
2766 ((mtd->size >> chip->page_shift) -
2767 (to >> chip->page_shift)) * len)) {
2768 pr_debug("%s: attempt to write beyond end of device\n",
2773 chipnr = (int)(to >> chip->chip_shift);
2774 chip->select_chip(mtd, chipnr);
2776 /* Shift to get page */
2777 page = (int)(to >> chip->page_shift);
2780 * Reset the chip. Some chips (like the Toshiba TC5832DC found in one
2781 * of my DiskOnChip 2000 test units) will clear the whole data page too
2782 * if we don't do this. I have no clue why, but I seem to have 'fixed'
2783 * it in the doc2000 driver in August 1999. dwmw2.
2785 chip->cmdfunc(mtd, NAND_CMD_RESET, -1, -1);
2787 /* Check, if it is write protected */
2788 if (nand_check_wp(mtd)) {
2789 chip->select_chip(mtd, -1);
2793 /* Invalidate the page cache, if we write to the cached page */
2794 if (page == chip->pagebuf)
2797 nand_fill_oob(mtd, ops->oobbuf, ops->ooblen, ops);
2799 if (ops->mode == MTD_OPS_RAW)
2800 status = chip->ecc.write_oob_raw(mtd, chip, page & chip->pagemask);
2802 status = chip->ecc.write_oob(mtd, chip, page & chip->pagemask);
2804 chip->select_chip(mtd, -1);
2809 ops->oobretlen = ops->ooblen;
2815 * nand_write_oob - [MTD Interface] NAND write data and/or out-of-band
2816 * @mtd: MTD device structure
2817 * @to: offset to write to
2818 * @ops: oob operation description structure
2820 static int nand_write_oob(struct mtd_info *mtd, loff_t to,
2821 struct mtd_oob_ops *ops)
2823 int ret = -ENOTSUPP;
2827 /* Do not allow writes past end of device */
2828 if (ops->datbuf && (to + ops->len) > mtd->size) {
2829 pr_debug("%s: attempt to write beyond end of device\n",
2834 nand_get_device(mtd, FL_WRITING);
2836 switch (ops->mode) {
2837 case MTD_OPS_PLACE_OOB:
2838 case MTD_OPS_AUTO_OOB:
2847 ret = nand_do_write_oob(mtd, to, ops);
2849 ret = nand_do_write_ops(mtd, to, ops);
2852 nand_release_device(mtd);
2857 * single_erase - [GENERIC] NAND standard block erase command function
2858 * @mtd: MTD device structure
2859 * @page: the page address of the block which will be erased
2861 * Standard erase command for NAND chips. Returns NAND status.
2863 static int single_erase(struct mtd_info *mtd, int page)
2865 struct nand_chip *chip = mtd_to_nand(mtd);
2866 /* Send commands to erase a block */
2867 chip->cmdfunc(mtd, NAND_CMD_ERASE1, -1, page);
2868 chip->cmdfunc(mtd, NAND_CMD_ERASE2, -1, -1);
2870 return chip->waitfunc(mtd, chip);
2874 * nand_erase - [MTD Interface] erase block(s)
2875 * @mtd: MTD device structure
2876 * @instr: erase instruction
2878 * Erase one ore more blocks.
2880 static int nand_erase(struct mtd_info *mtd, struct erase_info *instr)
2882 return nand_erase_nand(mtd, instr, 0);
2886 * nand_erase_nand - [INTERN] erase block(s)
2887 * @mtd: MTD device structure
2888 * @instr: erase instruction
2889 * @allowbbt: allow erasing the bbt area
2891 * Erase one ore more blocks.
2893 int nand_erase_nand(struct mtd_info *mtd, struct erase_info *instr,
2896 int page, status, pages_per_block, ret, chipnr;
2897 struct nand_chip *chip = mtd_to_nand(mtd);
2900 pr_debug("%s: start = 0x%012llx, len = %llu\n",
2901 __func__, (unsigned long long)instr->addr,
2902 (unsigned long long)instr->len);
2904 if (check_offs_len(mtd, instr->addr, instr->len))
2907 /* Grab the lock and see if the device is available */
2908 nand_get_device(mtd, FL_ERASING);
2910 /* Shift to get first page */
2911 page = (int)(instr->addr >> chip->page_shift);
2912 chipnr = (int)(instr->addr >> chip->chip_shift);
2914 /* Calculate pages in each block */
2915 pages_per_block = 1 << (chip->phys_erase_shift - chip->page_shift);
2917 /* Select the NAND device */
2918 chip->select_chip(mtd, chipnr);
2920 /* Check, if it is write protected */
2921 if (nand_check_wp(mtd)) {
2922 pr_debug("%s: device is write protected!\n",
2924 instr->state = MTD_ERASE_FAILED;
2928 /* Loop through the pages */
2931 instr->state = MTD_ERASING;
2934 /* Check if we have a bad block, we do not erase bad blocks! */
2935 if (nand_block_checkbad(mtd, ((loff_t) page) <<
2936 chip->page_shift, allowbbt)) {
2937 pr_warn("%s: attempt to erase a bad block at page 0x%08x\n",
2939 instr->state = MTD_ERASE_FAILED;
2944 * Invalidate the page cache, if we erase the block which
2945 * contains the current cached page.
2947 if (page <= chip->pagebuf && chip->pagebuf <
2948 (page + pages_per_block))
2951 status = chip->erase(mtd, page & chip->pagemask);
2954 * See if operation failed and additional status checks are
2957 if ((status & NAND_STATUS_FAIL) && (chip->errstat))
2958 status = chip->errstat(mtd, chip, FL_ERASING,
2961 /* See if block erase succeeded */
2962 if (status & NAND_STATUS_FAIL) {
2963 pr_debug("%s: failed erase, page 0x%08x\n",
2965 instr->state = MTD_ERASE_FAILED;
2967 ((loff_t)page << chip->page_shift);
2971 /* Increment page address and decrement length */
2972 len -= (1ULL << chip->phys_erase_shift);
2973 page += pages_per_block;
2975 /* Check, if we cross a chip boundary */
2976 if (len && !(page & chip->pagemask)) {
2978 chip->select_chip(mtd, -1);
2979 chip->select_chip(mtd, chipnr);
2982 instr->state = MTD_ERASE_DONE;
2986 ret = instr->state == MTD_ERASE_DONE ? 0 : -EIO;
2988 /* Deselect and wake up anyone waiting on the device */
2989 chip->select_chip(mtd, -1);
2990 nand_release_device(mtd);
2992 /* Do call back function */
2994 mtd_erase_callback(instr);
2996 /* Return more or less happy */
3001 * nand_sync - [MTD Interface] sync
3002 * @mtd: MTD device structure
3004 * Sync is actually a wait for chip ready function.
3006 static void nand_sync(struct mtd_info *mtd)
3008 pr_debug("%s: called\n", __func__);
3010 /* Grab the lock and see if the device is available */
3011 nand_get_device(mtd, FL_SYNCING);
3012 /* Release it and go back */
3013 nand_release_device(mtd);
3017 * nand_block_isbad - [MTD Interface] Check if block at offset is bad
3018 * @mtd: MTD device structure
3019 * @offs: offset relative to mtd start
3021 static int nand_block_isbad(struct mtd_info *mtd, loff_t offs)
3023 struct nand_chip *chip = mtd_to_nand(mtd);
3024 int chipnr = (int)(offs >> chip->chip_shift);
3027 /* Select the NAND device */
3028 nand_get_device(mtd, FL_READING);
3029 chip->select_chip(mtd, chipnr);
3031 ret = nand_block_checkbad(mtd, offs, 0);
3033 chip->select_chip(mtd, -1);
3034 nand_release_device(mtd);
3040 * nand_block_markbad - [MTD Interface] Mark block at the given offset as bad
3041 * @mtd: MTD device structure
3042 * @ofs: offset relative to mtd start
3044 static int nand_block_markbad(struct mtd_info *mtd, loff_t ofs)
3048 ret = nand_block_isbad(mtd, ofs);
3050 /* If it was bad already, return success and do nothing */
3056 return nand_block_markbad_lowlevel(mtd, ofs);
3060 * nand_onfi_set_features- [REPLACEABLE] set features for ONFI nand
3061 * @mtd: MTD device structure
3062 * @chip: nand chip info structure
3063 * @addr: feature address.
3064 * @subfeature_param: the subfeature parameters, a four bytes array.
3066 static int nand_onfi_set_features(struct mtd_info *mtd, struct nand_chip *chip,
3067 int addr, uint8_t *subfeature_param)
3072 if (!chip->onfi_version ||
3073 !(le16_to_cpu(chip->onfi_params.opt_cmd)
3074 & ONFI_OPT_CMD_SET_GET_FEATURES))
3077 chip->cmdfunc(mtd, NAND_CMD_SET_FEATURES, addr, -1);
3078 for (i = 0; i < ONFI_SUBFEATURE_PARAM_LEN; ++i)
3079 chip->write_byte(mtd, subfeature_param[i]);
3081 status = chip->waitfunc(mtd, chip);
3082 if (status & NAND_STATUS_FAIL)
3088 * nand_onfi_get_features- [REPLACEABLE] get features for ONFI nand
3089 * @mtd: MTD device structure
3090 * @chip: nand chip info structure
3091 * @addr: feature address.
3092 * @subfeature_param: the subfeature parameters, a four bytes array.
3094 static int nand_onfi_get_features(struct mtd_info *mtd, struct nand_chip *chip,
3095 int addr, uint8_t *subfeature_param)
3099 if (!chip->onfi_version ||
3100 !(le16_to_cpu(chip->onfi_params.opt_cmd)
3101 & ONFI_OPT_CMD_SET_GET_FEATURES))
3104 chip->cmdfunc(mtd, NAND_CMD_GET_FEATURES, addr, -1);
3105 for (i = 0; i < ONFI_SUBFEATURE_PARAM_LEN; ++i)
3106 *subfeature_param++ = chip->read_byte(mtd);
3111 * nand_suspend - [MTD Interface] Suspend the NAND flash
3112 * @mtd: MTD device structure
3114 static int nand_suspend(struct mtd_info *mtd)
3116 return nand_get_device(mtd, FL_PM_SUSPENDED);
3120 * nand_resume - [MTD Interface] Resume the NAND flash
3121 * @mtd: MTD device structure
3123 static void nand_resume(struct mtd_info *mtd)
3125 struct nand_chip *chip = mtd_to_nand(mtd);
3127 if (chip->state == FL_PM_SUSPENDED)
3128 nand_release_device(mtd);
3130 pr_err("%s called for a chip which is not in suspended state\n",
3135 * nand_shutdown - [MTD Interface] Finish the current NAND operation and
3136 * prevent further operations
3137 * @mtd: MTD device structure
3139 static void nand_shutdown(struct mtd_info *mtd)
3141 nand_get_device(mtd, FL_PM_SUSPENDED);
3144 /* Set default functions */
3145 static void nand_set_defaults(struct nand_chip *chip, int busw)
3147 /* check for proper chip_delay setup, set 20us if not */
3148 if (!chip->chip_delay)
3149 chip->chip_delay = 20;
3151 /* check, if a user supplied command function given */
3152 if (chip->cmdfunc == NULL)
3153 chip->cmdfunc = nand_command;
3155 /* check, if a user supplied wait function given */
3156 if (chip->waitfunc == NULL)
3157 chip->waitfunc = nand_wait;
3159 if (!chip->select_chip)
3160 chip->select_chip = nand_select_chip;
3162 /* set for ONFI nand */
3163 if (!chip->onfi_set_features)
3164 chip->onfi_set_features = nand_onfi_set_features;
3165 if (!chip->onfi_get_features)
3166 chip->onfi_get_features = nand_onfi_get_features;
3168 /* If called twice, pointers that depend on busw may need to be reset */
3169 if (!chip->read_byte || chip->read_byte == nand_read_byte)
3170 chip->read_byte = busw ? nand_read_byte16 : nand_read_byte;
3171 if (!chip->read_word)
3172 chip->read_word = nand_read_word;
3173 if (!chip->block_bad)
3174 chip->block_bad = nand_block_bad;
3175 if (!chip->block_markbad)
3176 chip->block_markbad = nand_default_block_markbad;
3177 if (!chip->write_buf || chip->write_buf == nand_write_buf)
3178 chip->write_buf = busw ? nand_write_buf16 : nand_write_buf;
3179 if (!chip->write_byte || chip->write_byte == nand_write_byte)
3180 chip->write_byte = busw ? nand_write_byte16 : nand_write_byte;
3181 if (!chip->read_buf || chip->read_buf == nand_read_buf)
3182 chip->read_buf = busw ? nand_read_buf16 : nand_read_buf;
3183 if (!chip->scan_bbt)
3184 chip->scan_bbt = nand_default_bbt;
3186 if (!chip->controller) {
3187 chip->controller = &chip->hwcontrol;
3188 spin_lock_init(&chip->controller->lock);
3189 init_waitqueue_head(&chip->controller->wq);
3194 /* Sanitize ONFI strings so we can safely print them */
3195 static void sanitize_string(uint8_t *s, size_t len)
3199 /* Null terminate */
3202 /* Remove non printable chars */
3203 for (i = 0; i < len - 1; i++) {
3204 if (s[i] < ' ' || s[i] > 127)
3208 /* Remove trailing spaces */
3212 static u16 onfi_crc16(u16 crc, u8 const *p, size_t len)
3217 for (i = 0; i < 8; i++)
3218 crc = (crc << 1) ^ ((crc & 0x8000) ? 0x8005 : 0);
3224 /* Parse the Extended Parameter Page. */
3225 static int nand_flash_detect_ext_param_page(struct mtd_info *mtd,
3226 struct nand_chip *chip, struct nand_onfi_params *p)
3228 struct onfi_ext_param_page *ep;
3229 struct onfi_ext_section *s;
3230 struct onfi_ext_ecc_info *ecc;
3236 len = le16_to_cpu(p->ext_param_page_length) * 16;
3237 ep = kmalloc(len, GFP_KERNEL);
3241 /* Send our own NAND_CMD_PARAM. */
3242 chip->cmdfunc(mtd, NAND_CMD_PARAM, 0, -1);
3244 /* Use the Change Read Column command to skip the ONFI param pages. */
3245 chip->cmdfunc(mtd, NAND_CMD_RNDOUT,
3246 sizeof(*p) * p->num_of_param_pages , -1);
3248 /* Read out the Extended Parameter Page. */
3249 chip->read_buf(mtd, (uint8_t *)ep, len);
3250 if ((onfi_crc16(ONFI_CRC_BASE, ((uint8_t *)ep) + 2, len - 2)
3251 != le16_to_cpu(ep->crc))) {
3252 pr_debug("fail in the CRC.\n");
3257 * Check the signature.
3258 * Do not strictly follow the ONFI spec, maybe changed in future.
3260 if (strncmp(ep->sig, "EPPS", 4)) {
3261 pr_debug("The signature is invalid.\n");
3265 /* find the ECC section. */
3266 cursor = (uint8_t *)(ep + 1);
3267 for (i = 0; i < ONFI_EXT_SECTION_MAX; i++) {
3268 s = ep->sections + i;
3269 if (s->type == ONFI_SECTION_TYPE_2)
3271 cursor += s->length * 16;
3273 if (i == ONFI_EXT_SECTION_MAX) {
3274 pr_debug("We can not find the ECC section.\n");
3278 /* get the info we want. */
3279 ecc = (struct onfi_ext_ecc_info *)cursor;
3281 if (!ecc->codeword_size) {
3282 pr_debug("Invalid codeword size\n");
3286 chip->ecc_strength_ds = ecc->ecc_bits;
3287 chip->ecc_step_ds = 1 << ecc->codeword_size;
3295 static int nand_setup_read_retry_micron(struct mtd_info *mtd, int retry_mode)
3297 struct nand_chip *chip = mtd_to_nand(mtd);
3298 uint8_t feature[ONFI_SUBFEATURE_PARAM_LEN] = {retry_mode};
3300 return chip->onfi_set_features(mtd, chip, ONFI_FEATURE_ADDR_READ_RETRY,
3305 * Configure chip properties from Micron vendor-specific ONFI table
3307 static void nand_onfi_detect_micron(struct nand_chip *chip,
3308 struct nand_onfi_params *p)
3310 struct nand_onfi_vendor_micron *micron = (void *)p->vendor;
3312 if (le16_to_cpu(p->vendor_revision) < 1)
3315 chip->read_retries = micron->read_retry_options;
3316 chip->setup_read_retry = nand_setup_read_retry_micron;
3320 * Check if the NAND chip is ONFI compliant, returns 1 if it is, 0 otherwise.
3322 static int nand_flash_detect_onfi(struct mtd_info *mtd, struct nand_chip *chip,
3325 struct nand_onfi_params *p = &chip->onfi_params;
3329 /* Try ONFI for unknown chip or LP */
3330 chip->cmdfunc(mtd, NAND_CMD_READID, 0x20, -1);
3331 if (chip->read_byte(mtd) != 'O' || chip->read_byte(mtd) != 'N' ||
3332 chip->read_byte(mtd) != 'F' || chip->read_byte(mtd) != 'I')
3335 chip->cmdfunc(mtd, NAND_CMD_PARAM, 0, -1);
3336 for (i = 0; i < 3; i++) {
3337 for (j = 0; j < sizeof(*p); j++)
3338 ((uint8_t *)p)[j] = chip->read_byte(mtd);
3339 if (onfi_crc16(ONFI_CRC_BASE, (uint8_t *)p, 254) ==
3340 le16_to_cpu(p->crc)) {
3346 pr_err("Could not find valid ONFI parameter page; aborting\n");
3351 val = le16_to_cpu(p->revision);
3353 chip->onfi_version = 23;
3354 else if (val & (1 << 4))
3355 chip->onfi_version = 22;
3356 else if (val & (1 << 3))
3357 chip->onfi_version = 21;
3358 else if (val & (1 << 2))
3359 chip->onfi_version = 20;
3360 else if (val & (1 << 1))
3361 chip->onfi_version = 10;
3363 if (!chip->onfi_version) {
3364 pr_info("unsupported ONFI version: %d\n", val);
3368 sanitize_string(p->manufacturer, sizeof(p->manufacturer));
3369 sanitize_string(p->model, sizeof(p->model));
3371 mtd->name = p->model;
3373 mtd->writesize = le32_to_cpu(p->byte_per_page);
3376 * pages_per_block and blocks_per_lun may not be a power-of-2 size
3377 * (don't ask me who thought of this...). MTD assumes that these
3378 * dimensions will be power-of-2, so just truncate the remaining area.
3380 mtd->erasesize = 1 << (fls(le32_to_cpu(p->pages_per_block)) - 1);
3381 mtd->erasesize *= mtd->writesize;
3383 mtd->oobsize = le16_to_cpu(p->spare_bytes_per_page);
3385 /* See erasesize comment */
3386 chip->chipsize = 1 << (fls(le32_to_cpu(p->blocks_per_lun)) - 1);
3387 chip->chipsize *= (uint64_t)mtd->erasesize * p->lun_count;
3388 chip->bits_per_cell = p->bits_per_cell;
3390 if (onfi_feature(chip) & ONFI_FEATURE_16_BIT_BUS)
3391 *busw = NAND_BUSWIDTH_16;
3395 if (p->ecc_bits != 0xff) {
3396 chip->ecc_strength_ds = p->ecc_bits;
3397 chip->ecc_step_ds = 512;
3398 } else if (chip->onfi_version >= 21 &&
3399 (onfi_feature(chip) & ONFI_FEATURE_EXT_PARAM_PAGE)) {
3402 * The nand_flash_detect_ext_param_page() uses the
3403 * Change Read Column command which maybe not supported
3404 * by the chip->cmdfunc. So try to update the chip->cmdfunc
3405 * now. We do not replace user supplied command function.
3407 if (mtd->writesize > 512 && chip->cmdfunc == nand_command)
3408 chip->cmdfunc = nand_command_lp;
3410 /* The Extended Parameter Page is supported since ONFI 2.1. */
3411 if (nand_flash_detect_ext_param_page(mtd, chip, p))
3412 pr_warn("Failed to detect ONFI extended param page\n");
3414 pr_warn("Could not retrieve ONFI ECC requirements\n");
3417 if (p->jedec_id == NAND_MFR_MICRON)
3418 nand_onfi_detect_micron(chip, p);
3424 * Check if the NAND chip is JEDEC compliant, returns 1 if it is, 0 otherwise.
3426 static int nand_flash_detect_jedec(struct mtd_info *mtd, struct nand_chip *chip,
3429 struct nand_jedec_params *p = &chip->jedec_params;
3430 struct jedec_ecc_info *ecc;
3434 /* Try JEDEC for unknown chip or LP */
3435 chip->cmdfunc(mtd, NAND_CMD_READID, 0x40, -1);
3436 if (chip->read_byte(mtd) != 'J' || chip->read_byte(mtd) != 'E' ||
3437 chip->read_byte(mtd) != 'D' || chip->read_byte(mtd) != 'E' ||
3438 chip->read_byte(mtd) != 'C')
3441 chip->cmdfunc(mtd, NAND_CMD_PARAM, 0x40, -1);
3442 for (i = 0; i < 3; i++) {
3443 for (j = 0; j < sizeof(*p); j++)
3444 ((uint8_t *)p)[j] = chip->read_byte(mtd);
3446 if (onfi_crc16(ONFI_CRC_BASE, (uint8_t *)p, 510) ==
3447 le16_to_cpu(p->crc))
3452 pr_err("Could not find valid JEDEC parameter page; aborting\n");
3457 val = le16_to_cpu(p->revision);
3459 chip->jedec_version = 10;
3460 else if (val & (1 << 1))
3461 chip->jedec_version = 1; /* vendor specific version */
3463 if (!chip->jedec_version) {
3464 pr_info("unsupported JEDEC version: %d\n", val);
3468 sanitize_string(p->manufacturer, sizeof(p->manufacturer));
3469 sanitize_string(p->model, sizeof(p->model));
3471 mtd->name = p->model;
3473 mtd->writesize = le32_to_cpu(p->byte_per_page);
3475 /* Please reference to the comment for nand_flash_detect_onfi. */
3476 mtd->erasesize = 1 << (fls(le32_to_cpu(p->pages_per_block)) - 1);
3477 mtd->erasesize *= mtd->writesize;
3479 mtd->oobsize = le16_to_cpu(p->spare_bytes_per_page);
3481 /* Please reference to the comment for nand_flash_detect_onfi. */
3482 chip->chipsize = 1 << (fls(le32_to_cpu(p->blocks_per_lun)) - 1);
3483 chip->chipsize *= (uint64_t)mtd->erasesize * p->lun_count;
3484 chip->bits_per_cell = p->bits_per_cell;
3486 if (jedec_feature(chip) & JEDEC_FEATURE_16_BIT_BUS)
3487 *busw = NAND_BUSWIDTH_16;
3492 ecc = &p->ecc_info[0];
3494 if (ecc->codeword_size >= 9) {
3495 chip->ecc_strength_ds = ecc->ecc_bits;
3496 chip->ecc_step_ds = 1 << ecc->codeword_size;
3498 pr_warn("Invalid codeword size\n");
3505 * nand_id_has_period - Check if an ID string has a given wraparound period
3506 * @id_data: the ID string
3507 * @arrlen: the length of the @id_data array
3508 * @period: the period of repitition
3510 * Check if an ID string is repeated within a given sequence of bytes at
3511 * specific repetition interval period (e.g., {0x20,0x01,0x7F,0x20} has a
3512 * period of 3). This is a helper function for nand_id_len(). Returns non-zero
3513 * if the repetition has a period of @period; otherwise, returns zero.
3515 static int nand_id_has_period(u8 *id_data, int arrlen, int period)
3518 for (i = 0; i < period; i++)
3519 for (j = i + period; j < arrlen; j += period)
3520 if (id_data[i] != id_data[j])
3526 * nand_id_len - Get the length of an ID string returned by CMD_READID
3527 * @id_data: the ID string
3528 * @arrlen: the length of the @id_data array
3530 * Returns the length of the ID string, according to known wraparound/trailing
3531 * zero patterns. If no pattern exists, returns the length of the array.
3533 static int nand_id_len(u8 *id_data, int arrlen)
3535 int last_nonzero, period;
3537 /* Find last non-zero byte */
3538 for (last_nonzero = arrlen - 1; last_nonzero >= 0; last_nonzero--)
3539 if (id_data[last_nonzero])
3543 if (last_nonzero < 0)
3546 /* Calculate wraparound period */
3547 for (period = 1; period < arrlen; period++)
3548 if (nand_id_has_period(id_data, arrlen, period))
3551 /* There's a repeated pattern */
3552 if (period < arrlen)
3555 /* There are trailing zeros */
3556 if (last_nonzero < arrlen - 1)
3557 return last_nonzero + 1;
3559 /* No pattern detected */
3563 /* Extract the bits of per cell from the 3rd byte of the extended ID */
3564 static int nand_get_bits_per_cell(u8 cellinfo)
3568 bits = cellinfo & NAND_CI_CELLTYPE_MSK;
3569 bits >>= NAND_CI_CELLTYPE_SHIFT;
3574 * Many new NAND share similar device ID codes, which represent the size of the
3575 * chip. The rest of the parameters must be decoded according to generic or
3576 * manufacturer-specific "extended ID" decoding patterns.
3578 static void nand_decode_ext_id(struct mtd_info *mtd, struct nand_chip *chip,
3579 u8 id_data[8], int *busw)
3582 /* The 3rd id byte holds MLC / multichip data */
3583 chip->bits_per_cell = nand_get_bits_per_cell(id_data[2]);
3584 /* The 4th id byte is the important one */
3587 id_len = nand_id_len(id_data, 8);
3590 * Field definitions are in the following datasheets:
3591 * Old style (4,5 byte ID): Samsung K9GAG08U0M (p.32)
3592 * New Samsung (6 byte ID): Samsung K9GAG08U0F (p.44)
3593 * Hynix MLC (6 byte ID): Hynix H27UBG8T2B (p.22)
3595 * Check for ID length, non-zero 6th byte, cell type, and Hynix/Samsung
3596 * ID to decide what to do.
3598 if (id_len == 6 && id_data[0] == NAND_MFR_SAMSUNG &&
3599 !nand_is_slc(chip) && id_data[5] != 0x00) {
3601 mtd->writesize = 2048 << (extid & 0x03);
3604 switch (((extid >> 2) & 0x04) | (extid & 0x03)) {
3624 default: /* Other cases are "reserved" (unknown) */
3625 mtd->oobsize = 1024;
3629 /* Calc blocksize */
3630 mtd->erasesize = (128 * 1024) <<
3631 (((extid >> 1) & 0x04) | (extid & 0x03));
3633 } else if (id_len == 6 && id_data[0] == NAND_MFR_HYNIX &&
3634 !nand_is_slc(chip)) {
3638 mtd->writesize = 2048 << (extid & 0x03);
3641 switch (((extid >> 2) & 0x04) | (extid & 0x03)) {
3665 /* Calc blocksize */
3666 tmp = ((extid >> 1) & 0x04) | (extid & 0x03);
3668 mtd->erasesize = (128 * 1024) << tmp;
3669 else if (tmp == 0x03)
3670 mtd->erasesize = 768 * 1024;
3672 mtd->erasesize = (64 * 1024) << tmp;
3676 mtd->writesize = 1024 << (extid & 0x03);
3679 mtd->oobsize = (8 << (extid & 0x01)) *
3680 (mtd->writesize >> 9);
3682 /* Calc blocksize. Blocksize is multiples of 64KiB */
3683 mtd->erasesize = (64 * 1024) << (extid & 0x03);
3685 /* Get buswidth information */
3686 *busw = (extid & 0x01) ? NAND_BUSWIDTH_16 : 0;
3689 * Toshiba 24nm raw SLC (i.e., not BENAND) have 32B OOB per
3690 * 512B page. For Toshiba SLC, we decode the 5th/6th byte as
3692 * - ID byte 6, bits[2:0]: 100b -> 43nm, 101b -> 32nm,
3694 * - ID byte 5, bit[7]: 1 -> BENAND, 0 -> raw SLC
3696 if (id_len >= 6 && id_data[0] == NAND_MFR_TOSHIBA &&
3697 nand_is_slc(chip) &&
3698 (id_data[5] & 0x7) == 0x6 /* 24nm */ &&
3699 !(id_data[4] & 0x80) /* !BENAND */) {
3700 mtd->oobsize = 32 * mtd->writesize >> 9;
3707 * Old devices have chip data hardcoded in the device ID table. nand_decode_id
3708 * decodes a matching ID table entry and assigns the MTD size parameters for
3711 static void nand_decode_id(struct mtd_info *mtd, struct nand_chip *chip,
3712 struct nand_flash_dev *type, u8 id_data[8],
3715 int maf_id = id_data[0];
3717 mtd->erasesize = type->erasesize;
3718 mtd->writesize = type->pagesize;
3719 mtd->oobsize = mtd->writesize / 32;
3720 *busw = type->options & NAND_BUSWIDTH_16;
3722 /* All legacy ID NAND are small-page, SLC */
3723 chip->bits_per_cell = 1;
3726 * Check for Spansion/AMD ID + repeating 5th, 6th byte since
3727 * some Spansion chips have erasesize that conflicts with size
3728 * listed in nand_ids table.
3729 * Data sheet (5 byte ID): Spansion S30ML-P ORNAND (p.39)
3731 if (maf_id == NAND_MFR_AMD && id_data[4] != 0x00 && id_data[5] == 0x00
3732 && id_data[6] == 0x00 && id_data[7] == 0x00
3733 && mtd->writesize == 512) {
3734 mtd->erasesize = 128 * 1024;
3735 mtd->erasesize <<= ((id_data[3] & 0x03) << 1);
3740 * Set the bad block marker/indicator (BBM/BBI) patterns according to some
3741 * heuristic patterns using various detected parameters (e.g., manufacturer,
3742 * page size, cell-type information).
3744 static void nand_decode_bbm_options(struct mtd_info *mtd,
3745 struct nand_chip *chip, u8 id_data[8])
3747 int maf_id = id_data[0];
3749 /* Set the bad block position */
3750 if (mtd->writesize > 512 || (chip->options & NAND_BUSWIDTH_16))
3751 chip->badblockpos = NAND_LARGE_BADBLOCK_POS;
3753 chip->badblockpos = NAND_SMALL_BADBLOCK_POS;
3756 * Bad block marker is stored in the last page of each block on Samsung
3757 * and Hynix MLC devices; stored in first two pages of each block on
3758 * Micron devices with 2KiB pages and on SLC Samsung, Hynix, Toshiba,
3759 * AMD/Spansion, and Macronix. All others scan only the first page.
3761 if (!nand_is_slc(chip) &&
3762 (maf_id == NAND_MFR_SAMSUNG ||
3763 maf_id == NAND_MFR_HYNIX))
3764 chip->bbt_options |= NAND_BBT_SCANLASTPAGE;
3765 else if ((nand_is_slc(chip) &&
3766 (maf_id == NAND_MFR_SAMSUNG ||
3767 maf_id == NAND_MFR_HYNIX ||
3768 maf_id == NAND_MFR_TOSHIBA ||
3769 maf_id == NAND_MFR_AMD ||
3770 maf_id == NAND_MFR_MACRONIX)) ||
3771 (mtd->writesize == 2048 &&
3772 maf_id == NAND_MFR_MICRON))
3773 chip->bbt_options |= NAND_BBT_SCAN2NDPAGE;
3776 static inline bool is_full_id_nand(struct nand_flash_dev *type)
3778 return type->id_len;
3781 static bool find_full_id_nand(struct mtd_info *mtd, struct nand_chip *chip,
3782 struct nand_flash_dev *type, u8 *id_data, int *busw)
3784 if (!strncmp(type->id, id_data, type->id_len)) {
3785 mtd->writesize = type->pagesize;
3786 mtd->erasesize = type->erasesize;
3787 mtd->oobsize = type->oobsize;
3789 chip->bits_per_cell = nand_get_bits_per_cell(id_data[2]);
3790 chip->chipsize = (uint64_t)type->chipsize << 20;
3791 chip->options |= type->options;
3792 chip->ecc_strength_ds = NAND_ECC_STRENGTH(type);
3793 chip->ecc_step_ds = NAND_ECC_STEP(type);
3794 chip->onfi_timing_mode_default =
3795 type->onfi_timing_mode_default;
3797 *busw = type->options & NAND_BUSWIDTH_16;
3800 mtd->name = type->name;
3808 * Get the flash and manufacturer id and lookup if the type is supported.
3810 static struct nand_flash_dev *nand_get_flash_type(struct mtd_info *mtd,
3811 struct nand_chip *chip,
3812 int *maf_id, int *dev_id,
3813 struct nand_flash_dev *type)
3819 /* Select the device */
3820 chip->select_chip(mtd, 0);
3823 * Reset the chip, required by some chips (e.g. Micron MT29FxGxxxxx)
3826 chip->cmdfunc(mtd, NAND_CMD_RESET, -1, -1);
3828 /* Send the command for reading device ID */
3829 chip->cmdfunc(mtd, NAND_CMD_READID, 0x00, -1);
3831 /* Read manufacturer and device IDs */
3832 *maf_id = chip->read_byte(mtd);
3833 *dev_id = chip->read_byte(mtd);
3836 * Try again to make sure, as some systems the bus-hold or other
3837 * interface concerns can cause random data which looks like a
3838 * possibly credible NAND flash to appear. If the two results do
3839 * not match, ignore the device completely.
3842 chip->cmdfunc(mtd, NAND_CMD_READID, 0x00, -1);
3844 /* Read entire ID string */
3845 for (i = 0; i < 8; i++)
3846 id_data[i] = chip->read_byte(mtd);
3848 if (id_data[0] != *maf_id || id_data[1] != *dev_id) {
3849 pr_info("second ID read did not match %02x,%02x against %02x,%02x\n",
3850 *maf_id, *dev_id, id_data[0], id_data[1]);
3851 return ERR_PTR(-ENODEV);
3855 type = nand_flash_ids;
3857 for (; type->name != NULL; type++) {
3858 if (is_full_id_nand(type)) {
3859 if (find_full_id_nand(mtd, chip, type, id_data, &busw))
3861 } else if (*dev_id == type->dev_id) {
3866 chip->onfi_version = 0;
3867 if (!type->name || !type->pagesize) {
3868 /* Check if the chip is ONFI compliant */
3869 if (nand_flash_detect_onfi(mtd, chip, &busw))
3872 /* Check if the chip is JEDEC compliant */
3873 if (nand_flash_detect_jedec(mtd, chip, &busw))
3878 return ERR_PTR(-ENODEV);
3881 mtd->name = type->name;
3883 chip->chipsize = (uint64_t)type->chipsize << 20;
3885 if (!type->pagesize) {
3886 /* Decode parameters from extended ID */
3887 nand_decode_ext_id(mtd, chip, id_data, &busw);
3889 nand_decode_id(mtd, chip, type, id_data, &busw);
3891 /* Get chip options */
3892 chip->options |= type->options;
3895 * Check if chip is not a Samsung device. Do not clear the
3896 * options for chips which do not have an extended id.
3898 if (*maf_id != NAND_MFR_SAMSUNG && !type->pagesize)
3899 chip->options &= ~NAND_SAMSUNG_LP_OPTIONS;
3902 /* Try to identify manufacturer */
3903 for (maf_idx = 0; nand_manuf_ids[maf_idx].id != 0x0; maf_idx++) {
3904 if (nand_manuf_ids[maf_idx].id == *maf_id)
3908 if (chip->options & NAND_BUSWIDTH_AUTO) {
3909 WARN_ON(chip->options & NAND_BUSWIDTH_16);
3910 chip->options |= busw;
3911 nand_set_defaults(chip, busw);
3912 } else if (busw != (chip->options & NAND_BUSWIDTH_16)) {
3914 * Check, if buswidth is correct. Hardware drivers should set
3917 pr_info("device found, Manufacturer ID: 0x%02x, Chip ID: 0x%02x\n",
3919 pr_info("%s %s\n", nand_manuf_ids[maf_idx].name, mtd->name);
3920 pr_warn("bus width %d instead %d bit\n",
3921 (chip->options & NAND_BUSWIDTH_16) ? 16 : 8,
3923 return ERR_PTR(-EINVAL);
3926 nand_decode_bbm_options(mtd, chip, id_data);
3928 /* Calculate the address shift from the page size */
3929 chip->page_shift = ffs(mtd->writesize) - 1;
3930 /* Convert chipsize to number of pages per chip -1 */
3931 chip->pagemask = (chip->chipsize >> chip->page_shift) - 1;
3933 chip->bbt_erase_shift = chip->phys_erase_shift =
3934 ffs(mtd->erasesize) - 1;
3935 if (chip->chipsize & 0xffffffff)
3936 chip->chip_shift = ffs((unsigned)chip->chipsize) - 1;
3938 chip->chip_shift = ffs((unsigned)(chip->chipsize >> 32));
3939 chip->chip_shift += 32 - 1;
3942 chip->badblockbits = 8;
3943 chip->erase = single_erase;
3945 /* Do not replace user supplied command function! */
3946 if (mtd->writesize > 512 && chip->cmdfunc == nand_command)
3947 chip->cmdfunc = nand_command_lp;
3949 pr_info("device found, Manufacturer ID: 0x%02x, Chip ID: 0x%02x\n",
3952 if (chip->onfi_version)
3953 pr_info("%s %s\n", nand_manuf_ids[maf_idx].name,
3954 chip->onfi_params.model);
3955 else if (chip->jedec_version)
3956 pr_info("%s %s\n", nand_manuf_ids[maf_idx].name,
3957 chip->jedec_params.model);
3959 pr_info("%s %s\n", nand_manuf_ids[maf_idx].name,
3962 pr_info("%d MiB, %s, erase size: %d KiB, page size: %d, OOB size: %d\n",
3963 (int)(chip->chipsize >> 20), nand_is_slc(chip) ? "SLC" : "MLC",
3964 mtd->erasesize >> 10, mtd->writesize, mtd->oobsize);
3968 static int nand_dt_init(struct nand_chip *chip)
3970 struct device_node *dn = nand_get_flash_node(chip);
3971 int ecc_mode, ecc_strength, ecc_step;
3976 if (of_get_nand_bus_width(dn) == 16)
3977 chip->options |= NAND_BUSWIDTH_16;
3979 if (of_get_nand_on_flash_bbt(dn))
3980 chip->bbt_options |= NAND_BBT_USE_FLASH;
3982 ecc_mode = of_get_nand_ecc_mode(dn);
3983 ecc_strength = of_get_nand_ecc_strength(dn);
3984 ecc_step = of_get_nand_ecc_step_size(dn);
3986 if ((ecc_step >= 0 && !(ecc_strength >= 0)) ||
3987 (!(ecc_step >= 0) && ecc_strength >= 0)) {
3988 pr_err("must set both strength and step size in DT\n");
3993 chip->ecc.mode = ecc_mode;
3995 if (ecc_strength >= 0)
3996 chip->ecc.strength = ecc_strength;
3999 chip->ecc.size = ecc_step;
4005 * nand_scan_ident - [NAND Interface] Scan for the NAND device
4006 * @mtd: MTD device structure
4007 * @maxchips: number of chips to scan for
4008 * @table: alternative NAND ID table
4010 * This is the first phase of the normal nand_scan() function. It reads the
4011 * flash ID and sets up MTD fields accordingly.
4013 * The mtd->owner field must be set to the module of the caller.
4015 int nand_scan_ident(struct mtd_info *mtd, int maxchips,
4016 struct nand_flash_dev *table)
4018 int i, nand_maf_id, nand_dev_id;
4019 struct nand_chip *chip = mtd_to_nand(mtd);
4020 struct nand_flash_dev *type;
4023 ret = nand_dt_init(chip);
4027 if (!mtd->name && mtd->dev.parent)
4028 mtd->name = dev_name(mtd->dev.parent);
4030 /* Set the default functions */
4031 nand_set_defaults(chip, chip->options & NAND_BUSWIDTH_16);
4033 /* Read the flash type */
4034 type = nand_get_flash_type(mtd, chip, &nand_maf_id,
4035 &nand_dev_id, table);
4038 if (!(chip->options & NAND_SCAN_SILENT_NODEV))
4039 pr_warn("No NAND device found\n");
4040 chip->select_chip(mtd, -1);
4041 return PTR_ERR(type);
4044 chip->select_chip(mtd, -1);
4046 /* Check for a chip array */
4047 for (i = 1; i < maxchips; i++) {
4048 chip->select_chip(mtd, i);
4049 /* See comment in nand_get_flash_type for reset */
4050 chip->cmdfunc(mtd, NAND_CMD_RESET, -1, -1);
4051 /* Send the command for reading device ID */
4052 chip->cmdfunc(mtd, NAND_CMD_READID, 0x00, -1);
4053 /* Read manufacturer and device IDs */
4054 if (nand_maf_id != chip->read_byte(mtd) ||
4055 nand_dev_id != chip->read_byte(mtd)) {
4056 chip->select_chip(mtd, -1);
4059 chip->select_chip(mtd, -1);
4062 pr_info("%d chips detected\n", i);
4064 /* Store the number of chips and calc total size for mtd */
4066 mtd->size = i * chip->chipsize;
4070 EXPORT_SYMBOL(nand_scan_ident);
4073 * Check if the chip configuration meet the datasheet requirements.
4075 * If our configuration corrects A bits per B bytes and the minimum
4076 * required correction level is X bits per Y bytes, then we must ensure
4077 * both of the following are true:
4079 * (1) A / B >= X / Y
4082 * Requirement (1) ensures we can correct for the required bitflip density.
4083 * Requirement (2) ensures we can correct even when all bitflips are clumped
4084 * in the same sector.
4086 static bool nand_ecc_strength_good(struct mtd_info *mtd)
4088 struct nand_chip *chip = mtd_to_nand(mtd);
4089 struct nand_ecc_ctrl *ecc = &chip->ecc;
4092 if (ecc->size == 0 || chip->ecc_step_ds == 0)
4093 /* Not enough information */
4097 * We get the number of corrected bits per page to compare
4098 * the correction density.
4100 corr = (mtd->writesize * ecc->strength) / ecc->size;
4101 ds_corr = (mtd->writesize * chip->ecc_strength_ds) / chip->ecc_step_ds;
4103 return corr >= ds_corr && ecc->strength >= chip->ecc_strength_ds;
4107 * nand_scan_tail - [NAND Interface] Scan for the NAND device
4108 * @mtd: MTD device structure
4110 * This is the second phase of the normal nand_scan() function. It fills out
4111 * all the uninitialized function pointers with the defaults and scans for a
4112 * bad block table if appropriate.
4114 int nand_scan_tail(struct mtd_info *mtd)
4117 struct nand_chip *chip = mtd_to_nand(mtd);
4118 struct nand_ecc_ctrl *ecc = &chip->ecc;
4119 struct nand_buffers *nbuf;
4121 /* New bad blocks should be marked in OOB, flash-based BBT, or both */
4122 BUG_ON((chip->bbt_options & NAND_BBT_NO_OOB_BBM) &&
4123 !(chip->bbt_options & NAND_BBT_USE_FLASH));
4125 if (!(chip->options & NAND_OWN_BUFFERS)) {
4126 nbuf = kzalloc(sizeof(*nbuf) + mtd->writesize
4127 + mtd->oobsize * 3, GFP_KERNEL);
4130 nbuf->ecccalc = (uint8_t *)(nbuf + 1);
4131 nbuf->ecccode = nbuf->ecccalc + mtd->oobsize;
4132 nbuf->databuf = nbuf->ecccode + mtd->oobsize;
4134 chip->buffers = nbuf;
4140 /* Set the internal oob buffer location, just after the page data */
4141 chip->oob_poi = chip->buffers->databuf + mtd->writesize;
4144 * If no default placement scheme is given, select an appropriate one.
4146 if (!ecc->layout && (ecc->mode != NAND_ECC_SOFT_BCH)) {
4147 switch (mtd->oobsize) {
4149 ecc->layout = &nand_oob_8;
4152 ecc->layout = &nand_oob_16;
4155 ecc->layout = &nand_oob_64;
4158 ecc->layout = &nand_oob_128;
4161 pr_warn("No oob scheme defined for oobsize %d\n",
4167 if (!chip->write_page)
4168 chip->write_page = nand_write_page;
4171 * Check ECC mode, default to software if 3byte/512byte hardware ECC is
4172 * selected and we have 256 byte pagesize fallback to software ECC
4175 switch (ecc->mode) {
4176 case NAND_ECC_HW_OOB_FIRST:
4177 /* Similar to NAND_ECC_HW, but a separate read_page handle */
4178 if (!ecc->calculate || !ecc->correct || !ecc->hwctl) {
4179 pr_warn("No ECC functions supplied; hardware ECC not possible\n");
4182 if (!ecc->read_page)
4183 ecc->read_page = nand_read_page_hwecc_oob_first;
4186 /* Use standard hwecc read page function? */
4187 if (!ecc->read_page)
4188 ecc->read_page = nand_read_page_hwecc;
4189 if (!ecc->write_page)
4190 ecc->write_page = nand_write_page_hwecc;
4191 if (!ecc->read_page_raw)
4192 ecc->read_page_raw = nand_read_page_raw;
4193 if (!ecc->write_page_raw)
4194 ecc->write_page_raw = nand_write_page_raw;
4196 ecc->read_oob = nand_read_oob_std;
4197 if (!ecc->write_oob)
4198 ecc->write_oob = nand_write_oob_std;
4199 if (!ecc->read_subpage)
4200 ecc->read_subpage = nand_read_subpage;
4201 if (!ecc->write_subpage && ecc->hwctl && ecc->calculate)
4202 ecc->write_subpage = nand_write_subpage_hwecc;
4204 case NAND_ECC_HW_SYNDROME:
4205 if ((!ecc->calculate || !ecc->correct || !ecc->hwctl) &&
4207 ecc->read_page == nand_read_page_hwecc ||
4209 ecc->write_page == nand_write_page_hwecc)) {
4210 pr_warn("No ECC functions supplied; hardware ECC not possible\n");
4213 /* Use standard syndrome read/write page function? */
4214 if (!ecc->read_page)
4215 ecc->read_page = nand_read_page_syndrome;
4216 if (!ecc->write_page)
4217 ecc->write_page = nand_write_page_syndrome;
4218 if (!ecc->read_page_raw)
4219 ecc->read_page_raw = nand_read_page_raw_syndrome;
4220 if (!ecc->write_page_raw)
4221 ecc->write_page_raw = nand_write_page_raw_syndrome;
4223 ecc->read_oob = nand_read_oob_syndrome;
4224 if (!ecc->write_oob)
4225 ecc->write_oob = nand_write_oob_syndrome;
4227 if (mtd->writesize >= ecc->size) {
4228 if (!ecc->strength) {
4229 pr_warn("Driver must set ecc.strength when using hardware ECC\n");
4234 pr_warn("%d byte HW ECC not possible on %d byte page size, fallback to SW ECC\n",
4235 ecc->size, mtd->writesize);
4236 ecc->mode = NAND_ECC_SOFT;
4239 ecc->calculate = nand_calculate_ecc;
4240 ecc->correct = nand_correct_data;
4241 ecc->read_page = nand_read_page_swecc;
4242 ecc->read_subpage = nand_read_subpage;
4243 ecc->write_page = nand_write_page_swecc;
4244 ecc->read_page_raw = nand_read_page_raw;
4245 ecc->write_page_raw = nand_write_page_raw;
4246 ecc->read_oob = nand_read_oob_std;
4247 ecc->write_oob = nand_write_oob_std;
4254 case NAND_ECC_SOFT_BCH:
4255 if (!mtd_nand_has_bch()) {
4256 pr_warn("CONFIG_MTD_NAND_ECC_BCH not enabled\n");
4259 ecc->calculate = nand_bch_calculate_ecc;
4260 ecc->correct = nand_bch_correct_data;
4261 ecc->read_page = nand_read_page_swecc;
4262 ecc->read_subpage = nand_read_subpage;
4263 ecc->write_page = nand_write_page_swecc;
4264 ecc->read_page_raw = nand_read_page_raw;
4265 ecc->write_page_raw = nand_write_page_raw;
4266 ecc->read_oob = nand_read_oob_std;
4267 ecc->write_oob = nand_write_oob_std;
4269 * Board driver should supply ecc.size and ecc.strength values
4270 * to select how many bits are correctable. Otherwise, default
4271 * to 4 bits for large page devices.
4273 if (!ecc->size && (mtd->oobsize >= 64)) {
4278 /* See nand_bch_init() for details. */
4280 ecc->priv = nand_bch_init(mtd);
4282 pr_warn("BCH ECC initialization failed!\n");
4288 pr_warn("NAND_ECC_NONE selected by board driver. This is not recommended!\n");
4289 ecc->read_page = nand_read_page_raw;
4290 ecc->write_page = nand_write_page_raw;
4291 ecc->read_oob = nand_read_oob_std;
4292 ecc->read_page_raw = nand_read_page_raw;
4293 ecc->write_page_raw = nand_write_page_raw;
4294 ecc->write_oob = nand_write_oob_std;
4295 ecc->size = mtd->writesize;
4301 pr_warn("Invalid NAND_ECC_MODE %d\n", ecc->mode);
4305 /* For many systems, the standard OOB write also works for raw */
4306 if (!ecc->read_oob_raw)
4307 ecc->read_oob_raw = ecc->read_oob;
4308 if (!ecc->write_oob_raw)
4309 ecc->write_oob_raw = ecc->write_oob;
4312 * The number of bytes available for a client to place data into
4313 * the out of band area.
4317 for (i = 0; ecc->layout->oobfree[i].length; i++)
4318 mtd->oobavail += ecc->layout->oobfree[i].length;
4321 /* ECC sanity check: warn if it's too weak */
4322 if (!nand_ecc_strength_good(mtd))
4323 pr_warn("WARNING: %s: the ECC used on your system is too weak compared to the one required by the NAND chip\n",
4327 * Set the number of read / write steps for one page depending on ECC
4330 ecc->steps = mtd->writesize / ecc->size;
4331 if (ecc->steps * ecc->size != mtd->writesize) {
4332 pr_warn("Invalid ECC parameters\n");
4335 ecc->total = ecc->steps * ecc->bytes;
4337 /* Allow subpage writes up to ecc.steps. Not possible for MLC flash */
4338 if (!(chip->options & NAND_NO_SUBPAGE_WRITE) && nand_is_slc(chip)) {
4339 switch (ecc->steps) {
4341 mtd->subpage_sft = 1;
4346 mtd->subpage_sft = 2;
4350 chip->subpagesize = mtd->writesize >> mtd->subpage_sft;
4352 /* Initialize state */
4353 chip->state = FL_READY;
4355 /* Invalidate the pagebuffer reference */
4358 /* Large page NAND with SOFT_ECC should support subpage reads */
4359 switch (ecc->mode) {
4361 case NAND_ECC_SOFT_BCH:
4362 if (chip->page_shift > 9)
4363 chip->options |= NAND_SUBPAGE_READ;
4370 /* Fill in remaining MTD driver data */
4371 mtd->type = nand_is_slc(chip) ? MTD_NANDFLASH : MTD_MLCNANDFLASH;
4372 mtd->flags = (chip->options & NAND_ROM) ? MTD_CAP_ROM :
4374 mtd->_erase = nand_erase;
4376 mtd->_unpoint = NULL;
4377 mtd->_read = nand_read;
4378 mtd->_write = nand_write;
4379 mtd->_panic_write = panic_nand_write;
4380 mtd->_read_oob = nand_read_oob;
4381 mtd->_write_oob = nand_write_oob;
4382 mtd->_sync = nand_sync;
4384 mtd->_unlock = NULL;
4385 mtd->_suspend = nand_suspend;
4386 mtd->_resume = nand_resume;
4387 mtd->_reboot = nand_shutdown;
4388 mtd->_block_isreserved = nand_block_isreserved;
4389 mtd->_block_isbad = nand_block_isbad;
4390 mtd->_block_markbad = nand_block_markbad;
4391 mtd->writebufsize = mtd->writesize;
4393 /* propagate ecc info to mtd_info */
4394 mtd->ecclayout = ecc->layout;
4395 mtd->ecc_strength = ecc->strength;
4396 mtd->ecc_step_size = ecc->size;
4398 * Initialize bitflip_threshold to its default prior scan_bbt() call.
4399 * scan_bbt() might invoke mtd_read(), thus bitflip_threshold must be
4402 if (!mtd->bitflip_threshold)
4403 mtd->bitflip_threshold = DIV_ROUND_UP(mtd->ecc_strength * 3, 4);
4405 /* Check, if we should skip the bad block table scan */
4406 if (chip->options & NAND_SKIP_BBTSCAN)
4409 /* Build bad block table */
4410 return chip->scan_bbt(mtd);
4412 EXPORT_SYMBOL(nand_scan_tail);
4415 * is_module_text_address() isn't exported, and it's mostly a pointless
4416 * test if this is a module _anyway_ -- they'd have to try _really_ hard
4417 * to call us from in-kernel code if the core NAND support is modular.
4420 #define caller_is_module() (1)
4422 #define caller_is_module() \
4423 is_module_text_address((unsigned long)__builtin_return_address(0))
4427 * nand_scan - [NAND Interface] Scan for the NAND device
4428 * @mtd: MTD device structure
4429 * @maxchips: number of chips to scan for
4431 * This fills out all the uninitialized function pointers with the defaults.
4432 * The flash ID is read and the mtd/chip structures are filled with the
4433 * appropriate values. The mtd->owner field must be set to the module of the
4436 int nand_scan(struct mtd_info *mtd, int maxchips)
4440 /* Many callers got this wrong, so check for it for a while... */
4441 if (!mtd->owner && caller_is_module()) {
4442 pr_crit("%s called with NULL mtd->owner!\n", __func__);
4446 ret = nand_scan_ident(mtd, maxchips, NULL);
4448 ret = nand_scan_tail(mtd);
4451 EXPORT_SYMBOL(nand_scan);
4454 * nand_release - [NAND Interface] Free resources held by the NAND device
4455 * @mtd: MTD device structure
4457 void nand_release(struct mtd_info *mtd)
4459 struct nand_chip *chip = mtd_to_nand(mtd);
4461 if (chip->ecc.mode == NAND_ECC_SOFT_BCH)
4462 nand_bch_free((struct nand_bch_control *)chip->ecc.priv);
4464 mtd_device_unregister(mtd);
4466 /* Free bad block table memory */
4468 if (!(chip->options & NAND_OWN_BUFFERS))
4469 kfree(chip->buffers);
4471 /* Free bad block descriptor memory */
4472 if (chip->badblock_pattern && chip->badblock_pattern->options
4473 & NAND_BBT_DYNAMICSTRUCT)
4474 kfree(chip->badblock_pattern);
4476 EXPORT_SYMBOL_GPL(nand_release);
4478 static int __init nand_base_init(void)
4480 led_trigger_register_simple("nand-disk", &nand_led_trigger);
4484 static void __exit nand_base_exit(void)
4486 led_trigger_unregister_simple(nand_led_trigger);
4489 module_init(nand_base_init);
4490 module_exit(nand_base_exit);
4492 MODULE_LICENSE("GPL");
4493 MODULE_AUTHOR("Steven J. Hill <sjhill@realitydiluted.com>");
4494 MODULE_AUTHOR("Thomas Gleixner <tglx@linutronix.de>");
4495 MODULE_DESCRIPTION("Generic NAND flash driver code");