]> git.sur5r.net Git - u-boot/blob - drivers/mtd/nand/nand_base.c
mtd: nand: Drop the ->errstat() hook
[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                         if (nand_standard_page_accessors(&chip->ecc))
1736                                 chip->cmdfunc(mtd, NAND_CMD_READ0, 0x00, page);
1737
1738                         /*
1739                          * Now read the page into the buffer.  Absent an error,
1740                          * the read methods return max bitflips per ecc step.
1741                          */
1742                         if (unlikely(ops->mode == MTD_OPS_RAW))
1743                                 ret = chip->ecc.read_page_raw(mtd, chip, bufpoi,
1744                                                               oob_required,
1745                                                               page);
1746                         else if (!aligned && NAND_HAS_SUBPAGE_READ(chip) &&
1747                                  !oob)
1748                                 ret = chip->ecc.read_subpage(mtd, chip,
1749                                                         col, bytes, bufpoi,
1750                                                         page);
1751                         else
1752                                 ret = chip->ecc.read_page(mtd, chip, bufpoi,
1753                                                           oob_required, page);
1754                         if (ret < 0) {
1755                                 if (use_bufpoi)
1756                                         /* Invalidate page cache */
1757                                         chip->pagebuf = -1;
1758                                 break;
1759                         }
1760
1761                         max_bitflips = max_t(unsigned int, max_bitflips, ret);
1762
1763                         /* Transfer not aligned data */
1764                         if (use_bufpoi) {
1765                                 if (!NAND_HAS_SUBPAGE_READ(chip) && !oob &&
1766                                     !(mtd->ecc_stats.failed - ecc_failures) &&
1767                                     (ops->mode != MTD_OPS_RAW)) {
1768                                         chip->pagebuf = realpage;
1769                                         chip->pagebuf_bitflips = ret;
1770                                 } else {
1771                                         /* Invalidate page cache */
1772                                         chip->pagebuf = -1;
1773                                 }
1774                                 memcpy(buf, chip->buffers->databuf + col, bytes);
1775                         }
1776
1777                         if (unlikely(oob)) {
1778                                 int toread = min(oobreadlen, max_oobsize);
1779
1780                                 if (toread) {
1781                                         oob = nand_transfer_oob(chip,
1782                                                 oob, ops, toread);
1783                                         oobreadlen -= toread;
1784                                 }
1785                         }
1786
1787                         if (chip->options & NAND_NEED_READRDY) {
1788                                 /* Apply delay or wait for ready/busy pin */
1789                                 if (!chip->dev_ready)
1790                                         udelay(chip->chip_delay);
1791                                 else
1792                                         nand_wait_ready(mtd);
1793                         }
1794
1795                         if (mtd->ecc_stats.failed - ecc_failures) {
1796                                 if (retry_mode + 1 < chip->read_retries) {
1797                                         retry_mode++;
1798                                         ret = nand_setup_read_retry(mtd,
1799                                                         retry_mode);
1800                                         if (ret < 0)
1801                                                 break;
1802
1803                                         /* Reset failures; retry */
1804                                         mtd->ecc_stats.failed = ecc_failures;
1805                                         goto read_retry;
1806                                 } else {
1807                                         /* No more retry modes; real failure */
1808                                         ecc_fail = true;
1809                                 }
1810                         }
1811
1812                         buf += bytes;
1813                 } else {
1814                         memcpy(buf, chip->buffers->databuf + col, bytes);
1815                         buf += bytes;
1816                         max_bitflips = max_t(unsigned int, max_bitflips,
1817                                              chip->pagebuf_bitflips);
1818                 }
1819
1820                 readlen -= bytes;
1821
1822                 /* Reset to retry mode 0 */
1823                 if (retry_mode) {
1824                         ret = nand_setup_read_retry(mtd, 0);
1825                         if (ret < 0)
1826                                 break;
1827                         retry_mode = 0;
1828                 }
1829
1830                 if (!readlen)
1831                         break;
1832
1833                 /* For subsequent reads align to page boundary */
1834                 col = 0;
1835                 /* Increment page address */
1836                 realpage++;
1837
1838                 page = realpage & chip->pagemask;
1839                 /* Check, if we cross a chip boundary */
1840                 if (!page) {
1841                         chipnr++;
1842                         chip->select_chip(mtd, -1);
1843                         chip->select_chip(mtd, chipnr);
1844                 }
1845         }
1846         chip->select_chip(mtd, -1);
1847
1848         ops->retlen = ops->len - (size_t) readlen;
1849         if (oob)
1850                 ops->oobretlen = ops->ooblen - oobreadlen;
1851
1852         if (ret < 0)
1853                 return ret;
1854
1855         if (ecc_fail)
1856                 return -EBADMSG;
1857
1858         return max_bitflips;
1859 }
1860
1861 /**
1862  * nand_read - [MTD Interface] MTD compatibility function for nand_do_read_ecc
1863  * @mtd: MTD device structure
1864  * @from: offset to read from
1865  * @len: number of bytes to read
1866  * @retlen: pointer to variable to store the number of read bytes
1867  * @buf: the databuffer to put data
1868  *
1869  * Get hold of the chip and call nand_do_read.
1870  */
1871 static int nand_read(struct mtd_info *mtd, loff_t from, size_t len,
1872                      size_t *retlen, uint8_t *buf)
1873 {
1874         struct mtd_oob_ops ops;
1875         int ret;
1876
1877         nand_get_device(mtd, FL_READING);
1878         memset(&ops, 0, sizeof(ops));
1879         ops.len = len;
1880         ops.datbuf = buf;
1881         ops.mode = MTD_OPS_PLACE_OOB;
1882         ret = nand_do_read_ops(mtd, from, &ops);
1883         *retlen = ops.retlen;
1884         nand_release_device(mtd);
1885         return ret;
1886 }
1887
1888 /**
1889  * nand_read_oob_std - [REPLACEABLE] the most common OOB data read function
1890  * @mtd: mtd info structure
1891  * @chip: nand chip info structure
1892  * @page: page number to read
1893  */
1894 static int nand_read_oob_std(struct mtd_info *mtd, struct nand_chip *chip,
1895                              int page)
1896 {
1897         chip->cmdfunc(mtd, NAND_CMD_READOOB, 0, page);
1898         chip->read_buf(mtd, chip->oob_poi, mtd->oobsize);
1899         return 0;
1900 }
1901
1902 /**
1903  * nand_read_oob_syndrome - [REPLACEABLE] OOB data read function for HW ECC
1904  *                          with syndromes
1905  * @mtd: mtd info structure
1906  * @chip: nand chip info structure
1907  * @page: page number to read
1908  */
1909 static int nand_read_oob_syndrome(struct mtd_info *mtd, struct nand_chip *chip,
1910                                   int page)
1911 {
1912         int length = mtd->oobsize;
1913         int chunk = chip->ecc.bytes + chip->ecc.prepad + chip->ecc.postpad;
1914         int eccsize = chip->ecc.size;
1915         uint8_t *bufpoi = chip->oob_poi;
1916         int i, toread, sndrnd = 0, pos;
1917
1918         chip->cmdfunc(mtd, NAND_CMD_READ0, chip->ecc.size, page);
1919         for (i = 0; i < chip->ecc.steps; i++) {
1920                 if (sndrnd) {
1921                         pos = eccsize + i * (eccsize + chunk);
1922                         if (mtd->writesize > 512)
1923                                 chip->cmdfunc(mtd, NAND_CMD_RNDOUT, pos, -1);
1924                         else
1925                                 chip->cmdfunc(mtd, NAND_CMD_READ0, pos, page);
1926                 } else
1927                         sndrnd = 1;
1928                 toread = min_t(int, length, chunk);
1929                 chip->read_buf(mtd, bufpoi, toread);
1930                 bufpoi += toread;
1931                 length -= toread;
1932         }
1933         if (length > 0)
1934                 chip->read_buf(mtd, bufpoi, length);
1935
1936         return 0;
1937 }
1938
1939 /**
1940  * nand_write_oob_std - [REPLACEABLE] the most common OOB data write function
1941  * @mtd: mtd info structure
1942  * @chip: nand chip info structure
1943  * @page: page number to write
1944  */
1945 static int nand_write_oob_std(struct mtd_info *mtd, struct nand_chip *chip,
1946                               int page)
1947 {
1948         int status = 0;
1949         const uint8_t *buf = chip->oob_poi;
1950         int length = mtd->oobsize;
1951
1952         chip->cmdfunc(mtd, NAND_CMD_SEQIN, mtd->writesize, page);
1953         chip->write_buf(mtd, buf, length);
1954         /* Send command to program the OOB data */
1955         chip->cmdfunc(mtd, NAND_CMD_PAGEPROG, -1, -1);
1956
1957         status = chip->waitfunc(mtd, chip);
1958
1959         return status & NAND_STATUS_FAIL ? -EIO : 0;
1960 }
1961
1962 /**
1963  * nand_write_oob_syndrome - [REPLACEABLE] OOB data write function for HW ECC
1964  *                           with syndrome - only for large page flash
1965  * @mtd: mtd info structure
1966  * @chip: nand chip info structure
1967  * @page: page number to write
1968  */
1969 static int nand_write_oob_syndrome(struct mtd_info *mtd,
1970                                    struct nand_chip *chip, int page)
1971 {
1972         int chunk = chip->ecc.bytes + chip->ecc.prepad + chip->ecc.postpad;
1973         int eccsize = chip->ecc.size, length = mtd->oobsize;
1974         int i, len, pos, status = 0, sndcmd = 0, steps = chip->ecc.steps;
1975         const uint8_t *bufpoi = chip->oob_poi;
1976
1977         /*
1978          * data-ecc-data-ecc ... ecc-oob
1979          * or
1980          * data-pad-ecc-pad-data-pad .... ecc-pad-oob
1981          */
1982         if (!chip->ecc.prepad && !chip->ecc.postpad) {
1983                 pos = steps * (eccsize + chunk);
1984                 steps = 0;
1985         } else
1986                 pos = eccsize;
1987
1988         chip->cmdfunc(mtd, NAND_CMD_SEQIN, pos, page);
1989         for (i = 0; i < steps; i++) {
1990                 if (sndcmd) {
1991                         if (mtd->writesize <= 512) {
1992                                 uint32_t fill = 0xFFFFFFFF;
1993
1994                                 len = eccsize;
1995                                 while (len > 0) {
1996                                         int num = min_t(int, len, 4);
1997                                         chip->write_buf(mtd, (uint8_t *)&fill,
1998                                                         num);
1999                                         len -= num;
2000                                 }
2001                         } else {
2002                                 pos = eccsize + i * (eccsize + chunk);
2003                                 chip->cmdfunc(mtd, NAND_CMD_RNDIN, pos, -1);
2004                         }
2005                 } else
2006                         sndcmd = 1;
2007                 len = min_t(int, length, chunk);
2008                 chip->write_buf(mtd, bufpoi, len);
2009                 bufpoi += len;
2010                 length -= len;
2011         }
2012         if (length > 0)
2013                 chip->write_buf(mtd, bufpoi, length);
2014
2015         chip->cmdfunc(mtd, NAND_CMD_PAGEPROG, -1, -1);
2016         status = chip->waitfunc(mtd, chip);
2017
2018         return status & NAND_STATUS_FAIL ? -EIO : 0;
2019 }
2020
2021 /**
2022  * nand_do_read_oob - [INTERN] NAND read out-of-band
2023  * @mtd: MTD device structure
2024  * @from: offset to read from
2025  * @ops: oob operations description structure
2026  *
2027  * NAND read out-of-band data from the spare area.
2028  */
2029 static int nand_do_read_oob(struct mtd_info *mtd, loff_t from,
2030                             struct mtd_oob_ops *ops)
2031 {
2032         int page, realpage, chipnr;
2033         struct nand_chip *chip = mtd_to_nand(mtd);
2034         struct mtd_ecc_stats stats;
2035         int readlen = ops->ooblen;
2036         int len;
2037         uint8_t *buf = ops->oobbuf;
2038         int ret = 0;
2039
2040         pr_debug("%s: from = 0x%08Lx, len = %i\n",
2041                         __func__, (unsigned long long)from, readlen);
2042
2043         stats = mtd->ecc_stats;
2044
2045         len = mtd_oobavail(mtd, ops);
2046
2047         if (unlikely(ops->ooboffs >= len)) {
2048                 pr_debug("%s: attempt to start read outside oob\n",
2049                                 __func__);
2050                 return -EINVAL;
2051         }
2052
2053         /* Do not allow reads past end of device */
2054         if (unlikely(from >= mtd->size ||
2055                      ops->ooboffs + readlen > ((mtd->size >> chip->page_shift) -
2056                                         (from >> chip->page_shift)) * len)) {
2057                 pr_debug("%s: attempt to read beyond end of device\n",
2058                                 __func__);
2059                 return -EINVAL;
2060         }
2061
2062         chipnr = (int)(from >> chip->chip_shift);
2063         chip->select_chip(mtd, chipnr);
2064
2065         /* Shift to get page */
2066         realpage = (int)(from >> chip->page_shift);
2067         page = realpage & chip->pagemask;
2068
2069         while (1) {
2070                 WATCHDOG_RESET();
2071
2072                 if (ops->mode == MTD_OPS_RAW)
2073                         ret = chip->ecc.read_oob_raw(mtd, chip, page);
2074                 else
2075                         ret = chip->ecc.read_oob(mtd, chip, page);
2076
2077                 if (ret < 0)
2078                         break;
2079
2080                 len = min(len, readlen);
2081                 buf = nand_transfer_oob(chip, buf, ops, len);
2082
2083                 if (chip->options & NAND_NEED_READRDY) {
2084                         /* Apply delay or wait for ready/busy pin */
2085                         if (!chip->dev_ready)
2086                                 udelay(chip->chip_delay);
2087                         else
2088                                 nand_wait_ready(mtd);
2089                 }
2090
2091                 readlen -= len;
2092                 if (!readlen)
2093                         break;
2094
2095                 /* Increment page address */
2096                 realpage++;
2097
2098                 page = realpage & chip->pagemask;
2099                 /* Check, if we cross a chip boundary */
2100                 if (!page) {
2101                         chipnr++;
2102                         chip->select_chip(mtd, -1);
2103                         chip->select_chip(mtd, chipnr);
2104                 }
2105         }
2106         chip->select_chip(mtd, -1);
2107
2108         ops->oobretlen = ops->ooblen - readlen;
2109
2110         if (ret < 0)
2111                 return ret;
2112
2113         if (mtd->ecc_stats.failed - stats.failed)
2114                 return -EBADMSG;
2115
2116         return  mtd->ecc_stats.corrected - stats.corrected ? -EUCLEAN : 0;
2117 }
2118
2119 /**
2120  * nand_read_oob - [MTD Interface] NAND read data and/or out-of-band
2121  * @mtd: MTD device structure
2122  * @from: offset to read from
2123  * @ops: oob operation description structure
2124  *
2125  * NAND read data and/or out-of-band data.
2126  */
2127 static int nand_read_oob(struct mtd_info *mtd, loff_t from,
2128                          struct mtd_oob_ops *ops)
2129 {
2130         int ret = -ENOTSUPP;
2131
2132         ops->retlen = 0;
2133
2134         /* Do not allow reads past end of device */
2135         if (ops->datbuf && (from + ops->len) > mtd->size) {
2136                 pr_debug("%s: attempt to read beyond end of device\n",
2137                                 __func__);
2138                 return -EINVAL;
2139         }
2140
2141         nand_get_device(mtd, FL_READING);
2142
2143         switch (ops->mode) {
2144         case MTD_OPS_PLACE_OOB:
2145         case MTD_OPS_AUTO_OOB:
2146         case MTD_OPS_RAW:
2147                 break;
2148
2149         default:
2150                 goto out;
2151         }
2152
2153         if (!ops->datbuf)
2154                 ret = nand_do_read_oob(mtd, from, ops);
2155         else
2156                 ret = nand_do_read_ops(mtd, from, ops);
2157
2158 out:
2159         nand_release_device(mtd);
2160         return ret;
2161 }
2162
2163
2164 /**
2165  * nand_write_page_raw - [INTERN] raw page write function
2166  * @mtd: mtd info structure
2167  * @chip: nand chip info structure
2168  * @buf: data buffer
2169  * @oob_required: must write chip->oob_poi to OOB
2170  * @page: page number to write
2171  *
2172  * Not for syndrome calculating ECC controllers, which use a special oob layout.
2173  */
2174 static int nand_write_page_raw(struct mtd_info *mtd, struct nand_chip *chip,
2175                                const uint8_t *buf, int oob_required, int page)
2176 {
2177         chip->write_buf(mtd, buf, mtd->writesize);
2178         if (oob_required)
2179                 chip->write_buf(mtd, chip->oob_poi, mtd->oobsize);
2180
2181         return 0;
2182 }
2183
2184 /**
2185  * nand_write_page_raw_syndrome - [INTERN] raw page write function
2186  * @mtd: mtd info structure
2187  * @chip: nand chip info structure
2188  * @buf: data buffer
2189  * @oob_required: must write chip->oob_poi to OOB
2190  * @page: page number to write
2191  *
2192  * We need a special oob layout and handling even when ECC isn't checked.
2193  */
2194 static int nand_write_page_raw_syndrome(struct mtd_info *mtd,
2195                                         struct nand_chip *chip,
2196                                         const uint8_t *buf, int oob_required,
2197                                         int page)
2198 {
2199         int eccsize = chip->ecc.size;
2200         int eccbytes = chip->ecc.bytes;
2201         uint8_t *oob = chip->oob_poi;
2202         int steps, size;
2203
2204         for (steps = chip->ecc.steps; steps > 0; steps--) {
2205                 chip->write_buf(mtd, buf, eccsize);
2206                 buf += eccsize;
2207
2208                 if (chip->ecc.prepad) {
2209                         chip->write_buf(mtd, oob, chip->ecc.prepad);
2210                         oob += chip->ecc.prepad;
2211                 }
2212
2213                 chip->write_buf(mtd, oob, eccbytes);
2214                 oob += eccbytes;
2215
2216                 if (chip->ecc.postpad) {
2217                         chip->write_buf(mtd, oob, chip->ecc.postpad);
2218                         oob += chip->ecc.postpad;
2219                 }
2220         }
2221
2222         size = mtd->oobsize - (oob - chip->oob_poi);
2223         if (size)
2224                 chip->write_buf(mtd, oob, size);
2225
2226         return 0;
2227 }
2228 /**
2229  * nand_write_page_swecc - [REPLACEABLE] software ECC based page write function
2230  * @mtd: mtd info structure
2231  * @chip: nand chip info structure
2232  * @buf: data buffer
2233  * @oob_required: must write chip->oob_poi to OOB
2234  * @page: page number to write
2235  */
2236 static int nand_write_page_swecc(struct mtd_info *mtd, struct nand_chip *chip,
2237                                  const uint8_t *buf, int oob_required,
2238                                  int page)
2239 {
2240         int i, eccsize = chip->ecc.size;
2241         int eccbytes = chip->ecc.bytes;
2242         int eccsteps = chip->ecc.steps;
2243         uint8_t *ecc_calc = chip->buffers->ecccalc;
2244         const uint8_t *p = buf;
2245         uint32_t *eccpos = chip->ecc.layout->eccpos;
2246
2247         /* Software ECC calculation */
2248         for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize)
2249                 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
2250
2251         for (i = 0; i < chip->ecc.total; i++)
2252                 chip->oob_poi[eccpos[i]] = ecc_calc[i];
2253
2254         return chip->ecc.write_page_raw(mtd, chip, buf, 1, page);
2255 }
2256
2257 /**
2258  * nand_write_page_hwecc - [REPLACEABLE] hardware ECC based page write function
2259  * @mtd: mtd info structure
2260  * @chip: nand chip info structure
2261  * @buf: data buffer
2262  * @oob_required: must write chip->oob_poi to OOB
2263  * @page: page number to write
2264  */
2265 static int nand_write_page_hwecc(struct mtd_info *mtd, struct nand_chip *chip,
2266                                   const uint8_t *buf, int oob_required,
2267                                   int page)
2268 {
2269         int i, eccsize = chip->ecc.size;
2270         int eccbytes = chip->ecc.bytes;
2271         int eccsteps = chip->ecc.steps;
2272         uint8_t *ecc_calc = chip->buffers->ecccalc;
2273         const uint8_t *p = buf;
2274         uint32_t *eccpos = chip->ecc.layout->eccpos;
2275
2276         for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
2277                 chip->ecc.hwctl(mtd, NAND_ECC_WRITE);
2278                 chip->write_buf(mtd, p, eccsize);
2279                 chip->ecc.calculate(mtd, p, &ecc_calc[i]);
2280         }
2281
2282         for (i = 0; i < chip->ecc.total; i++)
2283                 chip->oob_poi[eccpos[i]] = ecc_calc[i];
2284
2285         chip->write_buf(mtd, chip->oob_poi, mtd->oobsize);
2286
2287         return 0;
2288 }
2289
2290
2291 /**
2292  * nand_write_subpage_hwecc - [REPLACEABLE] hardware ECC based subpage write
2293  * @mtd:        mtd info structure
2294  * @chip:       nand chip info structure
2295  * @offset:     column address of subpage within the page
2296  * @data_len:   data length
2297  * @buf:        data buffer
2298  * @oob_required: must write chip->oob_poi to OOB
2299  * @page: page number to write
2300  */
2301 static int nand_write_subpage_hwecc(struct mtd_info *mtd,
2302                                 struct nand_chip *chip, uint32_t offset,
2303                                 uint32_t data_len, const uint8_t *buf,
2304                                 int oob_required, int page)
2305 {
2306         uint8_t *oob_buf  = chip->oob_poi;
2307         uint8_t *ecc_calc = chip->buffers->ecccalc;
2308         int ecc_size      = chip->ecc.size;
2309         int ecc_bytes     = chip->ecc.bytes;
2310         int ecc_steps     = chip->ecc.steps;
2311         uint32_t *eccpos  = chip->ecc.layout->eccpos;
2312         uint32_t start_step = offset / ecc_size;
2313         uint32_t end_step   = (offset + data_len - 1) / ecc_size;
2314         int oob_bytes       = mtd->oobsize / ecc_steps;
2315         int step, i;
2316
2317         for (step = 0; step < ecc_steps; step++) {
2318                 /* configure controller for WRITE access */
2319                 chip->ecc.hwctl(mtd, NAND_ECC_WRITE);
2320
2321                 /* write data (untouched subpages already masked by 0xFF) */
2322                 chip->write_buf(mtd, buf, ecc_size);
2323
2324                 /* mask ECC of un-touched subpages by padding 0xFF */
2325                 if ((step < start_step) || (step > end_step))
2326                         memset(ecc_calc, 0xff, ecc_bytes);
2327                 else
2328                         chip->ecc.calculate(mtd, buf, ecc_calc);
2329
2330                 /* mask OOB of un-touched subpages by padding 0xFF */
2331                 /* if oob_required, preserve OOB metadata of written subpage */
2332                 if (!oob_required || (step < start_step) || (step > end_step))
2333                         memset(oob_buf, 0xff, oob_bytes);
2334
2335                 buf += ecc_size;
2336                 ecc_calc += ecc_bytes;
2337                 oob_buf  += oob_bytes;
2338         }
2339
2340         /* copy calculated ECC for whole page to chip->buffer->oob */
2341         /* this include masked-value(0xFF) for unwritten subpages */
2342         ecc_calc = chip->buffers->ecccalc;
2343         for (i = 0; i < chip->ecc.total; i++)
2344                 chip->oob_poi[eccpos[i]] = ecc_calc[i];
2345
2346         /* write OOB buffer to NAND device */
2347         chip->write_buf(mtd, chip->oob_poi, mtd->oobsize);
2348
2349         return 0;
2350 }
2351
2352
2353 /**
2354  * nand_write_page_syndrome - [REPLACEABLE] hardware ECC syndrome based page write
2355  * @mtd: mtd info structure
2356  * @chip: nand chip info structure
2357  * @buf: data buffer
2358  * @oob_required: must write chip->oob_poi to OOB
2359  * @page: page number to write
2360  *
2361  * The hw generator calculates the error syndrome automatically. Therefore we
2362  * need a special oob layout and handling.
2363  */
2364 static int nand_write_page_syndrome(struct mtd_info *mtd,
2365                                     struct nand_chip *chip,
2366                                     const uint8_t *buf, int oob_required,
2367                                     int page)
2368 {
2369         int i, eccsize = chip->ecc.size;
2370         int eccbytes = chip->ecc.bytes;
2371         int eccsteps = chip->ecc.steps;
2372         const uint8_t *p = buf;
2373         uint8_t *oob = chip->oob_poi;
2374
2375         for (i = 0; eccsteps; eccsteps--, i += eccbytes, p += eccsize) {
2376
2377                 chip->ecc.hwctl(mtd, NAND_ECC_WRITE);
2378                 chip->write_buf(mtd, p, eccsize);
2379
2380                 if (chip->ecc.prepad) {
2381                         chip->write_buf(mtd, oob, chip->ecc.prepad);
2382                         oob += chip->ecc.prepad;
2383                 }
2384
2385                 chip->ecc.calculate(mtd, p, oob);
2386                 chip->write_buf(mtd, oob, eccbytes);
2387                 oob += eccbytes;
2388
2389                 if (chip->ecc.postpad) {
2390                         chip->write_buf(mtd, oob, chip->ecc.postpad);
2391                         oob += chip->ecc.postpad;
2392                 }
2393         }
2394
2395         /* Calculate remaining oob bytes */
2396         i = mtd->oobsize - (oob - chip->oob_poi);
2397         if (i)
2398                 chip->write_buf(mtd, oob, i);
2399
2400         return 0;
2401 }
2402
2403 /**
2404  * nand_write_page - [REPLACEABLE] write one page
2405  * @mtd: MTD device structure
2406  * @chip: NAND chip descriptor
2407  * @offset: address offset within the page
2408  * @data_len: length of actual data to be written
2409  * @buf: the data to write
2410  * @oob_required: must write chip->oob_poi to OOB
2411  * @page: page number to write
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 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         if (nand_standard_page_accessors(&chip->ecc))
2427                 chip->cmdfunc(mtd, NAND_CMD_SEQIN, 0x00, page);
2428
2429         if (unlikely(raw))
2430                 status = chip->ecc.write_page_raw(mtd, chip, buf,
2431                                                   oob_required, page);
2432         else if (subpage)
2433                 status = chip->ecc.write_subpage(mtd, chip, offset, data_len,
2434                                                  buf, oob_required, page);
2435         else
2436                 status = chip->ecc.write_page(mtd, chip, buf, oob_required,
2437                                               page);
2438
2439         if (status < 0)
2440                 return status;
2441
2442         if (nand_standard_page_accessors(&chip->ecc))
2443                 chip->cmdfunc(mtd, NAND_CMD_PAGEPROG, -1, -1);
2444         status = chip->waitfunc(mtd, chip);
2445
2446         if (status & NAND_STATUS_FAIL)
2447                 return -EIO;
2448
2449         return 0;
2450 }
2451
2452 /**
2453  * nand_fill_oob - [INTERN] Transfer client buffer to oob
2454  * @mtd: MTD device structure
2455  * @oob: oob data buffer
2456  * @len: oob data write length
2457  * @ops: oob ops structure
2458  */
2459 static uint8_t *nand_fill_oob(struct mtd_info *mtd, uint8_t *oob, size_t len,
2460                               struct mtd_oob_ops *ops)
2461 {
2462         struct nand_chip *chip = mtd_to_nand(mtd);
2463
2464         /*
2465          * Initialise to all 0xFF, to avoid the possibility of left over OOB
2466          * data from a previous OOB read.
2467          */
2468         memset(chip->oob_poi, 0xff, mtd->oobsize);
2469
2470         switch (ops->mode) {
2471
2472         case MTD_OPS_PLACE_OOB:
2473         case MTD_OPS_RAW:
2474                 memcpy(chip->oob_poi + ops->ooboffs, oob, len);
2475                 return oob + len;
2476
2477         case MTD_OPS_AUTO_OOB: {
2478                 struct nand_oobfree *free = chip->ecc.layout->oobfree;
2479                 uint32_t boffs = 0, woffs = ops->ooboffs;
2480                 size_t bytes = 0;
2481
2482                 for (; free->length && len; free++, len -= bytes) {
2483                         /* Write request not from offset 0? */
2484                         if (unlikely(woffs)) {
2485                                 if (woffs >= free->length) {
2486                                         woffs -= free->length;
2487                                         continue;
2488                                 }
2489                                 boffs = free->offset + woffs;
2490                                 bytes = min_t(size_t, len,
2491                                               (free->length - woffs));
2492                                 woffs = 0;
2493                         } else {
2494                                 bytes = min_t(size_t, len, free->length);
2495                                 boffs = free->offset;
2496                         }
2497                         memcpy(chip->oob_poi + boffs, oob, bytes);
2498                         oob += bytes;
2499                 }
2500                 return oob;
2501         }
2502         default:
2503                 BUG();
2504         }
2505         return NULL;
2506 }
2507
2508 #define NOTALIGNED(x)   ((x & (chip->subpagesize - 1)) != 0)
2509
2510 /**
2511  * nand_do_write_ops - [INTERN] NAND write with ECC
2512  * @mtd: MTD device structure
2513  * @to: offset to write to
2514  * @ops: oob operations description structure
2515  *
2516  * NAND write with ECC.
2517  */
2518 static int nand_do_write_ops(struct mtd_info *mtd, loff_t to,
2519                              struct mtd_oob_ops *ops)
2520 {
2521         int chipnr, realpage, page, column;
2522         struct nand_chip *chip = mtd_to_nand(mtd);
2523         uint32_t writelen = ops->len;
2524
2525         uint32_t oobwritelen = ops->ooblen;
2526         uint32_t oobmaxlen = mtd_oobavail(mtd, ops);
2527
2528         uint8_t *oob = ops->oobbuf;
2529         uint8_t *buf = ops->datbuf;
2530         int ret;
2531         int oob_required = oob ? 1 : 0;
2532
2533         ops->retlen = 0;
2534         if (!writelen)
2535                 return 0;
2536
2537         /* Reject writes, which are not page aligned */
2538         if (NOTALIGNED(to)) {
2539                 pr_notice("%s: attempt to write non page aligned data\n",
2540                            __func__);
2541                 return -EINVAL;
2542         }
2543
2544         column = to & (mtd->writesize - 1);
2545
2546         chipnr = (int)(to >> chip->chip_shift);
2547         chip->select_chip(mtd, chipnr);
2548
2549         /* Check, if it is write protected */
2550         if (nand_check_wp(mtd)) {
2551                 ret = -EIO;
2552                 goto err_out;
2553         }
2554
2555         realpage = (int)(to >> chip->page_shift);
2556         page = realpage & chip->pagemask;
2557
2558         /* Invalidate the page cache, when we write to the cached page */
2559         if (to <= ((loff_t)chip->pagebuf << chip->page_shift) &&
2560             ((loff_t)chip->pagebuf << chip->page_shift) < (to + ops->len))
2561                 chip->pagebuf = -1;
2562
2563         /* Don't allow multipage oob writes with offset */
2564         if (oob && ops->ooboffs && (ops->ooboffs + ops->ooblen > oobmaxlen)) {
2565                 ret = -EINVAL;
2566                 goto err_out;
2567         }
2568
2569         while (1) {
2570                 int bytes = mtd->writesize;
2571                 uint8_t *wbuf = buf;
2572                 int use_bufpoi;
2573                 int part_pagewr = (column || writelen < mtd->writesize);
2574
2575                 if (part_pagewr)
2576                         use_bufpoi = 1;
2577                 else
2578                         use_bufpoi = 0;
2579
2580                 WATCHDOG_RESET();
2581                 /* Partial page write?, or need to use bounce buffer */
2582                 if (use_bufpoi) {
2583                         pr_debug("%s: using write bounce buffer for buf@%p\n",
2584                                          __func__, buf);
2585                         if (part_pagewr)
2586                                 bytes = min_t(int, bytes - column, writelen);
2587                         chip->pagebuf = -1;
2588                         memset(chip->buffers->databuf, 0xff, mtd->writesize);
2589                         memcpy(&chip->buffers->databuf[column], buf, bytes);
2590                         wbuf = chip->buffers->databuf;
2591                 }
2592
2593                 if (unlikely(oob)) {
2594                         size_t len = min(oobwritelen, oobmaxlen);
2595                         oob = nand_fill_oob(mtd, oob, len, ops);
2596                         oobwritelen -= len;
2597                 } else {
2598                         /* We still need to erase leftover OOB data */
2599                         memset(chip->oob_poi, 0xff, mtd->oobsize);
2600                 }
2601                 ret = chip->write_page(mtd, chip, column, bytes, wbuf,
2602                                         oob_required, page,
2603                                         (ops->mode == MTD_OPS_RAW));
2604                 if (ret)
2605                         break;
2606
2607                 writelen -= bytes;
2608                 if (!writelen)
2609                         break;
2610
2611                 column = 0;
2612                 buf += bytes;
2613                 realpage++;
2614
2615                 page = realpage & chip->pagemask;
2616                 /* Check, if we cross a chip boundary */
2617                 if (!page) {
2618                         chipnr++;
2619                         chip->select_chip(mtd, -1);
2620                         chip->select_chip(mtd, chipnr);
2621                 }
2622         }
2623
2624         ops->retlen = ops->len - writelen;
2625         if (unlikely(oob))
2626                 ops->oobretlen = ops->ooblen;
2627
2628 err_out:
2629         chip->select_chip(mtd, -1);
2630         return ret;
2631 }
2632
2633 /**
2634  * panic_nand_write - [MTD Interface] NAND write with ECC
2635  * @mtd: MTD device structure
2636  * @to: offset to write to
2637  * @len: number of bytes to write
2638  * @retlen: pointer to variable to store the number of written bytes
2639  * @buf: the data to write
2640  *
2641  * NAND write with ECC. Used when performing writes in interrupt context, this
2642  * may for example be called by mtdoops when writing an oops while in panic.
2643  */
2644 static int panic_nand_write(struct mtd_info *mtd, loff_t to, size_t len,
2645                             size_t *retlen, const uint8_t *buf)
2646 {
2647         struct nand_chip *chip = mtd_to_nand(mtd);
2648         struct mtd_oob_ops ops;
2649         int ret;
2650
2651         /* Wait for the device to get ready */
2652         panic_nand_wait(mtd, chip, 400);
2653
2654         /* Grab the device */
2655         panic_nand_get_device(chip, mtd, FL_WRITING);
2656
2657         memset(&ops, 0, sizeof(ops));
2658         ops.len = len;
2659         ops.datbuf = (uint8_t *)buf;
2660         ops.mode = MTD_OPS_PLACE_OOB;
2661
2662         ret = nand_do_write_ops(mtd, to, &ops);
2663
2664         *retlen = ops.retlen;
2665         return ret;
2666 }
2667
2668 /**
2669  * nand_write - [MTD Interface] NAND write with ECC
2670  * @mtd: MTD device structure
2671  * @to: offset to write to
2672  * @len: number of bytes to write
2673  * @retlen: pointer to variable to store the number of written bytes
2674  * @buf: the data to write
2675  *
2676  * NAND write with ECC.
2677  */
2678 static int nand_write(struct mtd_info *mtd, loff_t to, size_t len,
2679                           size_t *retlen, const uint8_t *buf)
2680 {
2681         struct mtd_oob_ops ops;
2682         int ret;
2683
2684         nand_get_device(mtd, FL_WRITING);
2685         memset(&ops, 0, sizeof(ops));
2686         ops.len = len;
2687         ops.datbuf = (uint8_t *)buf;
2688         ops.mode = MTD_OPS_PLACE_OOB;
2689         ret = nand_do_write_ops(mtd, to, &ops);
2690         *retlen = ops.retlen;
2691         nand_release_device(mtd);
2692         return ret;
2693 }
2694
2695 /**
2696  * nand_do_write_oob - [MTD Interface] NAND write out-of-band
2697  * @mtd: MTD device structure
2698  * @to: offset to write to
2699  * @ops: oob operation description structure
2700  *
2701  * NAND write out-of-band.
2702  */
2703 static int nand_do_write_oob(struct mtd_info *mtd, loff_t to,
2704                              struct mtd_oob_ops *ops)
2705 {
2706         int chipnr, page, status, len;
2707         struct nand_chip *chip = mtd_to_nand(mtd);
2708
2709         pr_debug("%s: to = 0x%08x, len = %i\n",
2710                          __func__, (unsigned int)to, (int)ops->ooblen);
2711
2712         len = mtd_oobavail(mtd, ops);
2713
2714         /* Do not allow write past end of page */
2715         if ((ops->ooboffs + ops->ooblen) > len) {
2716                 pr_debug("%s: attempt to write past end of page\n",
2717                                 __func__);
2718                 return -EINVAL;
2719         }
2720
2721         if (unlikely(ops->ooboffs >= len)) {
2722                 pr_debug("%s: attempt to start write outside oob\n",
2723                                 __func__);
2724                 return -EINVAL;
2725         }
2726
2727         /* Do not allow write past end of device */
2728         if (unlikely(to >= mtd->size ||
2729                      ops->ooboffs + ops->ooblen >
2730                         ((mtd->size >> chip->page_shift) -
2731                          (to >> chip->page_shift)) * len)) {
2732                 pr_debug("%s: attempt to write beyond end of device\n",
2733                                 __func__);
2734                 return -EINVAL;
2735         }
2736
2737         chipnr = (int)(to >> chip->chip_shift);
2738
2739         /*
2740          * Reset the chip. Some chips (like the Toshiba TC5832DC found in one
2741          * of my DiskOnChip 2000 test units) will clear the whole data page too
2742          * if we don't do this. I have no clue why, but I seem to have 'fixed'
2743          * it in the doc2000 driver in August 1999.  dwmw2.
2744          */
2745         nand_reset(chip, chipnr);
2746
2747         chip->select_chip(mtd, chipnr);
2748
2749         /* Shift to get page */
2750         page = (int)(to >> chip->page_shift);
2751
2752         /* Check, if it is write protected */
2753         if (nand_check_wp(mtd)) {
2754                 chip->select_chip(mtd, -1);
2755                 return -EROFS;
2756         }
2757
2758         /* Invalidate the page cache, if we write to the cached page */
2759         if (page == chip->pagebuf)
2760                 chip->pagebuf = -1;
2761
2762         nand_fill_oob(mtd, ops->oobbuf, ops->ooblen, ops);
2763
2764         if (ops->mode == MTD_OPS_RAW)
2765                 status = chip->ecc.write_oob_raw(mtd, chip, page & chip->pagemask);
2766         else
2767                 status = chip->ecc.write_oob(mtd, chip, page & chip->pagemask);
2768
2769         chip->select_chip(mtd, -1);
2770
2771         if (status)
2772                 return status;
2773
2774         ops->oobretlen = ops->ooblen;
2775
2776         return 0;
2777 }
2778
2779 /**
2780  * nand_write_oob - [MTD Interface] NAND write data and/or out-of-band
2781  * @mtd: MTD device structure
2782  * @to: offset to write to
2783  * @ops: oob operation description structure
2784  */
2785 static int nand_write_oob(struct mtd_info *mtd, loff_t to,
2786                           struct mtd_oob_ops *ops)
2787 {
2788         int ret = -ENOTSUPP;
2789
2790         ops->retlen = 0;
2791
2792         /* Do not allow writes past end of device */
2793         if (ops->datbuf && (to + ops->len) > mtd->size) {
2794                 pr_debug("%s: attempt to write beyond end of device\n",
2795                                 __func__);
2796                 return -EINVAL;
2797         }
2798
2799         nand_get_device(mtd, FL_WRITING);
2800
2801         switch (ops->mode) {
2802         case MTD_OPS_PLACE_OOB:
2803         case MTD_OPS_AUTO_OOB:
2804         case MTD_OPS_RAW:
2805                 break;
2806
2807         default:
2808                 goto out;
2809         }
2810
2811         if (!ops->datbuf)
2812                 ret = nand_do_write_oob(mtd, to, ops);
2813         else
2814                 ret = nand_do_write_ops(mtd, to, ops);
2815
2816 out:
2817         nand_release_device(mtd);
2818         return ret;
2819 }
2820
2821 /**
2822  * single_erase - [GENERIC] NAND standard block erase command function
2823  * @mtd: MTD device structure
2824  * @page: the page address of the block which will be erased
2825  *
2826  * Standard erase command for NAND chips. Returns NAND status.
2827  */
2828 static int single_erase(struct mtd_info *mtd, int page)
2829 {
2830         struct nand_chip *chip = mtd_to_nand(mtd);
2831         /* Send commands to erase a block */
2832         chip->cmdfunc(mtd, NAND_CMD_ERASE1, -1, page);
2833         chip->cmdfunc(mtd, NAND_CMD_ERASE2, -1, -1);
2834
2835         return chip->waitfunc(mtd, chip);
2836 }
2837
2838 /**
2839  * nand_erase - [MTD Interface] erase block(s)
2840  * @mtd: MTD device structure
2841  * @instr: erase instruction
2842  *
2843  * Erase one ore more blocks.
2844  */
2845 static int nand_erase(struct mtd_info *mtd, struct erase_info *instr)
2846 {
2847         return nand_erase_nand(mtd, instr, 0);
2848 }
2849
2850 /**
2851  * nand_erase_nand - [INTERN] erase block(s)
2852  * @mtd: MTD device structure
2853  * @instr: erase instruction
2854  * @allowbbt: allow erasing the bbt area
2855  *
2856  * Erase one ore more blocks.
2857  */
2858 int nand_erase_nand(struct mtd_info *mtd, struct erase_info *instr,
2859                     int allowbbt)
2860 {
2861         int page, status, pages_per_block, ret, chipnr;
2862         struct nand_chip *chip = mtd_to_nand(mtd);
2863         loff_t len;
2864
2865         pr_debug("%s: start = 0x%012llx, len = %llu\n",
2866                         __func__, (unsigned long long)instr->addr,
2867                         (unsigned long long)instr->len);
2868
2869         if (check_offs_len(mtd, instr->addr, instr->len))
2870                 return -EINVAL;
2871
2872         /* Grab the lock and see if the device is available */
2873         nand_get_device(mtd, FL_ERASING);
2874
2875         /* Shift to get first page */
2876         page = (int)(instr->addr >> chip->page_shift);
2877         chipnr = (int)(instr->addr >> chip->chip_shift);
2878
2879         /* Calculate pages in each block */
2880         pages_per_block = 1 << (chip->phys_erase_shift - chip->page_shift);
2881
2882         /* Select the NAND device */
2883         chip->select_chip(mtd, chipnr);
2884
2885         /* Check, if it is write protected */
2886         if (nand_check_wp(mtd)) {
2887                 pr_debug("%s: device is write protected!\n",
2888                                 __func__);
2889                 instr->state = MTD_ERASE_FAILED;
2890                 goto erase_exit;
2891         }
2892
2893         /* Loop through the pages */
2894         len = instr->len;
2895
2896         instr->state = MTD_ERASING;
2897
2898         while (len) {
2899                 WATCHDOG_RESET();
2900
2901                 /* Check if we have a bad block, we do not erase bad blocks! */
2902                 if (!instr->scrub && nand_block_checkbad(mtd, ((loff_t) page) <<
2903                                         chip->page_shift, allowbbt)) {
2904                         pr_warn("%s: attempt to erase a bad block at page 0x%08x\n",
2905                                     __func__, page);
2906                         instr->state = MTD_ERASE_FAILED;
2907                         goto erase_exit;
2908                 }
2909
2910                 /*
2911                  * Invalidate the page cache, if we erase the block which
2912                  * contains the current cached page.
2913                  */
2914                 if (page <= chip->pagebuf && chip->pagebuf <
2915                     (page + pages_per_block))
2916                         chip->pagebuf = -1;
2917
2918                 status = chip->erase(mtd, page & chip->pagemask);
2919
2920                 /* See if block erase succeeded */
2921                 if (status & NAND_STATUS_FAIL) {
2922                         pr_debug("%s: failed erase, page 0x%08x\n",
2923                                         __func__, page);
2924                         instr->state = MTD_ERASE_FAILED;
2925                         instr->fail_addr =
2926                                 ((loff_t)page << chip->page_shift);
2927                         goto erase_exit;
2928                 }
2929
2930                 /* Increment page address and decrement length */
2931                 len -= (1ULL << chip->phys_erase_shift);
2932                 page += pages_per_block;
2933
2934                 /* Check, if we cross a chip boundary */
2935                 if (len && !(page & chip->pagemask)) {
2936                         chipnr++;
2937                         chip->select_chip(mtd, -1);
2938                         chip->select_chip(mtd, chipnr);
2939                 }
2940         }
2941         instr->state = MTD_ERASE_DONE;
2942
2943 erase_exit:
2944
2945         ret = instr->state == MTD_ERASE_DONE ? 0 : -EIO;
2946
2947         /* Deselect and wake up anyone waiting on the device */
2948         chip->select_chip(mtd, -1);
2949         nand_release_device(mtd);
2950
2951         /* Do call back function */
2952         if (!ret)
2953                 mtd_erase_callback(instr);
2954
2955         /* Return more or less happy */
2956         return ret;
2957 }
2958
2959 /**
2960  * nand_sync - [MTD Interface] sync
2961  * @mtd: MTD device structure
2962  *
2963  * Sync is actually a wait for chip ready function.
2964  */
2965 static void nand_sync(struct mtd_info *mtd)
2966 {
2967         pr_debug("%s: called\n", __func__);
2968
2969         /* Grab the lock and see if the device is available */
2970         nand_get_device(mtd, FL_SYNCING);
2971         /* Release it and go back */
2972         nand_release_device(mtd);
2973 }
2974
2975 /**
2976  * nand_block_isbad - [MTD Interface] Check if block at offset is bad
2977  * @mtd: MTD device structure
2978  * @offs: offset relative to mtd start
2979  */
2980 static int nand_block_isbad(struct mtd_info *mtd, loff_t offs)
2981 {
2982         struct nand_chip *chip = mtd_to_nand(mtd);
2983         int chipnr = (int)(offs >> chip->chip_shift);
2984         int ret;
2985
2986         /* Select the NAND device */
2987         nand_get_device(mtd, FL_READING);
2988         chip->select_chip(mtd, chipnr);
2989
2990         ret = nand_block_checkbad(mtd, offs, 0);
2991
2992         chip->select_chip(mtd, -1);
2993         nand_release_device(mtd);
2994
2995         return ret;
2996 }
2997
2998 /**
2999  * nand_block_markbad - [MTD Interface] Mark block at the given offset as bad
3000  * @mtd: MTD device structure
3001  * @ofs: offset relative to mtd start
3002  */
3003 static int nand_block_markbad(struct mtd_info *mtd, loff_t ofs)
3004 {
3005         int ret;
3006
3007         ret = nand_block_isbad(mtd, ofs);
3008         if (ret) {
3009                 /* If it was bad already, return success and do nothing */
3010                 if (ret > 0)
3011                         return 0;
3012                 return ret;
3013         }
3014
3015         return nand_block_markbad_lowlevel(mtd, ofs);
3016 }
3017
3018 /**
3019  * nand_onfi_set_features- [REPLACEABLE] set features for ONFI nand
3020  * @mtd: MTD device structure
3021  * @chip: nand chip info structure
3022  * @addr: feature address.
3023  * @subfeature_param: the subfeature parameters, a four bytes array.
3024  */
3025 static int nand_onfi_set_features(struct mtd_info *mtd, struct nand_chip *chip,
3026                         int addr, uint8_t *subfeature_param)
3027 {
3028         int status;
3029         int i;
3030
3031 #ifdef CONFIG_SYS_NAND_ONFI_DETECTION
3032         if (!chip->onfi_version ||
3033             !(le16_to_cpu(chip->onfi_params.opt_cmd)
3034               & ONFI_OPT_CMD_SET_GET_FEATURES))
3035                 return -EINVAL;
3036 #endif
3037
3038         chip->cmdfunc(mtd, NAND_CMD_SET_FEATURES, addr, -1);
3039         for (i = 0; i < ONFI_SUBFEATURE_PARAM_LEN; ++i)
3040                 chip->write_byte(mtd, subfeature_param[i]);
3041
3042         status = chip->waitfunc(mtd, chip);
3043         if (status & NAND_STATUS_FAIL)
3044                 return -EIO;
3045         return 0;
3046 }
3047
3048 /**
3049  * nand_onfi_get_features- [REPLACEABLE] get features for ONFI nand
3050  * @mtd: MTD device structure
3051  * @chip: nand chip info structure
3052  * @addr: feature address.
3053  * @subfeature_param: the subfeature parameters, a four bytes array.
3054  */
3055 static int nand_onfi_get_features(struct mtd_info *mtd, struct nand_chip *chip,
3056                         int addr, uint8_t *subfeature_param)
3057 {
3058         int i;
3059
3060 #ifdef CONFIG_SYS_NAND_ONFI_DETECTION
3061         if (!chip->onfi_version ||
3062             !(le16_to_cpu(chip->onfi_params.opt_cmd)
3063               & ONFI_OPT_CMD_SET_GET_FEATURES))
3064                 return -EINVAL;
3065 #endif
3066
3067         chip->cmdfunc(mtd, NAND_CMD_GET_FEATURES, addr, -1);
3068         for (i = 0; i < ONFI_SUBFEATURE_PARAM_LEN; ++i)
3069                 *subfeature_param++ = chip->read_byte(mtd);
3070         return 0;
3071 }
3072
3073 /* Set default functions */
3074 static void nand_set_defaults(struct nand_chip *chip, int busw)
3075 {
3076         /* check for proper chip_delay setup, set 20us if not */
3077         if (!chip->chip_delay)
3078                 chip->chip_delay = 20;
3079
3080         /* check, if a user supplied command function given */
3081         if (chip->cmdfunc == NULL)
3082                 chip->cmdfunc = nand_command;
3083
3084         /* check, if a user supplied wait function given */
3085         if (chip->waitfunc == NULL)
3086                 chip->waitfunc = nand_wait;
3087
3088         if (!chip->select_chip)
3089                 chip->select_chip = nand_select_chip;
3090
3091         /* set for ONFI nand */
3092         if (!chip->onfi_set_features)
3093                 chip->onfi_set_features = nand_onfi_set_features;
3094         if (!chip->onfi_get_features)
3095                 chip->onfi_get_features = nand_onfi_get_features;
3096
3097         /* If called twice, pointers that depend on busw may need to be reset */
3098         if (!chip->read_byte || chip->read_byte == nand_read_byte)
3099                 chip->read_byte = busw ? nand_read_byte16 : nand_read_byte;
3100         if (!chip->read_word)
3101                 chip->read_word = nand_read_word;
3102         if (!chip->block_bad)
3103                 chip->block_bad = nand_block_bad;
3104         if (!chip->block_markbad)
3105                 chip->block_markbad = nand_default_block_markbad;
3106         if (!chip->write_buf || chip->write_buf == nand_write_buf)
3107                 chip->write_buf = busw ? nand_write_buf16 : nand_write_buf;
3108         if (!chip->write_byte || chip->write_byte == nand_write_byte)
3109                 chip->write_byte = busw ? nand_write_byte16 : nand_write_byte;
3110         if (!chip->read_buf || chip->read_buf == nand_read_buf)
3111                 chip->read_buf = busw ? nand_read_buf16 : nand_read_buf;
3112         if (!chip->scan_bbt)
3113                 chip->scan_bbt = nand_default_bbt;
3114
3115         if (!chip->controller) {
3116                 chip->controller = &chip->hwcontrol;
3117                 spin_lock_init(&chip->controller->lock);
3118                 init_waitqueue_head(&chip->controller->wq);
3119         }
3120
3121 }
3122
3123 /* Sanitize ONFI strings so we can safely print them */
3124 static void sanitize_string(char *s, size_t len)
3125 {
3126         ssize_t i;
3127
3128         /* Null terminate */
3129         s[len - 1] = 0;
3130
3131         /* Remove non printable chars */
3132         for (i = 0; i < len - 1; i++) {
3133                 if (s[i] < ' ' || s[i] > 127)
3134                         s[i] = '?';
3135         }
3136
3137         /* Remove trailing spaces */
3138         strim(s);
3139 }
3140
3141 static u16 onfi_crc16(u16 crc, u8 const *p, size_t len)
3142 {
3143         int i;
3144         while (len--) {
3145                 crc ^= *p++ << 8;
3146                 for (i = 0; i < 8; i++)
3147                         crc = (crc << 1) ^ ((crc & 0x8000) ? 0x8005 : 0);
3148         }
3149
3150         return crc;
3151 }
3152
3153 #ifdef CONFIG_SYS_NAND_ONFI_DETECTION
3154 /* Parse the Extended Parameter Page. */
3155 static int nand_flash_detect_ext_param_page(struct mtd_info *mtd,
3156                 struct nand_chip *chip, struct nand_onfi_params *p)
3157 {
3158         struct onfi_ext_param_page *ep;
3159         struct onfi_ext_section *s;
3160         struct onfi_ext_ecc_info *ecc;
3161         uint8_t *cursor;
3162         int ret = -EINVAL;
3163         int len;
3164         int i;
3165
3166         len = le16_to_cpu(p->ext_param_page_length) * 16;
3167         ep = kmalloc(len, GFP_KERNEL);
3168         if (!ep)
3169                 return -ENOMEM;
3170
3171         /* Send our own NAND_CMD_PARAM. */
3172         chip->cmdfunc(mtd, NAND_CMD_PARAM, 0, -1);
3173
3174         /* Use the Change Read Column command to skip the ONFI param pages. */
3175         chip->cmdfunc(mtd, NAND_CMD_RNDOUT,
3176                         sizeof(*p) * p->num_of_param_pages , -1);
3177
3178         /* Read out the Extended Parameter Page. */
3179         chip->read_buf(mtd, (uint8_t *)ep, len);
3180         if ((onfi_crc16(ONFI_CRC_BASE, ((uint8_t *)ep) + 2, len - 2)
3181                 != le16_to_cpu(ep->crc))) {
3182                 pr_debug("fail in the CRC.\n");
3183                 goto ext_out;
3184         }
3185
3186         /*
3187          * Check the signature.
3188          * Do not strictly follow the ONFI spec, maybe changed in future.
3189          */
3190         if (strncmp((char *)ep->sig, "EPPS", 4)) {
3191                 pr_debug("The signature is invalid.\n");
3192                 goto ext_out;
3193         }
3194
3195         /* find the ECC section. */
3196         cursor = (uint8_t *)(ep + 1);
3197         for (i = 0; i < ONFI_EXT_SECTION_MAX; i++) {
3198                 s = ep->sections + i;
3199                 if (s->type == ONFI_SECTION_TYPE_2)
3200                         break;
3201                 cursor += s->length * 16;
3202         }
3203         if (i == ONFI_EXT_SECTION_MAX) {
3204                 pr_debug("We can not find the ECC section.\n");
3205                 goto ext_out;
3206         }
3207
3208         /* get the info we want. */
3209         ecc = (struct onfi_ext_ecc_info *)cursor;
3210
3211         if (!ecc->codeword_size) {
3212                 pr_debug("Invalid codeword size\n");
3213                 goto ext_out;
3214         }
3215
3216         chip->ecc_strength_ds = ecc->ecc_bits;
3217         chip->ecc_step_ds = 1 << ecc->codeword_size;
3218         ret = 0;
3219
3220 ext_out:
3221         kfree(ep);
3222         return ret;
3223 }
3224
3225 static int nand_setup_read_retry_micron(struct mtd_info *mtd, int retry_mode)
3226 {
3227         struct nand_chip *chip = mtd_to_nand(mtd);
3228         uint8_t feature[ONFI_SUBFEATURE_PARAM_LEN] = {retry_mode};
3229
3230         return chip->onfi_set_features(mtd, chip, ONFI_FEATURE_ADDR_READ_RETRY,
3231                         feature);
3232 }
3233
3234 /*
3235  * Configure chip properties from Micron vendor-specific ONFI table
3236  */
3237 static void nand_onfi_detect_micron(struct nand_chip *chip,
3238                 struct nand_onfi_params *p)
3239 {
3240         struct nand_onfi_vendor_micron *micron = (void *)p->vendor;
3241
3242         if (le16_to_cpu(p->vendor_revision) < 1)
3243                 return;
3244
3245         chip->read_retries = micron->read_retry_options;
3246         chip->setup_read_retry = nand_setup_read_retry_micron;
3247 }
3248
3249 /*
3250  * Check if the NAND chip is ONFI compliant, returns 1 if it is, 0 otherwise.
3251  */
3252 static int nand_flash_detect_onfi(struct mtd_info *mtd, struct nand_chip *chip,
3253                                         int *busw)
3254 {
3255         struct nand_onfi_params *p = &chip->onfi_params;
3256         int i, j;
3257         int val;
3258
3259         /* Try ONFI for unknown chip or LP */
3260         chip->cmdfunc(mtd, NAND_CMD_READID, 0x20, -1);
3261         if (chip->read_byte(mtd) != 'O' || chip->read_byte(mtd) != 'N' ||
3262                 chip->read_byte(mtd) != 'F' || chip->read_byte(mtd) != 'I')
3263                 return 0;
3264
3265         chip->cmdfunc(mtd, NAND_CMD_PARAM, 0, -1);
3266         for (i = 0; i < 3; i++) {
3267                 for (j = 0; j < sizeof(*p); j++)
3268                         ((uint8_t *)p)[j] = chip->read_byte(mtd);
3269                 if (onfi_crc16(ONFI_CRC_BASE, (uint8_t *)p, 254) ==
3270                                 le16_to_cpu(p->crc)) {
3271                         break;
3272                 }
3273         }
3274
3275         if (i == 3) {
3276                 pr_err("Could not find valid ONFI parameter page; aborting\n");
3277                 return 0;
3278         }
3279
3280         /* Check version */
3281         val = le16_to_cpu(p->revision);
3282         if (val & (1 << 5))
3283                 chip->onfi_version = 23;
3284         else if (val & (1 << 4))
3285                 chip->onfi_version = 22;
3286         else if (val & (1 << 3))
3287                 chip->onfi_version = 21;
3288         else if (val & (1 << 2))
3289                 chip->onfi_version = 20;
3290         else if (val & (1 << 1))
3291                 chip->onfi_version = 10;
3292
3293         if (!chip->onfi_version) {
3294                 pr_info("unsupported ONFI version: %d\n", val);
3295                 return 0;
3296         }
3297
3298         sanitize_string(p->manufacturer, sizeof(p->manufacturer));
3299         sanitize_string(p->model, sizeof(p->model));
3300         if (!mtd->name)
3301                 mtd->name = p->model;
3302
3303         mtd->writesize = le32_to_cpu(p->byte_per_page);
3304
3305         /*
3306          * pages_per_block and blocks_per_lun may not be a power-of-2 size
3307          * (don't ask me who thought of this...). MTD assumes that these
3308          * dimensions will be power-of-2, so just truncate the remaining area.
3309          */
3310         mtd->erasesize = 1 << (fls(le32_to_cpu(p->pages_per_block)) - 1);
3311         mtd->erasesize *= mtd->writesize;
3312
3313         mtd->oobsize = le16_to_cpu(p->spare_bytes_per_page);
3314
3315         /* See erasesize comment */
3316         chip->chipsize = 1 << (fls(le32_to_cpu(p->blocks_per_lun)) - 1);
3317         chip->chipsize *= (uint64_t)mtd->erasesize * p->lun_count;
3318         chip->bits_per_cell = p->bits_per_cell;
3319
3320         if (onfi_feature(chip) & ONFI_FEATURE_16_BIT_BUS)
3321                 *busw = NAND_BUSWIDTH_16;
3322         else
3323                 *busw = 0;
3324
3325         if (p->ecc_bits != 0xff) {
3326                 chip->ecc_strength_ds = p->ecc_bits;
3327                 chip->ecc_step_ds = 512;
3328         } else if (chip->onfi_version >= 21 &&
3329                 (onfi_feature(chip) & ONFI_FEATURE_EXT_PARAM_PAGE)) {
3330
3331                 /*
3332                  * The nand_flash_detect_ext_param_page() uses the
3333                  * Change Read Column command which maybe not supported
3334                  * by the chip->cmdfunc. So try to update the chip->cmdfunc
3335                  * now. We do not replace user supplied command function.
3336                  */
3337                 if (mtd->writesize > 512 && chip->cmdfunc == nand_command)
3338                         chip->cmdfunc = nand_command_lp;
3339
3340                 /* The Extended Parameter Page is supported since ONFI 2.1. */
3341                 if (nand_flash_detect_ext_param_page(mtd, chip, p))
3342                         pr_warn("Failed to detect ONFI extended param page\n");
3343         } else {
3344                 pr_warn("Could not retrieve ONFI ECC requirements\n");
3345         }
3346
3347         if (p->jedec_id == NAND_MFR_MICRON)
3348                 nand_onfi_detect_micron(chip, p);
3349
3350         return 1;
3351 }
3352 #else
3353 static int nand_flash_detect_onfi(struct mtd_info *mtd, struct nand_chip *chip,
3354                                         int *busw)
3355 {
3356         return 0;
3357 }
3358 #endif
3359
3360 /*
3361  * Check if the NAND chip is JEDEC compliant, returns 1 if it is, 0 otherwise.
3362  */
3363 static int nand_flash_detect_jedec(struct mtd_info *mtd, struct nand_chip *chip,
3364                                         int *busw)
3365 {
3366         struct nand_jedec_params *p = &chip->jedec_params;
3367         struct jedec_ecc_info *ecc;
3368         int val;
3369         int i, j;
3370
3371         /* Try JEDEC for unknown chip or LP */
3372         chip->cmdfunc(mtd, NAND_CMD_READID, 0x40, -1);
3373         if (chip->read_byte(mtd) != 'J' || chip->read_byte(mtd) != 'E' ||
3374                 chip->read_byte(mtd) != 'D' || chip->read_byte(mtd) != 'E' ||
3375                 chip->read_byte(mtd) != 'C')
3376                 return 0;
3377
3378         chip->cmdfunc(mtd, NAND_CMD_PARAM, 0x40, -1);
3379         for (i = 0; i < 3; i++) {
3380                 for (j = 0; j < sizeof(*p); j++)
3381                         ((uint8_t *)p)[j] = chip->read_byte(mtd);
3382
3383                 if (onfi_crc16(ONFI_CRC_BASE, (uint8_t *)p, 510) ==
3384                                 le16_to_cpu(p->crc))
3385                         break;
3386         }
3387
3388         if (i == 3) {
3389                 pr_err("Could not find valid JEDEC parameter page; aborting\n");
3390                 return 0;
3391         }
3392
3393         /* Check version */
3394         val = le16_to_cpu(p->revision);
3395         if (val & (1 << 2))
3396                 chip->jedec_version = 10;
3397         else if (val & (1 << 1))
3398                 chip->jedec_version = 1; /* vendor specific version */
3399
3400         if (!chip->jedec_version) {
3401                 pr_info("unsupported JEDEC version: %d\n", val);
3402                 return 0;
3403         }
3404
3405         sanitize_string(p->manufacturer, sizeof(p->manufacturer));
3406         sanitize_string(p->model, sizeof(p->model));
3407         if (!mtd->name)
3408                 mtd->name = p->model;
3409
3410         mtd->writesize = le32_to_cpu(p->byte_per_page);
3411
3412         /* Please reference to the comment for nand_flash_detect_onfi. */
3413         mtd->erasesize = 1 << (fls(le32_to_cpu(p->pages_per_block)) - 1);
3414         mtd->erasesize *= mtd->writesize;
3415
3416         mtd->oobsize = le16_to_cpu(p->spare_bytes_per_page);
3417
3418         /* Please reference to the comment for nand_flash_detect_onfi. */
3419         chip->chipsize = 1 << (fls(le32_to_cpu(p->blocks_per_lun)) - 1);
3420         chip->chipsize *= (uint64_t)mtd->erasesize * p->lun_count;
3421         chip->bits_per_cell = p->bits_per_cell;
3422
3423         if (jedec_feature(chip) & JEDEC_FEATURE_16_BIT_BUS)
3424                 *busw = NAND_BUSWIDTH_16;
3425         else
3426                 *busw = 0;
3427
3428         /* ECC info */
3429         ecc = &p->ecc_info[0];
3430
3431         if (ecc->codeword_size >= 9) {
3432                 chip->ecc_strength_ds = ecc->ecc_bits;
3433                 chip->ecc_step_ds = 1 << ecc->codeword_size;
3434         } else {
3435                 pr_warn("Invalid codeword size\n");
3436         }
3437
3438         return 1;
3439 }
3440
3441 /*
3442  * nand_id_has_period - Check if an ID string has a given wraparound period
3443  * @id_data: the ID string
3444  * @arrlen: the length of the @id_data array
3445  * @period: the period of repitition
3446  *
3447  * Check if an ID string is repeated within a given sequence of bytes at
3448  * specific repetition interval period (e.g., {0x20,0x01,0x7F,0x20} has a
3449  * period of 3). This is a helper function for nand_id_len(). Returns non-zero
3450  * if the repetition has a period of @period; otherwise, returns zero.
3451  */
3452 static int nand_id_has_period(u8 *id_data, int arrlen, int period)
3453 {
3454         int i, j;
3455         for (i = 0; i < period; i++)
3456                 for (j = i + period; j < arrlen; j += period)
3457                         if (id_data[i] != id_data[j])
3458                                 return 0;
3459         return 1;
3460 }
3461
3462 /*
3463  * nand_id_len - Get the length of an ID string returned by CMD_READID
3464  * @id_data: the ID string
3465  * @arrlen: the length of the @id_data array
3466
3467  * Returns the length of the ID string, according to known wraparound/trailing
3468  * zero patterns. If no pattern exists, returns the length of the array.
3469  */
3470 static int nand_id_len(u8 *id_data, int arrlen)
3471 {
3472         int last_nonzero, period;
3473
3474         /* Find last non-zero byte */
3475         for (last_nonzero = arrlen - 1; last_nonzero >= 0; last_nonzero--)
3476                 if (id_data[last_nonzero])
3477                         break;
3478
3479         /* All zeros */
3480         if (last_nonzero < 0)
3481                 return 0;
3482
3483         /* Calculate wraparound period */
3484         for (period = 1; period < arrlen; period++)
3485                 if (nand_id_has_period(id_data, arrlen, period))
3486                         break;
3487
3488         /* There's a repeated pattern */
3489         if (period < arrlen)
3490                 return period;
3491
3492         /* There are trailing zeros */
3493         if (last_nonzero < arrlen - 1)
3494                 return last_nonzero + 1;
3495
3496         /* No pattern detected */
3497         return arrlen;
3498 }
3499
3500 /* Extract the bits of per cell from the 3rd byte of the extended ID */
3501 static int nand_get_bits_per_cell(u8 cellinfo)
3502 {
3503         int bits;
3504
3505         bits = cellinfo & NAND_CI_CELLTYPE_MSK;
3506         bits >>= NAND_CI_CELLTYPE_SHIFT;
3507         return bits + 1;
3508 }
3509
3510 /*
3511  * Many new NAND share similar device ID codes, which represent the size of the
3512  * chip. The rest of the parameters must be decoded according to generic or
3513  * manufacturer-specific "extended ID" decoding patterns.
3514  */
3515 static void nand_decode_ext_id(struct mtd_info *mtd, struct nand_chip *chip,
3516                                 u8 id_data[8], int *busw)
3517 {
3518         int extid, id_len;
3519         /* The 3rd id byte holds MLC / multichip data */
3520         chip->bits_per_cell = nand_get_bits_per_cell(id_data[2]);
3521         /* The 4th id byte is the important one */
3522         extid = id_data[3];
3523
3524         id_len = nand_id_len(id_data, 8);
3525
3526         /*
3527          * Field definitions are in the following datasheets:
3528          * Old style (4,5 byte ID): Samsung K9GAG08U0M (p.32)
3529          * New Samsung (6 byte ID): Samsung K9GAG08U0F (p.44)
3530          * Hynix MLC   (6 byte ID): Hynix H27UBG8T2B (p.22)
3531          *
3532          * Check for ID length, non-zero 6th byte, cell type, and Hynix/Samsung
3533          * ID to decide what to do.
3534          */
3535         if (id_len == 6 && id_data[0] == NAND_MFR_SAMSUNG &&
3536                         !nand_is_slc(chip) && id_data[5] != 0x00) {
3537                 /* Calc pagesize */
3538                 mtd->writesize = 2048 << (extid & 0x03);
3539                 extid >>= 2;
3540                 /* Calc oobsize */
3541                 switch (((extid >> 2) & 0x04) | (extid & 0x03)) {
3542                 case 1:
3543                         mtd->oobsize = 128;
3544                         break;
3545                 case 2:
3546                         mtd->oobsize = 218;
3547                         break;
3548                 case 3:
3549                         mtd->oobsize = 400;
3550                         break;
3551                 case 4:
3552                         mtd->oobsize = 436;
3553                         break;
3554                 case 5:
3555                         mtd->oobsize = 512;
3556                         break;
3557                 case 6:
3558                         mtd->oobsize = 640;
3559                         break;
3560                 case 7:
3561                 default: /* Other cases are "reserved" (unknown) */
3562                         mtd->oobsize = 1024;
3563                         break;
3564                 }
3565                 extid >>= 2;
3566                 /* Calc blocksize */
3567                 mtd->erasesize = (128 * 1024) <<
3568                         (((extid >> 1) & 0x04) | (extid & 0x03));
3569                 *busw = 0;
3570         } else if (id_len == 6 && id_data[0] == NAND_MFR_HYNIX &&
3571                         !nand_is_slc(chip)) {
3572                 unsigned int tmp;
3573
3574                 /* Calc pagesize */
3575                 mtd->writesize = 2048 << (extid & 0x03);
3576                 extid >>= 2;
3577                 /* Calc oobsize */
3578                 switch (((extid >> 2) & 0x04) | (extid & 0x03)) {
3579                 case 0:
3580                         mtd->oobsize = 128;
3581                         break;
3582                 case 1:
3583                         mtd->oobsize = 224;
3584                         break;
3585                 case 2:
3586                         mtd->oobsize = 448;
3587                         break;
3588                 case 3:
3589                         mtd->oobsize = 64;
3590                         break;
3591                 case 4:
3592                         mtd->oobsize = 32;
3593                         break;
3594                 case 5:
3595                         mtd->oobsize = 16;
3596                         break;
3597                 default:
3598                         mtd->oobsize = 640;
3599                         break;
3600                 }
3601                 extid >>= 2;
3602                 /* Calc blocksize */
3603                 tmp = ((extid >> 1) & 0x04) | (extid & 0x03);
3604                 if (tmp < 0x03)
3605                         mtd->erasesize = (128 * 1024) << tmp;
3606                 else if (tmp == 0x03)
3607                         mtd->erasesize = 768 * 1024;
3608                 else
3609                         mtd->erasesize = (64 * 1024) << tmp;
3610                 *busw = 0;
3611         } else {
3612                 /* Calc pagesize */
3613                 mtd->writesize = 1024 << (extid & 0x03);
3614                 extid >>= 2;
3615                 /* Calc oobsize */
3616                 mtd->oobsize = (8 << (extid & 0x01)) *
3617                         (mtd->writesize >> 9);
3618                 extid >>= 2;
3619                 /* Calc blocksize. Blocksize is multiples of 64KiB */
3620                 mtd->erasesize = (64 * 1024) << (extid & 0x03);
3621                 extid >>= 2;
3622                 /* Get buswidth information */
3623                 *busw = (extid & 0x01) ? NAND_BUSWIDTH_16 : 0;
3624
3625                 /*
3626                  * Toshiba 24nm raw SLC (i.e., not BENAND) have 32B OOB per
3627                  * 512B page. For Toshiba SLC, we decode the 5th/6th byte as
3628                  * follows:
3629                  * - ID byte 6, bits[2:0]: 100b -> 43nm, 101b -> 32nm,
3630                  *                         110b -> 24nm
3631                  * - ID byte 5, bit[7]:    1 -> BENAND, 0 -> raw SLC
3632                  */
3633                 if (id_len >= 6 && id_data[0] == NAND_MFR_TOSHIBA &&
3634                                 nand_is_slc(chip) &&
3635                                 (id_data[5] & 0x7) == 0x6 /* 24nm */ &&
3636                                 !(id_data[4] & 0x80) /* !BENAND */) {
3637                         mtd->oobsize = 32 * mtd->writesize >> 9;
3638                 }
3639
3640         }
3641 }
3642
3643 /*
3644  * Old devices have chip data hardcoded in the device ID table. nand_decode_id
3645  * decodes a matching ID table entry and assigns the MTD size parameters for
3646  * the chip.
3647  */
3648 static void nand_decode_id(struct mtd_info *mtd, struct nand_chip *chip,
3649                                 struct nand_flash_dev *type, u8 id_data[8],
3650                                 int *busw)
3651 {
3652         int maf_id = id_data[0];
3653
3654         mtd->erasesize = type->erasesize;
3655         mtd->writesize = type->pagesize;
3656         mtd->oobsize = mtd->writesize / 32;
3657         *busw = type->options & NAND_BUSWIDTH_16;
3658
3659         /* All legacy ID NAND are small-page, SLC */
3660         chip->bits_per_cell = 1;
3661
3662         /*
3663          * Check for Spansion/AMD ID + repeating 5th, 6th byte since
3664          * some Spansion chips have erasesize that conflicts with size
3665          * listed in nand_ids table.
3666          * Data sheet (5 byte ID): Spansion S30ML-P ORNAND (p.39)
3667          */
3668         if (maf_id == NAND_MFR_AMD && id_data[4] != 0x00 && id_data[5] == 0x00
3669                         && id_data[6] == 0x00 && id_data[7] == 0x00
3670                         && mtd->writesize == 512) {
3671                 mtd->erasesize = 128 * 1024;
3672                 mtd->erasesize <<= ((id_data[3] & 0x03) << 1);
3673         }
3674 }
3675
3676 /*
3677  * Set the bad block marker/indicator (BBM/BBI) patterns according to some
3678  * heuristic patterns using various detected parameters (e.g., manufacturer,
3679  * page size, cell-type information).
3680  */
3681 static void nand_decode_bbm_options(struct mtd_info *mtd,
3682                                     struct nand_chip *chip, u8 id_data[8])
3683 {
3684         int maf_id = id_data[0];
3685
3686         /* Set the bad block position */
3687         if (mtd->writesize > 512 || (chip->options & NAND_BUSWIDTH_16))
3688                 chip->badblockpos = NAND_LARGE_BADBLOCK_POS;
3689         else
3690                 chip->badblockpos = NAND_SMALL_BADBLOCK_POS;
3691
3692         /*
3693          * Bad block marker is stored in the last page of each block on Samsung
3694          * and Hynix MLC devices; stored in first two pages of each block on
3695          * Micron devices with 2KiB pages and on SLC Samsung, Hynix, Toshiba,
3696          * AMD/Spansion, and Macronix.  All others scan only the first page.
3697          */
3698         if (!nand_is_slc(chip) &&
3699                         (maf_id == NAND_MFR_SAMSUNG ||
3700                          maf_id == NAND_MFR_HYNIX))
3701                 chip->bbt_options |= NAND_BBT_SCANLASTPAGE;
3702         else if ((nand_is_slc(chip) &&
3703                                 (maf_id == NAND_MFR_SAMSUNG ||
3704                                  maf_id == NAND_MFR_HYNIX ||
3705                                  maf_id == NAND_MFR_TOSHIBA ||
3706                                  maf_id == NAND_MFR_AMD ||
3707                                  maf_id == NAND_MFR_MACRONIX)) ||
3708                         (mtd->writesize == 2048 &&
3709                          maf_id == NAND_MFR_MICRON))
3710                 chip->bbt_options |= NAND_BBT_SCAN2NDPAGE;
3711 }
3712
3713 static inline bool is_full_id_nand(struct nand_flash_dev *type)
3714 {
3715         return type->id_len;
3716 }
3717
3718 static bool find_full_id_nand(struct mtd_info *mtd, struct nand_chip *chip,
3719                    struct nand_flash_dev *type, u8 *id_data, int *busw)
3720 {
3721         if (!strncmp((char *)type->id, (char *)id_data, type->id_len)) {
3722                 mtd->writesize = type->pagesize;
3723                 mtd->erasesize = type->erasesize;
3724                 mtd->oobsize = type->oobsize;
3725
3726                 chip->bits_per_cell = nand_get_bits_per_cell(id_data[2]);
3727                 chip->chipsize = (uint64_t)type->chipsize << 20;
3728                 chip->options |= type->options;
3729                 chip->ecc_strength_ds = NAND_ECC_STRENGTH(type);
3730                 chip->ecc_step_ds = NAND_ECC_STEP(type);
3731                 chip->onfi_timing_mode_default =
3732                                         type->onfi_timing_mode_default;
3733
3734                 *busw = type->options & NAND_BUSWIDTH_16;
3735
3736                 if (!mtd->name)
3737                         mtd->name = type->name;
3738
3739                 return true;
3740         }
3741         return false;
3742 }
3743
3744 /*
3745  * Get the flash and manufacturer id and lookup if the type is supported.
3746  */
3747 static struct nand_flash_dev *nand_get_flash_type(struct mtd_info *mtd,
3748                                                   struct nand_chip *chip,
3749                                                   int *maf_id, int *dev_id,
3750                                                   struct nand_flash_dev *type)
3751 {
3752         int busw;
3753         int i, maf_idx;
3754         u8 id_data[8];
3755
3756         /*
3757          * Reset the chip, required by some chips (e.g. Micron MT29FxGxxxxx)
3758          * after power-up.
3759          */
3760         nand_reset(chip, 0);
3761
3762         /* Select the device */
3763         chip->select_chip(mtd, 0);
3764
3765         /* Send the command for reading device ID */
3766         chip->cmdfunc(mtd, NAND_CMD_READID, 0x00, -1);
3767
3768         /* Read manufacturer and device IDs */
3769         *maf_id = chip->read_byte(mtd);
3770         *dev_id = chip->read_byte(mtd);
3771
3772         /*
3773          * Try again to make sure, as some systems the bus-hold or other
3774          * interface concerns can cause random data which looks like a
3775          * possibly credible NAND flash to appear. If the two results do
3776          * not match, ignore the device completely.
3777          */
3778
3779         chip->cmdfunc(mtd, NAND_CMD_READID, 0x00, -1);
3780
3781         /* Read entire ID string */
3782         for (i = 0; i < 8; i++)
3783                 id_data[i] = chip->read_byte(mtd);
3784
3785         if (id_data[0] != *maf_id || id_data[1] != *dev_id) {
3786                 pr_info("second ID read did not match %02x,%02x against %02x,%02x\n",
3787                         *maf_id, *dev_id, id_data[0], id_data[1]);
3788                 return ERR_PTR(-ENODEV);
3789         }
3790
3791         if (!type)
3792                 type = nand_flash_ids;
3793
3794         for (; type->name != NULL; type++) {
3795                 if (is_full_id_nand(type)) {
3796                         if (find_full_id_nand(mtd, chip, type, id_data, &busw))
3797                                 goto ident_done;
3798                 } else if (*dev_id == type->dev_id) {
3799                         break;
3800                 }
3801         }
3802
3803         chip->onfi_version = 0;
3804         if (!type->name || !type->pagesize) {
3805                 /* Check if the chip is ONFI compliant */
3806                 if (nand_flash_detect_onfi(mtd, chip, &busw))
3807                         goto ident_done;
3808
3809                 /* Check if the chip is JEDEC compliant */
3810                 if (nand_flash_detect_jedec(mtd, chip, &busw))
3811                         goto ident_done;
3812         }
3813
3814         if (!type->name)
3815                 return ERR_PTR(-ENODEV);
3816
3817         if (!mtd->name)
3818                 mtd->name = type->name;
3819
3820         chip->chipsize = (uint64_t)type->chipsize << 20;
3821
3822         if (!type->pagesize) {
3823                 /* Decode parameters from extended ID */
3824                 nand_decode_ext_id(mtd, chip, id_data, &busw);
3825         } else {
3826                 nand_decode_id(mtd, chip, type, id_data, &busw);
3827         }
3828         /* Get chip options */
3829         chip->options |= type->options;
3830
3831         /*
3832          * Check if chip is not a Samsung device. Do not clear the
3833          * options for chips which do not have an extended id.
3834          */
3835         if (*maf_id != NAND_MFR_SAMSUNG && !type->pagesize)
3836                 chip->options &= ~NAND_SAMSUNG_LP_OPTIONS;
3837 ident_done:
3838
3839         /* Try to identify manufacturer */
3840         for (maf_idx = 0; nand_manuf_ids[maf_idx].id != 0x0; maf_idx++) {
3841                 if (nand_manuf_ids[maf_idx].id == *maf_id)
3842                         break;
3843         }
3844
3845         if (chip->options & NAND_BUSWIDTH_AUTO) {
3846                 WARN_ON(chip->options & NAND_BUSWIDTH_16);
3847                 chip->options |= busw;
3848                 nand_set_defaults(chip, busw);
3849         } else if (busw != (chip->options & NAND_BUSWIDTH_16)) {
3850                 /*
3851                  * Check, if buswidth is correct. Hardware drivers should set
3852                  * chip correct!
3853                  */
3854                 pr_info("device found, Manufacturer ID: 0x%02x, Chip ID: 0x%02x\n",
3855                         *maf_id, *dev_id);
3856                 pr_info("%s %s\n", nand_manuf_ids[maf_idx].name, mtd->name);
3857                 pr_warn("bus width %d instead %d bit\n",
3858                            (chip->options & NAND_BUSWIDTH_16) ? 16 : 8,
3859                            busw ? 16 : 8);
3860                 return ERR_PTR(-EINVAL);
3861         }
3862
3863         nand_decode_bbm_options(mtd, chip, id_data);
3864
3865         /* Calculate the address shift from the page size */
3866         chip->page_shift = ffs(mtd->writesize) - 1;
3867         /* Convert chipsize to number of pages per chip -1 */
3868         chip->pagemask = (chip->chipsize >> chip->page_shift) - 1;
3869
3870         chip->bbt_erase_shift = chip->phys_erase_shift =
3871                 ffs(mtd->erasesize) - 1;
3872         if (chip->chipsize & 0xffffffff)
3873                 chip->chip_shift = ffs((unsigned)chip->chipsize) - 1;
3874         else {
3875                 chip->chip_shift = ffs((unsigned)(chip->chipsize >> 32));
3876                 chip->chip_shift += 32 - 1;
3877         }
3878
3879         chip->badblockbits = 8;
3880         chip->erase = single_erase;
3881
3882         /* Do not replace user supplied command function! */
3883         if (mtd->writesize > 512 && chip->cmdfunc == nand_command)
3884                 chip->cmdfunc = nand_command_lp;
3885
3886         pr_info("device found, Manufacturer ID: 0x%02x, Chip ID: 0x%02x\n",
3887                 *maf_id, *dev_id);
3888
3889 #ifdef CONFIG_SYS_NAND_ONFI_DETECTION
3890         if (chip->onfi_version)
3891                 pr_info("%s %s\n", nand_manuf_ids[maf_idx].name,
3892                                 chip->onfi_params.model);
3893         else if (chip->jedec_version)
3894                 pr_info("%s %s\n", nand_manuf_ids[maf_idx].name,
3895                                 chip->jedec_params.model);
3896         else
3897                 pr_info("%s %s\n", nand_manuf_ids[maf_idx].name,
3898                                 type->name);
3899 #else
3900         if (chip->jedec_version)
3901                 pr_info("%s %s\n", nand_manuf_ids[maf_idx].name,
3902                                 chip->jedec_params.model);
3903         else
3904                 pr_info("%s %s\n", nand_manuf_ids[maf_idx].name,
3905                                 type->name);
3906
3907         pr_info("%s %s\n", nand_manuf_ids[maf_idx].name,
3908                 type->name);
3909 #endif
3910
3911         pr_info("%d MiB, %s, erase size: %d KiB, page size: %d, OOB size: %d\n",
3912                 (int)(chip->chipsize >> 20), nand_is_slc(chip) ? "SLC" : "MLC",
3913                 mtd->erasesize >> 10, mtd->writesize, mtd->oobsize);
3914         return type;
3915 }
3916
3917 #if CONFIG_IS_ENABLED(OF_CONTROL)
3918 DECLARE_GLOBAL_DATA_PTR;
3919
3920 static int nand_dt_init(struct mtd_info *mtd, struct nand_chip *chip, int node)
3921 {
3922         int ret, ecc_mode = -1, ecc_strength, ecc_step;
3923         const void *blob = gd->fdt_blob;
3924         const char *str;
3925
3926         ret = fdtdec_get_int(blob, node, "nand-bus-width", -1);
3927         if (ret == 16)
3928                 chip->options |= NAND_BUSWIDTH_16;
3929
3930         if (fdtdec_get_bool(blob, node, "nand-on-flash-bbt"))
3931                 chip->bbt_options |= NAND_BBT_USE_FLASH;
3932
3933         str = fdt_getprop(blob, node, "nand-ecc-mode", NULL);
3934         if (str) {
3935                 if (!strcmp(str, "none"))
3936                         ecc_mode = NAND_ECC_NONE;
3937                 else if (!strcmp(str, "soft"))
3938                         ecc_mode = NAND_ECC_SOFT;
3939                 else if (!strcmp(str, "hw"))
3940                         ecc_mode = NAND_ECC_HW;
3941                 else if (!strcmp(str, "hw_syndrome"))
3942                         ecc_mode = NAND_ECC_HW_SYNDROME;
3943                 else if (!strcmp(str, "hw_oob_first"))
3944                         ecc_mode = NAND_ECC_HW_OOB_FIRST;
3945                 else if (!strcmp(str, "soft_bch"))
3946                         ecc_mode = NAND_ECC_SOFT_BCH;
3947         }
3948
3949
3950         ecc_strength = fdtdec_get_int(blob, node, "nand-ecc-strength", -1);
3951         ecc_step = fdtdec_get_int(blob, node, "nand-ecc-step-size", -1);
3952
3953         if ((ecc_step >= 0 && !(ecc_strength >= 0)) ||
3954             (!(ecc_step >= 0) && ecc_strength >= 0)) {
3955                 pr_err("must set both strength and step size in DT\n");
3956                 return -EINVAL;
3957         }
3958
3959         if (ecc_mode >= 0)
3960                 chip->ecc.mode = ecc_mode;
3961
3962         if (ecc_strength >= 0)
3963                 chip->ecc.strength = ecc_strength;
3964
3965         if (ecc_step > 0)
3966                 chip->ecc.size = ecc_step;
3967
3968         if (fdt_getprop(blob, node, "nand-ecc-maximize", NULL))
3969                 chip->ecc.options |= NAND_ECC_MAXIMIZE;
3970
3971         return 0;
3972 }
3973 #else
3974 static int nand_dt_init(struct mtd_info *mtd, struct nand_chip *chip, int node)
3975 {
3976         return 0;
3977 }
3978 #endif /* CONFIG_IS_ENABLED(OF_CONTROL) */
3979
3980 /**
3981  * nand_scan_ident - [NAND Interface] Scan for the NAND device
3982  * @mtd: MTD device structure
3983  * @maxchips: number of chips to scan for
3984  * @table: alternative NAND ID table
3985  *
3986  * This is the first phase of the normal nand_scan() function. It reads the
3987  * flash ID and sets up MTD fields accordingly.
3988  *
3989  */
3990 int nand_scan_ident(struct mtd_info *mtd, int maxchips,
3991                     struct nand_flash_dev *table)
3992 {
3993         int i, nand_maf_id, nand_dev_id;
3994         struct nand_chip *chip = mtd_to_nand(mtd);
3995         struct nand_flash_dev *type;
3996         int ret;
3997
3998         if (chip->flash_node) {
3999                 ret = nand_dt_init(mtd, chip, chip->flash_node);
4000                 if (ret)
4001                         return ret;
4002         }
4003
4004         /* Set the default functions */
4005         nand_set_defaults(chip, chip->options & NAND_BUSWIDTH_16);
4006
4007         /* Read the flash type */
4008         type = nand_get_flash_type(mtd, chip, &nand_maf_id,
4009                                    &nand_dev_id, table);
4010
4011         if (IS_ERR(type)) {
4012                 if (!(chip->options & NAND_SCAN_SILENT_NODEV))
4013                         pr_warn("No NAND device found\n");
4014                 chip->select_chip(mtd, -1);
4015                 return PTR_ERR(type);
4016         }
4017
4018         /* Initialize the ->data_interface field. */
4019         ret = nand_init_data_interface(chip);
4020         if (ret)
4021                 return ret;
4022
4023         /*
4024          * Setup the data interface correctly on the chip and controller side.
4025          * This explicit call to nand_setup_data_interface() is only required
4026          * for the first die, because nand_reset() has been called before
4027          * ->data_interface and ->default_onfi_timing_mode were set.
4028          * For the other dies, nand_reset() will automatically switch to the
4029          * best mode for us.
4030          */
4031         ret = nand_setup_data_interface(chip);
4032         if (ret)
4033                 return ret;
4034
4035         chip->select_chip(mtd, -1);
4036
4037         /* Check for a chip array */
4038         for (i = 1; i < maxchips; i++) {
4039                 /* See comment in nand_get_flash_type for reset */
4040                 nand_reset(chip, i);
4041
4042                 chip->select_chip(mtd, i);
4043                 /* Send the command for reading device ID */
4044                 chip->cmdfunc(mtd, NAND_CMD_READID, 0x00, -1);
4045                 /* Read manufacturer and device IDs */
4046                 if (nand_maf_id != chip->read_byte(mtd) ||
4047                     nand_dev_id != chip->read_byte(mtd)) {
4048                         chip->select_chip(mtd, -1);
4049                         break;
4050                 }
4051                 chip->select_chip(mtd, -1);
4052         }
4053
4054 #ifdef DEBUG
4055         if (i > 1)
4056                 pr_info("%d chips detected\n", i);
4057 #endif
4058
4059         /* Store the number of chips and calc total size for mtd */
4060         chip->numchips = i;
4061         mtd->size = i * chip->chipsize;
4062
4063         return 0;
4064 }
4065 EXPORT_SYMBOL(nand_scan_ident);
4066
4067 /*
4068  * Check if the chip configuration meet the datasheet requirements.
4069
4070  * If our configuration corrects A bits per B bytes and the minimum
4071  * required correction level is X bits per Y bytes, then we must ensure
4072  * both of the following are true:
4073  *
4074  * (1) A / B >= X / Y
4075  * (2) A >= X
4076  *
4077  * Requirement (1) ensures we can correct for the required bitflip density.
4078  * Requirement (2) ensures we can correct even when all bitflips are clumped
4079  * in the same sector.
4080  */
4081 static bool nand_ecc_strength_good(struct mtd_info *mtd)
4082 {
4083         struct nand_chip *chip = mtd_to_nand(mtd);
4084         struct nand_ecc_ctrl *ecc = &chip->ecc;
4085         int corr, ds_corr;
4086
4087         if (ecc->size == 0 || chip->ecc_step_ds == 0)
4088                 /* Not enough information */
4089                 return true;
4090
4091         /*
4092          * We get the number of corrected bits per page to compare
4093          * the correction density.
4094          */
4095         corr = (mtd->writesize * ecc->strength) / ecc->size;
4096         ds_corr = (mtd->writesize * chip->ecc_strength_ds) / chip->ecc_step_ds;
4097
4098         return corr >= ds_corr && ecc->strength >= chip->ecc_strength_ds;
4099 }
4100
4101 static bool invalid_ecc_page_accessors(struct nand_chip *chip)
4102 {
4103         struct nand_ecc_ctrl *ecc = &chip->ecc;
4104
4105         if (nand_standard_page_accessors(ecc))
4106                 return false;
4107
4108         /*
4109          * NAND_ECC_CUSTOM_PAGE_ACCESS flag is set, make sure the NAND
4110          * controller driver implements all the page accessors because
4111          * default helpers are not suitable when the core does not
4112          * send the READ0/PAGEPROG commands.
4113          */
4114         return (!ecc->read_page || !ecc->write_page ||
4115                 !ecc->read_page_raw || !ecc->write_page_raw ||
4116                 (NAND_HAS_SUBPAGE_READ(chip) && !ecc->read_subpage) ||
4117                 (NAND_HAS_SUBPAGE_WRITE(chip) && !ecc->write_subpage &&
4118                  ecc->hwctl && ecc->calculate));
4119 }
4120
4121 /**
4122  * nand_scan_tail - [NAND Interface] Scan for the NAND device
4123  * @mtd: MTD device structure
4124  *
4125  * This is the second phase of the normal nand_scan() function. It fills out
4126  * all the uninitialized function pointers with the defaults and scans for a
4127  * bad block table if appropriate.
4128  */
4129 int nand_scan_tail(struct mtd_info *mtd)
4130 {
4131         int i;
4132         struct nand_chip *chip = mtd_to_nand(mtd);
4133         struct nand_ecc_ctrl *ecc = &chip->ecc;
4134         struct nand_buffers *nbuf;
4135
4136         /* New bad blocks should be marked in OOB, flash-based BBT, or both */
4137         BUG_ON((chip->bbt_options & NAND_BBT_NO_OOB_BBM) &&
4138                         !(chip->bbt_options & NAND_BBT_USE_FLASH));
4139
4140         if (invalid_ecc_page_accessors(chip)) {
4141                 pr_err("Invalid ECC page accessors setup\n");
4142                 return -EINVAL;
4143         }
4144
4145         if (!(chip->options & NAND_OWN_BUFFERS)) {
4146                 nbuf = kzalloc(sizeof(struct nand_buffers), GFP_KERNEL);
4147                 chip->buffers = nbuf;
4148         } else {
4149                 if (!chip->buffers)
4150                         return -ENOMEM;
4151         }
4152
4153         /* Set the internal oob buffer location, just after the page data */
4154         chip->oob_poi = chip->buffers->databuf + mtd->writesize;
4155
4156         /*
4157          * If no default placement scheme is given, select an appropriate one.
4158          */
4159         if (!ecc->layout && (ecc->mode != NAND_ECC_SOFT_BCH)) {
4160                 switch (mtd->oobsize) {
4161                 case 8:
4162                         ecc->layout = &nand_oob_8;
4163                         break;
4164                 case 16:
4165                         ecc->layout = &nand_oob_16;
4166                         break;
4167                 case 64:
4168                         ecc->layout = &nand_oob_64;
4169                         break;
4170                 case 128:
4171                         ecc->layout = &nand_oob_128;
4172                         break;
4173                 default:
4174                         pr_warn("No oob scheme defined for oobsize %d\n",
4175                                    mtd->oobsize);
4176                         BUG();
4177                 }
4178         }
4179
4180         if (!chip->write_page)
4181                 chip->write_page = nand_write_page;
4182
4183         /*
4184          * Check ECC mode, default to software if 3byte/512byte hardware ECC is
4185          * selected and we have 256 byte pagesize fallback to software ECC
4186          */
4187
4188         switch (ecc->mode) {
4189         case NAND_ECC_HW_OOB_FIRST:
4190                 /* Similar to NAND_ECC_HW, but a separate read_page handle */
4191                 if (!ecc->calculate || !ecc->correct || !ecc->hwctl) {
4192                         pr_warn("No ECC functions supplied; hardware ECC not possible\n");
4193                         BUG();
4194                 }
4195                 if (!ecc->read_page)
4196                         ecc->read_page = nand_read_page_hwecc_oob_first;
4197
4198         case NAND_ECC_HW:
4199                 /* Use standard hwecc read page function? */
4200                 if (!ecc->read_page)
4201                         ecc->read_page = nand_read_page_hwecc;
4202                 if (!ecc->write_page)
4203                         ecc->write_page = nand_write_page_hwecc;
4204                 if (!ecc->read_page_raw)
4205                         ecc->read_page_raw = nand_read_page_raw;
4206                 if (!ecc->write_page_raw)
4207                         ecc->write_page_raw = nand_write_page_raw;
4208                 if (!ecc->read_oob)
4209                         ecc->read_oob = nand_read_oob_std;
4210                 if (!ecc->write_oob)
4211                         ecc->write_oob = nand_write_oob_std;
4212                 if (!ecc->read_subpage)
4213                         ecc->read_subpage = nand_read_subpage;
4214                 if (!ecc->write_subpage && ecc->hwctl && ecc->calculate)
4215                         ecc->write_subpage = nand_write_subpage_hwecc;
4216
4217         case NAND_ECC_HW_SYNDROME:
4218                 if ((!ecc->calculate || !ecc->correct || !ecc->hwctl) &&
4219                     (!ecc->read_page ||
4220                      ecc->read_page == nand_read_page_hwecc ||
4221                      !ecc->write_page ||
4222                      ecc->write_page == nand_write_page_hwecc)) {
4223                         pr_warn("No ECC functions supplied; hardware ECC not possible\n");
4224                         BUG();
4225                 }
4226                 /* Use standard syndrome read/write page function? */
4227                 if (!ecc->read_page)
4228                         ecc->read_page = nand_read_page_syndrome;
4229                 if (!ecc->write_page)
4230                         ecc->write_page = nand_write_page_syndrome;
4231                 if (!ecc->read_page_raw)
4232                         ecc->read_page_raw = nand_read_page_raw_syndrome;
4233                 if (!ecc->write_page_raw)
4234                         ecc->write_page_raw = nand_write_page_raw_syndrome;
4235                 if (!ecc->read_oob)
4236                         ecc->read_oob = nand_read_oob_syndrome;
4237                 if (!ecc->write_oob)
4238                         ecc->write_oob = nand_write_oob_syndrome;
4239
4240                 if (mtd->writesize >= ecc->size) {
4241                         if (!ecc->strength) {
4242                                 pr_warn("Driver must set ecc.strength when using hardware ECC\n");
4243                                 BUG();
4244                         }
4245                         break;
4246                 }
4247                 pr_warn("%d byte HW ECC not possible on %d byte page size, fallback to SW ECC\n",
4248                         ecc->size, mtd->writesize);
4249                 ecc->mode = NAND_ECC_SOFT;
4250
4251         case NAND_ECC_SOFT:
4252                 ecc->calculate = nand_calculate_ecc;
4253                 ecc->correct = nand_correct_data;
4254                 ecc->read_page = nand_read_page_swecc;
4255                 ecc->read_subpage = nand_read_subpage;
4256                 ecc->write_page = nand_write_page_swecc;
4257                 ecc->read_page_raw = nand_read_page_raw;
4258                 ecc->write_page_raw = nand_write_page_raw;
4259                 ecc->read_oob = nand_read_oob_std;
4260                 ecc->write_oob = nand_write_oob_std;
4261                 if (!ecc->size)
4262                         ecc->size = 256;
4263                 ecc->bytes = 3;
4264                 ecc->strength = 1;
4265                 break;
4266
4267         case NAND_ECC_SOFT_BCH:
4268                 if (!mtd_nand_has_bch()) {
4269                         pr_warn("CONFIG_MTD_NAND_ECC_BCH not enabled\n");
4270                         BUG();
4271                 }
4272                 ecc->calculate = nand_bch_calculate_ecc;
4273                 ecc->correct = nand_bch_correct_data;
4274                 ecc->read_page = nand_read_page_swecc;
4275                 ecc->read_subpage = nand_read_subpage;
4276                 ecc->write_page = nand_write_page_swecc;
4277                 ecc->read_page_raw = nand_read_page_raw;
4278                 ecc->write_page_raw = nand_write_page_raw;
4279                 ecc->read_oob = nand_read_oob_std;
4280                 ecc->write_oob = nand_write_oob_std;
4281                 /*
4282                  * Board driver should supply ecc.size and ecc.strength values
4283                  * to select how many bits are correctable. Otherwise, default
4284                  * to 4 bits for large page devices.
4285                  */
4286                 if (!ecc->size && (mtd->oobsize >= 64)) {
4287                         ecc->size = 512;
4288                         ecc->strength = 4;
4289                 }
4290
4291                 /* See nand_bch_init() for details. */
4292                 ecc->bytes = 0;
4293                 ecc->priv = nand_bch_init(mtd);
4294                 if (!ecc->priv) {
4295                         pr_warn("BCH ECC initialization failed!\n");
4296                         BUG();
4297                 }
4298                 break;
4299
4300         case NAND_ECC_NONE:
4301                 pr_warn("NAND_ECC_NONE selected by board driver. This is not recommended!\n");
4302                 ecc->read_page = nand_read_page_raw;
4303                 ecc->write_page = nand_write_page_raw;
4304                 ecc->read_oob = nand_read_oob_std;
4305                 ecc->read_page_raw = nand_read_page_raw;
4306                 ecc->write_page_raw = nand_write_page_raw;
4307                 ecc->write_oob = nand_write_oob_std;
4308                 ecc->size = mtd->writesize;
4309                 ecc->bytes = 0;
4310                 ecc->strength = 0;
4311                 break;
4312
4313         default:
4314                 pr_warn("Invalid NAND_ECC_MODE %d\n", ecc->mode);
4315                 BUG();
4316         }
4317
4318         /* For many systems, the standard OOB write also works for raw */
4319         if (!ecc->read_oob_raw)
4320                 ecc->read_oob_raw = ecc->read_oob;
4321         if (!ecc->write_oob_raw)
4322                 ecc->write_oob_raw = ecc->write_oob;
4323
4324         /*
4325          * The number of bytes available for a client to place data into
4326          * the out of band area.
4327          */
4328         mtd->oobavail = 0;
4329         if (ecc->layout) {
4330                 for (i = 0; ecc->layout->oobfree[i].length; i++)
4331                         mtd->oobavail += ecc->layout->oobfree[i].length;
4332         }
4333
4334         /* ECC sanity check: warn if it's too weak */
4335         if (!nand_ecc_strength_good(mtd))
4336                 pr_warn("WARNING: %s: the ECC used on your system is too weak compared to the one required by the NAND chip\n",
4337                         mtd->name);
4338
4339         /*
4340          * Set the number of read / write steps for one page depending on ECC
4341          * mode.
4342          */
4343         ecc->steps = mtd->writesize / ecc->size;
4344         if (ecc->steps * ecc->size != mtd->writesize) {
4345                 pr_warn("Invalid ECC parameters\n");
4346                 BUG();
4347         }
4348         ecc->total = ecc->steps * ecc->bytes;
4349
4350         /* Allow subpage writes up to ecc.steps. Not possible for MLC flash */
4351         if (!(chip->options & NAND_NO_SUBPAGE_WRITE) && nand_is_slc(chip)) {
4352                 switch (ecc->steps) {
4353                 case 2:
4354                         mtd->subpage_sft = 1;
4355                         break;
4356                 case 4:
4357                 case 8:
4358                 case 16:
4359                         mtd->subpage_sft = 2;
4360                         break;
4361                 }
4362         }
4363         chip->subpagesize = mtd->writesize >> mtd->subpage_sft;
4364
4365         /* Initialize state */
4366         chip->state = FL_READY;
4367
4368         /* Invalidate the pagebuffer reference */
4369         chip->pagebuf = -1;
4370
4371         /* Large page NAND with SOFT_ECC should support subpage reads */
4372         switch (ecc->mode) {
4373         case NAND_ECC_SOFT:
4374         case NAND_ECC_SOFT_BCH:
4375                 if (chip->page_shift > 9)
4376                         chip->options |= NAND_SUBPAGE_READ;
4377                 break;
4378
4379         default:
4380                 break;
4381         }
4382
4383         /* Fill in remaining MTD driver data */
4384         mtd->type = nand_is_slc(chip) ? MTD_NANDFLASH : MTD_MLCNANDFLASH;
4385         mtd->flags = (chip->options & NAND_ROM) ? MTD_CAP_ROM :
4386                                                 MTD_CAP_NANDFLASH;
4387         mtd->_erase = nand_erase;
4388         mtd->_read = nand_read;
4389         mtd->_write = nand_write;
4390         mtd->_panic_write = panic_nand_write;
4391         mtd->_read_oob = nand_read_oob;
4392         mtd->_write_oob = nand_write_oob;
4393         mtd->_sync = nand_sync;
4394         mtd->_lock = NULL;
4395         mtd->_unlock = NULL;
4396         mtd->_block_isreserved = nand_block_isreserved;
4397         mtd->_block_isbad = nand_block_isbad;
4398         mtd->_block_markbad = nand_block_markbad;
4399         mtd->writebufsize = mtd->writesize;
4400
4401         /* propagate ecc info to mtd_info */
4402         mtd->ecclayout = ecc->layout;
4403         mtd->ecc_strength = ecc->strength;
4404         mtd->ecc_step_size = ecc->size;
4405         /*
4406          * Initialize bitflip_threshold to its default prior scan_bbt() call.
4407          * scan_bbt() might invoke mtd_read(), thus bitflip_threshold must be
4408          * properly set.
4409          */
4410         if (!mtd->bitflip_threshold)
4411                 mtd->bitflip_threshold = DIV_ROUND_UP(mtd->ecc_strength * 3, 4);
4412
4413         return 0;
4414 }
4415 EXPORT_SYMBOL(nand_scan_tail);
4416
4417 /**
4418  * nand_scan - [NAND Interface] Scan for the NAND device
4419  * @mtd: MTD device structure
4420  * @maxchips: number of chips to scan for
4421  *
4422  * This fills out all the uninitialized function pointers with the defaults.
4423  * The flash ID is read and the mtd/chip structures are filled with the
4424  * appropriate values.
4425  */
4426 int nand_scan(struct mtd_info *mtd, int maxchips)
4427 {
4428         int ret;
4429
4430         ret = nand_scan_ident(mtd, maxchips, NULL);
4431         if (!ret)
4432                 ret = nand_scan_tail(mtd);
4433         return ret;
4434 }
4435 EXPORT_SYMBOL(nand_scan);
4436
4437 MODULE_LICENSE("GPL");
4438 MODULE_AUTHOR("Steven J. Hill <sjhill@realitydiluted.com>");
4439 MODULE_AUTHOR("Thomas Gleixner <tglx@linutronix.de>");
4440 MODULE_DESCRIPTION("Generic NAND flash driver code");