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