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