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->priv;
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->priv;
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->priv;
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->priv;
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->priv;
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->priv;
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->priv;
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->priv;
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->priv;
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->priv;
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->priv;
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->priv;
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, int getchip)
322 int page, chipnr, res = 0, i = 0;
323 struct nand_chip *chip = mtd->priv;
326 if (chip->bbt_options & NAND_BBT_SCANLASTPAGE)
327 ofs += mtd->erasesize - mtd->writesize;
329 page = (int)(ofs >> chip->page_shift) & chip->pagemask;
332 chipnr = (int)(ofs >> chip->chip_shift);
334 nand_get_device(mtd, FL_READING);
336 /* Select the NAND device */
337 chip->select_chip(mtd, chipnr);
341 if (chip->options & NAND_BUSWIDTH_16) {
342 chip->cmdfunc(mtd, NAND_CMD_READOOB,
343 chip->badblockpos & 0xFE, page);
344 bad = cpu_to_le16(chip->read_word(mtd));
345 if (chip->badblockpos & 0x1)
350 chip->cmdfunc(mtd, NAND_CMD_READOOB, chip->badblockpos,
352 bad = chip->read_byte(mtd);
355 if (likely(chip->badblockbits == 8))
358 res = hweight8(bad) < chip->badblockbits;
359 ofs += mtd->writesize;
360 page = (int)(ofs >> chip->page_shift) & chip->pagemask;
362 } while (!res && i < 2 && (chip->bbt_options & NAND_BBT_SCAN2NDPAGE));
365 chip->select_chip(mtd, -1);
366 nand_release_device(mtd);
373 * nand_default_block_markbad - [DEFAULT] mark a block bad via bad block marker
374 * @mtd: MTD device structure
375 * @ofs: offset from device start
377 * This is the default implementation, which can be overridden by a hardware
378 * specific driver. It provides the details for writing a bad block marker to a
381 static int nand_default_block_markbad(struct mtd_info *mtd, loff_t ofs)
383 struct nand_chip *chip = mtd->priv;
384 struct mtd_oob_ops ops;
385 uint8_t buf[2] = { 0, 0 };
386 int ret = 0, res, i = 0;
388 memset(&ops, 0, sizeof(ops));
390 ops.ooboffs = chip->badblockpos;
391 if (chip->options & NAND_BUSWIDTH_16) {
392 ops.ooboffs &= ~0x01;
393 ops.len = ops.ooblen = 2;
395 ops.len = ops.ooblen = 1;
397 ops.mode = MTD_OPS_PLACE_OOB;
399 /* Write to first/last page(s) if necessary */
400 if (chip->bbt_options & NAND_BBT_SCANLASTPAGE)
401 ofs += mtd->erasesize - mtd->writesize;
403 res = nand_do_write_oob(mtd, ofs, &ops);
408 ofs += mtd->writesize;
409 } while ((chip->bbt_options & NAND_BBT_SCAN2NDPAGE) && i < 2);
415 * nand_block_markbad_lowlevel - mark a block bad
416 * @mtd: MTD device structure
417 * @ofs: offset from device start
419 * This function performs the generic NAND bad block marking steps (i.e., bad
420 * block table(s) and/or marker(s)). We only allow the hardware driver to
421 * specify how to write bad block markers to OOB (chip->block_markbad).
423 * We try operations in the following order:
424 * (1) erase the affected block, to allow OOB marker to be written cleanly
425 * (2) write bad block marker to OOB area of affected block (unless flag
426 * NAND_BBT_NO_OOB_BBM is present)
428 * Note that we retain the first error encountered in (2) or (3), finish the
429 * procedures, and dump the error in the end.
431 static int nand_block_markbad_lowlevel(struct mtd_info *mtd, loff_t ofs)
433 struct nand_chip *chip = mtd->priv;
436 if (!(chip->bbt_options & NAND_BBT_NO_OOB_BBM)) {
437 struct erase_info einfo;
439 /* Attempt erase before marking OOB */
440 memset(&einfo, 0, sizeof(einfo));
443 einfo.len = 1ULL << chip->phys_erase_shift;
444 nand_erase_nand(mtd, &einfo, 0);
446 /* Write bad block marker to OOB */
447 nand_get_device(mtd, FL_WRITING);
448 ret = chip->block_markbad(mtd, ofs);
449 nand_release_device(mtd);
452 /* Mark block bad in BBT */
454 res = nand_markbad_bbt(mtd, ofs);
460 mtd->ecc_stats.badblocks++;
466 * nand_check_wp - [GENERIC] check if the chip is write protected
467 * @mtd: MTD device structure
469 * Check, if the device is write protected. The function expects, that the
470 * device is already selected.
472 static int nand_check_wp(struct mtd_info *mtd)
474 struct nand_chip *chip = mtd->priv;
476 /* Broken xD cards report WP despite being writable */
477 if (chip->options & NAND_BROKEN_XD)
480 /* Check the WP bit */
481 chip->cmdfunc(mtd, NAND_CMD_STATUS, -1, -1);
482 return (chip->read_byte(mtd) & NAND_STATUS_WP) ? 0 : 1;
486 * nand_block_isreserved - [GENERIC] Check if a block is marked reserved.
487 * @mtd: MTD device structure
488 * @ofs: offset from device start
490 * Check if the block is marked as reserved.
492 static int nand_block_isreserved(struct mtd_info *mtd, loff_t ofs)
494 struct nand_chip *chip = mtd->priv;
498 /* Return info from the table */
499 return nand_isreserved_bbt(mtd, ofs);
503 * nand_block_checkbad - [GENERIC] Check if a block is marked bad
504 * @mtd: MTD device structure
505 * @ofs: offset from device start
506 * @getchip: 0, if the chip is already selected
507 * @allowbbt: 1, if its allowed to access the bbt area
509 * Check, if the block is bad. Either by reading the bad block table or
510 * calling of the scan function.
512 static int nand_block_checkbad(struct mtd_info *mtd, loff_t ofs, int getchip,
515 struct nand_chip *chip = mtd->priv;
518 return chip->block_bad(mtd, ofs, getchip);
520 /* Return info from the table */
521 return nand_isbad_bbt(mtd, ofs, allowbbt);
525 * panic_nand_wait_ready - [GENERIC] Wait for the ready pin after commands.
526 * @mtd: MTD device structure
529 * Helper function for nand_wait_ready used when needing to wait in interrupt
532 static void panic_nand_wait_ready(struct mtd_info *mtd, unsigned long timeo)
534 struct nand_chip *chip = mtd->priv;
537 /* Wait for the device to get ready */
538 for (i = 0; i < timeo; i++) {
539 if (chip->dev_ready(mtd))
541 touch_softlockup_watchdog();
547 * nand_wait_ready - [GENERIC] Wait for the ready pin after commands.
548 * @mtd: MTD device structure
550 * Wait for the ready pin after a command, and warn if a timeout occurs.
552 void nand_wait_ready(struct mtd_info *mtd)
554 struct nand_chip *chip = mtd->priv;
555 unsigned long timeo = 400;
557 if (in_interrupt() || oops_in_progress)
558 return panic_nand_wait_ready(mtd, timeo);
560 led_trigger_event(nand_led_trigger, LED_FULL);
561 /* Wait until command is processed or timeout occurs */
562 timeo = jiffies + msecs_to_jiffies(timeo);
564 if (chip->dev_ready(mtd))
567 } while (time_before(jiffies, timeo));
570 "timeout while waiting for chip to become ready\n");
572 led_trigger_event(nand_led_trigger, LED_OFF);
574 EXPORT_SYMBOL_GPL(nand_wait_ready);
577 * nand_wait_status_ready - [GENERIC] Wait for the ready status after commands.
578 * @mtd: MTD device structure
579 * @timeo: Timeout in ms
581 * Wait for status ready (i.e. command done) or timeout.
583 static void nand_wait_status_ready(struct mtd_info *mtd, unsigned long timeo)
585 register struct nand_chip *chip = mtd->priv;
587 timeo = jiffies + msecs_to_jiffies(timeo);
589 if ((chip->read_byte(mtd) & NAND_STATUS_READY))
591 touch_softlockup_watchdog();
592 } while (time_before(jiffies, timeo));
596 * nand_command - [DEFAULT] Send command to NAND device
597 * @mtd: MTD device structure
598 * @command: the command to be sent
599 * @column: the column address for this command, -1 if none
600 * @page_addr: the page address for this command, -1 if none
602 * Send command to NAND device. This function is used for small page devices
603 * (512 Bytes per page).
605 static void nand_command(struct mtd_info *mtd, unsigned int command,
606 int column, int page_addr)
608 register struct nand_chip *chip = mtd->priv;
609 int ctrl = NAND_CTRL_CLE | NAND_CTRL_CHANGE;
611 /* Write out the command to the device */
612 if (command == NAND_CMD_SEQIN) {
615 if (column >= mtd->writesize) {
617 column -= mtd->writesize;
618 readcmd = NAND_CMD_READOOB;
619 } else if (column < 256) {
620 /* First 256 bytes --> READ0 */
621 readcmd = NAND_CMD_READ0;
624 readcmd = NAND_CMD_READ1;
626 chip->cmd_ctrl(mtd, readcmd, ctrl);
627 ctrl &= ~NAND_CTRL_CHANGE;
629 if (command != NAND_CMD_NONE)
630 chip->cmd_ctrl(mtd, command, ctrl);
632 /* Address cycle, when necessary */
633 ctrl = NAND_CTRL_ALE | NAND_CTRL_CHANGE;
634 /* Serially input address */
636 /* Adjust columns for 16 bit buswidth */
637 if (chip->options & NAND_BUSWIDTH_16 &&
638 !nand_opcode_8bits(command))
640 chip->cmd_ctrl(mtd, column, ctrl);
641 ctrl &= ~NAND_CTRL_CHANGE;
643 if (page_addr != -1) {
644 chip->cmd_ctrl(mtd, page_addr, ctrl);
645 ctrl &= ~NAND_CTRL_CHANGE;
646 chip->cmd_ctrl(mtd, page_addr >> 8, ctrl);
647 /* One more address cycle for devices > 32MiB */
648 if (chip->chipsize > (32 << 20))
649 chip->cmd_ctrl(mtd, page_addr >> 16, ctrl);
651 chip->cmd_ctrl(mtd, NAND_CMD_NONE, NAND_NCE | NAND_CTRL_CHANGE);
654 * Program and erase have their own busy handlers status and sequential
660 case NAND_CMD_PAGEPROG:
661 case NAND_CMD_ERASE1:
662 case NAND_CMD_ERASE2:
664 case NAND_CMD_STATUS:
670 udelay(chip->chip_delay);
671 chip->cmd_ctrl(mtd, NAND_CMD_STATUS,
672 NAND_CTRL_CLE | NAND_CTRL_CHANGE);
674 NAND_CMD_NONE, NAND_NCE | NAND_CTRL_CHANGE);
675 /* EZ-NAND can take upto 250ms as per ONFi v4.0 */
676 nand_wait_status_ready(mtd, 250);
679 /* This applies to read commands */
682 * If we don't have access to the busy pin, we apply the given
685 if (!chip->dev_ready) {
686 udelay(chip->chip_delay);
691 * Apply this short delay always to ensure that we do wait tWB in
692 * any case on any machine.
696 nand_wait_ready(mtd);
700 * nand_command_lp - [DEFAULT] Send command to NAND large page device
701 * @mtd: MTD device structure
702 * @command: the command to be sent
703 * @column: the column address for this command, -1 if none
704 * @page_addr: the page address for this command, -1 if none
706 * Send command to NAND device. This is the version for the new large page
707 * devices. We don't have the separate regions as we have in the small page
708 * devices. We must emulate NAND_CMD_READOOB to keep the code compatible.
710 static void nand_command_lp(struct mtd_info *mtd, unsigned int command,
711 int column, int page_addr)
713 register struct nand_chip *chip = mtd->priv;
715 /* Emulate NAND_CMD_READOOB */
716 if (command == NAND_CMD_READOOB) {
717 column += mtd->writesize;
718 command = NAND_CMD_READ0;
721 /* Command latch cycle */
722 if (command != NAND_CMD_NONE)
723 chip->cmd_ctrl(mtd, command,
724 NAND_NCE | NAND_CLE | NAND_CTRL_CHANGE);
726 if (column != -1 || page_addr != -1) {
727 int ctrl = NAND_CTRL_CHANGE | NAND_NCE | NAND_ALE;
729 /* Serially input address */
731 /* Adjust columns for 16 bit buswidth */
732 if (chip->options & NAND_BUSWIDTH_16 &&
733 !nand_opcode_8bits(command))
735 chip->cmd_ctrl(mtd, column, ctrl);
736 ctrl &= ~NAND_CTRL_CHANGE;
737 chip->cmd_ctrl(mtd, column >> 8, ctrl);
739 if (page_addr != -1) {
740 chip->cmd_ctrl(mtd, page_addr, ctrl);
741 chip->cmd_ctrl(mtd, page_addr >> 8,
742 NAND_NCE | NAND_ALE);
743 /* One more address cycle for devices > 128MiB */
744 if (chip->chipsize > (128 << 20))
745 chip->cmd_ctrl(mtd, page_addr >> 16,
746 NAND_NCE | NAND_ALE);
749 chip->cmd_ctrl(mtd, NAND_CMD_NONE, NAND_NCE | NAND_CTRL_CHANGE);
752 * Program and erase have their own busy handlers status, sequential
753 * in and status need no delay.
758 case NAND_CMD_CACHEDPROG:
759 case NAND_CMD_PAGEPROG:
760 case NAND_CMD_ERASE1:
761 case NAND_CMD_ERASE2:
764 case NAND_CMD_STATUS:
770 udelay(chip->chip_delay);
771 chip->cmd_ctrl(mtd, NAND_CMD_STATUS,
772 NAND_NCE | NAND_CLE | NAND_CTRL_CHANGE);
773 chip->cmd_ctrl(mtd, NAND_CMD_NONE,
774 NAND_NCE | NAND_CTRL_CHANGE);
775 /* EZ-NAND can take upto 250ms as per ONFi v4.0 */
776 nand_wait_status_ready(mtd, 250);
779 case NAND_CMD_RNDOUT:
780 /* No ready / busy check necessary */
781 chip->cmd_ctrl(mtd, NAND_CMD_RNDOUTSTART,
782 NAND_NCE | NAND_CLE | NAND_CTRL_CHANGE);
783 chip->cmd_ctrl(mtd, NAND_CMD_NONE,
784 NAND_NCE | NAND_CTRL_CHANGE);
788 chip->cmd_ctrl(mtd, NAND_CMD_READSTART,
789 NAND_NCE | NAND_CLE | NAND_CTRL_CHANGE);
790 chip->cmd_ctrl(mtd, NAND_CMD_NONE,
791 NAND_NCE | NAND_CTRL_CHANGE);
793 /* This applies to read commands */
796 * If we don't have access to the busy pin, we apply the given
799 if (!chip->dev_ready) {
800 udelay(chip->chip_delay);
806 * Apply this short delay always to ensure that we do wait tWB in
807 * any case on any machine.
811 nand_wait_ready(mtd);
815 * panic_nand_get_device - [GENERIC] Get chip for selected access
816 * @chip: the nand chip descriptor
817 * @mtd: MTD device structure
818 * @new_state: the state which is requested
820 * Used when in panic, no locks are taken.
822 static void panic_nand_get_device(struct nand_chip *chip,
823 struct mtd_info *mtd, int new_state)
825 /* Hardware controller shared among independent devices */
826 chip->controller->active = chip;
827 chip->state = new_state;
831 * nand_get_device - [GENERIC] Get chip for selected access
832 * @mtd: MTD device structure
833 * @new_state: the state which is requested
835 * Get the device and lock it for exclusive access
838 nand_get_device(struct mtd_info *mtd, int new_state)
840 struct nand_chip *chip = mtd->priv;
841 spinlock_t *lock = &chip->controller->lock;
842 wait_queue_head_t *wq = &chip->controller->wq;
843 DECLARE_WAITQUEUE(wait, current);
847 /* Hardware controller shared among independent devices */
848 if (!chip->controller->active)
849 chip->controller->active = chip;
851 if (chip->controller->active == chip && chip->state == FL_READY) {
852 chip->state = new_state;
856 if (new_state == FL_PM_SUSPENDED) {
857 if (chip->controller->active->state == FL_PM_SUSPENDED) {
858 chip->state = FL_PM_SUSPENDED;
863 set_current_state(TASK_UNINTERRUPTIBLE);
864 add_wait_queue(wq, &wait);
867 remove_wait_queue(wq, &wait);
872 * panic_nand_wait - [GENERIC] wait until the command is done
873 * @mtd: MTD device structure
874 * @chip: NAND chip structure
877 * Wait for command done. This is a helper function for nand_wait used when
878 * we are in interrupt context. May happen when in panic and trying to write
879 * an oops through mtdoops.
881 static void panic_nand_wait(struct mtd_info *mtd, struct nand_chip *chip,
885 for (i = 0; i < timeo; i++) {
886 if (chip->dev_ready) {
887 if (chip->dev_ready(mtd))
890 if (chip->read_byte(mtd) & NAND_STATUS_READY)
898 * nand_wait - [DEFAULT] wait until the command is done
899 * @mtd: MTD device structure
900 * @chip: NAND chip structure
902 * Wait for command done. This applies to erase and program only.
904 static int nand_wait(struct mtd_info *mtd, struct nand_chip *chip)
908 unsigned long timeo = 400;
910 led_trigger_event(nand_led_trigger, LED_FULL);
913 * Apply this short delay always to ensure that we do wait tWB in any
914 * case on any machine.
918 chip->cmdfunc(mtd, NAND_CMD_STATUS, -1, -1);
920 if (in_interrupt() || oops_in_progress)
921 panic_nand_wait(mtd, chip, timeo);
923 timeo = jiffies + msecs_to_jiffies(timeo);
925 if (chip->dev_ready) {
926 if (chip->dev_ready(mtd))
929 if (chip->read_byte(mtd) & NAND_STATUS_READY)
933 } while (time_before(jiffies, timeo));
935 led_trigger_event(nand_led_trigger, LED_OFF);
937 status = (int)chip->read_byte(mtd);
938 /* This can happen if in case of timeout or buggy dev_ready */
939 WARN_ON(!(status & NAND_STATUS_READY));
944 * __nand_unlock - [REPLACEABLE] unlocks specified locked blocks
946 * @ofs: offset to start unlock from
947 * @len: length to unlock
948 * @invert: when = 0, unlock the range of blocks within the lower and
949 * upper boundary address
950 * when = 1, unlock the range of blocks outside the boundaries
951 * of the lower and upper boundary address
953 * Returs unlock status.
955 static int __nand_unlock(struct mtd_info *mtd, loff_t ofs,
956 uint64_t len, int invert)
960 struct nand_chip *chip = mtd->priv;
962 /* Submit address of first page to unlock */
963 page = ofs >> chip->page_shift;
964 chip->cmdfunc(mtd, NAND_CMD_UNLOCK1, -1, page & chip->pagemask);
966 /* Submit address of last page to unlock */
967 page = (ofs + len) >> chip->page_shift;
968 chip->cmdfunc(mtd, NAND_CMD_UNLOCK2, -1,
969 (page | invert) & chip->pagemask);
971 /* Call wait ready function */
972 status = chip->waitfunc(mtd, chip);
973 /* See if device thinks it succeeded */
974 if (status & NAND_STATUS_FAIL) {
975 pr_debug("%s: error status = 0x%08x\n",
984 * nand_unlock - [REPLACEABLE] unlocks specified locked blocks
986 * @ofs: offset to start unlock from
987 * @len: length to unlock
989 * Returns unlock status.
991 int nand_unlock(struct mtd_info *mtd, loff_t ofs, uint64_t len)
995 struct nand_chip *chip = mtd->priv;
997 pr_debug("%s: start = 0x%012llx, len = %llu\n",
998 __func__, (unsigned long long)ofs, len);
1000 if (check_offs_len(mtd, ofs, len))
1003 /* Align to last block address if size addresses end of the device */
1004 if (ofs + len == mtd->size)
1005 len -= mtd->erasesize;
1007 nand_get_device(mtd, FL_UNLOCKING);
1009 /* Shift to get chip number */
1010 chipnr = ofs >> chip->chip_shift;
1012 chip->select_chip(mtd, chipnr);
1016 * If we want to check the WP through READ STATUS and check the bit 7
1017 * we must reset the chip
1018 * some operation can also clear the bit 7 of status register
1019 * eg. erase/program a locked block
1021 chip->cmdfunc(mtd, NAND_CMD_RESET, -1, -1);
1023 /* Check, if it is write protected */
1024 if (nand_check_wp(mtd)) {
1025 pr_debug("%s: device is write protected!\n",
1031 ret = __nand_unlock(mtd, ofs, len, 0);
1034 chip->select_chip(mtd, -1);
1035 nand_release_device(mtd);
1039 EXPORT_SYMBOL(nand_unlock);
1042 * nand_lock - [REPLACEABLE] locks all blocks present in the device
1044 * @ofs: offset to start unlock from
1045 * @len: length to unlock
1047 * This feature is not supported in many NAND parts. 'Micron' NAND parts do
1048 * have this feature, but it allows only to lock all blocks, not for specified
1049 * range for block. Implementing 'lock' feature by making use of 'unlock', for
1052 * Returns lock status.
1054 int nand_lock(struct mtd_info *mtd, loff_t ofs, uint64_t len)
1057 int chipnr, status, page;
1058 struct nand_chip *chip = mtd->priv;
1060 pr_debug("%s: start = 0x%012llx, len = %llu\n",
1061 __func__, (unsigned long long)ofs, len);
1063 if (check_offs_len(mtd, ofs, len))
1066 nand_get_device(mtd, FL_LOCKING);
1068 /* Shift to get chip number */
1069 chipnr = ofs >> chip->chip_shift;
1071 chip->select_chip(mtd, chipnr);
1075 * If we want to check the WP through READ STATUS and check the bit 7
1076 * we must reset the chip
1077 * some operation can also clear the bit 7 of status register
1078 * eg. erase/program a locked block
1080 chip->cmdfunc(mtd, NAND_CMD_RESET, -1, -1);
1082 /* Check, if it is write protected */
1083 if (nand_check_wp(mtd)) {
1084 pr_debug("%s: device is write protected!\n",
1086 status = MTD_ERASE_FAILED;
1091 /* Submit address of first page to lock */
1092 page = ofs >> chip->page_shift;
1093 chip->cmdfunc(mtd, NAND_CMD_LOCK, -1, page & chip->pagemask);
1095 /* Call wait ready function */
1096 status = chip->waitfunc(mtd, chip);
1097 /* See if device thinks it succeeded */
1098 if (status & NAND_STATUS_FAIL) {
1099 pr_debug("%s: error status = 0x%08x\n",
1105 ret = __nand_unlock(mtd, ofs, len, 0x1);
1108 chip->select_chip(mtd, -1);
1109 nand_release_device(mtd);
1113 EXPORT_SYMBOL(nand_lock);
1116 * nand_check_erased_buf - check if a buffer contains (almost) only 0xff data
1117 * @buf: buffer to test
1118 * @len: buffer length
1119 * @bitflips_threshold: maximum number of bitflips
1121 * Check if a buffer contains only 0xff, which means the underlying region
1122 * has been erased and is ready to be programmed.
1123 * The bitflips_threshold specify the maximum number of bitflips before
1124 * considering the region is not erased.
1125 * Note: The logic of this function has been extracted from the memweight
1126 * implementation, except that nand_check_erased_buf function exit before
1127 * testing the whole buffer if the number of bitflips exceed the
1128 * bitflips_threshold value.
1130 * Returns a positive number of bitflips less than or equal to
1131 * bitflips_threshold, or -ERROR_CODE for bitflips in excess of the
1134 static int nand_check_erased_buf(void *buf, int len, int bitflips_threshold)
1136 const unsigned char *bitmap = buf;
1140 for (; len && ((uintptr_t)bitmap) % sizeof(long);
1142 weight = hweight8(*bitmap);
1143 bitflips += BITS_PER_BYTE - weight;
1144 if (unlikely(bitflips > bitflips_threshold))
1148 for (; len >= sizeof(long);
1149 len -= sizeof(long), bitmap += sizeof(long)) {
1150 weight = hweight_long(*((unsigned long *)bitmap));
1151 bitflips += BITS_PER_LONG - weight;
1152 if (unlikely(bitflips > bitflips_threshold))
1156 for (; len > 0; len--, bitmap++) {
1157 weight = hweight8(*bitmap);
1158 bitflips += BITS_PER_BYTE - weight;
1159 if (unlikely(bitflips > bitflips_threshold))
1167 * nand_check_erased_ecc_chunk - check if an ECC chunk contains (almost) only
1169 * @data: data buffer to test
1170 * @datalen: data length
1172 * @ecclen: ECC length
1173 * @extraoob: extra OOB buffer
1174 * @extraooblen: extra OOB length
1175 * @bitflips_threshold: maximum number of bitflips
1177 * Check if a data buffer and its associated ECC and OOB data contains only
1178 * 0xff pattern, which means the underlying region has been erased and is
1179 * ready to be programmed.
1180 * The bitflips_threshold specify the maximum number of bitflips before
1181 * considering the region as not erased.
1184 * 1/ ECC algorithms are working on pre-defined block sizes which are usually
1185 * different from the NAND page size. When fixing bitflips, ECC engines will
1186 * report the number of errors per chunk, and the NAND core infrastructure
1187 * expect you to return the maximum number of bitflips for the whole page.
1188 * This is why you should always use this function on a single chunk and
1189 * not on the whole page. After checking each chunk you should update your
1190 * max_bitflips value accordingly.
1191 * 2/ When checking for bitflips in erased pages you should not only check
1192 * the payload data but also their associated ECC data, because a user might
1193 * have programmed almost all bits to 1 but a few. In this case, we
1194 * shouldn't consider the chunk as erased, and checking ECC bytes prevent
1196 * 3/ The extraoob argument is optional, and should be used if some of your OOB
1197 * data are protected by the ECC engine.
1198 * It could also be used if you support subpages and want to attach some
1199 * extra OOB data to an ECC chunk.
1201 * Returns a positive number of bitflips less than or equal to
1202 * bitflips_threshold, or -ERROR_CODE for bitflips in excess of the
1203 * threshold. In case of success, the passed buffers are filled with 0xff.
1205 int nand_check_erased_ecc_chunk(void *data, int datalen,
1206 void *ecc, int ecclen,
1207 void *extraoob, int extraooblen,
1208 int bitflips_threshold)
1210 int data_bitflips = 0, ecc_bitflips = 0, extraoob_bitflips = 0;
1212 data_bitflips = nand_check_erased_buf(data, datalen,
1213 bitflips_threshold);
1214 if (data_bitflips < 0)
1215 return data_bitflips;
1217 bitflips_threshold -= data_bitflips;
1219 ecc_bitflips = nand_check_erased_buf(ecc, ecclen, bitflips_threshold);
1220 if (ecc_bitflips < 0)
1221 return ecc_bitflips;
1223 bitflips_threshold -= ecc_bitflips;
1225 extraoob_bitflips = nand_check_erased_buf(extraoob, extraooblen,
1226 bitflips_threshold);
1227 if (extraoob_bitflips < 0)
1228 return extraoob_bitflips;
1231 memset(data, 0xff, datalen);
1234 memset(ecc, 0xff, ecclen);
1236 if (extraoob_bitflips)
1237 memset(extraoob, 0xff, extraooblen);
1239 return data_bitflips + ecc_bitflips + extraoob_bitflips;
1241 EXPORT_SYMBOL(nand_check_erased_ecc_chunk);
1244 * nand_read_page_raw - [INTERN] read raw page data without ecc
1245 * @mtd: mtd info structure
1246 * @chip: nand chip info structure
1247 * @buf: buffer to store read data
1248 * @oob_required: caller requires OOB data read to chip->oob_poi
1249 * @page: page number to read
1251 * Not for syndrome calculating ECC controllers, which use a special oob layout.
1253 static int nand_read_page_raw(struct mtd_info *mtd, struct nand_chip *chip,
1254 uint8_t *buf, int oob_required, int page)
1256 chip->read_buf(mtd, buf, mtd->writesize);
1258 chip->read_buf(mtd, chip->oob_poi, mtd->oobsize);
1263 * nand_read_page_raw_syndrome - [INTERN] read raw page data without ecc
1264 * @mtd: mtd info structure
1265 * @chip: nand chip info structure
1266 * @buf: buffer to store read data
1267 * @oob_required: caller requires OOB data read to chip->oob_poi
1268 * @page: page number to read
1270 * We need a special oob layout and handling even when OOB isn't used.
1272 static int nand_read_page_raw_syndrome(struct mtd_info *mtd,
1273 struct nand_chip *chip, uint8_t *buf,
1274 int oob_required, int page)
1276 int eccsize = chip->ecc.size;
1277 int eccbytes = chip->ecc.bytes;
1278 uint8_t *oob = chip->oob_poi;
1281 for (steps = chip->ecc.steps; steps > 0; steps--) {
1282 chip->read_buf(mtd, buf, eccsize);
1285 if (chip->ecc.prepad) {
1286 chip->read_buf(mtd, oob, chip->ecc.prepad);
1287 oob += chip->ecc.prepad;
1290 chip->read_buf(mtd, oob, eccbytes);
1293 if (chip->ecc.postpad) {
1294 chip->read_buf(mtd, oob, chip->ecc.postpad);
1295 oob += chip->ecc.postpad;
1299 size = mtd->oobsize - (oob - chip->oob_poi);
1301 chip->read_buf(mtd, oob, size);
1307 * nand_read_page_swecc - [REPLACEABLE] software ECC based page read function
1308 * @mtd: mtd info structure
1309 * @chip: nand chip info structure
1310 * @buf: buffer to store read data
1311 * @oob_required: caller requires OOB data read to chip->oob_poi
1312 * @page: page number to read
1314 static int nand_read_page_swecc(struct mtd_info *mtd, struct nand_chip *chip,
1315 uint8_t *buf, int oob_required, int page)
1317 int i, eccsize = chip->ecc.size;
1318 int eccbytes = chip->ecc.bytes;
1319 int eccsteps = chip->ecc.steps;
1321 uint8_t *ecc_calc = chip->buffers->ecccalc;
1322 uint8_t *ecc_code = chip->buffers->ecccode;
1323 uint32_t *eccpos = chip->ecc.layout->eccpos;
1324 unsigned int max_bitflips = 0;
1326 chip->ecc.read_page_raw(mtd, chip, buf, 1, page);
1328 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize)
1329 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
1331 for (i = 0; i < chip->ecc.total; i++)
1332 ecc_code[i] = chip->oob_poi[eccpos[i]];
1334 eccsteps = chip->ecc.steps;
1337 for (i = 0 ; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
1340 stat = chip->ecc.correct(mtd, p, &ecc_code[i], &ecc_calc[i]);
1342 mtd->ecc_stats.failed++;
1344 mtd->ecc_stats.corrected += stat;
1345 max_bitflips = max_t(unsigned int, max_bitflips, stat);
1348 return max_bitflips;
1352 * nand_read_subpage - [REPLACEABLE] ECC based sub-page read function
1353 * @mtd: mtd info structure
1354 * @chip: nand chip info structure
1355 * @data_offs: offset of requested data within the page
1356 * @readlen: data length
1357 * @bufpoi: buffer to store read data
1358 * @page: page number to read
1360 static int nand_read_subpage(struct mtd_info *mtd, struct nand_chip *chip,
1361 uint32_t data_offs, uint32_t readlen, uint8_t *bufpoi,
1364 int start_step, end_step, num_steps;
1365 uint32_t *eccpos = chip->ecc.layout->eccpos;
1367 int data_col_addr, i, gaps = 0;
1368 int datafrag_len, eccfrag_len, aligned_len, aligned_pos;
1369 int busw = (chip->options & NAND_BUSWIDTH_16) ? 2 : 1;
1371 unsigned int max_bitflips = 0;
1373 /* Column address within the page aligned to ECC size (256bytes) */
1374 start_step = data_offs / chip->ecc.size;
1375 end_step = (data_offs + readlen - 1) / chip->ecc.size;
1376 num_steps = end_step - start_step + 1;
1377 index = start_step * chip->ecc.bytes;
1379 /* Data size aligned to ECC ecc.size */
1380 datafrag_len = num_steps * chip->ecc.size;
1381 eccfrag_len = num_steps * chip->ecc.bytes;
1383 data_col_addr = start_step * chip->ecc.size;
1384 /* If we read not a page aligned data */
1385 if (data_col_addr != 0)
1386 chip->cmdfunc(mtd, NAND_CMD_RNDOUT, data_col_addr, -1);
1388 p = bufpoi + data_col_addr;
1389 chip->read_buf(mtd, p, datafrag_len);
1392 for (i = 0; i < eccfrag_len ; i += chip->ecc.bytes, p += chip->ecc.size)
1393 chip->ecc.calculate(mtd, p, &chip->buffers->ecccalc[i]);
1396 * The performance is faster if we position offsets according to
1397 * ecc.pos. Let's make sure that there are no gaps in ECC positions.
1399 for (i = 0; i < eccfrag_len - 1; i++) {
1400 if (eccpos[i + index] + 1 != eccpos[i + index + 1]) {
1406 chip->cmdfunc(mtd, NAND_CMD_RNDOUT, mtd->writesize, -1);
1407 chip->read_buf(mtd, chip->oob_poi, mtd->oobsize);
1410 * Send the command to read the particular ECC bytes take care
1411 * about buswidth alignment in read_buf.
1413 aligned_pos = eccpos[index] & ~(busw - 1);
1414 aligned_len = eccfrag_len;
1415 if (eccpos[index] & (busw - 1))
1417 if (eccpos[index + (num_steps * chip->ecc.bytes)] & (busw - 1))
1420 chip->cmdfunc(mtd, NAND_CMD_RNDOUT,
1421 mtd->writesize + aligned_pos, -1);
1422 chip->read_buf(mtd, &chip->oob_poi[aligned_pos], aligned_len);
1425 for (i = 0; i < eccfrag_len; i++)
1426 chip->buffers->ecccode[i] = chip->oob_poi[eccpos[i + index]];
1428 p = bufpoi + data_col_addr;
1429 for (i = 0; i < eccfrag_len ; i += chip->ecc.bytes, p += chip->ecc.size) {
1432 stat = chip->ecc.correct(mtd, p,
1433 &chip->buffers->ecccode[i], &chip->buffers->ecccalc[i]);
1435 mtd->ecc_stats.failed++;
1437 mtd->ecc_stats.corrected += stat;
1438 max_bitflips = max_t(unsigned int, max_bitflips, stat);
1441 return max_bitflips;
1445 * nand_read_page_hwecc - [REPLACEABLE] hardware ECC based page read function
1446 * @mtd: mtd info structure
1447 * @chip: nand chip info structure
1448 * @buf: buffer to store read data
1449 * @oob_required: caller requires OOB data read to chip->oob_poi
1450 * @page: page number to read
1452 * Not for syndrome calculating ECC controllers which need a special oob layout.
1454 static int nand_read_page_hwecc(struct mtd_info *mtd, struct nand_chip *chip,
1455 uint8_t *buf, int oob_required, int page)
1457 int i, eccsize = chip->ecc.size;
1458 int eccbytes = chip->ecc.bytes;
1459 int eccsteps = chip->ecc.steps;
1461 uint8_t *ecc_calc = chip->buffers->ecccalc;
1462 uint8_t *ecc_code = chip->buffers->ecccode;
1463 uint32_t *eccpos = chip->ecc.layout->eccpos;
1464 unsigned int max_bitflips = 0;
1466 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
1467 chip->ecc.hwctl(mtd, NAND_ECC_READ);
1468 chip->read_buf(mtd, p, eccsize);
1469 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
1471 chip->read_buf(mtd, chip->oob_poi, mtd->oobsize);
1473 for (i = 0; i < chip->ecc.total; i++)
1474 ecc_code[i] = chip->oob_poi[eccpos[i]];
1476 eccsteps = chip->ecc.steps;
1479 for (i = 0 ; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
1482 stat = chip->ecc.correct(mtd, p, &ecc_code[i], &ecc_calc[i]);
1484 mtd->ecc_stats.failed++;
1486 mtd->ecc_stats.corrected += stat;
1487 max_bitflips = max_t(unsigned int, max_bitflips, stat);
1490 return max_bitflips;
1494 * nand_read_page_hwecc_oob_first - [REPLACEABLE] hw ecc, read oob first
1495 * @mtd: mtd info structure
1496 * @chip: nand chip info structure
1497 * @buf: buffer to store read data
1498 * @oob_required: caller requires OOB data read to chip->oob_poi
1499 * @page: page number to read
1501 * Hardware ECC for large page chips, require OOB to be read first. For this
1502 * ECC mode, the write_page method is re-used from ECC_HW. These methods
1503 * read/write ECC from the OOB area, unlike the ECC_HW_SYNDROME support with
1504 * multiple ECC steps, follows the "infix ECC" scheme and reads/writes ECC from
1505 * the data area, by overwriting the NAND manufacturer bad block markings.
1507 static int nand_read_page_hwecc_oob_first(struct mtd_info *mtd,
1508 struct nand_chip *chip, uint8_t *buf, int oob_required, int page)
1510 int i, eccsize = chip->ecc.size;
1511 int eccbytes = chip->ecc.bytes;
1512 int eccsteps = chip->ecc.steps;
1514 uint8_t *ecc_code = chip->buffers->ecccode;
1515 uint32_t *eccpos = chip->ecc.layout->eccpos;
1516 uint8_t *ecc_calc = chip->buffers->ecccalc;
1517 unsigned int max_bitflips = 0;
1519 /* Read the OOB area first */
1520 chip->cmdfunc(mtd, NAND_CMD_READOOB, 0, page);
1521 chip->read_buf(mtd, chip->oob_poi, mtd->oobsize);
1522 chip->cmdfunc(mtd, NAND_CMD_READ0, 0, page);
1524 for (i = 0; i < chip->ecc.total; i++)
1525 ecc_code[i] = chip->oob_poi[eccpos[i]];
1527 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
1530 chip->ecc.hwctl(mtd, NAND_ECC_READ);
1531 chip->read_buf(mtd, p, eccsize);
1532 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
1534 stat = chip->ecc.correct(mtd, p, &ecc_code[i], NULL);
1536 mtd->ecc_stats.failed++;
1538 mtd->ecc_stats.corrected += stat;
1539 max_bitflips = max_t(unsigned int, max_bitflips, stat);
1542 return max_bitflips;
1546 * nand_read_page_syndrome - [REPLACEABLE] hardware ECC syndrome based page read
1547 * @mtd: mtd info structure
1548 * @chip: nand chip info structure
1549 * @buf: buffer to store read data
1550 * @oob_required: caller requires OOB data read to chip->oob_poi
1551 * @page: page number to read
1553 * The hw generator calculates the error syndrome automatically. Therefore we
1554 * need a special oob layout and handling.
1556 static int nand_read_page_syndrome(struct mtd_info *mtd, struct nand_chip *chip,
1557 uint8_t *buf, int oob_required, int page)
1559 int i, eccsize = chip->ecc.size;
1560 int eccbytes = chip->ecc.bytes;
1561 int eccsteps = chip->ecc.steps;
1563 uint8_t *oob = chip->oob_poi;
1564 unsigned int max_bitflips = 0;
1566 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
1569 chip->ecc.hwctl(mtd, NAND_ECC_READ);
1570 chip->read_buf(mtd, p, eccsize);
1572 if (chip->ecc.prepad) {
1573 chip->read_buf(mtd, oob, chip->ecc.prepad);
1574 oob += chip->ecc.prepad;
1577 chip->ecc.hwctl(mtd, NAND_ECC_READSYN);
1578 chip->read_buf(mtd, oob, eccbytes);
1579 stat = chip->ecc.correct(mtd, p, oob, NULL);
1582 mtd->ecc_stats.failed++;
1584 mtd->ecc_stats.corrected += stat;
1585 max_bitflips = max_t(unsigned int, max_bitflips, stat);
1590 if (chip->ecc.postpad) {
1591 chip->read_buf(mtd, oob, chip->ecc.postpad);
1592 oob += chip->ecc.postpad;
1596 /* Calculate remaining oob bytes */
1597 i = mtd->oobsize - (oob - chip->oob_poi);
1599 chip->read_buf(mtd, oob, i);
1601 return max_bitflips;
1605 * nand_transfer_oob - [INTERN] Transfer oob to client buffer
1606 * @chip: nand chip structure
1607 * @oob: oob destination address
1608 * @ops: oob ops structure
1609 * @len: size of oob to transfer
1611 static uint8_t *nand_transfer_oob(struct nand_chip *chip, uint8_t *oob,
1612 struct mtd_oob_ops *ops, size_t len)
1614 switch (ops->mode) {
1616 case MTD_OPS_PLACE_OOB:
1618 memcpy(oob, chip->oob_poi + ops->ooboffs, len);
1621 case MTD_OPS_AUTO_OOB: {
1622 struct nand_oobfree *free = chip->ecc.layout->oobfree;
1623 uint32_t boffs = 0, roffs = ops->ooboffs;
1626 for (; free->length && len; free++, len -= bytes) {
1627 /* Read request not from offset 0? */
1628 if (unlikely(roffs)) {
1629 if (roffs >= free->length) {
1630 roffs -= free->length;
1633 boffs = free->offset + roffs;
1634 bytes = min_t(size_t, len,
1635 (free->length - roffs));
1638 bytes = min_t(size_t, len, free->length);
1639 boffs = free->offset;
1641 memcpy(oob, chip->oob_poi + boffs, bytes);
1653 * nand_setup_read_retry - [INTERN] Set the READ RETRY mode
1654 * @mtd: MTD device structure
1655 * @retry_mode: the retry mode to use
1657 * Some vendors supply a special command to shift the Vt threshold, to be used
1658 * when there are too many bitflips in a page (i.e., ECC error). After setting
1659 * a new threshold, the host should retry reading the page.
1661 static int nand_setup_read_retry(struct mtd_info *mtd, int retry_mode)
1663 struct nand_chip *chip = mtd->priv;
1665 pr_debug("setting READ RETRY mode %d\n", retry_mode);
1667 if (retry_mode >= chip->read_retries)
1670 if (!chip->setup_read_retry)
1673 return chip->setup_read_retry(mtd, retry_mode);
1677 * nand_do_read_ops - [INTERN] Read data with ECC
1678 * @mtd: MTD device structure
1679 * @from: offset to read from
1680 * @ops: oob ops structure
1682 * Internal function. Called with chip held.
1684 static int nand_do_read_ops(struct mtd_info *mtd, loff_t from,
1685 struct mtd_oob_ops *ops)
1687 int chipnr, page, realpage, col, bytes, aligned, oob_required;
1688 struct nand_chip *chip = mtd->priv;
1690 uint32_t readlen = ops->len;
1691 uint32_t oobreadlen = ops->ooblen;
1692 uint32_t max_oobsize = ops->mode == MTD_OPS_AUTO_OOB ?
1693 mtd->oobavail : mtd->oobsize;
1695 uint8_t *bufpoi, *oob, *buf;
1697 unsigned int max_bitflips = 0;
1699 bool ecc_fail = false;
1701 chipnr = (int)(from >> chip->chip_shift);
1702 chip->select_chip(mtd, chipnr);
1704 realpage = (int)(from >> chip->page_shift);
1705 page = realpage & chip->pagemask;
1707 col = (int)(from & (mtd->writesize - 1));
1711 oob_required = oob ? 1 : 0;
1714 unsigned int ecc_failures = mtd->ecc_stats.failed;
1716 bytes = min(mtd->writesize - col, readlen);
1717 aligned = (bytes == mtd->writesize);
1721 else if (chip->options & NAND_USE_BOUNCE_BUFFER)
1722 use_bufpoi = !virt_addr_valid(buf);
1726 /* Is the current page in the buffer? */
1727 if (realpage != chip->pagebuf || oob) {
1728 bufpoi = use_bufpoi ? chip->buffers->databuf : buf;
1730 if (use_bufpoi && aligned)
1731 pr_debug("%s: using read bounce buffer for buf@%p\n",
1735 chip->cmdfunc(mtd, NAND_CMD_READ0, 0x00, page);
1738 * Now read the page into the buffer. Absent an error,
1739 * the read methods return max bitflips per ecc step.
1741 if (unlikely(ops->mode == MTD_OPS_RAW))
1742 ret = chip->ecc.read_page_raw(mtd, chip, bufpoi,
1745 else if (!aligned && NAND_HAS_SUBPAGE_READ(chip) &&
1747 ret = chip->ecc.read_subpage(mtd, chip,
1751 ret = chip->ecc.read_page(mtd, chip, bufpoi,
1752 oob_required, page);
1755 /* Invalidate page cache */
1760 max_bitflips = max_t(unsigned int, max_bitflips, ret);
1762 /* Transfer not aligned data */
1764 if (!NAND_HAS_SUBPAGE_READ(chip) && !oob &&
1765 !(mtd->ecc_stats.failed - ecc_failures) &&
1766 (ops->mode != MTD_OPS_RAW)) {
1767 chip->pagebuf = realpage;
1768 chip->pagebuf_bitflips = ret;
1770 /* Invalidate page cache */
1773 memcpy(buf, chip->buffers->databuf + col, bytes);
1776 if (unlikely(oob)) {
1777 int toread = min(oobreadlen, max_oobsize);
1780 oob = nand_transfer_oob(chip,
1782 oobreadlen -= toread;
1786 if (chip->options & NAND_NEED_READRDY) {
1787 /* Apply delay or wait for ready/busy pin */
1788 if (!chip->dev_ready)
1789 udelay(chip->chip_delay);
1791 nand_wait_ready(mtd);
1794 if (mtd->ecc_stats.failed - ecc_failures) {
1795 if (retry_mode + 1 < chip->read_retries) {
1797 ret = nand_setup_read_retry(mtd,
1802 /* Reset failures; retry */
1803 mtd->ecc_stats.failed = ecc_failures;
1806 /* No more retry modes; real failure */
1813 memcpy(buf, chip->buffers->databuf + col, bytes);
1815 max_bitflips = max_t(unsigned int, max_bitflips,
1816 chip->pagebuf_bitflips);
1821 /* Reset to retry mode 0 */
1823 ret = nand_setup_read_retry(mtd, 0);
1832 /* For subsequent reads align to page boundary */
1834 /* Increment page address */
1837 page = realpage & chip->pagemask;
1838 /* Check, if we cross a chip boundary */
1841 chip->select_chip(mtd, -1);
1842 chip->select_chip(mtd, chipnr);
1845 chip->select_chip(mtd, -1);
1847 ops->retlen = ops->len - (size_t) readlen;
1849 ops->oobretlen = ops->ooblen - oobreadlen;
1857 return max_bitflips;
1861 * nand_read - [MTD Interface] MTD compatibility function for nand_do_read_ecc
1862 * @mtd: MTD device structure
1863 * @from: offset to read from
1864 * @len: number of bytes to read
1865 * @retlen: pointer to variable to store the number of read bytes
1866 * @buf: the databuffer to put data
1868 * Get hold of the chip and call nand_do_read.
1870 static int nand_read(struct mtd_info *mtd, loff_t from, size_t len,
1871 size_t *retlen, uint8_t *buf)
1873 struct mtd_oob_ops ops;
1876 nand_get_device(mtd, FL_READING);
1877 memset(&ops, 0, sizeof(ops));
1880 ops.mode = MTD_OPS_PLACE_OOB;
1881 ret = nand_do_read_ops(mtd, from, &ops);
1882 *retlen = ops.retlen;
1883 nand_release_device(mtd);
1888 * nand_read_oob_std - [REPLACEABLE] the most common OOB data read function
1889 * @mtd: mtd info structure
1890 * @chip: nand chip info structure
1891 * @page: page number to read
1893 static int nand_read_oob_std(struct mtd_info *mtd, struct nand_chip *chip,
1896 chip->cmdfunc(mtd, NAND_CMD_READOOB, 0, page);
1897 chip->read_buf(mtd, chip->oob_poi, mtd->oobsize);
1902 * nand_read_oob_syndrome - [REPLACEABLE] OOB data read function for HW ECC
1904 * @mtd: mtd info structure
1905 * @chip: nand chip info structure
1906 * @page: page number to read
1908 static int nand_read_oob_syndrome(struct mtd_info *mtd, struct nand_chip *chip,
1911 int length = mtd->oobsize;
1912 int chunk = chip->ecc.bytes + chip->ecc.prepad + chip->ecc.postpad;
1913 int eccsize = chip->ecc.size;
1914 uint8_t *bufpoi = chip->oob_poi;
1915 int i, toread, sndrnd = 0, pos;
1917 chip->cmdfunc(mtd, NAND_CMD_READ0, chip->ecc.size, page);
1918 for (i = 0; i < chip->ecc.steps; i++) {
1920 pos = eccsize + i * (eccsize + chunk);
1921 if (mtd->writesize > 512)
1922 chip->cmdfunc(mtd, NAND_CMD_RNDOUT, pos, -1);
1924 chip->cmdfunc(mtd, NAND_CMD_READ0, pos, page);
1927 toread = min_t(int, length, chunk);
1928 chip->read_buf(mtd, bufpoi, toread);
1933 chip->read_buf(mtd, bufpoi, length);
1939 * nand_write_oob_std - [REPLACEABLE] the most common OOB data write function
1940 * @mtd: mtd info structure
1941 * @chip: nand chip info structure
1942 * @page: page number to write
1944 static int nand_write_oob_std(struct mtd_info *mtd, struct nand_chip *chip,
1948 const uint8_t *buf = chip->oob_poi;
1949 int length = mtd->oobsize;
1951 chip->cmdfunc(mtd, NAND_CMD_SEQIN, mtd->writesize, page);
1952 chip->write_buf(mtd, buf, length);
1953 /* Send command to program the OOB data */
1954 chip->cmdfunc(mtd, NAND_CMD_PAGEPROG, -1, -1);
1956 status = chip->waitfunc(mtd, chip);
1958 return status & NAND_STATUS_FAIL ? -EIO : 0;
1962 * nand_write_oob_syndrome - [REPLACEABLE] OOB data write function for HW ECC
1963 * with syndrome - only for large page flash
1964 * @mtd: mtd info structure
1965 * @chip: nand chip info structure
1966 * @page: page number to write
1968 static int nand_write_oob_syndrome(struct mtd_info *mtd,
1969 struct nand_chip *chip, int page)
1971 int chunk = chip->ecc.bytes + chip->ecc.prepad + chip->ecc.postpad;
1972 int eccsize = chip->ecc.size, length = mtd->oobsize;
1973 int i, len, pos, status = 0, sndcmd = 0, steps = chip->ecc.steps;
1974 const uint8_t *bufpoi = chip->oob_poi;
1977 * data-ecc-data-ecc ... ecc-oob
1979 * data-pad-ecc-pad-data-pad .... ecc-pad-oob
1981 if (!chip->ecc.prepad && !chip->ecc.postpad) {
1982 pos = steps * (eccsize + chunk);
1987 chip->cmdfunc(mtd, NAND_CMD_SEQIN, pos, page);
1988 for (i = 0; i < steps; i++) {
1990 if (mtd->writesize <= 512) {
1991 uint32_t fill = 0xFFFFFFFF;
1995 int num = min_t(int, len, 4);
1996 chip->write_buf(mtd, (uint8_t *)&fill,
2001 pos = eccsize + i * (eccsize + chunk);
2002 chip->cmdfunc(mtd, NAND_CMD_RNDIN, pos, -1);
2006 len = min_t(int, length, chunk);
2007 chip->write_buf(mtd, bufpoi, len);
2012 chip->write_buf(mtd, bufpoi, length);
2014 chip->cmdfunc(mtd, NAND_CMD_PAGEPROG, -1, -1);
2015 status = chip->waitfunc(mtd, chip);
2017 return status & NAND_STATUS_FAIL ? -EIO : 0;
2021 * nand_do_read_oob - [INTERN] NAND read out-of-band
2022 * @mtd: MTD device structure
2023 * @from: offset to read from
2024 * @ops: oob operations description structure
2026 * NAND read out-of-band data from the spare area.
2028 static int nand_do_read_oob(struct mtd_info *mtd, loff_t from,
2029 struct mtd_oob_ops *ops)
2031 unsigned int max_bitflips = 0;
2032 int page, realpage, chipnr;
2033 struct nand_chip *chip = mtd->priv;
2034 struct mtd_ecc_stats stats;
2035 int readlen = ops->ooblen;
2037 uint8_t *buf = ops->oobbuf;
2040 pr_debug("%s: from = 0x%08Lx, len = %i\n",
2041 __func__, (unsigned long long)from, readlen);
2043 stats = mtd->ecc_stats;
2045 if (ops->mode == MTD_OPS_AUTO_OOB)
2046 len = chip->ecc.layout->oobavail;
2050 if (unlikely(ops->ooboffs >= len)) {
2051 pr_debug("%s: attempt to start read outside oob\n",
2056 /* Do not allow reads past end of device */
2057 if (unlikely(from >= mtd->size ||
2058 ops->ooboffs + readlen > ((mtd->size >> chip->page_shift) -
2059 (from >> chip->page_shift)) * len)) {
2060 pr_debug("%s: attempt to read beyond end of device\n",
2065 chipnr = (int)(from >> chip->chip_shift);
2066 chip->select_chip(mtd, chipnr);
2068 /* Shift to get page */
2069 realpage = (int)(from >> chip->page_shift);
2070 page = realpage & chip->pagemask;
2073 if (ops->mode == MTD_OPS_RAW)
2074 ret = chip->ecc.read_oob_raw(mtd, chip, page);
2076 ret = chip->ecc.read_oob(mtd, chip, page);
2081 len = min(len, readlen);
2082 buf = nand_transfer_oob(chip, buf, ops, len);
2084 if (chip->options & NAND_NEED_READRDY) {
2085 /* Apply delay or wait for ready/busy pin */
2086 if (!chip->dev_ready)
2087 udelay(chip->chip_delay);
2089 nand_wait_ready(mtd);
2092 max_bitflips = max_t(unsigned int, max_bitflips, ret);
2098 /* Increment page address */
2101 page = realpage & chip->pagemask;
2102 /* Check, if we cross a chip boundary */
2105 chip->select_chip(mtd, -1);
2106 chip->select_chip(mtd, chipnr);
2109 chip->select_chip(mtd, -1);
2111 ops->oobretlen = ops->ooblen - readlen;
2116 if (mtd->ecc_stats.failed - stats.failed)
2119 return max_bitflips;
2123 * nand_read_oob - [MTD Interface] NAND read data and/or out-of-band
2124 * @mtd: MTD device structure
2125 * @from: offset to read from
2126 * @ops: oob operation description structure
2128 * NAND read data and/or out-of-band data.
2130 static int nand_read_oob(struct mtd_info *mtd, loff_t from,
2131 struct mtd_oob_ops *ops)
2133 int ret = -ENOTSUPP;
2137 /* Do not allow reads past end of device */
2138 if (ops->datbuf && (from + ops->len) > mtd->size) {
2139 pr_debug("%s: attempt to read beyond end of device\n",
2144 nand_get_device(mtd, FL_READING);
2146 switch (ops->mode) {
2147 case MTD_OPS_PLACE_OOB:
2148 case MTD_OPS_AUTO_OOB:
2157 ret = nand_do_read_oob(mtd, from, ops);
2159 ret = nand_do_read_ops(mtd, from, ops);
2162 nand_release_device(mtd);
2168 * nand_write_page_raw - [INTERN] raw page write function
2169 * @mtd: mtd info structure
2170 * @chip: nand chip info structure
2172 * @oob_required: must write chip->oob_poi to OOB
2173 * @page: page number to write
2175 * Not for syndrome calculating ECC controllers, which use a special oob layout.
2177 static int nand_write_page_raw(struct mtd_info *mtd, struct nand_chip *chip,
2178 const uint8_t *buf, int oob_required, int page)
2180 chip->write_buf(mtd, buf, mtd->writesize);
2182 chip->write_buf(mtd, chip->oob_poi, mtd->oobsize);
2188 * nand_write_page_raw_syndrome - [INTERN] raw page write function
2189 * @mtd: mtd info structure
2190 * @chip: nand chip info structure
2192 * @oob_required: must write chip->oob_poi to OOB
2193 * @page: page number to write
2195 * We need a special oob layout and handling even when ECC isn't checked.
2197 static int nand_write_page_raw_syndrome(struct mtd_info *mtd,
2198 struct nand_chip *chip,
2199 const uint8_t *buf, int oob_required,
2202 int eccsize = chip->ecc.size;
2203 int eccbytes = chip->ecc.bytes;
2204 uint8_t *oob = chip->oob_poi;
2207 for (steps = chip->ecc.steps; steps > 0; steps--) {
2208 chip->write_buf(mtd, buf, eccsize);
2211 if (chip->ecc.prepad) {
2212 chip->write_buf(mtd, oob, chip->ecc.prepad);
2213 oob += chip->ecc.prepad;
2216 chip->write_buf(mtd, oob, eccbytes);
2219 if (chip->ecc.postpad) {
2220 chip->write_buf(mtd, oob, chip->ecc.postpad);
2221 oob += chip->ecc.postpad;
2225 size = mtd->oobsize - (oob - chip->oob_poi);
2227 chip->write_buf(mtd, oob, size);
2232 * nand_write_page_swecc - [REPLACEABLE] software ECC based page write function
2233 * @mtd: mtd info structure
2234 * @chip: nand chip info structure
2236 * @oob_required: must write chip->oob_poi to OOB
2237 * @page: page number to write
2239 static int nand_write_page_swecc(struct mtd_info *mtd, struct nand_chip *chip,
2240 const uint8_t *buf, int oob_required,
2243 int i, eccsize = chip->ecc.size;
2244 int eccbytes = chip->ecc.bytes;
2245 int eccsteps = chip->ecc.steps;
2246 uint8_t *ecc_calc = chip->buffers->ecccalc;
2247 const uint8_t *p = buf;
2248 uint32_t *eccpos = chip->ecc.layout->eccpos;
2250 /* Software ECC calculation */
2251 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize)
2252 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
2254 for (i = 0; i < chip->ecc.total; i++)
2255 chip->oob_poi[eccpos[i]] = ecc_calc[i];
2257 return chip->ecc.write_page_raw(mtd, chip, buf, 1, page);
2261 * nand_write_page_hwecc - [REPLACEABLE] hardware ECC based page write function
2262 * @mtd: mtd info structure
2263 * @chip: nand chip info structure
2265 * @oob_required: must write chip->oob_poi to OOB
2266 * @page: page number to write
2268 static int nand_write_page_hwecc(struct mtd_info *mtd, struct nand_chip *chip,
2269 const uint8_t *buf, int oob_required,
2272 int i, eccsize = chip->ecc.size;
2273 int eccbytes = chip->ecc.bytes;
2274 int eccsteps = chip->ecc.steps;
2275 uint8_t *ecc_calc = chip->buffers->ecccalc;
2276 const uint8_t *p = buf;
2277 uint32_t *eccpos = chip->ecc.layout->eccpos;
2279 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
2280 chip->ecc.hwctl(mtd, NAND_ECC_WRITE);
2281 chip->write_buf(mtd, p, eccsize);
2282 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
2285 for (i = 0; i < chip->ecc.total; i++)
2286 chip->oob_poi[eccpos[i]] = ecc_calc[i];
2288 chip->write_buf(mtd, chip->oob_poi, mtd->oobsize);
2295 * nand_write_subpage_hwecc - [REPLACEABLE] hardware ECC based subpage write
2296 * @mtd: mtd info structure
2297 * @chip: nand chip info structure
2298 * @offset: column address of subpage within the page
2299 * @data_len: data length
2301 * @oob_required: must write chip->oob_poi to OOB
2302 * @page: page number to write
2304 static int nand_write_subpage_hwecc(struct mtd_info *mtd,
2305 struct nand_chip *chip, uint32_t offset,
2306 uint32_t data_len, const uint8_t *buf,
2307 int oob_required, int page)
2309 uint8_t *oob_buf = chip->oob_poi;
2310 uint8_t *ecc_calc = chip->buffers->ecccalc;
2311 int ecc_size = chip->ecc.size;
2312 int ecc_bytes = chip->ecc.bytes;
2313 int ecc_steps = chip->ecc.steps;
2314 uint32_t *eccpos = chip->ecc.layout->eccpos;
2315 uint32_t start_step = offset / ecc_size;
2316 uint32_t end_step = (offset + data_len - 1) / ecc_size;
2317 int oob_bytes = mtd->oobsize / ecc_steps;
2320 for (step = 0; step < ecc_steps; step++) {
2321 /* configure controller for WRITE access */
2322 chip->ecc.hwctl(mtd, NAND_ECC_WRITE);
2324 /* write data (untouched subpages already masked by 0xFF) */
2325 chip->write_buf(mtd, buf, ecc_size);
2327 /* mask ECC of un-touched subpages by padding 0xFF */
2328 if ((step < start_step) || (step > end_step))
2329 memset(ecc_calc, 0xff, ecc_bytes);
2331 chip->ecc.calculate(mtd, buf, ecc_calc);
2333 /* mask OOB of un-touched subpages by padding 0xFF */
2334 /* if oob_required, preserve OOB metadata of written subpage */
2335 if (!oob_required || (step < start_step) || (step > end_step))
2336 memset(oob_buf, 0xff, oob_bytes);
2339 ecc_calc += ecc_bytes;
2340 oob_buf += oob_bytes;
2343 /* copy calculated ECC for whole page to chip->buffer->oob */
2344 /* this include masked-value(0xFF) for unwritten subpages */
2345 ecc_calc = chip->buffers->ecccalc;
2346 for (i = 0; i < chip->ecc.total; i++)
2347 chip->oob_poi[eccpos[i]] = ecc_calc[i];
2349 /* write OOB buffer to NAND device */
2350 chip->write_buf(mtd, chip->oob_poi, mtd->oobsize);
2357 * nand_write_page_syndrome - [REPLACEABLE] hardware ECC syndrome based page write
2358 * @mtd: mtd info structure
2359 * @chip: nand chip info structure
2361 * @oob_required: must write chip->oob_poi to OOB
2362 * @page: page number to write
2364 * The hw generator calculates the error syndrome automatically. Therefore we
2365 * need a special oob layout and handling.
2367 static int nand_write_page_syndrome(struct mtd_info *mtd,
2368 struct nand_chip *chip,
2369 const uint8_t *buf, int oob_required,
2372 int i, eccsize = chip->ecc.size;
2373 int eccbytes = chip->ecc.bytes;
2374 int eccsteps = chip->ecc.steps;
2375 const uint8_t *p = buf;
2376 uint8_t *oob = chip->oob_poi;
2378 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
2380 chip->ecc.hwctl(mtd, NAND_ECC_WRITE);
2381 chip->write_buf(mtd, p, eccsize);
2383 if (chip->ecc.prepad) {
2384 chip->write_buf(mtd, oob, chip->ecc.prepad);
2385 oob += chip->ecc.prepad;
2388 chip->ecc.calculate(mtd, p, oob);
2389 chip->write_buf(mtd, oob, eccbytes);
2392 if (chip->ecc.postpad) {
2393 chip->write_buf(mtd, oob, chip->ecc.postpad);
2394 oob += chip->ecc.postpad;
2398 /* Calculate remaining oob bytes */
2399 i = mtd->oobsize - (oob - chip->oob_poi);
2401 chip->write_buf(mtd, oob, i);
2407 * nand_write_page - [REPLACEABLE] write one page
2408 * @mtd: MTD device structure
2409 * @chip: NAND chip descriptor
2410 * @offset: address offset within the page
2411 * @data_len: length of actual data to be written
2412 * @buf: the data to write
2413 * @oob_required: must write chip->oob_poi to OOB
2414 * @page: page number to write
2415 * @cached: cached programming
2416 * @raw: use _raw version of write_page
2418 static int nand_write_page(struct mtd_info *mtd, struct nand_chip *chip,
2419 uint32_t offset, int data_len, const uint8_t *buf,
2420 int oob_required, int page, int cached, int raw)
2422 int status, subpage;
2424 if (!(chip->options & NAND_NO_SUBPAGE_WRITE) &&
2425 chip->ecc.write_subpage)
2426 subpage = offset || (data_len < mtd->writesize);
2430 chip->cmdfunc(mtd, NAND_CMD_SEQIN, 0x00, page);
2433 status = chip->ecc.write_page_raw(mtd, chip, buf,
2434 oob_required, page);
2436 status = chip->ecc.write_subpage(mtd, chip, offset, data_len,
2437 buf, oob_required, page);
2439 status = chip->ecc.write_page(mtd, chip, buf, oob_required,
2446 * Cached progamming disabled for now. Not sure if it's worth the
2447 * trouble. The speed gain is not very impressive. (2.3->2.6Mib/s).
2451 if (!cached || !NAND_HAS_CACHEPROG(chip)) {
2453 chip->cmdfunc(mtd, NAND_CMD_PAGEPROG, -1, -1);
2454 status = chip->waitfunc(mtd, chip);
2456 * See if operation failed and additional status checks are
2459 if ((status & NAND_STATUS_FAIL) && (chip->errstat))
2460 status = chip->errstat(mtd, chip, FL_WRITING, status,
2463 if (status & NAND_STATUS_FAIL)
2466 chip->cmdfunc(mtd, NAND_CMD_CACHEDPROG, -1, -1);
2467 status = chip->waitfunc(mtd, chip);
2474 * nand_fill_oob - [INTERN] Transfer client buffer to oob
2475 * @mtd: MTD device structure
2476 * @oob: oob data buffer
2477 * @len: oob data write length
2478 * @ops: oob ops structure
2480 static uint8_t *nand_fill_oob(struct mtd_info *mtd, uint8_t *oob, size_t len,
2481 struct mtd_oob_ops *ops)
2483 struct nand_chip *chip = mtd->priv;
2486 * Initialise to all 0xFF, to avoid the possibility of left over OOB
2487 * data from a previous OOB read.
2489 memset(chip->oob_poi, 0xff, mtd->oobsize);
2491 switch (ops->mode) {
2493 case MTD_OPS_PLACE_OOB:
2495 memcpy(chip->oob_poi + ops->ooboffs, oob, len);
2498 case MTD_OPS_AUTO_OOB: {
2499 struct nand_oobfree *free = chip->ecc.layout->oobfree;
2500 uint32_t boffs = 0, woffs = ops->ooboffs;
2503 for (; free->length && len; free++, len -= bytes) {
2504 /* Write request not from offset 0? */
2505 if (unlikely(woffs)) {
2506 if (woffs >= free->length) {
2507 woffs -= free->length;
2510 boffs = free->offset + woffs;
2511 bytes = min_t(size_t, len,
2512 (free->length - woffs));
2515 bytes = min_t(size_t, len, free->length);
2516 boffs = free->offset;
2518 memcpy(chip->oob_poi + boffs, oob, bytes);
2529 #define NOTALIGNED(x) ((x & (chip->subpagesize - 1)) != 0)
2532 * nand_do_write_ops - [INTERN] NAND write with ECC
2533 * @mtd: MTD device structure
2534 * @to: offset to write to
2535 * @ops: oob operations description structure
2537 * NAND write with ECC.
2539 static int nand_do_write_ops(struct mtd_info *mtd, loff_t to,
2540 struct mtd_oob_ops *ops)
2542 int chipnr, realpage, page, blockmask, column;
2543 struct nand_chip *chip = mtd->priv;
2544 uint32_t writelen = ops->len;
2546 uint32_t oobwritelen = ops->ooblen;
2547 uint32_t oobmaxlen = ops->mode == MTD_OPS_AUTO_OOB ?
2548 mtd->oobavail : mtd->oobsize;
2550 uint8_t *oob = ops->oobbuf;
2551 uint8_t *buf = ops->datbuf;
2553 int oob_required = oob ? 1 : 0;
2559 /* Reject writes, which are not page aligned */
2560 if (NOTALIGNED(to) || NOTALIGNED(ops->len)) {
2561 pr_notice("%s: attempt to write non page aligned data\n",
2566 column = to & (mtd->writesize - 1);
2568 chipnr = (int)(to >> chip->chip_shift);
2569 chip->select_chip(mtd, chipnr);
2571 /* Check, if it is write protected */
2572 if (nand_check_wp(mtd)) {
2577 realpage = (int)(to >> chip->page_shift);
2578 page = realpage & chip->pagemask;
2579 blockmask = (1 << (chip->phys_erase_shift - chip->page_shift)) - 1;
2581 /* Invalidate the page cache, when we write to the cached page */
2582 if (to <= ((loff_t)chip->pagebuf << chip->page_shift) &&
2583 ((loff_t)chip->pagebuf << chip->page_shift) < (to + ops->len))
2586 /* Don't allow multipage oob writes with offset */
2587 if (oob && ops->ooboffs && (ops->ooboffs + ops->ooblen > oobmaxlen)) {
2593 int bytes = mtd->writesize;
2594 int cached = writelen > bytes && page != blockmask;
2595 uint8_t *wbuf = buf;
2597 int part_pagewr = (column || writelen < mtd->writesize);
2601 else if (chip->options & NAND_USE_BOUNCE_BUFFER)
2602 use_bufpoi = !virt_addr_valid(buf);
2606 /* Partial page write?, or need to use bounce buffer */
2608 pr_debug("%s: using write bounce buffer for buf@%p\n",
2612 bytes = min_t(int, bytes - column, writelen);
2614 memset(chip->buffers->databuf, 0xff, mtd->writesize);
2615 memcpy(&chip->buffers->databuf[column], buf, bytes);
2616 wbuf = chip->buffers->databuf;
2619 if (unlikely(oob)) {
2620 size_t len = min(oobwritelen, oobmaxlen);
2621 oob = nand_fill_oob(mtd, oob, len, ops);
2624 /* We still need to erase leftover OOB data */
2625 memset(chip->oob_poi, 0xff, mtd->oobsize);
2627 ret = chip->write_page(mtd, chip, column, bytes, wbuf,
2628 oob_required, page, cached,
2629 (ops->mode == MTD_OPS_RAW));
2641 page = realpage & chip->pagemask;
2642 /* Check, if we cross a chip boundary */
2645 chip->select_chip(mtd, -1);
2646 chip->select_chip(mtd, chipnr);
2650 ops->retlen = ops->len - writelen;
2652 ops->oobretlen = ops->ooblen;
2655 chip->select_chip(mtd, -1);
2660 * panic_nand_write - [MTD Interface] NAND write with ECC
2661 * @mtd: MTD device structure
2662 * @to: offset to write to
2663 * @len: number of bytes to write
2664 * @retlen: pointer to variable to store the number of written bytes
2665 * @buf: the data to write
2667 * NAND write with ECC. Used when performing writes in interrupt context, this
2668 * may for example be called by mtdoops when writing an oops while in panic.
2670 static int panic_nand_write(struct mtd_info *mtd, loff_t to, size_t len,
2671 size_t *retlen, const uint8_t *buf)
2673 struct nand_chip *chip = mtd->priv;
2674 int chipnr = (int)(to >> chip->chip_shift);
2675 struct mtd_oob_ops ops;
2678 /* Grab the device */
2679 panic_nand_get_device(chip, mtd, FL_WRITING);
2681 chip->select_chip(mtd, chipnr);
2683 /* Wait for the device to get ready */
2684 panic_nand_wait(mtd, chip, 400);
2686 memset(&ops, 0, sizeof(ops));
2688 ops.datbuf = (uint8_t *)buf;
2689 ops.mode = MTD_OPS_PLACE_OOB;
2691 ret = nand_do_write_ops(mtd, to, &ops);
2693 *retlen = ops.retlen;
2698 * nand_write - [MTD Interface] NAND write with ECC
2699 * @mtd: MTD device structure
2700 * @to: offset to write to
2701 * @len: number of bytes to write
2702 * @retlen: pointer to variable to store the number of written bytes
2703 * @buf: the data to write
2705 * NAND write with ECC.
2707 static int nand_write(struct mtd_info *mtd, loff_t to, size_t len,
2708 size_t *retlen, const uint8_t *buf)
2710 struct mtd_oob_ops ops;
2713 nand_get_device(mtd, FL_WRITING);
2714 memset(&ops, 0, sizeof(ops));
2716 ops.datbuf = (uint8_t *)buf;
2717 ops.mode = MTD_OPS_PLACE_OOB;
2718 ret = nand_do_write_ops(mtd, to, &ops);
2719 *retlen = ops.retlen;
2720 nand_release_device(mtd);
2725 * nand_do_write_oob - [MTD Interface] NAND write out-of-band
2726 * @mtd: MTD device structure
2727 * @to: offset to write to
2728 * @ops: oob operation description structure
2730 * NAND write out-of-band.
2732 static int nand_do_write_oob(struct mtd_info *mtd, loff_t to,
2733 struct mtd_oob_ops *ops)
2735 int chipnr, page, status, len;
2736 struct nand_chip *chip = mtd->priv;
2738 pr_debug("%s: to = 0x%08x, len = %i\n",
2739 __func__, (unsigned int)to, (int)ops->ooblen);
2741 if (ops->mode == MTD_OPS_AUTO_OOB)
2742 len = chip->ecc.layout->oobavail;
2746 /* Do not allow write past end of page */
2747 if ((ops->ooboffs + ops->ooblen) > len) {
2748 pr_debug("%s: attempt to write past end of page\n",
2753 if (unlikely(ops->ooboffs >= len)) {
2754 pr_debug("%s: attempt to start write outside oob\n",
2759 /* Do not allow write past end of device */
2760 if (unlikely(to >= mtd->size ||
2761 ops->ooboffs + ops->ooblen >
2762 ((mtd->size >> chip->page_shift) -
2763 (to >> chip->page_shift)) * len)) {
2764 pr_debug("%s: attempt to write beyond end of device\n",
2769 chipnr = (int)(to >> chip->chip_shift);
2770 chip->select_chip(mtd, chipnr);
2772 /* Shift to get page */
2773 page = (int)(to >> chip->page_shift);
2776 * Reset the chip. Some chips (like the Toshiba TC5832DC found in one
2777 * of my DiskOnChip 2000 test units) will clear the whole data page too
2778 * if we don't do this. I have no clue why, but I seem to have 'fixed'
2779 * it in the doc2000 driver in August 1999. dwmw2.
2781 chip->cmdfunc(mtd, NAND_CMD_RESET, -1, -1);
2783 /* Check, if it is write protected */
2784 if (nand_check_wp(mtd)) {
2785 chip->select_chip(mtd, -1);
2789 /* Invalidate the page cache, if we write to the cached page */
2790 if (page == chip->pagebuf)
2793 nand_fill_oob(mtd, ops->oobbuf, ops->ooblen, ops);
2795 if (ops->mode == MTD_OPS_RAW)
2796 status = chip->ecc.write_oob_raw(mtd, chip, page & chip->pagemask);
2798 status = chip->ecc.write_oob(mtd, chip, page & chip->pagemask);
2800 chip->select_chip(mtd, -1);
2805 ops->oobretlen = ops->ooblen;
2811 * nand_write_oob - [MTD Interface] NAND write data and/or out-of-band
2812 * @mtd: MTD device structure
2813 * @to: offset to write to
2814 * @ops: oob operation description structure
2816 static int nand_write_oob(struct mtd_info *mtd, loff_t to,
2817 struct mtd_oob_ops *ops)
2819 int ret = -ENOTSUPP;
2823 /* Do not allow writes past end of device */
2824 if (ops->datbuf && (to + ops->len) > mtd->size) {
2825 pr_debug("%s: attempt to write beyond end of device\n",
2830 nand_get_device(mtd, FL_WRITING);
2832 switch (ops->mode) {
2833 case MTD_OPS_PLACE_OOB:
2834 case MTD_OPS_AUTO_OOB:
2843 ret = nand_do_write_oob(mtd, to, ops);
2845 ret = nand_do_write_ops(mtd, to, ops);
2848 nand_release_device(mtd);
2853 * single_erase - [GENERIC] NAND standard block erase command function
2854 * @mtd: MTD device structure
2855 * @page: the page address of the block which will be erased
2857 * Standard erase command for NAND chips. Returns NAND status.
2859 static int single_erase(struct mtd_info *mtd, int page)
2861 struct nand_chip *chip = mtd->priv;
2862 /* Send commands to erase a block */
2863 chip->cmdfunc(mtd, NAND_CMD_ERASE1, -1, page);
2864 chip->cmdfunc(mtd, NAND_CMD_ERASE2, -1, -1);
2866 return chip->waitfunc(mtd, chip);
2870 * nand_erase - [MTD Interface] erase block(s)
2871 * @mtd: MTD device structure
2872 * @instr: erase instruction
2874 * Erase one ore more blocks.
2876 static int nand_erase(struct mtd_info *mtd, struct erase_info *instr)
2878 return nand_erase_nand(mtd, instr, 0);
2882 * nand_erase_nand - [INTERN] erase block(s)
2883 * @mtd: MTD device structure
2884 * @instr: erase instruction
2885 * @allowbbt: allow erasing the bbt area
2887 * Erase one ore more blocks.
2889 int nand_erase_nand(struct mtd_info *mtd, struct erase_info *instr,
2892 int page, status, pages_per_block, ret, chipnr;
2893 struct nand_chip *chip = mtd->priv;
2896 pr_debug("%s: start = 0x%012llx, len = %llu\n",
2897 __func__, (unsigned long long)instr->addr,
2898 (unsigned long long)instr->len);
2900 if (check_offs_len(mtd, instr->addr, instr->len))
2903 /* Grab the lock and see if the device is available */
2904 nand_get_device(mtd, FL_ERASING);
2906 /* Shift to get first page */
2907 page = (int)(instr->addr >> chip->page_shift);
2908 chipnr = (int)(instr->addr >> chip->chip_shift);
2910 /* Calculate pages in each block */
2911 pages_per_block = 1 << (chip->phys_erase_shift - chip->page_shift);
2913 /* Select the NAND device */
2914 chip->select_chip(mtd, chipnr);
2916 /* Check, if it is write protected */
2917 if (nand_check_wp(mtd)) {
2918 pr_debug("%s: device is write protected!\n",
2920 instr->state = MTD_ERASE_FAILED;
2924 /* Loop through the pages */
2927 instr->state = MTD_ERASING;
2930 /* Check if we have a bad block, we do not erase bad blocks! */
2931 if (nand_block_checkbad(mtd, ((loff_t) page) <<
2932 chip->page_shift, 0, allowbbt)) {
2933 pr_warn("%s: attempt to erase a bad block at page 0x%08x\n",
2935 instr->state = MTD_ERASE_FAILED;
2940 * Invalidate the page cache, if we erase the block which
2941 * contains the current cached page.
2943 if (page <= chip->pagebuf && chip->pagebuf <
2944 (page + pages_per_block))
2947 status = chip->erase(mtd, page & chip->pagemask);
2950 * See if operation failed and additional status checks are
2953 if ((status & NAND_STATUS_FAIL) && (chip->errstat))
2954 status = chip->errstat(mtd, chip, FL_ERASING,
2957 /* See if block erase succeeded */
2958 if (status & NAND_STATUS_FAIL) {
2959 pr_debug("%s: failed erase, page 0x%08x\n",
2961 instr->state = MTD_ERASE_FAILED;
2963 ((loff_t)page << chip->page_shift);
2967 /* Increment page address and decrement length */
2968 len -= (1ULL << chip->phys_erase_shift);
2969 page += pages_per_block;
2971 /* Check, if we cross a chip boundary */
2972 if (len && !(page & chip->pagemask)) {
2974 chip->select_chip(mtd, -1);
2975 chip->select_chip(mtd, chipnr);
2978 instr->state = MTD_ERASE_DONE;
2982 ret = instr->state == MTD_ERASE_DONE ? 0 : -EIO;
2984 /* Deselect and wake up anyone waiting on the device */
2985 chip->select_chip(mtd, -1);
2986 nand_release_device(mtd);
2988 /* Do call back function */
2990 mtd_erase_callback(instr);
2992 /* Return more or less happy */
2997 * nand_sync - [MTD Interface] sync
2998 * @mtd: MTD device structure
3000 * Sync is actually a wait for chip ready function.
3002 static void nand_sync(struct mtd_info *mtd)
3004 pr_debug("%s: called\n", __func__);
3006 /* Grab the lock and see if the device is available */
3007 nand_get_device(mtd, FL_SYNCING);
3008 /* Release it and go back */
3009 nand_release_device(mtd);
3013 * nand_block_isbad - [MTD Interface] Check if block at offset is bad
3014 * @mtd: MTD device structure
3015 * @offs: offset relative to mtd start
3017 static int nand_block_isbad(struct mtd_info *mtd, loff_t offs)
3019 return nand_block_checkbad(mtd, offs, 1, 0);
3023 * nand_block_markbad - [MTD Interface] Mark block at the given offset as bad
3024 * @mtd: MTD device structure
3025 * @ofs: offset relative to mtd start
3027 static int nand_block_markbad(struct mtd_info *mtd, loff_t ofs)
3031 ret = nand_block_isbad(mtd, ofs);
3033 /* If it was bad already, return success and do nothing */
3039 return nand_block_markbad_lowlevel(mtd, ofs);
3043 * nand_onfi_set_features- [REPLACEABLE] set features for ONFI nand
3044 * @mtd: MTD device structure
3045 * @chip: nand chip info structure
3046 * @addr: feature address.
3047 * @subfeature_param: the subfeature parameters, a four bytes array.
3049 static int nand_onfi_set_features(struct mtd_info *mtd, struct nand_chip *chip,
3050 int addr, uint8_t *subfeature_param)
3055 if (!chip->onfi_version ||
3056 !(le16_to_cpu(chip->onfi_params.opt_cmd)
3057 & ONFI_OPT_CMD_SET_GET_FEATURES))
3060 chip->cmdfunc(mtd, NAND_CMD_SET_FEATURES, addr, -1);
3061 for (i = 0; i < ONFI_SUBFEATURE_PARAM_LEN; ++i)
3062 chip->write_byte(mtd, subfeature_param[i]);
3064 status = chip->waitfunc(mtd, chip);
3065 if (status & NAND_STATUS_FAIL)
3071 * nand_onfi_get_features- [REPLACEABLE] get features for ONFI nand
3072 * @mtd: MTD device structure
3073 * @chip: nand chip info structure
3074 * @addr: feature address.
3075 * @subfeature_param: the subfeature parameters, a four bytes array.
3077 static int nand_onfi_get_features(struct mtd_info *mtd, struct nand_chip *chip,
3078 int addr, uint8_t *subfeature_param)
3082 if (!chip->onfi_version ||
3083 !(le16_to_cpu(chip->onfi_params.opt_cmd)
3084 & ONFI_OPT_CMD_SET_GET_FEATURES))
3087 chip->cmdfunc(mtd, NAND_CMD_GET_FEATURES, addr, -1);
3088 for (i = 0; i < ONFI_SUBFEATURE_PARAM_LEN; ++i)
3089 *subfeature_param++ = chip->read_byte(mtd);
3094 * nand_suspend - [MTD Interface] Suspend the NAND flash
3095 * @mtd: MTD device structure
3097 static int nand_suspend(struct mtd_info *mtd)
3099 return nand_get_device(mtd, FL_PM_SUSPENDED);
3103 * nand_resume - [MTD Interface] Resume the NAND flash
3104 * @mtd: MTD device structure
3106 static void nand_resume(struct mtd_info *mtd)
3108 struct nand_chip *chip = mtd->priv;
3110 if (chip->state == FL_PM_SUSPENDED)
3111 nand_release_device(mtd);
3113 pr_err("%s called for a chip which is not in suspended state\n",
3118 * nand_shutdown - [MTD Interface] Finish the current NAND operation and
3119 * prevent further operations
3120 * @mtd: MTD device structure
3122 static void nand_shutdown(struct mtd_info *mtd)
3124 nand_get_device(mtd, FL_PM_SUSPENDED);
3127 /* Set default functions */
3128 static void nand_set_defaults(struct nand_chip *chip, int busw)
3130 /* check for proper chip_delay setup, set 20us if not */
3131 if (!chip->chip_delay)
3132 chip->chip_delay = 20;
3134 /* check, if a user supplied command function given */
3135 if (chip->cmdfunc == NULL)
3136 chip->cmdfunc = nand_command;
3138 /* check, if a user supplied wait function given */
3139 if (chip->waitfunc == NULL)
3140 chip->waitfunc = nand_wait;
3142 if (!chip->select_chip)
3143 chip->select_chip = nand_select_chip;
3145 /* set for ONFI nand */
3146 if (!chip->onfi_set_features)
3147 chip->onfi_set_features = nand_onfi_set_features;
3148 if (!chip->onfi_get_features)
3149 chip->onfi_get_features = nand_onfi_get_features;
3151 /* If called twice, pointers that depend on busw may need to be reset */
3152 if (!chip->read_byte || chip->read_byte == nand_read_byte)
3153 chip->read_byte = busw ? nand_read_byte16 : nand_read_byte;
3154 if (!chip->read_word)
3155 chip->read_word = nand_read_word;
3156 if (!chip->block_bad)
3157 chip->block_bad = nand_block_bad;
3158 if (!chip->block_markbad)
3159 chip->block_markbad = nand_default_block_markbad;
3160 if (!chip->write_buf || chip->write_buf == nand_write_buf)
3161 chip->write_buf = busw ? nand_write_buf16 : nand_write_buf;
3162 if (!chip->write_byte || chip->write_byte == nand_write_byte)
3163 chip->write_byte = busw ? nand_write_byte16 : nand_write_byte;
3164 if (!chip->read_buf || chip->read_buf == nand_read_buf)
3165 chip->read_buf = busw ? nand_read_buf16 : nand_read_buf;
3166 if (!chip->scan_bbt)
3167 chip->scan_bbt = nand_default_bbt;
3169 if (!chip->controller) {
3170 chip->controller = &chip->hwcontrol;
3171 spin_lock_init(&chip->controller->lock);
3172 init_waitqueue_head(&chip->controller->wq);
3177 /* Sanitize ONFI strings so we can safely print them */
3178 static void sanitize_string(uint8_t *s, size_t len)
3182 /* Null terminate */
3185 /* Remove non printable chars */
3186 for (i = 0; i < len - 1; i++) {
3187 if (s[i] < ' ' || s[i] > 127)
3191 /* Remove trailing spaces */
3195 static u16 onfi_crc16(u16 crc, u8 const *p, size_t len)
3200 for (i = 0; i < 8; i++)
3201 crc = (crc << 1) ^ ((crc & 0x8000) ? 0x8005 : 0);
3207 /* Parse the Extended Parameter Page. */
3208 static int nand_flash_detect_ext_param_page(struct mtd_info *mtd,
3209 struct nand_chip *chip, struct nand_onfi_params *p)
3211 struct onfi_ext_param_page *ep;
3212 struct onfi_ext_section *s;
3213 struct onfi_ext_ecc_info *ecc;
3219 len = le16_to_cpu(p->ext_param_page_length) * 16;
3220 ep = kmalloc(len, GFP_KERNEL);
3224 /* Send our own NAND_CMD_PARAM. */
3225 chip->cmdfunc(mtd, NAND_CMD_PARAM, 0, -1);
3227 /* Use the Change Read Column command to skip the ONFI param pages. */
3228 chip->cmdfunc(mtd, NAND_CMD_RNDOUT,
3229 sizeof(*p) * p->num_of_param_pages , -1);
3231 /* Read out the Extended Parameter Page. */
3232 chip->read_buf(mtd, (uint8_t *)ep, len);
3233 if ((onfi_crc16(ONFI_CRC_BASE, ((uint8_t *)ep) + 2, len - 2)
3234 != le16_to_cpu(ep->crc))) {
3235 pr_debug("fail in the CRC.\n");
3240 * Check the signature.
3241 * Do not strictly follow the ONFI spec, maybe changed in future.
3243 if (strncmp(ep->sig, "EPPS", 4)) {
3244 pr_debug("The signature is invalid.\n");
3248 /* find the ECC section. */
3249 cursor = (uint8_t *)(ep + 1);
3250 for (i = 0; i < ONFI_EXT_SECTION_MAX; i++) {
3251 s = ep->sections + i;
3252 if (s->type == ONFI_SECTION_TYPE_2)
3254 cursor += s->length * 16;
3256 if (i == ONFI_EXT_SECTION_MAX) {
3257 pr_debug("We can not find the ECC section.\n");
3261 /* get the info we want. */
3262 ecc = (struct onfi_ext_ecc_info *)cursor;
3264 if (!ecc->codeword_size) {
3265 pr_debug("Invalid codeword size\n");
3269 chip->ecc_strength_ds = ecc->ecc_bits;
3270 chip->ecc_step_ds = 1 << ecc->codeword_size;
3278 static int nand_setup_read_retry_micron(struct mtd_info *mtd, int retry_mode)
3280 struct nand_chip *chip = mtd->priv;
3281 uint8_t feature[ONFI_SUBFEATURE_PARAM_LEN] = {retry_mode};
3283 return chip->onfi_set_features(mtd, chip, ONFI_FEATURE_ADDR_READ_RETRY,
3288 * Configure chip properties from Micron vendor-specific ONFI table
3290 static void nand_onfi_detect_micron(struct nand_chip *chip,
3291 struct nand_onfi_params *p)
3293 struct nand_onfi_vendor_micron *micron = (void *)p->vendor;
3295 if (le16_to_cpu(p->vendor_revision) < 1)
3298 chip->read_retries = micron->read_retry_options;
3299 chip->setup_read_retry = nand_setup_read_retry_micron;
3303 * Check if the NAND chip is ONFI compliant, returns 1 if it is, 0 otherwise.
3305 static int nand_flash_detect_onfi(struct mtd_info *mtd, struct nand_chip *chip,
3308 struct nand_onfi_params *p = &chip->onfi_params;
3312 /* Try ONFI for unknown chip or LP */
3313 chip->cmdfunc(mtd, NAND_CMD_READID, 0x20, -1);
3314 if (chip->read_byte(mtd) != 'O' || chip->read_byte(mtd) != 'N' ||
3315 chip->read_byte(mtd) != 'F' || chip->read_byte(mtd) != 'I')
3318 chip->cmdfunc(mtd, NAND_CMD_PARAM, 0, -1);
3319 for (i = 0; i < 3; i++) {
3320 for (j = 0; j < sizeof(*p); j++)
3321 ((uint8_t *)p)[j] = chip->read_byte(mtd);
3322 if (onfi_crc16(ONFI_CRC_BASE, (uint8_t *)p, 254) ==
3323 le16_to_cpu(p->crc)) {
3329 pr_err("Could not find valid ONFI parameter page; aborting\n");
3334 val = le16_to_cpu(p->revision);
3336 chip->onfi_version = 23;
3337 else if (val & (1 << 4))
3338 chip->onfi_version = 22;
3339 else if (val & (1 << 3))
3340 chip->onfi_version = 21;
3341 else if (val & (1 << 2))
3342 chip->onfi_version = 20;
3343 else if (val & (1 << 1))
3344 chip->onfi_version = 10;
3346 if (!chip->onfi_version) {
3347 pr_info("unsupported ONFI version: %d\n", val);
3351 sanitize_string(p->manufacturer, sizeof(p->manufacturer));
3352 sanitize_string(p->model, sizeof(p->model));
3354 mtd->name = p->model;
3356 mtd->writesize = le32_to_cpu(p->byte_per_page);
3359 * pages_per_block and blocks_per_lun may not be a power-of-2 size
3360 * (don't ask me who thought of this...). MTD assumes that these
3361 * dimensions will be power-of-2, so just truncate the remaining area.
3363 mtd->erasesize = 1 << (fls(le32_to_cpu(p->pages_per_block)) - 1);
3364 mtd->erasesize *= mtd->writesize;
3366 mtd->oobsize = le16_to_cpu(p->spare_bytes_per_page);
3368 /* See erasesize comment */
3369 chip->chipsize = 1 << (fls(le32_to_cpu(p->blocks_per_lun)) - 1);
3370 chip->chipsize *= (uint64_t)mtd->erasesize * p->lun_count;
3371 chip->bits_per_cell = p->bits_per_cell;
3373 if (onfi_feature(chip) & ONFI_FEATURE_16_BIT_BUS)
3374 *busw = NAND_BUSWIDTH_16;
3378 if (p->ecc_bits != 0xff) {
3379 chip->ecc_strength_ds = p->ecc_bits;
3380 chip->ecc_step_ds = 512;
3381 } else if (chip->onfi_version >= 21 &&
3382 (onfi_feature(chip) & ONFI_FEATURE_EXT_PARAM_PAGE)) {
3385 * The nand_flash_detect_ext_param_page() uses the
3386 * Change Read Column command which maybe not supported
3387 * by the chip->cmdfunc. So try to update the chip->cmdfunc
3388 * now. We do not replace user supplied command function.
3390 if (mtd->writesize > 512 && chip->cmdfunc == nand_command)
3391 chip->cmdfunc = nand_command_lp;
3393 /* The Extended Parameter Page is supported since ONFI 2.1. */
3394 if (nand_flash_detect_ext_param_page(mtd, chip, p))
3395 pr_warn("Failed to detect ONFI extended param page\n");
3397 pr_warn("Could not retrieve ONFI ECC requirements\n");
3400 if (p->jedec_id == NAND_MFR_MICRON)
3401 nand_onfi_detect_micron(chip, p);
3407 * Check if the NAND chip is JEDEC compliant, returns 1 if it is, 0 otherwise.
3409 static int nand_flash_detect_jedec(struct mtd_info *mtd, struct nand_chip *chip,
3412 struct nand_jedec_params *p = &chip->jedec_params;
3413 struct jedec_ecc_info *ecc;
3417 /* Try JEDEC for unknown chip or LP */
3418 chip->cmdfunc(mtd, NAND_CMD_READID, 0x40, -1);
3419 if (chip->read_byte(mtd) != 'J' || chip->read_byte(mtd) != 'E' ||
3420 chip->read_byte(mtd) != 'D' || chip->read_byte(mtd) != 'E' ||
3421 chip->read_byte(mtd) != 'C')
3424 chip->cmdfunc(mtd, NAND_CMD_PARAM, 0x40, -1);
3425 for (i = 0; i < 3; i++) {
3426 for (j = 0; j < sizeof(*p); j++)
3427 ((uint8_t *)p)[j] = chip->read_byte(mtd);
3429 if (onfi_crc16(ONFI_CRC_BASE, (uint8_t *)p, 510) ==
3430 le16_to_cpu(p->crc))
3435 pr_err("Could not find valid JEDEC parameter page; aborting\n");
3440 val = le16_to_cpu(p->revision);
3442 chip->jedec_version = 10;
3443 else if (val & (1 << 1))
3444 chip->jedec_version = 1; /* vendor specific version */
3446 if (!chip->jedec_version) {
3447 pr_info("unsupported JEDEC version: %d\n", val);
3451 sanitize_string(p->manufacturer, sizeof(p->manufacturer));
3452 sanitize_string(p->model, sizeof(p->model));
3454 mtd->name = p->model;
3456 mtd->writesize = le32_to_cpu(p->byte_per_page);
3458 /* Please reference to the comment for nand_flash_detect_onfi. */
3459 mtd->erasesize = 1 << (fls(le32_to_cpu(p->pages_per_block)) - 1);
3460 mtd->erasesize *= mtd->writesize;
3462 mtd->oobsize = le16_to_cpu(p->spare_bytes_per_page);
3464 /* Please reference to the comment for nand_flash_detect_onfi. */
3465 chip->chipsize = 1 << (fls(le32_to_cpu(p->blocks_per_lun)) - 1);
3466 chip->chipsize *= (uint64_t)mtd->erasesize * p->lun_count;
3467 chip->bits_per_cell = p->bits_per_cell;
3469 if (jedec_feature(chip) & JEDEC_FEATURE_16_BIT_BUS)
3470 *busw = NAND_BUSWIDTH_16;
3475 ecc = &p->ecc_info[0];
3477 if (ecc->codeword_size >= 9) {
3478 chip->ecc_strength_ds = ecc->ecc_bits;
3479 chip->ecc_step_ds = 1 << ecc->codeword_size;
3481 pr_warn("Invalid codeword size\n");
3488 * nand_id_has_period - Check if an ID string has a given wraparound period
3489 * @id_data: the ID string
3490 * @arrlen: the length of the @id_data array
3491 * @period: the period of repitition
3493 * Check if an ID string is repeated within a given sequence of bytes at
3494 * specific repetition interval period (e.g., {0x20,0x01,0x7F,0x20} has a
3495 * period of 3). This is a helper function for nand_id_len(). Returns non-zero
3496 * if the repetition has a period of @period; otherwise, returns zero.
3498 static int nand_id_has_period(u8 *id_data, int arrlen, int period)
3501 for (i = 0; i < period; i++)
3502 for (j = i + period; j < arrlen; j += period)
3503 if (id_data[i] != id_data[j])
3509 * nand_id_len - Get the length of an ID string returned by CMD_READID
3510 * @id_data: the ID string
3511 * @arrlen: the length of the @id_data array
3513 * Returns the length of the ID string, according to known wraparound/trailing
3514 * zero patterns. If no pattern exists, returns the length of the array.
3516 static int nand_id_len(u8 *id_data, int arrlen)
3518 int last_nonzero, period;
3520 /* Find last non-zero byte */
3521 for (last_nonzero = arrlen - 1; last_nonzero >= 0; last_nonzero--)
3522 if (id_data[last_nonzero])
3526 if (last_nonzero < 0)
3529 /* Calculate wraparound period */
3530 for (period = 1; period < arrlen; period++)
3531 if (nand_id_has_period(id_data, arrlen, period))
3534 /* There's a repeated pattern */
3535 if (period < arrlen)
3538 /* There are trailing zeros */
3539 if (last_nonzero < arrlen - 1)
3540 return last_nonzero + 1;
3542 /* No pattern detected */
3546 /* Extract the bits of per cell from the 3rd byte of the extended ID */
3547 static int nand_get_bits_per_cell(u8 cellinfo)
3551 bits = cellinfo & NAND_CI_CELLTYPE_MSK;
3552 bits >>= NAND_CI_CELLTYPE_SHIFT;
3557 * Many new NAND share similar device ID codes, which represent the size of the
3558 * chip. The rest of the parameters must be decoded according to generic or
3559 * manufacturer-specific "extended ID" decoding patterns.
3561 static void nand_decode_ext_id(struct mtd_info *mtd, struct nand_chip *chip,
3562 u8 id_data[8], int *busw)
3565 /* The 3rd id byte holds MLC / multichip data */
3566 chip->bits_per_cell = nand_get_bits_per_cell(id_data[2]);
3567 /* The 4th id byte is the important one */
3570 id_len = nand_id_len(id_data, 8);
3573 * Field definitions are in the following datasheets:
3574 * Old style (4,5 byte ID): Samsung K9GAG08U0M (p.32)
3575 * New Samsung (6 byte ID): Samsung K9GAG08U0F (p.44)
3576 * Hynix MLC (6 byte ID): Hynix H27UBG8T2B (p.22)
3578 * Check for ID length, non-zero 6th byte, cell type, and Hynix/Samsung
3579 * ID to decide what to do.
3581 if (id_len == 6 && id_data[0] == NAND_MFR_SAMSUNG &&
3582 !nand_is_slc(chip) && id_data[5] != 0x00) {
3584 mtd->writesize = 2048 << (extid & 0x03);
3587 switch (((extid >> 2) & 0x04) | (extid & 0x03)) {
3607 default: /* Other cases are "reserved" (unknown) */
3608 mtd->oobsize = 1024;
3612 /* Calc blocksize */
3613 mtd->erasesize = (128 * 1024) <<
3614 (((extid >> 1) & 0x04) | (extid & 0x03));
3616 } else if (id_len == 6 && id_data[0] == NAND_MFR_HYNIX &&
3617 !nand_is_slc(chip)) {
3621 mtd->writesize = 2048 << (extid & 0x03);
3624 switch (((extid >> 2) & 0x04) | (extid & 0x03)) {
3648 /* Calc blocksize */
3649 tmp = ((extid >> 1) & 0x04) | (extid & 0x03);
3651 mtd->erasesize = (128 * 1024) << tmp;
3652 else if (tmp == 0x03)
3653 mtd->erasesize = 768 * 1024;
3655 mtd->erasesize = (64 * 1024) << tmp;
3659 mtd->writesize = 1024 << (extid & 0x03);
3662 mtd->oobsize = (8 << (extid & 0x01)) *
3663 (mtd->writesize >> 9);
3665 /* Calc blocksize. Blocksize is multiples of 64KiB */
3666 mtd->erasesize = (64 * 1024) << (extid & 0x03);
3668 /* Get buswidth information */
3669 *busw = (extid & 0x01) ? NAND_BUSWIDTH_16 : 0;
3672 * Toshiba 24nm raw SLC (i.e., not BENAND) have 32B OOB per
3673 * 512B page. For Toshiba SLC, we decode the 5th/6th byte as
3675 * - ID byte 6, bits[2:0]: 100b -> 43nm, 101b -> 32nm,
3677 * - ID byte 5, bit[7]: 1 -> BENAND, 0 -> raw SLC
3679 if (id_len >= 6 && id_data[0] == NAND_MFR_TOSHIBA &&
3680 nand_is_slc(chip) &&
3681 (id_data[5] & 0x7) == 0x6 /* 24nm */ &&
3682 !(id_data[4] & 0x80) /* !BENAND */) {
3683 mtd->oobsize = 32 * mtd->writesize >> 9;
3690 * Old devices have chip data hardcoded in the device ID table. nand_decode_id
3691 * decodes a matching ID table entry and assigns the MTD size parameters for
3694 static void nand_decode_id(struct mtd_info *mtd, struct nand_chip *chip,
3695 struct nand_flash_dev *type, u8 id_data[8],
3698 int maf_id = id_data[0];
3700 mtd->erasesize = type->erasesize;
3701 mtd->writesize = type->pagesize;
3702 mtd->oobsize = mtd->writesize / 32;
3703 *busw = type->options & NAND_BUSWIDTH_16;
3705 /* All legacy ID NAND are small-page, SLC */
3706 chip->bits_per_cell = 1;
3709 * Check for Spansion/AMD ID + repeating 5th, 6th byte since
3710 * some Spansion chips have erasesize that conflicts with size
3711 * listed in nand_ids table.
3712 * Data sheet (5 byte ID): Spansion S30ML-P ORNAND (p.39)
3714 if (maf_id == NAND_MFR_AMD && id_data[4] != 0x00 && id_data[5] == 0x00
3715 && id_data[6] == 0x00 && id_data[7] == 0x00
3716 && mtd->writesize == 512) {
3717 mtd->erasesize = 128 * 1024;
3718 mtd->erasesize <<= ((id_data[3] & 0x03) << 1);
3723 * Set the bad block marker/indicator (BBM/BBI) patterns according to some
3724 * heuristic patterns using various detected parameters (e.g., manufacturer,
3725 * page size, cell-type information).
3727 static void nand_decode_bbm_options(struct mtd_info *mtd,
3728 struct nand_chip *chip, u8 id_data[8])
3730 int maf_id = id_data[0];
3732 /* Set the bad block position */
3733 if (mtd->writesize > 512 || (chip->options & NAND_BUSWIDTH_16))
3734 chip->badblockpos = NAND_LARGE_BADBLOCK_POS;
3736 chip->badblockpos = NAND_SMALL_BADBLOCK_POS;
3739 * Bad block marker is stored in the last page of each block on Samsung
3740 * and Hynix MLC devices; stored in first two pages of each block on
3741 * Micron devices with 2KiB pages and on SLC Samsung, Hynix, Toshiba,
3742 * AMD/Spansion, and Macronix. All others scan only the first page.
3744 if (!nand_is_slc(chip) &&
3745 (maf_id == NAND_MFR_SAMSUNG ||
3746 maf_id == NAND_MFR_HYNIX))
3747 chip->bbt_options |= NAND_BBT_SCANLASTPAGE;
3748 else if ((nand_is_slc(chip) &&
3749 (maf_id == NAND_MFR_SAMSUNG ||
3750 maf_id == NAND_MFR_HYNIX ||
3751 maf_id == NAND_MFR_TOSHIBA ||
3752 maf_id == NAND_MFR_AMD ||
3753 maf_id == NAND_MFR_MACRONIX)) ||
3754 (mtd->writesize == 2048 &&
3755 maf_id == NAND_MFR_MICRON))
3756 chip->bbt_options |= NAND_BBT_SCAN2NDPAGE;
3759 static inline bool is_full_id_nand(struct nand_flash_dev *type)
3761 return type->id_len;
3764 static bool find_full_id_nand(struct mtd_info *mtd, struct nand_chip *chip,
3765 struct nand_flash_dev *type, u8 *id_data, int *busw)
3767 if (!strncmp(type->id, id_data, type->id_len)) {
3768 mtd->writesize = type->pagesize;
3769 mtd->erasesize = type->erasesize;
3770 mtd->oobsize = type->oobsize;
3772 chip->bits_per_cell = nand_get_bits_per_cell(id_data[2]);
3773 chip->chipsize = (uint64_t)type->chipsize << 20;
3774 chip->options |= type->options;
3775 chip->ecc_strength_ds = NAND_ECC_STRENGTH(type);
3776 chip->ecc_step_ds = NAND_ECC_STEP(type);
3777 chip->onfi_timing_mode_default =
3778 type->onfi_timing_mode_default;
3780 *busw = type->options & NAND_BUSWIDTH_16;
3783 mtd->name = type->name;
3791 * Get the flash and manufacturer id and lookup if the type is supported.
3793 static struct nand_flash_dev *nand_get_flash_type(struct mtd_info *mtd,
3794 struct nand_chip *chip,
3795 int *maf_id, int *dev_id,
3796 struct nand_flash_dev *type)
3802 /* Select the device */
3803 chip->select_chip(mtd, 0);
3806 * Reset the chip, required by some chips (e.g. Micron MT29FxGxxxxx)
3809 chip->cmdfunc(mtd, NAND_CMD_RESET, -1, -1);
3811 /* Send the command for reading device ID */
3812 chip->cmdfunc(mtd, NAND_CMD_READID, 0x00, -1);
3814 /* Read manufacturer and device IDs */
3815 *maf_id = chip->read_byte(mtd);
3816 *dev_id = chip->read_byte(mtd);
3819 * Try again to make sure, as some systems the bus-hold or other
3820 * interface concerns can cause random data which looks like a
3821 * possibly credible NAND flash to appear. If the two results do
3822 * not match, ignore the device completely.
3825 chip->cmdfunc(mtd, NAND_CMD_READID, 0x00, -1);
3827 /* Read entire ID string */
3828 for (i = 0; i < 8; i++)
3829 id_data[i] = chip->read_byte(mtd);
3831 if (id_data[0] != *maf_id || id_data[1] != *dev_id) {
3832 pr_info("second ID read did not match %02x,%02x against %02x,%02x\n",
3833 *maf_id, *dev_id, id_data[0], id_data[1]);
3834 return ERR_PTR(-ENODEV);
3838 type = nand_flash_ids;
3840 for (; type->name != NULL; type++) {
3841 if (is_full_id_nand(type)) {
3842 if (find_full_id_nand(mtd, chip, type, id_data, &busw))
3844 } else if (*dev_id == type->dev_id) {
3849 chip->onfi_version = 0;
3850 if (!type->name || !type->pagesize) {
3851 /* Check if the chip is ONFI compliant */
3852 if (nand_flash_detect_onfi(mtd, chip, &busw))
3855 /* Check if the chip is JEDEC compliant */
3856 if (nand_flash_detect_jedec(mtd, chip, &busw))
3861 return ERR_PTR(-ENODEV);
3864 mtd->name = type->name;
3866 chip->chipsize = (uint64_t)type->chipsize << 20;
3868 if (!type->pagesize) {
3869 /* Decode parameters from extended ID */
3870 nand_decode_ext_id(mtd, chip, id_data, &busw);
3872 nand_decode_id(mtd, chip, type, id_data, &busw);
3874 /* Get chip options */
3875 chip->options |= type->options;
3878 * Check if chip is not a Samsung device. Do not clear the
3879 * options for chips which do not have an extended id.
3881 if (*maf_id != NAND_MFR_SAMSUNG && !type->pagesize)
3882 chip->options &= ~NAND_SAMSUNG_LP_OPTIONS;
3885 /* Try to identify manufacturer */
3886 for (maf_idx = 0; nand_manuf_ids[maf_idx].id != 0x0; maf_idx++) {
3887 if (nand_manuf_ids[maf_idx].id == *maf_id)
3891 if (chip->options & NAND_BUSWIDTH_AUTO) {
3892 WARN_ON(chip->options & NAND_BUSWIDTH_16);
3893 chip->options |= busw;
3894 nand_set_defaults(chip, busw);
3895 } else if (busw != (chip->options & NAND_BUSWIDTH_16)) {
3897 * Check, if buswidth is correct. Hardware drivers should set
3900 pr_info("device found, Manufacturer ID: 0x%02x, Chip ID: 0x%02x\n",
3902 pr_info("%s %s\n", nand_manuf_ids[maf_idx].name, mtd->name);
3903 pr_warn("bus width %d instead %d bit\n",
3904 (chip->options & NAND_BUSWIDTH_16) ? 16 : 8,
3906 return ERR_PTR(-EINVAL);
3909 nand_decode_bbm_options(mtd, chip, id_data);
3911 /* Calculate the address shift from the page size */
3912 chip->page_shift = ffs(mtd->writesize) - 1;
3913 /* Convert chipsize to number of pages per chip -1 */
3914 chip->pagemask = (chip->chipsize >> chip->page_shift) - 1;
3916 chip->bbt_erase_shift = chip->phys_erase_shift =
3917 ffs(mtd->erasesize) - 1;
3918 if (chip->chipsize & 0xffffffff)
3919 chip->chip_shift = ffs((unsigned)chip->chipsize) - 1;
3921 chip->chip_shift = ffs((unsigned)(chip->chipsize >> 32));
3922 chip->chip_shift += 32 - 1;
3925 chip->badblockbits = 8;
3926 chip->erase = single_erase;
3928 /* Do not replace user supplied command function! */
3929 if (mtd->writesize > 512 && chip->cmdfunc == nand_command)
3930 chip->cmdfunc = nand_command_lp;
3932 pr_info("device found, Manufacturer ID: 0x%02x, Chip ID: 0x%02x\n",
3935 if (chip->onfi_version)
3936 pr_info("%s %s\n", nand_manuf_ids[maf_idx].name,
3937 chip->onfi_params.model);
3938 else if (chip->jedec_version)
3939 pr_info("%s %s\n", nand_manuf_ids[maf_idx].name,
3940 chip->jedec_params.model);
3942 pr_info("%s %s\n", nand_manuf_ids[maf_idx].name,
3945 pr_info("%d MiB, %s, erase size: %d KiB, page size: %d, OOB size: %d\n",
3946 (int)(chip->chipsize >> 20), nand_is_slc(chip) ? "SLC" : "MLC",
3947 mtd->erasesize >> 10, mtd->writesize, mtd->oobsize);
3951 static int nand_dt_init(struct mtd_info *mtd, struct nand_chip *chip,
3952 struct device_node *dn)
3954 int ecc_mode, ecc_strength, ecc_step;
3956 if (of_get_nand_bus_width(dn) == 16)
3957 chip->options |= NAND_BUSWIDTH_16;
3959 if (of_get_nand_on_flash_bbt(dn))
3960 chip->bbt_options |= NAND_BBT_USE_FLASH;
3962 ecc_mode = of_get_nand_ecc_mode(dn);
3963 ecc_strength = of_get_nand_ecc_strength(dn);
3964 ecc_step = of_get_nand_ecc_step_size(dn);
3966 if ((ecc_step >= 0 && !(ecc_strength >= 0)) ||
3967 (!(ecc_step >= 0) && ecc_strength >= 0)) {
3968 pr_err("must set both strength and step size in DT\n");
3973 chip->ecc.mode = ecc_mode;
3975 if (ecc_strength >= 0)
3976 chip->ecc.strength = ecc_strength;
3979 chip->ecc.size = ecc_step;
3985 * nand_scan_ident - [NAND Interface] Scan for the NAND device
3986 * @mtd: MTD device structure
3987 * @maxchips: number of chips to scan for
3988 * @table: alternative NAND ID table
3990 * This is the first phase of the normal nand_scan() function. It reads the
3991 * flash ID and sets up MTD fields accordingly.
3994 int nand_scan_ident(struct mtd_info *mtd, int maxchips,
3995 struct nand_flash_dev *table)
3997 int i, nand_maf_id, nand_dev_id;
3998 struct nand_chip *chip = mtd->priv;
3999 struct nand_flash_dev *type;
4002 if (chip->flash_node) {
4003 ret = nand_dt_init(mtd, chip, chip->flash_node);
4008 if (!mtd->name && mtd->dev.parent)
4009 mtd->name = dev_name(mtd->dev.parent);
4011 /* Set the default functions */
4012 nand_set_defaults(chip, chip->options & NAND_BUSWIDTH_16);
4014 /* Read the flash type */
4015 type = nand_get_flash_type(mtd, chip, &nand_maf_id,
4016 &nand_dev_id, table);
4019 if (!(chip->options & NAND_SCAN_SILENT_NODEV))
4020 pr_warn("No NAND device found\n");
4021 chip->select_chip(mtd, -1);
4022 return PTR_ERR(type);
4025 chip->select_chip(mtd, -1);
4027 /* Check for a chip array */
4028 for (i = 1; i < maxchips; i++) {
4029 chip->select_chip(mtd, i);
4030 /* See comment in nand_get_flash_type for reset */
4031 chip->cmdfunc(mtd, NAND_CMD_RESET, -1, -1);
4032 /* Send the command for reading device ID */
4033 chip->cmdfunc(mtd, NAND_CMD_READID, 0x00, -1);
4034 /* Read manufacturer and device IDs */
4035 if (nand_maf_id != chip->read_byte(mtd) ||
4036 nand_dev_id != chip->read_byte(mtd)) {
4037 chip->select_chip(mtd, -1);
4040 chip->select_chip(mtd, -1);
4043 pr_info("%d chips detected\n", i);
4045 /* Store the number of chips and calc total size for mtd */
4047 mtd->size = i * chip->chipsize;
4051 EXPORT_SYMBOL(nand_scan_ident);
4054 * Check if the chip configuration meet the datasheet requirements.
4056 * If our configuration corrects A bits per B bytes and the minimum
4057 * required correction level is X bits per Y bytes, then we must ensure
4058 * both of the following are true:
4060 * (1) A / B >= X / Y
4063 * Requirement (1) ensures we can correct for the required bitflip density.
4064 * Requirement (2) ensures we can correct even when all bitflips are clumped
4065 * in the same sector.
4067 static bool nand_ecc_strength_good(struct mtd_info *mtd)
4069 struct nand_chip *chip = mtd->priv;
4070 struct nand_ecc_ctrl *ecc = &chip->ecc;
4073 if (ecc->size == 0 || chip->ecc_step_ds == 0)
4074 /* Not enough information */
4078 * We get the number of corrected bits per page to compare
4079 * the correction density.
4081 corr = (mtd->writesize * ecc->strength) / ecc->size;
4082 ds_corr = (mtd->writesize * chip->ecc_strength_ds) / chip->ecc_step_ds;
4084 return corr >= ds_corr && ecc->strength >= chip->ecc_strength_ds;
4088 * nand_scan_tail - [NAND Interface] Scan for the NAND device
4089 * @mtd: MTD device structure
4091 * This is the second phase of the normal nand_scan() function. It fills out
4092 * all the uninitialized function pointers with the defaults and scans for a
4093 * bad block table if appropriate.
4095 int nand_scan_tail(struct mtd_info *mtd)
4098 struct nand_chip *chip = mtd->priv;
4099 struct nand_ecc_ctrl *ecc = &chip->ecc;
4100 struct nand_buffers *nbuf;
4102 /* New bad blocks should be marked in OOB, flash-based BBT, or both */
4103 BUG_ON((chip->bbt_options & NAND_BBT_NO_OOB_BBM) &&
4104 !(chip->bbt_options & NAND_BBT_USE_FLASH));
4106 if (!(chip->options & NAND_OWN_BUFFERS)) {
4107 nbuf = kzalloc(sizeof(*nbuf) + mtd->writesize
4108 + mtd->oobsize * 3, GFP_KERNEL);
4111 nbuf->ecccalc = (uint8_t *)(nbuf + 1);
4112 nbuf->ecccode = nbuf->ecccalc + mtd->oobsize;
4113 nbuf->databuf = nbuf->ecccode + mtd->oobsize;
4115 chip->buffers = nbuf;
4121 /* Set the internal oob buffer location, just after the page data */
4122 chip->oob_poi = chip->buffers->databuf + mtd->writesize;
4125 * If no default placement scheme is given, select an appropriate one.
4127 if (!ecc->layout && (ecc->mode != NAND_ECC_SOFT_BCH)) {
4128 switch (mtd->oobsize) {
4130 ecc->layout = &nand_oob_8;
4133 ecc->layout = &nand_oob_16;
4136 ecc->layout = &nand_oob_64;
4139 ecc->layout = &nand_oob_128;
4142 pr_warn("No oob scheme defined for oobsize %d\n",
4148 if (!chip->write_page)
4149 chip->write_page = nand_write_page;
4152 * Check ECC mode, default to software if 3byte/512byte hardware ECC is
4153 * selected and we have 256 byte pagesize fallback to software ECC
4156 switch (ecc->mode) {
4157 case NAND_ECC_HW_OOB_FIRST:
4158 /* Similar to NAND_ECC_HW, but a separate read_page handle */
4159 if (!ecc->calculate || !ecc->correct || !ecc->hwctl) {
4160 pr_warn("No ECC functions supplied; hardware ECC not possible\n");
4163 if (!ecc->read_page)
4164 ecc->read_page = nand_read_page_hwecc_oob_first;
4167 /* Use standard hwecc read page function? */
4168 if (!ecc->read_page)
4169 ecc->read_page = nand_read_page_hwecc;
4170 if (!ecc->write_page)
4171 ecc->write_page = nand_write_page_hwecc;
4172 if (!ecc->read_page_raw)
4173 ecc->read_page_raw = nand_read_page_raw;
4174 if (!ecc->write_page_raw)
4175 ecc->write_page_raw = nand_write_page_raw;
4177 ecc->read_oob = nand_read_oob_std;
4178 if (!ecc->write_oob)
4179 ecc->write_oob = nand_write_oob_std;
4180 if (!ecc->read_subpage)
4181 ecc->read_subpage = nand_read_subpage;
4182 if (!ecc->write_subpage)
4183 ecc->write_subpage = nand_write_subpage_hwecc;
4185 case NAND_ECC_HW_SYNDROME:
4186 if ((!ecc->calculate || !ecc->correct || !ecc->hwctl) &&
4188 ecc->read_page == nand_read_page_hwecc ||
4190 ecc->write_page == nand_write_page_hwecc)) {
4191 pr_warn("No ECC functions supplied; hardware ECC not possible\n");
4194 /* Use standard syndrome read/write page function? */
4195 if (!ecc->read_page)
4196 ecc->read_page = nand_read_page_syndrome;
4197 if (!ecc->write_page)
4198 ecc->write_page = nand_write_page_syndrome;
4199 if (!ecc->read_page_raw)
4200 ecc->read_page_raw = nand_read_page_raw_syndrome;
4201 if (!ecc->write_page_raw)
4202 ecc->write_page_raw = nand_write_page_raw_syndrome;
4204 ecc->read_oob = nand_read_oob_syndrome;
4205 if (!ecc->write_oob)
4206 ecc->write_oob = nand_write_oob_syndrome;
4208 if (mtd->writesize >= ecc->size) {
4209 if (!ecc->strength) {
4210 pr_warn("Driver must set ecc.strength when using hardware ECC\n");
4215 pr_warn("%d byte HW ECC not possible on %d byte page size, fallback to SW ECC\n",
4216 ecc->size, mtd->writesize);
4217 ecc->mode = NAND_ECC_SOFT;
4220 ecc->calculate = nand_calculate_ecc;
4221 ecc->correct = nand_correct_data;
4222 ecc->read_page = nand_read_page_swecc;
4223 ecc->read_subpage = nand_read_subpage;
4224 ecc->write_page = nand_write_page_swecc;
4225 ecc->read_page_raw = nand_read_page_raw;
4226 ecc->write_page_raw = nand_write_page_raw;
4227 ecc->read_oob = nand_read_oob_std;
4228 ecc->write_oob = nand_write_oob_std;
4235 case NAND_ECC_SOFT_BCH:
4236 if (!mtd_nand_has_bch()) {
4237 pr_warn("CONFIG_MTD_NAND_ECC_BCH not enabled\n");
4240 ecc->calculate = nand_bch_calculate_ecc;
4241 ecc->correct = nand_bch_correct_data;
4242 ecc->read_page = nand_read_page_swecc;
4243 ecc->read_subpage = nand_read_subpage;
4244 ecc->write_page = nand_write_page_swecc;
4245 ecc->read_page_raw = nand_read_page_raw;
4246 ecc->write_page_raw = nand_write_page_raw;
4247 ecc->read_oob = nand_read_oob_std;
4248 ecc->write_oob = nand_write_oob_std;
4250 * Board driver should supply ecc.size and ecc.strength values
4251 * to select how many bits are correctable. Otherwise, default
4252 * to 4 bits for large page devices.
4254 if (!ecc->size && (mtd->oobsize >= 64)) {
4259 /* See nand_bch_init() for details. */
4260 ecc->bytes = DIV_ROUND_UP(
4261 ecc->strength * fls(8 * ecc->size), 8);
4262 ecc->priv = nand_bch_init(mtd, ecc->size, ecc->bytes,
4265 pr_warn("BCH ECC initialization failed!\n");
4271 pr_warn("NAND_ECC_NONE selected by board driver. This is not recommended!\n");
4272 ecc->read_page = nand_read_page_raw;
4273 ecc->write_page = nand_write_page_raw;
4274 ecc->read_oob = nand_read_oob_std;
4275 ecc->read_page_raw = nand_read_page_raw;
4276 ecc->write_page_raw = nand_write_page_raw;
4277 ecc->write_oob = nand_write_oob_std;
4278 ecc->size = mtd->writesize;
4284 pr_warn("Invalid NAND_ECC_MODE %d\n", ecc->mode);
4288 /* For many systems, the standard OOB write also works for raw */
4289 if (!ecc->read_oob_raw)
4290 ecc->read_oob_raw = ecc->read_oob;
4291 if (!ecc->write_oob_raw)
4292 ecc->write_oob_raw = ecc->write_oob;
4295 * The number of bytes available for a client to place data into
4296 * the out of band area.
4298 ecc->layout->oobavail = 0;
4299 for (i = 0; ecc->layout->oobfree[i].length
4300 && i < ARRAY_SIZE(ecc->layout->oobfree); i++)
4301 ecc->layout->oobavail += ecc->layout->oobfree[i].length;
4302 mtd->oobavail = ecc->layout->oobavail;
4304 /* ECC sanity check: warn if it's too weak */
4305 if (!nand_ecc_strength_good(mtd))
4306 pr_warn("WARNING: %s: the ECC used on your system is too weak compared to the one required by the NAND chip\n",
4310 * Set the number of read / write steps for one page depending on ECC
4313 ecc->steps = mtd->writesize / ecc->size;
4314 if (ecc->steps * ecc->size != mtd->writesize) {
4315 pr_warn("Invalid ECC parameters\n");
4318 ecc->total = ecc->steps * ecc->bytes;
4320 /* Allow subpage writes up to ecc.steps. Not possible for MLC flash */
4321 if (!(chip->options & NAND_NO_SUBPAGE_WRITE) && nand_is_slc(chip)) {
4322 switch (ecc->steps) {
4324 mtd->subpage_sft = 1;
4329 mtd->subpage_sft = 2;
4333 chip->subpagesize = mtd->writesize >> mtd->subpage_sft;
4335 /* Initialize state */
4336 chip->state = FL_READY;
4338 /* Invalidate the pagebuffer reference */
4341 /* Large page NAND with SOFT_ECC should support subpage reads */
4342 switch (ecc->mode) {
4344 case NAND_ECC_SOFT_BCH:
4345 if (chip->page_shift > 9)
4346 chip->options |= NAND_SUBPAGE_READ;
4353 /* Fill in remaining MTD driver data */
4354 mtd->type = nand_is_slc(chip) ? MTD_NANDFLASH : MTD_MLCNANDFLASH;
4355 mtd->flags = (chip->options & NAND_ROM) ? MTD_CAP_ROM :
4357 mtd->_erase = nand_erase;
4359 mtd->_unpoint = NULL;
4360 mtd->_read = nand_read;
4361 mtd->_write = nand_write;
4362 mtd->_panic_write = panic_nand_write;
4363 mtd->_read_oob = nand_read_oob;
4364 mtd->_write_oob = nand_write_oob;
4365 mtd->_sync = nand_sync;
4367 mtd->_unlock = NULL;
4368 mtd->_suspend = nand_suspend;
4369 mtd->_resume = nand_resume;
4370 mtd->_reboot = nand_shutdown;
4371 mtd->_block_isreserved = nand_block_isreserved;
4372 mtd->_block_isbad = nand_block_isbad;
4373 mtd->_block_markbad = nand_block_markbad;
4374 mtd->writebufsize = mtd->writesize;
4376 /* propagate ecc info to mtd_info */
4377 mtd->ecclayout = ecc->layout;
4378 mtd->ecc_strength = ecc->strength;
4379 mtd->ecc_step_size = ecc->size;
4381 * Initialize bitflip_threshold to its default prior scan_bbt() call.
4382 * scan_bbt() might invoke mtd_read(), thus bitflip_threshold must be
4385 if (!mtd->bitflip_threshold)
4386 mtd->bitflip_threshold = DIV_ROUND_UP(mtd->ecc_strength * 3, 4);
4388 /* Check, if we should skip the bad block table scan */
4389 if (chip->options & NAND_SKIP_BBTSCAN)
4392 /* Build bad block table */
4393 return chip->scan_bbt(mtd);
4395 EXPORT_SYMBOL(nand_scan_tail);
4398 * is_module_text_address() isn't exported, and it's mostly a pointless
4399 * test if this is a module _anyway_ -- they'd have to try _really_ hard
4400 * to call us from in-kernel code if the core NAND support is modular.
4403 #define caller_is_module() (1)
4405 #define caller_is_module() \
4406 is_module_text_address((unsigned long)__builtin_return_address(0))
4410 * nand_scan - [NAND Interface] Scan for the NAND device
4411 * @mtd: MTD device structure
4412 * @maxchips: number of chips to scan for
4414 * This fills out all the uninitialized function pointers with the defaults.
4415 * The flash ID is read and the mtd/chip structures are filled with the
4416 * appropriate values.
4418 int nand_scan(struct mtd_info *mtd, int maxchips)
4422 ret = nand_scan_ident(mtd, maxchips, NULL);
4424 ret = nand_scan_tail(mtd);
4427 EXPORT_SYMBOL(nand_scan);
4430 * nand_cleanup - [NAND Interface] Free resources held by the NAND device
4431 * @chip: NAND chip object
4433 void nand_cleanup(struct nand_chip *chip)
4435 if (chip->ecc.mode == NAND_ECC_SOFT_BCH)
4436 nand_bch_free((struct nand_bch_control *)chip->ecc.priv);
4438 /* Free bad block table memory */
4440 if (!(chip->options & NAND_OWN_BUFFERS))
4441 kfree(chip->buffers);
4443 /* Free bad block descriptor memory */
4444 if (chip->badblock_pattern && chip->badblock_pattern->options
4445 & NAND_BBT_DYNAMICSTRUCT)
4446 kfree(chip->badblock_pattern);
4448 EXPORT_SYMBOL_GPL(nand_cleanup);
4451 * nand_release - [NAND Interface] Unregister the MTD device and free resources
4452 * held by the NAND device
4453 * @mtd: MTD device structure
4455 void nand_release(struct mtd_info *mtd)
4457 mtd_device_unregister(mtd);
4458 nand_cleanup(mtd->priv);
4460 EXPORT_SYMBOL_GPL(nand_release);
4462 static int __init nand_base_init(void)
4464 led_trigger_register_simple("nand-disk", &nand_led_trigger);
4468 static void __exit nand_base_exit(void)
4470 led_trigger_unregister_simple(nand_led_trigger);
4473 module_init(nand_base_init);
4474 module_exit(nand_base_exit);
4476 MODULE_LICENSE("GPL");
4477 MODULE_AUTHOR("Steven J. Hill <sjhill@realitydiluted.com>");
4478 MODULE_AUTHOR("Thomas Gleixner <tglx@linutronix.de>");
4479 MODULE_DESCRIPTION("Generic NAND flash driver code");