KVM: nVMX: Fix returned value of MSR_IA32_VMX_VMCS_ENUM
[linux/fpc-iii.git] / drivers / mtd / nand / nand_base.c
blob41167e9e991e4e50c1e1c2b72dbc468d654db22d
1 /*
2 * drivers/mtd/nand.c
4 * Overview:
5 * This is the generic MTD driver for NAND flash devices. It should be
6 * capable of working with almost all NAND chips currently available.
8 * Additional technical information is available on
9 * http://www.linux-mtd.infradead.org/doc/nand.html
11 * Copyright (C) 2000 Steven J. Hill (sjhill@realitydiluted.com)
12 * 2002-2006 Thomas Gleixner (tglx@linutronix.de)
14 * Credits:
15 * David Woodhouse for adding multichip support
17 * Aleph One Ltd. and Toby Churchill Ltd. for supporting the
18 * rework for 2K page size chips
20 * TODO:
21 * Enable cached programming for 2k page size chips
22 * Check, if mtd->ecctype should be set to MTD_ECC_HW
23 * if we have HW ECC support.
24 * BBT table is not serialized, has to be fixed
26 * This program is free software; you can redistribute it and/or modify
27 * it under the terms of the GNU General Public License version 2 as
28 * published by the Free Software Foundation.
32 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
34 #include <linux/module.h>
35 #include <linux/delay.h>
36 #include <linux/errno.h>
37 #include <linux/err.h>
38 #include <linux/sched.h>
39 #include <linux/slab.h>
40 #include <linux/mm.h>
41 #include <linux/types.h>
42 #include <linux/mtd/mtd.h>
43 #include <linux/mtd/nand.h>
44 #include <linux/mtd/nand_ecc.h>
45 #include <linux/mtd/nand_bch.h>
46 #include <linux/interrupt.h>
47 #include <linux/bitops.h>
48 #include <linux/leds.h>
49 #include <linux/io.h>
50 #include <linux/mtd/partitions.h>
52 /* Define default oob placement schemes for large and small page devices */
53 static struct nand_ecclayout nand_oob_8 = {
54 .eccbytes = 3,
55 .eccpos = {0, 1, 2},
56 .oobfree = {
57 {.offset = 3,
58 .length = 2},
59 {.offset = 6,
60 .length = 2} }
63 static struct nand_ecclayout nand_oob_16 = {
64 .eccbytes = 6,
65 .eccpos = {0, 1, 2, 3, 6, 7},
66 .oobfree = {
67 {.offset = 8,
68 . length = 8} }
71 static struct nand_ecclayout nand_oob_64 = {
72 .eccbytes = 24,
73 .eccpos = {
74 40, 41, 42, 43, 44, 45, 46, 47,
75 48, 49, 50, 51, 52, 53, 54, 55,
76 56, 57, 58, 59, 60, 61, 62, 63},
77 .oobfree = {
78 {.offset = 2,
79 .length = 38} }
82 static struct nand_ecclayout nand_oob_128 = {
83 .eccbytes = 48,
84 .eccpos = {
85 80, 81, 82, 83, 84, 85, 86, 87,
86 88, 89, 90, 91, 92, 93, 94, 95,
87 96, 97, 98, 99, 100, 101, 102, 103,
88 104, 105, 106, 107, 108, 109, 110, 111,
89 112, 113, 114, 115, 116, 117, 118, 119,
90 120, 121, 122, 123, 124, 125, 126, 127},
91 .oobfree = {
92 {.offset = 2,
93 .length = 78} }
96 static int nand_get_device(struct mtd_info *mtd, int new_state);
98 static int nand_do_write_oob(struct mtd_info *mtd, loff_t to,
99 struct mtd_oob_ops *ops);
102 * For devices which display every fart in the system on a separate LED. Is
103 * compiled away when LED support is disabled.
105 DEFINE_LED_TRIGGER(nand_led_trigger);
107 static int check_offs_len(struct mtd_info *mtd,
108 loff_t ofs, uint64_t len)
110 struct nand_chip *chip = mtd->priv;
111 int ret = 0;
113 /* Start address must align on block boundary */
114 if (ofs & ((1ULL << chip->phys_erase_shift) - 1)) {
115 pr_debug("%s: unaligned address\n", __func__);
116 ret = -EINVAL;
119 /* Length must align on block boundary */
120 if (len & ((1ULL << chip->phys_erase_shift) - 1)) {
121 pr_debug("%s: length not block aligned\n", __func__);
122 ret = -EINVAL;
125 return ret;
129 * nand_release_device - [GENERIC] release chip
130 * @mtd: MTD device structure
132 * Release chip lock and wake up anyone waiting on the device.
134 static void nand_release_device(struct mtd_info *mtd)
136 struct nand_chip *chip = mtd->priv;
138 /* Release the controller and the chip */
139 spin_lock(&chip->controller->lock);
140 chip->controller->active = NULL;
141 chip->state = FL_READY;
142 wake_up(&chip->controller->wq);
143 spin_unlock(&chip->controller->lock);
147 * nand_read_byte - [DEFAULT] read one byte from the chip
148 * @mtd: MTD device structure
150 * Default read function for 8bit buswidth
152 static uint8_t nand_read_byte(struct mtd_info *mtd)
154 struct nand_chip *chip = mtd->priv;
155 return readb(chip->IO_ADDR_R);
159 * nand_read_byte16 - [DEFAULT] read one byte endianness aware from the chip
160 * nand_read_byte16 - [DEFAULT] read one byte endianness aware from the chip
161 * @mtd: MTD device structure
163 * Default read function for 16bit buswidth with endianness conversion.
166 static uint8_t nand_read_byte16(struct mtd_info *mtd)
168 struct nand_chip *chip = mtd->priv;
169 return (uint8_t) cpu_to_le16(readw(chip->IO_ADDR_R));
173 * nand_read_word - [DEFAULT] read one word from the chip
174 * @mtd: MTD device structure
176 * Default read function for 16bit buswidth without endianness conversion.
178 static u16 nand_read_word(struct mtd_info *mtd)
180 struct nand_chip *chip = mtd->priv;
181 return readw(chip->IO_ADDR_R);
185 * nand_select_chip - [DEFAULT] control CE line
186 * @mtd: MTD device structure
187 * @chipnr: chipnumber to select, -1 for deselect
189 * Default select function for 1 chip devices.
191 static void nand_select_chip(struct mtd_info *mtd, int chipnr)
193 struct nand_chip *chip = mtd->priv;
195 switch (chipnr) {
196 case -1:
197 chip->cmd_ctrl(mtd, NAND_CMD_NONE, 0 | NAND_CTRL_CHANGE);
198 break;
199 case 0:
200 break;
202 default:
203 BUG();
208 * nand_write_byte - [DEFAULT] write single byte to chip
209 * @mtd: MTD device structure
210 * @byte: value to write
212 * Default function to write a byte to I/O[7:0]
214 static void nand_write_byte(struct mtd_info *mtd, uint8_t byte)
216 struct nand_chip *chip = mtd->priv;
218 chip->write_buf(mtd, &byte, 1);
222 * nand_write_byte16 - [DEFAULT] write single byte to a chip with width 16
223 * @mtd: MTD device structure
224 * @byte: value to write
226 * Default function to write a byte to I/O[7:0] on a 16-bit wide chip.
228 static void nand_write_byte16(struct mtd_info *mtd, uint8_t byte)
230 struct nand_chip *chip = mtd->priv;
231 uint16_t word = byte;
234 * It's not entirely clear what should happen to I/O[15:8] when writing
235 * a byte. The ONFi spec (Revision 3.1; 2012-09-19, Section 2.16) reads:
237 * When the host supports a 16-bit bus width, only data is
238 * transferred at the 16-bit width. All address and command line
239 * transfers shall use only the lower 8-bits of the data bus. During
240 * command transfers, the host may place any value on the upper
241 * 8-bits of the data bus. During address transfers, the host shall
242 * set the upper 8-bits of the data bus to 00h.
244 * One user of the write_byte callback is nand_onfi_set_features. The
245 * four parameters are specified to be written to I/O[7:0], but this is
246 * neither an address nor a command transfer. Let's assume a 0 on the
247 * upper I/O lines is OK.
249 chip->write_buf(mtd, (uint8_t *)&word, 2);
253 * nand_write_buf - [DEFAULT] write buffer to chip
254 * @mtd: MTD device structure
255 * @buf: data buffer
256 * @len: number of bytes to write
258 * Default write function for 8bit buswidth.
260 static void nand_write_buf(struct mtd_info *mtd, const uint8_t *buf, int len)
262 struct nand_chip *chip = mtd->priv;
264 iowrite8_rep(chip->IO_ADDR_W, buf, len);
268 * nand_read_buf - [DEFAULT] read chip data into buffer
269 * @mtd: MTD device structure
270 * @buf: buffer to store date
271 * @len: number of bytes to read
273 * Default read function for 8bit buswidth.
275 static void nand_read_buf(struct mtd_info *mtd, uint8_t *buf, int len)
277 struct nand_chip *chip = mtd->priv;
279 ioread8_rep(chip->IO_ADDR_R, buf, len);
283 * nand_write_buf16 - [DEFAULT] write buffer to chip
284 * @mtd: MTD device structure
285 * @buf: data buffer
286 * @len: number of bytes to write
288 * Default write function for 16bit buswidth.
290 static void nand_write_buf16(struct mtd_info *mtd, const uint8_t *buf, int len)
292 struct nand_chip *chip = mtd->priv;
293 u16 *p = (u16 *) buf;
295 iowrite16_rep(chip->IO_ADDR_W, p, len >> 1);
299 * nand_read_buf16 - [DEFAULT] read chip data into buffer
300 * @mtd: MTD device structure
301 * @buf: buffer to store date
302 * @len: number of bytes to read
304 * Default read function for 16bit buswidth.
306 static void nand_read_buf16(struct mtd_info *mtd, uint8_t *buf, int len)
308 struct nand_chip *chip = mtd->priv;
309 u16 *p = (u16 *) buf;
311 ioread16_rep(chip->IO_ADDR_R, p, len >> 1);
315 * nand_block_bad - [DEFAULT] Read bad block marker from the chip
316 * @mtd: MTD device structure
317 * @ofs: offset from device start
318 * @getchip: 0, if the chip is already selected
320 * Check, if the block is bad.
322 static int nand_block_bad(struct mtd_info *mtd, loff_t ofs, int getchip)
324 int page, chipnr, res = 0, i = 0;
325 struct nand_chip *chip = mtd->priv;
326 u16 bad;
328 if (chip->bbt_options & NAND_BBT_SCANLASTPAGE)
329 ofs += mtd->erasesize - mtd->writesize;
331 page = (int)(ofs >> chip->page_shift) & chip->pagemask;
333 if (getchip) {
334 chipnr = (int)(ofs >> chip->chip_shift);
336 nand_get_device(mtd, FL_READING);
338 /* Select the NAND device */
339 chip->select_chip(mtd, chipnr);
342 do {
343 if (chip->options & NAND_BUSWIDTH_16) {
344 chip->cmdfunc(mtd, NAND_CMD_READOOB,
345 chip->badblockpos & 0xFE, page);
346 bad = cpu_to_le16(chip->read_word(mtd));
347 if (chip->badblockpos & 0x1)
348 bad >>= 8;
349 else
350 bad &= 0xFF;
351 } else {
352 chip->cmdfunc(mtd, NAND_CMD_READOOB, chip->badblockpos,
353 page);
354 bad = chip->read_byte(mtd);
357 if (likely(chip->badblockbits == 8))
358 res = bad != 0xFF;
359 else
360 res = hweight8(bad) < chip->badblockbits;
361 ofs += mtd->writesize;
362 page = (int)(ofs >> chip->page_shift) & chip->pagemask;
363 i++;
364 } while (!res && i < 2 && (chip->bbt_options & NAND_BBT_SCAN2NDPAGE));
366 if (getchip) {
367 chip->select_chip(mtd, -1);
368 nand_release_device(mtd);
371 return res;
375 * nand_default_block_markbad - [DEFAULT] mark a block bad via bad block marker
376 * @mtd: MTD device structure
377 * @ofs: offset from device start
379 * This is the default implementation, which can be overridden by a hardware
380 * specific driver. It provides the details for writing a bad block marker to a
381 * block.
383 static int nand_default_block_markbad(struct mtd_info *mtd, loff_t ofs)
385 struct nand_chip *chip = mtd->priv;
386 struct mtd_oob_ops ops;
387 uint8_t buf[2] = { 0, 0 };
388 int ret = 0, res, i = 0;
390 ops.datbuf = NULL;
391 ops.oobbuf = buf;
392 ops.ooboffs = chip->badblockpos;
393 if (chip->options & NAND_BUSWIDTH_16) {
394 ops.ooboffs &= ~0x01;
395 ops.len = ops.ooblen = 2;
396 } else {
397 ops.len = ops.ooblen = 1;
399 ops.mode = MTD_OPS_PLACE_OOB;
401 /* Write to first/last page(s) if necessary */
402 if (chip->bbt_options & NAND_BBT_SCANLASTPAGE)
403 ofs += mtd->erasesize - mtd->writesize;
404 do {
405 res = nand_do_write_oob(mtd, ofs, &ops);
406 if (!ret)
407 ret = res;
409 i++;
410 ofs += mtd->writesize;
411 } while ((chip->bbt_options & NAND_BBT_SCAN2NDPAGE) && i < 2);
413 return ret;
417 * nand_block_markbad_lowlevel - mark a block bad
418 * @mtd: MTD device structure
419 * @ofs: offset from device start
421 * This function performs the generic NAND bad block marking steps (i.e., bad
422 * block table(s) and/or marker(s)). We only allow the hardware driver to
423 * specify how to write bad block markers to OOB (chip->block_markbad).
425 * We try operations in the following order:
426 * (1) erase the affected block, to allow OOB marker to be written cleanly
427 * (2) write bad block marker to OOB area of affected block (unless flag
428 * NAND_BBT_NO_OOB_BBM is present)
429 * (3) update the BBT
430 * Note that we retain the first error encountered in (2) or (3), finish the
431 * procedures, and dump the error in the end.
433 static int nand_block_markbad_lowlevel(struct mtd_info *mtd, loff_t ofs)
435 struct nand_chip *chip = mtd->priv;
436 int res, ret = 0;
438 if (!(chip->bbt_options & NAND_BBT_NO_OOB_BBM)) {
439 struct erase_info einfo;
441 /* Attempt erase before marking OOB */
442 memset(&einfo, 0, sizeof(einfo));
443 einfo.mtd = mtd;
444 einfo.addr = ofs;
445 einfo.len = 1ULL << chip->phys_erase_shift;
446 nand_erase_nand(mtd, &einfo, 0);
448 /* Write bad block marker to OOB */
449 nand_get_device(mtd, FL_WRITING);
450 ret = chip->block_markbad(mtd, ofs);
451 nand_release_device(mtd);
454 /* Mark block bad in BBT */
455 if (chip->bbt) {
456 res = nand_markbad_bbt(mtd, ofs);
457 if (!ret)
458 ret = res;
461 if (!ret)
462 mtd->ecc_stats.badblocks++;
464 return ret;
468 * nand_check_wp - [GENERIC] check if the chip is write protected
469 * @mtd: MTD device structure
471 * Check, if the device is write protected. The function expects, that the
472 * device is already selected.
474 static int nand_check_wp(struct mtd_info *mtd)
476 struct nand_chip *chip = mtd->priv;
478 /* Broken xD cards report WP despite being writable */
479 if (chip->options & NAND_BROKEN_XD)
480 return 0;
482 /* Check the WP bit */
483 chip->cmdfunc(mtd, NAND_CMD_STATUS, -1, -1);
484 return (chip->read_byte(mtd) & NAND_STATUS_WP) ? 0 : 1;
488 * nand_block_checkbad - [GENERIC] Check if a block is marked bad
489 * @mtd: MTD device structure
490 * @ofs: offset from device start
491 * @getchip: 0, if the chip is already selected
492 * @allowbbt: 1, if its allowed to access the bbt area
494 * Check, if the block is bad. Either by reading the bad block table or
495 * calling of the scan function.
497 static int nand_block_checkbad(struct mtd_info *mtd, loff_t ofs, int getchip,
498 int allowbbt)
500 struct nand_chip *chip = mtd->priv;
502 if (!chip->bbt)
503 return chip->block_bad(mtd, ofs, getchip);
505 /* Return info from the table */
506 return nand_isbad_bbt(mtd, ofs, allowbbt);
510 * panic_nand_wait_ready - [GENERIC] Wait for the ready pin after commands.
511 * @mtd: MTD device structure
512 * @timeo: Timeout
514 * Helper function for nand_wait_ready used when needing to wait in interrupt
515 * context.
517 static void panic_nand_wait_ready(struct mtd_info *mtd, unsigned long timeo)
519 struct nand_chip *chip = mtd->priv;
520 int i;
522 /* Wait for the device to get ready */
523 for (i = 0; i < timeo; i++) {
524 if (chip->dev_ready(mtd))
525 break;
526 touch_softlockup_watchdog();
527 mdelay(1);
531 /* Wait for the ready pin, after a command. The timeout is caught later. */
532 void nand_wait_ready(struct mtd_info *mtd)
534 struct nand_chip *chip = mtd->priv;
535 unsigned long timeo = jiffies + msecs_to_jiffies(20);
537 /* 400ms timeout */
538 if (in_interrupt() || oops_in_progress)
539 return panic_nand_wait_ready(mtd, 400);
541 led_trigger_event(nand_led_trigger, LED_FULL);
542 /* Wait until command is processed or timeout occurs */
543 do {
544 if (chip->dev_ready(mtd))
545 break;
546 touch_softlockup_watchdog();
547 } while (time_before(jiffies, timeo));
548 led_trigger_event(nand_led_trigger, LED_OFF);
550 EXPORT_SYMBOL_GPL(nand_wait_ready);
553 * nand_command - [DEFAULT] Send command to NAND device
554 * @mtd: MTD device structure
555 * @command: the command to be sent
556 * @column: the column address for this command, -1 if none
557 * @page_addr: the page address for this command, -1 if none
559 * Send command to NAND device. This function is used for small page devices
560 * (512 Bytes per page).
562 static void nand_command(struct mtd_info *mtd, unsigned int command,
563 int column, int page_addr)
565 register struct nand_chip *chip = mtd->priv;
566 int ctrl = NAND_CTRL_CLE | NAND_CTRL_CHANGE;
568 /* Write out the command to the device */
569 if (command == NAND_CMD_SEQIN) {
570 int readcmd;
572 if (column >= mtd->writesize) {
573 /* OOB area */
574 column -= mtd->writesize;
575 readcmd = NAND_CMD_READOOB;
576 } else if (column < 256) {
577 /* First 256 bytes --> READ0 */
578 readcmd = NAND_CMD_READ0;
579 } else {
580 column -= 256;
581 readcmd = NAND_CMD_READ1;
583 chip->cmd_ctrl(mtd, readcmd, ctrl);
584 ctrl &= ~NAND_CTRL_CHANGE;
586 chip->cmd_ctrl(mtd, command, ctrl);
588 /* Address cycle, when necessary */
589 ctrl = NAND_CTRL_ALE | NAND_CTRL_CHANGE;
590 /* Serially input address */
591 if (column != -1) {
592 /* Adjust columns for 16 bit buswidth */
593 if (chip->options & NAND_BUSWIDTH_16 &&
594 !nand_opcode_8bits(command))
595 column >>= 1;
596 chip->cmd_ctrl(mtd, column, ctrl);
597 ctrl &= ~NAND_CTRL_CHANGE;
599 if (page_addr != -1) {
600 chip->cmd_ctrl(mtd, page_addr, ctrl);
601 ctrl &= ~NAND_CTRL_CHANGE;
602 chip->cmd_ctrl(mtd, page_addr >> 8, ctrl);
603 /* One more address cycle for devices > 32MiB */
604 if (chip->chipsize > (32 << 20))
605 chip->cmd_ctrl(mtd, page_addr >> 16, ctrl);
607 chip->cmd_ctrl(mtd, NAND_CMD_NONE, NAND_NCE | NAND_CTRL_CHANGE);
610 * Program and erase have their own busy handlers status and sequential
611 * in needs no delay
613 switch (command) {
615 case NAND_CMD_PAGEPROG:
616 case NAND_CMD_ERASE1:
617 case NAND_CMD_ERASE2:
618 case NAND_CMD_SEQIN:
619 case NAND_CMD_STATUS:
620 return;
622 case NAND_CMD_RESET:
623 if (chip->dev_ready)
624 break;
625 udelay(chip->chip_delay);
626 chip->cmd_ctrl(mtd, NAND_CMD_STATUS,
627 NAND_CTRL_CLE | NAND_CTRL_CHANGE);
628 chip->cmd_ctrl(mtd,
629 NAND_CMD_NONE, NAND_NCE | NAND_CTRL_CHANGE);
630 while (!(chip->read_byte(mtd) & NAND_STATUS_READY))
632 return;
634 /* This applies to read commands */
635 default:
637 * If we don't have access to the busy pin, we apply the given
638 * command delay
640 if (!chip->dev_ready) {
641 udelay(chip->chip_delay);
642 return;
646 * Apply this short delay always to ensure that we do wait tWB in
647 * any case on any machine.
649 ndelay(100);
651 nand_wait_ready(mtd);
655 * nand_command_lp - [DEFAULT] Send command to NAND large page device
656 * @mtd: MTD device structure
657 * @command: the command to be sent
658 * @column: the column address for this command, -1 if none
659 * @page_addr: the page address for this command, -1 if none
661 * Send command to NAND device. This is the version for the new large page
662 * devices. We don't have the separate regions as we have in the small page
663 * devices. We must emulate NAND_CMD_READOOB to keep the code compatible.
665 static void nand_command_lp(struct mtd_info *mtd, unsigned int command,
666 int column, int page_addr)
668 register struct nand_chip *chip = mtd->priv;
670 /* Emulate NAND_CMD_READOOB */
671 if (command == NAND_CMD_READOOB) {
672 column += mtd->writesize;
673 command = NAND_CMD_READ0;
676 /* Command latch cycle */
677 chip->cmd_ctrl(mtd, command, NAND_NCE | NAND_CLE | NAND_CTRL_CHANGE);
679 if (column != -1 || page_addr != -1) {
680 int ctrl = NAND_CTRL_CHANGE | NAND_NCE | NAND_ALE;
682 /* Serially input address */
683 if (column != -1) {
684 /* Adjust columns for 16 bit buswidth */
685 if (chip->options & NAND_BUSWIDTH_16 &&
686 !nand_opcode_8bits(command))
687 column >>= 1;
688 chip->cmd_ctrl(mtd, column, ctrl);
689 ctrl &= ~NAND_CTRL_CHANGE;
690 chip->cmd_ctrl(mtd, column >> 8, ctrl);
692 if (page_addr != -1) {
693 chip->cmd_ctrl(mtd, page_addr, ctrl);
694 chip->cmd_ctrl(mtd, page_addr >> 8,
695 NAND_NCE | NAND_ALE);
696 /* One more address cycle for devices > 128MiB */
697 if (chip->chipsize > (128 << 20))
698 chip->cmd_ctrl(mtd, page_addr >> 16,
699 NAND_NCE | NAND_ALE);
702 chip->cmd_ctrl(mtd, NAND_CMD_NONE, NAND_NCE | NAND_CTRL_CHANGE);
705 * Program and erase have their own busy handlers status, sequential
706 * in, and deplete1 need no delay.
708 switch (command) {
710 case NAND_CMD_CACHEDPROG:
711 case NAND_CMD_PAGEPROG:
712 case NAND_CMD_ERASE1:
713 case NAND_CMD_ERASE2:
714 case NAND_CMD_SEQIN:
715 case NAND_CMD_RNDIN:
716 case NAND_CMD_STATUS:
717 return;
719 case NAND_CMD_RESET:
720 if (chip->dev_ready)
721 break;
722 udelay(chip->chip_delay);
723 chip->cmd_ctrl(mtd, NAND_CMD_STATUS,
724 NAND_NCE | NAND_CLE | NAND_CTRL_CHANGE);
725 chip->cmd_ctrl(mtd, NAND_CMD_NONE,
726 NAND_NCE | NAND_CTRL_CHANGE);
727 while (!(chip->read_byte(mtd) & NAND_STATUS_READY))
729 return;
731 case NAND_CMD_RNDOUT:
732 /* No ready / busy check necessary */
733 chip->cmd_ctrl(mtd, NAND_CMD_RNDOUTSTART,
734 NAND_NCE | NAND_CLE | NAND_CTRL_CHANGE);
735 chip->cmd_ctrl(mtd, NAND_CMD_NONE,
736 NAND_NCE | NAND_CTRL_CHANGE);
737 return;
739 case NAND_CMD_READ0:
740 chip->cmd_ctrl(mtd, NAND_CMD_READSTART,
741 NAND_NCE | NAND_CLE | NAND_CTRL_CHANGE);
742 chip->cmd_ctrl(mtd, NAND_CMD_NONE,
743 NAND_NCE | NAND_CTRL_CHANGE);
745 /* This applies to read commands */
746 default:
748 * If we don't have access to the busy pin, we apply the given
749 * command delay.
751 if (!chip->dev_ready) {
752 udelay(chip->chip_delay);
753 return;
758 * Apply this short delay always to ensure that we do wait tWB in
759 * any case on any machine.
761 ndelay(100);
763 nand_wait_ready(mtd);
767 * panic_nand_get_device - [GENERIC] Get chip for selected access
768 * @chip: the nand chip descriptor
769 * @mtd: MTD device structure
770 * @new_state: the state which is requested
772 * Used when in panic, no locks are taken.
774 static void panic_nand_get_device(struct nand_chip *chip,
775 struct mtd_info *mtd, int new_state)
777 /* Hardware controller shared among independent devices */
778 chip->controller->active = chip;
779 chip->state = new_state;
783 * nand_get_device - [GENERIC] Get chip for selected access
784 * @mtd: MTD device structure
785 * @new_state: the state which is requested
787 * Get the device and lock it for exclusive access
789 static int
790 nand_get_device(struct mtd_info *mtd, int new_state)
792 struct nand_chip *chip = mtd->priv;
793 spinlock_t *lock = &chip->controller->lock;
794 wait_queue_head_t *wq = &chip->controller->wq;
795 DECLARE_WAITQUEUE(wait, current);
796 retry:
797 spin_lock(lock);
799 /* Hardware controller shared among independent devices */
800 if (!chip->controller->active)
801 chip->controller->active = chip;
803 if (chip->controller->active == chip && chip->state == FL_READY) {
804 chip->state = new_state;
805 spin_unlock(lock);
806 return 0;
808 if (new_state == FL_PM_SUSPENDED) {
809 if (chip->controller->active->state == FL_PM_SUSPENDED) {
810 chip->state = FL_PM_SUSPENDED;
811 spin_unlock(lock);
812 return 0;
815 set_current_state(TASK_UNINTERRUPTIBLE);
816 add_wait_queue(wq, &wait);
817 spin_unlock(lock);
818 schedule();
819 remove_wait_queue(wq, &wait);
820 goto retry;
824 * panic_nand_wait - [GENERIC] wait until the command is done
825 * @mtd: MTD device structure
826 * @chip: NAND chip structure
827 * @timeo: timeout
829 * Wait for command done. This is a helper function for nand_wait used when
830 * we are in interrupt context. May happen when in panic and trying to write
831 * an oops through mtdoops.
833 static void panic_nand_wait(struct mtd_info *mtd, struct nand_chip *chip,
834 unsigned long timeo)
836 int i;
837 for (i = 0; i < timeo; i++) {
838 if (chip->dev_ready) {
839 if (chip->dev_ready(mtd))
840 break;
841 } else {
842 if (chip->read_byte(mtd) & NAND_STATUS_READY)
843 break;
845 mdelay(1);
850 * nand_wait - [DEFAULT] wait until the command is done
851 * @mtd: MTD device structure
852 * @chip: NAND chip structure
854 * Wait for command done. This applies to erase and program only. Erase can
855 * take up to 400ms and program up to 20ms according to general NAND and
856 * SmartMedia specs.
858 static int nand_wait(struct mtd_info *mtd, struct nand_chip *chip)
861 int status, state = chip->state;
862 unsigned long timeo = (state == FL_ERASING ? 400 : 20);
864 led_trigger_event(nand_led_trigger, LED_FULL);
867 * Apply this short delay always to ensure that we do wait tWB in any
868 * case on any machine.
870 ndelay(100);
872 chip->cmdfunc(mtd, NAND_CMD_STATUS, -1, -1);
874 if (in_interrupt() || oops_in_progress)
875 panic_nand_wait(mtd, chip, timeo);
876 else {
877 timeo = jiffies + msecs_to_jiffies(timeo);
878 while (time_before(jiffies, timeo)) {
879 if (chip->dev_ready) {
880 if (chip->dev_ready(mtd))
881 break;
882 } else {
883 if (chip->read_byte(mtd) & NAND_STATUS_READY)
884 break;
886 cond_resched();
889 led_trigger_event(nand_led_trigger, LED_OFF);
891 status = (int)chip->read_byte(mtd);
892 /* This can happen if in case of timeout or buggy dev_ready */
893 WARN_ON(!(status & NAND_STATUS_READY));
894 return status;
898 * __nand_unlock - [REPLACEABLE] unlocks specified locked blocks
899 * @mtd: mtd info
900 * @ofs: offset to start unlock from
901 * @len: length to unlock
902 * @invert: when = 0, unlock the range of blocks within the lower and
903 * upper boundary address
904 * when = 1, unlock the range of blocks outside the boundaries
905 * of the lower and upper boundary address
907 * Returs unlock status.
909 static int __nand_unlock(struct mtd_info *mtd, loff_t ofs,
910 uint64_t len, int invert)
912 int ret = 0;
913 int status, page;
914 struct nand_chip *chip = mtd->priv;
916 /* Submit address of first page to unlock */
917 page = ofs >> chip->page_shift;
918 chip->cmdfunc(mtd, NAND_CMD_UNLOCK1, -1, page & chip->pagemask);
920 /* Submit address of last page to unlock */
921 page = (ofs + len) >> chip->page_shift;
922 chip->cmdfunc(mtd, NAND_CMD_UNLOCK2, -1,
923 (page | invert) & chip->pagemask);
925 /* Call wait ready function */
926 status = chip->waitfunc(mtd, chip);
927 /* See if device thinks it succeeded */
928 if (status & NAND_STATUS_FAIL) {
929 pr_debug("%s: error status = 0x%08x\n",
930 __func__, status);
931 ret = -EIO;
934 return ret;
938 * nand_unlock - [REPLACEABLE] unlocks specified locked blocks
939 * @mtd: mtd info
940 * @ofs: offset to start unlock from
941 * @len: length to unlock
943 * Returns unlock status.
945 int nand_unlock(struct mtd_info *mtd, loff_t ofs, uint64_t len)
947 int ret = 0;
948 int chipnr;
949 struct nand_chip *chip = mtd->priv;
951 pr_debug("%s: start = 0x%012llx, len = %llu\n",
952 __func__, (unsigned long long)ofs, len);
954 if (check_offs_len(mtd, ofs, len))
955 ret = -EINVAL;
957 /* Align to last block address if size addresses end of the device */
958 if (ofs + len == mtd->size)
959 len -= mtd->erasesize;
961 nand_get_device(mtd, FL_UNLOCKING);
963 /* Shift to get chip number */
964 chipnr = ofs >> chip->chip_shift;
966 chip->select_chip(mtd, chipnr);
968 /* Check, if it is write protected */
969 if (nand_check_wp(mtd)) {
970 pr_debug("%s: device is write protected!\n",
971 __func__);
972 ret = -EIO;
973 goto out;
976 ret = __nand_unlock(mtd, ofs, len, 0);
978 out:
979 chip->select_chip(mtd, -1);
980 nand_release_device(mtd);
982 return ret;
984 EXPORT_SYMBOL(nand_unlock);
987 * nand_lock - [REPLACEABLE] locks all blocks present in the device
988 * @mtd: mtd info
989 * @ofs: offset to start unlock from
990 * @len: length to unlock
992 * This feature is not supported in many NAND parts. 'Micron' NAND parts do
993 * have this feature, but it allows only to lock all blocks, not for specified
994 * range for block. Implementing 'lock' feature by making use of 'unlock', for
995 * now.
997 * Returns lock status.
999 int nand_lock(struct mtd_info *mtd, loff_t ofs, uint64_t len)
1001 int ret = 0;
1002 int chipnr, status, page;
1003 struct nand_chip *chip = mtd->priv;
1005 pr_debug("%s: start = 0x%012llx, len = %llu\n",
1006 __func__, (unsigned long long)ofs, len);
1008 if (check_offs_len(mtd, ofs, len))
1009 ret = -EINVAL;
1011 nand_get_device(mtd, FL_LOCKING);
1013 /* Shift to get chip number */
1014 chipnr = ofs >> chip->chip_shift;
1016 chip->select_chip(mtd, chipnr);
1018 /* Check, if it is write protected */
1019 if (nand_check_wp(mtd)) {
1020 pr_debug("%s: device is write protected!\n",
1021 __func__);
1022 status = MTD_ERASE_FAILED;
1023 ret = -EIO;
1024 goto out;
1027 /* Submit address of first page to lock */
1028 page = ofs >> chip->page_shift;
1029 chip->cmdfunc(mtd, NAND_CMD_LOCK, -1, page & chip->pagemask);
1031 /* Call wait ready function */
1032 status = chip->waitfunc(mtd, chip);
1033 /* See if device thinks it succeeded */
1034 if (status & NAND_STATUS_FAIL) {
1035 pr_debug("%s: error status = 0x%08x\n",
1036 __func__, status);
1037 ret = -EIO;
1038 goto out;
1041 ret = __nand_unlock(mtd, ofs, len, 0x1);
1043 out:
1044 chip->select_chip(mtd, -1);
1045 nand_release_device(mtd);
1047 return ret;
1049 EXPORT_SYMBOL(nand_lock);
1052 * nand_read_page_raw - [INTERN] read raw page data without ecc
1053 * @mtd: mtd info structure
1054 * @chip: nand chip info structure
1055 * @buf: buffer to store read data
1056 * @oob_required: caller requires OOB data read to chip->oob_poi
1057 * @page: page number to read
1059 * Not for syndrome calculating ECC controllers, which use a special oob layout.
1061 static int nand_read_page_raw(struct mtd_info *mtd, struct nand_chip *chip,
1062 uint8_t *buf, int oob_required, int page)
1064 chip->read_buf(mtd, buf, mtd->writesize);
1065 if (oob_required)
1066 chip->read_buf(mtd, chip->oob_poi, mtd->oobsize);
1067 return 0;
1071 * nand_read_page_raw_syndrome - [INTERN] read raw page data without ecc
1072 * @mtd: mtd info structure
1073 * @chip: nand chip info structure
1074 * @buf: buffer to store read data
1075 * @oob_required: caller requires OOB data read to chip->oob_poi
1076 * @page: page number to read
1078 * We need a special oob layout and handling even when OOB isn't used.
1080 static int nand_read_page_raw_syndrome(struct mtd_info *mtd,
1081 struct nand_chip *chip, uint8_t *buf,
1082 int oob_required, int page)
1084 int eccsize = chip->ecc.size;
1085 int eccbytes = chip->ecc.bytes;
1086 uint8_t *oob = chip->oob_poi;
1087 int steps, size;
1089 for (steps = chip->ecc.steps; steps > 0; steps--) {
1090 chip->read_buf(mtd, buf, eccsize);
1091 buf += eccsize;
1093 if (chip->ecc.prepad) {
1094 chip->read_buf(mtd, oob, chip->ecc.prepad);
1095 oob += chip->ecc.prepad;
1098 chip->read_buf(mtd, oob, eccbytes);
1099 oob += eccbytes;
1101 if (chip->ecc.postpad) {
1102 chip->read_buf(mtd, oob, chip->ecc.postpad);
1103 oob += chip->ecc.postpad;
1107 size = mtd->oobsize - (oob - chip->oob_poi);
1108 if (size)
1109 chip->read_buf(mtd, oob, size);
1111 return 0;
1115 * nand_read_page_swecc - [REPLACEABLE] software ECC based page read function
1116 * @mtd: mtd info structure
1117 * @chip: nand chip info structure
1118 * @buf: buffer to store read data
1119 * @oob_required: caller requires OOB data read to chip->oob_poi
1120 * @page: page number to read
1122 static int nand_read_page_swecc(struct mtd_info *mtd, struct nand_chip *chip,
1123 uint8_t *buf, int oob_required, int page)
1125 int i, eccsize = chip->ecc.size;
1126 int eccbytes = chip->ecc.bytes;
1127 int eccsteps = chip->ecc.steps;
1128 uint8_t *p = buf;
1129 uint8_t *ecc_calc = chip->buffers->ecccalc;
1130 uint8_t *ecc_code = chip->buffers->ecccode;
1131 uint32_t *eccpos = chip->ecc.layout->eccpos;
1132 unsigned int max_bitflips = 0;
1134 chip->ecc.read_page_raw(mtd, chip, buf, 1, page);
1136 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize)
1137 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
1139 for (i = 0; i < chip->ecc.total; i++)
1140 ecc_code[i] = chip->oob_poi[eccpos[i]];
1142 eccsteps = chip->ecc.steps;
1143 p = buf;
1145 for (i = 0 ; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
1146 int stat;
1148 stat = chip->ecc.correct(mtd, p, &ecc_code[i], &ecc_calc[i]);
1149 if (stat < 0) {
1150 mtd->ecc_stats.failed++;
1151 } else {
1152 mtd->ecc_stats.corrected += stat;
1153 max_bitflips = max_t(unsigned int, max_bitflips, stat);
1156 return max_bitflips;
1160 * nand_read_subpage - [REPLACEABLE] ECC based sub-page read function
1161 * @mtd: mtd info structure
1162 * @chip: nand chip info structure
1163 * @data_offs: offset of requested data within the page
1164 * @readlen: data length
1165 * @bufpoi: buffer to store read data
1166 * @page: page number to read
1168 static int nand_read_subpage(struct mtd_info *mtd, struct nand_chip *chip,
1169 uint32_t data_offs, uint32_t readlen, uint8_t *bufpoi,
1170 int page)
1172 int start_step, end_step, num_steps;
1173 uint32_t *eccpos = chip->ecc.layout->eccpos;
1174 uint8_t *p;
1175 int data_col_addr, i, gaps = 0;
1176 int datafrag_len, eccfrag_len, aligned_len, aligned_pos;
1177 int busw = (chip->options & NAND_BUSWIDTH_16) ? 2 : 1;
1178 int index;
1179 unsigned int max_bitflips = 0;
1181 /* Column address within the page aligned to ECC size (256bytes) */
1182 start_step = data_offs / chip->ecc.size;
1183 end_step = (data_offs + readlen - 1) / chip->ecc.size;
1184 num_steps = end_step - start_step + 1;
1185 index = start_step * chip->ecc.bytes;
1187 /* Data size aligned to ECC ecc.size */
1188 datafrag_len = num_steps * chip->ecc.size;
1189 eccfrag_len = num_steps * chip->ecc.bytes;
1191 data_col_addr = start_step * chip->ecc.size;
1192 /* If we read not a page aligned data */
1193 if (data_col_addr != 0)
1194 chip->cmdfunc(mtd, NAND_CMD_RNDOUT, data_col_addr, -1);
1196 p = bufpoi + data_col_addr;
1197 chip->read_buf(mtd, p, datafrag_len);
1199 /* Calculate ECC */
1200 for (i = 0; i < eccfrag_len ; i += chip->ecc.bytes, p += chip->ecc.size)
1201 chip->ecc.calculate(mtd, p, &chip->buffers->ecccalc[i]);
1204 * The performance is faster if we position offsets according to
1205 * ecc.pos. Let's make sure that there are no gaps in ECC positions.
1207 for (i = 0; i < eccfrag_len - 1; i++) {
1208 if (eccpos[i + index] + 1 != eccpos[i + index + 1]) {
1209 gaps = 1;
1210 break;
1213 if (gaps) {
1214 chip->cmdfunc(mtd, NAND_CMD_RNDOUT, mtd->writesize, -1);
1215 chip->read_buf(mtd, chip->oob_poi, mtd->oobsize);
1216 } else {
1218 * Send the command to read the particular ECC bytes take care
1219 * about buswidth alignment in read_buf.
1221 aligned_pos = eccpos[index] & ~(busw - 1);
1222 aligned_len = eccfrag_len;
1223 if (eccpos[index] & (busw - 1))
1224 aligned_len++;
1225 if (eccpos[index + (num_steps * chip->ecc.bytes)] & (busw - 1))
1226 aligned_len++;
1228 chip->cmdfunc(mtd, NAND_CMD_RNDOUT,
1229 mtd->writesize + aligned_pos, -1);
1230 chip->read_buf(mtd, &chip->oob_poi[aligned_pos], aligned_len);
1233 for (i = 0; i < eccfrag_len; i++)
1234 chip->buffers->ecccode[i] = chip->oob_poi[eccpos[i + index]];
1236 p = bufpoi + data_col_addr;
1237 for (i = 0; i < eccfrag_len ; i += chip->ecc.bytes, p += chip->ecc.size) {
1238 int stat;
1240 stat = chip->ecc.correct(mtd, p,
1241 &chip->buffers->ecccode[i], &chip->buffers->ecccalc[i]);
1242 if (stat < 0) {
1243 mtd->ecc_stats.failed++;
1244 } else {
1245 mtd->ecc_stats.corrected += stat;
1246 max_bitflips = max_t(unsigned int, max_bitflips, stat);
1249 return max_bitflips;
1253 * nand_read_page_hwecc - [REPLACEABLE] hardware ECC based page read function
1254 * @mtd: mtd info structure
1255 * @chip: nand chip info structure
1256 * @buf: buffer to store read data
1257 * @oob_required: caller requires OOB data read to chip->oob_poi
1258 * @page: page number to read
1260 * Not for syndrome calculating ECC controllers which need a special oob layout.
1262 static int nand_read_page_hwecc(struct mtd_info *mtd, struct nand_chip *chip,
1263 uint8_t *buf, int oob_required, int page)
1265 int i, eccsize = chip->ecc.size;
1266 int eccbytes = chip->ecc.bytes;
1267 int eccsteps = chip->ecc.steps;
1268 uint8_t *p = buf;
1269 uint8_t *ecc_calc = chip->buffers->ecccalc;
1270 uint8_t *ecc_code = chip->buffers->ecccode;
1271 uint32_t *eccpos = chip->ecc.layout->eccpos;
1272 unsigned int max_bitflips = 0;
1274 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
1275 chip->ecc.hwctl(mtd, NAND_ECC_READ);
1276 chip->read_buf(mtd, p, eccsize);
1277 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
1279 chip->read_buf(mtd, chip->oob_poi, mtd->oobsize);
1281 for (i = 0; i < chip->ecc.total; i++)
1282 ecc_code[i] = chip->oob_poi[eccpos[i]];
1284 eccsteps = chip->ecc.steps;
1285 p = buf;
1287 for (i = 0 ; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
1288 int stat;
1290 stat = chip->ecc.correct(mtd, p, &ecc_code[i], &ecc_calc[i]);
1291 if (stat < 0) {
1292 mtd->ecc_stats.failed++;
1293 } else {
1294 mtd->ecc_stats.corrected += stat;
1295 max_bitflips = max_t(unsigned int, max_bitflips, stat);
1298 return max_bitflips;
1302 * nand_read_page_hwecc_oob_first - [REPLACEABLE] hw ecc, read oob first
1303 * @mtd: mtd info structure
1304 * @chip: nand chip info structure
1305 * @buf: buffer to store read data
1306 * @oob_required: caller requires OOB data read to chip->oob_poi
1307 * @page: page number to read
1309 * Hardware ECC for large page chips, require OOB to be read first. For this
1310 * ECC mode, the write_page method is re-used from ECC_HW. These methods
1311 * read/write ECC from the OOB area, unlike the ECC_HW_SYNDROME support with
1312 * multiple ECC steps, follows the "infix ECC" scheme and reads/writes ECC from
1313 * the data area, by overwriting the NAND manufacturer bad block markings.
1315 static int nand_read_page_hwecc_oob_first(struct mtd_info *mtd,
1316 struct nand_chip *chip, uint8_t *buf, int oob_required, int page)
1318 int i, eccsize = chip->ecc.size;
1319 int eccbytes = chip->ecc.bytes;
1320 int eccsteps = chip->ecc.steps;
1321 uint8_t *p = buf;
1322 uint8_t *ecc_code = chip->buffers->ecccode;
1323 uint32_t *eccpos = chip->ecc.layout->eccpos;
1324 uint8_t *ecc_calc = chip->buffers->ecccalc;
1325 unsigned int max_bitflips = 0;
1327 /* Read the OOB area first */
1328 chip->cmdfunc(mtd, NAND_CMD_READOOB, 0, page);
1329 chip->read_buf(mtd, chip->oob_poi, mtd->oobsize);
1330 chip->cmdfunc(mtd, NAND_CMD_READ0, 0, page);
1332 for (i = 0; i < chip->ecc.total; i++)
1333 ecc_code[i] = chip->oob_poi[eccpos[i]];
1335 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
1336 int stat;
1338 chip->ecc.hwctl(mtd, NAND_ECC_READ);
1339 chip->read_buf(mtd, p, eccsize);
1340 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
1342 stat = chip->ecc.correct(mtd, p, &ecc_code[i], NULL);
1343 if (stat < 0) {
1344 mtd->ecc_stats.failed++;
1345 } else {
1346 mtd->ecc_stats.corrected += stat;
1347 max_bitflips = max_t(unsigned int, max_bitflips, stat);
1350 return max_bitflips;
1354 * nand_read_page_syndrome - [REPLACEABLE] hardware ECC syndrome based page read
1355 * @mtd: mtd info structure
1356 * @chip: nand chip info structure
1357 * @buf: buffer to store read data
1358 * @oob_required: caller requires OOB data read to chip->oob_poi
1359 * @page: page number to read
1361 * The hw generator calculates the error syndrome automatically. Therefore we
1362 * need a special oob layout and handling.
1364 static int nand_read_page_syndrome(struct mtd_info *mtd, struct nand_chip *chip,
1365 uint8_t *buf, int oob_required, int page)
1367 int i, eccsize = chip->ecc.size;
1368 int eccbytes = chip->ecc.bytes;
1369 int eccsteps = chip->ecc.steps;
1370 uint8_t *p = buf;
1371 uint8_t *oob = chip->oob_poi;
1372 unsigned int max_bitflips = 0;
1374 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
1375 int stat;
1377 chip->ecc.hwctl(mtd, NAND_ECC_READ);
1378 chip->read_buf(mtd, p, eccsize);
1380 if (chip->ecc.prepad) {
1381 chip->read_buf(mtd, oob, chip->ecc.prepad);
1382 oob += chip->ecc.prepad;
1385 chip->ecc.hwctl(mtd, NAND_ECC_READSYN);
1386 chip->read_buf(mtd, oob, eccbytes);
1387 stat = chip->ecc.correct(mtd, p, oob, NULL);
1389 if (stat < 0) {
1390 mtd->ecc_stats.failed++;
1391 } else {
1392 mtd->ecc_stats.corrected += stat;
1393 max_bitflips = max_t(unsigned int, max_bitflips, stat);
1396 oob += eccbytes;
1398 if (chip->ecc.postpad) {
1399 chip->read_buf(mtd, oob, chip->ecc.postpad);
1400 oob += chip->ecc.postpad;
1404 /* Calculate remaining oob bytes */
1405 i = mtd->oobsize - (oob - chip->oob_poi);
1406 if (i)
1407 chip->read_buf(mtd, oob, i);
1409 return max_bitflips;
1413 * nand_transfer_oob - [INTERN] Transfer oob to client buffer
1414 * @chip: nand chip structure
1415 * @oob: oob destination address
1416 * @ops: oob ops structure
1417 * @len: size of oob to transfer
1419 static uint8_t *nand_transfer_oob(struct nand_chip *chip, uint8_t *oob,
1420 struct mtd_oob_ops *ops, size_t len)
1422 switch (ops->mode) {
1424 case MTD_OPS_PLACE_OOB:
1425 case MTD_OPS_RAW:
1426 memcpy(oob, chip->oob_poi + ops->ooboffs, len);
1427 return oob + len;
1429 case MTD_OPS_AUTO_OOB: {
1430 struct nand_oobfree *free = chip->ecc.layout->oobfree;
1431 uint32_t boffs = 0, roffs = ops->ooboffs;
1432 size_t bytes = 0;
1434 for (; free->length && len; free++, len -= bytes) {
1435 /* Read request not from offset 0? */
1436 if (unlikely(roffs)) {
1437 if (roffs >= free->length) {
1438 roffs -= free->length;
1439 continue;
1441 boffs = free->offset + roffs;
1442 bytes = min_t(size_t, len,
1443 (free->length - roffs));
1444 roffs = 0;
1445 } else {
1446 bytes = min_t(size_t, len, free->length);
1447 boffs = free->offset;
1449 memcpy(oob, chip->oob_poi + boffs, bytes);
1450 oob += bytes;
1452 return oob;
1454 default:
1455 BUG();
1457 return NULL;
1461 * nand_setup_read_retry - [INTERN] Set the READ RETRY mode
1462 * @mtd: MTD device structure
1463 * @retry_mode: the retry mode to use
1465 * Some vendors supply a special command to shift the Vt threshold, to be used
1466 * when there are too many bitflips in a page (i.e., ECC error). After setting
1467 * a new threshold, the host should retry reading the page.
1469 static int nand_setup_read_retry(struct mtd_info *mtd, int retry_mode)
1471 struct nand_chip *chip = mtd->priv;
1473 pr_debug("setting READ RETRY mode %d\n", retry_mode);
1475 if (retry_mode >= chip->read_retries)
1476 return -EINVAL;
1478 if (!chip->setup_read_retry)
1479 return -EOPNOTSUPP;
1481 return chip->setup_read_retry(mtd, retry_mode);
1485 * nand_do_read_ops - [INTERN] Read data with ECC
1486 * @mtd: MTD device structure
1487 * @from: offset to read from
1488 * @ops: oob ops structure
1490 * Internal function. Called with chip held.
1492 static int nand_do_read_ops(struct mtd_info *mtd, loff_t from,
1493 struct mtd_oob_ops *ops)
1495 int chipnr, page, realpage, col, bytes, aligned, oob_required;
1496 struct nand_chip *chip = mtd->priv;
1497 int ret = 0;
1498 uint32_t readlen = ops->len;
1499 uint32_t oobreadlen = ops->ooblen;
1500 uint32_t max_oobsize = ops->mode == MTD_OPS_AUTO_OOB ?
1501 mtd->oobavail : mtd->oobsize;
1503 uint8_t *bufpoi, *oob, *buf;
1504 int use_bufpoi;
1505 unsigned int max_bitflips = 0;
1506 int retry_mode = 0;
1507 bool ecc_fail = false;
1509 chipnr = (int)(from >> chip->chip_shift);
1510 chip->select_chip(mtd, chipnr);
1512 realpage = (int)(from >> chip->page_shift);
1513 page = realpage & chip->pagemask;
1515 col = (int)(from & (mtd->writesize - 1));
1517 buf = ops->datbuf;
1518 oob = ops->oobbuf;
1519 oob_required = oob ? 1 : 0;
1521 while (1) {
1522 unsigned int ecc_failures = mtd->ecc_stats.failed;
1524 bytes = min(mtd->writesize - col, readlen);
1525 aligned = (bytes == mtd->writesize);
1527 if (!aligned)
1528 use_bufpoi = 1;
1529 else if (chip->options & NAND_USE_BOUNCE_BUFFER)
1530 use_bufpoi = !virt_addr_valid(buf);
1531 else
1532 use_bufpoi = 0;
1534 /* Is the current page in the buffer? */
1535 if (realpage != chip->pagebuf || oob) {
1536 bufpoi = use_bufpoi ? chip->buffers->databuf : buf;
1538 if (use_bufpoi && aligned)
1539 pr_debug("%s: using read bounce buffer for buf@%p\n",
1540 __func__, buf);
1542 read_retry:
1543 chip->cmdfunc(mtd, NAND_CMD_READ0, 0x00, page);
1546 * Now read the page into the buffer. Absent an error,
1547 * the read methods return max bitflips per ecc step.
1549 if (unlikely(ops->mode == MTD_OPS_RAW))
1550 ret = chip->ecc.read_page_raw(mtd, chip, bufpoi,
1551 oob_required,
1552 page);
1553 else if (!aligned && NAND_HAS_SUBPAGE_READ(chip) &&
1554 !oob)
1555 ret = chip->ecc.read_subpage(mtd, chip,
1556 col, bytes, bufpoi,
1557 page);
1558 else
1559 ret = chip->ecc.read_page(mtd, chip, bufpoi,
1560 oob_required, page);
1561 if (ret < 0) {
1562 if (use_bufpoi)
1563 /* Invalidate page cache */
1564 chip->pagebuf = -1;
1565 break;
1568 max_bitflips = max_t(unsigned int, max_bitflips, ret);
1570 /* Transfer not aligned data */
1571 if (use_bufpoi) {
1572 if (!NAND_HAS_SUBPAGE_READ(chip) && !oob &&
1573 !(mtd->ecc_stats.failed - ecc_failures) &&
1574 (ops->mode != MTD_OPS_RAW)) {
1575 chip->pagebuf = realpage;
1576 chip->pagebuf_bitflips = ret;
1577 } else {
1578 /* Invalidate page cache */
1579 chip->pagebuf = -1;
1581 memcpy(buf, chip->buffers->databuf + col, bytes);
1584 if (unlikely(oob)) {
1585 int toread = min(oobreadlen, max_oobsize);
1587 if (toread) {
1588 oob = nand_transfer_oob(chip,
1589 oob, ops, toread);
1590 oobreadlen -= toread;
1594 if (chip->options & NAND_NEED_READRDY) {
1595 /* Apply delay or wait for ready/busy pin */
1596 if (!chip->dev_ready)
1597 udelay(chip->chip_delay);
1598 else
1599 nand_wait_ready(mtd);
1602 if (mtd->ecc_stats.failed - ecc_failures) {
1603 if (retry_mode + 1 < chip->read_retries) {
1604 retry_mode++;
1605 ret = nand_setup_read_retry(mtd,
1606 retry_mode);
1607 if (ret < 0)
1608 break;
1610 /* Reset failures; retry */
1611 mtd->ecc_stats.failed = ecc_failures;
1612 goto read_retry;
1613 } else {
1614 /* No more retry modes; real failure */
1615 ecc_fail = true;
1619 buf += bytes;
1620 } else {
1621 memcpy(buf, chip->buffers->databuf + col, bytes);
1622 buf += bytes;
1623 max_bitflips = max_t(unsigned int, max_bitflips,
1624 chip->pagebuf_bitflips);
1627 readlen -= bytes;
1629 /* Reset to retry mode 0 */
1630 if (retry_mode) {
1631 ret = nand_setup_read_retry(mtd, 0);
1632 if (ret < 0)
1633 break;
1634 retry_mode = 0;
1637 if (!readlen)
1638 break;
1640 /* For subsequent reads align to page boundary */
1641 col = 0;
1642 /* Increment page address */
1643 realpage++;
1645 page = realpage & chip->pagemask;
1646 /* Check, if we cross a chip boundary */
1647 if (!page) {
1648 chipnr++;
1649 chip->select_chip(mtd, -1);
1650 chip->select_chip(mtd, chipnr);
1653 chip->select_chip(mtd, -1);
1655 ops->retlen = ops->len - (size_t) readlen;
1656 if (oob)
1657 ops->oobretlen = ops->ooblen - oobreadlen;
1659 if (ret < 0)
1660 return ret;
1662 if (ecc_fail)
1663 return -EBADMSG;
1665 return max_bitflips;
1669 * nand_read - [MTD Interface] MTD compatibility function for nand_do_read_ecc
1670 * @mtd: MTD device structure
1671 * @from: offset to read from
1672 * @len: number of bytes to read
1673 * @retlen: pointer to variable to store the number of read bytes
1674 * @buf: the databuffer to put data
1676 * Get hold of the chip and call nand_do_read.
1678 static int nand_read(struct mtd_info *mtd, loff_t from, size_t len,
1679 size_t *retlen, uint8_t *buf)
1681 struct mtd_oob_ops ops;
1682 int ret;
1684 nand_get_device(mtd, FL_READING);
1685 ops.len = len;
1686 ops.datbuf = buf;
1687 ops.oobbuf = NULL;
1688 ops.mode = MTD_OPS_PLACE_OOB;
1689 ret = nand_do_read_ops(mtd, from, &ops);
1690 *retlen = ops.retlen;
1691 nand_release_device(mtd);
1692 return ret;
1696 * nand_read_oob_std - [REPLACEABLE] the most common OOB data read function
1697 * @mtd: mtd info structure
1698 * @chip: nand chip info structure
1699 * @page: page number to read
1701 static int nand_read_oob_std(struct mtd_info *mtd, struct nand_chip *chip,
1702 int page)
1704 chip->cmdfunc(mtd, NAND_CMD_READOOB, 0, page);
1705 chip->read_buf(mtd, chip->oob_poi, mtd->oobsize);
1706 return 0;
1710 * nand_read_oob_syndrome - [REPLACEABLE] OOB data read function for HW ECC
1711 * with syndromes
1712 * @mtd: mtd info structure
1713 * @chip: nand chip info structure
1714 * @page: page number to read
1716 static int nand_read_oob_syndrome(struct mtd_info *mtd, struct nand_chip *chip,
1717 int page)
1719 uint8_t *buf = chip->oob_poi;
1720 int length = mtd->oobsize;
1721 int chunk = chip->ecc.bytes + chip->ecc.prepad + chip->ecc.postpad;
1722 int eccsize = chip->ecc.size;
1723 uint8_t *bufpoi = buf;
1724 int i, toread, sndrnd = 0, pos;
1726 chip->cmdfunc(mtd, NAND_CMD_READ0, chip->ecc.size, page);
1727 for (i = 0; i < chip->ecc.steps; i++) {
1728 if (sndrnd) {
1729 pos = eccsize + i * (eccsize + chunk);
1730 if (mtd->writesize > 512)
1731 chip->cmdfunc(mtd, NAND_CMD_RNDOUT, pos, -1);
1732 else
1733 chip->cmdfunc(mtd, NAND_CMD_READ0, pos, page);
1734 } else
1735 sndrnd = 1;
1736 toread = min_t(int, length, chunk);
1737 chip->read_buf(mtd, bufpoi, toread);
1738 bufpoi += toread;
1739 length -= toread;
1741 if (length > 0)
1742 chip->read_buf(mtd, bufpoi, length);
1744 return 0;
1748 * nand_write_oob_std - [REPLACEABLE] the most common OOB data write function
1749 * @mtd: mtd info structure
1750 * @chip: nand chip info structure
1751 * @page: page number to write
1753 static int nand_write_oob_std(struct mtd_info *mtd, struct nand_chip *chip,
1754 int page)
1756 int status = 0;
1757 const uint8_t *buf = chip->oob_poi;
1758 int length = mtd->oobsize;
1760 chip->cmdfunc(mtd, NAND_CMD_SEQIN, mtd->writesize, page);
1761 chip->write_buf(mtd, buf, length);
1762 /* Send command to program the OOB data */
1763 chip->cmdfunc(mtd, NAND_CMD_PAGEPROG, -1, -1);
1765 status = chip->waitfunc(mtd, chip);
1767 return status & NAND_STATUS_FAIL ? -EIO : 0;
1771 * nand_write_oob_syndrome - [REPLACEABLE] OOB data write function for HW ECC
1772 * with syndrome - only for large page flash
1773 * @mtd: mtd info structure
1774 * @chip: nand chip info structure
1775 * @page: page number to write
1777 static int nand_write_oob_syndrome(struct mtd_info *mtd,
1778 struct nand_chip *chip, int page)
1780 int chunk = chip->ecc.bytes + chip->ecc.prepad + chip->ecc.postpad;
1781 int eccsize = chip->ecc.size, length = mtd->oobsize;
1782 int i, len, pos, status = 0, sndcmd = 0, steps = chip->ecc.steps;
1783 const uint8_t *bufpoi = chip->oob_poi;
1786 * data-ecc-data-ecc ... ecc-oob
1787 * or
1788 * data-pad-ecc-pad-data-pad .... ecc-pad-oob
1790 if (!chip->ecc.prepad && !chip->ecc.postpad) {
1791 pos = steps * (eccsize + chunk);
1792 steps = 0;
1793 } else
1794 pos = eccsize;
1796 chip->cmdfunc(mtd, NAND_CMD_SEQIN, pos, page);
1797 for (i = 0; i < steps; i++) {
1798 if (sndcmd) {
1799 if (mtd->writesize <= 512) {
1800 uint32_t fill = 0xFFFFFFFF;
1802 len = eccsize;
1803 while (len > 0) {
1804 int num = min_t(int, len, 4);
1805 chip->write_buf(mtd, (uint8_t *)&fill,
1806 num);
1807 len -= num;
1809 } else {
1810 pos = eccsize + i * (eccsize + chunk);
1811 chip->cmdfunc(mtd, NAND_CMD_RNDIN, pos, -1);
1813 } else
1814 sndcmd = 1;
1815 len = min_t(int, length, chunk);
1816 chip->write_buf(mtd, bufpoi, len);
1817 bufpoi += len;
1818 length -= len;
1820 if (length > 0)
1821 chip->write_buf(mtd, bufpoi, length);
1823 chip->cmdfunc(mtd, NAND_CMD_PAGEPROG, -1, -1);
1824 status = chip->waitfunc(mtd, chip);
1826 return status & NAND_STATUS_FAIL ? -EIO : 0;
1830 * nand_do_read_oob - [INTERN] NAND read out-of-band
1831 * @mtd: MTD device structure
1832 * @from: offset to read from
1833 * @ops: oob operations description structure
1835 * NAND read out-of-band data from the spare area.
1837 static int nand_do_read_oob(struct mtd_info *mtd, loff_t from,
1838 struct mtd_oob_ops *ops)
1840 int page, realpage, chipnr;
1841 struct nand_chip *chip = mtd->priv;
1842 struct mtd_ecc_stats stats;
1843 int readlen = ops->ooblen;
1844 int len;
1845 uint8_t *buf = ops->oobbuf;
1846 int ret = 0;
1848 pr_debug("%s: from = 0x%08Lx, len = %i\n",
1849 __func__, (unsigned long long)from, readlen);
1851 stats = mtd->ecc_stats;
1853 if (ops->mode == MTD_OPS_AUTO_OOB)
1854 len = chip->ecc.layout->oobavail;
1855 else
1856 len = mtd->oobsize;
1858 if (unlikely(ops->ooboffs >= len)) {
1859 pr_debug("%s: attempt to start read outside oob\n",
1860 __func__);
1861 return -EINVAL;
1864 /* Do not allow reads past end of device */
1865 if (unlikely(from >= mtd->size ||
1866 ops->ooboffs + readlen > ((mtd->size >> chip->page_shift) -
1867 (from >> chip->page_shift)) * len)) {
1868 pr_debug("%s: attempt to read beyond end of device\n",
1869 __func__);
1870 return -EINVAL;
1873 chipnr = (int)(from >> chip->chip_shift);
1874 chip->select_chip(mtd, chipnr);
1876 /* Shift to get page */
1877 realpage = (int)(from >> chip->page_shift);
1878 page = realpage & chip->pagemask;
1880 while (1) {
1881 if (ops->mode == MTD_OPS_RAW)
1882 ret = chip->ecc.read_oob_raw(mtd, chip, page);
1883 else
1884 ret = chip->ecc.read_oob(mtd, chip, page);
1886 if (ret < 0)
1887 break;
1889 len = min(len, readlen);
1890 buf = nand_transfer_oob(chip, buf, ops, len);
1892 if (chip->options & NAND_NEED_READRDY) {
1893 /* Apply delay or wait for ready/busy pin */
1894 if (!chip->dev_ready)
1895 udelay(chip->chip_delay);
1896 else
1897 nand_wait_ready(mtd);
1900 readlen -= len;
1901 if (!readlen)
1902 break;
1904 /* Increment page address */
1905 realpage++;
1907 page = realpage & chip->pagemask;
1908 /* Check, if we cross a chip boundary */
1909 if (!page) {
1910 chipnr++;
1911 chip->select_chip(mtd, -1);
1912 chip->select_chip(mtd, chipnr);
1915 chip->select_chip(mtd, -1);
1917 ops->oobretlen = ops->ooblen - readlen;
1919 if (ret < 0)
1920 return ret;
1922 if (mtd->ecc_stats.failed - stats.failed)
1923 return -EBADMSG;
1925 return mtd->ecc_stats.corrected - stats.corrected ? -EUCLEAN : 0;
1929 * nand_read_oob - [MTD Interface] NAND read data and/or out-of-band
1930 * @mtd: MTD device structure
1931 * @from: offset to read from
1932 * @ops: oob operation description structure
1934 * NAND read data and/or out-of-band data.
1936 static int nand_read_oob(struct mtd_info *mtd, loff_t from,
1937 struct mtd_oob_ops *ops)
1939 int ret = -ENOTSUPP;
1941 ops->retlen = 0;
1943 /* Do not allow reads past end of device */
1944 if (ops->datbuf && (from + ops->len) > mtd->size) {
1945 pr_debug("%s: attempt to read beyond end of device\n",
1946 __func__);
1947 return -EINVAL;
1950 nand_get_device(mtd, FL_READING);
1952 switch (ops->mode) {
1953 case MTD_OPS_PLACE_OOB:
1954 case MTD_OPS_AUTO_OOB:
1955 case MTD_OPS_RAW:
1956 break;
1958 default:
1959 goto out;
1962 if (!ops->datbuf)
1963 ret = nand_do_read_oob(mtd, from, ops);
1964 else
1965 ret = nand_do_read_ops(mtd, from, ops);
1967 out:
1968 nand_release_device(mtd);
1969 return ret;
1974 * nand_write_page_raw - [INTERN] raw page write function
1975 * @mtd: mtd info structure
1976 * @chip: nand chip info structure
1977 * @buf: data buffer
1978 * @oob_required: must write chip->oob_poi to OOB
1980 * Not for syndrome calculating ECC controllers, which use a special oob layout.
1982 static int nand_write_page_raw(struct mtd_info *mtd, struct nand_chip *chip,
1983 const uint8_t *buf, int oob_required)
1985 chip->write_buf(mtd, buf, mtd->writesize);
1986 if (oob_required)
1987 chip->write_buf(mtd, chip->oob_poi, mtd->oobsize);
1989 return 0;
1993 * nand_write_page_raw_syndrome - [INTERN] raw page write function
1994 * @mtd: mtd info structure
1995 * @chip: nand chip info structure
1996 * @buf: data buffer
1997 * @oob_required: must write chip->oob_poi to OOB
1999 * We need a special oob layout and handling even when ECC isn't checked.
2001 static int nand_write_page_raw_syndrome(struct mtd_info *mtd,
2002 struct nand_chip *chip,
2003 const uint8_t *buf, int oob_required)
2005 int eccsize = chip->ecc.size;
2006 int eccbytes = chip->ecc.bytes;
2007 uint8_t *oob = chip->oob_poi;
2008 int steps, size;
2010 for (steps = chip->ecc.steps; steps > 0; steps--) {
2011 chip->write_buf(mtd, buf, eccsize);
2012 buf += eccsize;
2014 if (chip->ecc.prepad) {
2015 chip->write_buf(mtd, oob, chip->ecc.prepad);
2016 oob += chip->ecc.prepad;
2019 chip->write_buf(mtd, oob, eccbytes);
2020 oob += eccbytes;
2022 if (chip->ecc.postpad) {
2023 chip->write_buf(mtd, oob, chip->ecc.postpad);
2024 oob += chip->ecc.postpad;
2028 size = mtd->oobsize - (oob - chip->oob_poi);
2029 if (size)
2030 chip->write_buf(mtd, oob, size);
2032 return 0;
2035 * nand_write_page_swecc - [REPLACEABLE] software ECC based page write function
2036 * @mtd: mtd info structure
2037 * @chip: nand chip info structure
2038 * @buf: data buffer
2039 * @oob_required: must write chip->oob_poi to OOB
2041 static int nand_write_page_swecc(struct mtd_info *mtd, struct nand_chip *chip,
2042 const uint8_t *buf, int oob_required)
2044 int i, eccsize = chip->ecc.size;
2045 int eccbytes = chip->ecc.bytes;
2046 int eccsteps = chip->ecc.steps;
2047 uint8_t *ecc_calc = chip->buffers->ecccalc;
2048 const uint8_t *p = buf;
2049 uint32_t *eccpos = chip->ecc.layout->eccpos;
2051 /* Software ECC calculation */
2052 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize)
2053 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
2055 for (i = 0; i < chip->ecc.total; i++)
2056 chip->oob_poi[eccpos[i]] = ecc_calc[i];
2058 return chip->ecc.write_page_raw(mtd, chip, buf, 1);
2062 * nand_write_page_hwecc - [REPLACEABLE] hardware ECC based page write function
2063 * @mtd: mtd info structure
2064 * @chip: nand chip info structure
2065 * @buf: data buffer
2066 * @oob_required: must write chip->oob_poi to OOB
2068 static int nand_write_page_hwecc(struct mtd_info *mtd, struct nand_chip *chip,
2069 const uint8_t *buf, int oob_required)
2071 int i, eccsize = chip->ecc.size;
2072 int eccbytes = chip->ecc.bytes;
2073 int eccsteps = chip->ecc.steps;
2074 uint8_t *ecc_calc = chip->buffers->ecccalc;
2075 const uint8_t *p = buf;
2076 uint32_t *eccpos = chip->ecc.layout->eccpos;
2078 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
2079 chip->ecc.hwctl(mtd, NAND_ECC_WRITE);
2080 chip->write_buf(mtd, p, eccsize);
2081 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
2084 for (i = 0; i < chip->ecc.total; i++)
2085 chip->oob_poi[eccpos[i]] = ecc_calc[i];
2087 chip->write_buf(mtd, chip->oob_poi, mtd->oobsize);
2089 return 0;
2094 * nand_write_subpage_hwecc - [REPLACABLE] hardware ECC based subpage write
2095 * @mtd: mtd info structure
2096 * @chip: nand chip info structure
2097 * @offset: column address of subpage within the page
2098 * @data_len: data length
2099 * @buf: data buffer
2100 * @oob_required: must write chip->oob_poi to OOB
2102 static int nand_write_subpage_hwecc(struct mtd_info *mtd,
2103 struct nand_chip *chip, uint32_t offset,
2104 uint32_t data_len, const uint8_t *buf,
2105 int oob_required)
2107 uint8_t *oob_buf = chip->oob_poi;
2108 uint8_t *ecc_calc = chip->buffers->ecccalc;
2109 int ecc_size = chip->ecc.size;
2110 int ecc_bytes = chip->ecc.bytes;
2111 int ecc_steps = chip->ecc.steps;
2112 uint32_t *eccpos = chip->ecc.layout->eccpos;
2113 uint32_t start_step = offset / ecc_size;
2114 uint32_t end_step = (offset + data_len - 1) / ecc_size;
2115 int oob_bytes = mtd->oobsize / ecc_steps;
2116 int step, i;
2118 for (step = 0; step < ecc_steps; step++) {
2119 /* configure controller for WRITE access */
2120 chip->ecc.hwctl(mtd, NAND_ECC_WRITE);
2122 /* write data (untouched subpages already masked by 0xFF) */
2123 chip->write_buf(mtd, buf, ecc_size);
2125 /* mask ECC of un-touched subpages by padding 0xFF */
2126 if ((step < start_step) || (step > end_step))
2127 memset(ecc_calc, 0xff, ecc_bytes);
2128 else
2129 chip->ecc.calculate(mtd, buf, ecc_calc);
2131 /* mask OOB of un-touched subpages by padding 0xFF */
2132 /* if oob_required, preserve OOB metadata of written subpage */
2133 if (!oob_required || (step < start_step) || (step > end_step))
2134 memset(oob_buf, 0xff, oob_bytes);
2136 buf += ecc_size;
2137 ecc_calc += ecc_bytes;
2138 oob_buf += oob_bytes;
2141 /* copy calculated ECC for whole page to chip->buffer->oob */
2142 /* this include masked-value(0xFF) for unwritten subpages */
2143 ecc_calc = chip->buffers->ecccalc;
2144 for (i = 0; i < chip->ecc.total; i++)
2145 chip->oob_poi[eccpos[i]] = ecc_calc[i];
2147 /* write OOB buffer to NAND device */
2148 chip->write_buf(mtd, chip->oob_poi, mtd->oobsize);
2150 return 0;
2155 * nand_write_page_syndrome - [REPLACEABLE] hardware ECC syndrome based page write
2156 * @mtd: mtd info structure
2157 * @chip: nand chip info structure
2158 * @buf: data buffer
2159 * @oob_required: must write chip->oob_poi to OOB
2161 * The hw generator calculates the error syndrome automatically. Therefore we
2162 * need a special oob layout and handling.
2164 static int nand_write_page_syndrome(struct mtd_info *mtd,
2165 struct nand_chip *chip,
2166 const uint8_t *buf, int oob_required)
2168 int i, eccsize = chip->ecc.size;
2169 int eccbytes = chip->ecc.bytes;
2170 int eccsteps = chip->ecc.steps;
2171 const uint8_t *p = buf;
2172 uint8_t *oob = chip->oob_poi;
2174 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
2176 chip->ecc.hwctl(mtd, NAND_ECC_WRITE);
2177 chip->write_buf(mtd, p, eccsize);
2179 if (chip->ecc.prepad) {
2180 chip->write_buf(mtd, oob, chip->ecc.prepad);
2181 oob += chip->ecc.prepad;
2184 chip->ecc.calculate(mtd, p, oob);
2185 chip->write_buf(mtd, oob, eccbytes);
2186 oob += eccbytes;
2188 if (chip->ecc.postpad) {
2189 chip->write_buf(mtd, oob, chip->ecc.postpad);
2190 oob += chip->ecc.postpad;
2194 /* Calculate remaining oob bytes */
2195 i = mtd->oobsize - (oob - chip->oob_poi);
2196 if (i)
2197 chip->write_buf(mtd, oob, i);
2199 return 0;
2203 * nand_write_page - [REPLACEABLE] write one page
2204 * @mtd: MTD device structure
2205 * @chip: NAND chip descriptor
2206 * @offset: address offset within the page
2207 * @data_len: length of actual data to be written
2208 * @buf: the data to write
2209 * @oob_required: must write chip->oob_poi to OOB
2210 * @page: page number to write
2211 * @cached: cached programming
2212 * @raw: use _raw version of write_page
2214 static int nand_write_page(struct mtd_info *mtd, struct nand_chip *chip,
2215 uint32_t offset, int data_len, const uint8_t *buf,
2216 int oob_required, int page, int cached, int raw)
2218 int status, subpage;
2220 if (!(chip->options & NAND_NO_SUBPAGE_WRITE) &&
2221 chip->ecc.write_subpage)
2222 subpage = offset || (data_len < mtd->writesize);
2223 else
2224 subpage = 0;
2226 chip->cmdfunc(mtd, NAND_CMD_SEQIN, 0x00, page);
2228 if (unlikely(raw))
2229 status = chip->ecc.write_page_raw(mtd, chip, buf,
2230 oob_required);
2231 else if (subpage)
2232 status = chip->ecc.write_subpage(mtd, chip, offset, data_len,
2233 buf, oob_required);
2234 else
2235 status = chip->ecc.write_page(mtd, chip, buf, oob_required);
2237 if (status < 0)
2238 return status;
2241 * Cached progamming disabled for now. Not sure if it's worth the
2242 * trouble. The speed gain is not very impressive. (2.3->2.6Mib/s).
2244 cached = 0;
2246 if (!cached || !NAND_HAS_CACHEPROG(chip)) {
2248 chip->cmdfunc(mtd, NAND_CMD_PAGEPROG, -1, -1);
2249 status = chip->waitfunc(mtd, chip);
2251 * See if operation failed and additional status checks are
2252 * available.
2254 if ((status & NAND_STATUS_FAIL) && (chip->errstat))
2255 status = chip->errstat(mtd, chip, FL_WRITING, status,
2256 page);
2258 if (status & NAND_STATUS_FAIL)
2259 return -EIO;
2260 } else {
2261 chip->cmdfunc(mtd, NAND_CMD_CACHEDPROG, -1, -1);
2262 status = chip->waitfunc(mtd, chip);
2265 return 0;
2269 * nand_fill_oob - [INTERN] Transfer client buffer to oob
2270 * @mtd: MTD device structure
2271 * @oob: oob data buffer
2272 * @len: oob data write length
2273 * @ops: oob ops structure
2275 static uint8_t *nand_fill_oob(struct mtd_info *mtd, uint8_t *oob, size_t len,
2276 struct mtd_oob_ops *ops)
2278 struct nand_chip *chip = mtd->priv;
2281 * Initialise to all 0xFF, to avoid the possibility of left over OOB
2282 * data from a previous OOB read.
2284 memset(chip->oob_poi, 0xff, mtd->oobsize);
2286 switch (ops->mode) {
2288 case MTD_OPS_PLACE_OOB:
2289 case MTD_OPS_RAW:
2290 memcpy(chip->oob_poi + ops->ooboffs, oob, len);
2291 return oob + len;
2293 case MTD_OPS_AUTO_OOB: {
2294 struct nand_oobfree *free = chip->ecc.layout->oobfree;
2295 uint32_t boffs = 0, woffs = ops->ooboffs;
2296 size_t bytes = 0;
2298 for (; free->length && len; free++, len -= bytes) {
2299 /* Write request not from offset 0? */
2300 if (unlikely(woffs)) {
2301 if (woffs >= free->length) {
2302 woffs -= free->length;
2303 continue;
2305 boffs = free->offset + woffs;
2306 bytes = min_t(size_t, len,
2307 (free->length - woffs));
2308 woffs = 0;
2309 } else {
2310 bytes = min_t(size_t, len, free->length);
2311 boffs = free->offset;
2313 memcpy(chip->oob_poi + boffs, oob, bytes);
2314 oob += bytes;
2316 return oob;
2318 default:
2319 BUG();
2321 return NULL;
2324 #define NOTALIGNED(x) ((x & (chip->subpagesize - 1)) != 0)
2327 * nand_do_write_ops - [INTERN] NAND write with ECC
2328 * @mtd: MTD device structure
2329 * @to: offset to write to
2330 * @ops: oob operations description structure
2332 * NAND write with ECC.
2334 static int nand_do_write_ops(struct mtd_info *mtd, loff_t to,
2335 struct mtd_oob_ops *ops)
2337 int chipnr, realpage, page, blockmask, column;
2338 struct nand_chip *chip = mtd->priv;
2339 uint32_t writelen = ops->len;
2341 uint32_t oobwritelen = ops->ooblen;
2342 uint32_t oobmaxlen = ops->mode == MTD_OPS_AUTO_OOB ?
2343 mtd->oobavail : mtd->oobsize;
2345 uint8_t *oob = ops->oobbuf;
2346 uint8_t *buf = ops->datbuf;
2347 int ret;
2348 int oob_required = oob ? 1 : 0;
2350 ops->retlen = 0;
2351 if (!writelen)
2352 return 0;
2354 /* Reject writes, which are not page aligned */
2355 if (NOTALIGNED(to) || NOTALIGNED(ops->len)) {
2356 pr_notice("%s: attempt to write non page aligned data\n",
2357 __func__);
2358 return -EINVAL;
2361 column = to & (mtd->writesize - 1);
2363 chipnr = (int)(to >> chip->chip_shift);
2364 chip->select_chip(mtd, chipnr);
2366 /* Check, if it is write protected */
2367 if (nand_check_wp(mtd)) {
2368 ret = -EIO;
2369 goto err_out;
2372 realpage = (int)(to >> chip->page_shift);
2373 page = realpage & chip->pagemask;
2374 blockmask = (1 << (chip->phys_erase_shift - chip->page_shift)) - 1;
2376 /* Invalidate the page cache, when we write to the cached page */
2377 if (to <= (chip->pagebuf << chip->page_shift) &&
2378 (chip->pagebuf << chip->page_shift) < (to + ops->len))
2379 chip->pagebuf = -1;
2381 /* Don't allow multipage oob writes with offset */
2382 if (oob && ops->ooboffs && (ops->ooboffs + ops->ooblen > oobmaxlen)) {
2383 ret = -EINVAL;
2384 goto err_out;
2387 while (1) {
2388 int bytes = mtd->writesize;
2389 int cached = writelen > bytes && page != blockmask;
2390 uint8_t *wbuf = buf;
2391 int use_bufpoi;
2392 int part_pagewr = (column || writelen < (mtd->writesize - 1));
2394 if (part_pagewr)
2395 use_bufpoi = 1;
2396 else if (chip->options & NAND_USE_BOUNCE_BUFFER)
2397 use_bufpoi = !virt_addr_valid(buf);
2398 else
2399 use_bufpoi = 0;
2401 /* Partial page write?, or need to use bounce buffer */
2402 if (use_bufpoi) {
2403 pr_debug("%s: using write bounce buffer for buf@%p\n",
2404 __func__, buf);
2405 cached = 0;
2406 if (part_pagewr)
2407 bytes = min_t(int, bytes - column, writelen);
2408 chip->pagebuf = -1;
2409 memset(chip->buffers->databuf, 0xff, mtd->writesize);
2410 memcpy(&chip->buffers->databuf[column], buf, bytes);
2411 wbuf = chip->buffers->databuf;
2414 if (unlikely(oob)) {
2415 size_t len = min(oobwritelen, oobmaxlen);
2416 oob = nand_fill_oob(mtd, oob, len, ops);
2417 oobwritelen -= len;
2418 } else {
2419 /* We still need to erase leftover OOB data */
2420 memset(chip->oob_poi, 0xff, mtd->oobsize);
2422 ret = chip->write_page(mtd, chip, column, bytes, wbuf,
2423 oob_required, page, cached,
2424 (ops->mode == MTD_OPS_RAW));
2425 if (ret)
2426 break;
2428 writelen -= bytes;
2429 if (!writelen)
2430 break;
2432 column = 0;
2433 buf += bytes;
2434 realpage++;
2436 page = realpage & chip->pagemask;
2437 /* Check, if we cross a chip boundary */
2438 if (!page) {
2439 chipnr++;
2440 chip->select_chip(mtd, -1);
2441 chip->select_chip(mtd, chipnr);
2445 ops->retlen = ops->len - writelen;
2446 if (unlikely(oob))
2447 ops->oobretlen = ops->ooblen;
2449 err_out:
2450 chip->select_chip(mtd, -1);
2451 return ret;
2455 * panic_nand_write - [MTD Interface] NAND write with ECC
2456 * @mtd: MTD device structure
2457 * @to: offset to write to
2458 * @len: number of bytes to write
2459 * @retlen: pointer to variable to store the number of written bytes
2460 * @buf: the data to write
2462 * NAND write with ECC. Used when performing writes in interrupt context, this
2463 * may for example be called by mtdoops when writing an oops while in panic.
2465 static int panic_nand_write(struct mtd_info *mtd, loff_t to, size_t len,
2466 size_t *retlen, const uint8_t *buf)
2468 struct nand_chip *chip = mtd->priv;
2469 struct mtd_oob_ops ops;
2470 int ret;
2472 /* Wait for the device to get ready */
2473 panic_nand_wait(mtd, chip, 400);
2475 /* Grab the device */
2476 panic_nand_get_device(chip, mtd, FL_WRITING);
2478 ops.len = len;
2479 ops.datbuf = (uint8_t *)buf;
2480 ops.oobbuf = NULL;
2481 ops.mode = MTD_OPS_PLACE_OOB;
2483 ret = nand_do_write_ops(mtd, to, &ops);
2485 *retlen = ops.retlen;
2486 return ret;
2490 * nand_write - [MTD Interface] NAND write with ECC
2491 * @mtd: MTD device structure
2492 * @to: offset to write to
2493 * @len: number of bytes to write
2494 * @retlen: pointer to variable to store the number of written bytes
2495 * @buf: the data to write
2497 * NAND write with ECC.
2499 static int nand_write(struct mtd_info *mtd, loff_t to, size_t len,
2500 size_t *retlen, const uint8_t *buf)
2502 struct mtd_oob_ops ops;
2503 int ret;
2505 nand_get_device(mtd, FL_WRITING);
2506 ops.len = len;
2507 ops.datbuf = (uint8_t *)buf;
2508 ops.oobbuf = NULL;
2509 ops.mode = MTD_OPS_PLACE_OOB;
2510 ret = nand_do_write_ops(mtd, to, &ops);
2511 *retlen = ops.retlen;
2512 nand_release_device(mtd);
2513 return ret;
2517 * nand_do_write_oob - [MTD Interface] NAND write out-of-band
2518 * @mtd: MTD device structure
2519 * @to: offset to write to
2520 * @ops: oob operation description structure
2522 * NAND write out-of-band.
2524 static int nand_do_write_oob(struct mtd_info *mtd, loff_t to,
2525 struct mtd_oob_ops *ops)
2527 int chipnr, page, status, len;
2528 struct nand_chip *chip = mtd->priv;
2530 pr_debug("%s: to = 0x%08x, len = %i\n",
2531 __func__, (unsigned int)to, (int)ops->ooblen);
2533 if (ops->mode == MTD_OPS_AUTO_OOB)
2534 len = chip->ecc.layout->oobavail;
2535 else
2536 len = mtd->oobsize;
2538 /* Do not allow write past end of page */
2539 if ((ops->ooboffs + ops->ooblen) > len) {
2540 pr_debug("%s: attempt to write past end of page\n",
2541 __func__);
2542 return -EINVAL;
2545 if (unlikely(ops->ooboffs >= len)) {
2546 pr_debug("%s: attempt to start write outside oob\n",
2547 __func__);
2548 return -EINVAL;
2551 /* Do not allow write past end of device */
2552 if (unlikely(to >= mtd->size ||
2553 ops->ooboffs + ops->ooblen >
2554 ((mtd->size >> chip->page_shift) -
2555 (to >> chip->page_shift)) * len)) {
2556 pr_debug("%s: attempt to write beyond end of device\n",
2557 __func__);
2558 return -EINVAL;
2561 chipnr = (int)(to >> chip->chip_shift);
2562 chip->select_chip(mtd, chipnr);
2564 /* Shift to get page */
2565 page = (int)(to >> chip->page_shift);
2568 * Reset the chip. Some chips (like the Toshiba TC5832DC found in one
2569 * of my DiskOnChip 2000 test units) will clear the whole data page too
2570 * if we don't do this. I have no clue why, but I seem to have 'fixed'
2571 * it in the doc2000 driver in August 1999. dwmw2.
2573 chip->cmdfunc(mtd, NAND_CMD_RESET, -1, -1);
2575 /* Check, if it is write protected */
2576 if (nand_check_wp(mtd)) {
2577 chip->select_chip(mtd, -1);
2578 return -EROFS;
2581 /* Invalidate the page cache, if we write to the cached page */
2582 if (page == chip->pagebuf)
2583 chip->pagebuf = -1;
2585 nand_fill_oob(mtd, ops->oobbuf, ops->ooblen, ops);
2587 if (ops->mode == MTD_OPS_RAW)
2588 status = chip->ecc.write_oob_raw(mtd, chip, page & chip->pagemask);
2589 else
2590 status = chip->ecc.write_oob(mtd, chip, page & chip->pagemask);
2592 chip->select_chip(mtd, -1);
2594 if (status)
2595 return status;
2597 ops->oobretlen = ops->ooblen;
2599 return 0;
2603 * nand_write_oob - [MTD Interface] NAND write data and/or out-of-band
2604 * @mtd: MTD device structure
2605 * @to: offset to write to
2606 * @ops: oob operation description structure
2608 static int nand_write_oob(struct mtd_info *mtd, loff_t to,
2609 struct mtd_oob_ops *ops)
2611 int ret = -ENOTSUPP;
2613 ops->retlen = 0;
2615 /* Do not allow writes past end of device */
2616 if (ops->datbuf && (to + ops->len) > mtd->size) {
2617 pr_debug("%s: attempt to write beyond end of device\n",
2618 __func__);
2619 return -EINVAL;
2622 nand_get_device(mtd, FL_WRITING);
2624 switch (ops->mode) {
2625 case MTD_OPS_PLACE_OOB:
2626 case MTD_OPS_AUTO_OOB:
2627 case MTD_OPS_RAW:
2628 break;
2630 default:
2631 goto out;
2634 if (!ops->datbuf)
2635 ret = nand_do_write_oob(mtd, to, ops);
2636 else
2637 ret = nand_do_write_ops(mtd, to, ops);
2639 out:
2640 nand_release_device(mtd);
2641 return ret;
2645 * single_erase - [GENERIC] NAND standard block erase command function
2646 * @mtd: MTD device structure
2647 * @page: the page address of the block which will be erased
2649 * Standard erase command for NAND chips. Returns NAND status.
2651 static int single_erase(struct mtd_info *mtd, int page)
2653 struct nand_chip *chip = mtd->priv;
2654 /* Send commands to erase a block */
2655 chip->cmdfunc(mtd, NAND_CMD_ERASE1, -1, page);
2656 chip->cmdfunc(mtd, NAND_CMD_ERASE2, -1, -1);
2658 return chip->waitfunc(mtd, chip);
2662 * nand_erase - [MTD Interface] erase block(s)
2663 * @mtd: MTD device structure
2664 * @instr: erase instruction
2666 * Erase one ore more blocks.
2668 static int nand_erase(struct mtd_info *mtd, struct erase_info *instr)
2670 return nand_erase_nand(mtd, instr, 0);
2674 * nand_erase_nand - [INTERN] erase block(s)
2675 * @mtd: MTD device structure
2676 * @instr: erase instruction
2677 * @allowbbt: allow erasing the bbt area
2679 * Erase one ore more blocks.
2681 int nand_erase_nand(struct mtd_info *mtd, struct erase_info *instr,
2682 int allowbbt)
2684 int page, status, pages_per_block, ret, chipnr;
2685 struct nand_chip *chip = mtd->priv;
2686 loff_t len;
2688 pr_debug("%s: start = 0x%012llx, len = %llu\n",
2689 __func__, (unsigned long long)instr->addr,
2690 (unsigned long long)instr->len);
2692 if (check_offs_len(mtd, instr->addr, instr->len))
2693 return -EINVAL;
2695 /* Grab the lock and see if the device is available */
2696 nand_get_device(mtd, FL_ERASING);
2698 /* Shift to get first page */
2699 page = (int)(instr->addr >> chip->page_shift);
2700 chipnr = (int)(instr->addr >> chip->chip_shift);
2702 /* Calculate pages in each block */
2703 pages_per_block = 1 << (chip->phys_erase_shift - chip->page_shift);
2705 /* Select the NAND device */
2706 chip->select_chip(mtd, chipnr);
2708 /* Check, if it is write protected */
2709 if (nand_check_wp(mtd)) {
2710 pr_debug("%s: device is write protected!\n",
2711 __func__);
2712 instr->state = MTD_ERASE_FAILED;
2713 goto erase_exit;
2716 /* Loop through the pages */
2717 len = instr->len;
2719 instr->state = MTD_ERASING;
2721 while (len) {
2722 /* Check if we have a bad block, we do not erase bad blocks! */
2723 if (nand_block_checkbad(mtd, ((loff_t) page) <<
2724 chip->page_shift, 0, allowbbt)) {
2725 pr_warn("%s: attempt to erase a bad block at page 0x%08x\n",
2726 __func__, page);
2727 instr->state = MTD_ERASE_FAILED;
2728 goto erase_exit;
2732 * Invalidate the page cache, if we erase the block which
2733 * contains the current cached page.
2735 if (page <= chip->pagebuf && chip->pagebuf <
2736 (page + pages_per_block))
2737 chip->pagebuf = -1;
2739 status = chip->erase(mtd, page & chip->pagemask);
2742 * See if operation failed and additional status checks are
2743 * available
2745 if ((status & NAND_STATUS_FAIL) && (chip->errstat))
2746 status = chip->errstat(mtd, chip, FL_ERASING,
2747 status, page);
2749 /* See if block erase succeeded */
2750 if (status & NAND_STATUS_FAIL) {
2751 pr_debug("%s: failed erase, page 0x%08x\n",
2752 __func__, page);
2753 instr->state = MTD_ERASE_FAILED;
2754 instr->fail_addr =
2755 ((loff_t)page << chip->page_shift);
2756 goto erase_exit;
2759 /* Increment page address and decrement length */
2760 len -= (1ULL << chip->phys_erase_shift);
2761 page += pages_per_block;
2763 /* Check, if we cross a chip boundary */
2764 if (len && !(page & chip->pagemask)) {
2765 chipnr++;
2766 chip->select_chip(mtd, -1);
2767 chip->select_chip(mtd, chipnr);
2770 instr->state = MTD_ERASE_DONE;
2772 erase_exit:
2774 ret = instr->state == MTD_ERASE_DONE ? 0 : -EIO;
2776 /* Deselect and wake up anyone waiting on the device */
2777 chip->select_chip(mtd, -1);
2778 nand_release_device(mtd);
2780 /* Do call back function */
2781 if (!ret)
2782 mtd_erase_callback(instr);
2784 /* Return more or less happy */
2785 return ret;
2789 * nand_sync - [MTD Interface] sync
2790 * @mtd: MTD device structure
2792 * Sync is actually a wait for chip ready function.
2794 static void nand_sync(struct mtd_info *mtd)
2796 pr_debug("%s: called\n", __func__);
2798 /* Grab the lock and see if the device is available */
2799 nand_get_device(mtd, FL_SYNCING);
2800 /* Release it and go back */
2801 nand_release_device(mtd);
2805 * nand_block_isbad - [MTD Interface] Check if block at offset is bad
2806 * @mtd: MTD device structure
2807 * @offs: offset relative to mtd start
2809 static int nand_block_isbad(struct mtd_info *mtd, loff_t offs)
2811 return nand_block_checkbad(mtd, offs, 1, 0);
2815 * nand_block_markbad - [MTD Interface] Mark block at the given offset as bad
2816 * @mtd: MTD device structure
2817 * @ofs: offset relative to mtd start
2819 static int nand_block_markbad(struct mtd_info *mtd, loff_t ofs)
2821 int ret;
2823 ret = nand_block_isbad(mtd, ofs);
2824 if (ret) {
2825 /* If it was bad already, return success and do nothing */
2826 if (ret > 0)
2827 return 0;
2828 return ret;
2831 return nand_block_markbad_lowlevel(mtd, ofs);
2835 * nand_onfi_set_features- [REPLACEABLE] set features for ONFI nand
2836 * @mtd: MTD device structure
2837 * @chip: nand chip info structure
2838 * @addr: feature address.
2839 * @subfeature_param: the subfeature parameters, a four bytes array.
2841 static int nand_onfi_set_features(struct mtd_info *mtd, struct nand_chip *chip,
2842 int addr, uint8_t *subfeature_param)
2844 int status;
2845 int i;
2847 if (!chip->onfi_version ||
2848 !(le16_to_cpu(chip->onfi_params.opt_cmd)
2849 & ONFI_OPT_CMD_SET_GET_FEATURES))
2850 return -EINVAL;
2852 chip->cmdfunc(mtd, NAND_CMD_SET_FEATURES, addr, -1);
2853 for (i = 0; i < ONFI_SUBFEATURE_PARAM_LEN; ++i)
2854 chip->write_byte(mtd, subfeature_param[i]);
2856 status = chip->waitfunc(mtd, chip);
2857 if (status & NAND_STATUS_FAIL)
2858 return -EIO;
2859 return 0;
2863 * nand_onfi_get_features- [REPLACEABLE] get features for ONFI nand
2864 * @mtd: MTD device structure
2865 * @chip: nand chip info structure
2866 * @addr: feature address.
2867 * @subfeature_param: the subfeature parameters, a four bytes array.
2869 static int nand_onfi_get_features(struct mtd_info *mtd, struct nand_chip *chip,
2870 int addr, uint8_t *subfeature_param)
2872 int i;
2874 if (!chip->onfi_version ||
2875 !(le16_to_cpu(chip->onfi_params.opt_cmd)
2876 & ONFI_OPT_CMD_SET_GET_FEATURES))
2877 return -EINVAL;
2879 /* clear the sub feature parameters */
2880 memset(subfeature_param, 0, ONFI_SUBFEATURE_PARAM_LEN);
2882 chip->cmdfunc(mtd, NAND_CMD_GET_FEATURES, addr, -1);
2883 for (i = 0; i < ONFI_SUBFEATURE_PARAM_LEN; ++i)
2884 *subfeature_param++ = chip->read_byte(mtd);
2885 return 0;
2889 * nand_suspend - [MTD Interface] Suspend the NAND flash
2890 * @mtd: MTD device structure
2892 static int nand_suspend(struct mtd_info *mtd)
2894 return nand_get_device(mtd, FL_PM_SUSPENDED);
2898 * nand_resume - [MTD Interface] Resume the NAND flash
2899 * @mtd: MTD device structure
2901 static void nand_resume(struct mtd_info *mtd)
2903 struct nand_chip *chip = mtd->priv;
2905 if (chip->state == FL_PM_SUSPENDED)
2906 nand_release_device(mtd);
2907 else
2908 pr_err("%s called for a chip which is not in suspended state\n",
2909 __func__);
2912 /* Set default functions */
2913 static void nand_set_defaults(struct nand_chip *chip, int busw)
2915 /* check for proper chip_delay setup, set 20us if not */
2916 if (!chip->chip_delay)
2917 chip->chip_delay = 20;
2919 /* check, if a user supplied command function given */
2920 if (chip->cmdfunc == NULL)
2921 chip->cmdfunc = nand_command;
2923 /* check, if a user supplied wait function given */
2924 if (chip->waitfunc == NULL)
2925 chip->waitfunc = nand_wait;
2927 if (!chip->select_chip)
2928 chip->select_chip = nand_select_chip;
2930 /* set for ONFI nand */
2931 if (!chip->onfi_set_features)
2932 chip->onfi_set_features = nand_onfi_set_features;
2933 if (!chip->onfi_get_features)
2934 chip->onfi_get_features = nand_onfi_get_features;
2936 /* If called twice, pointers that depend on busw may need to be reset */
2937 if (!chip->read_byte || chip->read_byte == nand_read_byte)
2938 chip->read_byte = busw ? nand_read_byte16 : nand_read_byte;
2939 if (!chip->read_word)
2940 chip->read_word = nand_read_word;
2941 if (!chip->block_bad)
2942 chip->block_bad = nand_block_bad;
2943 if (!chip->block_markbad)
2944 chip->block_markbad = nand_default_block_markbad;
2945 if (!chip->write_buf || chip->write_buf == nand_write_buf)
2946 chip->write_buf = busw ? nand_write_buf16 : nand_write_buf;
2947 if (!chip->write_byte || chip->write_byte == nand_write_byte)
2948 chip->write_byte = busw ? nand_write_byte16 : nand_write_byte;
2949 if (!chip->read_buf || chip->read_buf == nand_read_buf)
2950 chip->read_buf = busw ? nand_read_buf16 : nand_read_buf;
2951 if (!chip->scan_bbt)
2952 chip->scan_bbt = nand_default_bbt;
2954 if (!chip->controller) {
2955 chip->controller = &chip->hwcontrol;
2956 spin_lock_init(&chip->controller->lock);
2957 init_waitqueue_head(&chip->controller->wq);
2962 /* Sanitize ONFI strings so we can safely print them */
2963 static void sanitize_string(uint8_t *s, size_t len)
2965 ssize_t i;
2967 /* Null terminate */
2968 s[len - 1] = 0;
2970 /* Remove non printable chars */
2971 for (i = 0; i < len - 1; i++) {
2972 if (s[i] < ' ' || s[i] > 127)
2973 s[i] = '?';
2976 /* Remove trailing spaces */
2977 strim(s);
2980 static u16 onfi_crc16(u16 crc, u8 const *p, size_t len)
2982 int i;
2983 while (len--) {
2984 crc ^= *p++ << 8;
2985 for (i = 0; i < 8; i++)
2986 crc = (crc << 1) ^ ((crc & 0x8000) ? 0x8005 : 0);
2989 return crc;
2992 /* Parse the Extended Parameter Page. */
2993 static int nand_flash_detect_ext_param_page(struct mtd_info *mtd,
2994 struct nand_chip *chip, struct nand_onfi_params *p)
2996 struct onfi_ext_param_page *ep;
2997 struct onfi_ext_section *s;
2998 struct onfi_ext_ecc_info *ecc;
2999 uint8_t *cursor;
3000 int ret = -EINVAL;
3001 int len;
3002 int i;
3004 len = le16_to_cpu(p->ext_param_page_length) * 16;
3005 ep = kmalloc(len, GFP_KERNEL);
3006 if (!ep)
3007 return -ENOMEM;
3009 /* Send our own NAND_CMD_PARAM. */
3010 chip->cmdfunc(mtd, NAND_CMD_PARAM, 0, -1);
3012 /* Use the Change Read Column command to skip the ONFI param pages. */
3013 chip->cmdfunc(mtd, NAND_CMD_RNDOUT,
3014 sizeof(*p) * p->num_of_param_pages , -1);
3016 /* Read out the Extended Parameter Page. */
3017 chip->read_buf(mtd, (uint8_t *)ep, len);
3018 if ((onfi_crc16(ONFI_CRC_BASE, ((uint8_t *)ep) + 2, len - 2)
3019 != le16_to_cpu(ep->crc))) {
3020 pr_debug("fail in the CRC.\n");
3021 goto ext_out;
3025 * Check the signature.
3026 * Do not strictly follow the ONFI spec, maybe changed in future.
3028 if (strncmp(ep->sig, "EPPS", 4)) {
3029 pr_debug("The signature is invalid.\n");
3030 goto ext_out;
3033 /* find the ECC section. */
3034 cursor = (uint8_t *)(ep + 1);
3035 for (i = 0; i < ONFI_EXT_SECTION_MAX; i++) {
3036 s = ep->sections + i;
3037 if (s->type == ONFI_SECTION_TYPE_2)
3038 break;
3039 cursor += s->length * 16;
3041 if (i == ONFI_EXT_SECTION_MAX) {
3042 pr_debug("We can not find the ECC section.\n");
3043 goto ext_out;
3046 /* get the info we want. */
3047 ecc = (struct onfi_ext_ecc_info *)cursor;
3049 if (!ecc->codeword_size) {
3050 pr_debug("Invalid codeword size\n");
3051 goto ext_out;
3054 chip->ecc_strength_ds = ecc->ecc_bits;
3055 chip->ecc_step_ds = 1 << ecc->codeword_size;
3056 ret = 0;
3058 ext_out:
3059 kfree(ep);
3060 return ret;
3063 static int nand_setup_read_retry_micron(struct mtd_info *mtd, int retry_mode)
3065 struct nand_chip *chip = mtd->priv;
3066 uint8_t feature[ONFI_SUBFEATURE_PARAM_LEN] = {retry_mode};
3068 return chip->onfi_set_features(mtd, chip, ONFI_FEATURE_ADDR_READ_RETRY,
3069 feature);
3073 * Configure chip properties from Micron vendor-specific ONFI table
3075 static void nand_onfi_detect_micron(struct nand_chip *chip,
3076 struct nand_onfi_params *p)
3078 struct nand_onfi_vendor_micron *micron = (void *)p->vendor;
3080 if (le16_to_cpu(p->vendor_revision) < 1)
3081 return;
3083 chip->read_retries = micron->read_retry_options;
3084 chip->setup_read_retry = nand_setup_read_retry_micron;
3088 * Check if the NAND chip is ONFI compliant, returns 1 if it is, 0 otherwise.
3090 static int nand_flash_detect_onfi(struct mtd_info *mtd, struct nand_chip *chip,
3091 int *busw)
3093 struct nand_onfi_params *p = &chip->onfi_params;
3094 int i, j;
3095 int val;
3097 /* Try ONFI for unknown chip or LP */
3098 chip->cmdfunc(mtd, NAND_CMD_READID, 0x20, -1);
3099 if (chip->read_byte(mtd) != 'O' || chip->read_byte(mtd) != 'N' ||
3100 chip->read_byte(mtd) != 'F' || chip->read_byte(mtd) != 'I')
3101 return 0;
3103 chip->cmdfunc(mtd, NAND_CMD_PARAM, 0, -1);
3104 for (i = 0; i < 3; i++) {
3105 for (j = 0; j < sizeof(*p); j++)
3106 ((uint8_t *)p)[j] = chip->read_byte(mtd);
3107 if (onfi_crc16(ONFI_CRC_BASE, (uint8_t *)p, 254) ==
3108 le16_to_cpu(p->crc)) {
3109 break;
3113 if (i == 3) {
3114 pr_err("Could not find valid ONFI parameter page; aborting\n");
3115 return 0;
3118 /* Check version */
3119 val = le16_to_cpu(p->revision);
3120 if (val & (1 << 5))
3121 chip->onfi_version = 23;
3122 else if (val & (1 << 4))
3123 chip->onfi_version = 22;
3124 else if (val & (1 << 3))
3125 chip->onfi_version = 21;
3126 else if (val & (1 << 2))
3127 chip->onfi_version = 20;
3128 else if (val & (1 << 1))
3129 chip->onfi_version = 10;
3131 if (!chip->onfi_version) {
3132 pr_info("unsupported ONFI version: %d\n", val);
3133 return 0;
3136 sanitize_string(p->manufacturer, sizeof(p->manufacturer));
3137 sanitize_string(p->model, sizeof(p->model));
3138 if (!mtd->name)
3139 mtd->name = p->model;
3141 mtd->writesize = le32_to_cpu(p->byte_per_page);
3144 * pages_per_block and blocks_per_lun may not be a power-of-2 size
3145 * (don't ask me who thought of this...). MTD assumes that these
3146 * dimensions will be power-of-2, so just truncate the remaining area.
3148 mtd->erasesize = 1 << (fls(le32_to_cpu(p->pages_per_block)) - 1);
3149 mtd->erasesize *= mtd->writesize;
3151 mtd->oobsize = le16_to_cpu(p->spare_bytes_per_page);
3153 /* See erasesize comment */
3154 chip->chipsize = 1 << (fls(le32_to_cpu(p->blocks_per_lun)) - 1);
3155 chip->chipsize *= (uint64_t)mtd->erasesize * p->lun_count;
3156 chip->bits_per_cell = p->bits_per_cell;
3158 if (onfi_feature(chip) & ONFI_FEATURE_16_BIT_BUS)
3159 *busw = NAND_BUSWIDTH_16;
3160 else
3161 *busw = 0;
3163 if (p->ecc_bits != 0xff) {
3164 chip->ecc_strength_ds = p->ecc_bits;
3165 chip->ecc_step_ds = 512;
3166 } else if (chip->onfi_version >= 21 &&
3167 (onfi_feature(chip) & ONFI_FEATURE_EXT_PARAM_PAGE)) {
3170 * The nand_flash_detect_ext_param_page() uses the
3171 * Change Read Column command which maybe not supported
3172 * by the chip->cmdfunc. So try to update the chip->cmdfunc
3173 * now. We do not replace user supplied command function.
3175 if (mtd->writesize > 512 && chip->cmdfunc == nand_command)
3176 chip->cmdfunc = nand_command_lp;
3178 /* The Extended Parameter Page is supported since ONFI 2.1. */
3179 if (nand_flash_detect_ext_param_page(mtd, chip, p))
3180 pr_warn("Failed to detect ONFI extended param page\n");
3181 } else {
3182 pr_warn("Could not retrieve ONFI ECC requirements\n");
3185 if (p->jedec_id == NAND_MFR_MICRON)
3186 nand_onfi_detect_micron(chip, p);
3188 return 1;
3192 * Check if the NAND chip is JEDEC compliant, returns 1 if it is, 0 otherwise.
3194 static int nand_flash_detect_jedec(struct mtd_info *mtd, struct nand_chip *chip,
3195 int *busw)
3197 struct nand_jedec_params *p = &chip->jedec_params;
3198 struct jedec_ecc_info *ecc;
3199 int val;
3200 int i, j;
3202 /* Try JEDEC for unknown chip or LP */
3203 chip->cmdfunc(mtd, NAND_CMD_READID, 0x40, -1);
3204 if (chip->read_byte(mtd) != 'J' || chip->read_byte(mtd) != 'E' ||
3205 chip->read_byte(mtd) != 'D' || chip->read_byte(mtd) != 'E' ||
3206 chip->read_byte(mtd) != 'C')
3207 return 0;
3209 chip->cmdfunc(mtd, NAND_CMD_PARAM, 0x40, -1);
3210 for (i = 0; i < 3; i++) {
3211 for (j = 0; j < sizeof(*p); j++)
3212 ((uint8_t *)p)[j] = chip->read_byte(mtd);
3214 if (onfi_crc16(ONFI_CRC_BASE, (uint8_t *)p, 510) ==
3215 le16_to_cpu(p->crc))
3216 break;
3219 if (i == 3) {
3220 pr_err("Could not find valid JEDEC parameter page; aborting\n");
3221 return 0;
3224 /* Check version */
3225 val = le16_to_cpu(p->revision);
3226 if (val & (1 << 2))
3227 chip->jedec_version = 10;
3228 else if (val & (1 << 1))
3229 chip->jedec_version = 1; /* vendor specific version */
3231 if (!chip->jedec_version) {
3232 pr_info("unsupported JEDEC version: %d\n", val);
3233 return 0;
3236 sanitize_string(p->manufacturer, sizeof(p->manufacturer));
3237 sanitize_string(p->model, sizeof(p->model));
3238 if (!mtd->name)
3239 mtd->name = p->model;
3241 mtd->writesize = le32_to_cpu(p->byte_per_page);
3243 /* Please reference to the comment for nand_flash_detect_onfi. */
3244 mtd->erasesize = 1 << (fls(le32_to_cpu(p->pages_per_block)) - 1);
3245 mtd->erasesize *= mtd->writesize;
3247 mtd->oobsize = le16_to_cpu(p->spare_bytes_per_page);
3249 /* Please reference to the comment for nand_flash_detect_onfi. */
3250 chip->chipsize = 1 << (fls(le32_to_cpu(p->blocks_per_lun)) - 1);
3251 chip->chipsize *= (uint64_t)mtd->erasesize * p->lun_count;
3252 chip->bits_per_cell = p->bits_per_cell;
3254 if (jedec_feature(chip) & JEDEC_FEATURE_16_BIT_BUS)
3255 *busw = NAND_BUSWIDTH_16;
3256 else
3257 *busw = 0;
3259 /* ECC info */
3260 ecc = &p->ecc_info[0];
3262 if (ecc->codeword_size >= 9) {
3263 chip->ecc_strength_ds = ecc->ecc_bits;
3264 chip->ecc_step_ds = 1 << ecc->codeword_size;
3265 } else {
3266 pr_warn("Invalid codeword size\n");
3269 return 1;
3273 * nand_id_has_period - Check if an ID string has a given wraparound period
3274 * @id_data: the ID string
3275 * @arrlen: the length of the @id_data array
3276 * @period: the period of repitition
3278 * Check if an ID string is repeated within a given sequence of bytes at
3279 * specific repetition interval period (e.g., {0x20,0x01,0x7F,0x20} has a
3280 * period of 3). This is a helper function for nand_id_len(). Returns non-zero
3281 * if the repetition has a period of @period; otherwise, returns zero.
3283 static int nand_id_has_period(u8 *id_data, int arrlen, int period)
3285 int i, j;
3286 for (i = 0; i < period; i++)
3287 for (j = i + period; j < arrlen; j += period)
3288 if (id_data[i] != id_data[j])
3289 return 0;
3290 return 1;
3294 * nand_id_len - Get the length of an ID string returned by CMD_READID
3295 * @id_data: the ID string
3296 * @arrlen: the length of the @id_data array
3298 * Returns the length of the ID string, according to known wraparound/trailing
3299 * zero patterns. If no pattern exists, returns the length of the array.
3301 static int nand_id_len(u8 *id_data, int arrlen)
3303 int last_nonzero, period;
3305 /* Find last non-zero byte */
3306 for (last_nonzero = arrlen - 1; last_nonzero >= 0; last_nonzero--)
3307 if (id_data[last_nonzero])
3308 break;
3310 /* All zeros */
3311 if (last_nonzero < 0)
3312 return 0;
3314 /* Calculate wraparound period */
3315 for (period = 1; period < arrlen; period++)
3316 if (nand_id_has_period(id_data, arrlen, period))
3317 break;
3319 /* There's a repeated pattern */
3320 if (period < arrlen)
3321 return period;
3323 /* There are trailing zeros */
3324 if (last_nonzero < arrlen - 1)
3325 return last_nonzero + 1;
3327 /* No pattern detected */
3328 return arrlen;
3331 /* Extract the bits of per cell from the 3rd byte of the extended ID */
3332 static int nand_get_bits_per_cell(u8 cellinfo)
3334 int bits;
3336 bits = cellinfo & NAND_CI_CELLTYPE_MSK;
3337 bits >>= NAND_CI_CELLTYPE_SHIFT;
3338 return bits + 1;
3342 * Many new NAND share similar device ID codes, which represent the size of the
3343 * chip. The rest of the parameters must be decoded according to generic or
3344 * manufacturer-specific "extended ID" decoding patterns.
3346 static void nand_decode_ext_id(struct mtd_info *mtd, struct nand_chip *chip,
3347 u8 id_data[8], int *busw)
3349 int extid, id_len;
3350 /* The 3rd id byte holds MLC / multichip data */
3351 chip->bits_per_cell = nand_get_bits_per_cell(id_data[2]);
3352 /* The 4th id byte is the important one */
3353 extid = id_data[3];
3355 id_len = nand_id_len(id_data, 8);
3358 * Field definitions are in the following datasheets:
3359 * Old style (4,5 byte ID): Samsung K9GAG08U0M (p.32)
3360 * New Samsung (6 byte ID): Samsung K9GAG08U0F (p.44)
3361 * Hynix MLC (6 byte ID): Hynix H27UBG8T2B (p.22)
3363 * Check for ID length, non-zero 6th byte, cell type, and Hynix/Samsung
3364 * ID to decide what to do.
3366 if (id_len == 6 && id_data[0] == NAND_MFR_SAMSUNG &&
3367 !nand_is_slc(chip) && id_data[5] != 0x00) {
3368 /* Calc pagesize */
3369 mtd->writesize = 2048 << (extid & 0x03);
3370 extid >>= 2;
3371 /* Calc oobsize */
3372 switch (((extid >> 2) & 0x04) | (extid & 0x03)) {
3373 case 1:
3374 mtd->oobsize = 128;
3375 break;
3376 case 2:
3377 mtd->oobsize = 218;
3378 break;
3379 case 3:
3380 mtd->oobsize = 400;
3381 break;
3382 case 4:
3383 mtd->oobsize = 436;
3384 break;
3385 case 5:
3386 mtd->oobsize = 512;
3387 break;
3388 case 6:
3389 mtd->oobsize = 640;
3390 break;
3391 case 7:
3392 default: /* Other cases are "reserved" (unknown) */
3393 mtd->oobsize = 1024;
3394 break;
3396 extid >>= 2;
3397 /* Calc blocksize */
3398 mtd->erasesize = (128 * 1024) <<
3399 (((extid >> 1) & 0x04) | (extid & 0x03));
3400 *busw = 0;
3401 } else if (id_len == 6 && id_data[0] == NAND_MFR_HYNIX &&
3402 !nand_is_slc(chip)) {
3403 unsigned int tmp;
3405 /* Calc pagesize */
3406 mtd->writesize = 2048 << (extid & 0x03);
3407 extid >>= 2;
3408 /* Calc oobsize */
3409 switch (((extid >> 2) & 0x04) | (extid & 0x03)) {
3410 case 0:
3411 mtd->oobsize = 128;
3412 break;
3413 case 1:
3414 mtd->oobsize = 224;
3415 break;
3416 case 2:
3417 mtd->oobsize = 448;
3418 break;
3419 case 3:
3420 mtd->oobsize = 64;
3421 break;
3422 case 4:
3423 mtd->oobsize = 32;
3424 break;
3425 case 5:
3426 mtd->oobsize = 16;
3427 break;
3428 default:
3429 mtd->oobsize = 640;
3430 break;
3432 extid >>= 2;
3433 /* Calc blocksize */
3434 tmp = ((extid >> 1) & 0x04) | (extid & 0x03);
3435 if (tmp < 0x03)
3436 mtd->erasesize = (128 * 1024) << tmp;
3437 else if (tmp == 0x03)
3438 mtd->erasesize = 768 * 1024;
3439 else
3440 mtd->erasesize = (64 * 1024) << tmp;
3441 *busw = 0;
3442 } else {
3443 /* Calc pagesize */
3444 mtd->writesize = 1024 << (extid & 0x03);
3445 extid >>= 2;
3446 /* Calc oobsize */
3447 mtd->oobsize = (8 << (extid & 0x01)) *
3448 (mtd->writesize >> 9);
3449 extid >>= 2;
3450 /* Calc blocksize. Blocksize is multiples of 64KiB */
3451 mtd->erasesize = (64 * 1024) << (extid & 0x03);
3452 extid >>= 2;
3453 /* Get buswidth information */
3454 *busw = (extid & 0x01) ? NAND_BUSWIDTH_16 : 0;
3457 * Toshiba 24nm raw SLC (i.e., not BENAND) have 32B OOB per
3458 * 512B page. For Toshiba SLC, we decode the 5th/6th byte as
3459 * follows:
3460 * - ID byte 6, bits[2:0]: 100b -> 43nm, 101b -> 32nm,
3461 * 110b -> 24nm
3462 * - ID byte 5, bit[7]: 1 -> BENAND, 0 -> raw SLC
3464 if (id_len >= 6 && id_data[0] == NAND_MFR_TOSHIBA &&
3465 nand_is_slc(chip) &&
3466 (id_data[5] & 0x7) == 0x6 /* 24nm */ &&
3467 !(id_data[4] & 0x80) /* !BENAND */) {
3468 mtd->oobsize = 32 * mtd->writesize >> 9;
3475 * Old devices have chip data hardcoded in the device ID table. nand_decode_id
3476 * decodes a matching ID table entry and assigns the MTD size parameters for
3477 * the chip.
3479 static void nand_decode_id(struct mtd_info *mtd, struct nand_chip *chip,
3480 struct nand_flash_dev *type, u8 id_data[8],
3481 int *busw)
3483 int maf_id = id_data[0];
3485 mtd->erasesize = type->erasesize;
3486 mtd->writesize = type->pagesize;
3487 mtd->oobsize = mtd->writesize / 32;
3488 *busw = type->options & NAND_BUSWIDTH_16;
3490 /* All legacy ID NAND are small-page, SLC */
3491 chip->bits_per_cell = 1;
3494 * Check for Spansion/AMD ID + repeating 5th, 6th byte since
3495 * some Spansion chips have erasesize that conflicts with size
3496 * listed in nand_ids table.
3497 * Data sheet (5 byte ID): Spansion S30ML-P ORNAND (p.39)
3499 if (maf_id == NAND_MFR_AMD && id_data[4] != 0x00 && id_data[5] == 0x00
3500 && id_data[6] == 0x00 && id_data[7] == 0x00
3501 && mtd->writesize == 512) {
3502 mtd->erasesize = 128 * 1024;
3503 mtd->erasesize <<= ((id_data[3] & 0x03) << 1);
3508 * Set the bad block marker/indicator (BBM/BBI) patterns according to some
3509 * heuristic patterns using various detected parameters (e.g., manufacturer,
3510 * page size, cell-type information).
3512 static void nand_decode_bbm_options(struct mtd_info *mtd,
3513 struct nand_chip *chip, u8 id_data[8])
3515 int maf_id = id_data[0];
3517 /* Set the bad block position */
3518 if (mtd->writesize > 512 || (chip->options & NAND_BUSWIDTH_16))
3519 chip->badblockpos = NAND_LARGE_BADBLOCK_POS;
3520 else
3521 chip->badblockpos = NAND_SMALL_BADBLOCK_POS;
3524 * Bad block marker is stored in the last page of each block on Samsung
3525 * and Hynix MLC devices; stored in first two pages of each block on
3526 * Micron devices with 2KiB pages and on SLC Samsung, Hynix, Toshiba,
3527 * AMD/Spansion, and Macronix. All others scan only the first page.
3529 if (!nand_is_slc(chip) &&
3530 (maf_id == NAND_MFR_SAMSUNG ||
3531 maf_id == NAND_MFR_HYNIX))
3532 chip->bbt_options |= NAND_BBT_SCANLASTPAGE;
3533 else if ((nand_is_slc(chip) &&
3534 (maf_id == NAND_MFR_SAMSUNG ||
3535 maf_id == NAND_MFR_HYNIX ||
3536 maf_id == NAND_MFR_TOSHIBA ||
3537 maf_id == NAND_MFR_AMD ||
3538 maf_id == NAND_MFR_MACRONIX)) ||
3539 (mtd->writesize == 2048 &&
3540 maf_id == NAND_MFR_MICRON))
3541 chip->bbt_options |= NAND_BBT_SCAN2NDPAGE;
3544 static inline bool is_full_id_nand(struct nand_flash_dev *type)
3546 return type->id_len;
3549 static bool find_full_id_nand(struct mtd_info *mtd, struct nand_chip *chip,
3550 struct nand_flash_dev *type, u8 *id_data, int *busw)
3552 if (!strncmp(type->id, id_data, type->id_len)) {
3553 mtd->writesize = type->pagesize;
3554 mtd->erasesize = type->erasesize;
3555 mtd->oobsize = type->oobsize;
3557 chip->bits_per_cell = nand_get_bits_per_cell(id_data[2]);
3558 chip->chipsize = (uint64_t)type->chipsize << 20;
3559 chip->options |= type->options;
3560 chip->ecc_strength_ds = NAND_ECC_STRENGTH(type);
3561 chip->ecc_step_ds = NAND_ECC_STEP(type);
3563 *busw = type->options & NAND_BUSWIDTH_16;
3565 if (!mtd->name)
3566 mtd->name = type->name;
3568 return true;
3570 return false;
3574 * Get the flash and manufacturer id and lookup if the type is supported.
3576 static struct nand_flash_dev *nand_get_flash_type(struct mtd_info *mtd,
3577 struct nand_chip *chip,
3578 int *maf_id, int *dev_id,
3579 struct nand_flash_dev *type)
3581 int busw;
3582 int i, maf_idx;
3583 u8 id_data[8];
3585 /* Select the device */
3586 chip->select_chip(mtd, 0);
3589 * Reset the chip, required by some chips (e.g. Micron MT29FxGxxxxx)
3590 * after power-up.
3592 chip->cmdfunc(mtd, NAND_CMD_RESET, -1, -1);
3594 /* Send the command for reading device ID */
3595 chip->cmdfunc(mtd, NAND_CMD_READID, 0x00, -1);
3597 /* Read manufacturer and device IDs */
3598 *maf_id = chip->read_byte(mtd);
3599 *dev_id = chip->read_byte(mtd);
3602 * Try again to make sure, as some systems the bus-hold or other
3603 * interface concerns can cause random data which looks like a
3604 * possibly credible NAND flash to appear. If the two results do
3605 * not match, ignore the device completely.
3608 chip->cmdfunc(mtd, NAND_CMD_READID, 0x00, -1);
3610 /* Read entire ID string */
3611 for (i = 0; i < 8; i++)
3612 id_data[i] = chip->read_byte(mtd);
3614 if (id_data[0] != *maf_id || id_data[1] != *dev_id) {
3615 pr_info("second ID read did not match %02x,%02x against %02x,%02x\n",
3616 *maf_id, *dev_id, id_data[0], id_data[1]);
3617 return ERR_PTR(-ENODEV);
3620 if (!type)
3621 type = nand_flash_ids;
3623 for (; type->name != NULL; type++) {
3624 if (is_full_id_nand(type)) {
3625 if (find_full_id_nand(mtd, chip, type, id_data, &busw))
3626 goto ident_done;
3627 } else if (*dev_id == type->dev_id) {
3628 break;
3632 chip->onfi_version = 0;
3633 if (!type->name || !type->pagesize) {
3634 /* Check if the chip is ONFI compliant */
3635 if (nand_flash_detect_onfi(mtd, chip, &busw))
3636 goto ident_done;
3638 /* Check if the chip is JEDEC compliant */
3639 if (nand_flash_detect_jedec(mtd, chip, &busw))
3640 goto ident_done;
3643 if (!type->name)
3644 return ERR_PTR(-ENODEV);
3646 if (!mtd->name)
3647 mtd->name = type->name;
3649 chip->chipsize = (uint64_t)type->chipsize << 20;
3651 if (!type->pagesize && chip->init_size) {
3652 /* Set the pagesize, oobsize, erasesize by the driver */
3653 busw = chip->init_size(mtd, chip, id_data);
3654 } else if (!type->pagesize) {
3655 /* Decode parameters from extended ID */
3656 nand_decode_ext_id(mtd, chip, id_data, &busw);
3657 } else {
3658 nand_decode_id(mtd, chip, type, id_data, &busw);
3660 /* Get chip options */
3661 chip->options |= type->options;
3664 * Check if chip is not a Samsung device. Do not clear the
3665 * options for chips which do not have an extended id.
3667 if (*maf_id != NAND_MFR_SAMSUNG && !type->pagesize)
3668 chip->options &= ~NAND_SAMSUNG_LP_OPTIONS;
3669 ident_done:
3671 /* Try to identify manufacturer */
3672 for (maf_idx = 0; nand_manuf_ids[maf_idx].id != 0x0; maf_idx++) {
3673 if (nand_manuf_ids[maf_idx].id == *maf_id)
3674 break;
3677 if (chip->options & NAND_BUSWIDTH_AUTO) {
3678 WARN_ON(chip->options & NAND_BUSWIDTH_16);
3679 chip->options |= busw;
3680 nand_set_defaults(chip, busw);
3681 } else if (busw != (chip->options & NAND_BUSWIDTH_16)) {
3683 * Check, if buswidth is correct. Hardware drivers should set
3684 * chip correct!
3686 pr_info("device found, Manufacturer ID: 0x%02x, Chip ID: 0x%02x\n",
3687 *maf_id, *dev_id);
3688 pr_info("%s %s\n", nand_manuf_ids[maf_idx].name, mtd->name);
3689 pr_warn("bus width %d instead %d bit\n",
3690 (chip->options & NAND_BUSWIDTH_16) ? 16 : 8,
3691 busw ? 16 : 8);
3692 return ERR_PTR(-EINVAL);
3695 nand_decode_bbm_options(mtd, chip, id_data);
3697 /* Calculate the address shift from the page size */
3698 chip->page_shift = ffs(mtd->writesize) - 1;
3699 /* Convert chipsize to number of pages per chip -1 */
3700 chip->pagemask = (chip->chipsize >> chip->page_shift) - 1;
3702 chip->bbt_erase_shift = chip->phys_erase_shift =
3703 ffs(mtd->erasesize) - 1;
3704 if (chip->chipsize & 0xffffffff)
3705 chip->chip_shift = ffs((unsigned)chip->chipsize) - 1;
3706 else {
3707 chip->chip_shift = ffs((unsigned)(chip->chipsize >> 32));
3708 chip->chip_shift += 32 - 1;
3711 chip->badblockbits = 8;
3712 chip->erase = single_erase;
3714 /* Do not replace user supplied command function! */
3715 if (mtd->writesize > 512 && chip->cmdfunc == nand_command)
3716 chip->cmdfunc = nand_command_lp;
3718 pr_info("device found, Manufacturer ID: 0x%02x, Chip ID: 0x%02x\n",
3719 *maf_id, *dev_id);
3721 if (chip->onfi_version)
3722 pr_info("%s %s\n", nand_manuf_ids[maf_idx].name,
3723 chip->onfi_params.model);
3724 else if (chip->jedec_version)
3725 pr_info("%s %s\n", nand_manuf_ids[maf_idx].name,
3726 chip->jedec_params.model);
3727 else
3728 pr_info("%s %s\n", nand_manuf_ids[maf_idx].name,
3729 type->name);
3731 pr_info("%dMiB, %s, page size: %d, OOB size: %d\n",
3732 (int)(chip->chipsize >> 20), nand_is_slc(chip) ? "SLC" : "MLC",
3733 mtd->writesize, mtd->oobsize);
3734 return type;
3738 * nand_scan_ident - [NAND Interface] Scan for the NAND device
3739 * @mtd: MTD device structure
3740 * @maxchips: number of chips to scan for
3741 * @table: alternative NAND ID table
3743 * This is the first phase of the normal nand_scan() function. It reads the
3744 * flash ID and sets up MTD fields accordingly.
3746 * The mtd->owner field must be set to the module of the caller.
3748 int nand_scan_ident(struct mtd_info *mtd, int maxchips,
3749 struct nand_flash_dev *table)
3751 int i, nand_maf_id, nand_dev_id;
3752 struct nand_chip *chip = mtd->priv;
3753 struct nand_flash_dev *type;
3755 /* Set the default functions */
3756 nand_set_defaults(chip, chip->options & NAND_BUSWIDTH_16);
3758 /* Read the flash type */
3759 type = nand_get_flash_type(mtd, chip, &nand_maf_id,
3760 &nand_dev_id, table);
3762 if (IS_ERR(type)) {
3763 if (!(chip->options & NAND_SCAN_SILENT_NODEV))
3764 pr_warn("No NAND device found\n");
3765 chip->select_chip(mtd, -1);
3766 return PTR_ERR(type);
3769 chip->select_chip(mtd, -1);
3771 /* Check for a chip array */
3772 for (i = 1; i < maxchips; i++) {
3773 chip->select_chip(mtd, i);
3774 /* See comment in nand_get_flash_type for reset */
3775 chip->cmdfunc(mtd, NAND_CMD_RESET, -1, -1);
3776 /* Send the command for reading device ID */
3777 chip->cmdfunc(mtd, NAND_CMD_READID, 0x00, -1);
3778 /* Read manufacturer and device IDs */
3779 if (nand_maf_id != chip->read_byte(mtd) ||
3780 nand_dev_id != chip->read_byte(mtd)) {
3781 chip->select_chip(mtd, -1);
3782 break;
3784 chip->select_chip(mtd, -1);
3786 if (i > 1)
3787 pr_info("%d chips detected\n", i);
3789 /* Store the number of chips and calc total size for mtd */
3790 chip->numchips = i;
3791 mtd->size = i * chip->chipsize;
3793 return 0;
3795 EXPORT_SYMBOL(nand_scan_ident);
3798 * Check if the chip configuration meet the datasheet requirements.
3800 * If our configuration corrects A bits per B bytes and the minimum
3801 * required correction level is X bits per Y bytes, then we must ensure
3802 * both of the following are true:
3804 * (1) A / B >= X / Y
3805 * (2) A >= X
3807 * Requirement (1) ensures we can correct for the required bitflip density.
3808 * Requirement (2) ensures we can correct even when all bitflips are clumped
3809 * in the same sector.
3811 static bool nand_ecc_strength_good(struct mtd_info *mtd)
3813 struct nand_chip *chip = mtd->priv;
3814 struct nand_ecc_ctrl *ecc = &chip->ecc;
3815 int corr, ds_corr;
3817 if (ecc->size == 0 || chip->ecc_step_ds == 0)
3818 /* Not enough information */
3819 return true;
3822 * We get the number of corrected bits per page to compare
3823 * the correction density.
3825 corr = (mtd->writesize * ecc->strength) / ecc->size;
3826 ds_corr = (mtd->writesize * chip->ecc_strength_ds) / chip->ecc_step_ds;
3828 return corr >= ds_corr && ecc->strength >= chip->ecc_strength_ds;
3832 * nand_scan_tail - [NAND Interface] Scan for the NAND device
3833 * @mtd: MTD device structure
3835 * This is the second phase of the normal nand_scan() function. It fills out
3836 * all the uninitialized function pointers with the defaults and scans for a
3837 * bad block table if appropriate.
3839 int nand_scan_tail(struct mtd_info *mtd)
3841 int i;
3842 struct nand_chip *chip = mtd->priv;
3843 struct nand_ecc_ctrl *ecc = &chip->ecc;
3844 struct nand_buffers *nbuf;
3846 /* New bad blocks should be marked in OOB, flash-based BBT, or both */
3847 BUG_ON((chip->bbt_options & NAND_BBT_NO_OOB_BBM) &&
3848 !(chip->bbt_options & NAND_BBT_USE_FLASH));
3850 if (!(chip->options & NAND_OWN_BUFFERS)) {
3851 nbuf = kzalloc(sizeof(*nbuf) + mtd->writesize
3852 + mtd->oobsize * 3, GFP_KERNEL);
3853 if (!nbuf)
3854 return -ENOMEM;
3855 nbuf->ecccalc = (uint8_t *)(nbuf + 1);
3856 nbuf->ecccode = nbuf->ecccalc + mtd->oobsize;
3857 nbuf->databuf = nbuf->ecccode + mtd->oobsize;
3859 chip->buffers = nbuf;
3860 } else {
3861 if (!chip->buffers)
3862 return -ENOMEM;
3865 /* Set the internal oob buffer location, just after the page data */
3866 chip->oob_poi = chip->buffers->databuf + mtd->writesize;
3869 * If no default placement scheme is given, select an appropriate one.
3871 if (!ecc->layout && (ecc->mode != NAND_ECC_SOFT_BCH)) {
3872 switch (mtd->oobsize) {
3873 case 8:
3874 ecc->layout = &nand_oob_8;
3875 break;
3876 case 16:
3877 ecc->layout = &nand_oob_16;
3878 break;
3879 case 64:
3880 ecc->layout = &nand_oob_64;
3881 break;
3882 case 128:
3883 ecc->layout = &nand_oob_128;
3884 break;
3885 default:
3886 pr_warn("No oob scheme defined for oobsize %d\n",
3887 mtd->oobsize);
3888 BUG();
3892 if (!chip->write_page)
3893 chip->write_page = nand_write_page;
3896 * Check ECC mode, default to software if 3byte/512byte hardware ECC is
3897 * selected and we have 256 byte pagesize fallback to software ECC
3900 switch (ecc->mode) {
3901 case NAND_ECC_HW_OOB_FIRST:
3902 /* Similar to NAND_ECC_HW, but a separate read_page handle */
3903 if (!ecc->calculate || !ecc->correct || !ecc->hwctl) {
3904 pr_warn("No ECC functions supplied; "
3905 "hardware ECC not possible\n");
3906 BUG();
3908 if (!ecc->read_page)
3909 ecc->read_page = nand_read_page_hwecc_oob_first;
3911 case NAND_ECC_HW:
3912 /* Use standard hwecc read page function? */
3913 if (!ecc->read_page)
3914 ecc->read_page = nand_read_page_hwecc;
3915 if (!ecc->write_page)
3916 ecc->write_page = nand_write_page_hwecc;
3917 if (!ecc->read_page_raw)
3918 ecc->read_page_raw = nand_read_page_raw;
3919 if (!ecc->write_page_raw)
3920 ecc->write_page_raw = nand_write_page_raw;
3921 if (!ecc->read_oob)
3922 ecc->read_oob = nand_read_oob_std;
3923 if (!ecc->write_oob)
3924 ecc->write_oob = nand_write_oob_std;
3925 if (!ecc->read_subpage)
3926 ecc->read_subpage = nand_read_subpage;
3927 if (!ecc->write_subpage)
3928 ecc->write_subpage = nand_write_subpage_hwecc;
3930 case NAND_ECC_HW_SYNDROME:
3931 if ((!ecc->calculate || !ecc->correct || !ecc->hwctl) &&
3932 (!ecc->read_page ||
3933 ecc->read_page == nand_read_page_hwecc ||
3934 !ecc->write_page ||
3935 ecc->write_page == nand_write_page_hwecc)) {
3936 pr_warn("No ECC functions supplied; "
3937 "hardware ECC not possible\n");
3938 BUG();
3940 /* Use standard syndrome read/write page function? */
3941 if (!ecc->read_page)
3942 ecc->read_page = nand_read_page_syndrome;
3943 if (!ecc->write_page)
3944 ecc->write_page = nand_write_page_syndrome;
3945 if (!ecc->read_page_raw)
3946 ecc->read_page_raw = nand_read_page_raw_syndrome;
3947 if (!ecc->write_page_raw)
3948 ecc->write_page_raw = nand_write_page_raw_syndrome;
3949 if (!ecc->read_oob)
3950 ecc->read_oob = nand_read_oob_syndrome;
3951 if (!ecc->write_oob)
3952 ecc->write_oob = nand_write_oob_syndrome;
3954 if (mtd->writesize >= ecc->size) {
3955 if (!ecc->strength) {
3956 pr_warn("Driver must set ecc.strength when using hardware ECC\n");
3957 BUG();
3959 break;
3961 pr_warn("%d byte HW ECC not possible on "
3962 "%d byte page size, fallback to SW ECC\n",
3963 ecc->size, mtd->writesize);
3964 ecc->mode = NAND_ECC_SOFT;
3966 case NAND_ECC_SOFT:
3967 ecc->calculate = nand_calculate_ecc;
3968 ecc->correct = nand_correct_data;
3969 ecc->read_page = nand_read_page_swecc;
3970 ecc->read_subpage = nand_read_subpage;
3971 ecc->write_page = nand_write_page_swecc;
3972 ecc->read_page_raw = nand_read_page_raw;
3973 ecc->write_page_raw = nand_write_page_raw;
3974 ecc->read_oob = nand_read_oob_std;
3975 ecc->write_oob = nand_write_oob_std;
3976 if (!ecc->size)
3977 ecc->size = 256;
3978 ecc->bytes = 3;
3979 ecc->strength = 1;
3980 break;
3982 case NAND_ECC_SOFT_BCH:
3983 if (!mtd_nand_has_bch()) {
3984 pr_warn("CONFIG_MTD_NAND_ECC_BCH not enabled\n");
3985 BUG();
3987 ecc->calculate = nand_bch_calculate_ecc;
3988 ecc->correct = nand_bch_correct_data;
3989 ecc->read_page = nand_read_page_swecc;
3990 ecc->read_subpage = nand_read_subpage;
3991 ecc->write_page = nand_write_page_swecc;
3992 ecc->read_page_raw = nand_read_page_raw;
3993 ecc->write_page_raw = nand_write_page_raw;
3994 ecc->read_oob = nand_read_oob_std;
3995 ecc->write_oob = nand_write_oob_std;
3997 * Board driver should supply ecc.size and ecc.bytes values to
3998 * select how many bits are correctable; see nand_bch_init()
3999 * for details. Otherwise, default to 4 bits for large page
4000 * devices.
4002 if (!ecc->size && (mtd->oobsize >= 64)) {
4003 ecc->size = 512;
4004 ecc->bytes = 7;
4006 ecc->priv = nand_bch_init(mtd, ecc->size, ecc->bytes,
4007 &ecc->layout);
4008 if (!ecc->priv) {
4009 pr_warn("BCH ECC initialization failed!\n");
4010 BUG();
4012 ecc->strength = ecc->bytes * 8 / fls(8 * ecc->size);
4013 break;
4015 case NAND_ECC_NONE:
4016 pr_warn("NAND_ECC_NONE selected by board driver. "
4017 "This is not recommended!\n");
4018 ecc->read_page = nand_read_page_raw;
4019 ecc->write_page = nand_write_page_raw;
4020 ecc->read_oob = nand_read_oob_std;
4021 ecc->read_page_raw = nand_read_page_raw;
4022 ecc->write_page_raw = nand_write_page_raw;
4023 ecc->write_oob = nand_write_oob_std;
4024 ecc->size = mtd->writesize;
4025 ecc->bytes = 0;
4026 ecc->strength = 0;
4027 break;
4029 default:
4030 pr_warn("Invalid NAND_ECC_MODE %d\n", ecc->mode);
4031 BUG();
4034 /* For many systems, the standard OOB write also works for raw */
4035 if (!ecc->read_oob_raw)
4036 ecc->read_oob_raw = ecc->read_oob;
4037 if (!ecc->write_oob_raw)
4038 ecc->write_oob_raw = ecc->write_oob;
4041 * The number of bytes available for a client to place data into
4042 * the out of band area.
4044 ecc->layout->oobavail = 0;
4045 for (i = 0; ecc->layout->oobfree[i].length
4046 && i < ARRAY_SIZE(ecc->layout->oobfree); i++)
4047 ecc->layout->oobavail += ecc->layout->oobfree[i].length;
4048 mtd->oobavail = ecc->layout->oobavail;
4050 /* ECC sanity check: warn noisily if it's too weak */
4051 WARN_ON(!nand_ecc_strength_good(mtd));
4054 * Set the number of read / write steps for one page depending on ECC
4055 * mode.
4057 ecc->steps = mtd->writesize / ecc->size;
4058 if (ecc->steps * ecc->size != mtd->writesize) {
4059 pr_warn("Invalid ECC parameters\n");
4060 BUG();
4062 ecc->total = ecc->steps * ecc->bytes;
4064 /* Allow subpage writes up to ecc.steps. Not possible for MLC flash */
4065 if (!(chip->options & NAND_NO_SUBPAGE_WRITE) && nand_is_slc(chip)) {
4066 switch (ecc->steps) {
4067 case 2:
4068 mtd->subpage_sft = 1;
4069 break;
4070 case 4:
4071 case 8:
4072 case 16:
4073 mtd->subpage_sft = 2;
4074 break;
4077 chip->subpagesize = mtd->writesize >> mtd->subpage_sft;
4079 /* Initialize state */
4080 chip->state = FL_READY;
4082 /* Invalidate the pagebuffer reference */
4083 chip->pagebuf = -1;
4085 /* Large page NAND with SOFT_ECC should support subpage reads */
4086 switch (ecc->mode) {
4087 case NAND_ECC_SOFT:
4088 case NAND_ECC_SOFT_BCH:
4089 if (chip->page_shift > 9)
4090 chip->options |= NAND_SUBPAGE_READ;
4091 break;
4093 default:
4094 break;
4097 /* Fill in remaining MTD driver data */
4098 mtd->type = nand_is_slc(chip) ? MTD_NANDFLASH : MTD_MLCNANDFLASH;
4099 mtd->flags = (chip->options & NAND_ROM) ? MTD_CAP_ROM :
4100 MTD_CAP_NANDFLASH;
4101 mtd->_erase = nand_erase;
4102 mtd->_point = NULL;
4103 mtd->_unpoint = NULL;
4104 mtd->_read = nand_read;
4105 mtd->_write = nand_write;
4106 mtd->_panic_write = panic_nand_write;
4107 mtd->_read_oob = nand_read_oob;
4108 mtd->_write_oob = nand_write_oob;
4109 mtd->_sync = nand_sync;
4110 mtd->_lock = NULL;
4111 mtd->_unlock = NULL;
4112 mtd->_suspend = nand_suspend;
4113 mtd->_resume = nand_resume;
4114 mtd->_block_isbad = nand_block_isbad;
4115 mtd->_block_markbad = nand_block_markbad;
4116 mtd->writebufsize = mtd->writesize;
4118 /* propagate ecc info to mtd_info */
4119 mtd->ecclayout = ecc->layout;
4120 mtd->ecc_strength = ecc->strength;
4121 mtd->ecc_step_size = ecc->size;
4123 * Initialize bitflip_threshold to its default prior scan_bbt() call.
4124 * scan_bbt() might invoke mtd_read(), thus bitflip_threshold must be
4125 * properly set.
4127 if (!mtd->bitflip_threshold)
4128 mtd->bitflip_threshold = mtd->ecc_strength;
4130 /* Check, if we should skip the bad block table scan */
4131 if (chip->options & NAND_SKIP_BBTSCAN)
4132 return 0;
4134 /* Build bad block table */
4135 return chip->scan_bbt(mtd);
4137 EXPORT_SYMBOL(nand_scan_tail);
4140 * is_module_text_address() isn't exported, and it's mostly a pointless
4141 * test if this is a module _anyway_ -- they'd have to try _really_ hard
4142 * to call us from in-kernel code if the core NAND support is modular.
4144 #ifdef MODULE
4145 #define caller_is_module() (1)
4146 #else
4147 #define caller_is_module() \
4148 is_module_text_address((unsigned long)__builtin_return_address(0))
4149 #endif
4152 * nand_scan - [NAND Interface] Scan for the NAND device
4153 * @mtd: MTD device structure
4154 * @maxchips: number of chips to scan for
4156 * This fills out all the uninitialized function pointers with the defaults.
4157 * The flash ID is read and the mtd/chip structures are filled with the
4158 * appropriate values. The mtd->owner field must be set to the module of the
4159 * caller.
4161 int nand_scan(struct mtd_info *mtd, int maxchips)
4163 int ret;
4165 /* Many callers got this wrong, so check for it for a while... */
4166 if (!mtd->owner && caller_is_module()) {
4167 pr_crit("%s called with NULL mtd->owner!\n", __func__);
4168 BUG();
4171 ret = nand_scan_ident(mtd, maxchips, NULL);
4172 if (!ret)
4173 ret = nand_scan_tail(mtd);
4174 return ret;
4176 EXPORT_SYMBOL(nand_scan);
4179 * nand_release - [NAND Interface] Free resources held by the NAND device
4180 * @mtd: MTD device structure
4182 void nand_release(struct mtd_info *mtd)
4184 struct nand_chip *chip = mtd->priv;
4186 if (chip->ecc.mode == NAND_ECC_SOFT_BCH)
4187 nand_bch_free((struct nand_bch_control *)chip->ecc.priv);
4189 mtd_device_unregister(mtd);
4191 /* Free bad block table memory */
4192 kfree(chip->bbt);
4193 if (!(chip->options & NAND_OWN_BUFFERS))
4194 kfree(chip->buffers);
4196 /* Free bad block descriptor memory */
4197 if (chip->badblock_pattern && chip->badblock_pattern->options
4198 & NAND_BBT_DYNAMICSTRUCT)
4199 kfree(chip->badblock_pattern);
4201 EXPORT_SYMBOL_GPL(nand_release);
4203 static int __init nand_base_init(void)
4205 led_trigger_register_simple("nand-disk", &nand_led_trigger);
4206 return 0;
4209 static void __exit nand_base_exit(void)
4211 led_trigger_unregister_simple(nand_led_trigger);
4214 module_init(nand_base_init);
4215 module_exit(nand_base_exit);
4217 MODULE_LICENSE("GPL");
4218 MODULE_AUTHOR("Steven J. Hill <sjhill@realitydiluted.com>");
4219 MODULE_AUTHOR("Thomas Gleixner <tglx@linutronix.de>");
4220 MODULE_DESCRIPTION("Generic NAND flash driver code");