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