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