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