]> git.ipfire.org Git - thirdparty/u-boot.git/blob - drivers/mtd/nand/raw/nand_base.c
Merge patch series "nand: Add sandbox tests"
[thirdparty/u-boot.git] / drivers / mtd / nand / raw / nand_base.c
1 /*
2 * Overview:
3 * This is the generic MTD driver for NAND flash devices. It should be
4 * capable of working with almost all NAND chips currently available.
5 *
6 * Additional technical information is available on
7 * http://www.linux-mtd.infradead.org/doc/nand.html
8 *
9 * Copyright (C) 2000 Steven J. Hill (sjhill@realitydiluted.com)
10 * 2002-2006 Thomas Gleixner (tglx@linutronix.de)
11 *
12 * Credits:
13 * David Woodhouse for adding multichip support
14 *
15 * Aleph One Ltd. and Toby Churchill Ltd. for supporting the
16 * rework for 2K page size chips
17 *
18 * TODO:
19 * Enable cached programming for 2k page size chips
20 * Check, if mtd->ecctype should be set to MTD_ECC_HW
21 * if we have HW ECC support.
22 * BBT table is not serialized, has to be fixed
23 *
24 * This program is free software; you can redistribute it and/or modify
25 * it under the terms of the GNU General Public License version 2 as
26 * published by the Free Software Foundation.
27 *
28 */
29
30 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
31 #include <common.h>
32 #include <log.h>
33 #include <malloc.h>
34 #include <watchdog.h>
35 #include <dm/devres.h>
36 #include <linux/bitops.h>
37 #include <linux/bug.h>
38 #include <linux/delay.h>
39 #include <linux/err.h>
40 #include <linux/compat.h>
41 #include <linux/mtd/mtd.h>
42 #include <linux/mtd/rawnand.h>
43 #include <linux/mtd/nand_ecc.h>
44 #include <linux/mtd/nand_bch.h>
45 #ifdef CONFIG_MTD_PARTITIONS
46 #include <linux/mtd/partitions.h>
47 #endif
48 #include <asm/io.h>
49 #include <linux/errno.h>
50
51 /* Define default oob placement schemes for large and small page devices */
52 #ifndef CONFIG_SYS_NAND_DRIVER_ECC_LAYOUT
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} }
61 };
62
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} }
69 };
70
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} }
80 };
81
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} }
94 };
95 #endif
96
97 static int nand_get_device(struct mtd_info *mtd, int new_state);
98
99 static int nand_do_write_oob(struct mtd_info *mtd, loff_t to,
100 struct mtd_oob_ops *ops);
101
102 /*
103 * For devices which display every fart in the system on a separate LED. Is
104 * compiled away when LED support is disabled.
105 */
106 DEFINE_LED_TRIGGER(nand_led_trigger);
107
108 static int check_offs_len(struct mtd_info *mtd,
109 loff_t ofs, uint64_t len)
110 {
111 struct nand_chip *chip = mtd_to_nand(mtd);
112 int ret = 0;
113
114 /* Start address must align on block boundary */
115 if (ofs & ((1ULL << chip->phys_erase_shift) - 1)) {
116 pr_debug("%s: unaligned address\n", __func__);
117 ret = -EINVAL;
118 }
119
120 /* Length must align on block boundary */
121 if (len & ((1ULL << chip->phys_erase_shift) - 1)) {
122 pr_debug("%s: length not block aligned\n", __func__);
123 ret = -EINVAL;
124 }
125
126 return ret;
127 }
128
129 /**
130 * nand_release_device - [GENERIC] release chip
131 * @mtd: MTD device structure
132 *
133 * Release chip lock and wake up anyone waiting on the device.
134 */
135 static void nand_release_device(struct mtd_info *mtd)
136 {
137 struct nand_chip *chip = mtd_to_nand(mtd);
138
139 /* De-select the NAND device */
140 chip->select_chip(mtd, -1);
141 }
142
143 /**
144 * nand_read_byte - [DEFAULT] read one byte from the chip
145 * @mtd: MTD device structure
146 *
147 * Default read function for 8bit buswidth
148 */
149 uint8_t nand_read_byte(struct mtd_info *mtd)
150 {
151 struct nand_chip *chip = mtd_to_nand(mtd);
152 return readb(chip->IO_ADDR_R);
153 }
154
155 /**
156 * nand_read_byte16 - [DEFAULT] read one byte endianness aware from the chip
157 * @mtd: MTD device structure
158 *
159 * Default read function for 16bit buswidth with endianness conversion.
160 *
161 */
162 static uint8_t nand_read_byte16(struct mtd_info *mtd)
163 {
164 struct nand_chip *chip = mtd_to_nand(mtd);
165 return (uint8_t) cpu_to_le16(readw(chip->IO_ADDR_R));
166 }
167
168 /**
169 * nand_read_word - [DEFAULT] read one word from the chip
170 * @mtd: MTD device structure
171 *
172 * Default read function for 16bit buswidth without endianness conversion.
173 */
174 static u16 nand_read_word(struct mtd_info *mtd)
175 {
176 struct nand_chip *chip = mtd_to_nand(mtd);
177 return readw(chip->IO_ADDR_R);
178 }
179
180 /**
181 * nand_select_chip - [DEFAULT] control CE line
182 * @mtd: MTD device structure
183 * @chipnr: chipnumber to select, -1 for deselect
184 *
185 * Default select function for 1 chip devices.
186 */
187 static void nand_select_chip(struct mtd_info *mtd, int chipnr)
188 {
189 struct nand_chip *chip = mtd_to_nand(mtd);
190
191 switch (chipnr) {
192 case -1:
193 chip->cmd_ctrl(mtd, NAND_CMD_NONE, 0 | NAND_CTRL_CHANGE);
194 break;
195 case 0:
196 break;
197
198 default:
199 BUG();
200 }
201 }
202
203 /**
204 * nand_write_byte - [DEFAULT] write single byte to chip
205 * @mtd: MTD device structure
206 * @byte: value to write
207 *
208 * Default function to write a byte to I/O[7:0]
209 */
210 static void nand_write_byte(struct mtd_info *mtd, uint8_t byte)
211 {
212 struct nand_chip *chip = mtd_to_nand(mtd);
213
214 chip->write_buf(mtd, &byte, 1);
215 }
216
217 /**
218 * nand_write_byte16 - [DEFAULT] write single byte to a chip with width 16
219 * @mtd: MTD device structure
220 * @byte: value to write
221 *
222 * Default function to write a byte to I/O[7:0] on a 16-bit wide chip.
223 */
224 static void nand_write_byte16(struct mtd_info *mtd, uint8_t byte)
225 {
226 struct nand_chip *chip = mtd_to_nand(mtd);
227 uint16_t word = byte;
228
229 /*
230 * It's not entirely clear what should happen to I/O[15:8] when writing
231 * a byte. The ONFi spec (Revision 3.1; 2012-09-19, Section 2.16) reads:
232 *
233 * When the host supports a 16-bit bus width, only data is
234 * transferred at the 16-bit width. All address and command line
235 * transfers shall use only the lower 8-bits of the data bus. During
236 * command transfers, the host may place any value on the upper
237 * 8-bits of the data bus. During address transfers, the host shall
238 * set the upper 8-bits of the data bus to 00h.
239 *
240 * One user of the write_byte callback is nand_onfi_set_features. The
241 * four parameters are specified to be written to I/O[7:0], but this is
242 * neither an address nor a command transfer. Let's assume a 0 on the
243 * upper I/O lines is OK.
244 */
245 chip->write_buf(mtd, (uint8_t *)&word, 2);
246 }
247
248 static void iowrite8_rep(void *addr, const uint8_t *buf, int len)
249 {
250 int i;
251
252 for (i = 0; i < len; i++)
253 writeb(buf[i], addr);
254 }
255 static void ioread8_rep(void *addr, uint8_t *buf, int len)
256 {
257 int i;
258
259 for (i = 0; i < len; i++)
260 buf[i] = readb(addr);
261 }
262
263 static void ioread16_rep(void *addr, void *buf, int len)
264 {
265 int i;
266 u16 *p = (u16 *) buf;
267
268 for (i = 0; i < len; i++)
269 p[i] = readw(addr);
270 }
271
272 static void iowrite16_rep(void *addr, void *buf, int len)
273 {
274 int i;
275 u16 *p = (u16 *) buf;
276
277 for (i = 0; i < len; i++)
278 writew(p[i], addr);
279 }
280
281 /**
282 * nand_write_buf - [DEFAULT] write buffer to chip
283 * @mtd: MTD device structure
284 * @buf: data buffer
285 * @len: number of bytes to write
286 *
287 * Default write function for 8bit buswidth.
288 */
289 void nand_write_buf(struct mtd_info *mtd, const uint8_t *buf, int len)
290 {
291 struct nand_chip *chip = mtd_to_nand(mtd);
292
293 iowrite8_rep(chip->IO_ADDR_W, buf, len);
294 }
295
296 /**
297 * nand_read_buf - [DEFAULT] read chip data into buffer
298 * @mtd: MTD device structure
299 * @buf: buffer to store date
300 * @len: number of bytes to read
301 *
302 * Default read function for 8bit buswidth.
303 */
304 void nand_read_buf(struct mtd_info *mtd, uint8_t *buf, int len)
305 {
306 struct nand_chip *chip = mtd_to_nand(mtd);
307
308 ioread8_rep(chip->IO_ADDR_R, buf, len);
309 }
310
311 /**
312 * nand_write_buf16 - [DEFAULT] write buffer to chip
313 * @mtd: MTD device structure
314 * @buf: data buffer
315 * @len: number of bytes to write
316 *
317 * Default write function for 16bit buswidth.
318 */
319 void nand_write_buf16(struct mtd_info *mtd, const uint8_t *buf, int len)
320 {
321 struct nand_chip *chip = mtd_to_nand(mtd);
322 u16 *p = (u16 *) buf;
323
324 iowrite16_rep(chip->IO_ADDR_W, p, len >> 1);
325 }
326
327 /**
328 * nand_read_buf16 - [DEFAULT] read chip data into buffer
329 * @mtd: MTD device structure
330 * @buf: buffer to store date
331 * @len: number of bytes to read
332 *
333 * Default read function for 16bit buswidth.
334 */
335 void nand_read_buf16(struct mtd_info *mtd, uint8_t *buf, int len)
336 {
337 struct nand_chip *chip = mtd_to_nand(mtd);
338 u16 *p = (u16 *) buf;
339
340 ioread16_rep(chip->IO_ADDR_R, p, len >> 1);
341 }
342
343 /**
344 * nand_block_bad - [DEFAULT] Read bad block marker from the chip
345 * @mtd: MTD device structure
346 * @ofs: offset from device start
347 *
348 * Check, if the block is bad.
349 */
350 static int nand_block_bad(struct mtd_info *mtd, loff_t ofs)
351 {
352 int page, res = 0, i = 0;
353 struct nand_chip *chip = mtd_to_nand(mtd);
354 u16 bad;
355
356 if (chip->bbt_options & NAND_BBT_SCANLASTPAGE)
357 ofs += mtd->erasesize - mtd->writesize;
358
359 page = (int)(ofs >> chip->page_shift) & chip->pagemask;
360
361 do {
362 if (chip->options & NAND_BUSWIDTH_16) {
363 chip->cmdfunc(mtd, NAND_CMD_READOOB,
364 chip->badblockpos & 0xFE, page);
365 bad = cpu_to_le16(chip->read_word(mtd));
366 if (chip->badblockpos & 0x1)
367 bad >>= 8;
368 else
369 bad &= 0xFF;
370 } else {
371 chip->cmdfunc(mtd, NAND_CMD_READOOB, chip->badblockpos,
372 page);
373 bad = chip->read_byte(mtd);
374 }
375
376 if (likely(chip->badblockbits == 8))
377 res = bad != 0xFF;
378 else
379 res = hweight8(bad) < chip->badblockbits;
380 ofs += mtd->writesize;
381 page = (int)(ofs >> chip->page_shift) & chip->pagemask;
382 i++;
383 } while (!res && i < 2 && (chip->bbt_options & NAND_BBT_SCAN2NDPAGE));
384
385 return res;
386 }
387
388 /**
389 * nand_default_block_markbad - [DEFAULT] mark a block bad via bad block marker
390 * @mtd: MTD device structure
391 * @ofs: offset from device start
392 *
393 * This is the default implementation, which can be overridden by a hardware
394 * specific driver. It provides the details for writing a bad block marker to a
395 * block.
396 */
397 static int nand_default_block_markbad(struct mtd_info *mtd, loff_t ofs)
398 {
399 struct nand_chip *chip = mtd_to_nand(mtd);
400 struct mtd_oob_ops ops;
401 uint8_t buf[2] = { 0, 0 };
402 int ret = 0, res, i = 0;
403
404 memset(&ops, 0, sizeof(ops));
405 ops.oobbuf = buf;
406 ops.ooboffs = chip->badblockpos;
407 if (chip->options & NAND_BUSWIDTH_16) {
408 ops.ooboffs &= ~0x01;
409 ops.len = ops.ooblen = 2;
410 } else {
411 ops.len = ops.ooblen = 1;
412 }
413 ops.mode = MTD_OPS_PLACE_OOB;
414
415 /* Write to first/last page(s) if necessary */
416 if (chip->bbt_options & NAND_BBT_SCANLASTPAGE)
417 ofs += mtd->erasesize - mtd->writesize;
418 do {
419 res = nand_do_write_oob(mtd, ofs, &ops);
420 if (!ret)
421 ret = res;
422
423 i++;
424 ofs += mtd->writesize;
425 } while ((chip->bbt_options & NAND_BBT_SCAN2NDPAGE) && i < 2);
426
427 return ret;
428 }
429
430 /**
431 * nand_block_markbad_lowlevel - mark a block bad
432 * @mtd: MTD device structure
433 * @ofs: offset from device start
434 *
435 * This function performs the generic NAND bad block marking steps (i.e., bad
436 * block table(s) and/or marker(s)). We only allow the hardware driver to
437 * specify how to write bad block markers to OOB (chip->block_markbad).
438 *
439 * We try operations in the following order:
440 * (1) erase the affected block, to allow OOB marker to be written cleanly
441 * (2) write bad block marker to OOB area of affected block (unless flag
442 * NAND_BBT_NO_OOB_BBM is present)
443 * (3) update the BBT
444 * Note that we retain the first error encountered in (2) or (3), finish the
445 * procedures, and dump the error in the end.
446 */
447 static int nand_block_markbad_lowlevel(struct mtd_info *mtd, loff_t ofs)
448 {
449 struct nand_chip *chip = mtd_to_nand(mtd);
450 int ret = 0;
451 #ifndef CONFIG_SPL_BUILD
452 int res;
453 #endif
454
455 if (!(chip->bbt_options & NAND_BBT_NO_OOB_BBM)) {
456 struct erase_info einfo;
457
458 /* Attempt erase before marking OOB */
459 memset(&einfo, 0, sizeof(einfo));
460 einfo.mtd = mtd;
461 einfo.addr = ofs;
462 einfo.len = 1ULL << chip->phys_erase_shift;
463 nand_erase_nand(mtd, &einfo, 0);
464
465 /* Write bad block marker to OOB */
466 nand_get_device(mtd, FL_WRITING);
467 ret = chip->block_markbad(mtd, ofs);
468 nand_release_device(mtd);
469 }
470
471 #ifndef CONFIG_SPL_BUILD
472 /* Mark block bad in BBT */
473 if (chip->bbt) {
474 res = nand_markbad_bbt(mtd, ofs);
475 if (!ret)
476 ret = res;
477 }
478 #endif
479
480 if (!ret)
481 mtd->ecc_stats.badblocks++;
482
483 return ret;
484 }
485
486 /**
487 * nand_check_wp - [GENERIC] check if the chip is write protected
488 * @mtd: MTD device structure
489 *
490 * Check, if the device is write protected. The function expects, that the
491 * device is already selected.
492 */
493 static int nand_check_wp(struct mtd_info *mtd)
494 {
495 struct nand_chip *chip = mtd_to_nand(mtd);
496 u8 status;
497 int ret;
498
499 /* Broken xD cards report WP despite being writable */
500 if (chip->options & NAND_BROKEN_XD)
501 return 0;
502
503 /* Check the WP bit */
504 ret = nand_status_op(chip, &status);
505 if (ret)
506 return ret;
507
508 return status & NAND_STATUS_WP ? 0 : 1;
509 }
510
511 /**
512 * nand_block_isreserved - [GENERIC] Check if a block is marked reserved.
513 * @mtd: MTD device structure
514 * @ofs: offset from device start
515 *
516 * Check if the block is marked as reserved.
517 */
518 static int nand_block_isreserved(struct mtd_info *mtd, loff_t ofs)
519 {
520 struct nand_chip *chip = mtd_to_nand(mtd);
521
522 if (!chip->bbt)
523 return 0;
524 /* Return info from the table */
525 #ifndef CONFIG_SPL_BUILD
526 return nand_isreserved_bbt(mtd, ofs);
527 #else
528 return 0;
529 #endif
530 }
531
532 /**
533 * nand_block_checkbad - [GENERIC] Check if a block is marked bad
534 * @mtd: MTD device structure
535 * @ofs: offset from device start
536 * @allowbbt: 1, if its allowed to access the bbt area
537 *
538 * Check, if the block is bad. Either by reading the bad block table or
539 * calling of the scan function.
540 */
541 static int nand_block_checkbad(struct mtd_info *mtd, loff_t ofs, int allowbbt)
542 {
543 struct nand_chip *chip = mtd_to_nand(mtd);
544
545 if (!(chip->options & NAND_SKIP_BBTSCAN) &&
546 !(chip->options & NAND_BBT_SCANNED)) {
547 chip->options |= NAND_BBT_SCANNED;
548 chip->scan_bbt(mtd);
549 }
550
551 if (!chip->bbt)
552 return chip->block_bad(mtd, ofs);
553
554 /* Return info from the table */
555 #ifndef CONFIG_SPL_BUILD
556 return nand_isbad_bbt(mtd, ofs, allowbbt);
557 #else
558 return 0;
559 #endif
560 }
561
562 /**
563 * nand_wait_ready - [GENERIC] Wait for the ready pin after commands.
564 * @mtd: MTD device structure
565 *
566 * Wait for the ready pin after a command, and warn if a timeout occurs.
567 */
568 void nand_wait_ready(struct mtd_info *mtd)
569 {
570 struct nand_chip *chip = mtd_to_nand(mtd);
571 u32 timeo = (CONFIG_SYS_HZ * 400) / 1000;
572 u32 time_start;
573
574 time_start = get_timer(0);
575 /* Wait until command is processed or timeout occurs */
576 while (get_timer(time_start) < timeo) {
577 if (chip->dev_ready)
578 if (chip->dev_ready(mtd))
579 break;
580 }
581
582 if (!chip->dev_ready(mtd))
583 pr_warn("timeout while waiting for chip to become ready\n");
584 }
585 EXPORT_SYMBOL_GPL(nand_wait_ready);
586
587 /**
588 * nand_wait_status_ready - [GENERIC] Wait for the ready status after commands.
589 * @mtd: MTD device structure
590 * @timeo: Timeout in ms
591 *
592 * Wait for status ready (i.e. command done) or timeout.
593 */
594 static void nand_wait_status_ready(struct mtd_info *mtd, unsigned long timeo)
595 {
596 register struct nand_chip *chip = mtd_to_nand(mtd);
597 u32 time_start;
598 int ret;
599
600 timeo = (CONFIG_SYS_HZ * timeo) / 1000;
601 time_start = get_timer(0);
602 while (get_timer(time_start) < timeo) {
603 u8 status;
604
605 ret = nand_read_data_op(chip, &status, sizeof(status), true);
606 if (ret)
607 return;
608
609 if (status & NAND_STATUS_READY)
610 break;
611 schedule();
612 }
613 };
614
615 /**
616 * nand_command - [DEFAULT] Send command to NAND device
617 * @mtd: MTD device structure
618 * @command: the command to be sent
619 * @column: the column address for this command, -1 if none
620 * @page_addr: the page address for this command, -1 if none
621 *
622 * Send command to NAND device. This function is used for small page devices
623 * (512 Bytes per page).
624 */
625 static void nand_command(struct mtd_info *mtd, unsigned int command,
626 int column, int page_addr)
627 {
628 register struct nand_chip *chip = mtd_to_nand(mtd);
629 int ctrl = NAND_CTRL_CLE | NAND_CTRL_CHANGE;
630
631 /* Write out the command to the device */
632 if (command == NAND_CMD_SEQIN) {
633 int readcmd;
634
635 if (column >= mtd->writesize) {
636 /* OOB area */
637 column -= mtd->writesize;
638 readcmd = NAND_CMD_READOOB;
639 } else if (column < 256) {
640 /* First 256 bytes --> READ0 */
641 readcmd = NAND_CMD_READ0;
642 } else {
643 column -= 256;
644 readcmd = NAND_CMD_READ1;
645 }
646 chip->cmd_ctrl(mtd, readcmd, ctrl);
647 ctrl &= ~NAND_CTRL_CHANGE;
648 }
649 chip->cmd_ctrl(mtd, command, ctrl);
650
651 /* Address cycle, when necessary */
652 ctrl = NAND_CTRL_ALE | NAND_CTRL_CHANGE;
653 /* Serially input address */
654 if (column != -1) {
655 /* Adjust columns for 16 bit buswidth */
656 if (chip->options & NAND_BUSWIDTH_16 &&
657 !nand_opcode_8bits(command))
658 column >>= 1;
659 chip->cmd_ctrl(mtd, column, ctrl);
660 ctrl &= ~NAND_CTRL_CHANGE;
661 }
662 if (page_addr != -1) {
663 chip->cmd_ctrl(mtd, page_addr, ctrl);
664 ctrl &= ~NAND_CTRL_CHANGE;
665 chip->cmd_ctrl(mtd, page_addr >> 8, ctrl);
666 if (chip->options & NAND_ROW_ADDR_3)
667 chip->cmd_ctrl(mtd, page_addr >> 16, ctrl);
668 }
669 chip->cmd_ctrl(mtd, NAND_CMD_NONE, NAND_NCE | NAND_CTRL_CHANGE);
670
671 /*
672 * Program and erase have their own busy handlers status and sequential
673 * in needs no delay
674 */
675 switch (command) {
676
677 case NAND_CMD_PAGEPROG:
678 case NAND_CMD_ERASE1:
679 case NAND_CMD_ERASE2:
680 case NAND_CMD_SEQIN:
681 case NAND_CMD_STATUS:
682 case NAND_CMD_READID:
683 case NAND_CMD_SET_FEATURES:
684 return;
685
686 case NAND_CMD_RESET:
687 if (chip->dev_ready)
688 break;
689 udelay(chip->chip_delay);
690 chip->cmd_ctrl(mtd, NAND_CMD_STATUS,
691 NAND_CTRL_CLE | NAND_CTRL_CHANGE);
692 chip->cmd_ctrl(mtd,
693 NAND_CMD_NONE, NAND_NCE | NAND_CTRL_CHANGE);
694 /* EZ-NAND can take upto 250ms as per ONFi v4.0 */
695 nand_wait_status_ready(mtd, 250);
696 return;
697
698 /* This applies to read commands */
699 default:
700 /*
701 * If we don't have access to the busy pin, we apply the given
702 * command delay
703 */
704 if (!chip->dev_ready) {
705 udelay(chip->chip_delay);
706 return;
707 }
708 }
709 /*
710 * Apply this short delay always to ensure that we do wait tWB in
711 * any case on any machine.
712 */
713 ndelay(100);
714
715 nand_wait_ready(mtd);
716 }
717
718 /**
719 * nand_command_lp - [DEFAULT] Send command to NAND large page device
720 * @mtd: MTD device structure
721 * @command: the command to be sent
722 * @column: the column address for this command, -1 if none
723 * @page_addr: the page address for this command, -1 if none
724 *
725 * Send command to NAND device. This is the version for the new large page
726 * devices. We don't have the separate regions as we have in the small page
727 * devices. We must emulate NAND_CMD_READOOB to keep the code compatible.
728 */
729 static void nand_command_lp(struct mtd_info *mtd, unsigned int command,
730 int column, int page_addr)
731 {
732 register struct nand_chip *chip = mtd_to_nand(mtd);
733
734 /* Emulate NAND_CMD_READOOB */
735 if (command == NAND_CMD_READOOB) {
736 column += mtd->writesize;
737 command = NAND_CMD_READ0;
738 }
739
740 /* Command latch cycle */
741 chip->cmd_ctrl(mtd, command, NAND_NCE | NAND_CLE | NAND_CTRL_CHANGE);
742
743 if (column != -1 || page_addr != -1) {
744 int ctrl = NAND_CTRL_CHANGE | NAND_NCE | NAND_ALE;
745
746 /* Serially input address */
747 if (column != -1) {
748 /* Adjust columns for 16 bit buswidth */
749 if (chip->options & NAND_BUSWIDTH_16 &&
750 !nand_opcode_8bits(command))
751 column >>= 1;
752 chip->cmd_ctrl(mtd, column, ctrl);
753 ctrl &= ~NAND_CTRL_CHANGE;
754 chip->cmd_ctrl(mtd, column >> 8, ctrl);
755 }
756 if (page_addr != -1) {
757 chip->cmd_ctrl(mtd, page_addr, ctrl);
758 chip->cmd_ctrl(mtd, page_addr >> 8,
759 NAND_NCE | NAND_ALE);
760 if (chip->options & NAND_ROW_ADDR_3)
761 chip->cmd_ctrl(mtd, page_addr >> 16,
762 NAND_NCE | NAND_ALE);
763 }
764 }
765 chip->cmd_ctrl(mtd, NAND_CMD_NONE, NAND_NCE | NAND_CTRL_CHANGE);
766
767 /*
768 * Program and erase have their own busy handlers status, sequential
769 * in and status need no delay.
770 */
771 switch (command) {
772
773 case NAND_CMD_CACHEDPROG:
774 case NAND_CMD_PAGEPROG:
775 case NAND_CMD_ERASE1:
776 case NAND_CMD_ERASE2:
777 case NAND_CMD_SEQIN:
778 case NAND_CMD_RNDIN:
779 case NAND_CMD_STATUS:
780 case NAND_CMD_READID:
781 case NAND_CMD_SET_FEATURES:
782 return;
783
784 case NAND_CMD_RESET:
785 if (chip->dev_ready)
786 break;
787 udelay(chip->chip_delay);
788 chip->cmd_ctrl(mtd, NAND_CMD_STATUS,
789 NAND_NCE | NAND_CLE | NAND_CTRL_CHANGE);
790 chip->cmd_ctrl(mtd, NAND_CMD_NONE,
791 NAND_NCE | NAND_CTRL_CHANGE);
792 /* EZ-NAND can take upto 250ms as per ONFi v4.0 */
793 nand_wait_status_ready(mtd, 250);
794 return;
795
796 case NAND_CMD_RNDOUT:
797 /* No ready / busy check necessary */
798 chip->cmd_ctrl(mtd, NAND_CMD_RNDOUTSTART,
799 NAND_NCE | NAND_CLE | NAND_CTRL_CHANGE);
800 chip->cmd_ctrl(mtd, NAND_CMD_NONE,
801 NAND_NCE | NAND_CTRL_CHANGE);
802 return;
803
804 case NAND_CMD_READ0:
805 chip->cmd_ctrl(mtd, NAND_CMD_READSTART,
806 NAND_NCE | NAND_CLE | NAND_CTRL_CHANGE);
807 chip->cmd_ctrl(mtd, NAND_CMD_NONE,
808 NAND_NCE | NAND_CTRL_CHANGE);
809
810 /* This applies to read commands */
811 default:
812 /*
813 * If we don't have access to the busy pin, we apply the given
814 * command delay.
815 */
816 if (!chip->dev_ready) {
817 udelay(chip->chip_delay);
818 return;
819 }
820 }
821
822 /*
823 * Apply this short delay always to ensure that we do wait tWB in
824 * any case on any machine.
825 */
826 ndelay(100);
827
828 nand_wait_ready(mtd);
829 }
830
831 /**
832 * panic_nand_get_device - [GENERIC] Get chip for selected access
833 * @chip: the nand chip descriptor
834 * @mtd: MTD device structure
835 * @new_state: the state which is requested
836 *
837 * Used when in panic, no locks are taken.
838 */
839 static void panic_nand_get_device(struct nand_chip *chip,
840 struct mtd_info *mtd, int new_state)
841 {
842 /* Hardware controller shared among independent devices */
843 chip->controller->active = chip;
844 chip->state = new_state;
845 }
846
847 /**
848 * nand_get_device - [GENERIC] Get chip for selected access
849 * @mtd: MTD device structure
850 * @new_state: the state which is requested
851 *
852 * Get the device and lock it for exclusive access
853 */
854 static int
855 nand_get_device(struct mtd_info *mtd, int new_state)
856 {
857 struct nand_chip *chip = mtd_to_nand(mtd);
858 chip->state = new_state;
859 return 0;
860 }
861
862 /**
863 * panic_nand_wait - [GENERIC] wait until the command is done
864 * @mtd: MTD device structure
865 * @chip: NAND chip structure
866 * @timeo: timeout
867 *
868 * Wait for command done. This is a helper function for nand_wait used when
869 * we are in interrupt context. May happen when in panic and trying to write
870 * an oops through mtdoops.
871 */
872 static void panic_nand_wait(struct mtd_info *mtd, struct nand_chip *chip,
873 unsigned long timeo)
874 {
875 int i;
876 for (i = 0; i < timeo; i++) {
877 if (chip->dev_ready) {
878 if (chip->dev_ready(mtd))
879 break;
880 } else {
881 int ret;
882 u8 status;
883
884 ret = nand_read_data_op(chip, &status, sizeof(status),
885 true);
886 if (ret)
887 return;
888
889 if (status & NAND_STATUS_READY)
890 break;
891 }
892 mdelay(1);
893 }
894 }
895
896 /**
897 * nand_wait - [DEFAULT] wait until the command is done
898 * @mtd: MTD device structure
899 * @chip: NAND chip structure
900 *
901 * Wait for command done. This applies to erase and program only.
902 */
903 static int nand_wait(struct mtd_info *mtd, struct nand_chip *chip)
904 {
905 unsigned long timeo = 400;
906 u8 status;
907 int ret;
908
909 led_trigger_event(nand_led_trigger, LED_FULL);
910
911 /*
912 * Apply this short delay always to ensure that we do wait tWB in any
913 * case on any machine.
914 */
915 ndelay(100);
916
917 ret = nand_status_op(chip, NULL);
918 if (ret)
919 return ret;
920
921 u32 timer = (CONFIG_SYS_HZ * timeo) / 1000;
922 u32 time_start;
923
924 time_start = get_timer(0);
925 while (get_timer(time_start) < timer) {
926 if (chip->dev_ready) {
927 if (chip->dev_ready(mtd))
928 break;
929 } else {
930 ret = nand_read_data_op(chip, &status,
931 sizeof(status), true);
932 if (ret)
933 return ret;
934
935 if (status & NAND_STATUS_READY)
936 break;
937 }
938 }
939 led_trigger_event(nand_led_trigger, LED_OFF);
940
941 ret = nand_read_data_op(chip, &status, sizeof(status), true);
942 if (ret)
943 return ret;
944
945 /* This can happen if in case of timeout or buggy dev_ready */
946 WARN_ON(!(status & NAND_STATUS_READY));
947 return status;
948 }
949
950 /**
951 * nand_reset_data_interface - Reset data interface and timings
952 * @chip: The NAND chip
953 * @chipnr: Internal die id
954 *
955 * Reset the Data interface and timings to ONFI mode 0.
956 *
957 * Returns 0 for success or negative error code otherwise.
958 */
959 static int nand_reset_data_interface(struct nand_chip *chip, int chipnr)
960 {
961 struct mtd_info *mtd = nand_to_mtd(chip);
962 const struct nand_data_interface *conf;
963 int ret;
964
965 if (!chip->setup_data_interface)
966 return 0;
967
968 /*
969 * The ONFI specification says:
970 * "
971 * To transition from NV-DDR or NV-DDR2 to the SDR data
972 * interface, the host shall use the Reset (FFh) command
973 * using SDR timing mode 0. A device in any timing mode is
974 * required to recognize Reset (FFh) command issued in SDR
975 * timing mode 0.
976 * "
977 *
978 * Configure the data interface in SDR mode and set the
979 * timings to timing mode 0.
980 */
981
982 conf = nand_get_default_data_interface();
983 ret = chip->setup_data_interface(mtd, chipnr, conf);
984 if (ret)
985 pr_err("Failed to configure data interface to SDR timing mode 0\n");
986
987 return ret;
988 }
989
990 static int nand_onfi_set_timings(struct mtd_info *mtd, struct nand_chip *chip)
991 {
992 if (!chip->onfi_version ||
993 !(le16_to_cpu(chip->onfi_params.opt_cmd)
994 & ONFI_OPT_CMD_SET_GET_FEATURES))
995 return 0;
996
997 u8 tmode_param[ONFI_SUBFEATURE_PARAM_LEN] = {
998 chip->onfi_timing_mode_default,
999 };
1000
1001 return chip->onfi_set_features(mtd, chip,
1002 ONFI_FEATURE_ADDR_TIMING_MODE,
1003 tmode_param);
1004 }
1005
1006 /**
1007 * nand_setup_data_interface - Setup the best data interface and timings
1008 * @chip: The NAND chip
1009 * @chipnr: Internal die id
1010 *
1011 * Find and configure the best data interface and NAND timings supported by
1012 * the chip and the driver.
1013 * First tries to retrieve supported timing modes from ONFI information,
1014 * and if the NAND chip does not support ONFI, relies on the
1015 * ->onfi_timing_mode_default specified in the nand_ids table.
1016 *
1017 * Returns 0 for success or negative error code otherwise.
1018 */
1019 static int nand_setup_data_interface(struct nand_chip *chip, int chipnr)
1020 {
1021 struct mtd_info *mtd = nand_to_mtd(chip);
1022 int ret;
1023
1024 if (!chip->setup_data_interface || !chip->data_interface)
1025 return 0;
1026
1027 /*
1028 * Ensure the timing mode has been changed on the chip side
1029 * before changing timings on the controller side.
1030 */
1031 ret = nand_onfi_set_timings(mtd, chip);
1032 if (ret)
1033 goto err;
1034
1035 ret = chip->setup_data_interface(mtd, chipnr, chip->data_interface);
1036 err:
1037 return ret;
1038 }
1039
1040 /**
1041 * nand_init_data_interface - find the best data interface and timings
1042 * @chip: The NAND chip
1043 *
1044 * Find the best data interface and NAND timings supported by the chip
1045 * and the driver.
1046 * First tries to retrieve supported timing modes from ONFI information,
1047 * and if the NAND chip does not support ONFI, relies on the
1048 * ->onfi_timing_mode_default specified in the nand_ids table. After this
1049 * function nand_chip->data_interface is initialized with the best timing mode
1050 * available.
1051 *
1052 * Returns 0 for success or negative error code otherwise.
1053 */
1054 static int nand_init_data_interface(struct nand_chip *chip)
1055 {
1056 struct mtd_info *mtd = nand_to_mtd(chip);
1057 int modes, mode, ret;
1058
1059 if (!chip->setup_data_interface)
1060 return 0;
1061
1062 /*
1063 * First try to identify the best timings from ONFI parameters and
1064 * if the NAND does not support ONFI, fallback to the default ONFI
1065 * timing mode.
1066 */
1067 modes = onfi_get_async_timing_mode(chip);
1068 if (modes == ONFI_TIMING_MODE_UNKNOWN) {
1069 if (!chip->onfi_timing_mode_default)
1070 return 0;
1071
1072 modes = GENMASK(chip->onfi_timing_mode_default, 0);
1073 }
1074
1075 chip->data_interface = kzalloc(sizeof(*chip->data_interface),
1076 GFP_KERNEL);
1077 if (!chip->data_interface)
1078 return -ENOMEM;
1079
1080 for (mode = fls(modes) - 1; mode >= 0; mode--) {
1081 ret = onfi_init_data_interface(chip, chip->data_interface,
1082 NAND_SDR_IFACE, mode);
1083 if (ret)
1084 continue;
1085
1086 /* Pass -1 to only */
1087 ret = chip->setup_data_interface(mtd,
1088 NAND_DATA_IFACE_CHECK_ONLY,
1089 chip->data_interface);
1090 if (!ret) {
1091 chip->onfi_timing_mode_default = mode;
1092 break;
1093 }
1094 }
1095
1096 return 0;
1097 }
1098
1099 static void __maybe_unused nand_release_data_interface(struct nand_chip *chip)
1100 {
1101 kfree(chip->data_interface);
1102 }
1103
1104 /**
1105 * nand_read_page_op - Do a READ PAGE operation
1106 * @chip: The NAND chip
1107 * @page: page to read
1108 * @offset_in_page: offset within the page
1109 * @buf: buffer used to store the data
1110 * @len: length of the buffer
1111 *
1112 * This function issues a READ PAGE operation.
1113 * This function does not select/unselect the CS line.
1114 *
1115 * Returns 0 on success, a negative error code otherwise.
1116 */
1117 int nand_read_page_op(struct nand_chip *chip, unsigned int page,
1118 unsigned int offset_in_page, void *buf, unsigned int len)
1119 {
1120 struct mtd_info *mtd = nand_to_mtd(chip);
1121
1122 if (len && !buf)
1123 return -EINVAL;
1124
1125 if (offset_in_page + len > mtd->writesize + mtd->oobsize)
1126 return -EINVAL;
1127
1128 chip->cmdfunc(mtd, NAND_CMD_READ0, offset_in_page, page);
1129 if (len)
1130 chip->read_buf(mtd, buf, len);
1131
1132 return 0;
1133 }
1134 EXPORT_SYMBOL_GPL(nand_read_page_op);
1135
1136 /**
1137 * nand_read_param_page_op - Do a READ PARAMETER PAGE operation
1138 * @chip: The NAND chip
1139 * @page: parameter page to read
1140 * @buf: buffer used to store the data
1141 * @len: length of the buffer
1142 *
1143 * This function issues a READ PARAMETER PAGE operation.
1144 * This function does not select/unselect the CS line.
1145 *
1146 * Returns 0 on success, a negative error code otherwise.
1147 */
1148 static int nand_read_param_page_op(struct nand_chip *chip, u8 page, void *buf,
1149 unsigned int len)
1150 {
1151 struct mtd_info *mtd = nand_to_mtd(chip);
1152 unsigned int i;
1153 u8 *p = buf;
1154
1155 if (len && !buf)
1156 return -EINVAL;
1157
1158 chip->cmdfunc(mtd, NAND_CMD_PARAM, page, -1);
1159 for (i = 0; i < len; i++)
1160 p[i] = chip->read_byte(mtd);
1161
1162 return 0;
1163 }
1164
1165 /**
1166 * nand_change_read_column_op - Do a CHANGE READ COLUMN operation
1167 * @chip: The NAND chip
1168 * @offset_in_page: offset within the page
1169 * @buf: buffer used to store the data
1170 * @len: length of the buffer
1171 * @force_8bit: force 8-bit bus access
1172 *
1173 * This function issues a CHANGE READ COLUMN operation.
1174 * This function does not select/unselect the CS line.
1175 *
1176 * Returns 0 on success, a negative error code otherwise.
1177 */
1178 int nand_change_read_column_op(struct nand_chip *chip,
1179 unsigned int offset_in_page, void *buf,
1180 unsigned int len, bool force_8bit)
1181 {
1182 struct mtd_info *mtd = nand_to_mtd(chip);
1183
1184 if (len && !buf)
1185 return -EINVAL;
1186
1187 if (offset_in_page + len > mtd->writesize + mtd->oobsize)
1188 return -EINVAL;
1189
1190 chip->cmdfunc(mtd, NAND_CMD_RNDOUT, offset_in_page, -1);
1191 if (len)
1192 chip->read_buf(mtd, buf, len);
1193
1194 return 0;
1195 }
1196 EXPORT_SYMBOL_GPL(nand_change_read_column_op);
1197
1198 /**
1199 * nand_read_oob_op - Do a READ OOB operation
1200 * @chip: The NAND chip
1201 * @page: page to read
1202 * @offset_in_oob: offset within the OOB area
1203 * @buf: buffer used to store the data
1204 * @len: length of the buffer
1205 *
1206 * This function issues a READ OOB operation.
1207 * This function does not select/unselect the CS line.
1208 *
1209 * Returns 0 on success, a negative error code otherwise.
1210 */
1211 int nand_read_oob_op(struct nand_chip *chip, unsigned int page,
1212 unsigned int offset_in_oob, void *buf, unsigned int len)
1213 {
1214 struct mtd_info *mtd = nand_to_mtd(chip);
1215
1216 if (len && !buf)
1217 return -EINVAL;
1218
1219 if (offset_in_oob + len > mtd->oobsize)
1220 return -EINVAL;
1221
1222 chip->cmdfunc(mtd, NAND_CMD_READOOB, offset_in_oob, page);
1223 if (len)
1224 chip->read_buf(mtd, buf, len);
1225
1226 return 0;
1227 }
1228 EXPORT_SYMBOL_GPL(nand_read_oob_op);
1229
1230 /**
1231 * nand_prog_page_begin_op - starts a PROG PAGE operation
1232 * @chip: The NAND chip
1233 * @page: page to write
1234 * @offset_in_page: offset within the page
1235 * @buf: buffer containing the data to write to the page
1236 * @len: length of the buffer
1237 *
1238 * This function issues the first half of a PROG PAGE operation.
1239 * This function does not select/unselect the CS line.
1240 *
1241 * Returns 0 on success, a negative error code otherwise.
1242 */
1243 int nand_prog_page_begin_op(struct nand_chip *chip, unsigned int page,
1244 unsigned int offset_in_page, const void *buf,
1245 unsigned int len)
1246 {
1247 struct mtd_info *mtd = nand_to_mtd(chip);
1248
1249 if (len && !buf)
1250 return -EINVAL;
1251
1252 if (offset_in_page + len > mtd->writesize + mtd->oobsize)
1253 return -EINVAL;
1254
1255 chip->cmdfunc(mtd, NAND_CMD_SEQIN, offset_in_page, page);
1256
1257 if (buf)
1258 chip->write_buf(mtd, buf, len);
1259
1260 return 0;
1261 }
1262 EXPORT_SYMBOL_GPL(nand_prog_page_begin_op);
1263
1264 /**
1265 * nand_prog_page_end_op - ends a PROG PAGE operation
1266 * @chip: The NAND chip
1267 *
1268 * This function issues the second half of a PROG PAGE operation.
1269 * This function does not select/unselect the CS line.
1270 *
1271 * Returns 0 on success, a negative error code otherwise.
1272 */
1273 int nand_prog_page_end_op(struct nand_chip *chip)
1274 {
1275 struct mtd_info *mtd = nand_to_mtd(chip);
1276 int status;
1277
1278 chip->cmdfunc(mtd, NAND_CMD_PAGEPROG, -1, -1);
1279
1280 status = chip->waitfunc(mtd, chip);
1281 if (status & NAND_STATUS_FAIL)
1282 return -EIO;
1283
1284 return 0;
1285 }
1286 EXPORT_SYMBOL_GPL(nand_prog_page_end_op);
1287
1288 /**
1289 * nand_prog_page_op - Do a full PROG PAGE operation
1290 * @chip: The NAND chip
1291 * @page: page to write
1292 * @offset_in_page: offset within the page
1293 * @buf: buffer containing the data to write to the page
1294 * @len: length of the buffer
1295 *
1296 * This function issues a full PROG PAGE operation.
1297 * This function does not select/unselect the CS line.
1298 *
1299 * Returns 0 on success, a negative error code otherwise.
1300 */
1301 int nand_prog_page_op(struct nand_chip *chip, unsigned int page,
1302 unsigned int offset_in_page, const void *buf,
1303 unsigned int len)
1304 {
1305 struct mtd_info *mtd = nand_to_mtd(chip);
1306 int status;
1307
1308 if (!len || !buf)
1309 return -EINVAL;
1310
1311 if (offset_in_page + len > mtd->writesize + mtd->oobsize)
1312 return -EINVAL;
1313
1314 chip->cmdfunc(mtd, NAND_CMD_SEQIN, offset_in_page, page);
1315 chip->write_buf(mtd, buf, len);
1316 chip->cmdfunc(mtd, NAND_CMD_PAGEPROG, -1, -1);
1317
1318 status = chip->waitfunc(mtd, chip);
1319 if (status & NAND_STATUS_FAIL)
1320 return -EIO;
1321
1322 return 0;
1323 }
1324 EXPORT_SYMBOL_GPL(nand_prog_page_op);
1325
1326 /**
1327 * nand_change_write_column_op - Do a CHANGE WRITE COLUMN operation
1328 * @chip: The NAND chip
1329 * @offset_in_page: offset within the page
1330 * @buf: buffer containing the data to send to the NAND
1331 * @len: length of the buffer
1332 * @force_8bit: force 8-bit bus access
1333 *
1334 * This function issues a CHANGE WRITE COLUMN operation.
1335 * This function does not select/unselect the CS line.
1336 *
1337 * Returns 0 on success, a negative error code otherwise.
1338 */
1339 int nand_change_write_column_op(struct nand_chip *chip,
1340 unsigned int offset_in_page,
1341 const void *buf, unsigned int len,
1342 bool force_8bit)
1343 {
1344 struct mtd_info *mtd = nand_to_mtd(chip);
1345
1346 if (len && !buf)
1347 return -EINVAL;
1348
1349 if (offset_in_page + len > mtd->writesize + mtd->oobsize)
1350 return -EINVAL;
1351
1352 chip->cmdfunc(mtd, NAND_CMD_RNDIN, offset_in_page, -1);
1353 if (len)
1354 chip->write_buf(mtd, buf, len);
1355
1356 return 0;
1357 }
1358 EXPORT_SYMBOL_GPL(nand_change_write_column_op);
1359
1360 /**
1361 * nand_readid_op - Do a READID operation
1362 * @chip: The NAND chip
1363 * @addr: address cycle to pass after the READID command
1364 * @buf: buffer used to store the ID
1365 * @len: length of the buffer
1366 *
1367 * This function sends a READID command and reads back the ID returned by the
1368 * NAND.
1369 * This function does not select/unselect the CS line.
1370 *
1371 * Returns 0 on success, a negative error code otherwise.
1372 */
1373 int nand_readid_op(struct nand_chip *chip, u8 addr, void *buf,
1374 unsigned int len)
1375 {
1376 struct mtd_info *mtd = nand_to_mtd(chip);
1377 unsigned int i;
1378 u8 *id = buf;
1379
1380 if (len && !buf)
1381 return -EINVAL;
1382
1383 chip->cmdfunc(mtd, NAND_CMD_READID, addr, -1);
1384
1385 for (i = 0; i < len; i++)
1386 id[i] = chip->read_byte(mtd);
1387
1388 return 0;
1389 }
1390 EXPORT_SYMBOL_GPL(nand_readid_op);
1391
1392 /**
1393 * nand_status_op - Do a STATUS operation
1394 * @chip: The NAND chip
1395 * @status: out variable to store the NAND status
1396 *
1397 * This function sends a STATUS command and reads back the status returned by
1398 * the NAND.
1399 * This function does not select/unselect the CS line.
1400 *
1401 * Returns 0 on success, a negative error code otherwise.
1402 */
1403 int nand_status_op(struct nand_chip *chip, u8 *status)
1404 {
1405 struct mtd_info *mtd = nand_to_mtd(chip);
1406
1407 chip->cmdfunc(mtd, NAND_CMD_STATUS, -1, -1);
1408 if (status)
1409 *status = chip->read_byte(mtd);
1410
1411 return 0;
1412 }
1413 EXPORT_SYMBOL_GPL(nand_status_op);
1414
1415 /**
1416 * nand_exit_status_op - Exit a STATUS operation
1417 * @chip: The NAND chip
1418 *
1419 * This function sends a READ0 command to cancel the effect of the STATUS
1420 * command to avoid reading only the status until a new read command is sent.
1421 *
1422 * This function does not select/unselect the CS line.
1423 *
1424 * Returns 0 on success, a negative error code otherwise.
1425 */
1426 int nand_exit_status_op(struct nand_chip *chip)
1427 {
1428 struct mtd_info *mtd = nand_to_mtd(chip);
1429
1430 chip->cmdfunc(mtd, NAND_CMD_READ0, -1, -1);
1431
1432 return 0;
1433 }
1434 EXPORT_SYMBOL_GPL(nand_exit_status_op);
1435
1436 /**
1437 * nand_erase_op - Do an erase operation
1438 * @chip: The NAND chip
1439 * @eraseblock: block to erase
1440 *
1441 * This function sends an ERASE command and waits for the NAND to be ready
1442 * before returning.
1443 * This function does not select/unselect the CS line.
1444 *
1445 * Returns 0 on success, a negative error code otherwise.
1446 */
1447 int nand_erase_op(struct nand_chip *chip, unsigned int eraseblock)
1448 {
1449 struct mtd_info *mtd = nand_to_mtd(chip);
1450 unsigned int page = eraseblock <<
1451 (chip->phys_erase_shift - chip->page_shift);
1452 int status;
1453
1454 chip->cmdfunc(mtd, NAND_CMD_ERASE1, -1, page);
1455 chip->cmdfunc(mtd, NAND_CMD_ERASE2, -1, -1);
1456
1457 status = chip->waitfunc(mtd, chip);
1458 if (status < 0)
1459 return status;
1460
1461 if (status & NAND_STATUS_FAIL)
1462 return -EIO;
1463
1464 return 0;
1465 }
1466 EXPORT_SYMBOL_GPL(nand_erase_op);
1467
1468 /**
1469 * nand_set_features_op - Do a SET FEATURES operation
1470 * @chip: The NAND chip
1471 * @feature: feature id
1472 * @data: 4 bytes of data
1473 *
1474 * This function sends a SET FEATURES command and waits for the NAND to be
1475 * ready before returning.
1476 * This function does not select/unselect the CS line.
1477 *
1478 * Returns 0 on success, a negative error code otherwise.
1479 */
1480 static int nand_set_features_op(struct nand_chip *chip, u8 feature,
1481 const void *data)
1482 {
1483 struct mtd_info *mtd = nand_to_mtd(chip);
1484 const u8 *params = data;
1485 int i, status;
1486
1487 chip->cmdfunc(mtd, NAND_CMD_SET_FEATURES, feature, -1);
1488 for (i = 0; i < ONFI_SUBFEATURE_PARAM_LEN; ++i)
1489 chip->write_byte(mtd, params[i]);
1490
1491 status = chip->waitfunc(mtd, chip);
1492 if (status & NAND_STATUS_FAIL)
1493 return -EIO;
1494
1495 return 0;
1496 }
1497
1498 /**
1499 * nand_get_features_op - Do a GET FEATURES operation
1500 * @chip: The NAND chip
1501 * @feature: feature id
1502 * @data: 4 bytes of data
1503 *
1504 * This function sends a GET FEATURES command and waits for the NAND to be
1505 * ready before returning.
1506 * This function does not select/unselect the CS line.
1507 *
1508 * Returns 0 on success, a negative error code otherwise.
1509 */
1510 static int nand_get_features_op(struct nand_chip *chip, u8 feature,
1511 void *data)
1512 {
1513 struct mtd_info *mtd = nand_to_mtd(chip);
1514 u8 *params = data;
1515 int i;
1516
1517 chip->cmdfunc(mtd, NAND_CMD_GET_FEATURES, feature, -1);
1518 for (i = 0; i < ONFI_SUBFEATURE_PARAM_LEN; ++i)
1519 params[i] = chip->read_byte(mtd);
1520
1521 return 0;
1522 }
1523
1524 /**
1525 * nand_reset_op - Do a reset operation
1526 * @chip: The NAND chip
1527 *
1528 * This function sends a RESET command and waits for the NAND to be ready
1529 * before returning.
1530 * This function does not select/unselect the CS line.
1531 *
1532 * Returns 0 on success, a negative error code otherwise.
1533 */
1534 int nand_reset_op(struct nand_chip *chip)
1535 {
1536 struct mtd_info *mtd = nand_to_mtd(chip);
1537
1538 chip->cmdfunc(mtd, NAND_CMD_RESET, -1, -1);
1539
1540 return 0;
1541 }
1542 EXPORT_SYMBOL_GPL(nand_reset_op);
1543
1544 /**
1545 * nand_read_data_op - Read data from the NAND
1546 * @chip: The NAND chip
1547 * @buf: buffer used to store the data
1548 * @len: length of the buffer
1549 * @force_8bit: force 8-bit bus access
1550 *
1551 * This function does a raw data read on the bus. Usually used after launching
1552 * another NAND operation like nand_read_page_op().
1553 * This function does not select/unselect the CS line.
1554 *
1555 * Returns 0 on success, a negative error code otherwise.
1556 */
1557 int nand_read_data_op(struct nand_chip *chip, void *buf, unsigned int len,
1558 bool force_8bit)
1559 {
1560 struct mtd_info *mtd = nand_to_mtd(chip);
1561
1562 if (!len || !buf)
1563 return -EINVAL;
1564
1565 if (force_8bit) {
1566 u8 *p = buf;
1567 unsigned int i;
1568
1569 for (i = 0; i < len; i++)
1570 p[i] = chip->read_byte(mtd);
1571 } else {
1572 chip->read_buf(mtd, buf, len);
1573 }
1574
1575 return 0;
1576 }
1577 EXPORT_SYMBOL_GPL(nand_read_data_op);
1578
1579 /**
1580 * nand_write_data_op - Write data from the NAND
1581 * @chip: The NAND chip
1582 * @buf: buffer containing the data to send on the bus
1583 * @len: length of the buffer
1584 * @force_8bit: force 8-bit bus access
1585 *
1586 * This function does a raw data write on the bus. Usually used after launching
1587 * another NAND operation like nand_write_page_begin_op().
1588 * This function does not select/unselect the CS line.
1589 *
1590 * Returns 0 on success, a negative error code otherwise.
1591 */
1592 int nand_write_data_op(struct nand_chip *chip, const void *buf,
1593 unsigned int len, bool force_8bit)
1594 {
1595 struct mtd_info *mtd = nand_to_mtd(chip);
1596
1597 if (!len || !buf)
1598 return -EINVAL;
1599
1600 if (force_8bit) {
1601 const u8 *p = buf;
1602 unsigned int i;
1603
1604 for (i = 0; i < len; i++)
1605 chip->write_byte(mtd, p[i]);
1606 } else {
1607 chip->write_buf(mtd, buf, len);
1608 }
1609
1610 return 0;
1611 }
1612 EXPORT_SYMBOL_GPL(nand_write_data_op);
1613
1614 /**
1615 * nand_reset - Reset and initialize a NAND device
1616 * @chip: The NAND chip
1617 * @chipnr: Internal die id
1618 *
1619 * Returns 0 for success or negative error code otherwise
1620 */
1621 int nand_reset(struct nand_chip *chip, int chipnr)
1622 {
1623 struct mtd_info *mtd = nand_to_mtd(chip);
1624 int ret;
1625
1626 ret = nand_reset_data_interface(chip, chipnr);
1627 if (ret)
1628 return ret;
1629
1630 /*
1631 * The CS line has to be released before we can apply the new NAND
1632 * interface settings, hence this weird ->select_chip() dance.
1633 */
1634 chip->select_chip(mtd, chipnr);
1635 ret = nand_reset_op(chip);
1636 chip->select_chip(mtd, -1);
1637 if (ret)
1638 return ret;
1639
1640 chip->select_chip(mtd, chipnr);
1641 ret = nand_setup_data_interface(chip, chipnr);
1642 chip->select_chip(mtd, -1);
1643 if (ret)
1644 return ret;
1645
1646 return 0;
1647 }
1648
1649 /**
1650 * nand_check_erased_buf - check if a buffer contains (almost) only 0xff data
1651 * @buf: buffer to test
1652 * @len: buffer length
1653 * @bitflips_threshold: maximum number of bitflips
1654 *
1655 * Check if a buffer contains only 0xff, which means the underlying region
1656 * has been erased and is ready to be programmed.
1657 * The bitflips_threshold specify the maximum number of bitflips before
1658 * considering the region is not erased.
1659 * Note: The logic of this function has been extracted from the memweight
1660 * implementation, except that nand_check_erased_buf function exit before
1661 * testing the whole buffer if the number of bitflips exceed the
1662 * bitflips_threshold value.
1663 *
1664 * Returns a positive number of bitflips less than or equal to
1665 * bitflips_threshold, or -ERROR_CODE for bitflips in excess of the
1666 * threshold.
1667 */
1668 static int nand_check_erased_buf(void *buf, int len, int bitflips_threshold)
1669 {
1670 const unsigned char *bitmap = buf;
1671 int bitflips = 0;
1672 int weight;
1673
1674 for (; len && ((uintptr_t)bitmap) % sizeof(long);
1675 len--, bitmap++) {
1676 weight = hweight8(*bitmap);
1677 bitflips += BITS_PER_BYTE - weight;
1678 if (unlikely(bitflips > bitflips_threshold))
1679 return -EBADMSG;
1680 }
1681
1682 for (; len >= 4; len -= 4, bitmap += 4) {
1683 weight = hweight32(*((u32 *)bitmap));
1684 bitflips += 32 - weight;
1685 if (unlikely(bitflips > bitflips_threshold))
1686 return -EBADMSG;
1687 }
1688
1689 for (; len > 0; len--, bitmap++) {
1690 weight = hweight8(*bitmap);
1691 bitflips += BITS_PER_BYTE - weight;
1692 if (unlikely(bitflips > bitflips_threshold))
1693 return -EBADMSG;
1694 }
1695
1696 return bitflips;
1697 }
1698
1699 /**
1700 * nand_check_erased_ecc_chunk - check if an ECC chunk contains (almost) only
1701 * 0xff data
1702 * @data: data buffer to test
1703 * @datalen: data length
1704 * @ecc: ECC buffer
1705 * @ecclen: ECC length
1706 * @extraoob: extra OOB buffer
1707 * @extraooblen: extra OOB length
1708 * @bitflips_threshold: maximum number of bitflips
1709 *
1710 * Check if a data buffer and its associated ECC and OOB data contains only
1711 * 0xff pattern, which means the underlying region has been erased and is
1712 * ready to be programmed.
1713 * The bitflips_threshold specify the maximum number of bitflips before
1714 * considering the region as not erased.
1715 *
1716 * Note:
1717 * 1/ ECC algorithms are working on pre-defined block sizes which are usually
1718 * different from the NAND page size. When fixing bitflips, ECC engines will
1719 * report the number of errors per chunk, and the NAND core infrastructure
1720 * expect you to return the maximum number of bitflips for the whole page.
1721 * This is why you should always use this function on a single chunk and
1722 * not on the whole page. After checking each chunk you should update your
1723 * max_bitflips value accordingly.
1724 * 2/ When checking for bitflips in erased pages you should not only check
1725 * the payload data but also their associated ECC data, because a user might
1726 * have programmed almost all bits to 1 but a few. In this case, we
1727 * shouldn't consider the chunk as erased, and checking ECC bytes prevent
1728 * this case.
1729 * 3/ The extraoob argument is optional, and should be used if some of your OOB
1730 * data are protected by the ECC engine.
1731 * It could also be used if you support subpages and want to attach some
1732 * extra OOB data to an ECC chunk.
1733 *
1734 * Returns a positive number of bitflips less than or equal to
1735 * bitflips_threshold, or -ERROR_CODE for bitflips in excess of the
1736 * threshold. In case of success, the passed buffers are filled with 0xff.
1737 */
1738 int nand_check_erased_ecc_chunk(void *data, int datalen,
1739 void *ecc, int ecclen,
1740 void *extraoob, int extraooblen,
1741 int bitflips_threshold)
1742 {
1743 int data_bitflips = 0, ecc_bitflips = 0, extraoob_bitflips = 0;
1744
1745 data_bitflips = nand_check_erased_buf(data, datalen,
1746 bitflips_threshold);
1747 if (data_bitflips < 0)
1748 return data_bitflips;
1749
1750 bitflips_threshold -= data_bitflips;
1751
1752 ecc_bitflips = nand_check_erased_buf(ecc, ecclen, bitflips_threshold);
1753 if (ecc_bitflips < 0)
1754 return ecc_bitflips;
1755
1756 bitflips_threshold -= ecc_bitflips;
1757
1758 extraoob_bitflips = nand_check_erased_buf(extraoob, extraooblen,
1759 bitflips_threshold);
1760 if (extraoob_bitflips < 0)
1761 return extraoob_bitflips;
1762
1763 if (data_bitflips)
1764 memset(data, 0xff, datalen);
1765
1766 if (ecc_bitflips)
1767 memset(ecc, 0xff, ecclen);
1768
1769 if (extraoob_bitflips)
1770 memset(extraoob, 0xff, extraooblen);
1771
1772 return data_bitflips + ecc_bitflips + extraoob_bitflips;
1773 }
1774 EXPORT_SYMBOL(nand_check_erased_ecc_chunk);
1775
1776 /**
1777 * nand_read_page_raw - [INTERN] read raw page data without ecc
1778 * @mtd: mtd info structure
1779 * @chip: nand chip info structure
1780 * @buf: buffer to store read data
1781 * @oob_required: caller requires OOB data read to chip->oob_poi
1782 * @page: page number to read
1783 *
1784 * Not for syndrome calculating ECC controllers, which use a special oob layout.
1785 */
1786 static int nand_read_page_raw(struct mtd_info *mtd, struct nand_chip *chip,
1787 uint8_t *buf, int oob_required, int page)
1788 {
1789 int ret;
1790
1791 ret = nand_read_data_op(chip, buf, mtd->writesize, false);
1792 if (ret)
1793 return ret;
1794
1795 if (oob_required) {
1796 ret = nand_read_data_op(chip, chip->oob_poi, mtd->oobsize,
1797 false);
1798 if (ret)
1799 return ret;
1800 }
1801
1802 return 0;
1803 }
1804
1805 /**
1806 * nand_read_page_raw_syndrome - [INTERN] read raw page data without ecc
1807 * @mtd: mtd info structure
1808 * @chip: nand chip info structure
1809 * @buf: buffer to store read data
1810 * @oob_required: caller requires OOB data read to chip->oob_poi
1811 * @page: page number to read
1812 *
1813 * We need a special oob layout and handling even when OOB isn't used.
1814 */
1815 static int nand_read_page_raw_syndrome(struct mtd_info *mtd,
1816 struct nand_chip *chip, uint8_t *buf,
1817 int oob_required, int page)
1818 {
1819 int eccsize = chip->ecc.size;
1820 int eccbytes = chip->ecc.bytes;
1821 uint8_t *oob = chip->oob_poi;
1822 int steps, size, ret;
1823
1824 for (steps = chip->ecc.steps; steps > 0; steps--) {
1825 ret = nand_read_data_op(chip, buf, eccsize, false);
1826 if (ret)
1827 return ret;
1828
1829 buf += eccsize;
1830
1831 if (chip->ecc.prepad) {
1832 ret = nand_read_data_op(chip, oob, chip->ecc.prepad,
1833 false);
1834 if (ret)
1835 return ret;
1836
1837 oob += chip->ecc.prepad;
1838 }
1839
1840 ret = nand_read_data_op(chip, oob, eccbytes, false);
1841 if (ret)
1842 return ret;
1843
1844 oob += eccbytes;
1845
1846 if (chip->ecc.postpad) {
1847 ret = nand_read_data_op(chip, oob, chip->ecc.postpad,
1848 false);
1849 if (ret)
1850 return ret;
1851
1852 oob += chip->ecc.postpad;
1853 }
1854 }
1855
1856 size = mtd->oobsize - (oob - chip->oob_poi);
1857 if (size) {
1858 ret = nand_read_data_op(chip, oob, size, false);
1859 if (ret)
1860 return ret;
1861 }
1862
1863 return 0;
1864 }
1865
1866 /**
1867 * nand_read_page_swecc - [REPLACEABLE] software ECC based page read function
1868 * @mtd: mtd info structure
1869 * @chip: nand chip info structure
1870 * @buf: buffer to store read data
1871 * @oob_required: caller requires OOB data read to chip->oob_poi
1872 * @page: page number to read
1873 */
1874 static int nand_read_page_swecc(struct mtd_info *mtd, struct nand_chip *chip,
1875 uint8_t *buf, int oob_required, int page)
1876 {
1877 int i, eccsize = chip->ecc.size;
1878 int eccbytes = chip->ecc.bytes;
1879 int eccsteps = chip->ecc.steps;
1880 uint8_t *p = buf;
1881 uint8_t *ecc_calc = chip->buffers->ecccalc;
1882 uint8_t *ecc_code = chip->buffers->ecccode;
1883 uint32_t *eccpos = chip->ecc.layout->eccpos;
1884 unsigned int max_bitflips = 0;
1885
1886 chip->ecc.read_page_raw(mtd, chip, buf, 1, page);
1887
1888 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize)
1889 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
1890
1891 for (i = 0; i < chip->ecc.total; i++)
1892 ecc_code[i] = chip->oob_poi[eccpos[i]];
1893
1894 eccsteps = chip->ecc.steps;
1895 p = buf;
1896
1897 for (i = 0 ; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
1898 int stat;
1899
1900 stat = chip->ecc.correct(mtd, p, &ecc_code[i], &ecc_calc[i]);
1901 if (stat < 0) {
1902 mtd->ecc_stats.failed++;
1903 } else {
1904 mtd->ecc_stats.corrected += stat;
1905 max_bitflips = max_t(unsigned int, max_bitflips, stat);
1906 }
1907 }
1908 return max_bitflips;
1909 }
1910
1911 /**
1912 * nand_read_subpage - [REPLACEABLE] ECC based sub-page read function
1913 * @mtd: mtd info structure
1914 * @chip: nand chip info structure
1915 * @data_offs: offset of requested data within the page
1916 * @readlen: data length
1917 * @bufpoi: buffer to store read data
1918 * @page: page number to read
1919 */
1920 static int nand_read_subpage(struct mtd_info *mtd, struct nand_chip *chip,
1921 uint32_t data_offs, uint32_t readlen, uint8_t *bufpoi,
1922 int page)
1923 {
1924 int start_step, end_step, num_steps;
1925 uint32_t *eccpos = chip->ecc.layout->eccpos;
1926 uint8_t *p;
1927 int data_col_addr, i, gaps = 0;
1928 int datafrag_len, eccfrag_len, aligned_len, aligned_pos;
1929 int busw = (chip->options & NAND_BUSWIDTH_16) ? 2 : 1;
1930 int index;
1931 unsigned int max_bitflips = 0;
1932 int ret;
1933
1934 /* Column address within the page aligned to ECC size (256bytes) */
1935 start_step = data_offs / chip->ecc.size;
1936 end_step = (data_offs + readlen - 1) / chip->ecc.size;
1937 num_steps = end_step - start_step + 1;
1938 index = start_step * chip->ecc.bytes;
1939
1940 /* Data size aligned to ECC ecc.size */
1941 datafrag_len = num_steps * chip->ecc.size;
1942 eccfrag_len = num_steps * chip->ecc.bytes;
1943
1944 data_col_addr = start_step * chip->ecc.size;
1945 /* If we read not a page aligned data */
1946 if (data_col_addr != 0)
1947 chip->cmdfunc(mtd, NAND_CMD_RNDOUT, data_col_addr, -1);
1948
1949 p = bufpoi + data_col_addr;
1950 ret = nand_read_data_op(chip, p, datafrag_len, false);
1951 if (ret)
1952 return ret;
1953
1954 /* Calculate ECC */
1955 for (i = 0; i < eccfrag_len ; i += chip->ecc.bytes, p += chip->ecc.size)
1956 chip->ecc.calculate(mtd, p, &chip->buffers->ecccalc[i]);
1957
1958 /*
1959 * The performance is faster if we position offsets according to
1960 * ecc.pos. Let's make sure that there are no gaps in ECC positions.
1961 */
1962 for (i = 0; i < eccfrag_len - 1; i++) {
1963 if (eccpos[i + index] + 1 != eccpos[i + index + 1]) {
1964 gaps = 1;
1965 break;
1966 }
1967 }
1968 if (gaps) {
1969 ret = nand_change_read_column_op(chip, mtd->writesize,
1970 chip->oob_poi, mtd->oobsize,
1971 false);
1972 if (ret)
1973 return ret;
1974 } else {
1975 /*
1976 * Send the command to read the particular ECC bytes take care
1977 * about buswidth alignment in read_buf.
1978 */
1979 aligned_pos = eccpos[index] & ~(busw - 1);
1980 aligned_len = eccfrag_len;
1981 if (eccpos[index] & (busw - 1))
1982 aligned_len++;
1983 if (eccpos[index + (num_steps * chip->ecc.bytes)] & (busw - 1))
1984 aligned_len++;
1985
1986 ret = nand_change_read_column_op(chip,
1987 mtd->writesize + aligned_pos,
1988 &chip->oob_poi[aligned_pos],
1989 aligned_len, false);
1990 if (ret)
1991 return ret;
1992 }
1993
1994 for (i = 0; i < eccfrag_len; i++)
1995 chip->buffers->ecccode[i] = chip->oob_poi[eccpos[i + index]];
1996
1997 p = bufpoi + data_col_addr;
1998 for (i = 0; i < eccfrag_len ; i += chip->ecc.bytes, p += chip->ecc.size) {
1999 int stat;
2000
2001 stat = chip->ecc.correct(mtd, p,
2002 &chip->buffers->ecccode[i], &chip->buffers->ecccalc[i]);
2003 if (stat == -EBADMSG &&
2004 (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
2005 /* check for empty pages with bitflips */
2006 stat = nand_check_erased_ecc_chunk(p, chip->ecc.size,
2007 &chip->buffers->ecccode[i],
2008 chip->ecc.bytes,
2009 NULL, 0,
2010 chip->ecc.strength);
2011 }
2012
2013 if (stat < 0) {
2014 mtd->ecc_stats.failed++;
2015 } else {
2016 mtd->ecc_stats.corrected += stat;
2017 max_bitflips = max_t(unsigned int, max_bitflips, stat);
2018 }
2019 }
2020 return max_bitflips;
2021 }
2022
2023 /**
2024 * nand_read_page_hwecc - [REPLACEABLE] hardware ECC based page read function
2025 * @mtd: mtd info structure
2026 * @chip: nand chip info structure
2027 * @buf: buffer to store read data
2028 * @oob_required: caller requires OOB data read to chip->oob_poi
2029 * @page: page number to read
2030 *
2031 * Not for syndrome calculating ECC controllers which need a special oob layout.
2032 */
2033 static int nand_read_page_hwecc(struct mtd_info *mtd, struct nand_chip *chip,
2034 uint8_t *buf, int oob_required, int page)
2035 {
2036 int i, eccsize = chip->ecc.size;
2037 int eccbytes = chip->ecc.bytes;
2038 int eccsteps = chip->ecc.steps;
2039 uint8_t *p = buf;
2040 uint8_t *ecc_calc = chip->buffers->ecccalc;
2041 uint8_t *ecc_code = chip->buffers->ecccode;
2042 uint32_t *eccpos = chip->ecc.layout->eccpos;
2043 unsigned int max_bitflips = 0;
2044 int ret;
2045
2046 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
2047 chip->ecc.hwctl(mtd, NAND_ECC_READ);
2048
2049 ret = nand_read_data_op(chip, p, eccsize, false);
2050 if (ret)
2051 return ret;
2052
2053 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
2054 }
2055
2056 ret = nand_read_data_op(chip, chip->oob_poi, mtd->oobsize, false);
2057 if (ret)
2058 return ret;
2059
2060 for (i = 0; i < chip->ecc.total; i++)
2061 ecc_code[i] = chip->oob_poi[eccpos[i]];
2062
2063 eccsteps = chip->ecc.steps;
2064 p = buf;
2065
2066 for (i = 0 ; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
2067 int stat;
2068
2069 stat = chip->ecc.correct(mtd, p, &ecc_code[i], &ecc_calc[i]);
2070 if (stat == -EBADMSG &&
2071 (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
2072 /* check for empty pages with bitflips */
2073 stat = nand_check_erased_ecc_chunk(p, eccsize,
2074 &ecc_code[i], eccbytes,
2075 NULL, 0,
2076 chip->ecc.strength);
2077 }
2078
2079 if (stat < 0) {
2080 mtd->ecc_stats.failed++;
2081 } else {
2082 mtd->ecc_stats.corrected += stat;
2083 max_bitflips = max_t(unsigned int, max_bitflips, stat);
2084 }
2085 }
2086 return max_bitflips;
2087 }
2088
2089 /**
2090 * nand_read_page_hwecc_oob_first - [REPLACEABLE] hw ecc, read oob first
2091 * @mtd: mtd info structure
2092 * @chip: nand chip info structure
2093 * @buf: buffer to store read data
2094 * @oob_required: caller requires OOB data read to chip->oob_poi
2095 * @page: page number to read
2096 *
2097 * Hardware ECC for large page chips, require OOB to be read first. For this
2098 * ECC mode, the write_page method is re-used from ECC_HW. These methods
2099 * read/write ECC from the OOB area, unlike the ECC_HW_SYNDROME support with
2100 * multiple ECC steps, follows the "infix ECC" scheme and reads/writes ECC from
2101 * the data area, by overwriting the NAND manufacturer bad block markings.
2102 */
2103 static int nand_read_page_hwecc_oob_first(struct mtd_info *mtd,
2104 struct nand_chip *chip, uint8_t *buf, int oob_required, int page)
2105 {
2106 int i, eccsize = chip->ecc.size;
2107 int eccbytes = chip->ecc.bytes;
2108 int eccsteps = chip->ecc.steps;
2109 uint8_t *p = buf;
2110 uint8_t *ecc_code = chip->buffers->ecccode;
2111 uint32_t *eccpos = chip->ecc.layout->eccpos;
2112 uint8_t *ecc_calc = chip->buffers->ecccalc;
2113 unsigned int max_bitflips = 0;
2114 int ret;
2115
2116 /* Read the OOB area first */
2117 ret = nand_read_oob_op(chip, page, 0, chip->oob_poi, mtd->oobsize);
2118 if (ret)
2119 return ret;
2120
2121 ret = nand_read_page_op(chip, page, 0, NULL, 0);
2122 if (ret)
2123 return ret;
2124
2125 for (i = 0; i < chip->ecc.total; i++)
2126 ecc_code[i] = chip->oob_poi[eccpos[i]];
2127
2128 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
2129 int stat;
2130
2131 chip->ecc.hwctl(mtd, NAND_ECC_READ);
2132
2133 ret = nand_read_data_op(chip, p, eccsize, false);
2134 if (ret)
2135 return ret;
2136
2137 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
2138
2139 stat = chip->ecc.correct(mtd, p, &ecc_code[i], NULL);
2140 if (stat == -EBADMSG &&
2141 (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
2142 /* check for empty pages with bitflips */
2143 stat = nand_check_erased_ecc_chunk(p, eccsize,
2144 &ecc_code[i], eccbytes,
2145 NULL, 0,
2146 chip->ecc.strength);
2147 }
2148
2149 if (stat < 0) {
2150 mtd->ecc_stats.failed++;
2151 } else {
2152 mtd->ecc_stats.corrected += stat;
2153 max_bitflips = max_t(unsigned int, max_bitflips, stat);
2154 }
2155 }
2156 return max_bitflips;
2157 }
2158
2159 /**
2160 * nand_read_page_syndrome - [REPLACEABLE] hardware ECC syndrome based page read
2161 * @mtd: mtd info structure
2162 * @chip: nand chip info structure
2163 * @buf: buffer to store read data
2164 * @oob_required: caller requires OOB data read to chip->oob_poi
2165 * @page: page number to read
2166 *
2167 * The hw generator calculates the error syndrome automatically. Therefore we
2168 * need a special oob layout and handling.
2169 */
2170 static int nand_read_page_syndrome(struct mtd_info *mtd, struct nand_chip *chip,
2171 uint8_t *buf, int oob_required, int page)
2172 {
2173 int ret, i, eccsize = chip->ecc.size;
2174 int eccbytes = chip->ecc.bytes;
2175 int eccsteps = chip->ecc.steps;
2176 int eccpadbytes = eccbytes + chip->ecc.prepad + chip->ecc.postpad;
2177 uint8_t *p = buf;
2178 uint8_t *oob = chip->oob_poi;
2179 unsigned int max_bitflips = 0;
2180
2181 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
2182 int stat;
2183
2184 chip->ecc.hwctl(mtd, NAND_ECC_READ);
2185
2186 ret = nand_read_data_op(chip, p, eccsize, false);
2187 if (ret)
2188 return ret;
2189
2190 if (chip->ecc.prepad) {
2191 ret = nand_read_data_op(chip, oob, chip->ecc.prepad,
2192 false);
2193 if (ret)
2194 return ret;
2195
2196 oob += chip->ecc.prepad;
2197 }
2198
2199 chip->ecc.hwctl(mtd, NAND_ECC_READSYN);
2200
2201 ret = nand_read_data_op(chip, oob, eccbytes, false);
2202 if (ret)
2203 return ret;
2204
2205 stat = chip->ecc.correct(mtd, p, oob, NULL);
2206
2207 oob += eccbytes;
2208
2209 if (chip->ecc.postpad) {
2210 ret = nand_read_data_op(chip, oob, chip->ecc.postpad,
2211 false);
2212 if (ret)
2213 return ret;
2214
2215 oob += chip->ecc.postpad;
2216 }
2217
2218 if (stat == -EBADMSG &&
2219 (chip->ecc.options & NAND_ECC_GENERIC_ERASED_CHECK)) {
2220 /* check for empty pages with bitflips */
2221 stat = nand_check_erased_ecc_chunk(p, chip->ecc.size,
2222 oob - eccpadbytes,
2223 eccpadbytes,
2224 NULL, 0,
2225 chip->ecc.strength);
2226 }
2227
2228 if (stat < 0) {
2229 mtd->ecc_stats.failed++;
2230 } else {
2231 mtd->ecc_stats.corrected += stat;
2232 max_bitflips = max_t(unsigned int, max_bitflips, stat);
2233 }
2234 }
2235
2236 /* Calculate remaining oob bytes */
2237 i = mtd->oobsize - (oob - chip->oob_poi);
2238 if (i) {
2239 ret = nand_read_data_op(chip, oob, i, false);
2240 if (ret)
2241 return ret;
2242 }
2243
2244 return max_bitflips;
2245 }
2246
2247 /**
2248 * nand_transfer_oob - [INTERN] Transfer oob to client buffer
2249 * @chip: nand chip structure
2250 * @oob: oob destination address
2251 * @ops: oob ops structure
2252 * @len: size of oob to transfer
2253 */
2254 static uint8_t *nand_transfer_oob(struct nand_chip *chip, uint8_t *oob,
2255 struct mtd_oob_ops *ops, size_t len)
2256 {
2257 switch (ops->mode) {
2258
2259 case MTD_OPS_PLACE_OOB:
2260 case MTD_OPS_RAW:
2261 memcpy(oob, chip->oob_poi + ops->ooboffs, len);
2262 return oob + len;
2263
2264 case MTD_OPS_AUTO_OOB: {
2265 struct nand_oobfree *free = chip->ecc.layout->oobfree;
2266 uint32_t boffs = 0, roffs = ops->ooboffs;
2267 size_t bytes = 0;
2268
2269 for (; free->length && len; free++, len -= bytes) {
2270 /* Read request not from offset 0? */
2271 if (unlikely(roffs)) {
2272 if (roffs >= free->length) {
2273 roffs -= free->length;
2274 continue;
2275 }
2276 boffs = free->offset + roffs;
2277 bytes = min_t(size_t, len,
2278 (free->length - roffs));
2279 roffs = 0;
2280 } else {
2281 bytes = min_t(size_t, len, free->length);
2282 boffs = free->offset;
2283 }
2284 memcpy(oob, chip->oob_poi + boffs, bytes);
2285 oob += bytes;
2286 }
2287 return oob;
2288 }
2289 default:
2290 BUG();
2291 }
2292 return NULL;
2293 }
2294
2295 /**
2296 * nand_setup_read_retry - [INTERN] Set the READ RETRY mode
2297 * @mtd: MTD device structure
2298 * @retry_mode: the retry mode to use
2299 *
2300 * Some vendors supply a special command to shift the Vt threshold, to be used
2301 * when there are too many bitflips in a page (i.e., ECC error). After setting
2302 * a new threshold, the host should retry reading the page.
2303 */
2304 static int nand_setup_read_retry(struct mtd_info *mtd, int retry_mode)
2305 {
2306 struct nand_chip *chip = mtd_to_nand(mtd);
2307
2308 pr_debug("setting READ RETRY mode %d\n", retry_mode);
2309
2310 if (retry_mode >= chip->read_retries)
2311 return -EINVAL;
2312
2313 if (!chip->setup_read_retry)
2314 return -EOPNOTSUPP;
2315
2316 return chip->setup_read_retry(mtd, retry_mode);
2317 }
2318
2319 /**
2320 * nand_do_read_ops - [INTERN] Read data with ECC
2321 * @mtd: MTD device structure
2322 * @from: offset to read from
2323 * @ops: oob ops structure
2324 *
2325 * Internal function. Called with chip held.
2326 */
2327 static int nand_do_read_ops(struct mtd_info *mtd, loff_t from,
2328 struct mtd_oob_ops *ops)
2329 {
2330 int chipnr, page, realpage, col, bytes, aligned, oob_required;
2331 struct nand_chip *chip = mtd_to_nand(mtd);
2332 int ret = 0;
2333 uint32_t readlen = ops->len;
2334 uint32_t oobreadlen = ops->ooblen;
2335 uint32_t max_oobsize = mtd_oobavail(mtd, ops);
2336
2337 uint8_t *bufpoi, *oob, *buf;
2338 int use_bufpoi;
2339 unsigned int max_bitflips = 0;
2340 int retry_mode = 0;
2341 bool ecc_fail = false;
2342
2343 chipnr = (int)(from >> chip->chip_shift);
2344 chip->select_chip(mtd, chipnr);
2345
2346 realpage = (int)(from >> chip->page_shift);
2347 page = realpage & chip->pagemask;
2348
2349 col = (int)(from & (mtd->writesize - 1));
2350
2351 buf = ops->datbuf;
2352 oob = ops->oobbuf;
2353 oob_required = oob ? 1 : 0;
2354
2355 while (1) {
2356 unsigned int ecc_failures = mtd->ecc_stats.failed;
2357
2358 schedule();
2359 bytes = min(mtd->writesize - col, readlen);
2360 aligned = (bytes == mtd->writesize);
2361
2362 if (!aligned)
2363 use_bufpoi = 1;
2364 else if (chip->options & NAND_USE_BOUNCE_BUFFER)
2365 use_bufpoi = !IS_ALIGNED((unsigned long)buf,
2366 chip->buf_align);
2367 else
2368 use_bufpoi = 0;
2369
2370 /* Is the current page in the buffer? */
2371 if (realpage != chip->pagebuf || oob) {
2372 bufpoi = use_bufpoi ? chip->buffers->databuf : buf;
2373
2374 if (use_bufpoi && aligned)
2375 pr_debug("%s: using read bounce buffer for buf@%p\n",
2376 __func__, buf);
2377
2378 read_retry:
2379 if (nand_standard_page_accessors(&chip->ecc)) {
2380 ret = nand_read_page_op(chip, page, 0, NULL, 0);
2381 if (ret)
2382 break;
2383 }
2384
2385 /*
2386 * Now read the page into the buffer. Absent an error,
2387 * the read methods return max bitflips per ecc step.
2388 */
2389 if (unlikely(ops->mode == MTD_OPS_RAW))
2390 ret = chip->ecc.read_page_raw(mtd, chip, bufpoi,
2391 oob_required,
2392 page);
2393 else if (!aligned && NAND_HAS_SUBPAGE_READ(chip) &&
2394 !oob)
2395 ret = chip->ecc.read_subpage(mtd, chip,
2396 col, bytes, bufpoi,
2397 page);
2398 else
2399 ret = chip->ecc.read_page(mtd, chip, bufpoi,
2400 oob_required, page);
2401 if (ret < 0) {
2402 if (use_bufpoi)
2403 /* Invalidate page cache */
2404 chip->pagebuf = -1;
2405 break;
2406 }
2407
2408 max_bitflips = max_t(unsigned int, max_bitflips, ret);
2409
2410 /* Transfer not aligned data */
2411 if (use_bufpoi) {
2412 if (!NAND_HAS_SUBPAGE_READ(chip) && !oob &&
2413 !(mtd->ecc_stats.failed - ecc_failures) &&
2414 (ops->mode != MTD_OPS_RAW)) {
2415 chip->pagebuf = realpage;
2416 chip->pagebuf_bitflips = ret;
2417 } else {
2418 /* Invalidate page cache */
2419 chip->pagebuf = -1;
2420 }
2421 memcpy(buf, chip->buffers->databuf + col, bytes);
2422 }
2423
2424 if (unlikely(oob)) {
2425 int toread = min(oobreadlen, max_oobsize);
2426
2427 if (toread) {
2428 oob = nand_transfer_oob(chip,
2429 oob, ops, toread);
2430 oobreadlen -= toread;
2431 }
2432 }
2433
2434 if (chip->options & NAND_NEED_READRDY) {
2435 /* Apply delay or wait for ready/busy pin */
2436 if (!chip->dev_ready)
2437 udelay(chip->chip_delay);
2438 else
2439 nand_wait_ready(mtd);
2440 }
2441
2442 if (mtd->ecc_stats.failed - ecc_failures) {
2443 if (retry_mode + 1 < chip->read_retries) {
2444 retry_mode++;
2445 ret = nand_setup_read_retry(mtd,
2446 retry_mode);
2447 if (ret < 0)
2448 break;
2449
2450 /* Reset failures; retry */
2451 mtd->ecc_stats.failed = ecc_failures;
2452 goto read_retry;
2453 } else {
2454 /* No more retry modes; real failure */
2455 ecc_fail = true;
2456 }
2457 }
2458
2459 buf += bytes;
2460 } else {
2461 memcpy(buf, chip->buffers->databuf + col, bytes);
2462 buf += bytes;
2463 max_bitflips = max_t(unsigned int, max_bitflips,
2464 chip->pagebuf_bitflips);
2465 }
2466
2467 readlen -= bytes;
2468
2469 /* Reset to retry mode 0 */
2470 if (retry_mode) {
2471 ret = nand_setup_read_retry(mtd, 0);
2472 if (ret < 0)
2473 break;
2474 retry_mode = 0;
2475 }
2476
2477 if (!readlen)
2478 break;
2479
2480 /* For subsequent reads align to page boundary */
2481 col = 0;
2482 /* Increment page address */
2483 realpage++;
2484
2485 page = realpage & chip->pagemask;
2486 /* Check, if we cross a chip boundary */
2487 if (!page) {
2488 chipnr++;
2489 chip->select_chip(mtd, -1);
2490 chip->select_chip(mtd, chipnr);
2491 }
2492 }
2493 chip->select_chip(mtd, -1);
2494
2495 ops->retlen = ops->len - (size_t) readlen;
2496 if (oob)
2497 ops->oobretlen = ops->ooblen - oobreadlen;
2498
2499 if (ret < 0)
2500 return ret;
2501
2502 if (ecc_fail)
2503 return -EBADMSG;
2504
2505 return max_bitflips;
2506 }
2507
2508 /**
2509 * nand_read_oob_std - [REPLACEABLE] the most common OOB data read function
2510 * @mtd: mtd info structure
2511 * @chip: nand chip info structure
2512 * @page: page number to read
2513 */
2514 static int nand_read_oob_std(struct mtd_info *mtd, struct nand_chip *chip,
2515 int page)
2516 {
2517 return nand_read_oob_op(chip, page, 0, chip->oob_poi, mtd->oobsize);
2518 }
2519
2520 /**
2521 * nand_read_oob_syndrome - [REPLACEABLE] OOB data read function for HW ECC
2522 * with syndromes
2523 * @mtd: mtd info structure
2524 * @chip: nand chip info structure
2525 * @page: page number to read
2526 */
2527 static int nand_read_oob_syndrome(struct mtd_info *mtd, struct nand_chip *chip,
2528 int page)
2529 {
2530 int length = mtd->oobsize;
2531 int chunk = chip->ecc.bytes + chip->ecc.prepad + chip->ecc.postpad;
2532 int eccsize = chip->ecc.size;
2533 uint8_t *bufpoi = chip->oob_poi;
2534 int i, toread, sndrnd = 0, pos, ret;
2535
2536 ret = nand_read_page_op(chip, page, chip->ecc.size, NULL, 0);
2537 if (ret)
2538 return ret;
2539
2540 for (i = 0; i < chip->ecc.steps; i++) {
2541 if (sndrnd) {
2542 int ret;
2543
2544 pos = eccsize + i * (eccsize + chunk);
2545 if (mtd->writesize > 512)
2546 ret = nand_change_read_column_op(chip, pos,
2547 NULL, 0,
2548 false);
2549 else
2550 ret = nand_read_page_op(chip, page, pos, NULL,
2551 0);
2552
2553 if (ret)
2554 return ret;
2555 } else
2556 sndrnd = 1;
2557 toread = min_t(int, length, chunk);
2558
2559 ret = nand_read_data_op(chip, bufpoi, toread, false);
2560 if (ret)
2561 return ret;
2562
2563 bufpoi += toread;
2564 length -= toread;
2565 }
2566 if (length > 0) {
2567 ret = nand_read_data_op(chip, bufpoi, length, false);
2568 if (ret)
2569 return ret;
2570 }
2571
2572 return 0;
2573 }
2574
2575 /**
2576 * nand_write_oob_std - [REPLACEABLE] the most common OOB data write function
2577 * @mtd: mtd info structure
2578 * @chip: nand chip info structure
2579 * @page: page number to write
2580 */
2581 static int nand_write_oob_std(struct mtd_info *mtd, struct nand_chip *chip,
2582 int page)
2583 {
2584 return nand_prog_page_op(chip, page, mtd->writesize, chip->oob_poi,
2585 mtd->oobsize);
2586 }
2587
2588 /**
2589 * nand_write_oob_syndrome - [REPLACEABLE] OOB data write function for HW ECC
2590 * with syndrome - only for large page flash
2591 * @mtd: mtd info structure
2592 * @chip: nand chip info structure
2593 * @page: page number to write
2594 */
2595 static int nand_write_oob_syndrome(struct mtd_info *mtd,
2596 struct nand_chip *chip, int page)
2597 {
2598 int chunk = chip->ecc.bytes + chip->ecc.prepad + chip->ecc.postpad;
2599 int eccsize = chip->ecc.size, length = mtd->oobsize;
2600 int ret, i, len, pos, sndcmd = 0, steps = chip->ecc.steps;
2601 const uint8_t *bufpoi = chip->oob_poi;
2602
2603 /*
2604 * data-ecc-data-ecc ... ecc-oob
2605 * or
2606 * data-pad-ecc-pad-data-pad .... ecc-pad-oob
2607 */
2608 if (!chip->ecc.prepad && !chip->ecc.postpad) {
2609 pos = steps * (eccsize + chunk);
2610 steps = 0;
2611 } else
2612 pos = eccsize;
2613
2614 ret = nand_prog_page_begin_op(chip, page, pos, NULL, 0);
2615 if (ret)
2616 return ret;
2617
2618 for (i = 0; i < steps; i++) {
2619 if (sndcmd) {
2620 if (mtd->writesize <= 512) {
2621 uint32_t fill = 0xFFFFFFFF;
2622
2623 len = eccsize;
2624 while (len > 0) {
2625 int num = min_t(int, len, 4);
2626
2627 ret = nand_write_data_op(chip, &fill,
2628 num, false);
2629 if (ret)
2630 return ret;
2631
2632 len -= num;
2633 }
2634 } else {
2635 pos = eccsize + i * (eccsize + chunk);
2636 ret = nand_change_write_column_op(chip, pos,
2637 NULL, 0,
2638 false);
2639 if (ret)
2640 return ret;
2641 }
2642 } else
2643 sndcmd = 1;
2644 len = min_t(int, length, chunk);
2645
2646 ret = nand_write_data_op(chip, bufpoi, len, false);
2647 if (ret)
2648 return ret;
2649
2650 bufpoi += len;
2651 length -= len;
2652 }
2653 if (length > 0) {
2654 ret = nand_write_data_op(chip, bufpoi, length, false);
2655 if (ret)
2656 return ret;
2657 }
2658
2659 return nand_prog_page_end_op(chip);
2660 }
2661
2662 /**
2663 * nand_do_read_oob - [INTERN] NAND read out-of-band
2664 * @mtd: MTD device structure
2665 * @from: offset to read from
2666 * @ops: oob operations description structure
2667 *
2668 * NAND read out-of-band data from the spare area.
2669 */
2670 static int nand_do_read_oob(struct mtd_info *mtd, loff_t from,
2671 struct mtd_oob_ops *ops)
2672 {
2673 int page, realpage, chipnr;
2674 struct nand_chip *chip = mtd_to_nand(mtd);
2675 struct mtd_ecc_stats stats;
2676 int readlen = ops->ooblen;
2677 int len;
2678 uint8_t *buf = ops->oobbuf;
2679 int ret = 0;
2680
2681 pr_debug("%s: from = 0x%08Lx, len = %i\n",
2682 __func__, (unsigned long long)from, readlen);
2683
2684 stats = mtd->ecc_stats;
2685
2686 len = mtd_oobavail(mtd, ops);
2687
2688 if (unlikely(ops->ooboffs >= len)) {
2689 pr_debug("%s: attempt to start read outside oob\n",
2690 __func__);
2691 return -EINVAL;
2692 }
2693
2694 /* Do not allow reads past end of device */
2695 if (unlikely(from >= mtd->size ||
2696 ops->ooboffs + readlen > ((mtd->size >> chip->page_shift) -
2697 (from >> chip->page_shift)) * len)) {
2698 pr_debug("%s: attempt to read beyond end of device\n",
2699 __func__);
2700 return -EINVAL;
2701 }
2702
2703 chipnr = (int)(from >> chip->chip_shift);
2704 chip->select_chip(mtd, chipnr);
2705
2706 /* Shift to get page */
2707 realpage = (int)(from >> chip->page_shift);
2708 page = realpage & chip->pagemask;
2709
2710 while (1) {
2711 schedule();
2712
2713 if (ops->mode == MTD_OPS_RAW)
2714 ret = chip->ecc.read_oob_raw(mtd, chip, page);
2715 else
2716 ret = chip->ecc.read_oob(mtd, chip, page);
2717
2718 if (ret < 0)
2719 break;
2720
2721 len = min(len, readlen);
2722 buf = nand_transfer_oob(chip, buf, ops, len);
2723
2724 if (chip->options & NAND_NEED_READRDY) {
2725 /* Apply delay or wait for ready/busy pin */
2726 if (!chip->dev_ready)
2727 udelay(chip->chip_delay);
2728 else
2729 nand_wait_ready(mtd);
2730 }
2731
2732 readlen -= len;
2733 if (!readlen)
2734 break;
2735
2736 /* Increment page address */
2737 realpage++;
2738
2739 page = realpage & chip->pagemask;
2740 /* Check, if we cross a chip boundary */
2741 if (!page) {
2742 chipnr++;
2743 chip->select_chip(mtd, -1);
2744 chip->select_chip(mtd, chipnr);
2745 }
2746 }
2747 chip->select_chip(mtd, -1);
2748
2749 ops->oobretlen = ops->ooblen - readlen;
2750
2751 if (ret < 0)
2752 return ret;
2753
2754 if (mtd->ecc_stats.failed - stats.failed)
2755 return -EBADMSG;
2756
2757 return mtd->ecc_stats.corrected - stats.corrected ? -EUCLEAN : 0;
2758 }
2759
2760 /**
2761 * nand_read_oob - [MTD Interface] NAND read data and/or out-of-band
2762 * @mtd: MTD device structure
2763 * @from: offset to read from
2764 * @ops: oob operation description structure
2765 *
2766 * NAND read data and/or out-of-band data.
2767 */
2768 static int nand_read_oob(struct mtd_info *mtd, loff_t from,
2769 struct mtd_oob_ops *ops)
2770 {
2771 int ret = -ENOTSUPP;
2772
2773 ops->retlen = 0;
2774
2775 /* Do not allow reads past end of device */
2776 if (ops->datbuf && (from + ops->len) > mtd->size) {
2777 pr_debug("%s: attempt to read beyond end of device\n",
2778 __func__);
2779 return -EINVAL;
2780 }
2781
2782 nand_get_device(mtd, FL_READING);
2783
2784 switch (ops->mode) {
2785 case MTD_OPS_PLACE_OOB:
2786 case MTD_OPS_AUTO_OOB:
2787 case MTD_OPS_RAW:
2788 break;
2789
2790 default:
2791 goto out;
2792 }
2793
2794 if (!ops->datbuf)
2795 ret = nand_do_read_oob(mtd, from, ops);
2796 else
2797 ret = nand_do_read_ops(mtd, from, ops);
2798
2799 out:
2800 nand_release_device(mtd);
2801 return ret;
2802 }
2803
2804
2805 /**
2806 * nand_write_page_raw - [INTERN] raw page write function
2807 * @mtd: mtd info structure
2808 * @chip: nand chip info structure
2809 * @buf: data buffer
2810 * @oob_required: must write chip->oob_poi to OOB
2811 * @page: page number to write
2812 *
2813 * Not for syndrome calculating ECC controllers, which use a special oob layout.
2814 */
2815 static int nand_write_page_raw(struct mtd_info *mtd, struct nand_chip *chip,
2816 const uint8_t *buf, int oob_required, int page)
2817 {
2818 int ret;
2819
2820 ret = nand_write_data_op(chip, buf, mtd->writesize, false);
2821 if (ret)
2822 return ret;
2823
2824 if (oob_required) {
2825 ret = nand_write_data_op(chip, chip->oob_poi, mtd->oobsize,
2826 false);
2827 if (ret)
2828 return ret;
2829 }
2830
2831 return 0;
2832 }
2833
2834 /**
2835 * nand_write_page_raw_syndrome - [INTERN] raw page write function
2836 * @mtd: mtd info structure
2837 * @chip: nand chip info structure
2838 * @buf: data buffer
2839 * @oob_required: must write chip->oob_poi to OOB
2840 * @page: page number to write
2841 *
2842 * We need a special oob layout and handling even when ECC isn't checked.
2843 */
2844 static int nand_write_page_raw_syndrome(struct mtd_info *mtd,
2845 struct nand_chip *chip,
2846 const uint8_t *buf, int oob_required,
2847 int page)
2848 {
2849 int eccsize = chip->ecc.size;
2850 int eccbytes = chip->ecc.bytes;
2851 uint8_t *oob = chip->oob_poi;
2852 int steps, size, ret;
2853
2854 for (steps = chip->ecc.steps; steps > 0; steps--) {
2855 ret = nand_write_data_op(chip, buf, eccsize, false);
2856 if (ret)
2857 return ret;
2858
2859 buf += eccsize;
2860
2861 if (chip->ecc.prepad) {
2862 ret = nand_write_data_op(chip, oob, chip->ecc.prepad,
2863 false);
2864 if (ret)
2865 return ret;
2866
2867 oob += chip->ecc.prepad;
2868 }
2869
2870 ret = nand_write_data_op(chip, oob, eccbytes, false);
2871 if (ret)
2872 return ret;
2873
2874 oob += eccbytes;
2875
2876 if (chip->ecc.postpad) {
2877 ret = nand_write_data_op(chip, oob, chip->ecc.postpad,
2878 false);
2879 if (ret)
2880 return ret;
2881
2882 oob += chip->ecc.postpad;
2883 }
2884 }
2885
2886 size = mtd->oobsize - (oob - chip->oob_poi);
2887 if (size) {
2888 ret = nand_write_data_op(chip, oob, size, false);
2889 if (ret)
2890 return ret;
2891 }
2892
2893 return 0;
2894 }
2895 /**
2896 * nand_write_page_swecc - [REPLACEABLE] software ECC based page write function
2897 * @mtd: mtd info structure
2898 * @chip: nand chip info structure
2899 * @buf: data buffer
2900 * @oob_required: must write chip->oob_poi to OOB
2901 * @page: page number to write
2902 */
2903 static int nand_write_page_swecc(struct mtd_info *mtd, struct nand_chip *chip,
2904 const uint8_t *buf, int oob_required,
2905 int page)
2906 {
2907 int i, eccsize = chip->ecc.size;
2908 int eccbytes = chip->ecc.bytes;
2909 int eccsteps = chip->ecc.steps;
2910 uint8_t *ecc_calc = chip->buffers->ecccalc;
2911 const uint8_t *p = buf;
2912 uint32_t *eccpos = chip->ecc.layout->eccpos;
2913
2914 /* Software ECC calculation */
2915 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize)
2916 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
2917
2918 for (i = 0; i < chip->ecc.total; i++)
2919 chip->oob_poi[eccpos[i]] = ecc_calc[i];
2920
2921 return chip->ecc.write_page_raw(mtd, chip, buf, 1, page);
2922 }
2923
2924 /**
2925 * nand_write_page_hwecc - [REPLACEABLE] hardware ECC based page write function
2926 * @mtd: mtd info structure
2927 * @chip: nand chip info structure
2928 * @buf: data buffer
2929 * @oob_required: must write chip->oob_poi to OOB
2930 * @page: page number to write
2931 */
2932 static int nand_write_page_hwecc(struct mtd_info *mtd, struct nand_chip *chip,
2933 const uint8_t *buf, int oob_required,
2934 int page)
2935 {
2936 int i, eccsize = chip->ecc.size;
2937 int eccbytes = chip->ecc.bytes;
2938 int eccsteps = chip->ecc.steps;
2939 uint8_t *ecc_calc = chip->buffers->ecccalc;
2940 const uint8_t *p = buf;
2941 uint32_t *eccpos = chip->ecc.layout->eccpos;
2942 int ret;
2943
2944 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
2945 chip->ecc.hwctl(mtd, NAND_ECC_WRITE);
2946
2947 ret = nand_write_data_op(chip, p, eccsize, false);
2948 if (ret)
2949 return ret;
2950
2951 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
2952 }
2953
2954 for (i = 0; i < chip->ecc.total; i++)
2955 chip->oob_poi[eccpos[i]] = ecc_calc[i];
2956
2957 ret = nand_write_data_op(chip, chip->oob_poi, mtd->oobsize, false);
2958 if (ret)
2959 return ret;
2960
2961 return 0;
2962 }
2963
2964
2965 /**
2966 * nand_write_subpage_hwecc - [REPLACEABLE] hardware ECC based subpage write
2967 * @mtd: mtd info structure
2968 * @chip: nand chip info structure
2969 * @offset: column address of subpage within the page
2970 * @data_len: data length
2971 * @buf: data buffer
2972 * @oob_required: must write chip->oob_poi to OOB
2973 * @page: page number to write
2974 */
2975 static int nand_write_subpage_hwecc(struct mtd_info *mtd,
2976 struct nand_chip *chip, uint32_t offset,
2977 uint32_t data_len, const uint8_t *buf,
2978 int oob_required, int page)
2979 {
2980 uint8_t *oob_buf = chip->oob_poi;
2981 uint8_t *ecc_calc = chip->buffers->ecccalc;
2982 int ecc_size = chip->ecc.size;
2983 int ecc_bytes = chip->ecc.bytes;
2984 int ecc_steps = chip->ecc.steps;
2985 uint32_t *eccpos = chip->ecc.layout->eccpos;
2986 uint32_t start_step = offset / ecc_size;
2987 uint32_t end_step = (offset + data_len - 1) / ecc_size;
2988 int oob_bytes = mtd->oobsize / ecc_steps;
2989 int step, i;
2990 int ret;
2991
2992 for (step = 0; step < ecc_steps; step++) {
2993 /* configure controller for WRITE access */
2994 chip->ecc.hwctl(mtd, NAND_ECC_WRITE);
2995
2996 /* write data (untouched subpages already masked by 0xFF) */
2997 ret = nand_write_data_op(chip, buf, ecc_size, false);
2998 if (ret)
2999 return ret;
3000
3001 /* mask ECC of un-touched subpages by padding 0xFF */
3002 if ((step < start_step) || (step > end_step))
3003 memset(ecc_calc, 0xff, ecc_bytes);
3004 else
3005 chip->ecc.calculate(mtd, buf, ecc_calc);
3006
3007 /* mask OOB of un-touched subpages by padding 0xFF */
3008 /* if oob_required, preserve OOB metadata of written subpage */
3009 if (!oob_required || (step < start_step) || (step > end_step))
3010 memset(oob_buf, 0xff, oob_bytes);
3011
3012 buf += ecc_size;
3013 ecc_calc += ecc_bytes;
3014 oob_buf += oob_bytes;
3015 }
3016
3017 /* copy calculated ECC for whole page to chip->buffer->oob */
3018 /* this include masked-value(0xFF) for unwritten subpages */
3019 ecc_calc = chip->buffers->ecccalc;
3020 for (i = 0; i < chip->ecc.total; i++)
3021 chip->oob_poi[eccpos[i]] = ecc_calc[i];
3022
3023 /* write OOB buffer to NAND device */
3024 ret = nand_write_data_op(chip, chip->oob_poi, mtd->oobsize, false);
3025 if (ret)
3026 return ret;
3027
3028 return 0;
3029 }
3030
3031
3032 /**
3033 * nand_write_page_syndrome - [REPLACEABLE] hardware ECC syndrome based page write
3034 * @mtd: mtd info structure
3035 * @chip: nand chip info structure
3036 * @buf: data buffer
3037 * @oob_required: must write chip->oob_poi to OOB
3038 * @page: page number to write
3039 *
3040 * The hw generator calculates the error syndrome automatically. Therefore we
3041 * need a special oob layout and handling.
3042 */
3043 static int nand_write_page_syndrome(struct mtd_info *mtd,
3044 struct nand_chip *chip,
3045 const uint8_t *buf, int oob_required,
3046 int page)
3047 {
3048 int i, eccsize = chip->ecc.size;
3049 int eccbytes = chip->ecc.bytes;
3050 int eccsteps = chip->ecc.steps;
3051 const uint8_t *p = buf;
3052 uint8_t *oob = chip->oob_poi;
3053 int ret;
3054
3055 for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
3056 chip->ecc.hwctl(mtd, NAND_ECC_WRITE);
3057
3058 ret = nand_write_data_op(chip, p, eccsize, false);
3059 if (ret)
3060 return ret;
3061
3062 if (chip->ecc.prepad) {
3063 ret = nand_write_data_op(chip, oob, chip->ecc.prepad,
3064 false);
3065 if (ret)
3066 return ret;
3067
3068 oob += chip->ecc.prepad;
3069 }
3070
3071 chip->ecc.calculate(mtd, p, oob);
3072
3073 ret = nand_write_data_op(chip, oob, eccbytes, false);
3074 if (ret)
3075 return ret;
3076
3077 oob += eccbytes;
3078
3079 if (chip->ecc.postpad) {
3080 ret = nand_write_data_op(chip, oob, chip->ecc.postpad,
3081 false);
3082 if (ret)
3083 return ret;
3084
3085 oob += chip->ecc.postpad;
3086 }
3087 }
3088
3089 /* Calculate remaining oob bytes */
3090 i = mtd->oobsize - (oob - chip->oob_poi);
3091 if (i) {
3092 ret = nand_write_data_op(chip, oob, i, false);
3093 if (ret)
3094 return ret;
3095 }
3096
3097 return 0;
3098 }
3099
3100 /**
3101 * nand_write_page - [REPLACEABLE] write one page
3102 * @mtd: MTD device structure
3103 * @chip: NAND chip descriptor
3104 * @offset: address offset within the page
3105 * @data_len: length of actual data to be written
3106 * @buf: the data to write
3107 * @oob_required: must write chip->oob_poi to OOB
3108 * @page: page number to write
3109 * @raw: use _raw version of write_page
3110 */
3111 static int nand_write_page(struct mtd_info *mtd, struct nand_chip *chip,
3112 uint32_t offset, int data_len, const uint8_t *buf,
3113 int oob_required, int page, int raw)
3114 {
3115 int status, subpage;
3116
3117 if (!(chip->options & NAND_NO_SUBPAGE_WRITE) &&
3118 chip->ecc.write_subpage)
3119 subpage = offset || (data_len < mtd->writesize);
3120 else
3121 subpage = 0;
3122
3123 if (nand_standard_page_accessors(&chip->ecc)) {
3124 status = nand_prog_page_begin_op(chip, page, 0, NULL, 0);
3125 if (status)
3126 return status;
3127 }
3128
3129 if (unlikely(raw))
3130 status = chip->ecc.write_page_raw(mtd, chip, buf,
3131 oob_required, page);
3132 else if (subpage)
3133 status = chip->ecc.write_subpage(mtd, chip, offset, data_len,
3134 buf, oob_required, page);
3135 else
3136 status = chip->ecc.write_page(mtd, chip, buf, oob_required,
3137 page);
3138
3139 if (status < 0)
3140 return status;
3141
3142 if (nand_standard_page_accessors(&chip->ecc))
3143 return nand_prog_page_end_op(chip);
3144
3145 return 0;
3146 }
3147
3148 /**
3149 * nand_fill_oob - [INTERN] Transfer client buffer to oob
3150 * @mtd: MTD device structure
3151 * @oob: oob data buffer
3152 * @len: oob data write length
3153 * @ops: oob ops structure
3154 */
3155 static uint8_t *nand_fill_oob(struct mtd_info *mtd, uint8_t *oob, size_t len,
3156 struct mtd_oob_ops *ops)
3157 {
3158 struct nand_chip *chip = mtd_to_nand(mtd);
3159
3160 /*
3161 * Initialise to all 0xFF, to avoid the possibility of left over OOB
3162 * data from a previous OOB read.
3163 */
3164 memset(chip->oob_poi, 0xff, mtd->oobsize);
3165
3166 switch (ops->mode) {
3167
3168 case MTD_OPS_PLACE_OOB:
3169 case MTD_OPS_RAW:
3170 memcpy(chip->oob_poi + ops->ooboffs, oob, len);
3171 return oob + len;
3172
3173 case MTD_OPS_AUTO_OOB: {
3174 struct nand_oobfree *free = chip->ecc.layout->oobfree;
3175 uint32_t boffs = 0, woffs = ops->ooboffs;
3176 size_t bytes = 0;
3177
3178 for (; free->length && len; free++, len -= bytes) {
3179 /* Write request not from offset 0? */
3180 if (unlikely(woffs)) {
3181 if (woffs >= free->length) {
3182 woffs -= free->length;
3183 continue;
3184 }
3185 boffs = free->offset + woffs;
3186 bytes = min_t(size_t, len,
3187 (free->length - woffs));
3188 woffs = 0;
3189 } else {
3190 bytes = min_t(size_t, len, free->length);
3191 boffs = free->offset;
3192 }
3193 memcpy(chip->oob_poi + boffs, oob, bytes);
3194 oob += bytes;
3195 }
3196 return oob;
3197 }
3198 default:
3199 BUG();
3200 }
3201 return NULL;
3202 }
3203
3204 #define NOTALIGNED(x) ((x & (chip->subpagesize - 1)) != 0)
3205
3206 /**
3207 * nand_do_write_ops - [INTERN] NAND write with ECC
3208 * @mtd: MTD device structure
3209 * @to: offset to write to
3210 * @ops: oob operations description structure
3211 *
3212 * NAND write with ECC.
3213 */
3214 static int nand_do_write_ops(struct mtd_info *mtd, loff_t to,
3215 struct mtd_oob_ops *ops)
3216 {
3217 int chipnr, realpage, page, column;
3218 struct nand_chip *chip = mtd_to_nand(mtd);
3219 uint32_t writelen = ops->len;
3220
3221 uint32_t oobwritelen = ops->ooblen;
3222 uint32_t oobmaxlen = mtd_oobavail(mtd, ops);
3223
3224 uint8_t *oob = ops->oobbuf;
3225 uint8_t *buf = ops->datbuf;
3226 int ret;
3227 int oob_required = oob ? 1 : 0;
3228
3229 ops->retlen = 0;
3230 if (!writelen)
3231 return 0;
3232
3233 /* Reject writes, which are not page aligned */
3234 if (NOTALIGNED(to)) {
3235 pr_notice("%s: attempt to write non page aligned data\n",
3236 __func__);
3237 return -EINVAL;
3238 }
3239
3240 column = to & (mtd->writesize - 1);
3241
3242 chipnr = (int)(to >> chip->chip_shift);
3243 chip->select_chip(mtd, chipnr);
3244
3245 /* Check, if it is write protected */
3246 if (nand_check_wp(mtd)) {
3247 ret = -EIO;
3248 goto err_out;
3249 }
3250
3251 realpage = (int)(to >> chip->page_shift);
3252 page = realpage & chip->pagemask;
3253
3254 /* Invalidate the page cache, when we write to the cached page */
3255 if (to <= ((loff_t)chip->pagebuf << chip->page_shift) &&
3256 ((loff_t)chip->pagebuf << chip->page_shift) < (to + ops->len))
3257 chip->pagebuf = -1;
3258
3259 /* Don't allow multipage oob writes with offset */
3260 if (oob && ops->ooboffs && (ops->ooboffs + ops->ooblen > oobmaxlen)) {
3261 ret = -EINVAL;
3262 goto err_out;
3263 }
3264
3265 while (1) {
3266 int bytes = mtd->writesize;
3267 uint8_t *wbuf = buf;
3268 int use_bufpoi;
3269 int part_pagewr = (column || writelen < mtd->writesize);
3270
3271 if (part_pagewr)
3272 use_bufpoi = 1;
3273 else if (chip->options & NAND_USE_BOUNCE_BUFFER)
3274 use_bufpoi = !IS_ALIGNED((unsigned long)buf,
3275 chip->buf_align);
3276 else
3277 use_bufpoi = 0;
3278
3279 schedule();
3280 /* Partial page write?, or need to use bounce buffer */
3281 if (use_bufpoi) {
3282 pr_debug("%s: using write bounce buffer for buf@%p\n",
3283 __func__, buf);
3284 if (part_pagewr)
3285 bytes = min_t(int, bytes - column, writelen);
3286 chip->pagebuf = -1;
3287 memset(chip->buffers->databuf, 0xff, mtd->writesize);
3288 memcpy(&chip->buffers->databuf[column], buf, bytes);
3289 wbuf = chip->buffers->databuf;
3290 }
3291
3292 if (unlikely(oob)) {
3293 size_t len = min(oobwritelen, oobmaxlen);
3294 oob = nand_fill_oob(mtd, oob, len, ops);
3295 oobwritelen -= len;
3296 } else {
3297 /* We still need to erase leftover OOB data */
3298 memset(chip->oob_poi, 0xff, mtd->oobsize);
3299 }
3300 ret = chip->write_page(mtd, chip, column, bytes, wbuf,
3301 oob_required, page,
3302 (ops->mode == MTD_OPS_RAW));
3303 if (ret)
3304 break;
3305
3306 writelen -= bytes;
3307 if (!writelen)
3308 break;
3309
3310 column = 0;
3311 buf += bytes;
3312 realpage++;
3313
3314 page = realpage & chip->pagemask;
3315 /* Check, if we cross a chip boundary */
3316 if (!page) {
3317 chipnr++;
3318 chip->select_chip(mtd, -1);
3319 chip->select_chip(mtd, chipnr);
3320 }
3321 }
3322
3323 ops->retlen = ops->len - writelen;
3324 if (unlikely(oob))
3325 ops->oobretlen = ops->ooblen;
3326
3327 err_out:
3328 chip->select_chip(mtd, -1);
3329 return ret;
3330 }
3331
3332 /**
3333 * panic_nand_write - [MTD Interface] NAND write with ECC
3334 * @mtd: MTD device structure
3335 * @to: offset to write to
3336 * @len: number of bytes to write
3337 * @retlen: pointer to variable to store the number of written bytes
3338 * @buf: the data to write
3339 *
3340 * NAND write with ECC. Used when performing writes in interrupt context, this
3341 * may for example be called by mtdoops when writing an oops while in panic.
3342 */
3343 static int panic_nand_write(struct mtd_info *mtd, loff_t to, size_t len,
3344 size_t *retlen, const uint8_t *buf)
3345 {
3346 struct nand_chip *chip = mtd_to_nand(mtd);
3347 struct mtd_oob_ops ops;
3348 int ret;
3349
3350 /* Wait for the device to get ready */
3351 panic_nand_wait(mtd, chip, 400);
3352
3353 /* Grab the device */
3354 panic_nand_get_device(chip, mtd, FL_WRITING);
3355
3356 memset(&ops, 0, sizeof(ops));
3357 ops.len = len;
3358 ops.datbuf = (uint8_t *)buf;
3359 ops.mode = MTD_OPS_PLACE_OOB;
3360
3361 ret = nand_do_write_ops(mtd, to, &ops);
3362
3363 *retlen = ops.retlen;
3364 return ret;
3365 }
3366
3367 /**
3368 * nand_do_write_oob - [MTD Interface] NAND write out-of-band
3369 * @mtd: MTD device structure
3370 * @to: offset to write to
3371 * @ops: oob operation description structure
3372 *
3373 * NAND write out-of-band.
3374 */
3375 static int nand_do_write_oob(struct mtd_info *mtd, loff_t to,
3376 struct mtd_oob_ops *ops)
3377 {
3378 int chipnr, page, status, len;
3379 struct nand_chip *chip = mtd_to_nand(mtd);
3380
3381 pr_debug("%s: to = 0x%08x, len = %i\n",
3382 __func__, (unsigned int)to, (int)ops->ooblen);
3383
3384 len = mtd_oobavail(mtd, ops);
3385
3386 /* Do not allow write past end of page */
3387 if ((ops->ooboffs + ops->ooblen) > len) {
3388 pr_debug("%s: attempt to write past end of page\n",
3389 __func__);
3390 return -EINVAL;
3391 }
3392
3393 if (unlikely(ops->ooboffs >= len)) {
3394 pr_debug("%s: attempt to start write outside oob\n",
3395 __func__);
3396 return -EINVAL;
3397 }
3398
3399 /* Do not allow write past end of device */
3400 if (unlikely(to >= mtd->size ||
3401 ops->ooboffs + ops->ooblen >
3402 ((mtd->size >> chip->page_shift) -
3403 (to >> chip->page_shift)) * len)) {
3404 pr_debug("%s: attempt to write beyond end of device\n",
3405 __func__);
3406 return -EINVAL;
3407 }
3408
3409 chipnr = (int)(to >> chip->chip_shift);
3410
3411 /*
3412 * Reset the chip. Some chips (like the Toshiba TC5832DC found in one
3413 * of my DiskOnChip 2000 test units) will clear the whole data page too
3414 * if we don't do this. I have no clue why, but I seem to have 'fixed'
3415 * it in the doc2000 driver in August 1999. dwmw2.
3416 */
3417 nand_reset(chip, chipnr);
3418
3419 chip->select_chip(mtd, chipnr);
3420
3421 /* Shift to get page */
3422 page = (int)(to >> chip->page_shift);
3423
3424 /* Check, if it is write protected */
3425 if (nand_check_wp(mtd)) {
3426 chip->select_chip(mtd, -1);
3427 return -EROFS;
3428 }
3429
3430 /* Invalidate the page cache, if we write to the cached page */
3431 if (page == chip->pagebuf)
3432 chip->pagebuf = -1;
3433
3434 nand_fill_oob(mtd, ops->oobbuf, ops->ooblen, ops);
3435
3436 if (ops->mode == MTD_OPS_RAW)
3437 status = chip->ecc.write_oob_raw(mtd, chip, page & chip->pagemask);
3438 else
3439 status = chip->ecc.write_oob(mtd, chip, page & chip->pagemask);
3440
3441 chip->select_chip(mtd, -1);
3442
3443 if (status)
3444 return status;
3445
3446 ops->oobretlen = ops->ooblen;
3447
3448 return 0;
3449 }
3450
3451 /**
3452 * nand_write_oob - [MTD Interface] NAND write data and/or out-of-band
3453 * @mtd: MTD device structure
3454 * @to: offset to write to
3455 * @ops: oob operation description structure
3456 */
3457 static int nand_write_oob(struct mtd_info *mtd, loff_t to,
3458 struct mtd_oob_ops *ops)
3459 {
3460 int ret = -ENOTSUPP;
3461
3462 ops->retlen = 0;
3463
3464 /* Do not allow writes past end of device */
3465 if (ops->datbuf && (to + ops->len) > mtd->size) {
3466 pr_debug("%s: attempt to write beyond end of device\n",
3467 __func__);
3468 return -EINVAL;
3469 }
3470
3471 nand_get_device(mtd, FL_WRITING);
3472
3473 switch (ops->mode) {
3474 case MTD_OPS_PLACE_OOB:
3475 case MTD_OPS_AUTO_OOB:
3476 case MTD_OPS_RAW:
3477 break;
3478
3479 default:
3480 goto out;
3481 }
3482
3483 if (!ops->datbuf)
3484 ret = nand_do_write_oob(mtd, to, ops);
3485 else
3486 ret = nand_do_write_ops(mtd, to, ops);
3487
3488 out:
3489 nand_release_device(mtd);
3490 return ret;
3491 }
3492
3493 /**
3494 * single_erase - [GENERIC] NAND standard block erase command function
3495 * @mtd: MTD device structure
3496 * @page: the page address of the block which will be erased
3497 *
3498 * Standard erase command for NAND chips. Returns NAND status.
3499 */
3500 static int single_erase(struct mtd_info *mtd, int page)
3501 {
3502 struct nand_chip *chip = mtd_to_nand(mtd);
3503 unsigned int eraseblock;
3504
3505 /* Send commands to erase a block */
3506 eraseblock = page >> (chip->phys_erase_shift - chip->page_shift);
3507
3508 return nand_erase_op(chip, eraseblock);
3509 }
3510
3511 /**
3512 * nand_erase - [MTD Interface] erase block(s)
3513 * @mtd: MTD device structure
3514 * @instr: erase instruction
3515 *
3516 * Erase one ore more blocks.
3517 */
3518 static int nand_erase(struct mtd_info *mtd, struct erase_info *instr)
3519 {
3520 return nand_erase_nand(mtd, instr, 0);
3521 }
3522
3523 /**
3524 * nand_erase_nand - [INTERN] erase block(s)
3525 * @mtd: MTD device structure
3526 * @instr: erase instruction
3527 * @allowbbt: allow erasing the bbt area
3528 *
3529 * Erase one ore more blocks.
3530 */
3531 int nand_erase_nand(struct mtd_info *mtd, struct erase_info *instr,
3532 int allowbbt)
3533 {
3534 int page, status, pages_per_block, ret, chipnr;
3535 struct nand_chip *chip = mtd_to_nand(mtd);
3536 loff_t len;
3537
3538 pr_debug("%s: start = 0x%012llx, len = %llu\n",
3539 __func__, (unsigned long long)instr->addr,
3540 (unsigned long long)instr->len);
3541
3542 if (check_offs_len(mtd, instr->addr, instr->len))
3543 return -EINVAL;
3544
3545 /* Grab the lock and see if the device is available */
3546 nand_get_device(mtd, FL_ERASING);
3547
3548 /* Shift to get first page */
3549 page = (int)(instr->addr >> chip->page_shift);
3550 chipnr = (int)(instr->addr >> chip->chip_shift);
3551
3552 /* Calculate pages in each block */
3553 pages_per_block = 1 << (chip->phys_erase_shift - chip->page_shift);
3554
3555 /* Select the NAND device */
3556 chip->select_chip(mtd, chipnr);
3557
3558 /* Check, if it is write protected */
3559 if (nand_check_wp(mtd)) {
3560 pr_debug("%s: device is write protected!\n",
3561 __func__);
3562 instr->state = MTD_ERASE_FAILED;
3563 goto erase_exit;
3564 }
3565
3566 /* Loop through the pages */
3567 len = instr->len;
3568
3569 instr->state = MTD_ERASING;
3570
3571 while (len) {
3572 schedule();
3573
3574 /* Check if we have a bad block, we do not erase bad blocks! */
3575 if (!instr->scrub && nand_block_checkbad(mtd, ((loff_t) page) <<
3576 chip->page_shift, allowbbt)) {
3577 pr_warn("%s: attempt to erase a bad block at page 0x%08x\n",
3578 __func__, page);
3579 instr->state = MTD_ERASE_FAILED;
3580 instr->fail_addr =
3581 ((loff_t)page << chip->page_shift);
3582 goto erase_exit;
3583 }
3584
3585 /*
3586 * Invalidate the page cache, if we erase the block which
3587 * contains the current cached page.
3588 */
3589 if (page <= chip->pagebuf && chip->pagebuf <
3590 (page + pages_per_block))
3591 chip->pagebuf = -1;
3592
3593 status = chip->erase(mtd, page & chip->pagemask);
3594
3595 /* See if block erase succeeded */
3596 if (status & NAND_STATUS_FAIL) {
3597 pr_debug("%s: failed erase, page 0x%08x\n",
3598 __func__, page);
3599 instr->state = MTD_ERASE_FAILED;
3600 instr->fail_addr =
3601 ((loff_t)page << chip->page_shift);
3602 goto erase_exit;
3603 }
3604
3605 /* Increment page address and decrement length */
3606 len -= (1ULL << chip->phys_erase_shift);
3607 page += pages_per_block;
3608
3609 /* Check, if we cross a chip boundary */
3610 if (len && !(page & chip->pagemask)) {
3611 chipnr++;
3612 chip->select_chip(mtd, -1);
3613 chip->select_chip(mtd, chipnr);
3614 }
3615 }
3616 instr->state = MTD_ERASE_DONE;
3617
3618 erase_exit:
3619
3620 ret = instr->state == MTD_ERASE_DONE ? 0 : -EIO;
3621
3622 /* Deselect and wake up anyone waiting on the device */
3623 chip->select_chip(mtd, -1);
3624 nand_release_device(mtd);
3625
3626 /* Return more or less happy */
3627 return ret;
3628 }
3629
3630 /**
3631 * nand_sync - [MTD Interface] sync
3632 * @mtd: MTD device structure
3633 *
3634 * Sync is actually a wait for chip ready function.
3635 */
3636 static void nand_sync(struct mtd_info *mtd)
3637 {
3638 pr_debug("%s: called\n", __func__);
3639
3640 /* Grab the lock and see if the device is available */
3641 nand_get_device(mtd, FL_SYNCING);
3642 /* Release it and go back */
3643 nand_release_device(mtd);
3644 }
3645
3646 /**
3647 * nand_block_isbad - [MTD Interface] Check if block at offset is bad
3648 * @mtd: MTD device structure
3649 * @offs: offset relative to mtd start
3650 */
3651 static int nand_block_isbad(struct mtd_info *mtd, loff_t offs)
3652 {
3653 struct nand_chip *chip = mtd_to_nand(mtd);
3654 int chipnr = (int)(offs >> chip->chip_shift);
3655 int ret;
3656
3657 /* Select the NAND device */
3658 nand_get_device(mtd, FL_READING);
3659 chip->select_chip(mtd, chipnr);
3660
3661 ret = nand_block_checkbad(mtd, offs, 0);
3662
3663 chip->select_chip(mtd, -1);
3664 nand_release_device(mtd);
3665
3666 return ret;
3667 }
3668
3669 /**
3670 * nand_block_markbad - [MTD Interface] Mark block at the given offset as bad
3671 * @mtd: MTD device structure
3672 * @ofs: offset relative to mtd start
3673 */
3674 static int nand_block_markbad(struct mtd_info *mtd, loff_t ofs)
3675 {
3676 int ret;
3677
3678 ret = nand_block_isbad(mtd, ofs);
3679 if (ret) {
3680 /* If it was bad already, return success and do nothing */
3681 if (ret > 0)
3682 return 0;
3683 return ret;
3684 }
3685
3686 return nand_block_markbad_lowlevel(mtd, ofs);
3687 }
3688
3689 /**
3690 * nand_onfi_set_features- [REPLACEABLE] set features for ONFI nand
3691 * @mtd: MTD device structure
3692 * @chip: nand chip info structure
3693 * @addr: feature address.
3694 * @subfeature_param: the subfeature parameters, a four bytes array.
3695 */
3696 static int nand_onfi_set_features(struct mtd_info *mtd, struct nand_chip *chip,
3697 int addr, uint8_t *subfeature_param)
3698 {
3699 #ifdef CONFIG_SYS_NAND_ONFI_DETECTION
3700 if (!chip->onfi_version ||
3701 !(le16_to_cpu(chip->onfi_params.opt_cmd)
3702 & ONFI_OPT_CMD_SET_GET_FEATURES))
3703 return -ENOTSUPP;
3704 #endif
3705
3706 return nand_set_features_op(chip, addr, subfeature_param);
3707 }
3708
3709 /**
3710 * nand_onfi_get_features- [REPLACEABLE] get features for ONFI nand
3711 * @mtd: MTD device structure
3712 * @chip: nand chip info structure
3713 * @addr: feature address.
3714 * @subfeature_param: the subfeature parameters, a four bytes array.
3715 */
3716 static int nand_onfi_get_features(struct mtd_info *mtd, struct nand_chip *chip,
3717 int addr, uint8_t *subfeature_param)
3718 {
3719 #ifdef CONFIG_SYS_NAND_ONFI_DETECTION
3720 if (!chip->onfi_version ||
3721 !(le16_to_cpu(chip->onfi_params.opt_cmd)
3722 & ONFI_OPT_CMD_SET_GET_FEATURES))
3723 return -ENOTSUPP;
3724 #endif
3725
3726 return nand_get_features_op(chip, addr, subfeature_param);
3727 }
3728
3729 /* Set default functions */
3730 static void nand_set_defaults(struct nand_chip *chip, int busw)
3731 {
3732 /* check for proper chip_delay setup, set 20us if not */
3733 if (!chip->chip_delay)
3734 chip->chip_delay = 20;
3735
3736 /* check, if a user supplied command function given */
3737 if (chip->cmdfunc == NULL)
3738 chip->cmdfunc = nand_command;
3739
3740 /* check, if a user supplied wait function given */
3741 if (chip->waitfunc == NULL)
3742 chip->waitfunc = nand_wait;
3743
3744 if (!chip->select_chip)
3745 chip->select_chip = nand_select_chip;
3746
3747 /* set for ONFI nand */
3748 if (!chip->onfi_set_features)
3749 chip->onfi_set_features = nand_onfi_set_features;
3750 if (!chip->onfi_get_features)
3751 chip->onfi_get_features = nand_onfi_get_features;
3752
3753 /* If called twice, pointers that depend on busw may need to be reset */
3754 if (!chip->read_byte || chip->read_byte == nand_read_byte)
3755 chip->read_byte = busw ? nand_read_byte16 : nand_read_byte;
3756 if (!chip->read_word)
3757 chip->read_word = nand_read_word;
3758 if (!chip->block_bad)
3759 chip->block_bad = nand_block_bad;
3760 if (!chip->block_markbad)
3761 chip->block_markbad = nand_default_block_markbad;
3762 if (!chip->write_buf || chip->write_buf == nand_write_buf)
3763 chip->write_buf = busw ? nand_write_buf16 : nand_write_buf;
3764 if (!chip->write_byte || chip->write_byte == nand_write_byte)
3765 chip->write_byte = busw ? nand_write_byte16 : nand_write_byte;
3766 if (!chip->read_buf || chip->read_buf == nand_read_buf)
3767 chip->read_buf = busw ? nand_read_buf16 : nand_read_buf;
3768
3769 #ifndef CONFIG_SPL_BUILD
3770 if (!chip->scan_bbt)
3771 chip->scan_bbt = nand_default_bbt;
3772 #endif
3773
3774 if (!chip->controller) {
3775 chip->controller = &chip->hwcontrol;
3776 spin_lock_init(&chip->controller->lock);
3777 init_waitqueue_head(&chip->controller->wq);
3778 }
3779
3780 if (!chip->buf_align)
3781 chip->buf_align = 1;
3782 }
3783
3784 /* Sanitize ONFI strings so we can safely print them */
3785 static void sanitize_string(char *s, size_t len)
3786 {
3787 ssize_t i;
3788
3789 /* Null terminate */
3790 s[len - 1] = 0;
3791
3792 /* Remove non printable chars */
3793 for (i = 0; i < len - 1; i++) {
3794 if (s[i] < ' ' || s[i] > 127)
3795 s[i] = '?';
3796 }
3797
3798 /* Remove trailing spaces */
3799 strim(s);
3800 }
3801
3802 static u16 onfi_crc16(u16 crc, u8 const *p, size_t len)
3803 {
3804 int i;
3805 while (len--) {
3806 crc ^= *p++ << 8;
3807 for (i = 0; i < 8; i++)
3808 crc = (crc << 1) ^ ((crc & 0x8000) ? 0x8005 : 0);
3809 }
3810
3811 return crc;
3812 }
3813
3814 #ifdef CONFIG_SYS_NAND_ONFI_DETECTION
3815 /* Parse the Extended Parameter Page. */
3816 static int nand_flash_detect_ext_param_page(struct mtd_info *mtd,
3817 struct nand_chip *chip, struct nand_onfi_params *p)
3818 {
3819 struct onfi_ext_param_page *ep;
3820 struct onfi_ext_section *s;
3821 struct onfi_ext_ecc_info *ecc;
3822 uint8_t *cursor;
3823 int ret;
3824 int len;
3825 int i;
3826
3827 len = le16_to_cpu(p->ext_param_page_length) * 16;
3828 ep = kmalloc(len, GFP_KERNEL);
3829 if (!ep)
3830 return -ENOMEM;
3831
3832 /* Send our own NAND_CMD_PARAM. */
3833 ret = nand_read_param_page_op(chip, 0, NULL, 0);
3834 if (ret)
3835 goto ext_out;
3836
3837 /* Use the Change Read Column command to skip the ONFI param pages. */
3838 ret = nand_change_read_column_op(chip,
3839 sizeof(*p) * p->num_of_param_pages,
3840 ep, len, true);
3841 if (ret)
3842 goto ext_out;
3843
3844 ret = -EINVAL;
3845 if ((onfi_crc16(ONFI_CRC_BASE, ((uint8_t *)ep) + 2, len - 2)
3846 != le16_to_cpu(ep->crc))) {
3847 pr_debug("fail in the CRC.\n");
3848 goto ext_out;
3849 }
3850
3851 /*
3852 * Check the signature.
3853 * Do not strictly follow the ONFI spec, maybe changed in future.
3854 */
3855 if (strncmp((char *)ep->sig, "EPPS", 4)) {
3856 pr_debug("The signature is invalid.\n");
3857 goto ext_out;
3858 }
3859
3860 /* find the ECC section. */
3861 cursor = (uint8_t *)(ep + 1);
3862 for (i = 0; i < ONFI_EXT_SECTION_MAX; i++) {
3863 s = ep->sections + i;
3864 if (s->type == ONFI_SECTION_TYPE_2)
3865 break;
3866 cursor += s->length * 16;
3867 }
3868 if (i == ONFI_EXT_SECTION_MAX) {
3869 pr_debug("We can not find the ECC section.\n");
3870 goto ext_out;
3871 }
3872
3873 /* get the info we want. */
3874 ecc = (struct onfi_ext_ecc_info *)cursor;
3875
3876 if (!ecc->codeword_size) {
3877 pr_debug("Invalid codeword size\n");
3878 goto ext_out;
3879 }
3880
3881 chip->ecc_strength_ds = ecc->ecc_bits;
3882 chip->ecc_step_ds = 1 << ecc->codeword_size;
3883 ret = 0;
3884
3885 ext_out:
3886 kfree(ep);
3887 return ret;
3888 }
3889
3890 /*
3891 * Check if the NAND chip is ONFI compliant, returns 1 if it is, 0 otherwise.
3892 */
3893 static int nand_flash_detect_onfi(struct mtd_info *mtd, struct nand_chip *chip)
3894 {
3895 struct nand_onfi_params *p = &chip->onfi_params;
3896 char id[4];
3897 int i, ret, val;
3898
3899 /* Try ONFI for unknown chip or LP */
3900 ret = nand_readid_op(chip, 0x20, id, sizeof(id));
3901 if (ret || strncmp(id, "ONFI", 4))
3902 return 0;
3903
3904 ret = nand_read_param_page_op(chip, 0, NULL, 0);
3905 if (ret)
3906 return 0;
3907
3908 for (i = 0; i < 3; i++) {
3909 ret = nand_read_data_op(chip, p, sizeof(*p), true);
3910 if (ret)
3911 return 0;
3912
3913 if (onfi_crc16(ONFI_CRC_BASE, (uint8_t *)p, 254) ==
3914 le16_to_cpu(p->crc)) {
3915 break;
3916 }
3917 }
3918
3919 if (i == 3) {
3920 pr_err("Could not find valid ONFI parameter page; aborting\n");
3921 return 0;
3922 }
3923
3924 /* Check version */
3925 val = le16_to_cpu(p->revision);
3926 if (val & (1 << 5))
3927 chip->onfi_version = 23;
3928 else if (val & (1 << 4))
3929 chip->onfi_version = 22;
3930 else if (val & (1 << 3))
3931 chip->onfi_version = 21;
3932 else if (val & (1 << 2))
3933 chip->onfi_version = 20;
3934 else if (val & (1 << 1))
3935 chip->onfi_version = 10;
3936
3937 if (!chip->onfi_version) {
3938 pr_info("unsupported ONFI version: %d\n", val);
3939 return 0;
3940 }
3941
3942 sanitize_string(p->manufacturer, sizeof(p->manufacturer));
3943 sanitize_string(p->model, sizeof(p->model));
3944 if (!mtd->name)
3945 mtd->name = p->model;
3946
3947 mtd->writesize = le32_to_cpu(p->byte_per_page);
3948
3949 /*
3950 * pages_per_block and blocks_per_lun may not be a power-of-2 size
3951 * (don't ask me who thought of this...). MTD assumes that these
3952 * dimensions will be power-of-2, so just truncate the remaining area.
3953 */
3954 mtd->erasesize = 1 << (fls(le32_to_cpu(p->pages_per_block)) - 1);
3955 mtd->erasesize *= mtd->writesize;
3956
3957 mtd->oobsize = le16_to_cpu(p->spare_bytes_per_page);
3958
3959 /* See erasesize comment */
3960 chip->chipsize = 1 << (fls(le32_to_cpu(p->blocks_per_lun)) - 1);
3961 chip->chipsize *= (uint64_t)mtd->erasesize * p->lun_count;
3962 chip->bits_per_cell = p->bits_per_cell;
3963
3964 if (onfi_feature(chip) & ONFI_FEATURE_16_BIT_BUS)
3965 chip->options |= NAND_BUSWIDTH_16;
3966
3967 if (p->ecc_bits != 0xff) {
3968 chip->ecc_strength_ds = p->ecc_bits;
3969 chip->ecc_step_ds = 512;
3970 } else if (chip->onfi_version >= 21 &&
3971 (onfi_feature(chip) & ONFI_FEATURE_EXT_PARAM_PAGE)) {
3972
3973 /*
3974 * The nand_flash_detect_ext_param_page() uses the
3975 * Change Read Column command which maybe not supported
3976 * by the chip->cmdfunc. So try to update the chip->cmdfunc
3977 * now. We do not replace user supplied command function.
3978 */
3979 if (mtd->writesize > 512 && chip->cmdfunc == nand_command)
3980 chip->cmdfunc = nand_command_lp;
3981
3982 /* The Extended Parameter Page is supported since ONFI 2.1. */
3983 if (nand_flash_detect_ext_param_page(mtd, chip, p))
3984 pr_warn("Failed to detect ONFI extended param page\n");
3985 } else {
3986 pr_warn("Could not retrieve ONFI ECC requirements\n");
3987 }
3988
3989 return 1;
3990 }
3991 #else
3992 static int nand_flash_detect_onfi(struct mtd_info *mtd, struct nand_chip *chip)
3993 {
3994 return 0;
3995 }
3996 #endif
3997
3998 /*
3999 * Check if the NAND chip is JEDEC compliant, returns 1 if it is, 0 otherwise.
4000 */
4001 static int nand_flash_detect_jedec(struct mtd_info *mtd, struct nand_chip *chip)
4002 {
4003 struct nand_jedec_params *p = &chip->jedec_params;
4004 struct jedec_ecc_info *ecc;
4005 char id[5];
4006 int i, val, ret;
4007
4008 /* Try JEDEC for unknown chip or LP */
4009 ret = nand_readid_op(chip, 0x40, id, sizeof(id));
4010 if (ret || strncmp(id, "JEDEC", sizeof(id)))
4011 return 0;
4012
4013 ret = nand_read_param_page_op(chip, 0x40, NULL, 0);
4014 if (ret)
4015 return 0;
4016
4017 for (i = 0; i < 3; i++) {
4018 ret = nand_read_data_op(chip, p, sizeof(*p), true);
4019 if (ret)
4020 return 0;
4021
4022 if (onfi_crc16(ONFI_CRC_BASE, (uint8_t *)p, 510) ==
4023 le16_to_cpu(p->crc))
4024 break;
4025 }
4026
4027 if (i == 3) {
4028 pr_err("Could not find valid JEDEC parameter page; aborting\n");
4029 return 0;
4030 }
4031
4032 /* Check version */
4033 val = le16_to_cpu(p->revision);
4034 if (val & (1 << 2))
4035 chip->jedec_version = 10;
4036 else if (val & (1 << 1))
4037 chip->jedec_version = 1; /* vendor specific version */
4038
4039 if (!chip->jedec_version) {
4040 pr_info("unsupported JEDEC version: %d\n", val);
4041 return 0;
4042 }
4043
4044 sanitize_string(p->manufacturer, sizeof(p->manufacturer));
4045 sanitize_string(p->model, sizeof(p->model));
4046 if (!mtd->name)
4047 mtd->name = p->model;
4048
4049 mtd->writesize = le32_to_cpu(p->byte_per_page);
4050
4051 /* Please reference to the comment for nand_flash_detect_onfi. */
4052 mtd->erasesize = 1 << (fls(le32_to_cpu(p->pages_per_block)) - 1);
4053 mtd->erasesize *= mtd->writesize;
4054
4055 mtd->oobsize = le16_to_cpu(p->spare_bytes_per_page);
4056
4057 /* Please reference to the comment for nand_flash_detect_onfi. */
4058 chip->chipsize = 1 << (fls(le32_to_cpu(p->blocks_per_lun)) - 1);
4059 chip->chipsize *= (uint64_t)mtd->erasesize * p->lun_count;
4060 chip->bits_per_cell = p->bits_per_cell;
4061
4062 if (jedec_feature(chip) & JEDEC_FEATURE_16_BIT_BUS)
4063 chip->options |= NAND_BUSWIDTH_16;
4064
4065 /* ECC info */
4066 ecc = &p->ecc_info[0];
4067
4068 if (ecc->codeword_size >= 9) {
4069 chip->ecc_strength_ds = ecc->ecc_bits;
4070 chip->ecc_step_ds = 1 << ecc->codeword_size;
4071 } else {
4072 pr_warn("Invalid codeword size\n");
4073 }
4074
4075 return 1;
4076 }
4077
4078 /*
4079 * nand_id_has_period - Check if an ID string has a given wraparound period
4080 * @id_data: the ID string
4081 * @arrlen: the length of the @id_data array
4082 * @period: the period of repitition
4083 *
4084 * Check if an ID string is repeated within a given sequence of bytes at
4085 * specific repetition interval period (e.g., {0x20,0x01,0x7F,0x20} has a
4086 * period of 3). This is a helper function for nand_id_len(). Returns non-zero
4087 * if the repetition has a period of @period; otherwise, returns zero.
4088 */
4089 static int nand_id_has_period(u8 *id_data, int arrlen, int period)
4090 {
4091 int i, j;
4092 for (i = 0; i < period; i++)
4093 for (j = i + period; j < arrlen; j += period)
4094 if (id_data[i] != id_data[j])
4095 return 0;
4096 return 1;
4097 }
4098
4099 /*
4100 * nand_id_len - Get the length of an ID string returned by CMD_READID
4101 * @id_data: the ID string
4102 * @arrlen: the length of the @id_data array
4103
4104 * Returns the length of the ID string, according to known wraparound/trailing
4105 * zero patterns. If no pattern exists, returns the length of the array.
4106 */
4107 static int nand_id_len(u8 *id_data, int arrlen)
4108 {
4109 int last_nonzero, period;
4110
4111 /* Find last non-zero byte */
4112 for (last_nonzero = arrlen - 1; last_nonzero >= 0; last_nonzero--)
4113 if (id_data[last_nonzero])
4114 break;
4115
4116 /* All zeros */
4117 if (last_nonzero < 0)
4118 return 0;
4119
4120 /* Calculate wraparound period */
4121 for (period = 1; period < arrlen; period++)
4122 if (nand_id_has_period(id_data, arrlen, period))
4123 break;
4124
4125 /* There's a repeated pattern */
4126 if (period < arrlen)
4127 return period;
4128
4129 /* There are trailing zeros */
4130 if (last_nonzero < arrlen - 1)
4131 return last_nonzero + 1;
4132
4133 /* No pattern detected */
4134 return arrlen;
4135 }
4136
4137 /* Extract the bits of per cell from the 3rd byte of the extended ID */
4138 static int nand_get_bits_per_cell(u8 cellinfo)
4139 {
4140 int bits;
4141
4142 bits = cellinfo & NAND_CI_CELLTYPE_MSK;
4143 bits >>= NAND_CI_CELLTYPE_SHIFT;
4144 return bits + 1;
4145 }
4146
4147 /*
4148 * Many new NAND share similar device ID codes, which represent the size of the
4149 * chip. The rest of the parameters must be decoded according to generic or
4150 * manufacturer-specific "extended ID" decoding patterns.
4151 */
4152 void nand_decode_ext_id(struct nand_chip *chip)
4153 {
4154 struct mtd_info *mtd = &chip->mtd;
4155 int extid;
4156 /* The 3rd id byte holds MLC / multichip data */
4157 chip->bits_per_cell = nand_get_bits_per_cell(chip->id.data[2]);
4158 /* The 4th id byte is the important one */
4159 extid = chip->id.data[3];
4160
4161 /* Calc pagesize */
4162 mtd->writesize = 1024 << (extid & 0x03);
4163 extid >>= 2;
4164 /* Calc oobsize */
4165 mtd->oobsize = (8 << (extid & 0x01)) *
4166 (mtd->writesize >> 9);
4167 extid >>= 2;
4168 /* Calc blocksize. Blocksize is multiples of 64KiB */
4169 mtd->erasesize = (64 * 1024) << (extid & 0x03);
4170 extid >>= 2;
4171 /* Get buswidth information */
4172 /* Get buswidth information */
4173 if (extid & 0x1)
4174 chip->options |= NAND_BUSWIDTH_16;
4175 }
4176 EXPORT_SYMBOL_GPL(nand_decode_ext_id);
4177
4178 /*
4179 * Manufacturer detection. Only used when the NAND is not ONFI or JEDEC
4180 * compliant and does not have a full-id or legacy-id entry in the nand_ids
4181 * table.
4182 */
4183 static void nand_manufacturer_detect(struct nand_chip *chip)
4184 {
4185 /*
4186 * Try manufacturer detection if available and use
4187 * nand_decode_ext_id() otherwise.
4188 */
4189 if (chip->manufacturer.desc && chip->manufacturer.desc->ops &&
4190 chip->manufacturer.desc->ops->detect) {
4191 /* The 3rd id byte holds MLC / multichip data */
4192 chip->bits_per_cell = nand_get_bits_per_cell(chip->id.data[2]);
4193 chip->manufacturer.desc->ops->detect(chip);
4194 } else {
4195 nand_decode_ext_id(chip);
4196 }
4197 }
4198
4199 /*
4200 * Manufacturer initialization. This function is called for all NANDs including
4201 * ONFI and JEDEC compliant ones.
4202 * Manufacturer drivers should put all their specific initialization code in
4203 * their ->init() hook.
4204 */
4205 static int nand_manufacturer_init(struct nand_chip *chip)
4206 {
4207 if (!chip->manufacturer.desc || !chip->manufacturer.desc->ops ||
4208 !chip->manufacturer.desc->ops->init)
4209 return 0;
4210
4211 return chip->manufacturer.desc->ops->init(chip);
4212 }
4213
4214 /*
4215 * Old devices have chip data hardcoded in the device ID table. nand_decode_id
4216 * decodes a matching ID table entry and assigns the MTD size parameters for
4217 * the chip.
4218 */
4219 static void nand_decode_id(struct nand_chip *chip, struct nand_flash_dev *type)
4220 {
4221 struct mtd_info *mtd = &chip->mtd;
4222
4223 mtd->erasesize = type->erasesize;
4224 mtd->writesize = type->pagesize;
4225 mtd->oobsize = mtd->writesize / 32;
4226
4227 /* All legacy ID NAND are small-page, SLC */
4228 chip->bits_per_cell = 1;
4229 }
4230
4231 /*
4232 * Set the bad block marker/indicator (BBM/BBI) patterns according to some
4233 * heuristic patterns using various detected parameters (e.g., manufacturer,
4234 * page size, cell-type information).
4235 */
4236 static void nand_decode_bbm_options(struct mtd_info *mtd,
4237 struct nand_chip *chip)
4238 {
4239 /* Set the bad block position */
4240 if (mtd->writesize > 512 || (chip->options & NAND_BUSWIDTH_16))
4241 chip->badblockpos = NAND_LARGE_BADBLOCK_POS;
4242 else
4243 chip->badblockpos = NAND_SMALL_BADBLOCK_POS;
4244 }
4245
4246 static inline bool is_full_id_nand(struct nand_flash_dev *type)
4247 {
4248 return type->id_len;
4249 }
4250
4251 static bool find_full_id_nand(struct mtd_info *mtd, struct nand_chip *chip,
4252 struct nand_flash_dev *type)
4253 {
4254 if (!strncmp((char *)type->id, (char *)chip->id.data, type->id_len)) {
4255 mtd->writesize = type->pagesize;
4256 mtd->erasesize = type->erasesize;
4257 mtd->oobsize = type->oobsize;
4258
4259 chip->bits_per_cell = nand_get_bits_per_cell(chip->id.data[2]);
4260 chip->chipsize = (uint64_t)type->chipsize << 20;
4261 chip->options |= type->options;
4262 chip->ecc_strength_ds = NAND_ECC_STRENGTH(type);
4263 chip->ecc_step_ds = NAND_ECC_STEP(type);
4264 chip->onfi_timing_mode_default =
4265 type->onfi_timing_mode_default;
4266
4267 if (!mtd->name)
4268 mtd->name = type->name;
4269
4270 return true;
4271 }
4272 return false;
4273 }
4274
4275 /**
4276 * nand_get_manufacturer_desc - Get manufacturer information from the
4277 * manufacturer ID
4278 * @id: manufacturer ID
4279 *
4280 * Returns a nand_manufacturer_desc object if the manufacturer is defined
4281 * in the NAND manufacturers database, NULL otherwise.
4282 */
4283 static const struct nand_manufacturer *nand_get_manufacturer_desc(u8 id)
4284 {
4285 int i;
4286
4287 for (i = 0; nand_manuf_ids[i].id != 0x0; i++) {
4288 if (nand_manuf_ids[i].id == id)
4289 return &nand_manuf_ids[i];
4290 }
4291
4292 return NULL;
4293 }
4294
4295 /*
4296 * Get the flash and manufacturer id and lookup if the type is supported.
4297 */
4298 int nand_detect(struct nand_chip *chip, int *maf_id,
4299 int *dev_id, struct nand_flash_dev *type)
4300 {
4301 struct mtd_info *mtd = &chip->mtd;
4302 const struct nand_manufacturer *manufacturer_desc;
4303 int busw, ret;
4304 u8 *id_data = chip->id.data;
4305
4306 /*
4307 * Reset the chip, required by some chips (e.g. Micron MT29FxGxxxxx)
4308 * after power-up.
4309 */
4310 ret = nand_reset(chip, 0);
4311 if (ret)
4312 return ret;
4313
4314 /* Select the device */
4315 chip->select_chip(mtd, 0);
4316
4317 /* Send the command for reading device ID */
4318 ret = nand_readid_op(chip, 0, id_data, 2);
4319 if (ret)
4320 return ret;
4321
4322 /* Read manufacturer and device IDs */
4323 *maf_id = id_data[0];
4324 *dev_id = id_data[1];
4325
4326 /*
4327 * Try again to make sure, as some systems the bus-hold or other
4328 * interface concerns can cause random data which looks like a
4329 * possibly credible NAND flash to appear. If the two results do
4330 * not match, ignore the device completely.
4331 */
4332
4333 /* Read entire ID string */
4334 ret = nand_readid_op(chip, 0, id_data, 8);
4335 if (ret)
4336 return ret;
4337
4338 if (id_data[0] != *maf_id || id_data[1] != *dev_id) {
4339 pr_info("second ID read did not match %02x,%02x against %02x,%02x\n",
4340 *maf_id, *dev_id, id_data[0], id_data[1]);
4341 return -ENODEV;
4342 }
4343
4344 chip->id.len = nand_id_len(id_data, ARRAY_SIZE(chip->id.data));
4345
4346 /* Try to identify manufacturer */
4347 manufacturer_desc = nand_get_manufacturer_desc(*maf_id);
4348 chip->manufacturer.desc = manufacturer_desc;
4349
4350 if (!type)
4351 type = nand_flash_ids;
4352
4353 /*
4354 * Save the NAND_BUSWIDTH_16 flag before letting auto-detection logic
4355 * override it.
4356 * This is required to make sure initial NAND bus width set by the
4357 * NAND controller driver is coherent with the real NAND bus width
4358 * (extracted by auto-detection code).
4359 */
4360 busw = chip->options & NAND_BUSWIDTH_16;
4361
4362 /*
4363 * The flag is only set (never cleared), reset it to its default value
4364 * before starting auto-detection.
4365 */
4366 chip->options &= ~NAND_BUSWIDTH_16;
4367
4368 for (; type->name != NULL; type++) {
4369 if (is_full_id_nand(type)) {
4370 if (find_full_id_nand(mtd, chip, type))
4371 goto ident_done;
4372 } else if (*dev_id == type->dev_id) {
4373 break;
4374 }
4375 }
4376
4377 chip->onfi_version = 0;
4378 if (!type->name || !type->pagesize) {
4379 /* Check if the chip is ONFI compliant */
4380 if (nand_flash_detect_onfi(mtd, chip))
4381 goto ident_done;
4382
4383 /* Check if the chip is JEDEC compliant */
4384 if (nand_flash_detect_jedec(mtd, chip))
4385 goto ident_done;
4386 }
4387
4388 if (!type->name)
4389 return -ENODEV;
4390
4391 if (!mtd->name)
4392 mtd->name = type->name;
4393
4394 chip->chipsize = (uint64_t)type->chipsize << 20;
4395
4396 if (!type->pagesize) {
4397 nand_manufacturer_detect(chip);
4398 } else {
4399 nand_decode_id(chip, type);
4400 }
4401
4402 /* Get chip options */
4403 chip->options |= type->options;
4404
4405 ident_done:
4406
4407 if (chip->options & NAND_BUSWIDTH_AUTO) {
4408 WARN_ON(chip->options & NAND_BUSWIDTH_16);
4409 chip->options |= busw;
4410 nand_set_defaults(chip, busw);
4411 } else if (busw != (chip->options & NAND_BUSWIDTH_16)) {
4412 /*
4413 * Check, if buswidth is correct. Hardware drivers should set
4414 * chip correct!
4415 */
4416 pr_info("device found, Manufacturer ID: 0x%02x, Chip ID: 0x%02x\n",
4417 *maf_id, *dev_id);
4418 pr_info("%s %s\n", manufacturer_desc->name, mtd->name);
4419 pr_warn("bus width %d instead %d bit\n",
4420 (chip->options & NAND_BUSWIDTH_16) ? 16 : 8,
4421 busw ? 16 : 8);
4422 return -EINVAL;
4423 }
4424
4425 nand_decode_bbm_options(mtd, chip);
4426
4427 /* Calculate the address shift from the page size */
4428 chip->page_shift = ffs(mtd->writesize) - 1;
4429 /* Convert chipsize to number of pages per chip -1 */
4430 chip->pagemask = (chip->chipsize >> chip->page_shift) - 1;
4431
4432 chip->bbt_erase_shift = chip->phys_erase_shift =
4433 ffs(mtd->erasesize) - 1;
4434 if (chip->chipsize & 0xffffffff)
4435 chip->chip_shift = ffs((unsigned)chip->chipsize) - 1;
4436 else {
4437 chip->chip_shift = ffs((unsigned)(chip->chipsize >> 32));
4438 chip->chip_shift += 32 - 1;
4439 }
4440
4441 if (chip->chip_shift - chip->page_shift > 16)
4442 chip->options |= NAND_ROW_ADDR_3;
4443
4444 chip->badblockbits = 8;
4445 chip->erase = single_erase;
4446
4447 /* Do not replace user supplied command function! */
4448 if (mtd->writesize > 512 && chip->cmdfunc == nand_command)
4449 chip->cmdfunc = nand_command_lp;
4450
4451 ret = nand_manufacturer_init(chip);
4452 if (ret)
4453 return ret;
4454
4455 pr_info("device found, Manufacturer ID: 0x%02x, Chip ID: 0x%02x\n",
4456 *maf_id, *dev_id);
4457
4458 #ifdef CONFIG_SYS_NAND_ONFI_DETECTION
4459 if (chip->onfi_version)
4460 pr_info("%s %s\n", manufacturer_desc->name,
4461 chip->onfi_params.model);
4462 else if (chip->jedec_version)
4463 pr_info("%s %s\n", manufacturer_desc->name,
4464 chip->jedec_params.model);
4465 else if (manufacturer_desc)
4466 pr_info("%s %s\n", manufacturer_desc->name, type->name);
4467 #else
4468 if (chip->jedec_version)
4469 pr_info("%s %s\n", manufacturer_desc->name,
4470 chip->jedec_params.model);
4471 else if (manufacturer_desc)
4472 pr_info("%s %s\n", manufacturer_desc->name, type->name);
4473 #endif
4474
4475 pr_info("%d MiB, %s, erase size: %d KiB, page size: %d, OOB size: %d\n",
4476 (int)(chip->chipsize >> 20), nand_is_slc(chip) ? "SLC" : "MLC",
4477 mtd->erasesize >> 10, mtd->writesize, mtd->oobsize);
4478 return 0;
4479 }
4480 EXPORT_SYMBOL(nand_detect);
4481
4482 #if CONFIG_IS_ENABLED(OF_CONTROL)
4483
4484 static int nand_dt_init(struct mtd_info *mtd, struct nand_chip *chip, ofnode node)
4485 {
4486 int ret, ecc_mode = -1, ecc_strength, ecc_step;
4487 int ecc_algo = NAND_ECC_UNKNOWN;
4488 const char *str;
4489
4490 ret = ofnode_read_s32_default(node, "nand-bus-width", -1);
4491 if (ret == 16)
4492 chip->options |= NAND_BUSWIDTH_16;
4493
4494 if (ofnode_read_bool(node, "nand-on-flash-bbt"))
4495 chip->bbt_options |= NAND_BBT_USE_FLASH;
4496
4497 str = ofnode_read_string(node, "nand-ecc-mode");
4498 if (str) {
4499 if (!strcmp(str, "none"))
4500 ecc_mode = NAND_ECC_NONE;
4501 else if (!strcmp(str, "soft"))
4502 ecc_mode = NAND_ECC_SOFT;
4503 else if (!strcmp(str, "hw"))
4504 ecc_mode = NAND_ECC_HW;
4505 else if (!strcmp(str, "hw_syndrome"))
4506 ecc_mode = NAND_ECC_HW_SYNDROME;
4507 else if (!strcmp(str, "hw_oob_first"))
4508 ecc_mode = NAND_ECC_HW_OOB_FIRST;
4509 else if (!strcmp(str, "soft_bch"))
4510 ecc_mode = NAND_ECC_SOFT_BCH;
4511 }
4512
4513 str = ofnode_read_string(node, "nand-ecc-algo");
4514 if (str) {
4515 /*
4516 * If we are in NAND_ECC_SOFT mode, just alter the
4517 * soft mode to BCH here. No change of algorithm.
4518 */
4519 if (ecc_mode == NAND_ECC_SOFT) {
4520 if (!strcmp(str, "bch"))
4521 ecc_mode = NAND_ECC_SOFT_BCH;
4522 } else {
4523 if (!strcmp(str, "bch")) {
4524 ecc_algo = NAND_ECC_BCH;
4525 } else if (!strcmp(str, "hamming")) {
4526 ecc_algo = NAND_ECC_HAMMING;
4527 }
4528 }
4529 }
4530
4531 ecc_strength = ofnode_read_s32_default(node,
4532 "nand-ecc-strength", -1);
4533 ecc_step = ofnode_read_s32_default(node,
4534 "nand-ecc-step-size", -1);
4535
4536 if ((ecc_step >= 0 && !(ecc_strength >= 0)) ||
4537 (!(ecc_step >= 0) && ecc_strength >= 0)) {
4538 pr_err("must set both strength and step size in DT\n");
4539 return -EINVAL;
4540 }
4541
4542 /*
4543 * Chip drivers may have assigned default algorithms here,
4544 * onlt override it if we have found something explicitly
4545 * specified in the device tree.
4546 */
4547 if (ecc_algo != NAND_ECC_UNKNOWN)
4548 chip->ecc.algo = ecc_algo;
4549
4550 if (ecc_mode >= 0)
4551 chip->ecc.mode = ecc_mode;
4552
4553 if (ecc_strength >= 0)
4554 chip->ecc.strength = ecc_strength;
4555
4556 if (ecc_step > 0)
4557 chip->ecc.size = ecc_step;
4558
4559 if (ofnode_read_bool(node, "nand-ecc-maximize"))
4560 chip->ecc.options |= NAND_ECC_MAXIMIZE;
4561
4562 return 0;
4563 }
4564 #else
4565 static int nand_dt_init(struct mtd_info *mtd, struct nand_chip *chip, ofnode node)
4566 {
4567 return 0;
4568 }
4569 #endif /* CONFIG_IS_ENABLED(OF_CONTROL) */
4570
4571 /**
4572 * nand_scan_ident - [NAND Interface] Scan for the NAND device
4573 * @mtd: MTD device structure
4574 * @maxchips: number of chips to scan for
4575 * @table: alternative NAND ID table
4576 *
4577 * This is the first phase of the normal nand_scan() function. It reads the
4578 * flash ID and sets up MTD fields accordingly.
4579 *
4580 */
4581 int nand_scan_ident(struct mtd_info *mtd, int maxchips,
4582 struct nand_flash_dev *table)
4583 {
4584 int i, nand_maf_id, nand_dev_id;
4585 struct nand_chip *chip = mtd_to_nand(mtd);
4586 int ret;
4587
4588 if (ofnode_valid(chip->flash_node)) {
4589 ret = nand_dt_init(mtd, chip, chip->flash_node);
4590 if (ret)
4591 return ret;
4592 }
4593
4594 /* Set the default functions */
4595 nand_set_defaults(chip, chip->options & NAND_BUSWIDTH_16);
4596
4597 /* Read the flash type */
4598 ret = nand_detect(chip, &nand_maf_id, &nand_dev_id, table);
4599
4600 if (ret) {
4601 if (!(chip->options & NAND_SCAN_SILENT_NODEV))
4602 pr_warn("No NAND device found\n");
4603 chip->select_chip(mtd, -1);
4604 return ret;
4605 }
4606
4607 /* Initialize the ->data_interface field. */
4608 ret = nand_init_data_interface(chip);
4609 if (ret)
4610 return ret;
4611
4612 /*
4613 * Setup the data interface correctly on the chip and controller side.
4614 * This explicit call to nand_setup_data_interface() is only required
4615 * for the first die, because nand_reset() has been called before
4616 * ->data_interface and ->default_onfi_timing_mode were set.
4617 * For the other dies, nand_reset() will automatically switch to the
4618 * best mode for us.
4619 */
4620 ret = nand_setup_data_interface(chip, 0);
4621 if (ret)
4622 return ret;
4623
4624 chip->select_chip(mtd, -1);
4625
4626 /* Check for a chip array */
4627 for (i = 1; i < maxchips; i++) {
4628 u8 id[2];
4629
4630 /* See comment in nand_detect for reset */
4631 nand_reset(chip, i);
4632
4633 chip->select_chip(mtd, i);
4634 /* Send the command for reading device ID */
4635 nand_readid_op(chip, 0, id, sizeof(id));
4636
4637 /* Read manufacturer and device IDs */
4638 if (nand_maf_id != id[0] || nand_dev_id != id[1]) {
4639 chip->select_chip(mtd, -1);
4640 break;
4641 }
4642 chip->select_chip(mtd, -1);
4643 }
4644
4645 #ifdef DEBUG
4646 if (i > 1)
4647 pr_info("%d chips detected\n", i);
4648 #endif
4649
4650 /* Store the number of chips and calc total size for mtd */
4651 chip->numchips = i;
4652 mtd->size = i * chip->chipsize;
4653
4654 return 0;
4655 }
4656 EXPORT_SYMBOL(nand_scan_ident);
4657
4658 /**
4659 * nand_check_ecc_caps - check the sanity of preset ECC settings
4660 * @chip: nand chip info structure
4661 * @caps: ECC caps info structure
4662 * @oobavail: OOB size that the ECC engine can use
4663 *
4664 * When ECC step size and strength are already set, check if they are supported
4665 * by the controller and the calculated ECC bytes fit within the chip's OOB.
4666 * On success, the calculated ECC bytes is set.
4667 */
4668 int nand_check_ecc_caps(struct nand_chip *chip,
4669 const struct nand_ecc_caps *caps, int oobavail)
4670 {
4671 struct mtd_info *mtd = nand_to_mtd(chip);
4672 const struct nand_ecc_step_info *stepinfo;
4673 int preset_step = chip->ecc.size;
4674 int preset_strength = chip->ecc.strength;
4675 int nsteps, ecc_bytes;
4676 int i, j;
4677
4678 if (WARN_ON(oobavail < 0))
4679 return -EINVAL;
4680
4681 if (!preset_step || !preset_strength)
4682 return -ENODATA;
4683
4684 nsteps = mtd->writesize / preset_step;
4685
4686 for (i = 0; i < caps->nstepinfos; i++) {
4687 stepinfo = &caps->stepinfos[i];
4688
4689 if (stepinfo->stepsize != preset_step)
4690 continue;
4691
4692 for (j = 0; j < stepinfo->nstrengths; j++) {
4693 if (stepinfo->strengths[j] != preset_strength)
4694 continue;
4695
4696 ecc_bytes = caps->calc_ecc_bytes(preset_step,
4697 preset_strength);
4698 if (WARN_ON_ONCE(ecc_bytes < 0))
4699 return ecc_bytes;
4700
4701 if (ecc_bytes * nsteps > oobavail) {
4702 pr_err("ECC (step, strength) = (%d, %d) does not fit in OOB",
4703 preset_step, preset_strength);
4704 return -ENOSPC;
4705 }
4706
4707 chip->ecc.bytes = ecc_bytes;
4708
4709 return 0;
4710 }
4711 }
4712
4713 pr_err("ECC (step, strength) = (%d, %d) not supported on this controller",
4714 preset_step, preset_strength);
4715
4716 return -ENOTSUPP;
4717 }
4718 EXPORT_SYMBOL_GPL(nand_check_ecc_caps);
4719
4720 /**
4721 * nand_match_ecc_req - meet the chip's requirement with least ECC bytes
4722 * @chip: nand chip info structure
4723 * @caps: ECC engine caps info structure
4724 * @oobavail: OOB size that the ECC engine can use
4725 *
4726 * If a chip's ECC requirement is provided, try to meet it with the least
4727 * number of ECC bytes (i.e. with the largest number of OOB-free bytes).
4728 * On success, the chosen ECC settings are set.
4729 */
4730 int nand_match_ecc_req(struct nand_chip *chip,
4731 const struct nand_ecc_caps *caps, int oobavail)
4732 {
4733 struct mtd_info *mtd = nand_to_mtd(chip);
4734 const struct nand_ecc_step_info *stepinfo;
4735 int req_step = chip->ecc_step_ds;
4736 int req_strength = chip->ecc_strength_ds;
4737 int req_corr, step_size, strength, nsteps, ecc_bytes, ecc_bytes_total;
4738 int best_step, best_strength, best_ecc_bytes;
4739 int best_ecc_bytes_total = INT_MAX;
4740 int i, j;
4741
4742 if (WARN_ON(oobavail < 0))
4743 return -EINVAL;
4744
4745 /* No information provided by the NAND chip */
4746 if (!req_step || !req_strength)
4747 return -ENOTSUPP;
4748
4749 /* number of correctable bits the chip requires in a page */
4750 req_corr = mtd->writesize / req_step * req_strength;
4751
4752 for (i = 0; i < caps->nstepinfos; i++) {
4753 stepinfo = &caps->stepinfos[i];
4754 step_size = stepinfo->stepsize;
4755
4756 for (j = 0; j < stepinfo->nstrengths; j++) {
4757 strength = stepinfo->strengths[j];
4758
4759 /*
4760 * If both step size and strength are smaller than the
4761 * chip's requirement, it is not easy to compare the
4762 * resulted reliability.
4763 */
4764 if (step_size < req_step && strength < req_strength)
4765 continue;
4766
4767 if (mtd->writesize % step_size)
4768 continue;
4769
4770 nsteps = mtd->writesize / step_size;
4771
4772 ecc_bytes = caps->calc_ecc_bytes(step_size, strength);
4773 if (WARN_ON_ONCE(ecc_bytes < 0))
4774 continue;
4775 ecc_bytes_total = ecc_bytes * nsteps;
4776
4777 if (ecc_bytes_total > oobavail ||
4778 strength * nsteps < req_corr)
4779 continue;
4780
4781 /*
4782 * We assume the best is to meet the chip's requrement
4783 * with the least number of ECC bytes.
4784 */
4785 if (ecc_bytes_total < best_ecc_bytes_total) {
4786 best_ecc_bytes_total = ecc_bytes_total;
4787 best_step = step_size;
4788 best_strength = strength;
4789 best_ecc_bytes = ecc_bytes;
4790 }
4791 }
4792 }
4793
4794 if (best_ecc_bytes_total == INT_MAX)
4795 return -ENOTSUPP;
4796
4797 chip->ecc.size = best_step;
4798 chip->ecc.strength = best_strength;
4799 chip->ecc.bytes = best_ecc_bytes;
4800
4801 return 0;
4802 }
4803 EXPORT_SYMBOL_GPL(nand_match_ecc_req);
4804
4805 /**
4806 * nand_maximize_ecc - choose the max ECC strength available
4807 * @chip: nand chip info structure
4808 * @caps: ECC engine caps info structure
4809 * @oobavail: OOB size that the ECC engine can use
4810 *
4811 * Choose the max ECC strength that is supported on the controller, and can fit
4812 * within the chip's OOB. On success, the chosen ECC settings are set.
4813 */
4814 int nand_maximize_ecc(struct nand_chip *chip,
4815 const struct nand_ecc_caps *caps, int oobavail)
4816 {
4817 struct mtd_info *mtd = nand_to_mtd(chip);
4818 const struct nand_ecc_step_info *stepinfo;
4819 int step_size, strength, nsteps, ecc_bytes, corr;
4820 int best_corr = 0;
4821 int best_step = 0;
4822 int best_strength, best_ecc_bytes;
4823 int i, j;
4824
4825 if (WARN_ON(oobavail < 0))
4826 return -EINVAL;
4827
4828 for (i = 0; i < caps->nstepinfos; i++) {
4829 stepinfo = &caps->stepinfos[i];
4830 step_size = stepinfo->stepsize;
4831
4832 /* If chip->ecc.size is already set, respect it */
4833 if (chip->ecc.size && step_size != chip->ecc.size)
4834 continue;
4835
4836 for (j = 0; j < stepinfo->nstrengths; j++) {
4837 strength = stepinfo->strengths[j];
4838
4839 if (mtd->writesize % step_size)
4840 continue;
4841
4842 nsteps = mtd->writesize / step_size;
4843
4844 ecc_bytes = caps->calc_ecc_bytes(step_size, strength);
4845 if (WARN_ON_ONCE(ecc_bytes < 0))
4846 continue;
4847
4848 if (ecc_bytes * nsteps > oobavail)
4849 continue;
4850
4851 corr = strength * nsteps;
4852
4853 /*
4854 * If the number of correctable bits is the same,
4855 * bigger step_size has more reliability.
4856 */
4857 if (corr > best_corr ||
4858 (corr == best_corr && step_size > best_step)) {
4859 best_corr = corr;
4860 best_step = step_size;
4861 best_strength = strength;
4862 best_ecc_bytes = ecc_bytes;
4863 }
4864 }
4865 }
4866
4867 if (!best_corr)
4868 return -ENOTSUPP;
4869
4870 chip->ecc.size = best_step;
4871 chip->ecc.strength = best_strength;
4872 chip->ecc.bytes = best_ecc_bytes;
4873
4874 return 0;
4875 }
4876 EXPORT_SYMBOL_GPL(nand_maximize_ecc);
4877
4878 /*
4879 * Check if the chip configuration meet the datasheet requirements.
4880
4881 * If our configuration corrects A bits per B bytes and the minimum
4882 * required correction level is X bits per Y bytes, then we must ensure
4883 * both of the following are true:
4884 *
4885 * (1) A / B >= X / Y
4886 * (2) A >= X
4887 *
4888 * Requirement (1) ensures we can correct for the required bitflip density.
4889 * Requirement (2) ensures we can correct even when all bitflips are clumped
4890 * in the same sector.
4891 */
4892 static bool nand_ecc_strength_good(struct mtd_info *mtd)
4893 {
4894 struct nand_chip *chip = mtd_to_nand(mtd);
4895 struct nand_ecc_ctrl *ecc = &chip->ecc;
4896 int corr, ds_corr;
4897
4898 if (ecc->size == 0 || chip->ecc_step_ds == 0)
4899 /* Not enough information */
4900 return true;
4901
4902 /*
4903 * We get the number of corrected bits per page to compare
4904 * the correction density.
4905 */
4906 corr = (mtd->writesize * ecc->strength) / ecc->size;
4907 ds_corr = (mtd->writesize * chip->ecc_strength_ds) / chip->ecc_step_ds;
4908
4909 return corr >= ds_corr && ecc->strength >= chip->ecc_strength_ds;
4910 }
4911
4912 static bool invalid_ecc_page_accessors(struct nand_chip *chip)
4913 {
4914 struct nand_ecc_ctrl *ecc = &chip->ecc;
4915
4916 if (nand_standard_page_accessors(ecc))
4917 return false;
4918
4919 /*
4920 * NAND_ECC_CUSTOM_PAGE_ACCESS flag is set, make sure the NAND
4921 * controller driver implements all the page accessors because
4922 * default helpers are not suitable when the core does not
4923 * send the READ0/PAGEPROG commands.
4924 */
4925 return (!ecc->read_page || !ecc->write_page ||
4926 !ecc->read_page_raw || !ecc->write_page_raw ||
4927 (NAND_HAS_SUBPAGE_READ(chip) && !ecc->read_subpage) ||
4928 (NAND_HAS_SUBPAGE_WRITE(chip) && !ecc->write_subpage &&
4929 ecc->hwctl && ecc->calculate));
4930 }
4931
4932 /**
4933 * nand_scan_tail - [NAND Interface] Scan for the NAND device
4934 * @mtd: MTD device structure
4935 *
4936 * This is the second phase of the normal nand_scan() function. It fills out
4937 * all the uninitialized function pointers with the defaults and scans for a
4938 * bad block table if appropriate.
4939 */
4940 int nand_scan_tail(struct mtd_info *mtd)
4941 {
4942 int i;
4943 struct nand_chip *chip = mtd_to_nand(mtd);
4944 struct nand_ecc_ctrl *ecc = &chip->ecc;
4945 struct nand_buffers *nbuf;
4946
4947 /* New bad blocks should be marked in OOB, flash-based BBT, or both */
4948 BUG_ON((chip->bbt_options & NAND_BBT_NO_OOB_BBM) &&
4949 !(chip->bbt_options & NAND_BBT_USE_FLASH));
4950
4951 if (invalid_ecc_page_accessors(chip)) {
4952 pr_err("Invalid ECC page accessors setup\n");
4953 return -EINVAL;
4954 }
4955
4956 if (!(chip->options & NAND_OWN_BUFFERS)) {
4957 nbuf = kzalloc(sizeof(struct nand_buffers), GFP_KERNEL);
4958 chip->buffers = nbuf;
4959 } else {
4960 if (!chip->buffers)
4961 return -ENOMEM;
4962 }
4963
4964 /* Set the internal oob buffer location, just after the page data */
4965 chip->oob_poi = chip->buffers->databuf + mtd->writesize;
4966
4967 /*
4968 * If no default placement scheme is given, select an appropriate one.
4969 */
4970 if (!ecc->layout && (ecc->mode != NAND_ECC_SOFT_BCH)) {
4971 switch (mtd->oobsize) {
4972 #ifndef CONFIG_SYS_NAND_DRIVER_ECC_LAYOUT
4973 case 8:
4974 ecc->layout = &nand_oob_8;
4975 break;
4976 case 16:
4977 ecc->layout = &nand_oob_16;
4978 break;
4979 case 64:
4980 ecc->layout = &nand_oob_64;
4981 break;
4982 case 128:
4983 ecc->layout = &nand_oob_128;
4984 break;
4985 #endif
4986 default:
4987 pr_warn("No oob scheme defined for oobsize %d\n",
4988 mtd->oobsize);
4989 BUG();
4990 }
4991 }
4992
4993 if (!chip->write_page)
4994 chip->write_page = nand_write_page;
4995
4996 /*
4997 * Check ECC mode, default to software if 3byte/512byte hardware ECC is
4998 * selected and we have 256 byte pagesize fallback to software ECC
4999 */
5000
5001 switch (ecc->mode) {
5002 case NAND_ECC_HW_OOB_FIRST:
5003 /* Similar to NAND_ECC_HW, but a separate read_page handle */
5004 if (!ecc->calculate || !ecc->correct || !ecc->hwctl) {
5005 pr_warn("No ECC functions supplied; hardware ECC not possible\n");
5006 BUG();
5007 }
5008 if (!ecc->read_page)
5009 ecc->read_page = nand_read_page_hwecc_oob_first;
5010
5011 case NAND_ECC_HW:
5012 /* Use standard hwecc read page function? */
5013 if (!ecc->read_page)
5014 ecc->read_page = nand_read_page_hwecc;
5015 if (!ecc->write_page)
5016 ecc->write_page = nand_write_page_hwecc;
5017 if (!ecc->read_page_raw)
5018 ecc->read_page_raw = nand_read_page_raw;
5019 if (!ecc->write_page_raw)
5020 ecc->write_page_raw = nand_write_page_raw;
5021 if (!ecc->read_oob)
5022 ecc->read_oob = nand_read_oob_std;
5023 if (!ecc->write_oob)
5024 ecc->write_oob = nand_write_oob_std;
5025 if (!ecc->read_subpage)
5026 ecc->read_subpage = nand_read_subpage;
5027 if (!ecc->write_subpage && ecc->hwctl && ecc->calculate)
5028 ecc->write_subpage = nand_write_subpage_hwecc;
5029
5030 case NAND_ECC_HW_SYNDROME:
5031 if ((!ecc->calculate || !ecc->correct || !ecc->hwctl) &&
5032 (!ecc->read_page ||
5033 ecc->read_page == nand_read_page_hwecc ||
5034 !ecc->write_page ||
5035 ecc->write_page == nand_write_page_hwecc)) {
5036 pr_warn("No ECC functions supplied; hardware ECC not possible\n");
5037 BUG();
5038 }
5039 /* Use standard syndrome read/write page function? */
5040 if (!ecc->read_page)
5041 ecc->read_page = nand_read_page_syndrome;
5042 if (!ecc->write_page)
5043 ecc->write_page = nand_write_page_syndrome;
5044 if (!ecc->read_page_raw)
5045 ecc->read_page_raw = nand_read_page_raw_syndrome;
5046 if (!ecc->write_page_raw)
5047 ecc->write_page_raw = nand_write_page_raw_syndrome;
5048 if (!ecc->read_oob)
5049 ecc->read_oob = nand_read_oob_syndrome;
5050 if (!ecc->write_oob)
5051 ecc->write_oob = nand_write_oob_syndrome;
5052
5053 if (mtd->writesize >= ecc->size) {
5054 if (!ecc->strength) {
5055 pr_warn("Driver must set ecc.strength when using hardware ECC\n");
5056 BUG();
5057 }
5058 break;
5059 }
5060 pr_warn("%d byte HW ECC not possible on %d byte page size, fallback to SW ECC\n",
5061 ecc->size, mtd->writesize);
5062 ecc->mode = NAND_ECC_SOFT;
5063
5064 case NAND_ECC_SOFT:
5065 ecc->calculate = nand_calculate_ecc;
5066 ecc->correct = nand_correct_data;
5067 ecc->read_page = nand_read_page_swecc;
5068 ecc->read_subpage = nand_read_subpage;
5069 ecc->write_page = nand_write_page_swecc;
5070 ecc->read_page_raw = nand_read_page_raw;
5071 ecc->write_page_raw = nand_write_page_raw;
5072 ecc->read_oob = nand_read_oob_std;
5073 ecc->write_oob = nand_write_oob_std;
5074 if (!ecc->size)
5075 ecc->size = 256;
5076 ecc->bytes = 3;
5077 ecc->strength = 1;
5078 break;
5079
5080 case NAND_ECC_SOFT_BCH:
5081 if (!mtd_nand_has_bch()) {
5082 pr_warn("CONFIG_MTD_NAND_ECC_BCH not enabled\n");
5083 BUG();
5084 }
5085 ecc->calculate = nand_bch_calculate_ecc;
5086 ecc->correct = nand_bch_correct_data;
5087 ecc->read_page = nand_read_page_swecc;
5088 ecc->read_subpage = nand_read_subpage;
5089 ecc->write_page = nand_write_page_swecc;
5090 ecc->read_page_raw = nand_read_page_raw;
5091 ecc->write_page_raw = nand_write_page_raw;
5092 ecc->read_oob = nand_read_oob_std;
5093 ecc->write_oob = nand_write_oob_std;
5094 /*
5095 * Board driver should supply ecc.size and ecc.strength values
5096 * to select how many bits are correctable. Otherwise, default
5097 * to 4 bits for large page devices.
5098 */
5099 if (!ecc->size && (mtd->oobsize >= 64)) {
5100 ecc->size = 512;
5101 ecc->strength = 4;
5102 }
5103
5104 /* See nand_bch_init() for details. */
5105 ecc->bytes = 0;
5106 ecc->priv = nand_bch_init(mtd);
5107 if (!ecc->priv) {
5108 pr_warn("BCH ECC initialization failed!\n");
5109 BUG();
5110 }
5111 break;
5112
5113 case NAND_ECC_NONE:
5114 pr_warn("NAND_ECC_NONE selected by board driver. This is not recommended!\n");
5115 ecc->read_page = nand_read_page_raw;
5116 ecc->write_page = nand_write_page_raw;
5117 ecc->read_oob = nand_read_oob_std;
5118 ecc->read_page_raw = nand_read_page_raw;
5119 ecc->write_page_raw = nand_write_page_raw;
5120 ecc->write_oob = nand_write_oob_std;
5121 ecc->size = mtd->writesize;
5122 ecc->bytes = 0;
5123 ecc->strength = 0;
5124 break;
5125
5126 default:
5127 pr_warn("Invalid NAND_ECC_MODE %d\n", ecc->mode);
5128 BUG();
5129 }
5130
5131 /* For many systems, the standard OOB write also works for raw */
5132 if (!ecc->read_oob_raw)
5133 ecc->read_oob_raw = ecc->read_oob;
5134 if (!ecc->write_oob_raw)
5135 ecc->write_oob_raw = ecc->write_oob;
5136
5137 /*
5138 * The number of bytes available for a client to place data into
5139 * the out of band area.
5140 */
5141 mtd->oobavail = 0;
5142 if (ecc->layout) {
5143 for (i = 0; ecc->layout->oobfree[i].length; i++)
5144 mtd->oobavail += ecc->layout->oobfree[i].length;
5145 }
5146
5147 /* ECC sanity check: warn if it's too weak */
5148 if (!nand_ecc_strength_good(mtd))
5149 pr_warn("WARNING: %s: the ECC used on your system is too weak compared to the one required by the NAND chip\n",
5150 mtd->name);
5151
5152 /*
5153 * Set the number of read / write steps for one page depending on ECC
5154 * mode.
5155 */
5156 ecc->steps = mtd->writesize / ecc->size;
5157 if (ecc->steps * ecc->size != mtd->writesize) {
5158 pr_warn("Invalid ECC parameters\n");
5159 BUG();
5160 }
5161 ecc->total = ecc->steps * ecc->bytes;
5162
5163 /* Allow subpage writes up to ecc.steps. Not possible for MLC flash */
5164 if (!(chip->options & NAND_NO_SUBPAGE_WRITE) && nand_is_slc(chip)) {
5165 switch (ecc->steps) {
5166 case 2:
5167 mtd->subpage_sft = 1;
5168 break;
5169 case 4:
5170 case 8:
5171 case 16:
5172 mtd->subpage_sft = 2;
5173 break;
5174 }
5175 }
5176 chip->subpagesize = mtd->writesize >> mtd->subpage_sft;
5177
5178 /* Initialize state */
5179 chip->state = FL_READY;
5180
5181 /* Invalidate the pagebuffer reference */
5182 chip->pagebuf = -1;
5183
5184 /* Large page NAND with SOFT_ECC should support subpage reads */
5185 switch (ecc->mode) {
5186 case NAND_ECC_SOFT:
5187 case NAND_ECC_SOFT_BCH:
5188 if (chip->page_shift > 9)
5189 chip->options |= NAND_SUBPAGE_READ;
5190 break;
5191
5192 default:
5193 break;
5194 }
5195
5196 mtd->flash_node = chip->flash_node;
5197 /* Fill in remaining MTD driver data */
5198 mtd->type = nand_is_slc(chip) ? MTD_NANDFLASH : MTD_MLCNANDFLASH;
5199 mtd->flags = (chip->options & NAND_ROM) ? MTD_CAP_ROM :
5200 MTD_CAP_NANDFLASH;
5201 mtd->_erase = nand_erase;
5202 mtd->_panic_write = panic_nand_write;
5203 mtd->_read_oob = nand_read_oob;
5204 mtd->_write_oob = nand_write_oob;
5205 mtd->_sync = nand_sync;
5206 mtd->_lock = NULL;
5207 mtd->_unlock = NULL;
5208 mtd->_block_isreserved = nand_block_isreserved;
5209 mtd->_block_isbad = nand_block_isbad;
5210 mtd->_block_markbad = nand_block_markbad;
5211 mtd->writebufsize = mtd->writesize;
5212
5213 /* propagate ecc info to mtd_info */
5214 mtd->ecclayout = ecc->layout;
5215 mtd->ecc_strength = ecc->strength;
5216 mtd->ecc_step_size = ecc->size;
5217 /*
5218 * Initialize bitflip_threshold to its default prior scan_bbt() call.
5219 * scan_bbt() might invoke mtd_read(), thus bitflip_threshold must be
5220 * properly set.
5221 */
5222 if (!mtd->bitflip_threshold)
5223 mtd->bitflip_threshold = DIV_ROUND_UP(mtd->ecc_strength * 3, 4);
5224
5225 return 0;
5226 }
5227 EXPORT_SYMBOL(nand_scan_tail);
5228
5229 /**
5230 * nand_scan - [NAND Interface] Scan for the NAND device
5231 * @mtd: MTD device structure
5232 * @maxchips: number of chips to scan for
5233 *
5234 * This fills out all the uninitialized function pointers with the defaults.
5235 * The flash ID is read and the mtd/chip structures are filled with the
5236 * appropriate values.
5237 */
5238 int nand_scan(struct mtd_info *mtd, int maxchips)
5239 {
5240 int ret;
5241
5242 ret = nand_scan_ident(mtd, maxchips, NULL);
5243 if (!ret)
5244 ret = nand_scan_tail(mtd);
5245 return ret;
5246 }
5247 EXPORT_SYMBOL(nand_scan);
5248
5249 MODULE_LICENSE("GPL");
5250 MODULE_AUTHOR("Steven J. Hill <sjhill@realitydiluted.com>");
5251 MODULE_AUTHOR("Thomas Gleixner <tglx@linutronix.de>");
5252 MODULE_DESCRIPTION("Generic NAND flash driver code");