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