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