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