mtd: nand: brcmnand: Check flash #WP pin status before nand erase/program
[linux/fpc-iii.git] / drivers / mtd / nand / nand_base.c
blobf222f8a7ba52a8683881520a6902c79b9f16c200
1 /*
2 * Overview:
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)
12 * Credits:
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
18 * TODO:
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>
38 #include <linux/mm.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/io.h>
47 #include <linux/mtd/partitions.h>
48 #include <linux/of.h>
50 static int nand_get_device(struct mtd_info *mtd, int new_state);
52 static int nand_do_write_oob(struct mtd_info *mtd, loff_t to,
53 struct mtd_oob_ops *ops);
55 /* Define default oob placement schemes for large and small page devices */
56 static int nand_ooblayout_ecc_sp(struct mtd_info *mtd, int section,
57 struct mtd_oob_region *oobregion)
59 struct nand_chip *chip = mtd_to_nand(mtd);
60 struct nand_ecc_ctrl *ecc = &chip->ecc;
62 if (section > 1)
63 return -ERANGE;
65 if (!section) {
66 oobregion->offset = 0;
67 oobregion->length = 4;
68 } else {
69 oobregion->offset = 6;
70 oobregion->length = ecc->total - 4;
73 return 0;
76 static int nand_ooblayout_free_sp(struct mtd_info *mtd, int section,
77 struct mtd_oob_region *oobregion)
79 if (section > 1)
80 return -ERANGE;
82 if (mtd->oobsize == 16) {
83 if (section)
84 return -ERANGE;
86 oobregion->length = 8;
87 oobregion->offset = 8;
88 } else {
89 oobregion->length = 2;
90 if (!section)
91 oobregion->offset = 3;
92 else
93 oobregion->offset = 6;
96 return 0;
99 const struct mtd_ooblayout_ops nand_ooblayout_sp_ops = {
100 .ecc = nand_ooblayout_ecc_sp,
101 .free = nand_ooblayout_free_sp,
103 EXPORT_SYMBOL_GPL(nand_ooblayout_sp_ops);
105 static int nand_ooblayout_ecc_lp(struct mtd_info *mtd, int section,
106 struct mtd_oob_region *oobregion)
108 struct nand_chip *chip = mtd_to_nand(mtd);
109 struct nand_ecc_ctrl *ecc = &chip->ecc;
111 if (section)
112 return -ERANGE;
114 oobregion->length = ecc->total;
115 oobregion->offset = mtd->oobsize - oobregion->length;
117 return 0;
120 static int nand_ooblayout_free_lp(struct mtd_info *mtd, int section,
121 struct mtd_oob_region *oobregion)
123 struct nand_chip *chip = mtd_to_nand(mtd);
124 struct nand_ecc_ctrl *ecc = &chip->ecc;
126 if (section)
127 return -ERANGE;
129 oobregion->length = mtd->oobsize - ecc->total - 2;
130 oobregion->offset = 2;
132 return 0;
135 const struct mtd_ooblayout_ops nand_ooblayout_lp_ops = {
136 .ecc = nand_ooblayout_ecc_lp,
137 .free = nand_ooblayout_free_lp,
139 EXPORT_SYMBOL_GPL(nand_ooblayout_lp_ops);
142 * Support the old "large page" layout used for 1-bit Hamming ECC where ECC
143 * are placed at a fixed offset.
145 static int nand_ooblayout_ecc_lp_hamming(struct mtd_info *mtd, int section,
146 struct mtd_oob_region *oobregion)
148 struct nand_chip *chip = mtd_to_nand(mtd);
149 struct nand_ecc_ctrl *ecc = &chip->ecc;
151 if (section)
152 return -ERANGE;
154 switch (mtd->oobsize) {
155 case 64:
156 oobregion->offset = 40;
157 break;
158 case 128:
159 oobregion->offset = 80;
160 break;
161 default:
162 return -EINVAL;
165 oobregion->length = ecc->total;
166 if (oobregion->offset + oobregion->length > mtd->oobsize)
167 return -ERANGE;
169 return 0;
172 static int nand_ooblayout_free_lp_hamming(struct mtd_info *mtd, int section,
173 struct mtd_oob_region *oobregion)
175 struct nand_chip *chip = mtd_to_nand(mtd);
176 struct nand_ecc_ctrl *ecc = &chip->ecc;
177 int ecc_offset = 0;
179 if (section < 0 || section > 1)
180 return -ERANGE;
182 switch (mtd->oobsize) {
183 case 64:
184 ecc_offset = 40;
185 break;
186 case 128:
187 ecc_offset = 80;
188 break;
189 default:
190 return -EINVAL;
193 if (section == 0) {
194 oobregion->offset = 2;
195 oobregion->length = ecc_offset - 2;
196 } else {
197 oobregion->offset = ecc_offset + ecc->total;
198 oobregion->length = mtd->oobsize - oobregion->offset;
201 return 0;
204 const struct mtd_ooblayout_ops nand_ooblayout_lp_hamming_ops = {
205 .ecc = nand_ooblayout_ecc_lp_hamming,
206 .free = nand_ooblayout_free_lp_hamming,
209 static int check_offs_len(struct mtd_info *mtd,
210 loff_t ofs, uint64_t len)
212 struct nand_chip *chip = mtd_to_nand(mtd);
213 int ret = 0;
215 /* Start address must align on block boundary */
216 if (ofs & ((1ULL << chip->phys_erase_shift) - 1)) {
217 pr_debug("%s: unaligned address\n", __func__);
218 ret = -EINVAL;
221 /* Length must align on block boundary */
222 if (len & ((1ULL << chip->phys_erase_shift) - 1)) {
223 pr_debug("%s: length not block aligned\n", __func__);
224 ret = -EINVAL;
227 return ret;
231 * nand_release_device - [GENERIC] release chip
232 * @mtd: MTD device structure
234 * Release chip lock and wake up anyone waiting on the device.
236 static void nand_release_device(struct mtd_info *mtd)
238 struct nand_chip *chip = mtd_to_nand(mtd);
240 /* Release the controller and the chip */
241 spin_lock(&chip->controller->lock);
242 chip->controller->active = NULL;
243 chip->state = FL_READY;
244 wake_up(&chip->controller->wq);
245 spin_unlock(&chip->controller->lock);
249 * nand_read_byte - [DEFAULT] read one byte from the chip
250 * @mtd: MTD device structure
252 * Default read function for 8bit buswidth
254 static uint8_t nand_read_byte(struct mtd_info *mtd)
256 struct nand_chip *chip = mtd_to_nand(mtd);
257 return readb(chip->IO_ADDR_R);
261 * nand_read_byte16 - [DEFAULT] read one byte endianness aware from the chip
262 * @mtd: MTD device structure
264 * Default read function for 16bit buswidth with endianness conversion.
267 static uint8_t nand_read_byte16(struct mtd_info *mtd)
269 struct nand_chip *chip = mtd_to_nand(mtd);
270 return (uint8_t) cpu_to_le16(readw(chip->IO_ADDR_R));
274 * nand_read_word - [DEFAULT] read one word from the chip
275 * @mtd: MTD device structure
277 * Default read function for 16bit buswidth without endianness conversion.
279 static u16 nand_read_word(struct mtd_info *mtd)
281 struct nand_chip *chip = mtd_to_nand(mtd);
282 return readw(chip->IO_ADDR_R);
286 * nand_select_chip - [DEFAULT] control CE line
287 * @mtd: MTD device structure
288 * @chipnr: chipnumber to select, -1 for deselect
290 * Default select function for 1 chip devices.
292 static void nand_select_chip(struct mtd_info *mtd, int chipnr)
294 struct nand_chip *chip = mtd_to_nand(mtd);
296 switch (chipnr) {
297 case -1:
298 chip->cmd_ctrl(mtd, NAND_CMD_NONE, 0 | NAND_CTRL_CHANGE);
299 break;
300 case 0:
301 break;
303 default:
304 BUG();
309 * nand_write_byte - [DEFAULT] write single byte to chip
310 * @mtd: MTD device structure
311 * @byte: value to write
313 * Default function to write a byte to I/O[7:0]
315 static void nand_write_byte(struct mtd_info *mtd, uint8_t byte)
317 struct nand_chip *chip = mtd_to_nand(mtd);
319 chip->write_buf(mtd, &byte, 1);
323 * nand_write_byte16 - [DEFAULT] write single byte to a chip with width 16
324 * @mtd: MTD device structure
325 * @byte: value to write
327 * Default function to write a byte to I/O[7:0] on a 16-bit wide chip.
329 static void nand_write_byte16(struct mtd_info *mtd, uint8_t byte)
331 struct nand_chip *chip = mtd_to_nand(mtd);
332 uint16_t word = byte;
335 * It's not entirely clear what should happen to I/O[15:8] when writing
336 * a byte. The ONFi spec (Revision 3.1; 2012-09-19, Section 2.16) reads:
338 * When the host supports a 16-bit bus width, only data is
339 * transferred at the 16-bit width. All address and command line
340 * transfers shall use only the lower 8-bits of the data bus. During
341 * command transfers, the host may place any value on the upper
342 * 8-bits of the data bus. During address transfers, the host shall
343 * set the upper 8-bits of the data bus to 00h.
345 * One user of the write_byte callback is nand_onfi_set_features. The
346 * four parameters are specified to be written to I/O[7:0], but this is
347 * neither an address nor a command transfer. Let's assume a 0 on the
348 * upper I/O lines is OK.
350 chip->write_buf(mtd, (uint8_t *)&word, 2);
354 * nand_write_buf - [DEFAULT] write buffer to chip
355 * @mtd: MTD device structure
356 * @buf: data buffer
357 * @len: number of bytes to write
359 * Default write function for 8bit buswidth.
361 static void nand_write_buf(struct mtd_info *mtd, const uint8_t *buf, int len)
363 struct nand_chip *chip = mtd_to_nand(mtd);
365 iowrite8_rep(chip->IO_ADDR_W, buf, len);
369 * nand_read_buf - [DEFAULT] read chip data into buffer
370 * @mtd: MTD device structure
371 * @buf: buffer to store date
372 * @len: number of bytes to read
374 * Default read function for 8bit buswidth.
376 static void nand_read_buf(struct mtd_info *mtd, uint8_t *buf, int len)
378 struct nand_chip *chip = mtd_to_nand(mtd);
380 ioread8_rep(chip->IO_ADDR_R, buf, len);
384 * nand_write_buf16 - [DEFAULT] write buffer to chip
385 * @mtd: MTD device structure
386 * @buf: data buffer
387 * @len: number of bytes to write
389 * Default write function for 16bit buswidth.
391 static void nand_write_buf16(struct mtd_info *mtd, const uint8_t *buf, int len)
393 struct nand_chip *chip = mtd_to_nand(mtd);
394 u16 *p = (u16 *) buf;
396 iowrite16_rep(chip->IO_ADDR_W, p, len >> 1);
400 * nand_read_buf16 - [DEFAULT] read chip data into buffer
401 * @mtd: MTD device structure
402 * @buf: buffer to store date
403 * @len: number of bytes to read
405 * Default read function for 16bit buswidth.
407 static void nand_read_buf16(struct mtd_info *mtd, uint8_t *buf, int len)
409 struct nand_chip *chip = mtd_to_nand(mtd);
410 u16 *p = (u16 *) buf;
412 ioread16_rep(chip->IO_ADDR_R, p, len >> 1);
416 * nand_block_bad - [DEFAULT] Read bad block marker from the chip
417 * @mtd: MTD device structure
418 * @ofs: offset from device start
420 * Check, if the block is bad.
422 static int nand_block_bad(struct mtd_info *mtd, loff_t ofs)
424 int page, res = 0, i = 0;
425 struct nand_chip *chip = mtd_to_nand(mtd);
426 u16 bad;
428 if (chip->bbt_options & NAND_BBT_SCANLASTPAGE)
429 ofs += mtd->erasesize - mtd->writesize;
431 page = (int)(ofs >> chip->page_shift) & chip->pagemask;
433 do {
434 if (chip->options & NAND_BUSWIDTH_16) {
435 chip->cmdfunc(mtd, NAND_CMD_READOOB,
436 chip->badblockpos & 0xFE, page);
437 bad = cpu_to_le16(chip->read_word(mtd));
438 if (chip->badblockpos & 0x1)
439 bad >>= 8;
440 else
441 bad &= 0xFF;
442 } else {
443 chip->cmdfunc(mtd, NAND_CMD_READOOB, chip->badblockpos,
444 page);
445 bad = chip->read_byte(mtd);
448 if (likely(chip->badblockbits == 8))
449 res = bad != 0xFF;
450 else
451 res = hweight8(bad) < chip->badblockbits;
452 ofs += mtd->writesize;
453 page = (int)(ofs >> chip->page_shift) & chip->pagemask;
454 i++;
455 } while (!res && i < 2 && (chip->bbt_options & NAND_BBT_SCAN2NDPAGE));
457 return res;
461 * nand_default_block_markbad - [DEFAULT] mark a block bad via bad block marker
462 * @mtd: MTD device structure
463 * @ofs: offset from device start
465 * This is the default implementation, which can be overridden by a hardware
466 * specific driver. It provides the details for writing a bad block marker to a
467 * block.
469 static int nand_default_block_markbad(struct mtd_info *mtd, loff_t ofs)
471 struct nand_chip *chip = mtd_to_nand(mtd);
472 struct mtd_oob_ops ops;
473 uint8_t buf[2] = { 0, 0 };
474 int ret = 0, res, i = 0;
476 memset(&ops, 0, sizeof(ops));
477 ops.oobbuf = buf;
478 ops.ooboffs = chip->badblockpos;
479 if (chip->options & NAND_BUSWIDTH_16) {
480 ops.ooboffs &= ~0x01;
481 ops.len = ops.ooblen = 2;
482 } else {
483 ops.len = ops.ooblen = 1;
485 ops.mode = MTD_OPS_PLACE_OOB;
487 /* Write to first/last page(s) if necessary */
488 if (chip->bbt_options & NAND_BBT_SCANLASTPAGE)
489 ofs += mtd->erasesize - mtd->writesize;
490 do {
491 res = nand_do_write_oob(mtd, ofs, &ops);
492 if (!ret)
493 ret = res;
495 i++;
496 ofs += mtd->writesize;
497 } while ((chip->bbt_options & NAND_BBT_SCAN2NDPAGE) && i < 2);
499 return ret;
503 * nand_block_markbad_lowlevel - mark a block bad
504 * @mtd: MTD device structure
505 * @ofs: offset from device start
507 * This function performs the generic NAND bad block marking steps (i.e., bad
508 * block table(s) and/or marker(s)). We only allow the hardware driver to
509 * specify how to write bad block markers to OOB (chip->block_markbad).
511 * We try operations in the following order:
512 * (1) erase the affected block, to allow OOB marker to be written cleanly
513 * (2) write bad block marker to OOB area of affected block (unless flag
514 * NAND_BBT_NO_OOB_BBM is present)
515 * (3) update the BBT
516 * Note that we retain the first error encountered in (2) or (3), finish the
517 * procedures, and dump the error in the end.
519 static int nand_block_markbad_lowlevel(struct mtd_info *mtd, loff_t ofs)
521 struct nand_chip *chip = mtd_to_nand(mtd);
522 int res, ret = 0;
524 if (!(chip->bbt_options & NAND_BBT_NO_OOB_BBM)) {
525 struct erase_info einfo;
527 /* Attempt erase before marking OOB */
528 memset(&einfo, 0, sizeof(einfo));
529 einfo.mtd = mtd;
530 einfo.addr = ofs;
531 einfo.len = 1ULL << chip->phys_erase_shift;
532 nand_erase_nand(mtd, &einfo, 0);
534 /* Write bad block marker to OOB */
535 nand_get_device(mtd, FL_WRITING);
536 ret = chip->block_markbad(mtd, ofs);
537 nand_release_device(mtd);
540 /* Mark block bad in BBT */
541 if (chip->bbt) {
542 res = nand_markbad_bbt(mtd, ofs);
543 if (!ret)
544 ret = res;
547 if (!ret)
548 mtd->ecc_stats.badblocks++;
550 return ret;
554 * nand_check_wp - [GENERIC] check if the chip is write protected
555 * @mtd: MTD device structure
557 * Check, if the device is write protected. The function expects, that the
558 * device is already selected.
560 static int nand_check_wp(struct mtd_info *mtd)
562 struct nand_chip *chip = mtd_to_nand(mtd);
564 /* Broken xD cards report WP despite being writable */
565 if (chip->options & NAND_BROKEN_XD)
566 return 0;
568 /* Check the WP bit */
569 chip->cmdfunc(mtd, NAND_CMD_STATUS, -1, -1);
570 return (chip->read_byte(mtd) & NAND_STATUS_WP) ? 0 : 1;
574 * nand_block_isreserved - [GENERIC] Check if a block is marked reserved.
575 * @mtd: MTD device structure
576 * @ofs: offset from device start
578 * Check if the block is marked as reserved.
580 static int nand_block_isreserved(struct mtd_info *mtd, loff_t ofs)
582 struct nand_chip *chip = mtd_to_nand(mtd);
584 if (!chip->bbt)
585 return 0;
586 /* Return info from the table */
587 return nand_isreserved_bbt(mtd, ofs);
591 * nand_block_checkbad - [GENERIC] Check if a block is marked bad
592 * @mtd: MTD device structure
593 * @ofs: offset from device start
594 * @allowbbt: 1, if its allowed to access the bbt area
596 * Check, if the block is bad. Either by reading the bad block table or
597 * calling of the scan function.
599 static int nand_block_checkbad(struct mtd_info *mtd, loff_t ofs, int allowbbt)
601 struct nand_chip *chip = mtd_to_nand(mtd);
603 if (!chip->bbt)
604 return chip->block_bad(mtd, ofs);
606 /* Return info from the table */
607 return nand_isbad_bbt(mtd, ofs, allowbbt);
611 * panic_nand_wait_ready - [GENERIC] Wait for the ready pin after commands.
612 * @mtd: MTD device structure
613 * @timeo: Timeout
615 * Helper function for nand_wait_ready used when needing to wait in interrupt
616 * context.
618 static void panic_nand_wait_ready(struct mtd_info *mtd, unsigned long timeo)
620 struct nand_chip *chip = mtd_to_nand(mtd);
621 int i;
623 /* Wait for the device to get ready */
624 for (i = 0; i < timeo; i++) {
625 if (chip->dev_ready(mtd))
626 break;
627 touch_softlockup_watchdog();
628 mdelay(1);
633 * nand_wait_ready - [GENERIC] Wait for the ready pin after commands.
634 * @mtd: MTD device structure
636 * Wait for the ready pin after a command, and warn if a timeout occurs.
638 void nand_wait_ready(struct mtd_info *mtd)
640 struct nand_chip *chip = mtd_to_nand(mtd);
641 unsigned long timeo = 400;
643 if (in_interrupt() || oops_in_progress)
644 return panic_nand_wait_ready(mtd, timeo);
646 /* Wait until command is processed or timeout occurs */
647 timeo = jiffies + msecs_to_jiffies(timeo);
648 do {
649 if (chip->dev_ready(mtd))
650 return;
651 cond_resched();
652 } while (time_before(jiffies, timeo));
654 if (!chip->dev_ready(mtd))
655 pr_warn_ratelimited("timeout while waiting for chip to become ready\n");
657 EXPORT_SYMBOL_GPL(nand_wait_ready);
660 * nand_wait_status_ready - [GENERIC] Wait for the ready status after commands.
661 * @mtd: MTD device structure
662 * @timeo: Timeout in ms
664 * Wait for status ready (i.e. command done) or timeout.
666 static void nand_wait_status_ready(struct mtd_info *mtd, unsigned long timeo)
668 register struct nand_chip *chip = mtd_to_nand(mtd);
670 timeo = jiffies + msecs_to_jiffies(timeo);
671 do {
672 if ((chip->read_byte(mtd) & NAND_STATUS_READY))
673 break;
674 touch_softlockup_watchdog();
675 } while (time_before(jiffies, timeo));
679 * nand_command - [DEFAULT] Send command to NAND device
680 * @mtd: MTD device structure
681 * @command: the command to be sent
682 * @column: the column address for this command, -1 if none
683 * @page_addr: the page address for this command, -1 if none
685 * Send command to NAND device. This function is used for small page devices
686 * (512 Bytes per page).
688 static void nand_command(struct mtd_info *mtd, unsigned int command,
689 int column, int page_addr)
691 register struct nand_chip *chip = mtd_to_nand(mtd);
692 int ctrl = NAND_CTRL_CLE | NAND_CTRL_CHANGE;
694 /* Write out the command to the device */
695 if (command == NAND_CMD_SEQIN) {
696 int readcmd;
698 if (column >= mtd->writesize) {
699 /* OOB area */
700 column -= mtd->writesize;
701 readcmd = NAND_CMD_READOOB;
702 } else if (column < 256) {
703 /* First 256 bytes --> READ0 */
704 readcmd = NAND_CMD_READ0;
705 } else {
706 column -= 256;
707 readcmd = NAND_CMD_READ1;
709 chip->cmd_ctrl(mtd, readcmd, ctrl);
710 ctrl &= ~NAND_CTRL_CHANGE;
712 chip->cmd_ctrl(mtd, command, ctrl);
714 /* Address cycle, when necessary */
715 ctrl = NAND_CTRL_ALE | NAND_CTRL_CHANGE;
716 /* Serially input address */
717 if (column != -1) {
718 /* Adjust columns for 16 bit buswidth */
719 if (chip->options & NAND_BUSWIDTH_16 &&
720 !nand_opcode_8bits(command))
721 column >>= 1;
722 chip->cmd_ctrl(mtd, column, ctrl);
723 ctrl &= ~NAND_CTRL_CHANGE;
725 if (page_addr != -1) {
726 chip->cmd_ctrl(mtd, page_addr, ctrl);
727 ctrl &= ~NAND_CTRL_CHANGE;
728 chip->cmd_ctrl(mtd, page_addr >> 8, ctrl);
729 /* One more address cycle for devices > 32MiB */
730 if (chip->chipsize > (32 << 20))
731 chip->cmd_ctrl(mtd, page_addr >> 16, ctrl);
733 chip->cmd_ctrl(mtd, NAND_CMD_NONE, NAND_NCE | NAND_CTRL_CHANGE);
736 * Program and erase have their own busy handlers status and sequential
737 * in needs no delay
739 switch (command) {
741 case NAND_CMD_PAGEPROG:
742 case NAND_CMD_ERASE1:
743 case NAND_CMD_ERASE2:
744 case NAND_CMD_SEQIN:
745 case NAND_CMD_STATUS:
746 return;
748 case NAND_CMD_RESET:
749 if (chip->dev_ready)
750 break;
751 udelay(chip->chip_delay);
752 chip->cmd_ctrl(mtd, NAND_CMD_STATUS,
753 NAND_CTRL_CLE | NAND_CTRL_CHANGE);
754 chip->cmd_ctrl(mtd,
755 NAND_CMD_NONE, NAND_NCE | NAND_CTRL_CHANGE);
756 /* EZ-NAND can take upto 250ms as per ONFi v4.0 */
757 nand_wait_status_ready(mtd, 250);
758 return;
760 /* This applies to read commands */
761 default:
763 * If we don't have access to the busy pin, we apply the given
764 * command delay
766 if (!chip->dev_ready) {
767 udelay(chip->chip_delay);
768 return;
772 * Apply this short delay always to ensure that we do wait tWB in
773 * any case on any machine.
775 ndelay(100);
777 nand_wait_ready(mtd);
781 * nand_command_lp - [DEFAULT] Send command to NAND large page device
782 * @mtd: MTD device structure
783 * @command: the command to be sent
784 * @column: the column address for this command, -1 if none
785 * @page_addr: the page address for this command, -1 if none
787 * Send command to NAND device. This is the version for the new large page
788 * devices. We don't have the separate regions as we have in the small page
789 * devices. We must emulate NAND_CMD_READOOB to keep the code compatible.
791 static void nand_command_lp(struct mtd_info *mtd, unsigned int command,
792 int column, int page_addr)
794 register struct nand_chip *chip = mtd_to_nand(mtd);
796 /* Emulate NAND_CMD_READOOB */
797 if (command == NAND_CMD_READOOB) {
798 column += mtd->writesize;
799 command = NAND_CMD_READ0;
802 /* Command latch cycle */
803 chip->cmd_ctrl(mtd, command, NAND_NCE | NAND_CLE | NAND_CTRL_CHANGE);
805 if (column != -1 || page_addr != -1) {
806 int ctrl = NAND_CTRL_CHANGE | NAND_NCE | NAND_ALE;
808 /* Serially input address */
809 if (column != -1) {
810 /* Adjust columns for 16 bit buswidth */
811 if (chip->options & NAND_BUSWIDTH_16 &&
812 !nand_opcode_8bits(command))
813 column >>= 1;
814 chip->cmd_ctrl(mtd, column, ctrl);
815 ctrl &= ~NAND_CTRL_CHANGE;
817 /* Only output a single addr cycle for 8bits opcodes. */
818 if (!nand_opcode_8bits(command))
819 chip->cmd_ctrl(mtd, column >> 8, ctrl);
821 if (page_addr != -1) {
822 chip->cmd_ctrl(mtd, page_addr, ctrl);
823 chip->cmd_ctrl(mtd, page_addr >> 8,
824 NAND_NCE | NAND_ALE);
825 /* One more address cycle for devices > 128MiB */
826 if (chip->chipsize > (128 << 20))
827 chip->cmd_ctrl(mtd, page_addr >> 16,
828 NAND_NCE | NAND_ALE);
831 chip->cmd_ctrl(mtd, NAND_CMD_NONE, NAND_NCE | NAND_CTRL_CHANGE);
834 * Program and erase have their own busy handlers status, sequential
835 * in and status need no delay.
837 switch (command) {
839 case NAND_CMD_CACHEDPROG:
840 case NAND_CMD_PAGEPROG:
841 case NAND_CMD_ERASE1:
842 case NAND_CMD_ERASE2:
843 case NAND_CMD_SEQIN:
844 case NAND_CMD_RNDIN:
845 case NAND_CMD_STATUS:
846 return;
848 case NAND_CMD_RESET:
849 if (chip->dev_ready)
850 break;
851 udelay(chip->chip_delay);
852 chip->cmd_ctrl(mtd, NAND_CMD_STATUS,
853 NAND_NCE | NAND_CLE | NAND_CTRL_CHANGE);
854 chip->cmd_ctrl(mtd, NAND_CMD_NONE,
855 NAND_NCE | NAND_CTRL_CHANGE);
856 /* EZ-NAND can take upto 250ms as per ONFi v4.0 */
857 nand_wait_status_ready(mtd, 250);
858 return;
860 case NAND_CMD_RNDOUT:
861 /* No ready / busy check necessary */
862 chip->cmd_ctrl(mtd, NAND_CMD_RNDOUTSTART,
863 NAND_NCE | NAND_CLE | NAND_CTRL_CHANGE);
864 chip->cmd_ctrl(mtd, NAND_CMD_NONE,
865 NAND_NCE | NAND_CTRL_CHANGE);
866 return;
868 case NAND_CMD_READ0:
869 chip->cmd_ctrl(mtd, NAND_CMD_READSTART,
870 NAND_NCE | NAND_CLE | NAND_CTRL_CHANGE);
871 chip->cmd_ctrl(mtd, NAND_CMD_NONE,
872 NAND_NCE | NAND_CTRL_CHANGE);
874 /* This applies to read commands */
875 default:
877 * If we don't have access to the busy pin, we apply the given
878 * command delay.
880 if (!chip->dev_ready) {
881 udelay(chip->chip_delay);
882 return;
887 * Apply this short delay always to ensure that we do wait tWB in
888 * any case on any machine.
890 ndelay(100);
892 nand_wait_ready(mtd);
896 * panic_nand_get_device - [GENERIC] Get chip for selected access
897 * @chip: the nand chip descriptor
898 * @mtd: MTD device structure
899 * @new_state: the state which is requested
901 * Used when in panic, no locks are taken.
903 static void panic_nand_get_device(struct nand_chip *chip,
904 struct mtd_info *mtd, int new_state)
906 /* Hardware controller shared among independent devices */
907 chip->controller->active = chip;
908 chip->state = new_state;
912 * nand_get_device - [GENERIC] Get chip for selected access
913 * @mtd: MTD device structure
914 * @new_state: the state which is requested
916 * Get the device and lock it for exclusive access
918 static int
919 nand_get_device(struct mtd_info *mtd, int new_state)
921 struct nand_chip *chip = mtd_to_nand(mtd);
922 spinlock_t *lock = &chip->controller->lock;
923 wait_queue_head_t *wq = &chip->controller->wq;
924 DECLARE_WAITQUEUE(wait, current);
925 retry:
926 spin_lock(lock);
928 /* Hardware controller shared among independent devices */
929 if (!chip->controller->active)
930 chip->controller->active = chip;
932 if (chip->controller->active == chip && chip->state == FL_READY) {
933 chip->state = new_state;
934 spin_unlock(lock);
935 return 0;
937 if (new_state == FL_PM_SUSPENDED) {
938 if (chip->controller->active->state == FL_PM_SUSPENDED) {
939 chip->state = FL_PM_SUSPENDED;
940 spin_unlock(lock);
941 return 0;
944 set_current_state(TASK_UNINTERRUPTIBLE);
945 add_wait_queue(wq, &wait);
946 spin_unlock(lock);
947 schedule();
948 remove_wait_queue(wq, &wait);
949 goto retry;
953 * panic_nand_wait - [GENERIC] wait until the command is done
954 * @mtd: MTD device structure
955 * @chip: NAND chip structure
956 * @timeo: timeout
958 * Wait for command done. This is a helper function for nand_wait used when
959 * we are in interrupt context. May happen when in panic and trying to write
960 * an oops through mtdoops.
962 static void panic_nand_wait(struct mtd_info *mtd, struct nand_chip *chip,
963 unsigned long timeo)
965 int i;
966 for (i = 0; i < timeo; i++) {
967 if (chip->dev_ready) {
968 if (chip->dev_ready(mtd))
969 break;
970 } else {
971 if (chip->read_byte(mtd) & NAND_STATUS_READY)
972 break;
974 mdelay(1);
979 * nand_wait - [DEFAULT] wait until the command is done
980 * @mtd: MTD device structure
981 * @chip: NAND chip structure
983 * Wait for command done. This applies to erase and program only.
985 static int nand_wait(struct mtd_info *mtd, struct nand_chip *chip)
988 int status;
989 unsigned long timeo = 400;
992 * Apply this short delay always to ensure that we do wait tWB in any
993 * case on any machine.
995 ndelay(100);
997 chip->cmdfunc(mtd, NAND_CMD_STATUS, -1, -1);
999 if (in_interrupt() || oops_in_progress)
1000 panic_nand_wait(mtd, chip, timeo);
1001 else {
1002 timeo = jiffies + msecs_to_jiffies(timeo);
1003 do {
1004 if (chip->dev_ready) {
1005 if (chip->dev_ready(mtd))
1006 break;
1007 } else {
1008 if (chip->read_byte(mtd) & NAND_STATUS_READY)
1009 break;
1011 cond_resched();
1012 } while (time_before(jiffies, timeo));
1015 status = (int)chip->read_byte(mtd);
1016 /* This can happen if in case of timeout or buggy dev_ready */
1017 WARN_ON(!(status & NAND_STATUS_READY));
1018 return status;
1022 * nand_reset_data_interface - Reset data interface and timings
1023 * @chip: The NAND chip
1025 * Reset the Data interface and timings to ONFI mode 0.
1027 * Returns 0 for success or negative error code otherwise.
1029 static int nand_reset_data_interface(struct nand_chip *chip)
1031 struct mtd_info *mtd = nand_to_mtd(chip);
1032 const struct nand_data_interface *conf;
1033 int ret;
1035 if (!chip->setup_data_interface)
1036 return 0;
1039 * The ONFI specification says:
1041 * To transition from NV-DDR or NV-DDR2 to the SDR data
1042 * interface, the host shall use the Reset (FFh) command
1043 * using SDR timing mode 0. A device in any timing mode is
1044 * required to recognize Reset (FFh) command issued in SDR
1045 * timing mode 0.
1048 * Configure the data interface in SDR mode and set the
1049 * timings to timing mode 0.
1052 conf = nand_get_default_data_interface();
1053 ret = chip->setup_data_interface(mtd, conf, false);
1054 if (ret)
1055 pr_err("Failed to configure data interface to SDR timing mode 0\n");
1057 return ret;
1061 * nand_setup_data_interface - Setup the best data interface and timings
1062 * @chip: The NAND chip
1064 * Find and configure the best data interface and NAND timings supported by
1065 * the chip and the driver.
1066 * First tries to retrieve supported timing modes from ONFI information,
1067 * and if the NAND chip does not support ONFI, relies on the
1068 * ->onfi_timing_mode_default specified in the nand_ids table.
1070 * Returns 0 for success or negative error code otherwise.
1072 static int nand_setup_data_interface(struct nand_chip *chip)
1074 struct mtd_info *mtd = nand_to_mtd(chip);
1075 int ret;
1077 if (!chip->setup_data_interface || !chip->data_interface)
1078 return 0;
1081 * Ensure the timing mode has been changed on the chip side
1082 * before changing timings on the controller side.
1084 if (chip->onfi_version) {
1085 u8 tmode_param[ONFI_SUBFEATURE_PARAM_LEN] = {
1086 chip->onfi_timing_mode_default,
1089 ret = chip->onfi_set_features(mtd, chip,
1090 ONFI_FEATURE_ADDR_TIMING_MODE,
1091 tmode_param);
1092 if (ret)
1093 goto err;
1096 ret = chip->setup_data_interface(mtd, chip->data_interface, false);
1097 err:
1098 return ret;
1102 * nand_init_data_interface - find the best data interface and timings
1103 * @chip: The NAND chip
1105 * Find the best data interface and NAND timings supported by the chip
1106 * and the driver.
1107 * First tries to retrieve supported timing modes from ONFI information,
1108 * and if the NAND chip does not support ONFI, relies on the
1109 * ->onfi_timing_mode_default specified in the nand_ids table. After this
1110 * function nand_chip->data_interface is initialized with the best timing mode
1111 * available.
1113 * Returns 0 for success or negative error code otherwise.
1115 static int nand_init_data_interface(struct nand_chip *chip)
1117 struct mtd_info *mtd = nand_to_mtd(chip);
1118 int modes, mode, ret;
1120 if (!chip->setup_data_interface)
1121 return 0;
1124 * First try to identify the best timings from ONFI parameters and
1125 * if the NAND does not support ONFI, fallback to the default ONFI
1126 * timing mode.
1128 modes = onfi_get_async_timing_mode(chip);
1129 if (modes == ONFI_TIMING_MODE_UNKNOWN) {
1130 if (!chip->onfi_timing_mode_default)
1131 return 0;
1133 modes = GENMASK(chip->onfi_timing_mode_default, 0);
1136 chip->data_interface = kzalloc(sizeof(*chip->data_interface),
1137 GFP_KERNEL);
1138 if (!chip->data_interface)
1139 return -ENOMEM;
1141 for (mode = fls(modes) - 1; mode >= 0; mode--) {
1142 ret = onfi_init_data_interface(chip, chip->data_interface,
1143 NAND_SDR_IFACE, mode);
1144 if (ret)
1145 continue;
1147 ret = chip->setup_data_interface(mtd, chip->data_interface,
1148 true);
1149 if (!ret) {
1150 chip->onfi_timing_mode_default = mode;
1151 break;
1155 return 0;
1158 static void nand_release_data_interface(struct nand_chip *chip)
1160 kfree(chip->data_interface);
1164 * nand_reset - Reset and initialize a NAND device
1165 * @chip: The NAND chip
1166 * @chipnr: Internal die id
1168 * Returns 0 for success or negative error code otherwise
1170 int nand_reset(struct nand_chip *chip, int chipnr)
1172 struct mtd_info *mtd = nand_to_mtd(chip);
1173 int ret;
1175 ret = nand_reset_data_interface(chip);
1176 if (ret)
1177 return ret;
1180 * The CS line has to be released before we can apply the new NAND
1181 * interface settings, hence this weird ->select_chip() dance.
1183 chip->select_chip(mtd, chipnr);
1184 chip->cmdfunc(mtd, NAND_CMD_RESET, -1, -1);
1185 chip->select_chip(mtd, -1);
1187 chip->select_chip(mtd, chipnr);
1188 ret = nand_setup_data_interface(chip);
1189 chip->select_chip(mtd, -1);
1190 if (ret)
1191 return ret;
1193 return 0;
1197 * __nand_unlock - [REPLACEABLE] unlocks specified locked blocks
1198 * @mtd: mtd info
1199 * @ofs: offset to start unlock from
1200 * @len: length to unlock
1201 * @invert: when = 0, unlock the range of blocks within the lower and
1202 * upper boundary address
1203 * when = 1, unlock the range of blocks outside the boundaries
1204 * of the lower and upper boundary address
1206 * Returs unlock status.
1208 static int __nand_unlock(struct mtd_info *mtd, loff_t ofs,
1209 uint64_t len, int invert)
1211 int ret = 0;
1212 int status, page;
1213 struct nand_chip *chip = mtd_to_nand(mtd);
1215 /* Submit address of first page to unlock */
1216 page = ofs >> chip->page_shift;
1217 chip->cmdfunc(mtd, NAND_CMD_UNLOCK1, -1, page & chip->pagemask);
1219 /* Submit address of last page to unlock */
1220 page = (ofs + len) >> chip->page_shift;
1221 chip->cmdfunc(mtd, NAND_CMD_UNLOCK2, -1,
1222 (page | invert) & chip->pagemask);
1224 /* Call wait ready function */
1225 status = chip->waitfunc(mtd, chip);
1226 /* See if device thinks it succeeded */
1227 if (status & NAND_STATUS_FAIL) {
1228 pr_debug("%s: error status = 0x%08x\n",
1229 __func__, status);
1230 ret = -EIO;
1233 return ret;
1237 * nand_unlock - [REPLACEABLE] unlocks specified locked blocks
1238 * @mtd: mtd info
1239 * @ofs: offset to start unlock from
1240 * @len: length to unlock
1242 * Returns unlock status.
1244 int nand_unlock(struct mtd_info *mtd, loff_t ofs, uint64_t len)
1246 int ret = 0;
1247 int chipnr;
1248 struct nand_chip *chip = mtd_to_nand(mtd);
1250 pr_debug("%s: start = 0x%012llx, len = %llu\n",
1251 __func__, (unsigned long long)ofs, len);
1253 if (check_offs_len(mtd, ofs, len))
1254 return -EINVAL;
1256 /* Align to last block address if size addresses end of the device */
1257 if (ofs + len == mtd->size)
1258 len -= mtd->erasesize;
1260 nand_get_device(mtd, FL_UNLOCKING);
1262 /* Shift to get chip number */
1263 chipnr = ofs >> chip->chip_shift;
1266 * Reset the chip.
1267 * If we want to check the WP through READ STATUS and check the bit 7
1268 * we must reset the chip
1269 * some operation can also clear the bit 7 of status register
1270 * eg. erase/program a locked block
1272 nand_reset(chip, chipnr);
1274 chip->select_chip(mtd, chipnr);
1276 /* Check, if it is write protected */
1277 if (nand_check_wp(mtd)) {
1278 pr_debug("%s: device is write protected!\n",
1279 __func__);
1280 ret = -EIO;
1281 goto out;
1284 ret = __nand_unlock(mtd, ofs, len, 0);
1286 out:
1287 chip->select_chip(mtd, -1);
1288 nand_release_device(mtd);
1290 return ret;
1292 EXPORT_SYMBOL(nand_unlock);
1295 * nand_lock - [REPLACEABLE] locks all blocks present in the device
1296 * @mtd: mtd info
1297 * @ofs: offset to start unlock from
1298 * @len: length to unlock
1300 * This feature is not supported in many NAND parts. 'Micron' NAND parts do
1301 * have this feature, but it allows only to lock all blocks, not for specified
1302 * range for block. Implementing 'lock' feature by making use of 'unlock', for
1303 * now.
1305 * Returns lock status.
1307 int nand_lock(struct mtd_info *mtd, loff_t ofs, uint64_t len)
1309 int ret = 0;
1310 int chipnr, status, page;
1311 struct nand_chip *chip = mtd_to_nand(mtd);
1313 pr_debug("%s: start = 0x%012llx, len = %llu\n",
1314 __func__, (unsigned long long)ofs, len);
1316 if (check_offs_len(mtd, ofs, len))
1317 return -EINVAL;
1319 nand_get_device(mtd, FL_LOCKING);
1321 /* Shift to get chip number */
1322 chipnr = ofs >> chip->chip_shift;
1325 * Reset the chip.
1326 * If we want to check the WP through READ STATUS and check the bit 7
1327 * we must reset the chip
1328 * some operation can also clear the bit 7 of status register
1329 * eg. erase/program a locked block
1331 nand_reset(chip, chipnr);
1333 chip->select_chip(mtd, chipnr);
1335 /* Check, if it is write protected */
1336 if (nand_check_wp(mtd)) {
1337 pr_debug("%s: device is write protected!\n",
1338 __func__);
1339 status = MTD_ERASE_FAILED;
1340 ret = -EIO;
1341 goto out;
1344 /* Submit address of first page to lock */
1345 page = ofs >> chip->page_shift;
1346 chip->cmdfunc(mtd, NAND_CMD_LOCK, -1, page & chip->pagemask);
1348 /* Call wait ready function */
1349 status = chip->waitfunc(mtd, chip);
1350 /* See if device thinks it succeeded */
1351 if (status & NAND_STATUS_FAIL) {
1352 pr_debug("%s: error status = 0x%08x\n",
1353 __func__, status);
1354 ret = -EIO;
1355 goto out;
1358 ret = __nand_unlock(mtd, ofs, len, 0x1);
1360 out:
1361 chip->select_chip(mtd, -1);
1362 nand_release_device(mtd);
1364 return ret;
1366 EXPORT_SYMBOL(nand_lock);
1369 * nand_check_erased_buf - check if a buffer contains (almost) only 0xff data
1370 * @buf: buffer to test
1371 * @len: buffer length
1372 * @bitflips_threshold: maximum number of bitflips
1374 * Check if a buffer contains only 0xff, which means the underlying region
1375 * has been erased and is ready to be programmed.
1376 * The bitflips_threshold specify the maximum number of bitflips before
1377 * considering the region is not erased.
1378 * Note: The logic of this function has been extracted from the memweight
1379 * implementation, except that nand_check_erased_buf function exit before
1380 * testing the whole buffer if the number of bitflips exceed the
1381 * bitflips_threshold value.
1383 * Returns a positive number of bitflips less than or equal to
1384 * bitflips_threshold, or -ERROR_CODE for bitflips in excess of the
1385 * threshold.
1387 static int nand_check_erased_buf(void *buf, int len, int bitflips_threshold)
1389 const unsigned char *bitmap = buf;
1390 int bitflips = 0;
1391 int weight;
1393 for (; len && ((uintptr_t)bitmap) % sizeof(long);
1394 len--, bitmap++) {
1395 weight = hweight8(*bitmap);
1396 bitflips += BITS_PER_BYTE - weight;
1397 if (unlikely(bitflips > bitflips_threshold))
1398 return -EBADMSG;
1401 for (; len >= sizeof(long);
1402 len -= sizeof(long), bitmap += sizeof(long)) {
1403 weight = hweight_long(*((unsigned long *)bitmap));
1404 bitflips += BITS_PER_LONG - weight;
1405 if (unlikely(bitflips > bitflips_threshold))
1406 return -EBADMSG;
1409 for (; len > 0; len--, bitmap++) {
1410 weight = hweight8(*bitmap);
1411 bitflips += BITS_PER_BYTE - weight;
1412 if (unlikely(bitflips > bitflips_threshold))
1413 return -EBADMSG;
1416 return bitflips;
1420 * nand_check_erased_ecc_chunk - check if an ECC chunk contains (almost) only
1421 * 0xff data
1422 * @data: data buffer to test
1423 * @datalen: data length
1424 * @ecc: ECC buffer
1425 * @ecclen: ECC length
1426 * @extraoob: extra OOB buffer
1427 * @extraooblen: extra OOB length
1428 * @bitflips_threshold: maximum number of bitflips
1430 * Check if a data buffer and its associated ECC and OOB data contains only
1431 * 0xff pattern, which means the underlying region has been erased and is
1432 * ready to be programmed.
1433 * The bitflips_threshold specify the maximum number of bitflips before
1434 * considering the region as not erased.
1436 * Note:
1437 * 1/ ECC algorithms are working on pre-defined block sizes which are usually
1438 * different from the NAND page size. When fixing bitflips, ECC engines will
1439 * report the number of errors per chunk, and the NAND core infrastructure
1440 * expect you to return the maximum number of bitflips for the whole page.
1441 * This is why you should always use this function on a single chunk and
1442 * not on the whole page. After checking each chunk you should update your
1443 * max_bitflips value accordingly.
1444 * 2/ When checking for bitflips in erased pages you should not only check
1445 * the payload data but also their associated ECC data, because a user might
1446 * have programmed almost all bits to 1 but a few. In this case, we
1447 * shouldn't consider the chunk as erased, and checking ECC bytes prevent
1448 * this case.
1449 * 3/ The extraoob argument is optional, and should be used if some of your OOB
1450 * data are protected by the ECC engine.
1451 * It could also be used if you support subpages and want to attach some
1452 * extra OOB data to an ECC chunk.
1454 * Returns a positive number of bitflips less than or equal to
1455 * bitflips_threshold, or -ERROR_CODE for bitflips in excess of the
1456 * threshold. In case of success, the passed buffers are filled with 0xff.
1458 int nand_check_erased_ecc_chunk(void *data, int datalen,
1459 void *ecc, int ecclen,
1460 void *extraoob, int extraooblen,
1461 int bitflips_threshold)
1463 int data_bitflips = 0, ecc_bitflips = 0, extraoob_bitflips = 0;
1465 data_bitflips = nand_check_erased_buf(data, datalen,
1466 bitflips_threshold);
1467 if (data_bitflips < 0)
1468 return data_bitflips;
1470 bitflips_threshold -= data_bitflips;
1472 ecc_bitflips = nand_check_erased_buf(ecc, ecclen, bitflips_threshold);
1473 if (ecc_bitflips < 0)
1474 return ecc_bitflips;
1476 bitflips_threshold -= ecc_bitflips;
1478 extraoob_bitflips = nand_check_erased_buf(extraoob, extraooblen,
1479 bitflips_threshold);
1480 if (extraoob_bitflips < 0)
1481 return extraoob_bitflips;
1483 if (data_bitflips)
1484 memset(data, 0xff, datalen);
1486 if (ecc_bitflips)
1487 memset(ecc, 0xff, ecclen);
1489 if (extraoob_bitflips)
1490 memset(extraoob, 0xff, extraooblen);
1492 return data_bitflips + ecc_bitflips + extraoob_bitflips;
1494 EXPORT_SYMBOL(nand_check_erased_ecc_chunk);
1497 * nand_read_page_raw - [INTERN] read raw page data without ecc
1498 * @mtd: mtd info structure
1499 * @chip: nand chip info structure
1500 * @buf: buffer to store read data
1501 * @oob_required: caller requires OOB data read to chip->oob_poi
1502 * @page: page number to read
1504 * Not for syndrome calculating ECC controllers, which use a special oob layout.
1506 static int nand_read_page_raw(struct mtd_info *mtd, struct nand_chip *chip,
1507 uint8_t *buf, int oob_required, int page)
1509 chip->read_buf(mtd, buf, mtd->writesize);
1510 if (oob_required)
1511 chip->read_buf(mtd, chip->oob_poi, mtd->oobsize);
1512 return 0;
1516 * nand_read_page_raw_syndrome - [INTERN] read raw page data without ecc
1517 * @mtd: mtd info structure
1518 * @chip: nand chip info structure
1519 * @buf: buffer to store read data
1520 * @oob_required: caller requires OOB data read to chip->oob_poi
1521 * @page: page number to read
1523 * We need a special oob layout and handling even when OOB isn't used.
1525 static int nand_read_page_raw_syndrome(struct mtd_info *mtd,
1526 struct nand_chip *chip, uint8_t *buf,
1527 int oob_required, int page)
1529 int eccsize = chip->ecc.size;
1530 int eccbytes = chip->ecc.bytes;
1531 uint8_t *oob = chip->oob_poi;
1532 int steps, size;
1534 for (steps = chip->ecc.steps; steps > 0; steps--) {
1535 chip->read_buf(mtd, buf, eccsize);
1536 buf += eccsize;
1538 if (chip->ecc.prepad) {
1539 chip->read_buf(mtd, oob, chip->ecc.prepad);
1540 oob += chip->ecc.prepad;
1543 chip->read_buf(mtd, oob, eccbytes);
1544 oob += eccbytes;
1546 if (chip->ecc.postpad) {
1547 chip->read_buf(mtd, oob, chip->ecc.postpad);
1548 oob += chip->ecc.postpad;
1552 size = mtd->oobsize - (oob - chip->oob_poi);
1553 if (size)
1554 chip->read_buf(mtd, oob, size);
1556 return 0;
1560 * nand_read_page_swecc - [REPLACEABLE] software ECC based page read function
1561 * @mtd: mtd info structure
1562 * @chip: nand chip info structure
1563 * @buf: buffer to store read data
1564 * @oob_required: caller requires OOB data read to chip->oob_poi
1565 * @page: page number to read
1567 static int nand_read_page_swecc(struct mtd_info *mtd, struct nand_chip *chip,
1568 uint8_t *buf, int oob_required, int page)
1570 int i, eccsize = chip->ecc.size, ret;
1571 int eccbytes = chip->ecc.bytes;
1572 int eccsteps = chip->ecc.steps;
1573 uint8_t *p = buf;
1574 uint8_t *ecc_calc = chip->buffers->ecccalc;
1575 uint8_t *ecc_code = chip->buffers->ecccode;
1576 unsigned int max_bitflips = 0;
1578 chip->ecc.read_page_raw(mtd, chip, buf, 1, page);
1580 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize)
1581 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
1583 ret = mtd_ooblayout_get_eccbytes(mtd, ecc_code, chip->oob_poi, 0,
1584 chip->ecc.total);
1585 if (ret)
1586 return ret;
1588 eccsteps = chip->ecc.steps;
1589 p = buf;
1591 for (i = 0 ; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
1592 int stat;
1594 stat = chip->ecc.correct(mtd, p, &ecc_code[i], &ecc_calc[i]);
1595 if (stat < 0) {
1596 mtd->ecc_stats.failed++;
1597 } else {
1598 mtd->ecc_stats.corrected += stat;
1599 max_bitflips = max_t(unsigned int, max_bitflips, stat);
1602 return max_bitflips;
1606 * nand_read_subpage - [REPLACEABLE] ECC based sub-page read function
1607 * @mtd: mtd info structure
1608 * @chip: nand chip info structure
1609 * @data_offs: offset of requested data within the page
1610 * @readlen: data length
1611 * @bufpoi: buffer to store read data
1612 * @page: page number to read
1614 static int nand_read_subpage(struct mtd_info *mtd, struct nand_chip *chip,
1615 uint32_t data_offs, uint32_t readlen, uint8_t *bufpoi,
1616 int page)
1618 int start_step, end_step, num_steps, ret;
1619 uint8_t *p;
1620 int data_col_addr, i, gaps = 0;
1621 int datafrag_len, eccfrag_len, aligned_len, aligned_pos;
1622 int busw = (chip->options & NAND_BUSWIDTH_16) ? 2 : 1;
1623 int index, section = 0;
1624 unsigned int max_bitflips = 0;
1625 struct mtd_oob_region oobregion = { };
1627 /* Column address within the page aligned to ECC size (256bytes) */
1628 start_step = data_offs / chip->ecc.size;
1629 end_step = (data_offs + readlen - 1) / chip->ecc.size;
1630 num_steps = end_step - start_step + 1;
1631 index = start_step * chip->ecc.bytes;
1633 /* Data size aligned to ECC ecc.size */
1634 datafrag_len = num_steps * chip->ecc.size;
1635 eccfrag_len = num_steps * chip->ecc.bytes;
1637 data_col_addr = start_step * chip->ecc.size;
1638 /* If we read not a page aligned data */
1639 if (data_col_addr != 0)
1640 chip->cmdfunc(mtd, NAND_CMD_RNDOUT, data_col_addr, -1);
1642 p = bufpoi + data_col_addr;
1643 chip->read_buf(mtd, p, datafrag_len);
1645 /* Calculate ECC */
1646 for (i = 0; i < eccfrag_len ; i += chip->ecc.bytes, p += chip->ecc.size)
1647 chip->ecc.calculate(mtd, p, &chip->buffers->ecccalc[i]);
1650 * The performance is faster if we position offsets according to
1651 * ecc.pos. Let's make sure that there are no gaps in ECC positions.
1653 ret = mtd_ooblayout_find_eccregion(mtd, index, &section, &oobregion);
1654 if (ret)
1655 return ret;
1657 if (oobregion.length < eccfrag_len)
1658 gaps = 1;
1660 if (gaps) {
1661 chip->cmdfunc(mtd, NAND_CMD_RNDOUT, mtd->writesize, -1);
1662 chip->read_buf(mtd, chip->oob_poi, mtd->oobsize);
1663 } else {
1665 * Send the command to read the particular ECC bytes take care
1666 * about buswidth alignment in read_buf.
1668 aligned_pos = oobregion.offset & ~(busw - 1);
1669 aligned_len = eccfrag_len;
1670 if (oobregion.offset & (busw - 1))
1671 aligned_len++;
1672 if ((oobregion.offset + (num_steps * chip->ecc.bytes)) &
1673 (busw - 1))
1674 aligned_len++;
1676 chip->cmdfunc(mtd, NAND_CMD_RNDOUT,
1677 mtd->writesize + aligned_pos, -1);
1678 chip->read_buf(mtd, &chip->oob_poi[aligned_pos], aligned_len);
1681 ret = mtd_ooblayout_get_eccbytes(mtd, chip->buffers->ecccode,
1682 chip->oob_poi, index, eccfrag_len);
1683 if (ret)
1684 return ret;
1686 p = bufpoi + data_col_addr;
1687 for (i = 0; i < eccfrag_len ; i += chip->ecc.bytes, p += chip->ecc.size) {
1688 int stat;
1690 stat = chip->ecc.correct(mtd, p,
1691 &chip->buffers->ecccode[i], &chip->buffers->ecccalc[i]);
1692 if (stat == -EBADMSG &&
1693 (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
1694 /* check for empty pages with bitflips */
1695 stat = nand_check_erased_ecc_chunk(p, chip->ecc.size,
1696 &chip->buffers->ecccode[i],
1697 chip->ecc.bytes,
1698 NULL, 0,
1699 chip->ecc.strength);
1702 if (stat < 0) {
1703 mtd->ecc_stats.failed++;
1704 } else {
1705 mtd->ecc_stats.corrected += stat;
1706 max_bitflips = max_t(unsigned int, max_bitflips, stat);
1709 return max_bitflips;
1713 * nand_read_page_hwecc - [REPLACEABLE] hardware ECC based page read function
1714 * @mtd: mtd info structure
1715 * @chip: nand chip info structure
1716 * @buf: buffer to store read data
1717 * @oob_required: caller requires OOB data read to chip->oob_poi
1718 * @page: page number to read
1720 * Not for syndrome calculating ECC controllers which need a special oob layout.
1722 static int nand_read_page_hwecc(struct mtd_info *mtd, struct nand_chip *chip,
1723 uint8_t *buf, int oob_required, int page)
1725 int i, eccsize = chip->ecc.size, ret;
1726 int eccbytes = chip->ecc.bytes;
1727 int eccsteps = chip->ecc.steps;
1728 uint8_t *p = buf;
1729 uint8_t *ecc_calc = chip->buffers->ecccalc;
1730 uint8_t *ecc_code = chip->buffers->ecccode;
1731 unsigned int max_bitflips = 0;
1733 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
1734 chip->ecc.hwctl(mtd, NAND_ECC_READ);
1735 chip->read_buf(mtd, p, eccsize);
1736 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
1738 chip->read_buf(mtd, chip->oob_poi, mtd->oobsize);
1740 ret = mtd_ooblayout_get_eccbytes(mtd, ecc_code, chip->oob_poi, 0,
1741 chip->ecc.total);
1742 if (ret)
1743 return ret;
1745 eccsteps = chip->ecc.steps;
1746 p = buf;
1748 for (i = 0 ; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
1749 int stat;
1751 stat = chip->ecc.correct(mtd, p, &ecc_code[i], &ecc_calc[i]);
1752 if (stat == -EBADMSG &&
1753 (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
1754 /* check for empty pages with bitflips */
1755 stat = nand_check_erased_ecc_chunk(p, eccsize,
1756 &ecc_code[i], eccbytes,
1757 NULL, 0,
1758 chip->ecc.strength);
1761 if (stat < 0) {
1762 mtd->ecc_stats.failed++;
1763 } else {
1764 mtd->ecc_stats.corrected += stat;
1765 max_bitflips = max_t(unsigned int, max_bitflips, stat);
1768 return max_bitflips;
1772 * nand_read_page_hwecc_oob_first - [REPLACEABLE] hw ecc, read oob first
1773 * @mtd: mtd info structure
1774 * @chip: nand chip info structure
1775 * @buf: buffer to store read data
1776 * @oob_required: caller requires OOB data read to chip->oob_poi
1777 * @page: page number to read
1779 * Hardware ECC for large page chips, require OOB to be read first. For this
1780 * ECC mode, the write_page method is re-used from ECC_HW. These methods
1781 * read/write ECC from the OOB area, unlike the ECC_HW_SYNDROME support with
1782 * multiple ECC steps, follows the "infix ECC" scheme and reads/writes ECC from
1783 * the data area, by overwriting the NAND manufacturer bad block markings.
1785 static int nand_read_page_hwecc_oob_first(struct mtd_info *mtd,
1786 struct nand_chip *chip, uint8_t *buf, int oob_required, int page)
1788 int i, eccsize = chip->ecc.size, ret;
1789 int eccbytes = chip->ecc.bytes;
1790 int eccsteps = chip->ecc.steps;
1791 uint8_t *p = buf;
1792 uint8_t *ecc_code = chip->buffers->ecccode;
1793 uint8_t *ecc_calc = chip->buffers->ecccalc;
1794 unsigned int max_bitflips = 0;
1796 /* Read the OOB area first */
1797 chip->cmdfunc(mtd, NAND_CMD_READOOB, 0, page);
1798 chip->read_buf(mtd, chip->oob_poi, mtd->oobsize);
1799 chip->cmdfunc(mtd, NAND_CMD_READ0, 0, page);
1801 ret = mtd_ooblayout_get_eccbytes(mtd, ecc_code, chip->oob_poi, 0,
1802 chip->ecc.total);
1803 if (ret)
1804 return ret;
1806 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
1807 int stat;
1809 chip->ecc.hwctl(mtd, NAND_ECC_READ);
1810 chip->read_buf(mtd, p, eccsize);
1811 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
1813 stat = chip->ecc.correct(mtd, p, &ecc_code[i], NULL);
1814 if (stat == -EBADMSG &&
1815 (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
1816 /* check for empty pages with bitflips */
1817 stat = nand_check_erased_ecc_chunk(p, eccsize,
1818 &ecc_code[i], eccbytes,
1819 NULL, 0,
1820 chip->ecc.strength);
1823 if (stat < 0) {
1824 mtd->ecc_stats.failed++;
1825 } else {
1826 mtd->ecc_stats.corrected += stat;
1827 max_bitflips = max_t(unsigned int, max_bitflips, stat);
1830 return max_bitflips;
1834 * nand_read_page_syndrome - [REPLACEABLE] hardware ECC syndrome based page read
1835 * @mtd: mtd info structure
1836 * @chip: nand chip info structure
1837 * @buf: buffer to store read data
1838 * @oob_required: caller requires OOB data read to chip->oob_poi
1839 * @page: page number to read
1841 * The hw generator calculates the error syndrome automatically. Therefore we
1842 * need a special oob layout and handling.
1844 static int nand_read_page_syndrome(struct mtd_info *mtd, struct nand_chip *chip,
1845 uint8_t *buf, int oob_required, int page)
1847 int i, eccsize = chip->ecc.size;
1848 int eccbytes = chip->ecc.bytes;
1849 int eccsteps = chip->ecc.steps;
1850 int eccpadbytes = eccbytes + chip->ecc.prepad + chip->ecc.postpad;
1851 uint8_t *p = buf;
1852 uint8_t *oob = chip->oob_poi;
1853 unsigned int max_bitflips = 0;
1855 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
1856 int stat;
1858 chip->ecc.hwctl(mtd, NAND_ECC_READ);
1859 chip->read_buf(mtd, p, eccsize);
1861 if (chip->ecc.prepad) {
1862 chip->read_buf(mtd, oob, chip->ecc.prepad);
1863 oob += chip->ecc.prepad;
1866 chip->ecc.hwctl(mtd, NAND_ECC_READSYN);
1867 chip->read_buf(mtd, oob, eccbytes);
1868 stat = chip->ecc.correct(mtd, p, oob, NULL);
1870 oob += eccbytes;
1872 if (chip->ecc.postpad) {
1873 chip->read_buf(mtd, oob, chip->ecc.postpad);
1874 oob += chip->ecc.postpad;
1877 if (stat == -EBADMSG &&
1878 (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
1879 /* check for empty pages with bitflips */
1880 stat = nand_check_erased_ecc_chunk(p, chip->ecc.size,
1881 oob - eccpadbytes,
1882 eccpadbytes,
1883 NULL, 0,
1884 chip->ecc.strength);
1887 if (stat < 0) {
1888 mtd->ecc_stats.failed++;
1889 } else {
1890 mtd->ecc_stats.corrected += stat;
1891 max_bitflips = max_t(unsigned int, max_bitflips, stat);
1895 /* Calculate remaining oob bytes */
1896 i = mtd->oobsize - (oob - chip->oob_poi);
1897 if (i)
1898 chip->read_buf(mtd, oob, i);
1900 return max_bitflips;
1904 * nand_transfer_oob - [INTERN] Transfer oob to client buffer
1905 * @mtd: mtd info structure
1906 * @oob: oob destination address
1907 * @ops: oob ops structure
1908 * @len: size of oob to transfer
1910 static uint8_t *nand_transfer_oob(struct mtd_info *mtd, uint8_t *oob,
1911 struct mtd_oob_ops *ops, size_t len)
1913 struct nand_chip *chip = mtd_to_nand(mtd);
1914 int ret;
1916 switch (ops->mode) {
1918 case MTD_OPS_PLACE_OOB:
1919 case MTD_OPS_RAW:
1920 memcpy(oob, chip->oob_poi + ops->ooboffs, len);
1921 return oob + len;
1923 case MTD_OPS_AUTO_OOB:
1924 ret = mtd_ooblayout_get_databytes(mtd, oob, chip->oob_poi,
1925 ops->ooboffs, len);
1926 BUG_ON(ret);
1927 return oob + len;
1929 default:
1930 BUG();
1932 return NULL;
1936 * nand_setup_read_retry - [INTERN] Set the READ RETRY mode
1937 * @mtd: MTD device structure
1938 * @retry_mode: the retry mode to use
1940 * Some vendors supply a special command to shift the Vt threshold, to be used
1941 * when there are too many bitflips in a page (i.e., ECC error). After setting
1942 * a new threshold, the host should retry reading the page.
1944 static int nand_setup_read_retry(struct mtd_info *mtd, int retry_mode)
1946 struct nand_chip *chip = mtd_to_nand(mtd);
1948 pr_debug("setting READ RETRY mode %d\n", retry_mode);
1950 if (retry_mode >= chip->read_retries)
1951 return -EINVAL;
1953 if (!chip->setup_read_retry)
1954 return -EOPNOTSUPP;
1956 return chip->setup_read_retry(mtd, retry_mode);
1960 * nand_do_read_ops - [INTERN] Read data with ECC
1961 * @mtd: MTD device structure
1962 * @from: offset to read from
1963 * @ops: oob ops structure
1965 * Internal function. Called with chip held.
1967 static int nand_do_read_ops(struct mtd_info *mtd, loff_t from,
1968 struct mtd_oob_ops *ops)
1970 int chipnr, page, realpage, col, bytes, aligned, oob_required;
1971 struct nand_chip *chip = mtd_to_nand(mtd);
1972 int ret = 0;
1973 uint32_t readlen = ops->len;
1974 uint32_t oobreadlen = ops->ooblen;
1975 uint32_t max_oobsize = mtd_oobavail(mtd, ops);
1977 uint8_t *bufpoi, *oob, *buf;
1978 int use_bufpoi;
1979 unsigned int max_bitflips = 0;
1980 int retry_mode = 0;
1981 bool ecc_fail = false;
1983 chipnr = (int)(from >> chip->chip_shift);
1984 chip->select_chip(mtd, chipnr);
1986 realpage = (int)(from >> chip->page_shift);
1987 page = realpage & chip->pagemask;
1989 col = (int)(from & (mtd->writesize - 1));
1991 buf = ops->datbuf;
1992 oob = ops->oobbuf;
1993 oob_required = oob ? 1 : 0;
1995 while (1) {
1996 unsigned int ecc_failures = mtd->ecc_stats.failed;
1998 bytes = min(mtd->writesize - col, readlen);
1999 aligned = (bytes == mtd->writesize);
2001 if (!aligned)
2002 use_bufpoi = 1;
2003 else if (chip->options & NAND_USE_BOUNCE_BUFFER)
2004 use_bufpoi = !virt_addr_valid(buf);
2005 else
2006 use_bufpoi = 0;
2008 /* Is the current page in the buffer? */
2009 if (realpage != chip->pagebuf || oob) {
2010 bufpoi = use_bufpoi ? chip->buffers->databuf : buf;
2012 if (use_bufpoi && aligned)
2013 pr_debug("%s: using read bounce buffer for buf@%p\n",
2014 __func__, buf);
2016 read_retry:
2017 chip->cmdfunc(mtd, NAND_CMD_READ0, 0x00, page);
2020 * Now read the page into the buffer. Absent an error,
2021 * the read methods return max bitflips per ecc step.
2023 if (unlikely(ops->mode == MTD_OPS_RAW))
2024 ret = chip->ecc.read_page_raw(mtd, chip, bufpoi,
2025 oob_required,
2026 page);
2027 else if (!aligned && NAND_HAS_SUBPAGE_READ(chip) &&
2028 !oob)
2029 ret = chip->ecc.read_subpage(mtd, chip,
2030 col, bytes, bufpoi,
2031 page);
2032 else
2033 ret = chip->ecc.read_page(mtd, chip, bufpoi,
2034 oob_required, page);
2035 if (ret < 0) {
2036 if (use_bufpoi)
2037 /* Invalidate page cache */
2038 chip->pagebuf = -1;
2039 break;
2042 max_bitflips = max_t(unsigned int, max_bitflips, ret);
2044 /* Transfer not aligned data */
2045 if (use_bufpoi) {
2046 if (!NAND_HAS_SUBPAGE_READ(chip) && !oob &&
2047 !(mtd->ecc_stats.failed - ecc_failures) &&
2048 (ops->mode != MTD_OPS_RAW)) {
2049 chip->pagebuf = realpage;
2050 chip->pagebuf_bitflips = ret;
2051 } else {
2052 /* Invalidate page cache */
2053 chip->pagebuf = -1;
2055 memcpy(buf, chip->buffers->databuf + col, bytes);
2058 if (unlikely(oob)) {
2059 int toread = min(oobreadlen, max_oobsize);
2061 if (toread) {
2062 oob = nand_transfer_oob(mtd,
2063 oob, ops, toread);
2064 oobreadlen -= toread;
2068 if (chip->options & NAND_NEED_READRDY) {
2069 /* Apply delay or wait for ready/busy pin */
2070 if (!chip->dev_ready)
2071 udelay(chip->chip_delay);
2072 else
2073 nand_wait_ready(mtd);
2076 if (mtd->ecc_stats.failed - ecc_failures) {
2077 if (retry_mode + 1 < chip->read_retries) {
2078 retry_mode++;
2079 ret = nand_setup_read_retry(mtd,
2080 retry_mode);
2081 if (ret < 0)
2082 break;
2084 /* Reset failures; retry */
2085 mtd->ecc_stats.failed = ecc_failures;
2086 goto read_retry;
2087 } else {
2088 /* No more retry modes; real failure */
2089 ecc_fail = true;
2093 buf += bytes;
2094 } else {
2095 memcpy(buf, chip->buffers->databuf + col, bytes);
2096 buf += bytes;
2097 max_bitflips = max_t(unsigned int, max_bitflips,
2098 chip->pagebuf_bitflips);
2101 readlen -= bytes;
2103 /* Reset to retry mode 0 */
2104 if (retry_mode) {
2105 ret = nand_setup_read_retry(mtd, 0);
2106 if (ret < 0)
2107 break;
2108 retry_mode = 0;
2111 if (!readlen)
2112 break;
2114 /* For subsequent reads align to page boundary */
2115 col = 0;
2116 /* Increment page address */
2117 realpage++;
2119 page = realpage & chip->pagemask;
2120 /* Check, if we cross a chip boundary */
2121 if (!page) {
2122 chipnr++;
2123 chip->select_chip(mtd, -1);
2124 chip->select_chip(mtd, chipnr);
2127 chip->select_chip(mtd, -1);
2129 ops->retlen = ops->len - (size_t) readlen;
2130 if (oob)
2131 ops->oobretlen = ops->ooblen - oobreadlen;
2133 if (ret < 0)
2134 return ret;
2136 if (ecc_fail)
2137 return -EBADMSG;
2139 return max_bitflips;
2143 * nand_read - [MTD Interface] MTD compatibility function for nand_do_read_ecc
2144 * @mtd: MTD device structure
2145 * @from: offset to read from
2146 * @len: number of bytes to read
2147 * @retlen: pointer to variable to store the number of read bytes
2148 * @buf: the databuffer to put data
2150 * Get hold of the chip and call nand_do_read.
2152 static int nand_read(struct mtd_info *mtd, loff_t from, size_t len,
2153 size_t *retlen, uint8_t *buf)
2155 struct mtd_oob_ops ops;
2156 int ret;
2158 nand_get_device(mtd, FL_READING);
2159 memset(&ops, 0, sizeof(ops));
2160 ops.len = len;
2161 ops.datbuf = buf;
2162 ops.mode = MTD_OPS_PLACE_OOB;
2163 ret = nand_do_read_ops(mtd, from, &ops);
2164 *retlen = ops.retlen;
2165 nand_release_device(mtd);
2166 return ret;
2170 * nand_read_oob_std - [REPLACEABLE] the most common OOB data read function
2171 * @mtd: mtd info structure
2172 * @chip: nand chip info structure
2173 * @page: page number to read
2175 int nand_read_oob_std(struct mtd_info *mtd, struct nand_chip *chip, int page)
2177 chip->cmdfunc(mtd, NAND_CMD_READOOB, 0, page);
2178 chip->read_buf(mtd, chip->oob_poi, mtd->oobsize);
2179 return 0;
2181 EXPORT_SYMBOL(nand_read_oob_std);
2184 * nand_read_oob_syndrome - [REPLACEABLE] OOB data read function for HW ECC
2185 * with syndromes
2186 * @mtd: mtd info structure
2187 * @chip: nand chip info structure
2188 * @page: page number to read
2190 int nand_read_oob_syndrome(struct mtd_info *mtd, struct nand_chip *chip,
2191 int page)
2193 int length = mtd->oobsize;
2194 int chunk = chip->ecc.bytes + chip->ecc.prepad + chip->ecc.postpad;
2195 int eccsize = chip->ecc.size;
2196 uint8_t *bufpoi = chip->oob_poi;
2197 int i, toread, sndrnd = 0, pos;
2199 chip->cmdfunc(mtd, NAND_CMD_READ0, chip->ecc.size, page);
2200 for (i = 0; i < chip->ecc.steps; i++) {
2201 if (sndrnd) {
2202 pos = eccsize + i * (eccsize + chunk);
2203 if (mtd->writesize > 512)
2204 chip->cmdfunc(mtd, NAND_CMD_RNDOUT, pos, -1);
2205 else
2206 chip->cmdfunc(mtd, NAND_CMD_READ0, pos, page);
2207 } else
2208 sndrnd = 1;
2209 toread = min_t(int, length, chunk);
2210 chip->read_buf(mtd, bufpoi, toread);
2211 bufpoi += toread;
2212 length -= toread;
2214 if (length > 0)
2215 chip->read_buf(mtd, bufpoi, length);
2217 return 0;
2219 EXPORT_SYMBOL(nand_read_oob_syndrome);
2222 * nand_write_oob_std - [REPLACEABLE] the most common OOB data write function
2223 * @mtd: mtd info structure
2224 * @chip: nand chip info structure
2225 * @page: page number to write
2227 int nand_write_oob_std(struct mtd_info *mtd, struct nand_chip *chip, int page)
2229 int status = 0;
2230 const uint8_t *buf = chip->oob_poi;
2231 int length = mtd->oobsize;
2233 chip->cmdfunc(mtd, NAND_CMD_SEQIN, mtd->writesize, page);
2234 chip->write_buf(mtd, buf, length);
2235 /* Send command to program the OOB data */
2236 chip->cmdfunc(mtd, NAND_CMD_PAGEPROG, -1, -1);
2238 status = chip->waitfunc(mtd, chip);
2240 return status & NAND_STATUS_FAIL ? -EIO : 0;
2242 EXPORT_SYMBOL(nand_write_oob_std);
2245 * nand_write_oob_syndrome - [REPLACEABLE] OOB data write function for HW ECC
2246 * with syndrome - only for large page flash
2247 * @mtd: mtd info structure
2248 * @chip: nand chip info structure
2249 * @page: page number to write
2251 int nand_write_oob_syndrome(struct mtd_info *mtd, struct nand_chip *chip,
2252 int page)
2254 int chunk = chip->ecc.bytes + chip->ecc.prepad + chip->ecc.postpad;
2255 int eccsize = chip->ecc.size, length = mtd->oobsize;
2256 int i, len, pos, status = 0, sndcmd = 0, steps = chip->ecc.steps;
2257 const uint8_t *bufpoi = chip->oob_poi;
2260 * data-ecc-data-ecc ... ecc-oob
2261 * or
2262 * data-pad-ecc-pad-data-pad .... ecc-pad-oob
2264 if (!chip->ecc.prepad && !chip->ecc.postpad) {
2265 pos = steps * (eccsize + chunk);
2266 steps = 0;
2267 } else
2268 pos = eccsize;
2270 chip->cmdfunc(mtd, NAND_CMD_SEQIN, pos, page);
2271 for (i = 0; i < steps; i++) {
2272 if (sndcmd) {
2273 if (mtd->writesize <= 512) {
2274 uint32_t fill = 0xFFFFFFFF;
2276 len = eccsize;
2277 while (len > 0) {
2278 int num = min_t(int, len, 4);
2279 chip->write_buf(mtd, (uint8_t *)&fill,
2280 num);
2281 len -= num;
2283 } else {
2284 pos = eccsize + i * (eccsize + chunk);
2285 chip->cmdfunc(mtd, NAND_CMD_RNDIN, pos, -1);
2287 } else
2288 sndcmd = 1;
2289 len = min_t(int, length, chunk);
2290 chip->write_buf(mtd, bufpoi, len);
2291 bufpoi += len;
2292 length -= len;
2294 if (length > 0)
2295 chip->write_buf(mtd, bufpoi, length);
2297 chip->cmdfunc(mtd, NAND_CMD_PAGEPROG, -1, -1);
2298 status = chip->waitfunc(mtd, chip);
2300 return status & NAND_STATUS_FAIL ? -EIO : 0;
2302 EXPORT_SYMBOL(nand_write_oob_syndrome);
2305 * nand_do_read_oob - [INTERN] NAND read out-of-band
2306 * @mtd: MTD device structure
2307 * @from: offset to read from
2308 * @ops: oob operations description structure
2310 * NAND read out-of-band data from the spare area.
2312 static int nand_do_read_oob(struct mtd_info *mtd, loff_t from,
2313 struct mtd_oob_ops *ops)
2315 int page, realpage, chipnr;
2316 struct nand_chip *chip = mtd_to_nand(mtd);
2317 struct mtd_ecc_stats stats;
2318 int readlen = ops->ooblen;
2319 int len;
2320 uint8_t *buf = ops->oobbuf;
2321 int ret = 0;
2323 pr_debug("%s: from = 0x%08Lx, len = %i\n",
2324 __func__, (unsigned long long)from, readlen);
2326 stats = mtd->ecc_stats;
2328 len = mtd_oobavail(mtd, ops);
2330 if (unlikely(ops->ooboffs >= len)) {
2331 pr_debug("%s: attempt to start read outside oob\n",
2332 __func__);
2333 return -EINVAL;
2336 /* Do not allow reads past end of device */
2337 if (unlikely(from >= mtd->size ||
2338 ops->ooboffs + readlen > ((mtd->size >> chip->page_shift) -
2339 (from >> chip->page_shift)) * len)) {
2340 pr_debug("%s: attempt to read beyond end of device\n",
2341 __func__);
2342 return -EINVAL;
2345 chipnr = (int)(from >> chip->chip_shift);
2346 chip->select_chip(mtd, chipnr);
2348 /* Shift to get page */
2349 realpage = (int)(from >> chip->page_shift);
2350 page = realpage & chip->pagemask;
2352 while (1) {
2353 if (ops->mode == MTD_OPS_RAW)
2354 ret = chip->ecc.read_oob_raw(mtd, chip, page);
2355 else
2356 ret = chip->ecc.read_oob(mtd, chip, page);
2358 if (ret < 0)
2359 break;
2361 len = min(len, readlen);
2362 buf = nand_transfer_oob(mtd, buf, ops, len);
2364 if (chip->options & NAND_NEED_READRDY) {
2365 /* Apply delay or wait for ready/busy pin */
2366 if (!chip->dev_ready)
2367 udelay(chip->chip_delay);
2368 else
2369 nand_wait_ready(mtd);
2372 readlen -= len;
2373 if (!readlen)
2374 break;
2376 /* Increment page address */
2377 realpage++;
2379 page = realpage & chip->pagemask;
2380 /* Check, if we cross a chip boundary */
2381 if (!page) {
2382 chipnr++;
2383 chip->select_chip(mtd, -1);
2384 chip->select_chip(mtd, chipnr);
2387 chip->select_chip(mtd, -1);
2389 ops->oobretlen = ops->ooblen - readlen;
2391 if (ret < 0)
2392 return ret;
2394 if (mtd->ecc_stats.failed - stats.failed)
2395 return -EBADMSG;
2397 return mtd->ecc_stats.corrected - stats.corrected ? -EUCLEAN : 0;
2401 * nand_read_oob - [MTD Interface] NAND read data and/or out-of-band
2402 * @mtd: MTD device structure
2403 * @from: offset to read from
2404 * @ops: oob operation description structure
2406 * NAND read data and/or out-of-band data.
2408 static int nand_read_oob(struct mtd_info *mtd, loff_t from,
2409 struct mtd_oob_ops *ops)
2411 int ret;
2413 ops->retlen = 0;
2415 /* Do not allow reads past end of device */
2416 if (ops->datbuf && (from + ops->len) > mtd->size) {
2417 pr_debug("%s: attempt to read beyond end of device\n",
2418 __func__);
2419 return -EINVAL;
2422 if (ops->mode != MTD_OPS_PLACE_OOB &&
2423 ops->mode != MTD_OPS_AUTO_OOB &&
2424 ops->mode != MTD_OPS_RAW)
2425 return -ENOTSUPP;
2427 nand_get_device(mtd, FL_READING);
2429 if (!ops->datbuf)
2430 ret = nand_do_read_oob(mtd, from, ops);
2431 else
2432 ret = nand_do_read_ops(mtd, from, ops);
2434 nand_release_device(mtd);
2435 return ret;
2440 * nand_write_page_raw - [INTERN] raw page write function
2441 * @mtd: mtd info structure
2442 * @chip: nand chip info structure
2443 * @buf: data buffer
2444 * @oob_required: must write chip->oob_poi to OOB
2445 * @page: page number to write
2447 * Not for syndrome calculating ECC controllers, which use a special oob layout.
2449 static int nand_write_page_raw(struct mtd_info *mtd, struct nand_chip *chip,
2450 const uint8_t *buf, int oob_required, int page)
2452 chip->write_buf(mtd, buf, mtd->writesize);
2453 if (oob_required)
2454 chip->write_buf(mtd, chip->oob_poi, mtd->oobsize);
2456 return 0;
2460 * nand_write_page_raw_syndrome - [INTERN] raw page write function
2461 * @mtd: mtd info structure
2462 * @chip: nand chip info structure
2463 * @buf: data buffer
2464 * @oob_required: must write chip->oob_poi to OOB
2465 * @page: page number to write
2467 * We need a special oob layout and handling even when ECC isn't checked.
2469 static int nand_write_page_raw_syndrome(struct mtd_info *mtd,
2470 struct nand_chip *chip,
2471 const uint8_t *buf, int oob_required,
2472 int page)
2474 int eccsize = chip->ecc.size;
2475 int eccbytes = chip->ecc.bytes;
2476 uint8_t *oob = chip->oob_poi;
2477 int steps, size;
2479 for (steps = chip->ecc.steps; steps > 0; steps--) {
2480 chip->write_buf(mtd, buf, eccsize);
2481 buf += eccsize;
2483 if (chip->ecc.prepad) {
2484 chip->write_buf(mtd, oob, chip->ecc.prepad);
2485 oob += chip->ecc.prepad;
2488 chip->write_buf(mtd, oob, eccbytes);
2489 oob += eccbytes;
2491 if (chip->ecc.postpad) {
2492 chip->write_buf(mtd, oob, chip->ecc.postpad);
2493 oob += chip->ecc.postpad;
2497 size = mtd->oobsize - (oob - chip->oob_poi);
2498 if (size)
2499 chip->write_buf(mtd, oob, size);
2501 return 0;
2504 * nand_write_page_swecc - [REPLACEABLE] software ECC based page write function
2505 * @mtd: mtd info structure
2506 * @chip: nand chip info structure
2507 * @buf: data buffer
2508 * @oob_required: must write chip->oob_poi to OOB
2509 * @page: page number to write
2511 static int nand_write_page_swecc(struct mtd_info *mtd, struct nand_chip *chip,
2512 const uint8_t *buf, int oob_required,
2513 int page)
2515 int i, eccsize = chip->ecc.size, ret;
2516 int eccbytes = chip->ecc.bytes;
2517 int eccsteps = chip->ecc.steps;
2518 uint8_t *ecc_calc = chip->buffers->ecccalc;
2519 const uint8_t *p = buf;
2521 /* Software ECC calculation */
2522 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize)
2523 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
2525 ret = mtd_ooblayout_set_eccbytes(mtd, ecc_calc, chip->oob_poi, 0,
2526 chip->ecc.total);
2527 if (ret)
2528 return ret;
2530 return chip->ecc.write_page_raw(mtd, chip, buf, 1, page);
2534 * nand_write_page_hwecc - [REPLACEABLE] hardware ECC based page write function
2535 * @mtd: mtd info structure
2536 * @chip: nand chip info structure
2537 * @buf: data buffer
2538 * @oob_required: must write chip->oob_poi to OOB
2539 * @page: page number to write
2541 static int nand_write_page_hwecc(struct mtd_info *mtd, struct nand_chip *chip,
2542 const uint8_t *buf, int oob_required,
2543 int page)
2545 int i, eccsize = chip->ecc.size, ret;
2546 int eccbytes = chip->ecc.bytes;
2547 int eccsteps = chip->ecc.steps;
2548 uint8_t *ecc_calc = chip->buffers->ecccalc;
2549 const uint8_t *p = buf;
2551 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
2552 chip->ecc.hwctl(mtd, NAND_ECC_WRITE);
2553 chip->write_buf(mtd, p, eccsize);
2554 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
2557 ret = mtd_ooblayout_set_eccbytes(mtd, ecc_calc, chip->oob_poi, 0,
2558 chip->ecc.total);
2559 if (ret)
2560 return ret;
2562 chip->write_buf(mtd, chip->oob_poi, mtd->oobsize);
2564 return 0;
2569 * nand_write_subpage_hwecc - [REPLACEABLE] hardware ECC based subpage write
2570 * @mtd: mtd info structure
2571 * @chip: nand chip info structure
2572 * @offset: column address of subpage within the page
2573 * @data_len: data length
2574 * @buf: data buffer
2575 * @oob_required: must write chip->oob_poi to OOB
2576 * @page: page number to write
2578 static int nand_write_subpage_hwecc(struct mtd_info *mtd,
2579 struct nand_chip *chip, uint32_t offset,
2580 uint32_t data_len, const uint8_t *buf,
2581 int oob_required, int page)
2583 uint8_t *oob_buf = chip->oob_poi;
2584 uint8_t *ecc_calc = chip->buffers->ecccalc;
2585 int ecc_size = chip->ecc.size;
2586 int ecc_bytes = chip->ecc.bytes;
2587 int ecc_steps = chip->ecc.steps;
2588 uint32_t start_step = offset / ecc_size;
2589 uint32_t end_step = (offset + data_len - 1) / ecc_size;
2590 int oob_bytes = mtd->oobsize / ecc_steps;
2591 int step, ret;
2593 for (step = 0; step < ecc_steps; step++) {
2594 /* configure controller for WRITE access */
2595 chip->ecc.hwctl(mtd, NAND_ECC_WRITE);
2597 /* write data (untouched subpages already masked by 0xFF) */
2598 chip->write_buf(mtd, buf, ecc_size);
2600 /* mask ECC of un-touched subpages by padding 0xFF */
2601 if ((step < start_step) || (step > end_step))
2602 memset(ecc_calc, 0xff, ecc_bytes);
2603 else
2604 chip->ecc.calculate(mtd, buf, ecc_calc);
2606 /* mask OOB of un-touched subpages by padding 0xFF */
2607 /* if oob_required, preserve OOB metadata of written subpage */
2608 if (!oob_required || (step < start_step) || (step > end_step))
2609 memset(oob_buf, 0xff, oob_bytes);
2611 buf += ecc_size;
2612 ecc_calc += ecc_bytes;
2613 oob_buf += oob_bytes;
2616 /* copy calculated ECC for whole page to chip->buffer->oob */
2617 /* this include masked-value(0xFF) for unwritten subpages */
2618 ecc_calc = chip->buffers->ecccalc;
2619 ret = mtd_ooblayout_set_eccbytes(mtd, ecc_calc, chip->oob_poi, 0,
2620 chip->ecc.total);
2621 if (ret)
2622 return ret;
2624 /* write OOB buffer to NAND device */
2625 chip->write_buf(mtd, chip->oob_poi, mtd->oobsize);
2627 return 0;
2632 * nand_write_page_syndrome - [REPLACEABLE] hardware ECC syndrome based page write
2633 * @mtd: mtd info structure
2634 * @chip: nand chip info structure
2635 * @buf: data buffer
2636 * @oob_required: must write chip->oob_poi to OOB
2637 * @page: page number to write
2639 * The hw generator calculates the error syndrome automatically. Therefore we
2640 * need a special oob layout and handling.
2642 static int nand_write_page_syndrome(struct mtd_info *mtd,
2643 struct nand_chip *chip,
2644 const uint8_t *buf, int oob_required,
2645 int page)
2647 int i, eccsize = chip->ecc.size;
2648 int eccbytes = chip->ecc.bytes;
2649 int eccsteps = chip->ecc.steps;
2650 const uint8_t *p = buf;
2651 uint8_t *oob = chip->oob_poi;
2653 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
2655 chip->ecc.hwctl(mtd, NAND_ECC_WRITE);
2656 chip->write_buf(mtd, p, eccsize);
2658 if (chip->ecc.prepad) {
2659 chip->write_buf(mtd, oob, chip->ecc.prepad);
2660 oob += chip->ecc.prepad;
2663 chip->ecc.calculate(mtd, p, oob);
2664 chip->write_buf(mtd, oob, eccbytes);
2665 oob += eccbytes;
2667 if (chip->ecc.postpad) {
2668 chip->write_buf(mtd, oob, chip->ecc.postpad);
2669 oob += chip->ecc.postpad;
2673 /* Calculate remaining oob bytes */
2674 i = mtd->oobsize - (oob - chip->oob_poi);
2675 if (i)
2676 chip->write_buf(mtd, oob, i);
2678 return 0;
2682 * nand_write_page - [REPLACEABLE] write one page
2683 * @mtd: MTD device structure
2684 * @chip: NAND chip descriptor
2685 * @offset: address offset within the page
2686 * @data_len: length of actual data to be written
2687 * @buf: the data to write
2688 * @oob_required: must write chip->oob_poi to OOB
2689 * @page: page number to write
2690 * @cached: cached programming
2691 * @raw: use _raw version of write_page
2693 static int nand_write_page(struct mtd_info *mtd, struct nand_chip *chip,
2694 uint32_t offset, int data_len, const uint8_t *buf,
2695 int oob_required, int page, int cached, int raw)
2697 int status, subpage;
2699 if (!(chip->options & NAND_NO_SUBPAGE_WRITE) &&
2700 chip->ecc.write_subpage)
2701 subpage = offset || (data_len < mtd->writesize);
2702 else
2703 subpage = 0;
2705 chip->cmdfunc(mtd, NAND_CMD_SEQIN, 0x00, page);
2707 if (unlikely(raw))
2708 status = chip->ecc.write_page_raw(mtd, chip, buf,
2709 oob_required, page);
2710 else if (subpage)
2711 status = chip->ecc.write_subpage(mtd, chip, offset, data_len,
2712 buf, oob_required, page);
2713 else
2714 status = chip->ecc.write_page(mtd, chip, buf, oob_required,
2715 page);
2717 if (status < 0)
2718 return status;
2721 * Cached progamming disabled for now. Not sure if it's worth the
2722 * trouble. The speed gain is not very impressive. (2.3->2.6Mib/s).
2724 cached = 0;
2726 if (!cached || !NAND_HAS_CACHEPROG(chip)) {
2728 chip->cmdfunc(mtd, NAND_CMD_PAGEPROG, -1, -1);
2729 status = chip->waitfunc(mtd, chip);
2731 * See if operation failed and additional status checks are
2732 * available.
2734 if ((status & NAND_STATUS_FAIL) && (chip->errstat))
2735 status = chip->errstat(mtd, chip, FL_WRITING, status,
2736 page);
2738 if (status & NAND_STATUS_FAIL)
2739 return -EIO;
2740 } else {
2741 chip->cmdfunc(mtd, NAND_CMD_CACHEDPROG, -1, -1);
2742 status = chip->waitfunc(mtd, chip);
2745 return 0;
2749 * nand_fill_oob - [INTERN] Transfer client buffer to oob
2750 * @mtd: MTD device structure
2751 * @oob: oob data buffer
2752 * @len: oob data write length
2753 * @ops: oob ops structure
2755 static uint8_t *nand_fill_oob(struct mtd_info *mtd, uint8_t *oob, size_t len,
2756 struct mtd_oob_ops *ops)
2758 struct nand_chip *chip = mtd_to_nand(mtd);
2759 int ret;
2762 * Initialise to all 0xFF, to avoid the possibility of left over OOB
2763 * data from a previous OOB read.
2765 memset(chip->oob_poi, 0xff, mtd->oobsize);
2767 switch (ops->mode) {
2769 case MTD_OPS_PLACE_OOB:
2770 case MTD_OPS_RAW:
2771 memcpy(chip->oob_poi + ops->ooboffs, oob, len);
2772 return oob + len;
2774 case MTD_OPS_AUTO_OOB:
2775 ret = mtd_ooblayout_set_databytes(mtd, oob, chip->oob_poi,
2776 ops->ooboffs, len);
2777 BUG_ON(ret);
2778 return oob + len;
2780 default:
2781 BUG();
2783 return NULL;
2786 #define NOTALIGNED(x) ((x & (chip->subpagesize - 1)) != 0)
2789 * nand_do_write_ops - [INTERN] NAND write with ECC
2790 * @mtd: MTD device structure
2791 * @to: offset to write to
2792 * @ops: oob operations description structure
2794 * NAND write with ECC.
2796 static int nand_do_write_ops(struct mtd_info *mtd, loff_t to,
2797 struct mtd_oob_ops *ops)
2799 int chipnr, realpage, page, blockmask, column;
2800 struct nand_chip *chip = mtd_to_nand(mtd);
2801 uint32_t writelen = ops->len;
2803 uint32_t oobwritelen = ops->ooblen;
2804 uint32_t oobmaxlen = mtd_oobavail(mtd, ops);
2806 uint8_t *oob = ops->oobbuf;
2807 uint8_t *buf = ops->datbuf;
2808 int ret;
2809 int oob_required = oob ? 1 : 0;
2811 ops->retlen = 0;
2812 if (!writelen)
2813 return 0;
2815 /* Reject writes, which are not page aligned */
2816 if (NOTALIGNED(to) || NOTALIGNED(ops->len)) {
2817 pr_notice("%s: attempt to write non page aligned data\n",
2818 __func__);
2819 return -EINVAL;
2822 column = to & (mtd->writesize - 1);
2824 chipnr = (int)(to >> chip->chip_shift);
2825 chip->select_chip(mtd, chipnr);
2827 /* Check, if it is write protected */
2828 if (nand_check_wp(mtd)) {
2829 ret = -EIO;
2830 goto err_out;
2833 realpage = (int)(to >> chip->page_shift);
2834 page = realpage & chip->pagemask;
2835 blockmask = (1 << (chip->phys_erase_shift - chip->page_shift)) - 1;
2837 /* Invalidate the page cache, when we write to the cached page */
2838 if (to <= ((loff_t)chip->pagebuf << chip->page_shift) &&
2839 ((loff_t)chip->pagebuf << chip->page_shift) < (to + ops->len))
2840 chip->pagebuf = -1;
2842 /* Don't allow multipage oob writes with offset */
2843 if (oob && ops->ooboffs && (ops->ooboffs + ops->ooblen > oobmaxlen)) {
2844 ret = -EINVAL;
2845 goto err_out;
2848 while (1) {
2849 int bytes = mtd->writesize;
2850 int cached = writelen > bytes && page != blockmask;
2851 uint8_t *wbuf = buf;
2852 int use_bufpoi;
2853 int part_pagewr = (column || writelen < mtd->writesize);
2855 if (part_pagewr)
2856 use_bufpoi = 1;
2857 else if (chip->options & NAND_USE_BOUNCE_BUFFER)
2858 use_bufpoi = !virt_addr_valid(buf);
2859 else
2860 use_bufpoi = 0;
2862 /* Partial page write?, or need to use bounce buffer */
2863 if (use_bufpoi) {
2864 pr_debug("%s: using write bounce buffer for buf@%p\n",
2865 __func__, buf);
2866 cached = 0;
2867 if (part_pagewr)
2868 bytes = min_t(int, bytes - column, writelen);
2869 chip->pagebuf = -1;
2870 memset(chip->buffers->databuf, 0xff, mtd->writesize);
2871 memcpy(&chip->buffers->databuf[column], buf, bytes);
2872 wbuf = chip->buffers->databuf;
2875 if (unlikely(oob)) {
2876 size_t len = min(oobwritelen, oobmaxlen);
2877 oob = nand_fill_oob(mtd, oob, len, ops);
2878 oobwritelen -= len;
2879 } else {
2880 /* We still need to erase leftover OOB data */
2881 memset(chip->oob_poi, 0xff, mtd->oobsize);
2883 ret = chip->write_page(mtd, chip, column, bytes, wbuf,
2884 oob_required, page, cached,
2885 (ops->mode == MTD_OPS_RAW));
2886 if (ret)
2887 break;
2889 writelen -= bytes;
2890 if (!writelen)
2891 break;
2893 column = 0;
2894 buf += bytes;
2895 realpage++;
2897 page = realpage & chip->pagemask;
2898 /* Check, if we cross a chip boundary */
2899 if (!page) {
2900 chipnr++;
2901 chip->select_chip(mtd, -1);
2902 chip->select_chip(mtd, chipnr);
2906 ops->retlen = ops->len - writelen;
2907 if (unlikely(oob))
2908 ops->oobretlen = ops->ooblen;
2910 err_out:
2911 chip->select_chip(mtd, -1);
2912 return ret;
2916 * panic_nand_write - [MTD Interface] NAND write with ECC
2917 * @mtd: MTD device structure
2918 * @to: offset to write to
2919 * @len: number of bytes to write
2920 * @retlen: pointer to variable to store the number of written bytes
2921 * @buf: the data to write
2923 * NAND write with ECC. Used when performing writes in interrupt context, this
2924 * may for example be called by mtdoops when writing an oops while in panic.
2926 static int panic_nand_write(struct mtd_info *mtd, loff_t to, size_t len,
2927 size_t *retlen, const uint8_t *buf)
2929 struct nand_chip *chip = mtd_to_nand(mtd);
2930 struct mtd_oob_ops ops;
2931 int ret;
2933 /* Wait for the device to get ready */
2934 panic_nand_wait(mtd, chip, 400);
2936 /* Grab the device */
2937 panic_nand_get_device(chip, mtd, FL_WRITING);
2939 memset(&ops, 0, sizeof(ops));
2940 ops.len = len;
2941 ops.datbuf = (uint8_t *)buf;
2942 ops.mode = MTD_OPS_PLACE_OOB;
2944 ret = nand_do_write_ops(mtd, to, &ops);
2946 *retlen = ops.retlen;
2947 return ret;
2951 * nand_write - [MTD Interface] NAND write with ECC
2952 * @mtd: MTD device structure
2953 * @to: offset to write to
2954 * @len: number of bytes to write
2955 * @retlen: pointer to variable to store the number of written bytes
2956 * @buf: the data to write
2958 * NAND write with ECC.
2960 static int nand_write(struct mtd_info *mtd, loff_t to, size_t len,
2961 size_t *retlen, const uint8_t *buf)
2963 struct mtd_oob_ops ops;
2964 int ret;
2966 nand_get_device(mtd, FL_WRITING);
2967 memset(&ops, 0, sizeof(ops));
2968 ops.len = len;
2969 ops.datbuf = (uint8_t *)buf;
2970 ops.mode = MTD_OPS_PLACE_OOB;
2971 ret = nand_do_write_ops(mtd, to, &ops);
2972 *retlen = ops.retlen;
2973 nand_release_device(mtd);
2974 return ret;
2978 * nand_do_write_oob - [MTD Interface] NAND write out-of-band
2979 * @mtd: MTD device structure
2980 * @to: offset to write to
2981 * @ops: oob operation description structure
2983 * NAND write out-of-band.
2985 static int nand_do_write_oob(struct mtd_info *mtd, loff_t to,
2986 struct mtd_oob_ops *ops)
2988 int chipnr, page, status, len;
2989 struct nand_chip *chip = mtd_to_nand(mtd);
2991 pr_debug("%s: to = 0x%08x, len = %i\n",
2992 __func__, (unsigned int)to, (int)ops->ooblen);
2994 len = mtd_oobavail(mtd, ops);
2996 /* Do not allow write past end of page */
2997 if ((ops->ooboffs + ops->ooblen) > len) {
2998 pr_debug("%s: attempt to write past end of page\n",
2999 __func__);
3000 return -EINVAL;
3003 if (unlikely(ops->ooboffs >= len)) {
3004 pr_debug("%s: attempt to start write outside oob\n",
3005 __func__);
3006 return -EINVAL;
3009 /* Do not allow write past end of device */
3010 if (unlikely(to >= mtd->size ||
3011 ops->ooboffs + ops->ooblen >
3012 ((mtd->size >> chip->page_shift) -
3013 (to >> chip->page_shift)) * len)) {
3014 pr_debug("%s: attempt to write beyond end of device\n",
3015 __func__);
3016 return -EINVAL;
3019 chipnr = (int)(to >> chip->chip_shift);
3022 * Reset the chip. Some chips (like the Toshiba TC5832DC found in one
3023 * of my DiskOnChip 2000 test units) will clear the whole data page too
3024 * if we don't do this. I have no clue why, but I seem to have 'fixed'
3025 * it in the doc2000 driver in August 1999. dwmw2.
3027 nand_reset(chip, chipnr);
3029 chip->select_chip(mtd, chipnr);
3031 /* Shift to get page */
3032 page = (int)(to >> chip->page_shift);
3034 /* Check, if it is write protected */
3035 if (nand_check_wp(mtd)) {
3036 chip->select_chip(mtd, -1);
3037 return -EROFS;
3040 /* Invalidate the page cache, if we write to the cached page */
3041 if (page == chip->pagebuf)
3042 chip->pagebuf = -1;
3044 nand_fill_oob(mtd, ops->oobbuf, ops->ooblen, ops);
3046 if (ops->mode == MTD_OPS_RAW)
3047 status = chip->ecc.write_oob_raw(mtd, chip, page & chip->pagemask);
3048 else
3049 status = chip->ecc.write_oob(mtd, chip, page & chip->pagemask);
3051 chip->select_chip(mtd, -1);
3053 if (status)
3054 return status;
3056 ops->oobretlen = ops->ooblen;
3058 return 0;
3062 * nand_write_oob - [MTD Interface] NAND write data and/or out-of-band
3063 * @mtd: MTD device structure
3064 * @to: offset to write to
3065 * @ops: oob operation description structure
3067 static int nand_write_oob(struct mtd_info *mtd, loff_t to,
3068 struct mtd_oob_ops *ops)
3070 int ret = -ENOTSUPP;
3072 ops->retlen = 0;
3074 /* Do not allow writes past end of device */
3075 if (ops->datbuf && (to + ops->len) > mtd->size) {
3076 pr_debug("%s: attempt to write beyond end of device\n",
3077 __func__);
3078 return -EINVAL;
3081 nand_get_device(mtd, FL_WRITING);
3083 switch (ops->mode) {
3084 case MTD_OPS_PLACE_OOB:
3085 case MTD_OPS_AUTO_OOB:
3086 case MTD_OPS_RAW:
3087 break;
3089 default:
3090 goto out;
3093 if (!ops->datbuf)
3094 ret = nand_do_write_oob(mtd, to, ops);
3095 else
3096 ret = nand_do_write_ops(mtd, to, ops);
3098 out:
3099 nand_release_device(mtd);
3100 return ret;
3104 * single_erase - [GENERIC] NAND standard block erase command function
3105 * @mtd: MTD device structure
3106 * @page: the page address of the block which will be erased
3108 * Standard erase command for NAND chips. Returns NAND status.
3110 static int single_erase(struct mtd_info *mtd, int page)
3112 struct nand_chip *chip = mtd_to_nand(mtd);
3113 /* Send commands to erase a block */
3114 chip->cmdfunc(mtd, NAND_CMD_ERASE1, -1, page);
3115 chip->cmdfunc(mtd, NAND_CMD_ERASE2, -1, -1);
3117 return chip->waitfunc(mtd, chip);
3121 * nand_erase - [MTD Interface] erase block(s)
3122 * @mtd: MTD device structure
3123 * @instr: erase instruction
3125 * Erase one ore more blocks.
3127 static int nand_erase(struct mtd_info *mtd, struct erase_info *instr)
3129 return nand_erase_nand(mtd, instr, 0);
3133 * nand_erase_nand - [INTERN] erase block(s)
3134 * @mtd: MTD device structure
3135 * @instr: erase instruction
3136 * @allowbbt: allow erasing the bbt area
3138 * Erase one ore more blocks.
3140 int nand_erase_nand(struct mtd_info *mtd, struct erase_info *instr,
3141 int allowbbt)
3143 int page, status, pages_per_block, ret, chipnr;
3144 struct nand_chip *chip = mtd_to_nand(mtd);
3145 loff_t len;
3147 pr_debug("%s: start = 0x%012llx, len = %llu\n",
3148 __func__, (unsigned long long)instr->addr,
3149 (unsigned long long)instr->len);
3151 if (check_offs_len(mtd, instr->addr, instr->len))
3152 return -EINVAL;
3154 /* Grab the lock and see if the device is available */
3155 nand_get_device(mtd, FL_ERASING);
3157 /* Shift to get first page */
3158 page = (int)(instr->addr >> chip->page_shift);
3159 chipnr = (int)(instr->addr >> chip->chip_shift);
3161 /* Calculate pages in each block */
3162 pages_per_block = 1 << (chip->phys_erase_shift - chip->page_shift);
3164 /* Select the NAND device */
3165 chip->select_chip(mtd, chipnr);
3167 /* Check, if it is write protected */
3168 if (nand_check_wp(mtd)) {
3169 pr_debug("%s: device is write protected!\n",
3170 __func__);
3171 instr->state = MTD_ERASE_FAILED;
3172 goto erase_exit;
3175 /* Loop through the pages */
3176 len = instr->len;
3178 instr->state = MTD_ERASING;
3180 while (len) {
3181 /* Check if we have a bad block, we do not erase bad blocks! */
3182 if (nand_block_checkbad(mtd, ((loff_t) page) <<
3183 chip->page_shift, allowbbt)) {
3184 pr_warn("%s: attempt to erase a bad block at page 0x%08x\n",
3185 __func__, page);
3186 instr->state = MTD_ERASE_FAILED;
3187 goto erase_exit;
3191 * Invalidate the page cache, if we erase the block which
3192 * contains the current cached page.
3194 if (page <= chip->pagebuf && chip->pagebuf <
3195 (page + pages_per_block))
3196 chip->pagebuf = -1;
3198 status = chip->erase(mtd, page & chip->pagemask);
3201 * See if operation failed and additional status checks are
3202 * available
3204 if ((status & NAND_STATUS_FAIL) && (chip->errstat))
3205 status = chip->errstat(mtd, chip, FL_ERASING,
3206 status, page);
3208 /* See if block erase succeeded */
3209 if (status & NAND_STATUS_FAIL) {
3210 pr_debug("%s: failed erase, page 0x%08x\n",
3211 __func__, page);
3212 instr->state = MTD_ERASE_FAILED;
3213 instr->fail_addr =
3214 ((loff_t)page << chip->page_shift);
3215 goto erase_exit;
3218 /* Increment page address and decrement length */
3219 len -= (1ULL << chip->phys_erase_shift);
3220 page += pages_per_block;
3222 /* Check, if we cross a chip boundary */
3223 if (len && !(page & chip->pagemask)) {
3224 chipnr++;
3225 chip->select_chip(mtd, -1);
3226 chip->select_chip(mtd, chipnr);
3229 instr->state = MTD_ERASE_DONE;
3231 erase_exit:
3233 ret = instr->state == MTD_ERASE_DONE ? 0 : -EIO;
3235 /* Deselect and wake up anyone waiting on the device */
3236 chip->select_chip(mtd, -1);
3237 nand_release_device(mtd);
3239 /* Do call back function */
3240 if (!ret)
3241 mtd_erase_callback(instr);
3243 /* Return more or less happy */
3244 return ret;
3248 * nand_sync - [MTD Interface] sync
3249 * @mtd: MTD device structure
3251 * Sync is actually a wait for chip ready function.
3253 static void nand_sync(struct mtd_info *mtd)
3255 pr_debug("%s: called\n", __func__);
3257 /* Grab the lock and see if the device is available */
3258 nand_get_device(mtd, FL_SYNCING);
3259 /* Release it and go back */
3260 nand_release_device(mtd);
3264 * nand_block_isbad - [MTD Interface] Check if block at offset is bad
3265 * @mtd: MTD device structure
3266 * @offs: offset relative to mtd start
3268 static int nand_block_isbad(struct mtd_info *mtd, loff_t offs)
3270 struct nand_chip *chip = mtd_to_nand(mtd);
3271 int chipnr = (int)(offs >> chip->chip_shift);
3272 int ret;
3274 /* Select the NAND device */
3275 nand_get_device(mtd, FL_READING);
3276 chip->select_chip(mtd, chipnr);
3278 ret = nand_block_checkbad(mtd, offs, 0);
3280 chip->select_chip(mtd, -1);
3281 nand_release_device(mtd);
3283 return ret;
3287 * nand_block_markbad - [MTD Interface] Mark block at the given offset as bad
3288 * @mtd: MTD device structure
3289 * @ofs: offset relative to mtd start
3291 static int nand_block_markbad(struct mtd_info *mtd, loff_t ofs)
3293 int ret;
3295 ret = nand_block_isbad(mtd, ofs);
3296 if (ret) {
3297 /* If it was bad already, return success and do nothing */
3298 if (ret > 0)
3299 return 0;
3300 return ret;
3303 return nand_block_markbad_lowlevel(mtd, ofs);
3307 * nand_onfi_set_features- [REPLACEABLE] set features for ONFI nand
3308 * @mtd: MTD device structure
3309 * @chip: nand chip info structure
3310 * @addr: feature address.
3311 * @subfeature_param: the subfeature parameters, a four bytes array.
3313 static int nand_onfi_set_features(struct mtd_info *mtd, struct nand_chip *chip,
3314 int addr, uint8_t *subfeature_param)
3316 int status;
3317 int i;
3319 if (!chip->onfi_version ||
3320 !(le16_to_cpu(chip->onfi_params.opt_cmd)
3321 & ONFI_OPT_CMD_SET_GET_FEATURES))
3322 return -EINVAL;
3324 chip->cmdfunc(mtd, NAND_CMD_SET_FEATURES, addr, -1);
3325 for (i = 0; i < ONFI_SUBFEATURE_PARAM_LEN; ++i)
3326 chip->write_byte(mtd, subfeature_param[i]);
3328 status = chip->waitfunc(mtd, chip);
3329 if (status & NAND_STATUS_FAIL)
3330 return -EIO;
3331 return 0;
3335 * nand_onfi_get_features- [REPLACEABLE] get features for ONFI nand
3336 * @mtd: MTD device structure
3337 * @chip: nand chip info structure
3338 * @addr: feature address.
3339 * @subfeature_param: the subfeature parameters, a four bytes array.
3341 static int nand_onfi_get_features(struct mtd_info *mtd, struct nand_chip *chip,
3342 int addr, uint8_t *subfeature_param)
3344 int i;
3346 if (!chip->onfi_version ||
3347 !(le16_to_cpu(chip->onfi_params.opt_cmd)
3348 & ONFI_OPT_CMD_SET_GET_FEATURES))
3349 return -EINVAL;
3351 chip->cmdfunc(mtd, NAND_CMD_GET_FEATURES, addr, -1);
3352 for (i = 0; i < ONFI_SUBFEATURE_PARAM_LEN; ++i)
3353 *subfeature_param++ = chip->read_byte(mtd);
3354 return 0;
3358 * nand_suspend - [MTD Interface] Suspend the NAND flash
3359 * @mtd: MTD device structure
3361 static int nand_suspend(struct mtd_info *mtd)
3363 return nand_get_device(mtd, FL_PM_SUSPENDED);
3367 * nand_resume - [MTD Interface] Resume the NAND flash
3368 * @mtd: MTD device structure
3370 static void nand_resume(struct mtd_info *mtd)
3372 struct nand_chip *chip = mtd_to_nand(mtd);
3374 if (chip->state == FL_PM_SUSPENDED)
3375 nand_release_device(mtd);
3376 else
3377 pr_err("%s called for a chip which is not in suspended state\n",
3378 __func__);
3382 * nand_shutdown - [MTD Interface] Finish the current NAND operation and
3383 * prevent further operations
3384 * @mtd: MTD device structure
3386 static void nand_shutdown(struct mtd_info *mtd)
3388 nand_get_device(mtd, FL_PM_SUSPENDED);
3391 /* Set default functions */
3392 static void nand_set_defaults(struct nand_chip *chip, int busw)
3394 /* check for proper chip_delay setup, set 20us if not */
3395 if (!chip->chip_delay)
3396 chip->chip_delay = 20;
3398 /* check, if a user supplied command function given */
3399 if (chip->cmdfunc == NULL)
3400 chip->cmdfunc = nand_command;
3402 /* check, if a user supplied wait function given */
3403 if (chip->waitfunc == NULL)
3404 chip->waitfunc = nand_wait;
3406 if (!chip->select_chip)
3407 chip->select_chip = nand_select_chip;
3409 /* set for ONFI nand */
3410 if (!chip->onfi_set_features)
3411 chip->onfi_set_features = nand_onfi_set_features;
3412 if (!chip->onfi_get_features)
3413 chip->onfi_get_features = nand_onfi_get_features;
3415 /* If called twice, pointers that depend on busw may need to be reset */
3416 if (!chip->read_byte || chip->read_byte == nand_read_byte)
3417 chip->read_byte = busw ? nand_read_byte16 : nand_read_byte;
3418 if (!chip->read_word)
3419 chip->read_word = nand_read_word;
3420 if (!chip->block_bad)
3421 chip->block_bad = nand_block_bad;
3422 if (!chip->block_markbad)
3423 chip->block_markbad = nand_default_block_markbad;
3424 if (!chip->write_buf || chip->write_buf == nand_write_buf)
3425 chip->write_buf = busw ? nand_write_buf16 : nand_write_buf;
3426 if (!chip->write_byte || chip->write_byte == nand_write_byte)
3427 chip->write_byte = busw ? nand_write_byte16 : nand_write_byte;
3428 if (!chip->read_buf || chip->read_buf == nand_read_buf)
3429 chip->read_buf = busw ? nand_read_buf16 : nand_read_buf;
3430 if (!chip->scan_bbt)
3431 chip->scan_bbt = nand_default_bbt;
3433 if (!chip->controller) {
3434 chip->controller = &chip->hwcontrol;
3435 nand_hw_control_init(chip->controller);
3440 /* Sanitize ONFI strings so we can safely print them */
3441 static void sanitize_string(uint8_t *s, size_t len)
3443 ssize_t i;
3445 /* Null terminate */
3446 s[len - 1] = 0;
3448 /* Remove non printable chars */
3449 for (i = 0; i < len - 1; i++) {
3450 if (s[i] < ' ' || s[i] > 127)
3451 s[i] = '?';
3454 /* Remove trailing spaces */
3455 strim(s);
3458 static u16 onfi_crc16(u16 crc, u8 const *p, size_t len)
3460 int i;
3461 while (len--) {
3462 crc ^= *p++ << 8;
3463 for (i = 0; i < 8; i++)
3464 crc = (crc << 1) ^ ((crc & 0x8000) ? 0x8005 : 0);
3467 return crc;
3470 /* Parse the Extended Parameter Page. */
3471 static int nand_flash_detect_ext_param_page(struct mtd_info *mtd,
3472 struct nand_chip *chip, struct nand_onfi_params *p)
3474 struct onfi_ext_param_page *ep;
3475 struct onfi_ext_section *s;
3476 struct onfi_ext_ecc_info *ecc;
3477 uint8_t *cursor;
3478 int ret = -EINVAL;
3479 int len;
3480 int i;
3482 len = le16_to_cpu(p->ext_param_page_length) * 16;
3483 ep = kmalloc(len, GFP_KERNEL);
3484 if (!ep)
3485 return -ENOMEM;
3487 /* Send our own NAND_CMD_PARAM. */
3488 chip->cmdfunc(mtd, NAND_CMD_PARAM, 0, -1);
3490 /* Use the Change Read Column command to skip the ONFI param pages. */
3491 chip->cmdfunc(mtd, NAND_CMD_RNDOUT,
3492 sizeof(*p) * p->num_of_param_pages , -1);
3494 /* Read out the Extended Parameter Page. */
3495 chip->read_buf(mtd, (uint8_t *)ep, len);
3496 if ((onfi_crc16(ONFI_CRC_BASE, ((uint8_t *)ep) + 2, len - 2)
3497 != le16_to_cpu(ep->crc))) {
3498 pr_debug("fail in the CRC.\n");
3499 goto ext_out;
3503 * Check the signature.
3504 * Do not strictly follow the ONFI spec, maybe changed in future.
3506 if (strncmp(ep->sig, "EPPS", 4)) {
3507 pr_debug("The signature is invalid.\n");
3508 goto ext_out;
3511 /* find the ECC section. */
3512 cursor = (uint8_t *)(ep + 1);
3513 for (i = 0; i < ONFI_EXT_SECTION_MAX; i++) {
3514 s = ep->sections + i;
3515 if (s->type == ONFI_SECTION_TYPE_2)
3516 break;
3517 cursor += s->length * 16;
3519 if (i == ONFI_EXT_SECTION_MAX) {
3520 pr_debug("We can not find the ECC section.\n");
3521 goto ext_out;
3524 /* get the info we want. */
3525 ecc = (struct onfi_ext_ecc_info *)cursor;
3527 if (!ecc->codeword_size) {
3528 pr_debug("Invalid codeword size\n");
3529 goto ext_out;
3532 chip->ecc_strength_ds = ecc->ecc_bits;
3533 chip->ecc_step_ds = 1 << ecc->codeword_size;
3534 ret = 0;
3536 ext_out:
3537 kfree(ep);
3538 return ret;
3541 static int nand_setup_read_retry_micron(struct mtd_info *mtd, int retry_mode)
3543 struct nand_chip *chip = mtd_to_nand(mtd);
3544 uint8_t feature[ONFI_SUBFEATURE_PARAM_LEN] = {retry_mode};
3546 return chip->onfi_set_features(mtd, chip, ONFI_FEATURE_ADDR_READ_RETRY,
3547 feature);
3551 * Configure chip properties from Micron vendor-specific ONFI table
3553 static void nand_onfi_detect_micron(struct nand_chip *chip,
3554 struct nand_onfi_params *p)
3556 struct nand_onfi_vendor_micron *micron = (void *)p->vendor;
3558 if (le16_to_cpu(p->vendor_revision) < 1)
3559 return;
3561 chip->read_retries = micron->read_retry_options;
3562 chip->setup_read_retry = nand_setup_read_retry_micron;
3566 * Check if the NAND chip is ONFI compliant, returns 1 if it is, 0 otherwise.
3568 static int nand_flash_detect_onfi(struct mtd_info *mtd, struct nand_chip *chip,
3569 int *busw)
3571 struct nand_onfi_params *p = &chip->onfi_params;
3572 int i, j;
3573 int val;
3575 /* Try ONFI for unknown chip or LP */
3576 chip->cmdfunc(mtd, NAND_CMD_READID, 0x20, -1);
3577 if (chip->read_byte(mtd) != 'O' || chip->read_byte(mtd) != 'N' ||
3578 chip->read_byte(mtd) != 'F' || chip->read_byte(mtd) != 'I')
3579 return 0;
3581 chip->cmdfunc(mtd, NAND_CMD_PARAM, 0, -1);
3582 for (i = 0; i < 3; i++) {
3583 for (j = 0; j < sizeof(*p); j++)
3584 ((uint8_t *)p)[j] = chip->read_byte(mtd);
3585 if (onfi_crc16(ONFI_CRC_BASE, (uint8_t *)p, 254) ==
3586 le16_to_cpu(p->crc)) {
3587 break;
3591 if (i == 3) {
3592 pr_err("Could not find valid ONFI parameter page; aborting\n");
3593 return 0;
3596 /* Check version */
3597 val = le16_to_cpu(p->revision);
3598 if (val & (1 << 5))
3599 chip->onfi_version = 23;
3600 else if (val & (1 << 4))
3601 chip->onfi_version = 22;
3602 else if (val & (1 << 3))
3603 chip->onfi_version = 21;
3604 else if (val & (1 << 2))
3605 chip->onfi_version = 20;
3606 else if (val & (1 << 1))
3607 chip->onfi_version = 10;
3609 if (!chip->onfi_version) {
3610 pr_info("unsupported ONFI version: %d\n", val);
3611 return 0;
3614 sanitize_string(p->manufacturer, sizeof(p->manufacturer));
3615 sanitize_string(p->model, sizeof(p->model));
3616 if (!mtd->name)
3617 mtd->name = p->model;
3619 mtd->writesize = le32_to_cpu(p->byte_per_page);
3622 * pages_per_block and blocks_per_lun may not be a power-of-2 size
3623 * (don't ask me who thought of this...). MTD assumes that these
3624 * dimensions will be power-of-2, so just truncate the remaining area.
3626 mtd->erasesize = 1 << (fls(le32_to_cpu(p->pages_per_block)) - 1);
3627 mtd->erasesize *= mtd->writesize;
3629 mtd->oobsize = le16_to_cpu(p->spare_bytes_per_page);
3631 /* See erasesize comment */
3632 chip->chipsize = 1 << (fls(le32_to_cpu(p->blocks_per_lun)) - 1);
3633 chip->chipsize *= (uint64_t)mtd->erasesize * p->lun_count;
3634 chip->bits_per_cell = p->bits_per_cell;
3636 if (onfi_feature(chip) & ONFI_FEATURE_16_BIT_BUS)
3637 *busw = NAND_BUSWIDTH_16;
3638 else
3639 *busw = 0;
3641 if (p->ecc_bits != 0xff) {
3642 chip->ecc_strength_ds = p->ecc_bits;
3643 chip->ecc_step_ds = 512;
3644 } else if (chip->onfi_version >= 21 &&
3645 (onfi_feature(chip) & ONFI_FEATURE_EXT_PARAM_PAGE)) {
3648 * The nand_flash_detect_ext_param_page() uses the
3649 * Change Read Column command which maybe not supported
3650 * by the chip->cmdfunc. So try to update the chip->cmdfunc
3651 * now. We do not replace user supplied command function.
3653 if (mtd->writesize > 512 && chip->cmdfunc == nand_command)
3654 chip->cmdfunc = nand_command_lp;
3656 /* The Extended Parameter Page is supported since ONFI 2.1. */
3657 if (nand_flash_detect_ext_param_page(mtd, chip, p))
3658 pr_warn("Failed to detect ONFI extended param page\n");
3659 } else {
3660 pr_warn("Could not retrieve ONFI ECC requirements\n");
3663 if (p->jedec_id == NAND_MFR_MICRON)
3664 nand_onfi_detect_micron(chip, p);
3666 return 1;
3670 * Check if the NAND chip is JEDEC compliant, returns 1 if it is, 0 otherwise.
3672 static int nand_flash_detect_jedec(struct mtd_info *mtd, struct nand_chip *chip,
3673 int *busw)
3675 struct nand_jedec_params *p = &chip->jedec_params;
3676 struct jedec_ecc_info *ecc;
3677 int val;
3678 int i, j;
3680 /* Try JEDEC for unknown chip or LP */
3681 chip->cmdfunc(mtd, NAND_CMD_READID, 0x40, -1);
3682 if (chip->read_byte(mtd) != 'J' || chip->read_byte(mtd) != 'E' ||
3683 chip->read_byte(mtd) != 'D' || chip->read_byte(mtd) != 'E' ||
3684 chip->read_byte(mtd) != 'C')
3685 return 0;
3687 chip->cmdfunc(mtd, NAND_CMD_PARAM, 0x40, -1);
3688 for (i = 0; i < 3; i++) {
3689 for (j = 0; j < sizeof(*p); j++)
3690 ((uint8_t *)p)[j] = chip->read_byte(mtd);
3692 if (onfi_crc16(ONFI_CRC_BASE, (uint8_t *)p, 510) ==
3693 le16_to_cpu(p->crc))
3694 break;
3697 if (i == 3) {
3698 pr_err("Could not find valid JEDEC parameter page; aborting\n");
3699 return 0;
3702 /* Check version */
3703 val = le16_to_cpu(p->revision);
3704 if (val & (1 << 2))
3705 chip->jedec_version = 10;
3706 else if (val & (1 << 1))
3707 chip->jedec_version = 1; /* vendor specific version */
3709 if (!chip->jedec_version) {
3710 pr_info("unsupported JEDEC version: %d\n", val);
3711 return 0;
3714 sanitize_string(p->manufacturer, sizeof(p->manufacturer));
3715 sanitize_string(p->model, sizeof(p->model));
3716 if (!mtd->name)
3717 mtd->name = p->model;
3719 mtd->writesize = le32_to_cpu(p->byte_per_page);
3721 /* Please reference to the comment for nand_flash_detect_onfi. */
3722 mtd->erasesize = 1 << (fls(le32_to_cpu(p->pages_per_block)) - 1);
3723 mtd->erasesize *= mtd->writesize;
3725 mtd->oobsize = le16_to_cpu(p->spare_bytes_per_page);
3727 /* Please reference to the comment for nand_flash_detect_onfi. */
3728 chip->chipsize = 1 << (fls(le32_to_cpu(p->blocks_per_lun)) - 1);
3729 chip->chipsize *= (uint64_t)mtd->erasesize * p->lun_count;
3730 chip->bits_per_cell = p->bits_per_cell;
3732 if (jedec_feature(chip) & JEDEC_FEATURE_16_BIT_BUS)
3733 *busw = NAND_BUSWIDTH_16;
3734 else
3735 *busw = 0;
3737 /* ECC info */
3738 ecc = &p->ecc_info[0];
3740 if (ecc->codeword_size >= 9) {
3741 chip->ecc_strength_ds = ecc->ecc_bits;
3742 chip->ecc_step_ds = 1 << ecc->codeword_size;
3743 } else {
3744 pr_warn("Invalid codeword size\n");
3747 return 1;
3751 * nand_id_has_period - Check if an ID string has a given wraparound period
3752 * @id_data: the ID string
3753 * @arrlen: the length of the @id_data array
3754 * @period: the period of repitition
3756 * Check if an ID string is repeated within a given sequence of bytes at
3757 * specific repetition interval period (e.g., {0x20,0x01,0x7F,0x20} has a
3758 * period of 3). This is a helper function for nand_id_len(). Returns non-zero
3759 * if the repetition has a period of @period; otherwise, returns zero.
3761 static int nand_id_has_period(u8 *id_data, int arrlen, int period)
3763 int i, j;
3764 for (i = 0; i < period; i++)
3765 for (j = i + period; j < arrlen; j += period)
3766 if (id_data[i] != id_data[j])
3767 return 0;
3768 return 1;
3772 * nand_id_len - Get the length of an ID string returned by CMD_READID
3773 * @id_data: the ID string
3774 * @arrlen: the length of the @id_data array
3776 * Returns the length of the ID string, according to known wraparound/trailing
3777 * zero patterns. If no pattern exists, returns the length of the array.
3779 static int nand_id_len(u8 *id_data, int arrlen)
3781 int last_nonzero, period;
3783 /* Find last non-zero byte */
3784 for (last_nonzero = arrlen - 1; last_nonzero >= 0; last_nonzero--)
3785 if (id_data[last_nonzero])
3786 break;
3788 /* All zeros */
3789 if (last_nonzero < 0)
3790 return 0;
3792 /* Calculate wraparound period */
3793 for (period = 1; period < arrlen; period++)
3794 if (nand_id_has_period(id_data, arrlen, period))
3795 break;
3797 /* There's a repeated pattern */
3798 if (period < arrlen)
3799 return period;
3801 /* There are trailing zeros */
3802 if (last_nonzero < arrlen - 1)
3803 return last_nonzero + 1;
3805 /* No pattern detected */
3806 return arrlen;
3809 /* Extract the bits of per cell from the 3rd byte of the extended ID */
3810 static int nand_get_bits_per_cell(u8 cellinfo)
3812 int bits;
3814 bits = cellinfo & NAND_CI_CELLTYPE_MSK;
3815 bits >>= NAND_CI_CELLTYPE_SHIFT;
3816 return bits + 1;
3820 * Many new NAND share similar device ID codes, which represent the size of the
3821 * chip. The rest of the parameters must be decoded according to generic or
3822 * manufacturer-specific "extended ID" decoding patterns.
3824 static void nand_decode_ext_id(struct mtd_info *mtd, struct nand_chip *chip,
3825 u8 id_data[8], int *busw)
3827 int extid, id_len;
3828 /* The 3rd id byte holds MLC / multichip data */
3829 chip->bits_per_cell = nand_get_bits_per_cell(id_data[2]);
3830 /* The 4th id byte is the important one */
3831 extid = id_data[3];
3833 id_len = nand_id_len(id_data, 8);
3836 * Field definitions are in the following datasheets:
3837 * Old style (4,5 byte ID): Samsung K9GAG08U0M (p.32)
3838 * New Samsung (6 byte ID): Samsung K9GAG08U0F (p.44)
3839 * Hynix MLC (6 byte ID): Hynix H27UBG8T2B (p.22)
3841 * Check for ID length, non-zero 6th byte, cell type, and Hynix/Samsung
3842 * ID to decide what to do.
3844 if (id_len == 6 && id_data[0] == NAND_MFR_SAMSUNG &&
3845 !nand_is_slc(chip) && id_data[5] != 0x00) {
3846 /* Calc pagesize */
3847 mtd->writesize = 2048 << (extid & 0x03);
3848 extid >>= 2;
3849 /* Calc oobsize */
3850 switch (((extid >> 2) & 0x04) | (extid & 0x03)) {
3851 case 1:
3852 mtd->oobsize = 128;
3853 break;
3854 case 2:
3855 mtd->oobsize = 218;
3856 break;
3857 case 3:
3858 mtd->oobsize = 400;
3859 break;
3860 case 4:
3861 mtd->oobsize = 436;
3862 break;
3863 case 5:
3864 mtd->oobsize = 512;
3865 break;
3866 case 6:
3867 mtd->oobsize = 640;
3868 break;
3869 case 7:
3870 default: /* Other cases are "reserved" (unknown) */
3871 mtd->oobsize = 1024;
3872 break;
3874 extid >>= 2;
3875 /* Calc blocksize */
3876 mtd->erasesize = (128 * 1024) <<
3877 (((extid >> 1) & 0x04) | (extid & 0x03));
3878 *busw = 0;
3879 } else if (id_len == 6 && id_data[0] == NAND_MFR_HYNIX &&
3880 !nand_is_slc(chip)) {
3881 unsigned int tmp;
3883 /* Calc pagesize */
3884 mtd->writesize = 2048 << (extid & 0x03);
3885 extid >>= 2;
3886 /* Calc oobsize */
3887 switch (((extid >> 2) & 0x04) | (extid & 0x03)) {
3888 case 0:
3889 mtd->oobsize = 128;
3890 break;
3891 case 1:
3892 mtd->oobsize = 224;
3893 break;
3894 case 2:
3895 mtd->oobsize = 448;
3896 break;
3897 case 3:
3898 mtd->oobsize = 64;
3899 break;
3900 case 4:
3901 mtd->oobsize = 32;
3902 break;
3903 case 5:
3904 mtd->oobsize = 16;
3905 break;
3906 default:
3907 mtd->oobsize = 640;
3908 break;
3910 extid >>= 2;
3911 /* Calc blocksize */
3912 tmp = ((extid >> 1) & 0x04) | (extid & 0x03);
3913 if (tmp < 0x03)
3914 mtd->erasesize = (128 * 1024) << tmp;
3915 else if (tmp == 0x03)
3916 mtd->erasesize = 768 * 1024;
3917 else
3918 mtd->erasesize = (64 * 1024) << tmp;
3919 *busw = 0;
3920 } else {
3921 /* Calc pagesize */
3922 mtd->writesize = 1024 << (extid & 0x03);
3923 extid >>= 2;
3924 /* Calc oobsize */
3925 mtd->oobsize = (8 << (extid & 0x01)) *
3926 (mtd->writesize >> 9);
3927 extid >>= 2;
3928 /* Calc blocksize. Blocksize is multiples of 64KiB */
3929 mtd->erasesize = (64 * 1024) << (extid & 0x03);
3930 extid >>= 2;
3931 /* Get buswidth information */
3932 *busw = (extid & 0x01) ? NAND_BUSWIDTH_16 : 0;
3935 * Toshiba 24nm raw SLC (i.e., not BENAND) have 32B OOB per
3936 * 512B page. For Toshiba SLC, we decode the 5th/6th byte as
3937 * follows:
3938 * - ID byte 6, bits[2:0]: 100b -> 43nm, 101b -> 32nm,
3939 * 110b -> 24nm
3940 * - ID byte 5, bit[7]: 1 -> BENAND, 0 -> raw SLC
3942 if (id_len >= 6 && id_data[0] == NAND_MFR_TOSHIBA &&
3943 nand_is_slc(chip) &&
3944 (id_data[5] & 0x7) == 0x6 /* 24nm */ &&
3945 !(id_data[4] & 0x80) /* !BENAND */) {
3946 mtd->oobsize = 32 * mtd->writesize >> 9;
3953 * Old devices have chip data hardcoded in the device ID table. nand_decode_id
3954 * decodes a matching ID table entry and assigns the MTD size parameters for
3955 * the chip.
3957 static void nand_decode_id(struct mtd_info *mtd, struct nand_chip *chip,
3958 struct nand_flash_dev *type, u8 id_data[8],
3959 int *busw)
3961 int maf_id = id_data[0];
3963 mtd->erasesize = type->erasesize;
3964 mtd->writesize = type->pagesize;
3965 mtd->oobsize = mtd->writesize / 32;
3966 *busw = type->options & NAND_BUSWIDTH_16;
3968 /* All legacy ID NAND are small-page, SLC */
3969 chip->bits_per_cell = 1;
3972 * Check for Spansion/AMD ID + repeating 5th, 6th byte since
3973 * some Spansion chips have erasesize that conflicts with size
3974 * listed in nand_ids table.
3975 * Data sheet (5 byte ID): Spansion S30ML-P ORNAND (p.39)
3977 if (maf_id == NAND_MFR_AMD && id_data[4] != 0x00 && id_data[5] == 0x00
3978 && id_data[6] == 0x00 && id_data[7] == 0x00
3979 && mtd->writesize == 512) {
3980 mtd->erasesize = 128 * 1024;
3981 mtd->erasesize <<= ((id_data[3] & 0x03) << 1);
3986 * Set the bad block marker/indicator (BBM/BBI) patterns according to some
3987 * heuristic patterns using various detected parameters (e.g., manufacturer,
3988 * page size, cell-type information).
3990 static void nand_decode_bbm_options(struct mtd_info *mtd,
3991 struct nand_chip *chip, u8 id_data[8])
3993 int maf_id = id_data[0];
3995 /* Set the bad block position */
3996 if (mtd->writesize > 512 || (chip->options & NAND_BUSWIDTH_16))
3997 chip->badblockpos = NAND_LARGE_BADBLOCK_POS;
3998 else
3999 chip->badblockpos = NAND_SMALL_BADBLOCK_POS;
4002 * Bad block marker is stored in the last page of each block on Samsung
4003 * and Hynix MLC devices; stored in first two pages of each block on
4004 * Micron devices with 2KiB pages and on SLC Samsung, Hynix, Toshiba,
4005 * AMD/Spansion, and Macronix. All others scan only the first page.
4007 if (!nand_is_slc(chip) &&
4008 (maf_id == NAND_MFR_SAMSUNG ||
4009 maf_id == NAND_MFR_HYNIX))
4010 chip->bbt_options |= NAND_BBT_SCANLASTPAGE;
4011 else if ((nand_is_slc(chip) &&
4012 (maf_id == NAND_MFR_SAMSUNG ||
4013 maf_id == NAND_MFR_HYNIX ||
4014 maf_id == NAND_MFR_TOSHIBA ||
4015 maf_id == NAND_MFR_AMD ||
4016 maf_id == NAND_MFR_MACRONIX)) ||
4017 (mtd->writesize == 2048 &&
4018 maf_id == NAND_MFR_MICRON))
4019 chip->bbt_options |= NAND_BBT_SCAN2NDPAGE;
4022 static inline bool is_full_id_nand(struct nand_flash_dev *type)
4024 return type->id_len;
4027 static bool find_full_id_nand(struct mtd_info *mtd, struct nand_chip *chip,
4028 struct nand_flash_dev *type, u8 *id_data, int *busw)
4030 if (!strncmp(type->id, id_data, type->id_len)) {
4031 mtd->writesize = type->pagesize;
4032 mtd->erasesize = type->erasesize;
4033 mtd->oobsize = type->oobsize;
4035 chip->bits_per_cell = nand_get_bits_per_cell(id_data[2]);
4036 chip->chipsize = (uint64_t)type->chipsize << 20;
4037 chip->options |= type->options;
4038 chip->ecc_strength_ds = NAND_ECC_STRENGTH(type);
4039 chip->ecc_step_ds = NAND_ECC_STEP(type);
4040 chip->onfi_timing_mode_default =
4041 type->onfi_timing_mode_default;
4043 *busw = type->options & NAND_BUSWIDTH_16;
4045 if (!mtd->name)
4046 mtd->name = type->name;
4048 return true;
4050 return false;
4054 * Get the flash and manufacturer id and lookup if the type is supported.
4056 static struct nand_flash_dev *nand_get_flash_type(struct mtd_info *mtd,
4057 struct nand_chip *chip,
4058 int *maf_id, int *dev_id,
4059 struct nand_flash_dev *type)
4061 int busw;
4062 int i, maf_idx;
4063 u8 id_data[8];
4066 * Reset the chip, required by some chips (e.g. Micron MT29FxGxxxxx)
4067 * after power-up.
4069 nand_reset(chip, 0);
4071 /* Select the device */
4072 chip->select_chip(mtd, 0);
4074 /* Send the command for reading device ID */
4075 chip->cmdfunc(mtd, NAND_CMD_READID, 0x00, -1);
4077 /* Read manufacturer and device IDs */
4078 *maf_id = chip->read_byte(mtd);
4079 *dev_id = chip->read_byte(mtd);
4082 * Try again to make sure, as some systems the bus-hold or other
4083 * interface concerns can cause random data which looks like a
4084 * possibly credible NAND flash to appear. If the two results do
4085 * not match, ignore the device completely.
4088 chip->cmdfunc(mtd, NAND_CMD_READID, 0x00, -1);
4090 /* Read entire ID string */
4091 for (i = 0; i < 8; i++)
4092 id_data[i] = chip->read_byte(mtd);
4094 if (id_data[0] != *maf_id || id_data[1] != *dev_id) {
4095 pr_info("second ID read did not match %02x,%02x against %02x,%02x\n",
4096 *maf_id, *dev_id, id_data[0], id_data[1]);
4097 return ERR_PTR(-ENODEV);
4100 if (!type)
4101 type = nand_flash_ids;
4103 for (; type->name != NULL; type++) {
4104 if (is_full_id_nand(type)) {
4105 if (find_full_id_nand(mtd, chip, type, id_data, &busw))
4106 goto ident_done;
4107 } else if (*dev_id == type->dev_id) {
4108 break;
4112 chip->onfi_version = 0;
4113 if (!type->name || !type->pagesize) {
4114 /* Check if the chip is ONFI compliant */
4115 if (nand_flash_detect_onfi(mtd, chip, &busw))
4116 goto ident_done;
4118 /* Check if the chip is JEDEC compliant */
4119 if (nand_flash_detect_jedec(mtd, chip, &busw))
4120 goto ident_done;
4123 if (!type->name)
4124 return ERR_PTR(-ENODEV);
4126 if (!mtd->name)
4127 mtd->name = type->name;
4129 chip->chipsize = (uint64_t)type->chipsize << 20;
4131 if (!type->pagesize) {
4132 /* Decode parameters from extended ID */
4133 nand_decode_ext_id(mtd, chip, id_data, &busw);
4134 } else {
4135 nand_decode_id(mtd, chip, type, id_data, &busw);
4137 /* Get chip options */
4138 chip->options |= type->options;
4141 * Check if chip is not a Samsung device. Do not clear the
4142 * options for chips which do not have an extended id.
4144 if (*maf_id != NAND_MFR_SAMSUNG && !type->pagesize)
4145 chip->options &= ~NAND_SAMSUNG_LP_OPTIONS;
4146 ident_done:
4148 /* Try to identify manufacturer */
4149 for (maf_idx = 0; nand_manuf_ids[maf_idx].id != 0x0; maf_idx++) {
4150 if (nand_manuf_ids[maf_idx].id == *maf_id)
4151 break;
4154 if (chip->options & NAND_BUSWIDTH_AUTO) {
4155 WARN_ON(chip->options & NAND_BUSWIDTH_16);
4156 chip->options |= busw;
4157 nand_set_defaults(chip, busw);
4158 } else if (busw != (chip->options & NAND_BUSWIDTH_16)) {
4160 * Check, if buswidth is correct. Hardware drivers should set
4161 * chip correct!
4163 pr_info("device found, Manufacturer ID: 0x%02x, Chip ID: 0x%02x\n",
4164 *maf_id, *dev_id);
4165 pr_info("%s %s\n", nand_manuf_ids[maf_idx].name, mtd->name);
4166 pr_warn("bus width %d instead %d bit\n",
4167 (chip->options & NAND_BUSWIDTH_16) ? 16 : 8,
4168 busw ? 16 : 8);
4169 return ERR_PTR(-EINVAL);
4172 nand_decode_bbm_options(mtd, chip, id_data);
4174 /* Calculate the address shift from the page size */
4175 chip->page_shift = ffs(mtd->writesize) - 1;
4176 /* Convert chipsize to number of pages per chip -1 */
4177 chip->pagemask = (chip->chipsize >> chip->page_shift) - 1;
4179 chip->bbt_erase_shift = chip->phys_erase_shift =
4180 ffs(mtd->erasesize) - 1;
4181 if (chip->chipsize & 0xffffffff)
4182 chip->chip_shift = ffs((unsigned)chip->chipsize) - 1;
4183 else {
4184 chip->chip_shift = ffs((unsigned)(chip->chipsize >> 32));
4185 chip->chip_shift += 32 - 1;
4188 chip->badblockbits = 8;
4189 chip->erase = single_erase;
4191 /* Do not replace user supplied command function! */
4192 if (mtd->writesize > 512 && chip->cmdfunc == nand_command)
4193 chip->cmdfunc = nand_command_lp;
4195 pr_info("device found, Manufacturer ID: 0x%02x, Chip ID: 0x%02x\n",
4196 *maf_id, *dev_id);
4198 if (chip->onfi_version)
4199 pr_info("%s %s\n", nand_manuf_ids[maf_idx].name,
4200 chip->onfi_params.model);
4201 else if (chip->jedec_version)
4202 pr_info("%s %s\n", nand_manuf_ids[maf_idx].name,
4203 chip->jedec_params.model);
4204 else
4205 pr_info("%s %s\n", nand_manuf_ids[maf_idx].name,
4206 type->name);
4208 pr_info("%d MiB, %s, erase size: %d KiB, page size: %d, OOB size: %d\n",
4209 (int)(chip->chipsize >> 20), nand_is_slc(chip) ? "SLC" : "MLC",
4210 mtd->erasesize >> 10, mtd->writesize, mtd->oobsize);
4211 return type;
4214 static const char * const nand_ecc_modes[] = {
4215 [NAND_ECC_NONE] = "none",
4216 [NAND_ECC_SOFT] = "soft",
4217 [NAND_ECC_HW] = "hw",
4218 [NAND_ECC_HW_SYNDROME] = "hw_syndrome",
4219 [NAND_ECC_HW_OOB_FIRST] = "hw_oob_first",
4222 static int of_get_nand_ecc_mode(struct device_node *np)
4224 const char *pm;
4225 int err, i;
4227 err = of_property_read_string(np, "nand-ecc-mode", &pm);
4228 if (err < 0)
4229 return err;
4231 for (i = 0; i < ARRAY_SIZE(nand_ecc_modes); i++)
4232 if (!strcasecmp(pm, nand_ecc_modes[i]))
4233 return i;
4236 * For backward compatibility we support few obsoleted values that don't
4237 * have their mappings into nand_ecc_modes_t anymore (they were merged
4238 * with other enums).
4240 if (!strcasecmp(pm, "soft_bch"))
4241 return NAND_ECC_SOFT;
4243 return -ENODEV;
4246 static const char * const nand_ecc_algos[] = {
4247 [NAND_ECC_HAMMING] = "hamming",
4248 [NAND_ECC_BCH] = "bch",
4251 static int of_get_nand_ecc_algo(struct device_node *np)
4253 const char *pm;
4254 int err, i;
4256 err = of_property_read_string(np, "nand-ecc-algo", &pm);
4257 if (!err) {
4258 for (i = NAND_ECC_HAMMING; i < ARRAY_SIZE(nand_ecc_algos); i++)
4259 if (!strcasecmp(pm, nand_ecc_algos[i]))
4260 return i;
4261 return -ENODEV;
4265 * For backward compatibility we also read "nand-ecc-mode" checking
4266 * for some obsoleted values that were specifying ECC algorithm.
4268 err = of_property_read_string(np, "nand-ecc-mode", &pm);
4269 if (err < 0)
4270 return err;
4272 if (!strcasecmp(pm, "soft"))
4273 return NAND_ECC_HAMMING;
4274 else if (!strcasecmp(pm, "soft_bch"))
4275 return NAND_ECC_BCH;
4277 return -ENODEV;
4280 static int of_get_nand_ecc_step_size(struct device_node *np)
4282 int ret;
4283 u32 val;
4285 ret = of_property_read_u32(np, "nand-ecc-step-size", &val);
4286 return ret ? ret : val;
4289 static int of_get_nand_ecc_strength(struct device_node *np)
4291 int ret;
4292 u32 val;
4294 ret = of_property_read_u32(np, "nand-ecc-strength", &val);
4295 return ret ? ret : val;
4298 static int of_get_nand_bus_width(struct device_node *np)
4300 u32 val;
4302 if (of_property_read_u32(np, "nand-bus-width", &val))
4303 return 8;
4305 switch (val) {
4306 case 8:
4307 case 16:
4308 return val;
4309 default:
4310 return -EIO;
4314 static bool of_get_nand_on_flash_bbt(struct device_node *np)
4316 return of_property_read_bool(np, "nand-on-flash-bbt");
4319 static int nand_dt_init(struct nand_chip *chip)
4321 struct device_node *dn = nand_get_flash_node(chip);
4322 int ecc_mode, ecc_algo, ecc_strength, ecc_step;
4324 if (!dn)
4325 return 0;
4327 if (of_get_nand_bus_width(dn) == 16)
4328 chip->options |= NAND_BUSWIDTH_16;
4330 if (of_get_nand_on_flash_bbt(dn))
4331 chip->bbt_options |= NAND_BBT_USE_FLASH;
4333 ecc_mode = of_get_nand_ecc_mode(dn);
4334 ecc_algo = of_get_nand_ecc_algo(dn);
4335 ecc_strength = of_get_nand_ecc_strength(dn);
4336 ecc_step = of_get_nand_ecc_step_size(dn);
4338 if ((ecc_step >= 0 && !(ecc_strength >= 0)) ||
4339 (!(ecc_step >= 0) && ecc_strength >= 0)) {
4340 pr_err("must set both strength and step size in DT\n");
4341 return -EINVAL;
4344 if (ecc_mode >= 0)
4345 chip->ecc.mode = ecc_mode;
4347 if (ecc_algo >= 0)
4348 chip->ecc.algo = ecc_algo;
4350 if (ecc_strength >= 0)
4351 chip->ecc.strength = ecc_strength;
4353 if (ecc_step > 0)
4354 chip->ecc.size = ecc_step;
4356 if (of_property_read_bool(dn, "nand-ecc-maximize"))
4357 chip->ecc.options |= NAND_ECC_MAXIMIZE;
4359 return 0;
4363 * nand_scan_ident - [NAND Interface] Scan for the NAND device
4364 * @mtd: MTD device structure
4365 * @maxchips: number of chips to scan for
4366 * @table: alternative NAND ID table
4368 * This is the first phase of the normal nand_scan() function. It reads the
4369 * flash ID and sets up MTD fields accordingly.
4372 int nand_scan_ident(struct mtd_info *mtd, int maxchips,
4373 struct nand_flash_dev *table)
4375 int i, nand_maf_id, nand_dev_id;
4376 struct nand_chip *chip = mtd_to_nand(mtd);
4377 struct nand_flash_dev *type;
4378 int ret;
4380 ret = nand_dt_init(chip);
4381 if (ret)
4382 return ret;
4384 if (!mtd->name && mtd->dev.parent)
4385 mtd->name = dev_name(mtd->dev.parent);
4387 if ((!chip->cmdfunc || !chip->select_chip) && !chip->cmd_ctrl) {
4389 * Default functions assigned for chip_select() and
4390 * cmdfunc() both expect cmd_ctrl() to be populated,
4391 * so we need to check that that's the case
4393 pr_err("chip.cmd_ctrl() callback is not provided");
4394 return -EINVAL;
4396 /* Set the default functions */
4397 nand_set_defaults(chip, chip->options & NAND_BUSWIDTH_16);
4399 /* Read the flash type */
4400 type = nand_get_flash_type(mtd, chip, &nand_maf_id,
4401 &nand_dev_id, table);
4403 if (IS_ERR(type)) {
4404 if (!(chip->options & NAND_SCAN_SILENT_NODEV))
4405 pr_warn("No NAND device found\n");
4406 chip->select_chip(mtd, -1);
4407 return PTR_ERR(type);
4410 /* Initialize the ->data_interface field. */
4411 ret = nand_init_data_interface(chip);
4412 if (ret)
4413 return ret;
4416 * Setup the data interface correctly on the chip and controller side.
4417 * This explicit call to nand_setup_data_interface() is only required
4418 * for the first die, because nand_reset() has been called before
4419 * ->data_interface and ->default_onfi_timing_mode were set.
4420 * For the other dies, nand_reset() will automatically switch to the
4421 * best mode for us.
4423 ret = nand_setup_data_interface(chip);
4424 if (ret)
4425 return ret;
4427 chip->select_chip(mtd, -1);
4429 /* Check for a chip array */
4430 for (i = 1; i < maxchips; i++) {
4431 /* See comment in nand_get_flash_type for reset */
4432 nand_reset(chip, i);
4434 chip->select_chip(mtd, i);
4435 /* Send the command for reading device ID */
4436 chip->cmdfunc(mtd, NAND_CMD_READID, 0x00, -1);
4437 /* Read manufacturer and device IDs */
4438 if (nand_maf_id != chip->read_byte(mtd) ||
4439 nand_dev_id != chip->read_byte(mtd)) {
4440 chip->select_chip(mtd, -1);
4441 break;
4443 chip->select_chip(mtd, -1);
4445 if (i > 1)
4446 pr_info("%d chips detected\n", i);
4448 /* Store the number of chips and calc total size for mtd */
4449 chip->numchips = i;
4450 mtd->size = i * chip->chipsize;
4452 return 0;
4454 EXPORT_SYMBOL(nand_scan_ident);
4456 static int nand_set_ecc_soft_ops(struct mtd_info *mtd)
4458 struct nand_chip *chip = mtd_to_nand(mtd);
4459 struct nand_ecc_ctrl *ecc = &chip->ecc;
4461 if (WARN_ON(ecc->mode != NAND_ECC_SOFT))
4462 return -EINVAL;
4464 switch (ecc->algo) {
4465 case NAND_ECC_HAMMING:
4466 ecc->calculate = nand_calculate_ecc;
4467 ecc->correct = nand_correct_data;
4468 ecc->read_page = nand_read_page_swecc;
4469 ecc->read_subpage = nand_read_subpage;
4470 ecc->write_page = nand_write_page_swecc;
4471 ecc->read_page_raw = nand_read_page_raw;
4472 ecc->write_page_raw = nand_write_page_raw;
4473 ecc->read_oob = nand_read_oob_std;
4474 ecc->write_oob = nand_write_oob_std;
4475 if (!ecc->size)
4476 ecc->size = 256;
4477 ecc->bytes = 3;
4478 ecc->strength = 1;
4479 return 0;
4480 case NAND_ECC_BCH:
4481 if (!mtd_nand_has_bch()) {
4482 WARN(1, "CONFIG_MTD_NAND_ECC_BCH not enabled\n");
4483 return -EINVAL;
4485 ecc->calculate = nand_bch_calculate_ecc;
4486 ecc->correct = nand_bch_correct_data;
4487 ecc->read_page = nand_read_page_swecc;
4488 ecc->read_subpage = nand_read_subpage;
4489 ecc->write_page = nand_write_page_swecc;
4490 ecc->read_page_raw = nand_read_page_raw;
4491 ecc->write_page_raw = nand_write_page_raw;
4492 ecc->read_oob = nand_read_oob_std;
4493 ecc->write_oob = nand_write_oob_std;
4496 * Board driver should supply ecc.size and ecc.strength
4497 * values to select how many bits are correctable.
4498 * Otherwise, default to 4 bits for large page devices.
4500 if (!ecc->size && (mtd->oobsize >= 64)) {
4501 ecc->size = 512;
4502 ecc->strength = 4;
4506 * if no ecc placement scheme was provided pickup the default
4507 * large page one.
4509 if (!mtd->ooblayout) {
4510 /* handle large page devices only */
4511 if (mtd->oobsize < 64) {
4512 WARN(1, "OOB layout is required when using software BCH on small pages\n");
4513 return -EINVAL;
4516 mtd_set_ooblayout(mtd, &nand_ooblayout_lp_ops);
4521 * We can only maximize ECC config when the default layout is
4522 * used, otherwise we don't know how many bytes can really be
4523 * used.
4525 if (mtd->ooblayout == &nand_ooblayout_lp_ops &&
4526 ecc->options & NAND_ECC_MAXIMIZE) {
4527 int steps, bytes;
4529 /* Always prefer 1k blocks over 512bytes ones */
4530 ecc->size = 1024;
4531 steps = mtd->writesize / ecc->size;
4533 /* Reserve 2 bytes for the BBM */
4534 bytes = (mtd->oobsize - 2) / steps;
4535 ecc->strength = bytes * 8 / fls(8 * ecc->size);
4538 /* See nand_bch_init() for details. */
4539 ecc->bytes = 0;
4540 ecc->priv = nand_bch_init(mtd);
4541 if (!ecc->priv) {
4542 WARN(1, "BCH ECC initialization failed!\n");
4543 return -EINVAL;
4545 return 0;
4546 default:
4547 WARN(1, "Unsupported ECC algorithm!\n");
4548 return -EINVAL;
4553 * Check if the chip configuration meet the datasheet requirements.
4555 * If our configuration corrects A bits per B bytes and the minimum
4556 * required correction level is X bits per Y bytes, then we must ensure
4557 * both of the following are true:
4559 * (1) A / B >= X / Y
4560 * (2) A >= X
4562 * Requirement (1) ensures we can correct for the required bitflip density.
4563 * Requirement (2) ensures we can correct even when all bitflips are clumped
4564 * in the same sector.
4566 static bool nand_ecc_strength_good(struct mtd_info *mtd)
4568 struct nand_chip *chip = mtd_to_nand(mtd);
4569 struct nand_ecc_ctrl *ecc = &chip->ecc;
4570 int corr, ds_corr;
4572 if (ecc->size == 0 || chip->ecc_step_ds == 0)
4573 /* Not enough information */
4574 return true;
4577 * We get the number of corrected bits per page to compare
4578 * the correction density.
4580 corr = (mtd->writesize * ecc->strength) / ecc->size;
4581 ds_corr = (mtd->writesize * chip->ecc_strength_ds) / chip->ecc_step_ds;
4583 return corr >= ds_corr && ecc->strength >= chip->ecc_strength_ds;
4587 * nand_scan_tail - [NAND Interface] Scan for the NAND device
4588 * @mtd: MTD device structure
4590 * This is the second phase of the normal nand_scan() function. It fills out
4591 * all the uninitialized function pointers with the defaults and scans for a
4592 * bad block table if appropriate.
4594 int nand_scan_tail(struct mtd_info *mtd)
4596 struct nand_chip *chip = mtd_to_nand(mtd);
4597 struct nand_ecc_ctrl *ecc = &chip->ecc;
4598 struct nand_buffers *nbuf;
4599 int ret;
4601 /* New bad blocks should be marked in OOB, flash-based BBT, or both */
4602 if (WARN_ON((chip->bbt_options & NAND_BBT_NO_OOB_BBM) &&
4603 !(chip->bbt_options & NAND_BBT_USE_FLASH)))
4604 return -EINVAL;
4606 if (!(chip->options & NAND_OWN_BUFFERS)) {
4607 nbuf = kzalloc(sizeof(*nbuf) + mtd->writesize
4608 + mtd->oobsize * 3, GFP_KERNEL);
4609 if (!nbuf)
4610 return -ENOMEM;
4611 nbuf->ecccalc = (uint8_t *)(nbuf + 1);
4612 nbuf->ecccode = nbuf->ecccalc + mtd->oobsize;
4613 nbuf->databuf = nbuf->ecccode + mtd->oobsize;
4615 chip->buffers = nbuf;
4616 } else {
4617 if (!chip->buffers)
4618 return -ENOMEM;
4621 /* Set the internal oob buffer location, just after the page data */
4622 chip->oob_poi = chip->buffers->databuf + mtd->writesize;
4625 * If no default placement scheme is given, select an appropriate one.
4627 if (!mtd->ooblayout &&
4628 !(ecc->mode == NAND_ECC_SOFT && ecc->algo == NAND_ECC_BCH)) {
4629 switch (mtd->oobsize) {
4630 case 8:
4631 case 16:
4632 mtd_set_ooblayout(mtd, &nand_ooblayout_sp_ops);
4633 break;
4634 case 64:
4635 case 128:
4636 mtd_set_ooblayout(mtd, &nand_ooblayout_lp_hamming_ops);
4637 break;
4638 default:
4639 WARN(1, "No oob scheme defined for oobsize %d\n",
4640 mtd->oobsize);
4641 ret = -EINVAL;
4642 goto err_free;
4646 if (!chip->write_page)
4647 chip->write_page = nand_write_page;
4650 * Check ECC mode, default to software if 3byte/512byte hardware ECC is
4651 * selected and we have 256 byte pagesize fallback to software ECC
4654 switch (ecc->mode) {
4655 case NAND_ECC_HW_OOB_FIRST:
4656 /* Similar to NAND_ECC_HW, but a separate read_page handle */
4657 if (!ecc->calculate || !ecc->correct || !ecc->hwctl) {
4658 WARN(1, "No ECC functions supplied; hardware ECC not possible\n");
4659 ret = -EINVAL;
4660 goto err_free;
4662 if (!ecc->read_page)
4663 ecc->read_page = nand_read_page_hwecc_oob_first;
4665 case NAND_ECC_HW:
4666 /* Use standard hwecc read page function? */
4667 if (!ecc->read_page)
4668 ecc->read_page = nand_read_page_hwecc;
4669 if (!ecc->write_page)
4670 ecc->write_page = nand_write_page_hwecc;
4671 if (!ecc->read_page_raw)
4672 ecc->read_page_raw = nand_read_page_raw;
4673 if (!ecc->write_page_raw)
4674 ecc->write_page_raw = nand_write_page_raw;
4675 if (!ecc->read_oob)
4676 ecc->read_oob = nand_read_oob_std;
4677 if (!ecc->write_oob)
4678 ecc->write_oob = nand_write_oob_std;
4679 if (!ecc->read_subpage)
4680 ecc->read_subpage = nand_read_subpage;
4681 if (!ecc->write_subpage && ecc->hwctl && ecc->calculate)
4682 ecc->write_subpage = nand_write_subpage_hwecc;
4684 case NAND_ECC_HW_SYNDROME:
4685 if ((!ecc->calculate || !ecc->correct || !ecc->hwctl) &&
4686 (!ecc->read_page ||
4687 ecc->read_page == nand_read_page_hwecc ||
4688 !ecc->write_page ||
4689 ecc->write_page == nand_write_page_hwecc)) {
4690 WARN(1, "No ECC functions supplied; hardware ECC not possible\n");
4691 ret = -EINVAL;
4692 goto err_free;
4694 /* Use standard syndrome read/write page function? */
4695 if (!ecc->read_page)
4696 ecc->read_page = nand_read_page_syndrome;
4697 if (!ecc->write_page)
4698 ecc->write_page = nand_write_page_syndrome;
4699 if (!ecc->read_page_raw)
4700 ecc->read_page_raw = nand_read_page_raw_syndrome;
4701 if (!ecc->write_page_raw)
4702 ecc->write_page_raw = nand_write_page_raw_syndrome;
4703 if (!ecc->read_oob)
4704 ecc->read_oob = nand_read_oob_syndrome;
4705 if (!ecc->write_oob)
4706 ecc->write_oob = nand_write_oob_syndrome;
4708 if (mtd->writesize >= ecc->size) {
4709 if (!ecc->strength) {
4710 WARN(1, "Driver must set ecc.strength when using hardware ECC\n");
4711 ret = -EINVAL;
4712 goto err_free;
4714 break;
4716 pr_warn("%d byte HW ECC not possible on %d byte page size, fallback to SW ECC\n",
4717 ecc->size, mtd->writesize);
4718 ecc->mode = NAND_ECC_SOFT;
4719 ecc->algo = NAND_ECC_HAMMING;
4721 case NAND_ECC_SOFT:
4722 ret = nand_set_ecc_soft_ops(mtd);
4723 if (ret) {
4724 ret = -EINVAL;
4725 goto err_free;
4727 break;
4729 case NAND_ECC_NONE:
4730 pr_warn("NAND_ECC_NONE selected by board driver. This is not recommended!\n");
4731 ecc->read_page = nand_read_page_raw;
4732 ecc->write_page = nand_write_page_raw;
4733 ecc->read_oob = nand_read_oob_std;
4734 ecc->read_page_raw = nand_read_page_raw;
4735 ecc->write_page_raw = nand_write_page_raw;
4736 ecc->write_oob = nand_write_oob_std;
4737 ecc->size = mtd->writesize;
4738 ecc->bytes = 0;
4739 ecc->strength = 0;
4740 break;
4742 default:
4743 WARN(1, "Invalid NAND_ECC_MODE %d\n", ecc->mode);
4744 ret = -EINVAL;
4745 goto err_free;
4748 /* For many systems, the standard OOB write also works for raw */
4749 if (!ecc->read_oob_raw)
4750 ecc->read_oob_raw = ecc->read_oob;
4751 if (!ecc->write_oob_raw)
4752 ecc->write_oob_raw = ecc->write_oob;
4754 /* propagate ecc info to mtd_info */
4755 mtd->ecc_strength = ecc->strength;
4756 mtd->ecc_step_size = ecc->size;
4759 * Set the number of read / write steps for one page depending on ECC
4760 * mode.
4762 ecc->steps = mtd->writesize / ecc->size;
4763 if (ecc->steps * ecc->size != mtd->writesize) {
4764 WARN(1, "Invalid ECC parameters\n");
4765 ret = -EINVAL;
4766 goto err_free;
4768 ecc->total = ecc->steps * ecc->bytes;
4771 * The number of bytes available for a client to place data into
4772 * the out of band area.
4774 ret = mtd_ooblayout_count_freebytes(mtd);
4775 if (ret < 0)
4776 ret = 0;
4778 mtd->oobavail = ret;
4780 /* ECC sanity check: warn if it's too weak */
4781 if (!nand_ecc_strength_good(mtd))
4782 pr_warn("WARNING: %s: the ECC used on your system is too weak compared to the one required by the NAND chip\n",
4783 mtd->name);
4785 /* Allow subpage writes up to ecc.steps. Not possible for MLC flash */
4786 if (!(chip->options & NAND_NO_SUBPAGE_WRITE) && nand_is_slc(chip)) {
4787 switch (ecc->steps) {
4788 case 2:
4789 mtd->subpage_sft = 1;
4790 break;
4791 case 4:
4792 case 8:
4793 case 16:
4794 mtd->subpage_sft = 2;
4795 break;
4798 chip->subpagesize = mtd->writesize >> mtd->subpage_sft;
4800 /* Initialize state */
4801 chip->state = FL_READY;
4803 /* Invalidate the pagebuffer reference */
4804 chip->pagebuf = -1;
4806 /* Large page NAND with SOFT_ECC should support subpage reads */
4807 switch (ecc->mode) {
4808 case NAND_ECC_SOFT:
4809 if (chip->page_shift > 9)
4810 chip->options |= NAND_SUBPAGE_READ;
4811 break;
4813 default:
4814 break;
4817 /* Fill in remaining MTD driver data */
4818 mtd->type = nand_is_slc(chip) ? MTD_NANDFLASH : MTD_MLCNANDFLASH;
4819 mtd->flags = (chip->options & NAND_ROM) ? MTD_CAP_ROM :
4820 MTD_CAP_NANDFLASH;
4821 mtd->_erase = nand_erase;
4822 mtd->_point = NULL;
4823 mtd->_unpoint = NULL;
4824 mtd->_read = nand_read;
4825 mtd->_write = nand_write;
4826 mtd->_panic_write = panic_nand_write;
4827 mtd->_read_oob = nand_read_oob;
4828 mtd->_write_oob = nand_write_oob;
4829 mtd->_sync = nand_sync;
4830 mtd->_lock = NULL;
4831 mtd->_unlock = NULL;
4832 mtd->_suspend = nand_suspend;
4833 mtd->_resume = nand_resume;
4834 mtd->_reboot = nand_shutdown;
4835 mtd->_block_isreserved = nand_block_isreserved;
4836 mtd->_block_isbad = nand_block_isbad;
4837 mtd->_block_markbad = nand_block_markbad;
4838 mtd->writebufsize = mtd->writesize;
4841 * Initialize bitflip_threshold to its default prior scan_bbt() call.
4842 * scan_bbt() might invoke mtd_read(), thus bitflip_threshold must be
4843 * properly set.
4845 if (!mtd->bitflip_threshold)
4846 mtd->bitflip_threshold = DIV_ROUND_UP(mtd->ecc_strength * 3, 4);
4848 /* Check, if we should skip the bad block table scan */
4849 if (chip->options & NAND_SKIP_BBTSCAN)
4850 return 0;
4852 /* Build bad block table */
4853 return chip->scan_bbt(mtd);
4854 err_free:
4855 if (!(chip->options & NAND_OWN_BUFFERS))
4856 kfree(chip->buffers);
4857 return ret;
4859 EXPORT_SYMBOL(nand_scan_tail);
4862 * is_module_text_address() isn't exported, and it's mostly a pointless
4863 * test if this is a module _anyway_ -- they'd have to try _really_ hard
4864 * to call us from in-kernel code if the core NAND support is modular.
4866 #ifdef MODULE
4867 #define caller_is_module() (1)
4868 #else
4869 #define caller_is_module() \
4870 is_module_text_address((unsigned long)__builtin_return_address(0))
4871 #endif
4874 * nand_scan - [NAND Interface] Scan for the NAND device
4875 * @mtd: MTD device structure
4876 * @maxchips: number of chips to scan for
4878 * This fills out all the uninitialized function pointers with the defaults.
4879 * The flash ID is read and the mtd/chip structures are filled with the
4880 * appropriate values.
4882 int nand_scan(struct mtd_info *mtd, int maxchips)
4884 int ret;
4886 ret = nand_scan_ident(mtd, maxchips, NULL);
4887 if (!ret)
4888 ret = nand_scan_tail(mtd);
4889 return ret;
4891 EXPORT_SYMBOL(nand_scan);
4894 * nand_cleanup - [NAND Interface] Free resources held by the NAND device
4895 * @chip: NAND chip object
4897 void nand_cleanup(struct nand_chip *chip)
4899 if (chip->ecc.mode == NAND_ECC_SOFT &&
4900 chip->ecc.algo == NAND_ECC_BCH)
4901 nand_bch_free((struct nand_bch_control *)chip->ecc.priv);
4903 nand_release_data_interface(chip);
4905 /* Free bad block table memory */
4906 kfree(chip->bbt);
4907 if (!(chip->options & NAND_OWN_BUFFERS))
4908 kfree(chip->buffers);
4910 /* Free bad block descriptor memory */
4911 if (chip->badblock_pattern && chip->badblock_pattern->options
4912 & NAND_BBT_DYNAMICSTRUCT)
4913 kfree(chip->badblock_pattern);
4915 EXPORT_SYMBOL_GPL(nand_cleanup);
4918 * nand_release - [NAND Interface] Unregister the MTD device and free resources
4919 * held by the NAND device
4920 * @mtd: MTD device structure
4922 void nand_release(struct mtd_info *mtd)
4924 mtd_device_unregister(mtd);
4925 nand_cleanup(mtd_to_nand(mtd));
4927 EXPORT_SYMBOL_GPL(nand_release);
4929 MODULE_LICENSE("GPL");
4930 MODULE_AUTHOR("Steven J. Hill <sjhill@realitydiluted.com>");
4931 MODULE_AUTHOR("Thomas Gleixner <tglx@linutronix.de>");
4932 MODULE_DESCRIPTION("Generic NAND flash driver code");