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