net: smc91x: ACPI Enable lan91x adapters
[linux/fpc-iii.git] / drivers / mtd / nand / nand_base.c
blob0b0dc29d2af78b59ca36bb7f706b1139e065f55a
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);
141 static int check_offs_len(struct mtd_info *mtd,
142 loff_t ofs, uint64_t len)
144 struct nand_chip *chip = mtd_to_nand(mtd);
145 int ret = 0;
147 /* Start address must align on block boundary */
148 if (ofs & ((1ULL << chip->phys_erase_shift) - 1)) {
149 pr_debug("%s: unaligned address\n", __func__);
150 ret = -EINVAL;
153 /* Length must align on block boundary */
154 if (len & ((1ULL << chip->phys_erase_shift) - 1)) {
155 pr_debug("%s: length not block aligned\n", __func__);
156 ret = -EINVAL;
159 return ret;
163 * nand_release_device - [GENERIC] release chip
164 * @mtd: MTD device structure
166 * Release chip lock and wake up anyone waiting on the device.
168 static void nand_release_device(struct mtd_info *mtd)
170 struct nand_chip *chip = mtd_to_nand(mtd);
172 /* Release the controller and the chip */
173 spin_lock(&chip->controller->lock);
174 chip->controller->active = NULL;
175 chip->state = FL_READY;
176 wake_up(&chip->controller->wq);
177 spin_unlock(&chip->controller->lock);
181 * nand_read_byte - [DEFAULT] read one byte from the chip
182 * @mtd: MTD device structure
184 * Default read function for 8bit buswidth
186 static uint8_t nand_read_byte(struct mtd_info *mtd)
188 struct nand_chip *chip = mtd_to_nand(mtd);
189 return readb(chip->IO_ADDR_R);
193 * nand_read_byte16 - [DEFAULT] read one byte endianness aware from the chip
194 * @mtd: MTD device structure
196 * Default read function for 16bit buswidth with endianness conversion.
199 static uint8_t nand_read_byte16(struct mtd_info *mtd)
201 struct nand_chip *chip = mtd_to_nand(mtd);
202 return (uint8_t) cpu_to_le16(readw(chip->IO_ADDR_R));
206 * nand_read_word - [DEFAULT] read one word from the chip
207 * @mtd: MTD device structure
209 * Default read function for 16bit buswidth without endianness conversion.
211 static u16 nand_read_word(struct mtd_info *mtd)
213 struct nand_chip *chip = mtd_to_nand(mtd);
214 return readw(chip->IO_ADDR_R);
218 * nand_select_chip - [DEFAULT] control CE line
219 * @mtd: MTD device structure
220 * @chipnr: chipnumber to select, -1 for deselect
222 * Default select function for 1 chip devices.
224 static void nand_select_chip(struct mtd_info *mtd, int chipnr)
226 struct nand_chip *chip = mtd_to_nand(mtd);
228 switch (chipnr) {
229 case -1:
230 chip->cmd_ctrl(mtd, NAND_CMD_NONE, 0 | NAND_CTRL_CHANGE);
231 break;
232 case 0:
233 break;
235 default:
236 BUG();
241 * nand_write_byte - [DEFAULT] write single byte to chip
242 * @mtd: MTD device structure
243 * @byte: value to write
245 * Default function to write a byte to I/O[7:0]
247 static void nand_write_byte(struct mtd_info *mtd, uint8_t byte)
249 struct nand_chip *chip = mtd_to_nand(mtd);
251 chip->write_buf(mtd, &byte, 1);
255 * nand_write_byte16 - [DEFAULT] write single byte to a chip with width 16
256 * @mtd: MTD device structure
257 * @byte: value to write
259 * Default function to write a byte to I/O[7:0] on a 16-bit wide chip.
261 static void nand_write_byte16(struct mtd_info *mtd, uint8_t byte)
263 struct nand_chip *chip = mtd_to_nand(mtd);
264 uint16_t word = byte;
267 * It's not entirely clear what should happen to I/O[15:8] when writing
268 * a byte. The ONFi spec (Revision 3.1; 2012-09-19, Section 2.16) reads:
270 * When the host supports a 16-bit bus width, only data is
271 * transferred at the 16-bit width. All address and command line
272 * transfers shall use only the lower 8-bits of the data bus. During
273 * command transfers, the host may place any value on the upper
274 * 8-bits of the data bus. During address transfers, the host shall
275 * set the upper 8-bits of the data bus to 00h.
277 * One user of the write_byte callback is nand_onfi_set_features. The
278 * four parameters are specified to be written to I/O[7:0], but this is
279 * neither an address nor a command transfer. Let's assume a 0 on the
280 * upper I/O lines is OK.
282 chip->write_buf(mtd, (uint8_t *)&word, 2);
286 * nand_write_buf - [DEFAULT] write buffer to chip
287 * @mtd: MTD device structure
288 * @buf: data buffer
289 * @len: number of bytes to write
291 * Default write function for 8bit buswidth.
293 static void nand_write_buf(struct mtd_info *mtd, const uint8_t *buf, int len)
295 struct nand_chip *chip = mtd_to_nand(mtd);
297 iowrite8_rep(chip->IO_ADDR_W, buf, len);
301 * nand_read_buf - [DEFAULT] read chip data into buffer
302 * @mtd: MTD device structure
303 * @buf: buffer to store date
304 * @len: number of bytes to read
306 * Default read function for 8bit buswidth.
308 static void nand_read_buf(struct mtd_info *mtd, uint8_t *buf, int len)
310 struct nand_chip *chip = mtd_to_nand(mtd);
312 ioread8_rep(chip->IO_ADDR_R, buf, len);
316 * nand_write_buf16 - [DEFAULT] write buffer to chip
317 * @mtd: MTD device structure
318 * @buf: data buffer
319 * @len: number of bytes to write
321 * Default write function for 16bit buswidth.
323 static void nand_write_buf16(struct mtd_info *mtd, const uint8_t *buf, int len)
325 struct nand_chip *chip = mtd_to_nand(mtd);
326 u16 *p = (u16 *) buf;
328 iowrite16_rep(chip->IO_ADDR_W, p, len >> 1);
332 * nand_read_buf16 - [DEFAULT] read chip data into buffer
333 * @mtd: MTD device structure
334 * @buf: buffer to store date
335 * @len: number of bytes to read
337 * Default read function for 16bit buswidth.
339 static void nand_read_buf16(struct mtd_info *mtd, uint8_t *buf, int len)
341 struct nand_chip *chip = mtd_to_nand(mtd);
342 u16 *p = (u16 *) buf;
344 ioread16_rep(chip->IO_ADDR_R, p, len >> 1);
348 * nand_block_bad - [DEFAULT] Read bad block marker from the chip
349 * @mtd: MTD device structure
350 * @ofs: offset from device start
352 * Check, if the block is bad.
354 static int nand_block_bad(struct mtd_info *mtd, loff_t ofs)
356 int page, res = 0, i = 0;
357 struct nand_chip *chip = mtd_to_nand(mtd);
358 u16 bad;
360 if (chip->bbt_options & NAND_BBT_SCANLASTPAGE)
361 ofs += mtd->erasesize - mtd->writesize;
363 page = (int)(ofs >> chip->page_shift) & chip->pagemask;
365 do {
366 if (chip->options & NAND_BUSWIDTH_16) {
367 chip->cmdfunc(mtd, NAND_CMD_READOOB,
368 chip->badblockpos & 0xFE, page);
369 bad = cpu_to_le16(chip->read_word(mtd));
370 if (chip->badblockpos & 0x1)
371 bad >>= 8;
372 else
373 bad &= 0xFF;
374 } else {
375 chip->cmdfunc(mtd, NAND_CMD_READOOB, chip->badblockpos,
376 page);
377 bad = chip->read_byte(mtd);
380 if (likely(chip->badblockbits == 8))
381 res = bad != 0xFF;
382 else
383 res = hweight8(bad) < chip->badblockbits;
384 ofs += mtd->writesize;
385 page = (int)(ofs >> chip->page_shift) & chip->pagemask;
386 i++;
387 } while (!res && i < 2 && (chip->bbt_options & NAND_BBT_SCAN2NDPAGE));
389 return res;
393 * nand_default_block_markbad - [DEFAULT] mark a block bad via bad block marker
394 * @mtd: MTD device structure
395 * @ofs: offset from device start
397 * This is the default implementation, which can be overridden by a hardware
398 * specific driver. It provides the details for writing a bad block marker to a
399 * block.
401 static int nand_default_block_markbad(struct mtd_info *mtd, loff_t ofs)
403 struct nand_chip *chip = mtd_to_nand(mtd);
404 struct mtd_oob_ops ops;
405 uint8_t buf[2] = { 0, 0 };
406 int ret = 0, res, i = 0;
408 memset(&ops, 0, sizeof(ops));
409 ops.oobbuf = buf;
410 ops.ooboffs = chip->badblockpos;
411 if (chip->options & NAND_BUSWIDTH_16) {
412 ops.ooboffs &= ~0x01;
413 ops.len = ops.ooblen = 2;
414 } else {
415 ops.len = ops.ooblen = 1;
417 ops.mode = MTD_OPS_PLACE_OOB;
419 /* Write to first/last page(s) if necessary */
420 if (chip->bbt_options & NAND_BBT_SCANLASTPAGE)
421 ofs += mtd->erasesize - mtd->writesize;
422 do {
423 res = nand_do_write_oob(mtd, ofs, &ops);
424 if (!ret)
425 ret = res;
427 i++;
428 ofs += mtd->writesize;
429 } while ((chip->bbt_options & NAND_BBT_SCAN2NDPAGE) && i < 2);
431 return ret;
435 * nand_block_markbad_lowlevel - mark a block bad
436 * @mtd: MTD device structure
437 * @ofs: offset from device start
439 * This function performs the generic NAND bad block marking steps (i.e., bad
440 * block table(s) and/or marker(s)). We only allow the hardware driver to
441 * specify how to write bad block markers to OOB (chip->block_markbad).
443 * We try operations in the following order:
444 * (1) erase the affected block, to allow OOB marker to be written cleanly
445 * (2) write bad block marker to OOB area of affected block (unless flag
446 * NAND_BBT_NO_OOB_BBM is present)
447 * (3) update the BBT
448 * Note that we retain the first error encountered in (2) or (3), finish the
449 * procedures, and dump the error in the end.
451 static int nand_block_markbad_lowlevel(struct mtd_info *mtd, loff_t ofs)
453 struct nand_chip *chip = mtd_to_nand(mtd);
454 int res, ret = 0;
456 if (!(chip->bbt_options & NAND_BBT_NO_OOB_BBM)) {
457 struct erase_info einfo;
459 /* Attempt erase before marking OOB */
460 memset(&einfo, 0, sizeof(einfo));
461 einfo.mtd = mtd;
462 einfo.addr = ofs;
463 einfo.len = 1ULL << chip->phys_erase_shift;
464 nand_erase_nand(mtd, &einfo, 0);
466 /* Write bad block marker to OOB */
467 nand_get_device(mtd, FL_WRITING);
468 ret = chip->block_markbad(mtd, ofs);
469 nand_release_device(mtd);
472 /* Mark block bad in BBT */
473 if (chip->bbt) {
474 res = nand_markbad_bbt(mtd, ofs);
475 if (!ret)
476 ret = res;
479 if (!ret)
480 mtd->ecc_stats.badblocks++;
482 return ret;
486 * nand_check_wp - [GENERIC] check if the chip is write protected
487 * @mtd: MTD device structure
489 * Check, if the device is write protected. The function expects, that the
490 * device is already selected.
492 static int nand_check_wp(struct mtd_info *mtd)
494 struct nand_chip *chip = mtd_to_nand(mtd);
496 /* Broken xD cards report WP despite being writable */
497 if (chip->options & NAND_BROKEN_XD)
498 return 0;
500 /* Check the WP bit */
501 chip->cmdfunc(mtd, NAND_CMD_STATUS, -1, -1);
502 return (chip->read_byte(mtd) & NAND_STATUS_WP) ? 0 : 1;
506 * nand_block_isreserved - [GENERIC] Check if a block is marked reserved.
507 * @mtd: MTD device structure
508 * @ofs: offset from device start
510 * Check if the block is marked as reserved.
512 static int nand_block_isreserved(struct mtd_info *mtd, loff_t ofs)
514 struct nand_chip *chip = mtd_to_nand(mtd);
516 if (!chip->bbt)
517 return 0;
518 /* Return info from the table */
519 return nand_isreserved_bbt(mtd, ofs);
523 * nand_block_checkbad - [GENERIC] Check if a block is marked bad
524 * @mtd: MTD device structure
525 * @ofs: offset from device start
526 * @allowbbt: 1, if its allowed to access the bbt area
528 * Check, if the block is bad. Either by reading the bad block table or
529 * calling of the scan function.
531 static int nand_block_checkbad(struct mtd_info *mtd, loff_t ofs, int allowbbt)
533 struct nand_chip *chip = mtd_to_nand(mtd);
535 if (!chip->bbt)
536 return chip->block_bad(mtd, ofs);
538 /* Return info from the table */
539 return nand_isbad_bbt(mtd, ofs, allowbbt);
543 * panic_nand_wait_ready - [GENERIC] Wait for the ready pin after commands.
544 * @mtd: MTD device structure
545 * @timeo: Timeout
547 * Helper function for nand_wait_ready used when needing to wait in interrupt
548 * context.
550 static void panic_nand_wait_ready(struct mtd_info *mtd, unsigned long timeo)
552 struct nand_chip *chip = mtd_to_nand(mtd);
553 int i;
555 /* Wait for the device to get ready */
556 for (i = 0; i < timeo; i++) {
557 if (chip->dev_ready(mtd))
558 break;
559 touch_softlockup_watchdog();
560 mdelay(1);
565 * nand_wait_ready - [GENERIC] Wait for the ready pin after commands.
566 * @mtd: MTD device structure
568 * Wait for the ready pin after a command, and warn if a timeout occurs.
570 void nand_wait_ready(struct mtd_info *mtd)
572 struct nand_chip *chip = mtd_to_nand(mtd);
573 unsigned long timeo = 400;
575 if (in_interrupt() || oops_in_progress)
576 return panic_nand_wait_ready(mtd, timeo);
578 /* Wait until command is processed or timeout occurs */
579 timeo = jiffies + msecs_to_jiffies(timeo);
580 do {
581 if (chip->dev_ready(mtd))
582 return;
583 cond_resched();
584 } while (time_before(jiffies, timeo));
586 if (!chip->dev_ready(mtd))
587 pr_warn_ratelimited("timeout while waiting for chip to become ready\n");
589 EXPORT_SYMBOL_GPL(nand_wait_ready);
592 * nand_wait_status_ready - [GENERIC] Wait for the ready status after commands.
593 * @mtd: MTD device structure
594 * @timeo: Timeout in ms
596 * Wait for status ready (i.e. command done) or timeout.
598 static void nand_wait_status_ready(struct mtd_info *mtd, unsigned long timeo)
600 register struct nand_chip *chip = mtd_to_nand(mtd);
602 timeo = jiffies + msecs_to_jiffies(timeo);
603 do {
604 if ((chip->read_byte(mtd) & NAND_STATUS_READY))
605 break;
606 touch_softlockup_watchdog();
607 } while (time_before(jiffies, timeo));
611 * nand_command - [DEFAULT] Send command to NAND device
612 * @mtd: MTD device structure
613 * @command: the command to be sent
614 * @column: the column address for this command, -1 if none
615 * @page_addr: the page address for this command, -1 if none
617 * Send command to NAND device. This function is used for small page devices
618 * (512 Bytes per page).
620 static void nand_command(struct mtd_info *mtd, unsigned int command,
621 int column, int page_addr)
623 register struct nand_chip *chip = mtd_to_nand(mtd);
624 int ctrl = NAND_CTRL_CLE | NAND_CTRL_CHANGE;
626 /* Write out the command to the device */
627 if (command == NAND_CMD_SEQIN) {
628 int readcmd;
630 if (column >= mtd->writesize) {
631 /* OOB area */
632 column -= mtd->writesize;
633 readcmd = NAND_CMD_READOOB;
634 } else if (column < 256) {
635 /* First 256 bytes --> READ0 */
636 readcmd = NAND_CMD_READ0;
637 } else {
638 column -= 256;
639 readcmd = NAND_CMD_READ1;
641 chip->cmd_ctrl(mtd, readcmd, ctrl);
642 ctrl &= ~NAND_CTRL_CHANGE;
644 chip->cmd_ctrl(mtd, command, ctrl);
646 /* Address cycle, when necessary */
647 ctrl = NAND_CTRL_ALE | NAND_CTRL_CHANGE;
648 /* Serially input address */
649 if (column != -1) {
650 /* Adjust columns for 16 bit buswidth */
651 if (chip->options & NAND_BUSWIDTH_16 &&
652 !nand_opcode_8bits(command))
653 column >>= 1;
654 chip->cmd_ctrl(mtd, column, ctrl);
655 ctrl &= ~NAND_CTRL_CHANGE;
657 if (page_addr != -1) {
658 chip->cmd_ctrl(mtd, page_addr, ctrl);
659 ctrl &= ~NAND_CTRL_CHANGE;
660 chip->cmd_ctrl(mtd, page_addr >> 8, ctrl);
661 /* One more address cycle for devices > 32MiB */
662 if (chip->chipsize > (32 << 20))
663 chip->cmd_ctrl(mtd, page_addr >> 16, ctrl);
665 chip->cmd_ctrl(mtd, NAND_CMD_NONE, NAND_NCE | NAND_CTRL_CHANGE);
668 * Program and erase have their own busy handlers status and sequential
669 * in needs no delay
671 switch (command) {
673 case NAND_CMD_PAGEPROG:
674 case NAND_CMD_ERASE1:
675 case NAND_CMD_ERASE2:
676 case NAND_CMD_SEQIN:
677 case NAND_CMD_STATUS:
678 return;
680 case NAND_CMD_RESET:
681 if (chip->dev_ready)
682 break;
683 udelay(chip->chip_delay);
684 chip->cmd_ctrl(mtd, NAND_CMD_STATUS,
685 NAND_CTRL_CLE | NAND_CTRL_CHANGE);
686 chip->cmd_ctrl(mtd,
687 NAND_CMD_NONE, NAND_NCE | NAND_CTRL_CHANGE);
688 /* EZ-NAND can take upto 250ms as per ONFi v4.0 */
689 nand_wait_status_ready(mtd, 250);
690 return;
692 /* This applies to read commands */
693 default:
695 * If we don't have access to the busy pin, we apply the given
696 * command delay
698 if (!chip->dev_ready) {
699 udelay(chip->chip_delay);
700 return;
704 * Apply this short delay always to ensure that we do wait tWB in
705 * any case on any machine.
707 ndelay(100);
709 nand_wait_ready(mtd);
713 * nand_command_lp - [DEFAULT] Send command to NAND large page device
714 * @mtd: MTD device structure
715 * @command: the command to be sent
716 * @column: the column address for this command, -1 if none
717 * @page_addr: the page address for this command, -1 if none
719 * Send command to NAND device. This is the version for the new large page
720 * devices. We don't have the separate regions as we have in the small page
721 * devices. We must emulate NAND_CMD_READOOB to keep the code compatible.
723 static void nand_command_lp(struct mtd_info *mtd, unsigned int command,
724 int column, int page_addr)
726 register struct nand_chip *chip = mtd_to_nand(mtd);
728 /* Emulate NAND_CMD_READOOB */
729 if (command == NAND_CMD_READOOB) {
730 column += mtd->writesize;
731 command = NAND_CMD_READ0;
734 /* Command latch cycle */
735 chip->cmd_ctrl(mtd, command, NAND_NCE | NAND_CLE | NAND_CTRL_CHANGE);
737 if (column != -1 || page_addr != -1) {
738 int ctrl = NAND_CTRL_CHANGE | NAND_NCE | NAND_ALE;
740 /* Serially input address */
741 if (column != -1) {
742 /* Adjust columns for 16 bit buswidth */
743 if (chip->options & NAND_BUSWIDTH_16 &&
744 !nand_opcode_8bits(command))
745 column >>= 1;
746 chip->cmd_ctrl(mtd, column, ctrl);
747 ctrl &= ~NAND_CTRL_CHANGE;
748 chip->cmd_ctrl(mtd, column >> 8, ctrl);
750 if (page_addr != -1) {
751 chip->cmd_ctrl(mtd, page_addr, ctrl);
752 chip->cmd_ctrl(mtd, page_addr >> 8,
753 NAND_NCE | NAND_ALE);
754 /* One more address cycle for devices > 128MiB */
755 if (chip->chipsize > (128 << 20))
756 chip->cmd_ctrl(mtd, page_addr >> 16,
757 NAND_NCE | NAND_ALE);
760 chip->cmd_ctrl(mtd, NAND_CMD_NONE, NAND_NCE | NAND_CTRL_CHANGE);
763 * Program and erase have their own busy handlers status, sequential
764 * in and status need no delay.
766 switch (command) {
768 case NAND_CMD_CACHEDPROG:
769 case NAND_CMD_PAGEPROG:
770 case NAND_CMD_ERASE1:
771 case NAND_CMD_ERASE2:
772 case NAND_CMD_SEQIN:
773 case NAND_CMD_RNDIN:
774 case NAND_CMD_STATUS:
775 return;
777 case NAND_CMD_RESET:
778 if (chip->dev_ready)
779 break;
780 udelay(chip->chip_delay);
781 chip->cmd_ctrl(mtd, NAND_CMD_STATUS,
782 NAND_NCE | NAND_CLE | NAND_CTRL_CHANGE);
783 chip->cmd_ctrl(mtd, NAND_CMD_NONE,
784 NAND_NCE | NAND_CTRL_CHANGE);
785 /* EZ-NAND can take upto 250ms as per ONFi v4.0 */
786 nand_wait_status_ready(mtd, 250);
787 return;
789 case NAND_CMD_RNDOUT:
790 /* No ready / busy check necessary */
791 chip->cmd_ctrl(mtd, NAND_CMD_RNDOUTSTART,
792 NAND_NCE | NAND_CLE | NAND_CTRL_CHANGE);
793 chip->cmd_ctrl(mtd, NAND_CMD_NONE,
794 NAND_NCE | NAND_CTRL_CHANGE);
795 return;
797 case NAND_CMD_READ0:
798 chip->cmd_ctrl(mtd, NAND_CMD_READSTART,
799 NAND_NCE | NAND_CLE | NAND_CTRL_CHANGE);
800 chip->cmd_ctrl(mtd, NAND_CMD_NONE,
801 NAND_NCE | NAND_CTRL_CHANGE);
803 /* This applies to read commands */
804 default:
806 * If we don't have access to the busy pin, we apply the given
807 * command delay.
809 if (!chip->dev_ready) {
810 udelay(chip->chip_delay);
811 return;
816 * Apply this short delay always to ensure that we do wait tWB in
817 * any case on any machine.
819 ndelay(100);
821 nand_wait_ready(mtd);
825 * panic_nand_get_device - [GENERIC] Get chip for selected access
826 * @chip: the nand chip descriptor
827 * @mtd: MTD device structure
828 * @new_state: the state which is requested
830 * Used when in panic, no locks are taken.
832 static void panic_nand_get_device(struct nand_chip *chip,
833 struct mtd_info *mtd, int new_state)
835 /* Hardware controller shared among independent devices */
836 chip->controller->active = chip;
837 chip->state = new_state;
841 * nand_get_device - [GENERIC] Get chip for selected access
842 * @mtd: MTD device structure
843 * @new_state: the state which is requested
845 * Get the device and lock it for exclusive access
847 static int
848 nand_get_device(struct mtd_info *mtd, int new_state)
850 struct nand_chip *chip = mtd_to_nand(mtd);
851 spinlock_t *lock = &chip->controller->lock;
852 wait_queue_head_t *wq = &chip->controller->wq;
853 DECLARE_WAITQUEUE(wait, current);
854 retry:
855 spin_lock(lock);
857 /* Hardware controller shared among independent devices */
858 if (!chip->controller->active)
859 chip->controller->active = chip;
861 if (chip->controller->active == chip && chip->state == FL_READY) {
862 chip->state = new_state;
863 spin_unlock(lock);
864 return 0;
866 if (new_state == FL_PM_SUSPENDED) {
867 if (chip->controller->active->state == FL_PM_SUSPENDED) {
868 chip->state = FL_PM_SUSPENDED;
869 spin_unlock(lock);
870 return 0;
873 set_current_state(TASK_UNINTERRUPTIBLE);
874 add_wait_queue(wq, &wait);
875 spin_unlock(lock);
876 schedule();
877 remove_wait_queue(wq, &wait);
878 goto retry;
882 * panic_nand_wait - [GENERIC] wait until the command is done
883 * @mtd: MTD device structure
884 * @chip: NAND chip structure
885 * @timeo: timeout
887 * Wait for command done. This is a helper function for nand_wait used when
888 * we are in interrupt context. May happen when in panic and trying to write
889 * an oops through mtdoops.
891 static void panic_nand_wait(struct mtd_info *mtd, struct nand_chip *chip,
892 unsigned long timeo)
894 int i;
895 for (i = 0; i < timeo; i++) {
896 if (chip->dev_ready) {
897 if (chip->dev_ready(mtd))
898 break;
899 } else {
900 if (chip->read_byte(mtd) & NAND_STATUS_READY)
901 break;
903 mdelay(1);
908 * nand_wait - [DEFAULT] wait until the command is done
909 * @mtd: MTD device structure
910 * @chip: NAND chip structure
912 * Wait for command done. This applies to erase and program only.
914 static int nand_wait(struct mtd_info *mtd, struct nand_chip *chip)
917 int status;
918 unsigned long timeo = 400;
921 * Apply this short delay always to ensure that we do wait tWB in any
922 * case on any machine.
924 ndelay(100);
926 chip->cmdfunc(mtd, NAND_CMD_STATUS, -1, -1);
928 if (in_interrupt() || oops_in_progress)
929 panic_nand_wait(mtd, chip, timeo);
930 else {
931 timeo = jiffies + msecs_to_jiffies(timeo);
932 do {
933 if (chip->dev_ready) {
934 if (chip->dev_ready(mtd))
935 break;
936 } else {
937 if (chip->read_byte(mtd) & NAND_STATUS_READY)
938 break;
940 cond_resched();
941 } while (time_before(jiffies, timeo));
944 status = (int)chip->read_byte(mtd);
945 /* This can happen if in case of timeout or buggy dev_ready */
946 WARN_ON(!(status & NAND_STATUS_READY));
947 return status;
951 * __nand_unlock - [REPLACEABLE] unlocks specified locked blocks
952 * @mtd: mtd info
953 * @ofs: offset to start unlock from
954 * @len: length to unlock
955 * @invert: when = 0, unlock the range of blocks within the lower and
956 * upper boundary address
957 * when = 1, unlock the range of blocks outside the boundaries
958 * of the lower and upper boundary address
960 * Returs unlock status.
962 static int __nand_unlock(struct mtd_info *mtd, loff_t ofs,
963 uint64_t len, int invert)
965 int ret = 0;
966 int status, page;
967 struct nand_chip *chip = mtd_to_nand(mtd);
969 /* Submit address of first page to unlock */
970 page = ofs >> chip->page_shift;
971 chip->cmdfunc(mtd, NAND_CMD_UNLOCK1, -1, page & chip->pagemask);
973 /* Submit address of last page to unlock */
974 page = (ofs + len) >> chip->page_shift;
975 chip->cmdfunc(mtd, NAND_CMD_UNLOCK2, -1,
976 (page | invert) & chip->pagemask);
978 /* Call wait ready function */
979 status = chip->waitfunc(mtd, chip);
980 /* See if device thinks it succeeded */
981 if (status & NAND_STATUS_FAIL) {
982 pr_debug("%s: error status = 0x%08x\n",
983 __func__, status);
984 ret = -EIO;
987 return ret;
991 * nand_unlock - [REPLACEABLE] unlocks specified locked blocks
992 * @mtd: mtd info
993 * @ofs: offset to start unlock from
994 * @len: length to unlock
996 * Returns unlock status.
998 int nand_unlock(struct mtd_info *mtd, loff_t ofs, uint64_t len)
1000 int ret = 0;
1001 int chipnr;
1002 struct nand_chip *chip = mtd_to_nand(mtd);
1004 pr_debug("%s: start = 0x%012llx, len = %llu\n",
1005 __func__, (unsigned long long)ofs, len);
1007 if (check_offs_len(mtd, ofs, len))
1008 return -EINVAL;
1010 /* Align to last block address if size addresses end of the device */
1011 if (ofs + len == mtd->size)
1012 len -= mtd->erasesize;
1014 nand_get_device(mtd, FL_UNLOCKING);
1016 /* Shift to get chip number */
1017 chipnr = ofs >> chip->chip_shift;
1019 chip->select_chip(mtd, chipnr);
1022 * Reset the chip.
1023 * If we want to check the WP through READ STATUS and check the bit 7
1024 * we must reset the chip
1025 * some operation can also clear the bit 7 of status register
1026 * eg. erase/program a locked block
1028 chip->cmdfunc(mtd, NAND_CMD_RESET, -1, -1);
1030 /* Check, if it is write protected */
1031 if (nand_check_wp(mtd)) {
1032 pr_debug("%s: device is write protected!\n",
1033 __func__);
1034 ret = -EIO;
1035 goto out;
1038 ret = __nand_unlock(mtd, ofs, len, 0);
1040 out:
1041 chip->select_chip(mtd, -1);
1042 nand_release_device(mtd);
1044 return ret;
1046 EXPORT_SYMBOL(nand_unlock);
1049 * nand_lock - [REPLACEABLE] locks all blocks present in the device
1050 * @mtd: mtd info
1051 * @ofs: offset to start unlock from
1052 * @len: length to unlock
1054 * This feature is not supported in many NAND parts. 'Micron' NAND parts do
1055 * have this feature, but it allows only to lock all blocks, not for specified
1056 * range for block. Implementing 'lock' feature by making use of 'unlock', for
1057 * now.
1059 * Returns lock status.
1061 int nand_lock(struct mtd_info *mtd, loff_t ofs, uint64_t len)
1063 int ret = 0;
1064 int chipnr, status, page;
1065 struct nand_chip *chip = mtd_to_nand(mtd);
1067 pr_debug("%s: start = 0x%012llx, len = %llu\n",
1068 __func__, (unsigned long long)ofs, len);
1070 if (check_offs_len(mtd, ofs, len))
1071 return -EINVAL;
1073 nand_get_device(mtd, FL_LOCKING);
1075 /* Shift to get chip number */
1076 chipnr = ofs >> chip->chip_shift;
1078 chip->select_chip(mtd, chipnr);
1081 * Reset the chip.
1082 * If we want to check the WP through READ STATUS and check the bit 7
1083 * we must reset the chip
1084 * some operation can also clear the bit 7 of status register
1085 * eg. erase/program a locked block
1087 chip->cmdfunc(mtd, NAND_CMD_RESET, -1, -1);
1089 /* Check, if it is write protected */
1090 if (nand_check_wp(mtd)) {
1091 pr_debug("%s: device is write protected!\n",
1092 __func__);
1093 status = MTD_ERASE_FAILED;
1094 ret = -EIO;
1095 goto out;
1098 /* Submit address of first page to lock */
1099 page = ofs >> chip->page_shift;
1100 chip->cmdfunc(mtd, NAND_CMD_LOCK, -1, page & chip->pagemask);
1102 /* Call wait ready function */
1103 status = chip->waitfunc(mtd, chip);
1104 /* See if device thinks it succeeded */
1105 if (status & NAND_STATUS_FAIL) {
1106 pr_debug("%s: error status = 0x%08x\n",
1107 __func__, status);
1108 ret = -EIO;
1109 goto out;
1112 ret = __nand_unlock(mtd, ofs, len, 0x1);
1114 out:
1115 chip->select_chip(mtd, -1);
1116 nand_release_device(mtd);
1118 return ret;
1120 EXPORT_SYMBOL(nand_lock);
1123 * nand_check_erased_buf - check if a buffer contains (almost) only 0xff data
1124 * @buf: buffer to test
1125 * @len: buffer length
1126 * @bitflips_threshold: maximum number of bitflips
1128 * Check if a buffer contains only 0xff, which means the underlying region
1129 * has been erased and is ready to be programmed.
1130 * The bitflips_threshold specify the maximum number of bitflips before
1131 * considering the region is not erased.
1132 * Note: The logic of this function has been extracted from the memweight
1133 * implementation, except that nand_check_erased_buf function exit before
1134 * testing the whole buffer if the number of bitflips exceed the
1135 * bitflips_threshold value.
1137 * Returns a positive number of bitflips less than or equal to
1138 * bitflips_threshold, or -ERROR_CODE for bitflips in excess of the
1139 * threshold.
1141 static int nand_check_erased_buf(void *buf, int len, int bitflips_threshold)
1143 const unsigned char *bitmap = buf;
1144 int bitflips = 0;
1145 int weight;
1147 for (; len && ((uintptr_t)bitmap) % sizeof(long);
1148 len--, bitmap++) {
1149 weight = hweight8(*bitmap);
1150 bitflips += BITS_PER_BYTE - weight;
1151 if (unlikely(bitflips > bitflips_threshold))
1152 return -EBADMSG;
1155 for (; len >= sizeof(long);
1156 len -= sizeof(long), bitmap += sizeof(long)) {
1157 weight = hweight_long(*((unsigned long *)bitmap));
1158 bitflips += BITS_PER_LONG - weight;
1159 if (unlikely(bitflips > bitflips_threshold))
1160 return -EBADMSG;
1163 for (; len > 0; len--, bitmap++) {
1164 weight = hweight8(*bitmap);
1165 bitflips += BITS_PER_BYTE - weight;
1166 if (unlikely(bitflips > bitflips_threshold))
1167 return -EBADMSG;
1170 return bitflips;
1174 * nand_check_erased_ecc_chunk - check if an ECC chunk contains (almost) only
1175 * 0xff data
1176 * @data: data buffer to test
1177 * @datalen: data length
1178 * @ecc: ECC buffer
1179 * @ecclen: ECC length
1180 * @extraoob: extra OOB buffer
1181 * @extraooblen: extra OOB length
1182 * @bitflips_threshold: maximum number of bitflips
1184 * Check if a data buffer and its associated ECC and OOB data contains only
1185 * 0xff pattern, which means the underlying region has been erased and is
1186 * ready to be programmed.
1187 * The bitflips_threshold specify the maximum number of bitflips before
1188 * considering the region as not erased.
1190 * Note:
1191 * 1/ ECC algorithms are working on pre-defined block sizes which are usually
1192 * different from the NAND page size. When fixing bitflips, ECC engines will
1193 * report the number of errors per chunk, and the NAND core infrastructure
1194 * expect you to return the maximum number of bitflips for the whole page.
1195 * This is why you should always use this function on a single chunk and
1196 * not on the whole page. After checking each chunk you should update your
1197 * max_bitflips value accordingly.
1198 * 2/ When checking for bitflips in erased pages you should not only check
1199 * the payload data but also their associated ECC data, because a user might
1200 * have programmed almost all bits to 1 but a few. In this case, we
1201 * shouldn't consider the chunk as erased, and checking ECC bytes prevent
1202 * this case.
1203 * 3/ The extraoob argument is optional, and should be used if some of your OOB
1204 * data are protected by the ECC engine.
1205 * It could also be used if you support subpages and want to attach some
1206 * extra OOB data to an ECC chunk.
1208 * Returns a positive number of bitflips less than or equal to
1209 * bitflips_threshold, or -ERROR_CODE for bitflips in excess of the
1210 * threshold. In case of success, the passed buffers are filled with 0xff.
1212 int nand_check_erased_ecc_chunk(void *data, int datalen,
1213 void *ecc, int ecclen,
1214 void *extraoob, int extraooblen,
1215 int bitflips_threshold)
1217 int data_bitflips = 0, ecc_bitflips = 0, extraoob_bitflips = 0;
1219 data_bitflips = nand_check_erased_buf(data, datalen,
1220 bitflips_threshold);
1221 if (data_bitflips < 0)
1222 return data_bitflips;
1224 bitflips_threshold -= data_bitflips;
1226 ecc_bitflips = nand_check_erased_buf(ecc, ecclen, bitflips_threshold);
1227 if (ecc_bitflips < 0)
1228 return ecc_bitflips;
1230 bitflips_threshold -= ecc_bitflips;
1232 extraoob_bitflips = nand_check_erased_buf(extraoob, extraooblen,
1233 bitflips_threshold);
1234 if (extraoob_bitflips < 0)
1235 return extraoob_bitflips;
1237 if (data_bitflips)
1238 memset(data, 0xff, datalen);
1240 if (ecc_bitflips)
1241 memset(ecc, 0xff, ecclen);
1243 if (extraoob_bitflips)
1244 memset(extraoob, 0xff, extraooblen);
1246 return data_bitflips + ecc_bitflips + extraoob_bitflips;
1248 EXPORT_SYMBOL(nand_check_erased_ecc_chunk);
1251 * nand_read_page_raw - [INTERN] read raw page data without ecc
1252 * @mtd: mtd info structure
1253 * @chip: nand chip info structure
1254 * @buf: buffer to store read data
1255 * @oob_required: caller requires OOB data read to chip->oob_poi
1256 * @page: page number to read
1258 * Not for syndrome calculating ECC controllers, which use a special oob layout.
1260 static int nand_read_page_raw(struct mtd_info *mtd, struct nand_chip *chip,
1261 uint8_t *buf, int oob_required, int page)
1263 chip->read_buf(mtd, buf, mtd->writesize);
1264 if (oob_required)
1265 chip->read_buf(mtd, chip->oob_poi, mtd->oobsize);
1266 return 0;
1270 * nand_read_page_raw_syndrome - [INTERN] read raw page data without ecc
1271 * @mtd: mtd info structure
1272 * @chip: nand chip info structure
1273 * @buf: buffer to store read data
1274 * @oob_required: caller requires OOB data read to chip->oob_poi
1275 * @page: page number to read
1277 * We need a special oob layout and handling even when OOB isn't used.
1279 static int nand_read_page_raw_syndrome(struct mtd_info *mtd,
1280 struct nand_chip *chip, uint8_t *buf,
1281 int oob_required, int page)
1283 int eccsize = chip->ecc.size;
1284 int eccbytes = chip->ecc.bytes;
1285 uint8_t *oob = chip->oob_poi;
1286 int steps, size;
1288 for (steps = chip->ecc.steps; steps > 0; steps--) {
1289 chip->read_buf(mtd, buf, eccsize);
1290 buf += eccsize;
1292 if (chip->ecc.prepad) {
1293 chip->read_buf(mtd, oob, chip->ecc.prepad);
1294 oob += chip->ecc.prepad;
1297 chip->read_buf(mtd, oob, eccbytes);
1298 oob += eccbytes;
1300 if (chip->ecc.postpad) {
1301 chip->read_buf(mtd, oob, chip->ecc.postpad);
1302 oob += chip->ecc.postpad;
1306 size = mtd->oobsize - (oob - chip->oob_poi);
1307 if (size)
1308 chip->read_buf(mtd, oob, size);
1310 return 0;
1314 * nand_read_page_swecc - [REPLACEABLE] software ECC based page read function
1315 * @mtd: mtd info structure
1316 * @chip: nand chip info structure
1317 * @buf: buffer to store read data
1318 * @oob_required: caller requires OOB data read to chip->oob_poi
1319 * @page: page number to read
1321 static int nand_read_page_swecc(struct mtd_info *mtd, struct nand_chip *chip,
1322 uint8_t *buf, int oob_required, int page)
1324 int i, eccsize = chip->ecc.size, ret;
1325 int eccbytes = chip->ecc.bytes;
1326 int eccsteps = chip->ecc.steps;
1327 uint8_t *p = buf;
1328 uint8_t *ecc_calc = chip->buffers->ecccalc;
1329 uint8_t *ecc_code = chip->buffers->ecccode;
1330 unsigned int max_bitflips = 0;
1332 chip->ecc.read_page_raw(mtd, chip, buf, 1, page);
1334 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize)
1335 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
1337 ret = mtd_ooblayout_get_eccbytes(mtd, ecc_code, chip->oob_poi, 0,
1338 chip->ecc.total);
1339 if (ret)
1340 return ret;
1342 eccsteps = chip->ecc.steps;
1343 p = buf;
1345 for (i = 0 ; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
1346 int stat;
1348 stat = chip->ecc.correct(mtd, p, &ecc_code[i], &ecc_calc[i]);
1349 if (stat < 0) {
1350 mtd->ecc_stats.failed++;
1351 } else {
1352 mtd->ecc_stats.corrected += stat;
1353 max_bitflips = max_t(unsigned int, max_bitflips, stat);
1356 return max_bitflips;
1360 * nand_read_subpage - [REPLACEABLE] ECC based sub-page read function
1361 * @mtd: mtd info structure
1362 * @chip: nand chip info structure
1363 * @data_offs: offset of requested data within the page
1364 * @readlen: data length
1365 * @bufpoi: buffer to store read data
1366 * @page: page number to read
1368 static int nand_read_subpage(struct mtd_info *mtd, struct nand_chip *chip,
1369 uint32_t data_offs, uint32_t readlen, uint8_t *bufpoi,
1370 int page)
1372 int start_step, end_step, num_steps, ret;
1373 uint8_t *p;
1374 int data_col_addr, i, gaps = 0;
1375 int datafrag_len, eccfrag_len, aligned_len, aligned_pos;
1376 int busw = (chip->options & NAND_BUSWIDTH_16) ? 2 : 1;
1377 int index, section = 0;
1378 unsigned int max_bitflips = 0;
1379 struct mtd_oob_region oobregion = { };
1381 /* Column address within the page aligned to ECC size (256bytes) */
1382 start_step = data_offs / chip->ecc.size;
1383 end_step = (data_offs + readlen - 1) / chip->ecc.size;
1384 num_steps = end_step - start_step + 1;
1385 index = start_step * chip->ecc.bytes;
1387 /* Data size aligned to ECC ecc.size */
1388 datafrag_len = num_steps * chip->ecc.size;
1389 eccfrag_len = num_steps * chip->ecc.bytes;
1391 data_col_addr = start_step * chip->ecc.size;
1392 /* If we read not a page aligned data */
1393 if (data_col_addr != 0)
1394 chip->cmdfunc(mtd, NAND_CMD_RNDOUT, data_col_addr, -1);
1396 p = bufpoi + data_col_addr;
1397 chip->read_buf(mtd, p, datafrag_len);
1399 /* Calculate ECC */
1400 for (i = 0; i < eccfrag_len ; i += chip->ecc.bytes, p += chip->ecc.size)
1401 chip->ecc.calculate(mtd, p, &chip->buffers->ecccalc[i]);
1404 * The performance is faster if we position offsets according to
1405 * ecc.pos. Let's make sure that there are no gaps in ECC positions.
1407 ret = mtd_ooblayout_find_eccregion(mtd, index, &section, &oobregion);
1408 if (ret)
1409 return ret;
1411 if (oobregion.length < eccfrag_len)
1412 gaps = 1;
1414 if (gaps) {
1415 chip->cmdfunc(mtd, NAND_CMD_RNDOUT, mtd->writesize, -1);
1416 chip->read_buf(mtd, chip->oob_poi, mtd->oobsize);
1417 } else {
1419 * Send the command to read the particular ECC bytes take care
1420 * about buswidth alignment in read_buf.
1422 aligned_pos = oobregion.offset & ~(busw - 1);
1423 aligned_len = eccfrag_len;
1424 if (oobregion.offset & (busw - 1))
1425 aligned_len++;
1426 if ((oobregion.offset + (num_steps * chip->ecc.bytes)) &
1427 (busw - 1))
1428 aligned_len++;
1430 chip->cmdfunc(mtd, NAND_CMD_RNDOUT,
1431 mtd->writesize + aligned_pos, -1);
1432 chip->read_buf(mtd, &chip->oob_poi[aligned_pos], aligned_len);
1435 ret = mtd_ooblayout_get_eccbytes(mtd, chip->buffers->ecccode,
1436 chip->oob_poi, index, eccfrag_len);
1437 if (ret)
1438 return ret;
1440 p = bufpoi + data_col_addr;
1441 for (i = 0; i < eccfrag_len ; i += chip->ecc.bytes, p += chip->ecc.size) {
1442 int stat;
1444 stat = chip->ecc.correct(mtd, p,
1445 &chip->buffers->ecccode[i], &chip->buffers->ecccalc[i]);
1446 if (stat == -EBADMSG &&
1447 (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
1448 /* check for empty pages with bitflips */
1449 stat = nand_check_erased_ecc_chunk(p, chip->ecc.size,
1450 &chip->buffers->ecccode[i],
1451 chip->ecc.bytes,
1452 NULL, 0,
1453 chip->ecc.strength);
1456 if (stat < 0) {
1457 mtd->ecc_stats.failed++;
1458 } else {
1459 mtd->ecc_stats.corrected += stat;
1460 max_bitflips = max_t(unsigned int, max_bitflips, stat);
1463 return max_bitflips;
1467 * nand_read_page_hwecc - [REPLACEABLE] hardware ECC based page read function
1468 * @mtd: mtd info structure
1469 * @chip: nand chip info structure
1470 * @buf: buffer to store read data
1471 * @oob_required: caller requires OOB data read to chip->oob_poi
1472 * @page: page number to read
1474 * Not for syndrome calculating ECC controllers which need a special oob layout.
1476 static int nand_read_page_hwecc(struct mtd_info *mtd, struct nand_chip *chip,
1477 uint8_t *buf, int oob_required, int page)
1479 int i, eccsize = chip->ecc.size, ret;
1480 int eccbytes = chip->ecc.bytes;
1481 int eccsteps = chip->ecc.steps;
1482 uint8_t *p = buf;
1483 uint8_t *ecc_calc = chip->buffers->ecccalc;
1484 uint8_t *ecc_code = chip->buffers->ecccode;
1485 unsigned int max_bitflips = 0;
1487 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
1488 chip->ecc.hwctl(mtd, NAND_ECC_READ);
1489 chip->read_buf(mtd, p, eccsize);
1490 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
1492 chip->read_buf(mtd, chip->oob_poi, mtd->oobsize);
1494 ret = mtd_ooblayout_get_eccbytes(mtd, ecc_code, chip->oob_poi, 0,
1495 chip->ecc.total);
1496 if (ret)
1497 return ret;
1499 eccsteps = chip->ecc.steps;
1500 p = buf;
1502 for (i = 0 ; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
1503 int stat;
1505 stat = chip->ecc.correct(mtd, p, &ecc_code[i], &ecc_calc[i]);
1506 if (stat == -EBADMSG &&
1507 (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
1508 /* check for empty pages with bitflips */
1509 stat = nand_check_erased_ecc_chunk(p, eccsize,
1510 &ecc_code[i], eccbytes,
1511 NULL, 0,
1512 chip->ecc.strength);
1515 if (stat < 0) {
1516 mtd->ecc_stats.failed++;
1517 } else {
1518 mtd->ecc_stats.corrected += stat;
1519 max_bitflips = max_t(unsigned int, max_bitflips, stat);
1522 return max_bitflips;
1526 * nand_read_page_hwecc_oob_first - [REPLACEABLE] hw ecc, read oob first
1527 * @mtd: mtd info structure
1528 * @chip: nand chip info structure
1529 * @buf: buffer to store read data
1530 * @oob_required: caller requires OOB data read to chip->oob_poi
1531 * @page: page number to read
1533 * Hardware ECC for large page chips, require OOB to be read first. For this
1534 * ECC mode, the write_page method is re-used from ECC_HW. These methods
1535 * read/write ECC from the OOB area, unlike the ECC_HW_SYNDROME support with
1536 * multiple ECC steps, follows the "infix ECC" scheme and reads/writes ECC from
1537 * the data area, by overwriting the NAND manufacturer bad block markings.
1539 static int nand_read_page_hwecc_oob_first(struct mtd_info *mtd,
1540 struct nand_chip *chip, uint8_t *buf, int oob_required, int page)
1542 int i, eccsize = chip->ecc.size, ret;
1543 int eccbytes = chip->ecc.bytes;
1544 int eccsteps = chip->ecc.steps;
1545 uint8_t *p = buf;
1546 uint8_t *ecc_code = chip->buffers->ecccode;
1547 uint8_t *ecc_calc = chip->buffers->ecccalc;
1548 unsigned int max_bitflips = 0;
1550 /* Read the OOB area first */
1551 chip->cmdfunc(mtd, NAND_CMD_READOOB, 0, page);
1552 chip->read_buf(mtd, chip->oob_poi, mtd->oobsize);
1553 chip->cmdfunc(mtd, NAND_CMD_READ0, 0, page);
1555 ret = mtd_ooblayout_get_eccbytes(mtd, ecc_code, chip->oob_poi, 0,
1556 chip->ecc.total);
1557 if (ret)
1558 return ret;
1560 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
1561 int stat;
1563 chip->ecc.hwctl(mtd, NAND_ECC_READ);
1564 chip->read_buf(mtd, p, eccsize);
1565 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
1567 stat = chip->ecc.correct(mtd, p, &ecc_code[i], NULL);
1568 if (stat == -EBADMSG &&
1569 (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
1570 /* check for empty pages with bitflips */
1571 stat = nand_check_erased_ecc_chunk(p, eccsize,
1572 &ecc_code[i], eccbytes,
1573 NULL, 0,
1574 chip->ecc.strength);
1577 if (stat < 0) {
1578 mtd->ecc_stats.failed++;
1579 } else {
1580 mtd->ecc_stats.corrected += stat;
1581 max_bitflips = max_t(unsigned int, max_bitflips, stat);
1584 return max_bitflips;
1588 * nand_read_page_syndrome - [REPLACEABLE] hardware ECC syndrome based page read
1589 * @mtd: mtd info structure
1590 * @chip: nand chip info structure
1591 * @buf: buffer to store read data
1592 * @oob_required: caller requires OOB data read to chip->oob_poi
1593 * @page: page number to read
1595 * The hw generator calculates the error syndrome automatically. Therefore we
1596 * need a special oob layout and handling.
1598 static int nand_read_page_syndrome(struct mtd_info *mtd, struct nand_chip *chip,
1599 uint8_t *buf, int oob_required, int page)
1601 int i, eccsize = chip->ecc.size;
1602 int eccbytes = chip->ecc.bytes;
1603 int eccsteps = chip->ecc.steps;
1604 int eccpadbytes = eccbytes + chip->ecc.prepad + chip->ecc.postpad;
1605 uint8_t *p = buf;
1606 uint8_t *oob = chip->oob_poi;
1607 unsigned int max_bitflips = 0;
1609 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
1610 int stat;
1612 chip->ecc.hwctl(mtd, NAND_ECC_READ);
1613 chip->read_buf(mtd, p, eccsize);
1615 if (chip->ecc.prepad) {
1616 chip->read_buf(mtd, oob, chip->ecc.prepad);
1617 oob += chip->ecc.prepad;
1620 chip->ecc.hwctl(mtd, NAND_ECC_READSYN);
1621 chip->read_buf(mtd, oob, eccbytes);
1622 stat = chip->ecc.correct(mtd, p, oob, NULL);
1624 oob += eccbytes;
1626 if (chip->ecc.postpad) {
1627 chip->read_buf(mtd, oob, chip->ecc.postpad);
1628 oob += chip->ecc.postpad;
1631 if (stat == -EBADMSG &&
1632 (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
1633 /* check for empty pages with bitflips */
1634 stat = nand_check_erased_ecc_chunk(p, chip->ecc.size,
1635 oob - eccpadbytes,
1636 eccpadbytes,
1637 NULL, 0,
1638 chip->ecc.strength);
1641 if (stat < 0) {
1642 mtd->ecc_stats.failed++;
1643 } else {
1644 mtd->ecc_stats.corrected += stat;
1645 max_bitflips = max_t(unsigned int, max_bitflips, stat);
1649 /* Calculate remaining oob bytes */
1650 i = mtd->oobsize - (oob - chip->oob_poi);
1651 if (i)
1652 chip->read_buf(mtd, oob, i);
1654 return max_bitflips;
1658 * nand_transfer_oob - [INTERN] Transfer oob to client buffer
1659 * @mtd: mtd info structure
1660 * @oob: oob destination address
1661 * @ops: oob ops structure
1662 * @len: size of oob to transfer
1664 static uint8_t *nand_transfer_oob(struct mtd_info *mtd, uint8_t *oob,
1665 struct mtd_oob_ops *ops, size_t len)
1667 struct nand_chip *chip = mtd_to_nand(mtd);
1668 int ret;
1670 switch (ops->mode) {
1672 case MTD_OPS_PLACE_OOB:
1673 case MTD_OPS_RAW:
1674 memcpy(oob, chip->oob_poi + ops->ooboffs, len);
1675 return oob + len;
1677 case MTD_OPS_AUTO_OOB:
1678 ret = mtd_ooblayout_get_databytes(mtd, oob, chip->oob_poi,
1679 ops->ooboffs, len);
1680 BUG_ON(ret);
1681 return oob + len;
1683 default:
1684 BUG();
1686 return NULL;
1690 * nand_setup_read_retry - [INTERN] Set the READ RETRY mode
1691 * @mtd: MTD device structure
1692 * @retry_mode: the retry mode to use
1694 * Some vendors supply a special command to shift the Vt threshold, to be used
1695 * when there are too many bitflips in a page (i.e., ECC error). After setting
1696 * a new threshold, the host should retry reading the page.
1698 static int nand_setup_read_retry(struct mtd_info *mtd, int retry_mode)
1700 struct nand_chip *chip = mtd_to_nand(mtd);
1702 pr_debug("setting READ RETRY mode %d\n", retry_mode);
1704 if (retry_mode >= chip->read_retries)
1705 return -EINVAL;
1707 if (!chip->setup_read_retry)
1708 return -EOPNOTSUPP;
1710 return chip->setup_read_retry(mtd, retry_mode);
1714 * nand_do_read_ops - [INTERN] Read data with ECC
1715 * @mtd: MTD device structure
1716 * @from: offset to read from
1717 * @ops: oob ops structure
1719 * Internal function. Called with chip held.
1721 static int nand_do_read_ops(struct mtd_info *mtd, loff_t from,
1722 struct mtd_oob_ops *ops)
1724 int chipnr, page, realpage, col, bytes, aligned, oob_required;
1725 struct nand_chip *chip = mtd_to_nand(mtd);
1726 int ret = 0;
1727 uint32_t readlen = ops->len;
1728 uint32_t oobreadlen = ops->ooblen;
1729 uint32_t max_oobsize = mtd_oobavail(mtd, ops);
1731 uint8_t *bufpoi, *oob, *buf;
1732 int use_bufpoi;
1733 unsigned int max_bitflips = 0;
1734 int retry_mode = 0;
1735 bool ecc_fail = false;
1737 chipnr = (int)(from >> chip->chip_shift);
1738 chip->select_chip(mtd, chipnr);
1740 realpage = (int)(from >> chip->page_shift);
1741 page = realpage & chip->pagemask;
1743 col = (int)(from & (mtd->writesize - 1));
1745 buf = ops->datbuf;
1746 oob = ops->oobbuf;
1747 oob_required = oob ? 1 : 0;
1749 while (1) {
1750 unsigned int ecc_failures = mtd->ecc_stats.failed;
1752 bytes = min(mtd->writesize - col, readlen);
1753 aligned = (bytes == mtd->writesize);
1755 if (!aligned)
1756 use_bufpoi = 1;
1757 else if (chip->options & NAND_USE_BOUNCE_BUFFER)
1758 use_bufpoi = !virt_addr_valid(buf);
1759 else
1760 use_bufpoi = 0;
1762 /* Is the current page in the buffer? */
1763 if (realpage != chip->pagebuf || oob) {
1764 bufpoi = use_bufpoi ? chip->buffers->databuf : buf;
1766 if (use_bufpoi && aligned)
1767 pr_debug("%s: using read bounce buffer for buf@%p\n",
1768 __func__, buf);
1770 read_retry:
1771 chip->cmdfunc(mtd, NAND_CMD_READ0, 0x00, page);
1774 * Now read the page into the buffer. Absent an error,
1775 * the read methods return max bitflips per ecc step.
1777 if (unlikely(ops->mode == MTD_OPS_RAW))
1778 ret = chip->ecc.read_page_raw(mtd, chip, bufpoi,
1779 oob_required,
1780 page);
1781 else if (!aligned && NAND_HAS_SUBPAGE_READ(chip) &&
1782 !oob)
1783 ret = chip->ecc.read_subpage(mtd, chip,
1784 col, bytes, bufpoi,
1785 page);
1786 else
1787 ret = chip->ecc.read_page(mtd, chip, bufpoi,
1788 oob_required, page);
1789 if (ret < 0) {
1790 if (use_bufpoi)
1791 /* Invalidate page cache */
1792 chip->pagebuf = -1;
1793 break;
1796 max_bitflips = max_t(unsigned int, max_bitflips, ret);
1798 /* Transfer not aligned data */
1799 if (use_bufpoi) {
1800 if (!NAND_HAS_SUBPAGE_READ(chip) && !oob &&
1801 !(mtd->ecc_stats.failed - ecc_failures) &&
1802 (ops->mode != MTD_OPS_RAW)) {
1803 chip->pagebuf = realpage;
1804 chip->pagebuf_bitflips = ret;
1805 } else {
1806 /* Invalidate page cache */
1807 chip->pagebuf = -1;
1809 memcpy(buf, chip->buffers->databuf + col, bytes);
1812 if (unlikely(oob)) {
1813 int toread = min(oobreadlen, max_oobsize);
1815 if (toread) {
1816 oob = nand_transfer_oob(mtd,
1817 oob, ops, toread);
1818 oobreadlen -= toread;
1822 if (chip->options & NAND_NEED_READRDY) {
1823 /* Apply delay or wait for ready/busy pin */
1824 if (!chip->dev_ready)
1825 udelay(chip->chip_delay);
1826 else
1827 nand_wait_ready(mtd);
1830 if (mtd->ecc_stats.failed - ecc_failures) {
1831 if (retry_mode + 1 < chip->read_retries) {
1832 retry_mode++;
1833 ret = nand_setup_read_retry(mtd,
1834 retry_mode);
1835 if (ret < 0)
1836 break;
1838 /* Reset failures; retry */
1839 mtd->ecc_stats.failed = ecc_failures;
1840 goto read_retry;
1841 } else {
1842 /* No more retry modes; real failure */
1843 ecc_fail = true;
1847 buf += bytes;
1848 } else {
1849 memcpy(buf, chip->buffers->databuf + col, bytes);
1850 buf += bytes;
1851 max_bitflips = max_t(unsigned int, max_bitflips,
1852 chip->pagebuf_bitflips);
1855 readlen -= bytes;
1857 /* Reset to retry mode 0 */
1858 if (retry_mode) {
1859 ret = nand_setup_read_retry(mtd, 0);
1860 if (ret < 0)
1861 break;
1862 retry_mode = 0;
1865 if (!readlen)
1866 break;
1868 /* For subsequent reads align to page boundary */
1869 col = 0;
1870 /* Increment page address */
1871 realpage++;
1873 page = realpage & chip->pagemask;
1874 /* Check, if we cross a chip boundary */
1875 if (!page) {
1876 chipnr++;
1877 chip->select_chip(mtd, -1);
1878 chip->select_chip(mtd, chipnr);
1881 chip->select_chip(mtd, -1);
1883 ops->retlen = ops->len - (size_t) readlen;
1884 if (oob)
1885 ops->oobretlen = ops->ooblen - oobreadlen;
1887 if (ret < 0)
1888 return ret;
1890 if (ecc_fail)
1891 return -EBADMSG;
1893 return max_bitflips;
1897 * nand_read - [MTD Interface] MTD compatibility function for nand_do_read_ecc
1898 * @mtd: MTD device structure
1899 * @from: offset to read from
1900 * @len: number of bytes to read
1901 * @retlen: pointer to variable to store the number of read bytes
1902 * @buf: the databuffer to put data
1904 * Get hold of the chip and call nand_do_read.
1906 static int nand_read(struct mtd_info *mtd, loff_t from, size_t len,
1907 size_t *retlen, uint8_t *buf)
1909 struct mtd_oob_ops ops;
1910 int ret;
1912 nand_get_device(mtd, FL_READING);
1913 memset(&ops, 0, sizeof(ops));
1914 ops.len = len;
1915 ops.datbuf = buf;
1916 ops.mode = MTD_OPS_PLACE_OOB;
1917 ret = nand_do_read_ops(mtd, from, &ops);
1918 *retlen = ops.retlen;
1919 nand_release_device(mtd);
1920 return ret;
1924 * nand_read_oob_std - [REPLACEABLE] the most common OOB data read function
1925 * @mtd: mtd info structure
1926 * @chip: nand chip info structure
1927 * @page: page number to read
1929 int nand_read_oob_std(struct mtd_info *mtd, struct nand_chip *chip, int page)
1931 chip->cmdfunc(mtd, NAND_CMD_READOOB, 0, page);
1932 chip->read_buf(mtd, chip->oob_poi, mtd->oobsize);
1933 return 0;
1935 EXPORT_SYMBOL(nand_read_oob_std);
1938 * nand_read_oob_syndrome - [REPLACEABLE] OOB data read function for HW ECC
1939 * with syndromes
1940 * @mtd: mtd info structure
1941 * @chip: nand chip info structure
1942 * @page: page number to read
1944 int nand_read_oob_syndrome(struct mtd_info *mtd, struct nand_chip *chip,
1945 int page)
1947 int length = mtd->oobsize;
1948 int chunk = chip->ecc.bytes + chip->ecc.prepad + chip->ecc.postpad;
1949 int eccsize = chip->ecc.size;
1950 uint8_t *bufpoi = chip->oob_poi;
1951 int i, toread, sndrnd = 0, pos;
1953 chip->cmdfunc(mtd, NAND_CMD_READ0, chip->ecc.size, page);
1954 for (i = 0; i < chip->ecc.steps; i++) {
1955 if (sndrnd) {
1956 pos = eccsize + i * (eccsize + chunk);
1957 if (mtd->writesize > 512)
1958 chip->cmdfunc(mtd, NAND_CMD_RNDOUT, pos, -1);
1959 else
1960 chip->cmdfunc(mtd, NAND_CMD_READ0, pos, page);
1961 } else
1962 sndrnd = 1;
1963 toread = min_t(int, length, chunk);
1964 chip->read_buf(mtd, bufpoi, toread);
1965 bufpoi += toread;
1966 length -= toread;
1968 if (length > 0)
1969 chip->read_buf(mtd, bufpoi, length);
1971 return 0;
1973 EXPORT_SYMBOL(nand_read_oob_syndrome);
1976 * nand_write_oob_std - [REPLACEABLE] the most common OOB data write function
1977 * @mtd: mtd info structure
1978 * @chip: nand chip info structure
1979 * @page: page number to write
1981 int nand_write_oob_std(struct mtd_info *mtd, struct nand_chip *chip, int page)
1983 int status = 0;
1984 const uint8_t *buf = chip->oob_poi;
1985 int length = mtd->oobsize;
1987 chip->cmdfunc(mtd, NAND_CMD_SEQIN, mtd->writesize, page);
1988 chip->write_buf(mtd, buf, length);
1989 /* Send command to program the OOB data */
1990 chip->cmdfunc(mtd, NAND_CMD_PAGEPROG, -1, -1);
1992 status = chip->waitfunc(mtd, chip);
1994 return status & NAND_STATUS_FAIL ? -EIO : 0;
1996 EXPORT_SYMBOL(nand_write_oob_std);
1999 * nand_write_oob_syndrome - [REPLACEABLE] OOB data write function for HW ECC
2000 * with syndrome - only for large page flash
2001 * @mtd: mtd info structure
2002 * @chip: nand chip info structure
2003 * @page: page number to write
2005 int nand_write_oob_syndrome(struct mtd_info *mtd, struct nand_chip *chip,
2006 int page)
2008 int chunk = chip->ecc.bytes + chip->ecc.prepad + chip->ecc.postpad;
2009 int eccsize = chip->ecc.size, length = mtd->oobsize;
2010 int i, len, pos, status = 0, sndcmd = 0, steps = chip->ecc.steps;
2011 const uint8_t *bufpoi = chip->oob_poi;
2014 * data-ecc-data-ecc ... ecc-oob
2015 * or
2016 * data-pad-ecc-pad-data-pad .... ecc-pad-oob
2018 if (!chip->ecc.prepad && !chip->ecc.postpad) {
2019 pos = steps * (eccsize + chunk);
2020 steps = 0;
2021 } else
2022 pos = eccsize;
2024 chip->cmdfunc(mtd, NAND_CMD_SEQIN, pos, page);
2025 for (i = 0; i < steps; i++) {
2026 if (sndcmd) {
2027 if (mtd->writesize <= 512) {
2028 uint32_t fill = 0xFFFFFFFF;
2030 len = eccsize;
2031 while (len > 0) {
2032 int num = min_t(int, len, 4);
2033 chip->write_buf(mtd, (uint8_t *)&fill,
2034 num);
2035 len -= num;
2037 } else {
2038 pos = eccsize + i * (eccsize + chunk);
2039 chip->cmdfunc(mtd, NAND_CMD_RNDIN, pos, -1);
2041 } else
2042 sndcmd = 1;
2043 len = min_t(int, length, chunk);
2044 chip->write_buf(mtd, bufpoi, len);
2045 bufpoi += len;
2046 length -= len;
2048 if (length > 0)
2049 chip->write_buf(mtd, bufpoi, length);
2051 chip->cmdfunc(mtd, NAND_CMD_PAGEPROG, -1, -1);
2052 status = chip->waitfunc(mtd, chip);
2054 return status & NAND_STATUS_FAIL ? -EIO : 0;
2056 EXPORT_SYMBOL(nand_write_oob_syndrome);
2059 * nand_do_read_oob - [INTERN] NAND read out-of-band
2060 * @mtd: MTD device structure
2061 * @from: offset to read from
2062 * @ops: oob operations description structure
2064 * NAND read out-of-band data from the spare area.
2066 static int nand_do_read_oob(struct mtd_info *mtd, loff_t from,
2067 struct mtd_oob_ops *ops)
2069 int page, realpage, chipnr;
2070 struct nand_chip *chip = mtd_to_nand(mtd);
2071 struct mtd_ecc_stats stats;
2072 int readlen = ops->ooblen;
2073 int len;
2074 uint8_t *buf = ops->oobbuf;
2075 int ret = 0;
2077 pr_debug("%s: from = 0x%08Lx, len = %i\n",
2078 __func__, (unsigned long long)from, readlen);
2080 stats = mtd->ecc_stats;
2082 len = mtd_oobavail(mtd, ops);
2084 if (unlikely(ops->ooboffs >= len)) {
2085 pr_debug("%s: attempt to start read outside oob\n",
2086 __func__);
2087 return -EINVAL;
2090 /* Do not allow reads past end of device */
2091 if (unlikely(from >= mtd->size ||
2092 ops->ooboffs + readlen > ((mtd->size >> chip->page_shift) -
2093 (from >> chip->page_shift)) * len)) {
2094 pr_debug("%s: attempt to read beyond end of device\n",
2095 __func__);
2096 return -EINVAL;
2099 chipnr = (int)(from >> chip->chip_shift);
2100 chip->select_chip(mtd, chipnr);
2102 /* Shift to get page */
2103 realpage = (int)(from >> chip->page_shift);
2104 page = realpage & chip->pagemask;
2106 while (1) {
2107 if (ops->mode == MTD_OPS_RAW)
2108 ret = chip->ecc.read_oob_raw(mtd, chip, page);
2109 else
2110 ret = chip->ecc.read_oob(mtd, chip, page);
2112 if (ret < 0)
2113 break;
2115 len = min(len, readlen);
2116 buf = nand_transfer_oob(mtd, buf, ops, len);
2118 if (chip->options & NAND_NEED_READRDY) {
2119 /* Apply delay or wait for ready/busy pin */
2120 if (!chip->dev_ready)
2121 udelay(chip->chip_delay);
2122 else
2123 nand_wait_ready(mtd);
2126 readlen -= len;
2127 if (!readlen)
2128 break;
2130 /* Increment page address */
2131 realpage++;
2133 page = realpage & chip->pagemask;
2134 /* Check, if we cross a chip boundary */
2135 if (!page) {
2136 chipnr++;
2137 chip->select_chip(mtd, -1);
2138 chip->select_chip(mtd, chipnr);
2141 chip->select_chip(mtd, -1);
2143 ops->oobretlen = ops->ooblen - readlen;
2145 if (ret < 0)
2146 return ret;
2148 if (mtd->ecc_stats.failed - stats.failed)
2149 return -EBADMSG;
2151 return mtd->ecc_stats.corrected - stats.corrected ? -EUCLEAN : 0;
2155 * nand_read_oob - [MTD Interface] NAND read data and/or out-of-band
2156 * @mtd: MTD device structure
2157 * @from: offset to read from
2158 * @ops: oob operation description structure
2160 * NAND read data and/or out-of-band data.
2162 static int nand_read_oob(struct mtd_info *mtd, loff_t from,
2163 struct mtd_oob_ops *ops)
2165 int ret = -ENOTSUPP;
2167 ops->retlen = 0;
2169 /* Do not allow reads past end of device */
2170 if (ops->datbuf && (from + ops->len) > mtd->size) {
2171 pr_debug("%s: attempt to read beyond end of device\n",
2172 __func__);
2173 return -EINVAL;
2176 nand_get_device(mtd, FL_READING);
2178 switch (ops->mode) {
2179 case MTD_OPS_PLACE_OOB:
2180 case MTD_OPS_AUTO_OOB:
2181 case MTD_OPS_RAW:
2182 break;
2184 default:
2185 goto out;
2188 if (!ops->datbuf)
2189 ret = nand_do_read_oob(mtd, from, ops);
2190 else
2191 ret = nand_do_read_ops(mtd, from, ops);
2193 out:
2194 nand_release_device(mtd);
2195 return ret;
2200 * nand_write_page_raw - [INTERN] raw page write function
2201 * @mtd: mtd info structure
2202 * @chip: nand chip info structure
2203 * @buf: data buffer
2204 * @oob_required: must write chip->oob_poi to OOB
2205 * @page: page number to write
2207 * Not for syndrome calculating ECC controllers, which use a special oob layout.
2209 static int nand_write_page_raw(struct mtd_info *mtd, struct nand_chip *chip,
2210 const uint8_t *buf, int oob_required, int page)
2212 chip->write_buf(mtd, buf, mtd->writesize);
2213 if (oob_required)
2214 chip->write_buf(mtd, chip->oob_poi, mtd->oobsize);
2216 return 0;
2220 * nand_write_page_raw_syndrome - [INTERN] raw page write function
2221 * @mtd: mtd info structure
2222 * @chip: nand chip info structure
2223 * @buf: data buffer
2224 * @oob_required: must write chip->oob_poi to OOB
2225 * @page: page number to write
2227 * We need a special oob layout and handling even when ECC isn't checked.
2229 static int nand_write_page_raw_syndrome(struct mtd_info *mtd,
2230 struct nand_chip *chip,
2231 const uint8_t *buf, int oob_required,
2232 int page)
2234 int eccsize = chip->ecc.size;
2235 int eccbytes = chip->ecc.bytes;
2236 uint8_t *oob = chip->oob_poi;
2237 int steps, size;
2239 for (steps = chip->ecc.steps; steps > 0; steps--) {
2240 chip->write_buf(mtd, buf, eccsize);
2241 buf += eccsize;
2243 if (chip->ecc.prepad) {
2244 chip->write_buf(mtd, oob, chip->ecc.prepad);
2245 oob += chip->ecc.prepad;
2248 chip->write_buf(mtd, oob, eccbytes);
2249 oob += eccbytes;
2251 if (chip->ecc.postpad) {
2252 chip->write_buf(mtd, oob, chip->ecc.postpad);
2253 oob += chip->ecc.postpad;
2257 size = mtd->oobsize - (oob - chip->oob_poi);
2258 if (size)
2259 chip->write_buf(mtd, oob, size);
2261 return 0;
2264 * nand_write_page_swecc - [REPLACEABLE] software ECC based page write function
2265 * @mtd: mtd info structure
2266 * @chip: nand chip info structure
2267 * @buf: data buffer
2268 * @oob_required: must write chip->oob_poi to OOB
2269 * @page: page number to write
2271 static int nand_write_page_swecc(struct mtd_info *mtd, struct nand_chip *chip,
2272 const uint8_t *buf, int oob_required,
2273 int page)
2275 int i, eccsize = chip->ecc.size, ret;
2276 int eccbytes = chip->ecc.bytes;
2277 int eccsteps = chip->ecc.steps;
2278 uint8_t *ecc_calc = chip->buffers->ecccalc;
2279 const uint8_t *p = buf;
2281 /* Software ECC calculation */
2282 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize)
2283 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
2285 ret = mtd_ooblayout_set_eccbytes(mtd, ecc_calc, chip->oob_poi, 0,
2286 chip->ecc.total);
2287 if (ret)
2288 return ret;
2290 return chip->ecc.write_page_raw(mtd, chip, buf, 1, page);
2294 * nand_write_page_hwecc - [REPLACEABLE] hardware ECC based page write function
2295 * @mtd: mtd info structure
2296 * @chip: nand chip info structure
2297 * @buf: data buffer
2298 * @oob_required: must write chip->oob_poi to OOB
2299 * @page: page number to write
2301 static int nand_write_page_hwecc(struct mtd_info *mtd, struct nand_chip *chip,
2302 const uint8_t *buf, int oob_required,
2303 int page)
2305 int i, eccsize = chip->ecc.size, ret;
2306 int eccbytes = chip->ecc.bytes;
2307 int eccsteps = chip->ecc.steps;
2308 uint8_t *ecc_calc = chip->buffers->ecccalc;
2309 const uint8_t *p = buf;
2311 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
2312 chip->ecc.hwctl(mtd, NAND_ECC_WRITE);
2313 chip->write_buf(mtd, p, eccsize);
2314 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
2317 ret = mtd_ooblayout_set_eccbytes(mtd, ecc_calc, chip->oob_poi, 0,
2318 chip->ecc.total);
2319 if (ret)
2320 return ret;
2322 chip->write_buf(mtd, chip->oob_poi, mtd->oobsize);
2324 return 0;
2329 * nand_write_subpage_hwecc - [REPLACEABLE] hardware ECC based subpage write
2330 * @mtd: mtd info structure
2331 * @chip: nand chip info structure
2332 * @offset: column address of subpage within the page
2333 * @data_len: data length
2334 * @buf: data buffer
2335 * @oob_required: must write chip->oob_poi to OOB
2336 * @page: page number to write
2338 static int nand_write_subpage_hwecc(struct mtd_info *mtd,
2339 struct nand_chip *chip, uint32_t offset,
2340 uint32_t data_len, const uint8_t *buf,
2341 int oob_required, int page)
2343 uint8_t *oob_buf = chip->oob_poi;
2344 uint8_t *ecc_calc = chip->buffers->ecccalc;
2345 int ecc_size = chip->ecc.size;
2346 int ecc_bytes = chip->ecc.bytes;
2347 int ecc_steps = chip->ecc.steps;
2348 uint32_t start_step = offset / ecc_size;
2349 uint32_t end_step = (offset + data_len - 1) / ecc_size;
2350 int oob_bytes = mtd->oobsize / ecc_steps;
2351 int step, ret;
2353 for (step = 0; step < ecc_steps; step++) {
2354 /* configure controller for WRITE access */
2355 chip->ecc.hwctl(mtd, NAND_ECC_WRITE);
2357 /* write data (untouched subpages already masked by 0xFF) */
2358 chip->write_buf(mtd, buf, ecc_size);
2360 /* mask ECC of un-touched subpages by padding 0xFF */
2361 if ((step < start_step) || (step > end_step))
2362 memset(ecc_calc, 0xff, ecc_bytes);
2363 else
2364 chip->ecc.calculate(mtd, buf, ecc_calc);
2366 /* mask OOB of un-touched subpages by padding 0xFF */
2367 /* if oob_required, preserve OOB metadata of written subpage */
2368 if (!oob_required || (step < start_step) || (step > end_step))
2369 memset(oob_buf, 0xff, oob_bytes);
2371 buf += ecc_size;
2372 ecc_calc += ecc_bytes;
2373 oob_buf += oob_bytes;
2376 /* copy calculated ECC for whole page to chip->buffer->oob */
2377 /* this include masked-value(0xFF) for unwritten subpages */
2378 ecc_calc = chip->buffers->ecccalc;
2379 ret = mtd_ooblayout_set_eccbytes(mtd, ecc_calc, chip->oob_poi, 0,
2380 chip->ecc.total);
2381 if (ret)
2382 return ret;
2384 /* write OOB buffer to NAND device */
2385 chip->write_buf(mtd, chip->oob_poi, mtd->oobsize);
2387 return 0;
2392 * nand_write_page_syndrome - [REPLACEABLE] hardware ECC syndrome based page write
2393 * @mtd: mtd info structure
2394 * @chip: nand chip info structure
2395 * @buf: data buffer
2396 * @oob_required: must write chip->oob_poi to OOB
2397 * @page: page number to write
2399 * The hw generator calculates the error syndrome automatically. Therefore we
2400 * need a special oob layout and handling.
2402 static int nand_write_page_syndrome(struct mtd_info *mtd,
2403 struct nand_chip *chip,
2404 const uint8_t *buf, int oob_required,
2405 int page)
2407 int i, eccsize = chip->ecc.size;
2408 int eccbytes = chip->ecc.bytes;
2409 int eccsteps = chip->ecc.steps;
2410 const uint8_t *p = buf;
2411 uint8_t *oob = chip->oob_poi;
2413 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
2415 chip->ecc.hwctl(mtd, NAND_ECC_WRITE);
2416 chip->write_buf(mtd, p, eccsize);
2418 if (chip->ecc.prepad) {
2419 chip->write_buf(mtd, oob, chip->ecc.prepad);
2420 oob += chip->ecc.prepad;
2423 chip->ecc.calculate(mtd, p, oob);
2424 chip->write_buf(mtd, oob, eccbytes);
2425 oob += eccbytes;
2427 if (chip->ecc.postpad) {
2428 chip->write_buf(mtd, oob, chip->ecc.postpad);
2429 oob += chip->ecc.postpad;
2433 /* Calculate remaining oob bytes */
2434 i = mtd->oobsize - (oob - chip->oob_poi);
2435 if (i)
2436 chip->write_buf(mtd, oob, i);
2438 return 0;
2442 * nand_write_page - [REPLACEABLE] write one page
2443 * @mtd: MTD device structure
2444 * @chip: NAND chip descriptor
2445 * @offset: address offset within the page
2446 * @data_len: length of actual data to be written
2447 * @buf: the data to write
2448 * @oob_required: must write chip->oob_poi to OOB
2449 * @page: page number to write
2450 * @cached: cached programming
2451 * @raw: use _raw version of write_page
2453 static int nand_write_page(struct mtd_info *mtd, struct nand_chip *chip,
2454 uint32_t offset, int data_len, const uint8_t *buf,
2455 int oob_required, int page, int cached, int raw)
2457 int status, subpage;
2459 if (!(chip->options & NAND_NO_SUBPAGE_WRITE) &&
2460 chip->ecc.write_subpage)
2461 subpage = offset || (data_len < mtd->writesize);
2462 else
2463 subpage = 0;
2465 chip->cmdfunc(mtd, NAND_CMD_SEQIN, 0x00, page);
2467 if (unlikely(raw))
2468 status = chip->ecc.write_page_raw(mtd, chip, buf,
2469 oob_required, page);
2470 else if (subpage)
2471 status = chip->ecc.write_subpage(mtd, chip, offset, data_len,
2472 buf, oob_required, page);
2473 else
2474 status = chip->ecc.write_page(mtd, chip, buf, oob_required,
2475 page);
2477 if (status < 0)
2478 return status;
2481 * Cached progamming disabled for now. Not sure if it's worth the
2482 * trouble. The speed gain is not very impressive. (2.3->2.6Mib/s).
2484 cached = 0;
2486 if (!cached || !NAND_HAS_CACHEPROG(chip)) {
2488 chip->cmdfunc(mtd, NAND_CMD_PAGEPROG, -1, -1);
2489 status = chip->waitfunc(mtd, chip);
2491 * See if operation failed and additional status checks are
2492 * available.
2494 if ((status & NAND_STATUS_FAIL) && (chip->errstat))
2495 status = chip->errstat(mtd, chip, FL_WRITING, status,
2496 page);
2498 if (status & NAND_STATUS_FAIL)
2499 return -EIO;
2500 } else {
2501 chip->cmdfunc(mtd, NAND_CMD_CACHEDPROG, -1, -1);
2502 status = chip->waitfunc(mtd, chip);
2505 return 0;
2509 * nand_fill_oob - [INTERN] Transfer client buffer to oob
2510 * @mtd: MTD device structure
2511 * @oob: oob data buffer
2512 * @len: oob data write length
2513 * @ops: oob ops structure
2515 static uint8_t *nand_fill_oob(struct mtd_info *mtd, uint8_t *oob, size_t len,
2516 struct mtd_oob_ops *ops)
2518 struct nand_chip *chip = mtd_to_nand(mtd);
2519 int ret;
2522 * Initialise to all 0xFF, to avoid the possibility of left over OOB
2523 * data from a previous OOB read.
2525 memset(chip->oob_poi, 0xff, mtd->oobsize);
2527 switch (ops->mode) {
2529 case MTD_OPS_PLACE_OOB:
2530 case MTD_OPS_RAW:
2531 memcpy(chip->oob_poi + ops->ooboffs, oob, len);
2532 return oob + len;
2534 case MTD_OPS_AUTO_OOB:
2535 ret = mtd_ooblayout_set_databytes(mtd, oob, chip->oob_poi,
2536 ops->ooboffs, len);
2537 BUG_ON(ret);
2538 return oob + len;
2540 default:
2541 BUG();
2543 return NULL;
2546 #define NOTALIGNED(x) ((x & (chip->subpagesize - 1)) != 0)
2549 * nand_do_write_ops - [INTERN] NAND write with ECC
2550 * @mtd: MTD device structure
2551 * @to: offset to write to
2552 * @ops: oob operations description structure
2554 * NAND write with ECC.
2556 static int nand_do_write_ops(struct mtd_info *mtd, loff_t to,
2557 struct mtd_oob_ops *ops)
2559 int chipnr, realpage, page, blockmask, column;
2560 struct nand_chip *chip = mtd_to_nand(mtd);
2561 uint32_t writelen = ops->len;
2563 uint32_t oobwritelen = ops->ooblen;
2564 uint32_t oobmaxlen = mtd_oobavail(mtd, ops);
2566 uint8_t *oob = ops->oobbuf;
2567 uint8_t *buf = ops->datbuf;
2568 int ret;
2569 int oob_required = oob ? 1 : 0;
2571 ops->retlen = 0;
2572 if (!writelen)
2573 return 0;
2575 /* Reject writes, which are not page aligned */
2576 if (NOTALIGNED(to) || NOTALIGNED(ops->len)) {
2577 pr_notice("%s: attempt to write non page aligned data\n",
2578 __func__);
2579 return -EINVAL;
2582 column = to & (mtd->writesize - 1);
2584 chipnr = (int)(to >> chip->chip_shift);
2585 chip->select_chip(mtd, chipnr);
2587 /* Check, if it is write protected */
2588 if (nand_check_wp(mtd)) {
2589 ret = -EIO;
2590 goto err_out;
2593 realpage = (int)(to >> chip->page_shift);
2594 page = realpage & chip->pagemask;
2595 blockmask = (1 << (chip->phys_erase_shift - chip->page_shift)) - 1;
2597 /* Invalidate the page cache, when we write to the cached page */
2598 if (to <= ((loff_t)chip->pagebuf << chip->page_shift) &&
2599 ((loff_t)chip->pagebuf << chip->page_shift) < (to + ops->len))
2600 chip->pagebuf = -1;
2602 /* Don't allow multipage oob writes with offset */
2603 if (oob && ops->ooboffs && (ops->ooboffs + ops->ooblen > oobmaxlen)) {
2604 ret = -EINVAL;
2605 goto err_out;
2608 while (1) {
2609 int bytes = mtd->writesize;
2610 int cached = writelen > bytes && page != blockmask;
2611 uint8_t *wbuf = buf;
2612 int use_bufpoi;
2613 int part_pagewr = (column || writelen < (mtd->writesize - 1));
2615 if (part_pagewr)
2616 use_bufpoi = 1;
2617 else if (chip->options & NAND_USE_BOUNCE_BUFFER)
2618 use_bufpoi = !virt_addr_valid(buf);
2619 else
2620 use_bufpoi = 0;
2622 /* Partial page write?, or need to use bounce buffer */
2623 if (use_bufpoi) {
2624 pr_debug("%s: using write bounce buffer for buf@%p\n",
2625 __func__, buf);
2626 cached = 0;
2627 if (part_pagewr)
2628 bytes = min_t(int, bytes - column, writelen);
2629 chip->pagebuf = -1;
2630 memset(chip->buffers->databuf, 0xff, mtd->writesize);
2631 memcpy(&chip->buffers->databuf[column], buf, bytes);
2632 wbuf = chip->buffers->databuf;
2635 if (unlikely(oob)) {
2636 size_t len = min(oobwritelen, oobmaxlen);
2637 oob = nand_fill_oob(mtd, oob, len, ops);
2638 oobwritelen -= len;
2639 } else {
2640 /* We still need to erase leftover OOB data */
2641 memset(chip->oob_poi, 0xff, mtd->oobsize);
2643 ret = chip->write_page(mtd, chip, column, bytes, wbuf,
2644 oob_required, page, cached,
2645 (ops->mode == MTD_OPS_RAW));
2646 if (ret)
2647 break;
2649 writelen -= bytes;
2650 if (!writelen)
2651 break;
2653 column = 0;
2654 buf += bytes;
2655 realpage++;
2657 page = realpage & chip->pagemask;
2658 /* Check, if we cross a chip boundary */
2659 if (!page) {
2660 chipnr++;
2661 chip->select_chip(mtd, -1);
2662 chip->select_chip(mtd, chipnr);
2666 ops->retlen = ops->len - writelen;
2667 if (unlikely(oob))
2668 ops->oobretlen = ops->ooblen;
2670 err_out:
2671 chip->select_chip(mtd, -1);
2672 return ret;
2676 * panic_nand_write - [MTD Interface] NAND write with ECC
2677 * @mtd: MTD device structure
2678 * @to: offset to write to
2679 * @len: number of bytes to write
2680 * @retlen: pointer to variable to store the number of written bytes
2681 * @buf: the data to write
2683 * NAND write with ECC. Used when performing writes in interrupt context, this
2684 * may for example be called by mtdoops when writing an oops while in panic.
2686 static int panic_nand_write(struct mtd_info *mtd, loff_t to, size_t len,
2687 size_t *retlen, const uint8_t *buf)
2689 struct nand_chip *chip = mtd_to_nand(mtd);
2690 struct mtd_oob_ops ops;
2691 int ret;
2693 /* Wait for the device to get ready */
2694 panic_nand_wait(mtd, chip, 400);
2696 /* Grab the device */
2697 panic_nand_get_device(chip, mtd, FL_WRITING);
2699 memset(&ops, 0, sizeof(ops));
2700 ops.len = len;
2701 ops.datbuf = (uint8_t *)buf;
2702 ops.mode = MTD_OPS_PLACE_OOB;
2704 ret = nand_do_write_ops(mtd, to, &ops);
2706 *retlen = ops.retlen;
2707 return ret;
2711 * nand_write - [MTD Interface] NAND write with ECC
2712 * @mtd: MTD device structure
2713 * @to: offset to write to
2714 * @len: number of bytes to write
2715 * @retlen: pointer to variable to store the number of written bytes
2716 * @buf: the data to write
2718 * NAND write with ECC.
2720 static int nand_write(struct mtd_info *mtd, loff_t to, size_t len,
2721 size_t *retlen, const uint8_t *buf)
2723 struct mtd_oob_ops ops;
2724 int ret;
2726 nand_get_device(mtd, FL_WRITING);
2727 memset(&ops, 0, sizeof(ops));
2728 ops.len = len;
2729 ops.datbuf = (uint8_t *)buf;
2730 ops.mode = MTD_OPS_PLACE_OOB;
2731 ret = nand_do_write_ops(mtd, to, &ops);
2732 *retlen = ops.retlen;
2733 nand_release_device(mtd);
2734 return ret;
2738 * nand_do_write_oob - [MTD Interface] NAND write out-of-band
2739 * @mtd: MTD device structure
2740 * @to: offset to write to
2741 * @ops: oob operation description structure
2743 * NAND write out-of-band.
2745 static int nand_do_write_oob(struct mtd_info *mtd, loff_t to,
2746 struct mtd_oob_ops *ops)
2748 int chipnr, page, status, len;
2749 struct nand_chip *chip = mtd_to_nand(mtd);
2751 pr_debug("%s: to = 0x%08x, len = %i\n",
2752 __func__, (unsigned int)to, (int)ops->ooblen);
2754 len = mtd_oobavail(mtd, ops);
2756 /* Do not allow write past end of page */
2757 if ((ops->ooboffs + ops->ooblen) > len) {
2758 pr_debug("%s: attempt to write past end of page\n",
2759 __func__);
2760 return -EINVAL;
2763 if (unlikely(ops->ooboffs >= len)) {
2764 pr_debug("%s: attempt to start write outside oob\n",
2765 __func__);
2766 return -EINVAL;
2769 /* Do not allow write past end of device */
2770 if (unlikely(to >= mtd->size ||
2771 ops->ooboffs + ops->ooblen >
2772 ((mtd->size >> chip->page_shift) -
2773 (to >> chip->page_shift)) * len)) {
2774 pr_debug("%s: attempt to write beyond end of device\n",
2775 __func__);
2776 return -EINVAL;
2779 chipnr = (int)(to >> chip->chip_shift);
2780 chip->select_chip(mtd, chipnr);
2782 /* Shift to get page */
2783 page = (int)(to >> chip->page_shift);
2786 * Reset the chip. Some chips (like the Toshiba TC5832DC found in one
2787 * of my DiskOnChip 2000 test units) will clear the whole data page too
2788 * if we don't do this. I have no clue why, but I seem to have 'fixed'
2789 * it in the doc2000 driver in August 1999. dwmw2.
2791 chip->cmdfunc(mtd, NAND_CMD_RESET, -1, -1);
2793 /* Check, if it is write protected */
2794 if (nand_check_wp(mtd)) {
2795 chip->select_chip(mtd, -1);
2796 return -EROFS;
2799 /* Invalidate the page cache, if we write to the cached page */
2800 if (page == chip->pagebuf)
2801 chip->pagebuf = -1;
2803 nand_fill_oob(mtd, ops->oobbuf, ops->ooblen, ops);
2805 if (ops->mode == MTD_OPS_RAW)
2806 status = chip->ecc.write_oob_raw(mtd, chip, page & chip->pagemask);
2807 else
2808 status = chip->ecc.write_oob(mtd, chip, page & chip->pagemask);
2810 chip->select_chip(mtd, -1);
2812 if (status)
2813 return status;
2815 ops->oobretlen = ops->ooblen;
2817 return 0;
2821 * nand_write_oob - [MTD Interface] NAND write data and/or out-of-band
2822 * @mtd: MTD device structure
2823 * @to: offset to write to
2824 * @ops: oob operation description structure
2826 static int nand_write_oob(struct mtd_info *mtd, loff_t to,
2827 struct mtd_oob_ops *ops)
2829 int ret = -ENOTSUPP;
2831 ops->retlen = 0;
2833 /* Do not allow writes past end of device */
2834 if (ops->datbuf && (to + ops->len) > mtd->size) {
2835 pr_debug("%s: attempt to write beyond end of device\n",
2836 __func__);
2837 return -EINVAL;
2840 nand_get_device(mtd, FL_WRITING);
2842 switch (ops->mode) {
2843 case MTD_OPS_PLACE_OOB:
2844 case MTD_OPS_AUTO_OOB:
2845 case MTD_OPS_RAW:
2846 break;
2848 default:
2849 goto out;
2852 if (!ops->datbuf)
2853 ret = nand_do_write_oob(mtd, to, ops);
2854 else
2855 ret = nand_do_write_ops(mtd, to, ops);
2857 out:
2858 nand_release_device(mtd);
2859 return ret;
2863 * single_erase - [GENERIC] NAND standard block erase command function
2864 * @mtd: MTD device structure
2865 * @page: the page address of the block which will be erased
2867 * Standard erase command for NAND chips. Returns NAND status.
2869 static int single_erase(struct mtd_info *mtd, int page)
2871 struct nand_chip *chip = mtd_to_nand(mtd);
2872 /* Send commands to erase a block */
2873 chip->cmdfunc(mtd, NAND_CMD_ERASE1, -1, page);
2874 chip->cmdfunc(mtd, NAND_CMD_ERASE2, -1, -1);
2876 return chip->waitfunc(mtd, chip);
2880 * nand_erase - [MTD Interface] erase block(s)
2881 * @mtd: MTD device structure
2882 * @instr: erase instruction
2884 * Erase one ore more blocks.
2886 static int nand_erase(struct mtd_info *mtd, struct erase_info *instr)
2888 return nand_erase_nand(mtd, instr, 0);
2892 * nand_erase_nand - [INTERN] erase block(s)
2893 * @mtd: MTD device structure
2894 * @instr: erase instruction
2895 * @allowbbt: allow erasing the bbt area
2897 * Erase one ore more blocks.
2899 int nand_erase_nand(struct mtd_info *mtd, struct erase_info *instr,
2900 int allowbbt)
2902 int page, status, pages_per_block, ret, chipnr;
2903 struct nand_chip *chip = mtd_to_nand(mtd);
2904 loff_t len;
2906 pr_debug("%s: start = 0x%012llx, len = %llu\n",
2907 __func__, (unsigned long long)instr->addr,
2908 (unsigned long long)instr->len);
2910 if (check_offs_len(mtd, instr->addr, instr->len))
2911 return -EINVAL;
2913 /* Grab the lock and see if the device is available */
2914 nand_get_device(mtd, FL_ERASING);
2916 /* Shift to get first page */
2917 page = (int)(instr->addr >> chip->page_shift);
2918 chipnr = (int)(instr->addr >> chip->chip_shift);
2920 /* Calculate pages in each block */
2921 pages_per_block = 1 << (chip->phys_erase_shift - chip->page_shift);
2923 /* Select the NAND device */
2924 chip->select_chip(mtd, chipnr);
2926 /* Check, if it is write protected */
2927 if (nand_check_wp(mtd)) {
2928 pr_debug("%s: device is write protected!\n",
2929 __func__);
2930 instr->state = MTD_ERASE_FAILED;
2931 goto erase_exit;
2934 /* Loop through the pages */
2935 len = instr->len;
2937 instr->state = MTD_ERASING;
2939 while (len) {
2940 /* Check if we have a bad block, we do not erase bad blocks! */
2941 if (nand_block_checkbad(mtd, ((loff_t) page) <<
2942 chip->page_shift, allowbbt)) {
2943 pr_warn("%s: attempt to erase a bad block at page 0x%08x\n",
2944 __func__, page);
2945 instr->state = MTD_ERASE_FAILED;
2946 goto erase_exit;
2950 * Invalidate the page cache, if we erase the block which
2951 * contains the current cached page.
2953 if (page <= chip->pagebuf && chip->pagebuf <
2954 (page + pages_per_block))
2955 chip->pagebuf = -1;
2957 status = chip->erase(mtd, page & chip->pagemask);
2960 * See if operation failed and additional status checks are
2961 * available
2963 if ((status & NAND_STATUS_FAIL) && (chip->errstat))
2964 status = chip->errstat(mtd, chip, FL_ERASING,
2965 status, page);
2967 /* See if block erase succeeded */
2968 if (status & NAND_STATUS_FAIL) {
2969 pr_debug("%s: failed erase, page 0x%08x\n",
2970 __func__, page);
2971 instr->state = MTD_ERASE_FAILED;
2972 instr->fail_addr =
2973 ((loff_t)page << chip->page_shift);
2974 goto erase_exit;
2977 /* Increment page address and decrement length */
2978 len -= (1ULL << chip->phys_erase_shift);
2979 page += pages_per_block;
2981 /* Check, if we cross a chip boundary */
2982 if (len && !(page & chip->pagemask)) {
2983 chipnr++;
2984 chip->select_chip(mtd, -1);
2985 chip->select_chip(mtd, chipnr);
2988 instr->state = MTD_ERASE_DONE;
2990 erase_exit:
2992 ret = instr->state == MTD_ERASE_DONE ? 0 : -EIO;
2994 /* Deselect and wake up anyone waiting on the device */
2995 chip->select_chip(mtd, -1);
2996 nand_release_device(mtd);
2998 /* Do call back function */
2999 if (!ret)
3000 mtd_erase_callback(instr);
3002 /* Return more or less happy */
3003 return ret;
3007 * nand_sync - [MTD Interface] sync
3008 * @mtd: MTD device structure
3010 * Sync is actually a wait for chip ready function.
3012 static void nand_sync(struct mtd_info *mtd)
3014 pr_debug("%s: called\n", __func__);
3016 /* Grab the lock and see if the device is available */
3017 nand_get_device(mtd, FL_SYNCING);
3018 /* Release it and go back */
3019 nand_release_device(mtd);
3023 * nand_block_isbad - [MTD Interface] Check if block at offset is bad
3024 * @mtd: MTD device structure
3025 * @offs: offset relative to mtd start
3027 static int nand_block_isbad(struct mtd_info *mtd, loff_t offs)
3029 struct nand_chip *chip = mtd_to_nand(mtd);
3030 int chipnr = (int)(offs >> chip->chip_shift);
3031 int ret;
3033 /* Select the NAND device */
3034 nand_get_device(mtd, FL_READING);
3035 chip->select_chip(mtd, chipnr);
3037 ret = nand_block_checkbad(mtd, offs, 0);
3039 chip->select_chip(mtd, -1);
3040 nand_release_device(mtd);
3042 return ret;
3046 * nand_block_markbad - [MTD Interface] Mark block at the given offset as bad
3047 * @mtd: MTD device structure
3048 * @ofs: offset relative to mtd start
3050 static int nand_block_markbad(struct mtd_info *mtd, loff_t ofs)
3052 int ret;
3054 ret = nand_block_isbad(mtd, ofs);
3055 if (ret) {
3056 /* If it was bad already, return success and do nothing */
3057 if (ret > 0)
3058 return 0;
3059 return ret;
3062 return nand_block_markbad_lowlevel(mtd, ofs);
3066 * nand_onfi_set_features- [REPLACEABLE] set features for ONFI nand
3067 * @mtd: MTD device structure
3068 * @chip: nand chip info structure
3069 * @addr: feature address.
3070 * @subfeature_param: the subfeature parameters, a four bytes array.
3072 static int nand_onfi_set_features(struct mtd_info *mtd, struct nand_chip *chip,
3073 int addr, uint8_t *subfeature_param)
3075 int status;
3076 int i;
3078 if (!chip->onfi_version ||
3079 !(le16_to_cpu(chip->onfi_params.opt_cmd)
3080 & ONFI_OPT_CMD_SET_GET_FEATURES))
3081 return -EINVAL;
3083 chip->cmdfunc(mtd, NAND_CMD_SET_FEATURES, addr, -1);
3084 for (i = 0; i < ONFI_SUBFEATURE_PARAM_LEN; ++i)
3085 chip->write_byte(mtd, subfeature_param[i]);
3087 status = chip->waitfunc(mtd, chip);
3088 if (status & NAND_STATUS_FAIL)
3089 return -EIO;
3090 return 0;
3094 * nand_onfi_get_features- [REPLACEABLE] get features for ONFI nand
3095 * @mtd: MTD device structure
3096 * @chip: nand chip info structure
3097 * @addr: feature address.
3098 * @subfeature_param: the subfeature parameters, a four bytes array.
3100 static int nand_onfi_get_features(struct mtd_info *mtd, struct nand_chip *chip,
3101 int addr, uint8_t *subfeature_param)
3103 int i;
3105 if (!chip->onfi_version ||
3106 !(le16_to_cpu(chip->onfi_params.opt_cmd)
3107 & ONFI_OPT_CMD_SET_GET_FEATURES))
3108 return -EINVAL;
3110 chip->cmdfunc(mtd, NAND_CMD_GET_FEATURES, addr, -1);
3111 for (i = 0; i < ONFI_SUBFEATURE_PARAM_LEN; ++i)
3112 *subfeature_param++ = chip->read_byte(mtd);
3113 return 0;
3117 * nand_suspend - [MTD Interface] Suspend the NAND flash
3118 * @mtd: MTD device structure
3120 static int nand_suspend(struct mtd_info *mtd)
3122 return nand_get_device(mtd, FL_PM_SUSPENDED);
3126 * nand_resume - [MTD Interface] Resume the NAND flash
3127 * @mtd: MTD device structure
3129 static void nand_resume(struct mtd_info *mtd)
3131 struct nand_chip *chip = mtd_to_nand(mtd);
3133 if (chip->state == FL_PM_SUSPENDED)
3134 nand_release_device(mtd);
3135 else
3136 pr_err("%s called for a chip which is not in suspended state\n",
3137 __func__);
3141 * nand_shutdown - [MTD Interface] Finish the current NAND operation and
3142 * prevent further operations
3143 * @mtd: MTD device structure
3145 static void nand_shutdown(struct mtd_info *mtd)
3147 nand_get_device(mtd, FL_PM_SUSPENDED);
3150 /* Set default functions */
3151 static void nand_set_defaults(struct nand_chip *chip, int busw)
3153 /* check for proper chip_delay setup, set 20us if not */
3154 if (!chip->chip_delay)
3155 chip->chip_delay = 20;
3157 /* check, if a user supplied command function given */
3158 if (chip->cmdfunc == NULL)
3159 chip->cmdfunc = nand_command;
3161 /* check, if a user supplied wait function given */
3162 if (chip->waitfunc == NULL)
3163 chip->waitfunc = nand_wait;
3165 if (!chip->select_chip)
3166 chip->select_chip = nand_select_chip;
3168 /* set for ONFI nand */
3169 if (!chip->onfi_set_features)
3170 chip->onfi_set_features = nand_onfi_set_features;
3171 if (!chip->onfi_get_features)
3172 chip->onfi_get_features = nand_onfi_get_features;
3174 /* If called twice, pointers that depend on busw may need to be reset */
3175 if (!chip->read_byte || chip->read_byte == nand_read_byte)
3176 chip->read_byte = busw ? nand_read_byte16 : nand_read_byte;
3177 if (!chip->read_word)
3178 chip->read_word = nand_read_word;
3179 if (!chip->block_bad)
3180 chip->block_bad = nand_block_bad;
3181 if (!chip->block_markbad)
3182 chip->block_markbad = nand_default_block_markbad;
3183 if (!chip->write_buf || chip->write_buf == nand_write_buf)
3184 chip->write_buf = busw ? nand_write_buf16 : nand_write_buf;
3185 if (!chip->write_byte || chip->write_byte == nand_write_byte)
3186 chip->write_byte = busw ? nand_write_byte16 : nand_write_byte;
3187 if (!chip->read_buf || chip->read_buf == nand_read_buf)
3188 chip->read_buf = busw ? nand_read_buf16 : nand_read_buf;
3189 if (!chip->scan_bbt)
3190 chip->scan_bbt = nand_default_bbt;
3192 if (!chip->controller) {
3193 chip->controller = &chip->hwcontrol;
3194 spin_lock_init(&chip->controller->lock);
3195 init_waitqueue_head(&chip->controller->wq);
3200 /* Sanitize ONFI strings so we can safely print them */
3201 static void sanitize_string(uint8_t *s, size_t len)
3203 ssize_t i;
3205 /* Null terminate */
3206 s[len - 1] = 0;
3208 /* Remove non printable chars */
3209 for (i = 0; i < len - 1; i++) {
3210 if (s[i] < ' ' || s[i] > 127)
3211 s[i] = '?';
3214 /* Remove trailing spaces */
3215 strim(s);
3218 static u16 onfi_crc16(u16 crc, u8 const *p, size_t len)
3220 int i;
3221 while (len--) {
3222 crc ^= *p++ << 8;
3223 for (i = 0; i < 8; i++)
3224 crc = (crc << 1) ^ ((crc & 0x8000) ? 0x8005 : 0);
3227 return crc;
3230 /* Parse the Extended Parameter Page. */
3231 static int nand_flash_detect_ext_param_page(struct mtd_info *mtd,
3232 struct nand_chip *chip, struct nand_onfi_params *p)
3234 struct onfi_ext_param_page *ep;
3235 struct onfi_ext_section *s;
3236 struct onfi_ext_ecc_info *ecc;
3237 uint8_t *cursor;
3238 int ret = -EINVAL;
3239 int len;
3240 int i;
3242 len = le16_to_cpu(p->ext_param_page_length) * 16;
3243 ep = kmalloc(len, GFP_KERNEL);
3244 if (!ep)
3245 return -ENOMEM;
3247 /* Send our own NAND_CMD_PARAM. */
3248 chip->cmdfunc(mtd, NAND_CMD_PARAM, 0, -1);
3250 /* Use the Change Read Column command to skip the ONFI param pages. */
3251 chip->cmdfunc(mtd, NAND_CMD_RNDOUT,
3252 sizeof(*p) * p->num_of_param_pages , -1);
3254 /* Read out the Extended Parameter Page. */
3255 chip->read_buf(mtd, (uint8_t *)ep, len);
3256 if ((onfi_crc16(ONFI_CRC_BASE, ((uint8_t *)ep) + 2, len - 2)
3257 != le16_to_cpu(ep->crc))) {
3258 pr_debug("fail in the CRC.\n");
3259 goto ext_out;
3263 * Check the signature.
3264 * Do not strictly follow the ONFI spec, maybe changed in future.
3266 if (strncmp(ep->sig, "EPPS", 4)) {
3267 pr_debug("The signature is invalid.\n");
3268 goto ext_out;
3271 /* find the ECC section. */
3272 cursor = (uint8_t *)(ep + 1);
3273 for (i = 0; i < ONFI_EXT_SECTION_MAX; i++) {
3274 s = ep->sections + i;
3275 if (s->type == ONFI_SECTION_TYPE_2)
3276 break;
3277 cursor += s->length * 16;
3279 if (i == ONFI_EXT_SECTION_MAX) {
3280 pr_debug("We can not find the ECC section.\n");
3281 goto ext_out;
3284 /* get the info we want. */
3285 ecc = (struct onfi_ext_ecc_info *)cursor;
3287 if (!ecc->codeword_size) {
3288 pr_debug("Invalid codeword size\n");
3289 goto ext_out;
3292 chip->ecc_strength_ds = ecc->ecc_bits;
3293 chip->ecc_step_ds = 1 << ecc->codeword_size;
3294 ret = 0;
3296 ext_out:
3297 kfree(ep);
3298 return ret;
3301 static int nand_setup_read_retry_micron(struct mtd_info *mtd, int retry_mode)
3303 struct nand_chip *chip = mtd_to_nand(mtd);
3304 uint8_t feature[ONFI_SUBFEATURE_PARAM_LEN] = {retry_mode};
3306 return chip->onfi_set_features(mtd, chip, ONFI_FEATURE_ADDR_READ_RETRY,
3307 feature);
3311 * Configure chip properties from Micron vendor-specific ONFI table
3313 static void nand_onfi_detect_micron(struct nand_chip *chip,
3314 struct nand_onfi_params *p)
3316 struct nand_onfi_vendor_micron *micron = (void *)p->vendor;
3318 if (le16_to_cpu(p->vendor_revision) < 1)
3319 return;
3321 chip->read_retries = micron->read_retry_options;
3322 chip->setup_read_retry = nand_setup_read_retry_micron;
3326 * Check if the NAND chip is ONFI compliant, returns 1 if it is, 0 otherwise.
3328 static int nand_flash_detect_onfi(struct mtd_info *mtd, struct nand_chip *chip,
3329 int *busw)
3331 struct nand_onfi_params *p = &chip->onfi_params;
3332 int i, j;
3333 int val;
3335 /* Try ONFI for unknown chip or LP */
3336 chip->cmdfunc(mtd, NAND_CMD_READID, 0x20, -1);
3337 if (chip->read_byte(mtd) != 'O' || chip->read_byte(mtd) != 'N' ||
3338 chip->read_byte(mtd) != 'F' || chip->read_byte(mtd) != 'I')
3339 return 0;
3341 chip->cmdfunc(mtd, NAND_CMD_PARAM, 0, -1);
3342 for (i = 0; i < 3; i++) {
3343 for (j = 0; j < sizeof(*p); j++)
3344 ((uint8_t *)p)[j] = chip->read_byte(mtd);
3345 if (onfi_crc16(ONFI_CRC_BASE, (uint8_t *)p, 254) ==
3346 le16_to_cpu(p->crc)) {
3347 break;
3351 if (i == 3) {
3352 pr_err("Could not find valid ONFI parameter page; aborting\n");
3353 return 0;
3356 /* Check version */
3357 val = le16_to_cpu(p->revision);
3358 if (val & (1 << 5))
3359 chip->onfi_version = 23;
3360 else if (val & (1 << 4))
3361 chip->onfi_version = 22;
3362 else if (val & (1 << 3))
3363 chip->onfi_version = 21;
3364 else if (val & (1 << 2))
3365 chip->onfi_version = 20;
3366 else if (val & (1 << 1))
3367 chip->onfi_version = 10;
3369 if (!chip->onfi_version) {
3370 pr_info("unsupported ONFI version: %d\n", val);
3371 return 0;
3374 sanitize_string(p->manufacturer, sizeof(p->manufacturer));
3375 sanitize_string(p->model, sizeof(p->model));
3376 if (!mtd->name)
3377 mtd->name = p->model;
3379 mtd->writesize = le32_to_cpu(p->byte_per_page);
3382 * pages_per_block and blocks_per_lun may not be a power-of-2 size
3383 * (don't ask me who thought of this...). MTD assumes that these
3384 * dimensions will be power-of-2, so just truncate the remaining area.
3386 mtd->erasesize = 1 << (fls(le32_to_cpu(p->pages_per_block)) - 1);
3387 mtd->erasesize *= mtd->writesize;
3389 mtd->oobsize = le16_to_cpu(p->spare_bytes_per_page);
3391 /* See erasesize comment */
3392 chip->chipsize = 1 << (fls(le32_to_cpu(p->blocks_per_lun)) - 1);
3393 chip->chipsize *= (uint64_t)mtd->erasesize * p->lun_count;
3394 chip->bits_per_cell = p->bits_per_cell;
3396 if (onfi_feature(chip) & ONFI_FEATURE_16_BIT_BUS)
3397 *busw = NAND_BUSWIDTH_16;
3398 else
3399 *busw = 0;
3401 if (p->ecc_bits != 0xff) {
3402 chip->ecc_strength_ds = p->ecc_bits;
3403 chip->ecc_step_ds = 512;
3404 } else if (chip->onfi_version >= 21 &&
3405 (onfi_feature(chip) & ONFI_FEATURE_EXT_PARAM_PAGE)) {
3408 * The nand_flash_detect_ext_param_page() uses the
3409 * Change Read Column command which maybe not supported
3410 * by the chip->cmdfunc. So try to update the chip->cmdfunc
3411 * now. We do not replace user supplied command function.
3413 if (mtd->writesize > 512 && chip->cmdfunc == nand_command)
3414 chip->cmdfunc = nand_command_lp;
3416 /* The Extended Parameter Page is supported since ONFI 2.1. */
3417 if (nand_flash_detect_ext_param_page(mtd, chip, p))
3418 pr_warn("Failed to detect ONFI extended param page\n");
3419 } else {
3420 pr_warn("Could not retrieve ONFI ECC requirements\n");
3423 if (p->jedec_id == NAND_MFR_MICRON)
3424 nand_onfi_detect_micron(chip, p);
3426 return 1;
3430 * Check if the NAND chip is JEDEC compliant, returns 1 if it is, 0 otherwise.
3432 static int nand_flash_detect_jedec(struct mtd_info *mtd, struct nand_chip *chip,
3433 int *busw)
3435 struct nand_jedec_params *p = &chip->jedec_params;
3436 struct jedec_ecc_info *ecc;
3437 int val;
3438 int i, j;
3440 /* Try JEDEC for unknown chip or LP */
3441 chip->cmdfunc(mtd, NAND_CMD_READID, 0x40, -1);
3442 if (chip->read_byte(mtd) != 'J' || chip->read_byte(mtd) != 'E' ||
3443 chip->read_byte(mtd) != 'D' || chip->read_byte(mtd) != 'E' ||
3444 chip->read_byte(mtd) != 'C')
3445 return 0;
3447 chip->cmdfunc(mtd, NAND_CMD_PARAM, 0x40, -1);
3448 for (i = 0; i < 3; i++) {
3449 for (j = 0; j < sizeof(*p); j++)
3450 ((uint8_t *)p)[j] = chip->read_byte(mtd);
3452 if (onfi_crc16(ONFI_CRC_BASE, (uint8_t *)p, 510) ==
3453 le16_to_cpu(p->crc))
3454 break;
3457 if (i == 3) {
3458 pr_err("Could not find valid JEDEC parameter page; aborting\n");
3459 return 0;
3462 /* Check version */
3463 val = le16_to_cpu(p->revision);
3464 if (val & (1 << 2))
3465 chip->jedec_version = 10;
3466 else if (val & (1 << 1))
3467 chip->jedec_version = 1; /* vendor specific version */
3469 if (!chip->jedec_version) {
3470 pr_info("unsupported JEDEC version: %d\n", val);
3471 return 0;
3474 sanitize_string(p->manufacturer, sizeof(p->manufacturer));
3475 sanitize_string(p->model, sizeof(p->model));
3476 if (!mtd->name)
3477 mtd->name = p->model;
3479 mtd->writesize = le32_to_cpu(p->byte_per_page);
3481 /* Please reference to the comment for nand_flash_detect_onfi. */
3482 mtd->erasesize = 1 << (fls(le32_to_cpu(p->pages_per_block)) - 1);
3483 mtd->erasesize *= mtd->writesize;
3485 mtd->oobsize = le16_to_cpu(p->spare_bytes_per_page);
3487 /* Please reference to the comment for nand_flash_detect_onfi. */
3488 chip->chipsize = 1 << (fls(le32_to_cpu(p->blocks_per_lun)) - 1);
3489 chip->chipsize *= (uint64_t)mtd->erasesize * p->lun_count;
3490 chip->bits_per_cell = p->bits_per_cell;
3492 if (jedec_feature(chip) & JEDEC_FEATURE_16_BIT_BUS)
3493 *busw = NAND_BUSWIDTH_16;
3494 else
3495 *busw = 0;
3497 /* ECC info */
3498 ecc = &p->ecc_info[0];
3500 if (ecc->codeword_size >= 9) {
3501 chip->ecc_strength_ds = ecc->ecc_bits;
3502 chip->ecc_step_ds = 1 << ecc->codeword_size;
3503 } else {
3504 pr_warn("Invalid codeword size\n");
3507 return 1;
3511 * nand_id_has_period - Check if an ID string has a given wraparound period
3512 * @id_data: the ID string
3513 * @arrlen: the length of the @id_data array
3514 * @period: the period of repitition
3516 * Check if an ID string is repeated within a given sequence of bytes at
3517 * specific repetition interval period (e.g., {0x20,0x01,0x7F,0x20} has a
3518 * period of 3). This is a helper function for nand_id_len(). Returns non-zero
3519 * if the repetition has a period of @period; otherwise, returns zero.
3521 static int nand_id_has_period(u8 *id_data, int arrlen, int period)
3523 int i, j;
3524 for (i = 0; i < period; i++)
3525 for (j = i + period; j < arrlen; j += period)
3526 if (id_data[i] != id_data[j])
3527 return 0;
3528 return 1;
3532 * nand_id_len - Get the length of an ID string returned by CMD_READID
3533 * @id_data: the ID string
3534 * @arrlen: the length of the @id_data array
3536 * Returns the length of the ID string, according to known wraparound/trailing
3537 * zero patterns. If no pattern exists, returns the length of the array.
3539 static int nand_id_len(u8 *id_data, int arrlen)
3541 int last_nonzero, period;
3543 /* Find last non-zero byte */
3544 for (last_nonzero = arrlen - 1; last_nonzero >= 0; last_nonzero--)
3545 if (id_data[last_nonzero])
3546 break;
3548 /* All zeros */
3549 if (last_nonzero < 0)
3550 return 0;
3552 /* Calculate wraparound period */
3553 for (period = 1; period < arrlen; period++)
3554 if (nand_id_has_period(id_data, arrlen, period))
3555 break;
3557 /* There's a repeated pattern */
3558 if (period < arrlen)
3559 return period;
3561 /* There are trailing zeros */
3562 if (last_nonzero < arrlen - 1)
3563 return last_nonzero + 1;
3565 /* No pattern detected */
3566 return arrlen;
3569 /* Extract the bits of per cell from the 3rd byte of the extended ID */
3570 static int nand_get_bits_per_cell(u8 cellinfo)
3572 int bits;
3574 bits = cellinfo & NAND_CI_CELLTYPE_MSK;
3575 bits >>= NAND_CI_CELLTYPE_SHIFT;
3576 return bits + 1;
3580 * Many new NAND share similar device ID codes, which represent the size of the
3581 * chip. The rest of the parameters must be decoded according to generic or
3582 * manufacturer-specific "extended ID" decoding patterns.
3584 static void nand_decode_ext_id(struct mtd_info *mtd, struct nand_chip *chip,
3585 u8 id_data[8], int *busw)
3587 int extid, id_len;
3588 /* The 3rd id byte holds MLC / multichip data */
3589 chip->bits_per_cell = nand_get_bits_per_cell(id_data[2]);
3590 /* The 4th id byte is the important one */
3591 extid = id_data[3];
3593 id_len = nand_id_len(id_data, 8);
3596 * Field definitions are in the following datasheets:
3597 * Old style (4,5 byte ID): Samsung K9GAG08U0M (p.32)
3598 * New Samsung (6 byte ID): Samsung K9GAG08U0F (p.44)
3599 * Hynix MLC (6 byte ID): Hynix H27UBG8T2B (p.22)
3601 * Check for ID length, non-zero 6th byte, cell type, and Hynix/Samsung
3602 * ID to decide what to do.
3604 if (id_len == 6 && id_data[0] == NAND_MFR_SAMSUNG &&
3605 !nand_is_slc(chip) && id_data[5] != 0x00) {
3606 /* Calc pagesize */
3607 mtd->writesize = 2048 << (extid & 0x03);
3608 extid >>= 2;
3609 /* Calc oobsize */
3610 switch (((extid >> 2) & 0x04) | (extid & 0x03)) {
3611 case 1:
3612 mtd->oobsize = 128;
3613 break;
3614 case 2:
3615 mtd->oobsize = 218;
3616 break;
3617 case 3:
3618 mtd->oobsize = 400;
3619 break;
3620 case 4:
3621 mtd->oobsize = 436;
3622 break;
3623 case 5:
3624 mtd->oobsize = 512;
3625 break;
3626 case 6:
3627 mtd->oobsize = 640;
3628 break;
3629 case 7:
3630 default: /* Other cases are "reserved" (unknown) */
3631 mtd->oobsize = 1024;
3632 break;
3634 extid >>= 2;
3635 /* Calc blocksize */
3636 mtd->erasesize = (128 * 1024) <<
3637 (((extid >> 1) & 0x04) | (extid & 0x03));
3638 *busw = 0;
3639 } else if (id_len == 6 && id_data[0] == NAND_MFR_HYNIX &&
3640 !nand_is_slc(chip)) {
3641 unsigned int tmp;
3643 /* Calc pagesize */
3644 mtd->writesize = 2048 << (extid & 0x03);
3645 extid >>= 2;
3646 /* Calc oobsize */
3647 switch (((extid >> 2) & 0x04) | (extid & 0x03)) {
3648 case 0:
3649 mtd->oobsize = 128;
3650 break;
3651 case 1:
3652 mtd->oobsize = 224;
3653 break;
3654 case 2:
3655 mtd->oobsize = 448;
3656 break;
3657 case 3:
3658 mtd->oobsize = 64;
3659 break;
3660 case 4:
3661 mtd->oobsize = 32;
3662 break;
3663 case 5:
3664 mtd->oobsize = 16;
3665 break;
3666 default:
3667 mtd->oobsize = 640;
3668 break;
3670 extid >>= 2;
3671 /* Calc blocksize */
3672 tmp = ((extid >> 1) & 0x04) | (extid & 0x03);
3673 if (tmp < 0x03)
3674 mtd->erasesize = (128 * 1024) << tmp;
3675 else if (tmp == 0x03)
3676 mtd->erasesize = 768 * 1024;
3677 else
3678 mtd->erasesize = (64 * 1024) << tmp;
3679 *busw = 0;
3680 } else {
3681 /* Calc pagesize */
3682 mtd->writesize = 1024 << (extid & 0x03);
3683 extid >>= 2;
3684 /* Calc oobsize */
3685 mtd->oobsize = (8 << (extid & 0x01)) *
3686 (mtd->writesize >> 9);
3687 extid >>= 2;
3688 /* Calc blocksize. Blocksize is multiples of 64KiB */
3689 mtd->erasesize = (64 * 1024) << (extid & 0x03);
3690 extid >>= 2;
3691 /* Get buswidth information */
3692 *busw = (extid & 0x01) ? NAND_BUSWIDTH_16 : 0;
3695 * Toshiba 24nm raw SLC (i.e., not BENAND) have 32B OOB per
3696 * 512B page. For Toshiba SLC, we decode the 5th/6th byte as
3697 * follows:
3698 * - ID byte 6, bits[2:0]: 100b -> 43nm, 101b -> 32nm,
3699 * 110b -> 24nm
3700 * - ID byte 5, bit[7]: 1 -> BENAND, 0 -> raw SLC
3702 if (id_len >= 6 && id_data[0] == NAND_MFR_TOSHIBA &&
3703 nand_is_slc(chip) &&
3704 (id_data[5] & 0x7) == 0x6 /* 24nm */ &&
3705 !(id_data[4] & 0x80) /* !BENAND */) {
3706 mtd->oobsize = 32 * mtd->writesize >> 9;
3713 * Old devices have chip data hardcoded in the device ID table. nand_decode_id
3714 * decodes a matching ID table entry and assigns the MTD size parameters for
3715 * the chip.
3717 static void nand_decode_id(struct mtd_info *mtd, struct nand_chip *chip,
3718 struct nand_flash_dev *type, u8 id_data[8],
3719 int *busw)
3721 int maf_id = id_data[0];
3723 mtd->erasesize = type->erasesize;
3724 mtd->writesize = type->pagesize;
3725 mtd->oobsize = mtd->writesize / 32;
3726 *busw = type->options & NAND_BUSWIDTH_16;
3728 /* All legacy ID NAND are small-page, SLC */
3729 chip->bits_per_cell = 1;
3732 * Check for Spansion/AMD ID + repeating 5th, 6th byte since
3733 * some Spansion chips have erasesize that conflicts with size
3734 * listed in nand_ids table.
3735 * Data sheet (5 byte ID): Spansion S30ML-P ORNAND (p.39)
3737 if (maf_id == NAND_MFR_AMD && id_data[4] != 0x00 && id_data[5] == 0x00
3738 && id_data[6] == 0x00 && id_data[7] == 0x00
3739 && mtd->writesize == 512) {
3740 mtd->erasesize = 128 * 1024;
3741 mtd->erasesize <<= ((id_data[3] & 0x03) << 1);
3746 * Set the bad block marker/indicator (BBM/BBI) patterns according to some
3747 * heuristic patterns using various detected parameters (e.g., manufacturer,
3748 * page size, cell-type information).
3750 static void nand_decode_bbm_options(struct mtd_info *mtd,
3751 struct nand_chip *chip, u8 id_data[8])
3753 int maf_id = id_data[0];
3755 /* Set the bad block position */
3756 if (mtd->writesize > 512 || (chip->options & NAND_BUSWIDTH_16))
3757 chip->badblockpos = NAND_LARGE_BADBLOCK_POS;
3758 else
3759 chip->badblockpos = NAND_SMALL_BADBLOCK_POS;
3762 * Bad block marker is stored in the last page of each block on Samsung
3763 * and Hynix MLC devices; stored in first two pages of each block on
3764 * Micron devices with 2KiB pages and on SLC Samsung, Hynix, Toshiba,
3765 * AMD/Spansion, and Macronix. All others scan only the first page.
3767 if (!nand_is_slc(chip) &&
3768 (maf_id == NAND_MFR_SAMSUNG ||
3769 maf_id == NAND_MFR_HYNIX))
3770 chip->bbt_options |= NAND_BBT_SCANLASTPAGE;
3771 else if ((nand_is_slc(chip) &&
3772 (maf_id == NAND_MFR_SAMSUNG ||
3773 maf_id == NAND_MFR_HYNIX ||
3774 maf_id == NAND_MFR_TOSHIBA ||
3775 maf_id == NAND_MFR_AMD ||
3776 maf_id == NAND_MFR_MACRONIX)) ||
3777 (mtd->writesize == 2048 &&
3778 maf_id == NAND_MFR_MICRON))
3779 chip->bbt_options |= NAND_BBT_SCAN2NDPAGE;
3782 static inline bool is_full_id_nand(struct nand_flash_dev *type)
3784 return type->id_len;
3787 static bool find_full_id_nand(struct mtd_info *mtd, struct nand_chip *chip,
3788 struct nand_flash_dev *type, u8 *id_data, int *busw)
3790 if (!strncmp(type->id, id_data, type->id_len)) {
3791 mtd->writesize = type->pagesize;
3792 mtd->erasesize = type->erasesize;
3793 mtd->oobsize = type->oobsize;
3795 chip->bits_per_cell = nand_get_bits_per_cell(id_data[2]);
3796 chip->chipsize = (uint64_t)type->chipsize << 20;
3797 chip->options |= type->options;
3798 chip->ecc_strength_ds = NAND_ECC_STRENGTH(type);
3799 chip->ecc_step_ds = NAND_ECC_STEP(type);
3800 chip->onfi_timing_mode_default =
3801 type->onfi_timing_mode_default;
3803 *busw = type->options & NAND_BUSWIDTH_16;
3805 if (!mtd->name)
3806 mtd->name = type->name;
3808 return true;
3810 return false;
3814 * Get the flash and manufacturer id and lookup if the type is supported.
3816 static struct nand_flash_dev *nand_get_flash_type(struct mtd_info *mtd,
3817 struct nand_chip *chip,
3818 int *maf_id, int *dev_id,
3819 struct nand_flash_dev *type)
3821 int busw;
3822 int i, maf_idx;
3823 u8 id_data[8];
3825 /* Select the device */
3826 chip->select_chip(mtd, 0);
3829 * Reset the chip, required by some chips (e.g. Micron MT29FxGxxxxx)
3830 * after power-up.
3832 chip->cmdfunc(mtd, NAND_CMD_RESET, -1, -1);
3834 /* Send the command for reading device ID */
3835 chip->cmdfunc(mtd, NAND_CMD_READID, 0x00, -1);
3837 /* Read manufacturer and device IDs */
3838 *maf_id = chip->read_byte(mtd);
3839 *dev_id = chip->read_byte(mtd);
3842 * Try again to make sure, as some systems the bus-hold or other
3843 * interface concerns can cause random data which looks like a
3844 * possibly credible NAND flash to appear. If the two results do
3845 * not match, ignore the device completely.
3848 chip->cmdfunc(mtd, NAND_CMD_READID, 0x00, -1);
3850 /* Read entire ID string */
3851 for (i = 0; i < 8; i++)
3852 id_data[i] = chip->read_byte(mtd);
3854 if (id_data[0] != *maf_id || id_data[1] != *dev_id) {
3855 pr_info("second ID read did not match %02x,%02x against %02x,%02x\n",
3856 *maf_id, *dev_id, id_data[0], id_data[1]);
3857 return ERR_PTR(-ENODEV);
3860 if (!type)
3861 type = nand_flash_ids;
3863 for (; type->name != NULL; type++) {
3864 if (is_full_id_nand(type)) {
3865 if (find_full_id_nand(mtd, chip, type, id_data, &busw))
3866 goto ident_done;
3867 } else if (*dev_id == type->dev_id) {
3868 break;
3872 chip->onfi_version = 0;
3873 if (!type->name || !type->pagesize) {
3874 /* Check if the chip is ONFI compliant */
3875 if (nand_flash_detect_onfi(mtd, chip, &busw))
3876 goto ident_done;
3878 /* Check if the chip is JEDEC compliant */
3879 if (nand_flash_detect_jedec(mtd, chip, &busw))
3880 goto ident_done;
3883 if (!type->name)
3884 return ERR_PTR(-ENODEV);
3886 if (!mtd->name)
3887 mtd->name = type->name;
3889 chip->chipsize = (uint64_t)type->chipsize << 20;
3891 if (!type->pagesize) {
3892 /* Decode parameters from extended ID */
3893 nand_decode_ext_id(mtd, chip, id_data, &busw);
3894 } else {
3895 nand_decode_id(mtd, chip, type, id_data, &busw);
3897 /* Get chip options */
3898 chip->options |= type->options;
3901 * Check if chip is not a Samsung device. Do not clear the
3902 * options for chips which do not have an extended id.
3904 if (*maf_id != NAND_MFR_SAMSUNG && !type->pagesize)
3905 chip->options &= ~NAND_SAMSUNG_LP_OPTIONS;
3906 ident_done:
3908 /* Try to identify manufacturer */
3909 for (maf_idx = 0; nand_manuf_ids[maf_idx].id != 0x0; maf_idx++) {
3910 if (nand_manuf_ids[maf_idx].id == *maf_id)
3911 break;
3914 if (chip->options & NAND_BUSWIDTH_AUTO) {
3915 WARN_ON(chip->options & NAND_BUSWIDTH_16);
3916 chip->options |= busw;
3917 nand_set_defaults(chip, busw);
3918 } else if (busw != (chip->options & NAND_BUSWIDTH_16)) {
3920 * Check, if buswidth is correct. Hardware drivers should set
3921 * chip correct!
3923 pr_info("device found, Manufacturer ID: 0x%02x, Chip ID: 0x%02x\n",
3924 *maf_id, *dev_id);
3925 pr_info("%s %s\n", nand_manuf_ids[maf_idx].name, mtd->name);
3926 pr_warn("bus width %d instead %d bit\n",
3927 (chip->options & NAND_BUSWIDTH_16) ? 16 : 8,
3928 busw ? 16 : 8);
3929 return ERR_PTR(-EINVAL);
3932 nand_decode_bbm_options(mtd, chip, id_data);
3934 /* Calculate the address shift from the page size */
3935 chip->page_shift = ffs(mtd->writesize) - 1;
3936 /* Convert chipsize to number of pages per chip -1 */
3937 chip->pagemask = (chip->chipsize >> chip->page_shift) - 1;
3939 chip->bbt_erase_shift = chip->phys_erase_shift =
3940 ffs(mtd->erasesize) - 1;
3941 if (chip->chipsize & 0xffffffff)
3942 chip->chip_shift = ffs((unsigned)chip->chipsize) - 1;
3943 else {
3944 chip->chip_shift = ffs((unsigned)(chip->chipsize >> 32));
3945 chip->chip_shift += 32 - 1;
3948 chip->badblockbits = 8;
3949 chip->erase = single_erase;
3951 /* Do not replace user supplied command function! */
3952 if (mtd->writesize > 512 && chip->cmdfunc == nand_command)
3953 chip->cmdfunc = nand_command_lp;
3955 pr_info("device found, Manufacturer ID: 0x%02x, Chip ID: 0x%02x\n",
3956 *maf_id, *dev_id);
3958 if (chip->onfi_version)
3959 pr_info("%s %s\n", nand_manuf_ids[maf_idx].name,
3960 chip->onfi_params.model);
3961 else if (chip->jedec_version)
3962 pr_info("%s %s\n", nand_manuf_ids[maf_idx].name,
3963 chip->jedec_params.model);
3964 else
3965 pr_info("%s %s\n", nand_manuf_ids[maf_idx].name,
3966 type->name);
3968 pr_info("%d MiB, %s, erase size: %d KiB, page size: %d, OOB size: %d\n",
3969 (int)(chip->chipsize >> 20), nand_is_slc(chip) ? "SLC" : "MLC",
3970 mtd->erasesize >> 10, mtd->writesize, mtd->oobsize);
3971 return type;
3974 static const char * const nand_ecc_modes[] = {
3975 [NAND_ECC_NONE] = "none",
3976 [NAND_ECC_SOFT] = "soft",
3977 [NAND_ECC_HW] = "hw",
3978 [NAND_ECC_HW_SYNDROME] = "hw_syndrome",
3979 [NAND_ECC_HW_OOB_FIRST] = "hw_oob_first",
3982 static int of_get_nand_ecc_mode(struct device_node *np)
3984 const char *pm;
3985 int err, i;
3987 err = of_property_read_string(np, "nand-ecc-mode", &pm);
3988 if (err < 0)
3989 return err;
3991 for (i = 0; i < ARRAY_SIZE(nand_ecc_modes); i++)
3992 if (!strcasecmp(pm, nand_ecc_modes[i]))
3993 return i;
3996 * For backward compatibility we support few obsoleted values that don't
3997 * have their mappings into nand_ecc_modes_t anymore (they were merged
3998 * with other enums).
4000 if (!strcasecmp(pm, "soft_bch"))
4001 return NAND_ECC_SOFT;
4003 return -ENODEV;
4006 static const char * const nand_ecc_algos[] = {
4007 [NAND_ECC_HAMMING] = "hamming",
4008 [NAND_ECC_BCH] = "bch",
4011 static int of_get_nand_ecc_algo(struct device_node *np)
4013 const char *pm;
4014 int err, i;
4016 err = of_property_read_string(np, "nand-ecc-algo", &pm);
4017 if (!err) {
4018 for (i = NAND_ECC_HAMMING; i < ARRAY_SIZE(nand_ecc_algos); i++)
4019 if (!strcasecmp(pm, nand_ecc_algos[i]))
4020 return i;
4021 return -ENODEV;
4025 * For backward compatibility we also read "nand-ecc-mode" checking
4026 * for some obsoleted values that were specifying ECC algorithm.
4028 err = of_property_read_string(np, "nand-ecc-mode", &pm);
4029 if (err < 0)
4030 return err;
4032 if (!strcasecmp(pm, "soft"))
4033 return NAND_ECC_HAMMING;
4034 else if (!strcasecmp(pm, "soft_bch"))
4035 return NAND_ECC_BCH;
4037 return -ENODEV;
4040 static int of_get_nand_ecc_step_size(struct device_node *np)
4042 int ret;
4043 u32 val;
4045 ret = of_property_read_u32(np, "nand-ecc-step-size", &val);
4046 return ret ? ret : val;
4049 static int of_get_nand_ecc_strength(struct device_node *np)
4051 int ret;
4052 u32 val;
4054 ret = of_property_read_u32(np, "nand-ecc-strength", &val);
4055 return ret ? ret : val;
4058 static int of_get_nand_bus_width(struct device_node *np)
4060 u32 val;
4062 if (of_property_read_u32(np, "nand-bus-width", &val))
4063 return 8;
4065 switch (val) {
4066 case 8:
4067 case 16:
4068 return val;
4069 default:
4070 return -EIO;
4074 static bool of_get_nand_on_flash_bbt(struct device_node *np)
4076 return of_property_read_bool(np, "nand-on-flash-bbt");
4079 static int nand_dt_init(struct nand_chip *chip)
4081 struct device_node *dn = nand_get_flash_node(chip);
4082 int ecc_mode, ecc_algo, ecc_strength, ecc_step;
4084 if (!dn)
4085 return 0;
4087 if (of_get_nand_bus_width(dn) == 16)
4088 chip->options |= NAND_BUSWIDTH_16;
4090 if (of_get_nand_on_flash_bbt(dn))
4091 chip->bbt_options |= NAND_BBT_USE_FLASH;
4093 ecc_mode = of_get_nand_ecc_mode(dn);
4094 ecc_algo = of_get_nand_ecc_algo(dn);
4095 ecc_strength = of_get_nand_ecc_strength(dn);
4096 ecc_step = of_get_nand_ecc_step_size(dn);
4098 if ((ecc_step >= 0 && !(ecc_strength >= 0)) ||
4099 (!(ecc_step >= 0) && ecc_strength >= 0)) {
4100 pr_err("must set both strength and step size in DT\n");
4101 return -EINVAL;
4104 if (ecc_mode >= 0)
4105 chip->ecc.mode = ecc_mode;
4107 if (ecc_algo >= 0)
4108 chip->ecc.algo = ecc_algo;
4110 if (ecc_strength >= 0)
4111 chip->ecc.strength = ecc_strength;
4113 if (ecc_step > 0)
4114 chip->ecc.size = ecc_step;
4116 return 0;
4120 * nand_scan_ident - [NAND Interface] Scan for the NAND device
4121 * @mtd: MTD device structure
4122 * @maxchips: number of chips to scan for
4123 * @table: alternative NAND ID table
4125 * This is the first phase of the normal nand_scan() function. It reads the
4126 * flash ID and sets up MTD fields accordingly.
4129 int nand_scan_ident(struct mtd_info *mtd, int maxchips,
4130 struct nand_flash_dev *table)
4132 int i, nand_maf_id, nand_dev_id;
4133 struct nand_chip *chip = mtd_to_nand(mtd);
4134 struct nand_flash_dev *type;
4135 int ret;
4137 ret = nand_dt_init(chip);
4138 if (ret)
4139 return ret;
4141 if (!mtd->name && mtd->dev.parent)
4142 mtd->name = dev_name(mtd->dev.parent);
4144 /* Set the default functions */
4145 nand_set_defaults(chip, chip->options & NAND_BUSWIDTH_16);
4147 /* Read the flash type */
4148 type = nand_get_flash_type(mtd, chip, &nand_maf_id,
4149 &nand_dev_id, table);
4151 if (IS_ERR(type)) {
4152 if (!(chip->options & NAND_SCAN_SILENT_NODEV))
4153 pr_warn("No NAND device found\n");
4154 chip->select_chip(mtd, -1);
4155 return PTR_ERR(type);
4158 chip->select_chip(mtd, -1);
4160 /* Check for a chip array */
4161 for (i = 1; i < maxchips; i++) {
4162 chip->select_chip(mtd, i);
4163 /* See comment in nand_get_flash_type for reset */
4164 chip->cmdfunc(mtd, NAND_CMD_RESET, -1, -1);
4165 /* Send the command for reading device ID */
4166 chip->cmdfunc(mtd, NAND_CMD_READID, 0x00, -1);
4167 /* Read manufacturer and device IDs */
4168 if (nand_maf_id != chip->read_byte(mtd) ||
4169 nand_dev_id != chip->read_byte(mtd)) {
4170 chip->select_chip(mtd, -1);
4171 break;
4173 chip->select_chip(mtd, -1);
4175 if (i > 1)
4176 pr_info("%d chips detected\n", i);
4178 /* Store the number of chips and calc total size for mtd */
4179 chip->numchips = i;
4180 mtd->size = i * chip->chipsize;
4182 return 0;
4184 EXPORT_SYMBOL(nand_scan_ident);
4186 static int nand_set_ecc_soft_ops(struct mtd_info *mtd)
4188 struct nand_chip *chip = mtd_to_nand(mtd);
4189 struct nand_ecc_ctrl *ecc = &chip->ecc;
4191 if (WARN_ON(ecc->mode != NAND_ECC_SOFT))
4192 return -EINVAL;
4194 switch (ecc->algo) {
4195 case NAND_ECC_HAMMING:
4196 ecc->calculate = nand_calculate_ecc;
4197 ecc->correct = nand_correct_data;
4198 ecc->read_page = nand_read_page_swecc;
4199 ecc->read_subpage = nand_read_subpage;
4200 ecc->write_page = nand_write_page_swecc;
4201 ecc->read_page_raw = nand_read_page_raw;
4202 ecc->write_page_raw = nand_write_page_raw;
4203 ecc->read_oob = nand_read_oob_std;
4204 ecc->write_oob = nand_write_oob_std;
4205 if (!ecc->size)
4206 ecc->size = 256;
4207 ecc->bytes = 3;
4208 ecc->strength = 1;
4209 return 0;
4210 case NAND_ECC_BCH:
4211 if (!mtd_nand_has_bch()) {
4212 WARN(1, "CONFIG_MTD_NAND_ECC_BCH not enabled\n");
4213 return -EINVAL;
4215 ecc->calculate = nand_bch_calculate_ecc;
4216 ecc->correct = nand_bch_correct_data;
4217 ecc->read_page = nand_read_page_swecc;
4218 ecc->read_subpage = nand_read_subpage;
4219 ecc->write_page = nand_write_page_swecc;
4220 ecc->read_page_raw = nand_read_page_raw;
4221 ecc->write_page_raw = nand_write_page_raw;
4222 ecc->read_oob = nand_read_oob_std;
4223 ecc->write_oob = nand_write_oob_std;
4225 * Board driver should supply ecc.size and ecc.strength
4226 * values to select how many bits are correctable.
4227 * Otherwise, default to 4 bits for large page devices.
4229 if (!ecc->size && (mtd->oobsize >= 64)) {
4230 ecc->size = 512;
4231 ecc->strength = 4;
4235 * if no ecc placement scheme was provided pickup the default
4236 * large page one.
4238 if (!mtd->ooblayout) {
4239 /* handle large page devices only */
4240 if (mtd->oobsize < 64) {
4241 WARN(1, "OOB layout is required when using software BCH on small pages\n");
4242 return -EINVAL;
4245 mtd_set_ooblayout(mtd, &nand_ooblayout_lp_ops);
4248 /* See nand_bch_init() for details. */
4249 ecc->bytes = 0;
4250 ecc->priv = nand_bch_init(mtd);
4251 if (!ecc->priv) {
4252 WARN(1, "BCH ECC initialization failed!\n");
4253 return -EINVAL;
4255 return 0;
4256 default:
4257 WARN(1, "Unsupported ECC algorithm!\n");
4258 return -EINVAL;
4263 * Check if the chip configuration meet the datasheet requirements.
4265 * If our configuration corrects A bits per B bytes and the minimum
4266 * required correction level is X bits per Y bytes, then we must ensure
4267 * both of the following are true:
4269 * (1) A / B >= X / Y
4270 * (2) A >= X
4272 * Requirement (1) ensures we can correct for the required bitflip density.
4273 * Requirement (2) ensures we can correct even when all bitflips are clumped
4274 * in the same sector.
4276 static bool nand_ecc_strength_good(struct mtd_info *mtd)
4278 struct nand_chip *chip = mtd_to_nand(mtd);
4279 struct nand_ecc_ctrl *ecc = &chip->ecc;
4280 int corr, ds_corr;
4282 if (ecc->size == 0 || chip->ecc_step_ds == 0)
4283 /* Not enough information */
4284 return true;
4287 * We get the number of corrected bits per page to compare
4288 * the correction density.
4290 corr = (mtd->writesize * ecc->strength) / ecc->size;
4291 ds_corr = (mtd->writesize * chip->ecc_strength_ds) / chip->ecc_step_ds;
4293 return corr >= ds_corr && ecc->strength >= chip->ecc_strength_ds;
4297 * nand_scan_tail - [NAND Interface] Scan for the NAND device
4298 * @mtd: MTD device structure
4300 * This is the second phase of the normal nand_scan() function. It fills out
4301 * all the uninitialized function pointers with the defaults and scans for a
4302 * bad block table if appropriate.
4304 int nand_scan_tail(struct mtd_info *mtd)
4306 struct nand_chip *chip = mtd_to_nand(mtd);
4307 struct nand_ecc_ctrl *ecc = &chip->ecc;
4308 struct nand_buffers *nbuf;
4309 int ret;
4311 /* New bad blocks should be marked in OOB, flash-based BBT, or both */
4312 if (WARN_ON((chip->bbt_options & NAND_BBT_NO_OOB_BBM) &&
4313 !(chip->bbt_options & NAND_BBT_USE_FLASH)))
4314 return -EINVAL;
4316 if (!(chip->options & NAND_OWN_BUFFERS)) {
4317 nbuf = kzalloc(sizeof(*nbuf) + mtd->writesize
4318 + mtd->oobsize * 3, GFP_KERNEL);
4319 if (!nbuf)
4320 return -ENOMEM;
4321 nbuf->ecccalc = (uint8_t *)(nbuf + 1);
4322 nbuf->ecccode = nbuf->ecccalc + mtd->oobsize;
4323 nbuf->databuf = nbuf->ecccode + mtd->oobsize;
4325 chip->buffers = nbuf;
4326 } else {
4327 if (!chip->buffers)
4328 return -ENOMEM;
4331 /* Set the internal oob buffer location, just after the page data */
4332 chip->oob_poi = chip->buffers->databuf + mtd->writesize;
4335 * If no default placement scheme is given, select an appropriate one.
4337 if (!mtd->ooblayout &&
4338 !(ecc->mode == NAND_ECC_SOFT && ecc->algo == NAND_ECC_BCH)) {
4339 switch (mtd->oobsize) {
4340 case 8:
4341 case 16:
4342 mtd_set_ooblayout(mtd, &nand_ooblayout_sp_ops);
4343 break;
4344 case 64:
4345 case 128:
4346 mtd_set_ooblayout(mtd, &nand_ooblayout_lp_ops);
4347 break;
4348 default:
4349 WARN(1, "No oob scheme defined for oobsize %d\n",
4350 mtd->oobsize);
4351 ret = -EINVAL;
4352 goto err_free;
4356 if (!chip->write_page)
4357 chip->write_page = nand_write_page;
4360 * Check ECC mode, default to software if 3byte/512byte hardware ECC is
4361 * selected and we have 256 byte pagesize fallback to software ECC
4364 switch (ecc->mode) {
4365 case NAND_ECC_HW_OOB_FIRST:
4366 /* Similar to NAND_ECC_HW, but a separate read_page handle */
4367 if (!ecc->calculate || !ecc->correct || !ecc->hwctl) {
4368 WARN(1, "No ECC functions supplied; hardware ECC not possible\n");
4369 ret = -EINVAL;
4370 goto err_free;
4372 if (!ecc->read_page)
4373 ecc->read_page = nand_read_page_hwecc_oob_first;
4375 case NAND_ECC_HW:
4376 /* Use standard hwecc read page function? */
4377 if (!ecc->read_page)
4378 ecc->read_page = nand_read_page_hwecc;
4379 if (!ecc->write_page)
4380 ecc->write_page = nand_write_page_hwecc;
4381 if (!ecc->read_page_raw)
4382 ecc->read_page_raw = nand_read_page_raw;
4383 if (!ecc->write_page_raw)
4384 ecc->write_page_raw = nand_write_page_raw;
4385 if (!ecc->read_oob)
4386 ecc->read_oob = nand_read_oob_std;
4387 if (!ecc->write_oob)
4388 ecc->write_oob = nand_write_oob_std;
4389 if (!ecc->read_subpage)
4390 ecc->read_subpage = nand_read_subpage;
4391 if (!ecc->write_subpage && ecc->hwctl && ecc->calculate)
4392 ecc->write_subpage = nand_write_subpage_hwecc;
4394 case NAND_ECC_HW_SYNDROME:
4395 if ((!ecc->calculate || !ecc->correct || !ecc->hwctl) &&
4396 (!ecc->read_page ||
4397 ecc->read_page == nand_read_page_hwecc ||
4398 !ecc->write_page ||
4399 ecc->write_page == nand_write_page_hwecc)) {
4400 WARN(1, "No ECC functions supplied; hardware ECC not possible\n");
4401 ret = -EINVAL;
4402 goto err_free;
4404 /* Use standard syndrome read/write page function? */
4405 if (!ecc->read_page)
4406 ecc->read_page = nand_read_page_syndrome;
4407 if (!ecc->write_page)
4408 ecc->write_page = nand_write_page_syndrome;
4409 if (!ecc->read_page_raw)
4410 ecc->read_page_raw = nand_read_page_raw_syndrome;
4411 if (!ecc->write_page_raw)
4412 ecc->write_page_raw = nand_write_page_raw_syndrome;
4413 if (!ecc->read_oob)
4414 ecc->read_oob = nand_read_oob_syndrome;
4415 if (!ecc->write_oob)
4416 ecc->write_oob = nand_write_oob_syndrome;
4418 if (mtd->writesize >= ecc->size) {
4419 if (!ecc->strength) {
4420 WARN(1, "Driver must set ecc.strength when using hardware ECC\n");
4421 ret = -EINVAL;
4422 goto err_free;
4424 break;
4426 pr_warn("%d byte HW ECC not possible on %d byte page size, fallback to SW ECC\n",
4427 ecc->size, mtd->writesize);
4428 ecc->mode = NAND_ECC_SOFT;
4429 ecc->algo = NAND_ECC_HAMMING;
4431 case NAND_ECC_SOFT:
4432 ret = nand_set_ecc_soft_ops(mtd);
4433 if (ret) {
4434 ret = -EINVAL;
4435 goto err_free;
4437 break;
4439 case NAND_ECC_NONE:
4440 pr_warn("NAND_ECC_NONE selected by board driver. This is not recommended!\n");
4441 ecc->read_page = nand_read_page_raw;
4442 ecc->write_page = nand_write_page_raw;
4443 ecc->read_oob = nand_read_oob_std;
4444 ecc->read_page_raw = nand_read_page_raw;
4445 ecc->write_page_raw = nand_write_page_raw;
4446 ecc->write_oob = nand_write_oob_std;
4447 ecc->size = mtd->writesize;
4448 ecc->bytes = 0;
4449 ecc->strength = 0;
4450 break;
4452 default:
4453 WARN(1, "Invalid NAND_ECC_MODE %d\n", ecc->mode);
4454 ret = -EINVAL;
4455 goto err_free;
4458 /* For many systems, the standard OOB write also works for raw */
4459 if (!ecc->read_oob_raw)
4460 ecc->read_oob_raw = ecc->read_oob;
4461 if (!ecc->write_oob_raw)
4462 ecc->write_oob_raw = ecc->write_oob;
4464 /* propagate ecc info to mtd_info */
4465 mtd->ecc_strength = ecc->strength;
4466 mtd->ecc_step_size = ecc->size;
4469 * Set the number of read / write steps for one page depending on ECC
4470 * mode.
4472 ecc->steps = mtd->writesize / ecc->size;
4473 if (ecc->steps * ecc->size != mtd->writesize) {
4474 WARN(1, "Invalid ECC parameters\n");
4475 ret = -EINVAL;
4476 goto err_free;
4478 ecc->total = ecc->steps * ecc->bytes;
4481 * The number of bytes available for a client to place data into
4482 * the out of band area.
4484 ret = mtd_ooblayout_count_freebytes(mtd);
4485 if (ret < 0)
4486 ret = 0;
4488 mtd->oobavail = ret;
4490 /* ECC sanity check: warn if it's too weak */
4491 if (!nand_ecc_strength_good(mtd))
4492 pr_warn("WARNING: %s: the ECC used on your system is too weak compared to the one required by the NAND chip\n",
4493 mtd->name);
4495 /* Allow subpage writes up to ecc.steps. Not possible for MLC flash */
4496 if (!(chip->options & NAND_NO_SUBPAGE_WRITE) && nand_is_slc(chip)) {
4497 switch (ecc->steps) {
4498 case 2:
4499 mtd->subpage_sft = 1;
4500 break;
4501 case 4:
4502 case 8:
4503 case 16:
4504 mtd->subpage_sft = 2;
4505 break;
4508 chip->subpagesize = mtd->writesize >> mtd->subpage_sft;
4510 /* Initialize state */
4511 chip->state = FL_READY;
4513 /* Invalidate the pagebuffer reference */
4514 chip->pagebuf = -1;
4516 /* Large page NAND with SOFT_ECC should support subpage reads */
4517 switch (ecc->mode) {
4518 case NAND_ECC_SOFT:
4519 if (chip->page_shift > 9)
4520 chip->options |= NAND_SUBPAGE_READ;
4521 break;
4523 default:
4524 break;
4527 /* Fill in remaining MTD driver data */
4528 mtd->type = nand_is_slc(chip) ? MTD_NANDFLASH : MTD_MLCNANDFLASH;
4529 mtd->flags = (chip->options & NAND_ROM) ? MTD_CAP_ROM :
4530 MTD_CAP_NANDFLASH;
4531 mtd->_erase = nand_erase;
4532 mtd->_point = NULL;
4533 mtd->_unpoint = NULL;
4534 mtd->_read = nand_read;
4535 mtd->_write = nand_write;
4536 mtd->_panic_write = panic_nand_write;
4537 mtd->_read_oob = nand_read_oob;
4538 mtd->_write_oob = nand_write_oob;
4539 mtd->_sync = nand_sync;
4540 mtd->_lock = NULL;
4541 mtd->_unlock = NULL;
4542 mtd->_suspend = nand_suspend;
4543 mtd->_resume = nand_resume;
4544 mtd->_reboot = nand_shutdown;
4545 mtd->_block_isreserved = nand_block_isreserved;
4546 mtd->_block_isbad = nand_block_isbad;
4547 mtd->_block_markbad = nand_block_markbad;
4548 mtd->writebufsize = mtd->writesize;
4551 * Initialize bitflip_threshold to its default prior scan_bbt() call.
4552 * scan_bbt() might invoke mtd_read(), thus bitflip_threshold must be
4553 * properly set.
4555 if (!mtd->bitflip_threshold)
4556 mtd->bitflip_threshold = DIV_ROUND_UP(mtd->ecc_strength * 3, 4);
4558 /* Check, if we should skip the bad block table scan */
4559 if (chip->options & NAND_SKIP_BBTSCAN)
4560 return 0;
4562 /* Build bad block table */
4563 return chip->scan_bbt(mtd);
4564 err_free:
4565 if (!(chip->options & NAND_OWN_BUFFERS))
4566 kfree(chip->buffers);
4567 return ret;
4569 EXPORT_SYMBOL(nand_scan_tail);
4572 * is_module_text_address() isn't exported, and it's mostly a pointless
4573 * test if this is a module _anyway_ -- they'd have to try _really_ hard
4574 * to call us from in-kernel code if the core NAND support is modular.
4576 #ifdef MODULE
4577 #define caller_is_module() (1)
4578 #else
4579 #define caller_is_module() \
4580 is_module_text_address((unsigned long)__builtin_return_address(0))
4581 #endif
4584 * nand_scan - [NAND Interface] Scan for the NAND device
4585 * @mtd: MTD device structure
4586 * @maxchips: number of chips to scan for
4588 * This fills out all the uninitialized function pointers with the defaults.
4589 * The flash ID is read and the mtd/chip structures are filled with the
4590 * appropriate values.
4592 int nand_scan(struct mtd_info *mtd, int maxchips)
4594 int ret;
4596 ret = nand_scan_ident(mtd, maxchips, NULL);
4597 if (!ret)
4598 ret = nand_scan_tail(mtd);
4599 return ret;
4601 EXPORT_SYMBOL(nand_scan);
4604 * nand_release - [NAND Interface] Free resources held by the NAND device
4605 * @mtd: MTD device structure
4607 void nand_release(struct mtd_info *mtd)
4609 struct nand_chip *chip = mtd_to_nand(mtd);
4611 if (chip->ecc.mode == NAND_ECC_SOFT &&
4612 chip->ecc.algo == NAND_ECC_BCH)
4613 nand_bch_free((struct nand_bch_control *)chip->ecc.priv);
4615 mtd_device_unregister(mtd);
4617 /* Free bad block table memory */
4618 kfree(chip->bbt);
4619 if (!(chip->options & NAND_OWN_BUFFERS))
4620 kfree(chip->buffers);
4622 /* Free bad block descriptor memory */
4623 if (chip->badblock_pattern && chip->badblock_pattern->options
4624 & NAND_BBT_DYNAMICSTRUCT)
4625 kfree(chip->badblock_pattern);
4627 EXPORT_SYMBOL_GPL(nand_release);
4629 MODULE_LICENSE("GPL");
4630 MODULE_AUTHOR("Steven J. Hill <sjhill@realitydiluted.com>");
4631 MODULE_AUTHOR("Thomas Gleixner <tglx@linutronix.de>");
4632 MODULE_DESCRIPTION("Generic NAND flash driver code");