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();
546 /* Wait for the ready pin, after a command. The timeout is caught later. */
547 void nand_wait_ready(struct mtd_info *mtd)
549 struct nand_chip *chip = mtd->priv;
550 unsigned long timeo = jiffies + msecs_to_jiffies(20);
553 if (in_interrupt() || oops_in_progress)
554 return panic_nand_wait_ready(mtd, 400);
556 led_trigger_event(nand_led_trigger, LED_FULL);
557 /* Wait until command is processed or timeout occurs */
559 if (chip->dev_ready(mtd))
561 touch_softlockup_watchdog();
562 } while (time_before(jiffies, timeo));
563 led_trigger_event(nand_led_trigger, LED_OFF);
565 EXPORT_SYMBOL_GPL(nand_wait_ready);
568 * nand_wait_status_ready - [GENERIC] Wait for the ready status after commands.
569 * @mtd: MTD device structure
570 * @timeo: Timeout in ms
572 * Wait for status ready (i.e. command done) or timeout.
574 static void nand_wait_status_ready(struct mtd_info *mtd, unsigned long timeo)
576 register struct nand_chip *chip = mtd->priv;
578 timeo = jiffies + msecs_to_jiffies(timeo);
580 if ((chip->read_byte(mtd) & NAND_STATUS_READY))
582 touch_softlockup_watchdog();
583 } while (time_before(jiffies, timeo));
587 * nand_command - [DEFAULT] Send command to NAND device
588 * @mtd: MTD device structure
589 * @command: the command to be sent
590 * @column: the column address for this command, -1 if none
591 * @page_addr: the page address for this command, -1 if none
593 * Send command to NAND device. This function is used for small page devices
594 * (512 Bytes per page).
596 static void nand_command(struct mtd_info *mtd, unsigned int command,
597 int column, int page_addr)
599 register struct nand_chip *chip = mtd->priv;
600 int ctrl = NAND_CTRL_CLE | NAND_CTRL_CHANGE;
602 /* Write out the command to the device */
603 if (command == NAND_CMD_SEQIN) {
606 if (column >= mtd->writesize) {
608 column -= mtd->writesize;
609 readcmd = NAND_CMD_READOOB;
610 } else if (column < 256) {
611 /* First 256 bytes --> READ0 */
612 readcmd = NAND_CMD_READ0;
615 readcmd = NAND_CMD_READ1;
617 chip->cmd_ctrl(mtd, readcmd, ctrl);
618 ctrl &= ~NAND_CTRL_CHANGE;
620 chip->cmd_ctrl(mtd, command, ctrl);
622 /* Address cycle, when necessary */
623 ctrl = NAND_CTRL_ALE | NAND_CTRL_CHANGE;
624 /* Serially input address */
626 /* Adjust columns for 16 bit buswidth */
627 if (chip->options & NAND_BUSWIDTH_16 &&
628 !nand_opcode_8bits(command))
630 chip->cmd_ctrl(mtd, column, ctrl);
631 ctrl &= ~NAND_CTRL_CHANGE;
633 if (page_addr != -1) {
634 chip->cmd_ctrl(mtd, page_addr, ctrl);
635 ctrl &= ~NAND_CTRL_CHANGE;
636 chip->cmd_ctrl(mtd, page_addr >> 8, ctrl);
637 /* One more address cycle for devices > 32MiB */
638 if (chip->chipsize > (32 << 20))
639 chip->cmd_ctrl(mtd, page_addr >> 16, ctrl);
641 chip->cmd_ctrl(mtd, NAND_CMD_NONE, NAND_NCE | NAND_CTRL_CHANGE);
644 * Program and erase have their own busy handlers status and sequential
649 case NAND_CMD_PAGEPROG:
650 case NAND_CMD_ERASE1:
651 case NAND_CMD_ERASE2:
653 case NAND_CMD_STATUS:
659 udelay(chip->chip_delay);
660 chip->cmd_ctrl(mtd, NAND_CMD_STATUS,
661 NAND_CTRL_CLE | NAND_CTRL_CHANGE);
663 NAND_CMD_NONE, NAND_NCE | NAND_CTRL_CHANGE);
664 /* EZ-NAND can take upto 250ms as per ONFi v4.0 */
665 nand_wait_status_ready(mtd, 250);
668 /* This applies to read commands */
671 * If we don't have access to the busy pin, we apply the given
674 if (!chip->dev_ready) {
675 udelay(chip->chip_delay);
680 * Apply this short delay always to ensure that we do wait tWB in
681 * any case on any machine.
685 nand_wait_ready(mtd);
689 * nand_command_lp - [DEFAULT] Send command to NAND large page device
690 * @mtd: MTD device structure
691 * @command: the command to be sent
692 * @column: the column address for this command, -1 if none
693 * @page_addr: the page address for this command, -1 if none
695 * Send command to NAND device. This is the version for the new large page
696 * devices. We don't have the separate regions as we have in the small page
697 * devices. We must emulate NAND_CMD_READOOB to keep the code compatible.
699 static void nand_command_lp(struct mtd_info *mtd, unsigned int command,
700 int column, int page_addr)
702 register struct nand_chip *chip = mtd->priv;
704 /* Emulate NAND_CMD_READOOB */
705 if (command == NAND_CMD_READOOB) {
706 column += mtd->writesize;
707 command = NAND_CMD_READ0;
710 /* Command latch cycle */
711 chip->cmd_ctrl(mtd, command, NAND_NCE | NAND_CLE | NAND_CTRL_CHANGE);
713 if (column != -1 || page_addr != -1) {
714 int ctrl = NAND_CTRL_CHANGE | NAND_NCE | NAND_ALE;
716 /* Serially input address */
718 /* Adjust columns for 16 bit buswidth */
719 if (chip->options & NAND_BUSWIDTH_16 &&
720 !nand_opcode_8bits(command))
722 chip->cmd_ctrl(mtd, column, ctrl);
723 ctrl &= ~NAND_CTRL_CHANGE;
724 chip->cmd_ctrl(mtd, column >> 8, ctrl);
726 if (page_addr != -1) {
727 chip->cmd_ctrl(mtd, page_addr, ctrl);
728 chip->cmd_ctrl(mtd, page_addr >> 8,
729 NAND_NCE | NAND_ALE);
730 /* One more address cycle for devices > 128MiB */
731 if (chip->chipsize > (128 << 20))
732 chip->cmd_ctrl(mtd, page_addr >> 16,
733 NAND_NCE | NAND_ALE);
736 chip->cmd_ctrl(mtd, NAND_CMD_NONE, NAND_NCE | NAND_CTRL_CHANGE);
739 * Program and erase have their own busy handlers status, sequential
740 * in and status need no delay.
744 case NAND_CMD_CACHEDPROG:
745 case NAND_CMD_PAGEPROG:
746 case NAND_CMD_ERASE1:
747 case NAND_CMD_ERASE2:
750 case NAND_CMD_STATUS:
756 udelay(chip->chip_delay);
757 chip->cmd_ctrl(mtd, NAND_CMD_STATUS,
758 NAND_NCE | NAND_CLE | NAND_CTRL_CHANGE);
759 chip->cmd_ctrl(mtd, NAND_CMD_NONE,
760 NAND_NCE | NAND_CTRL_CHANGE);
761 /* EZ-NAND can take upto 250ms as per ONFi v4.0 */
762 nand_wait_status_ready(mtd, 250);
765 case NAND_CMD_RNDOUT:
766 /* No ready / busy check necessary */
767 chip->cmd_ctrl(mtd, NAND_CMD_RNDOUTSTART,
768 NAND_NCE | NAND_CLE | NAND_CTRL_CHANGE);
769 chip->cmd_ctrl(mtd, NAND_CMD_NONE,
770 NAND_NCE | NAND_CTRL_CHANGE);
774 chip->cmd_ctrl(mtd, NAND_CMD_READSTART,
775 NAND_NCE | NAND_CLE | NAND_CTRL_CHANGE);
776 chip->cmd_ctrl(mtd, NAND_CMD_NONE,
777 NAND_NCE | NAND_CTRL_CHANGE);
779 /* This applies to read commands */
782 * If we don't have access to the busy pin, we apply the given
785 if (!chip->dev_ready) {
786 udelay(chip->chip_delay);
792 * Apply this short delay always to ensure that we do wait tWB in
793 * any case on any machine.
797 nand_wait_ready(mtd);
801 * panic_nand_get_device - [GENERIC] Get chip for selected access
802 * @chip: the nand chip descriptor
803 * @mtd: MTD device structure
804 * @new_state: the state which is requested
806 * Used when in panic, no locks are taken.
808 static void panic_nand_get_device(struct nand_chip *chip,
809 struct mtd_info *mtd, int new_state)
811 /* Hardware controller shared among independent devices */
812 chip->controller->active = chip;
813 chip->state = new_state;
817 * nand_get_device - [GENERIC] Get chip for selected access
818 * @mtd: MTD device structure
819 * @new_state: the state which is requested
821 * Get the device and lock it for exclusive access
824 nand_get_device(struct mtd_info *mtd, int new_state)
826 struct nand_chip *chip = mtd->priv;
827 spinlock_t *lock = &chip->controller->lock;
828 wait_queue_head_t *wq = &chip->controller->wq;
829 DECLARE_WAITQUEUE(wait, current);
833 /* Hardware controller shared among independent devices */
834 if (!chip->controller->active)
835 chip->controller->active = chip;
837 if (chip->controller->active == chip && chip->state == FL_READY) {
838 chip->state = new_state;
842 if (new_state == FL_PM_SUSPENDED) {
843 if (chip->controller->active->state == FL_PM_SUSPENDED) {
844 chip->state = FL_PM_SUSPENDED;
849 set_current_state(TASK_UNINTERRUPTIBLE);
850 add_wait_queue(wq, &wait);
853 remove_wait_queue(wq, &wait);
858 * panic_nand_wait - [GENERIC] wait until the command is done
859 * @mtd: MTD device structure
860 * @chip: NAND chip structure
863 * Wait for command done. This is a helper function for nand_wait used when
864 * we are in interrupt context. May happen when in panic and trying to write
865 * an oops through mtdoops.
867 static void panic_nand_wait(struct mtd_info *mtd, struct nand_chip *chip,
871 for (i = 0; i < timeo; i++) {
872 if (chip->dev_ready) {
873 if (chip->dev_ready(mtd))
876 if (chip->read_byte(mtd) & NAND_STATUS_READY)
884 * nand_wait - [DEFAULT] wait until the command is done
885 * @mtd: MTD device structure
886 * @chip: NAND chip structure
888 * Wait for command done. This applies to erase and program only. Erase can
889 * take up to 400ms and program up to 20ms according to general NAND and
892 static int nand_wait(struct mtd_info *mtd, struct nand_chip *chip)
895 int status, state = chip->state;
896 unsigned long timeo = (state == FL_ERASING ? 400 : 20);
898 led_trigger_event(nand_led_trigger, LED_FULL);
901 * Apply this short delay always to ensure that we do wait tWB in any
902 * case on any machine.
906 chip->cmdfunc(mtd, NAND_CMD_STATUS, -1, -1);
908 if (in_interrupt() || oops_in_progress)
909 panic_nand_wait(mtd, chip, timeo);
911 timeo = jiffies + msecs_to_jiffies(timeo);
912 while (time_before(jiffies, timeo)) {
913 if (chip->dev_ready) {
914 if (chip->dev_ready(mtd))
917 if (chip->read_byte(mtd) & NAND_STATUS_READY)
923 led_trigger_event(nand_led_trigger, LED_OFF);
925 status = (int)chip->read_byte(mtd);
926 /* This can happen if in case of timeout or buggy dev_ready */
927 WARN_ON(!(status & NAND_STATUS_READY));
932 * __nand_unlock - [REPLACEABLE] unlocks specified locked blocks
934 * @ofs: offset to start unlock from
935 * @len: length to unlock
936 * @invert: when = 0, unlock the range of blocks within the lower and
937 * upper boundary address
938 * when = 1, unlock the range of blocks outside the boundaries
939 * of the lower and upper boundary address
941 * Returs unlock status.
943 static int __nand_unlock(struct mtd_info *mtd, loff_t ofs,
944 uint64_t len, int invert)
948 struct nand_chip *chip = mtd->priv;
950 /* Submit address of first page to unlock */
951 page = ofs >> chip->page_shift;
952 chip->cmdfunc(mtd, NAND_CMD_UNLOCK1, -1, page & chip->pagemask);
954 /* Submit address of last page to unlock */
955 page = (ofs + len) >> chip->page_shift;
956 chip->cmdfunc(mtd, NAND_CMD_UNLOCK2, -1,
957 (page | invert) & chip->pagemask);
959 /* Call wait ready function */
960 status = chip->waitfunc(mtd, chip);
961 /* See if device thinks it succeeded */
962 if (status & NAND_STATUS_FAIL) {
963 pr_debug("%s: error status = 0x%08x\n",
972 * nand_unlock - [REPLACEABLE] unlocks specified locked blocks
974 * @ofs: offset to start unlock from
975 * @len: length to unlock
977 * Returns unlock status.
979 int nand_unlock(struct mtd_info *mtd, loff_t ofs, uint64_t len)
983 struct nand_chip *chip = mtd->priv;
985 pr_debug("%s: start = 0x%012llx, len = %llu\n",
986 __func__, (unsigned long long)ofs, len);
988 if (check_offs_len(mtd, ofs, len))
991 /* Align to last block address if size addresses end of the device */
992 if (ofs + len == mtd->size)
993 len -= mtd->erasesize;
995 nand_get_device(mtd, FL_UNLOCKING);
997 /* Shift to get chip number */
998 chipnr = ofs >> chip->chip_shift;
1000 chip->select_chip(mtd, chipnr);
1004 * If we want to check the WP through READ STATUS and check the bit 7
1005 * we must reset the chip
1006 * some operation can also clear the bit 7 of status register
1007 * eg. erase/program a locked block
1009 chip->cmdfunc(mtd, NAND_CMD_RESET, -1, -1);
1011 /* Check, if it is write protected */
1012 if (nand_check_wp(mtd)) {
1013 pr_debug("%s: device is write protected!\n",
1019 ret = __nand_unlock(mtd, ofs, len, 0);
1022 chip->select_chip(mtd, -1);
1023 nand_release_device(mtd);
1027 EXPORT_SYMBOL(nand_unlock);
1030 * nand_lock - [REPLACEABLE] locks all blocks present in the device
1032 * @ofs: offset to start unlock from
1033 * @len: length to unlock
1035 * This feature is not supported in many NAND parts. 'Micron' NAND parts do
1036 * have this feature, but it allows only to lock all blocks, not for specified
1037 * range for block. Implementing 'lock' feature by making use of 'unlock', for
1040 * Returns lock status.
1042 int nand_lock(struct mtd_info *mtd, loff_t ofs, uint64_t len)
1045 int chipnr, status, page;
1046 struct nand_chip *chip = mtd->priv;
1048 pr_debug("%s: start = 0x%012llx, len = %llu\n",
1049 __func__, (unsigned long long)ofs, len);
1051 if (check_offs_len(mtd, ofs, len))
1054 nand_get_device(mtd, FL_LOCKING);
1056 /* Shift to get chip number */
1057 chipnr = ofs >> chip->chip_shift;
1059 chip->select_chip(mtd, chipnr);
1063 * If we want to check the WP through READ STATUS and check the bit 7
1064 * we must reset the chip
1065 * some operation can also clear the bit 7 of status register
1066 * eg. erase/program a locked block
1068 chip->cmdfunc(mtd, NAND_CMD_RESET, -1, -1);
1070 /* Check, if it is write protected */
1071 if (nand_check_wp(mtd)) {
1072 pr_debug("%s: device is write protected!\n",
1074 status = MTD_ERASE_FAILED;
1079 /* Submit address of first page to lock */
1080 page = ofs >> chip->page_shift;
1081 chip->cmdfunc(mtd, NAND_CMD_LOCK, -1, page & chip->pagemask);
1083 /* Call wait ready function */
1084 status = chip->waitfunc(mtd, chip);
1085 /* See if device thinks it succeeded */
1086 if (status & NAND_STATUS_FAIL) {
1087 pr_debug("%s: error status = 0x%08x\n",
1093 ret = __nand_unlock(mtd, ofs, len, 0x1);
1096 chip->select_chip(mtd, -1);
1097 nand_release_device(mtd);
1101 EXPORT_SYMBOL(nand_lock);
1104 * nand_check_erased_buf - check if a buffer contains (almost) only 0xff data
1105 * @buf: buffer to test
1106 * @len: buffer length
1107 * @bitflips_threshold: maximum number of bitflips
1109 * Check if a buffer contains only 0xff, which means the underlying region
1110 * has been erased and is ready to be programmed.
1111 * The bitflips_threshold specify the maximum number of bitflips before
1112 * considering the region is not erased.
1113 * Note: The logic of this function has been extracted from the memweight
1114 * implementation, except that nand_check_erased_buf function exit before
1115 * testing the whole buffer if the number of bitflips exceed the
1116 * bitflips_threshold value.
1118 * Returns a positive number of bitflips less than or equal to
1119 * bitflips_threshold, or -ERROR_CODE for bitflips in excess of the
1122 static int nand_check_erased_buf(void *buf, int len, int bitflips_threshold)
1124 const unsigned char *bitmap = buf;
1128 for (; len && ((uintptr_t)bitmap) % sizeof(long);
1130 weight = hweight8(*bitmap);
1131 bitflips += BITS_PER_BYTE - weight;
1132 if (unlikely(bitflips > bitflips_threshold))
1136 for (; len >= sizeof(long);
1137 len -= sizeof(long), bitmap += sizeof(long)) {
1138 weight = hweight_long(*((unsigned long *)bitmap));
1139 bitflips += BITS_PER_LONG - weight;
1140 if (unlikely(bitflips > bitflips_threshold))
1144 for (; len > 0; len--, bitmap++) {
1145 weight = hweight8(*bitmap);
1146 bitflips += BITS_PER_BYTE - weight;
1147 if (unlikely(bitflips > bitflips_threshold))
1155 * nand_check_erased_ecc_chunk - check if an ECC chunk contains (almost) only
1157 * @data: data buffer to test
1158 * @datalen: data length
1160 * @ecclen: ECC length
1161 * @extraoob: extra OOB buffer
1162 * @extraooblen: extra OOB length
1163 * @bitflips_threshold: maximum number of bitflips
1165 * Check if a data buffer and its associated ECC and OOB data contains only
1166 * 0xff pattern, which means the underlying region has been erased and is
1167 * ready to be programmed.
1168 * The bitflips_threshold specify the maximum number of bitflips before
1169 * considering the region as not erased.
1172 * 1/ ECC algorithms are working on pre-defined block sizes which are usually
1173 * different from the NAND page size. When fixing bitflips, ECC engines will
1174 * report the number of errors per chunk, and the NAND core infrastructure
1175 * expect you to return the maximum number of bitflips for the whole page.
1176 * This is why you should always use this function on a single chunk and
1177 * not on the whole page. After checking each chunk you should update your
1178 * max_bitflips value accordingly.
1179 * 2/ When checking for bitflips in erased pages you should not only check
1180 * the payload data but also their associated ECC data, because a user might
1181 * have programmed almost all bits to 1 but a few. In this case, we
1182 * shouldn't consider the chunk as erased, and checking ECC bytes prevent
1184 * 3/ The extraoob argument is optional, and should be used if some of your OOB
1185 * data are protected by the ECC engine.
1186 * It could also be used if you support subpages and want to attach some
1187 * extra OOB data to an ECC chunk.
1189 * Returns a positive number of bitflips less than or equal to
1190 * bitflips_threshold, or -ERROR_CODE for bitflips in excess of the
1191 * threshold. In case of success, the passed buffers are filled with 0xff.
1193 int nand_check_erased_ecc_chunk(void *data, int datalen,
1194 void *ecc, int ecclen,
1195 void *extraoob, int extraooblen,
1196 int bitflips_threshold)
1198 int data_bitflips = 0, ecc_bitflips = 0, extraoob_bitflips = 0;
1200 data_bitflips = nand_check_erased_buf(data, datalen,
1201 bitflips_threshold);
1202 if (data_bitflips < 0)
1203 return data_bitflips;
1205 bitflips_threshold -= data_bitflips;
1207 ecc_bitflips = nand_check_erased_buf(ecc, ecclen, bitflips_threshold);
1208 if (ecc_bitflips < 0)
1209 return ecc_bitflips;
1211 bitflips_threshold -= ecc_bitflips;
1213 extraoob_bitflips = nand_check_erased_buf(extraoob, extraooblen,
1214 bitflips_threshold);
1215 if (extraoob_bitflips < 0)
1216 return extraoob_bitflips;
1219 memset(data, 0xff, datalen);
1222 memset(ecc, 0xff, ecclen);
1224 if (extraoob_bitflips)
1225 memset(extraoob, 0xff, extraooblen);
1227 return data_bitflips + ecc_bitflips + extraoob_bitflips;
1229 EXPORT_SYMBOL(nand_check_erased_ecc_chunk);
1232 * nand_read_page_raw - [INTERN] read raw page data without ecc
1233 * @mtd: mtd info structure
1234 * @chip: nand chip info structure
1235 * @buf: buffer to store read data
1236 * @oob_required: caller requires OOB data read to chip->oob_poi
1237 * @page: page number to read
1239 * Not for syndrome calculating ECC controllers, which use a special oob layout.
1241 static int nand_read_page_raw(struct mtd_info *mtd, struct nand_chip *chip,
1242 uint8_t *buf, int oob_required, int page)
1244 chip->read_buf(mtd, buf, mtd->writesize);
1246 chip->read_buf(mtd, chip->oob_poi, mtd->oobsize);
1251 * nand_read_page_raw_syndrome - [INTERN] read raw page data without ecc
1252 * @mtd: mtd info structure
1253 * @chip: nand chip info structure
1254 * @buf: buffer to store read data
1255 * @oob_required: caller requires OOB data read to chip->oob_poi
1256 * @page: page number to read
1258 * We need a special oob layout and handling even when OOB isn't used.
1260 static int nand_read_page_raw_syndrome(struct mtd_info *mtd,
1261 struct nand_chip *chip, uint8_t *buf,
1262 int oob_required, int page)
1264 int eccsize = chip->ecc.size;
1265 int eccbytes = chip->ecc.bytes;
1266 uint8_t *oob = chip->oob_poi;
1269 for (steps = chip->ecc.steps; steps > 0; steps--) {
1270 chip->read_buf(mtd, buf, eccsize);
1273 if (chip->ecc.prepad) {
1274 chip->read_buf(mtd, oob, chip->ecc.prepad);
1275 oob += chip->ecc.prepad;
1278 chip->read_buf(mtd, oob, eccbytes);
1281 if (chip->ecc.postpad) {
1282 chip->read_buf(mtd, oob, chip->ecc.postpad);
1283 oob += chip->ecc.postpad;
1287 size = mtd->oobsize - (oob - chip->oob_poi);
1289 chip->read_buf(mtd, oob, size);
1295 * nand_read_page_swecc - [REPLACEABLE] software ECC based page read function
1296 * @mtd: mtd info structure
1297 * @chip: nand chip info structure
1298 * @buf: buffer to store read data
1299 * @oob_required: caller requires OOB data read to chip->oob_poi
1300 * @page: page number to read
1302 static int nand_read_page_swecc(struct mtd_info *mtd, struct nand_chip *chip,
1303 uint8_t *buf, int oob_required, int page)
1305 int i, eccsize = chip->ecc.size;
1306 int eccbytes = chip->ecc.bytes;
1307 int eccsteps = chip->ecc.steps;
1309 uint8_t *ecc_calc = chip->buffers->ecccalc;
1310 uint8_t *ecc_code = chip->buffers->ecccode;
1311 uint32_t *eccpos = chip->ecc.layout->eccpos;
1312 unsigned int max_bitflips = 0;
1314 chip->ecc.read_page_raw(mtd, chip, buf, 1, page);
1316 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize)
1317 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
1319 for (i = 0; i < chip->ecc.total; i++)
1320 ecc_code[i] = chip->oob_poi[eccpos[i]];
1322 eccsteps = chip->ecc.steps;
1325 for (i = 0 ; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
1328 stat = chip->ecc.correct(mtd, p, &ecc_code[i], &ecc_calc[i]);
1330 mtd->ecc_stats.failed++;
1332 mtd->ecc_stats.corrected += stat;
1333 max_bitflips = max_t(unsigned int, max_bitflips, stat);
1336 return max_bitflips;
1340 * nand_read_subpage - [REPLACEABLE] ECC based sub-page read function
1341 * @mtd: mtd info structure
1342 * @chip: nand chip info structure
1343 * @data_offs: offset of requested data within the page
1344 * @readlen: data length
1345 * @bufpoi: buffer to store read data
1346 * @page: page number to read
1348 static int nand_read_subpage(struct mtd_info *mtd, struct nand_chip *chip,
1349 uint32_t data_offs, uint32_t readlen, uint8_t *bufpoi,
1352 int start_step, end_step, num_steps;
1353 uint32_t *eccpos = chip->ecc.layout->eccpos;
1355 int data_col_addr, i, gaps = 0;
1356 int datafrag_len, eccfrag_len, aligned_len, aligned_pos;
1357 int busw = (chip->options & NAND_BUSWIDTH_16) ? 2 : 1;
1359 unsigned int max_bitflips = 0;
1361 /* Column address within the page aligned to ECC size (256bytes) */
1362 start_step = data_offs / chip->ecc.size;
1363 end_step = (data_offs + readlen - 1) / chip->ecc.size;
1364 num_steps = end_step - start_step + 1;
1365 index = start_step * chip->ecc.bytes;
1367 /* Data size aligned to ECC ecc.size */
1368 datafrag_len = num_steps * chip->ecc.size;
1369 eccfrag_len = num_steps * chip->ecc.bytes;
1371 data_col_addr = start_step * chip->ecc.size;
1372 /* If we read not a page aligned data */
1373 if (data_col_addr != 0)
1374 chip->cmdfunc(mtd, NAND_CMD_RNDOUT, data_col_addr, -1);
1376 p = bufpoi + data_col_addr;
1377 chip->read_buf(mtd, p, datafrag_len);
1380 for (i = 0; i < eccfrag_len ; i += chip->ecc.bytes, p += chip->ecc.size)
1381 chip->ecc.calculate(mtd, p, &chip->buffers->ecccalc[i]);
1384 * The performance is faster if we position offsets according to
1385 * ecc.pos. Let's make sure that there are no gaps in ECC positions.
1387 for (i = 0; i < eccfrag_len - 1; i++) {
1388 if (eccpos[i + index] + 1 != eccpos[i + index + 1]) {
1394 chip->cmdfunc(mtd, NAND_CMD_RNDOUT, mtd->writesize, -1);
1395 chip->read_buf(mtd, chip->oob_poi, mtd->oobsize);
1398 * Send the command to read the particular ECC bytes take care
1399 * about buswidth alignment in read_buf.
1401 aligned_pos = eccpos[index] & ~(busw - 1);
1402 aligned_len = eccfrag_len;
1403 if (eccpos[index] & (busw - 1))
1405 if (eccpos[index + (num_steps * chip->ecc.bytes)] & (busw - 1))
1408 chip->cmdfunc(mtd, NAND_CMD_RNDOUT,
1409 mtd->writesize + aligned_pos, -1);
1410 chip->read_buf(mtd, &chip->oob_poi[aligned_pos], aligned_len);
1413 for (i = 0; i < eccfrag_len; i++)
1414 chip->buffers->ecccode[i] = chip->oob_poi[eccpos[i + index]];
1416 p = bufpoi + data_col_addr;
1417 for (i = 0; i < eccfrag_len ; i += chip->ecc.bytes, p += chip->ecc.size) {
1420 stat = chip->ecc.correct(mtd, p,
1421 &chip->buffers->ecccode[i], &chip->buffers->ecccalc[i]);
1423 mtd->ecc_stats.failed++;
1425 mtd->ecc_stats.corrected += stat;
1426 max_bitflips = max_t(unsigned int, max_bitflips, stat);
1429 return max_bitflips;
1433 * nand_read_page_hwecc - [REPLACEABLE] hardware ECC based page read function
1434 * @mtd: mtd info structure
1435 * @chip: nand chip info structure
1436 * @buf: buffer to store read data
1437 * @oob_required: caller requires OOB data read to chip->oob_poi
1438 * @page: page number to read
1440 * Not for syndrome calculating ECC controllers which need a special oob layout.
1442 static int nand_read_page_hwecc(struct mtd_info *mtd, struct nand_chip *chip,
1443 uint8_t *buf, int oob_required, int page)
1445 int i, eccsize = chip->ecc.size;
1446 int eccbytes = chip->ecc.bytes;
1447 int eccsteps = chip->ecc.steps;
1449 uint8_t *ecc_calc = chip->buffers->ecccalc;
1450 uint8_t *ecc_code = chip->buffers->ecccode;
1451 uint32_t *eccpos = chip->ecc.layout->eccpos;
1452 unsigned int max_bitflips = 0;
1454 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
1455 chip->ecc.hwctl(mtd, NAND_ECC_READ);
1456 chip->read_buf(mtd, p, eccsize);
1457 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
1459 chip->read_buf(mtd, chip->oob_poi, mtd->oobsize);
1461 for (i = 0; i < chip->ecc.total; i++)
1462 ecc_code[i] = chip->oob_poi[eccpos[i]];
1464 eccsteps = chip->ecc.steps;
1467 for (i = 0 ; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
1470 stat = chip->ecc.correct(mtd, p, &ecc_code[i], &ecc_calc[i]);
1472 mtd->ecc_stats.failed++;
1474 mtd->ecc_stats.corrected += stat;
1475 max_bitflips = max_t(unsigned int, max_bitflips, stat);
1478 return max_bitflips;
1482 * nand_read_page_hwecc_oob_first - [REPLACEABLE] hw ecc, read oob first
1483 * @mtd: mtd info structure
1484 * @chip: nand chip info structure
1485 * @buf: buffer to store read data
1486 * @oob_required: caller requires OOB data read to chip->oob_poi
1487 * @page: page number to read
1489 * Hardware ECC for large page chips, require OOB to be read first. For this
1490 * ECC mode, the write_page method is re-used from ECC_HW. These methods
1491 * read/write ECC from the OOB area, unlike the ECC_HW_SYNDROME support with
1492 * multiple ECC steps, follows the "infix ECC" scheme and reads/writes ECC from
1493 * the data area, by overwriting the NAND manufacturer bad block markings.
1495 static int nand_read_page_hwecc_oob_first(struct mtd_info *mtd,
1496 struct nand_chip *chip, uint8_t *buf, int oob_required, int page)
1498 int i, eccsize = chip->ecc.size;
1499 int eccbytes = chip->ecc.bytes;
1500 int eccsteps = chip->ecc.steps;
1502 uint8_t *ecc_code = chip->buffers->ecccode;
1503 uint32_t *eccpos = chip->ecc.layout->eccpos;
1504 uint8_t *ecc_calc = chip->buffers->ecccalc;
1505 unsigned int max_bitflips = 0;
1507 /* Read the OOB area first */
1508 chip->cmdfunc(mtd, NAND_CMD_READOOB, 0, page);
1509 chip->read_buf(mtd, chip->oob_poi, mtd->oobsize);
1510 chip->cmdfunc(mtd, NAND_CMD_READ0, 0, page);
1512 for (i = 0; i < chip->ecc.total; i++)
1513 ecc_code[i] = chip->oob_poi[eccpos[i]];
1515 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
1518 chip->ecc.hwctl(mtd, NAND_ECC_READ);
1519 chip->read_buf(mtd, p, eccsize);
1520 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
1522 stat = chip->ecc.correct(mtd, p, &ecc_code[i], NULL);
1524 mtd->ecc_stats.failed++;
1526 mtd->ecc_stats.corrected += stat;
1527 max_bitflips = max_t(unsigned int, max_bitflips, stat);
1530 return max_bitflips;
1534 * nand_read_page_syndrome - [REPLACEABLE] hardware ECC syndrome based page read
1535 * @mtd: mtd info structure
1536 * @chip: nand chip info structure
1537 * @buf: buffer to store read data
1538 * @oob_required: caller requires OOB data read to chip->oob_poi
1539 * @page: page number to read
1541 * The hw generator calculates the error syndrome automatically. Therefore we
1542 * need a special oob layout and handling.
1544 static int nand_read_page_syndrome(struct mtd_info *mtd, struct nand_chip *chip,
1545 uint8_t *buf, int oob_required, int page)
1547 int i, eccsize = chip->ecc.size;
1548 int eccbytes = chip->ecc.bytes;
1549 int eccsteps = chip->ecc.steps;
1551 uint8_t *oob = chip->oob_poi;
1552 unsigned int max_bitflips = 0;
1554 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
1557 chip->ecc.hwctl(mtd, NAND_ECC_READ);
1558 chip->read_buf(mtd, p, eccsize);
1560 if (chip->ecc.prepad) {
1561 chip->read_buf(mtd, oob, chip->ecc.prepad);
1562 oob += chip->ecc.prepad;
1565 chip->ecc.hwctl(mtd, NAND_ECC_READSYN);
1566 chip->read_buf(mtd, oob, eccbytes);
1567 stat = chip->ecc.correct(mtd, p, oob, NULL);
1570 mtd->ecc_stats.failed++;
1572 mtd->ecc_stats.corrected += stat;
1573 max_bitflips = max_t(unsigned int, max_bitflips, stat);
1578 if (chip->ecc.postpad) {
1579 chip->read_buf(mtd, oob, chip->ecc.postpad);
1580 oob += chip->ecc.postpad;
1584 /* Calculate remaining oob bytes */
1585 i = mtd->oobsize - (oob - chip->oob_poi);
1587 chip->read_buf(mtd, oob, i);
1589 return max_bitflips;
1593 * nand_transfer_oob - [INTERN] Transfer oob to client buffer
1594 * @chip: nand chip structure
1595 * @oob: oob destination address
1596 * @ops: oob ops structure
1597 * @len: size of oob to transfer
1599 static uint8_t *nand_transfer_oob(struct nand_chip *chip, uint8_t *oob,
1600 struct mtd_oob_ops *ops, size_t len)
1602 switch (ops->mode) {
1604 case MTD_OPS_PLACE_OOB:
1606 memcpy(oob, chip->oob_poi + ops->ooboffs, len);
1609 case MTD_OPS_AUTO_OOB: {
1610 struct nand_oobfree *free = chip->ecc.layout->oobfree;
1611 uint32_t boffs = 0, roffs = ops->ooboffs;
1614 for (; free->length && len; free++, len -= bytes) {
1615 /* Read request not from offset 0? */
1616 if (unlikely(roffs)) {
1617 if (roffs >= free->length) {
1618 roffs -= free->length;
1621 boffs = free->offset + roffs;
1622 bytes = min_t(size_t, len,
1623 (free->length - roffs));
1626 bytes = min_t(size_t, len, free->length);
1627 boffs = free->offset;
1629 memcpy(oob, chip->oob_poi + boffs, bytes);
1641 * nand_setup_read_retry - [INTERN] Set the READ RETRY mode
1642 * @mtd: MTD device structure
1643 * @retry_mode: the retry mode to use
1645 * Some vendors supply a special command to shift the Vt threshold, to be used
1646 * when there are too many bitflips in a page (i.e., ECC error). After setting
1647 * a new threshold, the host should retry reading the page.
1649 static int nand_setup_read_retry(struct mtd_info *mtd, int retry_mode)
1651 struct nand_chip *chip = mtd->priv;
1653 pr_debug("setting READ RETRY mode %d\n", retry_mode);
1655 if (retry_mode >= chip->read_retries)
1658 if (!chip->setup_read_retry)
1661 return chip->setup_read_retry(mtd, retry_mode);
1665 * nand_do_read_ops - [INTERN] Read data with ECC
1666 * @mtd: MTD device structure
1667 * @from: offset to read from
1668 * @ops: oob ops structure
1670 * Internal function. Called with chip held.
1672 static int nand_do_read_ops(struct mtd_info *mtd, loff_t from,
1673 struct mtd_oob_ops *ops)
1675 int chipnr, page, realpage, col, bytes, aligned, oob_required;
1676 struct nand_chip *chip = mtd->priv;
1678 uint32_t readlen = ops->len;
1679 uint32_t oobreadlen = ops->ooblen;
1680 uint32_t max_oobsize = ops->mode == MTD_OPS_AUTO_OOB ?
1681 mtd->oobavail : mtd->oobsize;
1683 uint8_t *bufpoi, *oob, *buf;
1685 unsigned int max_bitflips = 0;
1687 bool ecc_fail = false;
1689 chipnr = (int)(from >> chip->chip_shift);
1690 chip->select_chip(mtd, chipnr);
1692 realpage = (int)(from >> chip->page_shift);
1693 page = realpage & chip->pagemask;
1695 col = (int)(from & (mtd->writesize - 1));
1699 oob_required = oob ? 1 : 0;
1702 unsigned int ecc_failures = mtd->ecc_stats.failed;
1704 bytes = min(mtd->writesize - col, readlen);
1705 aligned = (bytes == mtd->writesize);
1709 else if (chip->options & NAND_USE_BOUNCE_BUFFER)
1710 use_bufpoi = !virt_addr_valid(buf);
1714 /* Is the current page in the buffer? */
1715 if (realpage != chip->pagebuf || oob) {
1716 bufpoi = use_bufpoi ? chip->buffers->databuf : buf;
1718 if (use_bufpoi && aligned)
1719 pr_debug("%s: using read bounce buffer for buf@%p\n",
1723 chip->cmdfunc(mtd, NAND_CMD_READ0, 0x00, page);
1726 * Now read the page into the buffer. Absent an error,
1727 * the read methods return max bitflips per ecc step.
1729 if (unlikely(ops->mode == MTD_OPS_RAW))
1730 ret = chip->ecc.read_page_raw(mtd, chip, bufpoi,
1733 else if (!aligned && NAND_HAS_SUBPAGE_READ(chip) &&
1735 ret = chip->ecc.read_subpage(mtd, chip,
1739 ret = chip->ecc.read_page(mtd, chip, bufpoi,
1740 oob_required, page);
1743 /* Invalidate page cache */
1748 max_bitflips = max_t(unsigned int, max_bitflips, ret);
1750 /* Transfer not aligned data */
1752 if (!NAND_HAS_SUBPAGE_READ(chip) && !oob &&
1753 !(mtd->ecc_stats.failed - ecc_failures) &&
1754 (ops->mode != MTD_OPS_RAW)) {
1755 chip->pagebuf = realpage;
1756 chip->pagebuf_bitflips = ret;
1758 /* Invalidate page cache */
1761 memcpy(buf, chip->buffers->databuf + col, bytes);
1764 if (unlikely(oob)) {
1765 int toread = min(oobreadlen, max_oobsize);
1768 oob = nand_transfer_oob(chip,
1770 oobreadlen -= toread;
1774 if (chip->options & NAND_NEED_READRDY) {
1775 /* Apply delay or wait for ready/busy pin */
1776 if (!chip->dev_ready)
1777 udelay(chip->chip_delay);
1779 nand_wait_ready(mtd);
1782 if (mtd->ecc_stats.failed - ecc_failures) {
1783 if (retry_mode + 1 < chip->read_retries) {
1785 ret = nand_setup_read_retry(mtd,
1790 /* Reset failures; retry */
1791 mtd->ecc_stats.failed = ecc_failures;
1794 /* No more retry modes; real failure */
1801 memcpy(buf, chip->buffers->databuf + col, bytes);
1803 max_bitflips = max_t(unsigned int, max_bitflips,
1804 chip->pagebuf_bitflips);
1809 /* Reset to retry mode 0 */
1811 ret = nand_setup_read_retry(mtd, 0);
1820 /* For subsequent reads align to page boundary */
1822 /* Increment page address */
1825 page = realpage & chip->pagemask;
1826 /* Check, if we cross a chip boundary */
1829 chip->select_chip(mtd, -1);
1830 chip->select_chip(mtd, chipnr);
1833 chip->select_chip(mtd, -1);
1835 ops->retlen = ops->len - (size_t) readlen;
1837 ops->oobretlen = ops->ooblen - oobreadlen;
1845 return max_bitflips;
1849 * nand_read - [MTD Interface] MTD compatibility function for nand_do_read_ecc
1850 * @mtd: MTD device structure
1851 * @from: offset to read from
1852 * @len: number of bytes to read
1853 * @retlen: pointer to variable to store the number of read bytes
1854 * @buf: the databuffer to put data
1856 * Get hold of the chip and call nand_do_read.
1858 static int nand_read(struct mtd_info *mtd, loff_t from, size_t len,
1859 size_t *retlen, uint8_t *buf)
1861 struct mtd_oob_ops ops;
1864 nand_get_device(mtd, FL_READING);
1865 memset(&ops, 0, sizeof(ops));
1868 ops.mode = MTD_OPS_PLACE_OOB;
1869 ret = nand_do_read_ops(mtd, from, &ops);
1870 *retlen = ops.retlen;
1871 nand_release_device(mtd);
1876 * nand_read_oob_std - [REPLACEABLE] the most common OOB data read function
1877 * @mtd: mtd info structure
1878 * @chip: nand chip info structure
1879 * @page: page number to read
1881 static int nand_read_oob_std(struct mtd_info *mtd, struct nand_chip *chip,
1884 chip->cmdfunc(mtd, NAND_CMD_READOOB, 0, page);
1885 chip->read_buf(mtd, chip->oob_poi, mtd->oobsize);
1890 * nand_read_oob_syndrome - [REPLACEABLE] OOB data read function for HW ECC
1892 * @mtd: mtd info structure
1893 * @chip: nand chip info structure
1894 * @page: page number to read
1896 static int nand_read_oob_syndrome(struct mtd_info *mtd, struct nand_chip *chip,
1899 int length = mtd->oobsize;
1900 int chunk = chip->ecc.bytes + chip->ecc.prepad + chip->ecc.postpad;
1901 int eccsize = chip->ecc.size;
1902 uint8_t *bufpoi = chip->oob_poi;
1903 int i, toread, sndrnd = 0, pos;
1905 chip->cmdfunc(mtd, NAND_CMD_READ0, chip->ecc.size, page);
1906 for (i = 0; i < chip->ecc.steps; i++) {
1908 pos = eccsize + i * (eccsize + chunk);
1909 if (mtd->writesize > 512)
1910 chip->cmdfunc(mtd, NAND_CMD_RNDOUT, pos, -1);
1912 chip->cmdfunc(mtd, NAND_CMD_READ0, pos, page);
1915 toread = min_t(int, length, chunk);
1916 chip->read_buf(mtd, bufpoi, toread);
1921 chip->read_buf(mtd, bufpoi, length);
1927 * nand_write_oob_std - [REPLACEABLE] the most common OOB data write function
1928 * @mtd: mtd info structure
1929 * @chip: nand chip info structure
1930 * @page: page number to write
1932 static int nand_write_oob_std(struct mtd_info *mtd, struct nand_chip *chip,
1936 const uint8_t *buf = chip->oob_poi;
1937 int length = mtd->oobsize;
1939 chip->cmdfunc(mtd, NAND_CMD_SEQIN, mtd->writesize, page);
1940 chip->write_buf(mtd, buf, length);
1941 /* Send command to program the OOB data */
1942 chip->cmdfunc(mtd, NAND_CMD_PAGEPROG, -1, -1);
1944 status = chip->waitfunc(mtd, chip);
1946 return status & NAND_STATUS_FAIL ? -EIO : 0;
1950 * nand_write_oob_syndrome - [REPLACEABLE] OOB data write function for HW ECC
1951 * with syndrome - only for large page flash
1952 * @mtd: mtd info structure
1953 * @chip: nand chip info structure
1954 * @page: page number to write
1956 static int nand_write_oob_syndrome(struct mtd_info *mtd,
1957 struct nand_chip *chip, int page)
1959 int chunk = chip->ecc.bytes + chip->ecc.prepad + chip->ecc.postpad;
1960 int eccsize = chip->ecc.size, length = mtd->oobsize;
1961 int i, len, pos, status = 0, sndcmd = 0, steps = chip->ecc.steps;
1962 const uint8_t *bufpoi = chip->oob_poi;
1965 * data-ecc-data-ecc ... ecc-oob
1967 * data-pad-ecc-pad-data-pad .... ecc-pad-oob
1969 if (!chip->ecc.prepad && !chip->ecc.postpad) {
1970 pos = steps * (eccsize + chunk);
1975 chip->cmdfunc(mtd, NAND_CMD_SEQIN, pos, page);
1976 for (i = 0; i < steps; i++) {
1978 if (mtd->writesize <= 512) {
1979 uint32_t fill = 0xFFFFFFFF;
1983 int num = min_t(int, len, 4);
1984 chip->write_buf(mtd, (uint8_t *)&fill,
1989 pos = eccsize + i * (eccsize + chunk);
1990 chip->cmdfunc(mtd, NAND_CMD_RNDIN, pos, -1);
1994 len = min_t(int, length, chunk);
1995 chip->write_buf(mtd, bufpoi, len);
2000 chip->write_buf(mtd, bufpoi, length);
2002 chip->cmdfunc(mtd, NAND_CMD_PAGEPROG, -1, -1);
2003 status = chip->waitfunc(mtd, chip);
2005 return status & NAND_STATUS_FAIL ? -EIO : 0;
2009 * nand_do_read_oob - [INTERN] NAND read out-of-band
2010 * @mtd: MTD device structure
2011 * @from: offset to read from
2012 * @ops: oob operations description structure
2014 * NAND read out-of-band data from the spare area.
2016 static int nand_do_read_oob(struct mtd_info *mtd, loff_t from,
2017 struct mtd_oob_ops *ops)
2019 int page, realpage, chipnr;
2020 struct nand_chip *chip = mtd->priv;
2021 struct mtd_ecc_stats stats;
2022 int readlen = ops->ooblen;
2024 uint8_t *buf = ops->oobbuf;
2027 pr_debug("%s: from = 0x%08Lx, len = %i\n",
2028 __func__, (unsigned long long)from, readlen);
2030 stats = mtd->ecc_stats;
2032 if (ops->mode == MTD_OPS_AUTO_OOB)
2033 len = chip->ecc.layout->oobavail;
2037 if (unlikely(ops->ooboffs >= len)) {
2038 pr_debug("%s: attempt to start read outside oob\n",
2043 /* Do not allow reads past end of device */
2044 if (unlikely(from >= mtd->size ||
2045 ops->ooboffs + readlen > ((mtd->size >> chip->page_shift) -
2046 (from >> chip->page_shift)) * len)) {
2047 pr_debug("%s: attempt to read beyond end of device\n",
2052 chipnr = (int)(from >> chip->chip_shift);
2053 chip->select_chip(mtd, chipnr);
2055 /* Shift to get page */
2056 realpage = (int)(from >> chip->page_shift);
2057 page = realpage & chip->pagemask;
2060 if (ops->mode == MTD_OPS_RAW)
2061 ret = chip->ecc.read_oob_raw(mtd, chip, page);
2063 ret = chip->ecc.read_oob(mtd, chip, page);
2068 len = min(len, readlen);
2069 buf = nand_transfer_oob(chip, buf, ops, len);
2071 if (chip->options & NAND_NEED_READRDY) {
2072 /* Apply delay or wait for ready/busy pin */
2073 if (!chip->dev_ready)
2074 udelay(chip->chip_delay);
2076 nand_wait_ready(mtd);
2083 /* Increment page address */
2086 page = realpage & chip->pagemask;
2087 /* Check, if we cross a chip boundary */
2090 chip->select_chip(mtd, -1);
2091 chip->select_chip(mtd, chipnr);
2094 chip->select_chip(mtd, -1);
2096 ops->oobretlen = ops->ooblen - readlen;
2101 if (mtd->ecc_stats.failed - stats.failed)
2104 return mtd->ecc_stats.corrected - stats.corrected ? -EUCLEAN : 0;
2108 * nand_read_oob - [MTD Interface] NAND read data and/or out-of-band
2109 * @mtd: MTD device structure
2110 * @from: offset to read from
2111 * @ops: oob operation description structure
2113 * NAND read data and/or out-of-band data.
2115 static int nand_read_oob(struct mtd_info *mtd, loff_t from,
2116 struct mtd_oob_ops *ops)
2118 int ret = -ENOTSUPP;
2122 /* Do not allow reads past end of device */
2123 if (ops->datbuf && (from + ops->len) > mtd->size) {
2124 pr_debug("%s: attempt to read beyond end of device\n",
2129 nand_get_device(mtd, FL_READING);
2131 switch (ops->mode) {
2132 case MTD_OPS_PLACE_OOB:
2133 case MTD_OPS_AUTO_OOB:
2142 ret = nand_do_read_oob(mtd, from, ops);
2144 ret = nand_do_read_ops(mtd, from, ops);
2147 nand_release_device(mtd);
2153 * nand_write_page_raw - [INTERN] raw page write function
2154 * @mtd: mtd info structure
2155 * @chip: nand chip info structure
2157 * @oob_required: must write chip->oob_poi to OOB
2159 * Not for syndrome calculating ECC controllers, which use a special oob layout.
2161 static int nand_write_page_raw(struct mtd_info *mtd, struct nand_chip *chip,
2162 const uint8_t *buf, int oob_required)
2164 chip->write_buf(mtd, buf, mtd->writesize);
2166 chip->write_buf(mtd, chip->oob_poi, mtd->oobsize);
2172 * nand_write_page_raw_syndrome - [INTERN] raw page write function
2173 * @mtd: mtd info structure
2174 * @chip: nand chip info structure
2176 * @oob_required: must write chip->oob_poi to OOB
2178 * We need a special oob layout and handling even when ECC isn't checked.
2180 static int nand_write_page_raw_syndrome(struct mtd_info *mtd,
2181 struct nand_chip *chip,
2182 const uint8_t *buf, int oob_required)
2184 int eccsize = chip->ecc.size;
2185 int eccbytes = chip->ecc.bytes;
2186 uint8_t *oob = chip->oob_poi;
2189 for (steps = chip->ecc.steps; steps > 0; steps--) {
2190 chip->write_buf(mtd, buf, eccsize);
2193 if (chip->ecc.prepad) {
2194 chip->write_buf(mtd, oob, chip->ecc.prepad);
2195 oob += chip->ecc.prepad;
2198 chip->write_buf(mtd, oob, eccbytes);
2201 if (chip->ecc.postpad) {
2202 chip->write_buf(mtd, oob, chip->ecc.postpad);
2203 oob += chip->ecc.postpad;
2207 size = mtd->oobsize - (oob - chip->oob_poi);
2209 chip->write_buf(mtd, oob, size);
2214 * nand_write_page_swecc - [REPLACEABLE] software ECC based page write function
2215 * @mtd: mtd info structure
2216 * @chip: nand chip info structure
2218 * @oob_required: must write chip->oob_poi to OOB
2220 static int nand_write_page_swecc(struct mtd_info *mtd, struct nand_chip *chip,
2221 const uint8_t *buf, int oob_required)
2223 int i, eccsize = chip->ecc.size;
2224 int eccbytes = chip->ecc.bytes;
2225 int eccsteps = chip->ecc.steps;
2226 uint8_t *ecc_calc = chip->buffers->ecccalc;
2227 const uint8_t *p = buf;
2228 uint32_t *eccpos = chip->ecc.layout->eccpos;
2230 /* Software ECC calculation */
2231 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize)
2232 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
2234 for (i = 0; i < chip->ecc.total; i++)
2235 chip->oob_poi[eccpos[i]] = ecc_calc[i];
2237 return chip->ecc.write_page_raw(mtd, chip, buf, 1);
2241 * nand_write_page_hwecc - [REPLACEABLE] hardware ECC based page write function
2242 * @mtd: mtd info structure
2243 * @chip: nand chip info structure
2245 * @oob_required: must write chip->oob_poi to OOB
2247 static int nand_write_page_hwecc(struct mtd_info *mtd, struct nand_chip *chip,
2248 const uint8_t *buf, int oob_required)
2250 int i, eccsize = chip->ecc.size;
2251 int eccbytes = chip->ecc.bytes;
2252 int eccsteps = chip->ecc.steps;
2253 uint8_t *ecc_calc = chip->buffers->ecccalc;
2254 const uint8_t *p = buf;
2255 uint32_t *eccpos = chip->ecc.layout->eccpos;
2257 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
2258 chip->ecc.hwctl(mtd, NAND_ECC_WRITE);
2259 chip->write_buf(mtd, p, eccsize);
2260 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
2263 for (i = 0; i < chip->ecc.total; i++)
2264 chip->oob_poi[eccpos[i]] = ecc_calc[i];
2266 chip->write_buf(mtd, chip->oob_poi, mtd->oobsize);
2273 * nand_write_subpage_hwecc - [REPLACEABLE] hardware ECC based subpage write
2274 * @mtd: mtd info structure
2275 * @chip: nand chip info structure
2276 * @offset: column address of subpage within the page
2277 * @data_len: data length
2279 * @oob_required: must write chip->oob_poi to OOB
2281 static int nand_write_subpage_hwecc(struct mtd_info *mtd,
2282 struct nand_chip *chip, uint32_t offset,
2283 uint32_t data_len, const uint8_t *buf,
2286 uint8_t *oob_buf = chip->oob_poi;
2287 uint8_t *ecc_calc = chip->buffers->ecccalc;
2288 int ecc_size = chip->ecc.size;
2289 int ecc_bytes = chip->ecc.bytes;
2290 int ecc_steps = chip->ecc.steps;
2291 uint32_t *eccpos = chip->ecc.layout->eccpos;
2292 uint32_t start_step = offset / ecc_size;
2293 uint32_t end_step = (offset + data_len - 1) / ecc_size;
2294 int oob_bytes = mtd->oobsize / ecc_steps;
2297 for (step = 0; step < ecc_steps; step++) {
2298 /* configure controller for WRITE access */
2299 chip->ecc.hwctl(mtd, NAND_ECC_WRITE);
2301 /* write data (untouched subpages already masked by 0xFF) */
2302 chip->write_buf(mtd, buf, ecc_size);
2304 /* mask ECC of un-touched subpages by padding 0xFF */
2305 if ((step < start_step) || (step > end_step))
2306 memset(ecc_calc, 0xff, ecc_bytes);
2308 chip->ecc.calculate(mtd, buf, ecc_calc);
2310 /* mask OOB of un-touched subpages by padding 0xFF */
2311 /* if oob_required, preserve OOB metadata of written subpage */
2312 if (!oob_required || (step < start_step) || (step > end_step))
2313 memset(oob_buf, 0xff, oob_bytes);
2316 ecc_calc += ecc_bytes;
2317 oob_buf += oob_bytes;
2320 /* copy calculated ECC for whole page to chip->buffer->oob */
2321 /* this include masked-value(0xFF) for unwritten subpages */
2322 ecc_calc = chip->buffers->ecccalc;
2323 for (i = 0; i < chip->ecc.total; i++)
2324 chip->oob_poi[eccpos[i]] = ecc_calc[i];
2326 /* write OOB buffer to NAND device */
2327 chip->write_buf(mtd, chip->oob_poi, mtd->oobsize);
2334 * nand_write_page_syndrome - [REPLACEABLE] hardware ECC syndrome based page write
2335 * @mtd: mtd info structure
2336 * @chip: nand chip info structure
2338 * @oob_required: must write chip->oob_poi to OOB
2340 * The hw generator calculates the error syndrome automatically. Therefore we
2341 * need a special oob layout and handling.
2343 static int nand_write_page_syndrome(struct mtd_info *mtd,
2344 struct nand_chip *chip,
2345 const uint8_t *buf, int oob_required)
2347 int i, eccsize = chip->ecc.size;
2348 int eccbytes = chip->ecc.bytes;
2349 int eccsteps = chip->ecc.steps;
2350 const uint8_t *p = buf;
2351 uint8_t *oob = chip->oob_poi;
2353 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
2355 chip->ecc.hwctl(mtd, NAND_ECC_WRITE);
2356 chip->write_buf(mtd, p, eccsize);
2358 if (chip->ecc.prepad) {
2359 chip->write_buf(mtd, oob, chip->ecc.prepad);
2360 oob += chip->ecc.prepad;
2363 chip->ecc.calculate(mtd, p, oob);
2364 chip->write_buf(mtd, oob, eccbytes);
2367 if (chip->ecc.postpad) {
2368 chip->write_buf(mtd, oob, chip->ecc.postpad);
2369 oob += chip->ecc.postpad;
2373 /* Calculate remaining oob bytes */
2374 i = mtd->oobsize - (oob - chip->oob_poi);
2376 chip->write_buf(mtd, oob, i);
2382 * nand_write_page - [REPLACEABLE] write one page
2383 * @mtd: MTD device structure
2384 * @chip: NAND chip descriptor
2385 * @offset: address offset within the page
2386 * @data_len: length of actual data to be written
2387 * @buf: the data to write
2388 * @oob_required: must write chip->oob_poi to OOB
2389 * @page: page number to write
2390 * @cached: cached programming
2391 * @raw: use _raw version of write_page
2393 static int nand_write_page(struct mtd_info *mtd, struct nand_chip *chip,
2394 uint32_t offset, int data_len, const uint8_t *buf,
2395 int oob_required, int page, int cached, int raw)
2397 int status, subpage;
2399 if (!(chip->options & NAND_NO_SUBPAGE_WRITE) &&
2400 chip->ecc.write_subpage)
2401 subpage = offset || (data_len < mtd->writesize);
2405 chip->cmdfunc(mtd, NAND_CMD_SEQIN, 0x00, page);
2408 status = chip->ecc.write_page_raw(mtd, chip, buf,
2411 status = chip->ecc.write_subpage(mtd, chip, offset, data_len,
2414 status = chip->ecc.write_page(mtd, chip, buf, oob_required);
2420 * Cached progamming disabled for now. Not sure if it's worth the
2421 * trouble. The speed gain is not very impressive. (2.3->2.6Mib/s).
2425 if (!cached || !NAND_HAS_CACHEPROG(chip)) {
2427 chip->cmdfunc(mtd, NAND_CMD_PAGEPROG, -1, -1);
2428 status = chip->waitfunc(mtd, chip);
2430 * See if operation failed and additional status checks are
2433 if ((status & NAND_STATUS_FAIL) && (chip->errstat))
2434 status = chip->errstat(mtd, chip, FL_WRITING, status,
2437 if (status & NAND_STATUS_FAIL)
2440 chip->cmdfunc(mtd, NAND_CMD_CACHEDPROG, -1, -1);
2441 status = chip->waitfunc(mtd, chip);
2448 * nand_fill_oob - [INTERN] Transfer client buffer to oob
2449 * @mtd: MTD device structure
2450 * @oob: oob data buffer
2451 * @len: oob data write length
2452 * @ops: oob ops structure
2454 static uint8_t *nand_fill_oob(struct mtd_info *mtd, uint8_t *oob, size_t len,
2455 struct mtd_oob_ops *ops)
2457 struct nand_chip *chip = mtd->priv;
2460 * Initialise to all 0xFF, to avoid the possibility of left over OOB
2461 * data from a previous OOB read.
2463 memset(chip->oob_poi, 0xff, mtd->oobsize);
2465 switch (ops->mode) {
2467 case MTD_OPS_PLACE_OOB:
2469 memcpy(chip->oob_poi + ops->ooboffs, oob, len);
2472 case MTD_OPS_AUTO_OOB: {
2473 struct nand_oobfree *free = chip->ecc.layout->oobfree;
2474 uint32_t boffs = 0, woffs = ops->ooboffs;
2477 for (; free->length && len; free++, len -= bytes) {
2478 /* Write request not from offset 0? */
2479 if (unlikely(woffs)) {
2480 if (woffs >= free->length) {
2481 woffs -= free->length;
2484 boffs = free->offset + woffs;
2485 bytes = min_t(size_t, len,
2486 (free->length - woffs));
2489 bytes = min_t(size_t, len, free->length);
2490 boffs = free->offset;
2492 memcpy(chip->oob_poi + boffs, oob, bytes);
2503 #define NOTALIGNED(x) ((x & (chip->subpagesize - 1)) != 0)
2506 * nand_do_write_ops - [INTERN] NAND write with ECC
2507 * @mtd: MTD device structure
2508 * @to: offset to write to
2509 * @ops: oob operations description structure
2511 * NAND write with ECC.
2513 static int nand_do_write_ops(struct mtd_info *mtd, loff_t to,
2514 struct mtd_oob_ops *ops)
2516 int chipnr, realpage, page, blockmask, column;
2517 struct nand_chip *chip = mtd->priv;
2518 uint32_t writelen = ops->len;
2520 uint32_t oobwritelen = ops->ooblen;
2521 uint32_t oobmaxlen = ops->mode == MTD_OPS_AUTO_OOB ?
2522 mtd->oobavail : mtd->oobsize;
2524 uint8_t *oob = ops->oobbuf;
2525 uint8_t *buf = ops->datbuf;
2527 int oob_required = oob ? 1 : 0;
2533 /* Reject writes, which are not page aligned */
2534 if (NOTALIGNED(to) || NOTALIGNED(ops->len)) {
2535 pr_notice("%s: attempt to write non page aligned data\n",
2540 column = to & (mtd->writesize - 1);
2542 chipnr = (int)(to >> chip->chip_shift);
2543 chip->select_chip(mtd, chipnr);
2545 /* Check, if it is write protected */
2546 if (nand_check_wp(mtd)) {
2551 realpage = (int)(to >> chip->page_shift);
2552 page = realpage & chip->pagemask;
2553 blockmask = (1 << (chip->phys_erase_shift - chip->page_shift)) - 1;
2555 /* Invalidate the page cache, when we write to the cached page */
2556 if (to <= ((loff_t)chip->pagebuf << chip->page_shift) &&
2557 ((loff_t)chip->pagebuf << chip->page_shift) < (to + ops->len))
2560 /* Don't allow multipage oob writes with offset */
2561 if (oob && ops->ooboffs && (ops->ooboffs + ops->ooblen > oobmaxlen)) {
2567 int bytes = mtd->writesize;
2568 int cached = writelen > bytes && page != blockmask;
2569 uint8_t *wbuf = buf;
2571 int part_pagewr = (column || writelen < (mtd->writesize - 1));
2575 else if (chip->options & NAND_USE_BOUNCE_BUFFER)
2576 use_bufpoi = !virt_addr_valid(buf);
2580 /* Partial page write?, or need to use bounce buffer */
2582 pr_debug("%s: using write bounce buffer for buf@%p\n",
2586 bytes = min_t(int, bytes - column, writelen);
2588 memset(chip->buffers->databuf, 0xff, mtd->writesize);
2589 memcpy(&chip->buffers->databuf[column], buf, bytes);
2590 wbuf = chip->buffers->databuf;
2593 if (unlikely(oob)) {
2594 size_t len = min(oobwritelen, oobmaxlen);
2595 oob = nand_fill_oob(mtd, oob, len, ops);
2598 /* We still need to erase leftover OOB data */
2599 memset(chip->oob_poi, 0xff, mtd->oobsize);
2601 ret = chip->write_page(mtd, chip, column, bytes, wbuf,
2602 oob_required, page, cached,
2603 (ops->mode == MTD_OPS_RAW));
2615 page = realpage & chip->pagemask;
2616 /* Check, if we cross a chip boundary */
2619 chip->select_chip(mtd, -1);
2620 chip->select_chip(mtd, chipnr);
2624 ops->retlen = ops->len - writelen;
2626 ops->oobretlen = ops->ooblen;
2629 chip->select_chip(mtd, -1);
2634 * panic_nand_write - [MTD Interface] NAND write with ECC
2635 * @mtd: MTD device structure
2636 * @to: offset to write to
2637 * @len: number of bytes to write
2638 * @retlen: pointer to variable to store the number of written bytes
2639 * @buf: the data to write
2641 * NAND write with ECC. Used when performing writes in interrupt context, this
2642 * may for example be called by mtdoops when writing an oops while in panic.
2644 static int panic_nand_write(struct mtd_info *mtd, loff_t to, size_t len,
2645 size_t *retlen, const uint8_t *buf)
2647 struct nand_chip *chip = mtd->priv;
2648 struct mtd_oob_ops ops;
2651 /* Wait for the device to get ready */
2652 panic_nand_wait(mtd, chip, 400);
2654 /* Grab the device */
2655 panic_nand_get_device(chip, mtd, FL_WRITING);
2657 memset(&ops, 0, sizeof(ops));
2659 ops.datbuf = (uint8_t *)buf;
2660 ops.mode = MTD_OPS_PLACE_OOB;
2662 ret = nand_do_write_ops(mtd, to, &ops);
2664 *retlen = ops.retlen;
2669 * nand_write - [MTD Interface] NAND write with ECC
2670 * @mtd: MTD device structure
2671 * @to: offset to write to
2672 * @len: number of bytes to write
2673 * @retlen: pointer to variable to store the number of written bytes
2674 * @buf: the data to write
2676 * NAND write with ECC.
2678 static int nand_write(struct mtd_info *mtd, loff_t to, size_t len,
2679 size_t *retlen, const uint8_t *buf)
2681 struct mtd_oob_ops ops;
2684 nand_get_device(mtd, FL_WRITING);
2685 memset(&ops, 0, sizeof(ops));
2687 ops.datbuf = (uint8_t *)buf;
2688 ops.mode = MTD_OPS_PLACE_OOB;
2689 ret = nand_do_write_ops(mtd, to, &ops);
2690 *retlen = ops.retlen;
2691 nand_release_device(mtd);
2696 * nand_do_write_oob - [MTD Interface] NAND write out-of-band
2697 * @mtd: MTD device structure
2698 * @to: offset to write to
2699 * @ops: oob operation description structure
2701 * NAND write out-of-band.
2703 static int nand_do_write_oob(struct mtd_info *mtd, loff_t to,
2704 struct mtd_oob_ops *ops)
2706 int chipnr, page, status, len;
2707 struct nand_chip *chip = mtd->priv;
2709 pr_debug("%s: to = 0x%08x, len = %i\n",
2710 __func__, (unsigned int)to, (int)ops->ooblen);
2712 if (ops->mode == MTD_OPS_AUTO_OOB)
2713 len = chip->ecc.layout->oobavail;
2717 /* Do not allow write past end of page */
2718 if ((ops->ooboffs + ops->ooblen) > len) {
2719 pr_debug("%s: attempt to write past end of page\n",
2724 if (unlikely(ops->ooboffs >= len)) {
2725 pr_debug("%s: attempt to start write outside oob\n",
2730 /* Do not allow write past end of device */
2731 if (unlikely(to >= mtd->size ||
2732 ops->ooboffs + ops->ooblen >
2733 ((mtd->size >> chip->page_shift) -
2734 (to >> chip->page_shift)) * len)) {
2735 pr_debug("%s: attempt to write beyond end of device\n",
2740 chipnr = (int)(to >> chip->chip_shift);
2741 chip->select_chip(mtd, chipnr);
2743 /* Shift to get page */
2744 page = (int)(to >> chip->page_shift);
2747 * Reset the chip. Some chips (like the Toshiba TC5832DC found in one
2748 * of my DiskOnChip 2000 test units) will clear the whole data page too
2749 * if we don't do this. I have no clue why, but I seem to have 'fixed'
2750 * it in the doc2000 driver in August 1999. dwmw2.
2752 chip->cmdfunc(mtd, NAND_CMD_RESET, -1, -1);
2754 /* Check, if it is write protected */
2755 if (nand_check_wp(mtd)) {
2756 chip->select_chip(mtd, -1);
2760 /* Invalidate the page cache, if we write to the cached page */
2761 if (page == chip->pagebuf)
2764 nand_fill_oob(mtd, ops->oobbuf, ops->ooblen, ops);
2766 if (ops->mode == MTD_OPS_RAW)
2767 status = chip->ecc.write_oob_raw(mtd, chip, page & chip->pagemask);
2769 status = chip->ecc.write_oob(mtd, chip, page & chip->pagemask);
2771 chip->select_chip(mtd, -1);
2776 ops->oobretlen = ops->ooblen;
2782 * nand_write_oob - [MTD Interface] NAND write data and/or out-of-band
2783 * @mtd: MTD device structure
2784 * @to: offset to write to
2785 * @ops: oob operation description structure
2787 static int nand_write_oob(struct mtd_info *mtd, loff_t to,
2788 struct mtd_oob_ops *ops)
2790 int ret = -ENOTSUPP;
2794 /* Do not allow writes past end of device */
2795 if (ops->datbuf && (to + ops->len) > mtd->size) {
2796 pr_debug("%s: attempt to write beyond end of device\n",
2801 nand_get_device(mtd, FL_WRITING);
2803 switch (ops->mode) {
2804 case MTD_OPS_PLACE_OOB:
2805 case MTD_OPS_AUTO_OOB:
2814 ret = nand_do_write_oob(mtd, to, ops);
2816 ret = nand_do_write_ops(mtd, to, ops);
2819 nand_release_device(mtd);
2824 * single_erase - [GENERIC] NAND standard block erase command function
2825 * @mtd: MTD device structure
2826 * @page: the page address of the block which will be erased
2828 * Standard erase command for NAND chips. Returns NAND status.
2830 static int single_erase(struct mtd_info *mtd, int page)
2832 struct nand_chip *chip = mtd->priv;
2833 /* Send commands to erase a block */
2834 chip->cmdfunc(mtd, NAND_CMD_ERASE1, -1, page);
2835 chip->cmdfunc(mtd, NAND_CMD_ERASE2, -1, -1);
2837 return chip->waitfunc(mtd, chip);
2841 * nand_erase - [MTD Interface] erase block(s)
2842 * @mtd: MTD device structure
2843 * @instr: erase instruction
2845 * Erase one ore more blocks.
2847 static int nand_erase(struct mtd_info *mtd, struct erase_info *instr)
2849 return nand_erase_nand(mtd, instr, 0);
2853 * nand_erase_nand - [INTERN] erase block(s)
2854 * @mtd: MTD device structure
2855 * @instr: erase instruction
2856 * @allowbbt: allow erasing the bbt area
2858 * Erase one ore more blocks.
2860 int nand_erase_nand(struct mtd_info *mtd, struct erase_info *instr,
2863 int page, status, pages_per_block, ret, chipnr;
2864 struct nand_chip *chip = mtd->priv;
2867 pr_debug("%s: start = 0x%012llx, len = %llu\n",
2868 __func__, (unsigned long long)instr->addr,
2869 (unsigned long long)instr->len);
2871 if (check_offs_len(mtd, instr->addr, instr->len))
2874 /* Grab the lock and see if the device is available */
2875 nand_get_device(mtd, FL_ERASING);
2877 /* Shift to get first page */
2878 page = (int)(instr->addr >> chip->page_shift);
2879 chipnr = (int)(instr->addr >> chip->chip_shift);
2881 /* Calculate pages in each block */
2882 pages_per_block = 1 << (chip->phys_erase_shift - chip->page_shift);
2884 /* Select the NAND device */
2885 chip->select_chip(mtd, chipnr);
2887 /* Check, if it is write protected */
2888 if (nand_check_wp(mtd)) {
2889 pr_debug("%s: device is write protected!\n",
2891 instr->state = MTD_ERASE_FAILED;
2895 /* Loop through the pages */
2898 instr->state = MTD_ERASING;
2901 /* Check if we have a bad block, we do not erase bad blocks! */
2902 if (nand_block_checkbad(mtd, ((loff_t) page) <<
2903 chip->page_shift, 0, allowbbt)) {
2904 pr_warn("%s: attempt to erase a bad block at page 0x%08x\n",
2906 instr->state = MTD_ERASE_FAILED;
2911 * Invalidate the page cache, if we erase the block which
2912 * contains the current cached page.
2914 if (page <= chip->pagebuf && chip->pagebuf <
2915 (page + pages_per_block))
2918 status = chip->erase(mtd, page & chip->pagemask);
2921 * See if operation failed and additional status checks are
2924 if ((status & NAND_STATUS_FAIL) && (chip->errstat))
2925 status = chip->errstat(mtd, chip, FL_ERASING,
2928 /* See if block erase succeeded */
2929 if (status & NAND_STATUS_FAIL) {
2930 pr_debug("%s: failed erase, page 0x%08x\n",
2932 instr->state = MTD_ERASE_FAILED;
2934 ((loff_t)page << chip->page_shift);
2938 /* Increment page address and decrement length */
2939 len -= (1ULL << chip->phys_erase_shift);
2940 page += pages_per_block;
2942 /* Check, if we cross a chip boundary */
2943 if (len && !(page & chip->pagemask)) {
2945 chip->select_chip(mtd, -1);
2946 chip->select_chip(mtd, chipnr);
2949 instr->state = MTD_ERASE_DONE;
2953 ret = instr->state == MTD_ERASE_DONE ? 0 : -EIO;
2955 /* Deselect and wake up anyone waiting on the device */
2956 chip->select_chip(mtd, -1);
2957 nand_release_device(mtd);
2959 /* Do call back function */
2961 mtd_erase_callback(instr);
2963 /* Return more or less happy */
2968 * nand_sync - [MTD Interface] sync
2969 * @mtd: MTD device structure
2971 * Sync is actually a wait for chip ready function.
2973 static void nand_sync(struct mtd_info *mtd)
2975 pr_debug("%s: called\n", __func__);
2977 /* Grab the lock and see if the device is available */
2978 nand_get_device(mtd, FL_SYNCING);
2979 /* Release it and go back */
2980 nand_release_device(mtd);
2984 * nand_block_isbad - [MTD Interface] Check if block at offset is bad
2985 * @mtd: MTD device structure
2986 * @offs: offset relative to mtd start
2988 static int nand_block_isbad(struct mtd_info *mtd, loff_t offs)
2990 return nand_block_checkbad(mtd, offs, 1, 0);
2994 * nand_block_markbad - [MTD Interface] Mark block at the given offset as bad
2995 * @mtd: MTD device structure
2996 * @ofs: offset relative to mtd start
2998 static int nand_block_markbad(struct mtd_info *mtd, loff_t ofs)
3002 ret = nand_block_isbad(mtd, ofs);
3004 /* If it was bad already, return success and do nothing */
3010 return nand_block_markbad_lowlevel(mtd, ofs);
3014 * nand_onfi_set_features- [REPLACEABLE] set features for ONFI nand
3015 * @mtd: MTD device structure
3016 * @chip: nand chip info structure
3017 * @addr: feature address.
3018 * @subfeature_param: the subfeature parameters, a four bytes array.
3020 static int nand_onfi_set_features(struct mtd_info *mtd, struct nand_chip *chip,
3021 int addr, uint8_t *subfeature_param)
3026 if (!chip->onfi_version ||
3027 !(le16_to_cpu(chip->onfi_params.opt_cmd)
3028 & ONFI_OPT_CMD_SET_GET_FEATURES))
3031 chip->cmdfunc(mtd, NAND_CMD_SET_FEATURES, addr, -1);
3032 for (i = 0; i < ONFI_SUBFEATURE_PARAM_LEN; ++i)
3033 chip->write_byte(mtd, subfeature_param[i]);
3035 status = chip->waitfunc(mtd, chip);
3036 if (status & NAND_STATUS_FAIL)
3042 * nand_onfi_get_features- [REPLACEABLE] get features for ONFI nand
3043 * @mtd: MTD device structure
3044 * @chip: nand chip info structure
3045 * @addr: feature address.
3046 * @subfeature_param: the subfeature parameters, a four bytes array.
3048 static int nand_onfi_get_features(struct mtd_info *mtd, struct nand_chip *chip,
3049 int addr, uint8_t *subfeature_param)
3053 if (!chip->onfi_version ||
3054 !(le16_to_cpu(chip->onfi_params.opt_cmd)
3055 & ONFI_OPT_CMD_SET_GET_FEATURES))
3058 chip->cmdfunc(mtd, NAND_CMD_GET_FEATURES, addr, -1);
3059 for (i = 0; i < ONFI_SUBFEATURE_PARAM_LEN; ++i)
3060 *subfeature_param++ = chip->read_byte(mtd);
3065 * nand_suspend - [MTD Interface] Suspend the NAND flash
3066 * @mtd: MTD device structure
3068 static int nand_suspend(struct mtd_info *mtd)
3070 return nand_get_device(mtd, FL_PM_SUSPENDED);
3074 * nand_resume - [MTD Interface] Resume the NAND flash
3075 * @mtd: MTD device structure
3077 static void nand_resume(struct mtd_info *mtd)
3079 struct nand_chip *chip = mtd->priv;
3081 if (chip->state == FL_PM_SUSPENDED)
3082 nand_release_device(mtd);
3084 pr_err("%s called for a chip which is not in suspended state\n",
3089 * nand_shutdown - [MTD Interface] Finish the current NAND operation and
3090 * prevent further operations
3091 * @mtd: MTD device structure
3093 static void nand_shutdown(struct mtd_info *mtd)
3095 nand_get_device(mtd, FL_SHUTDOWN);
3098 /* Set default functions */
3099 static void nand_set_defaults(struct nand_chip *chip, int busw)
3101 /* check for proper chip_delay setup, set 20us if not */
3102 if (!chip->chip_delay)
3103 chip->chip_delay = 20;
3105 /* check, if a user supplied command function given */
3106 if (chip->cmdfunc == NULL)
3107 chip->cmdfunc = nand_command;
3109 /* check, if a user supplied wait function given */
3110 if (chip->waitfunc == NULL)
3111 chip->waitfunc = nand_wait;
3113 if (!chip->select_chip)
3114 chip->select_chip = nand_select_chip;
3116 /* set for ONFI nand */
3117 if (!chip->onfi_set_features)
3118 chip->onfi_set_features = nand_onfi_set_features;
3119 if (!chip->onfi_get_features)
3120 chip->onfi_get_features = nand_onfi_get_features;
3122 /* If called twice, pointers that depend on busw may need to be reset */
3123 if (!chip->read_byte || chip->read_byte == nand_read_byte)
3124 chip->read_byte = busw ? nand_read_byte16 : nand_read_byte;
3125 if (!chip->read_word)
3126 chip->read_word = nand_read_word;
3127 if (!chip->block_bad)
3128 chip->block_bad = nand_block_bad;
3129 if (!chip->block_markbad)
3130 chip->block_markbad = nand_default_block_markbad;
3131 if (!chip->write_buf || chip->write_buf == nand_write_buf)
3132 chip->write_buf = busw ? nand_write_buf16 : nand_write_buf;
3133 if (!chip->write_byte || chip->write_byte == nand_write_byte)
3134 chip->write_byte = busw ? nand_write_byte16 : nand_write_byte;
3135 if (!chip->read_buf || chip->read_buf == nand_read_buf)
3136 chip->read_buf = busw ? nand_read_buf16 : nand_read_buf;
3137 if (!chip->scan_bbt)
3138 chip->scan_bbt = nand_default_bbt;
3140 if (!chip->controller) {
3141 chip->controller = &chip->hwcontrol;
3142 spin_lock_init(&chip->controller->lock);
3143 init_waitqueue_head(&chip->controller->wq);
3148 /* Sanitize ONFI strings so we can safely print them */
3149 static void sanitize_string(uint8_t *s, size_t len)
3153 /* Null terminate */
3156 /* Remove non printable chars */
3157 for (i = 0; i < len - 1; i++) {
3158 if (s[i] < ' ' || s[i] > 127)
3162 /* Remove trailing spaces */
3166 static u16 onfi_crc16(u16 crc, u8 const *p, size_t len)
3171 for (i = 0; i < 8; i++)
3172 crc = (crc << 1) ^ ((crc & 0x8000) ? 0x8005 : 0);
3178 /* Parse the Extended Parameter Page. */
3179 static int nand_flash_detect_ext_param_page(struct mtd_info *mtd,
3180 struct nand_chip *chip, struct nand_onfi_params *p)
3182 struct onfi_ext_param_page *ep;
3183 struct onfi_ext_section *s;
3184 struct onfi_ext_ecc_info *ecc;
3190 len = le16_to_cpu(p->ext_param_page_length) * 16;
3191 ep = kmalloc(len, GFP_KERNEL);
3195 /* Send our own NAND_CMD_PARAM. */
3196 chip->cmdfunc(mtd, NAND_CMD_PARAM, 0, -1);
3198 /* Use the Change Read Column command to skip the ONFI param pages. */
3199 chip->cmdfunc(mtd, NAND_CMD_RNDOUT,
3200 sizeof(*p) * p->num_of_param_pages , -1);
3202 /* Read out the Extended Parameter Page. */
3203 chip->read_buf(mtd, (uint8_t *)ep, len);
3204 if ((onfi_crc16(ONFI_CRC_BASE, ((uint8_t *)ep) + 2, len - 2)
3205 != le16_to_cpu(ep->crc))) {
3206 pr_debug("fail in the CRC.\n");
3211 * Check the signature.
3212 * Do not strictly follow the ONFI spec, maybe changed in future.
3214 if (strncmp(ep->sig, "EPPS", 4)) {
3215 pr_debug("The signature is invalid.\n");
3219 /* find the ECC section. */
3220 cursor = (uint8_t *)(ep + 1);
3221 for (i = 0; i < ONFI_EXT_SECTION_MAX; i++) {
3222 s = ep->sections + i;
3223 if (s->type == ONFI_SECTION_TYPE_2)
3225 cursor += s->length * 16;
3227 if (i == ONFI_EXT_SECTION_MAX) {
3228 pr_debug("We can not find the ECC section.\n");
3232 /* get the info we want. */
3233 ecc = (struct onfi_ext_ecc_info *)cursor;
3235 if (!ecc->codeword_size) {
3236 pr_debug("Invalid codeword size\n");
3240 chip->ecc_strength_ds = ecc->ecc_bits;
3241 chip->ecc_step_ds = 1 << ecc->codeword_size;
3249 static int nand_setup_read_retry_micron(struct mtd_info *mtd, int retry_mode)
3251 struct nand_chip *chip = mtd->priv;
3252 uint8_t feature[ONFI_SUBFEATURE_PARAM_LEN] = {retry_mode};
3254 return chip->onfi_set_features(mtd, chip, ONFI_FEATURE_ADDR_READ_RETRY,
3259 * Configure chip properties from Micron vendor-specific ONFI table
3261 static void nand_onfi_detect_micron(struct nand_chip *chip,
3262 struct nand_onfi_params *p)
3264 struct nand_onfi_vendor_micron *micron = (void *)p->vendor;
3266 if (le16_to_cpu(p->vendor_revision) < 1)
3269 chip->read_retries = micron->read_retry_options;
3270 chip->setup_read_retry = nand_setup_read_retry_micron;
3274 * Check if the NAND chip is ONFI compliant, returns 1 if it is, 0 otherwise.
3276 static int nand_flash_detect_onfi(struct mtd_info *mtd, struct nand_chip *chip,
3279 struct nand_onfi_params *p = &chip->onfi_params;
3283 /* Try ONFI for unknown chip or LP */
3284 chip->cmdfunc(mtd, NAND_CMD_READID, 0x20, -1);
3285 if (chip->read_byte(mtd) != 'O' || chip->read_byte(mtd) != 'N' ||
3286 chip->read_byte(mtd) != 'F' || chip->read_byte(mtd) != 'I')
3289 chip->cmdfunc(mtd, NAND_CMD_PARAM, 0, -1);
3290 for (i = 0; i < 3; i++) {
3291 for (j = 0; j < sizeof(*p); j++)
3292 ((uint8_t *)p)[j] = chip->read_byte(mtd);
3293 if (onfi_crc16(ONFI_CRC_BASE, (uint8_t *)p, 254) ==
3294 le16_to_cpu(p->crc)) {
3300 pr_err("Could not find valid ONFI parameter page; aborting\n");
3305 val = le16_to_cpu(p->revision);
3307 chip->onfi_version = 23;
3308 else if (val & (1 << 4))
3309 chip->onfi_version = 22;
3310 else if (val & (1 << 3))
3311 chip->onfi_version = 21;
3312 else if (val & (1 << 2))
3313 chip->onfi_version = 20;
3314 else if (val & (1 << 1))
3315 chip->onfi_version = 10;
3317 if (!chip->onfi_version) {
3318 pr_info("unsupported ONFI version: %d\n", val);
3322 sanitize_string(p->manufacturer, sizeof(p->manufacturer));
3323 sanitize_string(p->model, sizeof(p->model));
3325 mtd->name = p->model;
3327 mtd->writesize = le32_to_cpu(p->byte_per_page);
3330 * pages_per_block and blocks_per_lun may not be a power-of-2 size
3331 * (don't ask me who thought of this...). MTD assumes that these
3332 * dimensions will be power-of-2, so just truncate the remaining area.
3334 mtd->erasesize = 1 << (fls(le32_to_cpu(p->pages_per_block)) - 1);
3335 mtd->erasesize *= mtd->writesize;
3337 mtd->oobsize = le16_to_cpu(p->spare_bytes_per_page);
3339 /* See erasesize comment */
3340 chip->chipsize = 1 << (fls(le32_to_cpu(p->blocks_per_lun)) - 1);
3341 chip->chipsize *= (uint64_t)mtd->erasesize * p->lun_count;
3342 chip->bits_per_cell = p->bits_per_cell;
3344 if (onfi_feature(chip) & ONFI_FEATURE_16_BIT_BUS)
3345 *busw = NAND_BUSWIDTH_16;
3349 if (p->ecc_bits != 0xff) {
3350 chip->ecc_strength_ds = p->ecc_bits;
3351 chip->ecc_step_ds = 512;
3352 } else if (chip->onfi_version >= 21 &&
3353 (onfi_feature(chip) & ONFI_FEATURE_EXT_PARAM_PAGE)) {
3356 * The nand_flash_detect_ext_param_page() uses the
3357 * Change Read Column command which maybe not supported
3358 * by the chip->cmdfunc. So try to update the chip->cmdfunc
3359 * now. We do not replace user supplied command function.
3361 if (mtd->writesize > 512 && chip->cmdfunc == nand_command)
3362 chip->cmdfunc = nand_command_lp;
3364 /* The Extended Parameter Page is supported since ONFI 2.1. */
3365 if (nand_flash_detect_ext_param_page(mtd, chip, p))
3366 pr_warn("Failed to detect ONFI extended param page\n");
3368 pr_warn("Could not retrieve ONFI ECC requirements\n");
3371 if (p->jedec_id == NAND_MFR_MICRON)
3372 nand_onfi_detect_micron(chip, p);
3378 * Check if the NAND chip is JEDEC compliant, returns 1 if it is, 0 otherwise.
3380 static int nand_flash_detect_jedec(struct mtd_info *mtd, struct nand_chip *chip,
3383 struct nand_jedec_params *p = &chip->jedec_params;
3384 struct jedec_ecc_info *ecc;
3388 /* Try JEDEC for unknown chip or LP */
3389 chip->cmdfunc(mtd, NAND_CMD_READID, 0x40, -1);
3390 if (chip->read_byte(mtd) != 'J' || chip->read_byte(mtd) != 'E' ||
3391 chip->read_byte(mtd) != 'D' || chip->read_byte(mtd) != 'E' ||
3392 chip->read_byte(mtd) != 'C')
3395 chip->cmdfunc(mtd, NAND_CMD_PARAM, 0x40, -1);
3396 for (i = 0; i < 3; i++) {
3397 for (j = 0; j < sizeof(*p); j++)
3398 ((uint8_t *)p)[j] = chip->read_byte(mtd);
3400 if (onfi_crc16(ONFI_CRC_BASE, (uint8_t *)p, 510) ==
3401 le16_to_cpu(p->crc))
3406 pr_err("Could not find valid JEDEC parameter page; aborting\n");
3411 val = le16_to_cpu(p->revision);
3413 chip->jedec_version = 10;
3414 else if (val & (1 << 1))
3415 chip->jedec_version = 1; /* vendor specific version */
3417 if (!chip->jedec_version) {
3418 pr_info("unsupported JEDEC version: %d\n", val);
3422 sanitize_string(p->manufacturer, sizeof(p->manufacturer));
3423 sanitize_string(p->model, sizeof(p->model));
3425 mtd->name = p->model;
3427 mtd->writesize = le32_to_cpu(p->byte_per_page);
3429 /* Please reference to the comment for nand_flash_detect_onfi. */
3430 mtd->erasesize = 1 << (fls(le32_to_cpu(p->pages_per_block)) - 1);
3431 mtd->erasesize *= mtd->writesize;
3433 mtd->oobsize = le16_to_cpu(p->spare_bytes_per_page);
3435 /* Please reference to the comment for nand_flash_detect_onfi. */
3436 chip->chipsize = 1 << (fls(le32_to_cpu(p->blocks_per_lun)) - 1);
3437 chip->chipsize *= (uint64_t)mtd->erasesize * p->lun_count;
3438 chip->bits_per_cell = p->bits_per_cell;
3440 if (jedec_feature(chip) & JEDEC_FEATURE_16_BIT_BUS)
3441 *busw = NAND_BUSWIDTH_16;
3446 ecc = &p->ecc_info[0];
3448 if (ecc->codeword_size >= 9) {
3449 chip->ecc_strength_ds = ecc->ecc_bits;
3450 chip->ecc_step_ds = 1 << ecc->codeword_size;
3452 pr_warn("Invalid codeword size\n");
3459 * nand_id_has_period - Check if an ID string has a given wraparound period
3460 * @id_data: the ID string
3461 * @arrlen: the length of the @id_data array
3462 * @period: the period of repitition
3464 * Check if an ID string is repeated within a given sequence of bytes at
3465 * specific repetition interval period (e.g., {0x20,0x01,0x7F,0x20} has a
3466 * period of 3). This is a helper function for nand_id_len(). Returns non-zero
3467 * if the repetition has a period of @period; otherwise, returns zero.
3469 static int nand_id_has_period(u8 *id_data, int arrlen, int period)
3472 for (i = 0; i < period; i++)
3473 for (j = i + period; j < arrlen; j += period)
3474 if (id_data[i] != id_data[j])
3480 * nand_id_len - Get the length of an ID string returned by CMD_READID
3481 * @id_data: the ID string
3482 * @arrlen: the length of the @id_data array
3484 * Returns the length of the ID string, according to known wraparound/trailing
3485 * zero patterns. If no pattern exists, returns the length of the array.
3487 static int nand_id_len(u8 *id_data, int arrlen)
3489 int last_nonzero, period;
3491 /* Find last non-zero byte */
3492 for (last_nonzero = arrlen - 1; last_nonzero >= 0; last_nonzero--)
3493 if (id_data[last_nonzero])
3497 if (last_nonzero < 0)
3500 /* Calculate wraparound period */
3501 for (period = 1; period < arrlen; period++)
3502 if (nand_id_has_period(id_data, arrlen, period))
3505 /* There's a repeated pattern */
3506 if (period < arrlen)
3509 /* There are trailing zeros */
3510 if (last_nonzero < arrlen - 1)
3511 return last_nonzero + 1;
3513 /* No pattern detected */
3517 /* Extract the bits of per cell from the 3rd byte of the extended ID */
3518 static int nand_get_bits_per_cell(u8 cellinfo)
3522 bits = cellinfo & NAND_CI_CELLTYPE_MSK;
3523 bits >>= NAND_CI_CELLTYPE_SHIFT;
3528 * Many new NAND share similar device ID codes, which represent the size of the
3529 * chip. The rest of the parameters must be decoded according to generic or
3530 * manufacturer-specific "extended ID" decoding patterns.
3532 static void nand_decode_ext_id(struct mtd_info *mtd, struct nand_chip *chip,
3533 u8 id_data[8], int *busw)
3536 /* The 3rd id byte holds MLC / multichip data */
3537 chip->bits_per_cell = nand_get_bits_per_cell(id_data[2]);
3538 /* The 4th id byte is the important one */
3541 id_len = nand_id_len(id_data, 8);
3544 * Field definitions are in the following datasheets:
3545 * Old style (4,5 byte ID): Samsung K9GAG08U0M (p.32)
3546 * New Samsung (6 byte ID): Samsung K9GAG08U0F (p.44)
3547 * Hynix MLC (6 byte ID): Hynix H27UBG8T2B (p.22)
3549 * Check for ID length, non-zero 6th byte, cell type, and Hynix/Samsung
3550 * ID to decide what to do.
3552 if (id_len == 6 && id_data[0] == NAND_MFR_SAMSUNG &&
3553 !nand_is_slc(chip) && id_data[5] != 0x00) {
3555 mtd->writesize = 2048 << (extid & 0x03);
3558 switch (((extid >> 2) & 0x04) | (extid & 0x03)) {
3578 default: /* Other cases are "reserved" (unknown) */
3579 mtd->oobsize = 1024;
3583 /* Calc blocksize */
3584 mtd->erasesize = (128 * 1024) <<
3585 (((extid >> 1) & 0x04) | (extid & 0x03));
3587 } else if (id_len == 6 && id_data[0] == NAND_MFR_HYNIX &&
3588 !nand_is_slc(chip)) {
3592 mtd->writesize = 2048 << (extid & 0x03);
3595 switch (((extid >> 2) & 0x04) | (extid & 0x03)) {
3619 /* Calc blocksize */
3620 tmp = ((extid >> 1) & 0x04) | (extid & 0x03);
3622 mtd->erasesize = (128 * 1024) << tmp;
3623 else if (tmp == 0x03)
3624 mtd->erasesize = 768 * 1024;
3626 mtd->erasesize = (64 * 1024) << tmp;
3630 mtd->writesize = 1024 << (extid & 0x03);
3633 mtd->oobsize = (8 << (extid & 0x01)) *
3634 (mtd->writesize >> 9);
3636 /* Calc blocksize. Blocksize is multiples of 64KiB */
3637 mtd->erasesize = (64 * 1024) << (extid & 0x03);
3639 /* Get buswidth information */
3640 *busw = (extid & 0x01) ? NAND_BUSWIDTH_16 : 0;
3643 * Toshiba 24nm raw SLC (i.e., not BENAND) have 32B OOB per
3644 * 512B page. For Toshiba SLC, we decode the 5th/6th byte as
3646 * - ID byte 6, bits[2:0]: 100b -> 43nm, 101b -> 32nm,
3648 * - ID byte 5, bit[7]: 1 -> BENAND, 0 -> raw SLC
3650 if (id_len >= 6 && id_data[0] == NAND_MFR_TOSHIBA &&
3651 nand_is_slc(chip) &&
3652 (id_data[5] & 0x7) == 0x6 /* 24nm */ &&
3653 !(id_data[4] & 0x80) /* !BENAND */) {
3654 mtd->oobsize = 32 * mtd->writesize >> 9;
3661 * Old devices have chip data hardcoded in the device ID table. nand_decode_id
3662 * decodes a matching ID table entry and assigns the MTD size parameters for
3665 static void nand_decode_id(struct mtd_info *mtd, struct nand_chip *chip,
3666 struct nand_flash_dev *type, u8 id_data[8],
3669 int maf_id = id_data[0];
3671 mtd->erasesize = type->erasesize;
3672 mtd->writesize = type->pagesize;
3673 mtd->oobsize = mtd->writesize / 32;
3674 *busw = type->options & NAND_BUSWIDTH_16;
3676 /* All legacy ID NAND are small-page, SLC */
3677 chip->bits_per_cell = 1;
3680 * Check for Spansion/AMD ID + repeating 5th, 6th byte since
3681 * some Spansion chips have erasesize that conflicts with size
3682 * listed in nand_ids table.
3683 * Data sheet (5 byte ID): Spansion S30ML-P ORNAND (p.39)
3685 if (maf_id == NAND_MFR_AMD && id_data[4] != 0x00 && id_data[5] == 0x00
3686 && id_data[6] == 0x00 && id_data[7] == 0x00
3687 && mtd->writesize == 512) {
3688 mtd->erasesize = 128 * 1024;
3689 mtd->erasesize <<= ((id_data[3] & 0x03) << 1);
3694 * Set the bad block marker/indicator (BBM/BBI) patterns according to some
3695 * heuristic patterns using various detected parameters (e.g., manufacturer,
3696 * page size, cell-type information).
3698 static void nand_decode_bbm_options(struct mtd_info *mtd,
3699 struct nand_chip *chip, u8 id_data[8])
3701 int maf_id = id_data[0];
3703 /* Set the bad block position */
3704 if (mtd->writesize > 512 || (chip->options & NAND_BUSWIDTH_16))
3705 chip->badblockpos = NAND_LARGE_BADBLOCK_POS;
3707 chip->badblockpos = NAND_SMALL_BADBLOCK_POS;
3710 * Bad block marker is stored in the last page of each block on Samsung
3711 * and Hynix MLC devices; stored in first two pages of each block on
3712 * Micron devices with 2KiB pages and on SLC Samsung, Hynix, Toshiba,
3713 * AMD/Spansion, and Macronix. All others scan only the first page.
3715 if (!nand_is_slc(chip) &&
3716 (maf_id == NAND_MFR_SAMSUNG ||
3717 maf_id == NAND_MFR_HYNIX))
3718 chip->bbt_options |= NAND_BBT_SCANLASTPAGE;
3719 else if ((nand_is_slc(chip) &&
3720 (maf_id == NAND_MFR_SAMSUNG ||
3721 maf_id == NAND_MFR_HYNIX ||
3722 maf_id == NAND_MFR_TOSHIBA ||
3723 maf_id == NAND_MFR_AMD ||
3724 maf_id == NAND_MFR_MACRONIX)) ||
3725 (mtd->writesize == 2048 &&
3726 maf_id == NAND_MFR_MICRON))
3727 chip->bbt_options |= NAND_BBT_SCAN2NDPAGE;
3730 static inline bool is_full_id_nand(struct nand_flash_dev *type)
3732 return type->id_len;
3735 static bool find_full_id_nand(struct mtd_info *mtd, struct nand_chip *chip,
3736 struct nand_flash_dev *type, u8 *id_data, int *busw)
3738 if (!strncmp(type->id, id_data, type->id_len)) {
3739 mtd->writesize = type->pagesize;
3740 mtd->erasesize = type->erasesize;
3741 mtd->oobsize = type->oobsize;
3743 chip->bits_per_cell = nand_get_bits_per_cell(id_data[2]);
3744 chip->chipsize = (uint64_t)type->chipsize << 20;
3745 chip->options |= type->options;
3746 chip->ecc_strength_ds = NAND_ECC_STRENGTH(type);
3747 chip->ecc_step_ds = NAND_ECC_STEP(type);
3748 chip->onfi_timing_mode_default =
3749 type->onfi_timing_mode_default;
3751 *busw = type->options & NAND_BUSWIDTH_16;
3754 mtd->name = type->name;
3762 * Get the flash and manufacturer id and lookup if the type is supported.
3764 static struct nand_flash_dev *nand_get_flash_type(struct mtd_info *mtd,
3765 struct nand_chip *chip,
3766 int *maf_id, int *dev_id,
3767 struct nand_flash_dev *type)
3773 /* Select the device */
3774 chip->select_chip(mtd, 0);
3777 * Reset the chip, required by some chips (e.g. Micron MT29FxGxxxxx)
3780 chip->cmdfunc(mtd, NAND_CMD_RESET, -1, -1);
3782 /* Send the command for reading device ID */
3783 chip->cmdfunc(mtd, NAND_CMD_READID, 0x00, -1);
3785 /* Read manufacturer and device IDs */
3786 *maf_id = chip->read_byte(mtd);
3787 *dev_id = chip->read_byte(mtd);
3790 * Try again to make sure, as some systems the bus-hold or other
3791 * interface concerns can cause random data which looks like a
3792 * possibly credible NAND flash to appear. If the two results do
3793 * not match, ignore the device completely.
3796 chip->cmdfunc(mtd, NAND_CMD_READID, 0x00, -1);
3798 /* Read entire ID string */
3799 for (i = 0; i < 8; i++)
3800 id_data[i] = chip->read_byte(mtd);
3802 if (id_data[0] != *maf_id || id_data[1] != *dev_id) {
3803 pr_info("second ID read did not match %02x,%02x against %02x,%02x\n",
3804 *maf_id, *dev_id, id_data[0], id_data[1]);
3805 return ERR_PTR(-ENODEV);
3809 type = nand_flash_ids;
3811 for (; type->name != NULL; type++) {
3812 if (is_full_id_nand(type)) {
3813 if (find_full_id_nand(mtd, chip, type, id_data, &busw))
3815 } else if (*dev_id == type->dev_id) {
3820 chip->onfi_version = 0;
3821 if (!type->name || !type->pagesize) {
3822 /* Check if the chip is ONFI compliant */
3823 if (nand_flash_detect_onfi(mtd, chip, &busw))
3826 /* Check if the chip is JEDEC compliant */
3827 if (nand_flash_detect_jedec(mtd, chip, &busw))
3832 return ERR_PTR(-ENODEV);
3835 mtd->name = type->name;
3837 chip->chipsize = (uint64_t)type->chipsize << 20;
3839 if (!type->pagesize) {
3840 /* Decode parameters from extended ID */
3841 nand_decode_ext_id(mtd, chip, id_data, &busw);
3843 nand_decode_id(mtd, chip, type, id_data, &busw);
3845 /* Get chip options */
3846 chip->options |= type->options;
3849 * Check if chip is not a Samsung device. Do not clear the
3850 * options for chips which do not have an extended id.
3852 if (*maf_id != NAND_MFR_SAMSUNG && !type->pagesize)
3853 chip->options &= ~NAND_SAMSUNG_LP_OPTIONS;
3856 /* Try to identify manufacturer */
3857 for (maf_idx = 0; nand_manuf_ids[maf_idx].id != 0x0; maf_idx++) {
3858 if (nand_manuf_ids[maf_idx].id == *maf_id)
3862 if (chip->options & NAND_BUSWIDTH_AUTO) {
3863 WARN_ON(chip->options & NAND_BUSWIDTH_16);
3864 chip->options |= busw;
3865 nand_set_defaults(chip, busw);
3866 } else if (busw != (chip->options & NAND_BUSWIDTH_16)) {
3868 * Check, if buswidth is correct. Hardware drivers should set
3871 pr_info("device found, Manufacturer ID: 0x%02x, Chip ID: 0x%02x\n",
3873 pr_info("%s %s\n", nand_manuf_ids[maf_idx].name, mtd->name);
3874 pr_warn("bus width %d instead %d bit\n",
3875 (chip->options & NAND_BUSWIDTH_16) ? 16 : 8,
3877 return ERR_PTR(-EINVAL);
3880 nand_decode_bbm_options(mtd, chip, id_data);
3882 /* Calculate the address shift from the page size */
3883 chip->page_shift = ffs(mtd->writesize) - 1;
3884 /* Convert chipsize to number of pages per chip -1 */
3885 chip->pagemask = (chip->chipsize >> chip->page_shift) - 1;
3887 chip->bbt_erase_shift = chip->phys_erase_shift =
3888 ffs(mtd->erasesize) - 1;
3889 if (chip->chipsize & 0xffffffff)
3890 chip->chip_shift = ffs((unsigned)chip->chipsize) - 1;
3892 chip->chip_shift = ffs((unsigned)(chip->chipsize >> 32));
3893 chip->chip_shift += 32 - 1;
3896 chip->badblockbits = 8;
3897 chip->erase = single_erase;
3899 /* Do not replace user supplied command function! */
3900 if (mtd->writesize > 512 && chip->cmdfunc == nand_command)
3901 chip->cmdfunc = nand_command_lp;
3903 pr_info("device found, Manufacturer ID: 0x%02x, Chip ID: 0x%02x\n",
3906 if (chip->onfi_version)
3907 pr_info("%s %s\n", nand_manuf_ids[maf_idx].name,
3908 chip->onfi_params.model);
3909 else if (chip->jedec_version)
3910 pr_info("%s %s\n", nand_manuf_ids[maf_idx].name,
3911 chip->jedec_params.model);
3913 pr_info("%s %s\n", nand_manuf_ids[maf_idx].name,
3916 pr_info("%d MiB, %s, erase size: %d KiB, page size: %d, OOB size: %d\n",
3917 (int)(chip->chipsize >> 20), nand_is_slc(chip) ? "SLC" : "MLC",
3918 mtd->erasesize >> 10, mtd->writesize, mtd->oobsize);
3922 static int nand_dt_init(struct mtd_info *mtd, struct nand_chip *chip,
3923 struct device_node *dn)
3925 int ecc_mode, ecc_strength, ecc_step;
3927 if (of_get_nand_bus_width(dn) == 16)
3928 chip->options |= NAND_BUSWIDTH_16;
3930 if (of_get_nand_on_flash_bbt(dn))
3931 chip->bbt_options |= NAND_BBT_USE_FLASH;
3933 ecc_mode = of_get_nand_ecc_mode(dn);
3934 ecc_strength = of_get_nand_ecc_strength(dn);
3935 ecc_step = of_get_nand_ecc_step_size(dn);
3937 if ((ecc_step >= 0 && !(ecc_strength >= 0)) ||
3938 (!(ecc_step >= 0) && ecc_strength >= 0)) {
3939 pr_err("must set both strength and step size in DT\n");
3944 chip->ecc.mode = ecc_mode;
3946 if (ecc_strength >= 0)
3947 chip->ecc.strength = ecc_strength;
3950 chip->ecc.size = ecc_step;
3956 * nand_scan_ident - [NAND Interface] Scan for the NAND device
3957 * @mtd: MTD device structure
3958 * @maxchips: number of chips to scan for
3959 * @table: alternative NAND ID table
3961 * This is the first phase of the normal nand_scan() function. It reads the
3962 * flash ID and sets up MTD fields accordingly.
3964 * The mtd->owner field must be set to the module of the caller.
3966 int nand_scan_ident(struct mtd_info *mtd, int maxchips,
3967 struct nand_flash_dev *table)
3969 int i, nand_maf_id, nand_dev_id;
3970 struct nand_chip *chip = mtd->priv;
3971 struct nand_flash_dev *type;
3974 if (chip->flash_node) {
3975 ret = nand_dt_init(mtd, chip, chip->flash_node);
3980 /* Set the default functions */
3981 nand_set_defaults(chip, chip->options & NAND_BUSWIDTH_16);
3983 /* Read the flash type */
3984 type = nand_get_flash_type(mtd, chip, &nand_maf_id,
3985 &nand_dev_id, table);
3988 if (!(chip->options & NAND_SCAN_SILENT_NODEV))
3989 pr_warn("No NAND device found\n");
3990 chip->select_chip(mtd, -1);
3991 return PTR_ERR(type);
3994 chip->select_chip(mtd, -1);
3996 /* Check for a chip array */
3997 for (i = 1; i < maxchips; i++) {
3998 chip->select_chip(mtd, i);
3999 /* See comment in nand_get_flash_type for reset */
4000 chip->cmdfunc(mtd, NAND_CMD_RESET, -1, -1);
4001 /* Send the command for reading device ID */
4002 chip->cmdfunc(mtd, NAND_CMD_READID, 0x00, -1);
4003 /* Read manufacturer and device IDs */
4004 if (nand_maf_id != chip->read_byte(mtd) ||
4005 nand_dev_id != chip->read_byte(mtd)) {
4006 chip->select_chip(mtd, -1);
4009 chip->select_chip(mtd, -1);
4012 pr_info("%d chips detected\n", i);
4014 /* Store the number of chips and calc total size for mtd */
4016 mtd->size = i * chip->chipsize;
4020 EXPORT_SYMBOL(nand_scan_ident);
4023 * Check if the chip configuration meet the datasheet requirements.
4025 * If our configuration corrects A bits per B bytes and the minimum
4026 * required correction level is X bits per Y bytes, then we must ensure
4027 * both of the following are true:
4029 * (1) A / B >= X / Y
4032 * Requirement (1) ensures we can correct for the required bitflip density.
4033 * Requirement (2) ensures we can correct even when all bitflips are clumped
4034 * in the same sector.
4036 static bool nand_ecc_strength_good(struct mtd_info *mtd)
4038 struct nand_chip *chip = mtd->priv;
4039 struct nand_ecc_ctrl *ecc = &chip->ecc;
4042 if (ecc->size == 0 || chip->ecc_step_ds == 0)
4043 /* Not enough information */
4047 * We get the number of corrected bits per page to compare
4048 * the correction density.
4050 corr = (mtd->writesize * ecc->strength) / ecc->size;
4051 ds_corr = (mtd->writesize * chip->ecc_strength_ds) / chip->ecc_step_ds;
4053 return corr >= ds_corr && ecc->strength >= chip->ecc_strength_ds;
4057 * nand_scan_tail - [NAND Interface] Scan for the NAND device
4058 * @mtd: MTD device structure
4060 * This is the second phase of the normal nand_scan() function. It fills out
4061 * all the uninitialized function pointers with the defaults and scans for a
4062 * bad block table if appropriate.
4064 int nand_scan_tail(struct mtd_info *mtd)
4067 struct nand_chip *chip = mtd->priv;
4068 struct nand_ecc_ctrl *ecc = &chip->ecc;
4069 struct nand_buffers *nbuf;
4071 /* New bad blocks should be marked in OOB, flash-based BBT, or both */
4072 BUG_ON((chip->bbt_options & NAND_BBT_NO_OOB_BBM) &&
4073 !(chip->bbt_options & NAND_BBT_USE_FLASH));
4075 if (!(chip->options & NAND_OWN_BUFFERS)) {
4076 nbuf = kzalloc(sizeof(*nbuf) + mtd->writesize
4077 + mtd->oobsize * 3, GFP_KERNEL);
4080 nbuf->ecccalc = (uint8_t *)(nbuf + 1);
4081 nbuf->ecccode = nbuf->ecccalc + mtd->oobsize;
4082 nbuf->databuf = nbuf->ecccode + mtd->oobsize;
4084 chip->buffers = nbuf;
4090 /* Set the internal oob buffer location, just after the page data */
4091 chip->oob_poi = chip->buffers->databuf + mtd->writesize;
4094 * If no default placement scheme is given, select an appropriate one.
4096 if (!ecc->layout && (ecc->mode != NAND_ECC_SOFT_BCH)) {
4097 switch (mtd->oobsize) {
4099 ecc->layout = &nand_oob_8;
4102 ecc->layout = &nand_oob_16;
4105 ecc->layout = &nand_oob_64;
4108 ecc->layout = &nand_oob_128;
4111 pr_warn("No oob scheme defined for oobsize %d\n",
4117 if (!chip->write_page)
4118 chip->write_page = nand_write_page;
4121 * Check ECC mode, default to software if 3byte/512byte hardware ECC is
4122 * selected and we have 256 byte pagesize fallback to software ECC
4125 switch (ecc->mode) {
4126 case NAND_ECC_HW_OOB_FIRST:
4127 /* Similar to NAND_ECC_HW, but a separate read_page handle */
4128 if (!ecc->calculate || !ecc->correct || !ecc->hwctl) {
4129 pr_warn("No ECC functions supplied; hardware ECC not possible\n");
4132 if (!ecc->read_page)
4133 ecc->read_page = nand_read_page_hwecc_oob_first;
4136 /* Use standard hwecc read page function? */
4137 if (!ecc->read_page)
4138 ecc->read_page = nand_read_page_hwecc;
4139 if (!ecc->write_page)
4140 ecc->write_page = nand_write_page_hwecc;
4141 if (!ecc->read_page_raw)
4142 ecc->read_page_raw = nand_read_page_raw;
4143 if (!ecc->write_page_raw)
4144 ecc->write_page_raw = nand_write_page_raw;
4146 ecc->read_oob = nand_read_oob_std;
4147 if (!ecc->write_oob)
4148 ecc->write_oob = nand_write_oob_std;
4149 if (!ecc->read_subpage)
4150 ecc->read_subpage = nand_read_subpage;
4151 if (!ecc->write_subpage)
4152 ecc->write_subpage = nand_write_subpage_hwecc;
4154 case NAND_ECC_HW_SYNDROME:
4155 if ((!ecc->calculate || !ecc->correct || !ecc->hwctl) &&
4157 ecc->read_page == nand_read_page_hwecc ||
4159 ecc->write_page == nand_write_page_hwecc)) {
4160 pr_warn("No ECC functions supplied; hardware ECC not possible\n");
4163 /* Use standard syndrome read/write page function? */
4164 if (!ecc->read_page)
4165 ecc->read_page = nand_read_page_syndrome;
4166 if (!ecc->write_page)
4167 ecc->write_page = nand_write_page_syndrome;
4168 if (!ecc->read_page_raw)
4169 ecc->read_page_raw = nand_read_page_raw_syndrome;
4170 if (!ecc->write_page_raw)
4171 ecc->write_page_raw = nand_write_page_raw_syndrome;
4173 ecc->read_oob = nand_read_oob_syndrome;
4174 if (!ecc->write_oob)
4175 ecc->write_oob = nand_write_oob_syndrome;
4177 if (mtd->writesize >= ecc->size) {
4178 if (!ecc->strength) {
4179 pr_warn("Driver must set ecc.strength when using hardware ECC\n");
4184 pr_warn("%d byte HW ECC not possible on %d byte page size, fallback to SW ECC\n",
4185 ecc->size, mtd->writesize);
4186 ecc->mode = NAND_ECC_SOFT;
4189 ecc->calculate = nand_calculate_ecc;
4190 ecc->correct = nand_correct_data;
4191 ecc->read_page = nand_read_page_swecc;
4192 ecc->read_subpage = nand_read_subpage;
4193 ecc->write_page = nand_write_page_swecc;
4194 ecc->read_page_raw = nand_read_page_raw;
4195 ecc->write_page_raw = nand_write_page_raw;
4196 ecc->read_oob = nand_read_oob_std;
4197 ecc->write_oob = nand_write_oob_std;
4204 case NAND_ECC_SOFT_BCH:
4205 if (!mtd_nand_has_bch()) {
4206 pr_warn("CONFIG_MTD_NAND_ECC_BCH not enabled\n");
4209 ecc->calculate = nand_bch_calculate_ecc;
4210 ecc->correct = nand_bch_correct_data;
4211 ecc->read_page = nand_read_page_swecc;
4212 ecc->read_subpage = nand_read_subpage;
4213 ecc->write_page = nand_write_page_swecc;
4214 ecc->read_page_raw = nand_read_page_raw;
4215 ecc->write_page_raw = nand_write_page_raw;
4216 ecc->read_oob = nand_read_oob_std;
4217 ecc->write_oob = nand_write_oob_std;
4219 * Board driver should supply ecc.size and ecc.strength values
4220 * to select how many bits are correctable. Otherwise, default
4221 * to 4 bits for large page devices.
4223 if (!ecc->size && (mtd->oobsize >= 64)) {
4228 /* See nand_bch_init() for details. */
4229 ecc->bytes = DIV_ROUND_UP(
4230 ecc->strength * fls(8 * ecc->size), 8);
4231 ecc->priv = nand_bch_init(mtd, ecc->size, ecc->bytes,
4234 pr_warn("BCH ECC initialization failed!\n");
4240 pr_warn("NAND_ECC_NONE selected by board driver. This is not recommended!\n");
4241 ecc->read_page = nand_read_page_raw;
4242 ecc->write_page = nand_write_page_raw;
4243 ecc->read_oob = nand_read_oob_std;
4244 ecc->read_page_raw = nand_read_page_raw;
4245 ecc->write_page_raw = nand_write_page_raw;
4246 ecc->write_oob = nand_write_oob_std;
4247 ecc->size = mtd->writesize;
4253 pr_warn("Invalid NAND_ECC_MODE %d\n", ecc->mode);
4257 /* For many systems, the standard OOB write also works for raw */
4258 if (!ecc->read_oob_raw)
4259 ecc->read_oob_raw = ecc->read_oob;
4260 if (!ecc->write_oob_raw)
4261 ecc->write_oob_raw = ecc->write_oob;
4264 * The number of bytes available for a client to place data into
4265 * the out of band area.
4267 ecc->layout->oobavail = 0;
4268 for (i = 0; ecc->layout->oobfree[i].length
4269 && i < ARRAY_SIZE(ecc->layout->oobfree); i++)
4270 ecc->layout->oobavail += ecc->layout->oobfree[i].length;
4271 mtd->oobavail = ecc->layout->oobavail;
4273 /* ECC sanity check: warn if it's too weak */
4274 if (!nand_ecc_strength_good(mtd))
4275 pr_warn("WARNING: %s: the ECC used on your system is too weak compared to the one required by the NAND chip\n",
4279 * Set the number of read / write steps for one page depending on ECC
4282 ecc->steps = mtd->writesize / ecc->size;
4283 if (ecc->steps * ecc->size != mtd->writesize) {
4284 pr_warn("Invalid ECC parameters\n");
4287 ecc->total = ecc->steps * ecc->bytes;
4289 /* Allow subpage writes up to ecc.steps. Not possible for MLC flash */
4290 if (!(chip->options & NAND_NO_SUBPAGE_WRITE) && nand_is_slc(chip)) {
4291 switch (ecc->steps) {
4293 mtd->subpage_sft = 1;
4298 mtd->subpage_sft = 2;
4302 chip->subpagesize = mtd->writesize >> mtd->subpage_sft;
4304 /* Initialize state */
4305 chip->state = FL_READY;
4307 /* Invalidate the pagebuffer reference */
4310 /* Large page NAND with SOFT_ECC should support subpage reads */
4311 switch (ecc->mode) {
4313 case NAND_ECC_SOFT_BCH:
4314 if (chip->page_shift > 9)
4315 chip->options |= NAND_SUBPAGE_READ;
4322 /* Fill in remaining MTD driver data */
4323 mtd->type = nand_is_slc(chip) ? MTD_NANDFLASH : MTD_MLCNANDFLASH;
4324 mtd->flags = (chip->options & NAND_ROM) ? MTD_CAP_ROM :
4326 mtd->_erase = nand_erase;
4328 mtd->_unpoint = NULL;
4329 mtd->_read = nand_read;
4330 mtd->_write = nand_write;
4331 mtd->_panic_write = panic_nand_write;
4332 mtd->_read_oob = nand_read_oob;
4333 mtd->_write_oob = nand_write_oob;
4334 mtd->_sync = nand_sync;
4336 mtd->_unlock = NULL;
4337 mtd->_suspend = nand_suspend;
4338 mtd->_resume = nand_resume;
4339 mtd->_reboot = nand_shutdown;
4340 mtd->_block_isreserved = nand_block_isreserved;
4341 mtd->_block_isbad = nand_block_isbad;
4342 mtd->_block_markbad = nand_block_markbad;
4343 mtd->writebufsize = mtd->writesize;
4345 /* propagate ecc info to mtd_info */
4346 mtd->ecclayout = ecc->layout;
4347 mtd->ecc_strength = ecc->strength;
4348 mtd->ecc_step_size = ecc->size;
4350 * Initialize bitflip_threshold to its default prior scan_bbt() call.
4351 * scan_bbt() might invoke mtd_read(), thus bitflip_threshold must be
4354 if (!mtd->bitflip_threshold)
4355 mtd->bitflip_threshold = DIV_ROUND_UP(mtd->ecc_strength * 3, 4);
4357 /* Check, if we should skip the bad block table scan */
4358 if (chip->options & NAND_SKIP_BBTSCAN)
4361 /* Build bad block table */
4362 return chip->scan_bbt(mtd);
4364 EXPORT_SYMBOL(nand_scan_tail);
4367 * is_module_text_address() isn't exported, and it's mostly a pointless
4368 * test if this is a module _anyway_ -- they'd have to try _really_ hard
4369 * to call us from in-kernel code if the core NAND support is modular.
4372 #define caller_is_module() (1)
4374 #define caller_is_module() \
4375 is_module_text_address((unsigned long)__builtin_return_address(0))
4379 * nand_scan - [NAND Interface] Scan for the NAND device
4380 * @mtd: MTD device structure
4381 * @maxchips: number of chips to scan for
4383 * This fills out all the uninitialized function pointers with the defaults.
4384 * The flash ID is read and the mtd/chip structures are filled with the
4385 * appropriate values. The mtd->owner field must be set to the module of the
4388 int nand_scan(struct mtd_info *mtd, int maxchips)
4392 /* Many callers got this wrong, so check for it for a while... */
4393 if (!mtd->owner && caller_is_module()) {
4394 pr_crit("%s called with NULL mtd->owner!\n", __func__);
4398 ret = nand_scan_ident(mtd, maxchips, NULL);
4400 ret = nand_scan_tail(mtd);
4403 EXPORT_SYMBOL(nand_scan);
4406 * nand_release - [NAND Interface] Free resources held by the NAND device
4407 * @mtd: MTD device structure
4409 void nand_release(struct mtd_info *mtd)
4411 struct nand_chip *chip = mtd->priv;
4413 if (chip->ecc.mode == NAND_ECC_SOFT_BCH)
4414 nand_bch_free((struct nand_bch_control *)chip->ecc.priv);
4416 mtd_device_unregister(mtd);
4418 /* Free bad block table memory */
4420 if (!(chip->options & NAND_OWN_BUFFERS))
4421 kfree(chip->buffers);
4423 /* Free bad block descriptor memory */
4424 if (chip->badblock_pattern && chip->badblock_pattern->options
4425 & NAND_BBT_DYNAMICSTRUCT)
4426 kfree(chip->badblock_pattern);
4428 EXPORT_SYMBOL_GPL(nand_release);
4430 static int __init nand_base_init(void)
4432 led_trigger_register_simple("nand-disk", &nand_led_trigger);
4436 static void __exit nand_base_exit(void)
4438 led_trigger_unregister_simple(nand_led_trigger);
4441 module_init(nand_base_init);
4442 module_exit(nand_base_exit);
4444 MODULE_LICENSE("GPL");
4445 MODULE_AUTHOR("Steven J. Hill <sjhill@realitydiluted.com>");
4446 MODULE_AUTHOR("Thomas Gleixner <tglx@linutronix.de>");
4447 MODULE_DESCRIPTION("Generic NAND flash driver code");