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