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