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