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