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